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