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