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