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