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