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