Fix add_files_to_cache() to take pathspec, not user specified list of files
[git/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"
10#include "builtin.h"
11#include "diff.h"
12#include "diffcore.h"
13#include "commit.h"
14#include "revision.h"
15#include "wt-status.h"
16#include "run-command.h"
17#include "refs.h"
18#include "log-tree.h"
19#include "strbuf.h"
20#include "utf8.h"
21#include "parse-options.h"
22
23static const char * const builtin_commit_usage[] = {
24 "git-commit [options] [--] <filepattern>...",
25 NULL
26};
27
28static unsigned char head_sha1[20], merge_head_sha1[20];
29static char *use_message_buffer;
30static const char commit_editmsg[] = "COMMIT_EDITMSG";
31static struct lock_file lock_file;
32
f9568530 33static char *logfile, *force_author, *template_file;
f5bbc322
KH
34static char *edit_message, *use_message;
35static int all, edit_flag, also, interactive, only, amend, signoff;
36static int quiet, verbose, untracked_files, no_verify;
37
38static int no_edit, initial_commit, in_merge;
39const char *only_include_assumed;
f9568530
JS
40struct strbuf message;
41
42static int opt_parse_m(const struct option *opt, const char *arg, int unset)
43{
44 struct strbuf *buf = opt->value;
45 if (unset)
46 strbuf_setlen(buf, 0);
47 else {
48 strbuf_addstr(buf, arg);
49 strbuf_addch(buf, '\n');
50 strbuf_addch(buf, '\n');
51 }
52 return 0;
53}
f5bbc322
KH
54
55static struct option builtin_commit_options[] = {
56 OPT__QUIET(&quiet),
57 OPT__VERBOSE(&verbose),
58 OPT_GROUP("Commit message options"),
59
60 OPT_STRING('F', "file", &logfile, "FILE", "read log from file"),
61 OPT_STRING(0, "author", &force_author, "AUTHOR", "override author for commit"),
f9568530 62 OPT_CALLBACK('m', "message", &message, "MESSAGE", "specify commit message", opt_parse_m),
f5bbc322
KH
63 OPT_STRING('c', "reedit-message", &edit_message, "COMMIT", "reuse and edit message from specified commit "),
64 OPT_STRING('C', "reuse-message", &use_message, "COMMIT", "reuse message from specified commit"),
65 OPT_BOOLEAN('s', "signoff", &signoff, "add Signed-off-by: header"),
66 OPT_STRING('t', "template", &template_file, "FILE", "use specified template file"),
67 OPT_BOOLEAN('e', "edit", &edit_flag, "force edit of commit"),
68
69 OPT_GROUP("Commit contents options"),
70 OPT_BOOLEAN('a', "all", &all, "commit all changed files"),
71 OPT_BOOLEAN('i', "include", &also, "add specified files to index for commit"),
72 OPT_BOOLEAN(0, "interactive", &interactive, "interactively add files"),
73 OPT_BOOLEAN('o', "only", &only, ""),
74 OPT_BOOLEAN('n', "no-verify", &no_verify, "bypass pre-commit hook"),
75 OPT_BOOLEAN(0, "amend", &amend, "amend previous commit"),
76 OPT_BOOLEAN(0, "untracked-files", &untracked_files, "show all untracked files"),
77
78 OPT_END()
79};
80
81static char *prepare_index(const char **files, const char *prefix)
82{
83 int fd;
84 struct tree *tree;
85 struct lock_file *next_index_lock;
86
87 if (interactive) {
88 interactive_add();
89 return get_index_file();
90 }
91
92 fd = hold_locked_index(&lock_file, 1);
93 if (read_cache() < 0)
94 die("index file corrupt");
95
96 if (all || also) {
97 add_files_to_cache(verbose, also ? prefix : NULL, files);
d37d3203 98 refresh_cache(REFRESH_QUIET);
f5bbc322
KH
99 if (write_cache(fd, active_cache, active_nr) || close(fd))
100 die("unable to write new_index file");
101 return lock_file.filename;
102 }
103
104 if (*files == NULL) {
105 /* Commit index as-is. */
106 rollback_lock_file(&lock_file);
107 return get_index_file();
108 }
109
110 /* update the user index file */
111 add_files_to_cache(verbose, prefix, files);
ef12b50d 112 refresh_cache(REFRESH_QUIET);
f5bbc322
KH
113 if (write_cache(fd, active_cache, active_nr) || close(fd))
114 die("unable to write new_index file");
115
116 if (!initial_commit) {
117 tree = parse_tree_indirect(head_sha1);
118 if (!tree)
119 die("failed to unpack HEAD tree object");
120 if (read_tree(tree, 0, NULL))
121 die("failed to read HEAD tree object");
122 }
123
124 /* Use a lock file to garbage collect the temporary index file. */
125 next_index_lock = xmalloc(sizeof(*next_index_lock));
126 fd = hold_lock_file_for_update(next_index_lock,
127 git_path("next-index-%d", getpid()), 1);
128 add_files_to_cache(verbose, prefix, files);
d37d3203 129 refresh_cache(REFRESH_QUIET);
f5bbc322
KH
130 if (write_cache(fd, active_cache, active_nr) || close(fd))
131 die("unable to write new_index file");
132
133 return next_index_lock->filename;
134}
135
367c9886 136static int run_status(FILE *fp, const char *index_file, const char *prefix)
f5bbc322
KH
137{
138 struct wt_status s;
139
140 wt_status_prepare(&s);
367c9886 141 s.prefix = prefix;
f5bbc322
KH
142
143 if (amend) {
144 s.amend = 1;
145 s.reference = "HEAD^1";
146 }
147 s.verbose = verbose;
148 s.untracked = untracked_files;
149 s.index_file = index_file;
150 s.fp = fp;
151
152 wt_status_print(&s);
153
154 return s.commitable;
155}
156
157static const char sign_off_header[] = "Signed-off-by: ";
158
367c9886 159static int prepare_log_message(const char *index_file, const char *prefix)
f5bbc322
KH
160{
161 struct stat statbuf;
bc5d248a 162 int commitable, saved_color_setting;
f5bbc322
KH
163 struct strbuf sb;
164 char *buffer;
165 FILE *fp;
166
167 strbuf_init(&sb, 0);
f9568530
JS
168 if (message.len) {
169 strbuf_addbuf(&sb, &message);
f5bbc322
KH
170 } else if (logfile && !strcmp(logfile, "-")) {
171 if (isatty(0))
172 fprintf(stderr, "(reading log message from standard input)\n");
173 if (strbuf_read(&sb, 0, 0) < 0)
174 die("could not read log from standard input");
175 } else if (logfile) {
176 if (strbuf_read_file(&sb, logfile, 0) < 0)
177 die("could not read log file '%s': %s",
178 logfile, strerror(errno));
179 } else if (use_message) {
180 buffer = strstr(use_message_buffer, "\n\n");
181 if (!buffer || buffer[2] == '\0')
182 die("commit has empty message");
183 strbuf_add(&sb, buffer + 2, strlen(buffer + 2));
184 } else if (!stat(git_path("MERGE_MSG"), &statbuf)) {
185 if (strbuf_read_file(&sb, git_path("MERGE_MSG"), 0) < 0)
186 die("could not read MERGE_MSG: %s", strerror(errno));
187 } else if (!stat(git_path("SQUASH_MSG"), &statbuf)) {
188 if (strbuf_read_file(&sb, git_path("SQUASH_MSG"), 0) < 0)
189 die("could not read SQUASH_MSG: %s", strerror(errno));
190 } else if (template_file && !stat(template_file, &statbuf)) {
191 if (strbuf_read_file(&sb, template_file, 0) < 0)
192 die("could not read %s: %s",
193 template_file, strerror(errno));
194 }
195
196 fp = fopen(git_path(commit_editmsg), "w");
197 if (fp == NULL)
198 die("could not open %s\n", git_path(commit_editmsg));
199
200 stripspace(&sb, 0);
f5bbc322
KH
201
202 if (signoff) {
13208572
JS
203 struct strbuf sob;
204 int i;
205
206 strbuf_init(&sob, 0);
207 strbuf_addstr(&sob, sign_off_header);
208 strbuf_addstr(&sob, fmt_ident(getenv("GIT_COMMITTER_NAME"),
209 getenv("GIT_COMMITTER_EMAIL"),
210 "", 1));
211 strbuf_addch(&sob, '\n');
212
213 for (i = sb.len - 1; i > 0 && sb.buf[i - 1] != '\n'; i--)
214 ; /* do nothing */
2150554b
JS
215 if (prefixcmp(sb.buf + i, sob.buf)) {
216 if (prefixcmp(sb.buf + i, sign_off_header))
217 strbuf_addch(&sb, '\n');
13208572 218 strbuf_addbuf(&sb, &sob);
2150554b 219 }
13208572 220 strbuf_release(&sob);
f5bbc322
KH
221 }
222
13208572
JS
223 if (fwrite(sb.buf, 1, sb.len, fp) < sb.len)
224 die("could not write commit template: %s\n",
225 strerror(errno));
226
f5bbc322
KH
227 strbuf_release(&sb);
228
229 if (in_merge && !no_edit)
230 fprintf(fp,
231 "#\n"
232 "# It looks like you may be committing a MERGE.\n"
233 "# If this is not correct, please remove the file\n"
234 "# %s\n"
235 "# and try again.\n"
236 "#\n",
237 git_path("MERGE_HEAD"));
238
239 fprintf(fp,
240 "\n"
241 "# Please enter the commit message for your changes.\n"
242 "# (Comment lines starting with '#' will not be included)\n");
243 if (only_include_assumed)
244 fprintf(fp, "# %s\n", only_include_assumed);
245
bc5d248a
JH
246 saved_color_setting = wt_status_use_color;
247 wt_status_use_color = 0;
367c9886 248 commitable = run_status(fp, index_file, prefix);
bc5d248a 249 wt_status_use_color = saved_color_setting;
f5bbc322
KH
250
251 fclose(fp);
252
253 return commitable;
254}
255
256/*
257 * Find out if the message starting at position 'start' in the strbuf
258 * contains only whitespace and Signed-off-by lines.
259 */
260static int message_is_empty(struct strbuf *sb, int start)
261{
262 struct strbuf tmpl;
263 const char *nl;
264 int eol, i;
265
266 /* See if the template is just a prefix of the message. */
267 strbuf_init(&tmpl, 0);
268 if (template_file && strbuf_read_file(&tmpl, template_file, 0) > 0) {
269 stripspace(&tmpl, 1);
270 if (start + tmpl.len <= sb->len &&
271 memcmp(tmpl.buf, sb->buf + start, tmpl.len) == 0)
272 start += tmpl.len;
273 }
274 strbuf_release(&tmpl);
275
276 /* Check if the rest is just whitespace and Signed-of-by's. */
277 for (i = start; i < sb->len; i++) {
278 nl = memchr(sb->buf + i, '\n', sb->len - i);
279 if (nl)
280 eol = nl - sb->buf;
281 else
282 eol = sb->len;
283
284 if (strlen(sign_off_header) <= eol - i &&
285 !prefixcmp(sb->buf + i, sign_off_header)) {
286 i = eol;
287 continue;
288 }
289 while (i < eol)
290 if (!isspace(sb->buf[i++]))
291 return 0;
292 }
293
294 return 1;
295}
296
297static void determine_author_info(struct strbuf *sb)
298{
299 char *name, *email, *date;
300
301 name = getenv("GIT_AUTHOR_NAME");
302 email = getenv("GIT_AUTHOR_EMAIL");
303 date = getenv("GIT_AUTHOR_DATE");
304
305 if (use_message) {
306 const char *a, *lb, *rb, *eol;
307
308 a = strstr(use_message_buffer, "\nauthor ");
309 if (!a)
310 die("invalid commit: %s\n", use_message);
311
312 lb = strstr(a + 8, " <");
313 rb = strstr(a + 8, "> ");
314 eol = strchr(a + 8, '\n');
315 if (!lb || !rb || !eol)
316 die("invalid commit: %s\n", use_message);
317
318 name = xstrndup(a + 8, lb - (a + 8));
319 email = xstrndup(lb + 2, rb - (lb + 2));
320 date = xstrndup(rb + 2, eol - (rb + 2));
321 }
322
323 if (force_author) {
324 const char *lb = strstr(force_author, " <");
325 const char *rb = strchr(force_author, '>');
326
327 if (!lb || !rb)
328 die("malformed --author parameter\n");
329 name = xstrndup(force_author, lb - force_author);
330 email = xstrndup(lb + 2, rb - (lb + 2));
331 }
332
333 strbuf_addf(sb, "author %s\n", fmt_ident(name, email, date, 1));
334}
335
336static int parse_and_validate_options(int argc, const char *argv[])
337{
338 int f = 0;
339
340 argc = parse_options(argc, argv, builtin_commit_options,
341 builtin_commit_usage, 0);
342
f9568530 343 if (logfile || message.len || use_message)
f5bbc322
KH
344 no_edit = 1;
345 if (edit_flag)
346 no_edit = 0;
347
348 if (get_sha1("HEAD", head_sha1))
349 initial_commit = 1;
350
351 if (!get_sha1("MERGE_HEAD", merge_head_sha1))
352 in_merge = 1;
353
354 /* Sanity check options */
355 if (amend && initial_commit)
356 die("You have nothing to amend.");
357 if (amend && in_merge)
358 die("You are in the middle of a merger -- cannot amend.");
359
360 if (use_message)
361 f++;
362 if (edit_message)
363 f++;
364 if (logfile)
365 f++;
366 if (f > 1)
367 die("Only one of -c/-C/-F can be used.");
f9568530 368 if (message.len && f > 0)
f5bbc322
KH
369 die("Option -m cannot be combined with -c/-C/-F.");
370 if (edit_message)
371 use_message = edit_message;
372 if (amend)
373 use_message = "HEAD";
374 if (use_message) {
375 unsigned char sha1[20];
376 static char utf8[] = "UTF-8";
377 const char *out_enc;
378 char *enc, *end;
379 struct commit *commit;
380
381 if (get_sha1(use_message, sha1))
382 die("could not lookup commit %s", use_message);
383 commit = lookup_commit(sha1);
384 if (!commit || parse_commit(commit))
385 die("could not parse commit %s", use_message);
386
387 enc = strstr(commit->buffer, "\nencoding");
388 if (enc) {
389 end = strchr(enc + 10, '\n');
390 enc = xstrndup(enc + 10, end - (enc + 10));
391 } else {
392 enc = utf8;
393 }
394 out_enc = git_commit_encoding ? git_commit_encoding : utf8;
395
396 if (strcmp(out_enc, enc))
397 use_message_buffer =
398 reencode_string(commit->buffer, out_enc, enc);
399
400 /*
401 * If we failed to reencode the buffer, just copy it
402 * byte for byte so the user can try to fix it up.
403 * This also handles the case where input and output
404 * encodings are identical.
405 */
406 if (use_message_buffer == NULL)
407 use_message_buffer = xstrdup(commit->buffer);
408 if (enc != utf8)
409 free(enc);
410 }
411
412 if (!!also + !!only + !!all + !!interactive > 1)
413 die("Only one of --include/--only/--all/--interactive can be used.");
414 if (argc == 0 && (also || (only && !amend)))
415 die("No paths with --include/--only does not make sense.");
416 if (argc == 0 && only && amend)
417 only_include_assumed = "Clever... amending the last one with dirty index.";
418 if (argc > 0 && !also && !only) {
419 only_include_assumed = "Explicit paths specified without -i nor -o; assuming --only paths...";
420 also = 0;
421 }
422
423 if (all && argc > 0)
424 die("Paths with -a does not make sense.");
425 else if (interactive && argc > 0)
426 die("Paths with --interactive does not make sense.");
427
428 return argc;
429}
430
431int cmd_status(int argc, const char **argv, const char *prefix)
432{
433 const char *index_file;
434 int commitable;
435
436 git_config(git_status_config);
437
438 argc = parse_and_validate_options(argc, argv);
439
440 index_file = prepare_index(argv, prefix);
441
367c9886 442 commitable = run_status(stdout, index_file, prefix);
f5bbc322
KH
443
444 rollback_lock_file(&lock_file);
445
446 return commitable ? 0 : 1;
447}
448
449static int run_hook(const char *index_file, const char *name, const char *arg)
450{
451 struct child_process hook;
452 const char *argv[3], *env[2];
453 char index[PATH_MAX];
454
455 argv[0] = git_path("hooks/%s", name);
456 argv[1] = arg;
457 argv[2] = NULL;
458 snprintf(index, sizeof(index), "GIT_INDEX_FILE=%s", index_file);
459 env[0] = index;
460 env[1] = NULL;
461
462 if (access(argv[0], X_OK) < 0)
463 return 0;
464
465 memset(&hook, 0, sizeof(hook));
466 hook.argv = argv;
467 hook.no_stdin = 1;
468 hook.stdout_to_stderr = 1;
469 hook.env = env;
470
471 return run_command(&hook);
472}
473
474static void print_summary(const char *prefix, const unsigned char *sha1)
475{
476 struct rev_info rev;
477 struct commit *commit;
478
479 commit = lookup_commit(sha1);
480 if (!commit)
481 die("couldn't look up newly created commit\n");
482 if (!commit || parse_commit(commit))
483 die("could not parse newly created commit");
484
485 init_revisions(&rev, prefix);
486 setup_revisions(0, NULL, &rev, NULL);
487
488 rev.abbrev = 0;
489 rev.diff = 1;
490 rev.diffopt.output_format =
491 DIFF_FORMAT_SHORTSTAT | DIFF_FORMAT_SUMMARY;
492
493 rev.verbose_header = 1;
494 rev.show_root_diff = 1;
495 rev.commit_format = get_commit_format("format:%h: %s");
496 rev.always_show_header = 1;
497
498 printf("Created %scommit ", initial_commit ? "initial " : "");
499
500 log_tree_commit(&rev, commit);
129fa606 501 printf("\n");
f5bbc322
KH
502}
503
504int git_commit_config(const char *k, const char *v)
505{
506 if (!strcmp(k, "commit.template")) {
507 template_file = xstrdup(v);
508 return 0;
509 }
510
511 return git_status_config(k, v);
512}
513
514static const char commit_utf8_warn[] =
515"Warning: commit message does not conform to UTF-8.\n"
516"You may want to amend it after fixing the message, or set the config\n"
517"variable i18n.commitencoding to the encoding your project uses.\n";
518
519int cmd_commit(int argc, const char **argv, const char *prefix)
520{
18abc2db 521 int header_len;
f5bbc322
KH
522 struct strbuf sb;
523 const char *index_file, *reflog_msg;
741707b1 524 char *nl;
f5bbc322
KH
525 unsigned char commit_sha1[20];
526 struct ref_lock *ref_lock;
527
528 git_config(git_commit_config);
529
530 argc = parse_and_validate_options(argc, argv);
531
532 index_file = prepare_index(argv, prefix);
533
534 if (!no_verify && run_hook(index_file, "pre-commit", NULL))
535 exit(1);
536
367c9886
JS
537 if (!prepare_log_message(index_file, prefix) && !in_merge) {
538 run_status(stdout, index_file, prefix);
f5bbc322
KH
539 unlink(commit_editmsg);
540 return 1;
541 }
542
543 strbuf_init(&sb, 0);
544
545 /* Start building up the commit header */
546 read_cache_from(index_file);
547 active_cache_tree = cache_tree();
548 if (cache_tree_update(active_cache_tree,
549 active_cache, active_nr, 0, 0) < 0)
550 die("Error building trees");
551 strbuf_addf(&sb, "tree %s\n",
552 sha1_to_hex(active_cache_tree->sha1));
553
554 /* Determine parents */
555 if (initial_commit) {
556 reflog_msg = "commit (initial)";
f5bbc322
KH
557 } else if (amend) {
558 struct commit_list *c;
559 struct commit *commit;
560
561 reflog_msg = "commit (amend)";
562 commit = lookup_commit(head_sha1);
563 if (!commit || parse_commit(commit))
564 die("could not parse HEAD commit");
565
566 for (c = commit->parents; c; c = c->next)
567 strbuf_addf(&sb, "parent %s\n",
568 sha1_to_hex(c->item->object.sha1));
569 } else if (in_merge) {
570 struct strbuf m;
571 FILE *fp;
572
573 reflog_msg = "commit (merge)";
574 strbuf_addf(&sb, "parent %s\n", sha1_to_hex(head_sha1));
575 strbuf_init(&m, 0);
576 fp = fopen(git_path("MERGE_HEAD"), "r");
577 if (fp == NULL)
578 die("could not open %s for reading: %s",
579 git_path("MERGE_HEAD"), strerror(errno));
580 while (strbuf_getline(&m, fp, '\n') != EOF)
581 strbuf_addf(&sb, "parent %s\n", m.buf);
582 fclose(fp);
583 strbuf_release(&m);
584 } else {
585 reflog_msg = "commit";
586 strbuf_addf(&sb, "parent %s\n", sha1_to_hex(head_sha1));
587 }
588
589 determine_author_info(&sb);
590 strbuf_addf(&sb, "committer %s\n", git_committer_info(1));
591 if (!is_encoding_utf8(git_commit_encoding))
592 strbuf_addf(&sb, "encoding %s\n", git_commit_encoding);
593 strbuf_addch(&sb, '\n');
594
595 /* Get the commit message and validate it */
596 header_len = sb.len;
18abc2db 597 if (!no_edit)
f5bbc322 598 launch_editor(git_path(commit_editmsg), &sb);
18abc2db 599 else if (strbuf_read_file(&sb, git_path(commit_editmsg), 0) < 0)
f5bbc322 600 die("could not read commit message\n");
e06ad5ff 601 if (run_hook(index_file, "commit-msg", git_path(commit_editmsg)))
f5bbc322
KH
602 exit(1);
603 stripspace(&sb, 1);
604 if (sb.len < header_len ||
605 message_is_empty(&sb, header_len))
606 die("* no commit message? aborting commit.");
607 strbuf_addch(&sb, '\0');
608 if (is_encoding_utf8(git_commit_encoding) && !is_utf8(sb.buf))
609 fprintf(stderr, commit_utf8_warn);
610
611 if (write_sha1_file(sb.buf, sb.len - 1, commit_type, commit_sha1))
612 die("failed to write commit object");
613
614 ref_lock = lock_any_ref_for_update("HEAD",
615 initial_commit ? NULL : head_sha1,
616 0);
617
618 nl = strchr(sb.buf + header_len, '\n');
741707b1
JS
619 if (nl)
620 strbuf_setlen(&sb, nl + 1 - sb.buf);
621 else
622 strbuf_addch(&sb, '\n');
623 strbuf_remove(&sb, 0, header_len);
624 strbuf_insert(&sb, 0, reflog_msg, strlen(reflog_msg));
625 strbuf_insert(&sb, strlen(reflog_msg), ": ", 2);
f5bbc322
KH
626
627 if (!ref_lock)
628 die("cannot lock HEAD ref");
629 if (write_ref_sha1(ref_lock, commit_sha1, sb.buf) < 0)
630 die("cannot update HEAD ref");
631
632 unlink(git_path("MERGE_HEAD"));
633 unlink(git_path("MERGE_MSG"));
634
635 if (lock_file.filename[0] && commit_locked_index(&lock_file))
636 die("failed to write new index");
637
638 rerere();
639
640 run_hook(index_file, "post-commit", NULL);
641
642 if (!quiet)
643 print_summary(prefix, commit_sha1);
644
645 return 0;
646}