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