notes.c: use designated initializers for clarity
[git/debian.git] / builtin / commit.c
blob9d8e1ea91a327248799cf137ef3c0aaf0fc65ed1
1 /*
2 * Builtin "git commit"
4 * Copyright (c) 2007 Kristian Høgsberg <krh@redhat.com>
5 * Based on git-commit.sh by Junio C Hamano and Linus Torvalds
6 */
8 #define USE_THE_INDEX_VARIABLE
9 #include "cache.h"
10 #include "config.h"
11 #include "lockfile.h"
12 #include "cache-tree.h"
13 #include "color.h"
14 #include "dir.h"
15 #include "environment.h"
16 #include "builtin.h"
17 #include "diff.h"
18 #include "diffcore.h"
19 #include "commit.h"
20 #include "gettext.h"
21 #include "revision.h"
22 #include "wt-status.h"
23 #include "run-command.h"
24 #include "hook.h"
25 #include "refs.h"
26 #include "log-tree.h"
27 #include "strbuf.h"
28 #include "utf8.h"
29 #include "parse-options.h"
30 #include "string-list.h"
31 #include "rerere.h"
32 #include "unpack-trees.h"
33 #include "quote.h"
34 #include "submodule.h"
35 #include "gpg-interface.h"
36 #include "column.h"
37 #include "sequencer.h"
38 #include "mailmap.h"
39 #include "help.h"
40 #include "commit-reach.h"
41 #include "commit-graph.h"
42 #include "pretty.h"
44 static const char * const builtin_commit_usage[] = {
45 N_("git commit [-a | --interactive | --patch] [-s] [-v] [-u<mode>] [--amend]\n"
46 " [--dry-run] [(-c | -C | --squash) <commit> | --fixup [(amend|reword):]<commit>)]\n"
47 " [-F <file> | -m <msg>] [--reset-author] [--allow-empty]\n"
48 " [--allow-empty-message] [--no-verify] [-e] [--author=<author>]\n"
49 " [--date=<date>] [--cleanup=<mode>] [--[no-]status]\n"
50 " [-i | -o] [--pathspec-from-file=<file> [--pathspec-file-nul]]\n"
51 " [(--trailer <token>[(=|:)<value>])...] [-S[<keyid>]]\n"
52 " [--] [<pathspec>...]"),
53 NULL
56 static const char * const builtin_status_usage[] = {
57 N_("git status [<options>] [--] [<pathspec>...]"),
58 NULL
61 static const char empty_amend_advice[] =
62 N_("You asked to amend the most recent commit, but doing so would make\n"
63 "it empty. You can repeat your command with --allow-empty, or you can\n"
64 "remove the commit entirely with \"git reset HEAD^\".\n");
66 static const char empty_cherry_pick_advice[] =
67 N_("The previous cherry-pick is now empty, possibly due to conflict resolution.\n"
68 "If you wish to commit it anyway, use:\n"
69 "\n"
70 " git commit --allow-empty\n"
71 "\n");
73 static const char empty_rebase_pick_advice[] =
74 N_("Otherwise, please use 'git rebase --skip'\n");
76 static const char empty_cherry_pick_advice_single[] =
77 N_("Otherwise, please use 'git cherry-pick --skip'\n");
79 static const char empty_cherry_pick_advice_multi[] =
80 N_("and then use:\n"
81 "\n"
82 " git cherry-pick --continue\n"
83 "\n"
84 "to resume cherry-picking the remaining commits.\n"
85 "If you wish to skip this commit, use:\n"
86 "\n"
87 " git cherry-pick --skip\n"
88 "\n");
90 static const char *color_status_slots[] = {
91 [WT_STATUS_HEADER] = "header",
92 [WT_STATUS_UPDATED] = "updated",
93 [WT_STATUS_CHANGED] = "changed",
94 [WT_STATUS_UNTRACKED] = "untracked",
95 [WT_STATUS_NOBRANCH] = "noBranch",
96 [WT_STATUS_UNMERGED] = "unmerged",
97 [WT_STATUS_LOCAL_BRANCH] = "localBranch",
98 [WT_STATUS_REMOTE_BRANCH] = "remoteBranch",
99 [WT_STATUS_ONBRANCH] = "branch",
102 static const char *use_message_buffer;
103 static struct lock_file index_lock; /* real index */
104 static struct lock_file false_lock; /* used only for partial commits */
105 static enum {
106 COMMIT_AS_IS = 1,
107 COMMIT_NORMAL,
108 COMMIT_PARTIAL
109 } commit_style;
111 static const char *logfile, *force_author;
112 static const char *template_file;
114 * The _message variables are commit names from which to take
115 * the commit message and/or authorship.
117 static const char *author_message, *author_message_buffer;
118 static char *edit_message, *use_message;
119 static char *fixup_message, *fixup_commit, *squash_message;
120 static const char *fixup_prefix;
121 static int all, also, interactive, patch_interactive, only, amend, signoff;
122 static int edit_flag = -1; /* unspecified */
123 static int quiet, verbose, no_verify, allow_empty, dry_run, renew_authorship;
124 static int config_commit_verbose = -1; /* unspecified */
125 static int no_post_rewrite, allow_empty_message, pathspec_file_nul;
126 static char *untracked_files_arg, *force_date, *ignore_submodule_arg, *ignored_arg;
127 static char *sign_commit, *pathspec_from_file;
128 static struct strvec trailer_args = STRVEC_INIT;
131 * The default commit message cleanup mode will remove the lines
132 * beginning with # (shell comments) and leading and trailing
133 * whitespaces (empty lines or containing only whitespaces)
134 * if editor is used, and only the whitespaces if the message
135 * is specified explicitly.
137 static enum commit_msg_cleanup_mode cleanup_mode;
138 static const char *cleanup_arg;
140 static enum commit_whence whence;
141 static int use_editor = 1, include_status = 1;
142 static int have_option_m;
143 static struct strbuf message = STRBUF_INIT;
145 static enum wt_status_format status_format = STATUS_FORMAT_UNSPECIFIED;
147 static int opt_pass_trailer(const struct option *opt, const char *arg, int unset)
149 BUG_ON_OPT_NEG(unset);
151 strvec_pushl(opt->value, "--trailer", arg, NULL);
152 return 0;
155 static int opt_parse_porcelain(const struct option *opt, const char *arg, int unset)
157 enum wt_status_format *value = (enum wt_status_format *)opt->value;
158 if (unset)
159 *value = STATUS_FORMAT_NONE;
160 else if (!arg)
161 *value = STATUS_FORMAT_PORCELAIN;
162 else if (!strcmp(arg, "v1") || !strcmp(arg, "1"))
163 *value = STATUS_FORMAT_PORCELAIN;
164 else if (!strcmp(arg, "v2") || !strcmp(arg, "2"))
165 *value = STATUS_FORMAT_PORCELAIN_V2;
166 else
167 die("unsupported porcelain version '%s'", arg);
169 return 0;
172 static int opt_parse_m(const struct option *opt, const char *arg, int unset)
174 struct strbuf *buf = opt->value;
175 if (unset) {
176 have_option_m = 0;
177 strbuf_setlen(buf, 0);
178 } else {
179 have_option_m = 1;
180 if (buf->len)
181 strbuf_addch(buf, '\n');
182 strbuf_addstr(buf, arg);
183 strbuf_complete_line(buf);
185 return 0;
188 static int opt_parse_rename_score(const struct option *opt, const char *arg, int unset)
190 const char **value = opt->value;
192 BUG_ON_OPT_NEG(unset);
194 if (arg != NULL && *arg == '=')
195 arg = arg + 1;
197 *value = arg;
198 return 0;
201 static void determine_whence(struct wt_status *s)
203 if (file_exists(git_path_merge_head(the_repository)))
204 whence = FROM_MERGE;
205 else if (!sequencer_determine_whence(the_repository, &whence))
206 whence = FROM_COMMIT;
207 if (s)
208 s->whence = whence;
211 static void status_init_config(struct wt_status *s, config_fn_t fn)
213 wt_status_prepare(the_repository, s);
214 init_diff_ui_defaults();
215 git_config(fn, s);
216 determine_whence(s);
217 s->hints = advice_enabled(ADVICE_STATUS_HINTS); /* must come after git_config() */
220 static void rollback_index_files(void)
222 switch (commit_style) {
223 case COMMIT_AS_IS:
224 break; /* nothing to do */
225 case COMMIT_NORMAL:
226 rollback_lock_file(&index_lock);
227 break;
228 case COMMIT_PARTIAL:
229 rollback_lock_file(&index_lock);
230 rollback_lock_file(&false_lock);
231 break;
235 static int commit_index_files(void)
237 int err = 0;
239 switch (commit_style) {
240 case COMMIT_AS_IS:
241 break; /* nothing to do */
242 case COMMIT_NORMAL:
243 err = commit_lock_file(&index_lock);
244 break;
245 case COMMIT_PARTIAL:
246 err = commit_lock_file(&index_lock);
247 rollback_lock_file(&false_lock);
248 break;
251 return err;
255 * Take a union of paths in the index and the named tree (typically, "HEAD"),
256 * and return the paths that match the given pattern in list.
258 static int list_paths(struct string_list *list, const char *with_tree,
259 const struct pathspec *pattern)
261 int i, ret;
262 char *m;
264 if (!pattern->nr)
265 return 0;
267 m = xcalloc(1, pattern->nr);
269 if (with_tree) {
270 char *max_prefix = common_prefix(pattern);
271 overlay_tree_on_index(&the_index, with_tree, max_prefix);
272 free(max_prefix);
275 /* TODO: audit for interaction with sparse-index. */
276 ensure_full_index(&the_index);
277 for (i = 0; i < the_index.cache_nr; i++) {
278 const struct cache_entry *ce = the_index.cache[i];
279 struct string_list_item *item;
281 if (ce->ce_flags & CE_UPDATE)
282 continue;
283 if (!ce_path_match(&the_index, ce, pattern, m))
284 continue;
285 item = string_list_insert(list, ce->name);
286 if (ce_skip_worktree(ce))
287 item->util = item; /* better a valid pointer than a fake one */
290 ret = report_path_error(m, pattern);
291 free(m);
292 return ret;
295 static void add_remove_files(struct string_list *list)
297 int i;
298 for (i = 0; i < list->nr; i++) {
299 struct stat st;
300 struct string_list_item *p = &(list->items[i]);
302 /* p->util is skip-worktree */
303 if (p->util)
304 continue;
306 if (!lstat(p->string, &st)) {
307 if (add_to_index(&the_index, p->string, &st, 0))
308 die(_("updating files failed"));
309 } else
310 remove_file_from_index(&the_index, p->string);
314 static void create_base_index(const struct commit *current_head)
316 struct tree *tree;
317 struct unpack_trees_options opts;
318 struct tree_desc t;
320 if (!current_head) {
321 discard_index(&the_index);
322 return;
325 memset(&opts, 0, sizeof(opts));
326 opts.head_idx = 1;
327 opts.index_only = 1;
328 opts.merge = 1;
329 opts.src_index = &the_index;
330 opts.dst_index = &the_index;
332 opts.fn = oneway_merge;
333 tree = parse_tree_indirect(&current_head->object.oid);
334 if (!tree)
335 die(_("failed to unpack HEAD tree object"));
336 parse_tree(tree);
337 init_tree_desc(&t, tree->buffer, tree->size);
338 if (unpack_trees(1, &t, &opts))
339 exit(128); /* We've already reported the error, finish dying */
342 static void refresh_cache_or_die(int refresh_flags)
345 * refresh_flags contains REFRESH_QUIET, so the only errors
346 * are for unmerged entries.
348 if (refresh_index(&the_index, refresh_flags | REFRESH_IN_PORCELAIN, NULL, NULL, NULL))
349 die_resolve_conflict("commit");
352 static const char *prepare_index(const char **argv, const char *prefix,
353 const struct commit *current_head, int is_status)
355 struct string_list partial = STRING_LIST_INIT_DUP;
356 struct pathspec pathspec;
357 int refresh_flags = REFRESH_QUIET;
358 const char *ret;
360 if (is_status)
361 refresh_flags |= REFRESH_UNMERGED;
362 parse_pathspec(&pathspec, 0,
363 PATHSPEC_PREFER_FULL,
364 prefix, argv);
366 if (pathspec_from_file) {
367 if (interactive)
368 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--interactive/--patch");
370 if (all)
371 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "-a");
373 if (pathspec.nr)
374 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
376 parse_pathspec_file(&pathspec, 0,
377 PATHSPEC_PREFER_FULL,
378 prefix, pathspec_from_file, pathspec_file_nul);
379 } else if (pathspec_file_nul) {
380 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
383 if (!pathspec.nr && (also || (only && !allow_empty &&
384 (!amend || (fixup_message && strcmp(fixup_prefix, "amend"))))))
385 die(_("No paths with --include/--only does not make sense."));
387 if (repo_read_index_preload(the_repository, &pathspec, 0) < 0)
388 die(_("index file corrupt"));
390 if (interactive) {
391 char *old_index_env = NULL, *old_repo_index_file;
392 repo_hold_locked_index(the_repository, &index_lock,
393 LOCK_DIE_ON_ERROR);
395 refresh_cache_or_die(refresh_flags);
397 if (write_locked_index(&the_index, &index_lock, 0))
398 die(_("unable to create temporary index"));
400 old_repo_index_file = the_repository->index_file;
401 the_repository->index_file =
402 (char *)get_lock_file_path(&index_lock);
403 old_index_env = xstrdup_or_null(getenv(INDEX_ENVIRONMENT));
404 setenv(INDEX_ENVIRONMENT, the_repository->index_file, 1);
406 if (interactive_add(argv, prefix, patch_interactive) != 0)
407 die(_("interactive add failed"));
409 the_repository->index_file = old_repo_index_file;
410 if (old_index_env && *old_index_env)
411 setenv(INDEX_ENVIRONMENT, old_index_env, 1);
412 else
413 unsetenv(INDEX_ENVIRONMENT);
414 FREE_AND_NULL(old_index_env);
416 discard_index(&the_index);
417 read_index_from(&the_index, get_lock_file_path(&index_lock),
418 get_git_dir());
419 if (cache_tree_update(&the_index, WRITE_TREE_SILENT) == 0) {
420 if (reopen_lock_file(&index_lock) < 0)
421 die(_("unable to write index file"));
422 if (write_locked_index(&the_index, &index_lock, 0))
423 die(_("unable to update temporary index"));
424 } else
425 warning(_("Failed to update main cache tree"));
427 commit_style = COMMIT_NORMAL;
428 ret = get_lock_file_path(&index_lock);
429 goto out;
433 * Non partial, non as-is commit.
435 * (1) get the real index;
436 * (2) update the_index as necessary;
437 * (3) write the_index out to the real index (still locked);
438 * (4) return the name of the locked index file.
440 * The caller should run hooks on the locked real index, and
441 * (A) if all goes well, commit the real index;
442 * (B) on failure, rollback the real index.
444 if (all || (also && pathspec.nr)) {
445 repo_hold_locked_index(the_repository, &index_lock,
446 LOCK_DIE_ON_ERROR);
447 add_files_to_cache(also ? prefix : NULL, &pathspec, 0);
448 refresh_cache_or_die(refresh_flags);
449 cache_tree_update(&the_index, WRITE_TREE_SILENT);
450 if (write_locked_index(&the_index, &index_lock, 0))
451 die(_("unable to write new_index file"));
452 commit_style = COMMIT_NORMAL;
453 ret = get_lock_file_path(&index_lock);
454 goto out;
458 * As-is commit.
460 * (1) return the name of the real index file.
462 * The caller should run hooks on the real index,
463 * and create commit from the_index.
464 * We still need to refresh the index here.
466 if (!only && !pathspec.nr) {
467 repo_hold_locked_index(the_repository, &index_lock,
468 LOCK_DIE_ON_ERROR);
469 refresh_cache_or_die(refresh_flags);
470 if (the_index.cache_changed
471 || !cache_tree_fully_valid(the_index.cache_tree))
472 cache_tree_update(&the_index, WRITE_TREE_SILENT);
473 if (write_locked_index(&the_index, &index_lock,
474 COMMIT_LOCK | SKIP_IF_UNCHANGED))
475 die(_("unable to write new_index file"));
476 commit_style = COMMIT_AS_IS;
477 ret = get_index_file();
478 goto out;
482 * A partial commit.
484 * (0) find the set of affected paths;
485 * (1) get lock on the real index file;
486 * (2) update the_index with the given paths;
487 * (3) write the_index out to the real index (still locked);
488 * (4) get lock on the false index file;
489 * (5) reset the_index from HEAD;
490 * (6) update the_index the same way as (2);
491 * (7) write the_index out to the false index file;
492 * (8) return the name of the false index file (still locked);
494 * The caller should run hooks on the locked false index, and
495 * create commit from it. Then
496 * (A) if all goes well, commit the real index;
497 * (B) on failure, rollback the real index;
498 * In either case, rollback the false index.
500 commit_style = COMMIT_PARTIAL;
502 if (whence != FROM_COMMIT) {
503 if (whence == FROM_MERGE)
504 die(_("cannot do a partial commit during a merge."));
505 else if (is_from_cherry_pick(whence))
506 die(_("cannot do a partial commit during a cherry-pick."));
507 else if (is_from_rebase(whence))
508 die(_("cannot do a partial commit during a rebase."));
511 if (list_paths(&partial, !current_head ? NULL : "HEAD", &pathspec))
512 exit(1);
514 discard_index(&the_index);
515 if (repo_read_index(the_repository) < 0)
516 die(_("cannot read the index"));
518 repo_hold_locked_index(the_repository, &index_lock, LOCK_DIE_ON_ERROR);
519 add_remove_files(&partial);
520 refresh_index(&the_index, REFRESH_QUIET, NULL, NULL, NULL);
521 cache_tree_update(&the_index, WRITE_TREE_SILENT);
522 if (write_locked_index(&the_index, &index_lock, 0))
523 die(_("unable to write new_index file"));
525 hold_lock_file_for_update(&false_lock,
526 git_path("next-index-%"PRIuMAX,
527 (uintmax_t) getpid()),
528 LOCK_DIE_ON_ERROR);
530 create_base_index(current_head);
531 add_remove_files(&partial);
532 refresh_index(&the_index, REFRESH_QUIET, NULL, NULL, NULL);
534 if (write_locked_index(&the_index, &false_lock, 0))
535 die(_("unable to write temporary index file"));
537 discard_index(&the_index);
538 ret = get_lock_file_path(&false_lock);
539 read_index_from(&the_index, ret, get_git_dir());
540 out:
541 string_list_clear(&partial, 0);
542 clear_pathspec(&pathspec);
543 return ret;
546 static int run_status(FILE *fp, const char *index_file, const char *prefix, int nowarn,
547 struct wt_status *s)
549 struct object_id oid;
551 if (s->relative_paths)
552 s->prefix = prefix;
554 if (amend) {
555 s->amend = 1;
556 s->reference = "HEAD^1";
558 s->verbose = verbose;
559 s->index_file = index_file;
560 s->fp = fp;
561 s->nowarn = nowarn;
562 s->is_initial = repo_get_oid(the_repository, s->reference, &oid) ? 1 : 0;
563 if (!s->is_initial)
564 oidcpy(&s->oid_commit, &oid);
565 s->status_format = status_format;
566 s->ignore_submodule_arg = ignore_submodule_arg;
568 wt_status_collect(s);
569 wt_status_print(s);
570 wt_status_collect_free_buffers(s);
572 return s->committable;
575 static int is_a_merge(const struct commit *current_head)
577 return !!(current_head->parents && current_head->parents->next);
580 static void assert_split_ident(struct ident_split *id, const struct strbuf *buf)
582 if (split_ident_line(id, buf->buf, buf->len) || !id->date_begin)
583 BUG("unable to parse our own ident: %s", buf->buf);
586 static void export_one(const char *var, const char *s, const char *e, int hack)
588 struct strbuf buf = STRBUF_INIT;
589 if (hack)
590 strbuf_addch(&buf, hack);
591 strbuf_add(&buf, s, e - s);
592 setenv(var, buf.buf, 1);
593 strbuf_release(&buf);
596 static int parse_force_date(const char *in, struct strbuf *out)
598 strbuf_addch(out, '@');
600 if (parse_date(in, out) < 0) {
601 int errors = 0;
602 unsigned long t = approxidate_careful(in, &errors);
603 if (errors)
604 return -1;
605 strbuf_addf(out, "%lu", t);
608 return 0;
611 static void set_ident_var(char **buf, char *val)
613 free(*buf);
614 *buf = val;
617 static void determine_author_info(struct strbuf *author_ident)
619 char *name, *email, *date;
620 struct ident_split author;
622 name = xstrdup_or_null(getenv("GIT_AUTHOR_NAME"));
623 email = xstrdup_or_null(getenv("GIT_AUTHOR_EMAIL"));
624 date = xstrdup_or_null(getenv("GIT_AUTHOR_DATE"));
626 if (author_message) {
627 struct ident_split ident;
628 size_t len;
629 const char *a;
631 a = find_commit_header(author_message_buffer, "author", &len);
632 if (!a)
633 die(_("commit '%s' lacks author header"), author_message);
634 if (split_ident_line(&ident, a, len) < 0)
635 die(_("commit '%s' has malformed author line"), author_message);
637 set_ident_var(&name, xmemdupz(ident.name_begin, ident.name_end - ident.name_begin));
638 set_ident_var(&email, xmemdupz(ident.mail_begin, ident.mail_end - ident.mail_begin));
640 if (ident.date_begin) {
641 struct strbuf date_buf = STRBUF_INIT;
642 strbuf_addch(&date_buf, '@');
643 strbuf_add(&date_buf, ident.date_begin, ident.date_end - ident.date_begin);
644 strbuf_addch(&date_buf, ' ');
645 strbuf_add(&date_buf, ident.tz_begin, ident.tz_end - ident.tz_begin);
646 set_ident_var(&date, strbuf_detach(&date_buf, NULL));
650 if (force_author) {
651 struct ident_split ident;
653 if (split_ident_line(&ident, force_author, strlen(force_author)) < 0)
654 die(_("malformed --author parameter"));
655 set_ident_var(&name, xmemdupz(ident.name_begin, ident.name_end - ident.name_begin));
656 set_ident_var(&email, xmemdupz(ident.mail_begin, ident.mail_end - ident.mail_begin));
659 if (force_date) {
660 struct strbuf date_buf = STRBUF_INIT;
661 if (parse_force_date(force_date, &date_buf))
662 die(_("invalid date format: %s"), force_date);
663 set_ident_var(&date, strbuf_detach(&date_buf, NULL));
666 strbuf_addstr(author_ident, fmt_ident(name, email, WANT_AUTHOR_IDENT, date,
667 IDENT_STRICT));
668 assert_split_ident(&author, author_ident);
669 export_one("GIT_AUTHOR_NAME", author.name_begin, author.name_end, 0);
670 export_one("GIT_AUTHOR_EMAIL", author.mail_begin, author.mail_end, 0);
671 export_one("GIT_AUTHOR_DATE", author.date_begin, author.tz_end, '@');
672 free(name);
673 free(email);
674 free(date);
677 static int author_date_is_interesting(void)
679 return author_message || force_date;
682 static void adjust_comment_line_char(const struct strbuf *sb)
684 char candidates[] = "#;@!$%^&|:";
685 char *candidate;
686 const char *p;
688 comment_line_char = candidates[0];
689 if (!memchr(sb->buf, comment_line_char, sb->len))
690 return;
692 p = sb->buf;
693 candidate = strchr(candidates, *p);
694 if (candidate)
695 *candidate = ' ';
696 for (p = sb->buf; *p; p++) {
697 if ((p[0] == '\n' || p[0] == '\r') && p[1]) {
698 candidate = strchr(candidates, p[1]);
699 if (candidate)
700 *candidate = ' ';
704 for (p = candidates; *p == ' '; p++)
706 if (!*p)
707 die(_("unable to select a comment character that is not used\n"
708 "in the current commit message"));
709 comment_line_char = *p;
712 static void prepare_amend_commit(struct commit *commit, struct strbuf *sb,
713 struct pretty_print_context *ctx)
715 const char *buffer, *subject, *fmt;
717 buffer = repo_get_commit_buffer(the_repository, commit, NULL);
718 find_commit_subject(buffer, &subject);
720 * If we amend the 'amend!' commit then we don't want to
721 * duplicate the subject line.
723 fmt = starts_with(subject, "amend!") ? "%b" : "%B";
724 repo_format_commit_message(the_repository, commit, fmt, sb, ctx);
725 repo_unuse_commit_buffer(the_repository, commit, buffer);
728 static int prepare_to_commit(const char *index_file, const char *prefix,
729 struct commit *current_head,
730 struct wt_status *s,
731 struct strbuf *author_ident)
733 struct stat statbuf;
734 struct strbuf committer_ident = STRBUF_INIT;
735 int committable;
736 struct strbuf sb = STRBUF_INIT;
737 const char *hook_arg1 = NULL;
738 const char *hook_arg2 = NULL;
739 int clean_message_contents = (cleanup_mode != COMMIT_MSG_CLEANUP_NONE);
740 int old_display_comment_prefix;
741 int merge_contains_scissors = 0;
742 int invoked_hook;
744 /* This checks and barfs if author is badly specified */
745 determine_author_info(author_ident);
747 if (!no_verify && run_commit_hook(use_editor, index_file, &invoked_hook,
748 "pre-commit", NULL))
749 return 0;
751 if (squash_message) {
753 * Insert the proper subject line before other commit
754 * message options add their content.
756 if (use_message && !strcmp(use_message, squash_message))
757 strbuf_addstr(&sb, "squash! ");
758 else {
759 struct pretty_print_context ctx = {0};
760 struct commit *c;
761 c = lookup_commit_reference_by_name(squash_message);
762 if (!c)
763 die(_("could not lookup commit %s"), squash_message);
764 ctx.output_encoding = get_commit_output_encoding();
765 repo_format_commit_message(the_repository, c,
766 "squash! %s\n\n", &sb,
767 &ctx);
771 if (have_option_m && !fixup_message) {
772 strbuf_addbuf(&sb, &message);
773 hook_arg1 = "message";
774 } else if (logfile && !strcmp(logfile, "-")) {
775 if (isatty(0))
776 fprintf(stderr, _("(reading log message from standard input)\n"));
777 if (strbuf_read(&sb, 0, 0) < 0)
778 die_errno(_("could not read log from standard input"));
779 hook_arg1 = "message";
780 } else if (logfile) {
781 if (strbuf_read_file(&sb, logfile, 0) < 0)
782 die_errno(_("could not read log file '%s'"),
783 logfile);
784 hook_arg1 = "message";
785 } else if (use_message) {
786 char *buffer;
787 buffer = strstr(use_message_buffer, "\n\n");
788 if (buffer)
789 strbuf_addstr(&sb, skip_blank_lines(buffer + 2));
790 hook_arg1 = "commit";
791 hook_arg2 = use_message;
792 } else if (fixup_message) {
793 struct pretty_print_context ctx = {0};
794 struct commit *commit;
795 char *fmt;
796 commit = lookup_commit_reference_by_name(fixup_commit);
797 if (!commit)
798 die(_("could not lookup commit %s"), fixup_commit);
799 ctx.output_encoding = get_commit_output_encoding();
800 fmt = xstrfmt("%s! %%s\n\n", fixup_prefix);
801 repo_format_commit_message(the_repository, commit, fmt, &sb,
802 &ctx);
803 free(fmt);
804 hook_arg1 = "message";
807 * Only `-m` commit message option is checked here, as
808 * it supports `--fixup` to append the commit message.
810 * The other commit message options `-c`/`-C`/`-F` are
811 * incompatible with all the forms of `--fixup` and
812 * have already errored out while parsing the `git commit`
813 * options.
815 if (have_option_m && !strcmp(fixup_prefix, "fixup"))
816 strbuf_addbuf(&sb, &message);
818 if (!strcmp(fixup_prefix, "amend")) {
819 if (have_option_m)
820 die(_("options '%s' and '%s:%s' cannot be used together"), "-m", "--fixup", fixup_message);
821 prepare_amend_commit(commit, &sb, &ctx);
823 } else if (!stat(git_path_merge_msg(the_repository), &statbuf)) {
824 size_t merge_msg_start;
827 * prepend SQUASH_MSG here if it exists and a
828 * "merge --squash" was originally performed
830 if (!stat(git_path_squash_msg(the_repository), &statbuf)) {
831 if (strbuf_read_file(&sb, git_path_squash_msg(the_repository), 0) < 0)
832 die_errno(_("could not read SQUASH_MSG"));
833 hook_arg1 = "squash";
834 } else
835 hook_arg1 = "merge";
837 merge_msg_start = sb.len;
838 if (strbuf_read_file(&sb, git_path_merge_msg(the_repository), 0) < 0)
839 die_errno(_("could not read MERGE_MSG"));
841 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS &&
842 wt_status_locate_end(sb.buf + merge_msg_start,
843 sb.len - merge_msg_start) <
844 sb.len - merge_msg_start)
845 merge_contains_scissors = 1;
846 } else if (!stat(git_path_squash_msg(the_repository), &statbuf)) {
847 if (strbuf_read_file(&sb, git_path_squash_msg(the_repository), 0) < 0)
848 die_errno(_("could not read SQUASH_MSG"));
849 hook_arg1 = "squash";
850 } else if (template_file) {
851 if (strbuf_read_file(&sb, template_file, 0) < 0)
852 die_errno(_("could not read '%s'"), template_file);
853 hook_arg1 = "template";
854 clean_message_contents = 0;
858 * The remaining cases don't modify the template message, but
859 * just set the argument(s) to the prepare-commit-msg hook.
861 else if (whence == FROM_MERGE)
862 hook_arg1 = "merge";
863 else if (is_from_cherry_pick(whence) || whence == FROM_REBASE_PICK) {
864 hook_arg1 = "commit";
865 hook_arg2 = "CHERRY_PICK_HEAD";
868 if (squash_message) {
870 * If squash_commit was used for the commit subject,
871 * then we're possibly hijacking other commit log options.
872 * Reset the hook args to tell the real story.
874 hook_arg1 = "message";
875 hook_arg2 = "";
878 s->fp = fopen_for_writing(git_path_commit_editmsg());
879 if (!s->fp)
880 die_errno(_("could not open '%s'"), git_path_commit_editmsg());
882 /* Ignore status.displayCommentPrefix: we do need comments in COMMIT_EDITMSG. */
883 old_display_comment_prefix = s->display_comment_prefix;
884 s->display_comment_prefix = 1;
887 * Most hints are counter-productive when the commit has
888 * already started.
890 s->hints = 0;
892 if (clean_message_contents)
893 strbuf_stripspace(&sb, 0);
895 if (signoff)
896 append_signoff(&sb, ignore_non_trailer(sb.buf, sb.len), 0);
898 if (fwrite(sb.buf, 1, sb.len, s->fp) < sb.len)
899 die_errno(_("could not write commit template"));
901 if (auto_comment_line_char)
902 adjust_comment_line_char(&sb);
903 strbuf_release(&sb);
905 /* This checks if committer ident is explicitly given */
906 strbuf_addstr(&committer_ident, git_committer_info(IDENT_STRICT));
907 if (use_editor && include_status) {
908 int ident_shown = 0;
909 int saved_color_setting;
910 struct ident_split ci, ai;
911 const char *hint_cleanup_all = allow_empty_message ?
912 _("Please enter the commit message for your changes."
913 " Lines starting\nwith '%c' will be ignored.\n") :
914 _("Please enter the commit message for your changes."
915 " Lines starting\nwith '%c' will be ignored, and an empty"
916 " message aborts the commit.\n");
917 const char *hint_cleanup_space = allow_empty_message ?
918 _("Please enter the commit message for your changes."
919 " Lines starting\n"
920 "with '%c' will be kept; you may remove them"
921 " yourself if you want to.\n") :
922 _("Please enter the commit message for your changes."
923 " Lines starting\n"
924 "with '%c' will be kept; you may remove them"
925 " yourself if you want to.\n"
926 "An empty message aborts the commit.\n");
927 if (whence != FROM_COMMIT) {
928 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS &&
929 !merge_contains_scissors)
930 wt_status_add_cut_line(s->fp);
931 status_printf_ln(
932 s, GIT_COLOR_NORMAL,
933 whence == FROM_MERGE ?
934 _("\n"
935 "It looks like you may be committing a merge.\n"
936 "If this is not correct, please run\n"
937 " git update-ref -d MERGE_HEAD\n"
938 "and try again.\n") :
939 _("\n"
940 "It looks like you may be committing a cherry-pick.\n"
941 "If this is not correct, please run\n"
942 " git update-ref -d CHERRY_PICK_HEAD\n"
943 "and try again.\n"));
946 fprintf(s->fp, "\n");
947 if (cleanup_mode == COMMIT_MSG_CLEANUP_ALL)
948 status_printf(s, GIT_COLOR_NORMAL, hint_cleanup_all, comment_line_char);
949 else if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
950 if (whence == FROM_COMMIT && !merge_contains_scissors)
951 wt_status_add_cut_line(s->fp);
952 } else /* COMMIT_MSG_CLEANUP_SPACE, that is. */
953 status_printf(s, GIT_COLOR_NORMAL, hint_cleanup_space, comment_line_char);
956 * These should never fail because they come from our own
957 * fmt_ident. They may fail the sane_ident test, but we know
958 * that the name and mail pointers will at least be valid,
959 * which is enough for our tests and printing here.
961 assert_split_ident(&ai, author_ident);
962 assert_split_ident(&ci, &committer_ident);
964 if (ident_cmp(&ai, &ci))
965 status_printf_ln(s, GIT_COLOR_NORMAL,
966 _("%s"
967 "Author: %.*s <%.*s>"),
968 ident_shown++ ? "" : "\n",
969 (int)(ai.name_end - ai.name_begin), ai.name_begin,
970 (int)(ai.mail_end - ai.mail_begin), ai.mail_begin);
972 if (author_date_is_interesting())
973 status_printf_ln(s, GIT_COLOR_NORMAL,
974 _("%s"
975 "Date: %s"),
976 ident_shown++ ? "" : "\n",
977 show_ident_date(&ai, DATE_MODE(NORMAL)));
979 if (!committer_ident_sufficiently_given())
980 status_printf_ln(s, GIT_COLOR_NORMAL,
981 _("%s"
982 "Committer: %.*s <%.*s>"),
983 ident_shown++ ? "" : "\n",
984 (int)(ci.name_end - ci.name_begin), ci.name_begin,
985 (int)(ci.mail_end - ci.mail_begin), ci.mail_begin);
987 status_printf_ln(s, GIT_COLOR_NORMAL, "%s", ""); /* Add new line for clarity */
989 saved_color_setting = s->use_color;
990 s->use_color = 0;
991 committable = run_status(s->fp, index_file, prefix, 1, s);
992 s->use_color = saved_color_setting;
993 string_list_clear(&s->change, 1);
994 } else {
995 struct object_id oid;
996 const char *parent = "HEAD";
998 if (!the_index.cache_nr) {
999 discard_index(&the_index);
1000 if (repo_read_index(the_repository) < 0)
1001 die(_("Cannot read index"));
1004 if (amend)
1005 parent = "HEAD^1";
1007 if (repo_get_oid(the_repository, parent, &oid)) {
1008 int i, ita_nr = 0;
1010 /* TODO: audit for interaction with sparse-index. */
1011 ensure_full_index(&the_index);
1012 for (i = 0; i < the_index.cache_nr; i++)
1013 if (ce_intent_to_add(the_index.cache[i]))
1014 ita_nr++;
1015 committable = the_index.cache_nr - ita_nr > 0;
1016 } else {
1018 * Unless the user did explicitly request a submodule
1019 * ignore mode by passing a command line option we do
1020 * not ignore any changed submodule SHA-1s when
1021 * comparing index and parent, no matter what is
1022 * configured. Otherwise we won't commit any
1023 * submodules which were manually staged, which would
1024 * be really confusing.
1026 struct diff_flags flags = DIFF_FLAGS_INIT;
1027 flags.override_submodule_config = 1;
1028 if (ignore_submodule_arg &&
1029 !strcmp(ignore_submodule_arg, "all"))
1030 flags.ignore_submodules = 1;
1031 committable = index_differs_from(the_repository,
1032 parent, &flags, 1);
1035 strbuf_release(&committer_ident);
1037 fclose(s->fp);
1039 if (trailer_args.nr) {
1040 struct child_process run_trailer = CHILD_PROCESS_INIT;
1042 strvec_pushl(&run_trailer.args, "interpret-trailers",
1043 "--in-place", git_path_commit_editmsg(), NULL);
1044 strvec_pushv(&run_trailer.args, trailer_args.v);
1045 run_trailer.git_cmd = 1;
1046 if (run_command(&run_trailer))
1047 die(_("unable to pass trailers to --trailers"));
1048 strvec_clear(&trailer_args);
1052 * Reject an attempt to record a non-merge empty commit without
1053 * explicit --allow-empty. In the cherry-pick case, it may be
1054 * empty due to conflict resolution, which the user should okay.
1056 if (!committable && whence != FROM_MERGE && !allow_empty &&
1057 !(amend && is_a_merge(current_head))) {
1058 s->hints = advice_enabled(ADVICE_STATUS_HINTS);
1059 s->display_comment_prefix = old_display_comment_prefix;
1060 run_status(stdout, index_file, prefix, 0, s);
1061 if (amend)
1062 fputs(_(empty_amend_advice), stderr);
1063 else if (is_from_cherry_pick(whence) ||
1064 whence == FROM_REBASE_PICK) {
1065 fputs(_(empty_cherry_pick_advice), stderr);
1066 if (whence == FROM_CHERRY_PICK_SINGLE)
1067 fputs(_(empty_cherry_pick_advice_single), stderr);
1068 else if (whence == FROM_CHERRY_PICK_MULTI)
1069 fputs(_(empty_cherry_pick_advice_multi), stderr);
1070 else
1071 fputs(_(empty_rebase_pick_advice), stderr);
1073 return 0;
1076 if (!no_verify && invoked_hook) {
1078 * Re-read the index as the pre-commit-commit hook was invoked
1079 * and could have updated it. We must do this before we invoke
1080 * the editor and after we invoke run_status above.
1082 discard_index(&the_index);
1084 read_index_from(&the_index, index_file, get_git_dir());
1086 if (cache_tree_update(&the_index, 0)) {
1087 error(_("Error building trees"));
1088 return 0;
1091 if (run_commit_hook(use_editor, index_file, NULL, "prepare-commit-msg",
1092 git_path_commit_editmsg(), hook_arg1, hook_arg2, NULL))
1093 return 0;
1095 if (use_editor) {
1096 struct strvec env = STRVEC_INIT;
1098 strvec_pushf(&env, "GIT_INDEX_FILE=%s", index_file);
1099 if (launch_editor(git_path_commit_editmsg(), NULL, env.v)) {
1100 fprintf(stderr,
1101 _("Please supply the message using either -m or -F option.\n"));
1102 exit(1);
1104 strvec_clear(&env);
1107 if (!no_verify &&
1108 run_commit_hook(use_editor, index_file, NULL, "commit-msg",
1109 git_path_commit_editmsg(), NULL)) {
1110 return 0;
1113 return 1;
1116 static const char *find_author_by_nickname(const char *name)
1118 struct rev_info revs;
1119 struct commit *commit;
1120 struct strbuf buf = STRBUF_INIT;
1121 const char *av[20];
1122 int ac = 0;
1124 repo_init_revisions(the_repository, &revs, NULL);
1125 strbuf_addf(&buf, "--author=%s", name);
1126 av[++ac] = "--all";
1127 av[++ac] = "-i";
1128 av[++ac] = buf.buf;
1129 av[++ac] = NULL;
1130 setup_revisions(ac, av, &revs, NULL);
1131 revs.mailmap = xmalloc(sizeof(struct string_list));
1132 string_list_init_nodup(revs.mailmap);
1133 read_mailmap(revs.mailmap);
1135 if (prepare_revision_walk(&revs))
1136 die(_("revision walk setup failed"));
1137 commit = get_revision(&revs);
1138 if (commit) {
1139 struct pretty_print_context ctx = {0};
1140 ctx.date_mode.type = DATE_NORMAL;
1141 strbuf_release(&buf);
1142 repo_format_commit_message(the_repository, commit,
1143 "%aN <%aE>", &buf, &ctx);
1144 release_revisions(&revs);
1145 return strbuf_detach(&buf, NULL);
1147 die(_("--author '%s' is not 'Name <email>' and matches no existing author"), name);
1150 static void handle_ignored_arg(struct wt_status *s)
1152 if (!ignored_arg)
1153 ; /* default already initialized */
1154 else if (!strcmp(ignored_arg, "traditional"))
1155 s->show_ignored_mode = SHOW_TRADITIONAL_IGNORED;
1156 else if (!strcmp(ignored_arg, "no"))
1157 s->show_ignored_mode = SHOW_NO_IGNORED;
1158 else if (!strcmp(ignored_arg, "matching"))
1159 s->show_ignored_mode = SHOW_MATCHING_IGNORED;
1160 else
1161 die(_("Invalid ignored mode '%s'"), ignored_arg);
1164 static void handle_untracked_files_arg(struct wt_status *s)
1166 if (!untracked_files_arg)
1167 ; /* default already initialized */
1168 else if (!strcmp(untracked_files_arg, "no"))
1169 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
1170 else if (!strcmp(untracked_files_arg, "normal"))
1171 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
1172 else if (!strcmp(untracked_files_arg, "all"))
1173 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
1175 * Please update $__git_untracked_file_modes in
1176 * git-completion.bash when you add new options
1178 else
1179 die(_("Invalid untracked files mode '%s'"), untracked_files_arg);
1182 static const char *read_commit_message(const char *name)
1184 const char *out_enc;
1185 struct commit *commit;
1187 commit = lookup_commit_reference_by_name(name);
1188 if (!commit)
1189 die(_("could not lookup commit %s"), name);
1190 out_enc = get_commit_output_encoding();
1191 return repo_logmsg_reencode(the_repository, commit, NULL, out_enc);
1195 * Enumerate what needs to be propagated when --porcelain
1196 * is not in effect here.
1198 static struct status_deferred_config {
1199 enum wt_status_format status_format;
1200 int show_branch;
1201 enum ahead_behind_flags ahead_behind;
1202 } status_deferred_config = {
1203 STATUS_FORMAT_UNSPECIFIED,
1204 -1, /* unspecified */
1205 AHEAD_BEHIND_UNSPECIFIED,
1208 static void finalize_deferred_config(struct wt_status *s)
1210 int use_deferred_config = (status_format != STATUS_FORMAT_PORCELAIN &&
1211 status_format != STATUS_FORMAT_PORCELAIN_V2 &&
1212 !s->null_termination);
1214 if (s->null_termination) {
1215 if (status_format == STATUS_FORMAT_NONE ||
1216 status_format == STATUS_FORMAT_UNSPECIFIED)
1217 status_format = STATUS_FORMAT_PORCELAIN;
1218 else if (status_format == STATUS_FORMAT_LONG)
1219 die(_("options '%s' and '%s' cannot be used together"), "--long", "-z");
1222 if (use_deferred_config && status_format == STATUS_FORMAT_UNSPECIFIED)
1223 status_format = status_deferred_config.status_format;
1224 if (status_format == STATUS_FORMAT_UNSPECIFIED)
1225 status_format = STATUS_FORMAT_NONE;
1227 if (use_deferred_config && s->show_branch < 0)
1228 s->show_branch = status_deferred_config.show_branch;
1229 if (s->show_branch < 0)
1230 s->show_branch = 0;
1233 * If the user did not give a "--[no]-ahead-behind" command
1234 * line argument *AND* we will print in a human-readable format
1235 * (short, long etc.) then we inherit from the status.aheadbehind
1236 * config setting. In all other cases (and porcelain V[12] formats
1237 * in particular), we inherit _FULL for backwards compatibility.
1239 if (use_deferred_config &&
1240 s->ahead_behind_flags == AHEAD_BEHIND_UNSPECIFIED)
1241 s->ahead_behind_flags = status_deferred_config.ahead_behind;
1243 if (s->ahead_behind_flags == AHEAD_BEHIND_UNSPECIFIED)
1244 s->ahead_behind_flags = AHEAD_BEHIND_FULL;
1247 static void check_fixup_reword_options(int argc, const char *argv[]) {
1248 if (whence != FROM_COMMIT) {
1249 if (whence == FROM_MERGE)
1250 die(_("You are in the middle of a merge -- cannot reword."));
1251 else if (is_from_cherry_pick(whence))
1252 die(_("You are in the middle of a cherry-pick -- cannot reword."));
1254 if (argc)
1255 die(_("reword option of '%s' and path '%s' cannot be used together"), "--fixup", *argv);
1256 if (patch_interactive || interactive || all || also || only)
1257 die(_("reword option of '%s' and '%s' cannot be used together"),
1258 "--fixup", "--patch/--interactive/--all/--include/--only");
1261 static int parse_and_validate_options(int argc, const char *argv[],
1262 const struct option *options,
1263 const char * const usage[],
1264 const char *prefix,
1265 struct commit *current_head,
1266 struct wt_status *s)
1268 argc = parse_options(argc, argv, prefix, options, usage, 0);
1269 finalize_deferred_config(s);
1271 if (force_author && !strchr(force_author, '>'))
1272 force_author = find_author_by_nickname(force_author);
1274 if (force_author && renew_authorship)
1275 die(_("options '%s' and '%s' cannot be used together"), "--reset-author", "--author");
1277 if (logfile || have_option_m || use_message)
1278 use_editor = 0;
1280 /* Sanity check options */
1281 if (amend && !current_head)
1282 die(_("You have nothing to amend."));
1283 if (amend && whence != FROM_COMMIT) {
1284 if (whence == FROM_MERGE)
1285 die(_("You are in the middle of a merge -- cannot amend."));
1286 else if (is_from_cherry_pick(whence))
1287 die(_("You are in the middle of a cherry-pick -- cannot amend."));
1288 else if (whence == FROM_REBASE_PICK)
1289 die(_("You are in the middle of a rebase -- cannot amend."));
1291 if (fixup_message && squash_message)
1292 die(_("options '%s' and '%s' cannot be used together"), "--squash", "--fixup");
1293 die_for_incompatible_opt4(!!use_message, "-C",
1294 !!edit_message, "-c",
1295 !!logfile, "-F",
1296 !!fixup_message, "--fixup");
1297 die_for_incompatible_opt4(have_option_m, "-m",
1298 !!edit_message, "-c",
1299 !!use_message, "-C",
1300 !!logfile, "-F");
1301 if (use_message || edit_message || logfile ||fixup_message || have_option_m)
1302 template_file = NULL;
1303 if (edit_message)
1304 use_message = edit_message;
1305 if (amend && !use_message && !fixup_message)
1306 use_message = "HEAD";
1307 if (!use_message && !is_from_cherry_pick(whence) &&
1308 !is_from_rebase(whence) && renew_authorship)
1309 die(_("--reset-author can be used only with -C, -c or --amend."));
1310 if (use_message) {
1311 use_message_buffer = read_commit_message(use_message);
1312 if (!renew_authorship) {
1313 author_message = use_message;
1314 author_message_buffer = use_message_buffer;
1317 if ((is_from_cherry_pick(whence) || whence == FROM_REBASE_PICK) &&
1318 !renew_authorship) {
1319 author_message = "CHERRY_PICK_HEAD";
1320 author_message_buffer = read_commit_message(author_message);
1323 if (patch_interactive)
1324 interactive = 1;
1326 die_for_incompatible_opt4(also, "-i/--include",
1327 only, "-o/--only",
1328 all, "-a/--all",
1329 interactive, "--interactive/-p/--patch");
1330 if (fixup_message) {
1332 * We limit --fixup's suboptions to only alpha characters.
1333 * If the first character after a run of alpha is colon,
1334 * then the part before the colon may be a known suboption
1335 * name like `amend` or `reword`, or a misspelt suboption
1336 * name. In either case, we treat it as
1337 * --fixup=<suboption>:<arg>.
1339 * Otherwise, we are dealing with --fixup=<commit>.
1341 char *p = fixup_message;
1342 while (isalpha(*p))
1343 p++;
1344 if (p > fixup_message && *p == ':') {
1345 *p = '\0';
1346 fixup_commit = p + 1;
1347 if (!strcmp("amend", fixup_message) ||
1348 !strcmp("reword", fixup_message)) {
1349 fixup_prefix = "amend";
1350 allow_empty = 1;
1351 if (*fixup_message == 'r') {
1352 check_fixup_reword_options(argc, argv);
1353 only = 1;
1355 } else {
1356 die(_("unknown option: --fixup=%s:%s"), fixup_message, fixup_commit);
1358 } else {
1359 fixup_commit = fixup_message;
1360 fixup_prefix = "fixup";
1361 use_editor = 0;
1365 if (0 <= edit_flag)
1366 use_editor = edit_flag;
1368 cleanup_mode = get_cleanup_mode(cleanup_arg, use_editor);
1370 handle_untracked_files_arg(s);
1372 if (all && argc > 0)
1373 die(_("paths '%s ...' with -a does not make sense"),
1374 argv[0]);
1376 if (status_format != STATUS_FORMAT_NONE)
1377 dry_run = 1;
1379 return argc;
1382 static int dry_run_commit(const char **argv, const char *prefix,
1383 const struct commit *current_head, struct wt_status *s)
1385 int committable;
1386 const char *index_file;
1388 index_file = prepare_index(argv, prefix, current_head, 1);
1389 committable = run_status(stdout, index_file, prefix, 0, s);
1390 rollback_index_files();
1392 return committable ? 0 : 1;
1395 define_list_config_array_extra(color_status_slots, {"added"});
1397 static int parse_status_slot(const char *slot)
1399 if (!strcasecmp(slot, "added"))
1400 return WT_STATUS_UPDATED;
1402 return LOOKUP_CONFIG(color_status_slots, slot);
1405 static int git_status_config(const char *k, const char *v, void *cb)
1407 struct wt_status *s = cb;
1408 const char *slot_name;
1410 if (starts_with(k, "column."))
1411 return git_column_config(k, v, "status", &s->colopts);
1412 if (!strcmp(k, "status.submodulesummary")) {
1413 int is_bool;
1414 s->submodule_summary = git_config_bool_or_int(k, v, &is_bool);
1415 if (is_bool && s->submodule_summary)
1416 s->submodule_summary = -1;
1417 return 0;
1419 if (!strcmp(k, "status.short")) {
1420 if (git_config_bool(k, v))
1421 status_deferred_config.status_format = STATUS_FORMAT_SHORT;
1422 else
1423 status_deferred_config.status_format = STATUS_FORMAT_NONE;
1424 return 0;
1426 if (!strcmp(k, "status.branch")) {
1427 status_deferred_config.show_branch = git_config_bool(k, v);
1428 return 0;
1430 if (!strcmp(k, "status.aheadbehind")) {
1431 status_deferred_config.ahead_behind = git_config_bool(k, v);
1432 return 0;
1434 if (!strcmp(k, "status.showstash")) {
1435 s->show_stash = git_config_bool(k, v);
1436 return 0;
1438 if (!strcmp(k, "status.color") || !strcmp(k, "color.status")) {
1439 s->use_color = git_config_colorbool(k, v);
1440 return 0;
1442 if (!strcmp(k, "status.displaycommentprefix")) {
1443 s->display_comment_prefix = git_config_bool(k, v);
1444 return 0;
1446 if (skip_prefix(k, "status.color.", &slot_name) ||
1447 skip_prefix(k, "color.status.", &slot_name)) {
1448 int slot = parse_status_slot(slot_name);
1449 if (slot < 0)
1450 return 0;
1451 if (!v)
1452 return config_error_nonbool(k);
1453 return color_parse(v, s->color_palette[slot]);
1455 if (!strcmp(k, "status.relativepaths")) {
1456 s->relative_paths = git_config_bool(k, v);
1457 return 0;
1459 if (!strcmp(k, "status.showuntrackedfiles")) {
1460 if (!v)
1461 return config_error_nonbool(k);
1462 else if (!strcmp(v, "no"))
1463 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
1464 else if (!strcmp(v, "normal"))
1465 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
1466 else if (!strcmp(v, "all"))
1467 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
1468 else
1469 return error(_("Invalid untracked files mode '%s'"), v);
1470 return 0;
1472 if (!strcmp(k, "diff.renamelimit")) {
1473 if (s->rename_limit == -1)
1474 s->rename_limit = git_config_int(k, v);
1475 return 0;
1477 if (!strcmp(k, "status.renamelimit")) {
1478 s->rename_limit = git_config_int(k, v);
1479 return 0;
1481 if (!strcmp(k, "diff.renames")) {
1482 if (s->detect_rename == -1)
1483 s->detect_rename = git_config_rename(k, v);
1484 return 0;
1486 if (!strcmp(k, "status.renames")) {
1487 s->detect_rename = git_config_rename(k, v);
1488 return 0;
1490 return git_diff_ui_config(k, v, NULL);
1493 int cmd_status(int argc, const char **argv, const char *prefix)
1495 static int no_renames = -1;
1496 static const char *rename_score_arg = (const char *)-1;
1497 static struct wt_status s;
1498 unsigned int progress_flag = 0;
1499 int fd;
1500 struct object_id oid;
1501 static struct option builtin_status_options[] = {
1502 OPT__VERBOSE(&verbose, N_("be verbose")),
1503 OPT_SET_INT('s', "short", &status_format,
1504 N_("show status concisely"), STATUS_FORMAT_SHORT),
1505 OPT_BOOL('b', "branch", &s.show_branch,
1506 N_("show branch information")),
1507 OPT_BOOL(0, "show-stash", &s.show_stash,
1508 N_("show stash information")),
1509 OPT_BOOL(0, "ahead-behind", &s.ahead_behind_flags,
1510 N_("compute full ahead/behind values")),
1511 OPT_CALLBACK_F(0, "porcelain", &status_format,
1512 N_("version"), N_("machine-readable output"),
1513 PARSE_OPT_OPTARG, opt_parse_porcelain),
1514 OPT_SET_INT(0, "long", &status_format,
1515 N_("show status in long format (default)"),
1516 STATUS_FORMAT_LONG),
1517 OPT_BOOL('z', "null", &s.null_termination,
1518 N_("terminate entries with NUL")),
1519 { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg,
1520 N_("mode"),
1521 N_("show untracked files, optional modes: all, normal, no. (Default: all)"),
1522 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1523 { OPTION_STRING, 0, "ignored", &ignored_arg,
1524 N_("mode"),
1525 N_("show ignored files, optional modes: traditional, matching, no. (Default: traditional)"),
1526 PARSE_OPT_OPTARG, NULL, (intptr_t)"traditional" },
1527 { OPTION_STRING, 0, "ignore-submodules", &ignore_submodule_arg, N_("when"),
1528 N_("ignore changes to submodules, optional when: all, dirty, untracked. (Default: all)"),
1529 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1530 OPT_COLUMN(0, "column", &s.colopts, N_("list untracked files in columns")),
1531 OPT_BOOL(0, "no-renames", &no_renames, N_("do not detect renames")),
1532 OPT_CALLBACK_F('M', "find-renames", &rename_score_arg,
1533 N_("n"), N_("detect renames, optionally set similarity index"),
1534 PARSE_OPT_OPTARG | PARSE_OPT_NONEG, opt_parse_rename_score),
1535 OPT_END(),
1538 if (argc == 2 && !strcmp(argv[1], "-h"))
1539 usage_with_options(builtin_status_usage, builtin_status_options);
1541 prepare_repo_settings(the_repository);
1542 the_repository->settings.command_requires_full_index = 0;
1544 status_init_config(&s, git_status_config);
1545 argc = parse_options(argc, argv, prefix,
1546 builtin_status_options,
1547 builtin_status_usage, 0);
1548 finalize_colopts(&s.colopts, -1);
1549 finalize_deferred_config(&s);
1551 handle_untracked_files_arg(&s);
1552 handle_ignored_arg(&s);
1554 if (s.show_ignored_mode == SHOW_MATCHING_IGNORED &&
1555 s.show_untracked_files == SHOW_NO_UNTRACKED_FILES)
1556 die(_("Unsupported combination of ignored and untracked-files arguments"));
1558 parse_pathspec(&s.pathspec, 0,
1559 PATHSPEC_PREFER_FULL,
1560 prefix, argv);
1562 if (status_format != STATUS_FORMAT_PORCELAIN &&
1563 status_format != STATUS_FORMAT_PORCELAIN_V2)
1564 progress_flag = REFRESH_PROGRESS;
1565 repo_read_index(the_repository);
1566 refresh_index(&the_index,
1567 REFRESH_QUIET|REFRESH_UNMERGED|progress_flag,
1568 &s.pathspec, NULL, NULL);
1570 if (use_optional_locks())
1571 fd = repo_hold_locked_index(the_repository, &index_lock, 0);
1572 else
1573 fd = -1;
1575 s.is_initial = repo_get_oid(the_repository, s.reference, &oid) ? 1 : 0;
1576 if (!s.is_initial)
1577 oidcpy(&s.oid_commit, &oid);
1579 s.ignore_submodule_arg = ignore_submodule_arg;
1580 s.status_format = status_format;
1581 s.verbose = verbose;
1582 if (no_renames != -1)
1583 s.detect_rename = !no_renames;
1584 if ((intptr_t)rename_score_arg != -1) {
1585 if (s.detect_rename < DIFF_DETECT_RENAME)
1586 s.detect_rename = DIFF_DETECT_RENAME;
1587 if (rename_score_arg)
1588 s.rename_score = parse_rename_score(&rename_score_arg);
1591 wt_status_collect(&s);
1593 if (0 <= fd)
1594 repo_update_index_if_able(the_repository, &index_lock);
1596 if (s.relative_paths)
1597 s.prefix = prefix;
1599 wt_status_print(&s);
1600 wt_status_collect_free_buffers(&s);
1602 return 0;
1605 static int git_commit_config(const char *k, const char *v, void *cb)
1607 struct wt_status *s = cb;
1609 if (!strcmp(k, "commit.template"))
1610 return git_config_pathname(&template_file, k, v);
1611 if (!strcmp(k, "commit.status")) {
1612 include_status = git_config_bool(k, v);
1613 return 0;
1615 if (!strcmp(k, "commit.cleanup"))
1616 return git_config_string(&cleanup_arg, k, v);
1617 if (!strcmp(k, "commit.gpgsign")) {
1618 sign_commit = git_config_bool(k, v) ? "" : NULL;
1619 return 0;
1621 if (!strcmp(k, "commit.verbose")) {
1622 int is_bool;
1623 config_commit_verbose = git_config_bool_or_int(k, v, &is_bool);
1624 return 0;
1627 return git_status_config(k, v, s);
1630 int cmd_commit(int argc, const char **argv, const char *prefix)
1632 static struct wt_status s;
1633 static struct option builtin_commit_options[] = {
1634 OPT__QUIET(&quiet, N_("suppress summary after successful commit")),
1635 OPT__VERBOSE(&verbose, N_("show diff in commit message template")),
1637 OPT_GROUP(N_("Commit message options")),
1638 OPT_FILENAME('F', "file", &logfile, N_("read message from file")),
1639 OPT_STRING(0, "author", &force_author, N_("author"), N_("override author for commit")),
1640 OPT_STRING(0, "date", &force_date, N_("date"), N_("override date for commit")),
1641 OPT_CALLBACK('m', "message", &message, N_("message"), N_("commit message"), opt_parse_m),
1642 OPT_STRING('c', "reedit-message", &edit_message, N_("commit"), N_("reuse and edit message from specified commit")),
1643 OPT_STRING('C', "reuse-message", &use_message, N_("commit"), N_("reuse message from specified commit")),
1645 * TRANSLATORS: Leave "[(amend|reword):]" as-is,
1646 * and only translate <commit>.
1648 OPT_STRING(0, "fixup", &fixup_message, N_("[(amend|reword):]commit"), N_("use autosquash formatted message to fixup or amend/reword specified commit")),
1649 OPT_STRING(0, "squash", &squash_message, N_("commit"), N_("use autosquash formatted message to squash specified commit")),
1650 OPT_BOOL(0, "reset-author", &renew_authorship, N_("the commit is authored by me now (used with -C/-c/--amend)")),
1651 OPT_CALLBACK_F(0, "trailer", &trailer_args, N_("trailer"), N_("add custom trailer(s)"), PARSE_OPT_NONEG, opt_pass_trailer),
1652 OPT_BOOL('s', "signoff", &signoff, N_("add a Signed-off-by trailer")),
1653 OPT_FILENAME('t', "template", &template_file, N_("use specified template file")),
1654 OPT_BOOL('e', "edit", &edit_flag, N_("force edit of commit")),
1655 OPT_CLEANUP(&cleanup_arg),
1656 OPT_BOOL(0, "status", &include_status, N_("include status in commit message template")),
1657 { OPTION_STRING, 'S', "gpg-sign", &sign_commit, N_("key-id"),
1658 N_("GPG sign commit"), PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
1659 /* end commit message options */
1661 OPT_GROUP(N_("Commit contents options")),
1662 OPT_BOOL('a', "all", &all, N_("commit all changed files")),
1663 OPT_BOOL('i', "include", &also, N_("add specified files to index for commit")),
1664 OPT_BOOL(0, "interactive", &interactive, N_("interactively add files")),
1665 OPT_BOOL('p', "patch", &patch_interactive, N_("interactively add changes")),
1666 OPT_BOOL('o', "only", &only, N_("commit only specified files")),
1667 OPT_BOOL('n', "no-verify", &no_verify, N_("bypass pre-commit and commit-msg hooks")),
1668 OPT_BOOL(0, "dry-run", &dry_run, N_("show what would be committed")),
1669 OPT_SET_INT(0, "short", &status_format, N_("show status concisely"),
1670 STATUS_FORMAT_SHORT),
1671 OPT_BOOL(0, "branch", &s.show_branch, N_("show branch information")),
1672 OPT_BOOL(0, "ahead-behind", &s.ahead_behind_flags,
1673 N_("compute full ahead/behind values")),
1674 OPT_SET_INT(0, "porcelain", &status_format,
1675 N_("machine-readable output"), STATUS_FORMAT_PORCELAIN),
1676 OPT_SET_INT(0, "long", &status_format,
1677 N_("show status in long format (default)"),
1678 STATUS_FORMAT_LONG),
1679 OPT_BOOL('z', "null", &s.null_termination,
1680 N_("terminate entries with NUL")),
1681 OPT_BOOL(0, "amend", &amend, N_("amend previous commit")),
1682 OPT_BOOL(0, "no-post-rewrite", &no_post_rewrite, N_("bypass post-rewrite hook")),
1683 { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg, N_("mode"), N_("show untracked files, optional modes: all, normal, no. (Default: all)"), PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1684 OPT_PATHSPEC_FROM_FILE(&pathspec_from_file),
1685 OPT_PATHSPEC_FILE_NUL(&pathspec_file_nul),
1686 /* end commit contents options */
1688 OPT_HIDDEN_BOOL(0, "allow-empty", &allow_empty,
1689 N_("ok to record an empty change")),
1690 OPT_HIDDEN_BOOL(0, "allow-empty-message", &allow_empty_message,
1691 N_("ok to record a change with an empty message")),
1693 OPT_END()
1696 struct strbuf sb = STRBUF_INIT;
1697 struct strbuf author_ident = STRBUF_INIT;
1698 const char *index_file, *reflog_msg;
1699 struct object_id oid;
1700 struct commit_list *parents = NULL;
1701 struct stat statbuf;
1702 struct commit *current_head = NULL;
1703 struct commit_extra_header *extra = NULL;
1704 struct strbuf err = STRBUF_INIT;
1705 int ret = 0;
1707 if (argc == 2 && !strcmp(argv[1], "-h"))
1708 usage_with_options(builtin_commit_usage, builtin_commit_options);
1710 prepare_repo_settings(the_repository);
1711 the_repository->settings.command_requires_full_index = 0;
1713 status_init_config(&s, git_commit_config);
1714 s.commit_template = 1;
1715 status_format = STATUS_FORMAT_NONE; /* Ignore status.short */
1716 s.colopts = 0;
1718 if (repo_get_oid(the_repository, "HEAD", &oid))
1719 current_head = NULL;
1720 else {
1721 current_head = lookup_commit_or_die(&oid, "HEAD");
1722 if (repo_parse_commit(the_repository, current_head))
1723 die(_("could not parse HEAD commit"));
1725 verbose = -1; /* unspecified */
1726 argc = parse_and_validate_options(argc, argv, builtin_commit_options,
1727 builtin_commit_usage,
1728 prefix, current_head, &s);
1729 if (verbose == -1)
1730 verbose = (config_commit_verbose < 0) ? 0 : config_commit_verbose;
1732 if (dry_run)
1733 return dry_run_commit(argv, prefix, current_head, &s);
1734 index_file = prepare_index(argv, prefix, current_head, 0);
1736 /* Set up everything for writing the commit object. This includes
1737 running hooks, writing the trees, and interacting with the user. */
1738 if (!prepare_to_commit(index_file, prefix,
1739 current_head, &s, &author_ident)) {
1740 ret = 1;
1741 rollback_index_files();
1742 goto cleanup;
1745 /* Determine parents */
1746 reflog_msg = getenv("GIT_REFLOG_ACTION");
1747 if (!current_head) {
1748 if (!reflog_msg)
1749 reflog_msg = "commit (initial)";
1750 } else if (amend) {
1751 if (!reflog_msg)
1752 reflog_msg = "commit (amend)";
1753 parents = copy_commit_list(current_head->parents);
1754 } else if (whence == FROM_MERGE) {
1755 struct strbuf m = STRBUF_INIT;
1756 FILE *fp;
1757 int allow_fast_forward = 1;
1758 struct commit_list **pptr = &parents;
1760 if (!reflog_msg)
1761 reflog_msg = "commit (merge)";
1762 pptr = commit_list_append(current_head, pptr);
1763 fp = xfopen(git_path_merge_head(the_repository), "r");
1764 while (strbuf_getline_lf(&m, fp) != EOF) {
1765 struct commit *parent;
1767 parent = get_merge_parent(m.buf);
1768 if (!parent)
1769 die(_("Corrupt MERGE_HEAD file (%s)"), m.buf);
1770 pptr = commit_list_append(parent, pptr);
1772 fclose(fp);
1773 strbuf_release(&m);
1774 if (!stat(git_path_merge_mode(the_repository), &statbuf)) {
1775 if (strbuf_read_file(&sb, git_path_merge_mode(the_repository), 0) < 0)
1776 die_errno(_("could not read MERGE_MODE"));
1777 if (!strcmp(sb.buf, "no-ff"))
1778 allow_fast_forward = 0;
1780 if (allow_fast_forward)
1781 reduce_heads_replace(&parents);
1782 } else {
1783 if (!reflog_msg)
1784 reflog_msg = is_from_cherry_pick(whence)
1785 ? "commit (cherry-pick)"
1786 : is_from_rebase(whence)
1787 ? "commit (rebase)"
1788 : "commit";
1789 commit_list_insert(current_head, &parents);
1792 /* Finally, get the commit message */
1793 strbuf_reset(&sb);
1794 if (strbuf_read_file(&sb, git_path_commit_editmsg(), 0) < 0) {
1795 int saved_errno = errno;
1796 rollback_index_files();
1797 die(_("could not read commit message: %s"), strerror(saved_errno));
1800 cleanup_message(&sb, cleanup_mode, verbose);
1802 if (message_is_empty(&sb, cleanup_mode) && !allow_empty_message) {
1803 rollback_index_files();
1804 fprintf(stderr, _("Aborting commit due to empty commit message.\n"));
1805 exit(1);
1807 if (template_untouched(&sb, template_file, cleanup_mode) && !allow_empty_message) {
1808 rollback_index_files();
1809 fprintf(stderr, _("Aborting commit; you did not edit the message.\n"));
1810 exit(1);
1813 if (fixup_message && starts_with(sb.buf, "amend! ") &&
1814 !allow_empty_message) {
1815 struct strbuf body = STRBUF_INIT;
1816 size_t len = commit_subject_length(sb.buf);
1817 strbuf_addstr(&body, sb.buf + len);
1818 if (message_is_empty(&body, cleanup_mode)) {
1819 rollback_index_files();
1820 fprintf(stderr, _("Aborting commit due to empty commit message body.\n"));
1821 exit(1);
1823 strbuf_release(&body);
1826 if (amend) {
1827 const char *exclude_gpgsig[3] = { "gpgsig", "gpgsig-sha256", NULL };
1828 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1829 } else {
1830 struct commit_extra_header **tail = &extra;
1831 append_merge_tag_headers(parents, &tail);
1834 if (commit_tree_extended(sb.buf, sb.len, &the_index.cache_tree->oid,
1835 parents, &oid, author_ident.buf, NULL,
1836 sign_commit, extra)) {
1837 rollback_index_files();
1838 die(_("failed to write commit object"));
1840 free_commit_extra_headers(extra);
1842 if (update_head_with_reflog(current_head, &oid, reflog_msg, &sb,
1843 &err)) {
1844 rollback_index_files();
1845 die("%s", err.buf);
1848 sequencer_post_commit_cleanup(the_repository, 0);
1849 unlink(git_path_merge_head(the_repository));
1850 unlink(git_path_merge_msg(the_repository));
1851 unlink(git_path_merge_mode(the_repository));
1852 unlink(git_path_squash_msg(the_repository));
1854 if (commit_index_files())
1855 die(_("repository has been updated, but unable to write\n"
1856 "new_index file. Check that disk is not full and quota is\n"
1857 "not exceeded, and then \"git restore --staged :/\" to recover."));
1859 git_test_write_commit_graph_or_die();
1861 repo_rerere(the_repository, 0);
1862 run_auto_maintenance(quiet);
1863 run_commit_hook(use_editor, get_index_file(), NULL, "post-commit",
1864 NULL);
1865 if (amend && !no_post_rewrite) {
1866 commit_post_rewrite(the_repository, current_head, &oid);
1868 if (!quiet) {
1869 unsigned int flags = 0;
1871 if (!current_head)
1872 flags |= SUMMARY_INITIAL_COMMIT;
1873 if (author_date_is_interesting())
1874 flags |= SUMMARY_SHOW_AUTHOR_DATE;
1875 print_commit_summary(the_repository, prefix,
1876 &oid, flags);
1879 apply_autostash(git_path_merge_autostash(the_repository));
1881 cleanup:
1882 strbuf_release(&author_ident);
1883 strbuf_release(&err);
1884 strbuf_release(&sb);
1885 return ret;