t9402: Add missing &&; Code style
[git/raj.git] / builtin / commit.c
bloba17a5df4494e9414bd4b04fd008671d84d914ca0
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] [--] <filepattern>..."),
35 NULL
38 static const char * const builtin_status_usage[] = {
39 N_("git status [options] [--] <filepattern>..."),
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 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;
111 static const char *only_include_assumed;
112 static struct strbuf message = STRBUF_INIT;
114 static enum {
115 STATUS_FORMAT_LONG,
116 STATUS_FORMAT_SHORT,
117 STATUS_FORMAT_PORCELAIN
118 } status_format = STATUS_FORMAT_LONG;
120 static int opt_parse_m(const struct option *opt, const char *arg, int unset)
122 struct strbuf *buf = opt->value;
123 if (unset)
124 strbuf_setlen(buf, 0);
125 else {
126 strbuf_addstr(buf, arg);
127 strbuf_addstr(buf, "\n\n");
129 return 0;
132 static void determine_whence(struct wt_status *s)
134 if (file_exists(git_path("MERGE_HEAD")))
135 whence = FROM_MERGE;
136 else if (file_exists(git_path("CHERRY_PICK_HEAD")))
137 whence = FROM_CHERRY_PICK;
138 else
139 whence = FROM_COMMIT;
140 if (s)
141 s->whence = whence;
144 static void rollback_index_files(void)
146 switch (commit_style) {
147 case COMMIT_AS_IS:
148 break; /* nothing to do */
149 case COMMIT_NORMAL:
150 rollback_lock_file(&index_lock);
151 break;
152 case COMMIT_PARTIAL:
153 rollback_lock_file(&index_lock);
154 rollback_lock_file(&false_lock);
155 break;
159 static int commit_index_files(void)
161 int err = 0;
163 switch (commit_style) {
164 case COMMIT_AS_IS:
165 break; /* nothing to do */
166 case COMMIT_NORMAL:
167 err = commit_lock_file(&index_lock);
168 break;
169 case COMMIT_PARTIAL:
170 err = commit_lock_file(&index_lock);
171 rollback_lock_file(&false_lock);
172 break;
175 return err;
179 * Take a union of paths in the index and the named tree (typically, "HEAD"),
180 * and return the paths that match the given pattern in list.
182 static int list_paths(struct string_list *list, const char *with_tree,
183 const char *prefix, const char **pattern)
185 int i;
186 char *m;
188 if (!pattern)
189 return 0;
191 for (i = 0; pattern[i]; i++)
193 m = xcalloc(1, i);
195 if (with_tree) {
196 char *max_prefix = common_prefix(pattern);
197 overlay_tree_on_cache(with_tree, max_prefix ? max_prefix : prefix);
198 free(max_prefix);
201 for (i = 0; i < active_nr; i++) {
202 struct cache_entry *ce = active_cache[i];
203 struct string_list_item *item;
205 if (ce->ce_flags & CE_UPDATE)
206 continue;
207 if (!match_pathspec(pattern, ce->name, ce_namelen(ce), 0, m))
208 continue;
209 item = string_list_insert(list, ce->name);
210 if (ce_skip_worktree(ce))
211 item->util = item; /* better a valid pointer than a fake one */
214 return report_path_error(m, pattern, prefix);
217 static void add_remove_files(struct string_list *list)
219 int i;
220 for (i = 0; i < list->nr; i++) {
221 struct stat st;
222 struct string_list_item *p = &(list->items[i]);
224 /* p->util is skip-worktree */
225 if (p->util)
226 continue;
228 if (!lstat(p->string, &st)) {
229 if (add_to_cache(p->string, &st, 0))
230 die(_("updating files failed"));
231 } else
232 remove_file_from_cache(p->string);
236 static void create_base_index(const struct commit *current_head)
238 struct tree *tree;
239 struct unpack_trees_options opts;
240 struct tree_desc t;
242 if (!current_head) {
243 discard_cache();
244 return;
247 memset(&opts, 0, sizeof(opts));
248 opts.head_idx = 1;
249 opts.index_only = 1;
250 opts.merge = 1;
251 opts.src_index = &the_index;
252 opts.dst_index = &the_index;
254 opts.fn = oneway_merge;
255 tree = parse_tree_indirect(current_head->object.sha1);
256 if (!tree)
257 die(_("failed to unpack HEAD tree object"));
258 parse_tree(tree);
259 init_tree_desc(&t, tree->buffer, tree->size);
260 if (unpack_trees(1, &t, &opts))
261 exit(128); /* We've already reported the error, finish dying */
264 static void refresh_cache_or_die(int refresh_flags)
267 * refresh_flags contains REFRESH_QUIET, so the only errors
268 * are for unmerged entries.
270 if (refresh_cache(refresh_flags | REFRESH_IN_PORCELAIN))
271 die_resolve_conflict("commit");
274 static char *prepare_index(int argc, const char **argv, const char *prefix,
275 const struct commit *current_head, int is_status)
277 int fd;
278 struct string_list partial;
279 const char **pathspec = NULL;
280 char *old_index_env = NULL;
281 int refresh_flags = REFRESH_QUIET;
283 if (is_status)
284 refresh_flags |= REFRESH_UNMERGED;
286 if (*argv)
287 pathspec = get_pathspec(prefix, argv);
289 if (read_cache_preload(pathspec) < 0)
290 die(_("index file corrupt"));
292 if (interactive) {
293 fd = hold_locked_index(&index_lock, 1);
295 refresh_cache_or_die(refresh_flags);
297 if (write_cache(fd, active_cache, active_nr) ||
298 close_lock_file(&index_lock))
299 die(_("unable to create temporary index"));
301 old_index_env = getenv(INDEX_ENVIRONMENT);
302 setenv(INDEX_ENVIRONMENT, index_lock.filename, 1);
304 if (interactive_add(argc, argv, prefix, patch_interactive) != 0)
305 die(_("interactive add failed"));
307 if (old_index_env && *old_index_env)
308 setenv(INDEX_ENVIRONMENT, old_index_env, 1);
309 else
310 unsetenv(INDEX_ENVIRONMENT);
312 discard_cache();
313 read_cache_from(index_lock.filename);
315 commit_style = COMMIT_NORMAL;
316 return index_lock.filename;
320 * Non partial, non as-is commit.
322 * (1) get the real index;
323 * (2) update the_index as necessary;
324 * (3) write the_index out to the real index (still locked);
325 * (4) return the name of the locked index file.
327 * The caller should run hooks on the locked real index, and
328 * (A) if all goes well, commit the real index;
329 * (B) on failure, rollback the real index.
331 if (all || (also && pathspec && *pathspec)) {
332 fd = hold_locked_index(&index_lock, 1);
333 add_files_to_cache(also ? prefix : NULL, pathspec, 0);
334 refresh_cache_or_die(refresh_flags);
335 update_main_cache_tree(WRITE_TREE_SILENT);
336 if (write_cache(fd, active_cache, active_nr) ||
337 close_lock_file(&index_lock))
338 die(_("unable to write new_index file"));
339 commit_style = COMMIT_NORMAL;
340 return index_lock.filename;
344 * As-is commit.
346 * (1) return the name of the real index file.
348 * The caller should run hooks on the real index,
349 * and create commit from the_index.
350 * We still need to refresh the index here.
352 if (!only && (!pathspec || !*pathspec)) {
353 fd = hold_locked_index(&index_lock, 1);
354 refresh_cache_or_die(refresh_flags);
355 if (active_cache_changed) {
356 update_main_cache_tree(WRITE_TREE_SILENT);
357 if (write_cache(fd, active_cache, active_nr) ||
358 commit_locked_index(&index_lock))
359 die(_("unable to write new_index file"));
360 } else {
361 rollback_lock_file(&index_lock);
363 commit_style = COMMIT_AS_IS;
364 return get_index_file();
368 * A partial commit.
370 * (0) find the set of affected paths;
371 * (1) get lock on the real index file;
372 * (2) update the_index with the given paths;
373 * (3) write the_index out to the real index (still locked);
374 * (4) get lock on the false index file;
375 * (5) reset the_index from HEAD;
376 * (6) update the_index the same way as (2);
377 * (7) write the_index out to the false index file;
378 * (8) return the name of the false index file (still locked);
380 * The caller should run hooks on the locked false index, and
381 * create commit from it. Then
382 * (A) if all goes well, commit the real index;
383 * (B) on failure, rollback the real index;
384 * In either case, rollback the false index.
386 commit_style = COMMIT_PARTIAL;
388 if (whence != FROM_COMMIT) {
389 if (whence == FROM_MERGE)
390 die(_("cannot do a partial commit during a merge."));
391 else if (whence == FROM_CHERRY_PICK)
392 die(_("cannot do a partial commit during a cherry-pick."));
395 memset(&partial, 0, sizeof(partial));
396 partial.strdup_strings = 1;
397 if (list_paths(&partial, !current_head ? NULL : "HEAD", prefix, pathspec))
398 exit(1);
400 discard_cache();
401 if (read_cache() < 0)
402 die(_("cannot read the index"));
404 fd = hold_locked_index(&index_lock, 1);
405 add_remove_files(&partial);
406 refresh_cache(REFRESH_QUIET);
407 if (write_cache(fd, active_cache, active_nr) ||
408 close_lock_file(&index_lock))
409 die(_("unable to write new_index file"));
411 fd = hold_lock_file_for_update(&false_lock,
412 git_path("next-index-%"PRIuMAX,
413 (uintmax_t) getpid()),
414 LOCK_DIE_ON_ERROR);
416 create_base_index(current_head);
417 add_remove_files(&partial);
418 refresh_cache(REFRESH_QUIET);
420 if (write_cache(fd, active_cache, active_nr) ||
421 close_lock_file(&false_lock))
422 die(_("unable to write temporary index file"));
424 discard_cache();
425 read_cache_from(false_lock.filename);
427 return false_lock.filename;
430 static int run_status(FILE *fp, const char *index_file, const char *prefix, int nowarn,
431 struct wt_status *s)
433 unsigned char sha1[20];
435 if (s->relative_paths)
436 s->prefix = prefix;
438 if (amend) {
439 s->amend = 1;
440 s->reference = "HEAD^1";
442 s->verbose = verbose;
443 s->index_file = index_file;
444 s->fp = fp;
445 s->nowarn = nowarn;
446 s->is_initial = get_sha1(s->reference, sha1) ? 1 : 0;
448 wt_status_collect(s);
450 switch (status_format) {
451 case STATUS_FORMAT_SHORT:
452 wt_shortstatus_print(s);
453 break;
454 case STATUS_FORMAT_PORCELAIN:
455 wt_porcelain_print(s);
456 break;
457 case STATUS_FORMAT_LONG:
458 wt_status_print(s);
459 break;
462 return s->commitable;
465 static int is_a_merge(const struct commit *current_head)
467 return !!(current_head->parents && current_head->parents->next);
470 static void export_one(const char *var, const char *s, const char *e, int hack)
472 struct strbuf buf = STRBUF_INIT;
473 if (hack)
474 strbuf_addch(&buf, hack);
475 strbuf_addf(&buf, "%.*s", (int)(e - s), s);
476 setenv(var, buf.buf, 1);
477 strbuf_release(&buf);
480 static int sane_ident_split(struct ident_split *person)
482 if (!person->name_begin || !person->name_end ||
483 person->name_begin == person->name_end)
484 return 0; /* no human readable name */
485 if (!person->mail_begin || !person->mail_end ||
486 person->mail_begin == person->mail_end)
487 return 0; /* no usable mail */
488 if (!person->date_begin || !person->date_end ||
489 !person->tz_begin || !person->tz_end)
490 return 0;
491 return 1;
494 static void determine_author_info(struct strbuf *author_ident)
496 char *name, *email, *date;
497 struct ident_split author;
499 name = getenv("GIT_AUTHOR_NAME");
500 email = getenv("GIT_AUTHOR_EMAIL");
501 date = getenv("GIT_AUTHOR_DATE");
503 if (author_message) {
504 const char *a, *lb, *rb, *eol;
505 size_t len;
507 a = strstr(author_message_buffer, "\nauthor ");
508 if (!a)
509 die(_("invalid commit: %s"), author_message);
511 lb = strchrnul(a + strlen("\nauthor "), '<');
512 rb = strchrnul(lb, '>');
513 eol = strchrnul(rb, '\n');
514 if (!*lb || !*rb || !*eol)
515 die(_("invalid commit: %s"), author_message);
517 if (lb == a + strlen("\nauthor "))
518 /* \nauthor <foo@example.com> */
519 name = xcalloc(1, 1);
520 else
521 name = xmemdupz(a + strlen("\nauthor "),
522 (lb - strlen(" ") -
523 (a + strlen("\nauthor "))));
524 email = xmemdupz(lb + strlen("<"), rb - (lb + strlen("<")));
525 date = xmemdupz(rb + strlen("> "), eol - (rb + strlen("> ")));
526 len = eol - (rb + strlen("> "));
527 date = xmalloc(len + 2);
528 *date = '@';
529 memcpy(date + 1, rb + strlen("> "), len);
530 date[len + 1] = '\0';
533 if (force_author) {
534 const char *lb = strstr(force_author, " <");
535 const char *rb = strchr(force_author, '>');
537 if (!lb || !rb)
538 die(_("malformed --author parameter"));
539 name = xstrndup(force_author, lb - force_author);
540 email = xstrndup(lb + 2, rb - (lb + 2));
543 if (force_date)
544 date = force_date;
545 strbuf_addstr(author_ident, fmt_ident(name, email, date, IDENT_STRICT));
546 if (!split_ident_line(&author, author_ident->buf, author_ident->len) &&
547 sane_ident_split(&author)) {
548 export_one("GIT_AUTHOR_NAME", author.name_begin, author.name_end, 0);
549 export_one("GIT_AUTHOR_EMAIL", author.mail_begin, author.mail_end, 0);
550 export_one("GIT_AUTHOR_DATE", author.date_begin, author.tz_end, '@');
554 static char *cut_ident_timestamp_part(char *string)
556 char *ket = strrchr(string, '>');
557 if (!ket || ket[1] != ' ')
558 die(_("Malformed ident string: '%s'"), string);
559 *++ket = '\0';
560 return ket;
563 static int prepare_to_commit(const char *index_file, const char *prefix,
564 struct commit *current_head,
565 struct wt_status *s,
566 struct strbuf *author_ident)
568 struct stat statbuf;
569 struct strbuf committer_ident = STRBUF_INIT;
570 int commitable, saved_color_setting;
571 struct strbuf sb = STRBUF_INIT;
572 char *buffer;
573 const char *hook_arg1 = NULL;
574 const char *hook_arg2 = NULL;
575 int ident_shown = 0;
576 int clean_message_contents = (cleanup_mode != CLEANUP_NONE);
578 /* This checks and barfs if author is badly specified */
579 determine_author_info(author_ident);
581 if (!no_verify && run_hook(index_file, "pre-commit", NULL))
582 return 0;
584 if (squash_message) {
586 * Insert the proper subject line before other commit
587 * message options add their content.
589 if (use_message && !strcmp(use_message, squash_message))
590 strbuf_addstr(&sb, "squash! ");
591 else {
592 struct pretty_print_context ctx = {0};
593 struct commit *c;
594 c = lookup_commit_reference_by_name(squash_message);
595 if (!c)
596 die(_("could not lookup commit %s"), squash_message);
597 ctx.output_encoding = get_commit_output_encoding();
598 format_commit_message(c, "squash! %s\n\n", &sb,
599 &ctx);
603 if (message.len) {
604 strbuf_addbuf(&sb, &message);
605 hook_arg1 = "message";
606 } else if (logfile && !strcmp(logfile, "-")) {
607 if (isatty(0))
608 fprintf(stderr, _("(reading log message from standard input)\n"));
609 if (strbuf_read(&sb, 0, 0) < 0)
610 die_errno(_("could not read log from standard input"));
611 hook_arg1 = "message";
612 } else if (logfile) {
613 if (strbuf_read_file(&sb, logfile, 0) < 0)
614 die_errno(_("could not read log file '%s'"),
615 logfile);
616 hook_arg1 = "message";
617 } else if (use_message) {
618 buffer = strstr(use_message_buffer, "\n\n");
619 if (!use_editor && (!buffer || buffer[2] == '\0'))
620 die(_("commit has empty message"));
621 strbuf_add(&sb, buffer + 2, strlen(buffer + 2));
622 hook_arg1 = "commit";
623 hook_arg2 = use_message;
624 } else if (fixup_message) {
625 struct pretty_print_context ctx = {0};
626 struct commit *commit;
627 commit = lookup_commit_reference_by_name(fixup_message);
628 if (!commit)
629 die(_("could not lookup commit %s"), fixup_message);
630 ctx.output_encoding = get_commit_output_encoding();
631 format_commit_message(commit, "fixup! %s\n\n",
632 &sb, &ctx);
633 hook_arg1 = "message";
634 } else if (!stat(git_path("MERGE_MSG"), &statbuf)) {
635 if (strbuf_read_file(&sb, git_path("MERGE_MSG"), 0) < 0)
636 die_errno(_("could not read MERGE_MSG"));
637 hook_arg1 = "merge";
638 } else if (!stat(git_path("SQUASH_MSG"), &statbuf)) {
639 if (strbuf_read_file(&sb, git_path("SQUASH_MSG"), 0) < 0)
640 die_errno(_("could not read SQUASH_MSG"));
641 hook_arg1 = "squash";
642 } else if (template_file) {
643 if (strbuf_read_file(&sb, template_file, 0) < 0)
644 die_errno(_("could not read '%s'"), template_file);
645 hook_arg1 = "template";
646 clean_message_contents = 0;
650 * The remaining cases don't modify the template message, but
651 * just set the argument(s) to the prepare-commit-msg hook.
653 else if (whence == FROM_MERGE)
654 hook_arg1 = "merge";
655 else if (whence == FROM_CHERRY_PICK) {
656 hook_arg1 = "commit";
657 hook_arg2 = "CHERRY_PICK_HEAD";
660 if (squash_message) {
662 * If squash_commit was used for the commit subject,
663 * then we're possibly hijacking other commit log options.
664 * Reset the hook args to tell the real story.
666 hook_arg1 = "message";
667 hook_arg2 = "";
670 s->fp = fopen(git_path(commit_editmsg), "w");
671 if (s->fp == NULL)
672 die_errno(_("could not open '%s'"), git_path(commit_editmsg));
674 if (clean_message_contents)
675 stripspace(&sb, 0);
677 if (signoff) {
679 * See if we have a Conflicts: block at the end. If yes, count
680 * its size, so we can ignore it.
682 int ignore_footer = 0;
683 int i, eol, previous = 0;
684 const char *nl;
686 for (i = 0; i < sb.len; i++) {
687 nl = memchr(sb.buf + i, '\n', sb.len - i);
688 if (nl)
689 eol = nl - sb.buf;
690 else
691 eol = sb.len;
692 if (!prefixcmp(sb.buf + previous, "\nConflicts:\n")) {
693 ignore_footer = sb.len - previous;
694 break;
696 while (i < eol)
697 i++;
698 previous = eol;
701 append_signoff(&sb, ignore_footer);
704 if (fwrite(sb.buf, 1, sb.len, s->fp) < sb.len)
705 die_errno(_("could not write commit template"));
707 strbuf_release(&sb);
709 /* This checks if committer ident is explicitly given */
710 strbuf_addstr(&committer_ident, git_committer_info(IDENT_STRICT));
711 if (use_editor && include_status) {
712 char *ai_tmp, *ci_tmp;
713 if (whence != FROM_COMMIT)
714 status_printf_ln(s, GIT_COLOR_NORMAL,
715 whence == FROM_MERGE
716 ? _("\n"
717 "It looks like you may be committing a merge.\n"
718 "If this is not correct, please remove the file\n"
719 " %s\n"
720 "and try again.\n")
721 : _("\n"
722 "It looks like you may be committing a cherry-pick.\n"
723 "If this is not correct, please remove the file\n"
724 " %s\n"
725 "and try again.\n"),
726 git_path(whence == FROM_MERGE
727 ? "MERGE_HEAD"
728 : "CHERRY_PICK_HEAD"));
730 fprintf(s->fp, "\n");
731 if (cleanup_mode == CLEANUP_ALL)
732 status_printf(s, GIT_COLOR_NORMAL,
733 _("Please enter the commit message for your changes."
734 " Lines starting\nwith '#' will be ignored, and an empty"
735 " message aborts the commit.\n"));
736 else /* CLEANUP_SPACE, that is. */
737 status_printf(s, GIT_COLOR_NORMAL,
738 _("Please enter the commit message for your changes."
739 " Lines starting\n"
740 "with '#' will be kept; you may remove them"
741 " yourself if you want to.\n"
742 "An empty message aborts the commit.\n"));
743 if (only_include_assumed)
744 status_printf_ln(s, GIT_COLOR_NORMAL,
745 "%s", only_include_assumed);
747 ai_tmp = cut_ident_timestamp_part(author_ident->buf);
748 ci_tmp = cut_ident_timestamp_part(committer_ident.buf);
749 if (strcmp(author_ident->buf, committer_ident.buf))
750 status_printf_ln(s, GIT_COLOR_NORMAL,
751 _("%s"
752 "Author: %s"),
753 ident_shown++ ? "" : "\n",
754 author_ident->buf);
756 if (!user_ident_sufficiently_given())
757 status_printf_ln(s, GIT_COLOR_NORMAL,
758 _("%s"
759 "Committer: %s"),
760 ident_shown++ ? "" : "\n",
761 committer_ident.buf);
763 if (ident_shown)
764 status_printf_ln(s, GIT_COLOR_NORMAL, "");
766 saved_color_setting = s->use_color;
767 s->use_color = 0;
768 commitable = run_status(s->fp, index_file, prefix, 1, s);
769 s->use_color = saved_color_setting;
771 *ai_tmp = ' ';
772 *ci_tmp = ' ';
773 } else {
774 unsigned char sha1[20];
775 const char *parent = "HEAD";
777 if (!active_nr && read_cache() < 0)
778 die(_("Cannot read index"));
780 if (amend)
781 parent = "HEAD^1";
783 if (get_sha1(parent, sha1))
784 commitable = !!active_nr;
785 else
786 commitable = index_differs_from(parent, 0);
788 strbuf_release(&committer_ident);
790 fclose(s->fp);
793 * Reject an attempt to record a non-merge empty commit without
794 * explicit --allow-empty. In the cherry-pick case, it may be
795 * empty due to conflict resolution, which the user should okay.
797 if (!commitable && whence != FROM_MERGE && !allow_empty &&
798 !(amend && is_a_merge(current_head))) {
799 run_status(stdout, index_file, prefix, 0, s);
800 if (amend)
801 fputs(_(empty_amend_advice), stderr);
802 else if (whence == FROM_CHERRY_PICK)
803 fputs(_(empty_cherry_pick_advice), stderr);
804 return 0;
808 * Re-read the index as pre-commit hook could have updated it,
809 * and write it out as a tree. We must do this before we invoke
810 * the editor and after we invoke run_status above.
812 discard_cache();
813 read_cache_from(index_file);
814 if (update_main_cache_tree(0)) {
815 error(_("Error building trees"));
816 return 0;
819 if (run_hook(index_file, "prepare-commit-msg",
820 git_path(commit_editmsg), hook_arg1, hook_arg2, NULL))
821 return 0;
823 if (use_editor) {
824 char index[PATH_MAX];
825 const char *env[2] = { NULL };
826 env[0] = index;
827 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
828 if (launch_editor(git_path(commit_editmsg), NULL, env)) {
829 fprintf(stderr,
830 _("Please supply the message using either -m or -F option.\n"));
831 exit(1);
835 if (!no_verify &&
836 run_hook(index_file, "commit-msg", git_path(commit_editmsg), NULL)) {
837 return 0;
840 return 1;
843 static int rest_is_empty(struct strbuf *sb, int start)
845 int i, eol;
846 const char *nl;
848 /* Check if the rest is just whitespace and Signed-of-by's. */
849 for (i = start; i < sb->len; i++) {
850 nl = memchr(sb->buf + i, '\n', sb->len - i);
851 if (nl)
852 eol = nl - sb->buf;
853 else
854 eol = sb->len;
856 if (strlen(sign_off_header) <= eol - i &&
857 !prefixcmp(sb->buf + i, sign_off_header)) {
858 i = eol;
859 continue;
861 while (i < eol)
862 if (!isspace(sb->buf[i++]))
863 return 0;
866 return 1;
870 * Find out if the message in the strbuf contains only whitespace and
871 * Signed-off-by lines.
873 static int message_is_empty(struct strbuf *sb)
875 if (cleanup_mode == CLEANUP_NONE && sb->len)
876 return 0;
877 return rest_is_empty(sb, 0);
881 * See if the user edited the message in the editor or left what
882 * was in the template intact
884 static int template_untouched(struct strbuf *sb)
886 struct strbuf tmpl = STRBUF_INIT;
887 char *start;
889 if (cleanup_mode == CLEANUP_NONE && sb->len)
890 return 0;
892 if (!template_file || strbuf_read_file(&tmpl, template_file, 0) <= 0)
893 return 0;
895 stripspace(&tmpl, cleanup_mode == CLEANUP_ALL);
896 start = (char *)skip_prefix(sb->buf, tmpl.buf);
897 if (!start)
898 start = sb->buf;
899 strbuf_release(&tmpl);
900 return rest_is_empty(sb, start - sb->buf);
903 static const char *find_author_by_nickname(const char *name)
905 struct rev_info revs;
906 struct commit *commit;
907 struct strbuf buf = STRBUF_INIT;
908 const char *av[20];
909 int ac = 0;
911 init_revisions(&revs, NULL);
912 strbuf_addf(&buf, "--author=%s", name);
913 av[++ac] = "--all";
914 av[++ac] = "-i";
915 av[++ac] = buf.buf;
916 av[++ac] = NULL;
917 setup_revisions(ac, av, &revs, NULL);
918 prepare_revision_walk(&revs);
919 commit = get_revision(&revs);
920 if (commit) {
921 struct pretty_print_context ctx = {0};
922 ctx.date_mode = DATE_NORMAL;
923 strbuf_release(&buf);
924 format_commit_message(commit, "%an <%ae>", &buf, &ctx);
925 return strbuf_detach(&buf, NULL);
927 die(_("No existing author found with '%s'"), name);
931 static void handle_untracked_files_arg(struct wt_status *s)
933 if (!untracked_files_arg)
934 ; /* default already initialized */
935 else if (!strcmp(untracked_files_arg, "no"))
936 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
937 else if (!strcmp(untracked_files_arg, "normal"))
938 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
939 else if (!strcmp(untracked_files_arg, "all"))
940 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
941 else
942 die(_("Invalid untracked files mode '%s'"), untracked_files_arg);
945 static const char *read_commit_message(const char *name)
947 const char *out_enc, *out;
948 struct commit *commit;
950 commit = lookup_commit_reference_by_name(name);
951 if (!commit)
952 die(_("could not lookup commit %s"), name);
953 out_enc = get_commit_output_encoding();
954 out = logmsg_reencode(commit, out_enc);
957 * If we failed to reencode the buffer, just copy it
958 * byte for byte so the user can try to fix it up.
959 * This also handles the case where input and output
960 * encodings are identical.
962 if (out == NULL)
963 out = xstrdup(commit->buffer);
964 return out;
967 static int parse_and_validate_options(int argc, const char *argv[],
968 const struct option *options,
969 const char * const usage[],
970 const char *prefix,
971 struct commit *current_head,
972 struct wt_status *s)
974 int f = 0;
976 argc = parse_options(argc, argv, prefix, options, usage, 0);
978 if (force_author && !strchr(force_author, '>'))
979 force_author = find_author_by_nickname(force_author);
981 if (force_author && renew_authorship)
982 die(_("Using both --reset-author and --author does not make sense"));
984 if (logfile || message.len || use_message || fixup_message)
985 use_editor = 0;
986 if (0 <= edit_flag)
987 use_editor = edit_flag;
988 if (!use_editor)
989 setenv("GIT_EDITOR", ":", 1);
991 /* Sanity check options */
992 if (amend && !current_head)
993 die(_("You have nothing to amend."));
994 if (amend && whence != FROM_COMMIT) {
995 if (whence == FROM_MERGE)
996 die(_("You are in the middle of a merge -- cannot amend."));
997 else if (whence == FROM_CHERRY_PICK)
998 die(_("You are in the middle of a cherry-pick -- cannot amend."));
1000 if (fixup_message && squash_message)
1001 die(_("Options --squash and --fixup cannot be used together"));
1002 if (use_message)
1003 f++;
1004 if (edit_message)
1005 f++;
1006 if (fixup_message)
1007 f++;
1008 if (logfile)
1009 f++;
1010 if (f > 1)
1011 die(_("Only one of -c/-C/-F/--fixup can be used."));
1012 if (message.len && f > 0)
1013 die((_("Option -m cannot be combined with -c/-C/-F/--fixup.")));
1014 if (f || message.len)
1015 template_file = NULL;
1016 if (edit_message)
1017 use_message = edit_message;
1018 if (amend && !use_message && !fixup_message)
1019 use_message = "HEAD";
1020 if (!use_message && whence != FROM_CHERRY_PICK && renew_authorship)
1021 die(_("--reset-author can be used only with -C, -c or --amend."));
1022 if (use_message) {
1023 use_message_buffer = read_commit_message(use_message);
1024 if (!renew_authorship) {
1025 author_message = use_message;
1026 author_message_buffer = use_message_buffer;
1029 if (whence == FROM_CHERRY_PICK && !renew_authorship) {
1030 author_message = "CHERRY_PICK_HEAD";
1031 author_message_buffer = read_commit_message(author_message);
1034 if (patch_interactive)
1035 interactive = 1;
1037 if (!!also + !!only + !!all + !!interactive > 1)
1038 die(_("Only one of --include/--only/--all/--interactive/--patch can be used."));
1039 if (argc == 0 && (also || (only && !amend)))
1040 die(_("No paths with --include/--only does not make sense."));
1041 if (argc == 0 && only && amend)
1042 only_include_assumed = _("Clever... amending the last one with dirty index.");
1043 if (argc > 0 && !also && !only)
1044 only_include_assumed = _("Explicit paths specified without -i nor -o; assuming --only paths...");
1045 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
1046 cleanup_mode = use_editor ? CLEANUP_ALL : CLEANUP_SPACE;
1047 else if (!strcmp(cleanup_arg, "verbatim"))
1048 cleanup_mode = CLEANUP_NONE;
1049 else if (!strcmp(cleanup_arg, "whitespace"))
1050 cleanup_mode = CLEANUP_SPACE;
1051 else if (!strcmp(cleanup_arg, "strip"))
1052 cleanup_mode = CLEANUP_ALL;
1053 else
1054 die(_("Invalid cleanup mode %s"), cleanup_arg);
1056 handle_untracked_files_arg(s);
1058 if (all && argc > 0)
1059 die(_("Paths with -a does not make sense."));
1061 if (s->null_termination && status_format == STATUS_FORMAT_LONG)
1062 status_format = STATUS_FORMAT_PORCELAIN;
1063 if (status_format != STATUS_FORMAT_LONG)
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.color") || !strcmp(k, "color.status")) {
1116 s->use_color = git_config_colorbool(k, v);
1117 return 0;
1119 if (!prefixcmp(k, "status.color.") || !prefixcmp(k, "color.status.")) {
1120 int slot = parse_status_slot(k, 13);
1121 if (slot < 0)
1122 return 0;
1123 if (!v)
1124 return config_error_nonbool(k);
1125 color_parse(v, k, s->color_palette[slot]);
1126 return 0;
1128 if (!strcmp(k, "status.relativepaths")) {
1129 s->relative_paths = git_config_bool(k, v);
1130 return 0;
1132 if (!strcmp(k, "status.showuntrackedfiles")) {
1133 if (!v)
1134 return config_error_nonbool(k);
1135 else if (!strcmp(v, "no"))
1136 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
1137 else if (!strcmp(v, "normal"))
1138 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
1139 else if (!strcmp(v, "all"))
1140 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
1141 else
1142 return error(_("Invalid untracked files mode '%s'"), v);
1143 return 0;
1145 return git_diff_ui_config(k, v, NULL);
1148 int cmd_status(int argc, const char **argv, const char *prefix)
1150 static struct wt_status s;
1151 int fd;
1152 unsigned char sha1[20];
1153 static struct option builtin_status_options[] = {
1154 OPT__VERBOSE(&verbose, N_("be verbose")),
1155 OPT_SET_INT('s', "short", &status_format,
1156 N_("show status concisely"), STATUS_FORMAT_SHORT),
1157 OPT_BOOLEAN('b', "branch", &s.show_branch,
1158 N_("show branch information")),
1159 OPT_SET_INT(0, "porcelain", &status_format,
1160 N_("machine-readable output"),
1161 STATUS_FORMAT_PORCELAIN),
1162 OPT_BOOLEAN('z', "null", &s.null_termination,
1163 N_("terminate entries with NUL")),
1164 { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg,
1165 N_("mode"),
1166 N_("show untracked files, optional modes: all, normal, no. (Default: all)"),
1167 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1168 OPT_BOOLEAN(0, "ignored", &show_ignored_in_status,
1169 N_("show ignored files")),
1170 { OPTION_STRING, 0, "ignore-submodules", &ignore_submodule_arg, N_("when"),
1171 N_("ignore changes to submodules, optional when: all, dirty, untracked. (Default: all)"),
1172 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1173 OPT_COLUMN(0, "column", &s.colopts, N_("list untracked files in columns")),
1174 OPT_END(),
1177 if (argc == 2 && !strcmp(argv[1], "-h"))
1178 usage_with_options(builtin_status_usage, builtin_status_options);
1180 wt_status_prepare(&s);
1181 gitmodules_config();
1182 git_config(git_status_config, &s);
1183 determine_whence(&s);
1184 argc = parse_options(argc, argv, prefix,
1185 builtin_status_options,
1186 builtin_status_usage, 0);
1187 finalize_colopts(&s.colopts, -1);
1189 if (s.null_termination && status_format == STATUS_FORMAT_LONG)
1190 status_format = STATUS_FORMAT_PORCELAIN;
1192 handle_untracked_files_arg(&s);
1193 if (show_ignored_in_status)
1194 s.show_ignored_files = 1;
1195 if (*argv)
1196 s.pathspec = get_pathspec(prefix, argv);
1198 read_cache_preload(s.pathspec);
1199 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, s.pathspec, NULL, NULL);
1201 fd = hold_locked_index(&index_lock, 0);
1202 if (0 <= fd)
1203 update_index_if_able(&the_index, &index_lock);
1205 s.is_initial = get_sha1(s.reference, sha1) ? 1 : 0;
1206 s.ignore_submodule_arg = ignore_submodule_arg;
1207 wt_status_collect(&s);
1209 if (s.relative_paths)
1210 s.prefix = prefix;
1212 switch (status_format) {
1213 case STATUS_FORMAT_SHORT:
1214 wt_shortstatus_print(&s);
1215 break;
1216 case STATUS_FORMAT_PORCELAIN:
1217 wt_porcelain_print(&s);
1218 break;
1219 case STATUS_FORMAT_LONG:
1220 s.verbose = verbose;
1221 s.ignore_submodule_arg = ignore_submodule_arg;
1222 wt_status_print(&s);
1223 break;
1225 return 0;
1228 static void print_summary(const char *prefix, const unsigned char *sha1,
1229 int initial_commit)
1231 struct rev_info rev;
1232 struct commit *commit;
1233 struct strbuf format = STRBUF_INIT;
1234 unsigned char junk_sha1[20];
1235 const char *head;
1236 struct pretty_print_context pctx = {0};
1237 struct strbuf author_ident = STRBUF_INIT;
1238 struct strbuf committer_ident = STRBUF_INIT;
1240 commit = lookup_commit(sha1);
1241 if (!commit)
1242 die(_("couldn't look up newly created commit"));
1243 if (!commit || parse_commit(commit))
1244 die(_("could not parse newly created commit"));
1246 strbuf_addstr(&format, "format:%h] %s");
1248 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1249 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1250 if (strbuf_cmp(&author_ident, &committer_ident)) {
1251 strbuf_addstr(&format, "\n Author: ");
1252 strbuf_addbuf_percentquote(&format, &author_ident);
1254 if (!user_ident_sufficiently_given()) {
1255 strbuf_addstr(&format, "\n Committer: ");
1256 strbuf_addbuf_percentquote(&format, &committer_ident);
1257 if (advice_implicit_identity) {
1258 strbuf_addch(&format, '\n');
1259 strbuf_addstr(&format, _(implicit_ident_advice));
1262 strbuf_release(&author_ident);
1263 strbuf_release(&committer_ident);
1265 init_revisions(&rev, prefix);
1266 setup_revisions(0, NULL, &rev, NULL);
1268 rev.diff = 1;
1269 rev.diffopt.output_format =
1270 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1272 rev.verbose_header = 1;
1273 rev.show_root_diff = 1;
1274 get_commit_format(format.buf, &rev);
1275 rev.always_show_header = 0;
1276 rev.diffopt.detect_rename = 1;
1277 rev.diffopt.break_opt = 0;
1278 diff_setup_done(&rev.diffopt);
1280 head = resolve_ref_unsafe("HEAD", junk_sha1, 0, NULL);
1281 printf("[%s%s ",
1282 !prefixcmp(head, "refs/heads/") ?
1283 head + 11 :
1284 !strcmp(head, "HEAD") ?
1285 _("detached HEAD") :
1286 head,
1287 initial_commit ? _(" (root-commit)") : "");
1289 if (!log_tree_commit(&rev, commit)) {
1290 rev.always_show_header = 1;
1291 rev.use_terminator = 1;
1292 log_tree_commit(&rev, commit);
1295 strbuf_release(&format);
1298 static int git_commit_config(const char *k, const char *v, void *cb)
1300 struct wt_status *s = cb;
1301 int status;
1303 if (!strcmp(k, "commit.template"))
1304 return git_config_pathname(&template_file, k, v);
1305 if (!strcmp(k, "commit.status")) {
1306 include_status = git_config_bool(k, v);
1307 return 0;
1310 status = git_gpg_config(k, v, NULL);
1311 if (status)
1312 return status;
1313 return git_status_config(k, v, s);
1316 static const char post_rewrite_hook[] = "hooks/post-rewrite";
1318 static int run_rewrite_hook(const unsigned char *oldsha1,
1319 const unsigned char *newsha1)
1321 /* oldsha1 SP newsha1 LF NUL */
1322 static char buf[2*40 + 3];
1323 struct child_process proc;
1324 const char *argv[3];
1325 int code;
1326 size_t n;
1328 if (access(git_path(post_rewrite_hook), X_OK) < 0)
1329 return 0;
1331 argv[0] = git_path(post_rewrite_hook);
1332 argv[1] = "amend";
1333 argv[2] = NULL;
1335 memset(&proc, 0, sizeof(proc));
1336 proc.argv = argv;
1337 proc.in = -1;
1338 proc.stdout_to_stderr = 1;
1340 code = start_command(&proc);
1341 if (code)
1342 return code;
1343 n = snprintf(buf, sizeof(buf), "%s %s\n",
1344 sha1_to_hex(oldsha1), sha1_to_hex(newsha1));
1345 write_in_full(proc.in, buf, n);
1346 close(proc.in);
1347 return finish_command(&proc);
1350 int cmd_commit(int argc, const char **argv, const char *prefix)
1352 static struct wt_status s;
1353 static struct option builtin_commit_options[] = {
1354 OPT__QUIET(&quiet, N_("suppress summary after successful commit")),
1355 OPT__VERBOSE(&verbose, N_("show diff in commit message template")),
1357 OPT_GROUP(N_("Commit message options")),
1358 OPT_FILENAME('F', "file", &logfile, N_("read message from file")),
1359 OPT_STRING(0, "author", &force_author, N_("author"), N_("override author for commit")),
1360 OPT_STRING(0, "date", &force_date, N_("date"), N_("override date for commit")),
1361 OPT_CALLBACK('m', "message", &message, N_("message"), N_("commit message"), opt_parse_m),
1362 OPT_STRING('c', "reedit-message", &edit_message, N_("commit"), N_("reuse and edit message from specified commit")),
1363 OPT_STRING('C', "reuse-message", &use_message, N_("commit"), N_("reuse message from specified commit")),
1364 OPT_STRING(0, "fixup", &fixup_message, N_("commit"), N_("use autosquash formatted message to fixup specified commit")),
1365 OPT_STRING(0, "squash", &squash_message, N_("commit"), N_("use autosquash formatted message to squash specified commit")),
1366 OPT_BOOLEAN(0, "reset-author", &renew_authorship, N_("the commit is authored by me now (used with -C/-c/--amend)")),
1367 OPT_BOOLEAN('s', "signoff", &signoff, N_("add Signed-off-by:")),
1368 OPT_FILENAME('t', "template", &template_file, N_("use specified template file")),
1369 OPT_BOOL('e', "edit", &edit_flag, N_("force edit of commit")),
1370 OPT_STRING(0, "cleanup", &cleanup_arg, N_("default"), N_("how to strip spaces and #comments from message")),
1371 OPT_BOOLEAN(0, "status", &include_status, N_("include status in commit message template")),
1372 { OPTION_STRING, 'S', "gpg-sign", &sign_commit, N_("key id"),
1373 N_("GPG sign commit"), PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
1374 /* end commit message options */
1376 OPT_GROUP(N_("Commit contents options")),
1377 OPT_BOOLEAN('a', "all", &all, N_("commit all changed files")),
1378 OPT_BOOLEAN('i', "include", &also, N_("add specified files to index for commit")),
1379 OPT_BOOLEAN(0, "interactive", &interactive, N_("interactively add files")),
1380 OPT_BOOLEAN('p', "patch", &patch_interactive, N_("interactively add changes")),
1381 OPT_BOOLEAN('o', "only", &only, N_("commit only specified files")),
1382 OPT_BOOLEAN('n', "no-verify", &no_verify, N_("bypass pre-commit hook")),
1383 OPT_BOOLEAN(0, "dry-run", &dry_run, N_("show what would be committed")),
1384 OPT_SET_INT(0, "short", &status_format, N_("show status concisely"),
1385 STATUS_FORMAT_SHORT),
1386 OPT_BOOLEAN(0, "branch", &s.show_branch, N_("show branch information")),
1387 OPT_SET_INT(0, "porcelain", &status_format,
1388 N_("machine-readable output"), STATUS_FORMAT_PORCELAIN),
1389 OPT_BOOLEAN('z', "null", &s.null_termination,
1390 N_("terminate entries with NUL")),
1391 OPT_BOOLEAN(0, "amend", &amend, N_("amend previous commit")),
1392 OPT_BOOLEAN(0, "no-post-rewrite", &no_post_rewrite, N_("bypass post-rewrite hook")),
1393 { 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" },
1394 /* end commit contents options */
1396 { OPTION_BOOLEAN, 0, "allow-empty", &allow_empty, NULL,
1397 N_("ok to record an empty change"),
1398 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN },
1399 { OPTION_BOOLEAN, 0, "allow-empty-message", &allow_empty_message, NULL,
1400 N_("ok to record a change with an empty message"),
1401 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN },
1403 OPT_END()
1406 struct strbuf sb = STRBUF_INIT;
1407 struct strbuf author_ident = STRBUF_INIT;
1408 const char *index_file, *reflog_msg;
1409 char *nl, *p;
1410 unsigned char sha1[20];
1411 struct ref_lock *ref_lock;
1412 struct commit_list *parents = NULL, **pptr = &parents;
1413 struct stat statbuf;
1414 int allow_fast_forward = 1;
1415 struct commit *current_head = NULL;
1416 struct commit_extra_header *extra = NULL;
1418 if (argc == 2 && !strcmp(argv[1], "-h"))
1419 usage_with_options(builtin_commit_usage, builtin_commit_options);
1421 wt_status_prepare(&s);
1422 gitmodules_config();
1423 git_config(git_commit_config, &s);
1424 determine_whence(&s);
1425 s.colopts = 0;
1427 if (get_sha1("HEAD", sha1))
1428 current_head = NULL;
1429 else {
1430 current_head = lookup_commit_or_die(sha1, "HEAD");
1431 if (!current_head || parse_commit(current_head))
1432 die(_("could not parse HEAD commit"));
1434 argc = parse_and_validate_options(argc, argv, builtin_commit_options,
1435 builtin_commit_usage,
1436 prefix, current_head, &s);
1437 if (dry_run)
1438 return dry_run_commit(argc, argv, prefix, current_head, &s);
1439 index_file = prepare_index(argc, argv, prefix, current_head, 0);
1441 /* Set up everything for writing the commit object. This includes
1442 running hooks, writing the trees, and interacting with the user. */
1443 if (!prepare_to_commit(index_file, prefix,
1444 current_head, &s, &author_ident)) {
1445 rollback_index_files();
1446 return 1;
1449 /* Determine parents */
1450 reflog_msg = getenv("GIT_REFLOG_ACTION");
1451 if (!current_head) {
1452 if (!reflog_msg)
1453 reflog_msg = "commit (initial)";
1454 } else if (amend) {
1455 struct commit_list *c;
1457 if (!reflog_msg)
1458 reflog_msg = "commit (amend)";
1459 for (c = current_head->parents; c; c = c->next)
1460 pptr = &commit_list_insert(c->item, pptr)->next;
1461 } else if (whence == FROM_MERGE) {
1462 struct strbuf m = STRBUF_INIT;
1463 FILE *fp;
1465 if (!reflog_msg)
1466 reflog_msg = "commit (merge)";
1467 pptr = &commit_list_insert(current_head, pptr)->next;
1468 fp = fopen(git_path("MERGE_HEAD"), "r");
1469 if (fp == NULL)
1470 die_errno(_("could not open '%s' for reading"),
1471 git_path("MERGE_HEAD"));
1472 while (strbuf_getline(&m, fp, '\n') != EOF) {
1473 struct commit *parent;
1475 parent = get_merge_parent(m.buf);
1476 if (!parent)
1477 die(_("Corrupt MERGE_HEAD file (%s)"), m.buf);
1478 pptr = &commit_list_insert(parent, pptr)->next;
1480 fclose(fp);
1481 strbuf_release(&m);
1482 if (!stat(git_path("MERGE_MODE"), &statbuf)) {
1483 if (strbuf_read_file(&sb, git_path("MERGE_MODE"), 0) < 0)
1484 die_errno(_("could not read MERGE_MODE"));
1485 if (!strcmp(sb.buf, "no-ff"))
1486 allow_fast_forward = 0;
1488 if (allow_fast_forward)
1489 parents = reduce_heads(parents);
1490 } else {
1491 if (!reflog_msg)
1492 reflog_msg = (whence == FROM_CHERRY_PICK)
1493 ? "commit (cherry-pick)"
1494 : "commit";
1495 pptr = &commit_list_insert(current_head, pptr)->next;
1498 /* Finally, get the commit message */
1499 strbuf_reset(&sb);
1500 if (strbuf_read_file(&sb, git_path(commit_editmsg), 0) < 0) {
1501 int saved_errno = errno;
1502 rollback_index_files();
1503 die(_("could not read commit message: %s"), strerror(saved_errno));
1506 /* Truncate the message just before the diff, if any. */
1507 if (verbose) {
1508 p = strstr(sb.buf, "\ndiff --git ");
1509 if (p != NULL)
1510 strbuf_setlen(&sb, p - sb.buf + 1);
1513 if (cleanup_mode != CLEANUP_NONE)
1514 stripspace(&sb, cleanup_mode == CLEANUP_ALL);
1515 if (template_untouched(&sb) && !allow_empty_message) {
1516 rollback_index_files();
1517 fprintf(stderr, _("Aborting commit; you did not edit the message.\n"));
1518 exit(1);
1520 if (message_is_empty(&sb) && !allow_empty_message) {
1521 rollback_index_files();
1522 fprintf(stderr, _("Aborting commit due to empty commit message.\n"));
1523 exit(1);
1526 if (amend) {
1527 const char *exclude_gpgsig[2] = { "gpgsig", NULL };
1528 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1529 } else {
1530 struct commit_extra_header **tail = &extra;
1531 append_merge_tag_headers(parents, &tail);
1534 if (commit_tree_extended(&sb, active_cache_tree->sha1, parents, sha1,
1535 author_ident.buf, sign_commit, extra)) {
1536 rollback_index_files();
1537 die(_("failed to write commit object"));
1539 strbuf_release(&author_ident);
1540 free_commit_extra_headers(extra);
1542 ref_lock = lock_any_ref_for_update("HEAD",
1543 !current_head
1544 ? NULL
1545 : current_head->object.sha1,
1548 nl = strchr(sb.buf, '\n');
1549 if (nl)
1550 strbuf_setlen(&sb, nl + 1 - sb.buf);
1551 else
1552 strbuf_addch(&sb, '\n');
1553 strbuf_insert(&sb, 0, reflog_msg, strlen(reflog_msg));
1554 strbuf_insert(&sb, strlen(reflog_msg), ": ", 2);
1556 if (!ref_lock) {
1557 rollback_index_files();
1558 die(_("cannot lock HEAD ref"));
1560 if (write_ref_sha1(ref_lock, sha1, sb.buf) < 0) {
1561 rollback_index_files();
1562 die(_("cannot update HEAD ref"));
1565 unlink(git_path("CHERRY_PICK_HEAD"));
1566 unlink(git_path("REVERT_HEAD"));
1567 unlink(git_path("MERGE_HEAD"));
1568 unlink(git_path("MERGE_MSG"));
1569 unlink(git_path("MERGE_MODE"));
1570 unlink(git_path("SQUASH_MSG"));
1572 if (commit_index_files())
1573 die (_("Repository has been updated, but unable to write\n"
1574 "new_index file. Check that disk is not full or quota is\n"
1575 "not exceeded, and then \"git reset HEAD\" to recover."));
1577 rerere(0);
1578 run_hook(get_index_file(), "post-commit", NULL);
1579 if (amend && !no_post_rewrite) {
1580 struct notes_rewrite_cfg *cfg;
1581 cfg = init_copy_notes_for_rewrite("amend");
1582 if (cfg) {
1583 /* we are amending, so current_head is not NULL */
1584 copy_note_for_rewrite(cfg, current_head->object.sha1, sha1);
1585 finish_copy_notes_for_rewrite(cfg);
1587 run_rewrite_hook(current_head->object.sha1, sha1);
1589 if (!quiet)
1590 print_summary(prefix, sha1, !current_head);
1592 return 0;