config: add test cases for empty value and no value config variables.
[git/jnareb-git/bp-gitweb.git] / builtin-commit.c
bloba43f2019959a950639f013ff534610e228d8c149
1 /*
2 * Builtin "git commit"
4 * Copyright (c) 2007 Kristian Høgsberg <krh@redhat.com>
5 * Based on git-commit.sh by Junio C Hamano and Linus Torvalds
6 */
8 #include "cache.h"
9 #include "cache-tree.h"
10 #include "dir.h"
11 #include "builtin.h"
12 #include "diff.h"
13 #include "diffcore.h"
14 #include "commit.h"
15 #include "revision.h"
16 #include "wt-status.h"
17 #include "run-command.h"
18 #include "refs.h"
19 #include "log-tree.h"
20 #include "strbuf.h"
21 #include "utf8.h"
22 #include "parse-options.h"
23 #include "path-list.h"
24 #include "unpack-trees.h"
26 static const char * const builtin_commit_usage[] = {
27 "git-commit [options] [--] <filepattern>...",
28 NULL
31 static const char * const builtin_status_usage[] = {
32 "git-status [options] [--] <filepattern>...",
33 NULL
36 static unsigned char head_sha1[20], merge_head_sha1[20];
37 static char *use_message_buffer;
38 static const char commit_editmsg[] = "COMMIT_EDITMSG";
39 static struct lock_file index_lock; /* real index */
40 static struct lock_file false_lock; /* used only for partial commits */
41 static enum {
42 COMMIT_AS_IS = 1,
43 COMMIT_NORMAL,
44 COMMIT_PARTIAL,
45 } commit_style;
47 static char *logfile, *force_author, *template_file;
48 static char *edit_message, *use_message;
49 static int all, edit_flag, also, interactive, only, amend, signoff;
50 static int quiet, verbose, untracked_files, no_verify, allow_empty;
52 * The default commit message cleanup mode will remove the lines
53 * beginning with # (shell comments) and leading and trailing
54 * whitespaces (empty lines or containing only whitespaces)
55 * if editor is used, and only the whitespaces if the message
56 * is specified explicitly.
58 static enum {
59 CLEANUP_SPACE,
60 CLEANUP_NONE,
61 CLEANUP_ALL,
62 } cleanup_mode;
63 static char *cleanup_arg;
65 static int use_editor = 1, initial_commit, in_merge;
66 const char *only_include_assumed;
67 struct strbuf message;
69 static int opt_parse_m(const struct option *opt, const char *arg, int unset)
71 struct strbuf *buf = opt->value;
72 if (unset)
73 strbuf_setlen(buf, 0);
74 else {
75 strbuf_addstr(buf, arg);
76 strbuf_addch(buf, '\n');
77 strbuf_addch(buf, '\n');
79 return 0;
82 static struct option builtin_commit_options[] = {
83 OPT__QUIET(&quiet),
84 OPT__VERBOSE(&verbose),
85 OPT_GROUP("Commit message options"),
87 OPT_STRING('F', "file", &logfile, "FILE", "read log from file"),
88 OPT_STRING(0, "author", &force_author, "AUTHOR", "override author for commit"),
89 OPT_CALLBACK('m', "message", &message, "MESSAGE", "specify commit message", opt_parse_m),
90 OPT_STRING('c', "reedit-message", &edit_message, "COMMIT", "reuse and edit message from specified commit "),
91 OPT_STRING('C', "reuse-message", &use_message, "COMMIT", "reuse message from specified commit"),
92 OPT_BOOLEAN('s', "signoff", &signoff, "add Signed-off-by: header"),
93 OPT_STRING('t', "template", &template_file, "FILE", "use specified template file"),
94 OPT_BOOLEAN('e', "edit", &edit_flag, "force edit of commit"),
96 OPT_GROUP("Commit contents options"),
97 OPT_BOOLEAN('a', "all", &all, "commit all changed files"),
98 OPT_BOOLEAN('i', "include", &also, "add specified files to index for commit"),
99 OPT_BOOLEAN(0, "interactive", &interactive, "interactively add files"),
100 OPT_BOOLEAN('o', "only", &only, ""),
101 OPT_BOOLEAN('n', "no-verify", &no_verify, "bypass pre-commit hook"),
102 OPT_BOOLEAN(0, "amend", &amend, "amend previous commit"),
103 OPT_BOOLEAN(0, "untracked-files", &untracked_files, "show all untracked files"),
104 OPT_BOOLEAN(0, "allow-empty", &allow_empty, "ok to record an empty change"),
105 OPT_STRING(0, "cleanup", &cleanup_arg, "default", "how to strip spaces and #comments from message"),
107 OPT_END()
110 static void rollback_index_files(void)
112 switch (commit_style) {
113 case COMMIT_AS_IS:
114 break; /* nothing to do */
115 case COMMIT_NORMAL:
116 rollback_lock_file(&index_lock);
117 break;
118 case COMMIT_PARTIAL:
119 rollback_lock_file(&index_lock);
120 rollback_lock_file(&false_lock);
121 break;
125 static int commit_index_files(void)
127 int err = 0;
129 switch (commit_style) {
130 case COMMIT_AS_IS:
131 break; /* nothing to do */
132 case COMMIT_NORMAL:
133 err = commit_lock_file(&index_lock);
134 break;
135 case COMMIT_PARTIAL:
136 err = commit_lock_file(&index_lock);
137 rollback_lock_file(&false_lock);
138 break;
141 return err;
145 * Take a union of paths in the index and the named tree (typically, "HEAD"),
146 * and return the paths that match the given pattern in list.
148 static int list_paths(struct path_list *list, const char *with_tree,
149 const char *prefix, const char **pattern)
151 int i;
152 char *m;
154 for (i = 0; pattern[i]; i++)
156 m = xcalloc(1, i);
158 if (with_tree)
159 overlay_tree_on_cache(with_tree, prefix);
161 for (i = 0; i < active_nr; i++) {
162 struct cache_entry *ce = active_cache[i];
163 if (ce->ce_flags & htons(CE_UPDATE))
164 continue;
165 if (!pathspec_match(pattern, m, ce->name, 0))
166 continue;
167 path_list_insert(ce->name, list);
170 return report_path_error(m, pattern, prefix ? strlen(prefix) : 0);
173 static void add_remove_files(struct path_list *list)
175 int i;
176 for (i = 0; i < list->nr; i++) {
177 struct path_list_item *p = &(list->items[i]);
178 if (file_exists(p->path))
179 add_file_to_cache(p->path, 0);
180 else
181 remove_file_from_cache(p->path);
185 static void create_base_index(void)
187 struct tree *tree;
188 struct unpack_trees_options opts;
189 struct tree_desc t;
191 if (initial_commit) {
192 discard_cache();
193 return;
196 memset(&opts, 0, sizeof(opts));
197 opts.head_idx = 1;
198 opts.index_only = 1;
199 opts.merge = 1;
201 opts.fn = oneway_merge;
202 tree = parse_tree_indirect(head_sha1);
203 if (!tree)
204 die("failed to unpack HEAD tree object");
205 parse_tree(tree);
206 init_tree_desc(&t, tree->buffer, tree->size);
207 unpack_trees(1, &t, &opts);
210 static char *prepare_index(int argc, const char **argv, const char *prefix)
212 int fd;
213 struct path_list partial;
214 const char **pathspec = NULL;
216 if (interactive) {
217 interactive_add(argc, argv, prefix);
218 commit_style = COMMIT_AS_IS;
219 return get_index_file();
222 if (read_cache() < 0)
223 die("index file corrupt");
225 if (*argv)
226 pathspec = get_pathspec(prefix, argv);
229 * Non partial, non as-is commit.
231 * (1) get the real index;
232 * (2) update the_index as necessary;
233 * (3) write the_index out to the real index (still locked);
234 * (4) return the name of the locked index file.
236 * The caller should run hooks on the locked real index, and
237 * (A) if all goes well, commit the real index;
238 * (B) on failure, rollback the real index.
240 if (all || (also && pathspec && *pathspec)) {
241 int fd = hold_locked_index(&index_lock, 1);
242 add_files_to_cache(0, also ? prefix : NULL, pathspec);
243 refresh_cache(REFRESH_QUIET);
244 if (write_cache(fd, active_cache, active_nr) ||
245 close_lock_file(&index_lock))
246 die("unable to write new_index file");
247 commit_style = COMMIT_NORMAL;
248 return index_lock.filename;
252 * As-is commit.
254 * (1) return the name of the real index file.
256 * The caller should run hooks on the real index, and run
257 * hooks on the real index, and create commit from the_index.
258 * We still need to refresh the index here.
260 if (!pathspec || !*pathspec) {
261 fd = hold_locked_index(&index_lock, 1);
262 refresh_cache(REFRESH_QUIET);
263 if (write_cache(fd, active_cache, active_nr) ||
264 commit_locked_index(&index_lock))
265 die("unable to write new_index file");
266 commit_style = COMMIT_AS_IS;
267 return get_index_file();
271 * A partial commit.
273 * (0) find the set of affected paths;
274 * (1) get lock on the real index file;
275 * (2) update the_index with the given paths;
276 * (3) write the_index out to the real index (still locked);
277 * (4) get lock on the false index file;
278 * (5) reset the_index from HEAD;
279 * (6) update the_index the same way as (2);
280 * (7) write the_index out to the false index file;
281 * (8) return the name of the false index file (still locked);
283 * The caller should run hooks on the locked false index, and
284 * create commit from it. Then
285 * (A) if all goes well, commit the real index;
286 * (B) on failure, rollback the real index;
287 * In either case, rollback the false index.
289 commit_style = COMMIT_PARTIAL;
291 if (file_exists(git_path("MERGE_HEAD")))
292 die("cannot do a partial commit during a merge.");
294 memset(&partial, 0, sizeof(partial));
295 partial.strdup_paths = 1;
296 if (list_paths(&partial, initial_commit ? NULL : "HEAD", prefix, pathspec))
297 exit(1);
299 discard_cache();
300 if (read_cache() < 0)
301 die("cannot read the index");
303 fd = hold_locked_index(&index_lock, 1);
304 add_remove_files(&partial);
305 refresh_cache(REFRESH_QUIET);
306 if (write_cache(fd, active_cache, active_nr) ||
307 close_lock_file(&index_lock))
308 die("unable to write new_index file");
310 fd = hold_lock_file_for_update(&false_lock,
311 git_path("next-index-%d", getpid()), 1);
313 create_base_index();
314 add_remove_files(&partial);
315 refresh_cache(REFRESH_QUIET);
317 if (write_cache(fd, active_cache, active_nr) ||
318 close_lock_file(&false_lock))
319 die("unable to write temporary index file");
320 return false_lock.filename;
323 static int run_status(FILE *fp, const char *index_file, const char *prefix, int nowarn)
325 struct wt_status s;
327 wt_status_prepare(&s);
328 if (wt_status_relative_paths)
329 s.prefix = prefix;
331 if (amend) {
332 s.amend = 1;
333 s.reference = "HEAD^1";
335 s.verbose = verbose;
336 s.untracked = untracked_files;
337 s.index_file = index_file;
338 s.fp = fp;
339 s.nowarn = nowarn;
341 wt_status_print(&s);
343 return s.commitable;
346 static const char sign_off_header[] = "Signed-off-by: ";
348 static int prepare_log_message(const char *index_file, const char *prefix)
350 struct stat statbuf;
351 int commitable, saved_color_setting;
352 struct strbuf sb;
353 char *buffer;
354 FILE *fp;
356 strbuf_init(&sb, 0);
357 if (message.len) {
358 strbuf_addbuf(&sb, &message);
359 } else if (logfile && !strcmp(logfile, "-")) {
360 if (isatty(0))
361 fprintf(stderr, "(reading log message from standard input)\n");
362 if (strbuf_read(&sb, 0, 0) < 0)
363 die("could not read log from standard input");
364 } else if (logfile) {
365 if (strbuf_read_file(&sb, logfile, 0) < 0)
366 die("could not read log file '%s': %s",
367 logfile, strerror(errno));
368 } else if (use_message) {
369 buffer = strstr(use_message_buffer, "\n\n");
370 if (!buffer || buffer[2] == '\0')
371 die("commit has empty message");
372 strbuf_add(&sb, buffer + 2, strlen(buffer + 2));
373 } else if (!stat(git_path("MERGE_MSG"), &statbuf)) {
374 if (strbuf_read_file(&sb, git_path("MERGE_MSG"), 0) < 0)
375 die("could not read MERGE_MSG: %s", strerror(errno));
376 } else if (!stat(git_path("SQUASH_MSG"), &statbuf)) {
377 if (strbuf_read_file(&sb, git_path("SQUASH_MSG"), 0) < 0)
378 die("could not read SQUASH_MSG: %s", strerror(errno));
379 } else if (template_file && !stat(template_file, &statbuf)) {
380 if (strbuf_read_file(&sb, template_file, 0) < 0)
381 die("could not read %s: %s",
382 template_file, strerror(errno));
385 fp = fopen(git_path(commit_editmsg), "w");
386 if (fp == NULL)
387 die("could not open %s", git_path(commit_editmsg));
389 if (cleanup_mode != CLEANUP_NONE)
390 stripspace(&sb, 0);
392 if (signoff) {
393 struct strbuf sob;
394 int i;
396 strbuf_init(&sob, 0);
397 strbuf_addstr(&sob, sign_off_header);
398 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
399 getenv("GIT_COMMITTER_EMAIL")));
400 strbuf_addch(&sob, '\n');
401 for (i = sb.len - 1; i > 0 && sb.buf[i - 1] != '\n'; i--)
402 ; /* do nothing */
403 if (prefixcmp(sb.buf + i, sob.buf)) {
404 if (prefixcmp(sb.buf + i, sign_off_header))
405 strbuf_addch(&sb, '\n');
406 strbuf_addbuf(&sb, &sob);
408 strbuf_release(&sob);
411 if (fwrite(sb.buf, 1, sb.len, fp) < sb.len)
412 die("could not write commit template: %s", strerror(errno));
414 strbuf_release(&sb);
416 if (!use_editor) {
417 struct rev_info rev;
418 unsigned char sha1[20];
419 const char *parent = "HEAD";
421 fclose(fp);
423 if (!active_nr && read_cache() < 0)
424 die("Cannot read index");
426 if (amend)
427 parent = "HEAD^1";
429 if (get_sha1(parent, sha1))
430 return !!active_nr;
432 init_revisions(&rev, "");
433 rev.abbrev = 0;
434 setup_revisions(0, NULL, &rev, parent);
435 DIFF_OPT_SET(&rev.diffopt, QUIET);
436 DIFF_OPT_SET(&rev.diffopt, EXIT_WITH_STATUS);
437 run_diff_index(&rev, 1 /* cached */);
439 return !!DIFF_OPT_TST(&rev.diffopt, HAS_CHANGES);
442 if (in_merge)
443 fprintf(fp,
444 "#\n"
445 "# It looks like you may be committing a MERGE.\n"
446 "# If this is not correct, please remove the file\n"
447 "# %s\n"
448 "# and try again.\n"
449 "#\n",
450 git_path("MERGE_HEAD"));
452 fprintf(fp,
453 "\n"
454 "# Please enter the commit message for your changes.\n"
455 "# (Comment lines starting with '#' will ");
456 if (cleanup_mode == CLEANUP_ALL)
457 fprintf(fp, "not be included)\n");
458 else /* CLEANUP_SPACE, that is. */
459 fprintf(fp, "be kept.\n"
460 "# You can remove them yourself if you want to)\n");
461 if (only_include_assumed)
462 fprintf(fp, "# %s\n", only_include_assumed);
464 saved_color_setting = wt_status_use_color;
465 wt_status_use_color = 0;
466 commitable = run_status(fp, index_file, prefix, 1);
467 wt_status_use_color = saved_color_setting;
469 fclose(fp);
471 return commitable;
475 * Find out if the message starting at position 'start' in the strbuf
476 * contains only whitespace and Signed-off-by lines.
478 static int message_is_empty(struct strbuf *sb, int start)
480 struct strbuf tmpl;
481 const char *nl;
482 int eol, i;
484 if (cleanup_mode == CLEANUP_NONE && sb->len)
485 return 0;
487 /* See if the template is just a prefix of the message. */
488 strbuf_init(&tmpl, 0);
489 if (template_file && strbuf_read_file(&tmpl, template_file, 0) > 0) {
490 stripspace(&tmpl, cleanup_mode == CLEANUP_ALL);
491 if (start + tmpl.len <= sb->len &&
492 memcmp(tmpl.buf, sb->buf + start, tmpl.len) == 0)
493 start += tmpl.len;
495 strbuf_release(&tmpl);
497 /* Check if the rest is just whitespace and Signed-of-by's. */
498 for (i = start; i < sb->len; i++) {
499 nl = memchr(sb->buf + i, '\n', sb->len - i);
500 if (nl)
501 eol = nl - sb->buf;
502 else
503 eol = sb->len;
505 if (strlen(sign_off_header) <= eol - i &&
506 !prefixcmp(sb->buf + i, sign_off_header)) {
507 i = eol;
508 continue;
510 while (i < eol)
511 if (!isspace(sb->buf[i++]))
512 return 0;
515 return 1;
518 static void determine_author_info(struct strbuf *sb)
520 char *name, *email, *date;
522 name = getenv("GIT_AUTHOR_NAME");
523 email = getenv("GIT_AUTHOR_EMAIL");
524 date = getenv("GIT_AUTHOR_DATE");
526 if (use_message) {
527 const char *a, *lb, *rb, *eol;
529 a = strstr(use_message_buffer, "\nauthor ");
530 if (!a)
531 die("invalid commit: %s", use_message);
533 lb = strstr(a + 8, " <");
534 rb = strstr(a + 8, "> ");
535 eol = strchr(a + 8, '\n');
536 if (!lb || !rb || !eol)
537 die("invalid commit: %s", use_message);
539 name = xstrndup(a + 8, lb - (a + 8));
540 email = xstrndup(lb + 2, rb - (lb + 2));
541 date = xstrndup(rb + 2, eol - (rb + 2));
544 if (force_author) {
545 const char *lb = strstr(force_author, " <");
546 const char *rb = strchr(force_author, '>');
548 if (!lb || !rb)
549 die("malformed --author parameter");
550 name = xstrndup(force_author, lb - force_author);
551 email = xstrndup(lb + 2, rb - (lb + 2));
554 strbuf_addf(sb, "author %s\n", fmt_ident(name, email, date, IDENT_ERROR_ON_NO_NAME));
557 static int parse_and_validate_options(int argc, const char *argv[],
558 const char * const usage[])
560 int f = 0;
562 argc = parse_options(argc, argv, builtin_commit_options, usage, 0);
564 if (logfile || message.len || use_message)
565 use_editor = 0;
566 if (edit_flag)
567 use_editor = 1;
569 if (get_sha1("HEAD", head_sha1))
570 initial_commit = 1;
572 if (!get_sha1("MERGE_HEAD", merge_head_sha1))
573 in_merge = 1;
575 /* Sanity check options */
576 if (amend && initial_commit)
577 die("You have nothing to amend.");
578 if (amend && in_merge)
579 die("You are in the middle of a merge -- cannot amend.");
581 if (use_message)
582 f++;
583 if (edit_message)
584 f++;
585 if (logfile)
586 f++;
587 if (f > 1)
588 die("Only one of -c/-C/-F can be used.");
589 if (message.len && f > 0)
590 die("Option -m cannot be combined with -c/-C/-F.");
591 if (edit_message)
592 use_message = edit_message;
593 if (amend && !use_message)
594 use_message = "HEAD";
595 if (use_message) {
596 unsigned char sha1[20];
597 static char utf8[] = "UTF-8";
598 const char *out_enc;
599 char *enc, *end;
600 struct commit *commit;
602 if (get_sha1(use_message, sha1))
603 die("could not lookup commit %s", use_message);
604 commit = lookup_commit_reference(sha1);
605 if (!commit || parse_commit(commit))
606 die("could not parse commit %s", use_message);
608 enc = strstr(commit->buffer, "\nencoding");
609 if (enc) {
610 end = strchr(enc + 10, '\n');
611 enc = xstrndup(enc + 10, end - (enc + 10));
612 } else {
613 enc = utf8;
615 out_enc = git_commit_encoding ? git_commit_encoding : utf8;
617 if (strcmp(out_enc, enc))
618 use_message_buffer =
619 reencode_string(commit->buffer, out_enc, enc);
622 * If we failed to reencode the buffer, just copy it
623 * byte for byte so the user can try to fix it up.
624 * This also handles the case where input and output
625 * encodings are identical.
627 if (use_message_buffer == NULL)
628 use_message_buffer = xstrdup(commit->buffer);
629 if (enc != utf8)
630 free(enc);
633 if (!!also + !!only + !!all + !!interactive > 1)
634 die("Only one of --include/--only/--all/--interactive can be used.");
635 if (argc == 0 && (also || (only && !amend)))
636 die("No paths with --include/--only does not make sense.");
637 if (argc == 0 && only && amend)
638 only_include_assumed = "Clever... amending the last one with dirty index.";
639 if (argc > 0 && !also && !only) {
640 only_include_assumed = "Explicit paths specified without -i nor -o; assuming --only paths...";
641 also = 0;
643 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
644 cleanup_mode = use_editor ? CLEANUP_ALL : CLEANUP_SPACE;
645 else if (!strcmp(cleanup_arg, "verbatim"))
646 cleanup_mode = CLEANUP_NONE;
647 else if (!strcmp(cleanup_arg, "whitespace"))
648 cleanup_mode = CLEANUP_SPACE;
649 else if (!strcmp(cleanup_arg, "strip"))
650 cleanup_mode = CLEANUP_ALL;
651 else
652 die("Invalid cleanup mode %s", cleanup_arg);
654 if (all && argc > 0)
655 die("Paths with -a does not make sense.");
656 else if (interactive && argc > 0)
657 die("Paths with --interactive does not make sense.");
659 return argc;
662 int cmd_status(int argc, const char **argv, const char *prefix)
664 const char *index_file;
665 int commitable;
667 git_config(git_status_config);
669 argc = parse_and_validate_options(argc, argv, builtin_status_usage);
671 index_file = prepare_index(argc, argv, prefix);
673 commitable = run_status(stdout, index_file, prefix, 0);
675 rollback_index_files();
677 return commitable ? 0 : 1;
680 static int run_hook(const char *index_file, const char *name, const char *arg)
682 struct child_process hook;
683 const char *argv[3], *env[2];
684 char index[PATH_MAX];
686 argv[0] = git_path("hooks/%s", name);
687 argv[1] = arg;
688 argv[2] = NULL;
689 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
690 env[0] = index;
691 env[1] = NULL;
693 if (access(argv[0], X_OK) < 0)
694 return 0;
696 memset(&hook, 0, sizeof(hook));
697 hook.argv = argv;
698 hook.no_stdin = 1;
699 hook.stdout_to_stderr = 1;
700 hook.env = env;
702 return run_command(&hook);
705 static void print_summary(const char *prefix, const unsigned char *sha1)
707 struct rev_info rev;
708 struct commit *commit;
710 commit = lookup_commit(sha1);
711 if (!commit)
712 die("couldn't look up newly created commit");
713 if (!commit || parse_commit(commit))
714 die("could not parse newly created commit");
716 init_revisions(&rev, prefix);
717 setup_revisions(0, NULL, &rev, NULL);
719 rev.abbrev = 0;
720 rev.diff = 1;
721 rev.diffopt.output_format =
722 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
724 rev.verbose_header = 1;
725 rev.show_root_diff = 1;
726 rev.commit_format = get_commit_format("format:%h: %s");
727 rev.always_show_header = 0;
728 rev.diffopt.detect_rename = 1;
729 rev.diffopt.rename_limit = 100;
730 rev.diffopt.break_opt = 0;
731 diff_setup_done(&rev.diffopt);
733 printf("Created %scommit ", initial_commit ? "initial " : "");
735 if (!log_tree_commit(&rev, commit)) {
736 struct strbuf buf = STRBUF_INIT;
737 format_commit_message(commit, "%h: %s", &buf);
738 printf("%s\n", buf.buf);
739 strbuf_release(&buf);
743 int git_commit_config(const char *k, const char *v)
745 if (!strcmp(k, "commit.template")) {
746 if (!v)
747 return config_error_nonbool(v);
748 template_file = xstrdup(v);
749 return 0;
752 return git_status_config(k, v);
755 static int is_a_merge(const unsigned char *sha1)
757 struct commit *commit = lookup_commit(sha1);
758 if (!commit || parse_commit(commit))
759 die("could not parse HEAD commit");
760 return !!(commit->parents && commit->parents->next);
763 static const char commit_utf8_warn[] =
764 "Warning: commit message does not conform to UTF-8.\n"
765 "You may want to amend it after fixing the message, or set the config\n"
766 "variable i18n.commitencoding to the encoding your project uses.\n";
768 static void add_parent(struct strbuf *sb, const unsigned char *sha1)
770 struct object *obj = parse_object(sha1);
771 const char *parent = sha1_to_hex(sha1);
772 if (!obj)
773 die("Unable to find commit parent %s", parent);
774 if (obj->type != OBJ_COMMIT)
775 die("Parent %s isn't a proper commit", parent);
776 strbuf_addf(sb, "parent %s\n", parent);
779 int cmd_commit(int argc, const char **argv, const char *prefix)
781 int header_len;
782 struct strbuf sb;
783 const char *index_file, *reflog_msg;
784 char *nl, *p;
785 unsigned char commit_sha1[20];
786 struct ref_lock *ref_lock;
788 git_config(git_commit_config);
790 argc = parse_and_validate_options(argc, argv, builtin_commit_usage);
792 index_file = prepare_index(argc, argv, prefix);
794 if (!no_verify && run_hook(index_file, "pre-commit", NULL)) {
795 rollback_index_files();
796 return 1;
799 if (!prepare_log_message(index_file, prefix) && !in_merge &&
800 !allow_empty && !(amend && is_a_merge(head_sha1))) {
801 run_status(stdout, index_file, prefix, 0);
802 rollback_index_files();
803 unlink(commit_editmsg);
804 return 1;
808 * Re-read the index as pre-commit hook could have updated it,
809 * and write it out as a tree.
811 discard_cache();
812 read_cache_from(index_file);
813 if (!active_cache_tree)
814 active_cache_tree = cache_tree();
815 if (cache_tree_update(active_cache_tree,
816 active_cache, active_nr, 0, 0) < 0) {
817 rollback_index_files();
818 die("Error building trees");
822 * The commit object
824 strbuf_init(&sb, 0);
825 strbuf_addf(&sb, "tree %s\n",
826 sha1_to_hex(active_cache_tree->sha1));
828 /* Determine parents */
829 if (initial_commit) {
830 reflog_msg = "commit (initial)";
831 } else if (amend) {
832 struct commit_list *c;
833 struct commit *commit;
835 reflog_msg = "commit (amend)";
836 commit = lookup_commit(head_sha1);
837 if (!commit || parse_commit(commit))
838 die("could not parse HEAD commit");
840 for (c = commit->parents; c; c = c->next)
841 add_parent(&sb, c->item->object.sha1);
842 } else if (in_merge) {
843 struct strbuf m;
844 FILE *fp;
846 reflog_msg = "commit (merge)";
847 add_parent(&sb, head_sha1);
848 strbuf_init(&m, 0);
849 fp = fopen(git_path("MERGE_HEAD"), "r");
850 if (fp == NULL)
851 die("could not open %s for reading: %s",
852 git_path("MERGE_HEAD"), strerror(errno));
853 while (strbuf_getline(&m, fp, '\n') != EOF) {
854 unsigned char sha1[20];
855 if (get_sha1_hex(m.buf, sha1) < 0)
856 die("Corrupt MERGE_HEAD file (%s)", m.buf);
857 add_parent(&sb, sha1);
859 fclose(fp);
860 strbuf_release(&m);
861 } else {
862 reflog_msg = "commit";
863 strbuf_addf(&sb, "parent %s\n", sha1_to_hex(head_sha1));
866 determine_author_info(&sb);
867 strbuf_addf(&sb, "committer %s\n", git_committer_info(IDENT_ERROR_ON_NO_NAME));
868 if (!is_encoding_utf8(git_commit_encoding))
869 strbuf_addf(&sb, "encoding %s\n", git_commit_encoding);
870 strbuf_addch(&sb, '\n');
872 /* Get the commit message and validate it */
873 header_len = sb.len;
874 if (use_editor) {
875 char index[PATH_MAX];
876 const char *env[2] = { index, NULL };
877 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
878 launch_editor(git_path(commit_editmsg), NULL, env);
880 if (!no_verify &&
881 run_hook(index_file, "commit-msg", git_path(commit_editmsg))) {
882 rollback_index_files();
883 exit(1);
885 if (strbuf_read_file(&sb, git_path(commit_editmsg), 0) < 0) {
886 rollback_index_files();
887 die("could not read commit message");
890 /* Truncate the message just before the diff, if any. */
891 p = strstr(sb.buf, "\ndiff --git a/");
892 if (p != NULL)
893 strbuf_setlen(&sb, p - sb.buf + 1);
895 if (cleanup_mode != CLEANUP_NONE)
896 stripspace(&sb, cleanup_mode == CLEANUP_ALL);
897 if (sb.len < header_len || message_is_empty(&sb, header_len)) {
898 rollback_index_files();
899 die("no commit message? aborting commit.");
901 strbuf_addch(&sb, '\0');
902 if (is_encoding_utf8(git_commit_encoding) && !is_utf8(sb.buf))
903 fprintf(stderr, commit_utf8_warn);
905 if (write_sha1_file(sb.buf, sb.len - 1, commit_type, commit_sha1)) {
906 rollback_index_files();
907 die("failed to write commit object");
910 ref_lock = lock_any_ref_for_update("HEAD",
911 initial_commit ? NULL : head_sha1,
914 nl = strchr(sb.buf + header_len, '\n');
915 if (nl)
916 strbuf_setlen(&sb, nl + 1 - sb.buf);
917 else
918 strbuf_addch(&sb, '\n');
919 strbuf_remove(&sb, 0, header_len);
920 strbuf_insert(&sb, 0, reflog_msg, strlen(reflog_msg));
921 strbuf_insert(&sb, strlen(reflog_msg), ": ", 2);
923 if (!ref_lock) {
924 rollback_index_files();
925 die("cannot lock HEAD ref");
927 if (write_ref_sha1(ref_lock, commit_sha1, sb.buf) < 0) {
928 rollback_index_files();
929 die("cannot update HEAD ref");
932 unlink(git_path("MERGE_HEAD"));
933 unlink(git_path("MERGE_MSG"));
934 unlink(git_path("SQUASH_MSG"));
936 if (commit_index_files())
937 die ("Repository has been updated, but unable to write\n"
938 "new_index file. Check that disk is not full or quota is\n"
939 "not exceeded, and then \"git reset HEAD\" to recover.");
941 rerere();
942 run_hook(get_index_file(), "post-commit", NULL);
943 if (!quiet)
944 print_summary(prefix, commit_sha1);
946 return 0;