Update COPYING with GPLv2 with new FSF address
[git.git] / builtin-commit.c
blob592b10396d1d6aa25d5d1c0aa27556c93c219877
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 unsigned char head_sha1[20];
40 static char *use_message_buffer;
41 static const char commit_editmsg[] = "COMMIT_EDITMSG";
42 static struct lock_file index_lock; /* real index */
43 static struct lock_file false_lock; /* used only for partial commits */
44 static enum {
45 COMMIT_AS_IS = 1,
46 COMMIT_NORMAL,
47 COMMIT_PARTIAL,
48 } commit_style;
50 static const char *logfile, *force_author;
51 static const char *template_file;
52 static char *edit_message, *use_message;
53 static char *author_name, *author_email, *author_date;
54 static int all, edit_flag, also, interactive, only, amend, signoff;
55 static int quiet, verbose, no_verify, allow_empty, dry_run, renew_authorship;
56 static char *untracked_files_arg, *force_date;
58 * The default commit message cleanup mode will remove the lines
59 * beginning with # (shell comments) and leading and trailing
60 * whitespaces (empty lines or containing only whitespaces)
61 * if editor is used, and only the whitespaces if the message
62 * is specified explicitly.
64 static enum {
65 CLEANUP_SPACE,
66 CLEANUP_NONE,
67 CLEANUP_ALL,
68 } cleanup_mode;
69 static char *cleanup_arg;
71 static int use_editor = 1, initial_commit, in_merge;
72 static const char *only_include_assumed;
73 static struct strbuf message;
75 static int null_termination;
76 static enum {
77 STATUS_FORMAT_LONG,
78 STATUS_FORMAT_SHORT,
79 STATUS_FORMAT_PORCELAIN,
80 } status_format = STATUS_FORMAT_LONG;
82 static int opt_parse_m(const struct option *opt, const char *arg, int unset)
84 struct strbuf *buf = opt->value;
85 if (unset)
86 strbuf_setlen(buf, 0);
87 else {
88 strbuf_addstr(buf, arg);
89 strbuf_addstr(buf, "\n\n");
91 return 0;
94 static struct option builtin_commit_options[] = {
95 OPT__QUIET(&quiet),
96 OPT__VERBOSE(&verbose),
98 OPT_GROUP("Commit message options"),
99 OPT_FILENAME('F', "file", &logfile, "read log from file"),
100 OPT_STRING(0, "author", &force_author, "AUTHOR", "override author for commit"),
101 OPT_STRING(0, "date", &force_date, "DATE", "override date for commit"),
102 OPT_CALLBACK('m', "message", &message, "MESSAGE", "specify commit message", opt_parse_m),
103 OPT_STRING('c', "reedit-message", &edit_message, "COMMIT", "reuse and edit message from specified commit"),
104 OPT_STRING('C', "reuse-message", &use_message, "COMMIT", "reuse message from specified commit"),
105 OPT_BOOLEAN(0, "reset-author", &renew_authorship, "the commit is authored by me now (used with -C-c/--amend)"),
106 OPT_BOOLEAN('s', "signoff", &signoff, "add Signed-off-by:"),
107 OPT_FILENAME('t', "template", &template_file, "use specified template file"),
108 OPT_BOOLEAN('e', "edit", &edit_flag, "force edit of commit"),
109 OPT_STRING(0, "cleanup", &cleanup_arg, "default", "how to strip spaces and #comments from message"),
110 /* end commit message options */
112 OPT_GROUP("Commit contents options"),
113 OPT_BOOLEAN('a', "all", &all, "commit all changed files"),
114 OPT_BOOLEAN('i', "include", &also, "add specified files to index for commit"),
115 OPT_BOOLEAN(0, "interactive", &interactive, "interactively add files"),
116 OPT_BOOLEAN('o', "only", &only, "commit only specified files"),
117 OPT_BOOLEAN('n', "no-verify", &no_verify, "bypass pre-commit hook"),
118 OPT_BOOLEAN(0, "dry-run", &dry_run, "show what would be committed"),
119 OPT_SET_INT(0, "short", &status_format, "show status concisely",
120 STATUS_FORMAT_SHORT),
121 OPT_SET_INT(0, "porcelain", &status_format,
122 "show porcelain output format", STATUS_FORMAT_PORCELAIN),
123 OPT_BOOLEAN('z', "null", &null_termination,
124 "terminate entries with NUL"),
125 OPT_BOOLEAN(0, "amend", &amend, "amend previous commit"),
126 { 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" },
127 OPT_BOOLEAN(0, "allow-empty", &allow_empty, "ok to record an empty change"),
128 /* end commit contents options */
130 OPT_END()
133 static void rollback_index_files(void)
135 switch (commit_style) {
136 case COMMIT_AS_IS:
137 break; /* nothing to do */
138 case COMMIT_NORMAL:
139 rollback_lock_file(&index_lock);
140 break;
141 case COMMIT_PARTIAL:
142 rollback_lock_file(&index_lock);
143 rollback_lock_file(&false_lock);
144 break;
148 static int commit_index_files(void)
150 int err = 0;
152 switch (commit_style) {
153 case COMMIT_AS_IS:
154 break; /* nothing to do */
155 case COMMIT_NORMAL:
156 err = commit_lock_file(&index_lock);
157 break;
158 case COMMIT_PARTIAL:
159 err = commit_lock_file(&index_lock);
160 rollback_lock_file(&false_lock);
161 break;
164 return err;
168 * Take a union of paths in the index and the named tree (typically, "HEAD"),
169 * and return the paths that match the given pattern in list.
171 static int list_paths(struct string_list *list, const char *with_tree,
172 const char *prefix, const char **pattern)
174 int i;
175 char *m;
177 for (i = 0; pattern[i]; i++)
179 m = xcalloc(1, i);
181 if (with_tree)
182 overlay_tree_on_cache(with_tree, prefix);
184 for (i = 0; i < active_nr; i++) {
185 struct cache_entry *ce = active_cache[i];
186 struct string_list_item *item;
188 if (ce->ce_flags & CE_UPDATE)
189 continue;
190 if (!match_pathspec(pattern, ce->name, ce_namelen(ce), 0, m))
191 continue;
192 item = string_list_insert(ce->name, list);
193 if (ce_skip_worktree(ce))
194 item->util = item; /* better a valid pointer than a fake one */
197 return report_path_error(m, pattern, prefix ? strlen(prefix) : 0);
200 static void add_remove_files(struct string_list *list)
202 int i;
203 for (i = 0; i < list->nr; i++) {
204 struct stat st;
205 struct string_list_item *p = &(list->items[i]);
207 /* p->util is skip-worktree */
208 if (p->util)
209 continue;
211 if (!lstat(p->string, &st)) {
212 if (add_to_cache(p->string, &st, 0))
213 die("updating files failed");
214 } else
215 remove_file_from_cache(p->string);
219 static void create_base_index(void)
221 struct tree *tree;
222 struct unpack_trees_options opts;
223 struct tree_desc t;
225 if (initial_commit) {
226 discard_cache();
227 return;
230 memset(&opts, 0, sizeof(opts));
231 opts.head_idx = 1;
232 opts.index_only = 1;
233 opts.merge = 1;
234 opts.src_index = &the_index;
235 opts.dst_index = &the_index;
237 opts.fn = oneway_merge;
238 tree = parse_tree_indirect(head_sha1);
239 if (!tree)
240 die("failed to unpack HEAD tree object");
241 parse_tree(tree);
242 init_tree_desc(&t, tree->buffer, tree->size);
243 if (unpack_trees(1, &t, &opts))
244 exit(128); /* We've already reported the error, finish dying */
247 static char *prepare_index(int argc, const char **argv, const char *prefix, int is_status)
249 int fd;
250 struct string_list partial;
251 const char **pathspec = NULL;
252 int refresh_flags = REFRESH_QUIET;
254 if (is_status)
255 refresh_flags |= REFRESH_UNMERGED;
256 if (interactive) {
257 if (interactive_add(argc, argv, prefix) != 0)
258 die("interactive add failed");
259 if (read_cache_preload(NULL) < 0)
260 die("index file corrupt");
261 commit_style = COMMIT_AS_IS;
262 return get_index_file();
265 if (*argv)
266 pathspec = get_pathspec(prefix, argv);
268 if (read_cache_preload(pathspec) < 0)
269 die("index file corrupt");
272 * Non partial, non as-is commit.
274 * (1) get the real index;
275 * (2) update the_index as necessary;
276 * (3) write the_index out to the real index (still locked);
277 * (4) return the name of the locked index file.
279 * The caller should run hooks on the locked real index, and
280 * (A) if all goes well, commit the real index;
281 * (B) on failure, rollback the real index.
283 if (all || (also && pathspec && *pathspec)) {
284 int fd = hold_locked_index(&index_lock, 1);
285 add_files_to_cache(also ? prefix : NULL, pathspec, 0);
286 refresh_cache(refresh_flags);
287 if (write_cache(fd, active_cache, active_nr) ||
288 close_lock_file(&index_lock))
289 die("unable to write new_index file");
290 commit_style = COMMIT_NORMAL;
291 return index_lock.filename;
295 * As-is commit.
297 * (1) return the name of the real index file.
299 * The caller should run hooks on the real index, and run
300 * hooks on the real index, and create commit from the_index.
301 * We still need to refresh the index here.
303 if (!pathspec || !*pathspec) {
304 fd = hold_locked_index(&index_lock, 1);
305 refresh_cache(refresh_flags);
306 if (write_cache(fd, active_cache, active_nr) ||
307 commit_locked_index(&index_lock))
308 die("unable to write new_index file");
309 commit_style = COMMIT_AS_IS;
310 return get_index_file();
314 * A partial commit.
316 * (0) find the set of affected paths;
317 * (1) get lock on the real index file;
318 * (2) update the_index with the given paths;
319 * (3) write the_index out to the real index (still locked);
320 * (4) get lock on the false index file;
321 * (5) reset the_index from HEAD;
322 * (6) update the_index the same way as (2);
323 * (7) write the_index out to the false index file;
324 * (8) return the name of the false index file (still locked);
326 * The caller should run hooks on the locked false index, and
327 * create commit from it. Then
328 * (A) if all goes well, commit the real index;
329 * (B) on failure, rollback the real index;
330 * In either case, rollback the false index.
332 commit_style = COMMIT_PARTIAL;
334 if (in_merge)
335 die("cannot do a partial commit during a merge.");
337 memset(&partial, 0, sizeof(partial));
338 partial.strdup_strings = 1;
339 if (list_paths(&partial, initial_commit ? NULL : "HEAD", prefix, pathspec))
340 exit(1);
342 discard_cache();
343 if (read_cache() < 0)
344 die("cannot read the index");
346 fd = hold_locked_index(&index_lock, 1);
347 add_remove_files(&partial);
348 refresh_cache(REFRESH_QUIET);
349 if (write_cache(fd, active_cache, active_nr) ||
350 close_lock_file(&index_lock))
351 die("unable to write new_index file");
353 fd = hold_lock_file_for_update(&false_lock,
354 git_path("next-index-%"PRIuMAX,
355 (uintmax_t) getpid()),
356 LOCK_DIE_ON_ERROR);
358 create_base_index();
359 add_remove_files(&partial);
360 refresh_cache(REFRESH_QUIET);
362 if (write_cache(fd, active_cache, active_nr) ||
363 close_lock_file(&false_lock))
364 die("unable to write temporary index file");
366 discard_cache();
367 read_cache_from(false_lock.filename);
369 return false_lock.filename;
372 static int run_status(FILE *fp, const char *index_file, const char *prefix, int nowarn,
373 struct wt_status *s)
375 unsigned char sha1[20];
377 if (s->relative_paths)
378 s->prefix = prefix;
380 if (amend) {
381 s->amend = 1;
382 s->reference = "HEAD^1";
384 s->verbose = verbose;
385 s->index_file = index_file;
386 s->fp = fp;
387 s->nowarn = nowarn;
388 s->is_initial = get_sha1(s->reference, sha1) ? 1 : 0;
390 wt_status_collect(s);
392 switch (status_format) {
393 case STATUS_FORMAT_SHORT:
394 wt_shortstatus_print(s, null_termination);
395 break;
396 case STATUS_FORMAT_PORCELAIN:
397 wt_porcelain_print(s, null_termination);
398 break;
399 case STATUS_FORMAT_LONG:
400 wt_status_print(s);
401 break;
404 return s->commitable;
407 static int is_a_merge(const unsigned char *sha1)
409 struct commit *commit = lookup_commit(sha1);
410 if (!commit || parse_commit(commit))
411 die("could not parse HEAD commit");
412 return !!(commit->parents && commit->parents->next);
415 static const char sign_off_header[] = "Signed-off-by: ";
417 static void determine_author_info(void)
419 char *name, *email, *date;
421 name = getenv("GIT_AUTHOR_NAME");
422 email = getenv("GIT_AUTHOR_EMAIL");
423 date = getenv("GIT_AUTHOR_DATE");
425 if (use_message && !renew_authorship) {
426 const char *a, *lb, *rb, *eol;
428 a = strstr(use_message_buffer, "\nauthor ");
429 if (!a)
430 die("invalid commit: %s", use_message);
432 lb = strstr(a + 8, " <");
433 rb = strstr(a + 8, "> ");
434 eol = strchr(a + 8, '\n');
435 if (!lb || !rb || !eol)
436 die("invalid commit: %s", use_message);
438 name = xstrndup(a + 8, lb - (a + 8));
439 email = xstrndup(lb + 2, rb - (lb + 2));
440 date = xstrndup(rb + 2, eol - (rb + 2));
443 if (force_author) {
444 const char *lb = strstr(force_author, " <");
445 const char *rb = strchr(force_author, '>');
447 if (!lb || !rb)
448 die("malformed --author parameter");
449 name = xstrndup(force_author, lb - force_author);
450 email = xstrndup(lb + 2, rb - (lb + 2));
453 if (force_date)
454 date = force_date;
456 author_name = name;
457 author_email = email;
458 author_date = date;
461 static int ends_rfc2822_footer(struct strbuf *sb)
463 int ch;
464 int hit = 0;
465 int i, j, k;
466 int len = sb->len;
467 int first = 1;
468 const char *buf = sb->buf;
470 for (i = len - 1; i > 0; i--) {
471 if (hit && buf[i] == '\n')
472 break;
473 hit = (buf[i] == '\n');
476 while (i < len - 1 && buf[i] == '\n')
477 i++;
479 for (; i < len; i = k) {
480 for (k = i; k < len && buf[k] != '\n'; k++)
481 ; /* do nothing */
482 k++;
484 if ((buf[k] == ' ' || buf[k] == '\t') && !first)
485 continue;
487 first = 0;
489 for (j = 0; i + j < len; j++) {
490 ch = buf[i + j];
491 if (ch == ':')
492 break;
493 if (isalnum(ch) ||
494 (ch == '-'))
495 continue;
496 return 0;
499 return 1;
502 static int prepare_to_commit(const char *index_file, const char *prefix,
503 struct wt_status *s)
505 struct stat statbuf;
506 int commitable, saved_color_setting;
507 struct strbuf sb = STRBUF_INIT;
508 char *buffer;
509 FILE *fp;
510 const char *hook_arg1 = NULL;
511 const char *hook_arg2 = NULL;
512 int ident_shown = 0;
514 if (!no_verify && run_hook(index_file, "pre-commit", NULL))
515 return 0;
517 if (message.len) {
518 strbuf_addbuf(&sb, &message);
519 hook_arg1 = "message";
520 } else if (logfile && !strcmp(logfile, "-")) {
521 if (isatty(0))
522 fprintf(stderr, "(reading log message from standard input)\n");
523 if (strbuf_read(&sb, 0, 0) < 0)
524 die_errno("could not read log from standard input");
525 hook_arg1 = "message";
526 } else if (logfile) {
527 if (strbuf_read_file(&sb, logfile, 0) < 0)
528 die_errno("could not read log file '%s'",
529 logfile);
530 hook_arg1 = "message";
531 } else if (use_message) {
532 buffer = strstr(use_message_buffer, "\n\n");
533 if (!buffer || buffer[2] == '\0')
534 die("commit has empty message");
535 strbuf_add(&sb, buffer + 2, strlen(buffer + 2));
536 hook_arg1 = "commit";
537 hook_arg2 = use_message;
538 } else if (!stat(git_path("MERGE_MSG"), &statbuf)) {
539 if (strbuf_read_file(&sb, git_path("MERGE_MSG"), 0) < 0)
540 die_errno("could not read MERGE_MSG");
541 hook_arg1 = "merge";
542 } else if (!stat(git_path("SQUASH_MSG"), &statbuf)) {
543 if (strbuf_read_file(&sb, git_path("SQUASH_MSG"), 0) < 0)
544 die_errno("could not read SQUASH_MSG");
545 hook_arg1 = "squash";
546 } else if (template_file && !stat(template_file, &statbuf)) {
547 if (strbuf_read_file(&sb, template_file, 0) < 0)
548 die_errno("could not read '%s'", template_file);
549 hook_arg1 = "template";
553 * This final case does not modify the template message,
554 * it just sets the argument to the prepare-commit-msg hook.
556 else if (in_merge)
557 hook_arg1 = "merge";
559 fp = fopen(git_path(commit_editmsg), "w");
560 if (fp == NULL)
561 die_errno("could not open '%s'", git_path(commit_editmsg));
563 if (cleanup_mode != CLEANUP_NONE)
564 stripspace(&sb, 0);
566 if (signoff) {
567 struct strbuf sob = STRBUF_INIT;
568 int i;
570 strbuf_addstr(&sob, sign_off_header);
571 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
572 getenv("GIT_COMMITTER_EMAIL")));
573 strbuf_addch(&sob, '\n');
574 for (i = sb.len - 1; i > 0 && sb.buf[i - 1] != '\n'; i--)
575 ; /* do nothing */
576 if (prefixcmp(sb.buf + i, sob.buf)) {
577 if (!i || !ends_rfc2822_footer(&sb))
578 strbuf_addch(&sb, '\n');
579 strbuf_addbuf(&sb, &sob);
581 strbuf_release(&sob);
584 if (fwrite(sb.buf, 1, sb.len, fp) < sb.len)
585 die_errno("could not write commit template");
587 strbuf_release(&sb);
589 determine_author_info();
591 /* This checks if committer ident is explicitly given */
592 git_committer_info(0);
593 if (use_editor) {
594 char *author_ident;
595 const char *committer_ident;
597 if (in_merge)
598 fprintf(fp,
599 "#\n"
600 "# It looks like you may be committing a MERGE.\n"
601 "# If this is not correct, please remove the file\n"
602 "# %s\n"
603 "# and try again.\n"
604 "#\n",
605 git_path("MERGE_HEAD"));
607 fprintf(fp,
608 "\n"
609 "# Please enter the commit message for your changes.");
610 if (cleanup_mode == CLEANUP_ALL)
611 fprintf(fp,
612 " Lines starting\n"
613 "# with '#' will be ignored, and an empty"
614 " message aborts the commit.\n");
615 else /* CLEANUP_SPACE, that is. */
616 fprintf(fp,
617 " Lines starting\n"
618 "# with '#' will be kept; you may remove them"
619 " yourself if you want to.\n"
620 "# An empty message aborts the commit.\n");
621 if (only_include_assumed)
622 fprintf(fp, "# %s\n", only_include_assumed);
624 author_ident = xstrdup(fmt_name(author_name, author_email));
625 committer_ident = fmt_name(getenv("GIT_COMMITTER_NAME"),
626 getenv("GIT_COMMITTER_EMAIL"));
627 if (strcmp(author_ident, committer_ident))
628 fprintf(fp,
629 "%s"
630 "# Author: %s\n",
631 ident_shown++ ? "" : "#\n",
632 author_ident);
633 free(author_ident);
635 if (!user_ident_explicitly_given)
636 fprintf(fp,
637 "%s"
638 "# Committer: %s\n",
639 ident_shown++ ? "" : "#\n",
640 committer_ident);
642 if (ident_shown)
643 fprintf(fp, "#\n");
645 saved_color_setting = s->use_color;
646 s->use_color = 0;
647 commitable = run_status(fp, index_file, prefix, 1, s);
648 s->use_color = saved_color_setting;
649 } else {
650 unsigned char sha1[20];
651 const char *parent = "HEAD";
653 if (!active_nr && read_cache() < 0)
654 die("Cannot read index");
656 if (amend)
657 parent = "HEAD^1";
659 if (get_sha1(parent, sha1))
660 commitable = !!active_nr;
661 else
662 commitable = index_differs_from(parent, 0);
665 fclose(fp);
667 if (!commitable && !in_merge && !allow_empty &&
668 !(amend && is_a_merge(head_sha1))) {
669 run_status(stdout, index_file, prefix, 0, s);
670 return 0;
674 * Re-read the index as pre-commit hook could have updated it,
675 * and write it out as a tree. We must do this before we invoke
676 * the editor and after we invoke run_status above.
678 discard_cache();
679 read_cache_from(index_file);
680 if (!active_cache_tree)
681 active_cache_tree = cache_tree();
682 if (cache_tree_update(active_cache_tree,
683 active_cache, active_nr, 0, 0) < 0) {
684 error("Error building trees");
685 return 0;
688 if (run_hook(index_file, "prepare-commit-msg",
689 git_path(commit_editmsg), hook_arg1, hook_arg2, NULL))
690 return 0;
692 if (use_editor) {
693 char index[PATH_MAX];
694 const char *env[2] = { index, NULL };
695 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
696 if (launch_editor(git_path(commit_editmsg), NULL, env)) {
697 fprintf(stderr,
698 "Please supply the message using either -m or -F option.\n");
699 exit(1);
703 if (!no_verify &&
704 run_hook(index_file, "commit-msg", git_path(commit_editmsg), NULL)) {
705 return 0;
708 return 1;
712 * Find out if the message in the strbuf contains only whitespace and
713 * Signed-off-by lines.
715 static int message_is_empty(struct strbuf *sb)
717 struct strbuf tmpl = STRBUF_INIT;
718 const char *nl;
719 int eol, i, start = 0;
721 if (cleanup_mode == CLEANUP_NONE && sb->len)
722 return 0;
724 /* See if the template is just a prefix of the message. */
725 if (template_file && strbuf_read_file(&tmpl, template_file, 0) > 0) {
726 stripspace(&tmpl, cleanup_mode == CLEANUP_ALL);
727 if (start + tmpl.len <= sb->len &&
728 memcmp(tmpl.buf, sb->buf + start, tmpl.len) == 0)
729 start += tmpl.len;
731 strbuf_release(&tmpl);
733 /* Check if the rest is just whitespace and Signed-of-by's. */
734 for (i = start; i < sb->len; i++) {
735 nl = memchr(sb->buf + i, '\n', sb->len - i);
736 if (nl)
737 eol = nl - sb->buf;
738 else
739 eol = sb->len;
741 if (strlen(sign_off_header) <= eol - i &&
742 !prefixcmp(sb->buf + i, sign_off_header)) {
743 i = eol;
744 continue;
746 while (i < eol)
747 if (!isspace(sb->buf[i++]))
748 return 0;
751 return 1;
754 static const char *find_author_by_nickname(const char *name)
756 struct rev_info revs;
757 struct commit *commit;
758 struct strbuf buf = STRBUF_INIT;
759 const char *av[20];
760 int ac = 0;
762 init_revisions(&revs, NULL);
763 strbuf_addf(&buf, "--author=%s", name);
764 av[++ac] = "--all";
765 av[++ac] = "-i";
766 av[++ac] = buf.buf;
767 av[++ac] = NULL;
768 setup_revisions(ac, av, &revs, NULL);
769 prepare_revision_walk(&revs);
770 commit = get_revision(&revs);
771 if (commit) {
772 struct pretty_print_context ctx = {0};
773 ctx.date_mode = DATE_NORMAL;
774 strbuf_release(&buf);
775 format_commit_message(commit, "%an <%ae>", &buf, &ctx);
776 return strbuf_detach(&buf, NULL);
778 die("No existing author found with '%s'", name);
782 static void handle_untracked_files_arg(struct wt_status *s)
784 if (!untracked_files_arg)
785 ; /* default already initialized */
786 else if (!strcmp(untracked_files_arg, "no"))
787 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
788 else if (!strcmp(untracked_files_arg, "normal"))
789 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
790 else if (!strcmp(untracked_files_arg, "all"))
791 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
792 else
793 die("Invalid untracked files mode '%s'", untracked_files_arg);
796 static int parse_and_validate_options(int argc, const char *argv[],
797 const char * const usage[],
798 const char *prefix,
799 struct wt_status *s)
801 int f = 0;
803 argc = parse_options(argc, argv, prefix, builtin_commit_options, usage,
806 if (force_author && !strchr(force_author, '>'))
807 force_author = find_author_by_nickname(force_author);
809 if (force_author && renew_authorship)
810 die("Using both --reset-author and --author does not make sense");
812 if (logfile || message.len || use_message)
813 use_editor = 0;
814 if (edit_flag)
815 use_editor = 1;
816 if (!use_editor)
817 setenv("GIT_EDITOR", ":", 1);
819 if (get_sha1("HEAD", head_sha1))
820 initial_commit = 1;
822 /* Sanity check options */
823 if (amend && initial_commit)
824 die("You have nothing to amend.");
825 if (amend && in_merge)
826 die("You are in the middle of a merge -- cannot amend.");
828 if (use_message)
829 f++;
830 if (edit_message)
831 f++;
832 if (logfile)
833 f++;
834 if (f > 1)
835 die("Only one of -c/-C/-F can be used.");
836 if (message.len && f > 0)
837 die("Option -m cannot be combined with -c/-C/-F.");
838 if (edit_message)
839 use_message = edit_message;
840 if (amend && !use_message)
841 use_message = "HEAD";
842 if (!use_message && renew_authorship)
843 die("--reset-author can be used only with -C, -c or --amend.");
844 if (use_message) {
845 unsigned char sha1[20];
846 static char utf8[] = "UTF-8";
847 const char *out_enc;
848 char *enc, *end;
849 struct commit *commit;
851 if (get_sha1(use_message, sha1))
852 die("could not lookup commit %s", use_message);
853 commit = lookup_commit_reference(sha1);
854 if (!commit || parse_commit(commit))
855 die("could not parse commit %s", use_message);
857 enc = strstr(commit->buffer, "\nencoding");
858 if (enc) {
859 end = strchr(enc + 10, '\n');
860 enc = xstrndup(enc + 10, end - (enc + 10));
861 } else {
862 enc = utf8;
864 out_enc = git_commit_encoding ? git_commit_encoding : utf8;
866 if (strcmp(out_enc, enc))
867 use_message_buffer =
868 reencode_string(commit->buffer, out_enc, enc);
871 * If we failed to reencode the buffer, just copy it
872 * byte for byte so the user can try to fix it up.
873 * This also handles the case where input and output
874 * encodings are identical.
876 if (use_message_buffer == NULL)
877 use_message_buffer = xstrdup(commit->buffer);
878 if (enc != utf8)
879 free(enc);
882 if (!!also + !!only + !!all + !!interactive > 1)
883 die("Only one of --include/--only/--all/--interactive can be used.");
884 if (argc == 0 && (also || (only && !amend)))
885 die("No paths with --include/--only does not make sense.");
886 if (argc == 0 && only && amend)
887 only_include_assumed = "Clever... amending the last one with dirty index.";
888 if (argc > 0 && !also && !only)
889 only_include_assumed = "Explicit paths specified without -i nor -o; assuming --only paths...";
890 if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
891 cleanup_mode = use_editor ? CLEANUP_ALL : CLEANUP_SPACE;
892 else if (!strcmp(cleanup_arg, "verbatim"))
893 cleanup_mode = CLEANUP_NONE;
894 else if (!strcmp(cleanup_arg, "whitespace"))
895 cleanup_mode = CLEANUP_SPACE;
896 else if (!strcmp(cleanup_arg, "strip"))
897 cleanup_mode = CLEANUP_ALL;
898 else
899 die("Invalid cleanup mode %s", cleanup_arg);
901 handle_untracked_files_arg(s);
903 if (all && argc > 0)
904 die("Paths with -a does not make sense.");
905 else if (interactive && argc > 0)
906 die("Paths with --interactive does not make sense.");
908 if (null_termination && status_format == STATUS_FORMAT_LONG)
909 status_format = STATUS_FORMAT_PORCELAIN;
910 if (status_format != STATUS_FORMAT_LONG)
911 dry_run = 1;
913 return argc;
916 static int dry_run_commit(int argc, const char **argv, const char *prefix,
917 struct wt_status *s)
919 int commitable;
920 const char *index_file;
922 index_file = prepare_index(argc, argv, prefix, 1);
923 commitable = run_status(stdout, index_file, prefix, 0, s);
924 rollback_index_files();
926 return commitable ? 0 : 1;
929 static int parse_status_slot(const char *var, int offset)
931 if (!strcasecmp(var+offset, "header"))
932 return WT_STATUS_HEADER;
933 if (!strcasecmp(var+offset, "updated")
934 || !strcasecmp(var+offset, "added"))
935 return WT_STATUS_UPDATED;
936 if (!strcasecmp(var+offset, "changed"))
937 return WT_STATUS_CHANGED;
938 if (!strcasecmp(var+offset, "untracked"))
939 return WT_STATUS_UNTRACKED;
940 if (!strcasecmp(var+offset, "nobranch"))
941 return WT_STATUS_NOBRANCH;
942 if (!strcasecmp(var+offset, "unmerged"))
943 return WT_STATUS_UNMERGED;
944 return -1;
947 static int git_status_config(const char *k, const char *v, void *cb)
949 struct wt_status *s = cb;
951 if (!strcmp(k, "status.submodulesummary")) {
952 int is_bool;
953 s->submodule_summary = git_config_bool_or_int(k, v, &is_bool);
954 if (is_bool && s->submodule_summary)
955 s->submodule_summary = -1;
956 return 0;
958 if (!strcmp(k, "status.color") || !strcmp(k, "color.status")) {
959 s->use_color = git_config_colorbool(k, v, -1);
960 return 0;
962 if (!prefixcmp(k, "status.color.") || !prefixcmp(k, "color.status.")) {
963 int slot = parse_status_slot(k, 13);
964 if (slot < 0)
965 return 0;
966 if (!v)
967 return config_error_nonbool(k);
968 color_parse(v, k, s->color_palette[slot]);
969 return 0;
971 if (!strcmp(k, "status.relativepaths")) {
972 s->relative_paths = git_config_bool(k, v);
973 return 0;
975 if (!strcmp(k, "status.showuntrackedfiles")) {
976 if (!v)
977 return config_error_nonbool(k);
978 else if (!strcmp(v, "no"))
979 s->show_untracked_files = SHOW_NO_UNTRACKED_FILES;
980 else if (!strcmp(v, "normal"))
981 s->show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES;
982 else if (!strcmp(v, "all"))
983 s->show_untracked_files = SHOW_ALL_UNTRACKED_FILES;
984 else
985 return error("Invalid untracked files mode '%s'", v);
986 return 0;
988 return git_diff_ui_config(k, v, NULL);
991 int cmd_status(int argc, const char **argv, const char *prefix)
993 struct wt_status s;
994 unsigned char sha1[20];
995 static struct option builtin_status_options[] = {
996 OPT__VERBOSE(&verbose),
997 OPT_SET_INT('s', "short", &status_format,
998 "show status concisely", STATUS_FORMAT_SHORT),
999 OPT_SET_INT(0, "porcelain", &status_format,
1000 "show porcelain output format",
1001 STATUS_FORMAT_PORCELAIN),
1002 OPT_BOOLEAN('z', "null", &null_termination,
1003 "terminate entries with NUL"),
1004 { OPTION_STRING, 'u', "untracked-files", &untracked_files_arg,
1005 "mode",
1006 "show untracked files, optional modes: all, normal, no. (Default: all)",
1007 PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
1008 OPT_END(),
1011 if (null_termination && status_format == STATUS_FORMAT_LONG)
1012 status_format = STATUS_FORMAT_PORCELAIN;
1014 wt_status_prepare(&s);
1015 git_config(git_status_config, &s);
1016 in_merge = file_exists(git_path("MERGE_HEAD"));
1017 argc = parse_options(argc, argv, prefix,
1018 builtin_status_options,
1019 builtin_status_usage, 0);
1020 handle_untracked_files_arg(&s);
1022 if (*argv)
1023 s.pathspec = get_pathspec(prefix, argv);
1025 read_cache();
1026 refresh_cache(REFRESH_QUIET|REFRESH_UNMERGED);
1027 s.is_initial = get_sha1(s.reference, sha1) ? 1 : 0;
1028 s.in_merge = in_merge;
1029 wt_status_collect(&s);
1031 if (s.relative_paths)
1032 s.prefix = prefix;
1033 if (s.use_color == -1)
1034 s.use_color = git_use_color_default;
1035 if (diff_use_color_default == -1)
1036 diff_use_color_default = git_use_color_default;
1038 switch (status_format) {
1039 case STATUS_FORMAT_SHORT:
1040 wt_shortstatus_print(&s, null_termination);
1041 break;
1042 case STATUS_FORMAT_PORCELAIN:
1043 wt_porcelain_print(&s, null_termination);
1044 break;
1045 case STATUS_FORMAT_LONG:
1046 s.verbose = verbose;
1047 wt_status_print(&s);
1048 break;
1050 return 0;
1053 static void print_summary(const char *prefix, const unsigned char *sha1)
1055 struct rev_info rev;
1056 struct commit *commit;
1057 static const char *format = "format:%h] %s";
1058 unsigned char junk_sha1[20];
1059 const char *head = resolve_ref("HEAD", junk_sha1, 0, NULL);
1061 commit = lookup_commit(sha1);
1062 if (!commit)
1063 die("couldn't look up newly created commit");
1064 if (!commit || parse_commit(commit))
1065 die("could not parse newly created commit");
1067 init_revisions(&rev, prefix);
1068 setup_revisions(0, NULL, &rev, NULL);
1070 rev.abbrev = 0;
1071 rev.diff = 1;
1072 rev.diffopt.output_format =
1073 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
1075 rev.verbose_header = 1;
1076 rev.show_root_diff = 1;
1077 get_commit_format(format, &rev);
1078 rev.always_show_header = 0;
1079 rev.diffopt.detect_rename = 1;
1080 rev.diffopt.rename_limit = 100;
1081 rev.diffopt.break_opt = 0;
1082 diff_setup_done(&rev.diffopt);
1084 printf("[%s%s ",
1085 !prefixcmp(head, "refs/heads/") ?
1086 head + 11 :
1087 !strcmp(head, "HEAD") ?
1088 "detached HEAD" :
1089 head,
1090 initial_commit ? " (root-commit)" : "");
1092 if (!log_tree_commit(&rev, commit)) {
1093 struct pretty_print_context ctx = {0};
1094 struct strbuf buf = STRBUF_INIT;
1095 ctx.date_mode = DATE_NORMAL;
1096 format_commit_message(commit, format + 7, &buf, &ctx);
1097 printf("%s\n", buf.buf);
1098 strbuf_release(&buf);
1102 static int git_commit_config(const char *k, const char *v, void *cb)
1104 struct wt_status *s = cb;
1106 if (!strcmp(k, "commit.template"))
1107 return git_config_pathname(&template_file, k, v);
1109 return git_status_config(k, v, s);
1112 int cmd_commit(int argc, const char **argv, const char *prefix)
1114 struct strbuf sb = STRBUF_INIT;
1115 const char *index_file, *reflog_msg;
1116 char *nl, *p;
1117 unsigned char commit_sha1[20];
1118 struct ref_lock *ref_lock;
1119 struct commit_list *parents = NULL, **pptr = &parents;
1120 struct stat statbuf;
1121 int allow_fast_forward = 1;
1122 struct wt_status s;
1124 wt_status_prepare(&s);
1125 git_config(git_commit_config, &s);
1126 in_merge = file_exists(git_path("MERGE_HEAD"));
1127 s.in_merge = in_merge;
1129 if (s.use_color == -1)
1130 s.use_color = git_use_color_default;
1131 argc = parse_and_validate_options(argc, argv, builtin_commit_usage,
1132 prefix, &s);
1133 if (dry_run) {
1134 if (diff_use_color_default == -1)
1135 diff_use_color_default = git_use_color_default;
1136 return dry_run_commit(argc, argv, prefix, &s);
1138 index_file = prepare_index(argc, argv, prefix, 0);
1140 /* Set up everything for writing the commit object. This includes
1141 running hooks, writing the trees, and interacting with the user. */
1142 if (!prepare_to_commit(index_file, prefix, &s)) {
1143 rollback_index_files();
1144 return 1;
1147 /* Determine parents */
1148 if (initial_commit) {
1149 reflog_msg = "commit (initial)";
1150 } else if (amend) {
1151 struct commit_list *c;
1152 struct commit *commit;
1154 reflog_msg = "commit (amend)";
1155 commit = lookup_commit(head_sha1);
1156 if (!commit || parse_commit(commit))
1157 die("could not parse HEAD commit");
1159 for (c = commit->parents; c; c = c->next)
1160 pptr = &commit_list_insert(c->item, pptr)->next;
1161 } else if (in_merge) {
1162 struct strbuf m = STRBUF_INIT;
1163 FILE *fp;
1165 reflog_msg = "commit (merge)";
1166 pptr = &commit_list_insert(lookup_commit(head_sha1), pptr)->next;
1167 fp = fopen(git_path("MERGE_HEAD"), "r");
1168 if (fp == NULL)
1169 die_errno("could not open '%s' for reading",
1170 git_path("MERGE_HEAD"));
1171 while (strbuf_getline(&m, fp, '\n') != EOF) {
1172 unsigned char sha1[20];
1173 if (get_sha1_hex(m.buf, sha1) < 0)
1174 die("Corrupt MERGE_HEAD file (%s)", m.buf);
1175 pptr = &commit_list_insert(lookup_commit(sha1), pptr)->next;
1177 fclose(fp);
1178 strbuf_release(&m);
1179 if (!stat(git_path("MERGE_MODE"), &statbuf)) {
1180 if (strbuf_read_file(&sb, git_path("MERGE_MODE"), 0) < 0)
1181 die_errno("could not read MERGE_MODE");
1182 if (!strcmp(sb.buf, "no-ff"))
1183 allow_fast_forward = 0;
1185 if (allow_fast_forward)
1186 parents = reduce_heads(parents);
1187 } else {
1188 reflog_msg = "commit";
1189 pptr = &commit_list_insert(lookup_commit(head_sha1), pptr)->next;
1192 /* Finally, get the commit message */
1193 strbuf_reset(&sb);
1194 if (strbuf_read_file(&sb, git_path(commit_editmsg), 0) < 0) {
1195 int saved_errno = errno;
1196 rollback_index_files();
1197 die("could not read commit message: %s", strerror(saved_errno));
1200 /* Truncate the message just before the diff, if any. */
1201 if (verbose) {
1202 p = strstr(sb.buf, "\ndiff --git ");
1203 if (p != NULL)
1204 strbuf_setlen(&sb, p - sb.buf + 1);
1207 if (cleanup_mode != CLEANUP_NONE)
1208 stripspace(&sb, cleanup_mode == CLEANUP_ALL);
1209 if (message_is_empty(&sb)) {
1210 rollback_index_files();
1211 fprintf(stderr, "Aborting commit due to empty commit message.\n");
1212 exit(1);
1215 if (commit_tree(sb.buf, active_cache_tree->sha1, parents, commit_sha1,
1216 fmt_ident(author_name, author_email, author_date,
1217 IDENT_ERROR_ON_NO_NAME))) {
1218 rollback_index_files();
1219 die("failed to write commit object");
1222 ref_lock = lock_any_ref_for_update("HEAD",
1223 initial_commit ? NULL : head_sha1,
1226 nl = strchr(sb.buf, '\n');
1227 if (nl)
1228 strbuf_setlen(&sb, nl + 1 - sb.buf);
1229 else
1230 strbuf_addch(&sb, '\n');
1231 strbuf_insert(&sb, 0, reflog_msg, strlen(reflog_msg));
1232 strbuf_insert(&sb, strlen(reflog_msg), ": ", 2);
1234 if (!ref_lock) {
1235 rollback_index_files();
1236 die("cannot lock HEAD ref");
1238 if (write_ref_sha1(ref_lock, commit_sha1, sb.buf) < 0) {
1239 rollback_index_files();
1240 die("cannot update HEAD ref");
1243 unlink(git_path("MERGE_HEAD"));
1244 unlink(git_path("MERGE_MSG"));
1245 unlink(git_path("MERGE_MODE"));
1246 unlink(git_path("SQUASH_MSG"));
1248 if (commit_index_files())
1249 die ("Repository has been updated, but unable to write\n"
1250 "new_index file. Check that disk is not full or quota is\n"
1251 "not exceeded, and then \"git reset HEAD\" to recover.");
1253 rerere();
1254 run_hook(get_index_file(), "post-commit", NULL);
1255 if (!quiet)
1256 print_summary(prefix, commit_sha1);
1258 return 0;