stagit

My personal build of stagit 😸️

stagit.c (38499B)

      1 #include <sys/stat.h>
      2 #include <sys/types.h>
      3 
      4 #include <err.h>
      5 #include <errno.h>
      6 #include <libgen.h>
      7 #include <limits.h>
      8 #include <stdint.h>
      9 #include <stdio.h>
     10 #include <stdlib.h>
     11 #include <stdbool.h>
     12 #include <string.h>
     13 #include <time.h>
     14 #include <unistd.h>
     15 #include <fcntl.h>
     16 
     17 #include <git2.h>
     18 #include "cmark.h"
     19 
     20 #include "compat.h"
     21 
     22 #define LEN(s)    (sizeof(s)/sizeof(*s))
     23 
     24 struct deltainfo {
     25   git_patch *patch;
     26 
     27   size_t addcount;
     28   size_t delcount;
     29 };
     30 
     31 struct commitinfo {
     32   const git_oid *id;
     33 
     34   char oid[GIT_OID_HEXSZ + 1];
     35   char parentoid[GIT_OID_HEXSZ + 1];
     36 
     37   const git_signature *author;
     38   const git_signature *committer;
     39   const char          *summary;
     40   const char          *msg;
     41 
     42   git_diff   *diff;
     43   git_commit *commit;
     44   git_commit *parent;
     45   git_tree   *commit_tree;
     46   git_tree   *parent_tree;
     47 
     48   size_t addcount;
     49   size_t delcount;
     50   size_t filecount;
     51 
     52   struct deltainfo **deltas;
     53   size_t ndeltas;
     54 };
     55 
     56 /* reference and associated data for sorting */
     57 struct referenceinfo {
     58   struct git_reference *ref;
     59   struct commitinfo *ci;
     60 };
     61 
     62 static git_repository *repo;
     63 
     64 static const char *baseurl = ""; /* base URL to make absolute RSS/Atom URI */
     65 static const char *relpath = "";
     66 static const char *repodir;
     67 
     68 static char *name = "";
     69 static char *strippedname = "";
     70 static char description[255];
     71 static char cloneurl[1024];
     72 static char *submodules;
     73 static char *licensefiles[] = { "HEAD:LICENSE", "HEAD:COPYING" };
     74 static char *license;
     75 static char *readmefiles[] = { "HEAD:README", "HEAD:README.md", "HEAD:README.adoc" };
     76 static char *readme;
     77 static long long nlogcommits = -1; /* < 0 indicates not used */
     78 
     79 /* cache */
     80 static git_oid lastoid;
     81 static char lastoidstr[GIT_OID_HEXSZ + 2]; /* id + newline + NUL byte */
     82 static FILE *rcachefp, *wcachefp;
     83 static const char *cachefile;
     84 
     85 void joinpath(char *buf, size_t bufsiz, const char *path, const char *path2)
     86 {
     87   int r;
     88 
     89   r = snprintf(buf, bufsiz, "%s%s%s",
     90       path, path[0] && path[strlen(path) - 1] != '/' ? "/" : "", path2);
     91   if (r < 0 || (size_t)r >= bufsiz)
     92     errx(1, "path truncated: '%s%s%s'",
     93         path, path[0] && path[strlen(path) - 1] != '/' ? "/" : "", path2);
     94 }
     95 
     96 void deltainfo_free(struct deltainfo *di)
     97 {
     98   if (!di)
     99     return;
    100   git_patch_free(di->patch);
    101   memset(di, 0, sizeof(*di));
    102   free(di);
    103 }
    104 
    105 int commitinfo_getstats(struct commitinfo *ci)
    106 {
    107   struct deltainfo *di;
    108   git_diff_options opts;
    109   git_diff_find_options fopts;
    110   const git_diff_delta *delta;
    111   const git_diff_hunk *hunk;
    112   const git_diff_line *line;
    113   git_patch *patch = NULL;
    114   size_t ndeltas, nhunks, nhunklines;
    115   size_t i, j, k;
    116 
    117   if (git_tree_lookup(&(ci->commit_tree), repo, git_commit_tree_id(ci->commit)))
    118     goto err;
    119   if (!git_commit_parent(&(ci->parent), ci->commit, 0)) {
    120     if (git_tree_lookup(&(ci->parent_tree), repo, git_commit_tree_id(ci->parent))) {
    121       ci->parent = NULL;
    122       ci->parent_tree = NULL;
    123     }
    124   }
    125 
    126   git_diff_init_options(&opts, GIT_DIFF_OPTIONS_VERSION);
    127   opts.flags |= GIT_DIFF_DISABLE_PATHSPEC_MATCH |
    128     GIT_DIFF_IGNORE_SUBMODULES |
    129     GIT_DIFF_INCLUDE_TYPECHANGE;
    130   if (git_diff_tree_to_tree(&(ci->diff), repo, ci->parent_tree, ci->commit_tree, &opts))
    131     goto err;
    132 
    133   if (git_diff_find_init_options(&fopts, GIT_DIFF_FIND_OPTIONS_VERSION))
    134     goto err;
    135   /* find renames and copies, exact matches (no heuristic) for renames. */
    136   fopts.flags |= GIT_DIFF_FIND_RENAMES | GIT_DIFF_FIND_COPIES |
    137     GIT_DIFF_FIND_EXACT_MATCH_ONLY;
    138   if (git_diff_find_similar(ci->diff, &fopts))
    139     goto err;
    140 
    141   ndeltas = git_diff_num_deltas(ci->diff);
    142   if (ndeltas && !(ci->deltas = calloc(ndeltas, sizeof(struct deltainfo *))))
    143     err(1, "calloc");
    144 
    145   for (i = 0; i < ndeltas; i++) {
    146     if (git_patch_from_diff(&patch, ci->diff, i))
    147       goto err;
    148 
    149     if (!(di = calloc(1, sizeof(struct deltainfo))))
    150       err(1, "calloc");
    151     di->patch = patch;
    152     ci->deltas[i] = di;
    153 
    154     delta = git_patch_get_delta(patch);
    155 
    156     /* skip stats for binary data */
    157     if (delta->flags & GIT_DIFF_FLAG_BINARY)
    158       continue;
    159 
    160     nhunks = git_patch_num_hunks(patch);
    161     for (j = 0; j < nhunks; j++) {
    162       if (git_patch_get_hunk(&hunk, &nhunklines, patch, j))
    163         break;
    164       for (k = 0; ; k++) {
    165         if (git_patch_get_line_in_hunk(&line, patch, j, k))
    166           break;
    167         if (line->old_lineno == -1) {
    168           di->addcount++;
    169           ci->addcount++;
    170         } else if (line->new_lineno == -1) {
    171           di->delcount++;
    172           ci->delcount++;
    173         }
    174       }
    175     }
    176   }
    177   ci->ndeltas = i;
    178   ci->filecount = i;
    179 
    180   return 0;
    181 
    182 err:
    183   git_diff_free(ci->diff);
    184   ci->diff = NULL;
    185   git_tree_free(ci->commit_tree);
    186   ci->commit_tree = NULL;
    187   git_tree_free(ci->parent_tree);
    188   ci->parent_tree = NULL;
    189   git_commit_free(ci->parent);
    190   ci->parent = NULL;
    191 
    192   if (ci->deltas)
    193     for (i = 0; i < ci->ndeltas; i++)
    194       deltainfo_free(ci->deltas[i]);
    195   free(ci->deltas);
    196   ci->deltas = NULL;
    197   ci->ndeltas = 0;
    198   ci->addcount = 0;
    199   ci->delcount = 0;
    200   ci->filecount = 0;
    201 
    202   return -1;
    203 }
    204 
    205 void commitinfo_free(struct commitinfo *ci)
    206 {
    207   size_t i;
    208 
    209   if (!ci)
    210     return;
    211   if (ci->deltas)
    212     for (i = 0; i < ci->ndeltas; i++)
    213       deltainfo_free(ci->deltas[i]);
    214 
    215   free(ci->deltas);
    216   git_diff_free(ci->diff);
    217   git_tree_free(ci->commit_tree);
    218   git_tree_free(ci->parent_tree);
    219   git_commit_free(ci->commit);
    220   git_commit_free(ci->parent);
    221   memset(ci, 0, sizeof(*ci));
    222   free(ci);
    223 }
    224 
    225   struct commitinfo *
    226 commitinfo_getbyoid(const git_oid *id)
    227 {
    228   struct commitinfo *ci;
    229 
    230   if (!(ci = calloc(1, sizeof(struct commitinfo))))
    231     err(1, "calloc");
    232 
    233   if (git_commit_lookup(&(ci->commit), repo, id))
    234     goto err;
    235   ci->id = id;
    236 
    237   git_oid_tostr(ci->oid, sizeof(ci->oid), git_commit_id(ci->commit));
    238   git_oid_tostr(ci->parentoid, sizeof(ci->parentoid), git_commit_parent_id(ci->commit, 0));
    239 
    240   ci->author = git_commit_author(ci->commit);
    241   ci->committer = git_commit_committer(ci->commit);
    242   ci->summary = git_commit_summary(ci->commit);
    243   ci->msg = git_commit_message(ci->commit);
    244 
    245   return ci;
    246 
    247 err:
    248   commitinfo_free(ci);
    249 
    250   return NULL;
    251 }
    252 
    253 int refs_cmp(const void *v1, const void *v2)
    254 {
    255   const struct referenceinfo *r1 = v1, *r2 = v2;
    256   time_t t1, t2;
    257   int r;
    258 
    259   if ((r = git_reference_is_tag(r1->ref) - git_reference_is_tag(r2->ref)))
    260     return r;
    261 
    262   t1 = r1->ci->author ? r1->ci->author->when.time : 0;
    263   t2 = r2->ci->author ? r2->ci->author->when.time : 0;
    264   if ((r = t1 > t2 ? -1 : (t1 == t2 ? 0 : 1)))
    265     return r;
    266 
    267   return strcmp(git_reference_shorthand(r1->ref),
    268       git_reference_shorthand(r2->ref));
    269 }
    270 
    271   int
    272 getrefs(struct referenceinfo **pris, size_t *prefcount)
    273 {
    274   struct referenceinfo *ris = NULL;
    275   struct commitinfo *ci = NULL;
    276   git_reference_iterator *it = NULL;
    277   const git_oid *id = NULL;
    278   git_object *obj = NULL;
    279   git_reference *dref = NULL, *r, *ref = NULL;
    280   size_t i, refcount;
    281 
    282   *pris = NULL;
    283   *prefcount = 0;
    284 
    285   if (git_reference_iterator_new(&it, repo))
    286     return -1;
    287 
    288   for (refcount = 0; !git_reference_next(&ref, it); ) {
    289     if (!git_reference_is_branch(ref) && !git_reference_is_tag(ref)) {
    290       git_reference_free(ref);
    291       ref = NULL;
    292       continue;
    293     }
    294 
    295     switch (git_reference_type(ref)) {
    296       case GIT_REF_SYMBOLIC:
    297         if (git_reference_resolve(&dref, ref))
    298           goto err;
    299         r = dref;
    300         break;
    301       case GIT_REF_OID:
    302         r = ref;
    303         break;
    304       default:
    305         continue;
    306     }
    307     if (!git_reference_target(r) ||
    308         git_reference_peel(&obj, r, GIT_OBJ_ANY))
    309       goto err;
    310     if (!(id = git_object_id(obj)))
    311       goto err;
    312     if (!(ci = commitinfo_getbyoid(id)))
    313       break;
    314 
    315     if (!(ris = reallocarray(ris, refcount + 1, sizeof(*ris))))
    316       err(1, "realloc");
    317     ris[refcount].ci = ci;
    318     ris[refcount].ref = r;
    319     refcount++;
    320 
    321     git_object_free(obj);
    322     obj = NULL;
    323     git_reference_free(dref);
    324     dref = NULL;
    325   }
    326   git_reference_iterator_free(it);
    327 
    328   /* sort by type, date then shorthand name */
    329   qsort(ris, refcount, sizeof(*ris), refs_cmp);
    330 
    331   *pris = ris;
    332   *prefcount = refcount;
    333 
    334   return 0;
    335 
    336 err:
    337   git_object_free(obj);
    338   git_reference_free(dref);
    339   commitinfo_free(ci);
    340   for (i = 0; i < refcount; i++) {
    341     commitinfo_free(ris[i].ci);
    342     git_reference_free(ris[i].ref);
    343   }
    344   free(ris);
    345 
    346   return -1;
    347 }
    348 
    349 FILE * efopen(const char *filename, const char *flags)
    350 {
    351   FILE *fp;
    352 
    353   if (!(fp = fopen(filename, flags)))
    354     err(1, "fopen: '%s'", filename);
    355 
    356   return fp;
    357 }
    358 
    359 /* Escape characters below as HTML 2.0 / XML 1.0. */
    360 void xmlencode(FILE *fp, const char *s, size_t len)
    361 {
    362   size_t i;
    363 
    364   for (i = 0; *s && i < len; s++, i++) {
    365     switch(*s) {
    366       case '<':  fputs("&lt;",   fp); break;
    367       case '>':  fputs("&gt;",   fp); break;
    368       case '\'': fputs("&#39;",  fp); break;
    369       case '&':  fputs("&amp;",  fp); break;
    370       case '"':  fputs("&quot;", fp); break;
    371       default:   putc(*s, fp);
    372     }
    373   }
    374 }
    375 
    376 int mkdirp(const char *path)
    377 {
    378   char tmp[PATH_MAX], *p;
    379 
    380   if (strlcpy(tmp, path, sizeof(tmp)) >= sizeof(tmp))
    381     errx(1, "path truncated: '%s'", path);
    382   for (p = tmp + (tmp[0] == '/'); *p; p++) {
    383     if (*p != '/')
    384       continue;
    385     *p = '\0';
    386     if (mkdir(tmp, S_IRWXU | S_IRWXG | S_IRWXO) < 0 && errno != EEXIST)
    387       return -1;
    388     *p = '/';
    389   }
    390   if (mkdir(tmp, S_IRWXU | S_IRWXG | S_IRWXO) < 0 && errno != EEXIST)
    391     return -1;
    392   return 0;
    393 }
    394 
    395 void printtimez(FILE *fp, const git_time *intime)
    396 {
    397   struct tm *intm;
    398   time_t t;
    399   char out[32];
    400 
    401   t = (time_t)intime->time;
    402   if (!(intm = gmtime(&t)))
    403     return;
    404   strftime(out, sizeof(out), "%Y-%m-%dT%H:%M:%SZ", intm);
    405   fputs(out, fp);
    406 }
    407 
    408 void printtime(FILE *fp, const git_time *intime)
    409 {
    410   struct tm *intm;
    411   time_t t;
    412   char out[32];
    413 
    414   t = (time_t)intime->time + (intime->offset * 60);
    415   if (!(intm = gmtime(&t)))
    416     return;
    417   strftime(out, sizeof(out), "%a, %e %b %Y %H:%M:%S", intm);
    418   if (intime->offset < 0)
    419     fprintf(fp, "%s -%02d%02d", out,
    420         -(intime->offset) / 60, -(intime->offset) % 60);
    421   else
    422     fprintf(fp, "%s +%02d%02d", out,
    423         intime->offset / 60, intime->offset % 60);
    424 }
    425 
    426 void printtimeshort(FILE *fp, const git_time *intime)
    427 {
    428   struct tm *intm;
    429   time_t t;
    430   char out[32];
    431 
    432   t = (time_t)intime->time;
    433   if (!(intm = gmtime(&t)))
    434     return;
    435   strftime(out, sizeof(out), "%Y-%m-%d %H:%M", intm);
    436   fputs(out, fp);
    437 }
    438 
    439 void writeheader(FILE *fp, const char *title)
    440 {
    441   fputs("<!DOCTYPE html>\n"
    442       "<html>\n<head>\n"
    443       "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n"
    444       "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n"
    445       "<title>", fp);
    446   xmlencode(fp, title, strlen(title));
    447   if (title[0] && strippedname[0])
    448     fputs(" - ", fp);
    449   xmlencode(fp, strippedname, strlen(strippedname));
    450   if (description[0])
    451     fputs(" - ", fp);
    452   xmlencode(fp, description, strlen(description));
    453   fprintf(fp, "</title>\n<link rel=\"icon\" type=\"image/svg\" href=\"/icons/favicon.svg\"/>\n");
    454   fprintf(fp, "<link rel=\"alternate\" type=\"application/atom+xml\" title=\"%s Atom Feed\" href=\"%satom.xml\" />\n",
    455       name, relpath);
    456   fprintf(fp, "<link rel=\"alternate\" type=\"application/atom+xml\" title=\"%s Atom Feed (tags)\" href=\"%stags.xml\" />\n",
    457       name, relpath);
    458   fprintf(fp, "<link rel=\"stylesheet\" type=\"text/css\" href=\"/css/styles.css\" />\n", relpath);
    459   fputs("</head>\n<body>\n", fp);
    460 
    461   // The navigation bar
    462   fputs("<nav>\n", fp);
    463   fputs("<a href=\"https://pablo.escobar.life\">@pablo 🚬️</a>\n", fp);
    464   fputs("<a href=\"https://git.escobar.life\">repos 🙀️</a>\n", fp);
    465   fputs("</nav>\n", fp);
    466 
    467   fputs("<main>\n<h1>", fp);
    468   xmlencode(fp, strippedname, strlen(strippedname));
    469   fputs("</h1>\n<p>", fp);
    470   xmlencode(fp, description, strlen(description));
    471   fputs("</p>\n<ul>", fp);
    472   if (cloneurl[0]) {
    473     fputs("<li>git clone: <a href=\"", fp);
    474     xmlencode(fp, cloneurl, strlen(cloneurl));
    475     fputs("\">", fp);
    476     xmlencode(fp, cloneurl, strlen(cloneurl));
    477     fputs("</a></li>\n", fp);
    478   }
    479   fprintf(fp, "<li><a href=\"%slog.html\">Log</a></li>", relpath);
    480   fprintf(fp, "<li><a href=\"%sfiles.html\">Files</a></li>", relpath);
    481   fprintf(fp, "<li><a href=\"%srefs.html\">Refs</a></li>", relpath);
    482   if (submodules)
    483     fprintf(fp, "<li><a href=\"%sfile/%s.html\">Submodules</a></li>\n",
    484         relpath, submodules);
    485   if (readme)
    486     fprintf(fp, "<li><a href=\"%s\">README</a></li>\n", readme);
    487   if (license)
    488     fprintf(fp, "<li><a href=\"%sfile/%s.html\">LICENSE</a></li>\n",
    489         relpath, license);
    490 }
    491 
    492 void writefooter(FILE *fp)
    493 {
    494   fputs("</main>\n", fp);
    495   fputs("<footer>Pablo © 2021</footer>\n", fp);
    496   fputs("</body>\n</html>\n", fp);
    497 }
    498 
    499 /*
    500  * Writes the raw contents of a blob in a file
    501  */
    502 ssize_t writeblobraw(const git_blob *blob, const char *fpath)
    503 {
    504   char tmp[PATH_MAX] = "", *d;
    505 
    506   if (strlcpy(tmp, fpath, sizeof(tmp)) >= sizeof(tmp))
    507     errx(1, "path truncated: '%s'", fpath);
    508   if (!(d = dirname(tmp)))
    509     err(1, "dirname");
    510   if (mkdirp(d))
    511     return -1;
    512 
    513   int fd = open(fpath, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
    514   if (fd == -1) return -1;
    515 
    516   int len = git_blob_rawsize(blob);
    517   const void *s = git_blob_rawcontent(blob);
    518   size_t size = write(fd, s, len);
    519   close(fd);
    520 
    521   return size;
    522 }
    523 
    524 size_t writeblobhtml(FILE *fp, const git_blob *blob)
    525 {
    526   size_t n = 0, i, len, prev;
    527   const char *nfmt = "<a href=\"#l%zu\" class=\"line\" id=\"l%zu\">%7zu</a> ";
    528   const char *s = git_blob_rawcontent(blob);
    529 
    530   len = git_blob_rawsize(blob);
    531   fputs("<pre id=\"blob\">\n", fp);
    532 
    533   if (len > 0) {
    534     for (i = 0, prev = 0; i < len; i++) {
    535       if (s[i] != '\n')
    536         continue;
    537       n++;
    538       fprintf(fp, nfmt, n, n, n);
    539       xmlencode(fp, &s[prev], i - prev + 1);
    540       prev = i + 1;
    541     }
    542     /* trailing data */
    543     if ((len - prev) > 0) {
    544       n++;
    545       fprintf(fp, nfmt, n, n, n);
    546       xmlencode(fp, &s[prev], len - prev);
    547     }
    548   }
    549 
    550   fputs("</pre>\n", fp);
    551   return n;
    552 }
    553 
    554 void printcommit(FILE *fp, struct commitinfo *ci)
    555 {
    556   fprintf(fp, "<b>commit</b> <a href=\"%scommit/%s.html\">%s</a>\n",
    557       relpath, ci->oid, ci->oid);
    558 
    559   if (ci->parentoid[0])
    560     fprintf(fp, "<b>parent</b> <a href=\"%scommit/%s.html\">%s</a>\n",
    561         relpath, ci->parentoid, ci->parentoid);
    562 
    563   if (ci->author) {
    564     fputs("<b>Author:</b> ", fp);
    565     xmlencode(fp, ci->author->name, strlen(ci->author->name));
    566     fputs(" &lt;<a href=\"mailto:", fp);
    567     xmlencode(fp, ci->author->email, strlen(ci->author->email));
    568     fputs("\">", fp);
    569     xmlencode(fp, ci->author->email, strlen(ci->author->email));
    570     fputs("</a>&gt;\n<b>Date:</b>   ", fp);
    571     printtime(fp, &(ci->author->when));
    572     putc('\n', fp);
    573   }
    574   if (ci->msg) {
    575     putc('\n', fp);
    576     xmlencode(fp, ci->msg, strlen(ci->msg));
    577     putc('\n', fp);
    578   }
    579 }
    580 
    581 void printshowfile(FILE *fp, struct commitinfo *ci)
    582 {
    583   const git_diff_delta *delta;
    584   const git_diff_hunk *hunk;
    585   const git_diff_line *line;
    586   git_patch *patch;
    587   size_t nhunks, nhunklines, changed, add, del, total, i, j, k;
    588   char linestr[80];
    589   int c;
    590 
    591   printcommit(fp, ci);
    592 
    593   if (!ci->deltas)
    594     return;
    595 
    596   if (ci->filecount > 1000   ||
    597       ci->ndeltas   > 1000   ||
    598       ci->addcount  > 100000 ||
    599       ci->delcount  > 100000) {
    600     fputs("Diff is too large, output suppressed.\n", fp);
    601     return;
    602   }
    603 
    604   /* diff stat */
    605   fputs("<b>Diffstat:</b>\n<table>", fp);
    606   for (i = 0; i < ci->ndeltas; i++) {
    607     delta = git_patch_get_delta(ci->deltas[i]->patch);
    608 
    609     switch (delta->status) {
    610       case GIT_DELTA_ADDED:      c = 'A'; break;
    611       case GIT_DELTA_COPIED:     c = 'C'; break;
    612       case GIT_DELTA_DELETED:    c = 'D'; break;
    613       case GIT_DELTA_MODIFIED:   c = 'M'; break;
    614       case GIT_DELTA_RENAMED:    c = 'R'; break;
    615       case GIT_DELTA_TYPECHANGE: c = 'T'; break;
    616       default:                   c = ' '; break;
    617     }
    618     if (c == ' ')
    619       fprintf(fp, "<tr><td>%c", c);
    620     else
    621       fprintf(fp, "<tr><td class=\"%c\">%c", c, c);
    622 
    623     fprintf(fp, "</td><td><a href=\"#h%zu\">", i);
    624     xmlencode(fp, delta->old_file.path, strlen(delta->old_file.path));
    625     if (strcmp(delta->old_file.path, delta->new_file.path)) {
    626       fputs(" -&gt; ", fp);
    627       xmlencode(fp, delta->new_file.path, strlen(delta->new_file.path));
    628     }
    629 
    630     add = ci->deltas[i]->addcount;
    631     del = ci->deltas[i]->delcount;
    632     changed = add + del;
    633     total = sizeof(linestr) - 2;
    634     if (changed > total) {
    635       if (add)
    636         add = ((float)total / changed * add) + 1;
    637       if (del)
    638         del = ((float)total / changed * del) + 1;
    639     }
    640     memset(&linestr, '+', add);
    641     memset(&linestr[add], '-', del);
    642 
    643     fprintf(fp, "</a></td><td> | </td><td class=\"num\">%zu</td><td><span class=\"i\">",
    644         ci->deltas[i]->addcount + ci->deltas[i]->delcount);
    645     fwrite(&linestr, 1, add, fp);
    646     fputs("</span><span class=\"d\">", fp);
    647     fwrite(&linestr[add], 1, del, fp);
    648     fputs("</span></td></tr>\n", fp);
    649   }
    650   fprintf(fp, "</table>\n%zu file%s changed, %zu insertion%s(+), %zu deletion%s(-)\n",
    651       ci->filecount, ci->filecount == 1 ? "" : "s",
    652       ci->addcount,  ci->addcount  == 1 ? "" : "s",
    653       ci->delcount,  ci->delcount  == 1 ? "" : "s");
    654 
    655   fputs("</pre>\n</div>\n<div class=\"codeblock\">\n<pre>", fp);
    656 
    657   for (i = 0; i < ci->ndeltas; i++) {
    658     patch = ci->deltas[i]->patch;
    659     delta = git_patch_get_delta(patch);
    660     fprintf(fp, "<b>diff --git a/<a id=\"h%zu\" href=\"%sfile/", i, relpath);
    661     xmlencode(fp, delta->old_file.path, strlen(delta->old_file.path));
    662     fputs(".html\">", fp);
    663     xmlencode(fp, delta->old_file.path, strlen(delta->old_file.path));
    664     fprintf(fp, "</a> b/<a href=\"%sfile/", relpath);
    665     xmlencode(fp, delta->new_file.path, strlen(delta->new_file.path));
    666     fprintf(fp, ".html\">");
    667     xmlencode(fp, delta->new_file.path, strlen(delta->new_file.path));
    668     fprintf(fp, "</a></b>\n");
    669 
    670     /* check binary data */
    671     if (delta->flags & GIT_DIFF_FLAG_BINARY) {
    672       fputs("Binary files differ.\n", fp);
    673       continue;
    674     }
    675 
    676     nhunks = git_patch_num_hunks(patch);
    677     for (j = 0; j < nhunks; j++) {
    678       if (git_patch_get_hunk(&hunk, &nhunklines, patch, j))
    679         break;
    680 
    681       fprintf(fp, "<a href=\"#h%zu-%zu\" id=\"h%zu-%zu\" class=\"h\">", i, j, i, j);
    682       xmlencode(fp, hunk->header, hunk->header_len);
    683       fputs("</a>", fp);
    684 
    685       for (k = 0; ; k++) {
    686         if (git_patch_get_line_in_hunk(&line, patch, j, k))
    687           break;
    688         if (line->old_lineno == -1)
    689           fprintf(fp, "<a href=\"#h%zu-%zu-%zu\" id=\"h%zu-%zu-%zu\" class=\"i\">+",
    690               i, j, k, i, j, k);
    691         else if (line->new_lineno == -1)
    692           fprintf(fp, "<a href=\"#h%zu-%zu-%zu\" id=\"h%zu-%zu-%zu\" class=\"d\">-",
    693               i, j, k, i, j, k);
    694         else
    695           putc(' ', fp);
    696         xmlencode(fp, line->content, line->content_len);
    697         if (line->old_lineno == -1 || line->new_lineno == -1)
    698           fputs("</a>", fp);
    699       }
    700     }
    701   }
    702 }
    703 
    704 void writelogline(FILE *fp, struct commitinfo *ci)
    705 {
    706   fputs("<tr><td>", fp);
    707   if (ci->author)
    708   {
    709     fputs("<time datetime=\"", fp);
    710     printtimeshort(fp, &(ci->author->when));
    711     fputs("\">", fp);
    712     printtimeshort(fp, &(ci->author->when));
    713     fputs("</time>", fp);
    714   }
    715   fputs("</td><td>", fp);
    716   if (ci->summary) {
    717     fprintf(fp, "<a href=\"%scommit/%s.html\">", relpath, ci->oid);
    718     xmlencode(fp, ci->summary, strlen(ci->summary));
    719     fputs("</a>", fp);
    720   }
    721   fputs("</td><td>", fp);
    722   if (ci->author)
    723     xmlencode(fp, ci->author->name, strlen(ci->author->name));
    724   fputs("</td><td class=\"num\" align=\"right\">", fp);
    725   fprintf(fp, "%zu", ci->filecount);
    726   fputs("</td><td class=\"num\" align=\"right\">", fp);
    727   fprintf(fp, "+%zu", ci->addcount);
    728   fputs("</td><td class=\"num\" align=\"right\">", fp);
    729   fprintf(fp, "-%zu", ci->delcount);
    730   fputs("</td></tr>\n", fp);
    731 }
    732 
    733 int writelog(FILE *fp, const git_oid *oid)
    734 {
    735   struct commitinfo *ci;
    736   git_revwalk *w = NULL;
    737   git_oid id;
    738   char path[PATH_MAX], oidstr[GIT_OID_HEXSZ + 1];
    739   FILE *fpfile;
    740   int r;
    741 
    742   git_revwalk_new(&w, repo);
    743   git_revwalk_push(w, oid);
    744   git_revwalk_simplify_first_parent(w);
    745 
    746   while (!git_revwalk_next(&id, w)) {
    747     relpath = "";
    748 
    749     if (cachefile && !memcmp(&id, &lastoid, sizeof(id)))
    750       break;
    751 
    752     git_oid_tostr(oidstr, sizeof(oidstr), &id);
    753     r = snprintf(path, sizeof(path), "commit/%s.html", oidstr);
    754     if (r < 0 || (size_t)r >= sizeof(path))
    755       errx(1, "path truncated: 'commit/%s.html'", oidstr);
    756     r = access(path, F_OK);
    757 
    758     /* optimization: if there are no log lines to write and
    759        the commit file already exists: skip the diffstat */
    760     if (!nlogcommits && !r)
    761       continue;
    762 
    763     if (!(ci = commitinfo_getbyoid(&id)))
    764       break;
    765     /* diffstat: for stagit HTML required for the log.html line */
    766     if (commitinfo_getstats(ci) == -1)
    767       goto err;
    768 
    769     if (nlogcommits < 0) {
    770       writelogline(fp, ci);
    771     } else if (nlogcommits > 0) {
    772       writelogline(fp, ci);
    773       nlogcommits--;
    774       if (!nlogcommits && ci->parentoid[0])
    775         fputs("<tr><td></td><td colspan=\"5\">"
    776             "More commits remaining [...]</td>"
    777             "</tr>\n", fp);
    778     }
    779 
    780     if (cachefile)
    781       writelogline(wcachefp, ci);
    782 
    783     /* check if file exists if so skip it */
    784     if (r) {
    785       relpath = "../";
    786       fpfile = efopen(path, "w");
    787       writeheader(fpfile, ci->summary);
    788       fputs("</ul>\n", fp);
    789       fputs("<div class=\"codeblock\">\n", fpfile);
    790       fputs("<pre>", fpfile);
    791       printshowfile(fpfile, ci);
    792       fputs("</pre>\n", fpfile);
    793       fputs("</div>\n", fpfile);
    794       writefooter(fpfile);
    795       fclose(fpfile);
    796     }
    797 err:
    798     commitinfo_free(ci);
    799   }
    800   git_revwalk_free(w);
    801 
    802   relpath = "";
    803 
    804   return 0;
    805 }
    806 
    807 void printcommitatom(FILE *fp, struct commitinfo *ci, const char *tag)
    808 {
    809   fputs("<entry>\n", fp);
    810 
    811   fprintf(fp, "<id>%s</id>\n", ci->oid);
    812   if (ci->author) {
    813     fputs("<published>", fp);
    814     printtimez(fp, &(ci->author->when));
    815     fputs("</published>\n", fp);
    816   }
    817   if (ci->committer) {
    818     fputs("<updated>", fp);
    819     printtimez(fp, &(ci->committer->when));
    820     fputs("</updated>\n", fp);
    821   }
    822   if (ci->summary) {
    823     fputs("<title type=\"text\">", fp);
    824     if (tag && tag[0]) {
    825       fputs("[", fp);
    826       xmlencode(fp, tag, strlen(tag));
    827       fputs("] ", fp);
    828     }
    829     xmlencode(fp, ci->summary, strlen(ci->summary));
    830     fputs("</title>\n", fp);
    831   }
    832   fprintf(fp, "<link rel=\"alternate\" type=\"text/html\" href=\"%scommit/%s.html\" />\n",
    833       baseurl, ci->oid);
    834 
    835   if (ci->author) {
    836     fputs("<author>\n<name>", fp);
    837     xmlencode(fp, ci->author->name, strlen(ci->author->name));
    838     fputs("</name>\n<email>", fp);
    839     xmlencode(fp, ci->author->email, strlen(ci->author->email));
    840     fputs("</email>\n</author>\n", fp);
    841   }
    842 
    843   fputs("<content type=\"text\">", fp);
    844   fprintf(fp, "commit %s\n", ci->oid);
    845   if (ci->parentoid[0])
    846     fprintf(fp, "parent %s\n", ci->parentoid);
    847   if (ci->author) {
    848     fputs("Author: ", fp);
    849     xmlencode(fp, ci->author->name, strlen(ci->author->name));
    850     fputs(" &lt;", fp);
    851     xmlencode(fp, ci->author->email, strlen(ci->author->email));
    852     fputs("&gt;\nDate:   ", fp);
    853     printtime(fp, &(ci->author->when));
    854     putc('\n', fp);
    855   }
    856   if (ci->msg) {
    857     putc('\n', fp);
    858     xmlencode(fp, ci->msg, strlen(ci->msg));
    859   }
    860   fputs("\n</content>\n</entry>\n", fp);
    861 }
    862 
    863 int writeatom(FILE *fp, int all)
    864 {
    865   struct referenceinfo *ris = NULL;
    866   size_t refcount = 0;
    867   struct commitinfo *ci;
    868   git_revwalk *w = NULL;
    869   git_oid id;
    870   size_t i, m = 100; /* last 'm' commits */
    871 
    872   fputs("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
    873       "<feed xmlns=\"http://www.w3.org/2005/Atom\">\n<title>", fp);
    874   xmlencode(fp, strippedname, strlen(strippedname));
    875   fputs(", branch HEAD</title>\n<subtitle>", fp);
    876   xmlencode(fp, description, strlen(description));
    877   fputs("</subtitle>\n", fp);
    878 
    879   /* all commits or only tags? */
    880   if (all) {
    881     git_revwalk_new(&w, repo);
    882     git_revwalk_push_head(w);
    883     git_revwalk_simplify_first_parent(w);
    884     for (i = 0; i < m && !git_revwalk_next(&id, w); i++) {
    885       if (!(ci = commitinfo_getbyoid(&id)))
    886         break;
    887       printcommitatom(fp, ci, "");
    888       commitinfo_free(ci);
    889     }
    890     git_revwalk_free(w);
    891   } else if (getrefs(&ris, &refcount) != -1) {
    892     /* references: tags */
    893     for (i = 0; i < refcount; i++) {
    894       if (git_reference_is_tag(ris[i].ref))
    895         printcommitatom(fp, ris[i].ci,
    896             git_reference_shorthand(ris[i].ref));
    897 
    898       commitinfo_free(ris[i].ci);
    899       git_reference_free(ris[i].ref);
    900     }
    901     free(ris);
    902   }
    903 
    904   fputs("</feed>\n", fp);
    905 
    906   return 0;
    907 }
    908 
    909 size_t writeblob(git_object *obj, const char *fpath, const char *filename, size_t filesize)
    910 {
    911   char tmp[PATH_MAX] = "", *d;
    912   const char *p;
    913   size_t lc = 0;
    914   FILE *fp;
    915 
    916   if (strlcpy(tmp, fpath, sizeof(tmp)) >= sizeof(tmp))
    917     errx(1, "path truncated: '%s'", fpath);
    918   if (!(d = dirname(tmp)))
    919     err(1, "dirname");
    920   if (mkdirp(d))
    921     return -1;
    922 
    923   for (p = fpath, tmp[0] = '\0'; *p; p++) {
    924     if (*p == '/' && strlcat(tmp, "../", sizeof(tmp)) >= sizeof(tmp))
    925       errx(1, "path truncated: '../%s'", tmp);
    926   }
    927   relpath = tmp;
    928 
    929   fp = efopen(fpath, "w");
    930   writeheader(fp, filename);
    931   fprintf(fp, "<li><a href=\"%sblob/%s\">raw file (blob)</a></li>", relpath, filename);
    932   fputs("</ul>\n", fp);
    933   fputs("<div class=\"titled-block\">\n<h1>", fp);
    934   xmlencode(fp, filename, strlen(filename));
    935   fprintf(fp, " (%zuB)", filesize);
    936   fputs("</h1>\n<div class=\"codeblock\">", fp);
    937 
    938   if (git_blob_is_binary((git_blob *)obj)) {
    939     fputs("<pre>Binary file</pre>\n", fp);
    940   } else {
    941     lc = writeblobhtml(fp, (git_blob *)obj);
    942     if (ferror(fp))
    943       err(1, "fwrite");
    944   }
    945 
    946   fputs("</div>\n</div>\n", fp);
    947   writefooter(fp);
    948   fclose(fp);
    949 
    950   relpath = "";
    951   return lc;
    952 }
    953 
    954 const char * filemode(git_filemode_t m)
    955 {
    956   static char mode[11];
    957 
    958   memset(mode, '-', sizeof(mode) - 1);
    959   mode[10] = '\0';
    960 
    961   if (S_ISREG(m))
    962     mode[0] = '-';
    963   else if (S_ISBLK(m))
    964     mode[0] = 'b';
    965   else if (S_ISCHR(m))
    966     mode[0] = 'c';
    967   else if (S_ISDIR(m))
    968     mode[0] = 'd';
    969   else if (S_ISFIFO(m))
    970     mode[0] = 'p';
    971   else if (S_ISLNK(m))
    972     mode[0] = 'l';
    973   else if (S_ISSOCK(m))
    974     mode[0] = 's';
    975   else
    976     mode[0] = '?';
    977 
    978   if (m & S_IRUSR) mode[1] = 'r';
    979   if (m & S_IWUSR) mode[2] = 'w';
    980   if (m & S_IXUSR) mode[3] = 'x';
    981   if (m & S_IRGRP) mode[4] = 'r';
    982   if (m & S_IWGRP) mode[5] = 'w';
    983   if (m & S_IXGRP) mode[6] = 'x';
    984   if (m & S_IROTH) mode[7] = 'r';
    985   if (m & S_IWOTH) mode[8] = 'w';
    986   if (m & S_IXOTH) mode[9] = 'x';
    987 
    988   if (m & S_ISUID) mode[3] = (mode[3] == 'x') ? 's' : 'S';
    989   if (m & S_ISGID) mode[6] = (mode[6] == 'x') ? 's' : 'S';
    990   if (m & S_ISVTX) mode[9] = (mode[9] == 'x') ? 't' : 'T';
    991 
    992   return mode;
    993 }
    994 
    995 int writefilestree(FILE *fp, git_tree *tree, const char *path)
    996 {
    997   const git_tree_entry *entry = NULL;
    998   git_object *obj = NULL;
    999   const char *entryname;
   1000   char filepath[PATH_MAX], blobpath[PATH_MAX], entrypath[PATH_MAX], oid[8];
   1001   size_t count, i, lc, filesize;
   1002   int r, ret;
   1003 
   1004   count = git_tree_entrycount(tree);
   1005   for (i = 0; i < count; i++) {
   1006     if (!(entry = git_tree_entry_byindex(tree, i)) ||
   1007         !(entryname = git_tree_entry_name(entry)))
   1008       return -1;
   1009     joinpath(entrypath, sizeof(entrypath), path, entryname);
   1010 
   1011     r = snprintf(filepath, sizeof(filepath), "file/%s.html",
   1012         entrypath);
   1013     if (r < 0 || (size_t)r >= sizeof(filepath))
   1014       errx(1, "path truncated: 'file/%s.html'", entrypath);
   1015     r = snprintf(blobpath, sizeof(filepath), "blob/%s",
   1016         entrypath);
   1017     if (r < 0 || (size_t)r >= sizeof(filepath))
   1018       errx(1, "path truncated: 'file/%s.html'", entrypath);
   1019 
   1020     if (!git_tree_entry_to_object(&obj, repo, entry)) {
   1021       switch (git_object_type(obj)) {
   1022         case GIT_OBJ_BLOB:
   1023           break;
   1024         case GIT_OBJ_TREE:
   1025           /* NOTE: recurses */
   1026           ret = writefilestree(fp, (git_tree *)obj,
   1027               entrypath);
   1028           git_object_free(obj);
   1029           if (ret)
   1030             return ret;
   1031           continue;
   1032         default:
   1033           git_object_free(obj);
   1034           continue;
   1035       }
   1036 
   1037       filesize = git_blob_rawsize((git_blob *)obj);
   1038       lc = writeblob(obj, filepath, entryname, filesize);
   1039       if (writeblobraw((git_blob *)obj, blobpath) < 0)
   1040         return 1;
   1041 
   1042       fputs("<tr><td>", fp);
   1043       fputs(filemode(git_tree_entry_filemode(entry)), fp);
   1044       fprintf(fp, "</td><td><a href=\"%s", relpath);
   1045       xmlencode(fp, filepath, strlen(filepath));
   1046       fputs("\">", fp);
   1047       xmlencode(fp, entrypath, strlen(entrypath));
   1048       fputs("</a></td><td class=\"num\" align=\"right\">", fp);
   1049       if (lc > 0)
   1050         fprintf(fp, "%zuL", lc);
   1051       else
   1052         fprintf(fp, "%zuB", filesize);
   1053       fputs("</td></tr>\n", fp);
   1054       git_object_free(obj);
   1055     } else if (git_tree_entry_type(entry) == GIT_OBJ_COMMIT) {
   1056       /* commit object in tree is a submodule */
   1057       fprintf(fp, "<tr><td>m---------</td><td><a href=\"%sfile/.gitmodules.html\">",
   1058           relpath);
   1059       xmlencode(fp, entrypath, strlen(entrypath));
   1060       fputs("</a> @ ", fp);
   1061       git_oid_tostr(oid, sizeof(oid), git_tree_entry_id(entry));
   1062       xmlencode(fp, oid, strlen(oid));
   1063       fputs("</td><td class=\"num\" align=\"right\"></td></tr>\n", fp);
   1064     }
   1065   }
   1066 
   1067   return 0;
   1068 }
   1069 
   1070 int writefiles(FILE *fp, const git_oid *id)
   1071 {
   1072   git_tree *tree = NULL;
   1073   git_commit *commit = NULL;
   1074   int ret = -1;
   1075 
   1076   fputs("<div class=\"table-container\"><table id=\"files\"><thead>\n<tr>"
   1077       "<td><b>Mode</b></td><td><b>Name</b></td>"
   1078       "<td class=\"num\" align=\"right\"><b>Size</b></td>"
   1079       "</tr>\n</thead><tbody>\n", fp);
   1080 
   1081   if (!git_commit_lookup(&commit, repo, id) &&
   1082       !git_commit_tree(&tree, commit))
   1083     ret = writefilestree(fp, tree, "");
   1084 
   1085   fputs("</tbody></table></div>", fp);
   1086 
   1087   git_commit_free(commit);
   1088   git_tree_free(tree);
   1089 
   1090   return ret;
   1091 }
   1092 
   1093 int writerefs(FILE *fp)
   1094 {
   1095   struct referenceinfo *ris = NULL;
   1096   struct commitinfo *ci;
   1097   size_t count, i, j, refcount;
   1098   const char *titles[] = { "Branches", "Tags" };
   1099   const char *ids[] = { "branches", "tags" };
   1100   const char *s;
   1101 
   1102   if (getrefs(&ris, &refcount) == -1)
   1103     return -1;
   1104 
   1105   for (i = 0, j = 0, count = 0; i < refcount; i++) {
   1106     if (j == 0 && git_reference_is_tag(ris[i].ref)) {
   1107       if (count)
   1108         fputs("</tbody></table></div><br/>\n", fp);
   1109       count = 0;
   1110       j = 1;
   1111     }
   1112 
   1113     /* print header if it has an entry (first). */
   1114     if (++count == 1) {
   1115       fprintf(fp, "<h2>%s</h2><div class=\"table-container\"><table id=\"%s\">"
   1116           "<thead>\n<tr><td><b>Name</b></td>"
   1117           "<td><b>Last commit date</b></td>"
   1118           "<td><b>Author</b></td>\n</tr>\n"
   1119           "</thead><tbody>\n",
   1120           titles[j], ids[j]);
   1121     }
   1122 
   1123     ci = ris[i].ci;
   1124     s = git_reference_shorthand(ris[i].ref);
   1125 
   1126     fputs("<tr><td>", fp);
   1127     xmlencode(fp, s, strlen(s));
   1128     fputs("</td><td>", fp);
   1129     if (ci->author)
   1130       printtimeshort(fp, &(ci->author->when));
   1131     fputs("</td><td>", fp);
   1132     if (ci->author)
   1133       xmlencode(fp, ci->author->name, strlen(ci->author->name));
   1134     fputs("</td></tr>\n", fp);
   1135   }
   1136   /* table footer */
   1137   if (count)
   1138     fputs("</tbody></table><br/>\n", fp);
   1139 
   1140   for (i = 0; i < refcount; i++) {
   1141     commitinfo_free(ris[i].ci);
   1142     git_reference_free(ris[i].ref);
   1143   }
   1144   free(ris);
   1145 
   1146   return 0;
   1147 }
   1148 
   1149 void usage(char *argv0)
   1150 {
   1151   fprintf(stderr, "%s [-c cachefile | -l commits] "
   1152       "[-u baseurl] repodir\n", argv0);
   1153   exit(1);
   1154 }
   1155 
   1156 /* Writes a Markdown README to the file using CMark */
   1157 void write_markdown_readme(FILE *fp, git_blob *readme)
   1158 {
   1159   const char *markdown = git_blob_rawcontent(readme);
   1160   char *html = cmark_markdown_to_html(markdown, 
   1161                                       strlen(markdown), CMARK_OPT_SAFE);
   1162   writeheader(fp, "README");
   1163   fputs("</ul>\n", fp);
   1164   fprintf(fp, "<section id=\"readme\">\n");
   1165   fprintf(fp, "%s", html);
   1166   fprintf(fp, "</section>\n");
   1167   writefooter(fp);
   1168 
   1169   free(html);
   1170 }
   1171 
   1172 int main(int argc, char *argv[])
   1173 {
   1174   git_object *obj = NULL;
   1175   const git_oid *head = NULL;
   1176   mode_t mask;
   1177   FILE *fp, *fpread;
   1178   char path[PATH_MAX], repodirabs[PATH_MAX + 1], *p;
   1179   char tmppath[64] = "cache.XXXXXXXXXXXX", buf[BUFSIZ];
   1180   size_t n;
   1181   int i, fd;
   1182 
   1183   for (i = 1; i < argc; i++) {
   1184     if (argv[i][0] != '-') {
   1185       if (repodir)
   1186         usage(argv[0]);
   1187       repodir = argv[i];
   1188     } else if (argv[i][1] == 'c') {
   1189       if (nlogcommits > 0 || i + 1 >= argc)
   1190         usage(argv[0]);
   1191       cachefile = argv[++i];
   1192     } else if (argv[i][1] == 'l') {
   1193       if (cachefile || i + 1 >= argc)
   1194         usage(argv[0]);
   1195       errno = 0;
   1196       nlogcommits = strtoll(argv[++i], &p, 10);
   1197       if (argv[i][0] == '\0' || *p != '\0' ||
   1198           nlogcommits <= 0 || errno)
   1199         usage(argv[0]);
   1200     } else if (argv[i][1] == 'u') {
   1201       if (i + 1 >= argc)
   1202         usage(argv[0]);
   1203       baseurl = argv[++i];
   1204     }
   1205   }
   1206   if (!repodir)
   1207     usage(argv[0]);
   1208 
   1209   if (!realpath(repodir, repodirabs))
   1210     err(1, "realpath");
   1211 
   1212   git_libgit2_init();
   1213 
   1214 #ifdef __OpenBSD__
   1215   if (unveil(repodir, "r") == -1)
   1216     err(1, "unveil: %s", repodir);
   1217   if (unveil(".", "rwc") == -1)
   1218     err(1, "unveil: .");
   1219   if (cachefile && unveil(cachefile, "rwc") == -1)
   1220     err(1, "unveil: %s", cachefile);
   1221 
   1222   if (cachefile) {
   1223     if (pledge("stdio rpath wpath cpath fattr", NULL) == -1)
   1224       err(1, "pledge");
   1225   } else {
   1226     if (pledge("stdio rpath wpath cpath", NULL) == -1)
   1227       err(1, "pledge");
   1228   }
   1229 #endif
   1230 
   1231   if (git_repository_open_ext(&repo, repodir,
   1232         GIT_REPOSITORY_OPEN_NO_SEARCH, NULL) < 0) {
   1233     fprintf(stderr, "%s: cannot open repository\n", argv[0]);
   1234     return 1;
   1235   }
   1236 
   1237   /* find HEAD */
   1238   if (!git_revparse_single(&obj, repo, "HEAD"))
   1239     head = git_object_id(obj);
   1240   git_object_free(obj);
   1241 
   1242   /* use directory name as name */
   1243   if ((name = strrchr(repodirabs, '/')))
   1244     name++;
   1245   else
   1246     name = "";
   1247 
   1248   /* strip .git suffix */
   1249   if (!(strippedname = strdup(name)))
   1250     err(1, "strdup");
   1251   if ((p = strrchr(strippedname, '.')))
   1252     if (!strcmp(p, ".git"))
   1253       *p = '\0';
   1254 
   1255   /* read description or .git/description */
   1256   joinpath(path, sizeof(path), repodir, "description");
   1257   if (!(fpread = fopen(path, "r"))) {
   1258     joinpath(path, sizeof(path), repodir, ".git/description");
   1259     fpread = fopen(path, "r");
   1260   }
   1261   if (fpread) {
   1262     if (!fgets(description, sizeof(description), fpread))
   1263       description[0] = '\0';
   1264     fclose(fpread);
   1265   }
   1266 
   1267   /* read url or .git/url */
   1268   joinpath(path, sizeof(path), repodir, "url");
   1269   if (!(fpread = fopen(path, "r"))) {
   1270     joinpath(path, sizeof(path), repodir, ".git/url");
   1271     fpread = fopen(path, "r");
   1272   }
   1273   if (fpread) {
   1274     if (!fgets(cloneurl, sizeof(cloneurl), fpread))
   1275       cloneurl[0] = '\0';
   1276     cloneurl[strcspn(cloneurl, "\n")] = '\0';
   1277     fclose(fpread);
   1278   }
   1279 
   1280   /* check LICENSE */
   1281   for (i = 0; i < LEN(licensefiles) && !license; i++) {
   1282     if (!git_revparse_single(&obj, repo, licensefiles[i]) &&
   1283         git_object_type(obj) == GIT_OBJ_BLOB)
   1284       license = licensefiles[i] + strlen("HEAD:");
   1285     git_object_free(obj);
   1286   }
   1287 
   1288   /* check README */
   1289   for (i = 0; i < LEN(readmefiles) && !readme; i++) {
   1290     if (!git_revparse_single(&obj, repo, readmefiles[i]) &&
   1291         git_object_type(obj) == GIT_OBJ_BLOB)
   1292     {
   1293       readme = readmefiles[i] + strlen("HEAD:");
   1294       char *ext = readme + strlen("README.");
   1295 
   1296       // If the README is a Markdown file, use CMark to render it as HTML
   1297       if (!strcmp(ext, "md") && !git_blob_is_binary((git_blob *)obj))
   1298       {
   1299         readme = "README.html";
   1300         fp = efopen(readme, "w");
   1301 
   1302         write_markdown_readme(fp, (git_blob*)obj);
   1303         fclose(fp);
   1304       }
   1305       else
   1306       {
   1307         char tmp[510];
   1308         sprintf(tmp, "%sfile/%s.html", relpath, readme);
   1309         readme = tmp;
   1310       }
   1311     }
   1312     git_object_free(obj);
   1313   }
   1314 
   1315   if (!git_revparse_single(&obj, repo, "HEAD:.gitmodules") &&
   1316       git_object_type(obj) == GIT_OBJ_BLOB)
   1317     submodules = ".gitmodules";
   1318   git_object_free(obj);
   1319 
   1320   /* Create the blob directory */
   1321   mkdir("blob", S_IRWXU | S_IRWXG | S_IRWXO);
   1322 
   1323   /* log for HEAD */
   1324   fp = efopen("log.html", "w");
   1325   relpath = "";
   1326   mkdir("commit", S_IRWXU | S_IRWXG | S_IRWXO);
   1327   writeheader(fp, "Log");
   1328   fputs("</ul>\n", fp);
   1329   fputs("<div class=\"table-container\"><table id=\"log\"><thead>\n<tr><td><b>Date</b></td>"
   1330       "<td><b>Commit message</b></td>"
   1331       "<td><b>Author</b></td><td class=\"num\" align=\"right\"><b>Files</b></td>"
   1332       "<td class=\"num\" align=\"right\"><b>+</b></td>"
   1333       "<td class=\"num\" align=\"right\"><b>-</b></td></tr>\n</thead><tbody>\n", fp);
   1334 
   1335   if (cachefile && head) {
   1336     /* read from cache file (does not need to exist) */
   1337     if ((rcachefp = fopen(cachefile, "r"))) {
   1338       if (!fgets(lastoidstr, sizeof(lastoidstr), rcachefp))
   1339         errx(1, "%s: no object id", cachefile);
   1340       if (git_oid_fromstr(&lastoid, lastoidstr))
   1341         errx(1, "%s: invalid object id", cachefile);
   1342     }
   1343 
   1344     /* write log to (temporary) cache */
   1345     if ((fd = mkstemp(tmppath)) == -1)
   1346       err(1, "mkstemp");
   1347     if (!(wcachefp = fdopen(fd, "w")))
   1348       err(1, "fdopen: '%s'", tmppath);
   1349     /* write last commit id (HEAD) */
   1350     git_oid_tostr(buf, sizeof(buf), head);
   1351     fprintf(wcachefp, "%s\n", buf);
   1352 
   1353     writelog(fp, head);
   1354 
   1355     if (rcachefp) {
   1356       /* append previous log to log.html and the new cache */
   1357       while (!feof(rcachefp)) {
   1358         n = fread(buf, 1, sizeof(buf), rcachefp);
   1359         if (ferror(rcachefp))
   1360           err(1, "fread");
   1361         if (fwrite(buf, 1, n, fp) != n ||
   1362             fwrite(buf, 1, n, wcachefp) != n)
   1363           err(1, "fwrite");
   1364       }
   1365       fclose(rcachefp);
   1366     }
   1367     fclose(wcachefp);
   1368   } else {
   1369     if (head)
   1370       writelog(fp, head);
   1371   }
   1372 
   1373   fputs("</tbody></table></div>", fp);
   1374   writefooter(fp);
   1375   fclose(fp);
   1376 
   1377   /* files for HEAD */
   1378   fp = efopen("files.html", "w");
   1379   writeheader(fp, "Files");
   1380   fputs("</ul>\n", fp);
   1381   if (head)
   1382     writefiles(fp, head);
   1383   writefooter(fp);
   1384   fclose(fp);
   1385 
   1386   /* summary page with branches and tags */
   1387   fp = efopen("refs.html", "w");
   1388   writeheader(fp, "Refs");
   1389   fputs("</ul>\n", fp);
   1390   writerefs(fp);
   1391   writefooter(fp);
   1392   fclose(fp);
   1393 
   1394   /* Atom feed */
   1395   fp = efopen("atom.xml", "w");
   1396   writeatom(fp, 1);
   1397   fclose(fp);
   1398 
   1399   /* Atom feed for tags / releases */
   1400   fp = efopen("tags.xml", "w");
   1401   writeatom(fp, 0);
   1402   fclose(fp);
   1403 
   1404   /* rename new cache file on success */
   1405   if (cachefile && head) {
   1406     if (rename(tmppath, cachefile))
   1407       err(1, "rename: '%s' to '%s'", tmppath, cachefile);
   1408     umask((mask = umask(0)));
   1409     if (chmod(cachefile,
   1410           (S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH) & ~mask))
   1411       err(1, "chmod: '%s'", cachefile);
   1412   }
   1413 
   1414   /* cleanup */
   1415   git_repository_free(repo);
   1416   git_libgit2_shutdown();
   1417 
   1418   return 0;
   1419 }