]> git.armaanb.net Git - stagit.git/blob - stagit.c
Add cachefile for each repo.
[stagit.git] / stagit.c
1 #include <sys/stat.h>
2 #include <sys/types.h>
3
4 #include <err.h>
5 #include <errno.h>
6 #include <libgen.h>
7 #include <limits.h>
8 #include <stdint.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <time.h>
13 #include <unistd.h>
14
15 #include <git2.h>
16
17 #include "compat.h"
18
19 struct deltainfo {
20         git_patch *patch;
21
22         size_t addcount;
23         size_t delcount;
24 };
25
26 struct commitinfo {
27         const git_oid *id;
28
29         char oid[GIT_OID_HEXSZ + 1];
30         char parentoid[GIT_OID_HEXSZ + 1];
31
32         const git_signature *author;
33         const git_signature *committer;
34         const char          *summary;
35         const char          *msg;
36
37         git_diff   *diff;
38         git_commit *commit;
39         git_commit *parent;
40         git_tree   *commit_tree;
41         git_tree   *parent_tree;
42
43         size_t addcount;
44         size_t delcount;
45         size_t filecount;
46
47         struct deltainfo **deltas;
48         size_t ndeltas;
49 };
50
51 static git_repository *repo;
52
53 static const char *relpath = "";
54 static const char *repodir;
55
56 static char *name = "";
57 static char *strippedname = "";
58 static char description[255];
59 static char cloneurl[1024];
60 static char *submodules;
61 static char *licensefiles[] = { "HEAD:LICENSE", "HEAD:LICENSE.md", "HEAD:COPYING" };
62 static char *license;
63 static char *readmefiles[] = { "HEAD:README", "HEAD:README.md" };
64 static char *readme;
65 static long long nlogcommits = -1; /* < 0 indicates not used */
66
67 /* cache */
68 static git_oid lastoid;
69 static char lastoidstr[GIT_OID_HEXSZ + 2]; /* id + newline + NUL byte */
70 static FILE *rcachefp, *wcachefp;
71 static const char *cachefile;
72
73 void
74 joinpath(char *buf, size_t bufsiz, const char *path, const char *path2)
75 {
76         int r;
77
78         r = snprintf(buf, bufsiz, "%s%s%s",
79                 path, path[0] && path[strlen(path) - 1] != '/' ? "/" : "", path2);
80         if (r < 0 || (size_t)r >= bufsiz)
81                 errx(1, "path truncated: '%s%s%s'",
82                         path, path[0] && path[strlen(path) - 1] != '/' ? "/" : "", path2);
83 }
84
85 void
86 deltainfo_free(struct deltainfo *di)
87 {
88         if (!di)
89                 return;
90         git_patch_free(di->patch);
91         memset(di, 0, sizeof(*di));
92         free(di);
93 }
94
95 int
96 commitinfo_getstats(struct commitinfo *ci)
97 {
98         struct deltainfo *di;
99         git_diff_options opts;
100         git_diff_find_options fopts;
101         const git_diff_delta *delta;
102         const git_diff_hunk *hunk;
103         const git_diff_line *line;
104         git_patch *patch = NULL;
105         size_t ndeltas, nhunks, nhunklines;
106         size_t i, j, k;
107
108         if (git_tree_lookup(&(ci->commit_tree), repo, git_commit_tree_id(ci->commit)))
109                 goto err;
110         if (!git_commit_parent(&(ci->parent), ci->commit, 0)) {
111                 if (git_tree_lookup(&(ci->parent_tree), repo, git_commit_tree_id(ci->parent))) {
112                         ci->parent = NULL;
113                         ci->parent_tree = NULL;
114                 }
115         }
116
117         git_diff_init_options(&opts, GIT_DIFF_OPTIONS_VERSION);
118         opts.flags |= GIT_DIFF_DISABLE_PATHSPEC_MATCH |
119                       GIT_DIFF_IGNORE_SUBMODULES |
120                       GIT_DIFF_INCLUDE_TYPECHANGE;
121         if (git_diff_tree_to_tree(&(ci->diff), repo, ci->parent_tree, ci->commit_tree, &opts))
122                 goto err;
123
124         if (git_diff_find_init_options(&fopts, GIT_DIFF_FIND_OPTIONS_VERSION))
125                 goto err;
126         /* find renames and copies, exact matches (no heuristic) for renames. */
127         fopts.flags |= GIT_DIFF_FIND_RENAMES | GIT_DIFF_FIND_COPIES |
128                        GIT_DIFF_FIND_EXACT_MATCH_ONLY;
129         if (git_diff_find_similar(ci->diff, &fopts))
130                 goto err;
131
132         ndeltas = git_diff_num_deltas(ci->diff);
133         if (ndeltas && !(ci->deltas = calloc(ndeltas, sizeof(struct deltainfo *))))
134                 err(1, "calloc");
135
136         for (i = 0; i < ndeltas; i++) {
137                 if (git_patch_from_diff(&patch, ci->diff, i))
138                         goto err;
139
140                 if (!(di = calloc(1, sizeof(struct deltainfo))))
141                         err(1, "calloc");
142                 di->patch = patch;
143                 ci->deltas[i] = di;
144
145                 delta = git_patch_get_delta(patch);
146
147                 /* skip stats for binary data */
148                 if (delta->flags & GIT_DIFF_FLAG_BINARY)
149                         continue;
150
151                 nhunks = git_patch_num_hunks(patch);
152                 for (j = 0; j < nhunks; j++) {
153                         if (git_patch_get_hunk(&hunk, &nhunklines, patch, j))
154                                 break;
155                         for (k = 0; ; k++) {
156                                 if (git_patch_get_line_in_hunk(&line, patch, j, k))
157                                         break;
158                                 if (line->old_lineno == -1) {
159                                         di->addcount++;
160                                         ci->addcount++;
161                                 } else if (line->new_lineno == -1) {
162                                         di->delcount++;
163                                         ci->delcount++;
164                                 }
165                         }
166                 }
167         }
168         ci->ndeltas = i;
169         ci->filecount = i;
170
171         return 0;
172
173 err:
174         git_diff_free(ci->diff);
175         ci->diff = NULL;
176         git_tree_free(ci->commit_tree);
177         ci->commit_tree = NULL;
178         git_tree_free(ci->parent_tree);
179         ci->parent_tree = NULL;
180         git_commit_free(ci->parent);
181         ci->parent = NULL;
182
183         if (ci->deltas)
184                 for (i = 0; i < ci->ndeltas; i++)
185                         deltainfo_free(ci->deltas[i]);
186         free(ci->deltas);
187         ci->deltas = NULL;
188         ci->ndeltas = 0;
189         ci->addcount = 0;
190         ci->delcount = 0;
191         ci->filecount = 0;
192
193         return -1;
194 }
195
196 void
197 commitinfo_free(struct commitinfo *ci)
198 {
199         size_t i;
200
201         if (!ci)
202                 return;
203         if (ci->deltas)
204                 for (i = 0; i < ci->ndeltas; i++)
205                         deltainfo_free(ci->deltas[i]);
206
207         free(ci->deltas);
208         git_diff_free(ci->diff);
209         git_tree_free(ci->commit_tree);
210         git_tree_free(ci->parent_tree);
211         git_commit_free(ci->commit);
212         git_commit_free(ci->parent);
213         memset(ci, 0, sizeof(*ci));
214         free(ci);
215 }
216
217 struct commitinfo *
218 commitinfo_getbyoid(const git_oid *id)
219 {
220         struct commitinfo *ci;
221
222         if (!(ci = calloc(1, sizeof(struct commitinfo))))
223                 err(1, "calloc");
224
225         if (git_commit_lookup(&(ci->commit), repo, id))
226                 goto err;
227         ci->id = id;
228
229         git_oid_tostr(ci->oid, sizeof(ci->oid), git_commit_id(ci->commit));
230         git_oid_tostr(ci->parentoid, sizeof(ci->parentoid), git_commit_parent_id(ci->commit, 0));
231
232         ci->author = git_commit_author(ci->commit);
233         ci->committer = git_commit_committer(ci->commit);
234         ci->summary = git_commit_summary(ci->commit);
235         ci->msg = git_commit_message(ci->commit);
236
237         return ci;
238
239 err:
240         commitinfo_free(ci);
241
242         return NULL;
243 }
244
245 FILE *
246 efopen(const char *name, const char *flags)
247 {
248         FILE *fp;
249
250         if (!(fp = fopen(name, flags)))
251                 err(1, "fopen: '%s'", name);
252
253         return fp;
254 }
255
256 /* Escape characters below as HTML 2.0 / XML 1.0. */
257 void
258 xmlencode(FILE *fp, const char *s, size_t len)
259 {
260         size_t i;
261
262         for (i = 0; *s && i < len; s++, i++) {
263                 switch(*s) {
264                 case '<':  fputs("&lt;",   fp); break;
265                 case '>':  fputs("&gt;",   fp); break;
266                 case '\'': fputs("&#39;",  fp); break;
267                 case '&':  fputs("&amp;",  fp); break;
268                 case '"':  fputs("&quot;", fp); break;
269                 default:   fputc(*s, fp);
270                 }
271         }
272 }
273
274 int
275 mkdirp(const char *path)
276 {
277         char tmp[PATH_MAX], *p;
278
279         if (strlcpy(tmp, path, sizeof(tmp)) >= sizeof(tmp))
280                 errx(1, "path truncated: '%s'", path);
281         for (p = tmp + (tmp[0] == '/'); *p; p++) {
282                 if (*p != '/')
283                         continue;
284                 *p = '\0';
285                 if (mkdir(tmp, S_IRWXU | S_IRWXG | S_IRWXO) < 0 && errno != EEXIST)
286                         return -1;
287                 *p = '/';
288         }
289         if (mkdir(tmp, S_IRWXU | S_IRWXG | S_IRWXO) < 0 && errno != EEXIST)
290                 return -1;
291         return 0;
292 }
293
294 void
295 printtimez(FILE *fp, const git_time *intime)
296 {
297         struct tm *intm;
298         time_t t;
299         char out[32];
300
301         t = (time_t)intime->time;
302         if (!(intm = gmtime(&t)))
303                 return;
304         strftime(out, sizeof(out), "%Y-%m-%dT%H:%M:%SZ", intm);
305         fputs(out, fp);
306 }
307
308 void
309 printtime(FILE *fp, const git_time *intime)
310 {
311         struct tm *intm;
312         time_t t;
313         char out[32];
314
315         t = (time_t)intime->time + (intime->offset * 60);
316         if (!(intm = gmtime(&t)))
317                 return;
318         strftime(out, sizeof(out), "%a, %e %b %Y %H:%M:%S", intm);
319         if (intime->offset < 0)
320                 fprintf(fp, "%s -%02d%02d", out,
321                             -(intime->offset) / 60, -(intime->offset) % 60);
322         else
323                 fprintf(fp, "%s +%02d%02d", out,
324                             intime->offset / 60, intime->offset % 60);
325 }
326
327 void
328 printtimeshort(FILE *fp, const git_time *intime)
329 {
330         struct tm *intm;
331         time_t t;
332         char out[32];
333
334         t = (time_t)intime->time;
335         if (!(intm = gmtime(&t)))
336                 return;
337         strftime(out, sizeof(out), "%Y-%m-%d %H:%M", intm);
338         fputs(out, fp);
339 }
340
341 void
342 writeheader(FILE *fp, const char *title)
343 {
344         fputs("<!DOCTYPE html>\n"
345                 "<html>\n<head>\n"
346                 "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n"
347                 "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n"
348                 "<title>", fp);
349         xmlencode(fp, title, strlen(title));
350         if (title[0] && strippedname[0])
351                 fputs(" - ", fp);
352         xmlencode(fp, strippedname, strlen(strippedname));
353         if (description[0])
354                 fputs(" - ", fp);
355         xmlencode(fp, description, strlen(description));
356         fprintf(fp, "</title>\n<link rel=\"icon\" type=\"image/png\" href=\"%sfavicon.png\" />\n", relpath);
357         fprintf(fp, "<link rel=\"alternate\" type=\"application/atom+xml\" title=\"%s Atom Feed\" href=\"%satom.xml\" />\n",
358                 name, relpath);
359         fprintf(fp, "<link rel=\"stylesheet\" type=\"text/css\" href=\"%sstyle.css\" />\n", relpath);
360         fputs("</head>\n<body>\n<table><tr><td>", fp);
361         fprintf(fp, "<a href=\"../%s\"><img src=\"%slogo.png\" alt=\"\" width=\"32\" height=\"32\" /></a>",
362                 relpath, relpath);
363         fputs("</td><td><h1>", fp);
364         xmlencode(fp, strippedname, strlen(strippedname));
365         fputs("</h1><span class=\"desc\">", fp);
366         xmlencode(fp, description, strlen(description));
367         fputs("</span></td></tr>", fp);
368         if (cloneurl[0]) {
369                 fputs("<tr class=\"url\"><td></td><td><span class=\"clone\">git clone <a href=\"", fp);
370                 xmlencode(fp, cloneurl, strlen(cloneurl));
371                 fputs("\">", fp);
372                 xmlencode(fp, cloneurl, strlen(cloneurl));
373                 fputs("</a></span></td></tr>", fp);
374         }
375         fputs("<tr><td></td><td>\n", fp);
376         fprintf(fp, "<a href=\"%slog.html\">Log</a> | ", relpath);
377         fprintf(fp, "<a href=\"%sfiles.html\">Files</a> | ", relpath);
378         fprintf(fp, "<a href=\"%srefs.html\">Refs</a>", relpath);
379         if (submodules)
380                 fprintf(fp, " | <a href=\"%sfile/%s.html\">Submodules</a>",
381                         relpath, submodules);
382         if (readme)
383                 fprintf(fp, " | <a href=\"%sfile/%s.html\">README</a>",
384                         relpath, readme);
385         if (license)
386                 fprintf(fp, " | <a href=\"%sfile/%s.html\">LICENSE</a>",
387                         relpath, license);
388         fputs("</td></tr></table>\n<hr/>\n<div id=\"content\">\n", fp);
389 }
390
391 void
392 writefooter(FILE *fp)
393 {
394         fputs("</div>\n</body>\n</html>\n", fp);
395 }
396
397 int
398 syntax_highlight(const char *filename, FILE *fp, const char *s, size_t len)
399 {
400         // Flush HTML-file
401         fflush(fp);
402         // Copy STDOUT
403         int stdout_copy = dup(1);
404         // Redirect STDOUT
405         dup2(fileno(fp), 1);
406
407         // Python Pygments script for syntax highlighting.
408         FILE *child = popen("./highlight", "w");
409         if (child == NULL) {
410                 printf("child is null: %s", strerror(errno));
411                 exit(1);
412         }
413         // Give filename through STDIN:
414         fprintf(child, "%s\n", filename);
415         // Give code to highlight through STDIN:
416         int lc;
417         size_t i;
418         for (i = 0; *s && i < len; s++, i++) {
419                 if (*s == '\n') lc++;
420                 fprintf(child, "%c", *s);
421         }
422
423         pclose(child);
424         fflush(stdout);
425         // Give back STDOUT.
426         dup2(stdout_copy, 1);
427         return lc;
428 }
429
430 int
431 writeblobhtml(const char *filename, FILE *fp, const git_blob *blob)
432 {
433         int lc = 0;
434         const char *s = git_blob_rawcontent(blob);
435         git_off_t len = git_blob_rawsize(blob);
436
437         if (len > 0) {
438                 lc = syntax_highlight(filename, fp, s, len);
439         }
440
441         return lc;
442 }
443
444 void
445 printcommit(FILE *fp, struct commitinfo *ci)
446 {
447         fprintf(fp, "<b>commit</b> <a href=\"%scommit/%s.html\">%s</a>\n",
448                 relpath, ci->oid, ci->oid);
449
450         if (ci->parentoid[0])
451                 fprintf(fp, "<b>parent</b> <a href=\"%scommit/%s.html\">%s</a>\n",
452                         relpath, ci->parentoid, ci->parentoid);
453
454         if (ci->author) {
455                 fputs("<b>Author:</b> ", fp);
456                 xmlencode(fp, ci->author->name, strlen(ci->author->name));
457                 fputs(" &lt;<a href=\"mailto:", fp);
458                 xmlencode(fp, ci->author->email, strlen(ci->author->email));
459                 fputs("\">", fp);
460                 xmlencode(fp, ci->author->email, strlen(ci->author->email));
461                 fputs("</a>&gt;\n<b>Date:</b>   ", fp);
462                 printtime(fp, &(ci->author->when));
463                 fputc('\n', fp);
464         }
465         if (ci->msg) {
466                 fputc('\n', fp);
467                 xmlencode(fp, ci->msg, strlen(ci->msg));
468                 fputc('\n', fp);
469         }
470 }
471
472 void
473 printshowfile(FILE *fp, struct commitinfo *ci)
474 {
475         const git_diff_delta *delta;
476         const git_diff_hunk *hunk;
477         const git_diff_line *line;
478         git_patch *patch;
479         size_t nhunks, nhunklines, changed, add, del, total, i, j, k;
480         char linestr[80];
481         int c;
482
483         printcommit(fp, ci);
484
485         if (!ci->deltas)
486                 return;
487
488         if (ci->filecount > 1000   ||
489             ci->ndeltas   > 1000   ||
490             ci->addcount  > 100000 ||
491             ci->delcount  > 100000) {
492                 fputs("Diff is too large, output suppressed.\n", fp);
493                 return;
494         }
495
496         /* diff stat */
497         fputs("<b>Diffstat:</b>\n<table>", fp);
498         for (i = 0; i < ci->ndeltas; i++) {
499                 delta = git_patch_get_delta(ci->deltas[i]->patch);
500
501                 switch (delta->status) {
502                 case GIT_DELTA_ADDED:      c = 'A'; break;
503                 case GIT_DELTA_COPIED:     c = 'C'; break;
504                 case GIT_DELTA_DELETED:    c = 'D'; break;
505                 case GIT_DELTA_MODIFIED:   c = 'M'; break;
506                 case GIT_DELTA_RENAMED:    c = 'R'; break;
507                 case GIT_DELTA_TYPECHANGE: c = 'T'; break;
508                 default:                   c = ' '; break;
509                 }
510                 if (c == ' ')
511                         fprintf(fp, "<tr><td>%c", c);
512                 else
513                         fprintf(fp, "<tr><td class=\"%c\">%c", c, c);
514
515                 fprintf(fp, "</td><td><a href=\"#h%zu\">", i);
516                 xmlencode(fp, delta->old_file.path, strlen(delta->old_file.path));
517                 if (strcmp(delta->old_file.path, delta->new_file.path)) {
518                         fputs(" -&gt; ", fp);
519                         xmlencode(fp, delta->new_file.path, strlen(delta->new_file.path));
520                 }
521
522                 add = ci->deltas[i]->addcount;
523                 del = ci->deltas[i]->delcount;
524                 changed = add + del;
525                 total = sizeof(linestr) - 2;
526                 if (changed > total) {
527                         if (add)
528                                 add = ((float)total / changed * add) + 1;
529                         if (del)
530                                 del = ((float)total / changed * del) + 1;
531                 }
532                 memset(&linestr, '+', add);
533                 memset(&linestr[add], '-', del);
534
535                 fprintf(fp, "</a></td><td> | </td><td class=\"num\">%zu</td><td><span class=\"i\">",
536                         ci->deltas[i]->addcount + ci->deltas[i]->delcount);
537                 fwrite(&linestr, 1, add, fp);
538                 fputs("</span><span class=\"d\">", fp);
539                 fwrite(&linestr[add], 1, del, fp);
540                 fputs("</span></td></tr>\n", fp);
541         }
542         fprintf(fp, "</table></pre><pre>%zu file%s changed, %zu insertion%s(+), %zu deletion%s(-)\n",
543                 ci->filecount, ci->filecount == 1 ? "" : "s",
544                 ci->addcount,  ci->addcount  == 1 ? "" : "s",
545                 ci->delcount,  ci->delcount  == 1 ? "" : "s");
546
547         fputs("<hr/>", fp);
548
549         for (i = 0; i < ci->ndeltas; i++) {
550                 patch = ci->deltas[i]->patch;
551                 delta = git_patch_get_delta(patch);
552                 fprintf(fp, "<b>diff --git a/<a id=\"h%zu\" href=\"%sfile/", i, relpath);
553                 xmlencode(fp, delta->old_file.path, strlen(delta->old_file.path));
554                 fputs(".html\">", fp);
555                 xmlencode(fp, delta->old_file.path, strlen(delta->old_file.path));
556                 fprintf(fp, "</a> b/<a href=\"%sfile/", relpath);
557                 xmlencode(fp, delta->new_file.path, strlen(delta->new_file.path));
558                 fprintf(fp, ".html\">");
559                 xmlencode(fp, delta->new_file.path, strlen(delta->new_file.path));
560                 fprintf(fp, "</a></b>\n");
561
562                 /* check binary data */
563                 if (delta->flags & GIT_DIFF_FLAG_BINARY) {
564                         fputs("Binary files differ.\n", fp);
565                         continue;
566                 }
567
568                 nhunks = git_patch_num_hunks(patch);
569                 for (j = 0; j < nhunks; j++) {
570                         if (git_patch_get_hunk(&hunk, &nhunklines, patch, j))
571                                 break;
572
573                         fprintf(fp, "<a href=\"#h%zu-%zu\" id=\"h%zu-%zu\" class=\"h\">", i, j, i, j);
574                         xmlencode(fp, hunk->header, hunk->header_len);
575                         fputs("</a>", fp);
576
577                         for (k = 0; ; k++) {
578                                 if (git_patch_get_line_in_hunk(&line, patch, j, k))
579                                         break;
580                                 if (line->old_lineno == -1)
581                                         fprintf(fp, "<a href=\"#h%zu-%zu-%zu\" id=\"h%zu-%zu-%zu\" class=\"i\">+",
582                                                 i, j, k, i, j, k);
583                                 else if (line->new_lineno == -1)
584                                         fprintf(fp, "<a href=\"#h%zu-%zu-%zu\" id=\"h%zu-%zu-%zu\" class=\"d\">-",
585                                                 i, j, k, i, j, k);
586                                 else
587                                         fputc(' ', fp);
588                                 xmlencode(fp, line->content, line->content_len);
589                                 if (line->old_lineno == -1 || line->new_lineno == -1)
590                                         fputs("</a>", fp);
591                         }
592                 }
593         }
594 }
595
596 void
597 writelogline(FILE *fp, struct commitinfo *ci)
598 {
599         fputs("<tr><td>", fp);
600         if (ci->author)
601                 printtimeshort(fp, &(ci->author->when));
602         fputs("</td><td>", fp);
603         if (ci->summary) {
604                 fprintf(fp, "<a href=\"%scommit/%s.html\">", relpath, ci->oid);
605                 xmlencode(fp, ci->summary, strlen(ci->summary));
606                 fputs("</a>", fp);
607         }
608         fputs("</td><td>", fp);
609         if (ci->author)
610                 xmlencode(fp, ci->author->name, strlen(ci->author->name));
611         fputs("</td><td class=\"num\" align=\"right\">", fp);
612         fprintf(fp, "%zu", ci->filecount);
613         fputs("</td><td class=\"num\" align=\"right\">", fp);
614         fprintf(fp, "+%zu", ci->addcount);
615         fputs("</td><td class=\"num\" align=\"right\">", fp);
616         fprintf(fp, "-%zu", ci->delcount);
617         fputs("</td></tr>\n", fp);
618 }
619
620 int
621 writelog(FILE *fp, const git_oid *oid)
622 {
623         struct commitinfo *ci;
624         git_revwalk *w = NULL;
625         git_oid id;
626         char path[PATH_MAX], oidstr[GIT_OID_HEXSZ + 1];
627         FILE *fpfile;
628         int r;
629
630         git_revwalk_new(&w, repo);
631         git_revwalk_push(w, oid);
632         git_revwalk_simplify_first_parent(w);
633
634         while (!git_revwalk_next(&id, w)) {
635                 relpath = "";
636
637                 if (cachefile && !memcmp(&id, &lastoid, sizeof(id)))
638                         break;
639
640                 git_oid_tostr(oidstr, sizeof(oidstr), &id);
641                 r = snprintf(path, sizeof(path), "commit/%s.html", oidstr);
642                 if (r < 0 || (size_t)r >= sizeof(path))
643                         errx(1, "path truncated: 'commit/%s.html'", oidstr);
644                 r = access(path, F_OK);
645
646                 /* optimization: if there are no log lines to write and
647                    the commit file already exists: skip the diffstat */
648                 if (!nlogcommits && !r)
649                         continue;
650
651                 if (!(ci = commitinfo_getbyoid(&id)))
652                         break;
653                 /* diffstat: for stagit HTML required for the log.html line */
654                 if (commitinfo_getstats(ci) == -1)
655                         goto err;
656
657                 if (nlogcommits < 0) {
658                         writelogline(fp, ci);
659                 } else if (nlogcommits > 0) {
660                         writelogline(fp, ci);
661                         nlogcommits--;
662                         if (!nlogcommits && ci->parentoid[0])
663                                 fputs("<tr><td></td><td colspan=\"5\">"
664                                       "More commits remaining [...]</td>"
665                                       "</tr>\n", fp);
666                 }
667
668                 if (cachefile)
669                         writelogline(wcachefp, ci);
670
671                 /* check if file exists if so skip it */
672                 if (r) {
673                         relpath = "../";
674                         fpfile = efopen(path, "w");
675                         writeheader(fpfile, ci->summary);
676                         fputs("<pre>", fpfile);
677                         printshowfile(fpfile, ci);
678                         fputs("</pre>\n", fpfile);
679                         writefooter(fpfile);
680                         fclose(fpfile);
681                 }
682 err:
683                 commitinfo_free(ci);
684         }
685         git_revwalk_free(w);
686
687         relpath = "";
688
689         return 0;
690 }
691
692 void
693 printcommitatom(FILE *fp, struct commitinfo *ci)
694 {
695         fputs("<entry>\n", fp);
696
697         fprintf(fp, "<id>%s</id>\n", ci->oid);
698         if (ci->author) {
699                 fputs("<published>", fp);
700                 printtimez(fp, &(ci->author->when));
701                 fputs("</published>\n", fp);
702         }
703         if (ci->committer) {
704                 fputs("<updated>", fp);
705                 printtimez(fp, &(ci->committer->when));
706                 fputs("</updated>\n", fp);
707         }
708         if (ci->summary) {
709                 fputs("<title type=\"text\">", fp);
710                 xmlencode(fp, ci->summary, strlen(ci->summary));
711                 fputs("</title>\n", fp);
712         }
713         fprintf(fp, "<link rel=\"alternate\" type=\"text/html\" href=\"commit/%s.html\" />\n",
714                 ci->oid);
715
716         if (ci->author) {
717                 fputs("<author>\n<name>", fp);
718                 xmlencode(fp, ci->author->name, strlen(ci->author->name));
719                 fputs("</name>\n<email>", fp);
720                 xmlencode(fp, ci->author->email, strlen(ci->author->email));
721                 fputs("</email>\n</author>\n", fp);
722         }
723
724         fputs("<content type=\"text\">", fp);
725         fprintf(fp, "commit %s\n", ci->oid);
726         if (ci->parentoid[0])
727                 fprintf(fp, "parent %s\n", ci->parentoid);
728         if (ci->author) {
729                 fputs("Author: ", fp);
730                 xmlencode(fp, ci->author->name, strlen(ci->author->name));
731                 fputs(" &lt;", fp);
732                 xmlencode(fp, ci->author->email, strlen(ci->author->email));
733                 fputs("&gt;\nDate:   ", fp);
734                 printtime(fp, &(ci->author->when));
735                 fputc('\n', fp);
736         }
737         if (ci->msg) {
738                 fputc('\n', fp);
739                 xmlencode(fp, ci->msg, strlen(ci->msg));
740         }
741         fputs("\n</content>\n</entry>\n", fp);
742 }
743
744 int
745 writeatom(FILE *fp)
746 {
747         struct commitinfo *ci;
748         git_revwalk *w = NULL;
749         git_oid id;
750         size_t i, m = 100; /* last 'm' commits */
751
752         fputs("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
753               "<feed xmlns=\"http://www.w3.org/2005/Atom\">\n<title>", fp);
754         xmlencode(fp, strippedname, strlen(strippedname));
755         fputs(", branch HEAD</title>\n<subtitle>", fp);
756         xmlencode(fp, description, strlen(description));
757         fputs("</subtitle>\n", fp);
758
759         git_revwalk_new(&w, repo);
760         git_revwalk_push_head(w);
761         git_revwalk_simplify_first_parent(w);
762
763         for (i = 0; i < m && !git_revwalk_next(&id, w); i++) {
764                 if (!(ci = commitinfo_getbyoid(&id)))
765                         break;
766                 printcommitatom(fp, ci);
767                 commitinfo_free(ci);
768         }
769         git_revwalk_free(w);
770
771         fputs("</feed>\n", fp);
772
773         return 0;
774 }
775
776 int
777 writeblob(git_object *obj, const char *fpath, const char *filename, git_off_t filesize)
778 {
779         char tmp[PATH_MAX] = "", *d;
780         const char *p;
781         int lc = 0;
782         FILE *fp;
783
784         if (strlcpy(tmp, fpath, sizeof(tmp)) >= sizeof(tmp))
785                 errx(1, "path truncated: '%s'", fpath);
786         if (!(d = dirname(tmp)))
787                 err(1, "dirname");
788         if (mkdirp(d))
789                 return -1;
790
791         for (p = fpath, tmp[0] = '\0'; *p; p++) {
792                 if (*p == '/' && strlcat(tmp, "../", sizeof(tmp)) >= sizeof(tmp))
793                         errx(1, "path truncated: '../%s'", tmp);
794         }
795         relpath = tmp;
796
797         fp = efopen(fpath, "w");
798         writeheader(fp, filename);
799         fputs("<p> ", fp);
800         xmlencode(fp, filename, strlen(filename));
801         fprintf(fp, " (%juB)", (uintmax_t)filesize);
802         fputs("</p><hr/>", fp);
803
804         if (git_blob_is_binary((git_blob *)obj)) {
805                 fputs("<p>Binary file.</p>\n", fp);
806         } else {
807                 lc = writeblobhtml(filename, fp, (git_blob *)obj);
808                 if (ferror(fp))
809                         err(1, "fwrite");
810         }
811         writefooter(fp);
812         fclose(fp);
813
814         relpath = "";
815
816         return lc;
817 }
818
819 const char *
820 filemode(git_filemode_t m)
821 {
822         static char mode[11];
823
824         memset(mode, '-', sizeof(mode) - 1);
825         mode[10] = '\0';
826
827         if (S_ISREG(m))
828                 mode[0] = '-';
829         else if (S_ISBLK(m))
830                 mode[0] = 'b';
831         else if (S_ISCHR(m))
832                 mode[0] = 'c';
833         else if (S_ISDIR(m))
834                 mode[0] = 'd';
835         else if (S_ISFIFO(m))
836                 mode[0] = 'p';
837         else if (S_ISLNK(m))
838                 mode[0] = 'l';
839         else if (S_ISSOCK(m))
840                 mode[0] = 's';
841         else
842                 mode[0] = '?';
843
844         if (m & S_IRUSR) mode[1] = 'r';
845         if (m & S_IWUSR) mode[2] = 'w';
846         if (m & S_IXUSR) mode[3] = 'x';
847         if (m & S_IRGRP) mode[4] = 'r';
848         if (m & S_IWGRP) mode[5] = 'w';
849         if (m & S_IXGRP) mode[6] = 'x';
850         if (m & S_IROTH) mode[7] = 'r';
851         if (m & S_IWOTH) mode[8] = 'w';
852         if (m & S_IXOTH) mode[9] = 'x';
853
854         if (m & S_ISUID) mode[3] = (mode[3] == 'x') ? 's' : 'S';
855         if (m & S_ISGID) mode[6] = (mode[6] == 'x') ? 's' : 'S';
856         if (m & S_ISVTX) mode[9] = (mode[9] == 'x') ? 't' : 'T';
857
858         return mode;
859 }
860
861 int
862 writefilestree(FILE *fp, git_tree *tree, const char *path)
863 {
864         const git_tree_entry *entry = NULL;
865         git_submodule *module = NULL;
866         git_object *obj = NULL;
867         git_off_t filesize;
868         const char *entryname;
869         char filepath[PATH_MAX], entrypath[PATH_MAX];
870         size_t count, i;
871         int lc, r, ret;
872
873         count = git_tree_entrycount(tree);
874         for (i = 0; i < count; i++) {
875                 if (!(entry = git_tree_entry_byindex(tree, i)) ||
876                     !(entryname = git_tree_entry_name(entry)))
877                         return -1;
878                 joinpath(entrypath, sizeof(entrypath), path, entryname);
879
880                 r = snprintf(filepath, sizeof(filepath), "file/%s.html",
881                          entrypath);
882                 if (r < 0 || (size_t)r >= sizeof(filepath))
883                         errx(1, "path truncated: 'file/%s.html'", entrypath);
884
885                 if (!git_tree_entry_to_object(&obj, repo, entry)) {
886                         switch (git_object_type(obj)) {
887                         case GIT_OBJ_BLOB:
888                                 break;
889                         case GIT_OBJ_TREE:
890                                 /* NOTE: recurses */
891                                 ret = writefilestree(fp, (git_tree *)obj,
892                                                      entrypath);
893                                 git_object_free(obj);
894                                 if (ret)
895                                         return ret;
896                                 continue;
897                         default:
898                                 git_object_free(obj);
899                                 continue;
900                         }
901
902                         filesize = git_blob_rawsize((git_blob *)obj);
903                         lc = writeblob(obj, filepath, entryname, filesize);
904
905                         fputs("<tr><td>", fp);
906                         fputs(filemode(git_tree_entry_filemode(entry)), fp);
907                         fprintf(fp, "</td><td><a href=\"%s", relpath);
908                         xmlencode(fp, filepath, strlen(filepath));
909                         fputs("\">", fp);
910                         xmlencode(fp, entrypath, strlen(entrypath));
911                         fputs("</a></td><td class=\"num\" align=\"right\">", fp);
912                         if (lc > 0)
913                                 fprintf(fp, "%dL", lc);
914                         else
915                                 fprintf(fp, "%juB", (uintmax_t)filesize);
916                         fputs("</td></tr>\n", fp);
917                         git_object_free(obj);
918                 } else if (!git_submodule_lookup(&module, repo, entryname)) {
919                         fprintf(fp, "<tr><td>m---------</td><td><a href=\"%sfile/.gitmodules.html\">",
920                                 relpath);
921                         xmlencode(fp, entrypath, strlen(entrypath));
922                         git_submodule_free(module);
923                         fputs("</a></td><td class=\"num\" align=\"right\"></td></tr>\n", fp);
924                 }
925         }
926
927         return 0;
928 }
929
930 int
931 writefiles(FILE *fp, const git_oid *id)
932 {
933         git_tree *tree = NULL;
934         git_commit *commit = NULL;
935         int ret = -1;
936
937         fputs("<table id=\"files\"><thead>\n<tr>"
938               "<td><b>Mode</b></td><td><b>Name</b></td>"
939               "<td class=\"num\" align=\"right\"><b>Size</b></td>"
940               "</tr>\n</thead><tbody>\n", fp);
941
942         if (!git_commit_lookup(&commit, repo, id) &&
943             !git_commit_tree(&tree, commit))
944                 ret = writefilestree(fp, tree, "");
945
946         fputs("</tbody></table>", fp);
947
948         git_commit_free(commit);
949         git_tree_free(tree);
950
951         return ret;
952 }
953
954 int
955 refs_cmp(const void *v1, const void *v2)
956 {
957         git_reference *r1 = (*(git_reference **)v1);
958         git_reference *r2 = (*(git_reference **)v2);
959         int r;
960
961         if ((r = git_reference_is_branch(r1) - git_reference_is_branch(r2)))
962                 return r;
963
964         return strcmp(git_reference_shorthand(r1),
965                       git_reference_shorthand(r2));
966 }
967
968 int
969 writerefs(FILE *fp)
970 {
971         struct commitinfo *ci;
972         const git_oid *id = NULL;
973         git_object *obj = NULL;
974         git_reference *dref = NULL, *r, *ref = NULL;
975         git_reference_iterator *it = NULL;
976         git_reference **refs = NULL;
977         size_t count, i, j, refcount;
978         const char *titles[] = { "Branches", "Tags" };
979         const char *ids[] = { "branches", "tags" };
980         const char *name;
981
982         if (git_reference_iterator_new(&it, repo))
983                 return -1;
984
985         for (refcount = 0; !git_reference_next(&ref, it); refcount++) {
986                 if (!(refs = reallocarray(refs, refcount + 1, sizeof(git_reference *))))
987                         err(1, "realloc");
988                 refs[refcount] = ref;
989         }
990         git_reference_iterator_free(it);
991
992         /* sort by type then shorthand name */
993         qsort(refs, refcount, sizeof(git_reference *), refs_cmp);
994
995         for (j = 0; j < 2; j++) {
996                 for (i = 0, count = 0; i < refcount; i++) {
997                         if (!(git_reference_is_branch(refs[i]) && j == 0) &&
998                             !(git_reference_is_tag(refs[i]) && j == 1))
999                                 continue;
1000
1001                         switch (git_reference_type(refs[i])) {
1002                         case GIT_REF_SYMBOLIC:
1003                                 if (git_reference_resolve(&dref, refs[i]))
1004                                         goto err;
1005                                 r = dref;
1006                                 break;
1007                         case GIT_REF_OID:
1008                                 r = refs[i];
1009                                 break;
1010                         default:
1011                                 continue;
1012                         }
1013                         if (!git_reference_target(r) ||
1014                             git_reference_peel(&obj, r, GIT_OBJ_ANY))
1015                                 goto err;
1016                         if (!(id = git_object_id(obj)))
1017                                 goto err;
1018                         if (!(ci = commitinfo_getbyoid(id)))
1019                                 break;
1020
1021                         /* print header if it has an entry (first). */
1022                         if (++count == 1) {
1023                                 fprintf(fp, "<h2>%s</h2><table id=\"%s\">"
1024                                         "<thead>\n<tr><td><b>Name</b></td>"
1025                                         "<td><b>Last commit date</b></td>"
1026                                         "<td><b>Author</b></td>\n</tr>\n"
1027                                         "</thead><tbody>\n",
1028                                          titles[j], ids[j]);
1029                         }
1030
1031                         relpath = "";
1032                         name = git_reference_shorthand(r);
1033
1034                         fputs("<tr><td>", fp);
1035                         xmlencode(fp, name, strlen(name));
1036                         fputs("</td><td>", fp);
1037                         if (ci->author)
1038                                 printtimeshort(fp, &(ci->author->when));
1039                         fputs("</td><td>", fp);
1040                         if (ci->author)
1041                                 xmlencode(fp, ci->author->name, strlen(ci->author->name));
1042                         fputs("</td></tr>\n", fp);
1043
1044                         relpath = "../";
1045
1046                         commitinfo_free(ci);
1047                         git_object_free(obj);
1048                         obj = NULL;
1049                         git_reference_free(dref);
1050                         dref = NULL;
1051                 }
1052                 /* table footer */
1053                 if (count)
1054                         fputs("</tbody></table><br/>", fp);
1055         }
1056
1057 err:
1058         git_object_free(obj);
1059         git_reference_free(dref);
1060
1061         for (i = 0; i < refcount; i++)
1062                 git_reference_free(refs[i]);
1063         free(refs);
1064
1065         return 0;
1066 }
1067
1068 void
1069 usage(char *argv0)
1070 {
1071         fprintf(stderr, "%s [-c cachefile | -l commits] repodir\n", argv0);
1072         exit(1);
1073 }
1074
1075 int
1076 main(int argc, char *argv[])
1077 {
1078         git_object *obj = NULL;
1079         const git_oid *head = NULL;
1080         mode_t mask;
1081         FILE *fp, *fpread;
1082         char path[PATH_MAX], repodirabs[PATH_MAX + 1], *p;
1083         char tmppath[64] = "cache.XXXXXXXXXXXX", buf[BUFSIZ];
1084         size_t n;
1085         int i, fd;
1086
1087         for (i = 1; i < argc; i++) {
1088                 if (argv[i][0] != '-') {
1089                         if (repodir)
1090                                 usage(argv[0]);
1091                         repodir = argv[i];
1092                 } else if (argv[i][1] == 'c') {
1093                         if (nlogcommits > 0 || i + 1 >= argc)
1094                                 usage(argv[0]);
1095                         cachefile = argv[++i];
1096                 } else if (argv[i][1] == 'l') {
1097                         if (cachefile || i + 1 >= argc)
1098                                 usage(argv[0]);
1099                         errno = 0;
1100                         nlogcommits = strtoll(argv[++i], &p, 10);
1101                         if (argv[i][0] == '\0' || *p != '\0' ||
1102                             nlogcommits <= 0 || errno)
1103                                 usage(argv[0]);
1104                 }
1105         }
1106         if (!repodir)
1107                 usage(argv[0]);
1108
1109         if (!realpath(repodir, repodirabs))
1110                 err(1, "realpath");
1111
1112         git_libgit2_init();
1113
1114 #ifdef __OpenBSD__
1115         if (unveil(repodir, "r") == -1)
1116                 err(1, "unveil: %s", repodir);
1117         if (unveil(".", "rwc") == -1)
1118                 err(1, "unveil: .");
1119         if (cachefile && unveil(cachefile, "rwc") == -1)
1120                 err(1, "unveil: %s", cachefile);
1121
1122         if (cachefile) {
1123                 if (pledge("stdio rpath wpath cpath fattr", NULL) == -1)
1124                         err(1, "pledge");
1125         } else {
1126                 if (pledge("stdio rpath wpath cpath", NULL) == -1)
1127                         err(1, "pledge");
1128         }
1129 #endif
1130
1131         if (git_repository_open_ext(&repo, repodir,
1132                 GIT_REPOSITORY_OPEN_NO_SEARCH, NULL) < 0) {
1133                 fprintf(stderr, "%s: cannot open repository\n", argv[0]);
1134                 return 1;
1135         }
1136
1137         /* find HEAD */
1138         if (!git_revparse_single(&obj, repo, "HEAD"))
1139                 head = git_object_id(obj);
1140         git_object_free(obj);
1141
1142         /* use directory name as name */
1143         if ((name = strrchr(repodirabs, '/')))
1144                 name++;
1145         else
1146                 name = "";
1147
1148         /* strip .git suffix */
1149         if (!(strippedname = strdup(name)))
1150                 err(1, "strdup");
1151         if ((p = strrchr(strippedname, '.')))
1152                 if (!strcmp(p, ".git"))
1153                         *p = '\0';
1154
1155         /* read description or .git/description */
1156         joinpath(path, sizeof(path), repodir, "description");
1157         if (!(fpread = fopen(path, "r"))) {
1158                 joinpath(path, sizeof(path), repodir, ".git/description");
1159                 fpread = fopen(path, "r");
1160         }
1161         if (fpread) {
1162                 if (!fgets(description, sizeof(description), fpread))
1163                         description[0] = '\0';
1164                 fclose(fpread);
1165         }
1166
1167         /* read url or .git/url */
1168         joinpath(path, sizeof(path), repodir, "url");
1169         if (!(fpread = fopen(path, "r"))) {
1170                 joinpath(path, sizeof(path), repodir, ".git/url");
1171                 fpread = fopen(path, "r");
1172         }
1173         if (fpread) {
1174                 if (!fgets(cloneurl, sizeof(cloneurl), fpread))
1175                         cloneurl[0] = '\0';
1176                 cloneurl[strcspn(cloneurl, "\n")] = '\0';
1177                 fclose(fpread);
1178         }
1179
1180         /* check LICENSE */
1181         for (i = 0; i < sizeof(licensefiles) / sizeof(*licensefiles) && !license; i++) {
1182                 if (!git_revparse_single(&obj, repo, licensefiles[i]) &&
1183                     git_object_type(obj) == GIT_OBJ_BLOB)
1184                         license = licensefiles[i] + strlen("HEAD:");
1185                 git_object_free(obj);
1186         }
1187
1188         /* check README */
1189         for (i = 0; i < sizeof(readmefiles) / sizeof(*readmefiles) && !readme; i++) {
1190                 if (!git_revparse_single(&obj, repo, readmefiles[i]) &&
1191                     git_object_type(obj) == GIT_OBJ_BLOB)
1192                         readme = readmefiles[i] + strlen("HEAD:");
1193                 git_object_free(obj);
1194         }
1195
1196         if (!git_revparse_single(&obj, repo, "HEAD:.gitmodules") &&
1197             git_object_type(obj) == GIT_OBJ_BLOB)
1198                 submodules = ".gitmodules";
1199         git_object_free(obj);
1200
1201         /* log for HEAD */
1202         fp = efopen("log.html", "w");
1203         relpath = "";
1204         mkdir("commit", S_IRWXU | S_IRWXG | S_IRWXO);
1205         writeheader(fp, "Log");
1206         fputs("<table id=\"log\"><thead>\n<tr><td><b>Date</b></td>"
1207               "<td><b>Commit</b></td>"
1208               "<td><b>Author</b></td><td class=\"num\" align=\"right\"><b>Files</b></td>"
1209               "<td class=\"num\" align=\"right\"><b>+</b></td>"
1210               "<td class=\"num\" align=\"right\"><b>-</b></td></tr>\n</thead><tbody>\n", fp);
1211
1212         if (cachefile && head) {
1213                 /* read from cache file (does not need to exist) */
1214                 if ((rcachefp = fopen(cachefile, "r"))) {
1215                         if (!fgets(lastoidstr, sizeof(lastoidstr), rcachefp))
1216                                 errx(1, "%s: no object id", cachefile);
1217                         if (git_oid_fromstr(&lastoid, lastoidstr))
1218                                 errx(1, "%s: invalid object id", cachefile);
1219                 }
1220
1221                 /* write log to (temporary) cache */
1222                 if ((fd = mkstemp(tmppath)) == -1)
1223                         err(1, "mkstemp");
1224                 if (!(wcachefp = fdopen(fd, "w")))
1225                         err(1, "fdopen: '%s'", tmppath);
1226                 /* write last commit id (HEAD) */
1227                 git_oid_tostr(buf, sizeof(buf), head);
1228                 fprintf(wcachefp, "%s\n", buf);
1229
1230                 writelog(fp, head);
1231
1232                 if (rcachefp) {
1233                         /* append previous log to log.html and the new cache */
1234                         while (!feof(rcachefp)) {
1235                                 n = fread(buf, 1, sizeof(buf), rcachefp);
1236                                 if (ferror(rcachefp))
1237                                         err(1, "fread");
1238                                 if (fwrite(buf, 1, n, fp) != n ||
1239                                     fwrite(buf, 1, n, wcachefp) != n)
1240                                         err(1, "fwrite");
1241                         }
1242                         fclose(rcachefp);
1243                 }
1244                 fclose(wcachefp);
1245         } else {
1246                 if (head)
1247                         writelog(fp, head);
1248         }
1249
1250         fputs("</tbody></table>", fp);
1251         writefooter(fp);
1252         fclose(fp);
1253
1254         /* files for HEAD */
1255         fp = efopen("files.html", "w");
1256         writeheader(fp, "Files");
1257         if (head)
1258                 writefiles(fp, head);
1259         writefooter(fp);
1260         fclose(fp);
1261
1262         /* summary page with branches and tags */
1263         fp = efopen("refs.html", "w");
1264         writeheader(fp, "Refs");
1265         writerefs(fp);
1266         writefooter(fp);
1267         fclose(fp);
1268
1269         /* Atom feed */
1270         fp = efopen("atom.xml", "w");
1271         writeatom(fp);
1272         fclose(fp);
1273
1274         /* rename new cache file on success */
1275         if (cachefile && head) {
1276                 if (rename(tmppath, cachefile))
1277                         err(1, "rename: '%s' to '%s'", tmppath, cachefile);
1278                 umask((mask = umask(0)));
1279                 if (chmod(cachefile,
1280                     (S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH) & ~mask))
1281                         err(1, "chmod: '%s'", cachefile);
1282         }
1283
1284         /* cleanup */
1285         git_repository_free(repo);
1286         git_libgit2_shutdown();
1287
1288         return 0;
1289 }