t0410: make test description clearer
[git/gitster.git] / builtin / commit.c
blob8db4e9df0c9944ff4d8712ffcf23d5c800e9d334
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 */
7 #define USE_THE_REPOSITORY_VARIABLE
8 #include "builtin.h"
9 #include "advice.h"
10 #include "config.h"
11 #include "lockfile.h"
12 #include "cache-tree.h"
13 #include "color.h"
14 #include "dir.h"
15 #include "editor.h"
16 #include "environment.h"
17 #include "diff.h"
18 #include "commit.h"
19 #include "gettext.h"
20 #include "revision.h"
21 #include "wt-status.h"
22 #include "run-command.h"
23 #include "strbuf.h"
24 #include "object-name.h"
25 #include "parse-options.h"
26 #include "path.h"
27 #include "preload-index.h"
28 #include "read-cache.h"
29 #include "repository.h"
30 #include "string-list.h"
31 #include "rerere.h"
32 #include "unpack-trees.h"
33 #include "column.h"
34 #include "sequencer.h"
35 #include "sparse-index.h"
36 #include "mailmap.h"
37 #include "help.h"
38 #include "commit-reach.h"
39 #include "commit-graph.h"
40 #include "pretty.h"
41 #include "trailer.h"
43 static const char * const builtin_commit_usage[] = {
44 N_("git commit [-a | --interactive | --patch] [-s] [-v] [-u<mode>] [--amend]\n"
45 " [--dry-run] [(-c | -C | --squash) <commit> | --fixup [(amend|reword):]<commit>]\n"
46 " [-F <file> | -m <msg>] [--reset-author] [--allow-empty]\n"
47 " [--allow-empty-message] [--no-verify] [-e] [--author=<author>]\n"
48 " [--date=<date>] [--cleanup=<mode>] [--[no-]status]\n"
49 " [-i | -o] [--pathspec-from-file=<file> [--pathspec-file-nul]]\n"
50 " [(--trailer <token>[(=|:)<value>])...] [-S[<keyid>]]\n"
51 " [--] [<pathspec>...]"),
52 NULL
55 static const char * const builtin_status_usage[] = {
56 N_("git status [<options>] [--] [<pathspec>...]"),
57 NULL
60 static const char empty_amend_advice[] =
61 N_("You asked to amend the most recent commit, but doing so would make\n"
62 "it empty. You can repeat your command with --allow-empty, or you can\n"
63 "remove the commit entirely with \"git reset HEAD^\".\n");
65 static const char empty_cherry_pick_advice[] =
66 N_("The previous cherry-pick is now empty, possibly due to conflict resolution.\n"
67 "If you wish to commit it anyway, use:\n"
68 "\n"
69 " git commit --allow-empty\n"
70 "\n");
72 static const char empty_rebase_pick_advice[] =
73 N_("Otherwise, please use 'git rebase --skip'\n");
75 static const char empty_cherry_pick_advice_single[] =
76 N_("Otherwise, please use 'git cherry-pick --skip'\n");
78 static const char empty_cherry_pick_advice_multi[] =
79 N_("and then use:\n"
80 "\n"
81 " git cherry-pick --continue\n"
82 "\n"
83 "to resume cherry-picking the remaining commits.\n"
84 "If you wish to skip this commit, use:\n"
85 "\n"
86 " git cherry-pick --skip\n"
87 "\n");
89 static const char *color_status_slots[] = {
90 [WT_STATUS_HEADER] = "header",
91 [WT_STATUS_UPDATED] = "updated",
92 [WT_STATUS_CHANGED] = "changed",
93 [WT_STATUS_UNTRACKED] = "untracked",
94 [WT_STATUS_NOBRANCH] = "noBranch",
95 [WT_STATUS_UNMERGED] = "unmerged",
96 [WT_STATUS_LOCAL_BRANCH] = "localBranch",
97 [WT_STATUS_REMOTE_BRANCH] = "remoteBranch",
98 [WT_STATUS_ONBRANCH] = "branch",
101 static const char *use_message_buffer;
102 static struct lock_file index_lock; /* real index */
103 static struct lock_file false_lock; /* used only for partial commits */
104 static enum {
105 COMMIT_AS_IS = 1,
106 COMMIT_NORMAL,
107 COMMIT_PARTIAL
108 } commit_style;
110 static const char *force_author;
111 static char *logfile;
112 static 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 const 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 const char *untracked_files_arg, *force_date, *ignore_submodule_arg, *ignored_arg;
127 static const 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 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_parse_porcelain(const struct option *opt, const char *arg, int unset)
149 enum wt_status_format *value = (enum wt_status_format *)opt->value;
150 if (unset)
151 *value = STATUS_FORMAT_NONE;
152 else if (!arg)
153 *value = STATUS_FORMAT_PORCELAIN;
154 else if (!strcmp(arg, "v1") || !strcmp(arg, "1"))
155 *value = STATUS_FORMAT_PORCELAIN;
156 else if (!strcmp(arg, "v2") || !strcmp(arg, "2"))
157 *value = STATUS_FORMAT_PORCELAIN_V2;
158 else
159 die("unsupported porcelain version '%s'", arg);
161 return 0;
164 static int opt_parse_m(const struct option *opt, const char *arg, int unset)
166 struct strbuf *buf = opt->value;
167 if (unset) {
168 have_option_m = 0;
169 strbuf_setlen(buf, 0);
170 } else {
171 have_option_m = 1;
172 if (buf->len)
173 strbuf_addch(buf, '\n');
174 strbuf_addstr(buf, arg);
175 strbuf_complete_line(buf);
177 return 0;
180 static int opt_parse_rename_score(const struct option *opt, const char *arg, int unset)
182 const char **value = opt->value;
184 BUG_ON_OPT_NEG(unset);
186 if (arg != NULL && *arg == '=')
187 arg = arg + 1;
189 *value = arg;
190 return 0;
193 static void determine_whence(struct wt_status *s)
195 if (file_exists(git_path_merge_head(the_repository)))
196 whence = FROM_MERGE;
197 else if (!sequencer_determine_whence(the_repository, &whence))
198 whence = FROM_COMMIT;
199 if (s)
200 s->whence = whence;
203 static void status_init_config(struct wt_status *s, config_fn_t fn)
205 wt_status_prepare(the_repository, s);
206 init_diff_ui_defaults();
207 git_config(fn, s);
208 determine_whence(s);
209 s->hints = advice_enabled(ADVICE_STATUS_HINTS); /* must come after git_config() */
212 static void rollback_index_files(void)
214 switch (commit_style) {
215 case COMMIT_AS_IS:
216 break; /* nothing to do */
217 case COMMIT_NORMAL:
218 rollback_lock_file(&index_lock);
219 break;
220 case COMMIT_PARTIAL:
221 rollback_lock_file(&index_lock);
222 rollback_lock_file(&false_lock);
223 break;
227 static int commit_index_files(void)
229 int err = 0;
231 switch (commit_style) {
232 case COMMIT_AS_IS:
233 break; /* nothing to do */
234 case COMMIT_NORMAL:
235 err = commit_lock_file(&index_lock);
236 break;
237 case COMMIT_PARTIAL:
238 err = commit_lock_file(&index_lock);
239 rollback_lock_file(&false_lock);
240 break;
243 return err;
247 * Take a union of paths in the index and the named tree (typically, "HEAD"),
248 * and return the paths that match the given pattern in list.
250 static int list_paths(struct string_list *list, const char *with_tree,
251 const struct pathspec *pattern)
253 int i, ret;
254 char *m;
256 if (!pattern->nr)
257 return 0;
259 m = xcalloc(1, pattern->nr);
261 if (with_tree) {
262 char *max_prefix = common_prefix(pattern);
263 overlay_tree_on_index(the_repository->index, with_tree, max_prefix);
264 free(max_prefix);
267 /* TODO: audit for interaction with sparse-index. */
268 ensure_full_index(the_repository->index);
269 for (i = 0; i < the_repository->index->cache_nr; i++) {
270 const struct cache_entry *ce = the_repository->index->cache[i];
271 struct string_list_item *item;
273 if (ce->ce_flags & CE_UPDATE)
274 continue;
275 if (!ce_path_match(the_repository->index, ce, pattern, m))
276 continue;
277 item = string_list_insert(list, ce->name);
278 if (ce_skip_worktree(ce))
279 item->util = item; /* better a valid pointer than a fake one */
282 ret = report_path_error(m, pattern);
283 free(m);
284 return ret;
287 static void add_remove_files(struct string_list *list)
289 int i;
290 for (i = 0; i < list->nr; i++) {
291 struct stat st;
292 struct string_list_item *p = &(list->items[i]);
294 /* p->util is skip-worktree */
295 if (p->util)
296 continue;
298 if (!lstat(p->string, &st)) {
299 if (add_to_index(the_repository->index, p->string, &st, 0))
300 die(_("updating files failed"));
301 } else
302 remove_file_from_index(the_repository->index, p->string);
306 static void create_base_index(const struct commit *current_head)
308 struct tree *tree;
309 struct unpack_trees_options opts;
310 struct tree_desc t;
312 if (!current_head) {
313 discard_index(the_repository->index);
314 return;
317 memset(&opts, 0, sizeof(opts));
318 opts.head_idx = 1;
319 opts.index_only = 1;
320 opts.merge = 1;
321 opts.src_index = the_repository->index;
322 opts.dst_index = the_repository->index;
324 opts.fn = oneway_merge;
325 tree = parse_tree_indirect(&current_head->object.oid);
326 if (!tree)
327 die(_("failed to unpack HEAD tree object"));
328 if (parse_tree(tree) < 0)
329 exit(128);
330 init_tree_desc(&t, &tree->object.oid, tree->buffer, tree->size);
331 if (unpack_trees(1, &t, &opts))
332 exit(128); /* We've already reported the error, finish dying */
335 static void refresh_cache_or_die(int refresh_flags)
338 * refresh_flags contains REFRESH_QUIET, so the only errors
339 * are for unmerged entries.
341 if (refresh_index(the_repository->index, refresh_flags | REFRESH_IN_PORCELAIN, NULL, NULL, NULL))
342 die_resolve_conflict("commit");
345 static const char *prepare_index(const char **argv, const char *prefix,
346 const struct commit *current_head, int is_status)
348 struct string_list partial = STRING_LIST_INIT_DUP;
349 struct pathspec pathspec;
350 int refresh_flags = REFRESH_QUIET;
351 const char *ret;
353 if (is_status)
354 refresh_flags |= REFRESH_UNMERGED;
355 parse_pathspec(&pathspec, 0,
356 PATHSPEC_PREFER_FULL,
357 prefix, argv);
359 if (pathspec_from_file) {
360 if (interactive)
361 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--interactive/--patch");
363 if (all)
364 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "-a");
366 if (pathspec.nr)
367 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
369 parse_pathspec_file(&pathspec, 0,
370 PATHSPEC_PREFER_FULL,
371 prefix, pathspec_from_file, pathspec_file_nul);
372 } else if (pathspec_file_nul) {
373 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
376 if (!pathspec.nr && (also || (only && !allow_empty &&
377 (!amend || (fixup_message && strcmp(fixup_prefix, "amend"))))))
378 die(_("No paths with --include/--only does not make sense."));
380 if (repo_read_index_preload(the_repository, &pathspec, 0) < 0)
381 die(_("index file corrupt"));
383 if (interactive) {
384 char *old_index_env = NULL, *old_repo_index_file;
385 repo_hold_locked_index(the_repository, &index_lock,
386 LOCK_DIE_ON_ERROR);
388 refresh_cache_or_die(refresh_flags);
390 if (write_locked_index(the_repository->index, &index_lock, 0))
391 die(_("unable to create temporary index"));
393 old_repo_index_file = the_repository->index_file;
394 the_repository->index_file =
395 (char *)get_lock_file_path(&index_lock);
396 old_index_env = xstrdup_or_null(getenv(INDEX_ENVIRONMENT));
397 setenv(INDEX_ENVIRONMENT, the_repository->index_file, 1);
399 if (interactive_add(the_repository, argv, prefix, patch_interactive) != 0)
400 die(_("interactive add failed"));
402 the_repository->index_file = old_repo_index_file;
403 if (old_index_env && *old_index_env)
404 setenv(INDEX_ENVIRONMENT, old_index_env, 1);
405 else
406 unsetenv(INDEX_ENVIRONMENT);
407 FREE_AND_NULL(old_index_env);
409 discard_index(the_repository->index);
410 read_index_from(the_repository->index, get_lock_file_path(&index_lock),
411 repo_get_git_dir(the_repository));
412 if (cache_tree_update(the_repository->index, WRITE_TREE_SILENT) == 0) {
413 if (reopen_lock_file(&index_lock) < 0)
414 die(_("unable to write index file"));
415 if (write_locked_index(the_repository->index, &index_lock, 0))
416 die(_("unable to update temporary index"));
417 } else
418 warning(_("Failed to update main cache tree"));
420 commit_style = COMMIT_NORMAL;
421 ret = get_lock_file_path(&index_lock);
422 goto out;
426 * Non partial, non as-is commit.
428 * (1) get the real index;
429 * (2) update the_index as necessary;
430 * (3) write the_index out to the real index (still locked);
431 * (4) return the name of the locked index file.
433 * The caller should run hooks on the locked real index, and
434 * (A) if all goes well, commit the real index;
435 * (B) on failure, rollback the real index.
437 if (all || (also && pathspec.nr)) {
438 char *ps_matched = xcalloc(pathspec.nr, 1);
439 repo_hold_locked_index(the_repository, &index_lock,
440 LOCK_DIE_ON_ERROR);
441 add_files_to_cache(the_repository, also ? prefix : NULL,
442 &pathspec, ps_matched, 0, 0);
443 if (!all && report_path_error(ps_matched, &pathspec))
444 exit(128);
446 refresh_cache_or_die(refresh_flags);
447 cache_tree_update(the_repository->index, WRITE_TREE_SILENT);
448 if (write_locked_index(the_repository->index, &index_lock, 0))
449 die(_("unable to write new index file"));
450 commit_style = COMMIT_NORMAL;
451 ret = get_lock_file_path(&index_lock);
452 free(ps_matched);
453 goto out;
457 * As-is commit.
459 * (1) return the name of the real index file.
461 * The caller should run hooks on the real index,
462 * and create commit from the_index.
463 * We still need to refresh the index here.
465 if (!only && !pathspec.nr) {
466 repo_hold_locked_index(the_repository, &index_lock,
467 LOCK_DIE_ON_ERROR);
468 refresh_cache_or_die(refresh_flags);
469 if (the_repository->index->cache_changed
470 || !cache_tree_fully_valid(the_repository->index->cache_tree))
471 cache_tree_update(the_repository->index, WRITE_TREE_SILENT);
472 if (write_locked_index(the_repository->index, &index_lock,
473 COMMIT_LOCK | SKIP_IF_UNCHANGED))
474 die(_("unable to write new index file"));
475 commit_style = COMMIT_AS_IS;
476 ret = repo_get_index_file(the_repository);
477 goto out;
481 * A partial commit.
483 * (0) find the set of affected paths;
484 * (1) get lock on the real index file;
485 * (2) update the_index with the given paths;
486 * (3) write the_index out to the real index (still locked);
487 * (4) get lock on the false index file;
488 * (5) reset the_index from HEAD;
489 * (6) update the_index the same way as (2);
490 * (7) write the_index out to the false index file;
491 * (8) return the name of the false index file (still locked);
493 * The caller should run hooks on the locked false index, and
494 * create commit from it. Then
495 * (A) if all goes well, commit the real index;
496 * (B) on failure, rollback the real index;
497 * In either case, rollback the false index.
499 commit_style = COMMIT_PARTIAL;
501 if (whence != FROM_COMMIT) {
502 if (whence == FROM_MERGE)
503 die(_("cannot do a partial commit during a merge."));
504 else if (is_from_cherry_pick(whence))
505 die(_("cannot do a partial commit during a cherry-pick."));
506 else if (is_from_rebase(whence))
507 die(_("cannot do a partial commit during a rebase."));
510 if (list_paths(&partial, !current_head ? NULL : "HEAD", &pathspec))
511 exit(1);
513 discard_index(the_repository->index);
514 if (repo_read_index(the_repository) < 0)
515 die(_("cannot read the index"));
517 repo_hold_locked_index(the_repository, &index_lock, LOCK_DIE_ON_ERROR);
518 add_remove_files(&partial);
519 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL, NULL);
520 cache_tree_update(the_repository->index, WRITE_TREE_SILENT);
521 if (write_locked_index(the_repository->index, &index_lock, 0))
522 die(_("unable to write new index file"));
524 hold_lock_file_for_update(&false_lock,
525 git_path("next-index-%"PRIuMAX,
526 (uintmax_t) getpid()),
527 LOCK_DIE_ON_ERROR);
529 create_base_index(current_head);
530 add_remove_files(&partial);
531 refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL, NULL);
533 if (write_locked_index(the_repository->index, &false_lock, 0))
534 die(_("unable to write temporary index file"));
536 discard_index(the_repository->index);
537 ret = get_lock_file_path(&false_lock);
538 read_index_from(the_repository->index, ret, repo_get_git_dir(the_repository));
539 out:
540 string_list_clear(&partial, 0);
541 clear_pathspec(&pathspec);
542 return ret;
545 static int run_status(FILE *fp, const char *index_file, const char *prefix, int nowarn,
546 struct wt_status *s)
548 struct object_id oid;
550 if (s->relative_paths)
551 s->prefix = prefix;
553 if (amend) {
554 s->amend = 1;
555 s->reference = "HEAD^1";
557 s->verbose = verbose;
558 s->index_file = index_file;
559 s->fp = fp;
560 s->nowarn = nowarn;
561 s->is_initial = repo_get_oid(the_repository, s->reference, &oid) ? 1 : 0;
562 if (!s->is_initial)
563 oidcpy(&s->oid_commit, &oid);
564 s->status_format = status_format;
565 s->ignore_submodule_arg = ignore_submodule_arg;
567 wt_status_collect(s);
568 wt_status_print(s);
569 wt_status_collect_free_buffers(s);
571 return s->committable;
574 static int is_a_merge(const struct commit *current_head)
576 return !!(current_head->parents && current_head->parents->next);
579 static void assert_split_ident(struct ident_split *id, const struct strbuf *buf)
581 if (split_ident_line(id, buf->buf, buf->len) || !id->date_begin)
582 BUG("unable to parse our own ident: %s", buf->buf);
585 static void export_one(const char *var, const char *s, const char *e, int hack)
587 struct strbuf buf = STRBUF_INIT;
588 if (hack)
589 strbuf_addch(&buf, hack);
590 strbuf_add(&buf, s, e - s);
591 setenv(var, buf.buf, 1);
592 strbuf_release(&buf);
595 static int parse_force_date(const char *in, struct strbuf *out)
597 strbuf_addch(out, '@');
599 if (parse_date(in, out) < 0) {
600 int errors = 0;
601 unsigned long t = approxidate_careful(in, &errors);
602 if (errors)
603 return -1;
604 strbuf_addf(out, "%lu", t);
607 return 0;
610 static void set_ident_var(char **buf, char *val)
612 free(*buf);
613 *buf = val;
616 static void determine_author_info(struct strbuf *author_ident)
618 char *name, *email, *date;
619 struct ident_split author;
621 name = xstrdup_or_null(getenv("GIT_AUTHOR_NAME"));
622 email = xstrdup_or_null(getenv("GIT_AUTHOR_EMAIL"));
623 date = xstrdup_or_null(getenv("GIT_AUTHOR_DATE"));
625 if (author_message) {
626 struct ident_split ident;
627 size_t len;
628 const char *a;
630 a = find_commit_header(author_message_buffer, "author", &len);
631 if (!a)
632 die(_("commit '%s' lacks author header"), author_message);
633 if (split_ident_line(&ident, a, len) < 0)
634 die(_("commit '%s' has malformed author line"), author_message);
636 set_ident_var(&name, xmemdupz(ident.name_begin, ident.name_end - ident.name_begin));
637 set_ident_var(&email, xmemdupz(ident.mail_begin, ident.mail_end - ident.mail_begin));
639 if (ident.date_begin) {
640 struct strbuf date_buf = STRBUF_INIT;
641 strbuf_addch(&date_buf, '@');
642 strbuf_add(&date_buf, ident.date_begin, ident.date_end - ident.date_begin);
643 strbuf_addch(&date_buf, ' ');
644 strbuf_add(&date_buf, ident.tz_begin, ident.tz_end - ident.tz_begin);
645 set_ident_var(&date, strbuf_detach(&date_buf, NULL));
649 if (force_author) {
650 struct ident_split ident;
652 if (split_ident_line(&ident, force_author, strlen(force_author)) < 0)
653 die(_("malformed --author parameter"));
654 set_ident_var(&name, xmemdupz(ident.name_begin, ident.name_end - ident.name_begin));
655 set_ident_var(&email, xmemdupz(ident.mail_begin, ident.mail_end - ident.mail_begin));
658 if (force_date) {
659 struct strbuf date_buf = STRBUF_INIT;
660 if (parse_force_date(force_date, &date_buf))
661 die(_("invalid date format: %s"), force_date);
662 set_ident_var(&date, strbuf_detach(&date_buf, NULL));
665 strbuf_addstr(author_ident, fmt_ident(name, email, WANT_AUTHOR_IDENT, date,
666 IDENT_STRICT));
667 assert_split_ident(&author, author_ident);
668 export_one("GIT_AUTHOR_NAME", author.name_begin, author.name_end, 0);
669 export_one("GIT_AUTHOR_EMAIL", author.mail_begin, author.mail_end, 0);
670 export_one("GIT_AUTHOR_DATE", author.date_begin, author.tz_end, '@');
671 free(name);
672 free(email);
673 free(date);
676 static int author_date_is_interesting(void)
678 return author_message || force_date;
681 static void adjust_comment_line_char(const struct strbuf *sb)
683 char candidates[] = "#;@!$%^&|:";
684 char *candidate;
685 const char *p;
687 if (!memchr(sb->buf, candidates[0], sb->len)) {
688 free(comment_line_str_to_free);
689 comment_line_str = comment_line_str_to_free =
690 xstrfmt("%c", candidates[0]);
691 return;
694 p = sb->buf;
695 candidate = strchr(candidates, *p);
696 if (candidate)
697 *candidate = ' ';
698 for (p = sb->buf; *p; p++) {
699 if ((p[0] == '\n' || p[0] == '\r') && p[1]) {
700 candidate = strchr(candidates, p[1]);
701 if (candidate)
702 *candidate = ' ';
706 for (p = candidates; *p == ' '; p++)
708 if (!*p)
709 die(_("unable to select a comment character that is not used\n"
710 "in the current commit message"));
711 free(comment_line_str_to_free);
712 comment_line_str = comment_line_str_to_free = xstrfmt("%c", *p);
715 static void prepare_amend_commit(struct commit *commit, struct strbuf *sb,
716 struct pretty_print_context *ctx)
718 const char *buffer, *subject, *fmt;
720 buffer = repo_get_commit_buffer(the_repository, commit, NULL);
721 find_commit_subject(buffer, &subject);
723 * If we amend the 'amend!' commit then we don't want to
724 * duplicate the subject line.
726 fmt = starts_with(subject, "amend!") ? "%b" : "%B";
727 repo_format_commit_message(the_repository, commit, fmt, sb, ctx);
728 repo_unuse_commit_buffer(the_repository, commit, buffer);
731 static int prepare_to_commit(const char *index_file, const char *prefix,
732 struct commit *current_head,
733 struct wt_status *s,
734 struct strbuf *author_ident)
736 struct stat statbuf;
737 struct strbuf committer_ident = STRBUF_INIT;
738 int committable;
739 struct strbuf sb = STRBUF_INIT;
740 const char *hook_arg1 = NULL;
741 const char *hook_arg2 = NULL;
742 int clean_message_contents = (cleanup_mode != COMMIT_MSG_CLEANUP_NONE);
743 int old_display_comment_prefix;
744 int invoked_hook;
746 /* This checks and barfs if author is badly specified */
747 determine_author_info(author_ident);
749 if (!no_verify && run_commit_hook(use_editor, index_file, &invoked_hook,
750 "pre-commit", NULL))
751 return 0;
753 if (squash_message) {
755 * Insert the proper subject line before other commit
756 * message options add their content.
758 if (use_message && !strcmp(use_message, squash_message))
759 strbuf_addstr(&sb, "squash! ");
760 else {
761 struct pretty_print_context ctx = {0};
762 struct commit *c;
763 c = lookup_commit_reference_by_name(squash_message);
764 if (!c)
765 die(_("could not lookup commit '%s'"), squash_message);
766 ctx.output_encoding = get_commit_output_encoding();
767 repo_format_commit_message(the_repository, c,
768 "squash! %s\n\n", &sb,
769 &ctx);
773 if (have_option_m && !fixup_message) {
774 strbuf_addbuf(&sb, &message);
775 hook_arg1 = "message";
776 } else if (logfile && !strcmp(logfile, "-")) {
777 if (isatty(0))
778 fprintf(stderr, _("(reading log message from standard input)\n"));
779 if (strbuf_read(&sb, 0, 0) < 0)
780 die_errno(_("could not read log from standard input"));
781 hook_arg1 = "message";
782 } else if (logfile) {
783 if (strbuf_read_file(&sb, logfile, 0) < 0)
784 die_errno(_("could not read log file '%s'"),
785 logfile);
786 hook_arg1 = "message";
787 } else if (use_message) {
788 char *buffer;
789 buffer = strstr(use_message_buffer, "\n\n");
790 if (buffer)
791 strbuf_addstr(&sb, skip_blank_lines(buffer + 2));
792 hook_arg1 = "commit";
793 hook_arg2 = use_message;
794 } else if (fixup_message) {
795 struct pretty_print_context ctx = {0};
796 struct commit *commit;
797 char *fmt;
798 commit = lookup_commit_reference_by_name(fixup_commit);
799 if (!commit)
800 die(_("could not lookup commit '%s'"), fixup_commit);
801 ctx.output_encoding = get_commit_output_encoding();
802 fmt = xstrfmt("%s! %%s\n\n", fixup_prefix);
803 repo_format_commit_message(the_repository, commit, fmt, &sb,
804 &ctx);
805 free(fmt);
806 hook_arg1 = "message";
809 * Only `-m` commit message option is checked here, as
810 * it supports `--fixup` to append the commit message.
812 * The other commit message options `-c`/`-C`/`-F` are
813 * incompatible with all the forms of `--fixup` and
814 * have already errored out while parsing the `git commit`
815 * options.
817 if (have_option_m && !strcmp(fixup_prefix, "fixup"))
818 strbuf_addbuf(&sb, &message);
820 if (!strcmp(fixup_prefix, "amend")) {
821 if (have_option_m)
822 die(_("options '%s' and '%s:%s' cannot be used together"), "-m", "--fixup", fixup_message);
823 prepare_amend_commit(commit, &sb, &ctx);
825 } else if (!stat(git_path_merge_msg(the_repository), &statbuf)) {
826 size_t merge_msg_start;
829 * prepend SQUASH_MSG here if it exists and a
830 * "merge --squash" was originally performed
832 if (!stat(git_path_squash_msg(the_repository), &statbuf)) {
833 if (strbuf_read_file(&sb, git_path_squash_msg(the_repository), 0) < 0)
834 die_errno(_("could not read SQUASH_MSG"));
835 hook_arg1 = "squash";
836 } else
837 hook_arg1 = "merge";
839 merge_msg_start = sb.len;
840 if (strbuf_read_file(&sb, git_path_merge_msg(the_repository), 0) < 0)
841 die_errno(_("could not read MERGE_MSG"));
843 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS &&
844 wt_status_locate_end(sb.buf + merge_msg_start,
845 sb.len - merge_msg_start) <
846 sb.len - merge_msg_start)
847 s->added_cut_line = 1;
848 } else if (!stat(git_path_squash_msg(the_repository), &statbuf)) {
849 if (strbuf_read_file(&sb, git_path_squash_msg(the_repository), 0) < 0)
850 die_errno(_("could not read SQUASH_MSG"));
851 hook_arg1 = "squash";
852 } else if (template_file) {
853 if (strbuf_read_file(&sb, template_file, 0) < 0)
854 die_errno(_("could not read '%s'"), template_file);
855 hook_arg1 = "template";
856 clean_message_contents = 0;
860 * The remaining cases don't modify the template message, but
861 * just set the argument(s) to the prepare-commit-msg hook.
863 else if (whence == FROM_MERGE)
864 hook_arg1 = "merge";
865 else if (is_from_cherry_pick(whence) || whence == FROM_REBASE_PICK) {
866 hook_arg1 = "commit";
867 hook_arg2 = "CHERRY_PICK_HEAD";
870 if (squash_message) {
872 * If squash_commit was used for the commit subject,
873 * then we're possibly hijacking other commit log options.
874 * Reset the hook args to tell the real story.
876 hook_arg1 = "message";
877 hook_arg2 = "";
880 s->fp = fopen_for_writing(git_path_commit_editmsg());
881 if (!s->fp)
882 die_errno(_("could not open '%s'"), git_path_commit_editmsg());
884 /* Ignore status.displayCommentPrefix: we do need comments in COMMIT_EDITMSG. */
885 old_display_comment_prefix = s->display_comment_prefix;
886 s->display_comment_prefix = 1;
889 * Most hints are counter-productive when the commit has
890 * already started.
892 s->hints = 0;
894 if (clean_message_contents)
895 strbuf_stripspace(&sb, NULL);
897 if (signoff)
898 append_signoff(&sb, ignored_log_message_bytes(sb.buf, sb.len), 0);
900 if (fwrite(sb.buf, 1, sb.len, s->fp) < sb.len)
901 die_errno(_("could not write commit template"));
903 if (auto_comment_line_char)
904 adjust_comment_line_char(&sb);
905 strbuf_release(&sb);
907 /* This checks if committer ident is explicitly given */
908 strbuf_addstr(&committer_ident, git_committer_info(IDENT_STRICT));
909 if (use_editor && include_status) {
910 int ident_shown = 0;
911 int saved_color_setting;
912 struct ident_split ci, ai;
913 const char *hint_cleanup_all = allow_empty_message ?
914 _("Please enter the commit message for your changes."
915 " Lines starting\nwith '%s' will be ignored.\n") :
916 _("Please enter the commit message for your changes."
917 " Lines starting\nwith '%s' will be ignored, and an empty"
918 " message aborts the commit.\n");
919 const char *hint_cleanup_space = allow_empty_message ?
920 _("Please enter the commit message for your changes."
921 " Lines starting\n"
922 "with '%s' will be kept; you may remove them"
923 " yourself if you want to.\n") :
924 _("Please enter the commit message for your changes."
925 " Lines starting\n"
926 "with '%s' will be kept; you may remove them"
927 " yourself if you want to.\n"
928 "An empty message aborts the commit.\n");
929 if (whence != FROM_COMMIT) {
930 if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS)
931 wt_status_add_cut_line(s);
932 status_printf_ln(
933 s, GIT_COLOR_NORMAL,
934 whence == FROM_MERGE ?
935 _("\n"
936 "It looks like you may be committing a merge.\n"
937 "If this is not correct, please run\n"
938 " git update-ref -d MERGE_HEAD\n"
939 "and try again.\n") :
940 _("\n"
941 "It looks like you may be committing a cherry-pick.\n"
942 "If this is not correct, please run\n"
943 " git update-ref -d CHERRY_PICK_HEAD\n"
944 "and try again.\n"));
947 fprintf(s->fp, "\n");
948 if (cleanup_mode == COMMIT_MSG_CLEANUP_ALL)
949 status_printf(s, GIT_COLOR_NORMAL, hint_cleanup_all, comment_line_str);
950 else if (cleanup_mode == COMMIT_MSG_CLEANUP_SCISSORS) {
951 if (whence == FROM_COMMIT)
952 wt_status_add_cut_line(s);
953 } else /* COMMIT_MSG_CLEANUP_SPACE, that is. */
954 status_printf(s, GIT_COLOR_NORMAL, hint_cleanup_space, comment_line_str);
957 * These should never fail because they come from our own
958 * fmt_ident. They may fail the sane_ident test, but we know
959 * that the name and mail pointers will at least be valid,
960 * which is enough for our tests and printing here.
962 assert_split_ident(&ai, author_ident);
963 assert_split_ident(&ci, &committer_ident);
965 if (ident_cmp(&ai, &ci))
966 status_printf_ln(s, GIT_COLOR_NORMAL,
967 _("%s"
968 "Author: %.*s <%.*s>"),
969 ident_shown++ ? "" : "\n",
970 (int)(ai.name_end - ai.name_begin), ai.name_begin,
971 (int)(ai.mail_end - ai.mail_begin), ai.mail_begin);
973 if (author_date_is_interesting())
974 status_printf_ln(s, GIT_COLOR_NORMAL,
975 _("%s"
976 "Date: %s"),
977 ident_shown++ ? "" : "\n",
978 show_ident_date(&ai, DATE_MODE(NORMAL)));
980 if (!committer_ident_sufficiently_given())
981 status_printf_ln(s, GIT_COLOR_NORMAL,
982 _("%s"
983 "Committer: %.*s <%.*s>"),
984 ident_shown++ ? "" : "\n",
985 (int)(ci.name_end - ci.name_begin), ci.name_begin,
986 (int)(ci.mail_end - ci.mail_begin), ci.mail_begin);
988 status_printf_ln(s, GIT_COLOR_NORMAL, "%s", ""); /* Add new line for clarity */
990 saved_color_setting = s->use_color;
991 s->use_color = 0;
992 committable = run_status(s->fp, index_file, prefix, 1, s);
993 s->use_color = saved_color_setting;
994 string_list_clear(&s->change, 1);
995 } else {
996 struct object_id oid;
997 const char *parent = "HEAD";
999 if (!the_repository->index->initialized && repo_read_index(the_repository) < 0)
1000 die(_("Cannot read index"));
1002 if (amend)
1003 parent = "HEAD^1";
1005 if (repo_get_oid(the_repository, parent, &oid)) {
1006 int i, ita_nr = 0;
1008 /* TODO: audit for interaction with sparse-index. */
1009 ensure_full_index(the_repository->index);
1010 for (i = 0; i < the_repository->index->cache_nr; i++)
1011 if (ce_intent_to_add(the_repository->index->cache[i]))
1012 ita_nr++;
1013 committable = the_repository->index->cache_nr - ita_nr > 0;
1014 } else {
1016 * Unless the user did explicitly request a submodule
1017 * ignore mode by passing a command line option we do
1018 * not ignore any changed submodule SHA-1s when
1019 * comparing index and parent, no matter what is
1020 * configured. Otherwise we won't commit any
1021 * submodules which were manually staged, which would
1022 * be really confusing.
1024 struct diff_flags flags = DIFF_FLAGS_INIT;
1025 flags.override_submodule_config = 1;
1026 if (ignore_submodule_arg &&
1027 !strcmp(ignore_submodule_arg, "all"))
1028 flags.ignore_submodules = 1;
1029 committable = index_differs_from(the_repository,
1030 parent, &flags, 1);
1033 strbuf_release(&committer_ident);
1035 fclose(s->fp);
1037 if (trailer_args.nr) {
1038 if (amend_file_with_trailers(git_path_commit_editmsg(), &trailer_args))
1039 die(_("unable to pass trailers to --trailers"));
1040 strvec_clear(&trailer_args);
1044 * Reject an attempt to record a non-merge empty commit without
1045 * explicit --allow-empty. In the cherry-pick case, it may be
1046 * empty due to conflict resolution, which the user should okay.
1048 if (!committable && whence != FROM_MERGE && !allow_empty &&
1049 !(amend && is_a_merge(current_head))) {
1050 s->hints = advice_enabled(ADVICE_STATUS_HINTS);
1051 s->display_comment_prefix = old_display_comment_prefix;
1052 run_status(stdout, index_file, prefix, 0, s);
1053 if (amend)
1054 fputs(_(empty_amend_advice), stderr);
1055 else if (is_from_cherry_pick(whence) ||
1056 whence == FROM_REBASE_PICK) {
1057 fputs(_(empty_cherry_pick_advice), stderr);
1058 if (whence == FROM_CHERRY_PICK_SINGLE)
1059 fputs(_(empty_cherry_pick_advice_single), stderr);
1060 else if (whence == FROM_CHERRY_PICK_MULTI)
1061 fputs(_(empty_cherry_pick_advice_multi), stderr);
1062 else
1063 fputs(_(empty_rebase_pick_advice), stderr);
1065 return 0;
1068 if (!no_verify && invoked_hook) {
1070 * Re-read the index as the pre-commit-commit hook was invoked
1071 * and could have updated it. We must do this before we invoke
1072 * the editor and after we invoke run_status above.
1074 discard_index(the_repository->index);
1076 read_index_from(the_repository->index, index_file, repo_get_git_dir(the_repository));
1078 if (cache_tree_update(the_repository->index, 0)) {
1079 error(_("Error building trees"));
1080 return 0;
1083 if (run_commit_hook(use_editor, index_file, NULL, "prepare-commit-msg",
1084 git_path_commit_editmsg(), hook_arg1, hook_arg2, NULL))
1085 return 0;
1087 if (use_editor) {
1088 struct strvec env = STRVEC_INIT;
1090 strvec_pushf(&env, "GIT_INDEX_FILE=%s", index_file);
1091 if (launch_editor(git_path_commit_editmsg(), NULL, env.v)) {
1092 fprintf(stderr,
1093 _("Please supply the message using either -m or -F option.\n"));
1094 exit(1);
1096 strvec_clear(&env);
1099 if (!no_verify &&
1100 run_commit_hook(use_editor, index_file, NULL, "commit-msg",
1101 git_path_commit_editmsg(), NULL)) {
1102 return 0;
1105 return 1;
1108 static const char *find_author_by_nickname(const char *name)
1110 struct rev_info revs;
1111 struct commit *commit;
1112 struct strbuf buf = STRBUF_INIT;
1113 const char *av[20];
1114 int ac = 0;
1116 repo_init_revisions(the_repository, &revs, NULL);
1117 strbuf_addf(&buf, "--author=%s", name);
1118 av[++ac] = "--all";
1119 av[++ac] = "-i";
1120 av[++ac] = buf.buf;
1121 av[++ac] = NULL;
1122 setup_revisions(ac, av, &revs, NULL);
1123 revs.mailmap = xmalloc(sizeof(struct string_list));
1124 string_list_init_nodup(revs.mailmap);
1125 read_mailmap(revs.mailmap);
1127 if (prepare_revision_walk(&revs))
1128 die(_("revision walk setup failed"));
1129 commit = get_revision(&revs);
1130 if (commit) {
1131 struct pretty_print_context ctx = {0};
1132 ctx.date_mode.type = DATE_NORMAL;
1133 strbuf_release(&buf);
1134 repo_format_commit_message(the_repository, commit,
1135 "%aN <%aE>", &buf, &ctx);
1136 release_revisions(&revs);
1137 return strbuf_detach(&buf, NULL);
1139 die(_("--author '%s' is not 'Name <email>' and matches no existing author"), name);
1142 static void handle_ignored_arg(struct wt_status *s)
1144 if (!ignored_arg)
1145 ; /* default already initialized */
1146 else if (!strcmp(ignored_arg, "traditional"))
1147 s->show_ignored_mode = SHOW_TRADITIONAL_IGNORED;
1148 else if (!strcmp(ignored_arg, "no"))
1149 s->show_ignored_mode = SHOW_NO_IGNORED;
1150 else if (!strcmp(ignored_arg, "matching"))
1151 s->show_ignored_mode = SHOW_MATCHING_IGNORED;
1152 else
1153 die(_("Invalid ignored mode '%s'"), ignored_arg);
1156 static enum untracked_status_type parse_untracked_setting_name(const char *u)
1159 * Please update $__git_untracked_file_modes in
1160 * git-completion.bash when you add new options
1162 switch (git_parse_maybe_bool(u)) {
1163 case 0:
1164 u = "no";
1165 break;
1166 case 1:
1167 u = "normal";
1168 break;
1169 default:
1170 break;
1173 if (!strcmp(u, "no"))
1174 return SHOW_NO_UNTRACKED_FILES;
1175 else if (!strcmp(u, "normal"))
1176 return SHOW_NORMAL_UNTRACKED_FILES;
1177 else if (!strcmp(u, "all"))
1178 return SHOW_ALL_UNTRACKED_FILES;
1179 else
1180 return SHOW_UNTRACKED_FILES_ERROR;
1183 static void handle_untracked_files_arg(struct wt_status *s)
1185 enum untracked_status_type u;
1187 if (!untracked_files_arg)
1188 return; /* default already initialized */
1190 u = parse_untracked_setting_name(untracked_files_arg);
1191 if (u == SHOW_UNTRACKED_FILES_ERROR)
1192 die(_("Invalid untracked files mode '%s'"),
1193 untracked_files_arg);
1194 s->show_untracked_files = u;
1197 static const char *read_commit_message(const char *name)
1199 const char *out_enc;
1200 struct commit *commit;
1202 commit = lookup_commit_reference_by_name(name);
1203 if (!commit)
1204 die(_("could not lookup commit '%s'"), name);
1205 out_enc = get_commit_output_encoding();
1206 return repo_logmsg_reencode(the_repository, commit, NULL, out_enc);
1210 * Enumerate what needs to be propagated when --porcelain
1211 * is not in effect here.
1213 static struct status_deferred_config {
1214 enum wt_status_format status_format;
1215 int show_branch;
1216 enum ahead_behind_flags ahead_behind;
1217 } status_deferred_config = {
1218 STATUS_FORMAT_UNSPECIFIED,
1219 -1, /* unspecified */
1220 AHEAD_BEHIND_UNSPECIFIED,
1223 static void finalize_deferred_config(struct wt_status *s)
1225 int use_deferred_config = (status_format != STATUS_FORMAT_PORCELAIN &&
1226 status_format != STATUS_FORMAT_PORCELAIN_V2 &&
1227 !s->null_termination);
1229 if (s->null_termination) {
1230 if (status_format == STATUS_FORMAT_NONE ||
1231 status_format == STATUS_FORMAT_UNSPECIFIED)
1232 status_format = STATUS_FORMAT_PORCELAIN;
1233 else if (status_format == STATUS_FORMAT_LONG)
1234 die(_("options '%s' and '%s' cannot be used together"), "--long", "-z");
1237 if (use_deferred_config && status_format == STATUS_FORMAT_UNSPECIFIED)
1238 status_format = status_deferred_config.status_format;
1239 if (status_format == STATUS_FORMAT_UNSPECIFIED)
1240 status_format = STATUS_FORMAT_NONE;
1242 if (use_deferred_config && s->show_branch < 0)
1243 s->show_branch = status_deferred_config.show_branch;
1244 if (s->show_branch < 0)
1245 s->show_branch = 0;
1248 * If the user did not give a "--[no]-ahead-behind" command
1249 * line argument *AND* we will print in a human-readable format
1250 * (short, long etc.) then we inherit from the status.aheadbehind
1251 * config setting. In all other cases (and porcelain V[12] formats
1252 * in particular), we inherit _FULL for backwards compatibility.
1254 if (use_deferred_config &&
1255 s->ahead_behind_flags == AHEAD_BEHIND_UNSPECIFIED)
1256 s->ahead_behind_flags = status_deferred_config.ahead_behind;
1258 if (s->ahead_behind_flags == AHEAD_BEHIND_UNSPECIFIED)
1259 s->ahead_behind_flags = AHEAD_BEHIND_FULL;
1262 static void check_fixup_reword_options(int argc, const char *argv[]) {
1263 if (whence != FROM_COMMIT) {
1264 if (whence == FROM_MERGE)
1265 die(_("You are in the middle of a merge -- cannot reword."));
1266 else if (is_from_cherry_pick(whence))
1267 die(_("You are in the middle of a cherry-pick -- cannot reword."));
1269 if (argc)
1270 die(_("reword option of '%s' and path '%s' cannot be used together"), "--fixup", *argv);
1271 if (patch_interactive || interactive || all || also || only)
1272 die(_("reword option of '%s' and '%s' cannot be used together"),
1273 "--fixup", "--patch/--interactive/--all/--include/--only");
1276 static int parse_and_validate_options(int argc, const char *argv[],
1277 const struct option *options,
1278 const char * const usage[],
1279 const char *prefix,
1280 struct commit *current_head,
1281 struct wt_status *s)
1283 argc = parse_options(argc, argv, prefix, options, usage, 0);
1284 finalize_deferred_config(s);
1286 if (force_author && !strchr(force_author, '>'))
1287 force_author = find_author_by_nickname(force_author);
1289 if (force_author && renew_authorship)
1290 die(_("options '%s' and '%s' cannot be used together"), "--reset-author", "--author");
1292 if (logfile || have_option_m || use_message)
1293 use_editor = 0;
1295 /* Sanity check options */
1296 if (amend && !current_head)
1297 die(_("You have nothing to amend."));
1298 if (amend && whence != FROM_COMMIT) {
1299 if (whence == FROM_MERGE)
1300 die(_("You are in the middle of a merge -- cannot amend."));
1301 else if (is_from_cherry_pick(whence))
1302 die(_("You are in the middle of a cherry-pick -- cannot amend."));
1303 else if (whence == FROM_REBASE_PICK)
1304 die(_("You are in the middle of a rebase -- cannot amend."));
1306 if (fixup_message && squash_message)
1307 die(_("options '%s' and '%s' cannot be used together"), "--squash", "--fixup");
1308 die_for_incompatible_opt4(!!use_message, "-C",
1309 !!edit_message, "-c",
1310 !!logfile, "-F",
1311 !!fixup_message, "--fixup");
1312 die_for_incompatible_opt4(have_option_m, "-m",
1313 !!edit_message, "-c",
1314 !!use_message, "-C",
1315 !!logfile, "-F");
1316 if (use_message || edit_message || logfile ||fixup_message || have_option_m)
1317 FREE_AND_NULL(template_file);
1318 if (edit_message)
1319 use_message = edit_message;
1320 if (amend && !use_message && !fixup_message)
1321 use_message = "HEAD";
1322 if (!use_message && !is_from_cherry_pick(whence) &&
1323 !is_from_rebase(whence) && renew_authorship)
1324 die(_("--reset-author can be used only with -C, -c or --amend."));
1325 if (use_message) {
1326 use_message_buffer = read_commit_message(use_message);
1327 if (!renew_authorship) {
1328 author_message = use_message;
1329 author_message_buffer = use_message_buffer;
1332 if ((is_from_cherry_pick(whence) || whence == FROM_REBASE_PICK) &&
1333 !renew_authorship) {
1334 author_message = "CHERRY_PICK_HEAD";
1335 author_message_buffer = read_commit_message(author_message);
1338 if (patch_interactive)
1339 interactive = 1;
1341 die_for_incompatible_opt4(also, "-i/--include",
1342 only, "-o/--only",
1343 all, "-a/--all",
1344 interactive, "--interactive/-p/--patch");
1345 if (fixup_message) {
1347 * We limit --fixup's suboptions to only alpha characters.
1348 * If the first character after a run of alpha is colon,
1349 * then the part before the colon may be a known suboption
1350 * name like `amend` or `reword`, or a misspelt suboption
1351 * name. In either case, we treat it as
1352 * --fixup=<suboption>:<arg>.
1354 * Otherwise, we are dealing with --fixup=<commit>.
1356 char *p = fixup_message;
1357 while (isalpha(*p))
1358 p++;
1359 if (p > fixup_message && *p == ':') {
1360 *p = '\0';
1361 fixup_commit = p + 1;
1362 if (!strcmp("amend", fixup_message) ||
1363 !strcmp("reword", fixup_message)) {
1364 fixup_prefix = "amend";
1365 allow_empty = 1;
1366 if (*fixup_message == 'r') {
1367 check_fixup_reword_options(argc, argv);
1368 only = 1;
1370 } else {
1371 die(_("unknown option: --fixup=%s:%s"), fixup_message, fixup_commit);
1373 } else {
1374 fixup_commit = fixup_message;
1375 fixup_prefix = "fixup";
1376 use_editor = 0;
1380 if (0 <= edit_flag)
1381 use_editor = edit_flag;
1383 cleanup_mode = get_cleanup_mode(cleanup_arg, use_editor);
1385 handle_untracked_files_arg(s);
1387 if (all && argc > 0)
1388 die(_("paths '%s ...' with -a does not make sense"),
1389 argv[0]);
1391 if (status_format != STATUS_FORMAT_NONE)
1392 dry_run = 1;
1394 return argc;
1397 static int dry_run_commit(const char **argv, const char *prefix,
1398 const struct commit *current_head, struct wt_status *s)
1400 int committable;
1401 const char *index_file;
1403 index_file = prepare_index(argv, prefix, current_head, 1);
1404 committable = run_status(stdout, index_file, prefix, 0, s);
1405 rollback_index_files();
1407 return committable ? 0 : 1;
1410 define_list_config_array_extra(color_status_slots, {"added"});
1412 static int parse_status_slot(const char *slot)
1414 if (!strcasecmp(slot, "added"))
1415 return WT_STATUS_UPDATED;
1417 return LOOKUP_CONFIG(color_status_slots, slot);
1420 static int git_status_config(const char *k, const char *v,
1421 const struct config_context *ctx, void *cb)
1423 struct wt_status *s = cb;
1424 const char *slot_name;
1426 if (starts_with(k, "column."))
1427 return git_column_config(k, v, "status", &s->colopts);
1428 if (!strcmp(k, "status.submodulesummary")) {
1429 int is_bool;
1430 s->submodule_summary = git_config_bool_or_int(k, v, ctx->kvi,
1431 &is_bool);
1432 if (is_bool && s->submodule_summary)
1433 s->submodule_summary = -1;
1434 return 0;
1436 if (!strcmp(k, "status.short")) {
1437 if (git_config_bool(k, v))
1438 status_deferred_config.status_format = STATUS_FORMAT_SHORT;
1439 else
1440 status_deferred_config.status_format = STATUS_FORMAT_NONE;
1441 return 0;
1443 if (!strcmp(k, "status.branch")) {
1444 status_deferred_config.show_branch = git_config_bool(k, v);
1445 return 0;
1447 if (!strcmp(k, "status.aheadbehind")) {
1448 status_deferred_config.ahead_behind = git_config_bool(k, v);
1449 return 0;
1451 if (!strcmp(k, "status.showstash")) {
1452 s->show_stash = git_config_bool(k, v);
1453 return 0;
1455 if (!strcmp(k, "status.color") || !strcmp(k, "color.status")) {
1456 s->use_color = git_config_colorbool(k, v);
1457 return 0;
1459 if (!strcmp(k, "status.displaycommentprefix")) {
1460 s->display_comment_prefix = git_config_bool(k, v);
1461 return 0;
1463 if (skip_prefix(k, "status.color.", &slot_name) ||
1464 skip_prefix(k, "color.status.", &slot_name)) {
1465 int slot = parse_status_slot(slot_name);
1466 if (slot < 0)
1467 return 0;
1468 if (!v)
1469 return config_error_nonbool(k);
1470 return color_parse(v, s->color_palette[slot]);
1472 if (!strcmp(k, "status.relativepaths")) {
1473 s->relative_paths = git_config_bool(k, v);
1474 return 0;
1476 if (!strcmp(k, "status.showuntrackedfiles")) {
1477 enum untracked_status_type u;
1479 u = parse_untracked_setting_name(v);
1480 if (u == SHOW_UNTRACKED_FILES_ERROR)
1481 return error(_("Invalid untracked files mode '%s'"), v);
1482 s->show_untracked_files = u;
1483 return 0;
1485 if (!strcmp(k, "diff.renamelimit")) {
1486 if (s->rename_limit == -1)
1487 s->rename_limit = git_config_int(k, v, ctx->kvi);
1488 return 0;
1490 if (!strcmp(k, "status.renamelimit")) {
1491 s->rename_limit = git_config_int(k, v, ctx->kvi);
1492 return 0;
1494 if (!strcmp(k, "diff.renames")) {
1495 if (s->detect_rename == -1)
1496 s->detect_rename = git_config_rename(k, v);
1497 return 0;
1499 if (!strcmp(k, "status.renames")) {
1500 s->detect_rename = git_config_rename(k, v);
1501 return 0;
1503 return git_diff_ui_config(k, v, ctx, NULL);
1506 int cmd_status(int argc,
1507 const char **argv,
1508 const char *prefix,
1509 struct repository *repo UNUSED)
1511 static int no_renames = -1;
1512 static const char *rename_score_arg = (const char *)-1;
1513 static struct wt_status s;
1514 unsigned int progress_flag = 0;
1515 int fd;
1516 struct object_id oid;
1517 static struct option builtin_status_options[] = {
1518 OPT__VERBOSE(&verbose, N_("be verbose")),
1519 OPT_SET_INT('s', "short", &status_format,
1520 N_("show status concisely"), STATUS_FORMAT_SHORT),
1521 OPT_BOOL('b', "branch", &s.show_branch,
1522 N_("show branch information")),
1523 OPT_BOOL(0, "show-stash", &s.show_stash,
1524 N_("show stash information")),
1525 OPT_BOOL(0, "ahead-behind", &s.ahead_behind_flags,
1526 N_("compute full ahead/behind values")),
1527 OPT_CALLBACK_F(0, "porcelain", &status_format,
1528 N_("version"), N_("machine-readable output"),
1529 PARSE_OPT_OPTARG, opt_parse_porcelain),
1530 OPT_SET_INT(0, "long", &status_format,
1531 N_("show status in long format (default)"),
1532 STATUS_FORMAT_LONG),
1533 OPT_BOOL('z', "null", &s.null_termination,
1534 N_("terminate entries with NUL")),
1535 { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg,
1536 N_("mode"),
1537 N_("show untracked files, optional modes: all, normal, no. (Default: all)"),
1538 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1539 { OPTION_STRING, 0, "ignored", &ignored_arg,
1540 N_("mode"),
1541 N_("show ignored files, optional modes: traditional, matching, no. (Default: traditional)"),
1542 PARSE_OPT_OPTARG, NULL, (intptr_t)"traditional" },
1543 { OPTION_STRING, 0, "ignore-submodules", &ignore_submodule_arg, N_("when"),
1544 N_("ignore changes to submodules, optional when: all, dirty, untracked. (Default: all)"),
1545 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1546 OPT_COLUMN(0, "column", &s.colopts, N_("list untracked files in columns")),
1547 OPT_BOOL(0, "no-renames", &no_renames, N_("do not detect renames")),
1548 OPT_CALLBACK_F('M', "find-renames", &rename_score_arg,
1549 N_("n"), N_("detect renames, optionally set similarity index"),
1550 PARSE_OPT_OPTARG | PARSE_OPT_NONEG, opt_parse_rename_score),
1551 OPT_END(),
1554 if (argc == 2 && !strcmp(argv[1], "-h"))
1555 usage_with_options(builtin_status_usage, builtin_status_options);
1557 prepare_repo_settings(the_repository);
1558 the_repository->settings.command_requires_full_index = 0;
1560 status_init_config(&s, git_status_config);
1561 argc = parse_options(argc, argv, prefix,
1562 builtin_status_options,
1563 builtin_status_usage, 0);
1564 finalize_colopts(&s.colopts, -1);
1565 finalize_deferred_config(&s);
1567 handle_untracked_files_arg(&s);
1568 handle_ignored_arg(&s);
1570 if (s.show_ignored_mode == SHOW_MATCHING_IGNORED &&
1571 s.show_untracked_files == SHOW_NO_UNTRACKED_FILES)
1572 die(_("Unsupported combination of ignored and untracked-files arguments"));
1574 parse_pathspec(&s.pathspec, 0,
1575 PATHSPEC_PREFER_FULL,
1576 prefix, argv);
1578 if (status_format != STATUS_FORMAT_PORCELAIN &&
1579 status_format != STATUS_FORMAT_PORCELAIN_V2)
1580 progress_flag = REFRESH_PROGRESS;
1581 repo_read_index(the_repository);
1582 refresh_index(the_repository->index,
1583 REFRESH_QUIET|REFRESH_UNMERGED|progress_flag,
1584 &s.pathspec, NULL, NULL);
1586 if (use_optional_locks())
1587 fd = repo_hold_locked_index(the_repository, &index_lock, 0);
1588 else
1589 fd = -1;
1591 s.is_initial = repo_get_oid(the_repository, s.reference, &oid) ? 1 : 0;
1592 if (!s.is_initial)
1593 oidcpy(&s.oid_commit, &oid);
1595 s.ignore_submodule_arg = ignore_submodule_arg;
1596 s.status_format = status_format;
1597 s.verbose = verbose;
1598 if (no_renames != -1)
1599 s.detect_rename = !no_renames;
1600 if ((intptr_t)rename_score_arg != -1) {
1601 if (s.detect_rename < DIFF_DETECT_RENAME)
1602 s.detect_rename = DIFF_DETECT_RENAME;
1603 if (rename_score_arg)
1604 s.rename_score = parse_rename_score(&rename_score_arg);
1607 wt_status_collect(&s);
1609 if (0 <= fd)
1610 repo_update_index_if_able(the_repository, &index_lock);
1612 if (s.relative_paths)
1613 s.prefix = prefix;
1615 wt_status_print(&s);
1616 wt_status_collect_free_buffers(&s);
1618 return 0;
1621 static int git_commit_config(const char *k, const char *v,
1622 const struct config_context *ctx, void *cb)
1624 struct wt_status *s = cb;
1626 if (!strcmp(k, "commit.template"))
1627 return git_config_pathname(&template_file, k, v);
1628 if (!strcmp(k, "commit.status")) {
1629 include_status = git_config_bool(k, v);
1630 return 0;
1632 if (!strcmp(k, "commit.cleanup"))
1633 return git_config_string(&cleanup_arg, k, v);
1634 if (!strcmp(k, "commit.gpgsign")) {
1635 sign_commit = git_config_bool(k, v) ? "" : NULL;
1636 return 0;
1638 if (!strcmp(k, "commit.verbose")) {
1639 int is_bool;
1640 config_commit_verbose = git_config_bool_or_int(k, v, ctx->kvi,
1641 &is_bool);
1642 return 0;
1645 return git_status_config(k, v, ctx, s);
1648 int cmd_commit(int argc,
1649 const char **argv,
1650 const char *prefix,
1651 struct repository *repo UNUSED)
1653 static struct wt_status s;
1654 static struct option builtin_commit_options[] = {
1655 OPT__QUIET(&quiet, N_("suppress summary after successful commit")),
1656 OPT__VERBOSE(&verbose, N_("show diff in commit message template")),
1658 OPT_GROUP(N_("Commit message options")),
1659 OPT_FILENAME('F', "file", &logfile, N_("read message from file")),
1660 OPT_STRING(0, "author", &force_author, N_("author"), N_("override author for commit")),
1661 OPT_STRING(0, "date", &force_date, N_("date"), N_("override date for commit")),
1662 OPT_CALLBACK('m', "message", &message, N_("message"), N_("commit message"), opt_parse_m),
1663 OPT_STRING('c', "reedit-message", &edit_message, N_("commit"), N_("reuse and edit message from specified commit")),
1664 OPT_STRING('C', "reuse-message", &use_message, N_("commit"), N_("reuse message from specified commit")),
1666 * TRANSLATORS: Leave "[(amend|reword):]" as-is,
1667 * and only translate <commit>.
1669 OPT_STRING(0, "fixup", &fixup_message, N_("[(amend|reword):]commit"), N_("use autosquash formatted message to fixup or amend/reword specified commit")),
1670 OPT_STRING(0, "squash", &squash_message, N_("commit"), N_("use autosquash formatted message to squash specified commit")),
1671 OPT_BOOL(0, "reset-author", &renew_authorship, N_("the commit is authored by me now (used with -C/-c/--amend)")),
1672 OPT_PASSTHRU_ARGV(0, "trailer", &trailer_args, N_("trailer"), N_("add custom trailer(s)"), PARSE_OPT_NONEG),
1673 OPT_BOOL('s', "signoff", &signoff, N_("add a Signed-off-by trailer")),
1674 OPT_FILENAME('t', "template", &template_file, N_("use specified template file")),
1675 OPT_BOOL('e', "edit", &edit_flag, N_("force edit of commit")),
1676 OPT_CLEANUP(&cleanup_arg),
1677 OPT_BOOL(0, "status", &include_status, N_("include status in commit message template")),
1678 { OPTION_STRING, 'S', "gpg-sign", &sign_commit, N_("key-id"),
1679 N_("GPG sign commit"), PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
1680 /* end commit message options */
1682 OPT_GROUP(N_("Commit contents options")),
1683 OPT_BOOL('a', "all", &all, N_("commit all changed files")),
1684 OPT_BOOL('i', "include", &also, N_("add specified files to index for commit")),
1685 OPT_BOOL(0, "interactive", &interactive, N_("interactively add files")),
1686 OPT_BOOL('p', "patch", &patch_interactive, N_("interactively add changes")),
1687 OPT_BOOL('o', "only", &only, N_("commit only specified files")),
1688 OPT_BOOL('n', "no-verify", &no_verify, N_("bypass pre-commit and commit-msg hooks")),
1689 OPT_BOOL(0, "dry-run", &dry_run, N_("show what would be committed")),
1690 OPT_SET_INT(0, "short", &status_format, N_("show status concisely"),
1691 STATUS_FORMAT_SHORT),
1692 OPT_BOOL(0, "branch", &s.show_branch, N_("show branch information")),
1693 OPT_BOOL(0, "ahead-behind", &s.ahead_behind_flags,
1694 N_("compute full ahead/behind values")),
1695 OPT_SET_INT(0, "porcelain", &status_format,
1696 N_("machine-readable output"), STATUS_FORMAT_PORCELAIN),
1697 OPT_SET_INT(0, "long", &status_format,
1698 N_("show status in long format (default)"),
1699 STATUS_FORMAT_LONG),
1700 OPT_BOOL('z', "null", &s.null_termination,
1701 N_("terminate entries with NUL")),
1702 OPT_BOOL(0, "amend", &amend, N_("amend previous commit")),
1703 OPT_BOOL(0, "no-post-rewrite", &no_post_rewrite, N_("bypass post-rewrite hook")),
1704 { 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" },
1705 OPT_PATHSPEC_FROM_FILE(&pathspec_from_file),
1706 OPT_PATHSPEC_FILE_NUL(&pathspec_file_nul),
1707 /* end commit contents options */
1709 OPT_HIDDEN_BOOL(0, "allow-empty", &allow_empty,
1710 N_("ok to record an empty change")),
1711 OPT_HIDDEN_BOOL(0, "allow-empty-message", &allow_empty_message,
1712 N_("ok to record a change with an empty message")),
1714 OPT_END()
1717 struct strbuf sb = STRBUF_INIT;
1718 struct strbuf author_ident = STRBUF_INIT;
1719 const char *index_file, *reflog_msg;
1720 struct object_id oid;
1721 struct commit_list *parents = NULL;
1722 struct stat statbuf;
1723 struct commit *current_head = NULL;
1724 struct commit_extra_header *extra = NULL;
1725 struct strbuf err = STRBUF_INIT;
1726 int ret = 0;
1728 if (argc == 2 && !strcmp(argv[1], "-h"))
1729 usage_with_options(builtin_commit_usage, builtin_commit_options);
1731 prepare_repo_settings(the_repository);
1732 the_repository->settings.command_requires_full_index = 0;
1734 status_init_config(&s, git_commit_config);
1735 s.commit_template = 1;
1736 status_format = STATUS_FORMAT_NONE; /* Ignore status.short */
1737 s.colopts = 0;
1739 if (repo_get_oid(the_repository, "HEAD", &oid))
1740 current_head = NULL;
1741 else {
1742 current_head = lookup_commit_or_die(&oid, "HEAD");
1743 if (repo_parse_commit(the_repository, current_head))
1744 die(_("could not parse HEAD commit"));
1746 verbose = -1; /* unspecified */
1747 argc = parse_and_validate_options(argc, argv, builtin_commit_options,
1748 builtin_commit_usage,
1749 prefix, current_head, &s);
1750 if (verbose == -1)
1751 verbose = (config_commit_verbose < 0) ? 0 : config_commit_verbose;
1753 if (dry_run)
1754 return dry_run_commit(argv, prefix, current_head, &s);
1755 index_file = prepare_index(argv, prefix, current_head, 0);
1757 /* Set up everything for writing the commit object. This includes
1758 running hooks, writing the trees, and interacting with the user. */
1759 if (!prepare_to_commit(index_file, prefix,
1760 current_head, &s, &author_ident)) {
1761 ret = 1;
1762 rollback_index_files();
1763 goto cleanup;
1766 /* Determine parents */
1767 reflog_msg = getenv("GIT_REFLOG_ACTION");
1768 if (!current_head) {
1769 if (!reflog_msg)
1770 reflog_msg = "commit (initial)";
1771 } else if (amend) {
1772 if (!reflog_msg)
1773 reflog_msg = "commit (amend)";
1774 parents = copy_commit_list(current_head->parents);
1775 } else if (whence == FROM_MERGE) {
1776 struct strbuf m = STRBUF_INIT;
1777 FILE *fp;
1778 int allow_fast_forward = 1;
1779 struct commit_list **pptr = &parents;
1781 if (!reflog_msg)
1782 reflog_msg = "commit (merge)";
1783 pptr = commit_list_append(current_head, pptr);
1784 fp = xfopen(git_path_merge_head(the_repository), "r");
1785 while (strbuf_getline_lf(&m, fp) != EOF) {
1786 struct commit *parent;
1788 parent = get_merge_parent(m.buf);
1789 if (!parent)
1790 die(_("Corrupt MERGE_HEAD file (%s)"), m.buf);
1791 pptr = commit_list_append(parent, pptr);
1793 fclose(fp);
1794 strbuf_release(&m);
1795 if (!stat(git_path_merge_mode(the_repository), &statbuf)) {
1796 if (strbuf_read_file(&sb, git_path_merge_mode(the_repository), 0) < 0)
1797 die_errno(_("could not read MERGE_MODE"));
1798 if (!strcmp(sb.buf, "no-ff"))
1799 allow_fast_forward = 0;
1801 if (allow_fast_forward)
1802 reduce_heads_replace(&parents);
1803 } else {
1804 if (!reflog_msg)
1805 reflog_msg = is_from_cherry_pick(whence)
1806 ? "commit (cherry-pick)"
1807 : is_from_rebase(whence)
1808 ? "commit (rebase)"
1809 : "commit";
1810 commit_list_insert(current_head, &parents);
1813 /* Finally, get the commit message */
1814 strbuf_reset(&sb);
1815 if (strbuf_read_file(&sb, git_path_commit_editmsg(), 0) < 0) {
1816 int saved_errno = errno;
1817 rollback_index_files();
1818 die(_("could not read commit message: %s"), strerror(saved_errno));
1821 cleanup_message(&sb, cleanup_mode, verbose);
1823 if (message_is_empty(&sb, cleanup_mode) && !allow_empty_message) {
1824 rollback_index_files();
1825 fprintf(stderr, _("Aborting commit due to empty commit message.\n"));
1826 exit(1);
1828 if (template_untouched(&sb, template_file, cleanup_mode) && !allow_empty_message) {
1829 rollback_index_files();
1830 fprintf(stderr, _("Aborting commit; you did not edit the message.\n"));
1831 exit(1);
1834 if (fixup_message && starts_with(sb.buf, "amend! ") &&
1835 !allow_empty_message) {
1836 struct strbuf body = STRBUF_INIT;
1837 size_t len = commit_subject_length(sb.buf);
1838 strbuf_addstr(&body, sb.buf + len);
1839 if (message_is_empty(&body, cleanup_mode)) {
1840 rollback_index_files();
1841 fprintf(stderr, _("Aborting commit due to empty commit message body.\n"));
1842 exit(1);
1844 strbuf_release(&body);
1847 if (amend) {
1848 const char *exclude_gpgsig[3] = { "gpgsig", "gpgsig-sha256", NULL };
1849 extra = read_commit_extra_headers(current_head, exclude_gpgsig);
1850 } else {
1851 struct commit_extra_header **tail = &extra;
1852 append_merge_tag_headers(parents, &tail);
1855 if (commit_tree_extended(sb.buf, sb.len, &the_repository->index->cache_tree->oid,
1856 parents, &oid, author_ident.buf, NULL,
1857 sign_commit, extra)) {
1858 rollback_index_files();
1859 die(_("failed to write commit object"));
1862 if (update_head_with_reflog(current_head, &oid, reflog_msg, &sb,
1863 &err)) {
1864 rollback_index_files();
1865 die("%s", err.buf);
1868 sequencer_post_commit_cleanup(the_repository, 0);
1869 unlink(git_path_merge_head(the_repository));
1870 unlink(git_path_merge_msg(the_repository));
1871 unlink(git_path_merge_mode(the_repository));
1872 unlink(git_path_squash_msg(the_repository));
1874 if (commit_index_files())
1875 die(_("repository has been updated, but unable to write\n"
1876 "new index file. Check that disk is not full and quota is\n"
1877 "not exceeded, and then \"git restore --staged :/\" to recover."));
1879 git_test_write_commit_graph_or_die();
1881 repo_rerere(the_repository, 0);
1882 run_auto_maintenance(quiet);
1883 run_commit_hook(use_editor, repo_get_index_file(the_repository),
1884 NULL, "post-commit", NULL);
1885 if (amend && !no_post_rewrite) {
1886 commit_post_rewrite(the_repository, current_head, &oid);
1888 if (!quiet) {
1889 unsigned int flags = 0;
1891 if (!current_head)
1892 flags |= SUMMARY_INITIAL_COMMIT;
1893 if (author_date_is_interesting())
1894 flags |= SUMMARY_SHOW_AUTHOR_DATE;
1895 print_commit_summary(the_repository, prefix,
1896 &oid, flags);
1899 apply_autostash_ref(the_repository, "MERGE_AUTOSTASH");
1901 cleanup:
1902 free_commit_extra_headers(extra);
1903 free_commit_list(parents);
1904 strbuf_release(&author_ident);
1905 strbuf_release(&err);
1906 strbuf_release(&sb);
1907 free(logfile);
1908 free(template_file);
1909 return ret;