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