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