at commit 3a055174

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 #define USE_THE_REPOSITORY_VARIABLE
9 #define DISABLE_SIGN_COMPARE_WARNINGS
10
11 #include "builtin.h"
12 #include "advice.h"
13 #include "config.h"
14 #include "lockfile.h"
15 #include "cache-tree.h"
16 #include "color.h"
17 #include "dir.h"
18 #include "editor.h"
19 #include "environment.h"
20 #include "diff.h"
21 #include "commit.h"
22 #include "add-interactive.h"
23 #include "gettext.h"
24 #include "revision.h"
25 #include "wt-status.h"
26 #include "run-command.h"
27 #include "strbuf.h"
28 #include "object-name.h"
29 #include "parse-options.h"
30 #include "path.h"
31 #include "preload-index.h"
32 #include "read-cache.h"
33 #include "repository.h"
34 #include "string-list.h"
35 #include "rerere.h"
36 #include "unpack-trees.h"
37 #include "column.h"
38 #include "sequencer.h"
39 #include "sparse-index.h"
40 #include "mailmap.h"
41 #include "help.h"
42 #include "commit-reach.h"
43 #include "commit-graph.h"
44 #include "pretty.h"
45 #include "trailer.h"
46
47 static const char * const builtin_commit_usage[] = {
48 N_("git commit [-a | --interactive | --patch] [-s] [-v] [-u[<mode>]] [--amend]\n"
49 " [--dry-run] [(-c | -C | --squash) <commit> | --fixup [(amend|reword):]<commit>]\n"
50 " [-F <file> | -m <msg>] [--reset-author] [--allow-empty]\n"
51 " [--allow-empty-message] [--no-verify] [-e] [--author=<author>]\n"
52 " [--date=<date>] [--cleanup=<mode>] [--[no-]status]\n"
53 " [-i | -o] [--pathspec-from-file=<file> [--pathspec-file-nul]]\n"
54 " [(--trailer <token>[(=|:)<value>])...] [-S[<keyid>]]\n"
55 " [--] [<pathspec>...]"),
56 NULL
57 };
58
59 static const char * const builtin_status_usage[] = {
60 N_("git status [<options>] [--] [<pathspec>...]"),
61 NULL
62 };
63
64 static const char empty_amend_advice[] =
65 N_("You asked to amend the most recent commit, but doing so would make\n"
66 "it empty. You can repeat your command with --allow-empty, or you can\n"
67 "remove the commit entirely with \"git reset HEAD^\".\n");
68
69 static const char empty_cherry_pick_advice[] =
70 N_("The previous cherry-pick is now empty, possibly due to conflict resolution.\n"
71 "If you wish to commit it anyway, use:\n"
72 "\n"
73 " git commit --allow-empty\n"
74 "\n");
75
76 static const char empty_rebase_pick_advice[] =
77 N_("Otherwise, please use 'git rebase --skip'\n");
78
79 static const char empty_cherry_pick_advice_single[] =
80 N_("Otherwise, please use 'git cherry-pick --skip'\n");
81
82 static const char empty_cherry_pick_advice_multi[] =
83 N_("and then use:\n"
84 "\n"
85 " git cherry-pick --continue\n"
86 "\n"
87 "to resume cherry-picking the remaining commits.\n"
88 "If you wish to skip this commit, use:\n"
89 "\n"
90 " git cherry-pick --skip\n"
91 "\n");
92
93 static const char *color_status_slots[] = {
94 [WT_STATUS_HEADER] = "header",
95 [WT_STATUS_UPDATED] = "updated",
96 [WT_STATUS_CHANGED] = "changed",
97 [WT_STATUS_UNTRACKED] = "untracked",
98 [WT_STATUS_NOBRANCH] = "noBranch",
99 [WT_STATUS_UNMERGED] = "unmerged",
100 [WT_STATUS_LOCAL_BRANCH] = "localBranch",
101 [WT_STATUS_REMOTE_BRANCH] = "remoteBranch",
102 [WT_STATUS_ONBRANCH] = "branch",
103 };
104
105 static const char *use_message_buffer;
106 static struct lock_file index_lock; /* real index */
107 static struct lock_file false_lock; /* used only for partial commits */
108 static enum {
109 COMMIT_AS_IS = 1,
110 COMMIT_NORMAL,
111 COMMIT_PARTIAL
112 } commit_style;
113
114 static const char *force_author;
115 static char *logfile;
116 static char *template_file;
117 /*
118 * The _message variables are commit names from which to take
119 * the commit message and/or authorship.
120 */
121 static const char *author_message, *author_message_buffer;
122 static const char *edit_message, *use_message;
123 static char *fixup_message, *fixup_commit, *squash_message;
124 static const char *fixup_prefix;
125 static int all, also, interactive, patch_interactive, only, amend, signoff;
126 static struct interactive_options interactive_opts = INTERACTIVE_OPTIONS_INIT;
127 static int edit_flag = -1; /* unspecified */
128 static int quiet, verbose, no_verify, allow_empty, dry_run, renew_authorship;
129 static int config_commit_verbose = -1; /* unspecified */
130 static int no_post_rewrite, allow_empty_message, pathspec_file_nul;
131 static const char *untracked_files_arg, *force_date, *ignore_submodule_arg, *ignored_arg;
132 static const char *sign_commit, *pathspec_from_file;
133 static struct strvec trailer_args = STRVEC_INIT;
134
135 /*
136 * The default commit message cleanup mode will remove the lines
137 * beginning with # (shell comments) and leading and trailing
138 * whitespaces (empty lines or containing only whitespaces)
139 * if editor is used, and only the whitespaces if the message
140 * is specified explicitly.
141 */
142 static enum commit_msg_cleanup_mode cleanup_mode;
143 static char *cleanup_config;
144
145 static enum commit_whence whence;
146 static int use_editor = 1, include_status = 1;
147 static int have_option_m;
148 static struct strbuf message = STRBUF_INIT;
149
150 static enum wt_status_format status_format = STATUS_FORMAT_UNSPECIFIED;
151
152 static int opt_parse_porcelain(const struct option *opt, const char *arg, int unset)
153 {
154 enum wt_status_format *value = (enum wt_status_format *)opt->value;
155 if (unset)
156 *value = STATUS_FORMAT_NONE;
157 else if (!arg)
158 *value = STATUS_FORMAT_PORCELAIN;
159 else if (!strcmp(arg, "v1") || !strcmp(arg, "1"))
160 *value = STATUS_FORMAT_PORCELAIN;
161 else if (!strcmp(arg, "v2") || !strcmp(arg, "2"))
162 *value = STATUS_FORMAT_PORCELAIN_V2;
163 else
164 die("unsupported porcelain version '%s'", arg);
165
166 return 0;
167 }
168
169 static int opt_parse_m(const struct option *opt, const char *arg, int unset)
170 {
171 struct strbuf *buf = opt->value;
172 if (unset) {
173 have_option_m = 0;
174 strbuf_setlen(buf, 0);
175 } else {
176 have_option_m = 1;
177 if (buf->len)
178 strbuf_addch(buf, '\n');
179 strbuf_addstr(buf, arg);
180 strbuf_complete_line(buf);
181 }
182 return 0;
183 }
184
185 static int opt_parse_rename_score(const struct option *opt, const char *arg, int unset)
186 {
187 const char **value = opt->value;
188
189 BUG_ON_OPT_NEG(unset);
190
191 if (arg != NULL && *arg == '=')
192 arg = arg + 1;
193
194 *value = arg;
195 return 0;
196 }
197
198 static void determine_whence(struct wt_status *s)
199 {
200 if (file_exists(git_path_merge_head(the_repository)))
201 whence = FROM_MERGE;
202 else if (!sequencer_determine_whence(the_repository, &whence))
203 whence = FROM_COMMIT;
204 if (s)
205 s->whence = whence;
206 }
207
208 static void status_init_config(struct wt_status *s, config_fn_t fn)
209 {
210 wt_status_prepare(the_repository, s);
211 init_diff_ui_defaults();
212 repo_config(the_repository, fn, s);
213 determine_whence(s);
214 s->hints = advice_enabled(ADVICE_STATUS_HINTS); /* must come after repo_config() */
215 }
216
217 static void rollback_index_files(void)
218 {
219 switch (commit_style) {
220 case COMMIT_AS_IS:
221 break; /* nothing to do */
222 case COMMIT_NORMAL:
223 rollback_lock_file(&index_lock);
224 break;
225 case COMMIT_PARTIAL:
226 rollback_lock_file(&index_lock);
227 rollback_lock_file(&false_lock);
228 break;
229 }
230 }
231
232 static int commit_index_files(void)
233 {
234 int err = 0;
235
236 switch (commit_style) {
237 case COMMIT_AS_IS:
238 break; /* nothing to do */
239 case COMMIT_NORMAL:
240 err = commit_lock_file(&index_lock);
241 break;
242 case COMMIT_PARTIAL:
243 err = commit_lock_file(&index_lock);
244 rollback_lock_file(&false_lock);
245 break;
246 }
247
248 return err;
249 }
250
251 /*
252 * Take a union of paths in the index and the named tree (typically, "HEAD"),
253 * and return the paths that match the given pattern in list.
254 */
255 static int list_paths(struct string_list *list, const char *with_tree,
256 const struct pathspec *pattern)
257 {
258 int i, ret;
259 char *m;
260
261 if (!pattern->nr)
262 return 0;
263
264 m = xcalloc(1, pattern->nr);
265
266 if (with_tree) {
267 char *max_prefix = common_prefix(pattern);
268 overlay_tree_on_index(the_repository->index, with_tree, max_prefix);
269 free(max_prefix);
270 }
271
272 /* TODO: audit for interaction with sparse-index. */
273 ensure_full_index(the_repository->index);
274 for (i = 0; i < the_repository->index->cache_nr; i++) {
275 const struct cache_entry *ce = the_repository->index->cache[i];
276 struct string_list_item *item;
277
278 if (ce->ce_flags & CE_UPDATE)
279 continue;
280 if (!ce_path_match(the_repository->index, ce, pattern, m))
281 continue;
282 item = string_list_insert(list, ce->name);
283 if (ce_skip_worktree(ce))
284 item->util = item; /* better a valid pointer than a fake one */
285 }
286
287 ret = report_path_error(m, pattern);
288 free(m);
289 return ret;
290 }
291
292 static void add_remove_files(struct string_list *list)
293 {
294 int i;
295 for (i = 0; i < list->nr; i++) {
296 struct stat st;
297 struct string_list_item *p = &(list->items[i]);
298
299 /* p->util is skip-worktree */
300 if (p->util)
301 continue;
302
303 if (!lstat(p->string, &st)) {
304 if (add_to_index(the_repository->index, p->string, &st, 0))
305 die(_("updating files failed"));
306 } else
307 remove_file_from_index(the_repository->index, p->string);
308 }
309 }
310
311 static void create_base_index(const struct commit *current_head)
312 {
313 struct tree *tree;
314 struct unpack_trees_options opts;
315 struct tree_desc t;
316
317 if (!current_head) {
318 discard_index(the_repository->index);
319 return;
320 }
321
322 memset(&opts, 0, sizeof(opts));
323 opts.head_idx = 1;
324 opts.index_only = 1;
325 opts.merge = 1;
326 opts.src_index = the_repository->index;
327 opts.dst_index = the_repository->index;
328
329 opts.fn = oneway_merge;
330 tree = repo_parse_tree_indirect(the_repository,
331 &current_head->object.oid);
332 if (!tree)
333 die(_("failed to unpack HEAD tree object"));
334 if (repo_parse_tree(the_repository, tree) < 0)
335 exit(128);
336 init_tree_desc(&t, &tree->object.oid, tree->buffer, tree->size);
337 if (unpack_trees(1, &t, &opts))
338 exit(128); /* We've already reported the error, finish dying */
339 }
340
341 static void refresh_cache_or_die(int refresh_flags)
342 {
343 /*
344 * refresh_flags contains REFRESH_QUIET, so the only errors
345 * are for unmerged entries.
346 */
347 if (refresh_index(the_repository->index, refresh_flags | REFRESH_IN_PORCELAIN, NULL, NULL, NULL))
348 die_resolve_conflict("commit");
349 }
350
351 static const char *prepare_index(const char **argv, const char *prefix,
352 const struct commit *current_head, int is_status)
353 {
354 struct string_list partial = STRING_LIST_INIT_DUP;
355 struct pathspec pathspec;
356 int refresh_flags = REFRESH_QUIET;
357 const char *ret;
358 char *path = NULL;
359
360 if (interactive_opts.context < -1)
361 die(_("'%s' cannot be negative"), "--unified");
362 if (interactive_opts.interhunkcontext < -1)
363 die(_("'%s' cannot be negative"), "--inter-hunk-context");
364
365 if (is_status)
366 refresh_flags |= REFRESH_UNMERGED;
367 parse_pathspec(&pathspec, 0,
368 PATHSPEC_PREFER_FULL,
369 prefix, argv);
370
371 if (pathspec_from_file) {
372 if (interactive)
373 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--interactive/--patch");
374
375 if (all)
376 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "-a");
377
378 if (pathspec.nr)
379 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
380
381 parse_pathspec_file(&pathspec, 0,
382 PATHSPEC_PREFER_FULL,
383 prefix, pathspec_from_file, pathspec_file_nul);
384 } else if (pathspec_file_nul) {
385 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
386 }
387
388 if (!pathspec.nr && (also || (only && !allow_empty &&
389 (!amend || (fixup_message && strcmp(fixup_prefix, "amend"))))))
390 die(_("No paths with --include/--only does not make sense."));
391
392 if (repo_read_index_preload(the_repository, &pathspec, 0) < 0)
393 die(_("index file corrupt"));
394
395 if (interactive) {
396 char *old_index_env = NULL, *old_repo_index_file;
397 repo_hold_locked_index(the_repository, &index_lock,
398 LOCK_DIE_ON_ERROR);
399
400 refresh_cache_or_die(refresh_flags);
401
402 if (write_locked_index(the_repository->index, &index_lock, 0))
403 die(_("unable to create temporary index"));
404
405 old_repo_index_file = the_repository->index_file;
406 the_repository->index_file =
407 (char *)get_lock_file_path(&index_lock);
408 old_index_env = xstrdup_or_null(getenv(INDEX_ENVIRONMENT));
409 setenv(INDEX_ENVIRONMENT, the_repository->index_file, 1);
410
411 if (interactive_add(the_repository, argv, prefix, patch_interactive, &interactive_opts) != 0)
412 die(_("interactive add failed"));
413
414 the_repository->index_file = old_repo_index_file;
415 if (old_index_env && *old_index_env)
416 setenv(INDEX_ENVIRONMENT, old_index_env, 1);
417 else
418 unsetenv(INDEX_ENVIRONMENT);
419 FREE_AND_NULL(old_index_env);
420
421 discard_index(the_repository->index);
422 read_index_from(the_repository->index, get_lock_file_path(&index_lock),
423 repo_get_git_dir(the_repository));
424 if (cache_tree_update(the_repository->index, WRITE_TREE_SILENT) == 0) {
425 if (reopen_lock_file(&index_lock) < 0)
426 die(_("unable to write index file"));
427 if (write_locked_index(the_repository->index, &index_lock, 0))
428 die(_("unable to update temporary index"));
429 } else
430 warning(_("Failed to update main cache tree"));
431
432 commit_style = COMMIT_NORMAL;
433 ret = get_lock_file_path(&index_lock);
434 goto out;
435 } else {
436 if (interactive_opts.context != -1)
437 die(_("the option '%s' requires '%s'"), "--unified", "--interactive/--patch");
438 if (interactive_opts.interhunkcontext != -1)
439 die(_("the option '%s' requires '%s'"), "--inter-hunk-context", "--interactive/--patch");
440 }
441
442 /*
443 * Non partial, non as-is commit.
444 *
445 * (1) get the real index;
446 * (2) update the_index as necessary;
447 * (3) write the_index out to the real index (still locked);
448 * (4) return the name of the locked index file.
449 *
450 * The caller should run hooks on the locked real index, and
451 * (A) if all goes well, commit the real index;
452 * (B) on failure, rollback the real index.
453 */
454 if (all || (also && pathspec.nr)) {
455 char *ps_matched = xcalloc(pathspec.nr, 1);
456 repo_hold_locked_index(the_repository, &index_lock,
457 LOCK_DIE_ON_ERROR);
458 add_files_to_cache(the_repository, also ? prefix : NULL,
459 &pathspec, ps_matched, 0, 0, 0 );
460 if (!all && report_path_error(ps_matched, &pathspec))
461 exit(128);
462
463 refresh_cache_or_die(refresh_flags);
464 cache_tree_update(the_repository->index, WRITE_TREE_SILENT);
465 if (write_locked_index(the_repository->index, &index_lock, 0))
466 die(_("unable to write new index file"));
467 commit_style = COMMIT_NORMAL;
468 ret = get_lock_file_path(&index_lock);
469 free(ps_matched);
470 goto out;
471 }
472
473 /*
474 * As-is commit.
475 *
476 * (1) return the name of the real index file.
477 *
478 * The caller should run hooks on the real index,
479 * and create commit from the_index.
480 * We still need to refresh the index here.
481 */
482 if (!only && !pathspec.nr) {
483 repo_hold_locked_index(the_repository, &index_lock,
484 LOCK_DIE_ON_ERROR);
485 refresh_cache_or_die(refresh_flags);
486 if (the_repository->index->cache_changed
487 || !cache_tree_fully_valid(the_repository->index))
488 cache_tree_update(the_repository->index, WRITE_TREE_SILENT);
489 if (write_locked_index(the_repository->index, &index_lock,
490 COMMIT_LOCK | SKIP_IF_UNCHANGED))
491 die(_("unable to write new index file"));
492 commit_style = COMMIT_AS_IS;
493 ret = repo_get_index_file(the_repository);
494 goto out;
495 }
496
497 /*
498 * A partial commit.
499 *
500 * (0) find the set of affected paths;
501 * (1) get lock on the real index file;
502 * (2) update the_index with the given paths;
503 * (3) write the_index out to the real index (still locked);
504 * (4) get lock on the false index file;
505 * (5) reset the_index from HEAD;
506 * (6) update the_index the same way as (2);
507 * (7) write the_index out to the false index file;
508 * (8) return the name of the false index file (still locked);
509 *
510 * The caller should run hooks on the locked false index, and
511 * create commit from it. Then
512 * (A) if all goes well, commit the real index;
513 * (B) on failure, rollback the real index;
514 * In either case, rollback the false index.
515 */
516 commit_style = COMMIT_PARTIAL;
517
518 switch (sequencer_ongoing_operation(the_repository, whence)) {
519 case ONGOING_NONE:
520 break;
521 case ONGOING_MERGE:
522 die(_("cannot do a partial commit during a merge."));
523 case ONGOING_CHERRY_PICK:
524 die(_("cannot do a partial commit during a cherry-pick."));
525 case ONGOING_REBASE_NOW_EMPTY:
526 /*
527 * A pick that became empty is not a conflict, and creating
528 * a new commit (partial or not) poses no problem.
529 */
530 break;
531 case ONGOING_REVERT:
532 die(_("cannot do a partial commit during a revert."));
533 case ONGOING_AM:
534 die(_("cannot do a partial commit during an am session."));
535 case ONGOING_REBASE_CONFLICT:
536 die(_("cannot do a partial commit while resolving conflicts during a rebase."));
537 }
538
539 if (list_paths(&partial, !current_head ? NULL : "HEAD", &pathspec))
540 exit(1);
541
542 discard_index(the_repository->index);
543 if (repo_read_index(the_repository) < 0)
544 die(_("cannot read the index"));
545
546 repo_hold_locked_index(the_repository, &index_lock, LOCK_DIE_ON_ERROR);
547 add_remove_files(&partial);
548 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL, NULL);
549 cache_tree_update(the_repository->index, WRITE_TREE_SILENT);
550 if (write_locked_index(the_repository->index, &index_lock, 0))
551 die(_("unable to write new index file"));
552
553 path = repo_git_path(the_repository, "next-index-%"PRIuMAX,
554 (uintmax_t) getpid());
555 hold_lock_file_for_update(&false_lock, path,
556 LOCK_DIE_ON_ERROR);
557
558 create_base_index(current_head);
559 add_remove_files(&partial);
560 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL, NULL);
561
562 if (write_locked_index(the_repository->index, &false_lock, 0))
563 die(_("unable to write temporary index file"));
564
565 discard_index(the_repository->index);
566 ret = get_lock_file_path(&false_lock);
567 read_index_from(the_repository->index, ret, repo_get_git_dir(the_repository));
568 out:
569 string_list_clear(&partial, 0);
570 clear_pathspec(&pathspec);
571 free(path);
572 return ret;
573 }
574
575 static int run_status(FILE *fp, const char *index_file, const char *prefix, int nowarn,
576 struct wt_status *s)
577 {
578 struct object_id oid;
579
580 if (s->relative_paths)
581 s->prefix = prefix;
582
583 if (amend) {
584 s->amend = 1;
585 s->reference = "HEAD^1";
586 }
587 s->verbose = verbose;
588 s->index_file = index_file;
589 s->fp = fp;
590 s->nowarn = nowarn;
591 s->is_initial = repo_get_oid(the_repository, s->reference, &oid) ? 1 : 0;
592 if (!s->is_initial)
593 oidcpy(&s->oid_commit, &oid);
594 s->status_format = status_format;
595 s->ignore_submodule_arg = ignore_submodule_arg;
596
597 wt_status_collect(s);
598 wt_status_print(s);
599 wt_status_collect_free_buffers(s);
600
601 return s->committable;
602 }
603
604 static int is_a_merge(const struct commit *current_head)
605 {
606 return !!(current_head->parents && current_head->parents->next);
607 }
608
609 static void assert_split_ident(struct ident_split *id, const struct strbuf *buf)
610 {
611 if (split_ident_line(id, buf->buf, buf->len) || !id->date_begin)
612 BUG("unable to parse our own ident: %s", buf->buf);
613 }
614
615 static void export_one(const char *var, const char *s, const char *e, int hack)
616 {
617 struct strbuf buf = STRBUF_INIT;
618 if (hack)
619 strbuf_addch(&buf, hack);
620 strbuf_add(&buf, s, e - s);
621 setenv(var, buf.buf, 1);
622 strbuf_release(&buf);
623 }
624
625 static int parse_force_date(const char *in, struct strbuf *out)
626 {
627 strbuf_addch(out, '@');
628
629 if (parse_date(in, out) < 0) {
630 int errors = 0;
631 unsigned long t = approxidate_careful(in, &errors);
632 if (errors)
633 return -1;
634 strbuf_addf(out, "%lu", t);
635 }
636
637 return 0;
638 }
639
640 static void set_ident_var(char **buf, char *val)
641 {
642 free(*buf);
643 *buf = val;
644 }
645
646 static void determine_author_info(struct strbuf *author_ident)
647 {
648 char *name, *email, *date;
649 struct ident_split author;
650
651 name = xstrdup_or_null(getenv("GIT_AUTHOR_NAME"));
652 email = xstrdup_or_null(getenv("GIT_AUTHOR_EMAIL"));
653 date = xstrdup_or_null(getenv("GIT_AUTHOR_DATE"));
654
655 if (author_message) {
656 struct ident_split ident;
657 size_t len;
658 const char *a;
659
660 a = find_commit_header(author_message_buffer, "author", &len);
661 if (!a)
662 die(_("commit '%s' lacks author header"), author_message);
663 if (split_ident_line(&ident, a, len) < 0)
664 die(_("commit '%s' has malformed author line"), author_message);
665
666 set_ident_var(&name, xmemdupz(ident.name_begin, ident.name_end - ident.name_begin));
667 set_ident_var(&email, xmemdupz(ident.mail_begin, ident.mail_end - ident.mail_begin));
668
669 if (ident.date_begin) {
670 struct strbuf date_buf = STRBUF_INIT;
671 strbuf_addch(&date_buf, '@');
672 strbuf_add(&date_buf, ident.date_begin, ident.date_end - ident.date_begin);
673 strbuf_addch(&date_buf, ' ');
674 strbuf_add(&date_buf, ident.tz_begin, ident.tz_end - ident.tz_begin);
675 set_ident_var(&date, strbuf_detach(&date_buf, NULL));
676 }
677 }
678
679 if (force_author) {
680 struct ident_split ident;
681
682 if (split_ident_line(&ident, force_author, strlen(force_author)) < 0)
683 die(_("malformed --author parameter"));
684 set_ident_var(&name, xmemdupz(ident.name_begin, ident.name_end - ident.name_begin));
685 set_ident_var(&email, xmemdupz(ident.mail_begin, ident.mail_end - ident.mail_begin));
686 }
687
688 if (force_date) {
689 struct strbuf date_buf = STRBUF_INIT;
690 if (parse_force_date(force_date, &date_buf))
691 die(_("invalid date format: %s"), force_date);
692 set_ident_var(&date, strbuf_detach(&date_buf, NULL));
693 }
694
695 strbuf_addstr(author_ident, fmt_ident(name, email, WANT_AUTHOR_IDENT, date,
696 IDENT_STRICT));
697 assert_split_ident(&author, author_ident);
698 export_one("GIT_AUTHOR_NAME", author.name_begin, author.name_end, 0);
699 export_one("GIT_AUTHOR_EMAIL", author.mail_begin, author.mail_end, 0);
700 export_one("GIT_AUTHOR_DATE", author.date_begin, author.tz_end, '@');
701 free(name);
702 free(email);
703 free(date);
704 }
705
706 static int author_date_is_interesting(void)
707 {
708 return author_message || force_date;
709 }
710
711 #ifndef WITH_BREAKING_CHANGES
712 static void adjust_comment_line_char(const struct strbuf *sb)
713 {
714 char candidates[] = "#;@!$%^&|:";
715 char *candidate;
716 const char *p;
717 size_t cutoff;
718
719 /* Ignore comment chars in trailing comments (e.g., Conflicts:) */
720 cutoff = sb->len - ignored_log_message_bytes(sb->buf, sb->len);
721
722 if (!memchr(sb->buf, candidates[0], sb->len)) {
723 free(comment_line_str_to_free);
724 comment_line_str = comment_line_str_to_free =
725 xstrfmt("%c", candidates[0]);
726 return;
727 }
728
729 p = sb->buf;
730 candidate = strchr(candidates, *p);
731 if (candidate)
732 *candidate = ' ';
733 for (p = sb->buf; p + 1 < sb->buf + cutoff; p++) {
734 if ((p[0] == '\n' || p[0] == '\r') && p[1]) {
735 candidate = strchr(candidates, p[1]);
736 if (candidate)
737 *candidate = ' ';
738 }
739 }
740
741 for (p = candidates; *p == ' '; p++)
742 ;
743 if (!*p)
744 die(_("unable to select a comment character that is not used\n"
745 "in the current commit message"));
746 free(comment_line_str_to_free);
747 comment_line_str = comment_line_str_to_free = xstrfmt("%c", *p);
748 }
749 #endif /* !WITH_BREAKING_CHANGES */
750
751 static void prepare_amend_commit(struct commit *commit, struct strbuf *sb,
752 struct pretty_print_context *ctx)
753 {
754 const char *buffer, *subject, *fmt;
755
756 buffer = repo_get_commit_buffer(the_repository, commit, NULL);
757 find_commit_subject(buffer, &subject);
758 /*
759 * If we amend the 'amend!' commit then we don't want to
760 * duplicate the subject line.
761 */
762 fmt = starts_with(subject, "amend!") ? "%b" : "%B";
763 repo_format_commit_message(the_repository, commit, fmt, sb, ctx);
764 repo_unuse_commit_buffer(the_repository, commit, buffer);
765 }
766
767 static void change_data_free(void *util, const char *str UNUSED)
768 {
769 struct wt_status_change_data *d = util;
770 free(d->rename_source);
771 free(d);
772 }
773
774 static int prepare_to_commit(const char *index_file, const char *prefix,
775 struct commit *current_head,
776 struct wt_status *s,
777 struct strbuf *author_ident)
778 {
779 struct stat statbuf;
780 struct strbuf committer_ident = STRBUF_INIT;
781 int committable;
782 struct strbuf sb = STRBUF_INIT;
783 const char *hook_arg1 = NULL;
784 const char *hook_arg2 = NULL;
785 int clean_message_contents = (cleanup_mode != COMMIT_MSG_CLEANUP_NONE);
786 int old_display_comment_prefix;
787 int invoked_hook;
788
789 /* This checks and barfs if author is badly specified */
790 determine_author_info(author_ident);
791
792 if (!no_verify && run_commit_hook(use_editor, index_file, &invoked_hook,
793 "pre-commit", NULL))
794 return 0;
795
796 if (squash_message) {
797 /*
798 * Insert the proper subject line before other commit
799 * message options add their content.
800 */
801 if (use_message && !strcmp(use_message, squash_message))
802 strbuf_addstr(&sb, "squash! ");
803 else {
804 struct pretty_print_context ctx = {0};
805 struct commit *c;
806 c = lookup_commit_reference_by_name(squash_message);
807 if (!c)
808 die(_("could not lookup commit '%s'"), squash_message);
809 ctx.output_encoding = get_commit_output_encoding();
810 repo_format_commit_message(the_repository, c,
811 "squash! %s\n\n", &sb,
812 &ctx);
813 }
814 }
815
816 if (have_option_m && !fixup_message) {
817 strbuf_addbuf(&sb, &message);
818 hook_arg1 = "message";
819 } else if (logfile && !strcmp(logfile, "-")) {
820 if (isatty(0))
821 fprintf(stderr, _("(reading log message from standard input)\n"));
822 if (strbuf_read(&sb, 0, 0) < 0)
823 die_errno(_("could not read log from standard input"));
824 hook_arg1 = "message";
825 } else if (logfile) {
826 if (strbuf_read_file(&sb, logfile, 0) < 0)
827 die_errno(_("could not read log file '%s'"),
828 logfile);
829 hook_arg1 = "message";
830 } else if (use_message) {
831 const char *buffer;
832 buffer = strstr(use_message_buffer, "\n\n");
833 if (buffer)
834 strbuf_addstr(&sb, skip_blank_lines(buffer + 2));
835 hook_arg1 = "commit";
836 hook_arg2 = use_message;
837 } else if (fixup_message) {
838 struct pretty_print_context ctx = {0};
839 struct commit *commit;
840 char *fmt;
841 commit = lookup_commit_reference_by_name(fixup_commit);
842 if (!commit)
843 die(_("could not lookup commit '%s'"), fixup_commit);
844 ctx.output_encoding = get_commit_output_encoding();
845 fmt = xstrfmt("%s! %%s\n\n", fixup_prefix);
846 repo_format_commit_message(the_repository, commit, fmt, &sb,
847 &ctx);
848 free(fmt);
849 hook_arg1 = "message";
850
851 /*
852 * Only `-m` commit message option is checked here, as
853 * it supports `--fixup` to append the commit message.
854 *
855 * The other commit message options `-c`/`-C`/`-F` are
856 * incompatible with all the forms of `--fixup` and
857 * have already errored out while parsing the `git commit`
858 * options.
859 */
860 if (have_option_m && !strcmp(fixup_prefix, "fixup"))
861 strbuf_addbuf(&sb, &message);
862
863 if (!strcmp(fixup_prefix, "amend")) {
864 if (have_option_m)
865 die(_("options '%s' and '%s:%s' cannot be used together"), "-m", "--fixup", fixup_message);
866 prepare_amend_commit(commit, &sb, &ctx);
867 }
868 } else if (!stat(git_path_merge_msg(the_repository), &statbuf)) {
869 size_t merge_msg_start;
870
871 /*
872 * prepend SQUASH_MSG here if it exists and a
873 * "merge --squash" was originally performed
874 */
875 if (!stat(git_path_squash_msg(the_repository), &statbuf)) {
876 if (strbuf_read_file(&sb, git_path_squash_msg(the_repository), 0) < 0)
877 die_errno(_("could not read SQUASH_MSG"));
878 hook_arg1 = "squash";
879 } else
880 hook_arg1 = "merge";
881
882 merge_msg_start = sb.len;
883 if (strbuf_read_file(&sb, git_path_merge_msg(the_repository), 0) < 0)
884 die_errno(_("could not read MERGE_MSG"));
885
886 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS &&
887 wt_status_locate_end(sb.buf + merge_msg_start,
888 sb.len - merge_msg_start) <
889 sb.len - merge_msg_start)
890 s->added_cut_line = 1;
891 } else if (!stat(git_path_squash_msg(the_repository), &statbuf)) {
892 if (strbuf_read_file(&sb, git_path_squash_msg(the_repository), 0) < 0)
893 die_errno(_("could not read SQUASH_MSG"));
894 hook_arg1 = "squash";
895 } else if (template_file) {
896 if (strbuf_read_file(&sb, template_file, 0) < 0)
897 die_errno(_("could not read '%s'"), template_file);
898 hook_arg1 = "template";
899 clean_message_contents = 0;
900 }
901
902 /*
903 * The remaining cases don't modify the template message, but
904 * just set the argument(s) to the prepare-commit-msg hook.
905 */
906 else if (whence == FROM_MERGE)
907 hook_arg1 = "merge";
908 else if (is_from_cherry_pick(whence) || is_from_rebase_now_empty(whence)) {
909 hook_arg1 = "commit";
910 hook_arg2 = "CHERRY_PICK_HEAD";
911 }
912
913 if (squash_message) {
914 /*
915 * If squash_commit was used for the commit subject,
916 * then we're possibly hijacking other commit log options.
917 * Reset the hook args to tell the real story.
918 */
919 hook_arg1 = "message";
920 hook_arg2 = "";
921 }
922
923 s->fp = fopen_for_writing(git_path_commit_editmsg());
924 if (!s->fp)
925 die_errno(_("could not open '%s'"), git_path_commit_editmsg());
926
927 /* Ignore status.displayCommentPrefix: we do need comments in COMMIT_EDITMSG. */
928 old_display_comment_prefix = s->display_comment_prefix;
929 s->display_comment_prefix = 1;
930
931 /*
932 * Most hints are counter-productive when the commit has
933 * already started.
934 */
935 s->hints = 0;
936
937 if (clean_message_contents)
938 strbuf_stripspace(&sb, NULL);
939
940 if (signoff)
941 append_signoff(&sb, ignored_log_message_bytes(sb.buf, sb.len), 0);
942
943 if (fwrite(sb.buf, 1, sb.len, s->fp) < sb.len)
944 die_errno(_("could not write commit template"));
945
946 #ifndef WITH_BREAKING_CHANGES
947 if (auto_comment_line_char)
948 adjust_comment_line_char(&sb);
949 #endif /* !WITH_BREAKING_CHANGES */
950 strbuf_release(&sb);
951
952 /* This checks if committer ident is explicitly given */
953 strbuf_addstr(&committer_ident, git_committer_info(IDENT_STRICT));
954 if (use_editor && include_status) {
955 int ident_shown = 0;
956 enum git_colorbool saved_color_setting;
957 struct ident_split ci, ai;
958 const char *hint_cleanup_all = allow_empty_message ?
959 _("Please enter the commit message for your changes."
960 " Lines starting\nwith '%s' will be ignored.\n") :
961 _("Please enter the commit message for your changes."
962 " Lines starting\nwith '%s' will be ignored, and an empty"
963 " message aborts the commit.\n");
964 const char *hint_cleanup_space = allow_empty_message ?
965 _("Please enter the commit message for your changes."
966 " Lines starting\n"
967 "with '%s' will be kept; you may remove them"
968 " yourself if you want to.\n") :
969 _("Please enter the commit message for your changes."
970 " Lines starting\n"
971 "with '%s' will be kept; you may remove them"
972 " yourself if you want to.\n"
973 "An empty message aborts the commit.\n");
974 if (whence != FROM_COMMIT) {
975 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
976 wt_status_add_cut_line(s);
977 status_printf_ln(
978 s, GIT_COLOR_NORMAL,
979 whence == FROM_MERGE ?
980 _("\n"
981 "It looks like you may be committing a merge.\n"
982 "If this is not correct, please run\n"
983 " git update-ref -d MERGE_HEAD\n"
984 "and try again.\n") :
985 _("\n"
986 "It looks like you may be committing a cherry-pick.\n"
987 "If this is not correct, please run\n"
988 " git update-ref -d CHERRY_PICK_HEAD\n"
989 "and try again.\n"));
990 }
991
992 fprintf(s->fp, "\n");
993 if (cleanup_mode == COMMIT_MSG_CLEANUP_ALL)
994 status_printf(s, GIT_COLOR_NORMAL, hint_cleanup_all, comment_line_str);
995 else if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
996 if (whence == FROM_COMMIT)
997 wt_status_add_cut_line(s);
998 } else /* COMMIT_MSG_CLEANUP_SPACE, that is. */
999 status_printf(s, GIT_COLOR_NORMAL, hint_cleanup_space, comment_line_str);
1000
1001 /*
1002 * These should never fail because they come from our own
1003 * fmt_ident. They may fail the sane_ident test, but we know
1004 * that the name and mail pointers will at least be valid,
1005 * which is enough for our tests and printing here.
1006 */
1007 assert_split_ident(&ai, author_ident);
1008 assert_split_ident(&ci, &committer_ident);
1009
1010 if (ident_cmp(&ai, &ci))
1011 status_printf_ln(s, GIT_COLOR_NORMAL,
1012 _("%s"
1013 "Author: %.*s <%.*s>"),
1014 ident_shown++ ? "" : "\n",
1015 (int)(ai.name_end - ai.name_begin), ai.name_begin,
1016 (int)(ai.mail_end - ai.mail_begin), ai.mail_begin);
1017
1018 if (author_date_is_interesting())
1019 status_printf_ln(s, GIT_COLOR_NORMAL,
1020 _("%s"
1021 "Date: %s"),
1022 ident_shown++ ? "" : "\n",
1023 show_ident_date(&ai, DATE_MODE(NORMAL)));
1024
1025 if (!committer_ident_sufficiently_given())
1026 status_printf_ln(s, GIT_COLOR_NORMAL,
1027 _("%s"
1028 "Committer: %.*s <%.*s>"),
1029 ident_shown++ ? "" : "\n",
1030 (int)(ci.name_end - ci.name_begin), ci.name_begin,
1031 (int)(ci.mail_end - ci.mail_begin), ci.mail_begin);
1032
1033 status_printf_ln(s, GIT_COLOR_NORMAL, "%s", ""); /* Add new line for clarity */
1034
1035 saved_color_setting = s->use_color;
1036 s->use_color = GIT_COLOR_NEVER;
1037 committable = run_status(s->fp, index_file, prefix, 1, s);
1038 s->use_color = saved_color_setting;
1039 string_list_clear_func(&s->change, change_data_free);
1040 } else {
1041 struct object_id oid;
1042 const char *parent = "HEAD";
1043
1044 if (!the_repository->index->initialized && repo_read_index(the_repository) < 0)
1045 die(_("Cannot read index"));
1046
1047 if (amend)
1048 parent = "HEAD^1";
1049
1050 if (repo_get_oid(the_repository, parent, &oid)) {
1051 int i, ita_nr = 0;
1052
1053 /* TODO: audit for interaction with sparse-index. */
1054 ensure_full_index(the_repository->index);
1055 for (i = 0; i < the_repository->index->cache_nr; i++)
1056 if (ce_intent_to_add(the_repository->index->cache[i]))
1057 ita_nr++;
1058 committable = the_repository->index->cache_nr > ita_nr;
1059 } else {
1060 /*
1061 * Unless the user did explicitly request a submodule
1062 * ignore mode by passing a command line option we do
1063 * not ignore any changed submodule SHA-1s when
1064 * comparing index and parent, no matter what is
1065 * configured. Otherwise we won't commit any
1066 * submodules which were manually staged, which would
1067 * be really confusing.
1068 */
1069 struct diff_flags flags = DIFF_FLAGS_INIT;
1070 flags.override_submodule_config = 1;
1071 if (ignore_submodule_arg &&
1072 !strcmp(ignore_submodule_arg, "all"))
1073 flags.ignore_submodules = 1;
1074 committable = index_differs_from(the_repository,
1075 parent, &flags, 1);
1076 }
1077 }
1078 strbuf_release(&committer_ident);
1079
1080 fclose(s->fp);
1081
1082 if (trailer_args.nr) {
1083 if (amend_file_with_trailers(git_path_commit_editmsg(), &trailer_args))
1084 die(_("unable to pass trailers to --trailers"));
1085 strvec_clear(&trailer_args);
1086 }
1087
1088 /*
1089 * Reject an attempt to record a non-merge empty commit without
1090 * explicit --allow-empty. In the cherry-pick case, it may be
1091 * empty due to conflict resolution, which the user should okay.
1092 */
1093 if (!committable && whence != FROM_MERGE && !allow_empty &&
1094 !(amend && is_a_merge(current_head))) {
1095 s->hints = advice_enabled(ADVICE_STATUS_HINTS);
1096 s->display_comment_prefix = old_display_comment_prefix;
1097 run_status(stdout, index_file, prefix, 0, s);
1098 if (amend)
1099 fputs(_(empty_amend_advice), stderr);
1100 else if (is_from_cherry_pick(whence) ||
1101 is_from_rebase_now_empty(whence)) {
1102 fputs(_(empty_cherry_pick_advice), stderr);
1103 if (whence == FROM_CHERRY_PICK_SINGLE)
1104 fputs(_(empty_cherry_pick_advice_single), stderr);
1105 else if (whence == FROM_CHERRY_PICK_MULTI)
1106 fputs(_(empty_cherry_pick_advice_multi), stderr);
1107 else
1108 fputs(_(empty_rebase_pick_advice), stderr);
1109 }
1110 return 0;
1111 }
1112
1113 if (!no_verify && invoked_hook) {
1114 /*
1115 * Re-read the index as the pre-commit-commit hook was invoked
1116 * and could have updated it. We must do this before we invoke
1117 * the editor and after we invoke run_status above.
1118 */
1119 discard_index(the_repository->index);
1120 }
1121 read_index_from(the_repository->index, index_file, repo_get_git_dir(the_repository));
1122
1123 if (cache_tree_update(the_repository->index, 0)) {
1124 error(_("Error building trees"));
1125 return 0;
1126 }
1127
1128 if (run_commit_hook(use_editor, index_file, NULL, "prepare-commit-msg",
1129 git_path_commit_editmsg(), hook_arg1, hook_arg2, NULL))
1130 return 0;
1131
1132 if (use_editor) {
1133 struct strvec env = STRVEC_INIT;
1134
1135 strvec_pushf(&env, "GIT_INDEX_FILE=%s", index_file);
1136 if (launch_editor(git_path_commit_editmsg(), NULL, env.v)) {
1137 fprintf(stderr,
1138 _("Please supply the message using either -m or -F option.\n"));
1139 exit(1);
1140 }
1141 strvec_clear(&env);
1142 }
1143
1144 if (!no_verify &&
1145 run_commit_hook(use_editor, index_file, NULL, "commit-msg",
1146 git_path_commit_editmsg(), NULL)) {
1147 return 0;
1148 }
1149
1150 return 1;
1151 }
1152
1153 static const char *find_author_by_nickname(const char *name)
1154 {
1155 struct rev_info revs;
1156 struct commit *commit;
1157 struct strbuf buf = STRBUF_INIT;
1158 const char *av[20];
1159 int ac = 0;
1160
1161 repo_init_revisions(the_repository, &revs, NULL);
1162 strbuf_addf(&buf, "--author=%s", name);
1163 av[++ac] = "--all";
1164 av[++ac] = "-i";
1165 av[++ac] = buf.buf;
1166 av[++ac] = NULL;
1167 setup_revisions(ac, av, &revs, NULL);
1168 revs.mailmap = xmalloc(sizeof(struct string_list));
1169 string_list_init_nodup(revs.mailmap);
1170 read_mailmap(the_repository, revs.mailmap);
1171
1172 if (prepare_revision_walk(&revs))
1173 die(_("revision walk setup failed"));
1174 commit = get_revision(&revs);
1175 if (commit) {
1176 struct pretty_print_context ctx = {0};
1177 ctx.date_mode.type = DATE_NORMAL;
1178 strbuf_release(&buf);
1179 repo_format_commit_message(the_repository, commit,
1180 "%aN <%aE>", &buf, &ctx);
1181 release_revisions(&revs);
1182 return strbuf_detach(&buf, NULL);
1183 }
1184 die(_("--author '%s' is not 'Name <email>' and matches no existing author"), name);
1185 }
1186
1187 static void handle_ignored_arg(struct wt_status *s)
1188 {
1189 if (!ignored_arg)
1190 ; /* default already initialized */
1191 else if (!strcmp(ignored_arg, "traditional"))
1192 s->show_ignored_mode = SHOW_TRADITIONAL_IGNORED;
1193 else if (!strcmp(ignored_arg, "no"))
1194 s->show_ignored_mode = SHOW_NO_IGNORED;
1195 else if (!strcmp(ignored_arg, "matching"))
1196 s->show_ignored_mode = SHOW_MATCHING_IGNORED;
1197 else
1198 die(_("Invalid ignored mode '%s'"), ignored_arg);
1199 }
1200
1201 static enum untracked_status_type parse_untracked_setting_name(const char *u)
1202 {
1203 /*
1204 * Please update $__git_untracked_file_modes in
1205 * git-completion.bash when you add new options
1206 */
1207 switch (git_parse_maybe_bool(u)) {
1208 case 0:
1209 u = "no";
1210 break;
1211 case 1:
1212 u = "normal";
1213 break;
1214 default:
1215 break;
1216 }
1217
1218 if (!strcmp(u, "no"))
1219 return SHOW_NO_UNTRACKED_FILES;
1220 else if (!strcmp(u, "normal"))
1221 return SHOW_NORMAL_UNTRACKED_FILES;
1222 else if (!strcmp(u, "all"))
1223 return SHOW_ALL_UNTRACKED_FILES;
1224 else
1225 return SHOW_UNTRACKED_FILES_ERROR;
1226 }
1227
1228 static void handle_untracked_files_arg(struct wt_status *s)
1229 {
1230 enum untracked_status_type u;
1231
1232 if (!untracked_files_arg)
1233 return; /* default already initialized */
1234
1235 u = parse_untracked_setting_name(untracked_files_arg);
1236 if (u == SHOW_UNTRACKED_FILES_ERROR)
1237 die(_("Invalid untracked files mode '%s'"),
1238 untracked_files_arg);
1239 s->show_untracked_files = u;
1240 }
1241
1242 static const char *read_commit_message(const char *name)
1243 {
1244 const char *out_enc;
1245 struct commit *commit;
1246
1247 commit = lookup_commit_reference_by_name(name);
1248 if (!commit)
1249 die(_("could not lookup commit '%s'"), name);
1250 out_enc = get_commit_output_encoding();
1251 return repo_logmsg_reencode(the_repository, commit, NULL, out_enc);
1252 }
1253
1254 /*
1255 * Enumerate what needs to be propagated when --porcelain
1256 * is not in effect here.
1257 */
1258 static struct status_deferred_config {
1259 enum wt_status_format status_format;
1260 int show_branch;
1261 enum ahead_behind_flags ahead_behind;
1262 } status_deferred_config = {
1263 STATUS_FORMAT_UNSPECIFIED,
1264 -1, /* unspecified */
1265 AHEAD_BEHIND_UNSPECIFIED,
1266 };
1267
1268 static void finalize_deferred_config(struct wt_status *s)
1269 {
1270 int use_deferred_config = (status_format != STATUS_FORMAT_PORCELAIN &&
1271 status_format != STATUS_FORMAT_PORCELAIN_V2 &&
1272 !s->null_termination);
1273
1274 if (s->null_termination) {
1275 if (status_format == STATUS_FORMAT_NONE ||
1276 status_format == STATUS_FORMAT_UNSPECIFIED)
1277 status_format = STATUS_FORMAT_PORCELAIN;
1278 else if (status_format == STATUS_FORMAT_LONG)
1279 die(_("options '%s' and '%s' cannot be used together"), "--long", "-z");
1280 }
1281
1282 if (use_deferred_config && status_format == STATUS_FORMAT_UNSPECIFIED)
1283 status_format = status_deferred_config.status_format;
1284 if (status_format == STATUS_FORMAT_UNSPECIFIED)
1285 status_format = STATUS_FORMAT_NONE;
1286
1287 if (use_deferred_config && s->show_branch < 0)
1288 s->show_branch = status_deferred_config.show_branch;
1289 if (s->show_branch < 0)
1290 s->show_branch = 0;
1291
1292 /*
1293 * If the user did not give a "--[no]-ahead-behind" command
1294 * line argument *AND* we will print in a human-readable format
1295 * (short, long etc.) then we inherit from the status.aheadbehind
1296 * config setting. In all other cases (and porcelain V[12] formats
1297 * in particular), we inherit _FULL for backwards compatibility.
1298 */
1299 if (use_deferred_config &&
1300 s->ahead_behind_flags == AHEAD_BEHIND_UNSPECIFIED)
1301 s->ahead_behind_flags = status_deferred_config.ahead_behind;
1302
1303 if (s->ahead_behind_flags == AHEAD_BEHIND_UNSPECIFIED)
1304 s->ahead_behind_flags = AHEAD_BEHIND_FULL;
1305 }
1306
1307 static void check_fixup_reword_options(int argc, const char *argv[]) {
1308 if (whence != FROM_COMMIT) {
1309 if (whence == FROM_MERGE)
1310 die(_("You are in the middle of a merge -- cannot reword."));
1311 else if (is_from_cherry_pick(whence))
1312 die(_("You are in the middle of a cherry-pick -- cannot reword."));
1313 }
1314 if (argc)
1315 die(_("reword option of '%s' and path '%s' cannot be used together"), "--fixup", *argv);
1316 if (patch_interactive || interactive || all || also || only)
1317 die(_("reword option of '%s' and '%s' cannot be used together"),
1318 "--fixup", "--patch/--interactive/--all/--include/--only");
1319 }
1320
1321 static int parse_and_validate_options(int argc, const char *argv[],
1322 const struct option *options,
1323 const char * const usage[],
1324 const char *prefix,
1325 struct commit *current_head,
1326 struct wt_status *s)
1327 {
1328 argc = parse_options(argc, argv, prefix, options, usage, 0);
1329 finalize_deferred_config(s);
1330
1331 if (force_author && !strchr(force_author, '>'))
1332 force_author = find_author_by_nickname(force_author);
1333
1334 if (force_author && renew_authorship)
1335 die(_("options '%s' and '%s' cannot be used together"), "--reset-author", "--author");
1336
1337 if (logfile || have_option_m || use_message)
1338 use_editor = 0;
1339
1340 /* Sanity check options */
1341 if (amend) {
1342 if (!current_head)
1343 die(_("You have nothing to amend."));
1344 /*
1345 * Refuse to amend in the middle of any operation that is
1346 * meant to record its result as a new commit on top of HEAD
1347 * rather than by rewriting HEAD.
1348 */
1349 switch (sequencer_ongoing_operation(s->repo, whence)) {
1350 case ONGOING_NONE:
1351 break;
1352 case ONGOING_MERGE:
1353 die(_("You are in the middle of a merge -- cannot amend."));
1354 case ONGOING_CHERRY_PICK:
1355 die(_("You are in the middle of a cherry-pick -- cannot amend."));
1356 case ONGOING_REBASE_NOW_EMPTY:
1357 die(_("The now-empty commit has been dropped -- cannot amend."));
1358 case ONGOING_REVERT:
1359 die(_("You are in the middle of a revert -- cannot amend."));
1360 case ONGOING_AM:
1361 die(_("You are in the middle of an am session -- cannot amend."));
1362 case ONGOING_REBASE_CONFLICT:
1363 die(_("You are resolving conflicts during a rebase -- cannot amend."));
1364 }
1365 }
1366 if (fixup_message && squash_message)
1367 die(_("options '%s' and '%s' cannot be used together"), "--squash", "--fixup");
1368 die_for_incompatible_opt4(!!use_message, "-C",
1369 !!edit_message, "-c",
1370 !!logfile, "-F",
1371 !!fixup_message, "--fixup");
1372 die_for_incompatible_opt4(have_option_m, "-m",
1373 !!edit_message, "-c",
1374 !!use_message, "-C",
1375 !!logfile, "-F");
1376 if (use_message || edit_message || logfile ||fixup_message || have_option_m)
1377 FREE_AND_NULL(template_file);
1378 if (edit_message)
1379 use_message = edit_message;
1380 if (amend && !use_message && !fixup_message)
1381 use_message = "HEAD";
1382 if (!use_message && !is_from_cherry_pick(whence) &&
1383 !is_from_rebase_now_empty(whence) && renew_authorship)
1384 die(_("--reset-author can be used only with -C, -c or --amend."));
1385 if (use_message) {
1386 use_message_buffer = read_commit_message(use_message);
1387 if (!renew_authorship) {
1388 author_message = use_message;
1389 author_message_buffer = use_message_buffer;
1390 }
1391 }
1392 if ((is_from_cherry_pick(whence) || is_from_rebase_now_empty(whence)) &&
1393 !renew_authorship) {
1394 author_message = "CHERRY_PICK_HEAD";
1395 author_message_buffer = read_commit_message(author_message);
1396 }
1397
1398 if (patch_interactive)
1399 interactive = 1;
1400
1401 die_for_incompatible_opt4(also, "-i/--include",
1402 only, "-o/--only",
1403 all, "-a/--all",
1404 interactive, "--interactive/-p/--patch");
1405 if (fixup_message) {
1406 /*
1407 * We limit --fixup's suboptions to only alpha characters.
1408 * If the first character after a run of alpha is colon,
1409 * then the part before the colon may be a known suboption
1410 * name like `amend` or `reword`, or a misspelt suboption
1411 * name. In either case, we treat it as
1412 * --fixup=<suboption>:<arg>.
1413 *
1414 * Otherwise, we are dealing with --fixup=<commit>.
1415 */
1416 char *p = fixup_message;
1417 while (isalpha(*p))
1418 p++;
1419 if (p > fixup_message && *p == ':') {
1420 *p = '\0';
1421 fixup_commit = p + 1;
1422 if (!strcmp("amend", fixup_message) ||
1423 !strcmp("reword", fixup_message)) {
1424 fixup_prefix = "amend";
1425 allow_empty = 1;
1426 if (*fixup_message == 'r') {
1427 check_fixup_reword_options(argc, argv);
1428 only = 1;
1429 }
1430 } else {
1431 die(_("unknown option: --fixup=%s:%s"), fixup_message, fixup_commit);
1432 }
1433 } else {
1434 fixup_commit = fixup_message;
1435 fixup_prefix = "fixup";
1436 use_editor = 0;
1437 }
1438 }
1439
1440 if (0 <= edit_flag)
1441 use_editor = edit_flag;
1442
1443 handle_untracked_files_arg(s);
1444
1445 if (all && argc > 0)
1446 die(_("paths '%s ...' with -a does not make sense"),
1447 argv[0]);
1448
1449 if (status_format != STATUS_FORMAT_NONE)
1450 dry_run = 1;
1451
1452 return argc;
1453 }
1454
1455 static int dry_run_commit(const char **argv, const char *prefix,
1456 const struct commit *current_head, struct wt_status *s)
1457 {
1458 int committable;
1459 const char *index_file;
1460
1461 index_file = prepare_index(argv, prefix, current_head, 1);
1462 committable = run_status(stdout, index_file, prefix, 0, s);
1463 rollback_index_files();
1464
1465 return committable ? 0 : 1;
1466 }
1467
1468 define_list_config_array_extra(color_status_slots, {"added"});
1469
1470 static int parse_status_slot(const char *slot)
1471 {
1472 if (!strcasecmp(slot, "added"))
1473 return WT_STATUS_UPDATED;
1474
1475 return LOOKUP_CONFIG(color_status_slots, slot);
1476 }
1477
1478 static int git_status_config(const char *k, const char *v,
1479 const struct config_context *ctx, void *cb)
1480 {
1481 struct wt_status *s = cb;
1482 const char *slot_name;
1483
1484 if (starts_with(k, "column."))
1485 return git_column_config(k, v, "status", &s->colopts);
1486 if (!strcmp(k, "status.submodulesummary")) {
1487 int is_bool;
1488 s->submodule_summary = git_config_bool_or_int(k, v, ctx->kvi,
1489 &is_bool);
1490 if (is_bool && s->submodule_summary)
1491 s->submodule_summary = -1;
1492 return 0;
1493 }
1494 if (!strcmp(k, "status.short")) {
1495 if (git_config_bool(k, v))
1496 status_deferred_config.status_format = STATUS_FORMAT_SHORT;
1497 else
1498 status_deferred_config.status_format = STATUS_FORMAT_NONE;
1499 return 0;
1500 }
1501 if (!strcmp(k, "status.branch")) {
1502 status_deferred_config.show_branch = git_config_bool(k, v);
1503 return 0;
1504 }
1505 if (!strcmp(k, "status.aheadbehind")) {
1506 status_deferred_config.ahead_behind = git_config_bool(k, v);
1507 return 0;
1508 }
1509 if (!strcmp(k, "status.showstash")) {
1510 s->show_stash = git_config_bool(k, v);
1511 return 0;
1512 }
1513 if (!strcmp(k, "status.color") || !strcmp(k, "color.status")) {
1514 s->use_color = git_config_colorbool(k, v);
1515 return 0;
1516 }
1517 if (!strcmp(k, "status.displaycommentprefix")) {
1518 s->display_comment_prefix = git_config_bool(k, v);
1519 return 0;
1520 }
1521 if (skip_prefix(k, "status.color.", &slot_name) ||
1522 skip_prefix(k, "color.status.", &slot_name)) {
1523 int slot = parse_status_slot(slot_name);
1524 if (slot < 0)
1525 return 0;
1526 if (!v)
1527 return config_error_nonbool(k);
1528 return color_parse(v, s->color_palette[slot]);
1529 }
1530 if (!strcmp(k, "status.relativepaths")) {
1531 s->relative_paths = git_config_bool(k, v);
1532 return 0;
1533 }
1534 if (!strcmp(k, "status.showuntrackedfiles")) {
1535 enum untracked_status_type u;
1536
1537 u = parse_untracked_setting_name(v);
1538 if (u == SHOW_UNTRACKED_FILES_ERROR)
1539 return error(_("Invalid untracked files mode '%s'"), v);
1540 s->show_untracked_files = u;
1541 return 0;
1542 }
1543 if (!strcmp(k, "diff.renamelimit")) {
1544 if (s->rename_limit == -1)
1545 s->rename_limit = git_config_int(k, v, ctx->kvi);
1546 return 0;
1547 }
1548 if (!strcmp(k, "status.renamelimit")) {
1549 s->rename_limit = git_config_int(k, v, ctx->kvi);
1550 return 0;
1551 }
1552 if (!strcmp(k, "diff.renames")) {
1553 if (s->detect_rename == -1)
1554 s->detect_rename = git_config_rename(k, v);
1555 return 0;
1556 }
1557 if (!strcmp(k, "status.renames")) {
1558 s->detect_rename = git_config_rename(k, v);
1559 return 0;
1560 }
1561 return git_diff_ui_config(k, v, ctx, NULL);
1562 }
1563
1564 int cmd_status(int argc,
1565 const char **argv,
1566 const char *prefix,
1567 struct repository *repo UNUSED)
1568 {
1569 static int no_renames = -1;
1570 static const char *rename_score_arg = (const char *)-1;
1571 static struct wt_status s;
1572 unsigned int progress_flag = 0;
1573 int fd;
1574 struct object_id oid;
1575 static struct option builtin_status_options[] = {
1576 OPT__VERBOSE(&verbose, N_("be verbose")),
1577 OPT_SET_INT('s', "short", &status_format,
1578 N_("show status concisely"), STATUS_FORMAT_SHORT),
1579 OPT_BOOL('b', "branch", &s.show_branch,
1580 N_("show branch information")),
1581 OPT_BOOL(0, "show-stash", &s.show_stash,
1582 N_("show stash information")),
1583 OPT_BOOL(0, "ahead-behind", &s.ahead_behind_flags,
1584 N_("compute full ahead/behind values")),
1585 OPT_CALLBACK_F(0, "porcelain", &status_format,
1586 N_("version"), N_("machine-readable output"),
1587 PARSE_OPT_OPTARG, opt_parse_porcelain),
1588 OPT_SET_INT(0, "long", &status_format,
1589 N_("show status in long format (default)"),
1590 STATUS_FORMAT_LONG),
1591 OPT_BOOL('z', "null", &s.null_termination,
1592 N_("terminate entries with NUL")),
1593 {
1594 .type = OPTION_STRING,
1595 .short_name = 'u',
1596 .long_name = "untracked-files",
1597 .value = &untracked_files_arg,
1598 .argh = N_("mode"),
1599 .help = N_("show untracked files, optional modes: all, normal, no. (Default: all)"),
1600 .flags = PARSE_OPT_OPTARG,
1601 .defval = (intptr_t)"all",
1602 },
1603 {
1604 .type = OPTION_STRING,
1605 .long_name = "ignored",
1606 .value = &ignored_arg,
1607 .argh = N_("mode"),
1608 .help = N_("show ignored files, optional modes: traditional, matching, no. (Default: traditional)"),
1609 .flags = PARSE_OPT_OPTARG,
1610 .defval = (intptr_t)"traditional",
1611 },
1612 {
1613 .type = OPTION_STRING,
1614 .long_name = "ignore-submodules",
1615 .value = &ignore_submodule_arg,
1616 .argh = N_("when"),
1617 .help = N_("ignore changes to submodules, optional when: all, dirty, untracked. (Default: all)"),
1618 .flags = PARSE_OPT_OPTARG,
1619 .defval = (intptr_t)"all",
1620 },
1621 OPT_COLUMN(0, "column", &s.colopts, N_("list untracked files in columns")),
1622 OPT_BOOL(0, "no-renames", &no_renames, N_("do not detect renames")),
1623 OPT_CALLBACK_F('M', "find-renames", &rename_score_arg,
1624 N_("n"), N_("detect renames, optionally set similarity index"),
1625 PARSE_OPT_OPTARG | PARSE_OPT_NONEG, opt_parse_rename_score),
1626 OPT_END(),
1627 };
1628
1629 show_usage_with_options_if_asked(argc, argv,
1630 builtin_status_usage, builtin_status_options);
1631
1632 prepare_repo_settings(the_repository);
1633 the_repository->settings.command_requires_full_index = 0;
1634
1635 status_init_config(&s, git_status_config);
1636 argc = parse_options(argc, argv, prefix,
1637 builtin_status_options,
1638 builtin_status_usage, 0);
1639 finalize_colopts(&s.colopts, -1);
1640 finalize_deferred_config(&s);
1641
1642 handle_untracked_files_arg(&s);
1643 handle_ignored_arg(&s);
1644
1645 if (s.show_ignored_mode == SHOW_MATCHING_IGNORED &&
1646 s.show_untracked_files == SHOW_NO_UNTRACKED_FILES)
1647 die(_("Unsupported combination of ignored and untracked-files arguments"));
1648
1649 parse_pathspec(&s.pathspec, 0,
1650 PATHSPEC_PREFER_FULL,
1651 prefix, argv);
1652
1653 if (status_format != STATUS_FORMAT_PORCELAIN &&
1654 status_format != STATUS_FORMAT_PORCELAIN_V2)
1655 progress_flag = REFRESH_PROGRESS;
1656 repo_read_index(the_repository);
1657 refresh_index(the_repository->index,
1658 REFRESH_QUIET|REFRESH_UNMERGED|progress_flag,
1659 &s.pathspec, NULL, NULL);
1660
1661 if (use_optional_locks())
1662 fd = repo_hold_locked_index(the_repository, &index_lock, 0);
1663 else
1664 fd = -1;
1665
1666 s.is_initial = repo_get_oid(the_repository, s.reference, &oid) ? 1 : 0;
1667 if (!s.is_initial)
1668 oidcpy(&s.oid_commit, &oid);
1669
1670 s.ignore_submodule_arg = ignore_submodule_arg;
1671 s.status_format = status_format;
1672 s.verbose = verbose;
1673 if (no_renames != -1)
1674 s.detect_rename = !no_renames;
1675 if ((intptr_t)rename_score_arg != -1) {
1676 if (s.detect_rename < DIFF_DETECT_RENAME)
1677 s.detect_rename = DIFF_DETECT_RENAME;
1678 if (rename_score_arg)
1679 s.rename_score = parse_rename_score(&rename_score_arg);
1680 }
1681
1682 wt_status_collect(&s);
1683
1684 if (0 <= fd)
1685 repo_update_index_if_able(the_repository, &index_lock);
1686
1687 if (s.relative_paths)
1688 s.prefix = prefix;
1689
1690 wt_status_print(&s);
1691 wt_status_collect_free_buffers(&s);
1692
1693 return 0;
1694 }
1695
1696 static int git_commit_config(const char *k, const char *v,
1697 const struct config_context *ctx, void *cb)
1698 {
1699 struct wt_status *s = cb;
1700
1701 if (!strcmp(k, "commit.template"))
1702 return git_config_pathname(&template_file, k, v);
1703 if (!strcmp(k, "commit.status")) {
1704 include_status = git_config_bool(k, v);
1705 return 0;
1706 }
1707 if (!strcmp(k, "commit.cleanup")) {
1708 FREE_AND_NULL(cleanup_config);
1709 return git_config_string(&cleanup_config, k, v);
1710 }
1711 if (!strcmp(k, "commit.gpgsign")) {
1712 sign_commit = git_config_bool(k, v) ? "" : NULL;
1713 return 0;
1714 }
1715 if (!strcmp(k, "commit.verbose")) {
1716 int is_bool;
1717 config_commit_verbose = git_config_bool_or_int(k, v, ctx->kvi,
1718 &is_bool);
1719 return 0;
1720 }
1721
1722 return git_status_config(k, v, ctx, s);
1723 }
1724
1725 int cmd_commit(int argc,
1726 const char **argv,
1727 const char *prefix,
1728 struct repository *repo UNUSED)
1729 {
1730 static struct wt_status s;
1731 static const char *cleanup_arg = NULL;
1732 static struct option builtin_commit_options[] = {
1733 OPT__QUIET(&quiet, N_("suppress summary after successful commit")),
1734 OPT__VERBOSE(&verbose, N_("show diff in commit message template")),
1735
1736 OPT_GROUP(N_("Commit message options")),
1737 OPT_FILENAME('F', "file", &logfile, N_("read message from file")),
1738 OPT_STRING(0, "author", &force_author, N_("author"), N_("override author for commit")),
1739 OPT_STRING(0, "date", &force_date, N_("date"), N_("override date for commit")),
1740 OPT_CALLBACK('m', "message", &message, N_("message"), N_("commit message"), opt_parse_m),
1741 OPT_STRING('c', "reedit-message", &edit_message, N_("commit"), N_("reuse and edit message from specified commit")),
1742 OPT_STRING('C', "reuse-message", &use_message, N_("commit"), N_("reuse message from specified commit")),
1743 /*
1744 * TRANSLATORS: Leave "[(amend|reword):]" as-is,
1745 * and only translate <commit>.
1746 */
1747 OPT_STRING(0, "fixup", &fixup_message, N_("[(amend|reword):]commit"), N_("use autosquash formatted message to fixup or amend/reword specified commit")),
1748 OPT_STRING(0, "squash", &squash_message, N_("commit"), N_("use autosquash formatted message to squash specified commit")),
1749 OPT_BOOL(0, "reset-author", &renew_authorship, N_("the commit is authored by me now (used with -C/-c/--amend)")),
1750 OPT_STRVEC(0, "trailer", &trailer_args, N_("trailer"),
1751 N_("add custom trailer(s)")),
1752 OPT_BOOL('s', "signoff", &signoff, N_("add a Signed-off-by trailer")),
1753 OPT_FILENAME('t', "template", &template_file, N_("use specified template file")),
1754 OPT_BOOL('e', "edit", &edit_flag, N_("force edit of commit")),
1755 OPT_CLEANUP(&cleanup_arg),
1756 OPT_BOOL(0, "status", &include_status, N_("include status in commit message template")),
1757 {
1758 .type = OPTION_STRING,
1759 .short_name = 'S',
1760 .long_name = "gpg-sign",
1761 .value = &sign_commit,
1762 .argh = N_("key-id"),
1763 .help = N_("GPG sign commit"),
1764 .flags = PARSE_OPT_OPTARG,
1765 .defval = (intptr_t) "",
1766 },
1767 /* end commit message options */
1768
1769 OPT_GROUP(N_("Commit contents options")),
1770 OPT_BOOL('a', "all", &all, N_("commit all changed files")),
1771 OPT_BOOL('i', "include", &also, N_("add specified files to index for commit")),
1772 OPT_BOOL(0, "interactive", &interactive, N_("interactively add files")),
1773 OPT_BOOL('p', "patch", &patch_interactive, N_("interactively add changes")),
1774 OPT_DIFF_UNIFIED(&interactive_opts.context),
1775 OPT_DIFF_INTERHUNK_CONTEXT(&interactive_opts.interhunkcontext),
1776 OPT_BOOL('o', "only", &only, N_("commit only specified files")),
1777 OPT_BOOL('n', "no-verify", &no_verify, N_("bypass pre-commit and commit-msg hooks")),
1778 OPT_BOOL(0, "dry-run", &dry_run, N_("show what would be committed")),
1779 OPT_SET_INT(0, "short", &status_format, N_("show status concisely"),
1780 STATUS_FORMAT_SHORT),
1781 OPT_BOOL(0, "branch", &s.show_branch, N_("show branch information")),
1782 OPT_BOOL(0, "ahead-behind", &s.ahead_behind_flags,
1783 N_("compute full ahead/behind values")),
1784 OPT_SET_INT(0, "porcelain", &status_format,
1785 N_("machine-readable output"), STATUS_FORMAT_PORCELAIN),
1786 OPT_SET_INT(0, "long", &status_format,
1787 N_("show status in long format (default)"),
1788 STATUS_FORMAT_LONG),
1789 OPT_BOOL('z', "null", &s.null_termination,
1790 N_("terminate entries with NUL")),
1791 OPT_BOOL(0, "amend", &amend, N_("amend previous commit")),
1792 OPT_BOOL(0, "no-post-rewrite", &no_post_rewrite, N_("bypass post-rewrite hook")),
1793 {
1794 .type = OPTION_STRING,
1795 .short_name = 'u',
1796 .long_name = "untracked-files",
1797 .value = &untracked_files_arg,
1798 .argh = N_("mode"),
1799 .help = N_("show untracked files, optional modes: all, normal, no. (Default: all)"),
1800 .flags = PARSE_OPT_OPTARG,
1801 .defval = (intptr_t)"all",
1802 },
1803 OPT_PATHSPEC_FROM_FILE(&pathspec_from_file),
1804 OPT_PATHSPEC_FILE_NUL(&pathspec_file_nul),
1805 /* end commit contents options */
1806
1807 OPT_HIDDEN_BOOL(0, "allow-empty", &allow_empty,
1808 N_("ok to record an empty change")),
1809 OPT_HIDDEN_BOOL(0, "allow-empty-message", &allow_empty_message,
1810 N_("ok to record a change with an empty message")),
1811
1812 OPT_END()
1813 };
1814
1815 struct strbuf sb = STRBUF_INIT;
1816 struct strbuf author_ident = STRBUF_INIT;
1817 const char *index_file, *reflog_msg;
1818 struct object_id oid;
1819 struct commit_list *parents = NULL;
1820 struct stat statbuf;
1821 struct commit *current_head = NULL;
1822 struct commit_extra_header *extra = NULL;
1823 struct strbuf err = STRBUF_INIT;
1824 int ret = 0;
1825
1826 show_usage_with_options_if_asked(argc, argv,
1827 builtin_commit_usage, builtin_commit_options);
1828
1829 #ifndef WITH_BREAKING_CHANGES
1830 warn_on_auto_comment_char = true;
1831 #endif /* !WITH_BREAKING_CHANGES */
1832 prepare_repo_settings(the_repository);
1833 the_repository->settings.command_requires_full_index = 0;
1834
1835 status_init_config(&s, git_commit_config);
1836 s.commit_template = 1;
1837 status_format = STATUS_FORMAT_NONE; /* Ignore status.short */
1838 s.colopts = 0;
1839
1840 if (repo_get_oid(the_repository, "HEAD", &oid))
1841 current_head = NULL;
1842 else {
1843 current_head = lookup_commit_or_die(&oid, "HEAD");
1844 if (repo_parse_commit(the_repository, current_head))
1845 die(_("could not parse HEAD commit"));
1846 }
1847 verbose = -1; /* unspecified */
1848 argc = parse_and_validate_options(argc, argv, builtin_commit_options,
1849 builtin_commit_usage,
1850 prefix, current_head, &s);
1851 if (trailer_args.nr)
1852 trailer_config_init();
1853
1854 if (verbose == -1)
1855 verbose = (config_commit_verbose < 0) ? 0 : config_commit_verbose;
1856
1857 if (cleanup_arg) {
1858 free(cleanup_config);
1859 cleanup_config = xstrdup(cleanup_arg);
1860 }
1861 cleanup_mode = get_cleanup_mode(cleanup_config, use_editor);
1862
1863 if (dry_run)
1864 return dry_run_commit(argv, prefix, current_head, &s);
1865 index_file = prepare_index(argv, prefix, current_head, 0);
1866
1867 /* Set up everything for writing the commit object. This includes
1868 running hooks, writing the trees, and interacting with the user. */
1869 if (!prepare_to_commit(index_file, prefix,
1870 current_head, &s, &author_ident)) {
1871 ret = 1;
1872 rollback_index_files();
1873 goto cleanup;
1874 }
1875
1876 /* Determine parents */
1877 reflog_msg = getenv("GIT_REFLOG_ACTION");
1878 if (!current_head) {
1879 if (!reflog_msg)
1880 reflog_msg = "commit (initial)";
1881 } else if (amend) {
1882 if (!reflog_msg)
1883 reflog_msg = "commit (amend)";
1884 parents = commit_list_copy(current_head->parents);
1885 } else if (whence == FROM_MERGE) {
1886 struct strbuf m = STRBUF_INIT;
1887 FILE *fp;
1888 int allow_fast_forward = 1;
1889 struct commit_list **pptr = &parents;
1890
1891 if (!reflog_msg)
1892 reflog_msg = "commit (merge)";
1893 pptr = commit_list_append(current_head, pptr);
1894 fp = xfopen(git_path_merge_head(the_repository), "r");
1895 while (strbuf_getline_lf(&m, fp) != EOF) {
1896 struct commit *parent;
1897
1898 parent = get_merge_parent(m.buf);
1899 if (!parent)
1900 die(_("Corrupt MERGE_HEAD file (%s)"), m.buf);
1901 pptr = commit_list_append(parent, pptr);
1902 }
1903 fclose(fp);
1904 strbuf_release(&m);
1905 if (!stat(git_path_merge_mode(the_repository), &statbuf)) {
1906 if (strbuf_read_file(&sb, git_path_merge_mode(the_repository), 0) < 0)
1907 die_errno(_("could not read MERGE_MODE"));
1908 if (!strcmp(sb.buf, "no-ff"))
1909 allow_fast_forward = 0;
1910 }
1911 if (allow_fast_forward)
1912 reduce_heads_replace(&parents);
1913 } else {
1914 if (!reflog_msg)
1915 reflog_msg = is_from_cherry_pick(whence)
1916 ? "commit (cherry-pick)"
1917 : is_from_rebase_now_empty(whence)
1918 ? "commit (rebase)"
1919 : "commit";
1920 commit_list_insert(current_head, &parents);
1921 }
1922
1923 /* Finally, get the commit message */
1924 strbuf_reset(&sb);
1925 if (strbuf_read_file(&sb, git_path_commit_editmsg(), 0) < 0) {
1926 int saved_errno = errno;
1927 rollback_index_files();
1928 die(_("could not read commit message: %s"), strerror(saved_errno));
1929 }
1930
1931 cleanup_message(&sb, cleanup_mode, verbose);
1932
1933 if (message_is_empty(&sb, cleanup_mode) && !allow_empty_message) {
1934 rollback_index_files();
1935 fprintf(stderr, _("Aborting commit due to empty commit message.\n"));
1936 exit(1);
1937 }
1938 if (template_untouched(&sb, template_file, cleanup_mode) && !allow_empty_message) {
1939 rollback_index_files();
1940 fprintf(stderr, _("Aborting commit; you did not edit the message.\n"));
1941 exit(1);
1942 }
1943
1944 if (fixup_message && starts_with(sb.buf, "amend! ") &&
1945 !allow_empty_message) {
1946 struct strbuf body = STRBUF_INIT;
1947 size_t len = commit_subject_length(sb.buf);
1948 strbuf_addstr(&body, sb.buf + len);
1949 if (message_is_empty(&body, cleanup_mode)) {
1950 rollback_index_files();
1951 fprintf(stderr, _("Aborting commit due to empty commit message body.\n"));
1952 exit(1);
1953 }
1954 strbuf_release(&body);
1955 }
1956
1957 if (amend) {
1958 const char *exclude_gpgsig[3] = { "gpgsig", "gpgsig-sha256", NULL };
1959 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1960 } else {
1961 struct commit_extra_header **tail = &extra;
1962 append_merge_tag_headers(parents, &tail);
1963 }
1964
1965 if (commit_tree_extended(sb.buf, sb.len, &the_repository->index->cache_tree->oid,
1966 parents, &oid, author_ident.buf, NULL,
1967 sign_commit, extra)) {
1968 rollback_index_files();
1969 die(_("failed to write commit object"));
1970 }
1971
1972 if (update_head_with_reflog(current_head, &oid, reflog_msg, &sb,
1973 &err)) {
1974 rollback_index_files();
1975 die("%s", err.buf);
1976 }
1977
1978 sequencer_post_commit_cleanup(the_repository, 0);
1979 unlink(git_path_merge_head(the_repository));
1980 unlink(git_path_merge_msg(the_repository));
1981 unlink(git_path_merge_mode(the_repository));
1982 unlink(git_path_squash_msg(the_repository));
1983
1984 if (commit_index_files())
1985 die(_("repository has been updated, but unable to write\n"
1986 "new index file. Check that disk is not full and quota is\n"
1987 "not exceeded, and then \"git restore --staged :/\" to recover."));
1988
1989 git_test_write_commit_graph_or_die(the_repository->objects->sources);
1990
1991 repo_rerere(the_repository, 0);
1992 run_auto_maintenance(the_repository, quiet);
1993 run_commit_hook(use_editor, repo_get_index_file(the_repository),
1994 NULL, "post-commit", NULL);
1995 if (amend && !no_post_rewrite) {
1996 commit_post_rewrite(the_repository, current_head, &oid);
1997 }
1998 if (!quiet) {
1999 unsigned int flags = 0;
2000
2001 if (!current_head)
2002 flags |= SUMMARY_INITIAL_COMMIT;
2003 if (author_date_is_interesting())
2004 flags |= SUMMARY_SHOW_AUTHOR_DATE;
2005 print_commit_summary(the_repository, prefix,
2006 &oid, flags);
2007 }
2008
2009 apply_autostash_ref(the_repository, "MERGE_AUTOSTASH",
2010 NULL, NULL, NULL, NULL);
2011
2012 cleanup:
2013 free_commit_extra_headers(extra);
2014 commit_list_free(parents);
2015 strbuf_release(&author_ident);
2016 strbuf_release(&err);
2017 strbuf_release(&sb);
2018 free(logfile);
2019 free(template_file);
2020 return ret;
2021 }