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"
28 #include "submodule.h"
30 static const char * const builtin_commit_usage
[] = {
31 "git commit [options] [--] <filepattern>...",
35 static const char * const builtin_status_usage
[] = {
36 "git status [options] [--] <filepattern>...",
40 static const char implicit_ident_advice
[] =
41 "Your name and email address were configured automatically based\n"
42 "on your username and hostname. Please check that they are accurate.\n"
43 "You can suppress this message by setting them explicitly:\n"
45 " git config --global user.name \"Your Name\"\n"
46 " git config --global user.email you@example.com\n"
48 "After doing this, you may fix the identity used for this commit with:\n"
50 " git commit --amend --reset-author\n";
52 static const char empty_amend_advice
[] =
53 "You asked to amend the most recent commit, but doing so would make\n"
54 "it empty. You can repeat your command with --allow-empty, or you can\n"
55 "remove the commit entirely with \"git reset HEAD^\".\n";
57 static const char empty_cherry_pick_advice
[] =
58 "The previous cherry-pick is now empty, possibly due to conflict resolution.\n"
59 "If you wish to commit it anyway, use:\n"
61 " git commit --allow-empty\n"
63 "Otherwise, please use 'git reset'\n";
65 static unsigned char head_sha1
[20];
67 static const char *use_message_buffer
;
68 static const char commit_editmsg
[] = "COMMIT_EDITMSG";
69 static struct lock_file index_lock
; /* real index */
70 static struct lock_file false_lock
; /* used only for partial commits */
77 static const char *logfile
, *force_author
;
78 static const char *template_file
;
80 * The _message variables are commit names from which to take
81 * the commit message and/or authorship.
83 static const char *author_message
, *author_message_buffer
;
84 static char *edit_message
, *use_message
;
85 static char *fixup_message
, *squash_message
;
86 static int all
, edit_flag
, also
, interactive
, only
, amend
, signoff
;
87 static int quiet
, verbose
, no_verify
, allow_empty
, dry_run
, renew_authorship
;
88 static int no_post_rewrite
, allow_empty_message
;
89 static char *untracked_files_arg
, *force_date
, *ignore_submodule_arg
;
91 * The default commit message cleanup mode will remove the lines
92 * beginning with # (shell comments) and leading and trailing
93 * whitespaces (empty lines or containing only whitespaces)
94 * if editor is used, and only the whitespaces if the message
95 * is specified explicitly.
102 static char *cleanup_arg
;
104 static enum commit_whence whence
;
105 static int use_editor
= 1, initial_commit
, include_status
= 1;
106 static int show_ignored_in_status
;
107 static const char *only_include_assumed
;
108 static struct strbuf message
;
110 static int null_termination
;
114 STATUS_FORMAT_PORCELAIN
115 } status_format
= STATUS_FORMAT_LONG
;
116 static int status_show_branch
;
118 static int opt_parse_m(const struct option
*opt
, const char *arg
, int unset
)
120 struct strbuf
*buf
= opt
->value
;
122 strbuf_setlen(buf
, 0);
124 strbuf_addstr(buf
, arg
);
125 strbuf_addstr(buf
, "\n\n");
130 static struct option builtin_commit_options
[] = {
131 OPT__QUIET(&quiet
, "suppress summary after successful commit"),
132 OPT__VERBOSE(&verbose
, "show diff in commit message template"),
134 OPT_GROUP("Commit message options"),
135 OPT_FILENAME('F', "file", &logfile
, "read message from file"),
136 OPT_STRING(0, "author", &force_author
, "author", "override author for commit"),
137 OPT_STRING(0, "date", &force_date
, "date", "override date for commit"),
138 OPT_CALLBACK('m', "message", &message
, "message", "commit message", opt_parse_m
),
139 OPT_STRING('c', "reedit-message", &edit_message
, "commit", "reuse and edit message from specified commit"),
140 OPT_STRING('C', "reuse-message", &use_message
, "commit", "reuse message from specified commit"),
141 OPT_STRING(0, "fixup", &fixup_message
, "commit", "use autosquash formatted message to fixup specified commit"),
142 OPT_STRING(0, "squash", &squash_message
, "commit", "use autosquash formatted message to squash specified commit"),
143 OPT_BOOLEAN(0, "reset-author", &renew_authorship
, "the commit is authored by me now (used with -C-c/--amend)"),
144 OPT_BOOLEAN('s', "signoff", &signoff
, "add Signed-off-by:"),
145 OPT_FILENAME('t', "template", &template_file
, "use specified template file"),
146 OPT_BOOLEAN('e', "edit", &edit_flag
, "force edit of commit"),
147 OPT_STRING(0, "cleanup", &cleanup_arg
, "default", "how to strip spaces and #comments from message"),
148 OPT_BOOLEAN(0, "status", &include_status
, "include status in commit message template"),
149 /* end commit message options */
151 OPT_GROUP("Commit contents options"),
152 OPT_BOOLEAN('a', "all", &all
, "commit all changed files"),
153 OPT_BOOLEAN('i', "include", &also
, "add specified files to index for commit"),
154 OPT_BOOLEAN(0, "interactive", &interactive
, "interactively add files"),
155 OPT_BOOLEAN('o', "only", &only
, "commit only specified files"),
156 OPT_BOOLEAN('n', "no-verify", &no_verify
, "bypass pre-commit hook"),
157 OPT_BOOLEAN(0, "dry-run", &dry_run
, "show what would be committed"),
158 OPT_SET_INT(0, "short", &status_format
, "show status concisely",
159 STATUS_FORMAT_SHORT
),
160 OPT_BOOLEAN(0, "branch", &status_show_branch
, "show branch information"),
161 OPT_SET_INT(0, "porcelain", &status_format
,
162 "machine-readable output", STATUS_FORMAT_PORCELAIN
),
163 OPT_BOOLEAN('z', "null", &null_termination
,
164 "terminate entries with NUL"),
165 OPT_BOOLEAN(0, "amend", &amend
, "amend previous commit"),
166 OPT_BOOLEAN(0, "no-post-rewrite", &no_post_rewrite
, "bypass post-rewrite hook"),
167 { 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" },
168 /* end commit contents options */
170 { OPTION_BOOLEAN
, 0, "allow-empty", &allow_empty
, NULL
,
171 "ok to record an empty change",
172 PARSE_OPT_NOARG
| PARSE_OPT_HIDDEN
},
173 { OPTION_BOOLEAN
, 0, "allow-empty-message", &allow_empty_message
, NULL
,
174 "ok to record a change with an empty message",
175 PARSE_OPT_NOARG
| PARSE_OPT_HIDDEN
},
180 static void determine_whence(struct wt_status
*s
)
182 if (file_exists(git_path("MERGE_HEAD")))
184 else if (file_exists(git_path("CHERRY_PICK_HEAD")))
185 whence
= FROM_CHERRY_PICK
;
187 whence
= FROM_COMMIT
;
192 static const char *whence_s(void)
202 case FROM_CHERRY_PICK
:
210 static void rollback_index_files(void)
212 switch (commit_style
) {
214 break; /* nothing to do */
216 rollback_lock_file(&index_lock
);
219 rollback_lock_file(&index_lock
);
220 rollback_lock_file(&false_lock
);
225 static int commit_index_files(void)
229 switch (commit_style
) {
231 break; /* nothing to do */
233 err
= commit_lock_file(&index_lock
);
236 err
= commit_lock_file(&index_lock
);
237 rollback_lock_file(&false_lock
);
245 * Take a union of paths in the index and the named tree (typically, "HEAD"),
246 * and return the paths that match the given pattern in list.
248 static int list_paths(struct string_list
*list
, const char *with_tree
,
249 const char *prefix
, const char **pattern
)
254 for (i
= 0; pattern
[i
]; i
++)
259 overlay_tree_on_cache(with_tree
, prefix
);
261 for (i
= 0; i
< active_nr
; i
++) {
262 struct cache_entry
*ce
= active_cache
[i
];
263 struct string_list_item
*item
;
265 if (ce
->ce_flags
& CE_UPDATE
)
267 if (!match_pathspec(pattern
, ce
->name
, ce_namelen(ce
), 0, m
))
269 item
= string_list_insert(list
, ce
->name
);
270 if (ce_skip_worktree(ce
))
271 item
->util
= item
; /* better a valid pointer than a fake one */
274 return report_path_error(m
, pattern
, prefix
? strlen(prefix
) : 0);
277 static void add_remove_files(struct string_list
*list
)
280 for (i
= 0; i
< list
->nr
; i
++) {
282 struct string_list_item
*p
= &(list
->items
[i
]);
284 /* p->util is skip-worktree */
288 if (!lstat(p
->string
, &st
)) {
289 if (add_to_cache(p
->string
, &st
, 0))
290 die("updating files failed");
292 remove_file_from_cache(p
->string
);
296 static void create_base_index(void)
299 struct unpack_trees_options opts
;
302 if (initial_commit
) {
307 memset(&opts
, 0, sizeof(opts
));
311 opts
.src_index
= &the_index
;
312 opts
.dst_index
= &the_index
;
314 opts
.fn
= oneway_merge
;
315 tree
= parse_tree_indirect(head_sha1
);
317 die("failed to unpack HEAD tree object");
319 init_tree_desc(&t
, tree
->buffer
, tree
->size
);
320 if (unpack_trees(1, &t
, &opts
))
321 exit(128); /* We've already reported the error, finish dying */
324 static void refresh_cache_or_die(int refresh_flags
)
327 * refresh_flags contains REFRESH_QUIET, so the only errors
328 * are for unmerged entries.
330 if (refresh_cache(refresh_flags
| REFRESH_IN_PORCELAIN
))
331 die_resolve_conflict("commit");
334 static char *prepare_index(int argc
, const char **argv
, const char *prefix
, int is_status
)
337 struct string_list partial
;
338 const char **pathspec
= NULL
;
339 int refresh_flags
= REFRESH_QUIET
;
342 refresh_flags
|= REFRESH_UNMERGED
;
344 if (interactive_add(argc
, argv
, prefix
) != 0)
345 die("interactive add failed");
346 if (read_cache_preload(NULL
) < 0)
347 die("index file corrupt");
348 commit_style
= COMMIT_AS_IS
;
349 return get_index_file();
353 pathspec
= get_pathspec(prefix
, argv
);
355 if (read_cache_preload(pathspec
) < 0)
356 die("index file corrupt");
359 * Non partial, non as-is commit.
361 * (1) get the real index;
362 * (2) update the_index as necessary;
363 * (3) write the_index out to the real index (still locked);
364 * (4) return the name of the locked index file.
366 * The caller should run hooks on the locked real index, and
367 * (A) if all goes well, commit the real index;
368 * (B) on failure, rollback the real index.
370 if (all
|| (also
&& pathspec
&& *pathspec
)) {
371 fd
= hold_locked_index(&index_lock
, 1);
372 add_files_to_cache(also
? prefix
: NULL
, pathspec
, 0);
373 refresh_cache_or_die(refresh_flags
);
374 if (write_cache(fd
, active_cache
, active_nr
) ||
375 close_lock_file(&index_lock
))
376 die("unable to write new_index file");
377 commit_style
= COMMIT_NORMAL
;
378 return index_lock
.filename
;
384 * (1) return the name of the real index file.
386 * The caller should run hooks on the real index,
387 * and create commit from the_index.
388 * We still need to refresh the index here.
390 if (!pathspec
|| !*pathspec
) {
391 fd
= hold_locked_index(&index_lock
, 1);
392 refresh_cache_or_die(refresh_flags
);
393 if (active_cache_changed
) {
394 if (write_cache(fd
, active_cache
, active_nr
) ||
395 commit_locked_index(&index_lock
))
396 die("unable to write new_index file");
398 rollback_lock_file(&index_lock
);
400 commit_style
= COMMIT_AS_IS
;
401 return get_index_file();
407 * (0) find the set of affected paths;
408 * (1) get lock on the real index file;
409 * (2) update the_index with the given paths;
410 * (3) write the_index out to the real index (still locked);
411 * (4) get lock on the false index file;
412 * (5) reset the_index from HEAD;
413 * (6) update the_index the same way as (2);
414 * (7) write the_index out to the false index file;
415 * (8) return the name of the false index file (still locked);
417 * The caller should run hooks on the locked false index, and
418 * create commit from it. Then
419 * (A) if all goes well, commit the real index;
420 * (B) on failure, rollback the real index;
421 * In either case, rollback the false index.
423 commit_style
= COMMIT_PARTIAL
;
425 if (whence
!= FROM_COMMIT
)
426 die("cannot do a partial commit during a %s.", whence_s());
428 memset(&partial
, 0, sizeof(partial
));
429 partial
.strdup_strings
= 1;
430 if (list_paths(&partial
, initial_commit
? NULL
: "HEAD", prefix
, pathspec
))
434 if (read_cache() < 0)
435 die("cannot read the index");
437 fd
= hold_locked_index(&index_lock
, 1);
438 add_remove_files(&partial
);
439 refresh_cache(REFRESH_QUIET
);
440 if (write_cache(fd
, active_cache
, active_nr
) ||
441 close_lock_file(&index_lock
))
442 die("unable to write new_index file");
444 fd
= hold_lock_file_for_update(&false_lock
,
445 git_path("next-index-%"PRIuMAX
,
446 (uintmax_t) getpid()),
450 add_remove_files(&partial
);
451 refresh_cache(REFRESH_QUIET
);
453 if (write_cache(fd
, active_cache
, active_nr
) ||
454 close_lock_file(&false_lock
))
455 die("unable to write temporary index file");
458 read_cache_from(false_lock
.filename
);
460 return false_lock
.filename
;
463 static int run_status(FILE *fp
, const char *index_file
, const char *prefix
, int nowarn
,
466 unsigned char sha1
[20];
468 if (s
->relative_paths
)
473 s
->reference
= "HEAD^1";
475 s
->verbose
= verbose
;
476 s
->index_file
= index_file
;
479 s
->is_initial
= get_sha1(s
->reference
, sha1
) ? 1 : 0;
481 wt_status_collect(s
);
483 switch (status_format
) {
484 case STATUS_FORMAT_SHORT
:
485 wt_shortstatus_print(s
, null_termination
, status_show_branch
);
487 case STATUS_FORMAT_PORCELAIN
:
488 wt_porcelain_print(s
, null_termination
);
490 case STATUS_FORMAT_LONG
:
495 return s
->commitable
;
498 static int is_a_merge(const unsigned char *sha1
)
500 struct commit
*commit
= lookup_commit(sha1
);
501 if (!commit
|| parse_commit(commit
))
502 die("could not parse HEAD commit");
503 return !!(commit
->parents
&& commit
->parents
->next
);
506 static const char sign_off_header
[] = "Signed-off-by: ";
508 static void determine_author_info(struct strbuf
*author_ident
)
510 char *name
, *email
, *date
;
512 name
= getenv("GIT_AUTHOR_NAME");
513 email
= getenv("GIT_AUTHOR_EMAIL");
514 date
= getenv("GIT_AUTHOR_DATE");
516 if (author_message
) {
517 const char *a
, *lb
, *rb
, *eol
;
519 a
= strstr(author_message_buffer
, "\nauthor ");
521 die("invalid commit: %s", author_message
);
523 lb
= strchrnul(a
+ strlen("\nauthor "), '<');
524 rb
= strchrnul(lb
, '>');
525 eol
= strchrnul(rb
, '\n');
526 if (!*lb
|| !*rb
|| !*eol
)
527 die("invalid commit: %s", author_message
);
529 if (lb
== a
+ strlen("\nauthor "))
530 /* \nauthor <foo@example.com> */
531 name
= xcalloc(1, 1);
533 name
= xmemdupz(a
+ strlen("\nauthor "),
535 (a
+ strlen("\nauthor "))));
536 email
= xmemdupz(lb
+ strlen("<"), rb
- (lb
+ strlen("<")));
537 date
= xmemdupz(rb
+ strlen("> "), eol
- (rb
+ strlen("> ")));
541 const char *lb
= strstr(force_author
, " <");
542 const char *rb
= strchr(force_author
, '>');
545 die("malformed --author parameter");
546 name
= xstrndup(force_author
, lb
- force_author
);
547 email
= xstrndup(lb
+ 2, rb
- (lb
+ 2));
552 strbuf_addstr(author_ident
, fmt_ident(name
, email
, date
,
553 IDENT_ERROR_ON_NO_NAME
));
556 static int ends_rfc2822_footer(struct strbuf
*sb
)
563 const char *buf
= sb
->buf
;
565 for (i
= len
- 1; i
> 0; i
--) {
566 if (hit
&& buf
[i
] == '\n')
568 hit
= (buf
[i
] == '\n');
571 while (i
< len
- 1 && buf
[i
] == '\n')
574 for (; i
< len
; i
= k
) {
575 for (k
= i
; k
< len
&& buf
[k
] != '\n'; k
++)
579 if ((buf
[k
] == ' ' || buf
[k
] == '\t') && !first
)
584 for (j
= 0; i
+ j
< len
; j
++) {
597 static char *cut_ident_timestamp_part(char *string
)
599 char *ket
= strrchr(string
, '>');
600 if (!ket
|| ket
[1] != ' ')
601 die("Malformed ident string: '%s'", string
);
606 static int prepare_to_commit(const char *index_file
, const char *prefix
,
608 struct strbuf
*author_ident
)
611 struct strbuf committer_ident
= STRBUF_INIT
;
612 int commitable
, saved_color_setting
;
613 struct strbuf sb
= STRBUF_INIT
;
615 const char *hook_arg1
= NULL
;
616 const char *hook_arg2
= NULL
;
619 if (!no_verify
&& run_hook(index_file
, "pre-commit", NULL
))
622 if (squash_message
) {
624 * Insert the proper subject line before other commit
625 * message options add their content.
627 if (use_message
&& !strcmp(use_message
, squash_message
))
628 strbuf_addstr(&sb
, "squash! ");
630 struct pretty_print_context ctx
= {0};
632 c
= lookup_commit_reference_by_name(squash_message
);
634 die("could not lookup commit %s", squash_message
);
635 ctx
.output_encoding
= get_commit_output_encoding();
636 format_commit_message(c
, "squash! %s\n\n", &sb
,
642 strbuf_addbuf(&sb
, &message
);
643 hook_arg1
= "message";
644 } else if (logfile
&& !strcmp(logfile
, "-")) {
646 fprintf(stderr
, "(reading log message from standard input)\n");
647 if (strbuf_read(&sb
, 0, 0) < 0)
648 die_errno("could not read log from standard input");
649 hook_arg1
= "message";
650 } else if (logfile
) {
651 if (strbuf_read_file(&sb
, logfile
, 0) < 0)
652 die_errno("could not read log file '%s'",
654 hook_arg1
= "message";
655 } else if (use_message
) {
656 buffer
= strstr(use_message_buffer
, "\n\n");
657 if (!buffer
|| buffer
[2] == '\0')
658 die("commit has empty message");
659 strbuf_add(&sb
, buffer
+ 2, strlen(buffer
+ 2));
660 hook_arg1
= "commit";
661 hook_arg2
= use_message
;
662 } else if (fixup_message
) {
663 struct pretty_print_context ctx
= {0};
664 struct commit
*commit
;
665 commit
= lookup_commit_reference_by_name(fixup_message
);
667 die("could not lookup commit %s", fixup_message
);
668 ctx
.output_encoding
= get_commit_output_encoding();
669 format_commit_message(commit
, "fixup! %s\n\n",
671 hook_arg1
= "message";
672 } else if (!stat(git_path("MERGE_MSG"), &statbuf
)) {
673 if (strbuf_read_file(&sb
, git_path("MERGE_MSG"), 0) < 0)
674 die_errno("could not read MERGE_MSG");
676 } else if (!stat(git_path("SQUASH_MSG"), &statbuf
)) {
677 if (strbuf_read_file(&sb
, git_path("SQUASH_MSG"), 0) < 0)
678 die_errno("could not read SQUASH_MSG");
679 hook_arg1
= "squash";
680 } else if (template_file
) {
681 if (strbuf_read_file(&sb
, template_file
, 0) < 0)
682 die_errno("could not read '%s'", template_file
);
683 hook_arg1
= "template";
687 * The remaining cases don't modify the template message, but
688 * just set the argument(s) to the prepare-commit-msg hook.
690 else if (whence
== FROM_MERGE
)
692 else if (whence
== FROM_CHERRY_PICK
) {
693 hook_arg1
= "commit";
694 hook_arg2
= "CHERRY_PICK_HEAD";
697 if (squash_message
) {
699 * If squash_commit was used for the commit subject,
700 * then we're possibly hijacking other commit log options.
701 * Reset the hook args to tell the real story.
703 hook_arg1
= "message";
707 s
->fp
= fopen(git_path(commit_editmsg
), "w");
709 die_errno("could not open '%s'", git_path(commit_editmsg
));
711 if (cleanup_mode
!= CLEANUP_NONE
)
715 struct strbuf sob
= STRBUF_INIT
;
718 strbuf_addstr(&sob
, sign_off_header
);
719 strbuf_addstr(&sob
, fmt_name(getenv("GIT_COMMITTER_NAME"),
720 getenv("GIT_COMMITTER_EMAIL")));
721 strbuf_addch(&sob
, '\n');
722 for (i
= sb
.len
- 1; i
> 0 && sb
.buf
[i
- 1] != '\n'; i
--)
724 if (prefixcmp(sb
.buf
+ i
, sob
.buf
)) {
725 if (!i
|| !ends_rfc2822_footer(&sb
))
726 strbuf_addch(&sb
, '\n');
727 strbuf_addbuf(&sb
, &sob
);
729 strbuf_release(&sob
);
732 if (fwrite(sb
.buf
, 1, sb
.len
, s
->fp
) < sb
.len
)
733 die_errno("could not write commit template");
737 /* This checks and barfs if author is badly specified */
738 determine_author_info(author_ident
);
740 /* This checks if committer ident is explicitly given */
741 strbuf_addstr(&committer_ident
, git_committer_info(0));
742 if (use_editor
&& include_status
) {
743 char *ai_tmp
, *ci_tmp
;
744 if (whence
!= FROM_COMMIT
)
745 status_printf_ln(s
, GIT_COLOR_NORMAL
,
747 "It looks like you may be committing a %s.\n"
748 "If this is not correct, please remove the file\n"
753 git_path(whence
== FROM_MERGE
755 : "CHERRY_PICK_HEAD"));
757 fprintf(s
->fp
, "\n");
758 status_printf(s
, GIT_COLOR_NORMAL
,
759 "Please enter the commit message for your changes.");
760 if (cleanup_mode
== CLEANUP_ALL
)
761 status_printf_more(s
, GIT_COLOR_NORMAL
,
763 "with '#' will be ignored, and an empty"
764 " message aborts the commit.\n");
765 else /* CLEANUP_SPACE, that is. */
766 status_printf_more(s
, GIT_COLOR_NORMAL
,
768 "with '#' will be kept; you may remove them"
769 " yourself if you want to.\n"
770 "An empty message aborts the commit.\n");
771 if (only_include_assumed
)
772 status_printf_ln(s
, GIT_COLOR_NORMAL
,
773 "%s", only_include_assumed
);
775 ai_tmp
= cut_ident_timestamp_part(author_ident
->buf
);
776 ci_tmp
= cut_ident_timestamp_part(committer_ident
.buf
);
777 if (strcmp(author_ident
->buf
, committer_ident
.buf
))
778 status_printf_ln(s
, GIT_COLOR_NORMAL
,
781 ident_shown
++ ? "" : "\n",
784 if (!user_ident_sufficiently_given())
785 status_printf_ln(s
, GIT_COLOR_NORMAL
,
788 ident_shown
++ ? "" : "\n",
789 committer_ident
.buf
);
792 status_printf_ln(s
, GIT_COLOR_NORMAL
, "");
794 saved_color_setting
= s
->use_color
;
796 commitable
= run_status(s
->fp
, index_file
, prefix
, 1, s
);
797 s
->use_color
= saved_color_setting
;
802 unsigned char sha1
[20];
803 const char *parent
= "HEAD";
805 if (!active_nr
&& read_cache() < 0)
806 die("Cannot read index");
811 if (get_sha1(parent
, sha1
))
812 commitable
= !!active_nr
;
814 commitable
= index_differs_from(parent
, 0);
816 strbuf_release(&committer_ident
);
821 * Reject an attempt to record a non-merge empty commit without
822 * explicit --allow-empty. In the cherry-pick case, it may be
823 * empty due to conflict resolution, which the user should okay.
825 if (!commitable
&& whence
!= FROM_MERGE
&& !allow_empty
&&
826 !(amend
&& is_a_merge(head_sha1
))) {
827 run_status(stdout
, index_file
, prefix
, 0, s
);
829 fputs(empty_amend_advice
, stderr
);
830 else if (whence
== FROM_CHERRY_PICK
)
831 fputs(empty_cherry_pick_advice
, stderr
);
836 * Re-read the index as pre-commit hook could have updated it,
837 * and write it out as a tree. We must do this before we invoke
838 * the editor and after we invoke run_status above.
841 read_cache_from(index_file
);
842 if (!active_cache_tree
)
843 active_cache_tree
= cache_tree();
844 if (cache_tree_update(active_cache_tree
,
845 active_cache
, active_nr
, 0, 0) < 0) {
846 error("Error building trees");
850 if (run_hook(index_file
, "prepare-commit-msg",
851 git_path(commit_editmsg
), hook_arg1
, hook_arg2
, NULL
))
855 char index
[PATH_MAX
];
856 const char *env
[2] = { NULL
};
858 snprintf(index
, sizeof(index
), "GIT_INDEX_FILE=%s", index_file
);
859 if (launch_editor(git_path(commit_editmsg
), NULL
, env
)) {
861 "Please supply the message using either -m or -F option.\n");
867 run_hook(index_file
, "commit-msg", git_path(commit_editmsg
), NULL
)) {
875 * Find out if the message in the strbuf contains only whitespace and
876 * Signed-off-by lines.
878 static int message_is_empty(struct strbuf
*sb
)
880 struct strbuf tmpl
= STRBUF_INIT
;
882 int eol
, i
, start
= 0;
884 if (cleanup_mode
== CLEANUP_NONE
&& sb
->len
)
887 /* See if the template is just a prefix of the message. */
888 if (template_file
&& strbuf_read_file(&tmpl
, template_file
, 0) > 0) {
889 stripspace(&tmpl
, cleanup_mode
== CLEANUP_ALL
);
890 if (start
+ tmpl
.len
<= sb
->len
&&
891 memcmp(tmpl
.buf
, sb
->buf
+ start
, tmpl
.len
) == 0)
894 strbuf_release(&tmpl
);
896 /* Check if the rest is just whitespace and Signed-of-by's. */
897 for (i
= start
; i
< sb
->len
; i
++) {
898 nl
= memchr(sb
->buf
+ i
, '\n', sb
->len
- i
);
904 if (strlen(sign_off_header
) <= eol
- i
&&
905 !prefixcmp(sb
->buf
+ i
, sign_off_header
)) {
910 if (!isspace(sb
->buf
[i
++]))
917 static const char *find_author_by_nickname(const char *name
)
919 struct rev_info revs
;
920 struct commit
*commit
;
921 struct strbuf buf
= STRBUF_INIT
;
925 init_revisions(&revs
, NULL
);
926 strbuf_addf(&buf
, "--author=%s", name
);
931 setup_revisions(ac
, av
, &revs
, NULL
);
932 prepare_revision_walk(&revs
);
933 commit
= get_revision(&revs
);
935 struct pretty_print_context ctx
= {0};
936 ctx
.date_mode
= DATE_NORMAL
;
937 strbuf_release(&buf
);
938 format_commit_message(commit
, "%an <%ae>", &buf
, &ctx
);
939 return strbuf_detach(&buf
, NULL
);
941 die("No existing author found with '%s'", name
);
945 static void handle_untracked_files_arg(struct wt_status
*s
)
947 if (!untracked_files_arg
)
948 ; /* default already initialized */
949 else if (!strcmp(untracked_files_arg
, "no"))
950 s
->show_untracked_files
= SHOW_NO_UNTRACKED_FILES
;
951 else if (!strcmp(untracked_files_arg
, "normal"))
952 s
->show_untracked_files
= SHOW_NORMAL_UNTRACKED_FILES
;
953 else if (!strcmp(untracked_files_arg
, "all"))
954 s
->show_untracked_files
= SHOW_ALL_UNTRACKED_FILES
;
956 die("Invalid untracked files mode '%s'", untracked_files_arg
);
959 static const char *read_commit_message(const char *name
)
961 const char *out_enc
, *out
;
962 struct commit
*commit
;
964 commit
= lookup_commit_reference_by_name(name
);
966 die("could not lookup commit %s", name
);
967 out_enc
= get_commit_output_encoding();
968 out
= logmsg_reencode(commit
, out_enc
);
971 * If we failed to reencode the buffer, just copy it
972 * byte for byte so the user can try to fix it up.
973 * This also handles the case where input and output
974 * encodings are identical.
977 out
= xstrdup(commit
->buffer
);
981 static int parse_and_validate_options(int argc
, const char *argv
[],
982 const char * const usage
[],
988 argc
= parse_options(argc
, argv
, prefix
, builtin_commit_options
, usage
,
991 if (force_author
&& !strchr(force_author
, '>'))
992 force_author
= find_author_by_nickname(force_author
);
994 if (force_author
&& renew_authorship
)
995 die("Using both --reset-author and --author does not make sense");
997 if (logfile
|| message
.len
|| use_message
|| fixup_message
)
1002 setenv("GIT_EDITOR", ":", 1);
1004 if (get_sha1("HEAD", head_sha1
))
1007 /* Sanity check options */
1008 if (amend
&& initial_commit
)
1009 die("You have nothing to amend.");
1010 if (amend
&& whence
!= FROM_COMMIT
)
1011 die("You are in the middle of a %s -- cannot amend.", whence_s());
1012 if (fixup_message
&& squash_message
)
1013 die("Options --squash and --fixup cannot be used together");
1023 die("Only one of -c/-C/-F/--fixup can be used.");
1024 if (message
.len
&& f
> 0)
1025 die("Option -m cannot be combined with -c/-C/-F/--fixup.");
1027 use_message
= edit_message
;
1028 if (amend
&& !use_message
&& !fixup_message
)
1029 use_message
= "HEAD";
1030 if (!use_message
&& whence
!= FROM_CHERRY_PICK
&& renew_authorship
)
1031 die("--reset-author can be used only with -C, -c or --amend.");
1033 use_message_buffer
= read_commit_message(use_message
);
1034 if (!renew_authorship
) {
1035 author_message
= use_message
;
1036 author_message_buffer
= use_message_buffer
;
1039 if (whence
== FROM_CHERRY_PICK
&& !renew_authorship
) {
1040 author_message
= "CHERRY_PICK_HEAD";
1041 author_message_buffer
= read_commit_message(author_message
);
1044 if (!!also
+ !!only
+ !!all
+ !!interactive
> 1)
1045 die("Only one of --include/--only/--all/--interactive can be used.");
1046 if (argc
== 0 && (also
|| (only
&& !amend
)))
1047 die("No paths with --include/--only does not make sense.");
1048 if (argc
== 0 && only
&& amend
)
1049 only_include_assumed
= "Clever... amending the last one with dirty index.";
1050 if (argc
> 0 && !also
&& !only
)
1051 only_include_assumed
= "Explicit paths specified without -i nor -o; assuming --only paths...";
1052 if (!cleanup_arg
|| !strcmp(cleanup_arg
, "default"))
1053 cleanup_mode
= use_editor
? CLEANUP_ALL
: CLEANUP_SPACE
;
1054 else if (!strcmp(cleanup_arg
, "verbatim"))
1055 cleanup_mode
= CLEANUP_NONE
;
1056 else if (!strcmp(cleanup_arg
, "whitespace"))
1057 cleanup_mode
= CLEANUP_SPACE
;
1058 else if (!strcmp(cleanup_arg
, "strip"))
1059 cleanup_mode
= CLEANUP_ALL
;
1061 die("Invalid cleanup mode %s", cleanup_arg
);
1063 handle_untracked_files_arg(s
);
1065 if (all
&& argc
> 0)
1066 die("Paths with -a does not make sense.");
1067 else if (interactive
&& argc
> 0)
1068 die("Paths with --interactive does not make sense.");
1070 if (null_termination
&& status_format
== STATUS_FORMAT_LONG
)
1071 status_format
= STATUS_FORMAT_PORCELAIN
;
1072 if (status_format
!= STATUS_FORMAT_LONG
)
1078 static int dry_run_commit(int argc
, const char **argv
, const char *prefix
,
1079 struct wt_status
*s
)
1082 const char *index_file
;
1084 index_file
= prepare_index(argc
, argv
, prefix
, 1);
1085 commitable
= run_status(stdout
, index_file
, prefix
, 0, s
);
1086 rollback_index_files();
1088 return commitable
? 0 : 1;
1091 static int parse_status_slot(const char *var
, int offset
)
1093 if (!strcasecmp(var
+offset
, "header"))
1094 return WT_STATUS_HEADER
;
1095 if (!strcasecmp(var
+offset
, "branch"))
1096 return WT_STATUS_ONBRANCH
;
1097 if (!strcasecmp(var
+offset
, "updated")
1098 || !strcasecmp(var
+offset
, "added"))
1099 return WT_STATUS_UPDATED
;
1100 if (!strcasecmp(var
+offset
, "changed"))
1101 return WT_STATUS_CHANGED
;
1102 if (!strcasecmp(var
+offset
, "untracked"))
1103 return WT_STATUS_UNTRACKED
;
1104 if (!strcasecmp(var
+offset
, "nobranch"))
1105 return WT_STATUS_NOBRANCH
;
1106 if (!strcasecmp(var
+offset
, "unmerged"))
1107 return WT_STATUS_UNMERGED
;
1111 static int git_status_config(const char *k
, const char *v
, void *cb
)
1113 struct wt_status
*s
= cb
;
1115 if (!strcmp(k
, "status.submodulesummary")) {
1117 s
->submodule_summary
= git_config_bool_or_int(k
, v
, &is_bool
);
1118 if (is_bool
&& s
->submodule_summary
)
1119 s
->submodule_summary
= -1;
1122 if (!strcmp(k
, "status.color") || !strcmp(k
, "color.status")) {
1123 s
->use_color
= git_config_colorbool(k
, v
, -1);
1126 if (!prefixcmp(k
, "status.color.") || !prefixcmp(k
, "color.status.")) {
1127 int slot
= parse_status_slot(k
, 13);
1131 return config_error_nonbool(k
);
1132 color_parse(v
, k
, s
->color_palette
[slot
]);
1135 if (!strcmp(k
, "status.relativepaths")) {
1136 s
->relative_paths
= git_config_bool(k
, v
);
1139 if (!strcmp(k
, "status.showuntrackedfiles")) {
1141 return config_error_nonbool(k
);
1142 else if (!strcmp(v
, "no"))
1143 s
->show_untracked_files
= SHOW_NO_UNTRACKED_FILES
;
1144 else if (!strcmp(v
, "normal"))
1145 s
->show_untracked_files
= SHOW_NORMAL_UNTRACKED_FILES
;
1146 else if (!strcmp(v
, "all"))
1147 s
->show_untracked_files
= SHOW_ALL_UNTRACKED_FILES
;
1149 return error("Invalid untracked files mode '%s'", v
);
1152 return git_diff_ui_config(k
, v
, NULL
);
1155 int cmd_status(int argc
, const char **argv
, const char *prefix
)
1159 unsigned char sha1
[20];
1160 static struct option builtin_status_options
[] = {
1161 OPT__VERBOSE(&verbose
, "be verbose"),
1162 OPT_SET_INT('s', "short", &status_format
,
1163 "show status concisely", STATUS_FORMAT_SHORT
),
1164 OPT_BOOLEAN('b', "branch", &status_show_branch
,
1165 "show branch information"),
1166 OPT_SET_INT(0, "porcelain", &status_format
,
1167 "machine-readable output",
1168 STATUS_FORMAT_PORCELAIN
),
1169 OPT_BOOLEAN('z', "null", &null_termination
,
1170 "terminate entries with NUL"),
1171 { OPTION_STRING
, 'u', "untracked-files", &untracked_files_arg
,
1173 "show untracked files, optional modes: all, normal, no. (Default: all)",
1174 PARSE_OPT_OPTARG
, NULL
, (intptr_t)"all" },
1175 OPT_BOOLEAN(0, "ignored", &show_ignored_in_status
,
1176 "show ignored files"),
1177 { OPTION_STRING
, 0, "ignore-submodules", &ignore_submodule_arg
, "when",
1178 "ignore changes to submodules, optional when: all, dirty, untracked. (Default: all)",
1179 PARSE_OPT_OPTARG
, NULL
, (intptr_t)"all" },
1183 if (argc
== 2 && !strcmp(argv
[1], "-h"))
1184 usage_with_options(builtin_status_usage
, builtin_status_options
);
1186 if (null_termination
&& status_format
== STATUS_FORMAT_LONG
)
1187 status_format
= STATUS_FORMAT_PORCELAIN
;
1189 wt_status_prepare(&s
);
1190 gitmodules_config();
1191 git_config(git_status_config
, &s
);
1192 determine_whence(&s
);
1193 argc
= parse_options(argc
, argv
, prefix
,
1194 builtin_status_options
,
1195 builtin_status_usage
, 0);
1196 handle_untracked_files_arg(&s
);
1197 if (show_ignored_in_status
)
1198 s
.show_ignored_files
= 1;
1200 s
.pathspec
= get_pathspec(prefix
, argv
);
1202 read_cache_preload(s
.pathspec
);
1203 refresh_index(&the_index
, REFRESH_QUIET
|REFRESH_UNMERGED
, s
.pathspec
, NULL
, NULL
);
1205 fd
= hold_locked_index(&index_lock
, 0);
1207 update_index_if_able(&the_index
, &index_lock
);
1209 s
.is_initial
= get_sha1(s
.reference
, sha1
) ? 1 : 0;
1210 s
.ignore_submodule_arg
= ignore_submodule_arg
;
1211 wt_status_collect(&s
);
1213 if (s
.relative_paths
)
1215 if (s
.use_color
== -1)
1216 s
.use_color
= git_use_color_default
;
1217 if (diff_use_color_default
== -1)
1218 diff_use_color_default
= git_use_color_default
;
1220 switch (status_format
) {
1221 case STATUS_FORMAT_SHORT
:
1222 wt_shortstatus_print(&s
, null_termination
, status_show_branch
);
1224 case STATUS_FORMAT_PORCELAIN
:
1225 wt_porcelain_print(&s
, null_termination
);
1227 case STATUS_FORMAT_LONG
:
1228 s
.verbose
= verbose
;
1229 s
.ignore_submodule_arg
= ignore_submodule_arg
;
1230 wt_status_print(&s
);
1236 static void print_summary(const char *prefix
, const unsigned char *sha1
)
1238 struct rev_info rev
;
1239 struct commit
*commit
;
1240 struct strbuf format
= STRBUF_INIT
;
1241 unsigned char junk_sha1
[20];
1242 const char *head
= resolve_ref("HEAD", junk_sha1
, 0, NULL
);
1243 struct pretty_print_context pctx
= {0};
1244 struct strbuf author_ident
= STRBUF_INIT
;
1245 struct strbuf committer_ident
= STRBUF_INIT
;
1247 commit
= lookup_commit(sha1
);
1249 die("couldn't look up newly created commit");
1250 if (!commit
|| parse_commit(commit
))
1251 die("could not parse newly created commit");
1253 strbuf_addstr(&format
, "format:%h] %s");
1255 format_commit_message(commit
, "%an <%ae>", &author_ident
, &pctx
);
1256 format_commit_message(commit
, "%cn <%ce>", &committer_ident
, &pctx
);
1257 if (strbuf_cmp(&author_ident
, &committer_ident
)) {
1258 strbuf_addstr(&format
, "\n Author: ");
1259 strbuf_addbuf_percentquote(&format
, &author_ident
);
1261 if (!user_ident_sufficiently_given()) {
1262 strbuf_addstr(&format
, "\n Committer: ");
1263 strbuf_addbuf_percentquote(&format
, &committer_ident
);
1264 if (advice_implicit_identity
) {
1265 strbuf_addch(&format
, '\n');
1266 strbuf_addstr(&format
, implicit_ident_advice
);
1269 strbuf_release(&author_ident
);
1270 strbuf_release(&committer_ident
);
1272 init_revisions(&rev
, prefix
);
1273 setup_revisions(0, NULL
, &rev
, NULL
);
1276 rev
.diffopt
.output_format
=
1277 DIFF_FORMAT_SHORTSTAT
| DIFF_FORMAT_SUMMARY
;
1279 rev
.verbose_header
= 1;
1280 rev
.show_root_diff
= 1;
1281 get_commit_format(format
.buf
, &rev
);
1282 rev
.always_show_header
= 0;
1283 rev
.diffopt
.detect_rename
= 1;
1284 rev
.diffopt
.break_opt
= 0;
1285 diff_setup_done(&rev
.diffopt
);
1288 !prefixcmp(head
, "refs/heads/") ?
1290 !strcmp(head
, "HEAD") ?
1293 initial_commit
? " (root-commit)" : "");
1295 if (!log_tree_commit(&rev
, commit
)) {
1296 rev
.always_show_header
= 1;
1297 rev
.use_terminator
= 1;
1298 log_tree_commit(&rev
, commit
);
1301 strbuf_release(&format
);
1304 static int git_commit_config(const char *k
, const char *v
, void *cb
)
1306 struct wt_status
*s
= cb
;
1308 if (!strcmp(k
, "commit.template"))
1309 return git_config_pathname(&template_file
, k
, v
);
1310 if (!strcmp(k
, "commit.status")) {
1311 include_status
= git_config_bool(k
, v
);
1315 return git_status_config(k
, v
, s
);
1318 static const char post_rewrite_hook
[] = "hooks/post-rewrite";
1320 static int run_rewrite_hook(const unsigned char *oldsha1
,
1321 const unsigned char *newsha1
)
1323 /* oldsha1 SP newsha1 LF NUL */
1324 static char buf
[2*40 + 3];
1325 struct child_process proc
;
1326 const char *argv
[3];
1330 if (access(git_path(post_rewrite_hook
), X_OK
) < 0)
1333 argv
[0] = git_path(post_rewrite_hook
);
1337 memset(&proc
, 0, sizeof(proc
));
1340 proc
.stdout_to_stderr
= 1;
1342 code
= start_command(&proc
);
1345 n
= snprintf(buf
, sizeof(buf
), "%s %s\n",
1346 sha1_to_hex(oldsha1
), sha1_to_hex(newsha1
));
1347 write_in_full(proc
.in
, buf
, n
);
1349 return finish_command(&proc
);
1352 int cmd_commit(int argc
, const char **argv
, const char *prefix
)
1354 struct strbuf sb
= STRBUF_INIT
;
1355 struct strbuf author_ident
= STRBUF_INIT
;
1356 const char *index_file
, *reflog_msg
;
1358 unsigned char commit_sha1
[20];
1359 struct ref_lock
*ref_lock
;
1360 struct commit_list
*parents
= NULL
, **pptr
= &parents
;
1361 struct stat statbuf
;
1362 int allow_fast_forward
= 1;
1365 if (argc
== 2 && !strcmp(argv
[1], "-h"))
1366 usage_with_options(builtin_commit_usage
, builtin_commit_options
);
1368 wt_status_prepare(&s
);
1369 git_config(git_commit_config
, &s
);
1370 determine_whence(&s
);
1372 if (s
.use_color
== -1)
1373 s
.use_color
= git_use_color_default
;
1374 argc
= parse_and_validate_options(argc
, argv
, builtin_commit_usage
,
1377 if (diff_use_color_default
== -1)
1378 diff_use_color_default
= git_use_color_default
;
1379 return dry_run_commit(argc
, argv
, prefix
, &s
);
1381 index_file
= prepare_index(argc
, argv
, prefix
, 0);
1383 /* Set up everything for writing the commit object. This includes
1384 running hooks, writing the trees, and interacting with the user. */
1385 if (!prepare_to_commit(index_file
, prefix
, &s
, &author_ident
)) {
1386 rollback_index_files();
1390 /* Determine parents */
1391 reflog_msg
= getenv("GIT_REFLOG_ACTION");
1392 if (initial_commit
) {
1394 reflog_msg
= "commit (initial)";
1396 struct commit_list
*c
;
1397 struct commit
*commit
;
1400 reflog_msg
= "commit (amend)";
1401 commit
= lookup_commit(head_sha1
);
1402 if (!commit
|| parse_commit(commit
))
1403 die("could not parse HEAD commit");
1405 for (c
= commit
->parents
; c
; c
= c
->next
)
1406 pptr
= &commit_list_insert(c
->item
, pptr
)->next
;
1407 } else if (whence
== FROM_MERGE
) {
1408 struct strbuf m
= STRBUF_INIT
;
1412 reflog_msg
= "commit (merge)";
1413 pptr
= &commit_list_insert(lookup_commit(head_sha1
), pptr
)->next
;
1414 fp
= fopen(git_path("MERGE_HEAD"), "r");
1416 die_errno("could not open '%s' for reading",
1417 git_path("MERGE_HEAD"));
1418 while (strbuf_getline(&m
, fp
, '\n') != EOF
) {
1419 unsigned char sha1
[20];
1420 if (get_sha1_hex(m
.buf
, sha1
) < 0)
1421 die("Corrupt MERGE_HEAD file (%s)", m
.buf
);
1422 pptr
= &commit_list_insert(lookup_commit(sha1
), pptr
)->next
;
1426 if (!stat(git_path("MERGE_MODE"), &statbuf
)) {
1427 if (strbuf_read_file(&sb
, git_path("MERGE_MODE"), 0) < 0)
1428 die_errno("could not read MERGE_MODE");
1429 if (!strcmp(sb
.buf
, "no-ff"))
1430 allow_fast_forward
= 0;
1432 if (allow_fast_forward
)
1433 parents
= reduce_heads(parents
);
1436 reflog_msg
= (whence
== FROM_CHERRY_PICK
)
1437 ? "commit (cherry-pick)"
1439 pptr
= &commit_list_insert(lookup_commit(head_sha1
), pptr
)->next
;
1442 /* Finally, get the commit message */
1444 if (strbuf_read_file(&sb
, git_path(commit_editmsg
), 0) < 0) {
1445 int saved_errno
= errno
;
1446 rollback_index_files();
1447 die("could not read commit message: %s", strerror(saved_errno
));
1450 /* Truncate the message just before the diff, if any. */
1452 p
= strstr(sb
.buf
, "\ndiff --git ");
1454 strbuf_setlen(&sb
, p
- sb
.buf
+ 1);
1457 if (cleanup_mode
!= CLEANUP_NONE
)
1458 stripspace(&sb
, cleanup_mode
== CLEANUP_ALL
);
1459 if (message_is_empty(&sb
) && !allow_empty_message
) {
1460 rollback_index_files();
1461 fprintf(stderr
, "Aborting commit due to empty commit message.\n");
1465 if (commit_tree(sb
.buf
, active_cache_tree
->sha1
, parents
, commit_sha1
,
1466 author_ident
.buf
)) {
1467 rollback_index_files();
1468 die("failed to write commit object");
1470 strbuf_release(&author_ident
);
1472 ref_lock
= lock_any_ref_for_update("HEAD",
1473 initial_commit
? NULL
: head_sha1
,
1476 nl
= strchr(sb
.buf
, '\n');
1478 strbuf_setlen(&sb
, nl
+ 1 - sb
.buf
);
1480 strbuf_addch(&sb
, '\n');
1481 strbuf_insert(&sb
, 0, reflog_msg
, strlen(reflog_msg
));
1482 strbuf_insert(&sb
, strlen(reflog_msg
), ": ", 2);
1485 rollback_index_files();
1486 die("cannot lock HEAD ref");
1488 if (write_ref_sha1(ref_lock
, commit_sha1
, sb
.buf
) < 0) {
1489 rollback_index_files();
1490 die("cannot update HEAD ref");
1493 unlink(git_path("CHERRY_PICK_HEAD"));
1494 unlink(git_path("MERGE_HEAD"));
1495 unlink(git_path("MERGE_MSG"));
1496 unlink(git_path("MERGE_MODE"));
1497 unlink(git_path("SQUASH_MSG"));
1499 if (commit_index_files())
1500 die ("Repository has been updated, but unable to write\n"
1501 "new_index file. Check that disk is not full or quota is\n"
1502 "not exceeded, and then \"git reset HEAD\" to recover.");
1505 run_hook(get_index_file(), "post-commit", NULL
);
1506 if (amend
&& !no_post_rewrite
) {
1507 struct notes_rewrite_cfg
*cfg
;
1508 cfg
= init_copy_notes_for_rewrite("amend");
1510 copy_note_for_rewrite(cfg
, head_sha1
, commit_sha1
);
1511 finish_copy_notes_for_rewrite(cfg
);
1513 run_rewrite_hook(head_sha1
, commit_sha1
);
1516 print_summary(prefix
, commit_sha1
);