Merge branch 'jg/status-config'
[git.git] / builtin / commit.c
blobb589ce02ff1d22d349799a8296a93d6bd21e003e
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"
33 static const char * const builtin_commit_usage[] = {
34 N_("git commit [options] [--] <pathspec>..."),
35 NULL
38 static const char * const builtin_status_usage[] = {
39 N_("git status [options] [--] <pathspec>..."),
40 NULL
43 static const char implicit_ident_advice[] =
44 N_("Your name and email address were configured automatically based\n"
45 "on your username and hostname. Please check that they are accurate.\n"
46 "You can suppress this message by setting them explicitly:\n"
47 "\n"
48 " git config --global user.name \"Your Name\"\n"
49 " git config --global user.email you@example.com\n"
50 "\n"
51 "After doing this, you may fix the identity used for this commit with:\n"
52 "\n"
53 " git commit --amend --reset-author\n");
55 static const char empty_amend_advice[] =
56 N_("You asked to amend the most recent commit, but doing so would make\n"
57 "it empty. You can repeat your command with --allow-empty, or you can\n"
58 "remove the commit entirely with \"git reset HEAD^\".\n");
60 static const char empty_cherry_pick_advice[] =
61 N_("The previous cherry-pick is now empty, possibly due to conflict resolution.\n"
62 "If you wish to commit it anyway, use:\n"
63 "\n"
64 " git commit --allow-empty\n"
65 "\n"
66 "Otherwise, please use 'git reset'\n");
68 static const char *use_message_buffer;
69 static const char commit_editmsg[] = "COMMIT_EDITMSG";
70 static struct lock_file index_lock; /* real index */
71 static struct lock_file false_lock; /* used only for partial commits */
72 static enum {
73 COMMIT_AS_IS = 1,
74 COMMIT_NORMAL,
75 COMMIT_PARTIAL
76 } commit_style;
78 static const char *logfile, *force_author;
79 static const char *template_file;
81 * The _message variables are commit names from which to take
82 * the commit message and/or authorship.
84 static const char *author_message, *author_message_buffer;
85 static char *edit_message, *use_message;
86 static char *fixup_message, *squash_message;
87 static int all, also, interactive, patch_interactive, only, amend, signoff;
88 static int edit_flag = -1; /* unspecified */
89 static int quiet, verbose, no_verify, allow_empty, dry_run, renew_authorship;
90 static int no_post_rewrite, allow_empty_message;
91 static char *untracked_files_arg, *force_date, *ignore_submodule_arg;
92 static char *sign_commit;
95 * The default commit message cleanup mode will remove the lines
96 * beginning with # (shell comments) and leading and trailing
97 * whitespaces (empty lines or containing only whitespaces)
98 * if editor is used, and only the whitespaces if the message
99 * is specified explicitly.
101 static enum {
102 CLEANUP_SPACE,
103 CLEANUP_NONE,
104 CLEANUP_ALL
105 } cleanup_mode;
106 static const char *cleanup_arg;
108 static enum commit_whence whence;
109 static int use_editor = 1, include_status = 1;
110 static int show_ignored_in_status, have_option_m;
111 static const char *only_include_assumed;
112 static struct strbuf message = STRBUF_INIT;
114 static enum {
115 STATUS_FORMAT_NONE = 0,
116 STATUS_FORMAT_LONG,
117 STATUS_FORMAT_SHORT,
118 STATUS_FORMAT_PORCELAIN
119 } status_format;
121 static int opt_parse_m(const struct option *opt, const char *arg, int unset)
123 struct strbuf *buf = opt->value;
124 if (unset) {
125 have_option_m = 0;
126 strbuf_setlen(buf, 0);
127 } else {
128 have_option_m = 1;
129 if (buf->len)
130 strbuf_addch(buf, '\n');
131 strbuf_addstr(buf, arg);
132 strbuf_complete_line(buf);
134 return 0;
137 static void determine_whence(struct wt_status *s)
139 if (file_exists(git_path("MERGE_HEAD")))
140 whence = FROM_MERGE;
141 else if (file_exists(git_path("CHERRY_PICK_HEAD")))
142 whence = FROM_CHERRY_PICK;
143 else
144 whence = FROM_COMMIT;
145 if (s)
146 s->whence = whence;
149 static void rollback_index_files(void)
151 switch (commit_style) {
152 case COMMIT_AS_IS:
153 break; /* nothing to do */
154 case COMMIT_NORMAL:
155 rollback_lock_file(&index_lock);
156 break;
157 case COMMIT_PARTIAL:
158 rollback_lock_file(&index_lock);
159 rollback_lock_file(&false_lock);
160 break;
164 static int commit_index_files(void)
166 int err = 0;
168 switch (commit_style) {
169 case COMMIT_AS_IS:
170 break; /* nothing to do */
171 case COMMIT_NORMAL:
172 err = commit_lock_file(&index_lock);
173 break;
174 case COMMIT_PARTIAL:
175 err = commit_lock_file(&index_lock);
176 rollback_lock_file(&false_lock);
177 break;
180 return err;
184 * Take a union of paths in the index and the named tree (typically, "HEAD"),
185 * and return the paths that match the given pattern in list.
187 static int list_paths(struct string_list *list, const char *with_tree,
188 const char *prefix, const char **pattern)
190 int i;
191 char *m;
193 if (!pattern)
194 return 0;
196 for (i = 0; pattern[i]; i++)
198 m = xcalloc(1, i);
200 if (with_tree) {
201 char *max_prefix = common_prefix(pattern);
202 overlay_tree_on_cache(with_tree, max_prefix ? max_prefix : prefix);
203 free(max_prefix);
206 for (i = 0; i < active_nr; i++) {
207 struct cache_entry *ce = active_cache[i];
208 struct string_list_item *item;
210 if (ce->ce_flags & CE_UPDATE)
211 continue;
212 if (!match_pathspec(pattern, ce->name, ce_namelen(ce), 0, m))
213 continue;
214 item = string_list_insert(list, ce->name);
215 if (ce_skip_worktree(ce))
216 item->util = item; /* better a valid pointer than a fake one */
219 return report_path_error(m, pattern, prefix);
222 static void add_remove_files(struct string_list *list)
224 int i;
225 for (i = 0; i < list->nr; i++) {
226 struct stat st;
227 struct string_list_item *p = &(list->items[i]);
229 /* p->util is skip-worktree */
230 if (p->util)
231 continue;
233 if (!lstat(p->string, &st)) {
234 if (add_to_cache(p->string, &st, 0))
235 die(_("updating files failed"));
236 } else
237 remove_file_from_cache(p->string);
241 static void create_base_index(const struct commit *current_head)
243 struct tree *tree;
244 struct unpack_trees_options opts;
245 struct tree_desc t;
247 if (!current_head) {
248 discard_cache();
249 return;
252 memset(&opts, 0, sizeof(opts));
253 opts.head_idx = 1;
254 opts.index_only = 1;
255 opts.merge = 1;
256 opts.src_index = &the_index;
257 opts.dst_index = &the_index;
259 opts.fn = oneway_merge;
260 tree = parse_tree_indirect(current_head->object.sha1);
261 if (!tree)
262 die(_("failed to unpack HEAD tree object"));
263 parse_tree(tree);
264 init_tree_desc(&t, tree->buffer, tree->size);
265 if (unpack_trees(1, &t, &opts))
266 exit(128); /* We've already reported the error, finish dying */
269 static void refresh_cache_or_die(int refresh_flags)
272 * refresh_flags contains REFRESH_QUIET, so the only errors
273 * are for unmerged entries.
275 if (refresh_cache(refresh_flags | REFRESH_IN_PORCELAIN))
276 die_resolve_conflict("commit");
279 static char *prepare_index(int argc, const char **argv, const char *prefix,
280 const struct commit *current_head, int is_status)
282 int fd;
283 struct string_list partial;
284 const char **pathspec = NULL;
285 char *old_index_env = NULL;
286 int refresh_flags = REFRESH_QUIET;
288 if (is_status)
289 refresh_flags |= REFRESH_UNMERGED;
291 if (*argv)
292 pathspec = get_pathspec(prefix, argv);
294 if (read_cache_preload(pathspec) < 0)
295 die(_("index file corrupt"));
297 if (interactive) {
298 fd = hold_locked_index(&index_lock, 1);
300 refresh_cache_or_die(refresh_flags);
302 if (write_cache(fd, active_cache, active_nr) ||
303 close_lock_file(&index_lock))
304 die(_("unable to create temporary index"));
306 old_index_env = getenv(INDEX_ENVIRONMENT);
307 setenv(INDEX_ENVIRONMENT, index_lock.filename, 1);
309 if (interactive_add(argc, argv, prefix, patch_interactive) != 0)
310 die(_("interactive add failed"));
312 if (old_index_env && *old_index_env)
313 setenv(INDEX_ENVIRONMENT, old_index_env, 1);
314 else
315 unsetenv(INDEX_ENVIRONMENT);
317 discard_cache();
318 read_cache_from(index_lock.filename);
320 commit_style = COMMIT_NORMAL;
321 return index_lock.filename;
325 * Non partial, non as-is commit.
327 * (1) get the real index;
328 * (2) update the_index as necessary;
329 * (3) write the_index out to the real index (still locked);
330 * (4) return the name of the locked index file.
332 * The caller should run hooks on the locked real index, and
333 * (A) if all goes well, commit the real index;
334 * (B) on failure, rollback the real index.
336 if (all || (also && pathspec && *pathspec)) {
337 fd = hold_locked_index(&index_lock, 1);
338 add_files_to_cache(also ? prefix : NULL, pathspec, 0);
339 refresh_cache_or_die(refresh_flags);
340 update_main_cache_tree(WRITE_TREE_SILENT);
341 if (write_cache(fd, active_cache, active_nr) ||
342 close_lock_file(&index_lock))
343 die(_("unable to write new_index file"));
344 commit_style = COMMIT_NORMAL;
345 return index_lock.filename;
349 * As-is commit.
351 * (1) return the name of the real index file.
353 * The caller should run hooks on the real index,
354 * and create commit from the_index.
355 * We still need to refresh the index here.
357 if (!only && (!pathspec || !*pathspec)) {
358 fd = hold_locked_index(&index_lock, 1);
359 refresh_cache_or_die(refresh_flags);
360 if (active_cache_changed) {
361 update_main_cache_tree(WRITE_TREE_SILENT);
362 if (write_cache(fd, active_cache, active_nr) ||
363 commit_locked_index(&index_lock))
364 die(_("unable to write new_index file"));
365 } else {
366 rollback_lock_file(&index_lock);
368 commit_style = COMMIT_AS_IS;
369 return get_index_file();
373 * A partial commit.
375 * (0) find the set of affected paths;
376 * (1) get lock on the real index file;
377 * (2) update the_index with the given paths;
378 * (3) write the_index out to the real index (still locked);
379 * (4) get lock on the false index file;
380 * (5) reset the_index from HEAD;
381 * (6) update the_index the same way as (2);
382 * (7) write the_index out to the false index file;
383 * (8) return the name of the false index file (still locked);
385 * The caller should run hooks on the locked false index, and
386 * create commit from it. Then
387 * (A) if all goes well, commit the real index;
388 * (B) on failure, rollback the real index;
389 * In either case, rollback the false index.
391 commit_style = COMMIT_PARTIAL;
393 if (whence != FROM_COMMIT) {
394 if (whence == FROM_MERGE)
395 die(_("cannot do a partial commit during a merge."));
396 else if (whence == FROM_CHERRY_PICK)
397 die(_("cannot do a partial commit during a cherry-pick."));
400 memset(&partial, 0, sizeof(partial));
401 partial.strdup_strings = 1;
402 if (list_paths(&partial, !current_head ? NULL : "HEAD", prefix, pathspec))
403 exit(1);
405 discard_cache();
406 if (read_cache() < 0)
407 die(_("cannot read the index"));
409 fd = hold_locked_index(&index_lock, 1);
410 add_remove_files(&partial);
411 refresh_cache(REFRESH_QUIET);
412 if (write_cache(fd, active_cache, active_nr) ||
413 close_lock_file(&index_lock))
414 die(_("unable to write new_index file"));
416 fd = hold_lock_file_for_update(&false_lock,
417 git_path("next-index-%"PRIuMAX,
418 (uintmax_t) getpid()),
419 LOCK_DIE_ON_ERROR);
421 create_base_index(current_head);
422 add_remove_files(&partial);
423 refresh_cache(REFRESH_QUIET);
425 if (write_cache(fd, active_cache, active_nr) ||
426 close_lock_file(&false_lock))
427 die(_("unable to write temporary index file"));
429 discard_cache();
430 read_cache_from(false_lock.filename);
432 return false_lock.filename;
435 static int run_status(FILE *fp, const char *index_file, const char *prefix, int nowarn,
436 struct wt_status *s)
438 unsigned char sha1[20];
440 if (s->relative_paths)
441 s->prefix = prefix;
443 if (amend) {
444 s->amend = 1;
445 s->reference = "HEAD^1";
447 s->verbose = verbose;
448 s->index_file = index_file;
449 s->fp = fp;
450 s->nowarn = nowarn;
451 s->is_initial = get_sha1(s->reference, sha1) ? 1 : 0;
453 wt_status_collect(s);
455 switch (status_format) {
456 case STATUS_FORMAT_SHORT:
457 wt_shortstatus_print(s);
458 break;
459 case STATUS_FORMAT_PORCELAIN:
460 wt_porcelain_print(s);
461 break;
462 case STATUS_FORMAT_NONE:
463 case STATUS_FORMAT_LONG:
464 wt_status_print(s);
465 break;
468 return s->commitable;
471 static int is_a_merge(const struct commit *current_head)
473 return !!(current_head->parents && current_head->parents->next);
476 static void export_one(const char *var, const char *s, const char *e, int hack)
478 struct strbuf buf = STRBUF_INIT;
479 if (hack)
480 strbuf_addch(&buf, hack);
481 strbuf_addf(&buf, "%.*s", (int)(e - s), s);
482 setenv(var, buf.buf, 1);
483 strbuf_release(&buf);
486 static int sane_ident_split(struct ident_split *person)
488 if (!person->name_begin || !person->name_end ||
489 person->name_begin == person->name_end)
490 return 0; /* no human readable name */
491 if (!person->mail_begin || !person->mail_end ||
492 person->mail_begin == person->mail_end)
493 return 0; /* no usable mail */
494 if (!person->date_begin || !person->date_end ||
495 !person->tz_begin || !person->tz_end)
496 return 0;
497 return 1;
500 static void determine_author_info(struct strbuf *author_ident)
502 char *name, *email, *date;
503 struct ident_split author;
505 name = getenv("GIT_AUTHOR_NAME");
506 email = getenv("GIT_AUTHOR_EMAIL");
507 date = getenv("GIT_AUTHOR_DATE");
509 if (author_message) {
510 const char *a, *lb, *rb, *eol;
511 size_t len;
513 a = strstr(author_message_buffer, "\nauthor ");
514 if (!a)
515 die(_("invalid commit: %s"), author_message);
517 lb = strchrnul(a + strlen("\nauthor "), '<');
518 rb = strchrnul(lb, '>');
519 eol = strchrnul(rb, '\n');
520 if (!*lb || !*rb || !*eol)
521 die(_("invalid commit: %s"), author_message);
523 if (lb == a + strlen("\nauthor "))
524 /* \nauthor <foo@example.com> */
525 name = xcalloc(1, 1);
526 else
527 name = xmemdupz(a + strlen("\nauthor "),
528 (lb - strlen(" ") -
529 (a + strlen("\nauthor "))));
530 email = xmemdupz(lb + strlen("<"), rb - (lb + strlen("<")));
531 date = xmemdupz(rb + strlen("> "), eol - (rb + strlen("> ")));
532 len = eol - (rb + strlen("> "));
533 date = xmalloc(len + 2);
534 *date = '@';
535 memcpy(date + 1, rb + strlen("> "), len);
536 date[len + 1] = '\0';
539 if (force_author) {
540 const char *lb = strstr(force_author, " <");
541 const char *rb = strchr(force_author, '>');
543 if (!lb || !rb)
544 die(_("malformed --author parameter"));
545 name = xstrndup(force_author, lb - force_author);
546 email = xstrndup(lb + 2, rb - (lb + 2));
549 if (force_date)
550 date = force_date;
551 strbuf_addstr(author_ident, fmt_ident(name, email, date, IDENT_STRICT));
552 if (!split_ident_line(&author, author_ident->buf, author_ident->len) &&
553 sane_ident_split(&author)) {
554 export_one("GIT_AUTHOR_NAME", author.name_begin, author.name_end, 0);
555 export_one("GIT_AUTHOR_EMAIL", author.mail_begin, author.mail_end, 0);
556 export_one("GIT_AUTHOR_DATE", author.date_begin, author.tz_end, '@');
560 static char *cut_ident_timestamp_part(char *string)
562 char *ket = strrchr(string, '>');
563 if (!ket || ket[1] != ' ')
564 die(_("Malformed ident string: '%s'"), string);
565 *++ket = '\0';
566 return ket;
569 static int prepare_to_commit(const char *index_file, const char *prefix,
570 struct commit *current_head,
571 struct wt_status *s,
572 struct strbuf *author_ident)
574 struct stat statbuf;
575 struct strbuf committer_ident = STRBUF_INIT;
576 int commitable, saved_color_setting;
577 struct strbuf sb = STRBUF_INIT;
578 char *buffer;
579 const char *hook_arg1 = NULL;
580 const char *hook_arg2 = NULL;
581 int ident_shown = 0;
582 int clean_message_contents = (cleanup_mode != CLEANUP_NONE);
584 /* This checks and barfs if author is badly specified */
585 determine_author_info(author_ident);
587 if (!no_verify && run_hook(index_file, "pre-commit", NULL))
588 return 0;
590 if (squash_message) {
592 * Insert the proper subject line before other commit
593 * message options add their content.
595 if (use_message && !strcmp(use_message, squash_message))
596 strbuf_addstr(&sb, "squash! ");
597 else {
598 struct pretty_print_context ctx = {0};
599 struct commit *c;
600 c = lookup_commit_reference_by_name(squash_message);
601 if (!c)
602 die(_("could not lookup commit %s"), squash_message);
603 ctx.output_encoding = get_commit_output_encoding();
604 format_commit_message(c, "squash! %s\n\n", &sb,
605 &ctx);
609 if (message.len) {
610 strbuf_addbuf(&sb, &message);
611 hook_arg1 = "message";
612 } else if (logfile && !strcmp(logfile, "-")) {
613 if (isatty(0))
614 fprintf(stderr, _("(reading log message from standard input)\n"));
615 if (strbuf_read(&sb, 0, 0) < 0)
616 die_errno(_("could not read log from standard input"));
617 hook_arg1 = "message";
618 } else if (logfile) {
619 if (strbuf_read_file(&sb, logfile, 0) < 0)
620 die_errno(_("could not read log file '%s'"),
621 logfile);
622 hook_arg1 = "message";
623 } else if (use_message) {
624 buffer = strstr(use_message_buffer, "\n\n");
625 if (!use_editor && (!buffer || buffer[2] == '\0'))
626 die(_("commit has empty message"));
627 strbuf_add(&sb, buffer + 2, strlen(buffer + 2));
628 hook_arg1 = "commit";
629 hook_arg2 = use_message;
630 } else if (fixup_message) {
631 struct pretty_print_context ctx = {0};
632 struct commit *commit;
633 commit = lookup_commit_reference_by_name(fixup_message);
634 if (!commit)
635 die(_("could not lookup commit %s"), fixup_message);
636 ctx.output_encoding = get_commit_output_encoding();
637 format_commit_message(commit, "fixup! %s\n\n",
638 &sb, &ctx);
639 hook_arg1 = "message";
640 } else if (!stat(git_path("MERGE_MSG"), &statbuf)) {
641 if (strbuf_read_file(&sb, git_path("MERGE_MSG"), 0) < 0)
642 die_errno(_("could not read MERGE_MSG"));
643 hook_arg1 = "merge";
644 } else if (!stat(git_path("SQUASH_MSG"), &statbuf)) {
645 if (strbuf_read_file(&sb, git_path("SQUASH_MSG"), 0) < 0)
646 die_errno(_("could not read SQUASH_MSG"));
647 hook_arg1 = "squash";
648 } else if (template_file) {
649 if (strbuf_read_file(&sb, template_file, 0) < 0)
650 die_errno(_("could not read '%s'"), template_file);
651 hook_arg1 = "template";
652 clean_message_contents = 0;
656 * The remaining cases don't modify the template message, but
657 * just set the argument(s) to the prepare-commit-msg hook.
659 else if (whence == FROM_MERGE)
660 hook_arg1 = "merge";
661 else if (whence == FROM_CHERRY_PICK) {
662 hook_arg1 = "commit";
663 hook_arg2 = "CHERRY_PICK_HEAD";
666 if (squash_message) {
668 * If squash_commit was used for the commit subject,
669 * then we're possibly hijacking other commit log options.
670 * Reset the hook args to tell the real story.
672 hook_arg1 = "message";
673 hook_arg2 = "";
676 s->fp = fopen(git_path(commit_editmsg), "w");
677 if (s->fp == NULL)
678 die_errno(_("could not open '%s'"), git_path(commit_editmsg));
680 if (clean_message_contents)
681 stripspace(&sb, 0);
683 if (signoff) {
685 * See if we have a Conflicts: block at the end. If yes, count
686 * its size, so we can ignore it.
688 int ignore_footer = 0;
689 int i, eol, previous = 0;
690 const char *nl;
692 for (i = 0; i < sb.len; i++) {
693 nl = memchr(sb.buf + i, '\n', sb.len - i);
694 if (nl)
695 eol = nl - sb.buf;
696 else
697 eol = sb.len;
698 if (!prefixcmp(sb.buf + previous, "\nConflicts:\n")) {
699 ignore_footer = sb.len - previous;
700 break;
702 while (i < eol)
703 i++;
704 previous = eol;
707 append_signoff(&sb, ignore_footer, 0);
710 if (fwrite(sb.buf, 1, sb.len, s->fp) < sb.len)
711 die_errno(_("could not write commit template"));
713 strbuf_release(&sb);
715 /* This checks if committer ident is explicitly given */
716 strbuf_addstr(&committer_ident, git_committer_info(IDENT_STRICT));
717 if (use_editor && include_status) {
718 char *ai_tmp, *ci_tmp;
719 if (whence != FROM_COMMIT)
720 status_printf_ln(s, GIT_COLOR_NORMAL,
721 whence == FROM_MERGE
722 ? _("\n"
723 "It looks like you may be committing a merge.\n"
724 "If this is not correct, please remove the file\n"
725 " %s\n"
726 "and try again.\n")
727 : _("\n"
728 "It looks like you may be committing a cherry-pick.\n"
729 "If this is not correct, please remove the file\n"
730 " %s\n"
731 "and try again.\n"),
732 git_path(whence == FROM_MERGE
733 ? "MERGE_HEAD"
734 : "CHERRY_PICK_HEAD"));
736 fprintf(s->fp, "\n");
737 if (cleanup_mode == CLEANUP_ALL)
738 status_printf(s, GIT_COLOR_NORMAL,
739 _("Please enter the commit message for your changes."
740 " Lines starting\nwith '%c' will be ignored, and an empty"
741 " message aborts the commit.\n"), comment_line_char);
742 else /* CLEANUP_SPACE, that is. */
743 status_printf(s, GIT_COLOR_NORMAL,
744 _("Please enter the commit message for your changes."
745 " Lines starting\n"
746 "with '%c' will be kept; you may remove them"
747 " yourself if you want to.\n"
748 "An empty message aborts the commit.\n"), comment_line_char);
749 if (only_include_assumed)
750 status_printf_ln(s, GIT_COLOR_NORMAL,
751 "%s", only_include_assumed);
753 ai_tmp = cut_ident_timestamp_part(author_ident->buf);
754 ci_tmp = cut_ident_timestamp_part(committer_ident.buf);
755 if (strcmp(author_ident->buf, committer_ident.buf))
756 status_printf_ln(s, GIT_COLOR_NORMAL,
757 _("%s"
758 "Author: %s"),
759 ident_shown++ ? "" : "\n",
760 author_ident->buf);
762 if (!committer_ident_sufficiently_given())
763 status_printf_ln(s, GIT_COLOR_NORMAL,
764 _("%s"
765 "Committer: %s"),
766 ident_shown++ ? "" : "\n",
767 committer_ident.buf);
769 if (ident_shown)
770 status_printf_ln(s, GIT_COLOR_NORMAL, "");
772 saved_color_setting = s->use_color;
773 s->use_color = 0;
774 commitable = run_status(s->fp, index_file, prefix, 1, s);
775 s->use_color = saved_color_setting;
777 *ai_tmp = ' ';
778 *ci_tmp = ' ';
779 } else {
780 unsigned char sha1[20];
781 const char *parent = "HEAD";
783 if (!active_nr && read_cache() < 0)
784 die(_("Cannot read index"));
786 if (amend)
787 parent = "HEAD^1";
789 if (get_sha1(parent, sha1))
790 commitable = !!active_nr;
791 else
792 commitable = index_differs_from(parent, 0);
794 strbuf_release(&committer_ident);
796 fclose(s->fp);
799 * Reject an attempt to record a non-merge empty commit without
800 * explicit --allow-empty. In the cherry-pick case, it may be
801 * empty due to conflict resolution, which the user should okay.
803 if (!commitable && whence != FROM_MERGE && !allow_empty &&
804 !(amend && is_a_merge(current_head))) {
805 run_status(stdout, index_file, prefix, 0, s);
806 if (amend)
807 fputs(_(empty_amend_advice), stderr);
808 else if (whence == FROM_CHERRY_PICK)
809 fputs(_(empty_cherry_pick_advice), stderr);
810 return 0;
814 * Re-read the index as pre-commit hook could have updated it,
815 * and write it out as a tree. We must do this before we invoke
816 * the editor and after we invoke run_status above.
818 discard_cache();
819 read_cache_from(index_file);
820 if (update_main_cache_tree(0)) {
821 error(_("Error building trees"));
822 return 0;
825 if (run_hook(index_file, "prepare-commit-msg",
826 git_path(commit_editmsg), hook_arg1, hook_arg2, NULL))
827 return 0;
829 if (use_editor) {
830 char index[PATH_MAX];
831 const char *env[2] = { NULL };
832 env[0] = index;
833 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
834 if (launch_editor(git_path(commit_editmsg), NULL, env)) {
835 fprintf(stderr,
836 _("Please supply the message using either -m or -F option.\n"));
837 exit(1);
841 if (!no_verify &&
842 run_hook(index_file, "commit-msg", git_path(commit_editmsg), NULL)) {
843 return 0;
846 return 1;
849 static int rest_is_empty(struct strbuf *sb, int start)
851 int i, eol;
852 const char *nl;
854 /* Check if the rest is just whitespace and Signed-of-by's. */
855 for (i = start; i < sb->len; i++) {
856 nl = memchr(sb->buf + i, '\n', sb->len - i);
857 if (nl)
858 eol = nl - sb->buf;
859 else
860 eol = sb->len;
862 if (strlen(sign_off_header) <= eol - i &&
863 !prefixcmp(sb->buf + i, sign_off_header)) {
864 i = eol;
865 continue;
867 while (i < eol)
868 if (!isspace(sb->buf[i++]))
869 return 0;
872 return 1;
876 * Find out if the message in the strbuf contains only whitespace and
877 * Signed-off-by lines.
879 static int message_is_empty(struct strbuf *sb)
881 if (cleanup_mode == CLEANUP_NONE && sb->len)
882 return 0;
883 return rest_is_empty(sb, 0);
887 * See if the user edited the message in the editor or left what
888 * was in the template intact
890 static int template_untouched(struct strbuf *sb)
892 struct strbuf tmpl = STRBUF_INIT;
893 char *start;
895 if (cleanup_mode == CLEANUP_NONE && sb->len)
896 return 0;
898 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
899 return 0;
901 stripspace(&tmpl, cleanup_mode == CLEANUP_ALL);
902 start = (char *)skip_prefix(sb->buf, tmpl.buf);
903 if (!start)
904 start = sb->buf;
905 strbuf_release(&tmpl);
906 return rest_is_empty(sb, start - sb->buf);
909 static const char *find_author_by_nickname(const char *name)
911 struct rev_info revs;
912 struct commit *commit;
913 struct strbuf buf = STRBUF_INIT;
914 const char *av[20];
915 int ac = 0;
917 init_revisions(&revs, NULL);
918 strbuf_addf(&buf, "--author=%s", name);
919 av[++ac] = "--all";
920 av[++ac] = "-i";
921 av[++ac] = buf.buf;
922 av[++ac] = NULL;
923 setup_revisions(ac, av, &revs, NULL);
924 prepare_revision_walk(&revs);
925 commit = get_revision(&revs);
926 if (commit) {
927 struct pretty_print_context ctx = {0};
928 ctx.date_mode = DATE_NORMAL;
929 strbuf_release(&buf);
930 format_commit_message(commit, "%an <%ae>", &buf, &ctx);
931 return strbuf_detach(&buf, NULL);
933 die(_("No existing author found with '%s'"), name);
937 static void handle_untracked_files_arg(struct wt_status *s)
939 if (!untracked_files_arg)
940 ; /* default already initialized */
941 else if (!strcmp(untracked_files_arg, "no"))
942 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
943 else if (!strcmp(untracked_files_arg, "normal"))
944 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
945 else if (!strcmp(untracked_files_arg, "all"))
946 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
947 else
948 die(_("Invalid untracked files mode '%s'"), untracked_files_arg);
951 static const char *read_commit_message(const char *name)
953 const char *out_enc;
954 struct commit *commit;
956 commit = lookup_commit_reference_by_name(name);
957 if (!commit)
958 die(_("could not lookup commit %s"), name);
959 out_enc = get_commit_output_encoding();
960 return logmsg_reencode(commit, NULL, out_enc);
963 static int parse_and_validate_options(int argc, const char *argv[],
964 const struct option *options,
965 const char * const usage[],
966 const char *prefix,
967 struct commit *current_head,
968 struct wt_status *s)
970 int f = 0;
972 argc = parse_options(argc, argv, prefix, options, usage, 0);
974 if (force_author && !strchr(force_author, '>'))
975 force_author = find_author_by_nickname(force_author);
977 if (force_author && renew_authorship)
978 die(_("Using both --reset-author and --author does not make sense"));
980 if (logfile || have_option_m || use_message || fixup_message)
981 use_editor = 0;
982 if (0 <= edit_flag)
983 use_editor = edit_flag;
984 if (!use_editor)
985 setenv("GIT_EDITOR", ":", 1);
987 /* Sanity check options */
988 if (amend && !current_head)
989 die(_("You have nothing to amend."));
990 if (amend && whence != FROM_COMMIT) {
991 if (whence == FROM_MERGE)
992 die(_("You are in the middle of a merge -- cannot amend."));
993 else if (whence == FROM_CHERRY_PICK)
994 die(_("You are in the middle of a cherry-pick -- cannot amend."));
996 if (fixup_message && squash_message)
997 die(_("Options --squash and --fixup cannot be used together"));
998 if (use_message)
999 f++;
1000 if (edit_message)
1001 f++;
1002 if (fixup_message)
1003 f++;
1004 if (logfile)
1005 f++;
1006 if (f > 1)
1007 die(_("Only one of -c/-C/-F/--fixup can be used."));
1008 if (message.len && f > 0)
1009 die((_("Option -m cannot be combined with -c/-C/-F/--fixup.")));
1010 if (f || message.len)
1011 template_file = NULL;
1012 if (edit_message)
1013 use_message = edit_message;
1014 if (amend && !use_message && !fixup_message)
1015 use_message = "HEAD";
1016 if (!use_message && whence != FROM_CHERRY_PICK && renew_authorship)
1017 die(_("--reset-author can be used only with -C, -c or --amend."));
1018 if (use_message) {
1019 use_message_buffer = read_commit_message(use_message);
1020 if (!renew_authorship) {
1021 author_message = use_message;
1022 author_message_buffer = use_message_buffer;
1025 if (whence == FROM_CHERRY_PICK && !renew_authorship) {
1026 author_message = "CHERRY_PICK_HEAD";
1027 author_message_buffer = read_commit_message(author_message);
1030 if (patch_interactive)
1031 interactive = 1;
1033 if (!!also + !!only + !!all + !!interactive > 1)
1034 die(_("Only one of --include/--only/--all/--interactive/--patch can be used."));
1035 if (argc == 0 && (also || (only && !amend)))
1036 die(_("No paths with --include/--only does not make sense."));
1037 if (argc == 0 && only && amend)
1038 only_include_assumed = _("Clever... amending the last one with dirty index.");
1039 if (argc > 0 && !also && !only)
1040 only_include_assumed = _("Explicit paths specified without -i nor -o; assuming --only paths...");
1041 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
1042 cleanup_mode = use_editor ? CLEANUP_ALL : CLEANUP_SPACE;
1043 else if (!strcmp(cleanup_arg, "verbatim"))
1044 cleanup_mode = CLEANUP_NONE;
1045 else if (!strcmp(cleanup_arg, "whitespace"))
1046 cleanup_mode = CLEANUP_SPACE;
1047 else if (!strcmp(cleanup_arg, "strip"))
1048 cleanup_mode = CLEANUP_ALL;
1049 else
1050 die(_("Invalid cleanup mode %s"), cleanup_arg);
1052 handle_untracked_files_arg(s);
1054 if (all && argc > 0)
1055 die(_("Paths with -a does not make sense."));
1057 if (s->null_termination) {
1058 if (status_format == STATUS_FORMAT_NONE)
1059 status_format = STATUS_FORMAT_PORCELAIN;
1060 else if (status_format == STATUS_FORMAT_LONG)
1061 die(_("--long and -z are incompatible"));
1063 if (status_format != STATUS_FORMAT_NONE)
1064 dry_run = 1;
1066 return argc;
1069 static int dry_run_commit(int argc, const char **argv, const char *prefix,
1070 const struct commit *current_head, struct wt_status *s)
1072 int commitable;
1073 const char *index_file;
1075 index_file = prepare_index(argc, argv, prefix, current_head, 1);
1076 commitable = run_status(stdout, index_file, prefix, 0, s);
1077 rollback_index_files();
1079 return commitable ? 0 : 1;
1082 static int parse_status_slot(const char *var, int offset)
1084 if (!strcasecmp(var+offset, "header"))
1085 return WT_STATUS_HEADER;
1086 if (!strcasecmp(var+offset, "branch"))
1087 return WT_STATUS_ONBRANCH;
1088 if (!strcasecmp(var+offset, "updated")
1089 || !strcasecmp(var+offset, "added"))
1090 return WT_STATUS_UPDATED;
1091 if (!strcasecmp(var+offset, "changed"))
1092 return WT_STATUS_CHANGED;
1093 if (!strcasecmp(var+offset, "untracked"))
1094 return WT_STATUS_UNTRACKED;
1095 if (!strcasecmp(var+offset, "nobranch"))
1096 return WT_STATUS_NOBRANCH;
1097 if (!strcasecmp(var+offset, "unmerged"))
1098 return WT_STATUS_UNMERGED;
1099 return -1;
1102 static int git_status_config(const char *k, const char *v, void *cb)
1104 struct wt_status *s = cb;
1106 if (!prefixcmp(k, "column."))
1107 return git_column_config(k, v, "status", &s->colopts);
1108 if (!strcmp(k, "status.submodulesummary")) {
1109 int is_bool;
1110 s->submodule_summary = git_config_bool_or_int(k, v, &is_bool);
1111 if (is_bool && s->submodule_summary)
1112 s->submodule_summary = -1;
1113 return 0;
1115 if (!strcmp(k, "status.short")) {
1116 if (git_config_bool(k, v))
1117 status_format = STATUS_FORMAT_SHORT;
1118 else
1119 status_format = STATUS_FORMAT_NONE;
1120 return 0;
1122 if (!strcmp(k, "status.branch")) {
1123 s->show_branch = git_config_bool(k, v);
1124 return 0;
1126 if (!strcmp(k, "status.color") || !strcmp(k, "color.status")) {
1127 s->use_color = git_config_colorbool(k, v);
1128 return 0;
1130 if (!prefixcmp(k, "status.color.") || !prefixcmp(k, "color.status.")) {
1131 int slot = parse_status_slot(k, 13);
1132 if (slot < 0)
1133 return 0;
1134 if (!v)
1135 return config_error_nonbool(k);
1136 color_parse(v, k, s->color_palette[slot]);
1137 return 0;
1139 if (!strcmp(k, "status.relativepaths")) {
1140 s->relative_paths = git_config_bool(k, v);
1141 return 0;
1143 if (!strcmp(k, "status.showuntrackedfiles")) {
1144 if (!v)
1145 return config_error_nonbool(k);
1146 else if (!strcmp(v, "no"))
1147 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
1148 else if (!strcmp(v, "normal"))
1149 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
1150 else if (!strcmp(v, "all"))
1151 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
1152 else
1153 return error(_("Invalid untracked files mode '%s'"), v);
1154 return 0;
1156 return git_diff_ui_config(k, v, NULL);
1159 int cmd_status(int argc, const char **argv, const char *prefix)
1161 static struct wt_status s;
1162 int fd;
1163 unsigned char sha1[20];
1164 static struct option builtin_status_options[] = {
1165 OPT__VERBOSE(&verbose, N_("be verbose")),
1166 OPT_SET_INT('s', "short", &status_format,
1167 N_("show status concisely"), STATUS_FORMAT_SHORT),
1168 OPT_BOOLEAN('b', "branch", &s.show_branch,
1169 N_("show branch information")),
1170 OPT_SET_INT(0, "porcelain", &status_format,
1171 N_("machine-readable output"),
1172 STATUS_FORMAT_PORCELAIN),
1173 OPT_SET_INT(0, "long", &status_format,
1174 N_("show status in long format (default)"),
1175 STATUS_FORMAT_LONG),
1176 OPT_BOOLEAN('z', "null", &s.null_termination,
1177 N_("terminate entries with NUL")),
1178 { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg,
1179 N_("mode"),
1180 N_("show untracked files, optional modes: all, normal, no. (Default: all)"),
1181 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1182 OPT_BOOLEAN(0, "ignored", &show_ignored_in_status,
1183 N_("show ignored files")),
1184 { OPTION_STRING, 0, "ignore-submodules", &ignore_submodule_arg, N_("when"),
1185 N_("ignore changes to submodules, optional when: all, dirty, untracked. (Default: all)"),
1186 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1187 OPT_COLUMN(0, "column", &s.colopts, N_("list untracked files in columns")),
1188 OPT_END(),
1191 if (argc == 2 && !strcmp(argv[1], "-h"))
1192 usage_with_options(builtin_status_usage, builtin_status_options);
1194 wt_status_prepare(&s);
1195 gitmodules_config();
1196 git_config(git_status_config, &s);
1197 determine_whence(&s);
1198 argc = parse_options(argc, argv, prefix,
1199 builtin_status_options,
1200 builtin_status_usage, 0);
1201 finalize_colopts(&s.colopts, -1);
1203 if (s.null_termination) {
1204 if (status_format == STATUS_FORMAT_NONE)
1205 status_format = STATUS_FORMAT_PORCELAIN;
1206 else if (status_format == STATUS_FORMAT_LONG)
1207 die(_("--long and -z are incompatible"));
1210 handle_untracked_files_arg(&s);
1211 if (show_ignored_in_status)
1212 s.show_ignored_files = 1;
1213 if (*argv)
1214 s.pathspec = get_pathspec(prefix, argv);
1216 read_cache_preload(s.pathspec);
1217 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, s.pathspec, NULL, NULL);
1219 fd = hold_locked_index(&index_lock, 0);
1220 if (0 <= fd)
1221 update_index_if_able(&the_index, &index_lock);
1223 s.is_initial = get_sha1(s.reference, sha1) ? 1 : 0;
1224 s.ignore_submodule_arg = ignore_submodule_arg;
1225 wt_status_collect(&s);
1227 if (s.relative_paths)
1228 s.prefix = prefix;
1230 switch (status_format) {
1231 case STATUS_FORMAT_SHORT:
1232 wt_shortstatus_print(&s);
1233 break;
1234 case STATUS_FORMAT_PORCELAIN:
1235 wt_porcelain_print(&s);
1236 break;
1237 case STATUS_FORMAT_NONE:
1238 case STATUS_FORMAT_LONG:
1239 s.verbose = verbose;
1240 s.ignore_submodule_arg = ignore_submodule_arg;
1241 wt_status_print(&s);
1242 break;
1244 return 0;
1247 static void print_summary(const char *prefix, const unsigned char *sha1,
1248 int initial_commit)
1250 struct rev_info rev;
1251 struct commit *commit;
1252 struct strbuf format = STRBUF_INIT;
1253 unsigned char junk_sha1[20];
1254 const char *head;
1255 struct pretty_print_context pctx = {0};
1256 struct strbuf author_ident = STRBUF_INIT;
1257 struct strbuf committer_ident = STRBUF_INIT;
1259 commit = lookup_commit(sha1);
1260 if (!commit)
1261 die(_("couldn't look up newly created commit"));
1262 if (!commit || parse_commit(commit))
1263 die(_("could not parse newly created commit"));
1265 strbuf_addstr(&format, "format:%h] %s");
1267 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1268 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1269 if (strbuf_cmp(&author_ident, &committer_ident)) {
1270 strbuf_addstr(&format, "\n Author: ");
1271 strbuf_addbuf_percentquote(&format, &author_ident);
1273 if (!committer_ident_sufficiently_given()) {
1274 strbuf_addstr(&format, "\n Committer: ");
1275 strbuf_addbuf_percentquote(&format, &committer_ident);
1276 if (advice_implicit_identity) {
1277 strbuf_addch(&format, '\n');
1278 strbuf_addstr(&format, _(implicit_ident_advice));
1281 strbuf_release(&author_ident);
1282 strbuf_release(&committer_ident);
1284 init_revisions(&rev, prefix);
1285 setup_revisions(0, NULL, &rev, NULL);
1287 rev.diff = 1;
1288 rev.diffopt.output_format =
1289 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1291 rev.verbose_header = 1;
1292 rev.show_root_diff = 1;
1293 get_commit_format(format.buf, &rev);
1294 rev.always_show_header = 0;
1295 rev.diffopt.detect_rename = 1;
1296 rev.diffopt.break_opt = 0;
1297 diff_setup_done(&rev.diffopt);
1299 head = resolve_ref_unsafe("HEAD", junk_sha1, 0, NULL);
1300 printf("[%s%s ",
1301 !prefixcmp(head, "refs/heads/") ?
1302 head + 11 :
1303 !strcmp(head, "HEAD") ?
1304 _("detached HEAD") :
1305 head,
1306 initial_commit ? _(" (root-commit)") : "");
1308 if (!log_tree_commit(&rev, commit)) {
1309 rev.always_show_header = 1;
1310 rev.use_terminator = 1;
1311 log_tree_commit(&rev, commit);
1314 strbuf_release(&format);
1317 static int git_commit_config(const char *k, const char *v, void *cb)
1319 struct wt_status *s = cb;
1320 int status;
1322 if (!strcmp(k, "commit.template"))
1323 return git_config_pathname(&template_file, k, v);
1324 if (!strcmp(k, "commit.status")) {
1325 include_status = git_config_bool(k, v);
1326 return 0;
1328 if (!strcmp(k, "commit.cleanup"))
1329 return git_config_string(&cleanup_arg, k, v);
1331 status = git_gpg_config(k, v, NULL);
1332 if (status)
1333 return status;
1334 return git_status_config(k, v, s);
1337 static int run_rewrite_hook(const unsigned char *oldsha1,
1338 const unsigned char *newsha1)
1340 /* oldsha1 SP newsha1 LF NUL */
1341 static char buf[2*40 + 3];
1342 struct child_process proc;
1343 const char *argv[3];
1344 int code;
1345 size_t n;
1347 argv[0] = find_hook("post-rewrite");
1348 if (!argv[0])
1349 return 0;
1351 argv[1] = "amend";
1352 argv[2] = NULL;
1354 memset(&proc, 0, sizeof(proc));
1355 proc.argv = argv;
1356 proc.in = -1;
1357 proc.stdout_to_stderr = 1;
1359 code = start_command(&proc);
1360 if (code)
1361 return code;
1362 n = snprintf(buf, sizeof(buf), "%s %s\n",
1363 sha1_to_hex(oldsha1), sha1_to_hex(newsha1));
1364 write_in_full(proc.in, buf, n);
1365 close(proc.in);
1366 return finish_command(&proc);
1369 int cmd_commit(int argc, const char **argv, const char *prefix)
1371 static struct wt_status s;
1372 static struct option builtin_commit_options[] = {
1373 OPT__QUIET(&quiet, N_("suppress summary after successful commit")),
1374 OPT__VERBOSE(&verbose, N_("show diff in commit message template")),
1376 OPT_GROUP(N_("Commit message options")),
1377 OPT_FILENAME('F', "file", &logfile, N_("read message from file")),
1378 OPT_STRING(0, "author", &force_author, N_("author"), N_("override author for commit")),
1379 OPT_STRING(0, "date", &force_date, N_("date"), N_("override date for commit")),
1380 OPT_CALLBACK('m', "message", &message, N_("message"), N_("commit message"), opt_parse_m),
1381 OPT_STRING('c', "reedit-message", &edit_message, N_("commit"), N_("reuse and edit message from specified commit")),
1382 OPT_STRING('C', "reuse-message", &use_message, N_("commit"), N_("reuse message from specified commit")),
1383 OPT_STRING(0, "fixup", &fixup_message, N_("commit"), N_("use autosquash formatted message to fixup specified commit")),
1384 OPT_STRING(0, "squash", &squash_message, N_("commit"), N_("use autosquash formatted message to squash specified commit")),
1385 OPT_BOOLEAN(0, "reset-author", &renew_authorship, N_("the commit is authored by me now (used with -C/-c/--amend)")),
1386 OPT_BOOLEAN('s', "signoff", &signoff, N_("add Signed-off-by:")),
1387 OPT_FILENAME('t', "template", &template_file, N_("use specified template file")),
1388 OPT_BOOL('e', "edit", &edit_flag, N_("force edit of commit")),
1389 OPT_STRING(0, "cleanup", &cleanup_arg, N_("default"), N_("how to strip spaces and #comments from message")),
1390 OPT_BOOLEAN(0, "status", &include_status, N_("include status in commit message template")),
1391 { OPTION_STRING, 'S', "gpg-sign", &sign_commit, N_("key id"),
1392 N_("GPG sign commit"), PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
1393 /* end commit message options */
1395 OPT_GROUP(N_("Commit contents options")),
1396 OPT_BOOLEAN('a', "all", &all, N_("commit all changed files")),
1397 OPT_BOOLEAN('i', "include", &also, N_("add specified files to index for commit")),
1398 OPT_BOOLEAN(0, "interactive", &interactive, N_("interactively add files")),
1399 OPT_BOOLEAN('p', "patch", &patch_interactive, N_("interactively add changes")),
1400 OPT_BOOLEAN('o', "only", &only, N_("commit only specified files")),
1401 OPT_BOOLEAN('n', "no-verify", &no_verify, N_("bypass pre-commit hook")),
1402 OPT_BOOLEAN(0, "dry-run", &dry_run, N_("show what would be committed")),
1403 OPT_SET_INT(0, "short", &status_format, N_("show status concisely"),
1404 STATUS_FORMAT_SHORT),
1405 OPT_BOOLEAN(0, "branch", &s.show_branch, N_("show branch information")),
1406 OPT_SET_INT(0, "porcelain", &status_format,
1407 N_("machine-readable output"), STATUS_FORMAT_PORCELAIN),
1408 OPT_SET_INT(0, "long", &status_format,
1409 N_("show status in long format (default)"),
1410 STATUS_FORMAT_LONG),
1411 OPT_BOOLEAN('z', "null", &s.null_termination,
1412 N_("terminate entries with NUL")),
1413 OPT_BOOLEAN(0, "amend", &amend, N_("amend previous commit")),
1414 OPT_BOOLEAN(0, "no-post-rewrite", &no_post_rewrite, N_("bypass post-rewrite hook")),
1415 { 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" },
1416 /* end commit contents options */
1418 { OPTION_BOOLEAN, 0, "allow-empty", &allow_empty, NULL,
1419 N_("ok to record an empty change"),
1420 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN },
1421 { OPTION_BOOLEAN, 0, "allow-empty-message", &allow_empty_message, NULL,
1422 N_("ok to record a change with an empty message"),
1423 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN },
1425 OPT_END()
1428 struct strbuf sb = STRBUF_INIT;
1429 struct strbuf author_ident = STRBUF_INIT;
1430 const char *index_file, *reflog_msg;
1431 char *nl, *p;
1432 unsigned char sha1[20];
1433 struct ref_lock *ref_lock;
1434 struct commit_list *parents = NULL, **pptr = &parents;
1435 struct stat statbuf;
1436 int allow_fast_forward = 1;
1437 struct commit *current_head = NULL;
1438 struct commit_extra_header *extra = NULL;
1440 if (argc == 2 && !strcmp(argv[1], "-h"))
1441 usage_with_options(builtin_commit_usage, builtin_commit_options);
1443 wt_status_prepare(&s);
1444 gitmodules_config();
1445 git_config(git_commit_config, &s);
1446 determine_whence(&s);
1447 s.colopts = 0;
1449 if (get_sha1("HEAD", sha1))
1450 current_head = NULL;
1451 else {
1452 current_head = lookup_commit_or_die(sha1, "HEAD");
1453 if (!current_head || parse_commit(current_head))
1454 die(_("could not parse HEAD commit"));
1456 argc = parse_and_validate_options(argc, argv, builtin_commit_options,
1457 builtin_commit_usage,
1458 prefix, current_head, &s);
1459 if (dry_run)
1460 return dry_run_commit(argc, argv, prefix, current_head, &s);
1461 index_file = prepare_index(argc, argv, prefix, current_head, 0);
1463 /* Set up everything for writing the commit object. This includes
1464 running hooks, writing the trees, and interacting with the user. */
1465 if (!prepare_to_commit(index_file, prefix,
1466 current_head, &s, &author_ident)) {
1467 rollback_index_files();
1468 return 1;
1471 /* Determine parents */
1472 reflog_msg = getenv("GIT_REFLOG_ACTION");
1473 if (!current_head) {
1474 if (!reflog_msg)
1475 reflog_msg = "commit (initial)";
1476 } else if (amend) {
1477 struct commit_list *c;
1479 if (!reflog_msg)
1480 reflog_msg = "commit (amend)";
1481 for (c = current_head->parents; c; c = c->next)
1482 pptr = &commit_list_insert(c->item, pptr)->next;
1483 } else if (whence == FROM_MERGE) {
1484 struct strbuf m = STRBUF_INIT;
1485 FILE *fp;
1487 if (!reflog_msg)
1488 reflog_msg = "commit (merge)";
1489 pptr = &commit_list_insert(current_head, pptr)->next;
1490 fp = fopen(git_path("MERGE_HEAD"), "r");
1491 if (fp == NULL)
1492 die_errno(_("could not open '%s' for reading"),
1493 git_path("MERGE_HEAD"));
1494 while (strbuf_getline(&m, fp, '\n') != EOF) {
1495 struct commit *parent;
1497 parent = get_merge_parent(m.buf);
1498 if (!parent)
1499 die(_("Corrupt MERGE_HEAD file (%s)"), m.buf);
1500 pptr = &commit_list_insert(parent, pptr)->next;
1502 fclose(fp);
1503 strbuf_release(&m);
1504 if (!stat(git_path("MERGE_MODE"), &statbuf)) {
1505 if (strbuf_read_file(&sb, git_path("MERGE_MODE"), 0) < 0)
1506 die_errno(_("could not read MERGE_MODE"));
1507 if (!strcmp(sb.buf, "no-ff"))
1508 allow_fast_forward = 0;
1510 if (allow_fast_forward)
1511 parents = reduce_heads(parents);
1512 } else {
1513 if (!reflog_msg)
1514 reflog_msg = (whence == FROM_CHERRY_PICK)
1515 ? "commit (cherry-pick)"
1516 : "commit";
1517 pptr = &commit_list_insert(current_head, pptr)->next;
1520 /* Finally, get the commit message */
1521 strbuf_reset(&sb);
1522 if (strbuf_read_file(&sb, git_path(commit_editmsg), 0) < 0) {
1523 int saved_errno = errno;
1524 rollback_index_files();
1525 die(_("could not read commit message: %s"), strerror(saved_errno));
1528 /* Truncate the message just before the diff, if any. */
1529 if (verbose) {
1530 p = strstr(sb.buf, "\ndiff --git ");
1531 if (p != NULL)
1532 strbuf_setlen(&sb, p - sb.buf + 1);
1535 if (cleanup_mode != CLEANUP_NONE)
1536 stripspace(&sb, cleanup_mode == CLEANUP_ALL);
1537 if (template_untouched(&sb) && !allow_empty_message) {
1538 rollback_index_files();
1539 fprintf(stderr, _("Aborting commit; you did not edit the message.\n"));
1540 exit(1);
1542 if (message_is_empty(&sb) && !allow_empty_message) {
1543 rollback_index_files();
1544 fprintf(stderr, _("Aborting commit due to empty commit message.\n"));
1545 exit(1);
1548 if (amend) {
1549 const char *exclude_gpgsig[2] = { "gpgsig", NULL };
1550 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1551 } else {
1552 struct commit_extra_header **tail = &extra;
1553 append_merge_tag_headers(parents, &tail);
1556 if (commit_tree_extended(&sb, active_cache_tree->sha1, parents, sha1,
1557 author_ident.buf, sign_commit, extra)) {
1558 rollback_index_files();
1559 die(_("failed to write commit object"));
1561 strbuf_release(&author_ident);
1562 free_commit_extra_headers(extra);
1564 ref_lock = lock_any_ref_for_update("HEAD",
1565 !current_head
1566 ? NULL
1567 : current_head->object.sha1,
1570 nl = strchr(sb.buf, '\n');
1571 if (nl)
1572 strbuf_setlen(&sb, nl + 1 - sb.buf);
1573 else
1574 strbuf_addch(&sb, '\n');
1575 strbuf_insert(&sb, 0, reflog_msg, strlen(reflog_msg));
1576 strbuf_insert(&sb, strlen(reflog_msg), ": ", 2);
1578 if (!ref_lock) {
1579 rollback_index_files();
1580 die(_("cannot lock HEAD ref"));
1582 if (write_ref_sha1(ref_lock, sha1, sb.buf) < 0) {
1583 rollback_index_files();
1584 die(_("cannot update HEAD ref"));
1587 unlink(git_path("CHERRY_PICK_HEAD"));
1588 unlink(git_path("REVERT_HEAD"));
1589 unlink(git_path("MERGE_HEAD"));
1590 unlink(git_path("MERGE_MSG"));
1591 unlink(git_path("MERGE_MODE"));
1592 unlink(git_path("SQUASH_MSG"));
1594 if (commit_index_files())
1595 die (_("Repository has been updated, but unable to write\n"
1596 "new_index file. Check that disk is not full or quota is\n"
1597 "not exceeded, and then \"git reset HEAD\" to recover."));
1599 rerere(0);
1600 run_hook(get_index_file(), "post-commit", NULL);
1601 if (amend && !no_post_rewrite) {
1602 struct notes_rewrite_cfg *cfg;
1603 cfg = init_copy_notes_for_rewrite("amend");
1604 if (cfg) {
1605 /* we are amending, so current_head is not NULL */
1606 copy_note_for_rewrite(cfg, current_head->object.sha1, sha1);
1607 finish_copy_notes_for_rewrite(cfg);
1609 run_rewrite_hook(current_head->object.sha1, sha1);
1611 if (!quiet)
1612 print_summary(prefix, sha1, !current_head);
1614 return 0;