Merge branch 'lt/dirstat'
[git] / builtin-commit.c
1 /*
2  * Builtin "git commit"
3  *
4  * Copyright (c) 2007 Kristian Høgsberg <krh@redhat.com>
5  * Based on git-commit.sh by Junio C Hamano and Linus Torvalds
6  */
7
8 #include "cache.h"
9 #include "cache-tree.h"
10 #include "color.h"
11 #include "dir.h"
12 #include "builtin.h"
13 #include "diff.h"
14 #include "diffcore.h"
15 #include "commit.h"
16 #include "revision.h"
17 #include "wt-status.h"
18 #include "run-command.h"
19 #include "refs.h"
20 #include "log-tree.h"
21 #include "strbuf.h"
22 #include "utf8.h"
23 #include "parse-options.h"
24 #include "path-list.h"
25 #include "unpack-trees.h"
26
27 static const char * const builtin_commit_usage[] = {
28         "git-commit [options] [--] <filepattern>...",
29         NULL
30 };
31
32 static const char * const builtin_status_usage[] = {
33         "git-status [options] [--] <filepattern>...",
34         NULL
35 };
36
37 static unsigned char head_sha1[20], merge_head_sha1[20];
38 static char *use_message_buffer;
39 static const char commit_editmsg[] = "COMMIT_EDITMSG";
40 static struct lock_file index_lock; /* real index */
41 static struct lock_file false_lock; /* used only for partial commits */
42 static enum {
43         COMMIT_AS_IS = 1,
44         COMMIT_NORMAL,
45         COMMIT_PARTIAL,
46 } commit_style;
47
48 static char *logfile, *force_author, *template_file;
49 static char *edit_message, *use_message;
50 static int all, edit_flag, also, interactive, only, amend, signoff;
51 static int quiet, verbose, untracked_files, no_verify, allow_empty;
52 /*
53  * The default commit message cleanup mode will remove the lines
54  * beginning with # (shell comments) and leading and trailing
55  * whitespaces (empty lines or containing only whitespaces)
56  * if editor is used, and only the whitespaces if the message
57  * is specified explicitly.
58  */
59 static enum {
60         CLEANUP_SPACE,
61         CLEANUP_NONE,
62         CLEANUP_ALL,
63 } cleanup_mode;
64 static char *cleanup_arg;
65
66 static int use_editor = 1, initial_commit, in_merge;
67 const char *only_include_assumed;
68 struct strbuf message;
69
70 static int opt_parse_m(const struct option *opt, const char *arg, int unset)
71 {
72         struct strbuf *buf = opt->value;
73         if (unset)
74                 strbuf_setlen(buf, 0);
75         else {
76                 strbuf_addstr(buf, arg);
77                 strbuf_addch(buf, '\n');
78                 strbuf_addch(buf, '\n');
79         }
80         return 0;
81 }
82
83 static struct option builtin_commit_options[] = {
84         OPT__QUIET(&quiet),
85         OPT__VERBOSE(&verbose),
86         OPT_GROUP("Commit message options"),
87
88         OPT_STRING('F', "file", &logfile, "FILE", "read log from file"),
89         OPT_STRING(0, "author", &force_author, "AUTHOR", "override author for commit"),
90         OPT_CALLBACK('m', "message", &message, "MESSAGE", "specify commit message", opt_parse_m),
91         OPT_STRING('c', "reedit-message", &edit_message, "COMMIT", "reuse and edit message from specified commit "),
92         OPT_STRING('C', "reuse-message", &use_message, "COMMIT", "reuse message from specified commit"),
93         OPT_BOOLEAN('s', "signoff", &signoff, "add Signed-off-by: header"),
94         OPT_STRING('t', "template", &template_file, "FILE", "use specified template file"),
95         OPT_BOOLEAN('e', "edit", &edit_flag, "force edit of commit"),
96
97         OPT_GROUP("Commit contents options"),
98         OPT_BOOLEAN('a', "all", &all, "commit all changed files"),
99         OPT_BOOLEAN('i', "include", &also, "add specified files to index for commit"),
100         OPT_BOOLEAN(0, "interactive", &interactive, "interactively add files"),
101         OPT_BOOLEAN('o', "only", &only, ""),
102         OPT_BOOLEAN('n', "no-verify", &no_verify, "bypass pre-commit hook"),
103         OPT_BOOLEAN(0, "amend", &amend, "amend previous commit"),
104         OPT_BOOLEAN(0, "untracked-files", &untracked_files, "show all untracked files"),
105         OPT_BOOLEAN(0, "allow-empty", &allow_empty, "ok to record an empty change"),
106         OPT_STRING(0, "cleanup", &cleanup_arg, "default", "how to strip spaces and #comments from message"),
107
108         OPT_END()
109 };
110
111 static void rollback_index_files(void)
112 {
113         switch (commit_style) {
114         case COMMIT_AS_IS:
115                 break; /* nothing to do */
116         case COMMIT_NORMAL:
117                 rollback_lock_file(&index_lock);
118                 break;
119         case COMMIT_PARTIAL:
120                 rollback_lock_file(&index_lock);
121                 rollback_lock_file(&false_lock);
122                 break;
123         }
124 }
125
126 static int commit_index_files(void)
127 {
128         int err = 0;
129
130         switch (commit_style) {
131         case COMMIT_AS_IS:
132                 break; /* nothing to do */
133         case COMMIT_NORMAL:
134                 err = commit_lock_file(&index_lock);
135                 break;
136         case COMMIT_PARTIAL:
137                 err = commit_lock_file(&index_lock);
138                 rollback_lock_file(&false_lock);
139                 break;
140         }
141
142         return err;
143 }
144
145 /*
146  * Take a union of paths in the index and the named tree (typically, "HEAD"),
147  * and return the paths that match the given pattern in list.
148  */
149 static int list_paths(struct path_list *list, const char *with_tree,
150                       const char *prefix, const char **pattern)
151 {
152         int i;
153         char *m;
154
155         for (i = 0; pattern[i]; i++)
156                 ;
157         m = xcalloc(1, i);
158
159         if (with_tree)
160                 overlay_tree_on_cache(with_tree, prefix);
161
162         for (i = 0; i < active_nr; i++) {
163                 struct cache_entry *ce = active_cache[i];
164                 if (ce->ce_flags & CE_UPDATE)
165                         continue;
166                 if (!pathspec_match(pattern, m, ce->name, 0))
167                         continue;
168                 path_list_insert(ce->name, list);
169         }
170
171         return report_path_error(m, pattern, prefix ? strlen(prefix) : 0);
172 }
173
174 static void add_remove_files(struct path_list *list)
175 {
176         int i;
177         for (i = 0; i < list->nr; i++) {
178                 struct path_list_item *p = &(list->items[i]);
179                 if (file_exists(p->path))
180                         add_file_to_cache(p->path, 0);
181                 else
182                         remove_file_from_cache(p->path);
183         }
184 }
185
186 static void create_base_index(void)
187 {
188         struct tree *tree;
189         struct unpack_trees_options opts;
190         struct tree_desc t;
191
192         if (initial_commit) {
193                 discard_cache();
194                 return;
195         }
196
197         memset(&opts, 0, sizeof(opts));
198         opts.head_idx = 1;
199         opts.index_only = 1;
200         opts.merge = 1;
201
202         opts.fn = oneway_merge;
203         tree = parse_tree_indirect(head_sha1);
204         if (!tree)
205                 die("failed to unpack HEAD tree object");
206         parse_tree(tree);
207         init_tree_desc(&t, tree->buffer, tree->size);
208         unpack_trees(1, &t, &opts);
209 }
210
211 static char *prepare_index(int argc, const char **argv, const char *prefix)
212 {
213         int fd;
214         struct path_list partial;
215         const char **pathspec = NULL;
216
217         if (interactive) {
218                 interactive_add(argc, argv, prefix);
219                 commit_style = COMMIT_AS_IS;
220                 return get_index_file();
221         }
222
223         if (read_cache() < 0)
224                 die("index file corrupt");
225
226         if (*argv)
227                 pathspec = get_pathspec(prefix, argv);
228
229         /*
230          * Non partial, non as-is commit.
231          *
232          * (1) get the real index;
233          * (2) update the_index as necessary;
234          * (3) write the_index out to the real index (still locked);
235          * (4) return the name of the locked index file.
236          *
237          * The caller should run hooks on the locked real index, and
238          * (A) if all goes well, commit the real index;
239          * (B) on failure, rollback the real index.
240          */
241         if (all || (also && pathspec && *pathspec)) {
242                 int fd = hold_locked_index(&index_lock, 1);
243                 add_files_to_cache(0, also ? prefix : NULL, pathspec);
244                 refresh_cache(REFRESH_QUIET);
245                 if (write_cache(fd, active_cache, active_nr) ||
246                     close_lock_file(&index_lock))
247                         die("unable to write new_index file");
248                 commit_style = COMMIT_NORMAL;
249                 return index_lock.filename;
250         }
251
252         /*
253          * As-is commit.
254          *
255          * (1) return the name of the real index file.
256          *
257          * The caller should run hooks on the real index, and run
258          * hooks on the real index, and create commit from the_index.
259          * We still need to refresh the index here.
260          */
261         if (!pathspec || !*pathspec) {
262                 fd = hold_locked_index(&index_lock, 1);
263                 refresh_cache(REFRESH_QUIET);
264                 if (write_cache(fd, active_cache, active_nr) ||
265                     commit_locked_index(&index_lock))
266                         die("unable to write new_index file");
267                 commit_style = COMMIT_AS_IS;
268                 return get_index_file();
269         }
270
271         /*
272          * A partial commit.
273          *
274          * (0) find the set of affected paths;
275          * (1) get lock on the real index file;
276          * (2) update the_index with the given paths;
277          * (3) write the_index out to the real index (still locked);
278          * (4) get lock on the false index file;
279          * (5) reset the_index from HEAD;
280          * (6) update the_index the same way as (2);
281          * (7) write the_index out to the false index file;
282          * (8) return the name of the false index file (still locked);
283          *
284          * The caller should run hooks on the locked false index, and
285          * create commit from it.  Then
286          * (A) if all goes well, commit the real index;
287          * (B) on failure, rollback the real index;
288          * In either case, rollback the false index.
289          */
290         commit_style = COMMIT_PARTIAL;
291
292         if (file_exists(git_path("MERGE_HEAD")))
293                 die("cannot do a partial commit during a merge.");
294
295         memset(&partial, 0, sizeof(partial));
296         partial.strdup_paths = 1;
297         if (list_paths(&partial, initial_commit ? NULL : "HEAD", prefix, pathspec))
298                 exit(1);
299
300         discard_cache();
301         if (read_cache() < 0)
302                 die("cannot read the index");
303
304         fd = hold_locked_index(&index_lock, 1);
305         add_remove_files(&partial);
306         refresh_cache(REFRESH_QUIET);
307         if (write_cache(fd, active_cache, active_nr) ||
308             close_lock_file(&index_lock))
309                 die("unable to write new_index file");
310
311         fd = hold_lock_file_for_update(&false_lock,
312                                        git_path("next-index-%d", getpid()), 1);
313
314         create_base_index();
315         add_remove_files(&partial);
316         refresh_cache(REFRESH_QUIET);
317
318         if (write_cache(fd, active_cache, active_nr) ||
319             close_lock_file(&false_lock))
320                 die("unable to write temporary index file");
321
322         discard_cache();
323         read_cache_from(false_lock.filename);
324
325         return false_lock.filename;
326 }
327
328 static int run_status(FILE *fp, const char *index_file, const char *prefix, int nowarn)
329 {
330         struct wt_status s;
331
332         wt_status_prepare(&s);
333         if (wt_status_relative_paths)
334                 s.prefix = prefix;
335
336         if (amend) {
337                 s.amend = 1;
338                 s.reference = "HEAD^1";
339         }
340         s.verbose = verbose;
341         s.untracked = untracked_files;
342         s.index_file = index_file;
343         s.fp = fp;
344         s.nowarn = nowarn;
345
346         wt_status_print(&s);
347
348         return s.commitable;
349 }
350
351 static int run_hook(const char *index_file, const char *name, ...)
352 {
353         struct child_process hook;
354         const char *argv[10], *env[2];
355         char index[PATH_MAX];
356         va_list args;
357         int i;
358
359         va_start(args, name);
360         argv[0] = git_path("hooks/%s", name);
361         i = 0;
362         do {
363                 if (++i >= ARRAY_SIZE(argv))
364                         die ("run_hook(): too many arguments");
365                 argv[i] = va_arg(args, const char *);
366         } while (argv[i]);
367         va_end(args);
368
369         snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
370         env[0] = index;
371         env[1] = NULL;
372
373         if (access(argv[0], X_OK) < 0)
374                 return 0;
375
376         memset(&hook, 0, sizeof(hook));
377         hook.argv = argv;
378         hook.no_stdin = 1;
379         hook.stdout_to_stderr = 1;
380         hook.env = env;
381
382         return run_command(&hook);
383 }
384
385 static int is_a_merge(const unsigned char *sha1)
386 {
387         struct commit *commit = lookup_commit(sha1);
388         if (!commit || parse_commit(commit))
389                 die("could not parse HEAD commit");
390         return !!(commit->parents && commit->parents->next);
391 }
392
393 static const char sign_off_header[] = "Signed-off-by: ";
394
395 static int prepare_to_commit(const char *index_file, const char *prefix)
396 {
397         struct stat statbuf;
398         int commitable, saved_color_setting;
399         struct strbuf sb;
400         char *buffer;
401         FILE *fp;
402         const char *hook_arg1 = NULL;
403         const char *hook_arg2 = NULL;
404
405         if (!no_verify && run_hook(index_file, "pre-commit", NULL))
406                 return 0;
407
408         strbuf_init(&sb, 0);
409         if (message.len) {
410                 strbuf_addbuf(&sb, &message);
411                 hook_arg1 = "message";
412         } else if (logfile && !strcmp(logfile, "-")) {
413                 if (isatty(0))
414                         fprintf(stderr, "(reading log message from standard input)\n");
415                 if (strbuf_read(&sb, 0, 0) < 0)
416                         die("could not read log from standard input");
417                 hook_arg1 = "message";
418         } else if (logfile) {
419                 if (strbuf_read_file(&sb, logfile, 0) < 0)
420                         die("could not read log file '%s': %s",
421                             logfile, strerror(errno));
422                 hook_arg1 = "message";
423         } else if (use_message) {
424                 buffer = strstr(use_message_buffer, "\n\n");
425                 if (!buffer || buffer[2] == '\0')
426                         die("commit has empty message");
427                 strbuf_add(&sb, buffer + 2, strlen(buffer + 2));
428                 hook_arg1 = "commit";
429                 hook_arg2 = use_message;
430         } else if (!stat(git_path("MERGE_MSG"), &statbuf)) {
431                 if (strbuf_read_file(&sb, git_path("MERGE_MSG"), 0) < 0)
432                         die("could not read MERGE_MSG: %s", strerror(errno));
433                 hook_arg1 = "merge";
434         } else if (!stat(git_path("SQUASH_MSG"), &statbuf)) {
435                 if (strbuf_read_file(&sb, git_path("SQUASH_MSG"), 0) < 0)
436                         die("could not read SQUASH_MSG: %s", strerror(errno));
437                 hook_arg1 = "squash";
438         } else if (template_file && !stat(template_file, &statbuf)) {
439                 if (strbuf_read_file(&sb, template_file, 0) < 0)
440                         die("could not read %s: %s",
441                             template_file, strerror(errno));
442                 hook_arg1 = "template";
443         }
444
445         /*
446          * This final case does not modify the template message,
447          * it just sets the argument to the prepare-commit-msg hook.
448          */
449         else if (in_merge)
450                 hook_arg1 = "merge";
451
452         fp = fopen(git_path(commit_editmsg), "w");
453         if (fp == NULL)
454                 die("could not open %s", git_path(commit_editmsg));
455
456         if (cleanup_mode != CLEANUP_NONE)
457                 stripspace(&sb, 0);
458
459         if (signoff) {
460                 struct strbuf sob;
461                 int i;
462
463                 strbuf_init(&sob, 0);
464                 strbuf_addstr(&sob, sign_off_header);
465                 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
466                                              getenv("GIT_COMMITTER_EMAIL")));
467                 strbuf_addch(&sob, '\n');
468                 for (i = sb.len - 1; i > 0 && sb.buf[i - 1] != '\n'; i--)
469                         ; /* do nothing */
470                 if (prefixcmp(sb.buf + i, sob.buf)) {
471                         if (prefixcmp(sb.buf + i, sign_off_header))
472                                 strbuf_addch(&sb, '\n');
473                         strbuf_addbuf(&sb, &sob);
474                 }
475                 strbuf_release(&sob);
476         }
477
478         if (fwrite(sb.buf, 1, sb.len, fp) < sb.len)
479                 die("could not write commit template: %s", strerror(errno));
480
481         strbuf_release(&sb);
482
483         if (use_editor) {
484                 if (in_merge)
485                         fprintf(fp,
486                                 "#\n"
487                                 "# It looks like you may be committing a MERGE.\n"
488                                 "# If this is not correct, please remove the file\n"
489                                 "#      %s\n"
490                                 "# and try again.\n"
491                                 "#\n",
492                                 git_path("MERGE_HEAD"));
493
494                 fprintf(fp,
495                         "\n"
496                         "# Please enter the commit message for your changes.\n"
497                         "# (Comment lines starting with '#' will ");
498                 if (cleanup_mode == CLEANUP_ALL)
499                         fprintf(fp, "not be included)\n");
500                 else /* CLEANUP_SPACE, that is. */
501                         fprintf(fp, "be kept.\n"
502                                 "# You can remove them yourself if you want to)\n");
503                 if (only_include_assumed)
504                         fprintf(fp, "# %s\n", only_include_assumed);
505
506                 saved_color_setting = wt_status_use_color;
507                 wt_status_use_color = 0;
508                 commitable = run_status(fp, index_file, prefix, 1);
509                 wt_status_use_color = saved_color_setting;
510         } else {
511                 struct rev_info rev;
512                 unsigned char sha1[20];
513                 const char *parent = "HEAD";
514
515                 if (!active_nr && read_cache() < 0)
516                         die("Cannot read index");
517
518                 if (amend)
519                         parent = "HEAD^1";
520
521                 if (get_sha1(parent, sha1))
522                         commitable = !!active_nr;
523                 else {
524                         init_revisions(&rev, "");
525                         rev.abbrev = 0;
526                         setup_revisions(0, NULL, &rev, parent);
527                         DIFF_OPT_SET(&rev.diffopt, QUIET);
528                         DIFF_OPT_SET(&rev.diffopt, EXIT_WITH_STATUS);
529                         run_diff_index(&rev, 1 /* cached */);
530
531                         commitable = !!DIFF_OPT_TST(&rev.diffopt, HAS_CHANGES);
532                 }
533         }
534
535         fclose(fp);
536
537         if (!commitable && !in_merge && !allow_empty &&
538             !(amend && is_a_merge(head_sha1))) {
539                 run_status(stdout, index_file, prefix, 0);
540                 unlink(commit_editmsg);
541                 return 0;
542         }
543
544         /*
545          * Re-read the index as pre-commit hook could have updated it,
546          * and write it out as a tree.  We must do this before we invoke
547          * the editor and after we invoke run_status above.
548          */
549         discard_cache();
550         read_cache_from(index_file);
551         if (!active_cache_tree)
552                 active_cache_tree = cache_tree();
553         if (cache_tree_update(active_cache_tree,
554                               active_cache, active_nr, 0, 0) < 0) {
555                 error("Error building trees");
556                 return 0;
557         }
558
559         if (run_hook(index_file, "prepare-commit-msg",
560                      git_path(commit_editmsg), hook_arg1, hook_arg2, NULL))
561                 return 0;
562
563         if (use_editor) {
564                 char index[PATH_MAX];
565                 const char *env[2] = { index, NULL };
566                 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
567                 launch_editor(git_path(commit_editmsg), NULL, env);
568         }
569
570         if (!no_verify &&
571             run_hook(index_file, "commit-msg", git_path(commit_editmsg), NULL)) {
572                 return 0;
573         }
574
575         return 1;
576 }
577
578 /*
579  * Find out if the message starting at position 'start' in the strbuf
580  * contains only whitespace and Signed-off-by lines.
581  */
582 static int message_is_empty(struct strbuf *sb, int start)
583 {
584         struct strbuf tmpl;
585         const char *nl;
586         int eol, i;
587
588         if (cleanup_mode == CLEANUP_NONE && sb->len)
589                 return 0;
590
591         /* See if the template is just a prefix of the message. */
592         strbuf_init(&tmpl, 0);
593         if (template_file && strbuf_read_file(&tmpl, template_file, 0) > 0) {
594                 stripspace(&tmpl, cleanup_mode == CLEANUP_ALL);
595                 if (start + tmpl.len <= sb->len &&
596                     memcmp(tmpl.buf, sb->buf + start, tmpl.len) == 0)
597                         start += tmpl.len;
598         }
599         strbuf_release(&tmpl);
600
601         /* Check if the rest is just whitespace and Signed-of-by's. */
602         for (i = start; i < sb->len; i++) {
603                 nl = memchr(sb->buf + i, '\n', sb->len - i);
604                 if (nl)
605                         eol = nl - sb->buf;
606                 else
607                         eol = sb->len;
608
609                 if (strlen(sign_off_header) <= eol - i &&
610                     !prefixcmp(sb->buf + i, sign_off_header)) {
611                         i = eol;
612                         continue;
613                 }
614                 while (i < eol)
615                         if (!isspace(sb->buf[i++]))
616                                 return 0;
617         }
618
619         return 1;
620 }
621
622 static void determine_author_info(struct strbuf *sb)
623 {
624         char *name, *email, *date;
625
626         name = getenv("GIT_AUTHOR_NAME");
627         email = getenv("GIT_AUTHOR_EMAIL");
628         date = getenv("GIT_AUTHOR_DATE");
629
630         if (use_message) {
631                 const char *a, *lb, *rb, *eol;
632
633                 a = strstr(use_message_buffer, "\nauthor ");
634                 if (!a)
635                         die("invalid commit: %s", use_message);
636
637                 lb = strstr(a + 8, " <");
638                 rb = strstr(a + 8, "> ");
639                 eol = strchr(a + 8, '\n');
640                 if (!lb || !rb || !eol)
641                         die("invalid commit: %s", use_message);
642
643                 name = xstrndup(a + 8, lb - (a + 8));
644                 email = xstrndup(lb + 2, rb - (lb + 2));
645                 date = xstrndup(rb + 2, eol - (rb + 2));
646         }
647
648         if (force_author) {
649                 const char *lb = strstr(force_author, " <");
650                 const char *rb = strchr(force_author, '>');
651
652                 if (!lb || !rb)
653                         die("malformed --author parameter");
654                 name = xstrndup(force_author, lb - force_author);
655                 email = xstrndup(lb + 2, rb - (lb + 2));
656         }
657
658         strbuf_addf(sb, "author %s\n", fmt_ident(name, email, date, IDENT_ERROR_ON_NO_NAME));
659 }
660
661 static int parse_and_validate_options(int argc, const char *argv[],
662                                       const char * const usage[])
663 {
664         int f = 0;
665
666         argc = parse_options(argc, argv, builtin_commit_options, usage, 0);
667
668         if (logfile || message.len || use_message)
669                 use_editor = 0;
670         if (edit_flag)
671                 use_editor = 1;
672         if (!use_editor)
673                 setenv("GIT_EDITOR", ":", 1);
674
675         if (get_sha1("HEAD", head_sha1))
676                 initial_commit = 1;
677
678         if (!get_sha1("MERGE_HEAD", merge_head_sha1))
679                 in_merge = 1;
680
681         /* Sanity check options */
682         if (amend && initial_commit)
683                 die("You have nothing to amend.");
684         if (amend && in_merge)
685                 die("You are in the middle of a merge -- cannot amend.");
686
687         if (use_message)
688                 f++;
689         if (edit_message)
690                 f++;
691         if (logfile)
692                 f++;
693         if (f > 1)
694                 die("Only one of -c/-C/-F can be used.");
695         if (message.len && f > 0)
696                 die("Option -m cannot be combined with -c/-C/-F.");
697         if (edit_message)
698                 use_message = edit_message;
699         if (amend && !use_message)
700                 use_message = "HEAD";
701         if (use_message) {
702                 unsigned char sha1[20];
703                 static char utf8[] = "UTF-8";
704                 const char *out_enc;
705                 char *enc, *end;
706                 struct commit *commit;
707
708                 if (get_sha1(use_message, sha1))
709                         die("could not lookup commit %s", use_message);
710                 commit = lookup_commit_reference(sha1);
711                 if (!commit || parse_commit(commit))
712                         die("could not parse commit %s", use_message);
713
714                 enc = strstr(commit->buffer, "\nencoding");
715                 if (enc) {
716                         end = strchr(enc + 10, '\n');
717                         enc = xstrndup(enc + 10, end - (enc + 10));
718                 } else {
719                         enc = utf8;
720                 }
721                 out_enc = git_commit_encoding ? git_commit_encoding : utf8;
722
723                 if (strcmp(out_enc, enc))
724                         use_message_buffer =
725                                 reencode_string(commit->buffer, out_enc, enc);
726
727                 /*
728                  * If we failed to reencode the buffer, just copy it
729                  * byte for byte so the user can try to fix it up.
730                  * This also handles the case where input and output
731                  * encodings are identical.
732                  */
733                 if (use_message_buffer == NULL)
734                         use_message_buffer = xstrdup(commit->buffer);
735                 if (enc != utf8)
736                         free(enc);
737         }
738
739         if (!!also + !!only + !!all + !!interactive > 1)
740                 die("Only one of --include/--only/--all/--interactive can be used.");
741         if (argc == 0 && (also || (only && !amend)))
742                 die("No paths with --include/--only does not make sense.");
743         if (argc == 0 && only && amend)
744                 only_include_assumed = "Clever... amending the last one with dirty index.";
745         if (argc > 0 && !also && !only) {
746                 only_include_assumed = "Explicit paths specified without -i nor -o; assuming --only paths...";
747                 also = 0;
748         }
749         if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
750                 cleanup_mode = use_editor ? CLEANUP_ALL : CLEANUP_SPACE;
751         else if (!strcmp(cleanup_arg, "verbatim"))
752                 cleanup_mode = CLEANUP_NONE;
753         else if (!strcmp(cleanup_arg, "whitespace"))
754                 cleanup_mode = CLEANUP_SPACE;
755         else if (!strcmp(cleanup_arg, "strip"))
756                 cleanup_mode = CLEANUP_ALL;
757         else
758                 die("Invalid cleanup mode %s", cleanup_arg);
759
760         if (all && argc > 0)
761                 die("Paths with -a does not make sense.");
762         else if (interactive && argc > 0)
763                 die("Paths with --interactive does not make sense.");
764
765         return argc;
766 }
767
768 int cmd_status(int argc, const char **argv, const char *prefix)
769 {
770         const char *index_file;
771         int commitable;
772
773         git_config(git_status_config);
774
775         if (wt_status_use_color == -1)
776                 wt_status_use_color = git_use_color_default;
777
778         argc = parse_and_validate_options(argc, argv, builtin_status_usage);
779
780         index_file = prepare_index(argc, argv, prefix);
781
782         commitable = run_status(stdout, index_file, prefix, 0);
783
784         rollback_index_files();
785
786         return commitable ? 0 : 1;
787 }
788
789 static void print_summary(const char *prefix, const unsigned char *sha1)
790 {
791         struct rev_info rev;
792         struct commit *commit;
793
794         commit = lookup_commit(sha1);
795         if (!commit)
796                 die("couldn't look up newly created commit");
797         if (!commit || parse_commit(commit))
798                 die("could not parse newly created commit");
799
800         init_revisions(&rev, prefix);
801         setup_revisions(0, NULL, &rev, NULL);
802
803         rev.abbrev = 0;
804         rev.diff = 1;
805         rev.diffopt.output_format =
806                 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
807
808         rev.verbose_header = 1;
809         rev.show_root_diff = 1;
810         rev.commit_format = get_commit_format("format:%h: %s");
811         rev.always_show_header = 0;
812         rev.diffopt.detect_rename = 1;
813         rev.diffopt.rename_limit = 100;
814         rev.diffopt.break_opt = 0;
815         diff_setup_done(&rev.diffopt);
816
817         printf("Created %scommit ", initial_commit ? "initial " : "");
818
819         if (!log_tree_commit(&rev, commit)) {
820                 struct strbuf buf = STRBUF_INIT;
821                 format_commit_message(commit, "%h: %s", &buf);
822                 printf("%s\n", buf.buf);
823                 strbuf_release(&buf);
824         }
825 }
826
827 int git_commit_config(const char *k, const char *v)
828 {
829         if (!strcmp(k, "commit.template")) {
830                 if (!v)
831                         return config_error_nonbool(v);
832                 template_file = xstrdup(v);
833                 return 0;
834         }
835
836         return git_status_config(k, v);
837 }
838
839 static const char commit_utf8_warn[] =
840 "Warning: commit message does not conform to UTF-8.\n"
841 "You may want to amend it after fixing the message, or set the config\n"
842 "variable i18n.commitencoding to the encoding your project uses.\n";
843
844 static void add_parent(struct strbuf *sb, const unsigned char *sha1)
845 {
846         struct object *obj = parse_object(sha1);
847         const char *parent = sha1_to_hex(sha1);
848         if (!obj)
849                 die("Unable to find commit parent %s", parent);
850         if (obj->type != OBJ_COMMIT)
851                 die("Parent %s isn't a proper commit", parent);
852         strbuf_addf(sb, "parent %s\n", parent);
853 }
854
855 int cmd_commit(int argc, const char **argv, const char *prefix)
856 {
857         int header_len;
858         struct strbuf sb;
859         const char *index_file, *reflog_msg;
860         char *nl, *p;
861         unsigned char commit_sha1[20];
862         struct ref_lock *ref_lock;
863
864         git_config(git_commit_config);
865
866         argc = parse_and_validate_options(argc, argv, builtin_commit_usage);
867
868         index_file = prepare_index(argc, argv, prefix);
869
870         /* Set up everything for writing the commit object.  This includes
871            running hooks, writing the trees, and interacting with the user.  */
872         if (!prepare_to_commit(index_file, prefix)) {
873                 rollback_index_files();
874                 return 1;
875         }
876
877         /*
878          * The commit object
879          */
880         strbuf_init(&sb, 0);
881         strbuf_addf(&sb, "tree %s\n",
882                     sha1_to_hex(active_cache_tree->sha1));
883
884         /* Determine parents */
885         if (initial_commit) {
886                 reflog_msg = "commit (initial)";
887         } else if (amend) {
888                 struct commit_list *c;
889                 struct commit *commit;
890
891                 reflog_msg = "commit (amend)";
892                 commit = lookup_commit(head_sha1);
893                 if (!commit || parse_commit(commit))
894                         die("could not parse HEAD commit");
895
896                 for (c = commit->parents; c; c = c->next)
897                         add_parent(&sb, c->item->object.sha1);
898         } else if (in_merge) {
899                 struct strbuf m;
900                 FILE *fp;
901
902                 reflog_msg = "commit (merge)";
903                 add_parent(&sb, head_sha1);
904                 strbuf_init(&m, 0);
905                 fp = fopen(git_path("MERGE_HEAD"), "r");
906                 if (fp == NULL)
907                         die("could not open %s for reading: %s",
908                             git_path("MERGE_HEAD"), strerror(errno));
909                 while (strbuf_getline(&m, fp, '\n') != EOF) {
910                         unsigned char sha1[20];
911                         if (get_sha1_hex(m.buf, sha1) < 0)
912                                 die("Corrupt MERGE_HEAD file (%s)", m.buf);
913                         add_parent(&sb, sha1);
914                 }
915                 fclose(fp);
916                 strbuf_release(&m);
917         } else {
918                 reflog_msg = "commit";
919                 strbuf_addf(&sb, "parent %s\n", sha1_to_hex(head_sha1));
920         }
921
922         determine_author_info(&sb);
923         strbuf_addf(&sb, "committer %s\n", git_committer_info(IDENT_ERROR_ON_NO_NAME));
924         if (!is_encoding_utf8(git_commit_encoding))
925                 strbuf_addf(&sb, "encoding %s\n", git_commit_encoding);
926         strbuf_addch(&sb, '\n');
927
928         /* Finally, get the commit message */
929         header_len = sb.len;
930         if (strbuf_read_file(&sb, git_path(commit_editmsg), 0) < 0) {
931                 rollback_index_files();
932                 die("could not read commit message");
933         }
934
935         /* Truncate the message just before the diff, if any. */
936         p = strstr(sb.buf, "\ndiff --git a/");
937         if (p != NULL)
938                 strbuf_setlen(&sb, p - sb.buf + 1);
939
940         if (cleanup_mode != CLEANUP_NONE)
941                 stripspace(&sb, cleanup_mode == CLEANUP_ALL);
942         if (sb.len < header_len || message_is_empty(&sb, header_len)) {
943                 rollback_index_files();
944                 die("no commit message?  aborting commit.");
945         }
946         strbuf_addch(&sb, '\0');
947         if (is_encoding_utf8(git_commit_encoding) && !is_utf8(sb.buf))
948                 fprintf(stderr, commit_utf8_warn);
949
950         if (write_sha1_file(sb.buf, sb.len - 1, commit_type, commit_sha1)) {
951                 rollback_index_files();
952                 die("failed to write commit object");
953         }
954
955         ref_lock = lock_any_ref_for_update("HEAD",
956                                            initial_commit ? NULL : head_sha1,
957                                            0);
958
959         nl = strchr(sb.buf + header_len, '\n');
960         if (nl)
961                 strbuf_setlen(&sb, nl + 1 - sb.buf);
962         else
963                 strbuf_addch(&sb, '\n');
964         strbuf_remove(&sb, 0, header_len);
965         strbuf_insert(&sb, 0, reflog_msg, strlen(reflog_msg));
966         strbuf_insert(&sb, strlen(reflog_msg), ": ", 2);
967
968         if (!ref_lock) {
969                 rollback_index_files();
970                 die("cannot lock HEAD ref");
971         }
972         if (write_ref_sha1(ref_lock, commit_sha1, sb.buf) < 0) {
973                 rollback_index_files();
974                 die("cannot update HEAD ref");
975         }
976
977         unlink(git_path("MERGE_HEAD"));
978         unlink(git_path("MERGE_MSG"));
979         unlink(git_path("SQUASH_MSG"));
980
981         if (commit_index_files())
982                 die ("Repository has been updated, but unable to write\n"
983                      "new_index file. Check that disk is not full or quota is\n"
984                      "not exceeded, and then \"git reset HEAD\" to recover.");
985
986         rerere();
987         run_hook(get_index_file(), "post-commit", NULL);
988         if (!quiet)
989                 print_summary(prefix, commit_sha1);
990
991         return 0;
992 }