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