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