1/* 2 * Builtin "git am" 3 * 4 * Based on git-am.sh by Junio C Hamano. 5 */ 6#include"cache.h" 7#include"builtin.h" 8#include"exec_cmd.h" 9#include"parse-options.h" 10#include"dir.h" 11#include"run-command.h" 12#include"quote.h" 13#include"lockfile.h" 14#include"cache-tree.h" 15#include"refs.h" 16#include"commit.h" 17#include"diff.h" 18#include"diffcore.h" 19#include"unpack-trees.h" 20#include"branch.h" 21#include"sequencer.h" 22#include"revision.h" 23#include"merge-recursive.h" 24#include"revision.h" 25#include"log-tree.h" 26#include"notes-utils.h" 27#include"rerere.h" 28 29/** 30 * Returns 1 if the file is empty or does not exist, 0 otherwise. 31 */ 32static intis_empty_file(const char*filename) 33{ 34struct stat st; 35 36if(stat(filename, &st) <0) { 37if(errno == ENOENT) 38return1; 39die_errno(_("could not stat%s"), filename); 40} 41 42return!st.st_size; 43} 44 45/** 46 * Like strbuf_getline(), but treats both '\n' and "\r\n" as line terminators. 47 */ 48static intstrbuf_getline_crlf(struct strbuf *sb,FILE*fp) 49{ 50if(strbuf_getwholeline(sb, fp,'\n')) 51return EOF; 52if(sb->buf[sb->len -1] =='\n') { 53strbuf_setlen(sb, sb->len -1); 54if(sb->len >0&& sb->buf[sb->len -1] =='\r') 55strbuf_setlen(sb, sb->len -1); 56} 57return0; 58} 59 60/** 61 * Returns the length of the first line of msg. 62 */ 63static intlinelen(const char*msg) 64{ 65returnstrchrnul(msg,'\n') - msg; 66} 67 68enum patch_format { 69 PATCH_FORMAT_UNKNOWN =0, 70 PATCH_FORMAT_MBOX 71}; 72 73enum keep_type { 74 KEEP_FALSE =0, 75 KEEP_TRUE,/* pass -k flag to git-mailinfo */ 76 KEEP_NON_PATCH /* pass -b flag to git-mailinfo */ 77}; 78 79enum scissors_type { 80 SCISSORS_UNSET = -1, 81 SCISSORS_FALSE =0,/* pass --no-scissors to git-mailinfo */ 82 SCISSORS_TRUE /* pass --scissors to git-mailinfo */ 83}; 84 85struct am_state { 86/* state directory path */ 87char*dir; 88 89/* current and last patch numbers, 1-indexed */ 90int cur; 91int last; 92 93/* commit metadata and message */ 94char*author_name; 95char*author_email; 96char*author_date; 97char*msg; 98size_t msg_len; 99 100/* when --rebasing, records the original commit the patch came from */ 101unsigned char orig_commit[GIT_SHA1_RAWSZ]; 102 103/* number of digits in patch filename */ 104int prec; 105 106/* various operating modes and command line options */ 107int threeway; 108int quiet; 109int signoff; 110int utf8; 111int keep;/* enum keep_type */ 112int message_id; 113int scissors;/* enum scissors_type */ 114struct argv_array git_apply_opts; 115const char*resolvemsg; 116int committer_date_is_author_date; 117int ignore_date; 118int allow_rerere_autoupdate; 119const char*sign_commit; 120int rebasing; 121}; 122 123/** 124 * Initializes am_state with the default values. The state directory is set to 125 * dir. 126 */ 127static voidam_state_init(struct am_state *state,const char*dir) 128{ 129int gpgsign; 130 131memset(state,0,sizeof(*state)); 132 133assert(dir); 134 state->dir =xstrdup(dir); 135 136 state->prec =4; 137 138 state->utf8 =1; 139 140git_config_get_bool("am.messageid", &state->message_id); 141 142 state->scissors = SCISSORS_UNSET; 143 144argv_array_init(&state->git_apply_opts); 145 146if(!git_config_get_bool("commit.gpgsign", &gpgsign)) 147 state->sign_commit = gpgsign ?"": NULL; 148} 149 150/** 151 * Releases memory allocated by an am_state. 152 */ 153static voidam_state_release(struct am_state *state) 154{ 155free(state->dir); 156free(state->author_name); 157free(state->author_email); 158free(state->author_date); 159free(state->msg); 160argv_array_clear(&state->git_apply_opts); 161} 162 163/** 164 * Returns path relative to the am_state directory. 165 */ 166staticinlineconst char*am_path(const struct am_state *state,const char*path) 167{ 168returnmkpath("%s/%s", state->dir, path); 169} 170 171/** 172 * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline 173 * at the end. 174 */ 175static voidsay(const struct am_state *state,FILE*fp,const char*fmt, ...) 176{ 177va_list ap; 178 179va_start(ap, fmt); 180if(!state->quiet) { 181vfprintf(fp, fmt, ap); 182putc('\n', fp); 183} 184va_end(ap); 185} 186 187/** 188 * Returns 1 if there is an am session in progress, 0 otherwise. 189 */ 190static intam_in_progress(const struct am_state *state) 191{ 192struct stat st; 193 194if(lstat(state->dir, &st) <0|| !S_ISDIR(st.st_mode)) 195return0; 196if(lstat(am_path(state,"last"), &st) || !S_ISREG(st.st_mode)) 197return0; 198if(lstat(am_path(state,"next"), &st) || !S_ISREG(st.st_mode)) 199return0; 200return1; 201} 202 203/** 204 * Reads the contents of `file` in the `state` directory into `sb`. Returns the 205 * number of bytes read on success, -1 if the file does not exist. If `trim` is 206 * set, trailing whitespace will be removed. 207 */ 208static intread_state_file(struct strbuf *sb,const struct am_state *state, 209const char*file,int trim) 210{ 211strbuf_reset(sb); 212 213if(strbuf_read_file(sb,am_path(state, file),0) >=0) { 214if(trim) 215strbuf_trim(sb); 216 217return sb->len; 218} 219 220if(errno == ENOENT) 221return-1; 222 223die_errno(_("could not read '%s'"),am_path(state, file)); 224} 225 226/** 227 * Reads a KEY=VALUE shell variable assignment from `fp`, returning the VALUE 228 * as a newly-allocated string. VALUE must be a quoted string, and the KEY must 229 * match `key`. Returns NULL on failure. 230 * 231 * This is used by read_author_script() to read the GIT_AUTHOR_* variables from 232 * the author-script. 233 */ 234static char*read_shell_var(FILE*fp,const char*key) 235{ 236struct strbuf sb = STRBUF_INIT; 237const char*str; 238 239if(strbuf_getline(&sb, fp,'\n')) 240goto fail; 241 242if(!skip_prefix(sb.buf, key, &str)) 243goto fail; 244 245if(!skip_prefix(str,"=", &str)) 246goto fail; 247 248strbuf_remove(&sb,0, str - sb.buf); 249 250 str =sq_dequote(sb.buf); 251if(!str) 252goto fail; 253 254returnstrbuf_detach(&sb, NULL); 255 256fail: 257strbuf_release(&sb); 258return NULL; 259} 260 261/** 262 * Reads and parses the state directory's "author-script" file, and sets 263 * state->author_name, state->author_email and state->author_date accordingly. 264 * Returns 0 on success, -1 if the file could not be parsed. 265 * 266 * The author script is of the format: 267 * 268 * GIT_AUTHOR_NAME='$author_name' 269 * GIT_AUTHOR_EMAIL='$author_email' 270 * GIT_AUTHOR_DATE='$author_date' 271 * 272 * where $author_name, $author_email and $author_date are quoted. We are strict 273 * with our parsing, as the file was meant to be eval'd in the old git-am.sh 274 * script, and thus if the file differs from what this function expects, it is 275 * better to bail out than to do something that the user does not expect. 276 */ 277static intread_author_script(struct am_state *state) 278{ 279const char*filename =am_path(state,"author-script"); 280FILE*fp; 281 282assert(!state->author_name); 283assert(!state->author_email); 284assert(!state->author_date); 285 286 fp =fopen(filename,"r"); 287if(!fp) { 288if(errno == ENOENT) 289return0; 290die_errno(_("could not open '%s' for reading"), filename); 291} 292 293 state->author_name =read_shell_var(fp,"GIT_AUTHOR_NAME"); 294if(!state->author_name) { 295fclose(fp); 296return-1; 297} 298 299 state->author_email =read_shell_var(fp,"GIT_AUTHOR_EMAIL"); 300if(!state->author_email) { 301fclose(fp); 302return-1; 303} 304 305 state->author_date =read_shell_var(fp,"GIT_AUTHOR_DATE"); 306if(!state->author_date) { 307fclose(fp); 308return-1; 309} 310 311if(fgetc(fp) != EOF) { 312fclose(fp); 313return-1; 314} 315 316fclose(fp); 317return0; 318} 319 320/** 321 * Saves state->author_name, state->author_email and state->author_date in the 322 * state directory's "author-script" file. 323 */ 324static voidwrite_author_script(const struct am_state *state) 325{ 326struct strbuf sb = STRBUF_INIT; 327 328strbuf_addstr(&sb,"GIT_AUTHOR_NAME="); 329sq_quote_buf(&sb, state->author_name); 330strbuf_addch(&sb,'\n'); 331 332strbuf_addstr(&sb,"GIT_AUTHOR_EMAIL="); 333sq_quote_buf(&sb, state->author_email); 334strbuf_addch(&sb,'\n'); 335 336strbuf_addstr(&sb,"GIT_AUTHOR_DATE="); 337sq_quote_buf(&sb, state->author_date); 338strbuf_addch(&sb,'\n'); 339 340write_file(am_path(state,"author-script"),1,"%s", sb.buf); 341 342strbuf_release(&sb); 343} 344 345/** 346 * Reads the commit message from the state directory's "final-commit" file, 347 * setting state->msg to its contents and state->msg_len to the length of its 348 * contents in bytes. 349 * 350 * Returns 0 on success, -1 if the file does not exist. 351 */ 352static intread_commit_msg(struct am_state *state) 353{ 354struct strbuf sb = STRBUF_INIT; 355 356assert(!state->msg); 357 358if(read_state_file(&sb, state,"final-commit",0) <0) { 359strbuf_release(&sb); 360return-1; 361} 362 363 state->msg =strbuf_detach(&sb, &state->msg_len); 364return0; 365} 366 367/** 368 * Saves state->msg in the state directory's "final-commit" file. 369 */ 370static voidwrite_commit_msg(const struct am_state *state) 371{ 372int fd; 373const char*filename =am_path(state,"final-commit"); 374 375 fd =xopen(filename, O_WRONLY | O_CREAT,0666); 376if(write_in_full(fd, state->msg, state->msg_len) <0) 377die_errno(_("could not write to%s"), filename); 378close(fd); 379} 380 381/** 382 * Loads state from disk. 383 */ 384static voidam_load(struct am_state *state) 385{ 386struct strbuf sb = STRBUF_INIT; 387 388if(read_state_file(&sb, state,"next",1) <0) 389die("BUG: state file 'next' does not exist"); 390 state->cur =strtol(sb.buf, NULL,10); 391 392if(read_state_file(&sb, state,"last",1) <0) 393die("BUG: state file 'last' does not exist"); 394 state->last =strtol(sb.buf, NULL,10); 395 396if(read_author_script(state) <0) 397die(_("could not parse author script")); 398 399read_commit_msg(state); 400 401if(read_state_file(&sb, state,"original-commit",1) <0) 402hashclr(state->orig_commit); 403else if(get_sha1_hex(sb.buf, state->orig_commit) <0) 404die(_("could not parse%s"),am_path(state,"original-commit")); 405 406read_state_file(&sb, state,"threeway",1); 407 state->threeway = !strcmp(sb.buf,"t"); 408 409read_state_file(&sb, state,"quiet",1); 410 state->quiet = !strcmp(sb.buf,"t"); 411 412read_state_file(&sb, state,"sign",1); 413 state->signoff = !strcmp(sb.buf,"t"); 414 415read_state_file(&sb, state,"utf8",1); 416 state->utf8 = !strcmp(sb.buf,"t"); 417 418read_state_file(&sb, state,"keep",1); 419if(!strcmp(sb.buf,"t")) 420 state->keep = KEEP_TRUE; 421else if(!strcmp(sb.buf,"b")) 422 state->keep = KEEP_NON_PATCH; 423else 424 state->keep = KEEP_FALSE; 425 426read_state_file(&sb, state,"messageid",1); 427 state->message_id = !strcmp(sb.buf,"t"); 428 429read_state_file(&sb, state,"scissors",1); 430if(!strcmp(sb.buf,"t")) 431 state->scissors = SCISSORS_TRUE; 432else if(!strcmp(sb.buf,"f")) 433 state->scissors = SCISSORS_FALSE; 434else 435 state->scissors = SCISSORS_UNSET; 436 437read_state_file(&sb, state,"apply-opt",1); 438argv_array_clear(&state->git_apply_opts); 439if(sq_dequote_to_argv_array(sb.buf, &state->git_apply_opts) <0) 440die(_("could not parse%s"),am_path(state,"apply-opt")); 441 442 state->rebasing = !!file_exists(am_path(state,"rebasing")); 443 444strbuf_release(&sb); 445} 446 447/** 448 * Removes the am_state directory, forcefully terminating the current am 449 * session. 450 */ 451static voidam_destroy(const struct am_state *state) 452{ 453struct strbuf sb = STRBUF_INIT; 454 455strbuf_addstr(&sb, state->dir); 456remove_dir_recursively(&sb,0); 457strbuf_release(&sb); 458} 459 460/** 461 * Runs applypatch-msg hook. Returns its exit code. 462 */ 463static intrun_applypatch_msg_hook(struct am_state *state) 464{ 465int ret; 466 467assert(state->msg); 468 ret =run_hook_le(NULL,"applypatch-msg",am_path(state,"final-commit"), NULL); 469 470if(!ret) { 471free(state->msg); 472 state->msg = NULL; 473if(read_commit_msg(state) <0) 474die(_("'%s' was deleted by the applypatch-msg hook"), 475am_path(state,"final-commit")); 476} 477 478return ret; 479} 480 481/** 482 * Runs post-rewrite hook. Returns it exit code. 483 */ 484static intrun_post_rewrite_hook(const struct am_state *state) 485{ 486struct child_process cp = CHILD_PROCESS_INIT; 487const char*hook =find_hook("post-rewrite"); 488int ret; 489 490if(!hook) 491return0; 492 493argv_array_push(&cp.args, hook); 494argv_array_push(&cp.args,"rebase"); 495 496 cp.in =xopen(am_path(state,"rewritten"), O_RDONLY); 497 cp.stdout_to_stderr =1; 498 499 ret =run_command(&cp); 500 501close(cp.in); 502return ret; 503} 504 505/** 506 * Reads the state directory's "rewritten" file, and copies notes from the old 507 * commits listed in the file to their rewritten commits. 508 * 509 * Returns 0 on success, -1 on failure. 510 */ 511static intcopy_notes_for_rebase(const struct am_state *state) 512{ 513struct notes_rewrite_cfg *c; 514struct strbuf sb = STRBUF_INIT; 515const char*invalid_line =_("Malformed input line: '%s'."); 516const char*msg ="Notes added by 'git rebase'"; 517FILE*fp; 518int ret =0; 519 520assert(state->rebasing); 521 522 c =init_copy_notes_for_rewrite("rebase"); 523if(!c) 524return0; 525 526 fp =xfopen(am_path(state,"rewritten"),"r"); 527 528while(!strbuf_getline(&sb, fp,'\n')) { 529unsigned char from_obj[GIT_SHA1_RAWSZ], to_obj[GIT_SHA1_RAWSZ]; 530 531if(sb.len != GIT_SHA1_HEXSZ *2+1) { 532 ret =error(invalid_line, sb.buf); 533goto finish; 534} 535 536if(get_sha1_hex(sb.buf, from_obj)) { 537 ret =error(invalid_line, sb.buf); 538goto finish; 539} 540 541if(sb.buf[GIT_SHA1_HEXSZ] !=' ') { 542 ret =error(invalid_line, sb.buf); 543goto finish; 544} 545 546if(get_sha1_hex(sb.buf + GIT_SHA1_HEXSZ +1, to_obj)) { 547 ret =error(invalid_line, sb.buf); 548goto finish; 549} 550 551if(copy_note_for_rewrite(c, from_obj, to_obj)) 552 ret =error(_("Failed to copy notes from '%s' to '%s'"), 553sha1_to_hex(from_obj),sha1_to_hex(to_obj)); 554} 555 556finish: 557finish_copy_notes_for_rewrite(c, msg); 558fclose(fp); 559strbuf_release(&sb); 560return ret; 561} 562 563/** 564 * Determines if the file looks like a piece of RFC2822 mail by grabbing all 565 * non-indented lines and checking if they look like they begin with valid 566 * header field names. 567 * 568 * Returns 1 if the file looks like a piece of mail, 0 otherwise. 569 */ 570static intis_mail(FILE*fp) 571{ 572const char*header_regex ="^[!-9;-~]+:"; 573struct strbuf sb = STRBUF_INIT; 574 regex_t regex; 575int ret =1; 576 577if(fseek(fp,0L, SEEK_SET)) 578die_errno(_("fseek failed")); 579 580if(regcomp(®ex, header_regex, REG_NOSUB | REG_EXTENDED)) 581die("invalid pattern:%s", header_regex); 582 583while(!strbuf_getline_crlf(&sb, fp)) { 584if(!sb.len) 585break;/* End of header */ 586 587/* Ignore indented folded lines */ 588if(*sb.buf =='\t'|| *sb.buf ==' ') 589continue; 590 591/* It's a header if it matches header_regex */ 592if(regexec(®ex, sb.buf,0, NULL,0)) { 593 ret =0; 594goto done; 595} 596} 597 598done: 599regfree(®ex); 600strbuf_release(&sb); 601return ret; 602} 603 604/** 605 * Attempts to detect the patch_format of the patches contained in `paths`, 606 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if 607 * detection fails. 608 */ 609static intdetect_patch_format(const char**paths) 610{ 611enum patch_format ret = PATCH_FORMAT_UNKNOWN; 612struct strbuf l1 = STRBUF_INIT; 613FILE*fp; 614 615/* 616 * We default to mbox format if input is from stdin and for directories 617 */ 618if(!*paths || !strcmp(*paths,"-") ||is_directory(*paths)) 619return PATCH_FORMAT_MBOX; 620 621/* 622 * Otherwise, check the first few lines of the first patch, starting 623 * from the first non-blank line, to try to detect its format. 624 */ 625 626 fp =xfopen(*paths,"r"); 627 628while(!strbuf_getline_crlf(&l1, fp)) { 629if(l1.len) 630break; 631} 632 633if(starts_with(l1.buf,"From ") ||starts_with(l1.buf,"From: ")) { 634 ret = PATCH_FORMAT_MBOX; 635goto done; 636} 637 638if(l1.len &&is_mail(fp)) { 639 ret = PATCH_FORMAT_MBOX; 640goto done; 641} 642 643done: 644fclose(fp); 645strbuf_release(&l1); 646return ret; 647} 648 649/** 650 * Splits out individual email patches from `paths`, where each path is either 651 * a mbox file or a Maildir. Returns 0 on success, -1 on failure. 652 */ 653static intsplit_mail_mbox(struct am_state *state,const char**paths,int keep_cr) 654{ 655struct child_process cp = CHILD_PROCESS_INIT; 656struct strbuf last = STRBUF_INIT; 657 658 cp.git_cmd =1; 659argv_array_push(&cp.args,"mailsplit"); 660argv_array_pushf(&cp.args,"-d%d", state->prec); 661argv_array_pushf(&cp.args,"-o%s", state->dir); 662argv_array_push(&cp.args,"-b"); 663if(keep_cr) 664argv_array_push(&cp.args,"--keep-cr"); 665argv_array_push(&cp.args,"--"); 666argv_array_pushv(&cp.args, paths); 667 668if(capture_command(&cp, &last,8)) 669return-1; 670 671 state->cur =1; 672 state->last =strtol(last.buf, NULL,10); 673 674return0; 675} 676 677/** 678 * Splits a list of files/directories into individual email patches. Each path 679 * in `paths` must be a file/directory that is formatted according to 680 * `patch_format`. 681 * 682 * Once split out, the individual email patches will be stored in the state 683 * directory, with each patch's filename being its index, padded to state->prec 684 * digits. 685 * 686 * state->cur will be set to the index of the first mail, and state->last will 687 * be set to the index of the last mail. 688 * 689 * Set keep_cr to 0 to convert all lines ending with \r\n to end with \n, 1 690 * to disable this behavior, -1 to use the default configured setting. 691 * 692 * Returns 0 on success, -1 on failure. 693 */ 694static intsplit_mail(struct am_state *state,enum patch_format patch_format, 695const char**paths,int keep_cr) 696{ 697if(keep_cr <0) { 698 keep_cr =0; 699git_config_get_bool("am.keepcr", &keep_cr); 700} 701 702switch(patch_format) { 703case PATCH_FORMAT_MBOX: 704returnsplit_mail_mbox(state, paths, keep_cr); 705default: 706die("BUG: invalid patch_format"); 707} 708return-1; 709} 710 711/** 712 * Setup a new am session for applying patches 713 */ 714static voidam_setup(struct am_state *state,enum patch_format patch_format, 715const char**paths,int keep_cr) 716{ 717unsigned char curr_head[GIT_SHA1_RAWSZ]; 718const char*str; 719struct strbuf sb = STRBUF_INIT; 720 721if(!patch_format) 722 patch_format =detect_patch_format(paths); 723 724if(!patch_format) { 725fprintf_ln(stderr,_("Patch format detection failed.")); 726exit(128); 727} 728 729if(mkdir(state->dir,0777) <0&& errno != EEXIST) 730die_errno(_("failed to create directory '%s'"), state->dir); 731 732if(split_mail(state, patch_format, paths, keep_cr) <0) { 733am_destroy(state); 734die(_("Failed to split patches.")); 735} 736 737if(state->rebasing) 738 state->threeway =1; 739 740write_file(am_path(state,"threeway"),1, state->threeway ?"t":"f"); 741 742write_file(am_path(state,"quiet"),1, state->quiet ?"t":"f"); 743 744write_file(am_path(state,"sign"),1, state->signoff ?"t":"f"); 745 746write_file(am_path(state,"utf8"),1, state->utf8 ?"t":"f"); 747 748switch(state->keep) { 749case KEEP_FALSE: 750 str ="f"; 751break; 752case KEEP_TRUE: 753 str ="t"; 754break; 755case KEEP_NON_PATCH: 756 str ="b"; 757break; 758default: 759die("BUG: invalid value for state->keep"); 760} 761 762write_file(am_path(state,"keep"),1,"%s", str); 763 764write_file(am_path(state,"messageid"),1, state->message_id ?"t":"f"); 765 766switch(state->scissors) { 767case SCISSORS_UNSET: 768 str =""; 769break; 770case SCISSORS_FALSE: 771 str ="f"; 772break; 773case SCISSORS_TRUE: 774 str ="t"; 775break; 776default: 777die("BUG: invalid value for state->scissors"); 778} 779 780write_file(am_path(state,"scissors"),1,"%s", str); 781 782sq_quote_argv(&sb, state->git_apply_opts.argv,0); 783write_file(am_path(state,"apply-opt"),1,"%s", sb.buf); 784 785if(state->rebasing) 786write_file(am_path(state,"rebasing"),1,"%s",""); 787else 788write_file(am_path(state,"applying"),1,"%s",""); 789 790if(!get_sha1("HEAD", curr_head)) { 791write_file(am_path(state,"abort-safety"),1,"%s",sha1_to_hex(curr_head)); 792if(!state->rebasing) 793update_ref("am","ORIG_HEAD", curr_head, NULL,0, 794 UPDATE_REFS_DIE_ON_ERR); 795}else{ 796write_file(am_path(state,"abort-safety"),1,"%s",""); 797if(!state->rebasing) 798delete_ref("ORIG_HEAD", NULL,0); 799} 800 801/* 802 * NOTE: Since the "next" and "last" files determine if an am_state 803 * session is in progress, they should be written last. 804 */ 805 806write_file(am_path(state,"next"),1,"%d", state->cur); 807 808write_file(am_path(state,"last"),1,"%d", state->last); 809 810strbuf_release(&sb); 811} 812 813/** 814 * Increments the patch pointer, and cleans am_state for the application of the 815 * next patch. 816 */ 817static voidam_next(struct am_state *state) 818{ 819unsigned char head[GIT_SHA1_RAWSZ]; 820 821free(state->author_name); 822 state->author_name = NULL; 823 824free(state->author_email); 825 state->author_email = NULL; 826 827free(state->author_date); 828 state->author_date = NULL; 829 830free(state->msg); 831 state->msg = NULL; 832 state->msg_len =0; 833 834unlink(am_path(state,"author-script")); 835unlink(am_path(state,"final-commit")); 836 837hashclr(state->orig_commit); 838unlink(am_path(state,"original-commit")); 839 840if(!get_sha1("HEAD", head)) 841write_file(am_path(state,"abort-safety"),1,"%s",sha1_to_hex(head)); 842else 843write_file(am_path(state,"abort-safety"),1,"%s",""); 844 845 state->cur++; 846write_file(am_path(state,"next"),1,"%d", state->cur); 847} 848 849/** 850 * Returns the filename of the current patch email. 851 */ 852static const char*msgnum(const struct am_state *state) 853{ 854static struct strbuf sb = STRBUF_INIT; 855 856strbuf_reset(&sb); 857strbuf_addf(&sb,"%0*d", state->prec, state->cur); 858 859return sb.buf; 860} 861 862/** 863 * Refresh and write index. 864 */ 865static voidrefresh_and_write_cache(void) 866{ 867struct lock_file *lock_file =xcalloc(1,sizeof(struct lock_file)); 868 869hold_locked_index(lock_file,1); 870refresh_cache(REFRESH_QUIET); 871if(write_locked_index(&the_index, lock_file, COMMIT_LOCK)) 872die(_("unable to write index file")); 873} 874 875/** 876 * Returns 1 if the index differs from HEAD, 0 otherwise. When on an unborn 877 * branch, returns 1 if there are entries in the index, 0 otherwise. If an 878 * strbuf is provided, the space-separated list of files that differ will be 879 * appended to it. 880 */ 881static intindex_has_changes(struct strbuf *sb) 882{ 883unsigned char head[GIT_SHA1_RAWSZ]; 884int i; 885 886if(!get_sha1_tree("HEAD", head)) { 887struct diff_options opt; 888 889diff_setup(&opt); 890DIFF_OPT_SET(&opt, EXIT_WITH_STATUS); 891if(!sb) 892DIFF_OPT_SET(&opt, QUICK); 893do_diff_cache(head, &opt); 894diffcore_std(&opt); 895for(i =0; sb && i < diff_queued_diff.nr; i++) { 896if(i) 897strbuf_addch(sb,' '); 898strbuf_addstr(sb, diff_queued_diff.queue[i]->two->path); 899} 900diff_flush(&opt); 901returnDIFF_OPT_TST(&opt, HAS_CHANGES) !=0; 902}else{ 903for(i =0; sb && i < active_nr; i++) { 904if(i) 905strbuf_addch(sb,' '); 906strbuf_addstr(sb, active_cache[i]->name); 907} 908return!!active_nr; 909} 910} 911 912/** 913 * Dies with a user-friendly message on how to proceed after resolving the 914 * problem. This message can be overridden with state->resolvemsg. 915 */ 916static void NORETURN die_user_resolve(const struct am_state *state) 917{ 918if(state->resolvemsg) { 919printf_ln("%s", state->resolvemsg); 920}else{ 921const char*cmdline ="git am"; 922 923printf_ln(_("When you have resolved this problem, run\"%s--continue\"."), cmdline); 924printf_ln(_("If you prefer to skip this patch, run\"%s--skip\"instead."), cmdline); 925printf_ln(_("To restore the original branch and stop patching, run\"%s--abort\"."), cmdline); 926} 927 928exit(128); 929} 930 931/** 932 * Parses `mail` using git-mailinfo, extracting its patch and authorship info. 933 * state->msg will be set to the patch message. state->author_name, 934 * state->author_email and state->author_date will be set to the patch author's 935 * name, email and date respectively. The patch body will be written to the 936 * state directory's "patch" file. 937 * 938 * Returns 1 if the patch should be skipped, 0 otherwise. 939 */ 940static intparse_mail(struct am_state *state,const char*mail) 941{ 942FILE*fp; 943struct child_process cp = CHILD_PROCESS_INIT; 944struct strbuf sb = STRBUF_INIT; 945struct strbuf msg = STRBUF_INIT; 946struct strbuf author_name = STRBUF_INIT; 947struct strbuf author_date = STRBUF_INIT; 948struct strbuf author_email = STRBUF_INIT; 949int ret =0; 950 951 cp.git_cmd =1; 952 cp.in =xopen(mail, O_RDONLY,0); 953 cp.out =xopen(am_path(state,"info"), O_WRONLY | O_CREAT,0777); 954 955argv_array_push(&cp.args,"mailinfo"); 956argv_array_push(&cp.args, state->utf8 ?"-u":"-n"); 957 958switch(state->keep) { 959case KEEP_FALSE: 960break; 961case KEEP_TRUE: 962argv_array_push(&cp.args,"-k"); 963break; 964case KEEP_NON_PATCH: 965argv_array_push(&cp.args,"-b"); 966break; 967default: 968die("BUG: invalid value for state->keep"); 969} 970 971if(state->message_id) 972argv_array_push(&cp.args,"-m"); 973 974switch(state->scissors) { 975case SCISSORS_UNSET: 976break; 977case SCISSORS_FALSE: 978argv_array_push(&cp.args,"--no-scissors"); 979break; 980case SCISSORS_TRUE: 981argv_array_push(&cp.args,"--scissors"); 982break; 983default: 984die("BUG: invalid value for state->scissors"); 985} 986 987argv_array_push(&cp.args,am_path(state,"msg")); 988argv_array_push(&cp.args,am_path(state,"patch")); 989 990if(run_command(&cp) <0) 991die("could not parse patch"); 992 993close(cp.in); 994close(cp.out); 995 996/* Extract message and author information */ 997 fp =xfopen(am_path(state,"info"),"r"); 998while(!strbuf_getline(&sb, fp,'\n')) { 999const char*x;10001001if(skip_prefix(sb.buf,"Subject: ", &x)) {1002if(msg.len)1003strbuf_addch(&msg,'\n');1004strbuf_addstr(&msg, x);1005}else if(skip_prefix(sb.buf,"Author: ", &x))1006strbuf_addstr(&author_name, x);1007else if(skip_prefix(sb.buf,"Email: ", &x))1008strbuf_addstr(&author_email, x);1009else if(skip_prefix(sb.buf,"Date: ", &x))1010strbuf_addstr(&author_date, x);1011}1012fclose(fp);10131014/* Skip pine's internal folder data */1015if(!strcmp(author_name.buf,"Mail System Internal Data")) {1016 ret =1;1017goto finish;1018}10191020if(is_empty_file(am_path(state,"patch"))) {1021printf_ln(_("Patch is empty. Was it split wrong?"));1022die_user_resolve(state);1023}10241025strbuf_addstr(&msg,"\n\n");1026if(strbuf_read_file(&msg,am_path(state,"msg"),0) <0)1027die_errno(_("could not read '%s'"),am_path(state,"msg"));1028stripspace(&msg,0);10291030if(state->signoff)1031append_signoff(&msg,0,0);10321033assert(!state->author_name);1034 state->author_name =strbuf_detach(&author_name, NULL);10351036assert(!state->author_email);1037 state->author_email =strbuf_detach(&author_email, NULL);10381039assert(!state->author_date);1040 state->author_date =strbuf_detach(&author_date, NULL);10411042assert(!state->msg);1043 state->msg =strbuf_detach(&msg, &state->msg_len);10441045finish:1046strbuf_release(&msg);1047strbuf_release(&author_date);1048strbuf_release(&author_email);1049strbuf_release(&author_name);1050strbuf_release(&sb);1051return ret;1052}10531054/**1055 * Sets commit_id to the commit hash where the mail was generated from.1056 * Returns 0 on success, -1 on failure.1057 */1058static intget_mail_commit_sha1(unsigned char*commit_id,const char*mail)1059{1060struct strbuf sb = STRBUF_INIT;1061FILE*fp =xfopen(mail,"r");1062const char*x;10631064if(strbuf_getline(&sb, fp,'\n'))1065return-1;10661067if(!skip_prefix(sb.buf,"From ", &x))1068return-1;10691070if(get_sha1_hex(x, commit_id) <0)1071return-1;10721073strbuf_release(&sb);1074fclose(fp);1075return0;1076}10771078/**1079 * Sets state->msg, state->author_name, state->author_email, state->author_date1080 * to the commit's respective info.1081 */1082static voidget_commit_info(struct am_state *state,struct commit *commit)1083{1084const char*buffer, *ident_line, *author_date, *msg;1085size_t ident_len;1086struct ident_split ident_split;1087struct strbuf sb = STRBUF_INIT;10881089 buffer =logmsg_reencode(commit, NULL,get_commit_output_encoding());10901091 ident_line =find_commit_header(buffer,"author", &ident_len);10921093if(split_ident_line(&ident_split, ident_line, ident_len) <0) {1094strbuf_add(&sb, ident_line, ident_len);1095die(_("invalid ident line:%s"), sb.buf);1096}10971098assert(!state->author_name);1099if(ident_split.name_begin) {1100strbuf_add(&sb, ident_split.name_begin,1101 ident_split.name_end - ident_split.name_begin);1102 state->author_name =strbuf_detach(&sb, NULL);1103}else1104 state->author_name =xstrdup("");11051106assert(!state->author_email);1107if(ident_split.mail_begin) {1108strbuf_add(&sb, ident_split.mail_begin,1109 ident_split.mail_end - ident_split.mail_begin);1110 state->author_email =strbuf_detach(&sb, NULL);1111}else1112 state->author_email =xstrdup("");11131114 author_date =show_ident_date(&ident_split,DATE_MODE(NORMAL));1115strbuf_addstr(&sb, author_date);1116assert(!state->author_date);1117 state->author_date =strbuf_detach(&sb, NULL);11181119assert(!state->msg);1120 msg =strstr(buffer,"\n\n");1121if(!msg)1122die(_("unable to parse commit%s"),sha1_to_hex(commit->object.sha1));1123 state->msg =xstrdup(msg +2);1124 state->msg_len =strlen(state->msg);1125}11261127/**1128 * Writes `commit` as a patch to the state directory's "patch" file.1129 */1130static voidwrite_commit_patch(const struct am_state *state,struct commit *commit)1131{1132struct rev_info rev_info;1133FILE*fp;11341135 fp =xfopen(am_path(state,"patch"),"w");1136init_revisions(&rev_info, NULL);1137 rev_info.diff =1;1138 rev_info.abbrev =0;1139 rev_info.disable_stdin =1;1140 rev_info.show_root_diff =1;1141 rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;1142 rev_info.no_commit_id =1;1143DIFF_OPT_SET(&rev_info.diffopt, BINARY);1144DIFF_OPT_SET(&rev_info.diffopt, FULL_INDEX);1145 rev_info.diffopt.use_color =0;1146 rev_info.diffopt.file = fp;1147 rev_info.diffopt.close_file =1;1148add_pending_object(&rev_info, &commit->object,"");1149diff_setup_done(&rev_info.diffopt);1150log_tree_commit(&rev_info, commit);1151}11521153/**1154 * Like parse_mail(), but parses the mail by looking up its commit ID1155 * directly. This is used in --rebasing mode to bypass git-mailinfo's munging1156 * of patches.1157 *1158 * state->orig_commit will be set to the original commit ID.1159 *1160 * Will always return 0 as the patch should never be skipped.1161 */1162static intparse_mail_rebase(struct am_state *state,const char*mail)1163{1164struct commit *commit;1165unsigned char commit_sha1[GIT_SHA1_RAWSZ];11661167if(get_mail_commit_sha1(commit_sha1, mail) <0)1168die(_("could not parse%s"), mail);11691170 commit =lookup_commit_or_die(commit_sha1, mail);11711172get_commit_info(state, commit);11731174write_commit_patch(state, commit);11751176hashcpy(state->orig_commit, commit_sha1);1177write_file(am_path(state,"original-commit"),1,"%s",1178sha1_to_hex(commit_sha1));11791180return0;1181}11821183/**1184 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If1185 * `index_file` is not NULL, the patch will be applied to that index.1186 */1187static intrun_apply(const struct am_state *state,const char*index_file)1188{1189struct child_process cp = CHILD_PROCESS_INIT;11901191 cp.git_cmd =1;11921193if(index_file)1194argv_array_pushf(&cp.env_array,"GIT_INDEX_FILE=%s", index_file);11951196/*1197 * If we are allowed to fall back on 3-way merge, don't give false1198 * errors during the initial attempt.1199 */1200if(state->threeway && !index_file) {1201 cp.no_stdout =1;1202 cp.no_stderr =1;1203}12041205argv_array_push(&cp.args,"apply");12061207argv_array_pushv(&cp.args, state->git_apply_opts.argv);12081209if(index_file)1210argv_array_push(&cp.args,"--cached");1211else1212argv_array_push(&cp.args,"--index");12131214argv_array_push(&cp.args,am_path(state,"patch"));12151216if(run_command(&cp))1217return-1;12181219/* Reload index as git-apply will have modified it. */1220discard_cache();1221read_cache_from(index_file ? index_file :get_index_file());12221223return0;1224}12251226/**1227 * Builds an index that contains just the blobs needed for a 3way merge.1228 */1229static intbuild_fake_ancestor(const struct am_state *state,const char*index_file)1230{1231struct child_process cp = CHILD_PROCESS_INIT;12321233 cp.git_cmd =1;1234argv_array_push(&cp.args,"apply");1235argv_array_pushv(&cp.args, state->git_apply_opts.argv);1236argv_array_pushf(&cp.args,"--build-fake-ancestor=%s", index_file);1237argv_array_push(&cp.args,am_path(state,"patch"));12381239if(run_command(&cp))1240return-1;12411242return0;1243}12441245/**1246 * Attempt a threeway merge, using index_path as the temporary index.1247 */1248static intfall_back_threeway(const struct am_state *state,const char*index_path)1249{1250unsigned char orig_tree[GIT_SHA1_RAWSZ], his_tree[GIT_SHA1_RAWSZ],1251 our_tree[GIT_SHA1_RAWSZ];1252const unsigned char*bases[1] = {orig_tree};1253struct merge_options o;1254struct commit *result;1255char*his_tree_name;12561257if(get_sha1("HEAD", our_tree) <0)1258hashcpy(our_tree, EMPTY_TREE_SHA1_BIN);12591260if(build_fake_ancestor(state, index_path))1261returnerror("could not build fake ancestor");12621263discard_cache();1264read_cache_from(index_path);12651266if(write_index_as_tree(orig_tree, &the_index, index_path,0, NULL))1267returnerror(_("Repository lacks necessary blobs to fall back on 3-way merge."));12681269say(state, stdout,_("Using index info to reconstruct a base tree..."));12701271if(!state->quiet) {1272/*1273 * List paths that needed 3-way fallback, so that the user can1274 * review them with extra care to spot mismerges.1275 */1276struct rev_info rev_info;1277const char*diff_filter_str ="--diff-filter=AM";12781279init_revisions(&rev_info, NULL);1280 rev_info.diffopt.output_format = DIFF_FORMAT_NAME_STATUS;1281diff_opt_parse(&rev_info.diffopt, &diff_filter_str,1);1282add_pending_sha1(&rev_info,"HEAD", our_tree,0);1283diff_setup_done(&rev_info.diffopt);1284run_diff_index(&rev_info,1);1285}12861287if(run_apply(state, index_path))1288returnerror(_("Did you hand edit your patch?\n"1289"It does not apply to blobs recorded in its index."));12901291if(write_index_as_tree(his_tree, &the_index, index_path,0, NULL))1292returnerror("could not write tree");12931294say(state, stdout,_("Falling back to patching base and 3-way merge..."));12951296discard_cache();1297read_cache();12981299/*1300 * This is not so wrong. Depending on which base we picked, orig_tree1301 * may be wildly different from ours, but his_tree has the same set of1302 * wildly different changes in parts the patch did not touch, so1303 * recursive ends up canceling them, saying that we reverted all those1304 * changes.1305 */13061307init_merge_options(&o);13081309 o.branch1 ="HEAD";1310 his_tree_name =xstrfmt("%.*s",linelen(state->msg), state->msg);1311 o.branch2 = his_tree_name;13121313if(state->quiet)1314 o.verbosity =0;13151316if(merge_recursive_generic(&o, our_tree, his_tree,1, bases, &result)) {1317rerere(state->allow_rerere_autoupdate);1318free(his_tree_name);1319returnerror(_("Failed to merge in the changes."));1320}13211322free(his_tree_name);1323return0;1324}13251326/**1327 * Commits the current index with state->msg as the commit message and1328 * state->author_name, state->author_email and state->author_date as the author1329 * information.1330 */1331static voiddo_commit(const struct am_state *state)1332{1333unsigned char tree[GIT_SHA1_RAWSZ], parent[GIT_SHA1_RAWSZ],1334 commit[GIT_SHA1_RAWSZ];1335unsigned char*ptr;1336struct commit_list *parents = NULL;1337const char*reflog_msg, *author;1338struct strbuf sb = STRBUF_INIT;13391340if(run_hook_le(NULL,"pre-applypatch", NULL))1341exit(1);13421343if(write_cache_as_tree(tree,0, NULL))1344die(_("git write-tree failed to write a tree"));13451346if(!get_sha1_commit("HEAD", parent)) {1347 ptr = parent;1348commit_list_insert(lookup_commit(parent), &parents);1349}else{1350 ptr = NULL;1351say(state, stderr,_("applying to an empty history"));1352}13531354 author =fmt_ident(state->author_name, state->author_email,1355 state->ignore_date ? NULL : state->author_date,1356 IDENT_STRICT);13571358if(state->committer_date_is_author_date)1359setenv("GIT_COMMITTER_DATE",1360 state->ignore_date ?"": state->author_date,1);13611362if(commit_tree(state->msg, state->msg_len, tree, parents, commit,1363 author, state->sign_commit))1364die(_("failed to write commit object"));13651366 reflog_msg =getenv("GIT_REFLOG_ACTION");1367if(!reflog_msg)1368 reflog_msg ="am";13691370strbuf_addf(&sb,"%s: %.*s", reflog_msg,linelen(state->msg),1371 state->msg);13721373update_ref(sb.buf,"HEAD", commit, ptr,0, UPDATE_REFS_DIE_ON_ERR);13741375if(state->rebasing) {1376FILE*fp =xfopen(am_path(state,"rewritten"),"a");13771378assert(!is_null_sha1(state->orig_commit));1379fprintf(fp,"%s",sha1_to_hex(state->orig_commit));1380fprintf(fp,"%s\n",sha1_to_hex(commit));1381fclose(fp);1382}13831384run_hook_le(NULL,"post-applypatch", NULL);13851386strbuf_release(&sb);1387}13881389/**1390 * Validates the am_state for resuming -- the "msg" and authorship fields must1391 * be filled up.1392 */1393static voidvalidate_resume_state(const struct am_state *state)1394{1395if(!state->msg)1396die(_("cannot resume:%sdoes not exist."),1397am_path(state,"final-commit"));13981399if(!state->author_name || !state->author_email || !state->author_date)1400die(_("cannot resume:%sdoes not exist."),1401am_path(state,"author-script"));1402}14031404/**1405 * Applies all queued mail.1406 *1407 * If `resume` is true, we are "resuming". The "msg" and authorship fields, as1408 * well as the state directory's "patch" file is used as-is for applying the1409 * patch and committing it.1410 */1411static voidam_run(struct am_state *state,int resume)1412{1413const char*argv_gc_auto[] = {"gc","--auto", NULL};1414struct strbuf sb = STRBUF_INIT;14151416unlink(am_path(state,"dirtyindex"));14171418refresh_and_write_cache();14191420if(index_has_changes(&sb)) {1421write_file(am_path(state,"dirtyindex"),1,"t");1422die(_("Dirty index: cannot apply patches (dirty:%s)"), sb.buf);1423}14241425strbuf_release(&sb);14261427while(state->cur <= state->last) {1428const char*mail =am_path(state,msgnum(state));1429int apply_status;14301431if(!file_exists(mail))1432goto next;14331434if(resume) {1435validate_resume_state(state);1436 resume =0;1437}else{1438int skip;14391440if(state->rebasing)1441 skip =parse_mail_rebase(state, mail);1442else1443 skip =parse_mail(state, mail);14441445if(skip)1446goto next;/* mail should be skipped */14471448write_author_script(state);1449write_commit_msg(state);1450}14511452if(run_applypatch_msg_hook(state))1453exit(1);14541455say(state, stdout,_("Applying: %.*s"),linelen(state->msg), state->msg);14561457 apply_status =run_apply(state, NULL);14581459if(apply_status && state->threeway) {1460struct strbuf sb = STRBUF_INIT;14611462strbuf_addstr(&sb,am_path(state,"patch-merge-index"));1463 apply_status =fall_back_threeway(state, sb.buf);1464strbuf_release(&sb);14651466/*1467 * Applying the patch to an earlier tree and merging1468 * the result may have produced the same tree as ours.1469 */1470if(!apply_status && !index_has_changes(NULL)) {1471say(state, stdout,_("No changes -- Patch already applied."));1472goto next;1473}1474}14751476if(apply_status) {1477int advice_amworkdir =1;14781479printf_ln(_("Patch failed at%s%.*s"),msgnum(state),1480linelen(state->msg), state->msg);14811482git_config_get_bool("advice.amworkdir", &advice_amworkdir);14831484if(advice_amworkdir)1485printf_ln(_("The copy of the patch that failed is found in:%s"),1486am_path(state,"patch"));14871488die_user_resolve(state);1489}14901491do_commit(state);14921493next:1494am_next(state);1495}14961497if(!is_empty_file(am_path(state,"rewritten"))) {1498assert(state->rebasing);1499copy_notes_for_rebase(state);1500run_post_rewrite_hook(state);1501}15021503/*1504 * In rebasing mode, it's up to the caller to take care of1505 * housekeeping.1506 */1507if(!state->rebasing) {1508am_destroy(state);1509run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);1510}1511}15121513/**1514 * Resume the current am session after patch application failure. The user did1515 * all the hard work, and we do not have to do any patch application. Just1516 * trust and commit what the user has in the index and working tree.1517 */1518static voidam_resolve(struct am_state *state)1519{1520validate_resume_state(state);15211522say(state, stdout,_("Applying: %.*s"),linelen(state->msg), state->msg);15231524if(!index_has_changes(NULL)) {1525printf_ln(_("No changes - did you forget to use 'git add'?\n"1526"If there is nothing left to stage, chances are that something else\n"1527"already introduced the same changes; you might want to skip this patch."));1528die_user_resolve(state);1529}15301531if(unmerged_cache()) {1532printf_ln(_("You still have unmerged paths in your index.\n"1533"Did you forget to use 'git add'?"));1534die_user_resolve(state);1535}15361537rerere(0);15381539do_commit(state);15401541am_next(state);1542am_run(state,0);1543}15441545/**1546 * Performs a checkout fast-forward from `head` to `remote`. If `reset` is1547 * true, any unmerged entries will be discarded. Returns 0 on success, -1 on1548 * failure.1549 */1550static intfast_forward_to(struct tree *head,struct tree *remote,int reset)1551{1552struct lock_file *lock_file;1553struct unpack_trees_options opts;1554struct tree_desc t[2];15551556if(parse_tree(head) ||parse_tree(remote))1557return-1;15581559 lock_file =xcalloc(1,sizeof(struct lock_file));1560hold_locked_index(lock_file,1);15611562refresh_cache(REFRESH_QUIET);15631564memset(&opts,0,sizeof(opts));1565 opts.head_idx =1;1566 opts.src_index = &the_index;1567 opts.dst_index = &the_index;1568 opts.update =1;1569 opts.merge =1;1570 opts.reset = reset;1571 opts.fn = twoway_merge;1572init_tree_desc(&t[0], head->buffer, head->size);1573init_tree_desc(&t[1], remote->buffer, remote->size);15741575if(unpack_trees(2, t, &opts)) {1576rollback_lock_file(lock_file);1577return-1;1578}15791580if(write_locked_index(&the_index, lock_file, COMMIT_LOCK))1581die(_("unable to write new index file"));15821583return0;1584}15851586/**1587 * Clean the index without touching entries that are not modified between1588 * `head` and `remote`.1589 */1590static intclean_index(const unsigned char*head,const unsigned char*remote)1591{1592struct lock_file *lock_file;1593struct tree *head_tree, *remote_tree, *index_tree;1594unsigned char index[GIT_SHA1_RAWSZ];1595struct pathspec pathspec;15961597 head_tree =parse_tree_indirect(head);1598if(!head_tree)1599returnerror(_("Could not parse object '%s'."),sha1_to_hex(head));16001601 remote_tree =parse_tree_indirect(remote);1602if(!remote_tree)1603returnerror(_("Could not parse object '%s'."),sha1_to_hex(remote));16041605read_cache_unmerged();16061607if(fast_forward_to(head_tree, head_tree,1))1608return-1;16091610if(write_cache_as_tree(index,0, NULL))1611return-1;16121613 index_tree =parse_tree_indirect(index);1614if(!index_tree)1615returnerror(_("Could not parse object '%s'."),sha1_to_hex(index));16161617if(fast_forward_to(index_tree, remote_tree,0))1618return-1;16191620memset(&pathspec,0,sizeof(pathspec));16211622 lock_file =xcalloc(1,sizeof(struct lock_file));1623hold_locked_index(lock_file,1);16241625if(read_tree(remote_tree,0, &pathspec)) {1626rollback_lock_file(lock_file);1627return-1;1628}16291630if(write_locked_index(&the_index, lock_file, COMMIT_LOCK))1631die(_("unable to write new index file"));16321633remove_branch_state();16341635return0;1636}16371638/**1639 * Resets rerere's merge resolution metadata.1640 */1641static voidam_rerere_clear(void)1642{1643struct string_list merge_rr = STRING_LIST_INIT_DUP;1644int fd =setup_rerere(&merge_rr,0);16451646if(fd <0)1647return;16481649rerere_clear(&merge_rr);1650string_list_clear(&merge_rr,1);1651}16521653/**1654 * Resume the current am session by skipping the current patch.1655 */1656static voidam_skip(struct am_state *state)1657{1658unsigned char head[GIT_SHA1_RAWSZ];16591660am_rerere_clear();16611662if(get_sha1("HEAD", head))1663hashcpy(head, EMPTY_TREE_SHA1_BIN);16641665if(clean_index(head, head))1666die(_("failed to clean index"));16671668am_next(state);1669am_run(state,0);1670}16711672/**1673 * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.1674 *1675 * It is not safe to reset HEAD when:1676 * 1. git-am previously failed because the index was dirty.1677 * 2. HEAD has moved since git-am previously failed.1678 */1679static intsafe_to_abort(const struct am_state *state)1680{1681struct strbuf sb = STRBUF_INIT;1682unsigned char abort_safety[GIT_SHA1_RAWSZ], head[GIT_SHA1_RAWSZ];16831684if(file_exists(am_path(state,"dirtyindex")))1685return0;16861687if(read_state_file(&sb, state,"abort-safety",1) >0) {1688if(get_sha1_hex(sb.buf, abort_safety))1689die(_("could not parse%s"),am_path(state,"abort_safety"));1690}else1691hashclr(abort_safety);16921693if(get_sha1("HEAD", head))1694hashclr(head);16951696if(!hashcmp(head, abort_safety))1697return1;16981699error(_("You seem to have moved HEAD since the last 'am' failure.\n"1700"Not rewinding to ORIG_HEAD"));17011702return0;1703}17041705/**1706 * Aborts the current am session if it is safe to do so.1707 */1708static voidam_abort(struct am_state *state)1709{1710unsigned char curr_head[GIT_SHA1_RAWSZ], orig_head[GIT_SHA1_RAWSZ];1711int has_curr_head, has_orig_head;1712char*curr_branch;17131714if(!safe_to_abort(state)) {1715am_destroy(state);1716return;1717}17181719am_rerere_clear();17201721 curr_branch =resolve_refdup("HEAD",0, curr_head, NULL);1722 has_curr_head = !is_null_sha1(curr_head);1723if(!has_curr_head)1724hashcpy(curr_head, EMPTY_TREE_SHA1_BIN);17251726 has_orig_head = !get_sha1("ORIG_HEAD", orig_head);1727if(!has_orig_head)1728hashcpy(orig_head, EMPTY_TREE_SHA1_BIN);17291730clean_index(curr_head, orig_head);17311732if(has_orig_head)1733update_ref("am --abort","HEAD", orig_head,1734 has_curr_head ? curr_head : NULL,0,1735 UPDATE_REFS_DIE_ON_ERR);1736else if(curr_branch)1737delete_ref(curr_branch, NULL, REF_NODEREF);17381739free(curr_branch);1740am_destroy(state);1741}17421743/**1744 * parse_options() callback that validates and sets opt->value to the1745 * PATCH_FORMAT_* enum value corresponding to `arg`.1746 */1747static intparse_opt_patchformat(const struct option *opt,const char*arg,int unset)1748{1749int*opt_value = opt->value;17501751if(!strcmp(arg,"mbox"))1752*opt_value = PATCH_FORMAT_MBOX;1753else1754returnerror(_("Invalid value for --patch-format:%s"), arg);1755return0;1756}17571758enum resume_mode {1759 RESUME_FALSE =0,1760 RESUME_APPLY,1761 RESUME_RESOLVED,1762 RESUME_SKIP,1763 RESUME_ABORT1764};17651766intcmd_am(int argc,const char**argv,const char*prefix)1767{1768struct am_state state;1769int keep_cr = -1;1770int patch_format = PATCH_FORMAT_UNKNOWN;1771enum resume_mode resume = RESUME_FALSE;17721773const char*const usage[] = {1774N_("git am [options] [(<mbox>|<Maildir>)...]"),1775N_("git am [options] (--continue | --skip | --abort)"),1776 NULL1777};17781779struct option options[] = {1780OPT_BOOL('3',"3way", &state.threeway,1781N_("allow fall back on 3way merging if needed")),1782OPT__QUIET(&state.quiet,N_("be quiet")),1783OPT_BOOL('s',"signoff", &state.signoff,1784N_("add a Signed-off-by line to the commit message")),1785OPT_BOOL('u',"utf8", &state.utf8,1786N_("recode into utf8 (default)")),1787OPT_SET_INT('k',"keep", &state.keep,1788N_("pass -k flag to git-mailinfo"), KEEP_TRUE),1789OPT_SET_INT(0,"keep-non-patch", &state.keep,1790N_("pass -b flag to git-mailinfo"), KEEP_NON_PATCH),1791OPT_BOOL('m',"message-id", &state.message_id,1792N_("pass -m flag to git-mailinfo")),1793{ OPTION_SET_INT,0,"keep-cr", &keep_cr, NULL,1794N_("pass --keep-cr flag to git-mailsplit for mbox format"),1795 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL,1},1796{ OPTION_SET_INT,0,"no-keep-cr", &keep_cr, NULL,1797N_("do not pass --keep-cr flag to git-mailsplit independent of am.keepcr"),1798 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL,0},1799OPT_BOOL('c',"scissors", &state.scissors,1800N_("strip everything before a scissors line")),1801OPT_PASSTHRU_ARGV(0,"whitespace", &state.git_apply_opts,N_("action"),1802N_("pass it through git-apply"),18030),1804OPT_PASSTHRU_ARGV(0,"ignore-space-change", &state.git_apply_opts, NULL,1805N_("pass it through git-apply"),1806 PARSE_OPT_NOARG),1807OPT_PASSTHRU_ARGV(0,"ignore-whitespace", &state.git_apply_opts, NULL,1808N_("pass it through git-apply"),1809 PARSE_OPT_NOARG),1810OPT_PASSTHRU_ARGV(0,"directory", &state.git_apply_opts,N_("root"),1811N_("pass it through git-apply"),18120),1813OPT_PASSTHRU_ARGV(0,"exclude", &state.git_apply_opts,N_("path"),1814N_("pass it through git-apply"),18150),1816OPT_PASSTHRU_ARGV(0,"include", &state.git_apply_opts,N_("path"),1817N_("pass it through git-apply"),18180),1819OPT_PASSTHRU_ARGV('C', NULL, &state.git_apply_opts,N_("n"),1820N_("pass it through git-apply"),18210),1822OPT_PASSTHRU_ARGV('p', NULL, &state.git_apply_opts,N_("num"),1823N_("pass it through git-apply"),18240),1825OPT_CALLBACK(0,"patch-format", &patch_format,N_("format"),1826N_("format the patch(es) are in"),1827 parse_opt_patchformat),1828OPT_PASSTHRU_ARGV(0,"reject", &state.git_apply_opts, NULL,1829N_("pass it through git-apply"),1830 PARSE_OPT_NOARG),1831OPT_STRING(0,"resolvemsg", &state.resolvemsg, NULL,1832N_("override error message when patch failure occurs")),1833OPT_CMDMODE(0,"continue", &resume,1834N_("continue applying patches after resolving a conflict"),1835 RESUME_RESOLVED),1836OPT_CMDMODE('r',"resolved", &resume,1837N_("synonyms for --continue"),1838 RESUME_RESOLVED),1839OPT_CMDMODE(0,"skip", &resume,1840N_("skip the current patch"),1841 RESUME_SKIP),1842OPT_CMDMODE(0,"abort", &resume,1843N_("restore the original branch and abort the patching operation."),1844 RESUME_ABORT),1845OPT_BOOL(0,"committer-date-is-author-date",1846&state.committer_date_is_author_date,1847N_("lie about committer date")),1848OPT_BOOL(0,"ignore-date", &state.ignore_date,1849N_("use current timestamp for author date")),1850OPT_RERERE_AUTOUPDATE(&state.allow_rerere_autoupdate),1851{ OPTION_STRING,'S',"gpg-sign", &state.sign_commit,N_("key-id"),1852N_("GPG-sign commits"),1853 PARSE_OPT_OPTARG, NULL, (intptr_t)""},1854OPT_HIDDEN_BOOL(0,"rebasing", &state.rebasing,1855N_("(internal use for git-rebase)")),1856OPT_END()1857};18581859/*1860 * NEEDSWORK: Once all the features of git-am.sh have been1861 * re-implemented in builtin/am.c, this preamble can be removed.1862 */1863if(!getenv("_GIT_USE_BUILTIN_AM")) {1864const char*path =mkpath("%s/git-am",git_exec_path());18651866if(sane_execvp(path, (char**)argv) <0)1867die_errno("could not exec%s", path);1868}else{1869 prefix =setup_git_directory();1870trace_repo_setup(prefix);1871setup_work_tree();1872}18731874git_config(git_default_config, NULL);18751876am_state_init(&state,git_path("rebase-apply"));18771878 argc =parse_options(argc, argv, prefix, options, usage,0);18791880if(read_index_preload(&the_index, NULL) <0)1881die(_("failed to read the index"));18821883if(am_in_progress(&state)) {1884/*1885 * Catch user error to feed us patches when there is a session1886 * in progress:1887 *1888 * 1. mbox path(s) are provided on the command-line.1889 * 2. stdin is not a tty: the user is trying to feed us a patch1890 * from standard input. This is somewhat unreliable -- stdin1891 * could be /dev/null for example and the caller did not1892 * intend to feed us a patch but wanted to continue1893 * unattended.1894 */1895if(argc || (resume == RESUME_FALSE && !isatty(0)))1896die(_("previous rebase directory%sstill exists but mbox given."),1897 state.dir);18981899if(resume == RESUME_FALSE)1900 resume = RESUME_APPLY;19011902am_load(&state);1903}else{1904struct argv_array paths = ARGV_ARRAY_INIT;1905int i;19061907/*1908 * Handle stray state directory in the independent-run case. In1909 * the --rebasing case, it is up to the caller to take care of1910 * stray directories.1911 */1912if(file_exists(state.dir) && !state.rebasing) {1913if(resume == RESUME_ABORT) {1914am_destroy(&state);1915am_state_release(&state);1916return0;1917}19181919die(_("Stray%sdirectory found.\n"1920"Use\"git am --abort\"to remove it."),1921 state.dir);1922}19231924if(resume)1925die(_("Resolve operation not in progress, we are not resuming."));19261927for(i =0; i < argc; i++) {1928if(is_absolute_path(argv[i]) || !prefix)1929argv_array_push(&paths, argv[i]);1930else1931argv_array_push(&paths,mkpath("%s/%s", prefix, argv[i]));1932}19331934am_setup(&state, patch_format, paths.argv, keep_cr);19351936argv_array_clear(&paths);1937}19381939switch(resume) {1940case RESUME_FALSE:1941am_run(&state,0);1942break;1943case RESUME_APPLY:1944am_run(&state,1);1945break;1946case RESUME_RESOLVED:1947am_resolve(&state);1948break;1949case RESUME_SKIP:1950am_skip(&state);1951break;1952case RESUME_ABORT:1953am_abort(&state);1954break;1955default:1956die("BUG: invalid resume value");1957}19581959am_state_release(&state);19601961return0;1962}