Code

Merge branch 'cc/hooks-doc'
[git.git] / builtin-commit.c
1 /*
2  * Builtin "git commit"
3  *
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 "path-list.h"
25 #include "unpack-trees.h"
27 static const char * const builtin_commit_usage[] = {
28         "git-commit [options] [--] <filepattern>...",
29         NULL
30 };
32 static const char * const builtin_status_usage[] = {
33         "git-status [options] [--] <filepattern>...",
34         NULL
35 };
37 static unsigned char head_sha1[20], merge_head_sha1[20];
38 static char *use_message_buffer;
39 static const char commit_editmsg[] = "COMMIT_EDITMSG";
40 static struct lock_file index_lock; /* real index */
41 static struct lock_file false_lock; /* used only for partial commits */
42 static enum {
43         COMMIT_AS_IS = 1,
44         COMMIT_NORMAL,
45         COMMIT_PARTIAL,
46 } commit_style;
48 static char *logfile, *force_author, *template_file;
49 static char *edit_message, *use_message;
50 static int all, edit_flag, also, interactive, only, amend, signoff;
51 static int quiet, verbose, untracked_files, no_verify, allow_empty;
52 /*
53  * The default commit message cleanup mode will remove the lines
54  * beginning with # (shell comments) and leading and trailing
55  * whitespaces (empty lines or containing only whitespaces)
56  * if editor is used, and only the whitespaces if the message
57  * is specified explicitly.
58  */
59 static enum {
60         CLEANUP_SPACE,
61         CLEANUP_NONE,
62         CLEANUP_ALL,
63 } cleanup_mode;
64 static char *cleanup_arg;
66 static int use_editor = 1, initial_commit, in_merge;
67 const char *only_include_assumed;
68 struct strbuf message;
70 static int opt_parse_m(const struct option *opt, const char *arg, int unset)
71 {
72         struct strbuf *buf = opt->value;
73         if (unset)
74                 strbuf_setlen(buf, 0);
75         else {
76                 strbuf_addstr(buf, arg);
77                 strbuf_addch(buf, '\n');
78                 strbuf_addch(buf, '\n');
79         }
80         return 0;
81 }
83 static struct option builtin_commit_options[] = {
84         OPT__QUIET(&quiet),
85         OPT__VERBOSE(&verbose),
86         OPT_GROUP("Commit message options"),
88         OPT_STRING('F', "file", &logfile, "FILE", "read log from file"),
89         OPT_STRING(0, "author", &force_author, "AUTHOR", "override author for commit"),
90         OPT_CALLBACK('m', "message", &message, "MESSAGE", "specify commit message", opt_parse_m),
91         OPT_STRING('c', "reedit-message", &edit_message, "COMMIT", "reuse and edit message from specified commit "),
92         OPT_STRING('C', "reuse-message", &use_message, "COMMIT", "reuse message from specified commit"),
93         OPT_BOOLEAN('s', "signoff", &signoff, "add Signed-off-by:"),
94         OPT_STRING('t', "template", &template_file, "FILE", "use specified template file"),
95         OPT_BOOLEAN('e', "edit", &edit_flag, "force edit of commit"),
97         OPT_GROUP("Commit contents options"),
98         OPT_BOOLEAN('a', "all", &all, "commit all changed files"),
99         OPT_BOOLEAN('i', "include", &also, "add specified files to index for commit"),
100         OPT_BOOLEAN(0, "interactive", &interactive, "interactively add files"),
101         OPT_BOOLEAN('o', "only", &only, "commit only specified files"),
102         OPT_BOOLEAN('n', "no-verify", &no_verify, "bypass pre-commit hook"),
103         OPT_BOOLEAN(0, "amend", &amend, "amend previous commit"),
104         OPT_BOOLEAN('u', "untracked-files", &untracked_files, "show all untracked files"),
105         OPT_BOOLEAN(0, "allow-empty", &allow_empty, "ok to record an empty change"),
106         OPT_STRING(0, "cleanup", &cleanup_arg, "default", "how to strip spaces and #comments from message"),
108         OPT_END()
109 };
111 static void rollback_index_files(void)
113         switch (commit_style) {
114         case COMMIT_AS_IS:
115                 break; /* nothing to do */
116         case COMMIT_NORMAL:
117                 rollback_lock_file(&index_lock);
118                 break;
119         case COMMIT_PARTIAL:
120                 rollback_lock_file(&index_lock);
121                 rollback_lock_file(&false_lock);
122                 break;
123         }
126 static int commit_index_files(void)
128         int err = 0;
130         switch (commit_style) {
131         case COMMIT_AS_IS:
132                 break; /* nothing to do */
133         case COMMIT_NORMAL:
134                 err = commit_lock_file(&index_lock);
135                 break;
136         case COMMIT_PARTIAL:
137                 err = commit_lock_file(&index_lock);
138                 rollback_lock_file(&false_lock);
139                 break;
140         }
142         return err;
145 /*
146  * Take a union of paths in the index and the named tree (typically, "HEAD"),
147  * and return the paths that match the given pattern in list.
148  */
149 static int list_paths(struct path_list *list, const char *with_tree,
150                       const char *prefix, const char **pattern)
152         int i;
153         char *m;
155         for (i = 0; pattern[i]; i++)
156                 ;
157         m = xcalloc(1, i);
159         if (with_tree)
160                 overlay_tree_on_cache(with_tree, prefix);
162         for (i = 0; i < active_nr; i++) {
163                 struct cache_entry *ce = active_cache[i];
164                 if (ce->ce_flags & CE_UPDATE)
165                         continue;
166                 if (!pathspec_match(pattern, m, ce->name, 0))
167                         continue;
168                 path_list_insert(ce->name, list);
169         }
171         return report_path_error(m, pattern, prefix ? strlen(prefix) : 0);
174 static void add_remove_files(struct path_list *list)
176         int i;
177         for (i = 0; i < list->nr; i++) {
178                 struct stat st;
179                 struct path_list_item *p = &(list->items[i]);
181                 if (!lstat(p->path, &st))
182                         add_to_cache(p->path, &st, 0);
183                 else
184                         remove_file_from_cache(p->path);
185         }
188 static void create_base_index(void)
190         struct tree *tree;
191         struct unpack_trees_options opts;
192         struct tree_desc t;
194         if (initial_commit) {
195                 discard_cache();
196                 return;
197         }
199         memset(&opts, 0, sizeof(opts));
200         opts.head_idx = 1;
201         opts.index_only = 1;
202         opts.merge = 1;
203         opts.src_index = &the_index;
204         opts.dst_index = &the_index;
206         opts.fn = oneway_merge;
207         tree = parse_tree_indirect(head_sha1);
208         if (!tree)
209                 die("failed to unpack HEAD tree object");
210         parse_tree(tree);
211         init_tree_desc(&t, tree->buffer, tree->size);
212         if (unpack_trees(1, &t, &opts))
213                 exit(128); /* We've already reported the error, finish dying */
216 static char *prepare_index(int argc, const char **argv, const char *prefix)
218         int fd;
219         struct path_list partial;
220         const char **pathspec = NULL;
222         if (interactive) {
223                 interactive_add(argc, argv, prefix);
224                 commit_style = COMMIT_AS_IS;
225                 return get_index_file();
226         }
228         if (read_cache() < 0)
229                 die("index file corrupt");
231         if (*argv)
232                 pathspec = get_pathspec(prefix, argv);
234         /*
235          * Non partial, non as-is commit.
236          *
237          * (1) get the real index;
238          * (2) update the_index as necessary;
239          * (3) write the_index out to the real index (still locked);
240          * (4) return the name of the locked index file.
241          *
242          * The caller should run hooks on the locked real index, and
243          * (A) if all goes well, commit the real index;
244          * (B) on failure, rollback the real index.
245          */
246         if (all || (also && pathspec && *pathspec)) {
247                 int fd = hold_locked_index(&index_lock, 1);
248                 add_files_to_cache(0, also ? prefix : NULL, pathspec);
249                 refresh_cache(REFRESH_QUIET);
250                 if (write_cache(fd, active_cache, active_nr) ||
251                     close_lock_file(&index_lock))
252                         die("unable to write new_index file");
253                 commit_style = COMMIT_NORMAL;
254                 return index_lock.filename;
255         }
257         /*
258          * As-is commit.
259          *
260          * (1) return the name of the real index file.
261          *
262          * The caller should run hooks on the real index, and run
263          * hooks on the real index, and create commit from the_index.
264          * We still need to refresh the index here.
265          */
266         if (!pathspec || !*pathspec) {
267                 fd = hold_locked_index(&index_lock, 1);
268                 refresh_cache(REFRESH_QUIET);
269                 if (write_cache(fd, active_cache, active_nr) ||
270                     commit_locked_index(&index_lock))
271                         die("unable to write new_index file");
272                 commit_style = COMMIT_AS_IS;
273                 return get_index_file();
274         }
276         /*
277          * A partial commit.
278          *
279          * (0) find the set of affected paths;
280          * (1) get lock on the real index file;
281          * (2) update the_index with the given paths;
282          * (3) write the_index out to the real index (still locked);
283          * (4) get lock on the false index file;
284          * (5) reset the_index from HEAD;
285          * (6) update the_index the same way as (2);
286          * (7) write the_index out to the false index file;
287          * (8) return the name of the false index file (still locked);
288          *
289          * The caller should run hooks on the locked false index, and
290          * create commit from it.  Then
291          * (A) if all goes well, commit the real index;
292          * (B) on failure, rollback the real index;
293          * In either case, rollback the false index.
294          */
295         commit_style = COMMIT_PARTIAL;
297         if (file_exists(git_path("MERGE_HEAD")))
298                 die("cannot do a partial commit during a merge.");
300         memset(&partial, 0, sizeof(partial));
301         partial.strdup_paths = 1;
302         if (list_paths(&partial, initial_commit ? NULL : "HEAD", prefix, pathspec))
303                 exit(1);
305         discard_cache();
306         if (read_cache() < 0)
307                 die("cannot read the index");
309         fd = hold_locked_index(&index_lock, 1);
310         add_remove_files(&partial);
311         refresh_cache(REFRESH_QUIET);
312         if (write_cache(fd, active_cache, active_nr) ||
313             close_lock_file(&index_lock))
314                 die("unable to write new_index file");
316         fd = hold_lock_file_for_update(&false_lock,
317                                        git_path("next-index-%d", getpid()), 1);
319         create_base_index();
320         add_remove_files(&partial);
321         refresh_cache(REFRESH_QUIET);
323         if (write_cache(fd, active_cache, active_nr) ||
324             close_lock_file(&false_lock))
325                 die("unable to write temporary index file");
327         discard_cache();
328         read_cache_from(false_lock.filename);
330         return false_lock.filename;
333 static int run_status(FILE *fp, const char *index_file, const char *prefix, int nowarn)
335         struct wt_status s;
337         wt_status_prepare(&s);
338         if (wt_status_relative_paths)
339                 s.prefix = prefix;
341         if (amend) {
342                 s.amend = 1;
343                 s.reference = "HEAD^1";
344         }
345         s.verbose = verbose;
346         s.untracked = untracked_files;
347         s.index_file = index_file;
348         s.fp = fp;
349         s.nowarn = nowarn;
351         wt_status_print(&s);
353         return s.commitable;
356 static int run_hook(const char *index_file, const char *name, ...)
358         struct child_process hook;
359         const char *argv[10], *env[2];
360         char index[PATH_MAX];
361         va_list args;
362         int i;
364         va_start(args, name);
365         argv[0] = git_path("hooks/%s", name);
366         i = 0;
367         do {
368                 if (++i >= ARRAY_SIZE(argv))
369                         die ("run_hook(): too many arguments");
370                 argv[i] = va_arg(args, const char *);
371         } while (argv[i]);
372         va_end(args);
374         snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
375         env[0] = index;
376         env[1] = NULL;
378         if (access(argv[0], X_OK) < 0)
379                 return 0;
381         memset(&hook, 0, sizeof(hook));
382         hook.argv = argv;
383         hook.no_stdin = 1;
384         hook.stdout_to_stderr = 1;
385         hook.env = env;
387         return run_command(&hook);
390 static int is_a_merge(const unsigned char *sha1)
392         struct commit *commit = lookup_commit(sha1);
393         if (!commit || parse_commit(commit))
394                 die("could not parse HEAD commit");
395         return !!(commit->parents && commit->parents->next);
398 static const char sign_off_header[] = "Signed-off-by: ";
400 static int prepare_to_commit(const char *index_file, const char *prefix)
402         struct stat statbuf;
403         int commitable, saved_color_setting;
404         struct strbuf sb;
405         char *buffer;
406         FILE *fp;
407         const char *hook_arg1 = NULL;
408         const char *hook_arg2 = NULL;
410         if (!no_verify && run_hook(index_file, "pre-commit", NULL))
411                 return 0;
413         strbuf_init(&sb, 0);
414         if (message.len) {
415                 strbuf_addbuf(&sb, &message);
416                 hook_arg1 = "message";
417         } else if (logfile && !strcmp(logfile, "-")) {
418                 if (isatty(0))
419                         fprintf(stderr, "(reading log message from standard input)\n");
420                 if (strbuf_read(&sb, 0, 0) < 0)
421                         die("could not read log from standard input");
422                 hook_arg1 = "message";
423         } else if (logfile) {
424                 if (strbuf_read_file(&sb, logfile, 0) < 0)
425                         die("could not read log file '%s': %s",
426                             logfile, strerror(errno));
427                 hook_arg1 = "message";
428         } else if (use_message) {
429                 buffer = strstr(use_message_buffer, "\n\n");
430                 if (!buffer || buffer[2] == '\0')
431                         die("commit has empty message");
432                 strbuf_add(&sb, buffer + 2, strlen(buffer + 2));
433                 hook_arg1 = "commit";
434                 hook_arg2 = use_message;
435         } else if (!stat(git_path("MERGE_MSG"), &statbuf)) {
436                 if (strbuf_read_file(&sb, git_path("MERGE_MSG"), 0) < 0)
437                         die("could not read MERGE_MSG: %s", strerror(errno));
438                 hook_arg1 = "merge";
439         } else if (!stat(git_path("SQUASH_MSG"), &statbuf)) {
440                 if (strbuf_read_file(&sb, git_path("SQUASH_MSG"), 0) < 0)
441                         die("could not read SQUASH_MSG: %s", strerror(errno));
442                 hook_arg1 = "squash";
443         } else if (template_file && !stat(template_file, &statbuf)) {
444                 if (strbuf_read_file(&sb, template_file, 0) < 0)
445                         die("could not read %s: %s",
446                             template_file, strerror(errno));
447                 hook_arg1 = "template";
448         }
450         /*
451          * This final case does not modify the template message,
452          * it just sets the argument to the prepare-commit-msg hook.
453          */
454         else if (in_merge)
455                 hook_arg1 = "merge";
457         fp = fopen(git_path(commit_editmsg), "w");
458         if (fp == NULL)
459                 die("could not open %s", git_path(commit_editmsg));
461         if (cleanup_mode != CLEANUP_NONE)
462                 stripspace(&sb, 0);
464         if (signoff) {
465                 struct strbuf sob;
466                 int i;
468                 strbuf_init(&sob, 0);
469                 strbuf_addstr(&sob, sign_off_header);
470                 strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"),
471                                              getenv("GIT_COMMITTER_EMAIL")));
472                 strbuf_addch(&sob, '\n');
473                 for (i = sb.len - 1; i > 0 && sb.buf[i - 1] != '\n'; i--)
474                         ; /* do nothing */
475                 if (prefixcmp(sb.buf + i, sob.buf)) {
476                         if (prefixcmp(sb.buf + i, sign_off_header))
477                                 strbuf_addch(&sb, '\n');
478                         strbuf_addbuf(&sb, &sob);
479                 }
480                 strbuf_release(&sob);
481         }
483         if (fwrite(sb.buf, 1, sb.len, fp) < sb.len)
484                 die("could not write commit template: %s", strerror(errno));
486         strbuf_release(&sb);
488         if (use_editor) {
489                 if (in_merge)
490                         fprintf(fp,
491                                 "#\n"
492                                 "# It looks like you may be committing a MERGE.\n"
493                                 "# If this is not correct, please remove the file\n"
494                                 "#      %s\n"
495                                 "# and try again.\n"
496                                 "#\n",
497                                 git_path("MERGE_HEAD"));
499                 fprintf(fp,
500                         "\n"
501                         "# Please enter the commit message for your changes.\n"
502                         "# (Comment lines starting with '#' will ");
503                 if (cleanup_mode == CLEANUP_ALL)
504                         fprintf(fp, "not be included)\n");
505                 else /* CLEANUP_SPACE, that is. */
506                         fprintf(fp, "be kept.\n"
507                                 "# You can remove them yourself if you want to)\n");
508                 if (only_include_assumed)
509                         fprintf(fp, "# %s\n", only_include_assumed);
511                 saved_color_setting = wt_status_use_color;
512                 wt_status_use_color = 0;
513                 commitable = run_status(fp, index_file, prefix, 1);
514                 wt_status_use_color = saved_color_setting;
515         } else {
516                 struct rev_info rev;
517                 unsigned char sha1[20];
518                 const char *parent = "HEAD";
520                 if (!active_nr && read_cache() < 0)
521                         die("Cannot read index");
523                 if (amend)
524                         parent = "HEAD^1";
526                 if (get_sha1(parent, sha1))
527                         commitable = !!active_nr;
528                 else {
529                         init_revisions(&rev, "");
530                         rev.abbrev = 0;
531                         setup_revisions(0, NULL, &rev, parent);
532                         DIFF_OPT_SET(&rev.diffopt, QUIET);
533                         DIFF_OPT_SET(&rev.diffopt, EXIT_WITH_STATUS);
534                         run_diff_index(&rev, 1 /* cached */);
536                         commitable = !!DIFF_OPT_TST(&rev.diffopt, HAS_CHANGES);
537                 }
538         }
540         fclose(fp);
542         if (!commitable && !in_merge && !allow_empty &&
543             !(amend && is_a_merge(head_sha1))) {
544                 run_status(stdout, index_file, prefix, 0);
545                 unlink(commit_editmsg);
546                 return 0;
547         }
549         /*
550          * Re-read the index as pre-commit hook could have updated it,
551          * and write it out as a tree.  We must do this before we invoke
552          * the editor and after we invoke run_status above.
553          */
554         discard_cache();
555         read_cache_from(index_file);
556         if (!active_cache_tree)
557                 active_cache_tree = cache_tree();
558         if (cache_tree_update(active_cache_tree,
559                               active_cache, active_nr, 0, 0) < 0) {
560                 error("Error building trees");
561                 return 0;
562         }
564         if (run_hook(index_file, "prepare-commit-msg",
565                      git_path(commit_editmsg), hook_arg1, hook_arg2, NULL))
566                 return 0;
568         if (use_editor) {
569                 char index[PATH_MAX];
570                 const char *env[2] = { index, NULL };
571                 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
572                 launch_editor(git_path(commit_editmsg), NULL, env);
573         }
575         if (!no_verify &&
576             run_hook(index_file, "commit-msg", git_path(commit_editmsg), NULL)) {
577                 return 0;
578         }
580         return 1;
583 /*
584  * Find out if the message starting at position 'start' in the strbuf
585  * contains only whitespace and Signed-off-by lines.
586  */
587 static int message_is_empty(struct strbuf *sb, int start)
589         struct strbuf tmpl;
590         const char *nl;
591         int eol, i;
593         if (cleanup_mode == CLEANUP_NONE && sb->len)
594                 return 0;
596         /* See if the template is just a prefix of the message. */
597         strbuf_init(&tmpl, 0);
598         if (template_file && strbuf_read_file(&tmpl, template_file, 0) > 0) {
599                 stripspace(&tmpl, cleanup_mode == CLEANUP_ALL);
600                 if (start + tmpl.len <= sb->len &&
601                     memcmp(tmpl.buf, sb->buf + start, tmpl.len) == 0)
602                         start += tmpl.len;
603         }
604         strbuf_release(&tmpl);
606         /* Check if the rest is just whitespace and Signed-of-by's. */
607         for (i = start; i < sb->len; i++) {
608                 nl = memchr(sb->buf + i, '\n', sb->len - i);
609                 if (nl)
610                         eol = nl - sb->buf;
611                 else
612                         eol = sb->len;
614                 if (strlen(sign_off_header) <= eol - i &&
615                     !prefixcmp(sb->buf + i, sign_off_header)) {
616                         i = eol;
617                         continue;
618                 }
619                 while (i < eol)
620                         if (!isspace(sb->buf[i++]))
621                                 return 0;
622         }
624         return 1;
627 static void determine_author_info(struct strbuf *sb)
629         char *name, *email, *date;
631         name = getenv("GIT_AUTHOR_NAME");
632         email = getenv("GIT_AUTHOR_EMAIL");
633         date = getenv("GIT_AUTHOR_DATE");
635         if (use_message) {
636                 const char *a, *lb, *rb, *eol;
638                 a = strstr(use_message_buffer, "\nauthor ");
639                 if (!a)
640                         die("invalid commit: %s", use_message);
642                 lb = strstr(a + 8, " <");
643                 rb = strstr(a + 8, "> ");
644                 eol = strchr(a + 8, '\n');
645                 if (!lb || !rb || !eol)
646                         die("invalid commit: %s", use_message);
648                 name = xstrndup(a + 8, lb - (a + 8));
649                 email = xstrndup(lb + 2, rb - (lb + 2));
650                 date = xstrndup(rb + 2, eol - (rb + 2));
651         }
653         if (force_author) {
654                 const char *lb = strstr(force_author, " <");
655                 const char *rb = strchr(force_author, '>');
657                 if (!lb || !rb)
658                         die("malformed --author parameter");
659                 name = xstrndup(force_author, lb - force_author);
660                 email = xstrndup(lb + 2, rb - (lb + 2));
661         }
663         strbuf_addf(sb, "author %s\n", fmt_ident(name, email, date, IDENT_ERROR_ON_NO_NAME));
666 static int parse_and_validate_options(int argc, const char *argv[],
667                                       const char * const usage[])
669         int f = 0;
671         argc = parse_options(argc, argv, builtin_commit_options, usage, 0);
673         if (logfile || message.len || use_message)
674                 use_editor = 0;
675         if (edit_flag)
676                 use_editor = 1;
677         if (!use_editor)
678                 setenv("GIT_EDITOR", ":", 1);
680         if (get_sha1("HEAD", head_sha1))
681                 initial_commit = 1;
683         if (!get_sha1("MERGE_HEAD", merge_head_sha1))
684                 in_merge = 1;
686         /* Sanity check options */
687         if (amend && initial_commit)
688                 die("You have nothing to amend.");
689         if (amend && in_merge)
690                 die("You are in the middle of a merge -- cannot amend.");
692         if (use_message)
693                 f++;
694         if (edit_message)
695                 f++;
696         if (logfile)
697                 f++;
698         if (f > 1)
699                 die("Only one of -c/-C/-F can be used.");
700         if (message.len && f > 0)
701                 die("Option -m cannot be combined with -c/-C/-F.");
702         if (edit_message)
703                 use_message = edit_message;
704         if (amend && !use_message)
705                 use_message = "HEAD";
706         if (use_message) {
707                 unsigned char sha1[20];
708                 static char utf8[] = "UTF-8";
709                 const char *out_enc;
710                 char *enc, *end;
711                 struct commit *commit;
713                 if (get_sha1(use_message, sha1))
714                         die("could not lookup commit %s", use_message);
715                 commit = lookup_commit_reference(sha1);
716                 if (!commit || parse_commit(commit))
717                         die("could not parse commit %s", use_message);
719                 enc = strstr(commit->buffer, "\nencoding");
720                 if (enc) {
721                         end = strchr(enc + 10, '\n');
722                         enc = xstrndup(enc + 10, end - (enc + 10));
723                 } else {
724                         enc = utf8;
725                 }
726                 out_enc = git_commit_encoding ? git_commit_encoding : utf8;
728                 if (strcmp(out_enc, enc))
729                         use_message_buffer =
730                                 reencode_string(commit->buffer, out_enc, enc);
732                 /*
733                  * If we failed to reencode the buffer, just copy it
734                  * byte for byte so the user can try to fix it up.
735                  * This also handles the case where input and output
736                  * encodings are identical.
737                  */
738                 if (use_message_buffer == NULL)
739                         use_message_buffer = xstrdup(commit->buffer);
740                 if (enc != utf8)
741                         free(enc);
742         }
744         if (!!also + !!only + !!all + !!interactive > 1)
745                 die("Only one of --include/--only/--all/--interactive can be used.");
746         if (argc == 0 && (also || (only && !amend)))
747                 die("No paths with --include/--only does not make sense.");
748         if (argc == 0 && only && amend)
749                 only_include_assumed = "Clever... amending the last one with dirty index.";
750         if (argc > 0 && !also && !only)
751                 only_include_assumed = "Explicit paths specified without -i nor -o; assuming --only paths...";
752         if (!cleanup_arg || !strcmp(cleanup_arg, "default"))
753                 cleanup_mode = use_editor ? CLEANUP_ALL : CLEANUP_SPACE;
754         else if (!strcmp(cleanup_arg, "verbatim"))
755                 cleanup_mode = CLEANUP_NONE;
756         else if (!strcmp(cleanup_arg, "whitespace"))
757                 cleanup_mode = CLEANUP_SPACE;
758         else if (!strcmp(cleanup_arg, "strip"))
759                 cleanup_mode = CLEANUP_ALL;
760         else
761                 die("Invalid cleanup mode %s", cleanup_arg);
763         if (all && argc > 0)
764                 die("Paths with -a does not make sense.");
765         else if (interactive && argc > 0)
766                 die("Paths with --interactive does not make sense.");
768         return argc;
771 int cmd_status(int argc, const char **argv, const char *prefix)
773         const char *index_file;
774         int commitable;
776         git_config(git_status_config);
778         if (wt_status_use_color == -1)
779                 wt_status_use_color = git_use_color_default;
781         argc = parse_and_validate_options(argc, argv, builtin_status_usage);
783         index_file = prepare_index(argc, argv, prefix);
785         commitable = run_status(stdout, index_file, prefix, 0);
787         rollback_index_files();
789         return commitable ? 0 : 1;
792 static void print_summary(const char *prefix, const unsigned char *sha1)
794         struct rev_info rev;
795         struct commit *commit;
797         commit = lookup_commit(sha1);
798         if (!commit)
799                 die("couldn't look up newly created commit");
800         if (!commit || parse_commit(commit))
801                 die("could not parse newly created commit");
803         init_revisions(&rev, prefix);
804         setup_revisions(0, NULL, &rev, NULL);
806         rev.abbrev = 0;
807         rev.diff = 1;
808         rev.diffopt.output_format =
809                 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
811         rev.verbose_header = 1;
812         rev.show_root_diff = 1;
813         get_commit_format("format:%h: %s", &rev);
814         rev.always_show_header = 0;
815         rev.diffopt.detect_rename = 1;
816         rev.diffopt.rename_limit = 100;
817         rev.diffopt.break_opt = 0;
818         diff_setup_done(&rev.diffopt);
820         printf("Created %scommit ", initial_commit ? "initial " : "");
822         if (!log_tree_commit(&rev, commit)) {
823                 struct strbuf buf = STRBUF_INIT;
824                 format_commit_message(commit, "%h: %s", &buf);
825                 printf("%s\n", buf.buf);
826                 strbuf_release(&buf);
827         }
830 int git_commit_config(const char *k, const char *v)
832         if (!strcmp(k, "commit.template")) {
833                 if (!v)
834                         return config_error_nonbool(v);
835                 template_file = xstrdup(v);
836                 return 0;
837         }
839         return git_status_config(k, v);
842 static const char commit_utf8_warn[] =
843 "Warning: commit message does not conform to UTF-8.\n"
844 "You may want to amend it after fixing the message, or set the config\n"
845 "variable i18n.commitencoding to the encoding your project uses.\n";
847 static void add_parent(struct strbuf *sb, const unsigned char *sha1)
849         struct object *obj = parse_object(sha1);
850         const char *parent = sha1_to_hex(sha1);
851         if (!obj)
852                 die("Unable to find commit parent %s", parent);
853         if (obj->type != OBJ_COMMIT)
854                 die("Parent %s isn't a proper commit", parent);
855         strbuf_addf(sb, "parent %s\n", parent);
858 int cmd_commit(int argc, const char **argv, const char *prefix)
860         int header_len;
861         struct strbuf sb;
862         const char *index_file, *reflog_msg;
863         char *nl, *p;
864         unsigned char commit_sha1[20];
865         struct ref_lock *ref_lock;
867         git_config(git_commit_config);
869         argc = parse_and_validate_options(argc, argv, builtin_commit_usage);
871         index_file = prepare_index(argc, argv, prefix);
873         /* Set up everything for writing the commit object.  This includes
874            running hooks, writing the trees, and interacting with the user.  */
875         if (!prepare_to_commit(index_file, prefix)) {
876                 rollback_index_files();
877                 return 1;
878         }
880         /*
881          * The commit object
882          */
883         strbuf_init(&sb, 0);
884         strbuf_addf(&sb, "tree %s\n",
885                     sha1_to_hex(active_cache_tree->sha1));
887         /* Determine parents */
888         if (initial_commit) {
889                 reflog_msg = "commit (initial)";
890         } else if (amend) {
891                 struct commit_list *c;
892                 struct commit *commit;
894                 reflog_msg = "commit (amend)";
895                 commit = lookup_commit(head_sha1);
896                 if (!commit || parse_commit(commit))
897                         die("could not parse HEAD commit");
899                 for (c = commit->parents; c; c = c->next)
900                         add_parent(&sb, c->item->object.sha1);
901         } else if (in_merge) {
902                 struct strbuf m;
903                 FILE *fp;
905                 reflog_msg = "commit (merge)";
906                 add_parent(&sb, head_sha1);
907                 strbuf_init(&m, 0);
908                 fp = fopen(git_path("MERGE_HEAD"), "r");
909                 if (fp == NULL)
910                         die("could not open %s for reading: %s",
911                             git_path("MERGE_HEAD"), strerror(errno));
912                 while (strbuf_getline(&m, fp, '\n') != EOF) {
913                         unsigned char sha1[20];
914                         if (get_sha1_hex(m.buf, sha1) < 0)
915                                 die("Corrupt MERGE_HEAD file (%s)", m.buf);
916                         add_parent(&sb, sha1);
917                 }
918                 fclose(fp);
919                 strbuf_release(&m);
920         } else {
921                 reflog_msg = "commit";
922                 strbuf_addf(&sb, "parent %s\n", sha1_to_hex(head_sha1));
923         }
925         determine_author_info(&sb);
926         strbuf_addf(&sb, "committer %s\n", git_committer_info(IDENT_ERROR_ON_NO_NAME));
927         if (!is_encoding_utf8(git_commit_encoding))
928                 strbuf_addf(&sb, "encoding %s\n", git_commit_encoding);
929         strbuf_addch(&sb, '\n');
931         /* Finally, get the commit message */
932         header_len = sb.len;
933         if (strbuf_read_file(&sb, git_path(commit_editmsg), 0) < 0) {
934                 rollback_index_files();
935                 die("could not read commit message");
936         }
938         /* Truncate the message just before the diff, if any. */
939         p = strstr(sb.buf, "\ndiff --git a/");
940         if (p != NULL)
941                 strbuf_setlen(&sb, p - sb.buf + 1);
943         if (cleanup_mode != CLEANUP_NONE)
944                 stripspace(&sb, cleanup_mode == CLEANUP_ALL);
945         if (sb.len < header_len || message_is_empty(&sb, header_len)) {
946                 rollback_index_files();
947                 die("no commit message?  aborting commit.");
948         }
949         strbuf_addch(&sb, '\0');
950         if (is_encoding_utf8(git_commit_encoding) && !is_utf8(sb.buf))
951                 fprintf(stderr, commit_utf8_warn);
953         if (write_sha1_file(sb.buf, sb.len - 1, commit_type, commit_sha1)) {
954                 rollback_index_files();
955                 die("failed to write commit object");
956         }
958         ref_lock = lock_any_ref_for_update("HEAD",
959                                            initial_commit ? NULL : head_sha1,
960                                            0);
962         nl = strchr(sb.buf + header_len, '\n');
963         if (nl)
964                 strbuf_setlen(&sb, nl + 1 - sb.buf);
965         else
966                 strbuf_addch(&sb, '\n');
967         strbuf_remove(&sb, 0, header_len);
968         strbuf_insert(&sb, 0, reflog_msg, strlen(reflog_msg));
969         strbuf_insert(&sb, strlen(reflog_msg), ": ", 2);
971         if (!ref_lock) {
972                 rollback_index_files();
973                 die("cannot lock HEAD ref");
974         }
975         if (write_ref_sha1(ref_lock, commit_sha1, sb.buf) < 0) {
976                 rollback_index_files();
977                 die("cannot update HEAD ref");
978         }
980         unlink(git_path("MERGE_HEAD"));
981         unlink(git_path("MERGE_MSG"));
982         unlink(git_path("SQUASH_MSG"));
984         if (commit_index_files())
985                 die ("Repository has been updated, but unable to write\n"
986                      "new_index file. Check that disk is not full or quota is\n"
987                      "not exceeded, and then \"git reset HEAD\" to recover.");
989         rerere();
990         run_hook(get_index_file(), "post-commit", NULL);
991         if (!quiet)
992                 print_summary(prefix, commit_sha1);
994         return 0;