4 * Copyright (c) 2007 Kristian Høgsberg <krh@redhat.com>
5 * Based on git-commit.sh by Junio C Hamano and Linus Torvalds
9 #include "cache-tree.h"
17 #include "wt-status.h"
18 #include "run-command.h"
23 #include "parse-options.h"
24 #include "string-list.h"
26 #include "unpack-trees.h"
29 static const char * const builtin_commit_usage[] = {
30 "git commit [options] [--] <filepattern>...",
34 static const char * const builtin_status_usage[] = {
35 "git status [options] [--] <filepattern>...",
39 static const char implicit_ident_advice[] =
40 "Your name and email address were configured automatically based\n"
41 "on your username and hostname. Please check that they are accurate.\n"
42 "You can suppress this message by setting them explicitly:\n"
44 " git config --global user.name \"Your Name\"\n"
45 " git config --global user.email you@example.com\n"
47 "If the identity used for this commit is wrong, you can fix it with:\n"
49 " git commit --amend --author='Your Name <you@example.com>'\n";
51 static const char empty_amend_advice[] =
52 "You asked to amend the most recent commit, but doing so would make\n"
53 "it empty. You can repeat your command with --allow-empty, or you can\n"
54 "remove the commit entirely with \"git reset HEAD^\".\n";
56 static unsigned char head_sha1[20];
58 static char *use_message_buffer;
59 static const char commit_editmsg[] = "COMMIT_EDITMSG";
60 static struct lock_file index_lock; /* real index */
61 static struct lock_file false_lock; /* used only for partial commits */
68 static const char *logfile, *force_author;
69 static const char *template_file;
70 static char *edit_message, *use_message;
71 static char *author_name, *author_email, *author_date;
72 static int all, edit_flag, also, interactive, only, amend, signoff;
73 static int quiet, verbose, no_verify, allow_empty, dry_run, renew_authorship;
74 static int no_post_rewrite, allow_empty_message;
75 static char *untracked_files_arg, *force_date, *ignore_submodule_arg;
77 * The default commit message cleanup mode will remove the lines
78 * beginning with # (shell comments) and leading and trailing
79 * whitespaces (empty lines or containing only whitespaces)
80 * if editor is used, and only the whitespaces if the message
81 * is specified explicitly.
88 static char *cleanup_arg;
90 static int use_editor = 1, initial_commit, in_merge, include_status = 1;
91 static int show_ignored_in_status;
92 static const char *only_include_assumed;
93 static struct strbuf message;
95 static int null_termination;
99 STATUS_FORMAT_PORCELAIN
100 } status_format = STATUS_FORMAT_LONG;
101 static int status_show_branch;
103 static int opt_parse_m(const struct option *opt, const char *arg, int unset)
105 struct strbuf *buf = opt->value;
107 strbuf_setlen(buf, 0);
109 strbuf_addstr(buf, arg);
110 strbuf_addstr(buf, "\n\n");
115 static struct option builtin_commit_options[] = {
117 OPT__VERBOSE(&verbose),
119 OPT_GROUP("Commit message options"),
120 OPT_FILENAME('F', "file", &logfile, "read log from file"),
121 OPT_STRING(0, "author", &force_author, "AUTHOR", "override author for commit"),
122 OPT_STRING(0, "date", &force_date, "DATE", "override date for commit"),
123 OPT_CALLBACK('m', "message", &message, "MESSAGE", "specify commit message", opt_parse_m),
124 OPT_STRING('c', "reedit-message", &edit_message, "COMMIT", "reuse and edit message from specified commit"),
125 OPT_STRING('C', "reuse-message", &use_message, "COMMIT", "reuse message from specified commit"),
126 OPT_BOOLEAN(0, "reset-author", &renew_authorship, "the commit is authored by me now (used with -C-c/--amend)"),
127 OPT_BOOLEAN('s', "signoff", &signoff, "add Signed-off-by:"),
128 OPT_FILENAME('t', "template", &template_file, "use specified template file"),
129 OPT_BOOLEAN('e', "edit", &edit_flag, "force edit of commit"),
130 OPT_STRING(0, "cleanup", &cleanup_arg, "default", "how to strip spaces and #comments from message"),
131 OPT_BOOLEAN(0, "status", &include_status, "include status in commit message template"),
132 /* end commit message options */
134 OPT_GROUP("Commit contents options"),
135 OPT_BOOLEAN('a', "all", &all, "commit all changed files"),
136 OPT_BOOLEAN('i', "include", &also, "add specified files to index for commit"),
137 OPT_BOOLEAN(0, "interactive", &interactive, "interactively add files"),
138 OPT_BOOLEAN('o', "only", &only, "commit only specified files"),
139 OPT_BOOLEAN('n', "no-verify", &no_verify, "bypass pre-commit hook"),
140 OPT_BOOLEAN(0, "dry-run", &dry_run, "show what would be committed"),
141 OPT_SET_INT(0, "short", &status_format, "show status concisely",
142 STATUS_FORMAT_SHORT),
143 OPT_BOOLEAN(0, "branch", &status_show_branch, "show branch information"),
144 OPT_SET_INT(0, "porcelain", &status_format,
145 "show porcelain output format", STATUS_FORMAT_PORCELAIN),
146 OPT_BOOLEAN('z', "null", &null_termination,
147 "terminate entries with NUL"),
148 OPT_BOOLEAN(0, "amend", &amend, "amend previous commit"),
149 OPT_BOOLEAN(0, "no-post-rewrite", &no_post_rewrite, "bypass post-rewrite hook"),
150 { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg, "mode", "show untracked files, optional modes: all, normal, no. (Default: all)", PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
151 /* end commit contents options */
153 { OPTION_BOOLEAN, 0, "allow-empty", &allow_empty, NULL,
154 "ok to record an empty change",
155 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN },
156 { OPTION_BOOLEAN, 0, "allow-empty-message", &allow_empty_message, NULL,
157 "ok to record a change with an empty message",
158 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN },
163 static void rollback_index_files(void)
165 switch (commit_style) {
167 break; /* nothing to do */
169 rollback_lock_file(&index_lock);
172 rollback_lock_file(&index_lock);
173 rollback_lock_file(&false_lock);
178 static int commit_index_files(void)
182 switch (commit_style) {
184 break; /* nothing to do */
186 err = commit_lock_file(&index_lock);
189 err = commit_lock_file(&index_lock);
190 rollback_lock_file(&false_lock);
198 * Take a union of paths in the index and the named tree (typically, "HEAD"),
199 * and return the paths that match the given pattern in list.
201 static int list_paths(struct string_list *list, const char *with_tree,
202 const char *prefix, const char **pattern)
207 for (i = 0; pattern[i]; i++)
212 overlay_tree_on_cache(with_tree, prefix);
214 for (i = 0; i < active_nr; i++) {
215 struct cache_entry *ce = active_cache[i];
216 struct string_list_item *item;
218 if (ce->ce_flags & CE_UPDATE)
220 if (!match_pathspec(pattern, ce->name, ce_namelen(ce), 0, m))
222 item = string_list_insert(list, ce->name);
223 if (ce_skip_worktree(ce))
224 item->util = item; /* better a valid pointer than a fake one */
227 return report_path_error(m, pattern, prefix ? strlen(prefix) : 0);
230 static void add_remove_files(struct string_list *list)
233 for (i = 0; i < list->nr; i++) {
235 struct string_list_item *p = &(list->items[i]);
237 /* p->util is skip-worktree */
241 if (!lstat(p->string, &st)) {
242 if (add_to_cache(p->string, &st, 0))
243 die("updating files failed");
245 remove_file_from_cache(p->string);
249 static void create_base_index(void)
252 struct unpack_trees_options opts;
255 if (initial_commit) {
260 memset(&opts, 0, sizeof(opts));
264 opts.src_index = &the_index;
265 opts.dst_index = &the_index;
267 opts.fn = oneway_merge;
268 tree = parse_tree_indirect(head_sha1);
270 die("failed to unpack HEAD tree object");
272 init_tree_desc(&t, tree->buffer, tree->size);
273 if (unpack_trees(1, &t, &opts))
274 exit(128); /* We've already reported the error, finish dying */
277 static void refresh_cache_or_die(int refresh_flags)
280 * refresh_flags contains REFRESH_QUIET, so the only errors
281 * are for unmerged entries.
283 if (refresh_cache(refresh_flags | REFRESH_IN_PORCELAIN))
284 die_resolve_conflict("commit");
287 static char *prepare_index(int argc, const char **argv, const char *prefix, int is_status)
290 struct string_list partial;
291 const char **pathspec = NULL;
292 int refresh_flags = REFRESH_QUIET;
295 refresh_flags |= REFRESH_UNMERGED;
297 if (interactive_add(argc, argv, prefix) != 0)
298 die("interactive add failed");
299 if (read_cache_preload(NULL) < 0)
300 die("index file corrupt");
301 commit_style = COMMIT_AS_IS;
302 return get_index_file();
306 pathspec = get_pathspec(prefix, argv);
308 if (read_cache_preload(pathspec) < 0)
309 die("index file corrupt");
312 * Non partial, non as-is commit.
314 * (1) get the real index;
315 * (2) update the_index as necessary;
316 * (3) write the_index out to the real index (still locked);
317 * (4) return the name of the locked index file.
319 * The caller should run hooks on the locked real index, and
320 * (A) if all goes well, commit the real index;
321 * (B) on failure, rollback the real index.
323 if (all || (also && pathspec && *pathspec)) {
324 fd = hold_locked_index(&index_lock, 1);
325 add_files_to_cache(also ? prefix : NULL, pathspec, 0);
326 refresh_cache_or_die(refresh_flags);
327 if (write_cache(fd, active_cache, active_nr) ||
328 close_lock_file(&index_lock))
329 die("unable to write new_index file");
330 commit_style = COMMIT_NORMAL;
331 return index_lock.filename;
337 * (1) return the name of the real index file.
339 * The caller should run hooks on the real index,
340 * and create commit from the_index.
341 * We still need to refresh the index here.
343 if (!pathspec || !*pathspec) {
344 fd = hold_locked_index(&index_lock, 1);
345 refresh_cache_or_die(refresh_flags);
346 if (write_cache(fd, active_cache, active_nr) ||
347 commit_locked_index(&index_lock))
348 die("unable to write new_index file");
349 commit_style = COMMIT_AS_IS;
350 return get_index_file();
356 * (0) find the set of affected paths;
357 * (1) get lock on the real index file;
358 * (2) update the_index with the given paths;
359 * (3) write the_index out to the real index (still locked);
360 * (4) get lock on the false index file;
361 * (5) reset the_index from HEAD;
362 * (6) update the_index the same way as (2);
363 * (7) write the_index out to the false index file;
364 * (8) return the name of the false index file (still locked);
366 * The caller should run hooks on the locked false index, and
367 * create commit from it. Then
368 * (A) if all goes well, commit the real index;
369 * (B) on failure, rollback the real index;
370 * In either case, rollback the false index.
372 commit_style = COMMIT_PARTIAL;
375 die("cannot do a partial commit during a merge.");
377 memset(&partial, 0, sizeof(partial));
378 partial.strdup_strings = 1;
379 if (list_paths(&partial, initial_commit ? NULL : "HEAD", prefix, pathspec))
383 if (read_cache() < 0)
384 die("cannot read the index");
386 fd = hold_locked_index(&index_lock, 1);
387 add_remove_files(&partial);
388 refresh_cache(REFRESH_QUIET);
389 if (write_cache(fd, active_cache, active_nr) ||
390 close_lock_file(&index_lock))
391 die("unable to write new_index file");
393 fd = hold_lock_file_for_update(&false_lock,
394 git_path("next-index-%"PRIuMAX,
395 (uintmax_t) getpid()),
399 add_remove_files(&partial);
400 refresh_cache(REFRESH_QUIET);
402 if (write_cache(fd, active_cache, active_nr) ||
403 close_lock_file(&false_lock))
404 die("unable to write temporary index file");
407 read_cache_from(false_lock.filename);
409 return false_lock.filename;
412 static int run_status(FILE *fp, const char *index_file, const char *prefix, int nowarn,
415 unsigned char sha1[20];
417 if (s->relative_paths)
422 s->reference = "HEAD^1";
424 s->verbose = verbose;
425 s->index_file = index_file;
428 s->is_initial = get_sha1(s->reference, sha1) ? 1 : 0;
430 wt_status_collect(s);
432 switch (status_format) {
433 case STATUS_FORMAT_SHORT:
434 wt_shortstatus_print(s, null_termination, status_show_branch);
436 case STATUS_FORMAT_PORCELAIN:
437 wt_porcelain_print(s, null_termination);
439 case STATUS_FORMAT_LONG:
444 return s->commitable;
447 static int is_a_merge(const unsigned char *sha1)
449 struct commit *commit = lookup_commit(sha1);
450 if (!commit || parse_commit(commit))
451 die("could not parse HEAD commit");
452 return !!(commit->parents && commit->parents->next);
455 static const char sign_off_header[] = "Signed-off-by: ";
457 static void determine_author_info(void)
459 char *name, *email, *date;
461 name = getenv("GIT_AUTHOR_NAME");
462 email = getenv("GIT_AUTHOR_EMAIL");
463 date = getenv("GIT_AUTHOR_DATE");
465 if (use_message && !renew_authorship) {
466 const char *a, *lb, *rb, *eol;
468 a = strstr(use_message_buffer, "\nauthor ");
470 die("invalid commit: %s", use_message);
472 lb = strchrnul(a + strlen("\nauthor "), '<');
473 rb = strchrnul(lb, '>');
474 eol = strchrnul(rb, '\n');
475 if (!*lb || !*rb || !*eol)
476 die("invalid commit: %s", use_message);
478 if (lb == a + strlen("\nauthor "))
479 /* \nauthor <foo@example.com> */
480 name = xcalloc(1, 1);
482 name = xmemdupz(a + strlen("\nauthor "),
484 (a + strlen("\nauthor "))));
485 email = xmemdupz(lb + strlen("<"), rb - (lb + strlen("<")));
486 date = xmemdupz(rb + strlen("> "), eol - (rb + strlen("> ")));
490 const char *lb = strstr(force_author, " <");
491 const char *rb = strchr(force_author, '>');
494 die("malformed --author parameter");
495 name = xstrndup(force_author, lb - force_author);
496 email = xstrndup(lb + 2, rb - (lb + 2));
503 author_email = email;
507 static int ends_rfc2822_footer(struct strbuf *sb)
514 const char *buf = sb->buf;
516 for (i = len - 1; i > 0; i--) {
517 if (hit && buf[i] == '\n')
519 hit = (buf[i] == '\n');
522 while (i < len - 1 && buf[i] == '\n')
525 for (; i < len; i = k) {
526 for (k = i; k < len && buf[k] != '\n'; k++)
530 if ((buf[k] == ' ' || buf[k] == '\t') && !first)
535 for (j = 0; i + j < len; j++) {
548 static int prepare_to_commit(const char *index_file, const char *prefix,
552 int commitable, saved_color_setting;
553 struct strbuf sb = STRBUF_INIT;
556 const char *hook_arg1 = NULL;
557 const char *hook_arg2 = NULL;
560 if (!no_verify && run_hook(index_file, "pre-commit", NULL))
564 strbuf_addbuf(&sb, &message);
565 hook_arg1 = "message";
566 } else if (logfile && !strcmp(logfile, "-")) {
568 fprintf(stderr, "(reading log message from standard input)\n");
569 if (strbuf_read(&sb, 0, 0) < 0)
570 die_errno("could not read log from standard input");
571 hook_arg1 = "message";
572 } else if (logfile) {
573 if (strbuf_read_file(&sb, logfile, 0) < 0)
574 die_errno("could not read log file '%s'",
576 hook_arg1 = "message";
577 } else if (use_message) {
578 buffer = strstr(use_message_buffer, "\n\n");
579 if (!buffer || buffer[2] == '\0')
580 die("commit has empty message");
581 strbuf_add(&sb, buffer + 2, strlen(buffer + 2));
582 hook_arg1 = "commit";
583 hook_arg2 = use_message;
584 } else if (!stat(git_path("MERGE_MSG"), &statbuf)) {
585 if (strbuf_read_file(&sb, git_path("MERGE_MSG"), 0) < 0)
586 die_errno("could not read MERGE_MSG");
588 } else if (!stat(git_path("SQUASH_MSG"), &statbuf)) {
589 if (strbuf_read_file(&sb, git_path("SQUASH_MSG"), 0) < 0)
590 die_errno("could not read SQUASH_MSG");
591 hook_arg1 = "squash";
592 } else if (template_file && !stat(template_file, &statbuf)) {
593 if (strbuf_read_file(&sb, template_file, 0) < 0)
594 die_errno("could not read '%s'", template_file);
595 hook_arg1 = "template";
599 * This final case does not modify the template message,
600 * it just sets the argument to the prepare-commit-msg hook.
605 fp = fopen(git_path(commit_editmsg), "w");
607 die_errno("could not open '%s'", git_path(commit_editmsg));
609 if (cleanup_mode != CLEANUP_NONE)
613 struct strbuf sob = STRBUF_INIT;
616 strbuf_addstr(&sob, sign_off_header);
617 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
618 getenv("GIT_COMMITTER_EMAIL")));
619 strbuf_addch(&sob, '\n');
620 for (i = sb.len - 1; i > 0 && sb.buf[i - 1] != '\n'; i--)
622 if (prefixcmp(sb.buf + i, sob.buf)) {
623 if (!i || !ends_rfc2822_footer(&sb))
624 strbuf_addch(&sb, '\n');
625 strbuf_addbuf(&sb, &sob);
627 strbuf_release(&sob);
630 if (fwrite(sb.buf, 1, sb.len, fp) < sb.len)
631 die_errno("could not write commit template");
635 determine_author_info();
637 /* This checks if committer ident is explicitly given */
638 git_committer_info(0);
639 if (use_editor && include_status) {
641 const char *committer_ident;
646 "# It looks like you may be committing a MERGE.\n"
647 "# If this is not correct, please remove the file\n"
651 git_path("MERGE_HEAD"));
655 "# Please enter the commit message for your changes.");
656 if (cleanup_mode == CLEANUP_ALL)
659 "# with '#' will be ignored, and an empty"
660 " message aborts the commit.\n");
661 else /* CLEANUP_SPACE, that is. */
664 "# with '#' will be kept; you may remove them"
665 " yourself if you want to.\n"
666 "# An empty message aborts the commit.\n");
667 if (only_include_assumed)
668 fprintf(fp, "# %s\n", only_include_assumed);
670 author_ident = xstrdup(fmt_name(author_name, author_email));
671 committer_ident = fmt_name(getenv("GIT_COMMITTER_NAME"),
672 getenv("GIT_COMMITTER_EMAIL"));
673 if (strcmp(author_ident, committer_ident))
677 ident_shown++ ? "" : "#\n",
681 if (!user_ident_sufficiently_given())
685 ident_shown++ ? "" : "#\n",
691 saved_color_setting = s->use_color;
693 commitable = run_status(fp, index_file, prefix, 1, s);
694 s->use_color = saved_color_setting;
696 unsigned char sha1[20];
697 const char *parent = "HEAD";
699 if (!active_nr && read_cache() < 0)
700 die("Cannot read index");
705 if (get_sha1(parent, sha1))
706 commitable = !!active_nr;
708 commitable = index_differs_from(parent, 0);
713 if (!commitable && !in_merge && !allow_empty &&
714 !(amend && is_a_merge(head_sha1))) {
715 run_status(stdout, index_file, prefix, 0, s);
717 fputs(empty_amend_advice, stderr);
722 * Re-read the index as pre-commit hook could have updated it,
723 * and write it out as a tree. We must do this before we invoke
724 * the editor and after we invoke run_status above.
727 read_cache_from(index_file);
728 if (!active_cache_tree)
729 active_cache_tree = cache_tree();
730 if (cache_tree_update(active_cache_tree,
731 active_cache, active_nr, 0, 0) < 0) {
732 error("Error building trees");
736 if (run_hook(index_file, "prepare-commit-msg",
737 git_path(commit_editmsg), hook_arg1, hook_arg2, NULL))
741 char index[PATH_MAX];
742 const char *env[2] = { NULL };
744 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
745 if (launch_editor(git_path(commit_editmsg), NULL, env)) {
747 "Please supply the message using either -m or -F option.\n");
753 run_hook(index_file, "commit-msg", git_path(commit_editmsg), NULL)) {
761 * Find out if the message in the strbuf contains only whitespace and
762 * Signed-off-by lines.
764 static int message_is_empty(struct strbuf *sb)
766 struct strbuf tmpl = STRBUF_INIT;
768 int eol, i, start = 0;
770 if (cleanup_mode == CLEANUP_NONE && sb->len)
773 /* See if the template is just a prefix of the message. */
774 if (template_file && strbuf_read_file(&tmpl, template_file, 0) > 0) {
775 stripspace(&tmpl, cleanup_mode == CLEANUP_ALL);
776 if (start + tmpl.len <= sb->len &&
777 memcmp(tmpl.buf, sb->buf + start, tmpl.len) == 0)
780 strbuf_release(&tmpl);
782 /* Check if the rest is just whitespace and Signed-of-by's. */
783 for (i = start; i < sb->len; i++) {
784 nl = memchr(sb->buf + i, '\n', sb->len - i);
790 if (strlen(sign_off_header) <= eol - i &&
791 !prefixcmp(sb->buf + i, sign_off_header)) {
796 if (!isspace(sb->buf[i++]))
803 static const char *find_author_by_nickname(const char *name)
805 struct rev_info revs;
806 struct commit *commit;
807 struct strbuf buf = STRBUF_INIT;
811 init_revisions(&revs, NULL);
812 strbuf_addf(&buf, "--author=%s", name);
817 setup_revisions(ac, av, &revs, NULL);
818 prepare_revision_walk(&revs);
819 commit = get_revision(&revs);
821 struct pretty_print_context ctx = {0};
822 ctx.date_mode = DATE_NORMAL;
823 strbuf_release(&buf);
824 format_commit_message(commit, "%an <%ae>", &buf, &ctx);
825 return strbuf_detach(&buf, NULL);
827 die("No existing author found with '%s'", name);
831 static void handle_untracked_files_arg(struct wt_status *s)
833 if (!untracked_files_arg)
834 ; /* default already initialized */
835 else if (!strcmp(untracked_files_arg, "no"))
836 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
837 else if (!strcmp(untracked_files_arg, "normal"))
838 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
839 else if (!strcmp(untracked_files_arg, "all"))
840 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
842 die("Invalid untracked files mode '%s'", untracked_files_arg);
845 static int parse_and_validate_options(int argc, const char *argv[],
846 const char * const usage[],
852 argc = parse_options(argc, argv, prefix, builtin_commit_options, usage,
855 if (force_author && !strchr(force_author, '>'))
856 force_author = find_author_by_nickname(force_author);
858 if (force_author && renew_authorship)
859 die("Using both --reset-author and --author does not make sense");
861 if (logfile || message.len || use_message)
866 setenv("GIT_EDITOR", ":", 1);
868 if (get_sha1("HEAD", head_sha1))
871 /* Sanity check options */
872 if (amend && initial_commit)
873 die("You have nothing to amend.");
874 if (amend && in_merge)
875 die("You are in the middle of a merge -- cannot amend.");
884 die("Only one of -c/-C/-F can be used.");
885 if (message.len && f > 0)
886 die("Option -m cannot be combined with -c/-C/-F.");
888 use_message = edit_message;
889 if (amend && !use_message)
890 use_message = "HEAD";
891 if (!use_message && renew_authorship)
892 die("--reset-author can be used only with -C, -c or --amend.");
894 unsigned char sha1[20];
895 static char utf8[] = "UTF-8";
898 struct commit *commit;
900 if (get_sha1(use_message, sha1))
901 die("could not lookup commit %s", use_message);
902 commit = lookup_commit_reference(sha1);
903 if (!commit || parse_commit(commit))
904 die("could not parse commit %s", use_message);
906 enc = strstr(commit->buffer, "\nencoding");
908 end = strchr(enc + 10, '\n');
909 enc = xstrndup(enc + 10, end - (enc + 10));
913 out_enc = git_commit_encoding ? git_commit_encoding : utf8;
915 if (strcmp(out_enc, enc))
917 reencode_string(commit->buffer, out_enc, enc);
920 * If we failed to reencode the buffer, just copy it
921 * byte for byte so the user can try to fix it up.
922 * This also handles the case where input and output
923 * encodings are identical.
925 if (use_message_buffer == NULL)
926 use_message_buffer = xstrdup(commit->buffer);
931 if (!!also + !!only + !!all + !!interactive > 1)
932 die("Only one of --include/--only/--all/--interactive can be used.");
933 if (argc == 0 && (also || (only && !amend)))
934 die("No paths with --include/--only does not make sense.");
935 if (argc == 0 && only && amend)
936 only_include_assumed = "Clever... amending the last one with dirty index.";
937 if (argc > 0 && !also && !only)
938 only_include_assumed = "Explicit paths specified without -i nor -o; assuming --only paths...";
939 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
940 cleanup_mode = use_editor ? CLEANUP_ALL : CLEANUP_SPACE;
941 else if (!strcmp(cleanup_arg, "verbatim"))
942 cleanup_mode = CLEANUP_NONE;
943 else if (!strcmp(cleanup_arg, "whitespace"))
944 cleanup_mode = CLEANUP_SPACE;
945 else if (!strcmp(cleanup_arg, "strip"))
946 cleanup_mode = CLEANUP_ALL;
948 die("Invalid cleanup mode %s", cleanup_arg);
950 handle_untracked_files_arg(s);
953 die("Paths with -a does not make sense.");
954 else if (interactive && argc > 0)
955 die("Paths with --interactive does not make sense.");
957 if (null_termination && status_format == STATUS_FORMAT_LONG)
958 status_format = STATUS_FORMAT_PORCELAIN;
959 if (status_format != STATUS_FORMAT_LONG)
965 static int dry_run_commit(int argc, const char **argv, const char *prefix,
969 const char *index_file;
971 index_file = prepare_index(argc, argv, prefix, 1);
972 commitable = run_status(stdout, index_file, prefix, 0, s);
973 rollback_index_files();
975 return commitable ? 0 : 1;
978 static int parse_status_slot(const char *var, int offset)
980 if (!strcasecmp(var+offset, "header"))
981 return WT_STATUS_HEADER;
982 if (!strcasecmp(var+offset, "updated")
983 || !strcasecmp(var+offset, "added"))
984 return WT_STATUS_UPDATED;
985 if (!strcasecmp(var+offset, "changed"))
986 return WT_STATUS_CHANGED;
987 if (!strcasecmp(var+offset, "untracked"))
988 return WT_STATUS_UNTRACKED;
989 if (!strcasecmp(var+offset, "nobranch"))
990 return WT_STATUS_NOBRANCH;
991 if (!strcasecmp(var+offset, "unmerged"))
992 return WT_STATUS_UNMERGED;
996 static int git_status_config(const char *k, const char *v, void *cb)
998 struct wt_status *s = cb;
1000 if (!strcmp(k, "status.submodulesummary")) {
1002 s->submodule_summary = git_config_bool_or_int(k, v, &is_bool);
1003 if (is_bool && s->submodule_summary)
1004 s->submodule_summary = -1;
1007 if (!strcmp(k, "status.color") || !strcmp(k, "color.status")) {
1008 s->use_color = git_config_colorbool(k, v, -1);
1011 if (!prefixcmp(k, "status.color.") || !prefixcmp(k, "color.status.")) {
1012 int slot = parse_status_slot(k, 13);
1016 return config_error_nonbool(k);
1017 color_parse(v, k, s->color_palette[slot]);
1020 if (!strcmp(k, "status.relativepaths")) {
1021 s->relative_paths = git_config_bool(k, v);
1024 if (!strcmp(k, "status.showuntrackedfiles")) {
1026 return config_error_nonbool(k);
1027 else if (!strcmp(v, "no"))
1028 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
1029 else if (!strcmp(v, "normal"))
1030 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
1031 else if (!strcmp(v, "all"))
1032 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
1034 return error("Invalid untracked files mode '%s'", v);
1037 return git_diff_ui_config(k, v, NULL);
1040 int cmd_status(int argc, const char **argv, const char *prefix)
1044 unsigned char sha1[20];
1045 static struct option builtin_status_options[] = {
1046 OPT__VERBOSE(&verbose),
1047 OPT_SET_INT('s', "short", &status_format,
1048 "show status concisely", STATUS_FORMAT_SHORT),
1049 OPT_BOOLEAN('b', "branch", &status_show_branch,
1050 "show branch information"),
1051 OPT_SET_INT(0, "porcelain", &status_format,
1052 "show porcelain output format",
1053 STATUS_FORMAT_PORCELAIN),
1054 OPT_BOOLEAN('z', "null", &null_termination,
1055 "terminate entries with NUL"),
1056 { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg,
1058 "show untracked files, optional modes: all, normal, no. (Default: all)",
1059 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1060 OPT_BOOLEAN(0, "ignored", &show_ignored_in_status,
1061 "show ignored files"),
1062 { OPTION_STRING, 0, "ignore-submodules", &ignore_submodule_arg, "when",
1063 "ignore changes to submodules, optional when: all, dirty, untracked. (Default: all)",
1064 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1068 if (null_termination && status_format == STATUS_FORMAT_LONG)
1069 status_format = STATUS_FORMAT_PORCELAIN;
1071 wt_status_prepare(&s);
1072 git_config(git_status_config, &s);
1073 in_merge = file_exists(git_path("MERGE_HEAD"));
1074 argc = parse_options(argc, argv, prefix,
1075 builtin_status_options,
1076 builtin_status_usage, 0);
1077 handle_untracked_files_arg(&s);
1078 if (show_ignored_in_status)
1079 s.show_ignored_files = 1;
1081 s.pathspec = get_pathspec(prefix, argv);
1083 read_cache_preload(s.pathspec);
1084 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, s.pathspec, NULL, NULL);
1086 fd = hold_locked_index(&index_lock, 0);
1088 if (!write_cache(fd, active_cache, active_nr))
1089 commit_locked_index(&index_lock);
1090 rollback_lock_file(&index_lock);
1093 s.is_initial = get_sha1(s.reference, sha1) ? 1 : 0;
1094 s.in_merge = in_merge;
1095 s.ignore_submodule_arg = ignore_submodule_arg;
1096 wt_status_collect(&s);
1098 if (s.relative_paths)
1100 if (s.use_color == -1)
1101 s.use_color = git_use_color_default;
1102 if (diff_use_color_default == -1)
1103 diff_use_color_default = git_use_color_default;
1105 switch (status_format) {
1106 case STATUS_FORMAT_SHORT:
1107 wt_shortstatus_print(&s, null_termination, status_show_branch);
1109 case STATUS_FORMAT_PORCELAIN:
1110 wt_porcelain_print(&s, null_termination);
1112 case STATUS_FORMAT_LONG:
1113 s.verbose = verbose;
1114 s.ignore_submodule_arg = ignore_submodule_arg;
1115 wt_status_print(&s);
1121 static void print_summary(const char *prefix, const unsigned char *sha1)
1123 struct rev_info rev;
1124 struct commit *commit;
1125 struct strbuf format = STRBUF_INIT;
1126 unsigned char junk_sha1[20];
1127 const char *head = resolve_ref("HEAD", junk_sha1, 0, NULL);
1128 struct pretty_print_context pctx = {0};
1129 struct strbuf author_ident = STRBUF_INIT;
1130 struct strbuf committer_ident = STRBUF_INIT;
1132 commit = lookup_commit(sha1);
1134 die("couldn't look up newly created commit");
1135 if (!commit || parse_commit(commit))
1136 die("could not parse newly created commit");
1138 strbuf_addstr(&format, "format:%h] %s");
1140 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1141 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1142 if (strbuf_cmp(&author_ident, &committer_ident)) {
1143 strbuf_addstr(&format, "\n Author: ");
1144 strbuf_addbuf_percentquote(&format, &author_ident);
1146 if (!user_ident_sufficiently_given()) {
1147 strbuf_addstr(&format, "\n Committer: ");
1148 strbuf_addbuf_percentquote(&format, &committer_ident);
1149 if (advice_implicit_identity) {
1150 strbuf_addch(&format, '\n');
1151 strbuf_addstr(&format, implicit_ident_advice);
1154 strbuf_release(&author_ident);
1155 strbuf_release(&committer_ident);
1157 init_revisions(&rev, prefix);
1158 setup_revisions(0, NULL, &rev, NULL);
1162 rev.diffopt.output_format =
1163 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1165 rev.verbose_header = 1;
1166 rev.show_root_diff = 1;
1167 get_commit_format(format.buf, &rev);
1168 rev.always_show_header = 0;
1169 rev.diffopt.detect_rename = 1;
1170 rev.diffopt.rename_limit = 100;
1171 rev.diffopt.break_opt = 0;
1172 diff_setup_done(&rev.diffopt);
1175 !prefixcmp(head, "refs/heads/") ?
1177 !strcmp(head, "HEAD") ?
1180 initial_commit ? " (root-commit)" : "");
1182 if (!log_tree_commit(&rev, commit)) {
1183 rev.always_show_header = 1;
1184 rev.use_terminator = 1;
1185 log_tree_commit(&rev, commit);
1188 strbuf_release(&format);
1191 static int git_commit_config(const char *k, const char *v, void *cb)
1193 struct wt_status *s = cb;
1195 if (!strcmp(k, "commit.template"))
1196 return git_config_pathname(&template_file, k, v);
1197 if (!strcmp(k, "commit.status")) {
1198 include_status = git_config_bool(k, v);
1202 return git_status_config(k, v, s);
1205 static const char post_rewrite_hook[] = "hooks/post-rewrite";
1207 static int run_rewrite_hook(const unsigned char *oldsha1,
1208 const unsigned char *newsha1)
1210 /* oldsha1 SP newsha1 LF NUL */
1211 static char buf[2*40 + 3];
1212 struct child_process proc;
1213 const char *argv[3];
1217 if (access(git_path(post_rewrite_hook), X_OK) < 0)
1220 argv[0] = git_path(post_rewrite_hook);
1224 memset(&proc, 0, sizeof(proc));
1227 proc.stdout_to_stderr = 1;
1229 code = start_command(&proc);
1232 n = snprintf(buf, sizeof(buf), "%s %s\n",
1233 sha1_to_hex(oldsha1), sha1_to_hex(newsha1));
1234 write_in_full(proc.in, buf, n);
1236 return finish_command(&proc);
1239 int cmd_commit(int argc, const char **argv, const char *prefix)
1241 struct strbuf sb = STRBUF_INIT;
1242 const char *index_file, *reflog_msg;
1244 unsigned char commit_sha1[20];
1245 struct ref_lock *ref_lock;
1246 struct commit_list *parents = NULL, **pptr = &parents;
1247 struct stat statbuf;
1248 int allow_fast_forward = 1;
1251 wt_status_prepare(&s);
1252 git_config(git_commit_config, &s);
1253 in_merge = file_exists(git_path("MERGE_HEAD"));
1254 s.in_merge = in_merge;
1256 if (s.use_color == -1)
1257 s.use_color = git_use_color_default;
1258 argc = parse_and_validate_options(argc, argv, builtin_commit_usage,
1261 if (diff_use_color_default == -1)
1262 diff_use_color_default = git_use_color_default;
1263 return dry_run_commit(argc, argv, prefix, &s);
1265 index_file = prepare_index(argc, argv, prefix, 0);
1267 /* Set up everything for writing the commit object. This includes
1268 running hooks, writing the trees, and interacting with the user. */
1269 if (!prepare_to_commit(index_file, prefix, &s)) {
1270 rollback_index_files();
1274 /* Determine parents */
1275 reflog_msg = getenv("GIT_REFLOG_ACTION");
1276 if (initial_commit) {
1278 reflog_msg = "commit (initial)";
1280 struct commit_list *c;
1281 struct commit *commit;
1284 reflog_msg = "commit (amend)";
1285 commit = lookup_commit(head_sha1);
1286 if (!commit || parse_commit(commit))
1287 die("could not parse HEAD commit");
1289 for (c = commit->parents; c; c = c->next)
1290 pptr = &commit_list_insert(c->item, pptr)->next;
1291 } else if (in_merge) {
1292 struct strbuf m = STRBUF_INIT;
1296 reflog_msg = "commit (merge)";
1297 pptr = &commit_list_insert(lookup_commit(head_sha1), pptr)->next;
1298 fp = fopen(git_path("MERGE_HEAD"), "r");
1300 die_errno("could not open '%s' for reading",
1301 git_path("MERGE_HEAD"));
1302 while (strbuf_getline(&m, fp, '\n') != EOF) {
1303 unsigned char sha1[20];
1304 if (get_sha1_hex(m.buf, sha1) < 0)
1305 die("Corrupt MERGE_HEAD file (%s)", m.buf);
1306 pptr = &commit_list_insert(lookup_commit(sha1), pptr)->next;
1310 if (!stat(git_path("MERGE_MODE"), &statbuf)) {
1311 if (strbuf_read_file(&sb, git_path("MERGE_MODE"), 0) < 0)
1312 die_errno("could not read MERGE_MODE");
1313 if (!strcmp(sb.buf, "no-ff"))
1314 allow_fast_forward = 0;
1316 if (allow_fast_forward)
1317 parents = reduce_heads(parents);
1320 reflog_msg = "commit";
1321 pptr = &commit_list_insert(lookup_commit(head_sha1), pptr)->next;
1324 /* Finally, get the commit message */
1326 if (strbuf_read_file(&sb, git_path(commit_editmsg), 0) < 0) {
1327 int saved_errno = errno;
1328 rollback_index_files();
1329 die("could not read commit message: %s", strerror(saved_errno));
1332 /* Truncate the message just before the diff, if any. */
1334 p = strstr(sb.buf, "\ndiff --git ");
1336 strbuf_setlen(&sb, p - sb.buf + 1);
1339 if (cleanup_mode != CLEANUP_NONE)
1340 stripspace(&sb, cleanup_mode == CLEANUP_ALL);
1341 if (message_is_empty(&sb) && !allow_empty_message) {
1342 rollback_index_files();
1343 fprintf(stderr, "Aborting commit due to empty commit message.\n");
1347 if (commit_tree(sb.buf, active_cache_tree->sha1, parents, commit_sha1,
1348 fmt_ident(author_name, author_email, author_date,
1349 IDENT_ERROR_ON_NO_NAME))) {
1350 rollback_index_files();
1351 die("failed to write commit object");
1354 ref_lock = lock_any_ref_for_update("HEAD",
1355 initial_commit ? NULL : head_sha1,
1358 nl = strchr(sb.buf, '\n');
1360 strbuf_setlen(&sb, nl + 1 - sb.buf);
1362 strbuf_addch(&sb, '\n');
1363 strbuf_insert(&sb, 0, reflog_msg, strlen(reflog_msg));
1364 strbuf_insert(&sb, strlen(reflog_msg), ": ", 2);
1367 rollback_index_files();
1368 die("cannot lock HEAD ref");
1370 if (write_ref_sha1(ref_lock, commit_sha1, sb.buf) < 0) {
1371 rollback_index_files();
1372 die("cannot update HEAD ref");
1375 unlink(git_path("MERGE_HEAD"));
1376 unlink(git_path("MERGE_MSG"));
1377 unlink(git_path("MERGE_MODE"));
1378 unlink(git_path("SQUASH_MSG"));
1380 if (commit_index_files())
1381 die ("Repository has been updated, but unable to write\n"
1382 "new_index file. Check that disk is not full or quota is\n"
1383 "not exceeded, and then \"git reset HEAD\" to recover.");
1386 run_hook(get_index_file(), "post-commit", NULL);
1387 if (amend && !no_post_rewrite) {
1388 struct notes_rewrite_cfg *cfg;
1389 cfg = init_copy_notes_for_rewrite("amend");
1391 copy_note_for_rewrite(cfg, head_sha1, commit_sha1);
1392 finish_copy_notes_for_rewrite(cfg);
1394 run_rewrite_hook(head_sha1, commit_sha1);
1397 print_summary(prefix, commit_sha1);