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