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"
16 #include "wt-status.h"
17 #include "run-command.h"
22 #include "parse-options.h"
23 #include "path-list.h"
25 static const char * const builtin_commit_usage[] = {
26 "git-commit [options] [--] <filepattern>...",
30 static const char * const builtin_status_usage[] = {
31 "git-status [options] [--] <filepattern>...",
35 static unsigned char head_sha1[20], merge_head_sha1[20];
36 static char *use_message_buffer;
37 static const char commit_editmsg[] = "COMMIT_EDITMSG";
38 static struct lock_file index_lock; /* real index */
39 static struct lock_file false_lock; /* used only for partial commits */
46 static char *logfile, *force_author, *template_file;
47 static char *edit_message, *use_message;
48 static int all, edit_flag, also, interactive, only, amend, signoff;
49 static int quiet, verbose, untracked_files, no_verify, allow_empty;
51 static int no_edit, initial_commit, in_merge;
52 const char *only_include_assumed;
53 struct strbuf message;
55 static int opt_parse_m(const struct option *opt, const char *arg, int unset)
57 struct strbuf *buf = opt->value;
59 strbuf_setlen(buf, 0);
61 strbuf_addstr(buf, arg);
62 strbuf_addch(buf, '\n');
63 strbuf_addch(buf, '\n');
68 static struct option builtin_commit_options[] = {
70 OPT__VERBOSE(&verbose),
71 OPT_GROUP("Commit message options"),
73 OPT_STRING('F', "file", &logfile, "FILE", "read log from file"),
74 OPT_STRING(0, "author", &force_author, "AUTHOR", "override author for commit"),
75 OPT_CALLBACK('m', "message", &message, "MESSAGE", "specify commit message", opt_parse_m),
76 OPT_STRING('c', "reedit-message", &edit_message, "COMMIT", "reuse and edit message from specified commit "),
77 OPT_STRING('C', "reuse-message", &use_message, "COMMIT", "reuse message from specified commit"),
78 OPT_BOOLEAN('s', "signoff", &signoff, "add Signed-off-by: header"),
79 OPT_STRING('t', "template", &template_file, "FILE", "use specified template file"),
80 OPT_BOOLEAN('e', "edit", &edit_flag, "force edit of commit"),
82 OPT_GROUP("Commit contents options"),
83 OPT_BOOLEAN('a', "all", &all, "commit all changed files"),
84 OPT_BOOLEAN('i', "include", &also, "add specified files to index for commit"),
85 OPT_BOOLEAN(0, "interactive", &interactive, "interactively add files"),
86 OPT_BOOLEAN('o', "only", &only, ""),
87 OPT_BOOLEAN('n', "no-verify", &no_verify, "bypass pre-commit hook"),
88 OPT_BOOLEAN(0, "amend", &amend, "amend previous commit"),
89 OPT_BOOLEAN(0, "untracked-files", &untracked_files, "show all untracked files"),
90 OPT_BOOLEAN(0, "allow-empty", &allow_empty, "ok to record an empty change"),
95 static void rollback_index_files(void)
97 switch (commit_style) {
99 break; /* nothing to do */
101 rollback_lock_file(&index_lock);
104 rollback_lock_file(&index_lock);
105 rollback_lock_file(&false_lock);
110 static void commit_index_files(void)
112 switch (commit_style) {
114 break; /* nothing to do */
116 commit_lock_file(&index_lock);
119 commit_lock_file(&index_lock);
120 rollback_lock_file(&false_lock);
126 * Take a union of paths in the index and the named tree (typically, "HEAD"),
127 * and return the paths that match the given pattern in list.
129 static int list_paths(struct path_list *list, const char *with_tree,
130 const char *prefix, const char **pattern)
135 for (i = 0; pattern[i]; i++)
140 overlay_tree_on_cache(with_tree, prefix);
142 for (i = 0; i < active_nr; i++) {
143 struct cache_entry *ce = active_cache[i];
144 if (ce->ce_flags & htons(CE_UPDATE))
146 if (!pathspec_match(pattern, m, ce->name, 0))
148 path_list_insert(ce->name, list);
151 return report_path_error(m, pattern, prefix ? strlen(prefix) : 0);
154 static void add_remove_files(struct path_list *list)
157 for (i = 0; i < list->nr; i++) {
158 struct path_list_item *p = &(list->items[i]);
159 if (file_exists(p->path))
160 add_file_to_cache(p->path, 0);
162 remove_file_from_cache(p->path);
166 static char *prepare_index(int argc, const char **argv, const char *prefix)
170 struct path_list partial;
171 const char **pathspec = NULL;
174 interactive_add(argc, argv, prefix);
175 commit_style = COMMIT_AS_IS;
176 return get_index_file();
179 if (read_cache() < 0)
180 die("index file corrupt");
183 pathspec = get_pathspec(prefix, argv);
186 * Non partial, non as-is commit.
188 * (1) get the real index;
189 * (2) update the_index as necessary;
190 * (3) write the_index out to the real index (still locked);
191 * (4) return the name of the locked index file.
193 * The caller should run hooks on the locked real index, and
194 * (A) if all goes well, commit the real index;
195 * (B) on failure, rollback the real index.
197 if (all || (also && pathspec && *pathspec)) {
198 int fd = hold_locked_index(&index_lock, 1);
199 add_files_to_cache(0, also ? prefix : NULL, pathspec);
200 refresh_cache(REFRESH_QUIET);
201 if (write_cache(fd, active_cache, active_nr) || close(fd))
202 die("unable to write new_index file");
203 commit_style = COMMIT_NORMAL;
204 return index_lock.filename;
210 * (1) return the name of the real index file.
212 * The caller should run hooks on the real index, and run
213 * hooks on the real index, and create commit from the_index.
214 * We still need to refresh the index here.
216 if (!pathspec || !*pathspec) {
217 fd = hold_locked_index(&index_lock, 1);
218 refresh_cache(REFRESH_QUIET);
219 if (write_cache(fd, active_cache, active_nr) ||
220 close(fd) || commit_locked_index(&index_lock))
221 die("unable to write new_index file");
222 commit_style = COMMIT_AS_IS;
223 return get_index_file();
229 * (0) find the set of affected paths;
230 * (1) get lock on the real index file;
231 * (2) update the_index with the given paths;
232 * (3) write the_index out to the real index (still locked);
233 * (4) get lock on the false index file;
234 * (5) reset the_index from HEAD;
235 * (6) update the_index the same way as (2);
236 * (7) write the_index out to the false index file;
237 * (8) return the name of the false index file (still locked);
239 * The caller should run hooks on the locked false index, and
240 * create commit from it. Then
241 * (A) if all goes well, commit the real index;
242 * (B) on failure, rollback the real index;
243 * In either case, rollback the false index.
245 commit_style = COMMIT_PARTIAL;
247 if (file_exists(git_path("MERGE_HEAD")))
248 die("cannot do a partial commit during a merge.");
250 memset(&partial, 0, sizeof(partial));
251 partial.strdup_paths = 1;
252 if (list_paths(&partial, initial_commit ? NULL : "HEAD", prefix, pathspec))
256 if (read_cache() < 0)
257 die("cannot read the index");
259 fd = hold_locked_index(&index_lock, 1);
260 add_remove_files(&partial);
261 refresh_cache(REFRESH_QUIET);
262 if (write_cache(fd, active_cache, active_nr) || close(fd))
263 die("unable to write new_index file");
265 fd = hold_lock_file_for_update(&false_lock,
266 git_path("next-index-%d", getpid()), 1);
268 if (!initial_commit) {
269 tree = parse_tree_indirect(head_sha1);
271 die("failed to unpack HEAD tree object");
272 if (read_tree(tree, 0, NULL))
273 die("failed to read HEAD tree object");
275 add_remove_files(&partial);
276 refresh_cache(REFRESH_QUIET);
278 if (write_cache(fd, active_cache, active_nr) || close(fd))
279 die("unable to write temporary index file");
280 return false_lock.filename;
283 static int run_status(FILE *fp, const char *index_file, const char *prefix)
287 wt_status_prepare(&s);
292 s.reference = "HEAD^1";
295 s.untracked = untracked_files;
296 s.index_file = index_file;
304 static const char sign_off_header[] = "Signed-off-by: ";
306 static int prepare_log_message(const char *index_file, const char *prefix)
309 int commitable, saved_color_setting;
316 strbuf_addbuf(&sb, &message);
317 } else if (logfile && !strcmp(logfile, "-")) {
319 fprintf(stderr, "(reading log message from standard input)\n");
320 if (strbuf_read(&sb, 0, 0) < 0)
321 die("could not read log from standard input");
322 } else if (logfile) {
323 if (strbuf_read_file(&sb, logfile, 0) < 0)
324 die("could not read log file '%s': %s",
325 logfile, strerror(errno));
326 } else if (use_message) {
327 buffer = strstr(use_message_buffer, "\n\n");
328 if (!buffer || buffer[2] == '\0')
329 die("commit has empty message");
330 strbuf_add(&sb, buffer + 2, strlen(buffer + 2));
331 } else if (!stat(git_path("MERGE_MSG"), &statbuf)) {
332 if (strbuf_read_file(&sb, git_path("MERGE_MSG"), 0) < 0)
333 die("could not read MERGE_MSG: %s", strerror(errno));
334 } else if (!stat(git_path("SQUASH_MSG"), &statbuf)) {
335 if (strbuf_read_file(&sb, git_path("SQUASH_MSG"), 0) < 0)
336 die("could not read SQUASH_MSG: %s", strerror(errno));
337 } else if (template_file && !stat(template_file, &statbuf)) {
338 if (strbuf_read_file(&sb, template_file, 0) < 0)
339 die("could not read %s: %s",
340 template_file, strerror(errno));
343 fp = fopen(git_path(commit_editmsg), "w");
345 die("could not open %s", git_path(commit_editmsg));
353 strbuf_init(&sob, 0);
354 strbuf_addstr(&sob, sign_off_header);
355 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
356 getenv("GIT_COMMITTER_EMAIL")));
357 strbuf_addch(&sob, '\n');
358 for (i = sb.len - 1; i > 0 && sb.buf[i - 1] != '\n'; i--)
360 if (prefixcmp(sb.buf + i, sob.buf)) {
361 if (prefixcmp(sb.buf + i, sign_off_header))
362 strbuf_addch(&sb, '\n');
363 strbuf_addbuf(&sb, &sob);
365 strbuf_release(&sob);
368 if (fwrite(sb.buf, 1, sb.len, fp) < sb.len)
369 die("could not write commit template: %s", strerror(errno));
375 unsigned char sha1[40];
379 if (!active_nr && read_cache() < 0)
380 die("Cannot read index");
382 if (get_sha1("HEAD", sha1) != 0)
385 init_revisions(&rev, "");
387 setup_revisions(0, NULL, &rev, "HEAD");
388 DIFF_OPT_SET(&rev.diffopt, QUIET);
389 DIFF_OPT_SET(&rev.diffopt, EXIT_WITH_STATUS);
390 run_diff_index(&rev, 1 /* cached */);
392 return !!DIFF_OPT_TST(&rev.diffopt, HAS_CHANGES);
395 if (in_merge && !no_edit)
398 "# It looks like you may be committing a MERGE.\n"
399 "# If this is not correct, please remove the file\n"
403 git_path("MERGE_HEAD"));
407 "# Please enter the commit message for your changes.\n"
408 "# (Comment lines starting with '#' will not be included)\n");
409 if (only_include_assumed)
410 fprintf(fp, "# %s\n", only_include_assumed);
412 saved_color_setting = wt_status_use_color;
413 wt_status_use_color = 0;
414 commitable = run_status(fp, index_file, prefix);
415 wt_status_use_color = saved_color_setting;
423 * Find out if the message starting at position 'start' in the strbuf
424 * contains only whitespace and Signed-off-by lines.
426 static int message_is_empty(struct strbuf *sb, int start)
432 /* See if the template is just a prefix of the message. */
433 strbuf_init(&tmpl, 0);
434 if (template_file && strbuf_read_file(&tmpl, template_file, 0) > 0) {
435 stripspace(&tmpl, 1);
436 if (start + tmpl.len <= sb->len &&
437 memcmp(tmpl.buf, sb->buf + start, tmpl.len) == 0)
440 strbuf_release(&tmpl);
442 /* Check if the rest is just whitespace and Signed-of-by's. */
443 for (i = start; i < sb->len; i++) {
444 nl = memchr(sb->buf + i, '\n', sb->len - i);
450 if (strlen(sign_off_header) <= eol - i &&
451 !prefixcmp(sb->buf + i, sign_off_header)) {
456 if (!isspace(sb->buf[i++]))
463 static void determine_author_info(struct strbuf *sb)
465 char *name, *email, *date;
467 name = getenv("GIT_AUTHOR_NAME");
468 email = getenv("GIT_AUTHOR_EMAIL");
469 date = getenv("GIT_AUTHOR_DATE");
472 const char *a, *lb, *rb, *eol;
474 a = strstr(use_message_buffer, "\nauthor ");
476 die("invalid commit: %s", use_message);
478 lb = strstr(a + 8, " <");
479 rb = strstr(a + 8, "> ");
480 eol = strchr(a + 8, '\n');
481 if (!lb || !rb || !eol)
482 die("invalid commit: %s", use_message);
484 name = xstrndup(a + 8, lb - (a + 8));
485 email = xstrndup(lb + 2, rb - (lb + 2));
486 date = xstrndup(rb + 2, eol - (rb + 2));
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));
499 strbuf_addf(sb, "author %s\n", fmt_ident(name, email, date, 1));
502 static int parse_and_validate_options(int argc, const char *argv[],
503 const char * const usage[])
507 argc = parse_options(argc, argv, builtin_commit_options, usage, 0);
509 if (logfile || message.len || use_message)
514 if (get_sha1("HEAD", head_sha1))
517 if (!get_sha1("MERGE_HEAD", merge_head_sha1))
520 /* Sanity check options */
521 if (amend && initial_commit)
522 die("You have nothing to amend.");
523 if (amend && in_merge)
524 die("You are in the middle of a merge -- cannot amend.");
533 die("Only one of -c/-C/-F can be used.");
534 if (message.len && f > 0)
535 die("Option -m cannot be combined with -c/-C/-F.");
537 use_message = edit_message;
539 use_message = "HEAD";
541 unsigned char sha1[20];
542 static char utf8[] = "UTF-8";
545 struct commit *commit;
547 if (get_sha1(use_message, sha1))
548 die("could not lookup commit %s", use_message);
549 commit = lookup_commit(sha1);
550 if (!commit || parse_commit(commit))
551 die("could not parse commit %s", use_message);
553 enc = strstr(commit->buffer, "\nencoding");
555 end = strchr(enc + 10, '\n');
556 enc = xstrndup(enc + 10, end - (enc + 10));
560 out_enc = git_commit_encoding ? git_commit_encoding : utf8;
562 if (strcmp(out_enc, enc))
564 reencode_string(commit->buffer, out_enc, enc);
567 * If we failed to reencode the buffer, just copy it
568 * byte for byte so the user can try to fix it up.
569 * This also handles the case where input and output
570 * encodings are identical.
572 if (use_message_buffer == NULL)
573 use_message_buffer = xstrdup(commit->buffer);
578 if (!!also + !!only + !!all + !!interactive > 1)
579 die("Only one of --include/--only/--all/--interactive can be used.");
580 if (argc == 0 && (also || (only && !amend)))
581 die("No paths with --include/--only does not make sense.");
582 if (argc == 0 && only && amend)
583 only_include_assumed = "Clever... amending the last one with dirty index.";
584 if (argc > 0 && !also && !only) {
585 only_include_assumed = "Explicit paths specified without -i nor -o; assuming --only paths...";
590 die("Paths with -a does not make sense.");
591 else if (interactive && argc > 0)
592 die("Paths with --interactive does not make sense.");
597 int cmd_status(int argc, const char **argv, const char *prefix)
599 const char *index_file;
602 git_config(git_status_config);
604 argc = parse_and_validate_options(argc, argv, builtin_status_usage);
606 index_file = prepare_index(argc, argv, prefix);
608 commitable = run_status(stdout, index_file, prefix);
610 rollback_index_files();
612 return commitable ? 0 : 1;
615 static int run_hook(const char *index_file, const char *name, const char *arg)
617 struct child_process hook;
618 const char *argv[3], *env[2];
619 char index[PATH_MAX];
621 argv[0] = git_path("hooks/%s", name);
624 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
628 if (access(argv[0], X_OK) < 0)
631 memset(&hook, 0, sizeof(hook));
634 hook.stdout_to_stderr = 1;
637 return run_command(&hook);
640 static void print_summary(const char *prefix, const unsigned char *sha1)
643 struct commit *commit;
645 commit = lookup_commit(sha1);
647 die("couldn't look up newly created commit");
648 if (!commit || parse_commit(commit))
649 die("could not parse newly created commit");
651 init_revisions(&rev, prefix);
652 setup_revisions(0, NULL, &rev, NULL);
656 rev.diffopt.output_format =
657 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
659 rev.verbose_header = 1;
660 rev.show_root_diff = 1;
661 rev.commit_format = get_commit_format("format:%h: %s");
662 rev.always_show_header = 1;
664 printf("Created %scommit ", initial_commit ? "initial " : "");
666 log_tree_commit(&rev, commit);
670 int git_commit_config(const char *k, const char *v)
672 if (!strcmp(k, "commit.template")) {
673 template_file = xstrdup(v);
677 return git_status_config(k, v);
680 static int is_a_merge(const unsigned char *sha1)
682 struct commit *commit = lookup_commit(sha1);
683 if (!commit || parse_commit(commit))
684 die("could not parse HEAD commit");
685 return !!(commit->parents && commit->parents->next);
688 static const char commit_utf8_warn[] =
689 "Warning: commit message does not conform to UTF-8.\n"
690 "You may want to amend it after fixing the message, or set the config\n"
691 "variable i18n.commitencoding to the encoding your project uses.\n";
693 int cmd_commit(int argc, const char **argv, const char *prefix)
697 const char *index_file, *reflog_msg;
699 unsigned char commit_sha1[20];
700 struct ref_lock *ref_lock;
702 git_config(git_commit_config);
704 argc = parse_and_validate_options(argc, argv, builtin_commit_usage);
706 index_file = prepare_index(argc, argv, prefix);
708 if (!no_verify && run_hook(index_file, "pre-commit", NULL)) {
709 rollback_index_files();
713 if (!prepare_log_message(index_file, prefix) && !in_merge &&
714 !allow_empty && !(amend && is_a_merge(head_sha1))) {
715 run_status(stdout, index_file, prefix);
716 rollback_index_files();
717 unlink(commit_editmsg);
722 * Re-read the index as pre-commit hook could have updated it,
723 * and write it out as a tree.
726 read_cache_from(index_file);
727 if (!active_cache_tree)
728 active_cache_tree = cache_tree();
729 if (cache_tree_update(active_cache_tree,
730 active_cache, active_nr, 0, 0) < 0) {
731 rollback_index_files();
732 die("Error building trees");
739 strbuf_addf(&sb, "tree %s\n",
740 sha1_to_hex(active_cache_tree->sha1));
742 /* Determine parents */
743 if (initial_commit) {
744 reflog_msg = "commit (initial)";
746 struct commit_list *c;
747 struct commit *commit;
749 reflog_msg = "commit (amend)";
750 commit = lookup_commit(head_sha1);
751 if (!commit || parse_commit(commit))
752 die("could not parse HEAD commit");
754 for (c = commit->parents; c; c = c->next)
755 strbuf_addf(&sb, "parent %s\n",
756 sha1_to_hex(c->item->object.sha1));
757 } else if (in_merge) {
761 reflog_msg = "commit (merge)";
762 strbuf_addf(&sb, "parent %s\n", sha1_to_hex(head_sha1));
764 fp = fopen(git_path("MERGE_HEAD"), "r");
766 die("could not open %s for reading: %s",
767 git_path("MERGE_HEAD"), strerror(errno));
768 while (strbuf_getline(&m, fp, '\n') != EOF)
769 strbuf_addf(&sb, "parent %s\n", m.buf);
773 reflog_msg = "commit";
774 strbuf_addf(&sb, "parent %s\n", sha1_to_hex(head_sha1));
777 determine_author_info(&sb);
778 strbuf_addf(&sb, "committer %s\n", git_committer_info(1));
779 if (!is_encoding_utf8(git_commit_encoding))
780 strbuf_addf(&sb, "encoding %s\n", git_commit_encoding);
781 strbuf_addch(&sb, '\n');
783 /* Get the commit message and validate it */
786 char index[PATH_MAX];
787 const char *env[2] = { index, NULL };
788 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
789 launch_editor(git_path(commit_editmsg), &sb, env);
790 } else if (strbuf_read_file(&sb, git_path(commit_editmsg), 0) < 0) {
791 rollback_index_files();
792 die("could not read commit message");
794 if (run_hook(index_file, "commit-msg", git_path(commit_editmsg))) {
795 rollback_index_files();
799 /* Truncate the message just before the diff, if any. */
800 p = strstr(sb.buf, "\ndiff --git a/");
802 strbuf_setlen(&sb, p - sb.buf + 1);
805 if (sb.len < header_len || message_is_empty(&sb, header_len)) {
806 rollback_index_files();
807 die("no commit message? aborting commit.");
809 strbuf_addch(&sb, '\0');
810 if (is_encoding_utf8(git_commit_encoding) && !is_utf8(sb.buf))
811 fprintf(stderr, commit_utf8_warn);
813 if (write_sha1_file(sb.buf, sb.len - 1, commit_type, commit_sha1)) {
814 rollback_index_files();
815 die("failed to write commit object");
818 ref_lock = lock_any_ref_for_update("HEAD",
819 initial_commit ? NULL : head_sha1,
822 nl = strchr(sb.buf + header_len, '\n');
824 strbuf_setlen(&sb, nl + 1 - sb.buf);
826 strbuf_addch(&sb, '\n');
827 strbuf_remove(&sb, 0, header_len);
828 strbuf_insert(&sb, 0, reflog_msg, strlen(reflog_msg));
829 strbuf_insert(&sb, strlen(reflog_msg), ": ", 2);
832 rollback_index_files();
833 die("cannot lock HEAD ref");
835 if (write_ref_sha1(ref_lock, commit_sha1, sb.buf) < 0) {
836 rollback_index_files();
837 die("cannot update HEAD ref");
840 unlink(git_path("MERGE_HEAD"));
841 unlink(git_path("MERGE_MSG"));
843 commit_index_files();
846 run_hook(get_index_file(), "post-commit", NULL);
848 print_summary(prefix, commit_sha1);