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