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