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