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