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