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