1#include"cache.h" 2#include"lockfile.h" 3#include"sequencer.h" 4#include"dir.h" 5#include"object.h" 6#include"commit.h" 7#include"tag.h" 8#include"run-command.h" 9#include"exec_cmd.h" 10#include"utf8.h" 11#include"cache-tree.h" 12#include"diff.h" 13#include"revision.h" 14#include"rerere.h" 15#include"merge-recursive.h" 16#include"refs.h" 17#include"argv-array.h" 18#include"quote.h" 19#include"trailer.h" 20#include"log-tree.h" 21#include"wt-status.h" 22 23#define GIT_REFLOG_ACTION"GIT_REFLOG_ACTION" 24 25const char sign_off_header[] ="Signed-off-by: "; 26static const char cherry_picked_prefix[] ="(cherry picked from commit "; 27 28GIT_PATH_FUNC(git_path_seq_dir,"sequencer") 29 30staticGIT_PATH_FUNC(git_path_todo_file,"sequencer/todo") 31staticGIT_PATH_FUNC(git_path_opts_file,"sequencer/opts") 32staticGIT_PATH_FUNC(git_path_head_file,"sequencer/head") 33staticGIT_PATH_FUNC(git_path_abort_safety_file,"sequencer/abort-safety") 34 35staticGIT_PATH_FUNC(rebase_path,"rebase-merge") 36/* 37 * The file containing rebase commands, comments, and empty lines. 38 * This file is created by "git rebase -i" then edited by the user. As 39 * the lines are processed, they are removed from the front of this 40 * file and written to the tail of 'done'. 41 */ 42staticGIT_PATH_FUNC(rebase_path_todo,"rebase-merge/git-rebase-todo") 43/* 44 * The rebase command lines that have already been processed. A line 45 * is moved here when it is first handled, before any associated user 46 * actions. 47 */ 48staticGIT_PATH_FUNC(rebase_path_done,"rebase-merge/done") 49/* 50 * The commit message that is planned to be used for any changes that 51 * need to be committed following a user interaction. 52 */ 53staticGIT_PATH_FUNC(rebase_path_message,"rebase-merge/message") 54/* 55 * The file into which is accumulated the suggested commit message for 56 * squash/fixup commands. When the first of a series of squash/fixups 57 * is seen, the file is created and the commit message from the 58 * previous commit and from the first squash/fixup commit are written 59 * to it. The commit message for each subsequent squash/fixup commit 60 * is appended to the file as it is processed. 61 * 62 * The first line of the file is of the form 63 * # This is a combination of $count commits. 64 * where $count is the number of commits whose messages have been 65 * written to the file so far (including the initial "pick" commit). 66 * Each time that a commit message is processed, this line is read and 67 * updated. It is deleted just before the combined commit is made. 68 */ 69staticGIT_PATH_FUNC(rebase_path_squash_msg,"rebase-merge/message-squash") 70/* 71 * If the current series of squash/fixups has not yet included a squash 72 * command, then this file exists and holds the commit message of the 73 * original "pick" commit. (If the series ends without a "squash" 74 * command, then this can be used as the commit message of the combined 75 * commit without opening the editor.) 76 */ 77staticGIT_PATH_FUNC(rebase_path_fixup_msg,"rebase-merge/message-fixup") 78/* 79 * A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and 80 * GIT_AUTHOR_DATE that will be used for the commit that is currently 81 * being rebased. 82 */ 83staticGIT_PATH_FUNC(rebase_path_author_script,"rebase-merge/author-script") 84/* 85 * When an "edit" rebase command is being processed, the SHA1 of the 86 * commit to be edited is recorded in this file. When "git rebase 87 * --continue" is executed, if there are any staged changes then they 88 * will be amended to the HEAD commit, but only provided the HEAD 89 * commit is still the commit to be edited. When any other rebase 90 * command is processed, this file is deleted. 91 */ 92staticGIT_PATH_FUNC(rebase_path_amend,"rebase-merge/amend") 93/* 94 * When we stop at a given patch via the "edit" command, this file contains 95 * the abbreviated commit name of the corresponding patch. 96 */ 97staticGIT_PATH_FUNC(rebase_path_stopped_sha,"rebase-merge/stopped-sha") 98/* 99 * The following files are written by git-rebase just after parsing the 100 * command-line (and are only consumed, not modified, by the sequencer). 101 */ 102staticGIT_PATH_FUNC(rebase_path_gpg_sign_opt,"rebase-merge/gpg_sign_opt") 103staticGIT_PATH_FUNC(rebase_path_orig_head,"rebase-merge/orig-head") 104staticGIT_PATH_FUNC(rebase_path_verbose,"rebase-merge/verbose") 105 106staticinlineintis_rebase_i(const struct replay_opts *opts) 107{ 108return opts->action == REPLAY_INTERACTIVE_REBASE; 109} 110 111static const char*get_dir(const struct replay_opts *opts) 112{ 113if(is_rebase_i(opts)) 114returnrebase_path(); 115returngit_path_seq_dir(); 116} 117 118static const char*get_todo_path(const struct replay_opts *opts) 119{ 120if(is_rebase_i(opts)) 121returnrebase_path_todo(); 122returngit_path_todo_file(); 123} 124 125/* 126 * Returns 0 for non-conforming footer 127 * Returns 1 for conforming footer 128 * Returns 2 when sob exists within conforming footer 129 * Returns 3 when sob exists within conforming footer as last entry 130 */ 131static inthas_conforming_footer(struct strbuf *sb,struct strbuf *sob, 132int ignore_footer) 133{ 134struct trailer_info info; 135int i; 136int found_sob =0, found_sob_last =0; 137 138trailer_info_get(&info, sb->buf); 139 140if(info.trailer_start == info.trailer_end) 141return0; 142 143for(i =0; i < info.trailer_nr; i++) 144if(sob && !strncmp(info.trailers[i], sob->buf, sob->len)) { 145 found_sob =1; 146if(i == info.trailer_nr -1) 147 found_sob_last =1; 148} 149 150trailer_info_release(&info); 151 152if(found_sob_last) 153return3; 154if(found_sob) 155return2; 156return1; 157} 158 159static const char*gpg_sign_opt_quoted(struct replay_opts *opts) 160{ 161static struct strbuf buf = STRBUF_INIT; 162 163strbuf_reset(&buf); 164if(opts->gpg_sign) 165sq_quotef(&buf,"-S%s", opts->gpg_sign); 166return buf.buf; 167} 168 169intsequencer_remove_state(struct replay_opts *opts) 170{ 171struct strbuf dir = STRBUF_INIT; 172int i; 173 174free(opts->gpg_sign); 175free(opts->strategy); 176for(i =0; i < opts->xopts_nr; i++) 177free(opts->xopts[i]); 178free(opts->xopts); 179 180strbuf_addf(&dir,"%s",get_dir(opts)); 181remove_dir_recursively(&dir,0); 182strbuf_release(&dir); 183 184return0; 185} 186 187static const char*action_name(const struct replay_opts *opts) 188{ 189switch(opts->action) { 190case REPLAY_REVERT: 191returnN_("revert"); 192case REPLAY_PICK: 193returnN_("cherry-pick"); 194case REPLAY_INTERACTIVE_REBASE: 195returnN_("rebase -i"); 196} 197die(_("Unknown action:%d"), opts->action); 198} 199 200struct commit_message { 201char*parent_label; 202char*label; 203char*subject; 204const char*message; 205}; 206 207static const char*short_commit_name(struct commit *commit) 208{ 209returnfind_unique_abbrev(commit->object.oid.hash, DEFAULT_ABBREV); 210} 211 212static intget_message(struct commit *commit,struct commit_message *out) 213{ 214const char*abbrev, *subject; 215int subject_len; 216 217 out->message =logmsg_reencode(commit, NULL,get_commit_output_encoding()); 218 abbrev =short_commit_name(commit); 219 220 subject_len =find_commit_subject(out->message, &subject); 221 222 out->subject =xmemdupz(subject, subject_len); 223 out->label =xstrfmt("%s...%s", abbrev, out->subject); 224 out->parent_label =xstrfmt("parent of%s", out->label); 225 226return0; 227} 228 229static voidfree_message(struct commit *commit,struct commit_message *msg) 230{ 231free(msg->parent_label); 232free(msg->label); 233free(msg->subject); 234unuse_commit_buffer(commit, msg->message); 235} 236 237static voidprint_advice(int show_hint,struct replay_opts *opts) 238{ 239char*msg =getenv("GIT_CHERRY_PICK_HELP"); 240 241if(msg) { 242fprintf(stderr,"%s\n", msg); 243/* 244 * A conflict has occurred but the porcelain 245 * (typically rebase --interactive) wants to take care 246 * of the commit itself so remove CHERRY_PICK_HEAD 247 */ 248unlink(git_path_cherry_pick_head()); 249return; 250} 251 252if(show_hint) { 253if(opts->no_commit) 254advise(_("after resolving the conflicts, mark the corrected paths\n" 255"with 'git add <paths>' or 'git rm <paths>'")); 256else 257advise(_("after resolving the conflicts, mark the corrected paths\n" 258"with 'git add <paths>' or 'git rm <paths>'\n" 259"and commit the result with 'git commit'")); 260} 261} 262 263static intwrite_message(const void*buf,size_t len,const char*filename, 264int append_eol) 265{ 266static struct lock_file msg_file; 267 268int msg_fd =hold_lock_file_for_update(&msg_file, filename,0); 269if(msg_fd <0) 270returnerror_errno(_("could not lock '%s'"), filename); 271if(write_in_full(msg_fd, buf, len) <0) { 272rollback_lock_file(&msg_file); 273returnerror_errno(_("could not write to '%s'"), filename); 274} 275if(append_eol &&write(msg_fd,"\n",1) <0) { 276rollback_lock_file(&msg_file); 277returnerror_errno(_("could not write eol to '%s'"), filename); 278} 279if(commit_lock_file(&msg_file) <0) { 280rollback_lock_file(&msg_file); 281returnerror(_("failed to finalize '%s'."), filename); 282} 283 284return0; 285} 286 287/* 288 * Reads a file that was presumably written by a shell script, i.e. with an 289 * end-of-line marker that needs to be stripped. 290 * 291 * Note that only the last end-of-line marker is stripped, consistent with the 292 * behavior of "$(cat path)" in a shell script. 293 * 294 * Returns 1 if the file was read, 0 if it could not be read or does not exist. 295 */ 296static intread_oneliner(struct strbuf *buf, 297const char*path,int skip_if_empty) 298{ 299int orig_len = buf->len; 300 301if(!file_exists(path)) 302return0; 303 304if(strbuf_read_file(buf, path,0) <0) { 305warning_errno(_("could not read '%s'"), path); 306return0; 307} 308 309if(buf->len > orig_len && buf->buf[buf->len -1] =='\n') { 310if(--buf->len > orig_len && buf->buf[buf->len -1] =='\r') 311--buf->len; 312 buf->buf[buf->len] ='\0'; 313} 314 315if(skip_if_empty && buf->len == orig_len) 316return0; 317 318return1; 319} 320 321static struct tree *empty_tree(void) 322{ 323returnlookup_tree(EMPTY_TREE_SHA1_BIN); 324} 325 326static interror_dirty_index(struct replay_opts *opts) 327{ 328if(read_cache_unmerged()) 329returnerror_resolve_conflict(_(action_name(opts))); 330 331error(_("your local changes would be overwritten by%s."), 332_(action_name(opts))); 333 334if(advice_commit_before_merge) 335advise(_("commit your changes or stash them to proceed.")); 336return-1; 337} 338 339static voidupdate_abort_safety_file(void) 340{ 341struct object_id head; 342 343/* Do nothing on a single-pick */ 344if(!file_exists(git_path_seq_dir())) 345return; 346 347if(!get_oid("HEAD", &head)) 348write_file(git_path_abort_safety_file(),"%s",oid_to_hex(&head)); 349else 350write_file(git_path_abort_safety_file(),"%s",""); 351} 352 353static intfast_forward_to(const unsigned char*to,const unsigned char*from, 354int unborn,struct replay_opts *opts) 355{ 356struct ref_transaction *transaction; 357struct strbuf sb = STRBUF_INIT; 358struct strbuf err = STRBUF_INIT; 359 360read_cache(); 361if(checkout_fast_forward(from, to,1)) 362return-1;/* the callee should have complained already */ 363 364strbuf_addf(&sb,_("%s: fast-forward"),_(action_name(opts))); 365 366 transaction =ref_transaction_begin(&err); 367if(!transaction || 368ref_transaction_update(transaction,"HEAD", 369 to, unborn ? null_sha1 : from, 3700, sb.buf, &err) || 371ref_transaction_commit(transaction, &err)) { 372ref_transaction_free(transaction); 373error("%s", err.buf); 374strbuf_release(&sb); 375strbuf_release(&err); 376return-1; 377} 378 379strbuf_release(&sb); 380strbuf_release(&err); 381ref_transaction_free(transaction); 382update_abort_safety_file(); 383return0; 384} 385 386voidappend_conflicts_hint(struct strbuf *msgbuf) 387{ 388int i; 389 390strbuf_addch(msgbuf,'\n'); 391strbuf_commented_addf(msgbuf,"Conflicts:\n"); 392for(i =0; i < active_nr;) { 393const struct cache_entry *ce = active_cache[i++]; 394if(ce_stage(ce)) { 395strbuf_commented_addf(msgbuf,"\t%s\n", ce->name); 396while(i < active_nr && !strcmp(ce->name, 397 active_cache[i]->name)) 398 i++; 399} 400} 401} 402 403static intdo_recursive_merge(struct commit *base,struct commit *next, 404const char*base_label,const char*next_label, 405unsigned char*head,struct strbuf *msgbuf, 406struct replay_opts *opts) 407{ 408struct merge_options o; 409struct tree *result, *next_tree, *base_tree, *head_tree; 410int clean; 411char**xopt; 412static struct lock_file index_lock; 413 414hold_locked_index(&index_lock, LOCK_DIE_ON_ERROR); 415 416read_cache(); 417 418init_merge_options(&o); 419 o.ancestor = base ? base_label :"(empty tree)"; 420 o.branch1 ="HEAD"; 421 o.branch2 = next ? next_label :"(empty tree)"; 422 423 head_tree =parse_tree_indirect(head); 424 next_tree = next ? next->tree :empty_tree(); 425 base_tree = base ? base->tree :empty_tree(); 426 427for(xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++) 428parse_merge_opt(&o, *xopt); 429 430 clean =merge_trees(&o, 431 head_tree, 432 next_tree, base_tree, &result); 433strbuf_release(&o.obuf); 434if(clean <0) 435return clean; 436 437if(active_cache_changed && 438write_locked_index(&the_index, &index_lock, COMMIT_LOCK)) 439/* TRANSLATORS: %s will be "revert", "cherry-pick" or 440 * "rebase -i". 441 */ 442returnerror(_("%s: Unable to write new index file"), 443_(action_name(opts))); 444rollback_lock_file(&index_lock); 445 446if(opts->signoff) 447append_signoff(msgbuf,0,0); 448 449if(!clean) 450append_conflicts_hint(msgbuf); 451 452return!clean; 453} 454 455static intis_index_unchanged(void) 456{ 457unsigned char head_sha1[20]; 458struct commit *head_commit; 459 460if(!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL)) 461returnerror(_("could not resolve HEAD commit\n")); 462 463 head_commit =lookup_commit(head_sha1); 464 465/* 466 * If head_commit is NULL, check_commit, called from 467 * lookup_commit, would have indicated that head_commit is not 468 * a commit object already. parse_commit() will return failure 469 * without further complaints in such a case. Otherwise, if 470 * the commit is invalid, parse_commit() will complain. So 471 * there is nothing for us to say here. Just return failure. 472 */ 473if(parse_commit(head_commit)) 474return-1; 475 476if(!active_cache_tree) 477 active_cache_tree =cache_tree(); 478 479if(!cache_tree_fully_valid(active_cache_tree)) 480if(cache_tree_update(&the_index,0)) 481returnerror(_("unable to update cache tree\n")); 482 483return!hashcmp(active_cache_tree->sha1, head_commit->tree->object.oid.hash); 484} 485 486/* 487 * Read the author-script file into an environment block, ready for use in 488 * run_command(), that can be free()d afterwards. 489 */ 490static char**read_author_script(void) 491{ 492struct strbuf script = STRBUF_INIT; 493int i, count =0; 494char*p, *p2, **env; 495size_t env_size; 496 497if(strbuf_read_file(&script,rebase_path_author_script(),256) <=0) 498return NULL; 499 500for(p = script.buf; *p; p++) 501if(skip_prefix(p,"'\\\\''", (const char**)&p2)) 502strbuf_splice(&script, p - script.buf, p2 - p,"'",1); 503else if(*p =='\'') 504strbuf_splice(&script, p-- - script.buf,1,"",0); 505else if(*p =='\n') { 506*p ='\0'; 507 count++; 508} 509 510 env_size = (count +1) *sizeof(*env); 511strbuf_grow(&script, env_size); 512memmove(script.buf + env_size, script.buf, script.len); 513 p = script.buf + env_size; 514 env = (char**)strbuf_detach(&script, NULL); 515 516for(i =0; i < count; i++) { 517 env[i] = p; 518 p +=strlen(p) +1; 519} 520 env[count] = NULL; 521 522return env; 523} 524 525static const char staged_changes_advice[] = 526N_("you have staged changes in your working tree\n" 527"If these changes are meant to be squashed into the previous commit, run:\n" 528"\n" 529" git commit --amend%s\n" 530"\n" 531"If they are meant to go into a new commit, run:\n" 532"\n" 533" git commit%s\n" 534"\n" 535"In both cases, once you're done, continue with:\n" 536"\n" 537" git rebase --continue\n"); 538 539/* 540 * If we are cherry-pick, and if the merge did not result in 541 * hand-editing, we will hit this commit and inherit the original 542 * author date and name. 543 * 544 * If we are revert, or if our cherry-pick results in a hand merge, 545 * we had better say that the current user is responsible for that. 546 * 547 * An exception is when run_git_commit() is called during an 548 * interactive rebase: in that case, we will want to retain the 549 * author metadata. 550 */ 551static intrun_git_commit(const char*defmsg,struct replay_opts *opts, 552int allow_empty,int edit,int amend, 553int cleanup_commit_message) 554{ 555char**env = NULL; 556struct argv_array array; 557int rc; 558const char*value; 559 560if(is_rebase_i(opts)) { 561 env =read_author_script(); 562if(!env) { 563const char*gpg_opt =gpg_sign_opt_quoted(opts); 564 565returnerror(_(staged_changes_advice), 566 gpg_opt, gpg_opt); 567} 568} 569 570argv_array_init(&array); 571argv_array_push(&array,"commit"); 572argv_array_push(&array,"-n"); 573 574if(amend) 575argv_array_push(&array,"--amend"); 576if(opts->gpg_sign) 577argv_array_pushf(&array,"-S%s", opts->gpg_sign); 578if(opts->signoff) 579argv_array_push(&array,"-s"); 580if(defmsg) 581argv_array_pushl(&array,"-F", defmsg, NULL); 582if(cleanup_commit_message) 583argv_array_push(&array,"--cleanup=strip"); 584if(edit) 585argv_array_push(&array,"-e"); 586else if(!cleanup_commit_message && 587!opts->signoff && !opts->record_origin && 588git_config_get_value("commit.cleanup", &value)) 589argv_array_push(&array,"--cleanup=verbatim"); 590 591if(allow_empty) 592argv_array_push(&array,"--allow-empty"); 593 594if(opts->allow_empty_message) 595argv_array_push(&array,"--allow-empty-message"); 596 597 rc =run_command_v_opt_cd_env(array.argv, RUN_GIT_CMD, NULL, 598(const char*const*)env); 599argv_array_clear(&array); 600free(env); 601 602return rc; 603} 604 605static intis_original_commit_empty(struct commit *commit) 606{ 607const unsigned char*ptree_sha1; 608 609if(parse_commit(commit)) 610returnerror(_("could not parse commit%s\n"), 611oid_to_hex(&commit->object.oid)); 612if(commit->parents) { 613struct commit *parent = commit->parents->item; 614if(parse_commit(parent)) 615returnerror(_("could not parse parent commit%s\n"), 616oid_to_hex(&parent->object.oid)); 617 ptree_sha1 = parent->tree->object.oid.hash; 618}else{ 619 ptree_sha1 = EMPTY_TREE_SHA1_BIN;/* commit is root */ 620} 621 622return!hashcmp(ptree_sha1, commit->tree->object.oid.hash); 623} 624 625/* 626 * Do we run "git commit" with "--allow-empty"? 627 */ 628static intallow_empty(struct replay_opts *opts,struct commit *commit) 629{ 630int index_unchanged, empty_commit; 631 632/* 633 * Three cases: 634 * 635 * (1) we do not allow empty at all and error out. 636 * 637 * (2) we allow ones that were initially empty, but 638 * forbid the ones that become empty; 639 * 640 * (3) we allow both. 641 */ 642if(!opts->allow_empty) 643return0;/* let "git commit" barf as necessary */ 644 645 index_unchanged =is_index_unchanged(); 646if(index_unchanged <0) 647return index_unchanged; 648if(!index_unchanged) 649return0;/* we do not have to say --allow-empty */ 650 651if(opts->keep_redundant_commits) 652return1; 653 654 empty_commit =is_original_commit_empty(commit); 655if(empty_commit <0) 656return empty_commit; 657if(!empty_commit) 658return0; 659else 660return1; 661} 662 663/* 664 * Note that ordering matters in this enum. Not only must it match the mapping 665 * below, it is also divided into several sections that matter. When adding 666 * new commands, make sure you add it in the right section. 667 */ 668enum todo_command { 669/* commands that handle commits */ 670 TODO_PICK =0, 671 TODO_REVERT, 672 TODO_EDIT, 673 TODO_FIXUP, 674 TODO_SQUASH, 675/* commands that do something else than handling a single commit */ 676 TODO_EXEC, 677/* commands that do nothing but are counted for reporting progress */ 678 TODO_NOOP 679}; 680 681static struct{ 682char c; 683const char*str; 684} todo_command_info[] = { 685{'p',"pick"}, 686{0,"revert"}, 687{'e',"edit"}, 688{'f',"fixup"}, 689{'s',"squash"}, 690{'x',"exec"}, 691{0,"noop"} 692}; 693 694static const char*command_to_string(const enum todo_command command) 695{ 696if((size_t)command <ARRAY_SIZE(todo_command_info)) 697return todo_command_info[command].str; 698die("Unknown command:%d", command); 699} 700 701static intis_noop(const enum todo_command command) 702{ 703return TODO_NOOP <= (size_t)command; 704} 705 706static intis_fixup(enum todo_command command) 707{ 708return command == TODO_FIXUP || command == TODO_SQUASH; 709} 710 711static intupdate_squash_messages(enum todo_command command, 712struct commit *commit,struct replay_opts *opts) 713{ 714struct strbuf buf = STRBUF_INIT; 715int count, res; 716const char*message, *body; 717 718if(file_exists(rebase_path_squash_msg())) { 719struct strbuf header = STRBUF_INIT; 720char*eol, *p; 721 722if(strbuf_read_file(&buf,rebase_path_squash_msg(),2048) <=0) 723returnerror(_("could not read '%s'"), 724rebase_path_squash_msg()); 725 726 p = buf.buf +1; 727 eol =strchrnul(buf.buf,'\n'); 728if(buf.buf[0] != comment_line_char || 729(p +=strcspn(p,"0123456789\n")) == eol) 730returnerror(_("unexpected 1st line of squash message:" 731"\n\n\t%.*s"), 732(int)(eol - buf.buf), buf.buf); 733 count =strtol(p, NULL,10); 734 735if(count <1) 736returnerror(_("invalid 1st line of squash message:\n" 737"\n\t%.*s"), 738(int)(eol - buf.buf), buf.buf); 739 740strbuf_addf(&header,"%c", comment_line_char); 741strbuf_addf(&header, 742_("This is a combination of%dcommits."), ++count); 743strbuf_splice(&buf,0, eol - buf.buf, header.buf, header.len); 744strbuf_release(&header); 745}else{ 746unsigned char head[20]; 747struct commit *head_commit; 748const char*head_message, *body; 749 750if(get_sha1("HEAD", head)) 751returnerror(_("need a HEAD to fixup")); 752if(!(head_commit =lookup_commit_reference(head))) 753returnerror(_("could not read HEAD")); 754if(!(head_message =get_commit_buffer(head_commit, NULL))) 755returnerror(_("could not read HEAD's commit message")); 756 757find_commit_subject(head_message, &body); 758if(write_message(body,strlen(body), 759rebase_path_fixup_msg(),0)) { 760unuse_commit_buffer(head_commit, head_message); 761returnerror(_("cannot write '%s'"), 762rebase_path_fixup_msg()); 763} 764 765 count =2; 766strbuf_addf(&buf,"%c", comment_line_char); 767strbuf_addf(&buf,_("This is a combination of%dcommits."), 768 count); 769strbuf_addf(&buf,"\n%c", comment_line_char); 770strbuf_addstr(&buf,_("This is the 1st commit message:")); 771strbuf_addstr(&buf,"\n\n"); 772strbuf_addstr(&buf, body); 773 774unuse_commit_buffer(head_commit, head_message); 775} 776 777if(!(message =get_commit_buffer(commit, NULL))) 778returnerror(_("could not read commit message of%s"), 779oid_to_hex(&commit->object.oid)); 780find_commit_subject(message, &body); 781 782if(command == TODO_SQUASH) { 783unlink(rebase_path_fixup_msg()); 784strbuf_addf(&buf,"\n%c", comment_line_char); 785strbuf_addf(&buf,_("This is the commit message #%d:"), count); 786strbuf_addstr(&buf,"\n\n"); 787strbuf_addstr(&buf, body); 788}else if(command == TODO_FIXUP) { 789strbuf_addf(&buf,"\n%c", comment_line_char); 790strbuf_addf(&buf,_("The commit message #%dwill be skipped:"), 791 count); 792strbuf_addstr(&buf,"\n\n"); 793strbuf_add_commented_lines(&buf, body,strlen(body)); 794}else 795returnerror(_("unknown command:%d"), command); 796unuse_commit_buffer(commit, message); 797 798 res =write_message(buf.buf, buf.len,rebase_path_squash_msg(),0); 799strbuf_release(&buf); 800return res; 801} 802 803static intdo_pick_commit(enum todo_command command,struct commit *commit, 804struct replay_opts *opts,int final_fixup) 805{ 806int edit = opts->edit, cleanup_commit_message =0; 807const char*msg_file = edit ? NULL :git_path_merge_msg(); 808unsigned char head[20]; 809struct commit *base, *next, *parent; 810const char*base_label, *next_label; 811struct commit_message msg = { NULL, NULL, NULL, NULL }; 812struct strbuf msgbuf = STRBUF_INIT; 813int res, unborn =0, amend =0, allow; 814 815if(opts->no_commit) { 816/* 817 * We do not intend to commit immediately. We just want to 818 * merge the differences in, so let's compute the tree 819 * that represents the "current" state for merge-recursive 820 * to work on. 821 */ 822if(write_cache_as_tree(head,0, NULL)) 823returnerror(_("your index file is unmerged.")); 824}else{ 825 unborn =get_sha1("HEAD", head); 826if(unborn) 827hashcpy(head, EMPTY_TREE_SHA1_BIN); 828if(index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX :"HEAD",0,0)) 829returnerror_dirty_index(opts); 830} 831discard_cache(); 832 833if(!commit->parents) 834 parent = NULL; 835else if(commit->parents->next) { 836/* Reverting or cherry-picking a merge commit */ 837int cnt; 838struct commit_list *p; 839 840if(!opts->mainline) 841returnerror(_("commit%sis a merge but no -m option was given."), 842oid_to_hex(&commit->object.oid)); 843 844for(cnt =1, p = commit->parents; 845 cnt != opts->mainline && p; 846 cnt++) 847 p = p->next; 848if(cnt != opts->mainline || !p) 849returnerror(_("commit%sdoes not have parent%d"), 850oid_to_hex(&commit->object.oid), opts->mainline); 851 parent = p->item; 852}else if(0< opts->mainline) 853returnerror(_("mainline was specified but commit%sis not a merge."), 854oid_to_hex(&commit->object.oid)); 855else 856 parent = commit->parents->item; 857 858if(opts->allow_ff && !is_fixup(command) && 859((parent && !hashcmp(parent->object.oid.hash, head)) || 860(!parent && unborn))) 861returnfast_forward_to(commit->object.oid.hash, head, unborn, opts); 862 863if(parent &&parse_commit(parent) <0) 864/* TRANSLATORS: The first %s will be a "todo" command like 865 "revert" or "pick", the second %s a SHA1. */ 866returnerror(_("%s: cannot parse parent commit%s"), 867command_to_string(command), 868oid_to_hex(&parent->object.oid)); 869 870if(get_message(commit, &msg) !=0) 871returnerror(_("cannot get commit message for%s"), 872oid_to_hex(&commit->object.oid)); 873 874/* 875 * "commit" is an existing commit. We would want to apply 876 * the difference it introduces since its first parent "prev" 877 * on top of the current HEAD if we are cherry-pick. Or the 878 * reverse of it if we are revert. 879 */ 880 881if(command == TODO_REVERT) { 882 base = commit; 883 base_label = msg.label; 884 next = parent; 885 next_label = msg.parent_label; 886strbuf_addstr(&msgbuf,"Revert\""); 887strbuf_addstr(&msgbuf, msg.subject); 888strbuf_addstr(&msgbuf,"\"\n\nThis reverts commit "); 889strbuf_addstr(&msgbuf,oid_to_hex(&commit->object.oid)); 890 891if(commit->parents && commit->parents->next) { 892strbuf_addstr(&msgbuf,", reversing\nchanges made to "); 893strbuf_addstr(&msgbuf,oid_to_hex(&parent->object.oid)); 894} 895strbuf_addstr(&msgbuf,".\n"); 896}else{ 897const char*p; 898 899 base = parent; 900 base_label = msg.parent_label; 901 next = commit; 902 next_label = msg.label; 903 904/* Append the commit log message to msgbuf. */ 905if(find_commit_subject(msg.message, &p)) 906strbuf_addstr(&msgbuf, p); 907 908if(opts->record_origin) { 909if(!has_conforming_footer(&msgbuf, NULL,0)) 910strbuf_addch(&msgbuf,'\n'); 911strbuf_addstr(&msgbuf, cherry_picked_prefix); 912strbuf_addstr(&msgbuf,oid_to_hex(&commit->object.oid)); 913strbuf_addstr(&msgbuf,")\n"); 914} 915} 916 917if(is_fixup(command)) { 918if(update_squash_messages(command, commit, opts)) 919return-1; 920 amend =1; 921if(!final_fixup) 922 msg_file =rebase_path_squash_msg(); 923else if(file_exists(rebase_path_fixup_msg())) { 924 cleanup_commit_message =1; 925 msg_file =rebase_path_fixup_msg(); 926}else{ 927const char*dest =git_path("SQUASH_MSG"); 928unlink(dest); 929if(copy_file(dest,rebase_path_squash_msg(),0666)) 930returnerror(_("could not rename '%s' to '%s'"), 931rebase_path_squash_msg(), dest); 932unlink(git_path("MERGE_MSG")); 933 msg_file = dest; 934 edit =1; 935} 936} 937 938if(!opts->strategy || !strcmp(opts->strategy,"recursive") || command == TODO_REVERT) { 939 res =do_recursive_merge(base, next, base_label, next_label, 940 head, &msgbuf, opts); 941if(res <0) 942return res; 943 res |=write_message(msgbuf.buf, msgbuf.len, 944git_path_merge_msg(),0); 945}else{ 946struct commit_list *common = NULL; 947struct commit_list *remotes = NULL; 948 949 res =write_message(msgbuf.buf, msgbuf.len, 950git_path_merge_msg(),0); 951 952commit_list_insert(base, &common); 953commit_list_insert(next, &remotes); 954 res |=try_merge_command(opts->strategy, 955 opts->xopts_nr, (const char**)opts->xopts, 956 common,sha1_to_hex(head), remotes); 957free_commit_list(common); 958free_commit_list(remotes); 959} 960strbuf_release(&msgbuf); 961 962/* 963 * If the merge was clean or if it failed due to conflict, we write 964 * CHERRY_PICK_HEAD for the subsequent invocation of commit to use. 965 * However, if the merge did not even start, then we don't want to 966 * write it at all. 967 */ 968if(command == TODO_PICK && !opts->no_commit && (res ==0|| res ==1) && 969update_ref(NULL,"CHERRY_PICK_HEAD", commit->object.oid.hash, NULL, 970 REF_NODEREF, UPDATE_REFS_MSG_ON_ERR)) 971 res = -1; 972if(command == TODO_REVERT && ((opts->no_commit && res ==0) || res ==1) && 973update_ref(NULL,"REVERT_HEAD", commit->object.oid.hash, NULL, 974 REF_NODEREF, UPDATE_REFS_MSG_ON_ERR)) 975 res = -1; 976 977if(res) { 978error(command == TODO_REVERT 979?_("could not revert%s...%s") 980:_("could not apply%s...%s"), 981short_commit_name(commit), msg.subject); 982print_advice(res ==1, opts); 983rerere(opts->allow_rerere_auto); 984goto leave; 985} 986 987 allow =allow_empty(opts, commit); 988if(allow <0) { 989 res = allow; 990goto leave; 991} 992if(!opts->no_commit) 993 res =run_git_commit(msg_file, opts, allow, edit, amend, 994 cleanup_commit_message); 995 996if(!res && final_fixup) { 997unlink(rebase_path_fixup_msg()); 998unlink(rebase_path_squash_msg()); 999}10001001leave:1002free_message(commit, &msg);1003update_abort_safety_file();10041005return res;1006}10071008static intprepare_revs(struct replay_opts *opts)1009{1010/*1011 * picking (but not reverting) ranges (but not individual revisions)1012 * should be done in reverse1013 */1014if(opts->action == REPLAY_PICK && !opts->revs->no_walk)1015 opts->revs->reverse ^=1;10161017if(prepare_revision_walk(opts->revs))1018returnerror(_("revision walk setup failed"));10191020if(!opts->revs->commits)1021returnerror(_("empty commit set passed"));1022return0;1023}10241025static intread_and_refresh_cache(struct replay_opts *opts)1026{1027static struct lock_file index_lock;1028int index_fd =hold_locked_index(&index_lock,0);1029if(read_index_preload(&the_index, NULL) <0) {1030rollback_lock_file(&index_lock);1031returnerror(_("git%s: failed to read the index"),1032_(action_name(opts)));1033}1034refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED, NULL, NULL, NULL);1035if(the_index.cache_changed && index_fd >=0) {1036if(write_locked_index(&the_index, &index_lock, COMMIT_LOCK)) {1037rollback_lock_file(&index_lock);1038returnerror(_("git%s: failed to refresh the index"),1039_(action_name(opts)));1040}1041}1042rollback_lock_file(&index_lock);1043return0;1044}10451046struct todo_item {1047enum todo_command command;1048struct commit *commit;1049const char*arg;1050int arg_len;1051size_t offset_in_buf;1052};10531054struct todo_list {1055struct strbuf buf;1056struct todo_item *items;1057int nr, alloc, current;1058};10591060#define TODO_LIST_INIT { STRBUF_INIT }10611062static voidtodo_list_release(struct todo_list *todo_list)1063{1064strbuf_release(&todo_list->buf);1065free(todo_list->items);1066 todo_list->items = NULL;1067 todo_list->nr = todo_list->alloc =0;1068}10691070static struct todo_item *append_new_todo(struct todo_list *todo_list)1071{1072ALLOC_GROW(todo_list->items, todo_list->nr +1, todo_list->alloc);1073return todo_list->items + todo_list->nr++;1074}10751076static intparse_insn_line(struct todo_item *item,const char*bol,char*eol)1077{1078unsigned char commit_sha1[20];1079char*end_of_object_name;1080int i, saved, status, padding;10811082/* left-trim */1083 bol +=strspn(bol,"\t");10841085if(bol == eol || *bol =='\r'|| *bol == comment_line_char) {1086 item->command = TODO_NOOP;1087 item->commit = NULL;1088 item->arg = bol;1089 item->arg_len = eol - bol;1090return0;1091}10921093for(i =0; i <ARRAY_SIZE(todo_command_info); i++)1094if(skip_prefix(bol, todo_command_info[i].str, &bol)) {1095 item->command = i;1096break;1097}else if(bol[1] ==' '&& *bol == todo_command_info[i].c) {1098 bol++;1099 item->command = i;1100break;1101}1102if(i >=ARRAY_SIZE(todo_command_info))1103return-1;11041105if(item->command == TODO_NOOP) {1106 item->commit = NULL;1107 item->arg = bol;1108 item->arg_len = eol - bol;1109return0;1110}11111112/* Eat up extra spaces/ tabs before object name */1113 padding =strspn(bol,"\t");1114if(!padding)1115return-1;1116 bol += padding;11171118if(item->command == TODO_EXEC) {1119 item->arg = bol;1120 item->arg_len = (int)(eol - bol);1121return0;1122}11231124 end_of_object_name = (char*) bol +strcspn(bol,"\t\n");1125 saved = *end_of_object_name;1126*end_of_object_name ='\0';1127 status =get_sha1(bol, commit_sha1);1128*end_of_object_name = saved;11291130 item->arg = end_of_object_name +strspn(end_of_object_name,"\t");1131 item->arg_len = (int)(eol - item->arg);11321133if(status <0)1134return-1;11351136 item->commit =lookup_commit_reference(commit_sha1);1137return!item->commit;1138}11391140static intparse_insn_buffer(char*buf,struct todo_list *todo_list)1141{1142struct todo_item *item;1143char*p = buf, *next_p;1144int i, res =0, fixup_okay =file_exists(rebase_path_done());11451146for(i =1; *p; i++, p = next_p) {1147char*eol =strchrnul(p,'\n');11481149 next_p = *eol ? eol +1/* skip LF */: eol;11501151if(p != eol && eol[-1] =='\r')1152 eol--;/* strip Carriage Return */11531154 item =append_new_todo(todo_list);1155 item->offset_in_buf = p - todo_list->buf.buf;1156if(parse_insn_line(item, p, eol)) {1157 res =error(_("invalid line%d: %.*s"),1158 i, (int)(eol - p), p);1159 item->command = TODO_NOOP;1160}11611162if(fixup_okay)1163;/* do nothing */1164else if(is_fixup(item->command))1165returnerror(_("cannot '%s' without a previous commit"),1166command_to_string(item->command));1167else if(!is_noop(item->command))1168 fixup_okay =1;1169}1170if(!todo_list->nr)1171returnerror(_("no commits parsed."));1172return res;1173}11741175static intread_populate_todo(struct todo_list *todo_list,1176struct replay_opts *opts)1177{1178const char*todo_file =get_todo_path(opts);1179int fd, res;11801181strbuf_reset(&todo_list->buf);1182 fd =open(todo_file, O_RDONLY);1183if(fd <0)1184returnerror_errno(_("could not open '%s'"), todo_file);1185if(strbuf_read(&todo_list->buf, fd,0) <0) {1186close(fd);1187returnerror(_("could not read '%s'."), todo_file);1188}1189close(fd);11901191 res =parse_insn_buffer(todo_list->buf.buf, todo_list);1192if(res)1193returnerror(_("unusable instruction sheet: '%s'"), todo_file);11941195if(!is_rebase_i(opts)) {1196enum todo_command valid =1197 opts->action == REPLAY_PICK ? TODO_PICK : TODO_REVERT;1198int i;11991200for(i =0; i < todo_list->nr; i++)1201if(valid == todo_list->items[i].command)1202continue;1203else if(valid == TODO_PICK)1204returnerror(_("cannot cherry-pick during a revert."));1205else1206returnerror(_("cannot revert during a cherry-pick."));1207}12081209return0;1210}12111212static intgit_config_string_dup(char**dest,1213const char*var,const char*value)1214{1215if(!value)1216returnconfig_error_nonbool(var);1217free(*dest);1218*dest =xstrdup(value);1219return0;1220}12211222static intpopulate_opts_cb(const char*key,const char*value,void*data)1223{1224struct replay_opts *opts = data;1225int error_flag =1;12261227if(!value)1228 error_flag =0;1229else if(!strcmp(key,"options.no-commit"))1230 opts->no_commit =git_config_bool_or_int(key, value, &error_flag);1231else if(!strcmp(key,"options.edit"))1232 opts->edit =git_config_bool_or_int(key, value, &error_flag);1233else if(!strcmp(key,"options.signoff"))1234 opts->signoff =git_config_bool_or_int(key, value, &error_flag);1235else if(!strcmp(key,"options.record-origin"))1236 opts->record_origin =git_config_bool_or_int(key, value, &error_flag);1237else if(!strcmp(key,"options.allow-ff"))1238 opts->allow_ff =git_config_bool_or_int(key, value, &error_flag);1239else if(!strcmp(key,"options.mainline"))1240 opts->mainline =git_config_int(key, value);1241else if(!strcmp(key,"options.strategy"))1242git_config_string_dup(&opts->strategy, key, value);1243else if(!strcmp(key,"options.gpg-sign"))1244git_config_string_dup(&opts->gpg_sign, key, value);1245else if(!strcmp(key,"options.strategy-option")) {1246ALLOC_GROW(opts->xopts, opts->xopts_nr +1, opts->xopts_alloc);1247 opts->xopts[opts->xopts_nr++] =xstrdup(value);1248}else1249returnerror(_("invalid key:%s"), key);12501251if(!error_flag)1252returnerror(_("invalid value for%s:%s"), key, value);12531254return0;1255}12561257static intread_populate_opts(struct replay_opts *opts)1258{1259if(is_rebase_i(opts)) {1260struct strbuf buf = STRBUF_INIT;12611262if(read_oneliner(&buf,rebase_path_gpg_sign_opt(),1)) {1263if(!starts_with(buf.buf,"-S"))1264strbuf_reset(&buf);1265else{1266free(opts->gpg_sign);1267 opts->gpg_sign =xstrdup(buf.buf +2);1268}1269}1270strbuf_release(&buf);12711272if(file_exists(rebase_path_verbose()))1273 opts->verbose =1;12741275return0;1276}12771278if(!file_exists(git_path_opts_file()))1279return0;1280/*1281 * The function git_parse_source(), called from git_config_from_file(),1282 * may die() in case of a syntactically incorrect file. We do not care1283 * about this case, though, because we wrote that file ourselves, so we1284 * are pretty certain that it is syntactically correct.1285 */1286if(git_config_from_file(populate_opts_cb,git_path_opts_file(), opts) <0)1287returnerror(_("malformed options sheet: '%s'"),1288git_path_opts_file());1289return0;1290}12911292static intwalk_revs_populate_todo(struct todo_list *todo_list,1293struct replay_opts *opts)1294{1295enum todo_command command = opts->action == REPLAY_PICK ?1296 TODO_PICK : TODO_REVERT;1297const char*command_string = todo_command_info[command].str;1298struct commit *commit;12991300if(prepare_revs(opts))1301return-1;13021303while((commit =get_revision(opts->revs))) {1304struct todo_item *item =append_new_todo(todo_list);1305const char*commit_buffer =get_commit_buffer(commit, NULL);1306const char*subject;1307int subject_len;13081309 item->command = command;1310 item->commit = commit;1311 item->arg = NULL;1312 item->arg_len =0;1313 item->offset_in_buf = todo_list->buf.len;1314 subject_len =find_commit_subject(commit_buffer, &subject);1315strbuf_addf(&todo_list->buf,"%s %s%.*s\n", command_string,1316short_commit_name(commit), subject_len, subject);1317unuse_commit_buffer(commit, commit_buffer);1318}1319return0;1320}13211322static intcreate_seq_dir(void)1323{1324if(file_exists(git_path_seq_dir())) {1325error(_("a cherry-pick or revert is already in progress"));1326advise(_("try\"git cherry-pick (--continue | --quit | --abort)\""));1327return-1;1328}else if(mkdir(git_path_seq_dir(),0777) <0)1329returnerror_errno(_("could not create sequencer directory '%s'"),1330git_path_seq_dir());1331return0;1332}13331334static intsave_head(const char*head)1335{1336static struct lock_file head_lock;1337struct strbuf buf = STRBUF_INIT;1338int fd;13391340 fd =hold_lock_file_for_update(&head_lock,git_path_head_file(),0);1341if(fd <0) {1342rollback_lock_file(&head_lock);1343returnerror_errno(_("could not lock HEAD"));1344}1345strbuf_addf(&buf,"%s\n", head);1346if(write_in_full(fd, buf.buf, buf.len) <0) {1347rollback_lock_file(&head_lock);1348returnerror_errno(_("could not write to '%s'"),1349git_path_head_file());1350}1351if(commit_lock_file(&head_lock) <0) {1352rollback_lock_file(&head_lock);1353returnerror(_("failed to finalize '%s'."),git_path_head_file());1354}1355return0;1356}13571358static introllback_is_safe(void)1359{1360struct strbuf sb = STRBUF_INIT;1361struct object_id expected_head, actual_head;13621363if(strbuf_read_file(&sb,git_path_abort_safety_file(),0) >=0) {1364strbuf_trim(&sb);1365if(get_oid_hex(sb.buf, &expected_head)) {1366strbuf_release(&sb);1367die(_("could not parse%s"),git_path_abort_safety_file());1368}1369strbuf_release(&sb);1370}1371else if(errno == ENOENT)1372oidclr(&expected_head);1373else1374die_errno(_("could not read '%s'"),git_path_abort_safety_file());13751376if(get_oid("HEAD", &actual_head))1377oidclr(&actual_head);13781379return!oidcmp(&actual_head, &expected_head);1380}13811382static intreset_for_rollback(const unsigned char*sha1)1383{1384const char*argv[4];/* reset --merge <arg> + NULL */13851386 argv[0] ="reset";1387 argv[1] ="--merge";1388 argv[2] =sha1_to_hex(sha1);1389 argv[3] = NULL;1390returnrun_command_v_opt(argv, RUN_GIT_CMD);1391}13921393static introllback_single_pick(void)1394{1395unsigned char head_sha1[20];13961397if(!file_exists(git_path_cherry_pick_head()) &&1398!file_exists(git_path_revert_head()))1399returnerror(_("no cherry-pick or revert in progress"));1400if(read_ref_full("HEAD",0, head_sha1, NULL))1401returnerror(_("cannot resolve HEAD"));1402if(is_null_sha1(head_sha1))1403returnerror(_("cannot abort from a branch yet to be born"));1404returnreset_for_rollback(head_sha1);1405}14061407intsequencer_rollback(struct replay_opts *opts)1408{1409FILE*f;1410unsigned char sha1[20];1411struct strbuf buf = STRBUF_INIT;14121413 f =fopen(git_path_head_file(),"r");1414if(!f && errno == ENOENT) {1415/*1416 * There is no multiple-cherry-pick in progress.1417 * If CHERRY_PICK_HEAD or REVERT_HEAD indicates1418 * a single-cherry-pick in progress, abort that.1419 */1420returnrollback_single_pick();1421}1422if(!f)1423returnerror_errno(_("cannot open '%s'"),git_path_head_file());1424if(strbuf_getline_lf(&buf, f)) {1425error(_("cannot read '%s':%s"),git_path_head_file(),1426ferror(f) ?strerror(errno) :_("unexpected end of file"));1427fclose(f);1428goto fail;1429}1430fclose(f);1431if(get_sha1_hex(buf.buf, sha1) || buf.buf[40] !='\0') {1432error(_("stored pre-cherry-pick HEAD file '%s' is corrupt"),1433git_path_head_file());1434goto fail;1435}1436if(is_null_sha1(sha1)) {1437error(_("cannot abort from a branch yet to be born"));1438goto fail;1439}14401441if(!rollback_is_safe()) {1442/* Do not error, just do not rollback */1443warning(_("You seem to have moved HEAD. "1444"Not rewinding, check your HEAD!"));1445}else1446if(reset_for_rollback(sha1))1447goto fail;1448strbuf_release(&buf);1449returnsequencer_remove_state(opts);1450fail:1451strbuf_release(&buf);1452return-1;1453}14541455static intsave_todo(struct todo_list *todo_list,struct replay_opts *opts)1456{1457static struct lock_file todo_lock;1458const char*todo_path =get_todo_path(opts);1459int next = todo_list->current, offset, fd;14601461/*1462 * rebase -i writes "git-rebase-todo" without the currently executing1463 * command, appending it to "done" instead.1464 */1465if(is_rebase_i(opts))1466 next++;14671468 fd =hold_lock_file_for_update(&todo_lock, todo_path,0);1469if(fd <0)1470returnerror_errno(_("could not lock '%s'"), todo_path);1471 offset = next < todo_list->nr ?1472 todo_list->items[next].offset_in_buf : todo_list->buf.len;1473if(write_in_full(fd, todo_list->buf.buf + offset,1474 todo_list->buf.len - offset) <0)1475returnerror_errno(_("could not write to '%s'"), todo_path);1476if(commit_lock_file(&todo_lock) <0)1477returnerror(_("failed to finalize '%s'."), todo_path);14781479if(is_rebase_i(opts)) {1480const char*done_path =rebase_path_done();1481int fd =open(done_path, O_CREAT | O_WRONLY | O_APPEND,0666);1482int prev_offset = !next ?0:1483 todo_list->items[next -1].offset_in_buf;14841485if(fd >=0&& offset > prev_offset &&1486write_in_full(fd, todo_list->buf.buf + prev_offset,1487 offset - prev_offset) <0) {1488close(fd);1489returnerror_errno(_("could not write to '%s'"),1490 done_path);1491}1492if(fd >=0)1493close(fd);1494}1495return0;1496}14971498static intsave_opts(struct replay_opts *opts)1499{1500const char*opts_file =git_path_opts_file();1501int res =0;15021503if(opts->no_commit)1504 res |=git_config_set_in_file_gently(opts_file,"options.no-commit","true");1505if(opts->edit)1506 res |=git_config_set_in_file_gently(opts_file,"options.edit","true");1507if(opts->signoff)1508 res |=git_config_set_in_file_gently(opts_file,"options.signoff","true");1509if(opts->record_origin)1510 res |=git_config_set_in_file_gently(opts_file,"options.record-origin","true");1511if(opts->allow_ff)1512 res |=git_config_set_in_file_gently(opts_file,"options.allow-ff","true");1513if(opts->mainline) {1514struct strbuf buf = STRBUF_INIT;1515strbuf_addf(&buf,"%d", opts->mainline);1516 res |=git_config_set_in_file_gently(opts_file,"options.mainline", buf.buf);1517strbuf_release(&buf);1518}1519if(opts->strategy)1520 res |=git_config_set_in_file_gently(opts_file,"options.strategy", opts->strategy);1521if(opts->gpg_sign)1522 res |=git_config_set_in_file_gently(opts_file,"options.gpg-sign", opts->gpg_sign);1523if(opts->xopts) {1524int i;1525for(i =0; i < opts->xopts_nr; i++)1526 res |=git_config_set_multivar_in_file_gently(opts_file,1527"options.strategy-option",1528 opts->xopts[i],"^$",0);1529}1530return res;1531}15321533static intmake_patch(struct commit *commit,struct replay_opts *opts)1534{1535struct strbuf buf = STRBUF_INIT;1536struct rev_info log_tree_opt;1537const char*subject, *p;1538int res =0;15391540 p =short_commit_name(commit);1541if(write_message(p,strlen(p),rebase_path_stopped_sha(),1) <0)1542return-1;15431544strbuf_addf(&buf,"%s/patch",get_dir(opts));1545memset(&log_tree_opt,0,sizeof(log_tree_opt));1546init_revisions(&log_tree_opt, NULL);1547 log_tree_opt.abbrev =0;1548 log_tree_opt.diff =1;1549 log_tree_opt.diffopt.output_format = DIFF_FORMAT_PATCH;1550 log_tree_opt.disable_stdin =1;1551 log_tree_opt.no_commit_id =1;1552 log_tree_opt.diffopt.file =fopen(buf.buf,"w");1553 log_tree_opt.diffopt.use_color = GIT_COLOR_NEVER;1554if(!log_tree_opt.diffopt.file)1555 res |=error_errno(_("could not open '%s'"), buf.buf);1556else{1557 res |=log_tree_commit(&log_tree_opt, commit);1558fclose(log_tree_opt.diffopt.file);1559}1560strbuf_reset(&buf);15611562strbuf_addf(&buf,"%s/message",get_dir(opts));1563if(!file_exists(buf.buf)) {1564const char*commit_buffer =get_commit_buffer(commit, NULL);1565find_commit_subject(commit_buffer, &subject);1566 res |=write_message(subject,strlen(subject), buf.buf,1);1567unuse_commit_buffer(commit, commit_buffer);1568}1569strbuf_release(&buf);15701571return res;1572}15731574static intintend_to_amend(void)1575{1576unsigned char head[20];1577char*p;15781579if(get_sha1("HEAD", head))1580returnerror(_("cannot read HEAD"));15811582 p =sha1_to_hex(head);1583returnwrite_message(p,strlen(p),rebase_path_amend(),1);1584}15851586static interror_with_patch(struct commit *commit,1587const char*subject,int subject_len,1588struct replay_opts *opts,int exit_code,int to_amend)1589{1590if(make_patch(commit, opts))1591return-1;15921593if(to_amend) {1594if(intend_to_amend())1595return-1;15961597fprintf(stderr,"You can amend the commit now, with\n"1598"\n"1599" git commit --amend%s\n"1600"\n"1601"Once you are satisfied with your changes, run\n"1602"\n"1603" git rebase --continue\n",gpg_sign_opt_quoted(opts));1604}else if(exit_code)1605fprintf(stderr,"Could not apply%s... %.*s\n",1606short_commit_name(commit), subject_len, subject);16071608return exit_code;1609}16101611static interror_failed_squash(struct commit *commit,1612struct replay_opts *opts,int subject_len,const char*subject)1613{1614if(rename(rebase_path_squash_msg(),rebase_path_message()))1615returnerror(_("could not rename '%s' to '%s'"),1616rebase_path_squash_msg(),rebase_path_message());1617unlink(rebase_path_fixup_msg());1618unlink(git_path("MERGE_MSG"));1619if(copy_file(git_path("MERGE_MSG"),rebase_path_message(),0666))1620returnerror(_("could not copy '%s' to '%s'"),1621rebase_path_message(),git_path("MERGE_MSG"));1622returnerror_with_patch(commit, subject, subject_len, opts,1,0);1623}16241625static intdo_exec(const char*command_line)1626{1627const char*child_argv[] = { NULL, NULL };1628int dirty, status;16291630fprintf(stderr,"Executing:%s\n", command_line);1631 child_argv[0] = command_line;1632 status =run_command_v_opt(child_argv, RUN_USING_SHELL);16331634/* force re-reading of the cache */1635if(discard_cache() <0||read_cache() <0)1636returnerror(_("could not read index"));16371638 dirty =require_clean_work_tree("rebase", NULL,1,1);16391640if(status) {1641warning(_("execution failed:%s\n%s"1642"You can fix the problem, and then run\n"1643"\n"1644" git rebase --continue\n"1645"\n"),1646 command_line,1647 dirty ?N_("and made changes to the index and/or the "1648"working tree\n") :"");1649if(status ==127)1650/* command not found */1651 status =1;1652}else if(dirty) {1653warning(_("execution succeeded:%s\nbut "1654"left changes to the index and/or the working tree\n"1655"Commit or stash your changes, and then run\n"1656"\n"1657" git rebase --continue\n"1658"\n"), command_line);1659 status =1;1660}16611662return status;1663}16641665static intis_final_fixup(struct todo_list *todo_list)1666{1667int i = todo_list->current;16681669if(!is_fixup(todo_list->items[i].command))1670return0;16711672while(++i < todo_list->nr)1673if(is_fixup(todo_list->items[i].command))1674return0;1675else if(!is_noop(todo_list->items[i].command))1676break;1677return1;1678}16791680static intpick_commits(struct todo_list *todo_list,struct replay_opts *opts)1681{1682int res =0;16831684setenv(GIT_REFLOG_ACTION,action_name(opts),0);1685if(opts->allow_ff)1686assert(!(opts->signoff || opts->no_commit ||1687 opts->record_origin || opts->edit));1688if(read_and_refresh_cache(opts))1689return-1;16901691while(todo_list->current < todo_list->nr) {1692struct todo_item *item = todo_list->items + todo_list->current;1693if(save_todo(todo_list, opts))1694return-1;1695if(is_rebase_i(opts)) {1696unlink(rebase_path_message());1697unlink(rebase_path_author_script());1698unlink(rebase_path_stopped_sha());1699unlink(rebase_path_amend());1700}1701if(item->command <= TODO_SQUASH) {1702 res =do_pick_commit(item->command, item->commit,1703 opts,is_final_fixup(todo_list));1704if(item->command == TODO_EDIT) {1705struct commit *commit = item->commit;1706if(!res)1707warning(_("stopped at%s... %.*s"),1708short_commit_name(commit),1709 item->arg_len, item->arg);1710returnerror_with_patch(commit,1711 item->arg, item->arg_len, opts, res,1712!res);1713}1714if(res &&is_fixup(item->command)) {1715if(res ==1)1716intend_to_amend();1717returnerror_failed_squash(item->commit, opts,1718 item->arg_len, item->arg);1719}1720}else if(item->command == TODO_EXEC) {1721char*end_of_arg = (char*)(item->arg + item->arg_len);1722int saved = *end_of_arg;17231724*end_of_arg ='\0';1725 res =do_exec(item->arg);1726*end_of_arg = saved;1727}else if(!is_noop(item->command))1728returnerror(_("unknown command%d"), item->command);17291730 todo_list->current++;1731if(res)1732return res;1733}17341735if(is_rebase_i(opts)) {1736struct strbuf buf = STRBUF_INIT;17371738/* Stopped in the middle, as planned? */1739if(todo_list->current < todo_list->nr)1740return0;17411742if(opts->verbose) {1743struct rev_info log_tree_opt;1744struct object_id orig, head;17451746memset(&log_tree_opt,0,sizeof(log_tree_opt));1747init_revisions(&log_tree_opt, NULL);1748 log_tree_opt.diff =1;1749 log_tree_opt.diffopt.output_format =1750 DIFF_FORMAT_DIFFSTAT;1751 log_tree_opt.disable_stdin =1;17521753if(read_oneliner(&buf,rebase_path_orig_head(),0) &&1754!get_sha1(buf.buf, orig.hash) &&1755!get_sha1("HEAD", head.hash)) {1756diff_tree_sha1(orig.hash, head.hash,1757"", &log_tree_opt.diffopt);1758log_tree_diff_flush(&log_tree_opt);1759}1760}1761strbuf_release(&buf);1762}17631764/*1765 * Sequence of picks finished successfully; cleanup by1766 * removing the .git/sequencer directory1767 */1768returnsequencer_remove_state(opts);1769}17701771static intcontinue_single_pick(void)1772{1773const char*argv[] = {"commit", NULL };17741775if(!file_exists(git_path_cherry_pick_head()) &&1776!file_exists(git_path_revert_head()))1777returnerror(_("no cherry-pick or revert in progress"));1778returnrun_command_v_opt(argv, RUN_GIT_CMD);1779}17801781intsequencer_continue(struct replay_opts *opts)1782{1783struct todo_list todo_list = TODO_LIST_INIT;1784int res;17851786if(read_and_refresh_cache(opts))1787return-1;17881789if(!file_exists(get_todo_path(opts)))1790returncontinue_single_pick();1791if(read_populate_opts(opts))1792return-1;1793if((res =read_populate_todo(&todo_list, opts)))1794goto release_todo_list;17951796/* Verify that the conflict has been resolved */1797if(file_exists(git_path_cherry_pick_head()) ||1798file_exists(git_path_revert_head())) {1799 res =continue_single_pick();1800if(res)1801goto release_todo_list;1802}1803if(index_differs_from("HEAD",0,0)) {1804 res =error_dirty_index(opts);1805goto release_todo_list;1806}1807 todo_list.current++;1808 res =pick_commits(&todo_list, opts);1809release_todo_list:1810todo_list_release(&todo_list);1811return res;1812}18131814static intsingle_pick(struct commit *cmit,struct replay_opts *opts)1815{1816setenv(GIT_REFLOG_ACTION,action_name(opts),0);1817returndo_pick_commit(opts->action == REPLAY_PICK ?1818 TODO_PICK : TODO_REVERT, cmit, opts,0);1819}18201821intsequencer_pick_revisions(struct replay_opts *opts)1822{1823struct todo_list todo_list = TODO_LIST_INIT;1824unsigned char sha1[20];1825int i, res;18261827assert(opts->revs);1828if(read_and_refresh_cache(opts))1829return-1;18301831for(i =0; i < opts->revs->pending.nr; i++) {1832unsigned char sha1[20];1833const char*name = opts->revs->pending.objects[i].name;18341835/* This happens when using --stdin. */1836if(!strlen(name))1837continue;18381839if(!get_sha1(name, sha1)) {1840if(!lookup_commit_reference_gently(sha1,1)) {1841enum object_type type =sha1_object_info(sha1, NULL);1842returnerror(_("%s: can't cherry-pick a%s"),1843 name,typename(type));1844}1845}else1846returnerror(_("%s: bad revision"), name);1847}18481849/*1850 * If we were called as "git cherry-pick <commit>", just1851 * cherry-pick/revert it, set CHERRY_PICK_HEAD /1852 * REVERT_HEAD, and don't touch the sequencer state.1853 * This means it is possible to cherry-pick in the middle1854 * of a cherry-pick sequence.1855 */1856if(opts->revs->cmdline.nr ==1&&1857 opts->revs->cmdline.rev->whence == REV_CMD_REV &&1858 opts->revs->no_walk &&1859!opts->revs->cmdline.rev->flags) {1860struct commit *cmit;1861if(prepare_revision_walk(opts->revs))1862returnerror(_("revision walk setup failed"));1863 cmit =get_revision(opts->revs);1864if(!cmit ||get_revision(opts->revs))1865returnerror("BUG: expected exactly one commit from walk");1866returnsingle_pick(cmit, opts);1867}18681869/*1870 * Start a new cherry-pick/ revert sequence; but1871 * first, make sure that an existing one isn't in1872 * progress1873 */18741875if(walk_revs_populate_todo(&todo_list, opts) ||1876create_seq_dir() <0)1877return-1;1878if(get_sha1("HEAD", sha1) && (opts->action == REPLAY_REVERT))1879returnerror(_("can't revert as initial commit"));1880if(save_head(sha1_to_hex(sha1)))1881return-1;1882if(save_opts(opts))1883return-1;1884update_abort_safety_file();1885 res =pick_commits(&todo_list, opts);1886todo_list_release(&todo_list);1887return res;1888}18891890voidappend_signoff(struct strbuf *msgbuf,int ignore_footer,unsigned flag)1891{1892unsigned no_dup_sob = flag & APPEND_SIGNOFF_DEDUP;1893struct strbuf sob = STRBUF_INIT;1894int has_footer;18951896strbuf_addstr(&sob, sign_off_header);1897strbuf_addstr(&sob,fmt_name(getenv("GIT_COMMITTER_NAME"),1898getenv("GIT_COMMITTER_EMAIL")));1899strbuf_addch(&sob,'\n');19001901/*1902 * If the whole message buffer is equal to the sob, pretend that we1903 * found a conforming footer with a matching sob1904 */1905if(msgbuf->len - ignore_footer == sob.len &&1906!strncmp(msgbuf->buf, sob.buf, sob.len))1907 has_footer =3;1908else1909 has_footer =has_conforming_footer(msgbuf, &sob, ignore_footer);19101911if(!has_footer) {1912const char*append_newlines = NULL;1913size_t len = msgbuf->len - ignore_footer;19141915if(!len) {1916/*1917 * The buffer is completely empty. Leave foom for1918 * the title and body to be filled in by the user.1919 */1920 append_newlines ="\n\n";1921}else if(msgbuf->buf[len -1] !='\n') {1922/*1923 * Incomplete line. Complete the line and add a1924 * blank one so that there is an empty line between1925 * the message body and the sob.1926 */1927 append_newlines ="\n\n";1928}else if(len ==1) {1929/*1930 * Buffer contains a single newline. Add another1931 * so that we leave room for the title and body.1932 */1933 append_newlines ="\n";1934}else if(msgbuf->buf[len -2] !='\n') {1935/*1936 * Buffer ends with a single newline. Add another1937 * so that there is an empty line between the message1938 * body and the sob.1939 */1940 append_newlines ="\n";1941}/* else, the buffer already ends with two newlines. */19421943if(append_newlines)1944strbuf_splice(msgbuf, msgbuf->len - ignore_footer,0,1945 append_newlines,strlen(append_newlines));1946}19471948if(has_footer !=3&& (!no_dup_sob || has_footer !=2))1949strbuf_splice(msgbuf, msgbuf->len - ignore_footer,0,1950 sob.buf, sob.len);19511952strbuf_release(&sob);1953}