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