use local cloning if insteadOf makes a local URL
[alt-git.git] / builtin / commit.c
blob72eb3beb36cd06f6e41d80d5761a953a1c3a1d56
1 /*
2 * Builtin "git commit"
4 * Copyright (c) 2007 Kristian Høgsberg <krh@redhat.com>
5 * Based on git-commit.sh by Junio C Hamano and Linus Torvalds
6 */
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 #include "quote.h"
28 #include "submodule.h"
29 #include "gpg-interface.h"
30 #include "column.h"
31 #include "sequencer.h"
32 #include "notes-utils.h"
33 #include "mailmap.h"
35 static const char * const builtin_commit_usage[] = {
36 N_("git commit [options] [--] <pathspec>..."),
37 NULL
40 static const char * const builtin_status_usage[] = {
41 N_("git status [options] [--] <pathspec>..."),
42 NULL
45 static const char implicit_ident_advice[] =
46 N_("Your name and email address were configured automatically based\n"
47 "on your username and hostname. Please check that they are accurate.\n"
48 "You can suppress this message by setting them explicitly:\n"
49 "\n"
50 " git config --global user.name \"Your Name\"\n"
51 " git config --global user.email you@example.com\n"
52 "\n"
53 "After doing this, you may fix the identity used for this commit with:\n"
54 "\n"
55 " git commit --amend --reset-author\n");
57 static const char empty_amend_advice[] =
58 N_("You asked to amend the most recent commit, but doing so would make\n"
59 "it empty. You can repeat your command with --allow-empty, or you can\n"
60 "remove the commit entirely with \"git reset HEAD^\".\n");
62 static const char empty_cherry_pick_advice[] =
63 N_("The previous cherry-pick is now empty, possibly due to conflict resolution.\n"
64 "If you wish to commit it anyway, use:\n"
65 "\n"
66 " git commit --allow-empty\n"
67 "\n");
69 static const char empty_cherry_pick_advice_single[] =
70 N_("Otherwise, please use 'git reset'\n");
72 static const char empty_cherry_pick_advice_multi[] =
73 N_("If you wish to skip this commit, use:\n"
74 "\n"
75 " git reset\n"
76 "\n"
77 "Then \"git cherry-pick --continue\" will resume cherry-picking\n"
78 "the remaining commits.\n");
80 static const char *use_message_buffer;
81 static const char commit_editmsg[] = "COMMIT_EDITMSG";
82 static struct lock_file index_lock; /* real index */
83 static struct lock_file false_lock; /* used only for partial commits */
84 static enum {
85 COMMIT_AS_IS = 1,
86 COMMIT_NORMAL,
87 COMMIT_PARTIAL
88 } commit_style;
90 static const char *logfile, *force_author;
91 static const char *template_file;
93 * The _message variables are commit names from which to take
94 * the commit message and/or authorship.
96 static const char *author_message, *author_message_buffer;
97 static char *edit_message, *use_message;
98 static char *fixup_message, *squash_message;
99 static int all, also, interactive, patch_interactive, only, amend, signoff;
100 static int edit_flag = -1; /* unspecified */
101 static int quiet, verbose, no_verify, allow_empty, dry_run, renew_authorship;
102 static int no_post_rewrite, allow_empty_message;
103 static char *untracked_files_arg, *force_date, *ignore_submodule_arg;
104 static char *sign_commit;
107 * The default commit message cleanup mode will remove the lines
108 * beginning with # (shell comments) and leading and trailing
109 * whitespaces (empty lines or containing only whitespaces)
110 * if editor is used, and only the whitespaces if the message
111 * is specified explicitly.
113 static enum {
114 CLEANUP_SPACE,
115 CLEANUP_NONE,
116 CLEANUP_SCISSORS,
117 CLEANUP_ALL
118 } cleanup_mode;
119 static const char *cleanup_arg;
121 static enum commit_whence whence;
122 static int sequencer_in_use;
123 static int use_editor = 1, include_status = 1;
124 static int show_ignored_in_status, have_option_m;
125 static const char *only_include_assumed;
126 static struct strbuf message = STRBUF_INIT;
128 static enum status_format {
129 STATUS_FORMAT_NONE = 0,
130 STATUS_FORMAT_LONG,
131 STATUS_FORMAT_SHORT,
132 STATUS_FORMAT_PORCELAIN,
134 STATUS_FORMAT_UNSPECIFIED
135 } status_format = STATUS_FORMAT_UNSPECIFIED;
137 static int opt_parse_m(const struct option *opt, const char *arg, int unset)
139 struct strbuf *buf = opt->value;
140 if (unset) {
141 have_option_m = 0;
142 strbuf_setlen(buf, 0);
143 } else {
144 have_option_m = 1;
145 if (buf->len)
146 strbuf_addch(buf, '\n');
147 strbuf_addstr(buf, arg);
148 strbuf_complete_line(buf);
150 return 0;
153 static void determine_whence(struct wt_status *s)
155 if (file_exists(git_path("MERGE_HEAD")))
156 whence = FROM_MERGE;
157 else if (file_exists(git_path("CHERRY_PICK_HEAD"))) {
158 whence = FROM_CHERRY_PICK;
159 if (file_exists(git_path("sequencer")))
160 sequencer_in_use = 1;
162 else
163 whence = FROM_COMMIT;
164 if (s)
165 s->whence = whence;
168 static void status_init_config(struct wt_status *s, config_fn_t fn)
170 wt_status_prepare(s);
171 gitmodules_config();
172 git_config(fn, s);
173 determine_whence(s);
174 s->hints = advice_status_hints; /* must come after git_config() */
177 static void rollback_index_files(void)
179 switch (commit_style) {
180 case COMMIT_AS_IS:
181 break; /* nothing to do */
182 case COMMIT_NORMAL:
183 rollback_lock_file(&index_lock);
184 break;
185 case COMMIT_PARTIAL:
186 rollback_lock_file(&index_lock);
187 rollback_lock_file(&false_lock);
188 break;
192 static int commit_index_files(void)
194 int err = 0;
196 switch (commit_style) {
197 case COMMIT_AS_IS:
198 break; /* nothing to do */
199 case COMMIT_NORMAL:
200 err = commit_lock_file(&index_lock);
201 break;
202 case COMMIT_PARTIAL:
203 err = commit_lock_file(&index_lock);
204 rollback_lock_file(&false_lock);
205 break;
208 return err;
212 * Take a union of paths in the index and the named tree (typically, "HEAD"),
213 * and return the paths that match the given pattern in list.
215 static int list_paths(struct string_list *list, const char *with_tree,
216 const char *prefix, const struct pathspec *pattern)
218 int i;
219 char *m;
221 if (!pattern->nr)
222 return 0;
224 m = xcalloc(1, pattern->nr);
226 if (with_tree) {
227 char *max_prefix = common_prefix(pattern);
228 overlay_tree_on_cache(with_tree, max_prefix ? max_prefix : prefix);
229 free(max_prefix);
232 for (i = 0; i < active_nr; i++) {
233 const struct cache_entry *ce = active_cache[i];
234 struct string_list_item *item;
236 if (ce->ce_flags & CE_UPDATE)
237 continue;
238 if (!ce_path_match(ce, pattern, m))
239 continue;
240 item = string_list_insert(list, ce->name);
241 if (ce_skip_worktree(ce))
242 item->util = item; /* better a valid pointer than a fake one */
245 return report_path_error(m, pattern, prefix);
248 static void add_remove_files(struct string_list *list)
250 int i;
251 for (i = 0; i < list->nr; i++) {
252 struct stat st;
253 struct string_list_item *p = &(list->items[i]);
255 /* p->util is skip-worktree */
256 if (p->util)
257 continue;
259 if (!lstat(p->string, &st)) {
260 if (add_to_cache(p->string, &st, 0))
261 die(_("updating files failed"));
262 } else
263 remove_file_from_cache(p->string);
267 static void create_base_index(const struct commit *current_head)
269 struct tree *tree;
270 struct unpack_trees_options opts;
271 struct tree_desc t;
273 if (!current_head) {
274 discard_cache();
275 return;
278 memset(&opts, 0, sizeof(opts));
279 opts.head_idx = 1;
280 opts.index_only = 1;
281 opts.merge = 1;
282 opts.src_index = &the_index;
283 opts.dst_index = &the_index;
285 opts.fn = oneway_merge;
286 tree = parse_tree_indirect(current_head->object.sha1);
287 if (!tree)
288 die(_("failed to unpack HEAD tree object"));
289 parse_tree(tree);
290 init_tree_desc(&t, tree->buffer, tree->size);
291 if (unpack_trees(1, &t, &opts))
292 exit(128); /* We've already reported the error, finish dying */
295 static void refresh_cache_or_die(int refresh_flags)
298 * refresh_flags contains REFRESH_QUIET, so the only errors
299 * are for unmerged entries.
301 if (refresh_cache(refresh_flags | REFRESH_IN_PORCELAIN))
302 die_resolve_conflict("commit");
305 static char *prepare_index(int argc, const char **argv, const char *prefix,
306 const struct commit *current_head, int is_status)
308 struct string_list partial;
309 struct pathspec pathspec;
310 int refresh_flags = REFRESH_QUIET;
312 if (is_status)
313 refresh_flags |= REFRESH_UNMERGED;
314 parse_pathspec(&pathspec, 0,
315 PATHSPEC_PREFER_FULL,
316 prefix, argv);
318 if (read_cache_preload(&pathspec) < 0)
319 die(_("index file corrupt"));
321 if (interactive) {
322 char *old_index_env = NULL;
323 hold_locked_index(&index_lock, 1);
325 refresh_cache_or_die(refresh_flags);
327 if (write_locked_index(&the_index, &index_lock, CLOSE_LOCK))
328 die(_("unable to create temporary index"));
330 old_index_env = getenv(INDEX_ENVIRONMENT);
331 setenv(INDEX_ENVIRONMENT, index_lock.filename, 1);
333 if (interactive_add(argc, argv, prefix, patch_interactive) != 0)
334 die(_("interactive add failed"));
336 if (old_index_env && *old_index_env)
337 setenv(INDEX_ENVIRONMENT, old_index_env, 1);
338 else
339 unsetenv(INDEX_ENVIRONMENT);
341 discard_cache();
342 read_cache_from(index_lock.filename);
344 commit_style = COMMIT_NORMAL;
345 return index_lock.filename;
349 * Non partial, non as-is commit.
351 * (1) get the real index;
352 * (2) update the_index as necessary;
353 * (3) write the_index out to the real index (still locked);
354 * (4) return the name of the locked index file.
356 * The caller should run hooks on the locked real index, and
357 * (A) if all goes well, commit the real index;
358 * (B) on failure, rollback the real index.
360 if (all || (also && pathspec.nr)) {
361 hold_locked_index(&index_lock, 1);
362 add_files_to_cache(also ? prefix : NULL, &pathspec, 0);
363 refresh_cache_or_die(refresh_flags);
364 update_main_cache_tree(WRITE_TREE_SILENT);
365 if (write_locked_index(&the_index, &index_lock, CLOSE_LOCK))
366 die(_("unable to write new_index file"));
367 commit_style = COMMIT_NORMAL;
368 return index_lock.filename;
372 * As-is commit.
374 * (1) return the name of the real index file.
376 * The caller should run hooks on the real index,
377 * and create commit from the_index.
378 * We still need to refresh the index here.
380 if (!only && !pathspec.nr) {
381 hold_locked_index(&index_lock, 1);
382 refresh_cache_or_die(refresh_flags);
383 if (active_cache_changed) {
384 update_main_cache_tree(WRITE_TREE_SILENT);
385 if (write_locked_index(&the_index, &index_lock,
386 COMMIT_LOCK))
387 die(_("unable to write new_index file"));
388 } else {
389 rollback_lock_file(&index_lock);
391 commit_style = COMMIT_AS_IS;
392 return get_index_file();
396 * A partial commit.
398 * (0) find the set of affected paths;
399 * (1) get lock on the real index file;
400 * (2) update the_index with the given paths;
401 * (3) write the_index out to the real index (still locked);
402 * (4) get lock on the false index file;
403 * (5) reset the_index from HEAD;
404 * (6) update the_index the same way as (2);
405 * (7) write the_index out to the false index file;
406 * (8) return the name of the false index file (still locked);
408 * The caller should run hooks on the locked false index, and
409 * create commit from it. Then
410 * (A) if all goes well, commit the real index;
411 * (B) on failure, rollback the real index;
412 * In either case, rollback the false index.
414 commit_style = COMMIT_PARTIAL;
416 if (whence != FROM_COMMIT) {
417 if (whence == FROM_MERGE)
418 die(_("cannot do a partial commit during a merge."));
419 else if (whence == FROM_CHERRY_PICK)
420 die(_("cannot do a partial commit during a cherry-pick."));
423 memset(&partial, 0, sizeof(partial));
424 partial.strdup_strings = 1;
425 if (list_paths(&partial, !current_head ? NULL : "HEAD", prefix, &pathspec))
426 exit(1);
428 discard_cache();
429 if (read_cache() < 0)
430 die(_("cannot read the index"));
432 hold_locked_index(&index_lock, 1);
433 add_remove_files(&partial);
434 refresh_cache(REFRESH_QUIET);
435 if (write_locked_index(&the_index, &index_lock, CLOSE_LOCK))
436 die(_("unable to write new_index file"));
438 hold_lock_file_for_update(&false_lock,
439 git_path("next-index-%"PRIuMAX,
440 (uintmax_t) getpid()),
441 LOCK_DIE_ON_ERROR);
443 create_base_index(current_head);
444 add_remove_files(&partial);
445 refresh_cache(REFRESH_QUIET);
447 if (write_locked_index(&the_index, &false_lock, CLOSE_LOCK))
448 die(_("unable to write temporary index file"));
450 discard_cache();
451 read_cache_from(false_lock.filename);
453 return false_lock.filename;
456 static int run_status(FILE *fp, const char *index_file, const char *prefix, int nowarn,
457 struct wt_status *s)
459 unsigned char sha1[20];
461 if (s->relative_paths)
462 s->prefix = prefix;
464 if (amend) {
465 s->amend = 1;
466 s->reference = "HEAD^1";
468 s->verbose = verbose;
469 s->index_file = index_file;
470 s->fp = fp;
471 s->nowarn = nowarn;
472 s->is_initial = get_sha1(s->reference, sha1) ? 1 : 0;
474 wt_status_collect(s);
476 switch (status_format) {
477 case STATUS_FORMAT_SHORT:
478 wt_shortstatus_print(s);
479 break;
480 case STATUS_FORMAT_PORCELAIN:
481 wt_porcelain_print(s);
482 break;
483 case STATUS_FORMAT_UNSPECIFIED:
484 die("BUG: finalize_deferred_config() should have been called");
485 break;
486 case STATUS_FORMAT_NONE:
487 case STATUS_FORMAT_LONG:
488 wt_status_print(s);
489 break;
492 return s->commitable;
495 static int is_a_merge(const struct commit *current_head)
497 return !!(current_head->parents && current_head->parents->next);
500 static void export_one(const char *var, const char *s, const char *e, int hack)
502 struct strbuf buf = STRBUF_INIT;
503 if (hack)
504 strbuf_addch(&buf, hack);
505 strbuf_addf(&buf, "%.*s", (int)(e - s), s);
506 setenv(var, buf.buf, 1);
507 strbuf_release(&buf);
510 static int sane_ident_split(struct ident_split *person)
512 if (!person->name_begin || !person->name_end ||
513 person->name_begin == person->name_end)
514 return 0; /* no human readable name */
515 if (!person->mail_begin || !person->mail_end ||
516 person->mail_begin == person->mail_end)
517 return 0; /* no usable mail */
518 if (!person->date_begin || !person->date_end ||
519 !person->tz_begin || !person->tz_end)
520 return 0;
521 return 1;
524 static int parse_force_date(const char *in, char *out, int len)
526 if (len < 1)
527 return -1;
528 *out++ = '@';
529 len--;
531 if (parse_date(in, out, len) < 0) {
532 int errors = 0;
533 unsigned long t = approxidate_careful(in, &errors);
534 if (errors)
535 return -1;
536 snprintf(out, len, "%lu", t);
539 return 0;
542 static void determine_author_info(struct strbuf *author_ident)
544 char *name, *email, *date;
545 struct ident_split author;
546 char date_buf[64];
548 name = getenv("GIT_AUTHOR_NAME");
549 email = getenv("GIT_AUTHOR_EMAIL");
550 date = getenv("GIT_AUTHOR_DATE");
552 if (author_message) {
553 const char *a, *lb, *rb, *eol;
554 size_t len;
556 a = strstr(author_message_buffer, "\nauthor ");
557 if (!a)
558 die(_("invalid commit: %s"), author_message);
560 lb = strchrnul(a + strlen("\nauthor "), '<');
561 rb = strchrnul(lb, '>');
562 eol = strchrnul(rb, '\n');
563 if (!*lb || !*rb || !*eol)
564 die(_("invalid commit: %s"), author_message);
566 if (lb == a + strlen("\nauthor "))
567 /* \nauthor <foo@example.com> */
568 name = xcalloc(1, 1);
569 else
570 name = xmemdupz(a + strlen("\nauthor "),
571 (lb - strlen(" ") -
572 (a + strlen("\nauthor "))));
573 email = xmemdupz(lb + strlen("<"), rb - (lb + strlen("<")));
574 len = eol - (rb + strlen("> "));
575 date = xmalloc(len + 2);
576 *date = '@';
577 memcpy(date + 1, rb + strlen("> "), len);
578 date[len + 1] = '\0';
581 if (force_author) {
582 const char *lb = strstr(force_author, " <");
583 const char *rb = strchr(force_author, '>');
585 if (!lb || !rb)
586 die(_("malformed --author parameter"));
587 name = xstrndup(force_author, lb - force_author);
588 email = xstrndup(lb + 2, rb - (lb + 2));
591 if (force_date) {
592 if (parse_force_date(force_date, date_buf, sizeof(date_buf)))
593 die(_("invalid date format: %s"), force_date);
594 date = date_buf;
597 strbuf_addstr(author_ident, fmt_ident(name, email, date, IDENT_STRICT));
598 if (!split_ident_line(&author, author_ident->buf, author_ident->len) &&
599 sane_ident_split(&author)) {
600 export_one("GIT_AUTHOR_NAME", author.name_begin, author.name_end, 0);
601 export_one("GIT_AUTHOR_EMAIL", author.mail_begin, author.mail_end, 0);
602 export_one("GIT_AUTHOR_DATE", author.date_begin, author.tz_end, '@');
606 static void split_ident_or_die(struct ident_split *id, const struct strbuf *buf)
608 if (split_ident_line(id, buf->buf, buf->len) ||
609 !sane_ident_split(id))
610 die(_("Malformed ident string: '%s'"), buf->buf);
613 static int author_date_is_interesting(void)
615 return author_message || force_date;
618 static void adjust_comment_line_char(const struct strbuf *sb)
620 char candidates[] = "#;@!$%^&|:";
621 char *candidate;
622 const char *p;
624 comment_line_char = candidates[0];
625 if (!memchr(sb->buf, comment_line_char, sb->len))
626 return;
628 p = sb->buf;
629 candidate = strchr(candidates, *p);
630 if (candidate)
631 *candidate = ' ';
632 for (p = sb->buf; *p; p++) {
633 if ((p[0] == '\n' || p[0] == '\r') && p[1]) {
634 candidate = strchr(candidates, p[1]);
635 if (candidate)
636 *candidate = ' ';
640 for (p = candidates; *p == ' '; p++)
642 if (!*p)
643 die(_("unable to select a comment character that is not used\n"
644 "in the current commit message"));
645 comment_line_char = *p;
648 static int prepare_to_commit(const char *index_file, const char *prefix,
649 struct commit *current_head,
650 struct wt_status *s,
651 struct strbuf *author_ident)
653 struct stat statbuf;
654 struct strbuf committer_ident = STRBUF_INIT;
655 int commitable;
656 struct strbuf sb = STRBUF_INIT;
657 const char *hook_arg1 = NULL;
658 const char *hook_arg2 = NULL;
659 int clean_message_contents = (cleanup_mode != CLEANUP_NONE);
660 int old_display_comment_prefix;
662 /* This checks and barfs if author is badly specified */
663 determine_author_info(author_ident);
665 if (!no_verify && run_commit_hook(use_editor, index_file, "pre-commit", NULL))
666 return 0;
668 if (squash_message) {
670 * Insert the proper subject line before other commit
671 * message options add their content.
673 if (use_message && !strcmp(use_message, squash_message))
674 strbuf_addstr(&sb, "squash! ");
675 else {
676 struct pretty_print_context ctx = {0};
677 struct commit *c;
678 c = lookup_commit_reference_by_name(squash_message);
679 if (!c)
680 die(_("could not lookup commit %s"), squash_message);
681 ctx.output_encoding = get_commit_output_encoding();
682 format_commit_message(c, "squash! %s\n\n", &sb,
683 &ctx);
687 if (message.len) {
688 strbuf_addbuf(&sb, &message);
689 hook_arg1 = "message";
690 } else if (logfile && !strcmp(logfile, "-")) {
691 if (isatty(0))
692 fprintf(stderr, _("(reading log message from standard input)\n"));
693 if (strbuf_read(&sb, 0, 0) < 0)
694 die_errno(_("could not read log from standard input"));
695 hook_arg1 = "message";
696 } else if (logfile) {
697 if (strbuf_read_file(&sb, logfile, 0) < 0)
698 die_errno(_("could not read log file '%s'"),
699 logfile);
700 hook_arg1 = "message";
701 } else if (use_message) {
702 char *buffer;
703 buffer = strstr(use_message_buffer, "\n\n");
704 if (buffer)
705 strbuf_add(&sb, buffer + 2, strlen(buffer + 2));
706 hook_arg1 = "commit";
707 hook_arg2 = use_message;
708 } else if (fixup_message) {
709 struct pretty_print_context ctx = {0};
710 struct commit *commit;
711 commit = lookup_commit_reference_by_name(fixup_message);
712 if (!commit)
713 die(_("could not lookup commit %s"), fixup_message);
714 ctx.output_encoding = get_commit_output_encoding();
715 format_commit_message(commit, "fixup! %s\n\n",
716 &sb, &ctx);
717 hook_arg1 = "message";
718 } else if (!stat(git_path("MERGE_MSG"), &statbuf)) {
719 if (strbuf_read_file(&sb, git_path("MERGE_MSG"), 0) < 0)
720 die_errno(_("could not read MERGE_MSG"));
721 hook_arg1 = "merge";
722 } else if (!stat(git_path("SQUASH_MSG"), &statbuf)) {
723 if (strbuf_read_file(&sb, git_path("SQUASH_MSG"), 0) < 0)
724 die_errno(_("could not read SQUASH_MSG"));
725 hook_arg1 = "squash";
726 } else if (template_file) {
727 if (strbuf_read_file(&sb, template_file, 0) < 0)
728 die_errno(_("could not read '%s'"), template_file);
729 hook_arg1 = "template";
730 clean_message_contents = 0;
734 * The remaining cases don't modify the template message, but
735 * just set the argument(s) to the prepare-commit-msg hook.
737 else if (whence == FROM_MERGE)
738 hook_arg1 = "merge";
739 else if (whence == FROM_CHERRY_PICK) {
740 hook_arg1 = "commit";
741 hook_arg2 = "CHERRY_PICK_HEAD";
744 if (squash_message) {
746 * If squash_commit was used for the commit subject,
747 * then we're possibly hijacking other commit log options.
748 * Reset the hook args to tell the real story.
750 hook_arg1 = "message";
751 hook_arg2 = "";
754 s->fp = fopen(git_path(commit_editmsg), "w");
755 if (s->fp == NULL)
756 die_errno(_("could not open '%s'"), git_path(commit_editmsg));
758 /* Ignore status.displayCommentPrefix: we do need comments in COMMIT_EDITMSG. */
759 old_display_comment_prefix = s->display_comment_prefix;
760 s->display_comment_prefix = 1;
763 * Most hints are counter-productive when the commit has
764 * already started.
766 s->hints = 0;
768 if (clean_message_contents)
769 stripspace(&sb, 0);
771 if (signoff) {
773 * See if we have a Conflicts: block at the end. If yes, count
774 * its size, so we can ignore it.
776 int ignore_footer = 0;
777 int i, eol, previous = 0;
778 const char *nl;
780 for (i = 0; i < sb.len; i++) {
781 nl = memchr(sb.buf + i, '\n', sb.len - i);
782 if (nl)
783 eol = nl - sb.buf;
784 else
785 eol = sb.len;
786 if (starts_with(sb.buf + previous, "\nConflicts:\n")) {
787 ignore_footer = sb.len - previous;
788 break;
790 while (i < eol)
791 i++;
792 previous = eol;
795 append_signoff(&sb, ignore_footer, 0);
798 if (fwrite(sb.buf, 1, sb.len, s->fp) < sb.len)
799 die_errno(_("could not write commit template"));
801 if (auto_comment_line_char)
802 adjust_comment_line_char(&sb);
803 strbuf_release(&sb);
805 /* This checks if committer ident is explicitly given */
806 strbuf_addstr(&committer_ident, git_committer_info(IDENT_STRICT));
807 if (use_editor && include_status) {
808 int ident_shown = 0;
809 int saved_color_setting;
810 struct ident_split ci, ai;
812 if (whence != FROM_COMMIT) {
813 if (cleanup_mode == CLEANUP_SCISSORS)
814 wt_status_add_cut_line(s->fp);
815 status_printf_ln(s, GIT_COLOR_NORMAL,
816 whence == FROM_MERGE
817 ? _("\n"
818 "It looks like you may be committing a merge.\n"
819 "If this is not correct, please remove the file\n"
820 " %s\n"
821 "and try again.\n")
822 : _("\n"
823 "It looks like you may be committing a cherry-pick.\n"
824 "If this is not correct, please remove the file\n"
825 " %s\n"
826 "and try again.\n"),
827 git_path(whence == FROM_MERGE
828 ? "MERGE_HEAD"
829 : "CHERRY_PICK_HEAD"));
832 fprintf(s->fp, "\n");
833 if (cleanup_mode == CLEANUP_ALL)
834 status_printf(s, GIT_COLOR_NORMAL,
835 _("Please enter the commit message for your changes."
836 " Lines starting\nwith '%c' will be ignored, and an empty"
837 " message aborts the commit.\n"), comment_line_char);
838 else if (cleanup_mode == CLEANUP_SCISSORS && whence == FROM_COMMIT)
839 wt_status_add_cut_line(s->fp);
840 else /* CLEANUP_SPACE, that is. */
841 status_printf(s, GIT_COLOR_NORMAL,
842 _("Please enter the commit message for your changes."
843 " Lines starting\n"
844 "with '%c' will be kept; you may remove them"
845 " yourself if you want to.\n"
846 "An empty message aborts the commit.\n"), comment_line_char);
847 if (only_include_assumed)
848 status_printf_ln(s, GIT_COLOR_NORMAL,
849 "%s", only_include_assumed);
851 split_ident_or_die(&ai, author_ident);
852 split_ident_or_die(&ci, &committer_ident);
854 if (ident_cmp(&ai, &ci))
855 status_printf_ln(s, GIT_COLOR_NORMAL,
856 _("%s"
857 "Author: %.*s <%.*s>"),
858 ident_shown++ ? "" : "\n",
859 (int)(ai.name_end - ai.name_begin), ai.name_begin,
860 (int)(ai.mail_end - ai.mail_begin), ai.mail_begin);
862 if (author_date_is_interesting())
863 status_printf_ln(s, GIT_COLOR_NORMAL,
864 _("%s"
865 "Date: %s"),
866 ident_shown++ ? "" : "\n",
867 show_ident_date(&ai, DATE_NORMAL));
869 if (!committer_ident_sufficiently_given())
870 status_printf_ln(s, GIT_COLOR_NORMAL,
871 _("%s"
872 "Committer: %.*s <%.*s>"),
873 ident_shown++ ? "" : "\n",
874 (int)(ci.name_end - ci.name_begin), ci.name_begin,
875 (int)(ci.mail_end - ci.mail_begin), ci.mail_begin);
877 if (ident_shown)
878 status_printf_ln(s, GIT_COLOR_NORMAL, "%s", "");
880 saved_color_setting = s->use_color;
881 s->use_color = 0;
882 commitable = run_status(s->fp, index_file, prefix, 1, s);
883 s->use_color = saved_color_setting;
884 } else {
885 unsigned char sha1[20];
886 const char *parent = "HEAD";
888 if (!active_nr && read_cache() < 0)
889 die(_("Cannot read index"));
891 if (amend)
892 parent = "HEAD^1";
894 if (get_sha1(parent, sha1))
895 commitable = !!active_nr;
896 else {
898 * Unless the user did explicitly request a submodule
899 * ignore mode by passing a command line option we do
900 * not ignore any changed submodule SHA-1s when
901 * comparing index and parent, no matter what is
902 * configured. Otherwise we won't commit any
903 * submodules which were manually staged, which would
904 * be really confusing.
906 int diff_flags = DIFF_OPT_OVERRIDE_SUBMODULE_CONFIG;
907 if (ignore_submodule_arg &&
908 !strcmp(ignore_submodule_arg, "all"))
909 diff_flags |= DIFF_OPT_IGNORE_SUBMODULES;
910 commitable = index_differs_from(parent, diff_flags);
913 strbuf_release(&committer_ident);
915 fclose(s->fp);
918 * Reject an attempt to record a non-merge empty commit without
919 * explicit --allow-empty. In the cherry-pick case, it may be
920 * empty due to conflict resolution, which the user should okay.
922 if (!commitable && whence != FROM_MERGE && !allow_empty &&
923 !(amend && is_a_merge(current_head))) {
924 s->display_comment_prefix = old_display_comment_prefix;
925 run_status(stdout, index_file, prefix, 0, s);
926 if (amend)
927 fputs(_(empty_amend_advice), stderr);
928 else if (whence == FROM_CHERRY_PICK) {
929 fputs(_(empty_cherry_pick_advice), stderr);
930 if (!sequencer_in_use)
931 fputs(_(empty_cherry_pick_advice_single), stderr);
932 else
933 fputs(_(empty_cherry_pick_advice_multi), stderr);
935 return 0;
939 * Re-read the index as pre-commit hook could have updated it,
940 * and write it out as a tree. We must do this before we invoke
941 * the editor and after we invoke run_status above.
943 discard_cache();
944 read_cache_from(index_file);
945 if (update_main_cache_tree(0)) {
946 error(_("Error building trees"));
947 return 0;
950 if (run_commit_hook(use_editor, index_file, "prepare-commit-msg",
951 git_path(commit_editmsg), hook_arg1, hook_arg2, NULL))
952 return 0;
954 if (use_editor) {
955 char index[PATH_MAX];
956 const char *env[2] = { NULL };
957 env[0] = index;
958 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
959 if (launch_editor(git_path(commit_editmsg), NULL, env)) {
960 fprintf(stderr,
961 _("Please supply the message using either -m or -F option.\n"));
962 exit(1);
966 if (!no_verify &&
967 run_commit_hook(use_editor, index_file, "commit-msg", git_path(commit_editmsg), NULL)) {
968 return 0;
971 return 1;
974 static int rest_is_empty(struct strbuf *sb, int start)
976 int i, eol;
977 const char *nl;
979 /* Check if the rest is just whitespace and Signed-of-by's. */
980 for (i = start; i < sb->len; i++) {
981 nl = memchr(sb->buf + i, '\n', sb->len - i);
982 if (nl)
983 eol = nl - sb->buf;
984 else
985 eol = sb->len;
987 if (strlen(sign_off_header) <= eol - i &&
988 starts_with(sb->buf + i, sign_off_header)) {
989 i = eol;
990 continue;
992 while (i < eol)
993 if (!isspace(sb->buf[i++]))
994 return 0;
997 return 1;
1001 * Find out if the message in the strbuf contains only whitespace and
1002 * Signed-off-by lines.
1004 static int message_is_empty(struct strbuf *sb)
1006 if (cleanup_mode == CLEANUP_NONE && sb->len)
1007 return 0;
1008 return rest_is_empty(sb, 0);
1012 * See if the user edited the message in the editor or left what
1013 * was in the template intact
1015 static int template_untouched(struct strbuf *sb)
1017 struct strbuf tmpl = STRBUF_INIT;
1018 const char *start;
1020 if (cleanup_mode == CLEANUP_NONE && sb->len)
1021 return 0;
1023 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
1024 return 0;
1026 stripspace(&tmpl, cleanup_mode == CLEANUP_ALL);
1027 if (!skip_prefix(sb->buf, tmpl.buf, &start))
1028 start = sb->buf;
1029 strbuf_release(&tmpl);
1030 return rest_is_empty(sb, start - sb->buf);
1033 static const char *find_author_by_nickname(const char *name)
1035 struct rev_info revs;
1036 struct commit *commit;
1037 struct strbuf buf = STRBUF_INIT;
1038 struct string_list mailmap = STRING_LIST_INIT_NODUP;
1039 const char *av[20];
1040 int ac = 0;
1042 init_revisions(&revs, NULL);
1043 strbuf_addf(&buf, "--author=%s", name);
1044 av[++ac] = "--all";
1045 av[++ac] = "-i";
1046 av[++ac] = buf.buf;
1047 av[++ac] = NULL;
1048 setup_revisions(ac, av, &revs, NULL);
1049 revs.mailmap = &mailmap;
1050 read_mailmap(revs.mailmap, NULL);
1052 prepare_revision_walk(&revs);
1053 commit = get_revision(&revs);
1054 if (commit) {
1055 struct pretty_print_context ctx = {0};
1056 ctx.date_mode = DATE_NORMAL;
1057 strbuf_release(&buf);
1058 format_commit_message(commit, "%aN <%aE>", &buf, &ctx);
1059 clear_mailmap(&mailmap);
1060 return strbuf_detach(&buf, NULL);
1062 die(_("No existing author found with '%s'"), name);
1066 static void handle_untracked_files_arg(struct wt_status *s)
1068 if (!untracked_files_arg)
1069 ; /* default already initialized */
1070 else if (!strcmp(untracked_files_arg, "no"))
1071 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
1072 else if (!strcmp(untracked_files_arg, "normal"))
1073 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
1074 else if (!strcmp(untracked_files_arg, "all"))
1075 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
1076 else
1077 die(_("Invalid untracked files mode '%s'"), untracked_files_arg);
1080 static const char *read_commit_message(const char *name)
1082 const char *out_enc;
1083 struct commit *commit;
1085 commit = lookup_commit_reference_by_name(name);
1086 if (!commit)
1087 die(_("could not lookup commit %s"), name);
1088 out_enc = get_commit_output_encoding();
1089 return logmsg_reencode(commit, NULL, out_enc);
1093 * Enumerate what needs to be propagated when --porcelain
1094 * is not in effect here.
1096 static struct status_deferred_config {
1097 enum status_format status_format;
1098 int show_branch;
1099 } status_deferred_config = {
1100 STATUS_FORMAT_UNSPECIFIED,
1101 -1 /* unspecified */
1104 static void finalize_deferred_config(struct wt_status *s)
1106 int use_deferred_config = (status_format != STATUS_FORMAT_PORCELAIN &&
1107 !s->null_termination);
1109 if (s->null_termination) {
1110 if (status_format == STATUS_FORMAT_NONE ||
1111 status_format == STATUS_FORMAT_UNSPECIFIED)
1112 status_format = STATUS_FORMAT_PORCELAIN;
1113 else if (status_format == STATUS_FORMAT_LONG)
1114 die(_("--long and -z are incompatible"));
1117 if (use_deferred_config && status_format == STATUS_FORMAT_UNSPECIFIED)
1118 status_format = status_deferred_config.status_format;
1119 if (status_format == STATUS_FORMAT_UNSPECIFIED)
1120 status_format = STATUS_FORMAT_NONE;
1122 if (use_deferred_config && s->show_branch < 0)
1123 s->show_branch = status_deferred_config.show_branch;
1124 if (s->show_branch < 0)
1125 s->show_branch = 0;
1128 static int parse_and_validate_options(int argc, const char *argv[],
1129 const struct option *options,
1130 const char * const usage[],
1131 const char *prefix,
1132 struct commit *current_head,
1133 struct wt_status *s)
1135 int f = 0;
1137 argc = parse_options(argc, argv, prefix, options, usage, 0);
1138 finalize_deferred_config(s);
1140 if (force_author && !strchr(force_author, '>'))
1141 force_author = find_author_by_nickname(force_author);
1143 if (force_author && renew_authorship)
1144 die(_("Using both --reset-author and --author does not make sense"));
1146 if (logfile || have_option_m || use_message || fixup_message)
1147 use_editor = 0;
1148 if (0 <= edit_flag)
1149 use_editor = edit_flag;
1151 /* Sanity check options */
1152 if (amend && !current_head)
1153 die(_("You have nothing to amend."));
1154 if (amend && whence != FROM_COMMIT) {
1155 if (whence == FROM_MERGE)
1156 die(_("You are in the middle of a merge -- cannot amend."));
1157 else if (whence == FROM_CHERRY_PICK)
1158 die(_("You are in the middle of a cherry-pick -- cannot amend."));
1160 if (fixup_message && squash_message)
1161 die(_("Options --squash and --fixup cannot be used together"));
1162 if (use_message)
1163 f++;
1164 if (edit_message)
1165 f++;
1166 if (fixup_message)
1167 f++;
1168 if (logfile)
1169 f++;
1170 if (f > 1)
1171 die(_("Only one of -c/-C/-F/--fixup can be used."));
1172 if (message.len && f > 0)
1173 die((_("Option -m cannot be combined with -c/-C/-F/--fixup.")));
1174 if (f || message.len)
1175 template_file = NULL;
1176 if (edit_message)
1177 use_message = edit_message;
1178 if (amend && !use_message && !fixup_message)
1179 use_message = "HEAD";
1180 if (!use_message && whence != FROM_CHERRY_PICK && renew_authorship)
1181 die(_("--reset-author can be used only with -C, -c or --amend."));
1182 if (use_message) {
1183 use_message_buffer = read_commit_message(use_message);
1184 if (!renew_authorship) {
1185 author_message = use_message;
1186 author_message_buffer = use_message_buffer;
1189 if (whence == FROM_CHERRY_PICK && !renew_authorship) {
1190 author_message = "CHERRY_PICK_HEAD";
1191 author_message_buffer = read_commit_message(author_message);
1194 if (patch_interactive)
1195 interactive = 1;
1197 if (also + only + all + interactive > 1)
1198 die(_("Only one of --include/--only/--all/--interactive/--patch can be used."));
1199 if (argc == 0 && (also || (only && !amend)))
1200 die(_("No paths with --include/--only does not make sense."));
1201 if (argc == 0 && only && amend)
1202 only_include_assumed = _("Clever... amending the last one with dirty index.");
1203 if (argc > 0 && !also && !only)
1204 only_include_assumed = _("Explicit paths specified without -i or -o; assuming --only paths...");
1205 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
1206 cleanup_mode = use_editor ? CLEANUP_ALL : CLEANUP_SPACE;
1207 else if (!strcmp(cleanup_arg, "verbatim"))
1208 cleanup_mode = CLEANUP_NONE;
1209 else if (!strcmp(cleanup_arg, "whitespace"))
1210 cleanup_mode = CLEANUP_SPACE;
1211 else if (!strcmp(cleanup_arg, "strip"))
1212 cleanup_mode = CLEANUP_ALL;
1213 else if (!strcmp(cleanup_arg, "scissors"))
1214 cleanup_mode = use_editor ? CLEANUP_SCISSORS : CLEANUP_SPACE;
1215 else
1216 die(_("Invalid cleanup mode %s"), cleanup_arg);
1218 handle_untracked_files_arg(s);
1220 if (all && argc > 0)
1221 die(_("Paths with -a does not make sense."));
1223 if (status_format != STATUS_FORMAT_NONE)
1224 dry_run = 1;
1226 return argc;
1229 static int dry_run_commit(int argc, const char **argv, const char *prefix,
1230 const struct commit *current_head, struct wt_status *s)
1232 int commitable;
1233 const char *index_file;
1235 index_file = prepare_index(argc, argv, prefix, current_head, 1);
1236 commitable = run_status(stdout, index_file, prefix, 0, s);
1237 rollback_index_files();
1239 return commitable ? 0 : 1;
1242 static int parse_status_slot(const char *var, int offset)
1244 if (!strcasecmp(var+offset, "header"))
1245 return WT_STATUS_HEADER;
1246 if (!strcasecmp(var+offset, "branch"))
1247 return WT_STATUS_ONBRANCH;
1248 if (!strcasecmp(var+offset, "updated")
1249 || !strcasecmp(var+offset, "added"))
1250 return WT_STATUS_UPDATED;
1251 if (!strcasecmp(var+offset, "changed"))
1252 return WT_STATUS_CHANGED;
1253 if (!strcasecmp(var+offset, "untracked"))
1254 return WT_STATUS_UNTRACKED;
1255 if (!strcasecmp(var+offset, "nobranch"))
1256 return WT_STATUS_NOBRANCH;
1257 if (!strcasecmp(var+offset, "unmerged"))
1258 return WT_STATUS_UNMERGED;
1259 return -1;
1262 static int git_status_config(const char *k, const char *v, void *cb)
1264 struct wt_status *s = cb;
1266 if (starts_with(k, "column."))
1267 return git_column_config(k, v, "status", &s->colopts);
1268 if (!strcmp(k, "status.submodulesummary")) {
1269 int is_bool;
1270 s->submodule_summary = git_config_bool_or_int(k, v, &is_bool);
1271 if (is_bool && s->submodule_summary)
1272 s->submodule_summary = -1;
1273 return 0;
1275 if (!strcmp(k, "status.short")) {
1276 if (git_config_bool(k, v))
1277 status_deferred_config.status_format = STATUS_FORMAT_SHORT;
1278 else
1279 status_deferred_config.status_format = STATUS_FORMAT_NONE;
1280 return 0;
1282 if (!strcmp(k, "status.branch")) {
1283 status_deferred_config.show_branch = git_config_bool(k, v);
1284 return 0;
1286 if (!strcmp(k, "status.color") || !strcmp(k, "color.status")) {
1287 s->use_color = git_config_colorbool(k, v);
1288 return 0;
1290 if (!strcmp(k, "status.displaycommentprefix")) {
1291 s->display_comment_prefix = git_config_bool(k, v);
1292 return 0;
1294 if (starts_with(k, "status.color.") || starts_with(k, "color.status.")) {
1295 int slot = parse_status_slot(k, 13);
1296 if (slot < 0)
1297 return 0;
1298 if (!v)
1299 return config_error_nonbool(k);
1300 color_parse(v, k, s->color_palette[slot]);
1301 return 0;
1303 if (!strcmp(k, "status.relativepaths")) {
1304 s->relative_paths = git_config_bool(k, v);
1305 return 0;
1307 if (!strcmp(k, "status.showuntrackedfiles")) {
1308 if (!v)
1309 return config_error_nonbool(k);
1310 else if (!strcmp(v, "no"))
1311 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
1312 else if (!strcmp(v, "normal"))
1313 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
1314 else if (!strcmp(v, "all"))
1315 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
1316 else
1317 return error(_("Invalid untracked files mode '%s'"), v);
1318 return 0;
1320 return git_diff_ui_config(k, v, NULL);
1323 int cmd_status(int argc, const char **argv, const char *prefix)
1325 static struct wt_status s;
1326 int fd;
1327 unsigned char sha1[20];
1328 static struct option builtin_status_options[] = {
1329 OPT__VERBOSE(&verbose, N_("be verbose")),
1330 OPT_SET_INT('s', "short", &status_format,
1331 N_("show status concisely"), STATUS_FORMAT_SHORT),
1332 OPT_BOOL('b', "branch", &s.show_branch,
1333 N_("show branch information")),
1334 OPT_SET_INT(0, "porcelain", &status_format,
1335 N_("machine-readable output"),
1336 STATUS_FORMAT_PORCELAIN),
1337 OPT_SET_INT(0, "long", &status_format,
1338 N_("show status in long format (default)"),
1339 STATUS_FORMAT_LONG),
1340 OPT_BOOL('z', "null", &s.null_termination,
1341 N_("terminate entries with NUL")),
1342 { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg,
1343 N_("mode"),
1344 N_("show untracked files, optional modes: all, normal, no. (Default: all)"),
1345 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1346 OPT_BOOL(0, "ignored", &show_ignored_in_status,
1347 N_("show ignored files")),
1348 { OPTION_STRING, 0, "ignore-submodules", &ignore_submodule_arg, N_("when"),
1349 N_("ignore changes to submodules, optional when: all, dirty, untracked. (Default: all)"),
1350 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1351 OPT_COLUMN(0, "column", &s.colopts, N_("list untracked files in columns")),
1352 OPT_END(),
1355 if (argc == 2 && !strcmp(argv[1], "-h"))
1356 usage_with_options(builtin_status_usage, builtin_status_options);
1358 status_init_config(&s, git_status_config);
1359 argc = parse_options(argc, argv, prefix,
1360 builtin_status_options,
1361 builtin_status_usage, 0);
1362 finalize_colopts(&s.colopts, -1);
1363 finalize_deferred_config(&s);
1365 handle_untracked_files_arg(&s);
1366 if (show_ignored_in_status)
1367 s.show_ignored_files = 1;
1368 parse_pathspec(&s.pathspec, 0,
1369 PATHSPEC_PREFER_FULL,
1370 prefix, argv);
1372 read_cache_preload(&s.pathspec);
1373 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, &s.pathspec, NULL, NULL);
1375 fd = hold_locked_index(&index_lock, 0);
1376 if (0 <= fd)
1377 update_index_if_able(&the_index, &index_lock);
1379 s.is_initial = get_sha1(s.reference, sha1) ? 1 : 0;
1380 s.ignore_submodule_arg = ignore_submodule_arg;
1381 wt_status_collect(&s);
1383 if (s.relative_paths)
1384 s.prefix = prefix;
1386 switch (status_format) {
1387 case STATUS_FORMAT_SHORT:
1388 wt_shortstatus_print(&s);
1389 break;
1390 case STATUS_FORMAT_PORCELAIN:
1391 wt_porcelain_print(&s);
1392 break;
1393 case STATUS_FORMAT_UNSPECIFIED:
1394 die("BUG: finalize_deferred_config() should have been called");
1395 break;
1396 case STATUS_FORMAT_NONE:
1397 case STATUS_FORMAT_LONG:
1398 s.verbose = verbose;
1399 s.ignore_submodule_arg = ignore_submodule_arg;
1400 wt_status_print(&s);
1401 break;
1403 return 0;
1406 static void print_summary(const char *prefix, const unsigned char *sha1,
1407 int initial_commit)
1409 struct rev_info rev;
1410 struct commit *commit;
1411 struct strbuf format = STRBUF_INIT;
1412 unsigned char junk_sha1[20];
1413 const char *head;
1414 struct pretty_print_context pctx = {0};
1415 struct strbuf author_ident = STRBUF_INIT;
1416 struct strbuf committer_ident = STRBUF_INIT;
1418 commit = lookup_commit(sha1);
1419 if (!commit)
1420 die(_("couldn't look up newly created commit"));
1421 if (parse_commit(commit))
1422 die(_("could not parse newly created commit"));
1424 strbuf_addstr(&format, "format:%h] %s");
1426 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1427 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1428 if (strbuf_cmp(&author_ident, &committer_ident)) {
1429 strbuf_addstr(&format, "\n Author: ");
1430 strbuf_addbuf_percentquote(&format, &author_ident);
1432 if (author_date_is_interesting()) {
1433 struct strbuf date = STRBUF_INIT;
1434 format_commit_message(commit, "%ad", &date, &pctx);
1435 strbuf_addstr(&format, "\n Date: ");
1436 strbuf_addbuf_percentquote(&format, &date);
1437 strbuf_release(&date);
1439 if (!committer_ident_sufficiently_given()) {
1440 strbuf_addstr(&format, "\n Committer: ");
1441 strbuf_addbuf_percentquote(&format, &committer_ident);
1442 if (advice_implicit_identity) {
1443 strbuf_addch(&format, '\n');
1444 strbuf_addstr(&format, _(implicit_ident_advice));
1447 strbuf_release(&author_ident);
1448 strbuf_release(&committer_ident);
1450 init_revisions(&rev, prefix);
1451 setup_revisions(0, NULL, &rev, NULL);
1453 rev.diff = 1;
1454 rev.diffopt.output_format =
1455 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1457 rev.verbose_header = 1;
1458 rev.show_root_diff = 1;
1459 get_commit_format(format.buf, &rev);
1460 rev.always_show_header = 0;
1461 rev.diffopt.detect_rename = 1;
1462 rev.diffopt.break_opt = 0;
1463 diff_setup_done(&rev.diffopt);
1465 head = resolve_ref_unsafe("HEAD", junk_sha1, 0, NULL);
1466 printf("[%s%s ",
1467 starts_with(head, "refs/heads/") ?
1468 head + 11 :
1469 !strcmp(head, "HEAD") ?
1470 _("detached HEAD") :
1471 head,
1472 initial_commit ? _(" (root-commit)") : "");
1474 if (!log_tree_commit(&rev, commit)) {
1475 rev.always_show_header = 1;
1476 rev.use_terminator = 1;
1477 log_tree_commit(&rev, commit);
1480 strbuf_release(&format);
1483 static int git_commit_config(const char *k, const char *v, void *cb)
1485 struct wt_status *s = cb;
1486 int status;
1488 if (!strcmp(k, "commit.template"))
1489 return git_config_pathname(&template_file, k, v);
1490 if (!strcmp(k, "commit.status")) {
1491 include_status = git_config_bool(k, v);
1492 return 0;
1494 if (!strcmp(k, "commit.cleanup"))
1495 return git_config_string(&cleanup_arg, k, v);
1496 if (!strcmp(k, "commit.gpgsign")) {
1497 sign_commit = git_config_bool(k, v) ? "" : NULL;
1498 return 0;
1501 status = git_gpg_config(k, v, NULL);
1502 if (status)
1503 return status;
1504 return git_status_config(k, v, s);
1507 static int run_rewrite_hook(const unsigned char *oldsha1,
1508 const unsigned char *newsha1)
1510 /* oldsha1 SP newsha1 LF NUL */
1511 static char buf[2*40 + 3];
1512 struct child_process proc;
1513 const char *argv[3];
1514 int code;
1515 size_t n;
1517 argv[0] = find_hook("post-rewrite");
1518 if (!argv[0])
1519 return 0;
1521 argv[1] = "amend";
1522 argv[2] = NULL;
1524 memset(&proc, 0, sizeof(proc));
1525 proc.argv = argv;
1526 proc.in = -1;
1527 proc.stdout_to_stderr = 1;
1529 code = start_command(&proc);
1530 if (code)
1531 return code;
1532 n = snprintf(buf, sizeof(buf), "%s %s\n",
1533 sha1_to_hex(oldsha1), sha1_to_hex(newsha1));
1534 write_in_full(proc.in, buf, n);
1535 close(proc.in);
1536 return finish_command(&proc);
1539 int run_commit_hook(int editor_is_used, const char *index_file, const char *name, ...)
1541 const char *hook_env[3] = { NULL };
1542 char index[PATH_MAX];
1543 va_list args;
1544 int ret;
1546 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
1547 hook_env[0] = index;
1550 * Let the hook know that no editor will be launched.
1552 if (!editor_is_used)
1553 hook_env[1] = "GIT_EDITOR=:";
1555 va_start(args, name);
1556 ret = run_hook_ve(hook_env, name, args);
1557 va_end(args);
1559 return ret;
1562 int cmd_commit(int argc, const char **argv, const char *prefix)
1564 static struct wt_status s;
1565 static struct option builtin_commit_options[] = {
1566 OPT__QUIET(&quiet, N_("suppress summary after successful commit")),
1567 OPT__VERBOSE(&verbose, N_("show diff in commit message template")),
1569 OPT_GROUP(N_("Commit message options")),
1570 OPT_FILENAME('F', "file", &logfile, N_("read message from file")),
1571 OPT_STRING(0, "author", &force_author, N_("author"), N_("override author for commit")),
1572 OPT_STRING(0, "date", &force_date, N_("date"), N_("override date for commit")),
1573 OPT_CALLBACK('m', "message", &message, N_("message"), N_("commit message"), opt_parse_m),
1574 OPT_STRING('c', "reedit-message", &edit_message, N_("commit"), N_("reuse and edit message from specified commit")),
1575 OPT_STRING('C', "reuse-message", &use_message, N_("commit"), N_("reuse message from specified commit")),
1576 OPT_STRING(0, "fixup", &fixup_message, N_("commit"), N_("use autosquash formatted message to fixup specified commit")),
1577 OPT_STRING(0, "squash", &squash_message, N_("commit"), N_("use autosquash formatted message to squash specified commit")),
1578 OPT_BOOL(0, "reset-author", &renew_authorship, N_("the commit is authored by me now (used with -C/-c/--amend)")),
1579 OPT_BOOL('s', "signoff", &signoff, N_("add Signed-off-by:")),
1580 OPT_FILENAME('t', "template", &template_file, N_("use specified template file")),
1581 OPT_BOOL('e', "edit", &edit_flag, N_("force edit of commit")),
1582 OPT_STRING(0, "cleanup", &cleanup_arg, N_("default"), N_("how to strip spaces and #comments from message")),
1583 OPT_BOOL(0, "status", &include_status, N_("include status in commit message template")),
1584 { OPTION_STRING, 'S', "gpg-sign", &sign_commit, N_("key-id"),
1585 N_("GPG sign commit"), PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
1586 /* end commit message options */
1588 OPT_GROUP(N_("Commit contents options")),
1589 OPT_BOOL('a', "all", &all, N_("commit all changed files")),
1590 OPT_BOOL('i', "include", &also, N_("add specified files to index for commit")),
1591 OPT_BOOL(0, "interactive", &interactive, N_("interactively add files")),
1592 OPT_BOOL('p', "patch", &patch_interactive, N_("interactively add changes")),
1593 OPT_BOOL('o', "only", &only, N_("commit only specified files")),
1594 OPT_BOOL('n', "no-verify", &no_verify, N_("bypass pre-commit hook")),
1595 OPT_BOOL(0, "dry-run", &dry_run, N_("show what would be committed")),
1596 OPT_SET_INT(0, "short", &status_format, N_("show status concisely"),
1597 STATUS_FORMAT_SHORT),
1598 OPT_BOOL(0, "branch", &s.show_branch, N_("show branch information")),
1599 OPT_SET_INT(0, "porcelain", &status_format,
1600 N_("machine-readable output"), STATUS_FORMAT_PORCELAIN),
1601 OPT_SET_INT(0, "long", &status_format,
1602 N_("show status in long format (default)"),
1603 STATUS_FORMAT_LONG),
1604 OPT_BOOL('z', "null", &s.null_termination,
1605 N_("terminate entries with NUL")),
1606 OPT_BOOL(0, "amend", &amend, N_("amend previous commit")),
1607 OPT_BOOL(0, "no-post-rewrite", &no_post_rewrite, N_("bypass post-rewrite hook")),
1608 { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg, N_("mode"), N_("show untracked files, optional modes: all, normal, no. (Default: all)"), PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1609 /* end commit contents options */
1611 OPT_HIDDEN_BOOL(0, "allow-empty", &allow_empty,
1612 N_("ok to record an empty change")),
1613 OPT_HIDDEN_BOOL(0, "allow-empty-message", &allow_empty_message,
1614 N_("ok to record a change with an empty message")),
1616 OPT_END()
1619 struct strbuf sb = STRBUF_INIT;
1620 struct strbuf author_ident = STRBUF_INIT;
1621 const char *index_file, *reflog_msg;
1622 char *nl;
1623 unsigned char sha1[20];
1624 struct ref_lock *ref_lock;
1625 struct commit_list *parents = NULL, **pptr = &parents;
1626 struct stat statbuf;
1627 struct commit *current_head = NULL;
1628 struct commit_extra_header *extra = NULL;
1630 if (argc == 2 && !strcmp(argv[1], "-h"))
1631 usage_with_options(builtin_commit_usage, builtin_commit_options);
1633 status_init_config(&s, git_commit_config);
1634 status_format = STATUS_FORMAT_NONE; /* Ignore status.short */
1635 s.colopts = 0;
1637 if (get_sha1("HEAD", sha1))
1638 current_head = NULL;
1639 else {
1640 current_head = lookup_commit_or_die(sha1, "HEAD");
1641 if (parse_commit(current_head))
1642 die(_("could not parse HEAD commit"));
1644 argc = parse_and_validate_options(argc, argv, builtin_commit_options,
1645 builtin_commit_usage,
1646 prefix, current_head, &s);
1647 if (dry_run)
1648 return dry_run_commit(argc, argv, prefix, current_head, &s);
1649 index_file = prepare_index(argc, argv, prefix, current_head, 0);
1651 /* Set up everything for writing the commit object. This includes
1652 running hooks, writing the trees, and interacting with the user. */
1653 if (!prepare_to_commit(index_file, prefix,
1654 current_head, &s, &author_ident)) {
1655 rollback_index_files();
1656 return 1;
1659 /* Determine parents */
1660 reflog_msg = getenv("GIT_REFLOG_ACTION");
1661 if (!current_head) {
1662 if (!reflog_msg)
1663 reflog_msg = "commit (initial)";
1664 } else if (amend) {
1665 struct commit_list *c;
1667 if (!reflog_msg)
1668 reflog_msg = "commit (amend)";
1669 for (c = current_head->parents; c; c = c->next)
1670 pptr = &commit_list_insert(c->item, pptr)->next;
1671 } else if (whence == FROM_MERGE) {
1672 struct strbuf m = STRBUF_INIT;
1673 FILE *fp;
1674 int allow_fast_forward = 1;
1676 if (!reflog_msg)
1677 reflog_msg = "commit (merge)";
1678 pptr = &commit_list_insert(current_head, pptr)->next;
1679 fp = fopen(git_path("MERGE_HEAD"), "r");
1680 if (fp == NULL)
1681 die_errno(_("could not open '%s' for reading"),
1682 git_path("MERGE_HEAD"));
1683 while (strbuf_getline(&m, fp, '\n') != EOF) {
1684 struct commit *parent;
1686 parent = get_merge_parent(m.buf);
1687 if (!parent)
1688 die(_("Corrupt MERGE_HEAD file (%s)"), m.buf);
1689 pptr = &commit_list_insert(parent, pptr)->next;
1691 fclose(fp);
1692 strbuf_release(&m);
1693 if (!stat(git_path("MERGE_MODE"), &statbuf)) {
1694 if (strbuf_read_file(&sb, git_path("MERGE_MODE"), 0) < 0)
1695 die_errno(_("could not read MERGE_MODE"));
1696 if (!strcmp(sb.buf, "no-ff"))
1697 allow_fast_forward = 0;
1699 if (allow_fast_forward)
1700 parents = reduce_heads(parents);
1701 } else {
1702 if (!reflog_msg)
1703 reflog_msg = (whence == FROM_CHERRY_PICK)
1704 ? "commit (cherry-pick)"
1705 : "commit";
1706 pptr = &commit_list_insert(current_head, pptr)->next;
1709 /* Finally, get the commit message */
1710 strbuf_reset(&sb);
1711 if (strbuf_read_file(&sb, git_path(commit_editmsg), 0) < 0) {
1712 int saved_errno = errno;
1713 rollback_index_files();
1714 die(_("could not read commit message: %s"), strerror(saved_errno));
1717 if (verbose || /* Truncate the message just before the diff, if any. */
1718 cleanup_mode == CLEANUP_SCISSORS)
1719 wt_status_truncate_message_at_cut_line(&sb);
1721 if (cleanup_mode != CLEANUP_NONE)
1722 stripspace(&sb, cleanup_mode == CLEANUP_ALL);
1723 if (template_untouched(&sb) && !allow_empty_message) {
1724 rollback_index_files();
1725 fprintf(stderr, _("Aborting commit; you did not edit the message.\n"));
1726 exit(1);
1728 if (message_is_empty(&sb) && !allow_empty_message) {
1729 rollback_index_files();
1730 fprintf(stderr, _("Aborting commit due to empty commit message.\n"));
1731 exit(1);
1734 if (amend) {
1735 const char *exclude_gpgsig[2] = { "gpgsig", NULL };
1736 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1737 } else {
1738 struct commit_extra_header **tail = &extra;
1739 append_merge_tag_headers(parents, &tail);
1742 if (commit_tree_extended(sb.buf, sb.len, active_cache_tree->sha1,
1743 parents, sha1, author_ident.buf, sign_commit, extra)) {
1744 rollback_index_files();
1745 die(_("failed to write commit object"));
1747 strbuf_release(&author_ident);
1748 free_commit_extra_headers(extra);
1750 ref_lock = lock_any_ref_for_update("HEAD",
1751 !current_head
1752 ? NULL
1753 : current_head->object.sha1,
1754 0, NULL);
1755 if (!ref_lock) {
1756 rollback_index_files();
1757 die(_("cannot lock HEAD ref"));
1760 nl = strchr(sb.buf, '\n');
1761 if (nl)
1762 strbuf_setlen(&sb, nl + 1 - sb.buf);
1763 else
1764 strbuf_addch(&sb, '\n');
1765 strbuf_insert(&sb, 0, reflog_msg, strlen(reflog_msg));
1766 strbuf_insert(&sb, strlen(reflog_msg), ": ", 2);
1768 if (write_ref_sha1(ref_lock, sha1, sb.buf) < 0) {
1769 rollback_index_files();
1770 die(_("cannot update HEAD ref"));
1773 unlink(git_path("CHERRY_PICK_HEAD"));
1774 unlink(git_path("REVERT_HEAD"));
1775 unlink(git_path("MERGE_HEAD"));
1776 unlink(git_path("MERGE_MSG"));
1777 unlink(git_path("MERGE_MODE"));
1778 unlink(git_path("SQUASH_MSG"));
1780 if (commit_index_files())
1781 die (_("Repository has been updated, but unable to write\n"
1782 "new_index file. Check that disk is not full or quota is\n"
1783 "not exceeded, and then \"git reset HEAD\" to recover."));
1785 rerere(0);
1786 run_commit_hook(use_editor, get_index_file(), "post-commit", NULL);
1787 if (amend && !no_post_rewrite) {
1788 struct notes_rewrite_cfg *cfg;
1789 cfg = init_copy_notes_for_rewrite("amend");
1790 if (cfg) {
1791 /* we are amending, so current_head is not NULL */
1792 copy_note_for_rewrite(cfg, current_head->object.sha1, sha1);
1793 finish_copy_notes_for_rewrite(cfg, "Notes added by 'git commit --amend'");
1795 run_rewrite_hook(current_head->object.sha1, sha1);
1797 if (!quiet)
1798 print_summary(prefix, sha1, !current_head);
1800 return 0;