]> gitweb.ps.run Git - ps-cgit/blob - shared.c
Free reflists after usage
[ps-cgit] / shared.c
1 /* shared.c: global vars + some callback functions
2  *
3  * Copyright (C) 2006 Lars Hjemli
4  *
5  * Licensed under GNU General Public License v2
6  *   (see COPYING for full license text)
7  */
8
9 #include "cgit.h"
10 #include <stdio.h>
11
12 struct cgit_repolist cgit_repolist;
13 struct cgit_context ctx;
14
15 int chk_zero(int result, char *msg)
16 {
17         if (result != 0)
18                 die("%s: %s", msg, strerror(errno));
19         return result;
20 }
21
22 int chk_positive(int result, char *msg)
23 {
24         if (result <= 0)
25                 die("%s: %s", msg, strerror(errno));
26         return result;
27 }
28
29 int chk_non_negative(int result, char *msg)
30 {
31         if (result < 0)
32                 die("%s: %s", msg, strerror(errno));
33         return result;
34 }
35
36 char *cgit_default_repo_desc = "[no description]";
37 struct cgit_repo *cgit_add_repo(const char *url)
38 {
39         struct cgit_repo *ret;
40
41         if (++cgit_repolist.count > cgit_repolist.length) {
42                 if (cgit_repolist.length == 0)
43                         cgit_repolist.length = 8;
44                 else
45                         cgit_repolist.length *= 2;
46                 cgit_repolist.repos = xrealloc(cgit_repolist.repos,
47                                                cgit_repolist.length *
48                                                sizeof(struct cgit_repo));
49         }
50
51         ret = &cgit_repolist.repos[cgit_repolist.count-1];
52         memset(ret, 0, sizeof(struct cgit_repo));
53         ret->url = trim_end(url, '/');
54         ret->name = ret->url;
55         ret->path = NULL;
56         ret->desc = cgit_default_repo_desc;
57         ret->owner = NULL;
58         ret->section = ctx.cfg.section;
59         ret->snapshots = ctx.cfg.snapshots;
60         ret->enable_commit_graph = ctx.cfg.enable_commit_graph;
61         ret->enable_log_filecount = ctx.cfg.enable_log_filecount;
62         ret->enable_log_linecount = ctx.cfg.enable_log_linecount;
63         ret->enable_remote_branches = ctx.cfg.enable_remote_branches;
64         ret->enable_subject_links = ctx.cfg.enable_subject_links;
65         ret->max_stats = ctx.cfg.max_stats;
66         ret->commit_sort = ctx.cfg.commit_sort;
67         ret->module_link = ctx.cfg.module_link;
68         ret->readme = ctx.cfg.readme;
69         ret->mtime = -1;
70         ret->about_filter = ctx.cfg.about_filter;
71         ret->commit_filter = ctx.cfg.commit_filter;
72         ret->source_filter = ctx.cfg.source_filter;
73         ret->clone_url = ctx.cfg.clone_url;
74         ret->submodules.strdup_strings = 1;
75         return ret;
76 }
77
78 struct cgit_repo *cgit_get_repoinfo(const char *url)
79 {
80         int i;
81         struct cgit_repo *repo;
82
83         for (i = 0; i < cgit_repolist.count; i++) {
84                 repo = &cgit_repolist.repos[i];
85                 if (!strcmp(repo->url, url))
86                         return repo;
87         }
88         return NULL;
89 }
90
91 void *cgit_free_commitinfo(struct commitinfo *info)
92 {
93         free(info->author);
94         free(info->author_email);
95         free(info->committer);
96         free(info->committer_email);
97         free(info->subject);
98         free(info->msg);
99         free(info->msg_encoding);
100         free(info);
101         return NULL;
102 }
103
104 char *trim_end(const char *str, char c)
105 {
106         int len;
107
108         if (str == NULL)
109                 return NULL;
110         len = strlen(str);
111         while (len > 0 && str[len - 1] == c)
112                 len--;
113         if (len == 0)
114                 return NULL;
115         return xstrndup(str, len);
116 }
117
118 char *strlpart(char *txt, int maxlen)
119 {
120         char *result;
121
122         if (!txt)
123                 return txt;
124
125         if (strlen(txt) <= maxlen)
126                 return txt;
127         result = xmalloc(maxlen + 1);
128         memcpy(result, txt, maxlen - 3);
129         result[maxlen-1] = result[maxlen-2] = result[maxlen-3] = '.';
130         result[maxlen] = '\0';
131         return result;
132 }
133
134 char *strrpart(char *txt, int maxlen)
135 {
136         char *result;
137
138         if (!txt)
139                 return txt;
140
141         if (strlen(txt) <= maxlen)
142                 return txt;
143         result = xmalloc(maxlen + 1);
144         memcpy(result + 3, txt + strlen(txt) - maxlen + 4, maxlen - 3);
145         result[0] = result[1] = result[2] = '.';
146         return result;
147 }
148
149 void cgit_add_ref(struct reflist *list, struct refinfo *ref)
150 {
151         size_t size;
152
153         if (list->count >= list->alloc) {
154                 list->alloc += (list->alloc ? list->alloc : 4);
155                 size = list->alloc * sizeof(struct refinfo *);
156                 list->refs = xrealloc(list->refs, size);
157         }
158         list->refs[list->count++] = ref;
159 }
160
161 static struct refinfo *cgit_mk_refinfo(const char *refname, const unsigned char *sha1)
162 {
163         struct refinfo *ref;
164
165         ref = xmalloc(sizeof (struct refinfo));
166         ref->refname = xstrdup(refname);
167         ref->object = parse_object(sha1);
168         switch (ref->object->type) {
169         case OBJ_TAG:
170                 ref->tag = cgit_parse_tag((struct tag *)ref->object);
171                 break;
172         case OBJ_COMMIT:
173                 ref->commit = cgit_parse_commit((struct commit *)ref->object);
174                 break;
175         }
176         return ref;
177 }
178
179 static void cgit_free_taginfo(struct taginfo *tag)
180 {
181         if (tag->tagger)
182                 free(tag->tagger);
183         if (tag->tagger_email)
184                 free(tag->tagger_email);
185         if (tag->msg)
186                 free(tag->msg);
187         free(tag);
188 }
189
190 static void cgit_free_refinfo(struct refinfo *ref)
191 {
192         if (ref->refname)
193                 free((char *)ref->refname);
194         switch (ref->object->type) {
195         case OBJ_TAG:
196                 cgit_free_taginfo(ref->tag);
197                 break;
198         case OBJ_COMMIT:
199                 cgit_free_commitinfo(ref->commit);
200                 break;
201         }
202         free(ref);
203 }
204
205 void cgit_free_reflist_inner(struct reflist *list)
206 {
207         int i;
208
209         for (i = 0; i < list->count; i++) {
210                 cgit_free_refinfo(list->refs[i]);
211         }
212         free(list->refs);
213 }
214
215 int cgit_refs_cb(const char *refname, const unsigned char *sha1, int flags,
216                   void *cb_data)
217 {
218         struct reflist *list = (struct reflist *)cb_data;
219         struct refinfo *info = cgit_mk_refinfo(refname, sha1);
220
221         if (info)
222                 cgit_add_ref(list, info);
223         return 0;
224 }
225
226 static void cgit_diff_tree_cb(struct diff_queue_struct *q,
227                               struct diff_options *options, void *data)
228 {
229         int i;
230
231         for (i = 0; i < q->nr; i++) {
232                 if (q->queue[i]->status == 'U')
233                         continue;
234                 ((filepair_fn)data)(q->queue[i]);
235         }
236 }
237
238 static int load_mmfile(mmfile_t *file, const unsigned char *sha1)
239 {
240         enum object_type type;
241
242         if (is_null_sha1(sha1)) {
243                 file->ptr = (char *)"";
244                 file->size = 0;
245         } else {
246                 file->ptr = read_sha1_file(sha1, &type,
247                                            (unsigned long *)&file->size);
248         }
249         return 1;
250 }
251
252 /*
253  * Receive diff-buffers from xdiff and concatenate them as
254  * needed across multiple callbacks.
255  *
256  * This is basically a copy of xdiff-interface.c/xdiff_outf(),
257  * ripped from git and modified to use globals instead of
258  * a special callback-struct.
259  */
260 char *diffbuf = NULL;
261 int buflen = 0;
262
263 static int filediff_cb(void *priv, mmbuffer_t *mb, int nbuf)
264 {
265         int i;
266
267         for (i = 0; i < nbuf; i++) {
268                 if (mb[i].ptr[mb[i].size-1] != '\n') {
269                         /* Incomplete line */
270                         diffbuf = xrealloc(diffbuf, buflen + mb[i].size);
271                         memcpy(diffbuf + buflen, mb[i].ptr, mb[i].size);
272                         buflen += mb[i].size;
273                         continue;
274                 }
275
276                 /* we have a complete line */
277                 if (!diffbuf) {
278                         ((linediff_fn)priv)(mb[i].ptr, mb[i].size);
279                         continue;
280                 }
281                 diffbuf = xrealloc(diffbuf, buflen + mb[i].size);
282                 memcpy(diffbuf + buflen, mb[i].ptr, mb[i].size);
283                 ((linediff_fn)priv)(diffbuf, buflen + mb[i].size);
284                 free(diffbuf);
285                 diffbuf = NULL;
286                 buflen = 0;
287         }
288         if (diffbuf) {
289                 ((linediff_fn)priv)(diffbuf, buflen);
290                 free(diffbuf);
291                 diffbuf = NULL;
292                 buflen = 0;
293         }
294         return 0;
295 }
296
297 int cgit_diff_files(const unsigned char *old_sha1,
298                     const unsigned char *new_sha1, unsigned long *old_size,
299                     unsigned long *new_size, int *binary, int context,
300                     int ignorews, linediff_fn fn)
301 {
302         mmfile_t file1, file2;
303         xpparam_t diff_params;
304         xdemitconf_t emit_params;
305         xdemitcb_t emit_cb;
306
307         if (!load_mmfile(&file1, old_sha1) || !load_mmfile(&file2, new_sha1))
308                 return 1;
309
310         *old_size = file1.size;
311         *new_size = file2.size;
312
313         if ((file1.ptr && buffer_is_binary(file1.ptr, file1.size)) ||
314             (file2.ptr && buffer_is_binary(file2.ptr, file2.size))) {
315                 *binary = 1;
316                 if (file1.size)
317                         free(file1.ptr);
318                 if (file2.size)
319                         free(file2.ptr);
320                 return 0;
321         }
322
323         memset(&diff_params, 0, sizeof(diff_params));
324         memset(&emit_params, 0, sizeof(emit_params));
325         memset(&emit_cb, 0, sizeof(emit_cb));
326         diff_params.flags = XDF_NEED_MINIMAL;
327         if (ignorews)
328                 diff_params.flags |= XDF_IGNORE_WHITESPACE;
329         emit_params.ctxlen = context > 0 ? context : 3;
330         emit_params.flags = XDL_EMIT_FUNCNAMES;
331         emit_cb.outf = filediff_cb;
332         emit_cb.priv = fn;
333         xdl_diff(&file1, &file2, &diff_params, &emit_params, &emit_cb);
334         if (file1.size)
335                 free(file1.ptr);
336         if (file2.size)
337                 free(file2.ptr);
338         return 0;
339 }
340
341 void cgit_diff_tree(const unsigned char *old_sha1,
342                     const unsigned char *new_sha1,
343                     filepair_fn fn, const char *prefix, int ignorews)
344 {
345         struct diff_options opt;
346         struct pathspec_item item;
347
348         diff_setup(&opt);
349         opt.output_format = DIFF_FORMAT_CALLBACK;
350         opt.detect_rename = 1;
351         opt.rename_limit = ctx.cfg.renamelimit;
352         DIFF_OPT_SET(&opt, RECURSIVE);
353         if (ignorews)
354                 DIFF_XDL_SET(&opt, IGNORE_WHITESPACE);
355         opt.format_callback = cgit_diff_tree_cb;
356         opt.format_callback_data = fn;
357         if (prefix) {
358                 item.match = prefix;
359                 item.len = strlen(prefix);
360                 opt.pathspec.nr = 1;
361                 opt.pathspec.items = &item;
362         }
363         diff_setup_done(&opt);
364
365         if (old_sha1 && !is_null_sha1(old_sha1))
366                 diff_tree_sha1(old_sha1, new_sha1, "", &opt);
367         else
368                 diff_root_tree_sha1(new_sha1, "", &opt);
369         diffcore_std(&opt);
370         diff_flush(&opt);
371 }
372
373 void cgit_diff_commit(struct commit *commit, filepair_fn fn, const char *prefix)
374 {
375         unsigned char *old_sha1 = NULL;
376
377         if (commit->parents)
378                 old_sha1 = commit->parents->item->object.sha1;
379         cgit_diff_tree(old_sha1, commit->object.sha1, fn, prefix,
380                        ctx.qry.ignorews);
381 }
382
383 int cgit_parse_snapshots_mask(const char *str)
384 {
385         const struct cgit_snapshot_format *f;
386         static const char *delim = " \t,:/|;";
387         int tl, sl, rv = 0;
388
389         /* favor legacy setting */
390         if (atoi(str))
391                 return 1;
392         for (;;) {
393                 str += strspn(str, delim);
394                 tl = strcspn(str, delim);
395                 if (!tl)
396                         break;
397                 for (f = cgit_snapshot_formats; f->suffix; f++) {
398                         sl = strlen(f->suffix);
399                         if ((tl == sl && !strncmp(f->suffix, str, tl)) ||
400                            (tl == sl - 1 && !strncmp(f->suffix + 1, str, tl - 1))) {
401                                 rv |= f->bit;
402                                 break;
403                         }
404                 }
405                 str += tl;
406         }
407         return rv;
408 }
409
410 typedef struct {
411         char * name;
412         char * value;
413 } cgit_env_var;
414
415 void cgit_prepare_repo_env(struct cgit_repo * repo)
416 {
417         cgit_env_var env_vars[] = {
418                 { .name = "CGIT_REPO_URL", .value = repo->url },
419                 { .name = "CGIT_REPO_NAME", .value = repo->name },
420                 { .name = "CGIT_REPO_PATH", .value = repo->path },
421                 { .name = "CGIT_REPO_OWNER", .value = repo->owner },
422                 { .name = "CGIT_REPO_DEFBRANCH", .value = repo->defbranch },
423                 { .name = "CGIT_REPO_SECTION", .value = repo->section },
424                 { .name = "CGIT_REPO_CLONE_URL", .value = repo->clone_url }
425         };
426         int env_var_count = ARRAY_SIZE(env_vars);
427         cgit_env_var *p, *q;
428         static char *warn = "cgit warning: failed to set env: %s=%s\n";
429
430         p = env_vars;
431         q = p + env_var_count;
432         for (; p < q; p++)
433                 if (p->value && setenv(p->name, p->value, 1))
434                         fprintf(stderr, warn, p->name, p->value);
435 }
436
437 int cgit_open_filter(struct cgit_filter *filter)
438 {
439
440         filter->old_stdout = chk_positive(dup(STDOUT_FILENO),
441                 "Unable to duplicate STDOUT");
442         chk_zero(pipe(filter->pipe_fh), "Unable to create pipe to subprocess");
443         filter->pid = chk_non_negative(fork(), "Unable to create subprocess");
444         if (filter->pid == 0) {
445                 close(filter->pipe_fh[1]);
446                 chk_non_negative(dup2(filter->pipe_fh[0], STDIN_FILENO),
447                         "Unable to use pipe as STDIN");
448                 execvp(filter->cmd, filter->argv);
449                 die("Unable to exec subprocess %s: %s (%d)", filter->cmd,
450                         strerror(errno), errno);
451         }
452         close(filter->pipe_fh[0]);
453         chk_non_negative(dup2(filter->pipe_fh[1], STDOUT_FILENO),
454                 "Unable to use pipe as STDOUT");
455         close(filter->pipe_fh[1]);
456         return 0;
457 }
458
459 int cgit_close_filter(struct cgit_filter *filter)
460 {
461         chk_non_negative(dup2(filter->old_stdout, STDOUT_FILENO),
462                 "Unable to restore STDOUT");
463         close(filter->old_stdout);
464         if (filter->pid < 0)
465                 return 0;
466         waitpid(filter->pid, &filter->exitstatus, 0);
467         if (WIFEXITED(filter->exitstatus) && !WEXITSTATUS(filter->exitstatus))
468                 return 0;
469         die("Subprocess %s exited abnormally", filter->cmd);
470 }
471
472 /* Read the content of the specified file into a newly allocated buffer,
473  * zeroterminate the buffer and return 0 on success, errno otherwise.
474  */
475 int readfile(const char *path, char **buf, size_t *size)
476 {
477         int fd, e;
478         struct stat st;
479
480         fd = open(path, O_RDONLY);
481         if (fd == -1)
482                 return errno;
483         if (fstat(fd, &st)) {
484                 e = errno;
485                 close(fd);
486                 return e;
487         }
488         if (!S_ISREG(st.st_mode)) {
489                 close(fd);
490                 return EISDIR;
491         }
492         *buf = xmalloc(st.st_size + 1);
493         *size = read_in_full(fd, *buf, st.st_size);
494         e = errno;
495         (*buf)[*size] = '\0';
496         close(fd);
497         return (*size == st.st_size ? 0 : e);
498 }
499
500 static int is_token_char(char c)
501 {
502         return isalnum(c) || c == '_';
503 }
504
505 /* Replace name with getenv(name), return pointer to zero-terminating char
506  */
507 static char *expand_macro(char *name, int maxlength)
508 {
509         char *value;
510         int len;
511
512         len = 0;
513         value = getenv(name);
514         if (value) {
515                 len = strlen(value);
516                 if (len > maxlength)
517                         len = maxlength;
518                 strncpy(name, value, len);
519         }
520         return name + len;
521 }
522
523 #define EXPBUFSIZE (1024 * 8)
524
525 /* Replace all tokens prefixed by '$' in the specified text with the
526  * value of the named environment variable.
527  * NB: the return value is a static buffer, i.e. it must be strdup'd
528  * by the caller.
529  */
530 char *expand_macros(const char *txt)
531 {
532         static char result[EXPBUFSIZE];
533         char *p, *start;
534         int len;
535
536         p = result;
537         start = NULL;
538         while (p < result + EXPBUFSIZE - 1 && txt && *txt) {
539                 *p = *txt;
540                 if (start) {
541                         if (!is_token_char(*txt)) {
542                                 if (p - start > 0) {
543                                         *p = '\0';
544                                         len = result + EXPBUFSIZE - start - 1;
545                                         p = expand_macro(start, len) - 1;
546                                 }
547                                 start = NULL;
548                                 txt--;
549                         }
550                         p++;
551                         txt++;
552                         continue;
553                 }
554                 if (*txt == '$') {
555                         start = p;
556                         txt++;
557                         continue;
558                 }
559                 p++;
560                 txt++;
561         }
562         *p = '\0';
563         if (start && p - start > 0) {
564                 len = result + EXPBUFSIZE - start - 1;
565                 p = expand_macro(start, len);
566                 *p = '\0';
567         }
568         return result;
569 }