Merge branch 'seq-builtin-dev' into mymaster
[git/sbeyer.git] / builtin-sequencer.c
blob2f8ad2e40f558f4f409824673c071c35e766837d
1 /*
2 * git sequencer builtin command
4 * Copyright (C) 2008-2009 Stephan Beyer
5 */
6 #include "builtin.h"
7 #include "cache.h"
8 #include "cache-tree.h"
9 #include "utf8.h"
10 #include "dir.h"
11 #include "parse-options.h"
12 #include "refs.h"
13 #include "run-command.h"
14 #include "string-list.h"
15 #include "strbuf.h"
16 #include "pick.h"
17 #include "rerere.h"
18 #include "diff.h"
19 #include "revision.h"
20 #include "unpack-trees.h"
21 #include "merge-recursive.h"
23 #define SEQ_DIR "sequencer"
24 #define SEQ_MARK "refs/sequencer-marks"
26 #define TODO_FILE git_path(SEQ_DIR "/todo")
27 #define DONE_FILE git_path(SEQ_DIR "/done")
28 #define SAVE_FILE git_path(SEQ_DIR "/save")
29 #define DESTINY_FILE git_path(SEQ_DIR "/destiny")
30 #define PATCH_FILE git_path(SEQ_DIR "/patch")
31 #define MESSAGE_FILE git_path(SEQ_DIR "/message")
32 #define MERGE_HEAD git_path("MERGE_HEAD")
33 #define MERGE_MSG git_path("MERGE_MSG")
34 #define COMMIT_EDITMSG git_path("COMMIT_EDITMSG")
35 #define SQUASH_MSG git_path("SQUASH_MSG")
37 /**********************************************************************
38 * Data structures
41 struct user_info {
42 const char *name;
43 const char *mail;
44 const char *time; /* "<timestamp> <timezone>" */
47 struct commit_info {
48 struct user_info author; /* author info */
49 struct user_info committer; /* not used, but for easy extendability */
50 const char *encoding; /* encoding */
51 char *subject; /* basically the first line of the summary */
52 struct strbuf summary; /* the commit message */
53 char *source; /* source of the commit message, either
54 * "message", "merge", "squash" or a commit SHA1 */
55 char *patch; /* a patch */
56 struct string_list parents; /* list of parents' hex'ed sha1 ids */
59 /* A structure for a parsed instruction line plus a next pointer
60 * to allow linked list behavior */
61 struct parsed_insn {
62 int argc;
63 const char **argv;
64 int line;
65 struct strbuf orig;
66 struct parsed_insn *next;
69 struct parsed_file {
70 size_t count;
71 size_t total;
72 struct parsed_insn *first;
73 struct parsed_insn *last;
74 struct parsed_insn *cur; /* a versatile helper */
77 struct instruction {
78 const char * const *usage;
79 struct option *options;
80 void (*init)(void);
81 int (*check)(int, const char **);
82 int (*act)(int, const char **);
85 #define INSTRUCTION_NO_OPTS(name) \
86 { insn_ ## name ## _usage, \
87 no_insn_options, \
88 NULL, \
89 insn_ ## name ## _check, \
90 insn_ ## name ## _act }
92 #define INSTRUCTION(name) \
93 { insn_ ## name ## _usage, \
94 insn_ ## name ## _options, \
95 insn_ ## name ## _init, \
96 insn_ ## name ## _check, \
97 insn_ ## name ## _act }
100 /**********************************************************************
101 * Global variables
104 static char *reflog;
106 static const char *caller_abort, *caller_continue, *caller_skip;
107 static int caller_check_failed = 0;
109 static struct string_list available_marks;
110 static int marks_total;
111 /* This serves sanity checking purposes, but also need to be *written*
112 * on insn acting. */
114 static int squash_count = 0;
116 static int die_with_merges = 0;
118 #define ACTION_ABORT 1
119 #define ACTION_CONTINUE 2
120 #define ACTION_SKIP 4
121 #define ACTION_STATUS 8
122 #define ACTION_EDIT 16
124 static int allow_dirty = 0, batchmode = 0, verbosity = 1, advice = 1;
126 static struct parsed_file contents;
127 static int todo_line;
129 static const char *skiphead = NULL;
130 static const char *orig_headname = NULL;
131 static unsigned char orig_head_sha1[20];
132 static unsigned char head_sha1[20];
133 static unsigned char paused_at_sha1[20];
134 static enum {
135 WHY_UNKNOWN,
136 WHY_TODO,
137 WHY_CONFLICT,
138 WHY_PAUSE,
139 WHY_RUN
140 } why;
142 #define OPT_GENERAL_OPTIONS \
143 OPT_STRING(0, "author", &opt.author, "author", "override author"), \
144 OPT_STRING('C', "reuse-commit", &opt.reuse_commit, "commit", \
145 "reuse message and authorship data from commit"), \
146 OPT_STRING('F', "file", &opt.file, "file", \
147 "take commit message from given file"), \
148 OPT_STRING('m', "message", &opt.message, "msg", \
149 "specify commit message"), \
150 OPT_STRING('M', "reuse-message", &opt.reuse_message, "commit", \
151 "reuse message from commit"), \
152 OPT_BOOLEAN(0, "signoff", &opt.signoff, "add signoff"), \
153 OPT_BOOLEAN('e', "edit", &opt.edit, \
154 "invoke editor to edit commit message")
156 static struct {
157 char *author;
158 char *reuse_commit;
159 char *reuse_message;
160 char *file;
161 char *message;
162 int signoff;
163 int edit;
164 } opt;
166 static struct {
167 int standard;
168 char *strategy;
169 } merge_opt;
171 static struct {
172 int threeway;
173 int keep;
174 int noutf8;
175 struct string_list apply;
176 } patch_opt;
178 static struct {
179 int reverse;
180 int mainline;
181 } pick_opt;
183 static struct {
184 char *dir;
185 } run_opt;
187 static int squash_opt;
188 #define OPT_SQUASH_FROM 1
189 #define OPT_SQUASH_INCLUDE_MERGES 2
191 static struct commit_info next_commit;
193 /* Some forward declaration */
194 static int find_insn(const char *);
197 /**********************************************************************
198 * Cleanup routines
201 static void free_commit_info(struct commit_info *info)
203 /* We have to take care that the components are set to NULL
204 * after freeing, so that we can check if they are set or not. */
205 if (info->encoding) {
206 free((void *)info->encoding);
207 info->encoding = NULL;
209 if (info->subject) {
210 free(info->subject);
211 info->subject = NULL;
213 strbuf_release(&info->summary);
214 if (info->patch) {
215 free(info->patch);
216 info->patch = NULL;
218 if (info->source) {
219 free(info->source);
220 info->source = NULL;
222 if (info->author.name) {
223 free((void *)info->author.name);
224 info->author.name = NULL;
226 if (info->author.mail) {
227 free((void *)info->author.mail);
228 info->author.mail = NULL;
230 if (info->author.time) {
231 free((void *)info->author.time);
232 info->author.time = NULL;
234 if (info->committer.name) {
235 free((void *)info->committer.name);
236 info->committer.name = NULL;
238 if (info->committer.mail) {
239 free((void *)info->committer.mail);
240 info->committer.mail = NULL;
242 if (info->committer.time) {
243 free((void *)info->committer.time);
244 info->committer.time = NULL;
246 info->parents.strdup_strings = 1;
247 string_list_clear(&info->parents, 0);
248 info->parents.strdup_strings = 0;
251 /* Remove a parsed insn replace it by the next one */
252 static void free_parsed_insn(struct parsed_insn **p)
254 int i;
255 struct parsed_insn *cur = *p;
256 *p = cur->next;
257 for (i = 0; i < cur->argc; ++i)
258 free((void *)cur->argv[i]);
259 free(cur->argv);
260 strbuf_release(&cur->orig);
261 free(cur);
264 static void free_available_marks(void)
266 available_marks.nr = marks_total;
267 available_marks.strdup_strings = 1; /* free items */
268 string_list_clear(&available_marks, 0);
269 marks_total = 0;
272 static void small_cleanup(void)
274 struct parsed_insn *cur;
275 /* free parsed_insns of contents */
276 for (cur = contents.first; cur; free_parsed_insn(&cur));
278 /* free global stuff */
279 free_commit_info(&next_commit);
280 free_available_marks();
283 /* A callback function for for_each_ref() to get a list of marks */
284 static int mark_list(const char *ref, const unsigned char *sha, int flags, void *data)
286 if (!prefixcmp(ref, SEQ_MARK)) {
287 struct string_list marks = *(struct string_list *)data;
288 string_list_append(ref, &marks);
289 marks.items[marks.nr - 1].util = xmalloc(20);
290 hashcpy(marks.items[marks.nr - 1].util, sha);
291 *(struct string_list *)data = marks;
293 return 0;
296 static void cleanup(void)
298 struct string_list marks;
299 struct strbuf seq_dir = STRBUF_INIT;
300 int i;
301 /* remove all marks */
302 memset(&marks, 0, sizeof(struct string_list));
303 marks.strdup_strings = 1;
304 for_each_ref(mark_list, &marks);
305 for (i = 0; i < marks.nr; ++i)
306 delete_ref(marks.items[i].string, marks.items[i].util, 0);
307 string_list_clear(&marks, 1);
309 small_cleanup();
311 strbuf_addstr(&seq_dir, git_path(SEQ_DIR));
312 remove_dir_recursively(&seq_dir, 0);
313 strbuf_release(&seq_dir);
317 /**********************************************************************
318 * Miscellaneous helper functions
321 static void print_advice(void)
323 if (!advice)
324 return;
325 switch(why) {
326 case WHY_CONFLICT:
327 if (verbosity && next_commit.subject)
328 printf("\nConflict at: %s\n", next_commit.subject);
329 printf("\n"
330 "After resolving the conflicts, mark the corrected paths with"
331 "\n\n\tgit add <paths>\n\n"
332 "and run\n\n\t%s\n\n"
333 "Note, that your working tree must match the index.\n",
334 caller_continue);
335 break;
336 case WHY_PAUSE:
337 if (verbosity && next_commit.subject)
338 printf("Pause at: %s\n", next_commit.subject);
339 printf("\nYou can now edit files and add them to the index.\n"
340 "Once you are satisfied with your changes, run\n\n\t%s\n\n"
341 "If you only want to change the commit message, run\n"
342 "git commit --amend before.\n", caller_continue);
343 break;
344 case WHY_RUN:
345 if (verbosity && next_commit.subject)
346 printf("\nRunning failed at:\n\t%s\n",
347 next_commit.subject);
348 printf("You can now fix the problem. When manual runs pass,\n"
349 "add the changes to the index and invoke\n\n\t%s\n",
350 caller_continue);
351 break;
352 case WHY_TODO:
353 printf("\nFix with git sequencer --edit or abort with %s.\n",
354 caller_abort);
355 break;
356 default:
357 break;
361 static int parse_and_init_tree_desc(const unsigned char *sha1,
362 struct tree_desc *desc)
364 struct tree *tree = parse_tree_indirect(sha1);
365 if (!tree)
366 return 1;
367 init_tree_desc(desc, tree->buffer, tree->size);
368 return 0;
371 static int reset_index_file(const unsigned char *sha1, int update, int dirty)
373 int nr = 1;
374 int newfd;
375 struct tree_desc desc[2];
376 struct unpack_trees_options opts;
377 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
379 memset(&opts, 0, sizeof(opts));
380 opts.head_idx = 1;
381 opts.src_index = &the_index;
382 opts.dst_index = &the_index;
383 opts.reset = 1; /* ignore unmerged entries and overwrite wt files */
384 opts.merge = 1;
385 opts.fn = oneway_merge;
386 if (verbosity > 2)
387 opts.verbose_update = 1;
388 if (update) /* update working tree */
389 opts.update = 1;
391 newfd = hold_locked_index(lock, 1);
393 read_cache_unmerged();
395 if (dirty) {
396 if (get_sha1("HEAD", head_sha1))
397 return error("You do not have a valid HEAD.");
398 if (parse_and_init_tree_desc(head_sha1, desc))
399 return error("Failed to find tree of HEAD.");
400 nr++;
401 opts.fn = twoway_merge;
404 if (parse_and_init_tree_desc(sha1, desc + nr - 1))
405 return error("Failed to find tree of %s.", sha1_to_hex(sha1));
406 if (unpack_trees(nr, desc, &opts))
407 return -1;
408 if (write_cache(newfd, active_cache, active_nr) ||
409 commit_locked_index(lock))
410 return error("Could not write new index file.");
412 return 0;
416 * Realize reset --hard behavior.
417 * If allow_dirty is set and there is a dirty working tree,
418 * then the changes are to be kept.
420 static int reset_almost_hard(unsigned const char sha[20])
422 int err = allow_dirty ?
423 (reset_index_file(sha, 1, 1) || reset_index_file(sha, 0, 0)) :
424 reset_index_file(sha, 1, 0);
425 if (err)
426 return error("Could not reset index.");
428 return update_ref(reflog, "HEAD", sha, NULL, 0, MSG_ON_ERR);
431 /* rerere clear functionality */
432 static void rerere_clear(void) {
433 const char *args[] = {
434 "rerere",
435 "clear",
436 NULL
438 run_command_v_opt(args, RUN_GIT_CMD | RUN_COMMAND_NO_STDIN);
441 /* Generate purely informational patch file */
442 static void make_patch(struct commit *commit)
444 struct commit_list *parents = commit->parents;
445 const char **args;
446 struct child_process chld;
447 int fd = open(PATCH_FILE, O_WRONLY | O_CREAT, 0666);
448 if (fd < 0)
449 return;
451 memset(&chld, 0, sizeof(chld));
452 if (!parents) {
453 write(fd, "Root commit\n", 12);
454 close(fd);
455 return;
456 } else if (!parents->next) {
457 args = xcalloc(5, sizeof(char *));
458 args[0] = "diff-tree";
459 args[1] = "-p";
460 args[2] = xstrdup(sha1_to_hex(parents->item->object.sha1));
461 args[3] = xstrdup(sha1_to_hex(((struct object *)commit)->sha1));
462 } else {
463 int i = 0;
464 int count = 1;
466 for (; parents; parents = parents->next)
467 ++count;
468 args = xcalloc(count + 3, sizeof(char *));
469 args[i++] = "diff";
470 args[i++] = "--cc";
471 args[i++] = xstrdup(sha1_to_hex(commit->object.sha1));
473 for (parents = commit->parents; parents;
474 parents = parents->next)
475 args[i++] = xstrdup(sha1_to_hex(
476 parents->item->object.sha1));
479 chld.argv = args;
480 chld.git_cmd = 1;
481 chld.out = fd;
483 /* Run, ignore errors. */
484 if (start_command(&chld))
485 return;
486 finish_command(&chld);
488 /* TODO: free dup'ed SHAs in argument list */
491 /* Commit current index with information next_commit onto parent_sha1. */
492 static int do_commit(unsigned char *parent_sha1)
494 int failed;
495 unsigned char tree_sha1[20];
496 unsigned char commit_sha1[20];
497 struct strbuf sbuf;
498 const char *reencoded = NULL;
500 if (squash_count) {
501 squash_count = 0;
502 if (file_exists(SQUASH_MSG))
503 unlink(SQUASH_MSG);
506 if (!index_differs_from("HEAD", 0) &&
507 !next_commit.parents.nr)
508 return error("No changes! Do you really want an empty commit?");
510 if (!next_commit.author.name || !next_commit.author.mail)
511 return error("Internal error: Author information not set properly.");
513 if (write_cache_as_tree(tree_sha1, 0, NULL))
514 return 1;
516 if (!next_commit.encoding)
517 next_commit.encoding = xstrdup("utf-8");
518 if (!git_commit_encoding)
519 git_commit_encoding = "utf-8";
521 strbuf_init(&sbuf, 8192); /* should avoid reallocs for the headers */
522 strbuf_addf(&sbuf, "tree %s\n", sha1_to_hex(tree_sha1));
523 if (parent_sha1)
524 strbuf_addf(&sbuf, "parent %s\n", sha1_to_hex(parent_sha1));
525 if (next_commit.parents.nr) {
526 int i;
527 for (i = 0; i < next_commit.parents.nr; ++i)
528 strbuf_addf(&sbuf, "parent %s\n",
529 next_commit.parents.items[i].string);
531 if (!next_commit.author.time) {
532 char time[50];
533 datestamp(time, sizeof(time));
534 next_commit.author.time = xstrdup(time);
537 stripspace(&next_commit.summary, 1);
539 /* if encodings differ, reencode whole buffer */
540 if (strcasecmp(git_commit_encoding, next_commit.encoding)) {
541 if ((reencoded = reencode_string(next_commit.author.name,
542 git_commit_encoding, next_commit.encoding))) {
543 free((void *)next_commit.author.name);
544 next_commit.author.name = reencoded;
546 if ((reencoded = reencode_string(next_commit.summary.buf,
547 git_commit_encoding, next_commit.encoding))) {
548 strbuf_reset(&next_commit.summary);
549 strbuf_addstr(&next_commit.summary, reencoded);
552 strbuf_addf(&sbuf, "author %s <%s> %s\n", next_commit.author.name,
553 next_commit.author.mail, next_commit.author.time);
554 strbuf_addf(&sbuf, "committer %s\n", git_committer_info(0));
555 if (!is_encoding_utf8(git_commit_encoding))
556 strbuf_addf(&sbuf, "encoding %s\n", git_commit_encoding);
557 strbuf_addch(&sbuf, '\n');
558 strbuf_addbuf(&sbuf, &next_commit.summary);
559 if (sbuf.buf[sbuf.len-1] != '\n')
560 strbuf_addch(&sbuf, '\n');
562 failed = write_sha1_file(sbuf.buf, sbuf.len, commit_type, commit_sha1);
563 strbuf_release(&sbuf);
564 if (failed)
565 return 1;
567 if (verbosity > 1)
568 printf("Created %scommit %s\n",
569 parent_sha1 || next_commit.parents.nr ? "" : "initial ",
570 sha1_to_hex(commit_sha1));
572 if (update_ref(reflog, "HEAD", commit_sha1, NULL, 0, 0))
573 return error("Could not update HEAD to %s.",
574 sha1_to_hex(commit_sha1));
575 if (next_commit.parents.nr && available_marks.nr < marks_total &&
576 available_marks.items[available_marks.nr].string[0] == 'm')
577 ++available_marks.nr;
578 return 0;
581 static int do_commit_with_msgfile(unsigned char *parent_sha1)
583 strbuf_release(&next_commit.summary);
584 if (strbuf_read_file(&next_commit.summary, MESSAGE_FILE, 0) < 0)
585 return error("Could not read message file %s: %s.",
586 MESSAGE_FILE, strerror(errno));
587 stripspace(&next_commit.summary, 1);
588 if (!next_commit.summary.len)
589 return error("Commit message in %s is empty!", MESSAGE_FILE);
590 return do_commit(parent_sha1);
593 static int do_merge(void)
595 int i = 0;
596 int j;
597 const char **args;
599 args = xcalloc(next_commit.parents.nr + 5, sizeof(char *));
600 args[i++] = "merge";
601 args[i++] = "--no-commit";
602 if (merge_opt.strategy) {
603 args[i++] = "-s";
604 args[i++] = merge_opt.strategy;
606 if (next_commit.parents.nr) {
607 for (j = 0; j < next_commit.parents.nr; ++j)
608 args[i++] = next_commit.parents.items[j].string;
609 } else {
610 free(args);
611 return error("No parents specified.");
613 args[i++] = NULL;
614 j = run_command_v_opt(args, RUN_GIT_CMD | RUN_COMMAND_NO_STDIN);
615 free(args);
616 discard_cache();
617 return j;
621 * Fill next_commit.author according to ident.
622 * Ident may have one of the following forms:
623 * "name <e-mail> timestamp timezone\n..."
624 * "name <e-mail> timestamp timezone"
625 * "name <e-mail>"
627 static void set_author_info(const char *ident)
629 const char *tmp1 = strstr(ident, " <");
630 const char *tmp2;
631 char *data;
632 if (!tmp1)
633 return;
634 tmp2 = strstr(tmp1+2, ">");
635 if (!tmp2)
636 return;
637 if (tmp2[1] != 0 && tmp2[1] != ' ')
638 return;
640 data = xmalloc(strlen(ident)); /* a trivial upper bound */
642 snprintf(data, tmp1-ident+1, "%s", ident);
643 next_commit.author.name = xstrdup(data);
644 snprintf(data, tmp2-tmp1-1, "%s", tmp1+2);
645 next_commit.author.mail = xstrdup(data);
647 if (tmp2[1] == 0) {
648 free(data);
649 return;
652 tmp1 = strpbrk(tmp2+2, "\r\n");
653 if (!tmp1)
654 tmp1 = tmp2 + strlen(tmp2);
656 snprintf(data, tmp1-tmp2-1, "%s", tmp2+2);
657 next_commit.author.time = xstrdup(data);
658 free(data);
661 static void reset_next_commit(void)
663 const char *ident = git_author_info(IDENT_ERROR_ON_NO_NAME);
664 memset(&next_commit, 0, sizeof(next_commit));
665 strbuf_init(&next_commit.summary, 0);
666 set_author_info(ident);
669 static void set_message_source(const char *source)
671 if (next_commit.source)
672 free(next_commit.source);
673 next_commit.source = xstrdup(source);
676 /* Fill next_commit from commit header data (without commit summary),
677 * and return a pointer to the commit summary. */
678 static const char *get_commit_header(struct commit *commit, int get_parents)
680 const char *p = commit->buffer, *eol;
681 /* go through commit header */
682 while (*p && *p != '\n') {
683 eol = strchrnul(p + 1, '\n');
684 /* check for interesting headers */
685 if (!prefixcmp(p, "author "))
686 set_author_info(p + 7);
687 else if (!prefixcmp(p, "encoding "))
688 next_commit.encoding = xstrndup(p + 9, eol - p - 9);
689 else if (get_parents && !prefixcmp(p, "parent "))
690 string_list_append(xstrndup(p + 7, 40),
691 &next_commit.parents);
692 p = eol;
693 if (*p == '\n')
694 ++p;
696 return p;
699 /* Fill next_commit from commit data */
700 static void get_commit_info(struct commit *commit, int get_parents)
702 const char *p = get_commit_header(commit, get_parents);
703 if (*p)
704 strbuf_addstr(&next_commit.summary, p + 1);
705 set_message_source(sha1_to_hex(((struct object *)commit)->sha1));
708 /* Set subject, an information for the case of conflict */
709 static void set_pick_subject(const char *hex, struct commit *commit)
711 const char *tmp = strstr(commit->buffer, "\n\n");
712 if (tmp) {
713 const char *eol;
714 int len = strlen(hex);
715 tmp += 2;
716 eol = strchrnul(tmp, '\n');
717 next_commit.subject = xmalloc(eol - tmp + len + 5);
718 snprintf(next_commit.subject, eol - tmp + len + 5, "%s... %s",
719 hex, tmp);
723 /* Return a commit object of "arg" */
724 static struct commit *get_commit(const char *arg)
726 unsigned char sha1[20];
728 if (get_sha1(arg, sha1)) {
729 error("Could not find '%s'", arg);
730 return NULL;
732 return lookup_commit_reference(sha1);
735 static int fast_forward_possible(struct commit *commit)
737 struct commit_list *parents = commit->parents;
738 int i = 0;
740 /* check if first parent equal to HEAD */
741 if (!parents || hashcmp(head_sha1, parents->item->object.sha1))
742 return 0; /* not equal */
744 /* no other parents there? */
745 if (!parents->next && !next_commit.parents.nr)
746 return 1;
748 /* check if each further parent is equal */
749 while (parents->next) {
750 parents = parents->next;
751 if (i < next_commit.parents.nr) {
752 unsigned char sha[20];
753 if (get_sha1_hex(next_commit.parents.items[i].string,
754 sha))
755 return 0; /* no hex value */
756 if (hashcmp(sha, parents->item->object.sha1))
757 return 0; /* not equal */
758 } else
759 return 0; /* not equal number of parents */
760 ++i;
762 if (i < next_commit.parents.nr)
763 return 0; /* next commit will have further parents */
764 return 1; /* possible */
767 static int do_fast_forward(const unsigned char *sha)
769 if (reset_almost_hard(sha))
770 return error("Fast-forwarding %s failed.",
771 sha1_to_hex(sha));
772 if (verbosity > 1)
773 printf("Fast-forwarded %s\n",
774 sha1_to_hex(sha));
775 return 0;
778 static const char *resolve_symbolic_ref(const char *symref)
780 unsigned char dummy[20];
781 int flag;
782 const char *ref = resolve_ref(symref, dummy, 0, &flag);
783 return (flag & REF_ISSYMREF) ? ref : NULL;
787 * The --caller feature is for user scripts only. (Hence undocumented.)
788 * User scripts should pass an argument like:
789 * --caller="git foo|abrt|go|next"
790 * on every git sequencer call. (It is only ignored on
791 * --edit and --status.)
792 * So git sequencer knows that
793 * "git foo abrt" will abort,
794 * "git foo go" will continue and
795 * "git foo next" will skip the sequencing process.
796 * This is useful if your user script does some extra
797 * preparations or cleanup before/after calling
798 * git sequencer --caller="..." --abort|--continue|--skip
800 * Running git-sequencer without the same --caller string
801 * fails then, until the sequencing process has finished or
802 * aborted.
804 * Btw, --caller="my_tiny_script.sh|-a||" will be
805 * interpreted, that users must invoke "my_tiny_script.sh -a"
806 * to abort, but can invoke "git sequencer --continue" and
807 * "git sequencer --skip" to continue or skip.
808 * And it is also possible to provide three different scripts
809 * by --caller="|script 1|tool 2|util 3".
811 * If your user script does not need any special
812 * abort/continue/skip behavior, then just do NOT pass
813 * the --caller option.
815 static int prepare_caller_strings(const struct option *opt, const char *arg,
816 int unset)
818 struct strbuf **what;
819 char const **to[] = {
820 &caller_abort, &caller_continue, &caller_skip
822 struct strbuf arg_buf = STRBUF_INIT;
823 int len;
824 int i;
826 /* reset */
827 caller_abort = "git sequencer --abort";
828 caller_continue = "git sequencer --continue";
829 caller_skip = "git sequencer --skip";
830 if (unset) /* --no-caller: use reset caller */
831 return 0;
833 len = strlen(arg);
834 strbuf_add(&arg_buf, arg, len);
835 what = strbuf_split(&arg_buf, '|');
836 if (what[0]->len)
837 what[0]->buf[what[0]->len-1] = ' ';
838 for (i = 1; i < 4; ++i) {
839 if (!what[i])
840 return error("Wrong --caller format.");
841 if (i != 3) /* remove '|' delimiter in field 1 and 2 */
842 what[i]->len--;
843 if (!what[i]->len) /* keep the reset value if empty */
844 continue;
845 strbuf_insert(what[i], 0, what[0]->buf, what[0]->len);
846 *to[i - 1] = strbuf_detach(what[i], NULL);
848 strbuf_list_free(what);
849 strbuf_release(&arg_buf);
850 return 0;
853 /* Generate a real ref from :mark. ref is limited to 50 bytes. */
854 static int mark_to_ref(const char *arg, char *ref, int allow_uncoloned) {
855 if (!arg)
856 return 1;
857 if (arg[0] == ':')
858 snprintf(ref, 50, SEQ_MARK "/%d", atoi(arg + 1));
859 else if (allow_uncoloned)
860 snprintf(ref, 50, SEQ_MARK "/%d", atoi(arg));
861 else
862 return 1;
863 return 0;
866 /* Like get_sha1(), but also takes :mark as argument */
867 static int mark_to_sha1(const char *arg, unsigned char *sha1) {
868 char ref[50];
869 const char *x = ref;
870 if (mark_to_ref(arg, ref, 0))
871 x = arg;
872 if (get_sha1(x, sha1))
873 return 1;
874 return 0;
877 /* Is next_commit.summary empty? Ignore comments and Signed-off-by lines */
878 static int message_is_empty(void)
880 char *tmp;
881 stripspace(&next_commit.summary, 1);
882 if (!next_commit.summary.len)
883 return 1;
884 tmp = next_commit.summary.buf;
885 /* Ignore newlines and Signed-off-by: lines */
886 while (*tmp) {
887 while (*tmp++ == '\n');
888 if (!*tmp)
889 return 1;
890 if (!prefixcmp(tmp, "Signed-off-by:")) {
891 tmp = strchr(tmp + 14, '\n');
892 if (!tmp)
893 return 1;
894 ++tmp;
895 } else
896 return 0;
898 return 0;
901 static int set_verbosity(int verbose)
903 char tmp[] = "0";
904 verbosity = verbose;
905 if (verbosity <= 0) {
906 verbosity = 0;
907 advice = 0;
908 } else if (verbosity > 5)
909 verbosity = 5;
910 /* Git does not run on EBCDIC, so we rely on ASCII: */
911 tmp[0] += verbosity;
912 setenv("GIT_MERGE_VERBOSITY", tmp, 1);
913 return 0;
917 /**********************************************************************
918 * Functions that deal with saving and loading
921 static int write_commit_summary_into(const char *filename)
923 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
924 int fd = hold_lock_file_for_update(lock, filename, 0);
925 if (fd < 0)
926 return error("Unable to create '%s.lock': %s", filename,
927 strerror(errno));
928 if (write_in_full(fd, next_commit.summary.buf,
929 next_commit.summary.len) < 0)
930 return error("Could not write to %s: %s",
931 filename, strerror(errno));
932 if (commit_lock_file(lock) < 0)
933 return error("Error wrapping up %s", filename);
934 return 0;
937 /* Run the prepare-commit-msg hook on COMMIT_EDITMSG. */
938 static int prepare_commit_msg_hook(void)
940 const char *hook_arg1 = next_commit.source;
941 const char *hook_arg2 = NULL;
943 if (hook_arg1 &&
944 strcmp(hook_arg1, "message") &&
945 strcmp(hook_arg1, "template") &&
946 strcmp(hook_arg1, "merge") &&
947 strcmp(hook_arg1, "squash"))
949 hook_arg2 = hook_arg1;
950 hook_arg1 = "commit";
953 return run_hook(NULL, "prepare-commit-msg", COMMIT_EDITMSG,
954 hook_arg1, hook_arg2, NULL);
957 /* Copy file with mode 0666. If destination exists, unlink it before. */
958 static int copy_file_overwrite(const char *dst, const char *src)
960 if (file_exists(dst))
961 unlink(dst);
962 return copy_file(dst, src, 0666);
965 /* Edit commit message in COMMIT_EDITMSG. */
966 static int edit_message(int from_buf)
968 if (from_buf) {
969 if (write_commit_summary_into(COMMIT_EDITMSG))
970 return -1;
971 } else {
972 char *tmp = xstrdup(COMMIT_EDITMSG);
973 if (copy_file_overwrite(tmp, MESSAGE_FILE)) {
974 error("Could not copy '%s' to '%s'.",
975 MESSAGE_FILE, tmp);
976 free(tmp);
977 return -1;
979 free(tmp);
982 /* Run prepare-commit-msg hook and editor, ... */
983 if (prepare_commit_msg_hook() ||
984 launch_editor(COMMIT_EDITMSG, NULL, NULL))
985 return -1;
987 /* ...reread, ... */
988 strbuf_release(&next_commit.summary);
989 if (strbuf_read_file(&next_commit.summary, COMMIT_EDITMSG, 0) < 0)
990 return error("Could not read message file %s.", COMMIT_EDITMSG);
991 if (message_is_empty())
992 return error("No commit message given.");
994 /* ...and copy to our general message file. */
995 return write_commit_summary_into(MESSAGE_FILE);
998 /* Save a string that can be worthy after a pause. */
999 static int save(const char *name, const char *value)
1001 int ret;
1002 config_exclusive_filename = SAVE_FILE;
1003 ret = git_config_set(name, value);
1004 config_exclusive_filename = NULL;
1005 return ret;
1008 /* Save an integer that can be worthy after a pause. */
1009 static int save_int(const char *name, ssize_t value)
1011 char tmp[50];
1012 snprintf(tmp, sizeof(tmp), "%zi", value);
1013 return save(name, tmp);
1016 static int save_commit_data(void)
1018 char *msgfile;
1019 if (next_commit.author.name)
1020 save("sequencer.author.name", next_commit.author.name);
1021 if (next_commit.author.mail)
1022 save("sequencer.author.mail", next_commit.author.mail);
1023 if (next_commit.author.time)
1024 save("sequencer.author.time", next_commit.author.time);
1025 if (next_commit.encoding)
1026 save("sequencer.encoding", next_commit.encoding);
1027 if (die_with_merges && next_commit.parents.nr > 0) {
1028 FILE *fp;
1029 int i;
1030 /* write parents to MERGE_HEAD */
1031 fp = fopen(MERGE_HEAD, "w");
1032 if (!fp)
1033 return error("Could not open %s for writing.",
1034 MERGE_HEAD);
1035 for (i = 0; i < next_commit.parents.nr; ++i)
1036 if (fprintf(fp, "%s\n",
1037 next_commit.parents.items[i].string) < 0)
1038 return error("Could not write into %s.",
1039 MERGE_HEAD);
1040 fclose(fp);
1042 msgfile = MERGE_MSG;
1043 } else
1044 msgfile = COMMIT_EDITMSG;
1045 if (write_commit_summary_into(msgfile))
1046 return 1;
1047 if (write_commit_summary_into(MESSAGE_FILE))
1048 return 1;
1049 return 0;
1052 static int saved_options(const char *var, const char *value, void *cb)
1054 if (!strcmp(var, "sequencer.advice")) {
1055 advice = git_config_bool(var, value);
1056 return 0;
1058 if (!strcmp(var, "sequencer.allowdirty")) {
1059 allow_dirty = git_config_bool(var, value);
1060 return 0;
1062 if (!strcmp(var, "sequencer.author.name"))
1063 return git_config_string(&next_commit.author.name, var, value);
1064 if (!strcmp(var, "sequencer.author.mail"))
1065 return git_config_string(&next_commit.author.mail, var, value);
1066 if (!strcmp(var, "sequencer.author.time"))
1067 return git_config_string(&next_commit.author.time, var, value);
1068 if (!strcmp(var, "sequencer.encoding"))
1069 return git_config_string(&next_commit.encoding, var, value);
1070 if (!strcmp(var, "sequencer.headname"))
1071 return git_config_string(&orig_headname, var, value);
1072 if (!strcmp(var, "sequencer.skiphead"))
1073 return git_config_string(&skiphead, var, value);
1074 if (!strcmp(var, "sequencer.head")) {
1075 const char *head;
1076 if (git_config_string(&head, var, value))
1077 return 1;
1078 return get_sha1(head, orig_head_sha1);
1080 if (!strcmp(var, "sequencer.pausedat")) {
1081 const char *paused_at;
1082 if (git_config_string(&paused_at, var, value))
1083 return 1;
1084 return get_sha1(paused_at, paused_at_sha1);
1086 if (!strcmp(var, "sequencer.availmarks")) {
1087 const char *tmp1;
1088 if (git_config_string(&tmp1, var, value))
1089 return 1;
1090 while (tmp1) {
1091 const char *tmp2 = strchrnul(tmp1, ' ');
1092 string_list_append(xstrndup(tmp1, tmp2-tmp1),
1093 &available_marks);
1094 if (tmp2[0])
1095 tmp1 = tmp2+1;
1096 else
1097 tmp1 = NULL;
1099 return 0;
1101 if (!prefixcmp(var, "sequencer.caller.")) {
1102 const char *cmp = var+17, **expect;
1103 int action = 0;
1104 if (!strcmp(cmp, "abort")) {
1105 expect = &caller_abort;
1106 action = ACTION_ABORT;
1107 } else if (!strcmp(cmp, "continue")) {
1108 expect = &caller_continue;
1109 action = ACTION_CONTINUE;
1110 } else if (!strcmp(cmp, "skip")) {
1111 expect = &caller_skip;
1112 action = ACTION_SKIP;
1113 } else
1114 return 1;
1115 if (git_config_string(&cmp, var, value))
1116 return 1;
1117 if (strcmp(cmp, *expect)) {
1118 caller_check_failed |= action;
1119 *expect = cmp;
1121 return 0;
1123 if (!strcmp(var, "sequencer.squashcount")) {
1124 squash_count = git_config_int(var, value);
1125 return 0;
1127 if (!strcmp(var, "sequencer.verbosity"))
1128 return set_verbosity(git_config_int(var, value));
1129 if (!strcmp(var, "sequencer.why")) {
1130 why = git_config_int(var, value);
1131 return 0;
1133 return 1;
1136 static int get_saved_options(void)
1138 memset(&available_marks, 0, sizeof(struct string_list));
1139 if (git_config_from_file(saved_options, SAVE_FILE, NULL))
1140 return 1;
1141 marks_total = available_marks.nr;
1142 return 0;
1145 static void add_comment_to_donefile(const char *comment)
1147 FILE *fp = fopen(DONE_FILE, "a");
1148 if (!fp)
1149 return;
1150 fprintf(fp, "# %s\n", comment);
1151 fclose(fp);
1155 /**********************************************************************
1156 * Several die() and restore functions
1159 /* Restore refs updated by ref insn */
1160 static void restore_refs(void)
1162 struct strbuf buf = STRBUF_INIT;
1163 struct string_list list;
1164 FILE *fp = fopen(DESTINY_FILE, "r");
1165 if (!fp) {
1166 warning("Could not open file '%s': %s",
1167 DESTINY_FILE, strerror(errno));
1168 fprintf(stderr, "Hence I cannot restore updated refs.\n");
1169 return;
1171 memset(&list, 0, sizeof(struct string_list));
1172 while (strbuf_getline(&buf, fp, '\n') != EOF) {
1173 unsigned char sha[20];
1174 char *ref = strbuf_detach(&buf, NULL);
1176 if (strbuf_getline(&buf, fp, '\n') == EOF) {
1177 warning("This must not happen! "
1178 "Destiny file seems to be broken...");
1179 break;
1182 if (!string_list_has_string(&list, ref)) {
1183 /* insert into list and restore ref */
1184 if (buf.len > 1) {
1185 if (get_sha1(buf.buf, sha)) {
1186 warning("Could not reset ref '%s' to "
1187 "%s, because the SHA1 does not exist.",
1188 ref, buf.buf);
1189 free(ref);
1190 continue;
1192 update_ref(reflog, ref, sha, NULL, 0,
1193 MSG_ON_ERR);
1194 } else
1195 delete_ref(ref, NULL, 0);
1196 string_list_insert(ref, &list);
1197 } else
1198 free(ref);
1200 strbuf_release(&buf);
1201 list.strdup_strings = 1; /* free items */
1202 string_list_clear(&list, 0);
1205 static int restore(void)
1207 int failed;
1208 if (file_exists(DESTINY_FILE))
1209 restore_refs();
1210 failed = reset_almost_hard(orig_head_sha1);
1211 if (!failed && orig_headname)
1212 create_symref("HEAD", orig_headname, reflog);
1213 return failed;
1216 static NORETURN void die_abort_cb(const char *err, va_list params)
1218 restore();
1219 cleanup();
1220 if (!params)
1221 fprintf(stderr, "%s", err);
1222 else
1223 vfprintf(stderr, err, params);
1224 fprintf(stderr, "\n");
1225 exit(1);
1228 static void prepare_for_continue(void)
1230 if (batchmode)
1231 die_abort_cb("Aborting, because of batch mode.", NULL);
1232 save_int("sequencer.squashcount", squash_count);
1233 if (why == WHY_UNKNOWN)
1234 why = WHY_CONFLICT;
1235 save_int("sequencer.why", why);
1236 if (why == WHY_PAUSE || why == WHY_RUN) {
1237 if (get_sha1("HEAD", head_sha1))
1238 die("You do not have a valid HEAD.");
1239 save("sequencer.pausedat", sha1_to_hex(head_sha1));
1241 if (why != WHY_TODO) {
1242 int i;
1243 struct strbuf tmp = STRBUF_INIT;
1244 save_commit_data();
1245 for (i = 0; i < available_marks.nr; ++i) {
1246 strbuf_addstr(&tmp, available_marks.items[i].string);
1247 strbuf_addch(&tmp, ' ');
1249 save("sequencer.availmarks", tmp.buf);
1250 strbuf_release(&tmp);
1252 print_advice();
1253 small_cleanup();
1256 static NORETURN void die_continue_cb(const char *err, va_list params)
1258 vfprintf(stderr, err, params);
1259 fprintf(stderr, "\n");
1260 prepare_for_continue();
1261 exit(3);
1265 /**********************************************************************
1266 * "patch" related helper functions
1269 /* Invoke git-apply, to be used by insn patch */
1270 static int do_apply(const char *patch, const char *const *env, ...)
1272 va_list params;
1273 const char *args[50];
1274 const char *arg;
1275 int i = 0;
1276 int j;
1277 struct child_process chld;
1279 memset(&chld, 0, sizeof(chld));
1280 args[i++] = "apply";
1282 if (patch_opt.apply.nr >= ARRAY_SIZE(args))
1283 return error("too many arguments to git-apply.");
1284 for (j = 0; j < patch_opt.apply.nr; ++j)
1285 args[i++] = patch_opt.apply.items[j].string;
1287 va_start(params, env);
1288 while ((arg = va_arg(params, const char *)) &&
1289 (i < ARRAY_SIZE(args) - 1))
1290 args[i++] = arg;
1291 va_end(params);
1292 args[i++] = NULL;
1293 if (arg)
1294 return error("too many arguments to git-apply.");
1296 chld.argv = args;
1297 chld.env = env;
1298 chld.git_cmd = 1;
1299 chld.in = -1;
1300 if (!verbosity || patch_opt.threeway) {
1301 /* When we are allowed to fall back to 3-way later,
1302 * don't give false errors during the initial attempt. */
1303 chld.no_stdout = 1;
1304 chld.no_stderr = 1;
1307 if (start_command(&chld))
1308 return 1;
1310 if (write(chld.in, patch, strlen(patch)) < 0) {
1311 close(chld.in);
1312 finish_command(&chld);
1313 return error("Could not write to git-apply.");
1316 close(chld.in);
1317 return finish_command(&chld);
1320 /* This is a slightly simplified version of write_cache_as_tree() for
1321 * temporary index files. */
1322 static int write_cache_as_tree_temp(unsigned char *sha1, const char *indexfile)
1324 int entries, was_valid, newfd;
1325 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
1327 newfd = hold_lock_file_for_update(lock_file, indexfile, 0);
1328 if (newfd < 0)
1329 return error("Could not lock %s.", indexfile);
1331 entries = read_cache_from(indexfile);
1332 if (entries < 0)
1333 return error("Could not read the temporary index.");
1335 if (!active_cache_tree)
1336 active_cache_tree = cache_tree();
1338 was_valid = cache_tree_fully_valid(active_cache_tree);
1340 if (!was_valid) {
1341 if (cache_tree_update(active_cache_tree,
1342 active_cache, active_nr,
1343 0, 0) < 0)
1344 return WRITE_TREE_UNMERGED_INDEX;
1345 if (0 <= newfd) {
1346 if (!write_cache(newfd, active_cache, active_nr) &&
1347 !commit_lock_file(lock_file))
1348 newfd = -1;
1350 /* Not being able to write is fine -- we are only interested
1351 * in updating the cache-tree part, and if the next caller
1352 * ends up using the old index with unupdated cache-tree part
1353 * it misses the work we did here, but that is just a
1354 * performance penalty and not a big deal.
1358 hashcpy(sha1, active_cache_tree->sha1);
1360 if (0 <= newfd)
1361 rollback_lock_file(lock_file);
1363 return 0;
1366 static int fallback_threeway(const char *patch, const char *subject)
1368 unsigned char base_sha1[20];
1369 unsigned char next_sha1[20];
1370 const char *env[2];
1371 char tmp[PATH_MAX];
1372 struct merge_options o;
1373 struct tree *result, *next_tree, *base_tree, *head_tree;
1374 static struct lock_file index_lock;
1375 int index_fd, clean;
1376 const char *index_file = git_path(SEQ_DIR "/index-3way");
1378 /* First see if the patch records the index info that we can use. */
1379 if (do_apply(patch, NULL, "--build-fake-ancestor", index_file, NULL))
1380 return error("Could not build fake ancestor for 3way merge.");
1382 discard_cache();
1383 if (write_cache_as_tree_temp(base_sha1, index_file)) {
1384 unlink(index_file);
1385 if (verbosity)
1386 fprintf(stderr, "Repository lacks necessary blobs "
1387 "to fall back on 3-way merge.\n");
1388 return 1;
1391 if (verbosity)
1392 puts("Using index info to reconstruct a base tree...");
1394 memset(env, 0, sizeof(env));
1395 snprintf(tmp, PATH_MAX, "GIT_INDEX_FILE=%s", index_file);
1396 env[0] = tmp;
1398 if (do_apply(patch, env, "--cached", NULL)) {
1399 unlink(index_file);
1400 return error("Patch does not apply to blobs recorded in its index.");
1403 discard_cache();
1404 if (write_cache_as_tree_temp(next_sha1, index_file)) {
1405 unlink(index_file);
1406 return 1;
1408 unlink(index_file);
1410 if (verbosity)
1411 puts("Falling back to patching base and 3-way merge...");
1414 * This is not so wrong. Depending on which base we picked,
1415 * the merge base (base_sha1) may be wildly different from ours,
1416 * but the new tree (next_sha1) has the same set of wildly
1417 * different changes in parts the patch did not touch, so
1418 * recursive ends up canceling them, saying that we reverted
1419 * all those changes.
1422 discard_cache();
1423 index_fd = hold_locked_index(&index_lock, 0);
1424 if (index_fd < 0)
1425 return error("Unable to create locked index: %s",
1426 strerror(errno));
1428 read_cache();
1429 init_merge_options(&o);
1430 o.branch1 = "HEAD";
1431 o.branch2 = subject;
1432 base_tree = parse_tree_indirect(base_sha1);
1433 head_tree = parse_tree_indirect(head_sha1);
1434 next_tree = parse_tree_indirect(next_sha1);
1436 clean = merge_trees(&o, head_tree, next_tree, base_tree, &result);
1437 if ((write_cache(index_fd, active_cache, active_nr) ||
1438 commit_locked_index(&index_lock)))
1439 return error("Could not write new index file.");
1441 discard_cache();
1442 if (!clean) {
1443 rerere();
1444 write_commit_summary_into(MERGE_MSG);
1445 return error("Failed to merge in the changes.");
1447 return 0;
1450 /* A helper for mailinfo() */
1451 static char *get_info_from_infofile(char *buf, const char *what)
1453 char *tmp1, *tmp2;
1454 char *info = NULL;
1456 tmp1 = strstr(buf, what);
1457 if (tmp1) {
1458 char c;
1459 tmp1 += strlen(what);
1460 tmp2 = strpbrk(tmp1, "\r\n");
1461 if (tmp2) {
1462 c = *tmp2;
1463 *tmp2 = 0;
1465 info = xstrdup(tmp1);
1466 if (tmp2)
1467 *tmp2 = c;
1469 return info;
1473 * Invoke git-mailinfo, to be used by insn patch.
1474 * Set info, if return value is 0, otherwise info is in undefined state.
1476 static int mailinfo(int ifd, struct commit_info *info)
1478 const char *args[5];
1479 int i = 0;
1480 struct child_process chld;
1481 struct strbuf buf = STRBUF_INIT;
1482 char *msgfile = git_pathdup(SEQ_DIR "/patch-msg");
1483 char time[50];
1485 memset(&chld, 0, sizeof(chld));
1487 args[i++] = "mailinfo";
1488 if (patch_opt.keep)
1489 args[i++] = "-k";
1490 if (patch_opt.noutf8)
1491 args[i++] = "-n";
1492 args[i++] = msgfile;
1493 args[i++] = PATCH_FILE;
1494 args[i++] = NULL;
1496 chld.argv = args;
1497 chld.git_cmd = 1;
1498 chld.in = ifd;
1499 chld.out = -1;
1501 if (start_command(&chld))
1502 return 1;
1504 if (strbuf_read(&buf, chld.out, 1024) < 0) {
1505 close(chld.out);
1506 finish_command(&chld);
1507 return error("Could not read from git-mailinfo.");
1510 close(chld.out);
1511 if (finish_command(&chld)) {
1512 strbuf_release(&buf);
1513 return 1;
1516 /* parse the information from the infofile */
1517 info->subject = get_info_from_infofile(buf.buf, "Subject: ");
1518 info->author.name = get_info_from_infofile(buf.buf, "Author: ");
1519 info->author.mail = get_info_from_infofile(buf.buf, "Email: ");
1520 info->author.time = get_info_from_infofile(buf.buf, "Date: ");
1521 if (info->author.time) {
1522 parse_date(info->author.time, time, sizeof(time));
1523 free((void *)info->author.time);
1524 info->author.time = xstrdup(time);
1526 strbuf_release(&buf);
1528 /* get message */
1529 if (info->subject) {
1530 next_commit.subject = xstrdup(info->subject);
1531 strbuf_addstr(&buf, info->subject);
1532 strbuf_addstr(&buf, "\n\n");
1535 if (run_hook(NULL, "applypatch-msg", msgfile, NULL))
1536 return error("Hook applypatch-msg failed.");
1537 if (strbuf_read_file(&buf, msgfile, 1024) < 0)
1538 return error("Could not read message file %s: %s",
1539 msgfile, strerror(errno));
1540 stripspace(&buf, 0);
1542 unlink(msgfile);
1543 free(msgfile);
1545 strbuf_addbuf(&info->summary, &buf);
1546 strbuf_release(&buf);
1548 /* get patch */
1549 if (file_exists(PATCH_FILE)) {
1550 if (strbuf_read_file(&buf, PATCH_FILE, 4096) < 0)
1551 return error("Could not read patch %s: %s",
1552 PATCH_FILE, strerror(errno));
1553 info->patch = strbuf_detach(&buf, NULL);
1555 return 0;
1559 /**********************************************************************
1560 * "squash" related helper functions
1563 static char *nth_string(int i)
1565 static char nth[50];
1566 const char *suffix;
1567 switch (i % 10) {
1568 case 1:
1569 suffix = "st";
1570 break;
1571 case 2:
1572 suffix = "nd";
1573 break;
1574 case 3:
1575 suffix = "rd";
1576 break;
1577 default:
1578 suffix = "th";
1580 if ((i / 10) % 10 == 1) /* 11th, 12th, 13th */
1581 suffix = "th";
1582 snprintf(nth, sizeof(nth), "%d%s", i, suffix);
1583 return nth;
1586 static int make_squash_message_multiple(unsigned char *sha,
1587 unsigned char *base_sha)
1589 struct strbuf buf;
1590 char range[50];
1591 struct rev_info revs;
1592 struct commit *commit;
1593 int i = squash_count;
1594 init_revisions(&revs, NULL);
1595 snprintf(range, sizeof(range), "%s..HEAD", sha1_to_hex(sha));
1596 revs.abbrev = 40;
1597 revs.reverse = 1;
1598 if (handle_revision_arg(range, &revs, 0, 1))
1599 return error("Revision argument handling failed.");
1600 if (prepare_revision_walk(&revs))
1601 return error("Revision walk setup failed.");
1602 strbuf_init(&buf, 8192);
1603 while ((commit = get_revision(&revs))) {
1604 /* write base_sha to return it */
1605 if (i == squash_count && base_sha)
1606 hashcpy(base_sha, commit->object.sha1);
1607 /* write commit messages into buf */
1608 strbuf_addf(&buf, "\n# This is the %s commit message:",
1609 nth_string(++i));
1610 strbuf_addstr(&buf, strstr(commit->buffer, "\n\n"));
1612 squash_count = i;
1613 /* prepend an introduction message */
1614 strbuf_addf(&next_commit.summary,
1615 "# This is a combination of %d commits.\n%s",
1616 squash_count, buf.buf);
1617 strbuf_release(&buf);
1618 return 0;
1621 static void make_squash_message(struct strbuf *msg)
1623 char *tmp;
1624 if (squash_count)
1625 ++squash_count;
1626 else
1627 squash_count = 2;
1629 strbuf_addf(&next_commit.summary,
1630 "# This is a combination of %d commits.\n", squash_count);
1632 if (file_exists(SQUASH_MSG)) {
1633 struct strbuf buf;
1634 strbuf_init(&buf, 8192);
1635 if (strbuf_read_file(&buf, SQUASH_MSG, 0) < 0) {
1636 warning("Could not read message file %s.",
1637 SQUASH_MSG);
1638 goto rest;
1640 if (!prefixcmp(buf.buf, "# This is a")) {
1641 tmp = strchr(buf.buf, '\n');
1642 if (!tmp)
1643 tmp = buf.buf;
1644 strbuf_addf(&next_commit.summary, "%s\n", tmp+1);
1646 strbuf_release(&buf);
1647 } else {
1648 struct commit *head = lookup_commit_reference(head_sha1);
1649 if (!head)
1650 goto rest;
1651 tmp = strstr(head->buffer, "\n\n");
1652 if (tmp)
1653 strbuf_addf(&next_commit.summary,
1654 "# This is the 1st commit message:%s\n",
1655 tmp);
1657 rest:
1658 strbuf_addf(&next_commit.summary,
1659 "# This is the %s commit message:\n\n",
1660 nth_string(squash_count));
1661 strbuf_addbuf(&next_commit.summary, msg);
1664 static int peek_next_insn(void)
1666 struct parsed_insn *cur = contents.cur->next;
1667 for (; cur && !cur->argv; cur = cur->next);
1668 if (!cur)
1669 return -1;
1670 return find_insn(cur->argv[0]);
1674 /**********************************************************************
1675 * Helpers for the sanity check phase
1678 /* Raise an error on todo checking */
1679 static int todo_error(const char *fmt, ...)
1681 va_list params;
1682 char msg[256];
1684 snprintf(msg, sizeof(msg), "error at line %d: %s\n", todo_line, fmt);
1685 va_start(params, fmt);
1686 vfprintf(stderr, msg, params);
1687 va_end(params);
1689 return 1;
1692 /* Print a warning on todo checking */
1693 static void todo_warn(const char *fmt, ...)
1695 va_list params;
1696 char msg[256];
1698 snprintf(msg, sizeof(msg), "warning at line %d: %s\n", todo_line, fmt);
1699 va_start(params, fmt);
1700 vfprintf(stderr, msg, params);
1701 va_end(params);
1704 /* Return 1 if arg is a mark (must be colon-prefixed), 0 otherwise */
1705 static int arg_is_mark(const char *arg)
1707 if (!unsorted_string_list_has_string(&available_marks, arg))
1708 return !todo_error("Mark %s is not yet defined.", arg);
1709 return 1;
1712 /* Return commit struct if arg is a commit, NULL + todo_error otherwise */
1713 static struct commit *arg_is_commit(const char *arg)
1715 unsigned char sha1[20];
1716 struct commit *commit;
1717 if (get_sha1(arg, sha1)) {
1718 todo_error("Could not find '%s'.", arg);
1719 return NULL;
1721 if (!(commit = lookup_commit_reference_gently(sha1, 1))) {
1722 todo_error("Object '%s' is no commit.", arg);
1723 return NULL;
1725 return commit;
1728 /* Check if arg is in available_marks or a real commit */
1729 static int arg_is_mark_or_commit(const char *arg)
1731 if (arg[0] == ':')
1732 return arg_is_mark(arg);
1733 else
1734 return (arg_is_commit(arg) != NULL);
1738 /**********************************************************************
1739 * Functions for dealing with general options
1742 static int check_general_options(void)
1744 int msg = 0;
1745 if (opt.author) {
1746 const char *tmp1;
1747 tmp1 = strstr(opt.author, " <");
1748 if (tmp1 < opt.author+1 || tmp1[strlen(tmp1)-1] != '>')
1749 return todo_error("Author '%s' not in the correct format 'Name <e-mail>'.",
1750 opt.author);
1752 if (opt.reuse_message) {
1753 ++msg;
1754 if (!arg_is_commit(opt.reuse_message))
1755 return 1;
1757 if (opt.message)
1758 ++msg;
1759 if (opt.file) {
1760 ++msg;
1761 if (!file_exists(opt.file))
1762 return todo_error("File '%s' does not exist.", opt.file);
1763 /* Also check for readability? */
1765 if (opt.edit && batchmode)
1766 return todo_error("--batch and --edit options do not make sense together");
1767 if (opt.reuse_commit) {
1768 if (!arg_is_commit(opt.reuse_commit))
1769 return 1;
1770 if (msg)
1771 todo_warn("-M/-m/-F override message of -C option.");
1773 return 0;
1776 static int has_general_options(void)
1778 return (opt.reuse_commit || opt.author || opt.file || opt.message ||
1779 opt.reuse_message || opt.signoff || opt.edit);
1782 static int handle_general_options(void)
1784 if (opt.reuse_commit) {
1785 struct commit *commit = get_commit(opt.reuse_commit);
1786 strbuf_reset(&next_commit.summary);
1787 if (next_commit.author.name)
1788 free((void *)next_commit.author.name);
1789 if (next_commit.author.mail)
1790 free((void *)next_commit.author.mail);
1791 if (next_commit.author.time)
1792 free((void *)next_commit.author.time);
1793 if (next_commit.encoding)
1794 free((void *)next_commit.encoding);
1795 get_commit_info(commit, 0);
1797 if (opt.author) {
1798 if (next_commit.author.name)
1799 free((void *)next_commit.author.name);
1800 if (next_commit.author.mail)
1801 free((void *)next_commit.author.mail);
1802 if (next_commit.author.time) {
1803 free((void *)next_commit.author.time);
1804 next_commit.author.time = NULL; /* reset time */
1806 set_author_info(opt.author);
1808 if (opt.reuse_message) {
1809 struct commit *commit = get_commit(opt.reuse_message);
1810 const char *tmp = strstr(commit->buffer, "\n\n");
1811 strbuf_reset(&next_commit.summary);
1812 if (tmp)
1813 strbuf_addstr(&next_commit.summary, tmp+2);
1814 set_message_source("message");
1816 if (opt.file) {
1817 strbuf_reset(&next_commit.summary);
1818 if (strbuf_read_file(&next_commit.summary, opt.file, 8192) < 0)
1819 return error("Could not read message file %s.",
1820 opt.file);
1821 set_message_source("message");
1823 if (opt.message) {
1824 strbuf_reset(&next_commit.summary);
1825 strbuf_addstr(&next_commit.summary, opt.message);
1826 set_message_source("message");
1828 /* add trailing \n to message */
1829 if (next_commit.summary.len &&
1830 next_commit.summary.buf[next_commit.summary.len-1] != '\n')
1831 strbuf_addch(&next_commit.summary, '\n');
1832 if (opt.signoff) {
1833 struct strbuf tmp = STRBUF_INIT;
1834 int i;
1836 strbuf_addstr(&tmp, "Signed-off-by: ");
1837 strbuf_addstr(&tmp, fmt_name(getenv("GIT_COMMITTER_NAME"),
1838 getenv("GIT_COMMITTER_EMAIL")));
1839 strbuf_addch(&tmp, '\n');
1840 for (i = next_commit.summary.len-1; i > 0 &&
1841 next_commit.summary.buf[i-1] != '\n'; i--);
1842 if (prefixcmp(next_commit.summary.buf + i, tmp.buf)) {
1843 if (prefixcmp(next_commit.summary.buf + i,
1844 "Signed-off-by: "))
1845 strbuf_addch(&next_commit.summary, '\n');
1846 strbuf_addbuf(&next_commit.summary, &tmp);
1848 strbuf_release(&tmp);
1850 return 0;
1853 static int has_general_message_option(void)
1855 return opt.reuse_commit || opt.reuse_message || opt.file || opt.message;
1860 /**********************************************************************
1861 * Data structures and functions for TODO instructions
1864 static struct option no_insn_options[] = {
1865 OPT_END(),
1869 /* noop */
1870 static const char * const insn_noop_usage[] = {
1871 "noop",
1872 NULL
1875 static int insn_noop_check(int argc, const char **argv)
1877 if (argc)
1878 return todo_error("Instruction takes no arguments.");
1879 return 0;
1882 static int insn_noop_act(int argc, const char **argv)
1884 return 0;
1888 /* pause */
1889 static const char * const insn_pause_usage[] = {
1890 "pause",
1891 NULL
1894 static int insn_pause_check(int argc, const char **argv)
1896 if (batchmode)
1897 return todo_error("Instruction does not make sense in batch mode.");
1898 if (argc)
1899 return todo_error("Instruction takes no arguments.");
1900 return 0;
1903 static int insn_pause_act(int argc, const char **argv)
1905 /* We do not use reset_next_commit() after "pick" in the "edit"
1906 * insn, so perhaps next_commit is still set. We take a non-empty
1907 * commit message as evidence that next_commit is still set. */
1908 if (message_is_empty()) {
1909 struct commit *commit = lookup_commit_reference(head_sha1);
1910 get_commit_info(commit, 1);
1912 why = WHY_PAUSE;
1913 prepare_for_continue();
1914 exit(2);
1918 /* pick */
1919 static const char * const insn_pick_usage[] = {
1920 "pick [options] <commit>",
1921 NULL
1924 static struct option insn_pick_options[] = {
1925 OPT_BOOLEAN('R', "reverse", &pick_opt.reverse,
1926 "revert introduced changes"),
1927 OPT_INTEGER(0, "mainline", &pick_opt.mainline,
1928 "specify parent number to use for merge commits"),
1929 OPT_GENERAL_OPTIONS,
1930 OPT_END(),
1933 static void insn_pick_init(void)
1935 memset(&pick_opt, 0, sizeof(pick_opt));
1938 static int insn_pick_check(int argc, const char **argv)
1940 struct commit *commit;
1941 if (argc != 1)
1942 return todo_error("Wrong number of arguments. "
1943 "(%d given, 1 wanted)", argc);
1944 if (!(commit = arg_is_commit(argv[0])))
1945 return 1;
1946 if (check_general_options())
1947 return 1;
1948 if (pick_opt.mainline) {
1949 int parents = commit_list_count(commit->parents);
1950 if (parents < pick_opt.mainline)
1951 return todo_error("Commit has only %d (less than %d) "
1952 "parents.", parents, pick_opt.mainline);
1953 if (parents <= 1)
1954 todo_warn("Commit is not a merge at all.");
1956 return 0;
1959 static int insn_pick_act(int argc, const char **argv)
1961 struct commit *commit = get_commit(argv[0]);
1962 const char *author;
1963 int failed;
1964 int pick_flags = 0;
1966 set_pick_subject(argv[0], commit);
1968 if (pick_opt.reverse)
1969 pick_flags |= PICK_REVERSE;
1971 /* Be kind to users and ignore --mainline=1 on non-merge commits */
1972 if (pick_opt.mainline && commit_list_count(commit->parents) < 2)
1973 pick_opt.mainline = 0;
1975 if (!pick_opt.reverse && fast_forward_possible(commit) &&
1976 !has_general_options())
1977 return do_fast_forward(commit->object.sha1);
1979 failed = pick_commit(commit, pick_opt.mainline, pick_flags,
1980 &next_commit.summary);
1981 set_message_source(sha1_to_hex(((struct object *)commit)->sha1));
1982 author = strstr(commit->buffer, "\nauthor ");
1983 if (author)
1984 set_author_info(author + 8);
1986 /* We do not want extra Conflicts: lines on cherry-pick,
1987 so just take the old commit message. */
1988 if (failed && !pick_opt.reverse) {
1989 strbuf_setlen(&next_commit.summary, 0);
1990 strbuf_addstr(&next_commit.summary,
1991 strstr(commit->buffer, "\n\n")+2);
1994 if (handle_general_options())
1995 return 1;
1997 if (!failed && (message_is_empty() || opt.edit))
1998 if (edit_message(1))
1999 return 1;
2001 if (failed) {
2002 rerere();
2003 make_patch(commit);
2004 write_commit_summary_into(MERGE_MSG);
2005 return error("Picking %s failed.",
2006 sha1_to_hex(commit->object.sha1));
2009 if (do_commit(head_sha1))
2010 return error("Could not commit.");
2012 return 0;
2016 /* patch */
2017 static const char * const insn_patch_usage[] = {
2018 "patch [options] <file>",
2019 NULL
2022 static int apply_opt_cb(const struct option *opt, const char *arg, int unset)
2024 struct strbuf buf = STRBUF_INIT;
2025 if (unset)
2026 return 0;
2027 if (arg) {
2028 if (opt->long_name) {
2029 if (!strcmp("context", opt->long_name))
2030 strbuf_addf(&buf, "-C%s", arg);
2031 else
2032 strbuf_addf(&buf, "--%s=%s",
2033 opt->long_name, arg);
2034 } else
2035 strbuf_addf(&buf, "-%c%s", opt->short_name, arg);
2036 } else {
2037 if (opt->long_name)
2038 strbuf_addf(&buf, "--%s", opt->long_name);
2039 else
2040 strbuf_addf(&buf, "-%c", opt->short_name);
2042 string_list_append(buf.buf, &patch_opt.apply);
2043 strbuf_release(&buf);
2044 return 0;
2047 static struct option insn_patch_options[] = {
2048 OPT_BOOLEAN('3', "3way", &patch_opt.threeway,
2049 "fall back to 3-way merge"),
2050 OPT_BOOLEAN('k', NULL, &patch_opt.keep,
2051 "pass to git-mailinfo (keep subject)"),
2052 OPT_BOOLEAN('n', NULL, &patch_opt.noutf8,
2053 "pass to git-mailinfo (no utf8)"),
2054 OPT_GENERAL_OPTIONS,
2055 OPT_GROUP("Options passed to git-apply"),
2056 { OPTION_CALLBACK, 'R', "reverse", NULL, NULL,
2057 "reverse changes", PARSE_OPT_NOARG, apply_opt_cb },
2058 { OPTION_CALLBACK, 0, "context", NULL, "n",
2059 "ensure context of <n> lines", 0, apply_opt_cb },
2060 { OPTION_CALLBACK, 'p', NULL, NULL, "n",
2061 "remove <n> leading slashes", 0, apply_opt_cb },
2062 { OPTION_CALLBACK, 0, "unidiff-zero", NULL, NULL,
2063 "bypass unidiff checks", PARSE_OPT_NOARG, apply_opt_cb },
2064 { OPTION_CALLBACK, 0, "exclude", NULL, "path-pattern",
2065 "do not apply changes to given files", 0, apply_opt_cb },
2066 { OPTION_CALLBACK, 0, "no-add", NULL, NULL,
2067 "ignore additions of patch", PARSE_OPT_NOARG, apply_opt_cb },
2068 { OPTION_CALLBACK, 0, "whitespace", NULL, "action",
2069 "set whitespace error behavior", 0, apply_opt_cb },
2070 { OPTION_CALLBACK, 0, "inaccurate-eof", NULL, NULL,
2071 "support inaccurate EOFs", PARSE_OPT_NOARG, apply_opt_cb },
2072 { OPTION_CALLBACK, 0, "recount", NULL, NULL,
2073 "ignore line counts in hunk headers", PARSE_OPT_NOARG, apply_opt_cb },
2074 { OPTION_CALLBACK, 0, "reject", NULL, NULL,
2075 "save rejected hunks in .rej files", PARSE_OPT_NOARG, apply_opt_cb },
2076 { OPTION_CALLBACK, 0, "directory", NULL, "root",
2077 "prepend <root> to all filenames", 0, apply_opt_cb },
2078 OPT_END(),
2081 static void insn_patch_init(void)
2083 memset(&patch_opt, 0, sizeof(patch_opt));
2084 patch_opt.apply.strdup_strings = 1;
2087 static int insn_patch_check(int argc, const char **argv)
2089 struct strbuf buf = STRBUF_INIT;
2090 if (argc != 1)
2091 return todo_error("Wrong number of arguments. "
2092 "(%d given, 1 wanted)", argc);
2093 if (check_general_options())
2094 return 1;
2095 if (strbuf_read_file(&buf, argv[0], 8192) < 0)
2096 return todo_error("Cannot read patch file %s: %s",
2097 argv[0], strerror(errno));
2098 if (prefixcmp(buf.buf, "diff") && !strstr(buf.buf, "\ndiff")) {
2099 strbuf_release(&buf);
2100 return todo_error("Patch file '%s' contains no patch.",
2101 argv[0]);
2103 strbuf_release(&buf);
2104 return 0;
2107 static int insn_patch_act(int argc, const char **argv)
2109 int ifd;
2110 struct commit_info info;
2112 ifd = open(argv[0], O_RDONLY);
2113 if (ifd < 0)
2114 return error("Could not open patch %s.", argv[0]);
2116 memset(&info, 0, sizeof(info));
2117 strbuf_init(&info.summary, 0);
2119 if (mailinfo(ifd, &info))
2120 return error("Could not read or parse mail.");
2121 /* ifd is closed now */
2123 /* Ignore every mail that's not containing a patch */
2124 if (!info.patch) {
2125 fprintf(stderr, "Does not contain patch!");
2126 return 0;
2129 strbuf_addbuf(&next_commit.summary, &info.summary);
2130 set_message_source("message");
2132 if (info.author.name)
2133 next_commit.author.name = xstrdup(info.author.name);
2134 if (info.author.mail)
2135 next_commit.author.mail = xstrdup(info.author.mail);
2136 if (info.author.time)
2137 next_commit.author.time = xstrdup(info.author.time);
2139 if (handle_general_options())
2140 return 1;
2142 if (do_apply(info.patch, NULL, "--index", NULL)) {
2143 if (patch_opt.threeway &&
2144 !fallback_threeway(info.patch, info.subject)) {
2146 * Applying the patch to an earlier tree and merging
2147 * the result may have produced the same tree as ours.
2149 free_commit_info(&info);
2150 if (read_cache() < 0)
2151 return error("Could not read the index.");
2152 if (!index_differs_from("HEAD",
2153 DIFF_OPT_IGNORE_SUBMODULES)) {
2154 if (verbosity > 1)
2155 puts("No changes -- Patch already applied.");
2156 return 0; /* don't commit */
2158 * All those author/message options to "patch"
2159 * are for nothing now, but do we really have
2160 * a choice here?
2163 /* successfully merged */
2164 } else {
2165 free_commit_info(&info);
2166 return error("Applying patch failed.");
2169 free_commit_info(&info);
2171 if (run_hook(NULL, "pre-applypatch", NULL))
2172 return error("Hook pre-applypatch failed.");
2174 if (message_is_empty() || opt.edit) {
2175 strbuf_addstr(&next_commit.summary, "\n"
2176 "# Please enter the commit message for the applied patch.\n"
2177 "# (Comment lines starting with '#' will not be included)\n");
2178 if (edit_message(1))
2179 return 1;
2182 discard_cache();
2184 if (do_commit(head_sha1))
2185 return error("Could not commit.");
2187 /* We ignore errors of the post-applypatch hook. */
2188 run_hook(NULL, "post-applypatch", NULL);
2189 return 0;
2193 /* edit */
2194 static const char * const insn_edit_usage[] = {
2195 "edit <commit>",
2196 NULL
2199 static int insn_edit_check(int argc, const char **argv)
2201 if (batchmode)
2202 return todo_error("'edit' instruction and --batch do not "
2203 "make sense together.");
2204 return insn_pick_check(argc, argv);
2207 static int insn_edit_act(int argc, const char **argv)
2209 if (insn_pick_act(argc, argv))
2210 return 1;
2212 add_comment_to_donefile("pausing");
2214 if (get_sha1("HEAD", head_sha1))
2215 return error("You do not have a valid HEAD.");
2217 if (insn_pause_act(0, NULL))
2218 return 1;
2219 return 0;
2223 /* squash */
2224 static const char * const insn_squash_usage[] = {
2225 "squash <commit>",
2226 "squash [options] --from <mark>",
2227 NULL
2230 static struct option insn_squash_options[] = {
2231 OPT_BIT(0, "from", &squash_opt,
2232 "squash all commits from <mark>", OPT_SQUASH_FROM),
2233 OPT_BIT(0, "include-merges", &squash_opt,
2234 "do not fail on merge commits", OPT_SQUASH_INCLUDE_MERGES),
2235 OPT_GENERAL_OPTIONS,
2236 OPT_END(),
2239 static void insn_squash_init(void)
2241 squash_opt = 0;
2244 static int insn_squash_check(int argc, const char **argv)
2246 if (argc != 1)
2247 return todo_error("Wrong number of arguments. "
2248 "(%d given, 1 wanted)", argc);
2249 if (squash_opt & OPT_SQUASH_FROM) {
2250 if (argv[0][0] != ':')
2251 return todo_error("squash --from <mark> needs a "
2252 "colon-prefixed mark.");
2253 if (!(squash_opt & OPT_SQUASH_INCLUDE_MERGES)) {
2254 int i = 0;
2255 /* find mark in available_marks */
2256 for (i = 0; i < available_marks.nr &&
2257 strcmp(available_marks.items[i].string, argv[0]);
2258 ++i);
2259 if (i == available_marks.nr)
2260 return todo_error("Mark %s not found.", argv[0]);
2262 /* Let's look for forbidden reset or merges.
2263 * Those are marked with "m" or "r" */
2264 for (; i < available_marks.nr; ++i) {
2265 if (available_marks.items[i].string[0] == 'm')
2266 return todo_error("There is a merge "
2267 "instruction below mark %s. You may "
2268 " try --include-merges", argv[0]);
2269 if (available_marks.items[i].string[0] == 'r')
2270 return todo_error("There is a reset "
2271 "instruction below mark %s. You may "
2272 "try --include-merges", argv[0]);
2275 return !arg_is_mark(argv[0]);
2276 } else
2277 return !arg_is_commit(argv[0]);
2278 if (check_general_options())
2279 return 1;
2280 return 0;
2283 static int insn_squash_act(int argc, const char **argv)
2285 unsigned char base_sha1[20];
2286 unsigned char parent_sha1[20];
2287 unsigned char *parent = parent_sha1;
2288 struct commit *commit;
2289 int failed = 0;
2290 int multisquash = (peek_next_insn() == find_insn("squash"));
2293 * Hm, somehow I don't think --skip on a conflicting squash
2294 * may be useful, but if someone wants to do it, it should
2295 * do the obvious: skip what squash would do.
2297 save("sequencer.skiphead", sha1_to_hex(head_sha1));
2299 if (squash_opt & OPT_SQUASH_FROM) {
2300 char ref[50];
2301 mark_to_ref(argv[0], ref, 1);
2302 commit = get_commit(ref);
2303 hashcpy(parent_sha1, commit->object.sha1);
2304 make_squash_message_multiple(parent_sha1, base_sha1);
2305 failed = update_ref(reflog, "HEAD", base_sha1, head_sha1, 0,
2306 MSG_ON_ERR);
2307 } else {
2308 struct strbuf pick_msg = STRBUF_INIT;
2309 commit = get_commit(argv[0]);
2310 set_pick_subject(argv[0], commit);
2311 failed = pick_commit(commit, 0, 0, &pick_msg);
2312 if (failed)
2313 make_patch(commit);
2314 make_squash_message(&pick_msg);
2315 strbuf_release(&pick_msg);
2316 hashcpy(base_sha1, head_sha1);
2317 parent = NULL; /* we rely on next_commit.parents */
2318 if (get_sha1("HEAD^", parent_sha1))
2319 hashcpy(parent_sha1, null_sha1);
2321 commit = lookup_commit_reference(base_sha1);
2322 get_commit_header(commit, 1);
2324 set_message_source("squash");
2325 if (handle_general_options())
2326 return 1;
2328 if (!failed && !multisquash &&
2329 (!has_general_message_option() || opt.edit))
2330 if (edit_message(1))
2331 return 1;
2333 if (failed) {
2334 if (squash_opt & OPT_SQUASH_FROM)
2335 /* Hm, this means the update_ref() has failed. */
2336 return error("Squashing failed.");
2337 else {
2338 rerere();
2339 write_commit_summary_into(MERGE_MSG);
2340 update_ref(reflog, "HEAD", parent_sha1, head_sha1,
2341 0, MSG_ON_ERR);
2342 return error("Squashing %s failed.", argv[0]);
2346 if (multisquash) /* do not commit */
2347 return write_commit_summary_into(SQUASH_MSG);
2349 if (do_commit(parent))
2350 return error("Could not commit.");
2352 return 0;
2356 /* mark */
2357 static const char * const insn_mark_usage[] = {
2358 "mark <mark>",
2359 NULL
2362 static int insn_mark_check(int argc, const char **argv)
2364 int i = 0;
2365 int has_colon = 0;
2366 char *mark;
2367 if (argc != 1)
2368 return todo_error("Wrong number of arguments. "
2369 "(%d given, 1 wanted)", argc);
2370 if (argv[0][0] == ':') {
2371 i++;
2372 has_colon = 1;
2374 /* on "mark", the leading ":" may be omitted */
2375 for (; argv[0][i]; ++i)
2376 if (argv[0][i] < '0' || argv[0][i] > '9')
2377 return todo_error("Mark '%s' is not an integer.",
2378 has_colon ? argv[0]+1 : argv[0]);
2380 if (has_colon)
2381 mark = xstrdup(argv[0]);
2382 else {
2383 mark = xmalloc(strlen(argv[0]) + 2);
2384 sprintf(mark, ":%s", argv[0]);
2386 if (string_list_has_string(&available_marks, mark))
2387 return todo_error("Mark %s already defined. "
2388 "Choose another integer.", mark);
2389 string_list_append(mark, &available_marks);
2390 return 0;
2393 static int insn_mark_act(int argc, const char **argv)
2395 char ref[50];
2396 if (mark_to_ref(argv[0], ref, 1))
2397 return 1;
2398 ++available_marks.nr;
2399 return update_ref(reflog, ref, head_sha1, NULL, 0, MSG_ON_ERR);
2403 /* merge */
2404 static const char * const insn_merge_usage[] = {
2405 "merge [options] <commit-ish> ...",
2406 NULL
2409 static struct option insn_merge_options[] = {
2410 OPT_BOOLEAN(0, "standard", &merge_opt.standard,
2411 "generate default commit message"),
2412 OPT_STRING('s', "strategy", &merge_opt.strategy, "strategy",
2413 "Specify merge strategy"),
2414 OPT_GENERAL_OPTIONS,
2415 OPT_END(),
2418 static void insn_merge_init(void)
2420 memset(&merge_opt, 0, sizeof(merge_opt));
2423 static int insn_merge_check(int argc, const char **argv)
2425 int i;
2426 if (!argc)
2427 return todo_error("What are my parents? Need new parents!");
2429 for (i = 0; i < argc; ++i)
2430 if (!arg_is_mark_or_commit(argv[i]))
2431 return 1;
2432 if (check_general_options())
2433 return 1;
2435 string_list_append(xstrdup("m"), &available_marks);
2436 return 0;
2439 static int insn_merge_act(int argc, const char **argv)
2441 int i;
2442 for (i = 0; i < argc; ++i) {
2443 unsigned char sha[20];
2444 mark_to_sha1(argv[i], sha);
2445 string_list_append(xstrdup(sha1_to_hex(sha)),
2446 &next_commit.parents);
2449 set_message_source("merge");
2450 if (handle_general_options())
2451 return 1;
2453 if (merge_opt.standard) {
2454 struct strbuf msg = STRBUF_INIT;
2456 /* if there is some summary, ensure \n\n at the end */
2457 if (next_commit.summary.len > 1) {
2458 if (next_commit.summary.buf[next_commit.summary.len - 2] != '\n')
2459 strbuf_addch(&next_commit.summary, '\n');
2460 if (next_commit.summary.buf[next_commit.summary.len - 2] != '\n')
2461 strbuf_addch(&next_commit.summary, '\n');
2462 } else if (next_commit.summary.len == 1) {
2463 if (next_commit.summary.buf[0] == '\n')
2464 strbuf_release(&next_commit.summary);
2465 else
2466 strbuf_addstr(&next_commit.summary, "\n\n");
2469 for (i = 0; i < argc; i++) {
2470 if (argv[i][0] == ':')
2471 merge_name(next_commit.parents.items[i].string,
2472 &msg);
2473 else
2474 merge_name(argv[i], &msg);
2476 fmt_merge_msg(0, &msg, &next_commit.summary);
2477 strbuf_release(&msg);
2478 } else /* try fast-forward on merge -C .. ... */
2479 if (!opt.author && !opt.file && !opt.message && !opt.reuse_message &&
2480 !opt.signoff && !opt.edit && opt.reuse_commit) {
2481 struct commit *commit = get_commit(opt.reuse_commit);
2482 if (fast_forward_possible(commit))
2483 return do_fast_forward(commit->object.sha1);
2486 if (message_is_empty() || opt.edit) {
2487 strbuf_addstr(&next_commit.summary, "\n"
2488 "# Please enter the merge commit message.\n"
2489 "# (Comment lines starting with '#' will not be included)\n");
2490 if (edit_message(1))
2491 return 1;
2494 if (do_merge()) {
2495 rerere();
2496 if (opt.reuse_commit)
2497 make_patch(get_commit(opt.reuse_commit));
2498 die_with_merges = 1;
2499 return error("Could not merge.");
2501 if (do_commit(head_sha1))
2502 return error("Could not commit.");
2503 return 0;
2507 /* reset */
2508 static const char * const insn_reset_usage[] = {
2509 "reset <commit-ish>",
2510 NULL
2513 static int insn_reset_check(int argc, const char **argv)
2515 if (argc != 1)
2516 return todo_error("Wrong number of arguments. "
2517 "(%d given, 1 wanted)", argc);
2518 string_list_append(xstrdup("r"), &available_marks);
2519 return !arg_is_mark_or_commit(argv[0]);
2522 static int insn_reset_act(int argc, const char **argv)
2524 unsigned char sha1[20];
2526 if (mark_to_sha1(argv[0], sha1))
2527 return error("Could not get SHA1 for '%s'.", argv[0]);
2528 reset_almost_hard(sha1);
2529 ++available_marks.nr;
2530 return 0;
2534 /* ref */
2535 static const char * const insn_ref_usage[] = {
2536 "ref <ref>",
2537 NULL
2540 static int insn_ref_check(int argc, const char **argv)
2542 if (argc != 1)
2543 return todo_error("Wrong number of arguments. "
2544 "(%d given, 1 wanted)", argc);
2545 return 0;
2548 static int insn_ref_act(int argc, const char **argv)
2550 unsigned char sha[20], *old_sha1 = NULL;
2551 FILE *fp = fopen(DESTINY_FILE, "a");
2552 if (!fp)
2553 return error("Could not open file '%s': %s",
2554 DESTINY_FILE, strerror(errno));
2555 if (get_sha1(argv[0], sha))
2556 fprintf(fp, "%s\n-\n", argv[0]);
2557 else {
2558 old_sha1 = sha;
2559 fprintf(fp, "%s\n%s\n", argv[0], sha1_to_hex(sha));
2561 fclose(fp);
2562 return update_ref(reflog, argv[0], head_sha1, old_sha1, 0, MSG_ON_ERR);
2566 /* run */
2567 static const char * const insn_run_usage[] = {
2568 "run [--dir=<path>] [--] <cmd> <args>...",
2569 NULL
2572 static void insn_run_init(void)
2574 memset(&run_opt, 0, sizeof(run_opt));
2577 static struct option insn_run_options[] = {
2578 OPT_STRING(0, "directory", &run_opt.dir, "path",
2579 "change directory before running command"),
2580 OPT_END(),
2583 static int insn_run_check(int argc, const char **argv)
2585 if (argc < 1)
2586 return todo_error("No command given.");
2587 if (run_opt.dir) {
2588 #ifndef __MINGW32__
2589 struct stat st;
2590 if (lstat(run_opt.dir, &st))
2591 return todo_error("Directory '%s' does not exist",
2592 run_opt.dir);
2593 if (!S_ISDIR(st.st_mode))
2594 return todo_error("Path '%s' is not a directory.",
2595 run_opt.dir);
2596 #else
2597 return todo_error("Sorry, --directory is not implemented "
2598 "for MinGW.");
2599 #endif
2601 return 0;
2604 static NORETURN void fork_die_cb(const char *err, va_list params)
2606 fprintf(stderr, "fork error: ");
2607 vfprintf(stderr, err, params);
2608 fprintf(stderr, "\n");
2609 exit(128);
2612 static int insn_run_act(int argc, const char **argv)
2614 int status;
2615 /* If forking fails (e.g. the command does not exist), die() is called.
2616 * So we need to set a sane die routine for the fork. */
2617 set_die_routine(fork_die_cb);
2618 status = run_command_v_opt_cd_env(argv, RUN_COMMAND_NO_STDIN,
2619 run_opt.dir, NULL);
2620 set_die_routine(die_continue_cb);
2621 if (status) {
2622 struct commit *commit = lookup_commit_reference(head_sha1);
2623 get_commit_info(commit, 1);
2624 next_commit.subject = xstrdup(contents.cur->orig.buf);
2625 why = WHY_RUN;
2626 if (verbosity)
2627 printf("Program exited with code %d.", status);
2628 return 1;
2630 discard_cache();
2632 return 0;
2636 static struct instruction avail_insns[] = {
2637 INSTRUCTION_NO_OPTS(edit),
2638 INSTRUCTION_NO_OPTS(mark),
2639 INSTRUCTION(merge),
2640 INSTRUCTION_NO_OPTS(noop),
2641 INSTRUCTION(patch),
2642 INSTRUCTION_NO_OPTS(pause),
2643 INSTRUCTION(pick),
2644 INSTRUCTION_NO_OPTS(ref),
2645 INSTRUCTION_NO_OPTS(reset),
2646 INSTRUCTION(run),
2647 INSTRUCTION(squash),
2648 { NULL, NULL, NULL, NULL, NULL }
2651 /* Return the index in array "avail_insns" of the insn "name" */
2652 static int find_insn(const char *name)
2654 int i;
2655 if (!name)
2656 return -1;
2657 /* expand rebase -i shortcuts: */
2658 if (name[0] && !name[1]) {
2659 switch (*name) {
2660 case 'e': name = "edit"; break;
2661 case 'p': name = "pick"; break;
2662 case 's': name = "squash"; break;
2665 for (i = 0; avail_insns[i].usage; ++i)
2666 if (!prefixcmp(*avail_insns[i].usage, name))
2667 return i;
2668 return -1;
2672 /**********************************************************************
2673 * Functions for TODO parser
2676 /* Parse a line */
2677 static int parse_line(char *buf, size_t len, int lineno,
2678 struct parsed_insn **line)
2680 static int alloc = 0;
2681 static struct strbuf arg_sb = STRBUF_INIT;
2682 static enum {
2683 ST_START,
2684 ST_DELIMITER,
2685 ST_ARGUMENT,
2686 ST_ESCAPE,
2687 ST_DOUBLE_QUOTES,
2688 ST_DOUBLE_QUOTES_ESCAPE,
2689 ST_SINGLE_QUOTES,
2690 } state = ST_START;
2691 /* The current rules are as follows:
2692 * 1. whitespace at the beginning is ignored
2693 * 2. insn is everything up to next whitespace or EOL
2694 * 3. now whitespace acts as delimiter for arguments,
2695 * except if written in single or double quotes
2696 * 4. \ acts as escape inside and outside double quotes.
2697 * Inside double quotes, this is only useful for \".
2698 * Outside, it is useful for \', \", \\ and \ .
2699 * 5. single quotes do not have an escape character
2700 * 6. abort on "#" (comments)
2703 size_t i, j = 0;
2704 struct parsed_insn *ret = *line;
2706 for (i = 0; i <= len; ++i) {
2707 switch (state) {
2708 case ST_START:
2709 switch (buf[i]) {
2710 case ' ':
2711 case '\t':
2712 continue;
2713 case 0:
2714 case '#':
2715 break;
2716 case '\'':
2717 j = i+1;
2718 state = ST_SINGLE_QUOTES;
2719 break;
2720 case '"':
2721 j = i+1;
2722 state = ST_DOUBLE_QUOTES;
2723 break;
2724 default:
2725 j = i;
2726 state = ST_ARGUMENT;
2727 break;
2729 /* prepare everything */
2730 ret = xcalloc(1, sizeof(struct parsed_insn));
2731 ret->line = lineno;
2732 strbuf_init(&ret->orig, len+2);
2733 if (!buf[i] || buf[i] == '#') /* empty/comment */
2734 goto finish;
2735 break;
2736 case ST_DELIMITER:
2737 switch (buf[i]) {
2738 case ' ':
2739 case '\t':
2740 continue;
2741 case 0:
2742 break;
2743 case '\'':
2744 j = i+1;
2745 state = ST_SINGLE_QUOTES;
2746 break;
2747 case '"':
2748 j = i+1;
2749 state = ST_DOUBLE_QUOTES;
2750 break;
2751 default:
2752 j = i;
2753 state = ST_ARGUMENT;
2754 if (buf[i] == '#') /* a comment */
2755 goto finish;
2756 break;
2758 /* prepare next argument */
2759 ALLOC_GROW(ret->argv, ret->argc + 1, alloc);
2760 ret->argv[ret->argc++] = strbuf_detach(&arg_sb, NULL);
2761 break;
2762 case ST_ARGUMENT:
2763 switch (buf[i]) {
2764 case ' ':
2765 case '\t':
2766 strbuf_add(&arg_sb, buf+j, i-j);
2767 state = ST_DELIMITER;
2768 break;
2769 case '"':
2770 strbuf_add(&arg_sb, buf+j, i-j);
2771 j = i + 1;
2772 state = ST_DOUBLE_QUOTES;
2773 break;
2774 case '\'':
2775 strbuf_add(&arg_sb, buf+j, i-j);
2776 j = i + 1;
2777 state = ST_SINGLE_QUOTES;
2778 break;
2779 case '\\':
2780 strbuf_add(&arg_sb, buf+j, i-j);
2781 j = i + 1;
2782 state = ST_ESCAPE;
2783 default:
2784 break;
2786 break;
2787 case ST_ESCAPE:
2788 state = ST_ARGUMENT;
2789 break;
2790 case ST_DOUBLE_QUOTES:
2791 switch (buf[i]) {
2792 case '"':
2793 strbuf_add(&arg_sb, buf+j, i-j);
2794 j = i + 1;
2795 state = ST_ARGUMENT;
2796 break;
2797 case '\\':
2798 strbuf_add(&arg_sb, buf+j, i-j);
2799 j = i + 1;
2800 state = ST_DOUBLE_QUOTES_ESCAPE;
2801 break;
2802 default:
2803 break;
2805 break;
2806 case ST_DOUBLE_QUOTES_ESCAPE:
2807 state = ST_DOUBLE_QUOTES;
2808 break;
2809 case ST_SINGLE_QUOTES:
2810 switch (buf[i]) {
2811 case '\'':
2812 strbuf_add(&arg_sb, buf+j, i-j);
2813 j = i + 1;
2814 state = ST_ARGUMENT;
2815 break;
2816 default:
2817 break;
2819 break;
2822 finish:
2823 *line = ret;
2824 switch(state) {
2825 case ST_DOUBLE_QUOTES:
2826 case ST_DOUBLE_QUOTES_ESCAPE:
2827 case ST_SINGLE_QUOTES:
2828 strbuf_add(&arg_sb, buf+j, i-j-1);
2829 strbuf_add(&arg_sb, "\n", 1);
2830 return 1;
2831 case ST_ARGUMENT:
2832 if (i-j > 1)
2833 strbuf_add(&arg_sb, buf+j, i-j-1);
2834 ALLOC_GROW(ret->argv, ret->argc + 1, alloc);
2835 ret->argv[ret->argc++] = strbuf_detach(&arg_sb, NULL);
2836 case ST_DELIMITER:
2837 state = ST_START;
2838 alloc = 0;
2839 default:
2840 strbuf_addstr(&ret->orig, buf);
2841 strbuf_addch(&ret->orig, '\n');
2842 return 0;
2846 static void add_parsed_line_to_contents(struct parsed_insn *parsed_line)
2848 if (!contents.first) {
2849 contents.first = parsed_line;
2850 contents.last = parsed_line;
2851 } else {
2852 contents.last->next = parsed_line;
2853 contents.last = parsed_line;
2855 if (parsed_line->argv)
2856 contents.total++;
2859 /* Parse a file fp; write result into contents */
2860 static void parse_file(const char *filename)
2862 struct strbuf str = STRBUF_INIT;
2863 struct parsed_insn *parsed_line = NULL;
2864 int r = 0;
2865 int lineno = 0;
2866 FILE *fp = fp = fopen(filename, "r");
2867 if (!fp)
2868 die("Could not open file '%s': %s", filename, strerror(errno));
2870 memset(&contents, 0, sizeof(struct parsed_file));
2872 while (strbuf_getline(&str, fp, '\n') != EOF) {
2873 lineno++;
2874 r = parse_line(str.buf, str.len, lineno, &parsed_line);
2875 if (!r)
2876 add_parsed_line_to_contents(parsed_line);
2878 strbuf_release(&str);
2879 fclose(fp);
2880 if (r)
2881 die("Unexpected end of file.");
2885 /**********************************************************************
2886 * Helpers for main execution and sanity check functions
2889 static void comment_for_reflog(const char *str)
2891 static char tmp[50];
2892 reflog = getenv("GIT_REFLOG_ACTION");
2893 if (!reflog || !*reflog) {
2894 char comment[35];
2895 char *space = strchr(str, ' ');
2896 if (space) {
2897 strlcpy(comment, str, MIN(space - str + 1,
2898 sizeof(comment)-2));
2899 snprintf(tmp, sizeof(tmp), "sequencer (\"%s\")",
2900 comment);
2902 else {
2903 strlcpy(comment, str, sizeof(comment));
2904 snprintf(tmp, sizeof(tmp), "sequencer (%s)", comment);
2906 reflog = tmp;
2910 /* Test if working tree is dirty. */
2911 static int is_working_tree_dirty(void)
2913 struct rev_info rev;
2914 int result;
2915 if (read_cache() < 0)
2916 return error("Could not read cache. Corrupted?");
2917 if (allow_dirty) /* don't check if --allow-dirty is used */
2918 return 0;
2919 if (refresh_cache(REFRESH_IGNORE_SUBMODULES))
2920 return 1;
2921 init_revisions(&rev, NULL);
2922 rev.abbrev = 40;
2923 DIFF_OPT_SET(&rev.diffopt, QUIET);
2924 DIFF_OPT_SET(&rev.diffopt, IGNORE_SUBMODULES);
2925 DIFF_OPT_SET(&rev.diffopt, EXIT_WITH_STATUS);
2926 rev.diffopt.output_format = DIFF_FORMAT_RAW;
2927 result = run_diff_files(&rev, 0);
2928 return diff_result_code(&rev.diffopt, result);
2931 static void unlink_commit_files(void)
2933 if (file_exists(MERGE_MSG))
2934 unlink(MERGE_MSG);
2935 if (file_exists(MERGE_HEAD))
2936 unlink(MERGE_HEAD);
2937 if (file_exists(COMMIT_EDITMSG))
2938 unlink(COMMIT_EDITMSG);
2939 if (file_exists(PATCH_FILE))
2940 unlink(PATCH_FILE);
2941 if (file_exists(MESSAGE_FILE))
2942 unlink(MESSAGE_FILE);
2945 static int remove_from_todo(void)
2947 FILE *fp;
2948 struct parsed_insn *cur;
2950 fp = fopen(DONE_FILE, "a");
2951 if (!fp)
2952 return error("Could not open file %s.", DONE_FILE);
2953 if (!fwrite(contents.cur->orig.buf, contents.cur->orig.len, 1, fp))
2954 return error("Could not write into %s.", DONE_FILE);
2955 fclose(fp);
2956 cur = contents.cur->next;
2958 fp = fopen(TODO_FILE, "w");
2959 if (!fp)
2960 return error("Could not open file %s.", TODO_FILE);
2961 for (; cur; cur = cur->next) {
2962 if (!fwrite(cur->orig.buf, cur->orig.len, 1, fp))
2963 return error("Could not write into %s.", TODO_FILE);
2965 fclose(fp);
2967 if (contents.cur->argv) { /* we are not removing a comment */
2968 contents.count++;
2969 if ((verbosity && isatty(1)) || verbosity > 1) {
2970 printf("Sequencing (%zu/%zu)\r",
2971 contents.count, contents.total);
2972 if (verbosity > 1)
2973 putchar('\n');
2976 return 0;
2979 static int parse_insn_options(int argc, const char **argv,
2980 const char ***newargv, int idx)
2982 struct parse_opt_ctx_t ctx;
2983 int i;
2984 const struct option *options = avail_insns[idx].options;
2985 const char * const *usagestr = avail_insns[idx].usage;
2986 *newargv = xcalloc(argc, sizeof(const char *));
2988 /* copy old arg into new arg, will be changed on parsing */
2989 for (i = 0; i < argc; ++i)
2990 (*newargv)[i] = argv[i];
2992 /* reset general options and insn options */
2993 memset(&opt, 0, sizeof(opt));
2994 if (avail_insns[idx].init)
2995 avail_insns[idx].init();
2997 /* do parsing */
2998 parse_options_start(&ctx, argc, *newargv, NULL, 0);
2999 switch (parse_options_step(&ctx, options, usagestr)) {
3000 case PARSE_OPT_DONE:
3001 break;
3002 case PARSE_OPT_HELP:
3003 default: /* PARSE_OPT_UNKNOWN */
3004 if (ctx.argv[0][1] == '-')
3005 todo_error("unknown option `%s'", ctx.argv[0] + 2);
3006 else
3007 todo_error("unknown switch `%c'", *ctx.opt);
3008 parse_options_usage(usagestr, options);
3009 return -1;
3011 return parse_options_end(&ctx);
3015 /**********************************************************************
3016 * Execution and sanity check of instructions
3019 static int check_insns(void)
3021 int ret = 0;
3023 for (contents.cur = contents.first; contents.cur;
3024 contents.cur = contents.cur->next) {
3025 int i;
3026 int argc;
3027 const char **argv;
3029 if (!contents.cur->argv)
3030 continue;
3032 /* find instruction */
3033 i = find_insn(contents.cur->argv[0]);
3034 todo_line = contents.cur->line;
3035 if (i < 0) {
3036 ret |= todo_error("Unknown %s instruction.",
3037 contents.cur->argv[0]);
3038 continue;
3041 /* parse options */
3042 argc = parse_insn_options(contents.cur->argc,
3043 contents.cur->argv, &argv, i);
3044 if (argc < 0)
3045 return 1;
3047 /* run check */
3048 ret |= avail_insns[i].check(argc, argv);
3049 free(argv);
3052 return ret;
3055 static int execute_insns(void)
3057 int i;
3058 /* swap available_marks.nr and marks_total */
3059 i = available_marks.nr;
3060 available_marks.nr = marks_total;
3061 marks_total = i;
3063 for (contents.cur = contents.first; contents.cur;
3064 contents.cur = contents.cur->next) {
3065 int ret = 0;
3066 int argc, oldargc;
3067 const char **argv;
3069 if (remove_from_todo())
3070 return error("Could not mark instruction as done");
3071 if (!contents.cur->argv)
3072 continue;
3074 reset_next_commit();
3075 save("sequencer.skiphead", "HEAD");
3077 if (verbosity > 2) {
3078 printf("Next command: %s\n", contents.cur->argv[0]);
3079 for (i = 1; i < contents.cur->argc; ++i)
3080 printf(" - '%s'\n", contents.cur->argv[i]);
3083 /* find instruction */
3084 i = find_insn(contents.cur->argv[0]);
3086 /* parse options */
3087 oldargc = contents.cur->argc;
3088 argc = parse_insn_options(contents.cur->argc,
3089 contents.cur->argv, &argv, i);
3091 /* update head_sha1 for insn */
3092 if (get_sha1("HEAD", head_sha1)) {
3093 free(argv);
3094 return error("You do not have a valid HEAD.");
3097 unlink_commit_files();
3099 /* run */
3100 comment_for_reflog(avail_insns[i].usage[0]);
3101 ret = avail_insns[i].act(argc, argv);
3102 free(argv);
3104 if (ret) {
3105 error("%s instruction failed.", contents.cur->argv[0]);
3106 return 1;
3108 free_commit_info(&next_commit);
3111 comment_for_reflog("finish");
3113 if (orig_headname) {
3114 if (get_sha1("HEAD", head_sha1))
3115 return error("You do not have a valid HEAD.");
3116 if (update_ref(reflog, orig_headname, head_sha1, NULL, 0, 0))
3117 return error("Could not update %s to '%s'.",
3118 orig_headname, sha1_to_hex(head_sha1));
3119 if (create_symref("HEAD", orig_headname, NULL))
3120 return error("Could not update HEAD to %s.",
3121 orig_headname);
3123 return 0;
3127 /**********************************************************************
3128 * Different actions...
3131 int initial_checks(const char *act_name, int act_bit,
3132 const char **act_caller)
3134 if (!file_exists(git_path(SEQ_DIR))) {
3135 error("No sequencer running. Cannot %s.", act_name);
3136 return 1;
3138 reset_next_commit();
3139 if (get_saved_options())
3140 return 1;
3141 if (caller_check_failed & act_bit) {
3142 fprintf(stderr, "You must use '%s' to %s.\n",
3143 *act_caller, act_name);
3144 return 1;
3146 comment_for_reflog(act_name);
3148 return 0;
3151 /* Realize --abort */
3152 static int sequencer_abort(int argc, const char **argv)
3154 if (initial_checks("abort", ACTION_ABORT, &caller_abort))
3155 return 1;
3156 rerere_clear();
3157 unlink_commit_files();
3158 if (restore())
3159 return 1;
3160 cleanup();
3161 return 0;
3164 /* Realize --continue */
3165 static int sequencer_continue(int argc, const char **argv)
3167 if (initial_checks("continue", ACTION_CONTINUE, &caller_continue))
3168 return 1;
3169 set_die_routine(die_continue_cb);
3170 parse_file(TODO_FILE);
3171 if (check_insns()) {
3172 why = WHY_TODO;
3173 die("TODO file contains errors.");
3176 if (get_sha1("HEAD", head_sha1)) {
3177 error("You do not have a valid HEAD.");
3178 return 3;
3180 if (read_cache() < 0) {
3181 error("Could not read the index.");
3182 return 3;
3184 if (is_working_tree_dirty()) {
3185 error("Working tree is dirty. "
3186 "(Use git-add or git-stash first?)");
3187 return 3;
3190 /* Do we have anything to commit? (staged changes) */
3191 if (index_differs_from("HEAD", DIFF_OPT_IGNORE_SUBMODULES)) {
3192 unsigned char parent_sha1[20];
3193 unsigned char *tmp;
3195 /* prepare-msg-hook with "message"... This is the way
3196 * the original git-rebase --continue does it. */
3197 set_message_source("message");
3198 if (edit_message(0))
3199 return 3;
3201 if (file_exists(MERGE_HEAD)) { /* we are in a merge */
3202 struct strbuf m;
3203 FILE *fp;
3205 die_with_merges = 1;
3207 strbuf_init(&m, 0);
3208 fp = fopen(MERGE_HEAD, "r");
3209 if (fp == NULL)
3210 die("could not open %s for reading: %s",
3211 MERGE_HEAD, strerror(errno));
3212 while (strbuf_getline(&m, fp, '\n') != EOF) {
3213 unsigned char sha1[20];
3214 if (get_sha1_hex(m.buf, sha1) < 0)
3215 die("Corrupt %s file (%s)",
3216 MERGE_HEAD, m.buf);
3217 string_list_append(xstrdup(sha1_to_hex(sha1)),
3218 &next_commit.parents);
3220 fclose(fp);
3221 strbuf_release(&m);
3222 unlink(MERGE_HEAD);
3225 /* After "pause" or "run", we should amend (merge-safe!).
3226 * On conflict, we do not have a commit to amend, so we
3227 * should just commit. */
3228 switch(why) {
3229 case WHY_PAUSE:
3230 case WHY_RUN:
3231 why = WHY_UNKNOWN;
3232 if (get_sha1("HEAD^1", parent_sha1))
3233 tmp = NULL; /* parent is root commit */
3234 else {
3235 if (hashcmp(head_sha1, paused_at_sha1))
3236 die("\nYou have uncommitted changes "
3237 "in your working tree.\nPlease, "
3238 "commit them first and try again.");
3239 tmp = parent_sha1;
3241 if (do_commit_with_msgfile(tmp))
3242 die("Could not commit staged changes.");
3243 break;
3244 case WHY_CONFLICT:
3245 why = WHY_UNKNOWN;
3246 if (do_commit_with_msgfile(head_sha1))
3247 die("Could not commit staged changes.");
3248 add_comment_to_donefile("resolved conflicts of the last instruction");
3249 break;
3250 default:
3251 die("There are staged changes. "
3252 "Do not know what to do with them.");
3254 free_commit_info(&next_commit);
3256 unlink_commit_files();
3257 die_with_merges = 0;
3259 why = WHY_UNKNOWN;
3260 if (execute_insns())
3261 die("Error executing instructions.");
3263 cleanup();
3264 return 0;
3267 /* Realize --skip */
3268 static int sequencer_skip(int argc, const char **argv)
3270 if (initial_checks("skip", ACTION_SKIP, &caller_skip))
3271 return 1;
3272 set_die_routine(die_continue_cb);
3273 parse_file(TODO_FILE);
3274 if (check_insns()) {
3275 why = WHY_TODO;
3276 die("TODO file contains errors.");
3279 rerere_clear();
3280 unlink_commit_files();
3281 why = WHY_UNKNOWN;
3283 if (!skiphead)
3284 skiphead = "HEAD";
3286 if (get_sha1(skiphead, head_sha1)) {
3287 error("You do not have a valid HEAD to skip to.");
3288 return 3;
3290 if (reset_almost_hard(head_sha1))
3291 return 3;
3293 add_comment_to_donefile("skipped the last instruction");
3295 if (execute_insns())
3296 die("Error executing instructions.");
3297 cleanup();
3298 return 0;
3301 static int print_file_with_line_prefix(FILE *out, const char *filename,
3302 const char *prefix)
3304 struct strbuf line = STRBUF_INIT;
3305 FILE *fp = fopen(filename, "r");
3306 int fail = 0;
3307 if (fp) {
3308 while (strbuf_getline(&line, fp, '\n') != EOF)
3309 fprintf(out, "%s%s\n", prefix, line.buf);
3310 strbuf_release(&line);
3311 fclose(fp);
3312 } else {
3313 fprintf(out, "%s-- Could not open '%s'.\n", prefix, filename);
3314 fail = 1;
3316 return fail;
3319 static int prepare_editable_todo(const char *filename, const char *markline)
3321 int result;
3322 FILE *fp = fopen(filename, "w");
3323 if (!fp)
3324 return error("Could not open '%s': %s",
3325 filename, strerror(errno));
3326 if (file_exists(DONE_FILE)) {
3327 fprintf(fp, "# ALREADY DONE:\n");
3328 print_file_with_line_prefix(fp, DONE_FILE, "# ");
3329 fprintf(fp, "# \n");
3331 fprintf(fp, "%s\n", markline);
3332 result = print_file_with_line_prefix(fp, TODO_FILE, "");
3333 fclose(fp);
3334 return result;
3337 static int rewind_prepared_todo(const char *filename, const char *markline)
3339 int marked = 0;
3340 struct strbuf buf = STRBUF_INIT;
3341 FILE *ifp = fopen(filename, "r");
3342 FILE *ofp = fopen(TODO_FILE, "w");
3343 if (!ifp)
3344 return error("Could not open TODO file %s: %s",
3345 filename, strerror(errno));
3346 if (!ofp)
3347 return error("Could not open TODO file %s: %s",
3348 TODO_FILE, strerror(errno));
3349 while (strbuf_getline(&buf, ifp, '\n') != EOF) {
3350 if (buf.buf && (marked || buf.buf[0] != '#')) {
3351 puts(buf.buf);
3352 fprintf(ofp, "%s\n", buf.buf);
3353 } else if (!strcmp(buf.buf, markline))
3354 marked = 1;
3356 fclose(ifp);
3357 fclose(ofp);
3358 strbuf_release(&buf);
3359 return 0;
3362 /* Realize --edit */
3363 static int sequencer_edit(int argc, const char **argv)
3365 const char *markline = "### BEGIN EDITING BELOW THIS LINE ###";
3366 char *todo_edit_file, *todo_backup_file;
3367 if (!file_exists(git_path(SEQ_DIR)))
3368 die("No sequencer running.");
3369 if (get_saved_options())
3370 return 1;
3371 todo_edit_file = git_pathdup(SEQ_DIR "/git-rebase-todo");
3372 if (prepare_editable_todo(todo_edit_file, markline))
3373 return error("Could not prepare TODO file.");
3375 if (launch_editor(todo_edit_file, NULL, NULL))
3376 return 1;
3378 if (isatty(0) && isatty(1)) { /* interactive */
3379 putchar('\n');
3380 parse_file(todo_edit_file);
3381 while (!contents.total || check_insns()) {
3382 char reply;
3383 struct parsed_insn *cur;
3384 if (!contents.total)
3385 puts("TODO file is empty.");
3386 printf("What to do with the file? "
3387 "[c]orrect/[e]dit again/[r]ewind/[s]ave/[?] ");
3389 /* read character */
3391 scanf("%c", &reply);
3392 while (!isalpha(reply) && reply != '?');
3394 switch (reply) {
3395 case 'c': case 'C': /* correct */
3396 if (launch_editor(todo_edit_file, NULL, NULL))
3397 return 1;
3398 break;
3399 case 'e': case 'E': /* edit again */
3400 if (prepare_editable_todo(todo_edit_file,
3401 markline))
3402 return 1;
3403 if (launch_editor(todo_edit_file, NULL, NULL))
3404 return 1;
3405 break;
3406 case 'r': case 'R': /* rewind */
3407 case 'x': case 'X': case 'q': case 'Q': /* exit/quit */
3408 /* x, X, q and Q are for the confused user,
3409 * who just wants to exit. */
3410 unlink(todo_edit_file);
3411 return 0;
3412 case 's': case 'S':
3413 if (why == WHY_PAUSE)
3414 save_int("sequencer.why", WHY_TODO);
3415 goto force_finish;
3416 case '?': case 'h': case 'H':
3417 printf("\n\nHelp:\n"
3418 "s - save TODO file and exit\n"
3419 "c - respawn editor to correct TODO file\n"
3420 "e - drop changes and respawn editor on "
3421 "original TODO file\n"
3422 "r - drop changes and exit as if nothing "
3423 "happened\n"
3424 "? - print this help\n");
3425 break;
3426 default:
3427 putchar('\n');
3430 /* parse again */
3431 free_available_marks();
3432 for (cur = contents.first; cur; free_parsed_insn(&cur));
3433 parse_file(todo_edit_file);
3435 } else { /* non-interactive, default */
3436 parse_file(todo_edit_file);
3437 if (!contents.total) {
3438 puts("Nothing to do.");
3439 return 0;
3441 if (check_insns())
3442 die("TODO file still contains errors. Aborting.");
3444 force_finish:
3445 /* backup old TODO file */
3446 todo_backup_file = git_pathdup(SEQ_DIR "/todo.old");
3447 if (copy_file_overwrite(todo_backup_file, TODO_FILE))
3448 warning("Could not backup TODO file to '%s'.", *argv);
3449 free(todo_backup_file);
3451 /* remove markline and comment lines above and print TODO file */
3452 printf("TODO file contains:\n\n");
3453 if (rewind_prepared_todo(todo_edit_file, markline))
3454 return 1;
3455 unlink(todo_edit_file);
3456 free(todo_edit_file);
3457 return 0;
3460 /* Realize --status */
3461 static int sequencer_status(int argc, const char **argv)
3463 if (!file_exists(git_path(SEQ_DIR)))
3464 die("No sequencer running.");
3465 if (get_saved_options())
3466 return 1;
3467 if (file_exists(DONE_FILE)) {
3468 puts("Already done (or tried):");
3469 print_file_with_line_prefix(stdout, DONE_FILE, " ");
3470 putchar('\n');
3472 switch (why) {
3473 case WHY_PAUSE:
3474 puts("Intentionally paused.");
3475 break;
3476 case WHY_RUN:
3477 puts("Interrupted because a 'run' instruction failed.");
3478 break;
3479 case WHY_CONFLICT:
3480 puts("Interrupted by conflict at last line above.");
3481 break;
3482 case WHY_TODO:
3483 puts("Interrupted because of errors in the TODO file.");
3484 break;
3485 default:
3486 puts("Current state is broken.");
3488 if (verbosity > 1)
3489 puts("\nRunning verbosely.");
3490 if (!verbosity)
3491 puts("\nRunning quietly.");
3492 if (orig_headname) {
3493 char *name = strrchr(orig_headname, '/');
3494 printf("\nSequencing on branch '%s'.\n",
3495 name ? name+1 : orig_headname);
3497 if (file_exists(TODO_FILE)) {
3498 puts("\nStill to do:");
3499 print_file_with_line_prefix(stdout, TODO_FILE, " ");
3501 if (why == WHY_TODO)
3502 printf( "\n"
3503 "But there are errors. To edit, run:\n"
3504 "\tgit sequencer --edit\n");
3505 else {
3506 printf( "\n"
3507 "To abort & restore, invoke:\n"
3508 "\t%s\n", caller_abort);
3509 printf( "To continue, invoke:\n"
3510 "\t%s\n", caller_continue);
3511 /* --skip would only lead to confusion, on "pause" or "run" */
3512 if (why != WHY_PAUSE && why != WHY_RUN)
3513 printf( "To skip the current instruction, invoke:\n"
3514 "\t%s\n", caller_skip);
3516 return 0;
3519 /* Realize initial invocation */
3520 static int sequencer_startup(int argc, const char **argv)
3522 if (file_exists(git_path(SEQ_DIR)))
3523 die("Sequencer already started.");
3525 if (get_sha1("HEAD", head_sha1))
3526 die("You do not have a valid HEAD.");
3527 if (is_working_tree_dirty())
3528 die("Working tree is dirty. You can try --allow-dirty.");
3529 if (index_differs_from("HEAD", DIFF_OPT_IGNORE_SUBMODULES))
3530 die("Index is dirty.");
3532 if (mkdir(git_path(SEQ_DIR), 0777))
3533 die("Could not create temporary %s.", git_path(SEQ_DIR));
3535 set_die_routine(die_abort_cb);
3537 comment_for_reflog("start");
3539 set_verbosity(verbosity);
3540 save_int("sequencer.verbosity", verbosity);
3541 save("sequencer.advice", advice ? "true" : "false");
3542 save("sequencer.allowdirty", allow_dirty ? "true" : "false");
3544 save("sequencer.caller.abort", caller_abort);
3545 save("sequencer.caller.continue", caller_continue);
3546 save("sequencer.caller.skip", caller_skip);
3548 /* save old head before checking out the given <branch> */
3549 orig_headname = resolve_symbolic_ref("HEAD");
3550 if (orig_headname && !prefixcmp(orig_headname, "refs/heads/")) {
3551 /* save branch name and detach head */
3552 save("sequencer.headname", orig_headname);
3553 if (update_ref(reflog, "HEAD", head_sha1, head_sha1,
3554 REF_NODEREF, 0))
3555 die("Could not detach HEAD.");
3556 } else
3557 orig_headname = NULL;
3558 save("sequencer.head", sha1_to_hex(head_sha1));
3559 hashcpy(orig_head_sha1, head_sha1);
3561 if (argc) {
3562 if (copy_file(TODO_FILE, *argv, 0666))
3563 die("Could not copy TODO file '%s'.", *argv);
3564 } else {
3565 /* read from stdin and write into TODO_FILE */
3566 int fd;
3567 fd = open(TODO_FILE, O_WRONLY | O_CREAT, 0666);
3568 if (fd < 0)
3569 die("Could not open file '%s' for writing.", TODO_FILE);
3570 if (copy_fd(fileno(stdin), fd))
3571 die("Could not append to TODO file '%s'.", TODO_FILE);
3572 close(fd);
3575 parse_file(TODO_FILE);
3576 if (!contents.total)
3577 die("Nothing to do.");
3579 why = WHY_UNKNOWN;
3580 memset(&available_marks, 0, sizeof(struct string_list));
3581 set_die_routine(die_continue_cb);
3582 if (check_insns()) {
3583 why = WHY_TODO;
3584 die("TODO file contains errors.");
3587 if (execute_insns())
3588 die("Error executing instructions.");
3589 cleanup();
3590 return 0;
3593 int cmd_sequencer(int argc, const char **argv, const char *prefix)
3595 const char * const seq_usage[] = {
3596 "git sequencer [options] [--] [<file>]",
3597 "git sequencer (--continue | --abort | --skip)",
3598 "git sequencer (--edit | --status)",
3599 NULL
3601 int action = 0;
3602 struct option seq_options[] = {
3603 OPT_GROUP("Options to start a sequencing process"),
3604 OPT_BOOLEAN(0, "allow-dirty", &allow_dirty,
3605 "run even if working tree is dirty"),
3606 OPT_BOOLEAN('B', "batch", &batchmode, "run in batch-mode"),
3607 OPT__VERBOSE(&verbosity),
3608 OPT_SET_INT(0, "no-advice", &advice,
3609 "suppress advice when pausing (conflicts, etc)", 0),
3610 OPT_SET_INT('q', "quiet", &verbosity, "suppress output", 0),
3611 OPT_GROUP("Options to restart/change a sequencing process "
3612 "or show information"),
3613 OPT_BIT(0, "continue", &action,
3614 "continue paused sequencer process", ACTION_CONTINUE),
3615 OPT_BIT(0, "abort", &action,
3616 "restore original branch and abort", ACTION_ABORT),
3617 OPT_BIT(0, "skip", &action,
3618 "skip current patch and continue", ACTION_SKIP),
3619 OPT_BIT(0, "status", &action,
3620 "show the status of the sequencing process",
3621 ACTION_STATUS),
3622 OPT_BIT(0, "edit", &action,
3623 "invoke editor to let user edit the remaining insns",
3624 ACTION_EDIT),
3625 OPT_GROUP("Options to be used by user scripts"),
3626 OPT_CALLBACK(0, "caller", NULL, "infostring",
3627 "provide information string: name|abort|cont|skip",
3628 prepare_caller_strings),
3629 OPT_END(),
3632 refresh_cache(REFRESH_QUIET);
3633 if (unmerged_cache())
3634 die("You need to resolve your current index first.");
3636 git_config(git_default_config, NULL);
3638 git_committer_info(IDENT_ERROR_ON_NO_NAME);
3640 prepare_caller_strings(NULL, NULL, 1);
3641 argc = parse_options(argc, argv, NULL, seq_options, seq_usage, 0);
3643 if (action) {
3644 if (argc || batchmode || allow_dirty || advice-1 || verbosity-1)
3645 usage_with_options(seq_usage, seq_options);
3647 switch (action) {
3648 case ACTION_ABORT:
3649 return sequencer_abort(argc, argv);
3650 case ACTION_CONTINUE:
3651 return sequencer_continue(argc, argv);
3652 case ACTION_SKIP:
3653 return sequencer_skip(argc, argv);
3654 case ACTION_STATUS:
3655 return sequencer_status(argc, argv);
3656 case ACTION_EDIT:
3657 return sequencer_edit(argc, argv);
3658 default:
3659 usage_with_options(seq_usage, seq_options);
3661 } else if (argc <= 1)
3662 return sequencer_startup(argc, argv);
3663 else
3664 usage_with_options(seq_usage, seq_options);