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