gitweb: Use @diff_opts while using format-patch
[git/debian.git] / builtin / commit.c
blob017b8a5536804a4689aea0059f4d26467ad852af
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 "color.h"
11 #include "dir.h"
12 #include "builtin.h"
13 #include "diff.h"
14 #include "diffcore.h"
15 #include "commit.h"
16 #include "revision.h"
17 #include "wt-status.h"
18 #include "run-command.h"
19 #include "refs.h"
20 #include "log-tree.h"
21 #include "strbuf.h"
22 #include "utf8.h"
23 #include "parse-options.h"
24 #include "string-list.h"
25 #include "rerere.h"
26 #include "unpack-trees.h"
27 #include "quote.h"
29 static const char * const builtin_commit_usage[] = {
30 "git commit [options] [--] <filepattern>...",
31 NULL
34 static const char * const builtin_status_usage[] = {
35 "git status [options] [--] <filepattern>...",
36 NULL
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"
43 "\n"
44 " git config --global user.name \"Your Name\"\n"
45 " git config --global user.email you@example.com\n"
46 "\n"
47 "If the identity used for this commit is wrong, you can fix it with:\n"
48 "\n"
49 " git commit --amend --author='Your Name <you@example.com>'\n";
51 static unsigned char head_sha1[20];
53 static char *use_message_buffer;
54 static const char commit_editmsg[] = "COMMIT_EDITMSG";
55 static struct lock_file index_lock; /* real index */
56 static struct lock_file false_lock; /* used only for partial commits */
57 static enum {
58 COMMIT_AS_IS = 1,
59 COMMIT_NORMAL,
60 COMMIT_PARTIAL,
61 } commit_style;
63 static const char *logfile, *force_author;
64 static const char *template_file;
65 static char *edit_message, *use_message;
66 static char *author_name, *author_email, *author_date;
67 static int all, edit_flag, also, interactive, only, amend, signoff;
68 static int quiet, verbose, no_verify, allow_empty, dry_run, renew_authorship;
69 static int no_post_rewrite, allow_empty_message;
70 static char *untracked_files_arg, *force_date;
72 * The default commit message cleanup mode will remove the lines
73 * beginning with # (shell comments) and leading and trailing
74 * whitespaces (empty lines or containing only whitespaces)
75 * if editor is used, and only the whitespaces if the message
76 * is specified explicitly.
78 static enum {
79 CLEANUP_SPACE,
80 CLEANUP_NONE,
81 CLEANUP_ALL,
82 } cleanup_mode;
83 static char *cleanup_arg;
85 static int use_editor = 1, initial_commit, in_merge, include_status = 1;
86 static const char *only_include_assumed;
87 static struct strbuf message;
89 static int null_termination;
90 static enum {
91 STATUS_FORMAT_LONG,
92 STATUS_FORMAT_SHORT,
93 STATUS_FORMAT_PORCELAIN,
94 } status_format = STATUS_FORMAT_LONG;
96 static int opt_parse_m(const struct option *opt, const char *arg, int unset)
98 struct strbuf *buf = opt->value;
99 if (unset)
100 strbuf_setlen(buf, 0);
101 else {
102 strbuf_addstr(buf, arg);
103 strbuf_addstr(buf, "\n\n");
105 return 0;
108 static struct option builtin_commit_options[] = {
109 OPT__QUIET(&quiet),
110 OPT__VERBOSE(&verbose),
112 OPT_GROUP("Commit message options"),
113 OPT_FILENAME('F', "file", &logfile, "read log from file"),
114 OPT_STRING(0, "author", &force_author, "AUTHOR", "override author for commit"),
115 OPT_STRING(0, "date", &force_date, "DATE", "override date for commit"),
116 OPT_CALLBACK('m', "message", &message, "MESSAGE", "specify commit message", opt_parse_m),
117 OPT_STRING('c', "reedit-message", &edit_message, "COMMIT", "reuse and edit message from specified commit"),
118 OPT_STRING('C', "reuse-message", &use_message, "COMMIT", "reuse message from specified commit"),
119 OPT_BOOLEAN(0, "reset-author", &renew_authorship, "the commit is authored by me now (used with -C-c/--amend)"),
120 OPT_BOOLEAN('s', "signoff", &signoff, "add Signed-off-by:"),
121 OPT_FILENAME('t', "template", &template_file, "use specified template file"),
122 OPT_BOOLEAN('e', "edit", &edit_flag, "force edit of commit"),
123 OPT_STRING(0, "cleanup", &cleanup_arg, "default", "how to strip spaces and #comments from message"),
124 OPT_BOOLEAN(0, "status", &include_status, "include status in commit message template"),
125 /* end commit message options */
127 OPT_GROUP("Commit contents options"),
128 OPT_BOOLEAN('a', "all", &all, "commit all changed files"),
129 OPT_BOOLEAN('i', "include", &also, "add specified files to index for commit"),
130 OPT_BOOLEAN(0, "interactive", &interactive, "interactively add files"),
131 OPT_BOOLEAN('o', "only", &only, "commit only specified files"),
132 OPT_BOOLEAN('n', "no-verify", &no_verify, "bypass pre-commit hook"),
133 OPT_BOOLEAN(0, "dry-run", &dry_run, "show what would be committed"),
134 OPT_SET_INT(0, "short", &status_format, "show status concisely",
135 STATUS_FORMAT_SHORT),
136 OPT_SET_INT(0, "porcelain", &status_format,
137 "show porcelain output format", STATUS_FORMAT_PORCELAIN),
138 OPT_BOOLEAN('z', "null", &null_termination,
139 "terminate entries with NUL"),
140 OPT_BOOLEAN(0, "amend", &amend, "amend previous commit"),
141 OPT_BOOLEAN(0, "no-post-rewrite", &no_post_rewrite, "bypass post-rewrite hook"),
142 { 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" },
143 /* end commit contents options */
145 { OPTION_BOOLEAN, 0, "allow-empty", &allow_empty, NULL,
146 "ok to record an empty change",
147 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN },
148 { OPTION_BOOLEAN, 0, "allow-empty-message", &allow_empty_message, NULL,
149 "ok to record a change with an empty message",
150 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN },
152 OPT_END()
155 static void rollback_index_files(void)
157 switch (commit_style) {
158 case COMMIT_AS_IS:
159 break; /* nothing to do */
160 case COMMIT_NORMAL:
161 rollback_lock_file(&index_lock);
162 break;
163 case COMMIT_PARTIAL:
164 rollback_lock_file(&index_lock);
165 rollback_lock_file(&false_lock);
166 break;
170 static int commit_index_files(void)
172 int err = 0;
174 switch (commit_style) {
175 case COMMIT_AS_IS:
176 break; /* nothing to do */
177 case COMMIT_NORMAL:
178 err = commit_lock_file(&index_lock);
179 break;
180 case COMMIT_PARTIAL:
181 err = commit_lock_file(&index_lock);
182 rollback_lock_file(&false_lock);
183 break;
186 return err;
190 * Take a union of paths in the index and the named tree (typically, "HEAD"),
191 * and return the paths that match the given pattern in list.
193 static int list_paths(struct string_list *list, const char *with_tree,
194 const char *prefix, const char **pattern)
196 int i;
197 char *m;
199 for (i = 0; pattern[i]; i++)
201 m = xcalloc(1, i);
203 if (with_tree)
204 overlay_tree_on_cache(with_tree, prefix);
206 for (i = 0; i < active_nr; i++) {
207 struct cache_entry *ce = active_cache[i];
208 struct string_list_item *item;
210 if (ce->ce_flags & CE_UPDATE)
211 continue;
212 if (!match_pathspec(pattern, ce->name, ce_namelen(ce), 0, m))
213 continue;
214 item = string_list_insert(ce->name, list);
215 if (ce_skip_worktree(ce))
216 item->util = item; /* better a valid pointer than a fake one */
219 return report_path_error(m, pattern, prefix ? strlen(prefix) : 0);
222 static void add_remove_files(struct string_list *list)
224 int i;
225 for (i = 0; i < list->nr; i++) {
226 struct stat st;
227 struct string_list_item *p = &(list->items[i]);
229 /* p->util is skip-worktree */
230 if (p->util)
231 continue;
233 if (!lstat(p->string, &st)) {
234 if (add_to_cache(p->string, &st, 0))
235 die("updating files failed");
236 } else
237 remove_file_from_cache(p->string);
241 static void create_base_index(void)
243 struct tree *tree;
244 struct unpack_trees_options opts;
245 struct tree_desc t;
247 if (initial_commit) {
248 discard_cache();
249 return;
252 memset(&opts, 0, sizeof(opts));
253 opts.head_idx = 1;
254 opts.index_only = 1;
255 opts.merge = 1;
256 opts.src_index = &the_index;
257 opts.dst_index = &the_index;
259 opts.fn = oneway_merge;
260 tree = parse_tree_indirect(head_sha1);
261 if (!tree)
262 die("failed to unpack HEAD tree object");
263 parse_tree(tree);
264 init_tree_desc(&t, tree->buffer, tree->size);
265 if (unpack_trees(1, &t, &opts))
266 exit(128); /* We've already reported the error, finish dying */
269 static void refresh_cache_or_die(int refresh_flags)
272 * refresh_flags contains REFRESH_QUIET, so the only errors
273 * are for unmerged entries.
275 if (refresh_cache(refresh_flags | REFRESH_IN_PORCELAIN))
276 die_resolve_conflict("commit");
279 static char *prepare_index(int argc, const char **argv, const char *prefix, int is_status)
281 int fd;
282 struct string_list partial;
283 const char **pathspec = NULL;
284 int refresh_flags = REFRESH_QUIET;
286 if (is_status)
287 refresh_flags |= REFRESH_UNMERGED;
288 if (interactive) {
289 if (interactive_add(argc, argv, prefix) != 0)
290 die("interactive add failed");
291 if (read_cache_preload(NULL) < 0)
292 die("index file corrupt");
293 commit_style = COMMIT_AS_IS;
294 return get_index_file();
297 if (*argv)
298 pathspec = get_pathspec(prefix, argv);
300 if (read_cache_preload(pathspec) < 0)
301 die("index file corrupt");
304 * Non partial, non as-is commit.
306 * (1) get the real index;
307 * (2) update the_index as necessary;
308 * (3) write the_index out to the real index (still locked);
309 * (4) return the name of the locked index file.
311 * The caller should run hooks on the locked real index, and
312 * (A) if all goes well, commit the real index;
313 * (B) on failure, rollback the real index.
315 if (all || (also && pathspec && *pathspec)) {
316 fd = hold_locked_index(&index_lock, 1);
317 add_files_to_cache(also ? prefix : NULL, pathspec, 0);
318 refresh_cache_or_die(refresh_flags);
319 if (write_cache(fd, active_cache, active_nr) ||
320 close_lock_file(&index_lock))
321 die("unable to write new_index file");
322 commit_style = COMMIT_NORMAL;
323 return index_lock.filename;
327 * As-is commit.
329 * (1) return the name of the real index file.
331 * The caller should run hooks on the real index,
332 * and create commit from the_index.
333 * We still need to refresh the index here.
335 if (!pathspec || !*pathspec) {
336 fd = hold_locked_index(&index_lock, 1);
337 refresh_cache_or_die(refresh_flags);
338 if (write_cache(fd, active_cache, active_nr) ||
339 commit_locked_index(&index_lock))
340 die("unable to write new_index file");
341 commit_style = COMMIT_AS_IS;
342 return get_index_file();
346 * A partial commit.
348 * (0) find the set of affected paths;
349 * (1) get lock on the real index file;
350 * (2) update the_index with the given paths;
351 * (3) write the_index out to the real index (still locked);
352 * (4) get lock on the false index file;
353 * (5) reset the_index from HEAD;
354 * (6) update the_index the same way as (2);
355 * (7) write the_index out to the false index file;
356 * (8) return the name of the false index file (still locked);
358 * The caller should run hooks on the locked false index, and
359 * create commit from it. Then
360 * (A) if all goes well, commit the real index;
361 * (B) on failure, rollback the real index;
362 * In either case, rollback the false index.
364 commit_style = COMMIT_PARTIAL;
366 if (in_merge)
367 die("cannot do a partial commit during a merge.");
369 memset(&partial, 0, sizeof(partial));
370 partial.strdup_strings = 1;
371 if (list_paths(&partial, initial_commit ? NULL : "HEAD", prefix, pathspec))
372 exit(1);
374 discard_cache();
375 if (read_cache() < 0)
376 die("cannot read the index");
378 fd = hold_locked_index(&index_lock, 1);
379 add_remove_files(&partial);
380 refresh_cache(REFRESH_QUIET);
381 if (write_cache(fd, active_cache, active_nr) ||
382 close_lock_file(&index_lock))
383 die("unable to write new_index file");
385 fd = hold_lock_file_for_update(&false_lock,
386 git_path("next-index-%"PRIuMAX,
387 (uintmax_t) getpid()),
388 LOCK_DIE_ON_ERROR);
390 create_base_index();
391 add_remove_files(&partial);
392 refresh_cache(REFRESH_QUIET);
394 if (write_cache(fd, active_cache, active_nr) ||
395 close_lock_file(&false_lock))
396 die("unable to write temporary index file");
398 discard_cache();
399 read_cache_from(false_lock.filename);
401 return false_lock.filename;
404 static int run_status(FILE *fp, const char *index_file, const char *prefix, int nowarn,
405 struct wt_status *s)
407 unsigned char sha1[20];
409 if (s->relative_paths)
410 s->prefix = prefix;
412 if (amend) {
413 s->amend = 1;
414 s->reference = "HEAD^1";
416 s->verbose = verbose;
417 s->index_file = index_file;
418 s->fp = fp;
419 s->nowarn = nowarn;
420 s->is_initial = get_sha1(s->reference, sha1) ? 1 : 0;
422 wt_status_collect(s);
424 switch (status_format) {
425 case STATUS_FORMAT_SHORT:
426 wt_shortstatus_print(s, null_termination);
427 break;
428 case STATUS_FORMAT_PORCELAIN:
429 wt_porcelain_print(s, null_termination);
430 break;
431 case STATUS_FORMAT_LONG:
432 wt_status_print(s);
433 break;
436 return s->commitable;
439 static int is_a_merge(const unsigned char *sha1)
441 struct commit *commit = lookup_commit(sha1);
442 if (!commit || parse_commit(commit))
443 die("could not parse HEAD commit");
444 return !!(commit->parents && commit->parents->next);
447 static const char sign_off_header[] = "Signed-off-by: ";
449 static void determine_author_info(void)
451 char *name, *email, *date;
453 name = getenv("GIT_AUTHOR_NAME");
454 email = getenv("GIT_AUTHOR_EMAIL");
455 date = getenv("GIT_AUTHOR_DATE");
457 if (use_message && !renew_authorship) {
458 const char *a, *lb, *rb, *eol;
460 a = strstr(use_message_buffer, "\nauthor ");
461 if (!a)
462 die("invalid commit: %s", use_message);
464 lb = strstr(a + 8, " <");
465 rb = strstr(a + 8, "> ");
466 eol = strchr(a + 8, '\n');
467 if (!lb || !rb || !eol)
468 die("invalid commit: %s", use_message);
470 name = xstrndup(a + 8, lb - (a + 8));
471 email = xstrndup(lb + 2, rb - (lb + 2));
472 date = xstrndup(rb + 2, eol - (rb + 2));
475 if (force_author) {
476 const char *lb = strstr(force_author, " <");
477 const char *rb = strchr(force_author, '>');
479 if (!lb || !rb)
480 die("malformed --author parameter");
481 name = xstrndup(force_author, lb - force_author);
482 email = xstrndup(lb + 2, rb - (lb + 2));
485 if (force_date)
486 date = force_date;
488 author_name = name;
489 author_email = email;
490 author_date = date;
493 static int ends_rfc2822_footer(struct strbuf *sb)
495 int ch;
496 int hit = 0;
497 int i, j, k;
498 int len = sb->len;
499 int first = 1;
500 const char *buf = sb->buf;
502 for (i = len - 1; i > 0; i--) {
503 if (hit && buf[i] == '\n')
504 break;
505 hit = (buf[i] == '\n');
508 while (i < len - 1 && buf[i] == '\n')
509 i++;
511 for (; i < len; i = k) {
512 for (k = i; k < len && buf[k] != '\n'; k++)
513 ; /* do nothing */
514 k++;
516 if ((buf[k] == ' ' || buf[k] == '\t') && !first)
517 continue;
519 first = 0;
521 for (j = 0; i + j < len; j++) {
522 ch = buf[i + j];
523 if (ch == ':')
524 break;
525 if (isalnum(ch) ||
526 (ch == '-'))
527 continue;
528 return 0;
531 return 1;
534 static int prepare_to_commit(const char *index_file, const char *prefix,
535 struct wt_status *s)
537 struct stat statbuf;
538 int commitable, saved_color_setting;
539 struct strbuf sb = STRBUF_INIT;
540 char *buffer;
541 FILE *fp;
542 const char *hook_arg1 = NULL;
543 const char *hook_arg2 = NULL;
544 int ident_shown = 0;
546 if (!no_verify && run_hook(index_file, "pre-commit", NULL))
547 return 0;
549 if (message.len) {
550 strbuf_addbuf(&sb, &message);
551 hook_arg1 = "message";
552 } else if (logfile && !strcmp(logfile, "-")) {
553 if (isatty(0))
554 fprintf(stderr, "(reading log message from standard input)\n");
555 if (strbuf_read(&sb, 0, 0) < 0)
556 die_errno("could not read log from standard input");
557 hook_arg1 = "message";
558 } else if (logfile) {
559 if (strbuf_read_file(&sb, logfile, 0) < 0)
560 die_errno("could not read log file '%s'",
561 logfile);
562 hook_arg1 = "message";
563 } else if (use_message) {
564 buffer = strstr(use_message_buffer, "\n\n");
565 if (!buffer || buffer[2] == '\0')
566 die("commit has empty message");
567 strbuf_add(&sb, buffer + 2, strlen(buffer + 2));
568 hook_arg1 = "commit";
569 hook_arg2 = use_message;
570 } else if (!stat(git_path("MERGE_MSG"), &statbuf)) {
571 if (strbuf_read_file(&sb, git_path("MERGE_MSG"), 0) < 0)
572 die_errno("could not read MERGE_MSG");
573 hook_arg1 = "merge";
574 } else if (!stat(git_path("SQUASH_MSG"), &statbuf)) {
575 if (strbuf_read_file(&sb, git_path("SQUASH_MSG"), 0) < 0)
576 die_errno("could not read SQUASH_MSG");
577 hook_arg1 = "squash";
578 } else if (template_file && !stat(template_file, &statbuf)) {
579 if (strbuf_read_file(&sb, template_file, 0) < 0)
580 die_errno("could not read '%s'", template_file);
581 hook_arg1 = "template";
585 * This final case does not modify the template message,
586 * it just sets the argument to the prepare-commit-msg hook.
588 else if (in_merge)
589 hook_arg1 = "merge";
591 fp = fopen(git_path(commit_editmsg), "w");
592 if (fp == NULL)
593 die_errno("could not open '%s'", git_path(commit_editmsg));
595 if (cleanup_mode != CLEANUP_NONE)
596 stripspace(&sb, 0);
598 if (signoff) {
599 struct strbuf sob = STRBUF_INIT;
600 int i;
602 strbuf_addstr(&sob, sign_off_header);
603 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
604 getenv("GIT_COMMITTER_EMAIL")));
605 strbuf_addch(&sob, '\n');
606 for (i = sb.len - 1; i > 0 && sb.buf[i - 1] != '\n'; i--)
607 ; /* do nothing */
608 if (prefixcmp(sb.buf + i, sob.buf)) {
609 if (!i || !ends_rfc2822_footer(&sb))
610 strbuf_addch(&sb, '\n');
611 strbuf_addbuf(&sb, &sob);
613 strbuf_release(&sob);
616 if (fwrite(sb.buf, 1, sb.len, fp) < sb.len)
617 die_errno("could not write commit template");
619 strbuf_release(&sb);
621 determine_author_info();
623 /* This checks if committer ident is explicitly given */
624 git_committer_info(0);
625 if (use_editor && include_status) {
626 char *author_ident;
627 const char *committer_ident;
629 if (in_merge)
630 fprintf(fp,
631 "#\n"
632 "# It looks like you may be committing a MERGE.\n"
633 "# If this is not correct, please remove the file\n"
634 "# %s\n"
635 "# and try again.\n"
636 "#\n",
637 git_path("MERGE_HEAD"));
639 fprintf(fp,
640 "\n"
641 "# Please enter the commit message for your changes.");
642 if (cleanup_mode == CLEANUP_ALL)
643 fprintf(fp,
644 " Lines starting\n"
645 "# with '#' will be ignored, and an empty"
646 " message aborts the commit.\n");
647 else /* CLEANUP_SPACE, that is. */
648 fprintf(fp,
649 " Lines starting\n"
650 "# with '#' will be kept; you may remove them"
651 " yourself if you want to.\n"
652 "# An empty message aborts the commit.\n");
653 if (only_include_assumed)
654 fprintf(fp, "# %s\n", only_include_assumed);
656 author_ident = xstrdup(fmt_name(author_name, author_email));
657 committer_ident = fmt_name(getenv("GIT_COMMITTER_NAME"),
658 getenv("GIT_COMMITTER_EMAIL"));
659 if (strcmp(author_ident, committer_ident))
660 fprintf(fp,
661 "%s"
662 "# Author: %s\n",
663 ident_shown++ ? "" : "#\n",
664 author_ident);
665 free(author_ident);
667 if (!user_ident_sufficiently_given())
668 fprintf(fp,
669 "%s"
670 "# Committer: %s\n",
671 ident_shown++ ? "" : "#\n",
672 committer_ident);
674 if (ident_shown)
675 fprintf(fp, "#\n");
677 saved_color_setting = s->use_color;
678 s->use_color = 0;
679 commitable = run_status(fp, index_file, prefix, 1, s);
680 s->use_color = saved_color_setting;
681 } else {
682 unsigned char sha1[20];
683 const char *parent = "HEAD";
685 if (!active_nr && read_cache() < 0)
686 die("Cannot read index");
688 if (amend)
689 parent = "HEAD^1";
691 if (get_sha1(parent, sha1))
692 commitable = !!active_nr;
693 else
694 commitable = index_differs_from(parent, 0);
697 fclose(fp);
699 if (!commitable && !in_merge && !allow_empty &&
700 !(amend && is_a_merge(head_sha1))) {
701 run_status(stdout, index_file, prefix, 0, s);
702 return 0;
706 * Re-read the index as pre-commit hook could have updated it,
707 * and write it out as a tree. We must do this before we invoke
708 * the editor and after we invoke run_status above.
710 discard_cache();
711 read_cache_from(index_file);
712 if (!active_cache_tree)
713 active_cache_tree = cache_tree();
714 if (cache_tree_update(active_cache_tree,
715 active_cache, active_nr, 0, 0) < 0) {
716 error("Error building trees");
717 return 0;
720 if (run_hook(index_file, "prepare-commit-msg",
721 git_path(commit_editmsg), hook_arg1, hook_arg2, NULL))
722 return 0;
724 if (use_editor) {
725 char index[PATH_MAX];
726 const char *env[2] = { index, NULL };
727 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
728 if (launch_editor(git_path(commit_editmsg), NULL, env)) {
729 fprintf(stderr,
730 "Please supply the message using either -m or -F option.\n");
731 exit(1);
735 if (!no_verify &&
736 run_hook(index_file, "commit-msg", git_path(commit_editmsg), NULL)) {
737 return 0;
740 return 1;
744 * Find out if the message in the strbuf contains only whitespace and
745 * Signed-off-by lines.
747 static int message_is_empty(struct strbuf *sb)
749 struct strbuf tmpl = STRBUF_INIT;
750 const char *nl;
751 int eol, i, start = 0;
753 if (cleanup_mode == CLEANUP_NONE && sb->len)
754 return 0;
756 /* See if the template is just a prefix of the message. */
757 if (template_file && strbuf_read_file(&tmpl, template_file, 0) > 0) {
758 stripspace(&tmpl, cleanup_mode == CLEANUP_ALL);
759 if (start + tmpl.len <= sb->len &&
760 memcmp(tmpl.buf, sb->buf + start, tmpl.len) == 0)
761 start += tmpl.len;
763 strbuf_release(&tmpl);
765 /* Check if the rest is just whitespace and Signed-of-by's. */
766 for (i = start; i < sb->len; i++) {
767 nl = memchr(sb->buf + i, '\n', sb->len - i);
768 if (nl)
769 eol = nl - sb->buf;
770 else
771 eol = sb->len;
773 if (strlen(sign_off_header) <= eol - i &&
774 !prefixcmp(sb->buf + i, sign_off_header)) {
775 i = eol;
776 continue;
778 while (i < eol)
779 if (!isspace(sb->buf[i++]))
780 return 0;
783 return 1;
786 static const char *find_author_by_nickname(const char *name)
788 struct rev_info revs;
789 struct commit *commit;
790 struct strbuf buf = STRBUF_INIT;
791 const char *av[20];
792 int ac = 0;
794 init_revisions(&revs, NULL);
795 strbuf_addf(&buf, "--author=%s", name);
796 av[++ac] = "--all";
797 av[++ac] = "-i";
798 av[++ac] = buf.buf;
799 av[++ac] = NULL;
800 setup_revisions(ac, av, &revs, NULL);
801 prepare_revision_walk(&revs);
802 commit = get_revision(&revs);
803 if (commit) {
804 struct pretty_print_context ctx = {0};
805 ctx.date_mode = DATE_NORMAL;
806 strbuf_release(&buf);
807 format_commit_message(commit, "%an <%ae>", &buf, &ctx);
808 return strbuf_detach(&buf, NULL);
810 die("No existing author found with '%s'", name);
814 static void handle_untracked_files_arg(struct wt_status *s)
816 if (!untracked_files_arg)
817 ; /* default already initialized */
818 else if (!strcmp(untracked_files_arg, "no"))
819 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
820 else if (!strcmp(untracked_files_arg, "normal"))
821 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
822 else if (!strcmp(untracked_files_arg, "all"))
823 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
824 else
825 die("Invalid untracked files mode '%s'", untracked_files_arg);
828 static int parse_and_validate_options(int argc, const char *argv[],
829 const char * const usage[],
830 const char *prefix,
831 struct wt_status *s)
833 int f = 0;
835 argc = parse_options(argc, argv, prefix, builtin_commit_options, usage,
838 if (force_author && !strchr(force_author, '>'))
839 force_author = find_author_by_nickname(force_author);
841 if (force_author && renew_authorship)
842 die("Using both --reset-author and --author does not make sense");
844 if (logfile || message.len || use_message)
845 use_editor = 0;
846 if (edit_flag)
847 use_editor = 1;
848 if (!use_editor)
849 setenv("GIT_EDITOR", ":", 1);
851 if (get_sha1("HEAD", head_sha1))
852 initial_commit = 1;
854 /* Sanity check options */
855 if (amend && initial_commit)
856 die("You have nothing to amend.");
857 if (amend && in_merge)
858 die("You are in the middle of a merge -- cannot amend.");
860 if (use_message)
861 f++;
862 if (edit_message)
863 f++;
864 if (logfile)
865 f++;
866 if (f > 1)
867 die("Only one of -c/-C/-F can be used.");
868 if (message.len && f > 0)
869 die("Option -m cannot be combined with -c/-C/-F.");
870 if (edit_message)
871 use_message = edit_message;
872 if (amend && !use_message)
873 use_message = "HEAD";
874 if (!use_message && renew_authorship)
875 die("--reset-author can be used only with -C, -c or --amend.");
876 if (use_message) {
877 unsigned char sha1[20];
878 static char utf8[] = "UTF-8";
879 const char *out_enc;
880 char *enc, *end;
881 struct commit *commit;
883 if (get_sha1(use_message, sha1))
884 die("could not lookup commit %s", use_message);
885 commit = lookup_commit_reference(sha1);
886 if (!commit || parse_commit(commit))
887 die("could not parse commit %s", use_message);
889 enc = strstr(commit->buffer, "\nencoding");
890 if (enc) {
891 end = strchr(enc + 10, '\n');
892 enc = xstrndup(enc + 10, end - (enc + 10));
893 } else {
894 enc = utf8;
896 out_enc = git_commit_encoding ? git_commit_encoding : utf8;
898 if (strcmp(out_enc, enc))
899 use_message_buffer =
900 reencode_string(commit->buffer, out_enc, enc);
903 * If we failed to reencode the buffer, just copy it
904 * byte for byte so the user can try to fix it up.
905 * This also handles the case where input and output
906 * encodings are identical.
908 if (use_message_buffer == NULL)
909 use_message_buffer = xstrdup(commit->buffer);
910 if (enc != utf8)
911 free(enc);
914 if (!!also + !!only + !!all + !!interactive > 1)
915 die("Only one of --include/--only/--all/--interactive can be used.");
916 if (argc == 0 && (also || (only && !amend)))
917 die("No paths with --include/--only does not make sense.");
918 if (argc == 0 && only && amend)
919 only_include_assumed = "Clever... amending the last one with dirty index.";
920 if (argc > 0 && !also && !only)
921 only_include_assumed = "Explicit paths specified without -i nor -o; assuming --only paths...";
922 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
923 cleanup_mode = use_editor ? CLEANUP_ALL : CLEANUP_SPACE;
924 else if (!strcmp(cleanup_arg, "verbatim"))
925 cleanup_mode = CLEANUP_NONE;
926 else if (!strcmp(cleanup_arg, "whitespace"))
927 cleanup_mode = CLEANUP_SPACE;
928 else if (!strcmp(cleanup_arg, "strip"))
929 cleanup_mode = CLEANUP_ALL;
930 else
931 die("Invalid cleanup mode %s", cleanup_arg);
933 handle_untracked_files_arg(s);
935 if (all && argc > 0)
936 die("Paths with -a does not make sense.");
937 else if (interactive && argc > 0)
938 die("Paths with --interactive does not make sense.");
940 if (null_termination && status_format == STATUS_FORMAT_LONG)
941 status_format = STATUS_FORMAT_PORCELAIN;
942 if (status_format != STATUS_FORMAT_LONG)
943 dry_run = 1;
945 return argc;
948 static int dry_run_commit(int argc, const char **argv, const char *prefix,
949 struct wt_status *s)
951 int commitable;
952 const char *index_file;
954 index_file = prepare_index(argc, argv, prefix, 1);
955 commitable = run_status(stdout, index_file, prefix, 0, s);
956 rollback_index_files();
958 return commitable ? 0 : 1;
961 static int parse_status_slot(const char *var, int offset)
963 if (!strcasecmp(var+offset, "header"))
964 return WT_STATUS_HEADER;
965 if (!strcasecmp(var+offset, "updated")
966 || !strcasecmp(var+offset, "added"))
967 return WT_STATUS_UPDATED;
968 if (!strcasecmp(var+offset, "changed"))
969 return WT_STATUS_CHANGED;
970 if (!strcasecmp(var+offset, "untracked"))
971 return WT_STATUS_UNTRACKED;
972 if (!strcasecmp(var+offset, "nobranch"))
973 return WT_STATUS_NOBRANCH;
974 if (!strcasecmp(var+offset, "unmerged"))
975 return WT_STATUS_UNMERGED;
976 return -1;
979 static int git_status_config(const char *k, const char *v, void *cb)
981 struct wt_status *s = cb;
983 if (!strcmp(k, "status.submodulesummary")) {
984 int is_bool;
985 s->submodule_summary = git_config_bool_or_int(k, v, &is_bool);
986 if (is_bool && s->submodule_summary)
987 s->submodule_summary = -1;
988 return 0;
990 if (!strcmp(k, "status.color") || !strcmp(k, "color.status")) {
991 s->use_color = git_config_colorbool(k, v, -1);
992 return 0;
994 if (!prefixcmp(k, "status.color.") || !prefixcmp(k, "color.status.")) {
995 int slot = parse_status_slot(k, 13);
996 if (slot < 0)
997 return 0;
998 if (!v)
999 return config_error_nonbool(k);
1000 color_parse(v, k, s->color_palette[slot]);
1001 return 0;
1003 if (!strcmp(k, "status.relativepaths")) {
1004 s->relative_paths = git_config_bool(k, v);
1005 return 0;
1007 if (!strcmp(k, "status.showuntrackedfiles")) {
1008 if (!v)
1009 return config_error_nonbool(k);
1010 else if (!strcmp(v, "no"))
1011 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
1012 else if (!strcmp(v, "normal"))
1013 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
1014 else if (!strcmp(v, "all"))
1015 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
1016 else
1017 return error("Invalid untracked files mode '%s'", v);
1018 return 0;
1020 return git_diff_ui_config(k, v, NULL);
1023 int cmd_status(int argc, const char **argv, const char *prefix)
1025 struct wt_status s;
1026 int fd;
1027 unsigned char sha1[20];
1028 static struct option builtin_status_options[] = {
1029 OPT__VERBOSE(&verbose),
1030 OPT_SET_INT('s', "short", &status_format,
1031 "show status concisely", STATUS_FORMAT_SHORT),
1032 OPT_SET_INT(0, "porcelain", &status_format,
1033 "show porcelain output format",
1034 STATUS_FORMAT_PORCELAIN),
1035 OPT_BOOLEAN('z', "null", &null_termination,
1036 "terminate entries with NUL"),
1037 { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg,
1038 "mode",
1039 "show untracked files, optional modes: all, normal, no. (Default: all)",
1040 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1041 OPT_END(),
1044 if (null_termination && status_format == STATUS_FORMAT_LONG)
1045 status_format = STATUS_FORMAT_PORCELAIN;
1047 wt_status_prepare(&s);
1048 git_config(git_status_config, &s);
1049 in_merge = file_exists(git_path("MERGE_HEAD"));
1050 argc = parse_options(argc, argv, prefix,
1051 builtin_status_options,
1052 builtin_status_usage, 0);
1053 handle_untracked_files_arg(&s);
1055 if (*argv)
1056 s.pathspec = get_pathspec(prefix, argv);
1058 read_cache_preload(s.pathspec);
1059 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, s.pathspec, NULL, NULL);
1061 fd = hold_locked_index(&index_lock, 0);
1062 if (0 <= fd) {
1063 if (!write_cache(fd, active_cache, active_nr))
1064 commit_locked_index(&index_lock);
1065 rollback_lock_file(&index_lock);
1068 s.is_initial = get_sha1(s.reference, sha1) ? 1 : 0;
1069 s.in_merge = in_merge;
1070 wt_status_collect(&s);
1072 if (s.relative_paths)
1073 s.prefix = prefix;
1074 if (s.use_color == -1)
1075 s.use_color = git_use_color_default;
1076 if (diff_use_color_default == -1)
1077 diff_use_color_default = git_use_color_default;
1079 switch (status_format) {
1080 case STATUS_FORMAT_SHORT:
1081 wt_shortstatus_print(&s, null_termination);
1082 break;
1083 case STATUS_FORMAT_PORCELAIN:
1084 wt_porcelain_print(&s, null_termination);
1085 break;
1086 case STATUS_FORMAT_LONG:
1087 s.verbose = verbose;
1088 wt_status_print(&s);
1089 break;
1091 return 0;
1094 static void print_summary(const char *prefix, const unsigned char *sha1)
1096 struct rev_info rev;
1097 struct commit *commit;
1098 struct strbuf format = STRBUF_INIT;
1099 unsigned char junk_sha1[20];
1100 const char *head = resolve_ref("HEAD", junk_sha1, 0, NULL);
1101 struct pretty_print_context pctx = {0};
1102 struct strbuf author_ident = STRBUF_INIT;
1103 struct strbuf committer_ident = STRBUF_INIT;
1105 commit = lookup_commit(sha1);
1106 if (!commit)
1107 die("couldn't look up newly created commit");
1108 if (!commit || parse_commit(commit))
1109 die("could not parse newly created commit");
1111 strbuf_addstr(&format, "format:%h] %s");
1113 format_commit_message(commit, "%an <%ae>", &author_ident, &pctx);
1114 format_commit_message(commit, "%cn <%ce>", &committer_ident, &pctx);
1115 if (strbuf_cmp(&author_ident, &committer_ident)) {
1116 strbuf_addstr(&format, "\n Author: ");
1117 strbuf_addbuf_percentquote(&format, &author_ident);
1119 if (!user_ident_sufficiently_given()) {
1120 strbuf_addstr(&format, "\n Committer: ");
1121 strbuf_addbuf_percentquote(&format, &committer_ident);
1122 if (advice_implicit_identity) {
1123 strbuf_addch(&format, '\n');
1124 strbuf_addstr(&format, implicit_ident_advice);
1127 strbuf_release(&author_ident);
1128 strbuf_release(&committer_ident);
1130 init_revisions(&rev, prefix);
1131 setup_revisions(0, NULL, &rev, NULL);
1133 rev.abbrev = 0;
1134 rev.diff = 1;
1135 rev.diffopt.output_format =
1136 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1138 rev.verbose_header = 1;
1139 rev.show_root_diff = 1;
1140 get_commit_format(format.buf, &rev);
1141 rev.always_show_header = 0;
1142 rev.diffopt.detect_rename = 1;
1143 rev.diffopt.rename_limit = 100;
1144 rev.diffopt.break_opt = 0;
1145 diff_setup_done(&rev.diffopt);
1147 printf("[%s%s ",
1148 !prefixcmp(head, "refs/heads/") ?
1149 head + 11 :
1150 !strcmp(head, "HEAD") ?
1151 "detached HEAD" :
1152 head,
1153 initial_commit ? " (root-commit)" : "");
1155 if (!log_tree_commit(&rev, commit)) {
1156 struct pretty_print_context ctx = {0};
1157 struct strbuf buf = STRBUF_INIT;
1158 ctx.date_mode = DATE_NORMAL;
1159 format_commit_message(commit, format.buf + 7, &buf, &ctx);
1160 printf("%s\n", buf.buf);
1161 strbuf_release(&buf);
1163 strbuf_release(&format);
1166 static int git_commit_config(const char *k, const char *v, void *cb)
1168 struct wt_status *s = cb;
1170 if (!strcmp(k, "commit.template"))
1171 return git_config_pathname(&template_file, k, v);
1172 if (!strcmp(k, "commit.status")) {
1173 include_status = git_config_bool(k, v);
1174 return 0;
1177 return git_status_config(k, v, s);
1180 static const char post_rewrite_hook[] = "hooks/post-rewrite";
1182 static int run_rewrite_hook(const unsigned char *oldsha1,
1183 const unsigned char *newsha1)
1185 /* oldsha1 SP newsha1 LF NUL */
1186 static char buf[2*40 + 3];
1187 struct child_process proc;
1188 const char *argv[3];
1189 int code;
1190 size_t n;
1192 if (access(git_path(post_rewrite_hook), X_OK) < 0)
1193 return 0;
1195 argv[0] = git_path(post_rewrite_hook);
1196 argv[1] = "amend";
1197 argv[2] = NULL;
1199 memset(&proc, 0, sizeof(proc));
1200 proc.argv = argv;
1201 proc.in = -1;
1202 proc.stdout_to_stderr = 1;
1204 code = start_command(&proc);
1205 if (code)
1206 return code;
1207 n = snprintf(buf, sizeof(buf), "%s %s\n",
1208 sha1_to_hex(oldsha1), sha1_to_hex(newsha1));
1209 write_in_full(proc.in, buf, n);
1210 close(proc.in);
1211 return finish_command(&proc);
1214 int cmd_commit(int argc, const char **argv, const char *prefix)
1216 struct strbuf sb = STRBUF_INIT;
1217 const char *index_file, *reflog_msg;
1218 char *nl, *p;
1219 unsigned char commit_sha1[20];
1220 struct ref_lock *ref_lock;
1221 struct commit_list *parents = NULL, **pptr = &parents;
1222 struct stat statbuf;
1223 int allow_fast_forward = 1;
1224 struct wt_status s;
1226 wt_status_prepare(&s);
1227 git_config(git_commit_config, &s);
1228 in_merge = file_exists(git_path("MERGE_HEAD"));
1229 s.in_merge = in_merge;
1231 if (s.use_color == -1)
1232 s.use_color = git_use_color_default;
1233 argc = parse_and_validate_options(argc, argv, builtin_commit_usage,
1234 prefix, &s);
1235 if (dry_run) {
1236 if (diff_use_color_default == -1)
1237 diff_use_color_default = git_use_color_default;
1238 return dry_run_commit(argc, argv, prefix, &s);
1240 index_file = prepare_index(argc, argv, prefix, 0);
1242 /* Set up everything for writing the commit object. This includes
1243 running hooks, writing the trees, and interacting with the user. */
1244 if (!prepare_to_commit(index_file, prefix, &s)) {
1245 rollback_index_files();
1246 return 1;
1249 /* Determine parents */
1250 if (initial_commit) {
1251 reflog_msg = "commit (initial)";
1252 } else if (amend) {
1253 struct commit_list *c;
1254 struct commit *commit;
1256 reflog_msg = "commit (amend)";
1257 commit = lookup_commit(head_sha1);
1258 if (!commit || parse_commit(commit))
1259 die("could not parse HEAD commit");
1261 for (c = commit->parents; c; c = c->next)
1262 pptr = &commit_list_insert(c->item, pptr)->next;
1263 } else if (in_merge) {
1264 struct strbuf m = STRBUF_INIT;
1265 FILE *fp;
1267 reflog_msg = "commit (merge)";
1268 pptr = &commit_list_insert(lookup_commit(head_sha1), pptr)->next;
1269 fp = fopen(git_path("MERGE_HEAD"), "r");
1270 if (fp == NULL)
1271 die_errno("could not open '%s' for reading",
1272 git_path("MERGE_HEAD"));
1273 while (strbuf_getline(&m, fp, '\n') != EOF) {
1274 unsigned char sha1[20];
1275 if (get_sha1_hex(m.buf, sha1) < 0)
1276 die("Corrupt MERGE_HEAD file (%s)", m.buf);
1277 pptr = &commit_list_insert(lookup_commit(sha1), pptr)->next;
1279 fclose(fp);
1280 strbuf_release(&m);
1281 if (!stat(git_path("MERGE_MODE"), &statbuf)) {
1282 if (strbuf_read_file(&sb, git_path("MERGE_MODE"), 0) < 0)
1283 die_errno("could not read MERGE_MODE");
1284 if (!strcmp(sb.buf, "no-ff"))
1285 allow_fast_forward = 0;
1287 if (allow_fast_forward)
1288 parents = reduce_heads(parents);
1289 } else {
1290 reflog_msg = "commit";
1291 pptr = &commit_list_insert(lookup_commit(head_sha1), pptr)->next;
1294 /* Finally, get the commit message */
1295 strbuf_reset(&sb);
1296 if (strbuf_read_file(&sb, git_path(commit_editmsg), 0) < 0) {
1297 int saved_errno = errno;
1298 rollback_index_files();
1299 die("could not read commit message: %s", strerror(saved_errno));
1302 /* Truncate the message just before the diff, if any. */
1303 if (verbose) {
1304 p = strstr(sb.buf, "\ndiff --git ");
1305 if (p != NULL)
1306 strbuf_setlen(&sb, p - sb.buf + 1);
1309 if (cleanup_mode != CLEANUP_NONE)
1310 stripspace(&sb, cleanup_mode == CLEANUP_ALL);
1311 if (message_is_empty(&sb) && !allow_empty_message) {
1312 rollback_index_files();
1313 fprintf(stderr, "Aborting commit due to empty commit message.\n");
1314 exit(1);
1317 if (commit_tree(sb.buf, active_cache_tree->sha1, parents, commit_sha1,
1318 fmt_ident(author_name, author_email, author_date,
1319 IDENT_ERROR_ON_NO_NAME))) {
1320 rollback_index_files();
1321 die("failed to write commit object");
1324 ref_lock = lock_any_ref_for_update("HEAD",
1325 initial_commit ? NULL : head_sha1,
1328 nl = strchr(sb.buf, '\n');
1329 if (nl)
1330 strbuf_setlen(&sb, nl + 1 - sb.buf);
1331 else
1332 strbuf_addch(&sb, '\n');
1333 strbuf_insert(&sb, 0, reflog_msg, strlen(reflog_msg));
1334 strbuf_insert(&sb, strlen(reflog_msg), ": ", 2);
1336 if (!ref_lock) {
1337 rollback_index_files();
1338 die("cannot lock HEAD ref");
1340 if (write_ref_sha1(ref_lock, commit_sha1, sb.buf) < 0) {
1341 rollback_index_files();
1342 die("cannot update HEAD ref");
1345 unlink(git_path("MERGE_HEAD"));
1346 unlink(git_path("MERGE_MSG"));
1347 unlink(git_path("MERGE_MODE"));
1348 unlink(git_path("SQUASH_MSG"));
1350 if (commit_index_files())
1351 die ("Repository has been updated, but unable to write\n"
1352 "new_index file. Check that disk is not full or quota is\n"
1353 "not exceeded, and then \"git reset HEAD\" to recover.");
1355 rerere(0);
1356 run_hook(get_index_file(), "post-commit", NULL);
1357 if (amend && !no_post_rewrite) {
1358 struct notes_rewrite_cfg *cfg;
1359 cfg = init_copy_notes_for_rewrite("amend");
1360 if (cfg) {
1361 copy_note_for_rewrite(cfg, head_sha1, commit_sha1);
1362 finish_copy_notes_for_rewrite(cfg);
1364 run_rewrite_hook(head_sha1, commit_sha1);
1366 if (!quiet)
1367 print_summary(prefix, commit_sha1);
1369 return 0;