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 68/** 69 * Returns true if `str` consists of only whitespace, false otherwise. 70 */ 71static intstr_isspace(const char*str) 72{ 73for(; *str; str++) 74if(!isspace(*str)) 75return0; 76 77return1; 78} 79 80enum patch_format { 81 PATCH_FORMAT_UNKNOWN =0, 82 PATCH_FORMAT_MBOX, 83 PATCH_FORMAT_STGIT 84}; 85 86enum keep_type { 87 KEEP_FALSE =0, 88 KEEP_TRUE,/* pass -k flag to git-mailinfo */ 89 KEEP_NON_PATCH /* pass -b flag to git-mailinfo */ 90}; 91 92enum scissors_type { 93 SCISSORS_UNSET = -1, 94 SCISSORS_FALSE =0,/* pass --no-scissors to git-mailinfo */ 95 SCISSORS_TRUE /* pass --scissors to git-mailinfo */ 96}; 97 98struct am_state { 99/* state directory path */ 100char*dir; 101 102/* current and last patch numbers, 1-indexed */ 103int cur; 104int last; 105 106/* commit metadata and message */ 107char*author_name; 108char*author_email; 109char*author_date; 110char*msg; 111size_t msg_len; 112 113/* when --rebasing, records the original commit the patch came from */ 114unsigned char orig_commit[GIT_SHA1_RAWSZ]; 115 116/* number of digits in patch filename */ 117int prec; 118 119/* various operating modes and command line options */ 120int threeway; 121int quiet; 122int signoff; 123int utf8; 124int keep;/* enum keep_type */ 125int message_id; 126int scissors;/* enum scissors_type */ 127struct argv_array git_apply_opts; 128const char*resolvemsg; 129int committer_date_is_author_date; 130int ignore_date; 131int allow_rerere_autoupdate; 132const char*sign_commit; 133int rebasing; 134}; 135 136/** 137 * Initializes am_state with the default values. The state directory is set to 138 * dir. 139 */ 140static voidam_state_init(struct am_state *state,const char*dir) 141{ 142int gpgsign; 143 144memset(state,0,sizeof(*state)); 145 146assert(dir); 147 state->dir =xstrdup(dir); 148 149 state->prec =4; 150 151 state->utf8 =1; 152 153git_config_get_bool("am.messageid", &state->message_id); 154 155 state->scissors = SCISSORS_UNSET; 156 157argv_array_init(&state->git_apply_opts); 158 159if(!git_config_get_bool("commit.gpgsign", &gpgsign)) 160 state->sign_commit = gpgsign ?"": NULL; 161} 162 163/** 164 * Releases memory allocated by an am_state. 165 */ 166static voidam_state_release(struct am_state *state) 167{ 168free(state->dir); 169free(state->author_name); 170free(state->author_email); 171free(state->author_date); 172free(state->msg); 173argv_array_clear(&state->git_apply_opts); 174} 175 176/** 177 * Returns path relative to the am_state directory. 178 */ 179staticinlineconst char*am_path(const struct am_state *state,const char*path) 180{ 181returnmkpath("%s/%s", state->dir, path); 182} 183 184/** 185 * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline 186 * at the end. 187 */ 188static voidsay(const struct am_state *state,FILE*fp,const char*fmt, ...) 189{ 190va_list ap; 191 192va_start(ap, fmt); 193if(!state->quiet) { 194vfprintf(fp, fmt, ap); 195putc('\n', fp); 196} 197va_end(ap); 198} 199 200/** 201 * Returns 1 if there is an am session in progress, 0 otherwise. 202 */ 203static intam_in_progress(const struct am_state *state) 204{ 205struct stat st; 206 207if(lstat(state->dir, &st) <0|| !S_ISDIR(st.st_mode)) 208return0; 209if(lstat(am_path(state,"last"), &st) || !S_ISREG(st.st_mode)) 210return0; 211if(lstat(am_path(state,"next"), &st) || !S_ISREG(st.st_mode)) 212return0; 213return1; 214} 215 216/** 217 * Reads the contents of `file` in the `state` directory into `sb`. Returns the 218 * number of bytes read on success, -1 if the file does not exist. If `trim` is 219 * set, trailing whitespace will be removed. 220 */ 221static intread_state_file(struct strbuf *sb,const struct am_state *state, 222const char*file,int trim) 223{ 224strbuf_reset(sb); 225 226if(strbuf_read_file(sb,am_path(state, file),0) >=0) { 227if(trim) 228strbuf_trim(sb); 229 230return sb->len; 231} 232 233if(errno == ENOENT) 234return-1; 235 236die_errno(_("could not read '%s'"),am_path(state, file)); 237} 238 239/** 240 * Reads a KEY=VALUE shell variable assignment from `fp`, returning the VALUE 241 * as a newly-allocated string. VALUE must be a quoted string, and the KEY must 242 * match `key`. Returns NULL on failure. 243 * 244 * This is used by read_author_script() to read the GIT_AUTHOR_* variables from 245 * the author-script. 246 */ 247static char*read_shell_var(FILE*fp,const char*key) 248{ 249struct strbuf sb = STRBUF_INIT; 250const char*str; 251 252if(strbuf_getline(&sb, fp,'\n')) 253goto fail; 254 255if(!skip_prefix(sb.buf, key, &str)) 256goto fail; 257 258if(!skip_prefix(str,"=", &str)) 259goto fail; 260 261strbuf_remove(&sb,0, str - sb.buf); 262 263 str =sq_dequote(sb.buf); 264if(!str) 265goto fail; 266 267returnstrbuf_detach(&sb, NULL); 268 269fail: 270strbuf_release(&sb); 271return NULL; 272} 273 274/** 275 * Reads and parses the state directory's "author-script" file, and sets 276 * state->author_name, state->author_email and state->author_date accordingly. 277 * Returns 0 on success, -1 if the file could not be parsed. 278 * 279 * The author script is of the format: 280 * 281 * GIT_AUTHOR_NAME='$author_name' 282 * GIT_AUTHOR_EMAIL='$author_email' 283 * GIT_AUTHOR_DATE='$author_date' 284 * 285 * where $author_name, $author_email and $author_date are quoted. We are strict 286 * with our parsing, as the file was meant to be eval'd in the old git-am.sh 287 * script, and thus if the file differs from what this function expects, it is 288 * better to bail out than to do something that the user does not expect. 289 */ 290static intread_author_script(struct am_state *state) 291{ 292const char*filename =am_path(state,"author-script"); 293FILE*fp; 294 295assert(!state->author_name); 296assert(!state->author_email); 297assert(!state->author_date); 298 299 fp =fopen(filename,"r"); 300if(!fp) { 301if(errno == ENOENT) 302return0; 303die_errno(_("could not open '%s' for reading"), filename); 304} 305 306 state->author_name =read_shell_var(fp,"GIT_AUTHOR_NAME"); 307if(!state->author_name) { 308fclose(fp); 309return-1; 310} 311 312 state->author_email =read_shell_var(fp,"GIT_AUTHOR_EMAIL"); 313if(!state->author_email) { 314fclose(fp); 315return-1; 316} 317 318 state->author_date =read_shell_var(fp,"GIT_AUTHOR_DATE"); 319if(!state->author_date) { 320fclose(fp); 321return-1; 322} 323 324if(fgetc(fp) != EOF) { 325fclose(fp); 326return-1; 327} 328 329fclose(fp); 330return0; 331} 332 333/** 334 * Saves state->author_name, state->author_email and state->author_date in the 335 * state directory's "author-script" file. 336 */ 337static voidwrite_author_script(const struct am_state *state) 338{ 339struct strbuf sb = STRBUF_INIT; 340 341strbuf_addstr(&sb,"GIT_AUTHOR_NAME="); 342sq_quote_buf(&sb, state->author_name); 343strbuf_addch(&sb,'\n'); 344 345strbuf_addstr(&sb,"GIT_AUTHOR_EMAIL="); 346sq_quote_buf(&sb, state->author_email); 347strbuf_addch(&sb,'\n'); 348 349strbuf_addstr(&sb,"GIT_AUTHOR_DATE="); 350sq_quote_buf(&sb, state->author_date); 351strbuf_addch(&sb,'\n'); 352 353write_file(am_path(state,"author-script"),1,"%s", sb.buf); 354 355strbuf_release(&sb); 356} 357 358/** 359 * Reads the commit message from the state directory's "final-commit" file, 360 * setting state->msg to its contents and state->msg_len to the length of its 361 * contents in bytes. 362 * 363 * Returns 0 on success, -1 if the file does not exist. 364 */ 365static intread_commit_msg(struct am_state *state) 366{ 367struct strbuf sb = STRBUF_INIT; 368 369assert(!state->msg); 370 371if(read_state_file(&sb, state,"final-commit",0) <0) { 372strbuf_release(&sb); 373return-1; 374} 375 376 state->msg =strbuf_detach(&sb, &state->msg_len); 377return0; 378} 379 380/** 381 * Saves state->msg in the state directory's "final-commit" file. 382 */ 383static voidwrite_commit_msg(const struct am_state *state) 384{ 385int fd; 386const char*filename =am_path(state,"final-commit"); 387 388 fd =xopen(filename, O_WRONLY | O_CREAT,0666); 389if(write_in_full(fd, state->msg, state->msg_len) <0) 390die_errno(_("could not write to%s"), filename); 391close(fd); 392} 393 394/** 395 * Loads state from disk. 396 */ 397static voidam_load(struct am_state *state) 398{ 399struct strbuf sb = STRBUF_INIT; 400 401if(read_state_file(&sb, state,"next",1) <0) 402die("BUG: state file 'next' does not exist"); 403 state->cur =strtol(sb.buf, NULL,10); 404 405if(read_state_file(&sb, state,"last",1) <0) 406die("BUG: state file 'last' does not exist"); 407 state->last =strtol(sb.buf, NULL,10); 408 409if(read_author_script(state) <0) 410die(_("could not parse author script")); 411 412read_commit_msg(state); 413 414if(read_state_file(&sb, state,"original-commit",1) <0) 415hashclr(state->orig_commit); 416else if(get_sha1_hex(sb.buf, state->orig_commit) <0) 417die(_("could not parse%s"),am_path(state,"original-commit")); 418 419read_state_file(&sb, state,"threeway",1); 420 state->threeway = !strcmp(sb.buf,"t"); 421 422read_state_file(&sb, state,"quiet",1); 423 state->quiet = !strcmp(sb.buf,"t"); 424 425read_state_file(&sb, state,"sign",1); 426 state->signoff = !strcmp(sb.buf,"t"); 427 428read_state_file(&sb, state,"utf8",1); 429 state->utf8 = !strcmp(sb.buf,"t"); 430 431read_state_file(&sb, state,"keep",1); 432if(!strcmp(sb.buf,"t")) 433 state->keep = KEEP_TRUE; 434else if(!strcmp(sb.buf,"b")) 435 state->keep = KEEP_NON_PATCH; 436else 437 state->keep = KEEP_FALSE; 438 439read_state_file(&sb, state,"messageid",1); 440 state->message_id = !strcmp(sb.buf,"t"); 441 442read_state_file(&sb, state,"scissors",1); 443if(!strcmp(sb.buf,"t")) 444 state->scissors = SCISSORS_TRUE; 445else if(!strcmp(sb.buf,"f")) 446 state->scissors = SCISSORS_FALSE; 447else 448 state->scissors = SCISSORS_UNSET; 449 450read_state_file(&sb, state,"apply-opt",1); 451argv_array_clear(&state->git_apply_opts); 452if(sq_dequote_to_argv_array(sb.buf, &state->git_apply_opts) <0) 453die(_("could not parse%s"),am_path(state,"apply-opt")); 454 455 state->rebasing = !!file_exists(am_path(state,"rebasing")); 456 457strbuf_release(&sb); 458} 459 460/** 461 * Removes the am_state directory, forcefully terminating the current am 462 * session. 463 */ 464static voidam_destroy(const struct am_state *state) 465{ 466struct strbuf sb = STRBUF_INIT; 467 468strbuf_addstr(&sb, state->dir); 469remove_dir_recursively(&sb,0); 470strbuf_release(&sb); 471} 472 473/** 474 * Runs applypatch-msg hook. Returns its exit code. 475 */ 476static intrun_applypatch_msg_hook(struct am_state *state) 477{ 478int ret; 479 480assert(state->msg); 481 ret =run_hook_le(NULL,"applypatch-msg",am_path(state,"final-commit"), NULL); 482 483if(!ret) { 484free(state->msg); 485 state->msg = NULL; 486if(read_commit_msg(state) <0) 487die(_("'%s' was deleted by the applypatch-msg hook"), 488am_path(state,"final-commit")); 489} 490 491return ret; 492} 493 494/** 495 * Runs post-rewrite hook. Returns it exit code. 496 */ 497static intrun_post_rewrite_hook(const struct am_state *state) 498{ 499struct child_process cp = CHILD_PROCESS_INIT; 500const char*hook =find_hook("post-rewrite"); 501int ret; 502 503if(!hook) 504return0; 505 506argv_array_push(&cp.args, hook); 507argv_array_push(&cp.args,"rebase"); 508 509 cp.in =xopen(am_path(state,"rewritten"), O_RDONLY); 510 cp.stdout_to_stderr =1; 511 512 ret =run_command(&cp); 513 514close(cp.in); 515return ret; 516} 517 518/** 519 * Reads the state directory's "rewritten" file, and copies notes from the old 520 * commits listed in the file to their rewritten commits. 521 * 522 * Returns 0 on success, -1 on failure. 523 */ 524static intcopy_notes_for_rebase(const struct am_state *state) 525{ 526struct notes_rewrite_cfg *c; 527struct strbuf sb = STRBUF_INIT; 528const char*invalid_line =_("Malformed input line: '%s'."); 529const char*msg ="Notes added by 'git rebase'"; 530FILE*fp; 531int ret =0; 532 533assert(state->rebasing); 534 535 c =init_copy_notes_for_rewrite("rebase"); 536if(!c) 537return0; 538 539 fp =xfopen(am_path(state,"rewritten"),"r"); 540 541while(!strbuf_getline(&sb, fp,'\n')) { 542unsigned char from_obj[GIT_SHA1_RAWSZ], to_obj[GIT_SHA1_RAWSZ]; 543 544if(sb.len != GIT_SHA1_HEXSZ *2+1) { 545 ret =error(invalid_line, sb.buf); 546goto finish; 547} 548 549if(get_sha1_hex(sb.buf, from_obj)) { 550 ret =error(invalid_line, sb.buf); 551goto finish; 552} 553 554if(sb.buf[GIT_SHA1_HEXSZ] !=' ') { 555 ret =error(invalid_line, sb.buf); 556goto finish; 557} 558 559if(get_sha1_hex(sb.buf + GIT_SHA1_HEXSZ +1, to_obj)) { 560 ret =error(invalid_line, sb.buf); 561goto finish; 562} 563 564if(copy_note_for_rewrite(c, from_obj, to_obj)) 565 ret =error(_("Failed to copy notes from '%s' to '%s'"), 566sha1_to_hex(from_obj),sha1_to_hex(to_obj)); 567} 568 569finish: 570finish_copy_notes_for_rewrite(c, msg); 571fclose(fp); 572strbuf_release(&sb); 573return ret; 574} 575 576/** 577 * Determines if the file looks like a piece of RFC2822 mail by grabbing all 578 * non-indented lines and checking if they look like they begin with valid 579 * header field names. 580 * 581 * Returns 1 if the file looks like a piece of mail, 0 otherwise. 582 */ 583static intis_mail(FILE*fp) 584{ 585const char*header_regex ="^[!-9;-~]+:"; 586struct strbuf sb = STRBUF_INIT; 587 regex_t regex; 588int ret =1; 589 590if(fseek(fp,0L, SEEK_SET)) 591die_errno(_("fseek failed")); 592 593if(regcomp(®ex, header_regex, REG_NOSUB | REG_EXTENDED)) 594die("invalid pattern:%s", header_regex); 595 596while(!strbuf_getline_crlf(&sb, fp)) { 597if(!sb.len) 598break;/* End of header */ 599 600/* Ignore indented folded lines */ 601if(*sb.buf =='\t'|| *sb.buf ==' ') 602continue; 603 604/* It's a header if it matches header_regex */ 605if(regexec(®ex, sb.buf,0, NULL,0)) { 606 ret =0; 607goto done; 608} 609} 610 611done: 612regfree(®ex); 613strbuf_release(&sb); 614return ret; 615} 616 617/** 618 * Attempts to detect the patch_format of the patches contained in `paths`, 619 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if 620 * detection fails. 621 */ 622static intdetect_patch_format(const char**paths) 623{ 624enum patch_format ret = PATCH_FORMAT_UNKNOWN; 625struct strbuf l1 = STRBUF_INIT; 626struct strbuf l2 = STRBUF_INIT; 627struct strbuf l3 = STRBUF_INIT; 628FILE*fp; 629 630/* 631 * We default to mbox format if input is from stdin and for directories 632 */ 633if(!*paths || !strcmp(*paths,"-") ||is_directory(*paths)) 634return PATCH_FORMAT_MBOX; 635 636/* 637 * Otherwise, check the first few lines of the first patch, starting 638 * from the first non-blank line, to try to detect its format. 639 */ 640 641 fp =xfopen(*paths,"r"); 642 643while(!strbuf_getline_crlf(&l1, fp)) { 644if(l1.len) 645break; 646} 647 648if(starts_with(l1.buf,"From ") ||starts_with(l1.buf,"From: ")) { 649 ret = PATCH_FORMAT_MBOX; 650goto done; 651} 652 653strbuf_reset(&l2); 654strbuf_getline_crlf(&l2, fp); 655strbuf_reset(&l3); 656strbuf_getline_crlf(&l3, fp); 657 658/* 659 * If the second line is empty and the third is a From, Author or Date 660 * entry, this is likely an StGit patch. 661 */ 662if(l1.len && !l2.len && 663(starts_with(l3.buf,"From:") || 664starts_with(l3.buf,"Author:") || 665starts_with(l3.buf,"Date:"))) { 666 ret = PATCH_FORMAT_STGIT; 667goto done; 668} 669 670if(l1.len &&is_mail(fp)) { 671 ret = PATCH_FORMAT_MBOX; 672goto done; 673} 674 675done: 676fclose(fp); 677strbuf_release(&l1); 678return ret; 679} 680 681/** 682 * Splits out individual email patches from `paths`, where each path is either 683 * a mbox file or a Maildir. Returns 0 on success, -1 on failure. 684 */ 685static intsplit_mail_mbox(struct am_state *state,const char**paths,int keep_cr) 686{ 687struct child_process cp = CHILD_PROCESS_INIT; 688struct strbuf last = STRBUF_INIT; 689 690 cp.git_cmd =1; 691argv_array_push(&cp.args,"mailsplit"); 692argv_array_pushf(&cp.args,"-d%d", state->prec); 693argv_array_pushf(&cp.args,"-o%s", state->dir); 694argv_array_push(&cp.args,"-b"); 695if(keep_cr) 696argv_array_push(&cp.args,"--keep-cr"); 697argv_array_push(&cp.args,"--"); 698argv_array_pushv(&cp.args, paths); 699 700if(capture_command(&cp, &last,8)) 701return-1; 702 703 state->cur =1; 704 state->last =strtol(last.buf, NULL,10); 705 706return0; 707} 708 709/** 710 * Callback signature for split_mail_conv(). The foreign patch should be 711 * read from `in`, and the converted patch (in RFC2822 mail format) should be 712 * written to `out`. Return 0 on success, or -1 on failure. 713 */ 714typedefint(*mail_conv_fn)(FILE*out,FILE*in,int keep_cr); 715 716/** 717 * Calls `fn` for each file in `paths` to convert the foreign patch to the 718 * RFC2822 mail format suitable for parsing with git-mailinfo. 719 * 720 * Returns 0 on success, -1 on failure. 721 */ 722static intsplit_mail_conv(mail_conv_fn fn,struct am_state *state, 723const char**paths,int keep_cr) 724{ 725static const char*stdin_only[] = {"-", NULL}; 726int i; 727 728if(!*paths) 729 paths = stdin_only; 730 731for(i =0; *paths; paths++, i++) { 732FILE*in, *out; 733const char*mail; 734int ret; 735 736if(!strcmp(*paths,"-")) 737 in = stdin; 738else 739 in =fopen(*paths,"r"); 740 741if(!in) 742returnerror(_("could not open '%s' for reading:%s"), 743*paths,strerror(errno)); 744 745 mail =mkpath("%s/%0*d", state->dir, state->prec, i +1); 746 747 out =fopen(mail,"w"); 748if(!out) 749returnerror(_("could not open '%s' for writing:%s"), 750 mail,strerror(errno)); 751 752 ret =fn(out, in, keep_cr); 753 754fclose(out); 755fclose(in); 756 757if(ret) 758returnerror(_("could not parse patch '%s'"), *paths); 759} 760 761 state->cur =1; 762 state->last = i; 763return0; 764} 765 766/** 767 * A split_mail_conv() callback that converts an StGit patch to an RFC2822 768 * message suitable for parsing with git-mailinfo. 769 */ 770static intstgit_patch_to_mail(FILE*out,FILE*in,int keep_cr) 771{ 772struct strbuf sb = STRBUF_INIT; 773int subject_printed =0; 774 775while(!strbuf_getline(&sb, in,'\n')) { 776const char*str; 777 778if(str_isspace(sb.buf)) 779continue; 780else if(skip_prefix(sb.buf,"Author:", &str)) 781fprintf(out,"From:%s\n", str); 782else if(starts_with(sb.buf,"From") ||starts_with(sb.buf,"Date")) 783fprintf(out,"%s\n", sb.buf); 784else if(!subject_printed) { 785fprintf(out,"Subject:%s\n", sb.buf); 786 subject_printed =1; 787}else{ 788fprintf(out,"\n%s\n", sb.buf); 789break; 790} 791} 792 793strbuf_reset(&sb); 794while(strbuf_fread(&sb,8192, in) >0) { 795fwrite(sb.buf,1, sb.len, out); 796strbuf_reset(&sb); 797} 798 799strbuf_release(&sb); 800return0; 801} 802 803/** 804 * Splits a list of files/directories into individual email patches. Each path 805 * in `paths` must be a file/directory that is formatted according to 806 * `patch_format`. 807 * 808 * Once split out, the individual email patches will be stored in the state 809 * directory, with each patch's filename being its index, padded to state->prec 810 * digits. 811 * 812 * state->cur will be set to the index of the first mail, and state->last will 813 * be set to the index of the last mail. 814 * 815 * Set keep_cr to 0 to convert all lines ending with \r\n to end with \n, 1 816 * to disable this behavior, -1 to use the default configured setting. 817 * 818 * Returns 0 on success, -1 on failure. 819 */ 820static intsplit_mail(struct am_state *state,enum patch_format patch_format, 821const char**paths,int keep_cr) 822{ 823if(keep_cr <0) { 824 keep_cr =0; 825git_config_get_bool("am.keepcr", &keep_cr); 826} 827 828switch(patch_format) { 829case PATCH_FORMAT_MBOX: 830returnsplit_mail_mbox(state, paths, keep_cr); 831case PATCH_FORMAT_STGIT: 832returnsplit_mail_conv(stgit_patch_to_mail, state, paths, keep_cr); 833default: 834die("BUG: invalid patch_format"); 835} 836return-1; 837} 838 839/** 840 * Setup a new am session for applying patches 841 */ 842static voidam_setup(struct am_state *state,enum patch_format patch_format, 843const char**paths,int keep_cr) 844{ 845unsigned char curr_head[GIT_SHA1_RAWSZ]; 846const char*str; 847struct strbuf sb = STRBUF_INIT; 848 849if(!patch_format) 850 patch_format =detect_patch_format(paths); 851 852if(!patch_format) { 853fprintf_ln(stderr,_("Patch format detection failed.")); 854exit(128); 855} 856 857if(mkdir(state->dir,0777) <0&& errno != EEXIST) 858die_errno(_("failed to create directory '%s'"), state->dir); 859 860if(split_mail(state, patch_format, paths, keep_cr) <0) { 861am_destroy(state); 862die(_("Failed to split patches.")); 863} 864 865if(state->rebasing) 866 state->threeway =1; 867 868write_file(am_path(state,"threeway"),1, state->threeway ?"t":"f"); 869 870write_file(am_path(state,"quiet"),1, state->quiet ?"t":"f"); 871 872write_file(am_path(state,"sign"),1, state->signoff ?"t":"f"); 873 874write_file(am_path(state,"utf8"),1, state->utf8 ?"t":"f"); 875 876switch(state->keep) { 877case KEEP_FALSE: 878 str ="f"; 879break; 880case KEEP_TRUE: 881 str ="t"; 882break; 883case KEEP_NON_PATCH: 884 str ="b"; 885break; 886default: 887die("BUG: invalid value for state->keep"); 888} 889 890write_file(am_path(state,"keep"),1,"%s", str); 891 892write_file(am_path(state,"messageid"),1, state->message_id ?"t":"f"); 893 894switch(state->scissors) { 895case SCISSORS_UNSET: 896 str =""; 897break; 898case SCISSORS_FALSE: 899 str ="f"; 900break; 901case SCISSORS_TRUE: 902 str ="t"; 903break; 904default: 905die("BUG: invalid value for state->scissors"); 906} 907 908write_file(am_path(state,"scissors"),1,"%s", str); 909 910sq_quote_argv(&sb, state->git_apply_opts.argv,0); 911write_file(am_path(state,"apply-opt"),1,"%s", sb.buf); 912 913if(state->rebasing) 914write_file(am_path(state,"rebasing"),1,"%s",""); 915else 916write_file(am_path(state,"applying"),1,"%s",""); 917 918if(!get_sha1("HEAD", curr_head)) { 919write_file(am_path(state,"abort-safety"),1,"%s",sha1_to_hex(curr_head)); 920if(!state->rebasing) 921update_ref("am","ORIG_HEAD", curr_head, NULL,0, 922 UPDATE_REFS_DIE_ON_ERR); 923}else{ 924write_file(am_path(state,"abort-safety"),1,"%s",""); 925if(!state->rebasing) 926delete_ref("ORIG_HEAD", NULL,0); 927} 928 929/* 930 * NOTE: Since the "next" and "last" files determine if an am_state 931 * session is in progress, they should be written last. 932 */ 933 934write_file(am_path(state,"next"),1,"%d", state->cur); 935 936write_file(am_path(state,"last"),1,"%d", state->last); 937 938strbuf_release(&sb); 939} 940 941/** 942 * Increments the patch pointer, and cleans am_state for the application of the 943 * next patch. 944 */ 945static voidam_next(struct am_state *state) 946{ 947unsigned char head[GIT_SHA1_RAWSZ]; 948 949free(state->author_name); 950 state->author_name = NULL; 951 952free(state->author_email); 953 state->author_email = NULL; 954 955free(state->author_date); 956 state->author_date = NULL; 957 958free(state->msg); 959 state->msg = NULL; 960 state->msg_len =0; 961 962unlink(am_path(state,"author-script")); 963unlink(am_path(state,"final-commit")); 964 965hashclr(state->orig_commit); 966unlink(am_path(state,"original-commit")); 967 968if(!get_sha1("HEAD", head)) 969write_file(am_path(state,"abort-safety"),1,"%s",sha1_to_hex(head)); 970else 971write_file(am_path(state,"abort-safety"),1,"%s",""); 972 973 state->cur++; 974write_file(am_path(state,"next"),1,"%d", state->cur); 975} 976 977/** 978 * Returns the filename of the current patch email. 979 */ 980static const char*msgnum(const struct am_state *state) 981{ 982static struct strbuf sb = STRBUF_INIT; 983 984strbuf_reset(&sb); 985strbuf_addf(&sb,"%0*d", state->prec, state->cur); 986 987return sb.buf; 988} 989 990/** 991 * Refresh and write index. 992 */ 993static voidrefresh_and_write_cache(void) 994{ 995struct lock_file *lock_file =xcalloc(1,sizeof(struct lock_file)); 996 997hold_locked_index(lock_file,1); 998refresh_cache(REFRESH_QUIET); 999if(write_locked_index(&the_index, lock_file, COMMIT_LOCK))1000die(_("unable to write index file"));1001}10021003/**1004 * Returns 1 if the index differs from HEAD, 0 otherwise. When on an unborn1005 * branch, returns 1 if there are entries in the index, 0 otherwise. If an1006 * strbuf is provided, the space-separated list of files that differ will be1007 * appended to it.1008 */1009static intindex_has_changes(struct strbuf *sb)1010{1011unsigned char head[GIT_SHA1_RAWSZ];1012int i;10131014if(!get_sha1_tree("HEAD", head)) {1015struct diff_options opt;10161017diff_setup(&opt);1018DIFF_OPT_SET(&opt, EXIT_WITH_STATUS);1019if(!sb)1020DIFF_OPT_SET(&opt, QUICK);1021do_diff_cache(head, &opt);1022diffcore_std(&opt);1023for(i =0; sb && i < diff_queued_diff.nr; i++) {1024if(i)1025strbuf_addch(sb,' ');1026strbuf_addstr(sb, diff_queued_diff.queue[i]->two->path);1027}1028diff_flush(&opt);1029returnDIFF_OPT_TST(&opt, HAS_CHANGES) !=0;1030}else{1031for(i =0; sb && i < active_nr; i++) {1032if(i)1033strbuf_addch(sb,' ');1034strbuf_addstr(sb, active_cache[i]->name);1035}1036return!!active_nr;1037}1038}10391040/**1041 * Dies with a user-friendly message on how to proceed after resolving the1042 * problem. This message can be overridden with state->resolvemsg.1043 */1044static void NORETURN die_user_resolve(const struct am_state *state)1045{1046if(state->resolvemsg) {1047printf_ln("%s", state->resolvemsg);1048}else{1049const char*cmdline ="git am";10501051printf_ln(_("When you have resolved this problem, run\"%s--continue\"."), cmdline);1052printf_ln(_("If you prefer to skip this patch, run\"%s--skip\"instead."), cmdline);1053printf_ln(_("To restore the original branch and stop patching, run\"%s--abort\"."), cmdline);1054}10551056exit(128);1057}10581059/**1060 * Parses `mail` using git-mailinfo, extracting its patch and authorship info.1061 * state->msg will be set to the patch message. state->author_name,1062 * state->author_email and state->author_date will be set to the patch author's1063 * name, email and date respectively. The patch body will be written to the1064 * state directory's "patch" file.1065 *1066 * Returns 1 if the patch should be skipped, 0 otherwise.1067 */1068static intparse_mail(struct am_state *state,const char*mail)1069{1070FILE*fp;1071struct child_process cp = CHILD_PROCESS_INIT;1072struct strbuf sb = STRBUF_INIT;1073struct strbuf msg = STRBUF_INIT;1074struct strbuf author_name = STRBUF_INIT;1075struct strbuf author_date = STRBUF_INIT;1076struct strbuf author_email = STRBUF_INIT;1077int ret =0;10781079 cp.git_cmd =1;1080 cp.in =xopen(mail, O_RDONLY,0);1081 cp.out =xopen(am_path(state,"info"), O_WRONLY | O_CREAT,0777);10821083argv_array_push(&cp.args,"mailinfo");1084argv_array_push(&cp.args, state->utf8 ?"-u":"-n");10851086switch(state->keep) {1087case KEEP_FALSE:1088break;1089case KEEP_TRUE:1090argv_array_push(&cp.args,"-k");1091break;1092case KEEP_NON_PATCH:1093argv_array_push(&cp.args,"-b");1094break;1095default:1096die("BUG: invalid value for state->keep");1097}10981099if(state->message_id)1100argv_array_push(&cp.args,"-m");11011102switch(state->scissors) {1103case SCISSORS_UNSET:1104break;1105case SCISSORS_FALSE:1106argv_array_push(&cp.args,"--no-scissors");1107break;1108case SCISSORS_TRUE:1109argv_array_push(&cp.args,"--scissors");1110break;1111default:1112die("BUG: invalid value for state->scissors");1113}11141115argv_array_push(&cp.args,am_path(state,"msg"));1116argv_array_push(&cp.args,am_path(state,"patch"));11171118if(run_command(&cp) <0)1119die("could not parse patch");11201121close(cp.in);1122close(cp.out);11231124/* Extract message and author information */1125 fp =xfopen(am_path(state,"info"),"r");1126while(!strbuf_getline(&sb, fp,'\n')) {1127const char*x;11281129if(skip_prefix(sb.buf,"Subject: ", &x)) {1130if(msg.len)1131strbuf_addch(&msg,'\n');1132strbuf_addstr(&msg, x);1133}else if(skip_prefix(sb.buf,"Author: ", &x))1134strbuf_addstr(&author_name, x);1135else if(skip_prefix(sb.buf,"Email: ", &x))1136strbuf_addstr(&author_email, x);1137else if(skip_prefix(sb.buf,"Date: ", &x))1138strbuf_addstr(&author_date, x);1139}1140fclose(fp);11411142/* Skip pine's internal folder data */1143if(!strcmp(author_name.buf,"Mail System Internal Data")) {1144 ret =1;1145goto finish;1146}11471148if(is_empty_file(am_path(state,"patch"))) {1149printf_ln(_("Patch is empty. Was it split wrong?"));1150die_user_resolve(state);1151}11521153strbuf_addstr(&msg,"\n\n");1154if(strbuf_read_file(&msg,am_path(state,"msg"),0) <0)1155die_errno(_("could not read '%s'"),am_path(state,"msg"));1156stripspace(&msg,0);11571158if(state->signoff)1159append_signoff(&msg,0,0);11601161assert(!state->author_name);1162 state->author_name =strbuf_detach(&author_name, NULL);11631164assert(!state->author_email);1165 state->author_email =strbuf_detach(&author_email, NULL);11661167assert(!state->author_date);1168 state->author_date =strbuf_detach(&author_date, NULL);11691170assert(!state->msg);1171 state->msg =strbuf_detach(&msg, &state->msg_len);11721173finish:1174strbuf_release(&msg);1175strbuf_release(&author_date);1176strbuf_release(&author_email);1177strbuf_release(&author_name);1178strbuf_release(&sb);1179return ret;1180}11811182/**1183 * Sets commit_id to the commit hash where the mail was generated from.1184 * Returns 0 on success, -1 on failure.1185 */1186static intget_mail_commit_sha1(unsigned char*commit_id,const char*mail)1187{1188struct strbuf sb = STRBUF_INIT;1189FILE*fp =xfopen(mail,"r");1190const char*x;11911192if(strbuf_getline(&sb, fp,'\n'))1193return-1;11941195if(!skip_prefix(sb.buf,"From ", &x))1196return-1;11971198if(get_sha1_hex(x, commit_id) <0)1199return-1;12001201strbuf_release(&sb);1202fclose(fp);1203return0;1204}12051206/**1207 * Sets state->msg, state->author_name, state->author_email, state->author_date1208 * to the commit's respective info.1209 */1210static voidget_commit_info(struct am_state *state,struct commit *commit)1211{1212const char*buffer, *ident_line, *author_date, *msg;1213size_t ident_len;1214struct ident_split ident_split;1215struct strbuf sb = STRBUF_INIT;12161217 buffer =logmsg_reencode(commit, NULL,get_commit_output_encoding());12181219 ident_line =find_commit_header(buffer,"author", &ident_len);12201221if(split_ident_line(&ident_split, ident_line, ident_len) <0) {1222strbuf_add(&sb, ident_line, ident_len);1223die(_("invalid ident line:%s"), sb.buf);1224}12251226assert(!state->author_name);1227if(ident_split.name_begin) {1228strbuf_add(&sb, ident_split.name_begin,1229 ident_split.name_end - ident_split.name_begin);1230 state->author_name =strbuf_detach(&sb, NULL);1231}else1232 state->author_name =xstrdup("");12331234assert(!state->author_email);1235if(ident_split.mail_begin) {1236strbuf_add(&sb, ident_split.mail_begin,1237 ident_split.mail_end - ident_split.mail_begin);1238 state->author_email =strbuf_detach(&sb, NULL);1239}else1240 state->author_email =xstrdup("");12411242 author_date =show_ident_date(&ident_split,DATE_MODE(NORMAL));1243strbuf_addstr(&sb, author_date);1244assert(!state->author_date);1245 state->author_date =strbuf_detach(&sb, NULL);12461247assert(!state->msg);1248 msg =strstr(buffer,"\n\n");1249if(!msg)1250die(_("unable to parse commit%s"),sha1_to_hex(commit->object.sha1));1251 state->msg =xstrdup(msg +2);1252 state->msg_len =strlen(state->msg);1253}12541255/**1256 * Writes `commit` as a patch to the state directory's "patch" file.1257 */1258static voidwrite_commit_patch(const struct am_state *state,struct commit *commit)1259{1260struct rev_info rev_info;1261FILE*fp;12621263 fp =xfopen(am_path(state,"patch"),"w");1264init_revisions(&rev_info, NULL);1265 rev_info.diff =1;1266 rev_info.abbrev =0;1267 rev_info.disable_stdin =1;1268 rev_info.show_root_diff =1;1269 rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;1270 rev_info.no_commit_id =1;1271DIFF_OPT_SET(&rev_info.diffopt, BINARY);1272DIFF_OPT_SET(&rev_info.diffopt, FULL_INDEX);1273 rev_info.diffopt.use_color =0;1274 rev_info.diffopt.file = fp;1275 rev_info.diffopt.close_file =1;1276add_pending_object(&rev_info, &commit->object,"");1277diff_setup_done(&rev_info.diffopt);1278log_tree_commit(&rev_info, commit);1279}12801281/**1282 * Like parse_mail(), but parses the mail by looking up its commit ID1283 * directly. This is used in --rebasing mode to bypass git-mailinfo's munging1284 * of patches.1285 *1286 * state->orig_commit will be set to the original commit ID.1287 *1288 * Will always return 0 as the patch should never be skipped.1289 */1290static intparse_mail_rebase(struct am_state *state,const char*mail)1291{1292struct commit *commit;1293unsigned char commit_sha1[GIT_SHA1_RAWSZ];12941295if(get_mail_commit_sha1(commit_sha1, mail) <0)1296die(_("could not parse%s"), mail);12971298 commit =lookup_commit_or_die(commit_sha1, mail);12991300get_commit_info(state, commit);13011302write_commit_patch(state, commit);13031304hashcpy(state->orig_commit, commit_sha1);1305write_file(am_path(state,"original-commit"),1,"%s",1306sha1_to_hex(commit_sha1));13071308return0;1309}13101311/**1312 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If1313 * `index_file` is not NULL, the patch will be applied to that index.1314 */1315static intrun_apply(const struct am_state *state,const char*index_file)1316{1317struct child_process cp = CHILD_PROCESS_INIT;13181319 cp.git_cmd =1;13201321if(index_file)1322argv_array_pushf(&cp.env_array,"GIT_INDEX_FILE=%s", index_file);13231324/*1325 * If we are allowed to fall back on 3-way merge, don't give false1326 * errors during the initial attempt.1327 */1328if(state->threeway && !index_file) {1329 cp.no_stdout =1;1330 cp.no_stderr =1;1331}13321333argv_array_push(&cp.args,"apply");13341335argv_array_pushv(&cp.args, state->git_apply_opts.argv);13361337if(index_file)1338argv_array_push(&cp.args,"--cached");1339else1340argv_array_push(&cp.args,"--index");13411342argv_array_push(&cp.args,am_path(state,"patch"));13431344if(run_command(&cp))1345return-1;13461347/* Reload index as git-apply will have modified it. */1348discard_cache();1349read_cache_from(index_file ? index_file :get_index_file());13501351return0;1352}13531354/**1355 * Builds an index that contains just the blobs needed for a 3way merge.1356 */1357static intbuild_fake_ancestor(const struct am_state *state,const char*index_file)1358{1359struct child_process cp = CHILD_PROCESS_INIT;13601361 cp.git_cmd =1;1362argv_array_push(&cp.args,"apply");1363argv_array_pushv(&cp.args, state->git_apply_opts.argv);1364argv_array_pushf(&cp.args,"--build-fake-ancestor=%s", index_file);1365argv_array_push(&cp.args,am_path(state,"patch"));13661367if(run_command(&cp))1368return-1;13691370return0;1371}13721373/**1374 * Attempt a threeway merge, using index_path as the temporary index.1375 */1376static intfall_back_threeway(const struct am_state *state,const char*index_path)1377{1378unsigned char orig_tree[GIT_SHA1_RAWSZ], his_tree[GIT_SHA1_RAWSZ],1379 our_tree[GIT_SHA1_RAWSZ];1380const unsigned char*bases[1] = {orig_tree};1381struct merge_options o;1382struct commit *result;1383char*his_tree_name;13841385if(get_sha1("HEAD", our_tree) <0)1386hashcpy(our_tree, EMPTY_TREE_SHA1_BIN);13871388if(build_fake_ancestor(state, index_path))1389returnerror("could not build fake ancestor");13901391discard_cache();1392read_cache_from(index_path);13931394if(write_index_as_tree(orig_tree, &the_index, index_path,0, NULL))1395returnerror(_("Repository lacks necessary blobs to fall back on 3-way merge."));13961397say(state, stdout,_("Using index info to reconstruct a base tree..."));13981399if(!state->quiet) {1400/*1401 * List paths that needed 3-way fallback, so that the user can1402 * review them with extra care to spot mismerges.1403 */1404struct rev_info rev_info;1405const char*diff_filter_str ="--diff-filter=AM";14061407init_revisions(&rev_info, NULL);1408 rev_info.diffopt.output_format = DIFF_FORMAT_NAME_STATUS;1409diff_opt_parse(&rev_info.diffopt, &diff_filter_str,1);1410add_pending_sha1(&rev_info,"HEAD", our_tree,0);1411diff_setup_done(&rev_info.diffopt);1412run_diff_index(&rev_info,1);1413}14141415if(run_apply(state, index_path))1416returnerror(_("Did you hand edit your patch?\n"1417"It does not apply to blobs recorded in its index."));14181419if(write_index_as_tree(his_tree, &the_index, index_path,0, NULL))1420returnerror("could not write tree");14211422say(state, stdout,_("Falling back to patching base and 3-way merge..."));14231424discard_cache();1425read_cache();14261427/*1428 * This is not so wrong. Depending on which base we picked, orig_tree1429 * may be wildly different from ours, but his_tree has the same set of1430 * wildly different changes in parts the patch did not touch, so1431 * recursive ends up canceling them, saying that we reverted all those1432 * changes.1433 */14341435init_merge_options(&o);14361437 o.branch1 ="HEAD";1438 his_tree_name =xstrfmt("%.*s",linelen(state->msg), state->msg);1439 o.branch2 = his_tree_name;14401441if(state->quiet)1442 o.verbosity =0;14431444if(merge_recursive_generic(&o, our_tree, his_tree,1, bases, &result)) {1445rerere(state->allow_rerere_autoupdate);1446free(his_tree_name);1447returnerror(_("Failed to merge in the changes."));1448}14491450free(his_tree_name);1451return0;1452}14531454/**1455 * Commits the current index with state->msg as the commit message and1456 * state->author_name, state->author_email and state->author_date as the author1457 * information.1458 */1459static voiddo_commit(const struct am_state *state)1460{1461unsigned char tree[GIT_SHA1_RAWSZ], parent[GIT_SHA1_RAWSZ],1462 commit[GIT_SHA1_RAWSZ];1463unsigned char*ptr;1464struct commit_list *parents = NULL;1465const char*reflog_msg, *author;1466struct strbuf sb = STRBUF_INIT;14671468if(run_hook_le(NULL,"pre-applypatch", NULL))1469exit(1);14701471if(write_cache_as_tree(tree,0, NULL))1472die(_("git write-tree failed to write a tree"));14731474if(!get_sha1_commit("HEAD", parent)) {1475 ptr = parent;1476commit_list_insert(lookup_commit(parent), &parents);1477}else{1478 ptr = NULL;1479say(state, stderr,_("applying to an empty history"));1480}14811482 author =fmt_ident(state->author_name, state->author_email,1483 state->ignore_date ? NULL : state->author_date,1484 IDENT_STRICT);14851486if(state->committer_date_is_author_date)1487setenv("GIT_COMMITTER_DATE",1488 state->ignore_date ?"": state->author_date,1);14891490if(commit_tree(state->msg, state->msg_len, tree, parents, commit,1491 author, state->sign_commit))1492die(_("failed to write commit object"));14931494 reflog_msg =getenv("GIT_REFLOG_ACTION");1495if(!reflog_msg)1496 reflog_msg ="am";14971498strbuf_addf(&sb,"%s: %.*s", reflog_msg,linelen(state->msg),1499 state->msg);15001501update_ref(sb.buf,"HEAD", commit, ptr,0, UPDATE_REFS_DIE_ON_ERR);15021503if(state->rebasing) {1504FILE*fp =xfopen(am_path(state,"rewritten"),"a");15051506assert(!is_null_sha1(state->orig_commit));1507fprintf(fp,"%s",sha1_to_hex(state->orig_commit));1508fprintf(fp,"%s\n",sha1_to_hex(commit));1509fclose(fp);1510}15111512run_hook_le(NULL,"post-applypatch", NULL);15131514strbuf_release(&sb);1515}15161517/**1518 * Validates the am_state for resuming -- the "msg" and authorship fields must1519 * be filled up.1520 */1521static voidvalidate_resume_state(const struct am_state *state)1522{1523if(!state->msg)1524die(_("cannot resume:%sdoes not exist."),1525am_path(state,"final-commit"));15261527if(!state->author_name || !state->author_email || !state->author_date)1528die(_("cannot resume:%sdoes not exist."),1529am_path(state,"author-script"));1530}15311532/**1533 * Applies all queued mail.1534 *1535 * If `resume` is true, we are "resuming". The "msg" and authorship fields, as1536 * well as the state directory's "patch" file is used as-is for applying the1537 * patch and committing it.1538 */1539static voidam_run(struct am_state *state,int resume)1540{1541const char*argv_gc_auto[] = {"gc","--auto", NULL};1542struct strbuf sb = STRBUF_INIT;15431544unlink(am_path(state,"dirtyindex"));15451546refresh_and_write_cache();15471548if(index_has_changes(&sb)) {1549write_file(am_path(state,"dirtyindex"),1,"t");1550die(_("Dirty index: cannot apply patches (dirty:%s)"), sb.buf);1551}15521553strbuf_release(&sb);15541555while(state->cur <= state->last) {1556const char*mail =am_path(state,msgnum(state));1557int apply_status;15581559if(!file_exists(mail))1560goto next;15611562if(resume) {1563validate_resume_state(state);1564 resume =0;1565}else{1566int skip;15671568if(state->rebasing)1569 skip =parse_mail_rebase(state, mail);1570else1571 skip =parse_mail(state, mail);15721573if(skip)1574goto next;/* mail should be skipped */15751576write_author_script(state);1577write_commit_msg(state);1578}15791580if(run_applypatch_msg_hook(state))1581exit(1);15821583say(state, stdout,_("Applying: %.*s"),linelen(state->msg), state->msg);15841585 apply_status =run_apply(state, NULL);15861587if(apply_status && state->threeway) {1588struct strbuf sb = STRBUF_INIT;15891590strbuf_addstr(&sb,am_path(state,"patch-merge-index"));1591 apply_status =fall_back_threeway(state, sb.buf);1592strbuf_release(&sb);15931594/*1595 * Applying the patch to an earlier tree and merging1596 * the result may have produced the same tree as ours.1597 */1598if(!apply_status && !index_has_changes(NULL)) {1599say(state, stdout,_("No changes -- Patch already applied."));1600goto next;1601}1602}16031604if(apply_status) {1605int advice_amworkdir =1;16061607printf_ln(_("Patch failed at%s%.*s"),msgnum(state),1608linelen(state->msg), state->msg);16091610git_config_get_bool("advice.amworkdir", &advice_amworkdir);16111612if(advice_amworkdir)1613printf_ln(_("The copy of the patch that failed is found in:%s"),1614am_path(state,"patch"));16151616die_user_resolve(state);1617}16181619do_commit(state);16201621next:1622am_next(state);1623}16241625if(!is_empty_file(am_path(state,"rewritten"))) {1626assert(state->rebasing);1627copy_notes_for_rebase(state);1628run_post_rewrite_hook(state);1629}16301631/*1632 * In rebasing mode, it's up to the caller to take care of1633 * housekeeping.1634 */1635if(!state->rebasing) {1636am_destroy(state);1637run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);1638}1639}16401641/**1642 * Resume the current am session after patch application failure. The user did1643 * all the hard work, and we do not have to do any patch application. Just1644 * trust and commit what the user has in the index and working tree.1645 */1646static voidam_resolve(struct am_state *state)1647{1648validate_resume_state(state);16491650say(state, stdout,_("Applying: %.*s"),linelen(state->msg), state->msg);16511652if(!index_has_changes(NULL)) {1653printf_ln(_("No changes - did you forget to use 'git add'?\n"1654"If there is nothing left to stage, chances are that something else\n"1655"already introduced the same changes; you might want to skip this patch."));1656die_user_resolve(state);1657}16581659if(unmerged_cache()) {1660printf_ln(_("You still have unmerged paths in your index.\n"1661"Did you forget to use 'git add'?"));1662die_user_resolve(state);1663}16641665rerere(0);16661667do_commit(state);16681669am_next(state);1670am_run(state,0);1671}16721673/**1674 * Performs a checkout fast-forward from `head` to `remote`. If `reset` is1675 * true, any unmerged entries will be discarded. Returns 0 on success, -1 on1676 * failure.1677 */1678static intfast_forward_to(struct tree *head,struct tree *remote,int reset)1679{1680struct lock_file *lock_file;1681struct unpack_trees_options opts;1682struct tree_desc t[2];16831684if(parse_tree(head) ||parse_tree(remote))1685return-1;16861687 lock_file =xcalloc(1,sizeof(struct lock_file));1688hold_locked_index(lock_file,1);16891690refresh_cache(REFRESH_QUIET);16911692memset(&opts,0,sizeof(opts));1693 opts.head_idx =1;1694 opts.src_index = &the_index;1695 opts.dst_index = &the_index;1696 opts.update =1;1697 opts.merge =1;1698 opts.reset = reset;1699 opts.fn = twoway_merge;1700init_tree_desc(&t[0], head->buffer, head->size);1701init_tree_desc(&t[1], remote->buffer, remote->size);17021703if(unpack_trees(2, t, &opts)) {1704rollback_lock_file(lock_file);1705return-1;1706}17071708if(write_locked_index(&the_index, lock_file, COMMIT_LOCK))1709die(_("unable to write new index file"));17101711return0;1712}17131714/**1715 * Clean the index without touching entries that are not modified between1716 * `head` and `remote`.1717 */1718static intclean_index(const unsigned char*head,const unsigned char*remote)1719{1720struct lock_file *lock_file;1721struct tree *head_tree, *remote_tree, *index_tree;1722unsigned char index[GIT_SHA1_RAWSZ];1723struct pathspec pathspec;17241725 head_tree =parse_tree_indirect(head);1726if(!head_tree)1727returnerror(_("Could not parse object '%s'."),sha1_to_hex(head));17281729 remote_tree =parse_tree_indirect(remote);1730if(!remote_tree)1731returnerror(_("Could not parse object '%s'."),sha1_to_hex(remote));17321733read_cache_unmerged();17341735if(fast_forward_to(head_tree, head_tree,1))1736return-1;17371738if(write_cache_as_tree(index,0, NULL))1739return-1;17401741 index_tree =parse_tree_indirect(index);1742if(!index_tree)1743returnerror(_("Could not parse object '%s'."),sha1_to_hex(index));17441745if(fast_forward_to(index_tree, remote_tree,0))1746return-1;17471748memset(&pathspec,0,sizeof(pathspec));17491750 lock_file =xcalloc(1,sizeof(struct lock_file));1751hold_locked_index(lock_file,1);17521753if(read_tree(remote_tree,0, &pathspec)) {1754rollback_lock_file(lock_file);1755return-1;1756}17571758if(write_locked_index(&the_index, lock_file, COMMIT_LOCK))1759die(_("unable to write new index file"));17601761remove_branch_state();17621763return0;1764}17651766/**1767 * Resets rerere's merge resolution metadata.1768 */1769static voidam_rerere_clear(void)1770{1771struct string_list merge_rr = STRING_LIST_INIT_DUP;1772int fd =setup_rerere(&merge_rr,0);17731774if(fd <0)1775return;17761777rerere_clear(&merge_rr);1778string_list_clear(&merge_rr,1);1779}17801781/**1782 * Resume the current am session by skipping the current patch.1783 */1784static voidam_skip(struct am_state *state)1785{1786unsigned char head[GIT_SHA1_RAWSZ];17871788am_rerere_clear();17891790if(get_sha1("HEAD", head))1791hashcpy(head, EMPTY_TREE_SHA1_BIN);17921793if(clean_index(head, head))1794die(_("failed to clean index"));17951796am_next(state);1797am_run(state,0);1798}17991800/**1801 * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.1802 *1803 * It is not safe to reset HEAD when:1804 * 1. git-am previously failed because the index was dirty.1805 * 2. HEAD has moved since git-am previously failed.1806 */1807static intsafe_to_abort(const struct am_state *state)1808{1809struct strbuf sb = STRBUF_INIT;1810unsigned char abort_safety[GIT_SHA1_RAWSZ], head[GIT_SHA1_RAWSZ];18111812if(file_exists(am_path(state,"dirtyindex")))1813return0;18141815if(read_state_file(&sb, state,"abort-safety",1) >0) {1816if(get_sha1_hex(sb.buf, abort_safety))1817die(_("could not parse%s"),am_path(state,"abort_safety"));1818}else1819hashclr(abort_safety);18201821if(get_sha1("HEAD", head))1822hashclr(head);18231824if(!hashcmp(head, abort_safety))1825return1;18261827error(_("You seem to have moved HEAD since the last 'am' failure.\n"1828"Not rewinding to ORIG_HEAD"));18291830return0;1831}18321833/**1834 * Aborts the current am session if it is safe to do so.1835 */1836static voidam_abort(struct am_state *state)1837{1838unsigned char curr_head[GIT_SHA1_RAWSZ], orig_head[GIT_SHA1_RAWSZ];1839int has_curr_head, has_orig_head;1840char*curr_branch;18411842if(!safe_to_abort(state)) {1843am_destroy(state);1844return;1845}18461847am_rerere_clear();18481849 curr_branch =resolve_refdup("HEAD",0, curr_head, NULL);1850 has_curr_head = !is_null_sha1(curr_head);1851if(!has_curr_head)1852hashcpy(curr_head, EMPTY_TREE_SHA1_BIN);18531854 has_orig_head = !get_sha1("ORIG_HEAD", orig_head);1855if(!has_orig_head)1856hashcpy(orig_head, EMPTY_TREE_SHA1_BIN);18571858clean_index(curr_head, orig_head);18591860if(has_orig_head)1861update_ref("am --abort","HEAD", orig_head,1862 has_curr_head ? curr_head : NULL,0,1863 UPDATE_REFS_DIE_ON_ERR);1864else if(curr_branch)1865delete_ref(curr_branch, NULL, REF_NODEREF);18661867free(curr_branch);1868am_destroy(state);1869}18701871/**1872 * parse_options() callback that validates and sets opt->value to the1873 * PATCH_FORMAT_* enum value corresponding to `arg`.1874 */1875static intparse_opt_patchformat(const struct option *opt,const char*arg,int unset)1876{1877int*opt_value = opt->value;18781879if(!strcmp(arg,"mbox"))1880*opt_value = PATCH_FORMAT_MBOX;1881else if(!strcmp(arg,"stgit"))1882*opt_value = PATCH_FORMAT_STGIT;1883else1884returnerror(_("Invalid value for --patch-format:%s"), arg);1885return0;1886}18871888enum resume_mode {1889 RESUME_FALSE =0,1890 RESUME_APPLY,1891 RESUME_RESOLVED,1892 RESUME_SKIP,1893 RESUME_ABORT1894};18951896intcmd_am(int argc,const char**argv,const char*prefix)1897{1898struct am_state state;1899int keep_cr = -1;1900int patch_format = PATCH_FORMAT_UNKNOWN;1901enum resume_mode resume = RESUME_FALSE;19021903const char*const usage[] = {1904N_("git am [options] [(<mbox>|<Maildir>)...]"),1905N_("git am [options] (--continue | --skip | --abort)"),1906 NULL1907};19081909struct option options[] = {1910OPT_BOOL('3',"3way", &state.threeway,1911N_("allow fall back on 3way merging if needed")),1912OPT__QUIET(&state.quiet,N_("be quiet")),1913OPT_BOOL('s',"signoff", &state.signoff,1914N_("add a Signed-off-by line to the commit message")),1915OPT_BOOL('u',"utf8", &state.utf8,1916N_("recode into utf8 (default)")),1917OPT_SET_INT('k',"keep", &state.keep,1918N_("pass -k flag to git-mailinfo"), KEEP_TRUE),1919OPT_SET_INT(0,"keep-non-patch", &state.keep,1920N_("pass -b flag to git-mailinfo"), KEEP_NON_PATCH),1921OPT_BOOL('m',"message-id", &state.message_id,1922N_("pass -m flag to git-mailinfo")),1923{ OPTION_SET_INT,0,"keep-cr", &keep_cr, NULL,1924N_("pass --keep-cr flag to git-mailsplit for mbox format"),1925 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL,1},1926{ OPTION_SET_INT,0,"no-keep-cr", &keep_cr, NULL,1927N_("do not pass --keep-cr flag to git-mailsplit independent of am.keepcr"),1928 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL,0},1929OPT_BOOL('c',"scissors", &state.scissors,1930N_("strip everything before a scissors line")),1931OPT_PASSTHRU_ARGV(0,"whitespace", &state.git_apply_opts,N_("action"),1932N_("pass it through git-apply"),19330),1934OPT_PASSTHRU_ARGV(0,"ignore-space-change", &state.git_apply_opts, NULL,1935N_("pass it through git-apply"),1936 PARSE_OPT_NOARG),1937OPT_PASSTHRU_ARGV(0,"ignore-whitespace", &state.git_apply_opts, NULL,1938N_("pass it through git-apply"),1939 PARSE_OPT_NOARG),1940OPT_PASSTHRU_ARGV(0,"directory", &state.git_apply_opts,N_("root"),1941N_("pass it through git-apply"),19420),1943OPT_PASSTHRU_ARGV(0,"exclude", &state.git_apply_opts,N_("path"),1944N_("pass it through git-apply"),19450),1946OPT_PASSTHRU_ARGV(0,"include", &state.git_apply_opts,N_("path"),1947N_("pass it through git-apply"),19480),1949OPT_PASSTHRU_ARGV('C', NULL, &state.git_apply_opts,N_("n"),1950N_("pass it through git-apply"),19510),1952OPT_PASSTHRU_ARGV('p', NULL, &state.git_apply_opts,N_("num"),1953N_("pass it through git-apply"),19540),1955OPT_CALLBACK(0,"patch-format", &patch_format,N_("format"),1956N_("format the patch(es) are in"),1957 parse_opt_patchformat),1958OPT_PASSTHRU_ARGV(0,"reject", &state.git_apply_opts, NULL,1959N_("pass it through git-apply"),1960 PARSE_OPT_NOARG),1961OPT_STRING(0,"resolvemsg", &state.resolvemsg, NULL,1962N_("override error message when patch failure occurs")),1963OPT_CMDMODE(0,"continue", &resume,1964N_("continue applying patches after resolving a conflict"),1965 RESUME_RESOLVED),1966OPT_CMDMODE('r',"resolved", &resume,1967N_("synonyms for --continue"),1968 RESUME_RESOLVED),1969OPT_CMDMODE(0,"skip", &resume,1970N_("skip the current patch"),1971 RESUME_SKIP),1972OPT_CMDMODE(0,"abort", &resume,1973N_("restore the original branch and abort the patching operation."),1974 RESUME_ABORT),1975OPT_BOOL(0,"committer-date-is-author-date",1976&state.committer_date_is_author_date,1977N_("lie about committer date")),1978OPT_BOOL(0,"ignore-date", &state.ignore_date,1979N_("use current timestamp for author date")),1980OPT_RERERE_AUTOUPDATE(&state.allow_rerere_autoupdate),1981{ OPTION_STRING,'S',"gpg-sign", &state.sign_commit,N_("key-id"),1982N_("GPG-sign commits"),1983 PARSE_OPT_OPTARG, NULL, (intptr_t)""},1984OPT_HIDDEN_BOOL(0,"rebasing", &state.rebasing,1985N_("(internal use for git-rebase)")),1986OPT_END()1987};19881989/*1990 * NEEDSWORK: Once all the features of git-am.sh have been1991 * re-implemented in builtin/am.c, this preamble can be removed.1992 */1993if(!getenv("_GIT_USE_BUILTIN_AM")) {1994const char*path =mkpath("%s/git-am",git_exec_path());19951996if(sane_execvp(path, (char**)argv) <0)1997die_errno("could not exec%s", path);1998}else{1999 prefix =setup_git_directory();2000trace_repo_setup(prefix);2001setup_work_tree();2002}20032004git_config(git_default_config, NULL);20052006am_state_init(&state,git_path("rebase-apply"));20072008 argc =parse_options(argc, argv, prefix, options, usage,0);20092010if(read_index_preload(&the_index, NULL) <0)2011die(_("failed to read the index"));20122013if(am_in_progress(&state)) {2014/*2015 * Catch user error to feed us patches when there is a session2016 * in progress:2017 *2018 * 1. mbox path(s) are provided on the command-line.2019 * 2. stdin is not a tty: the user is trying to feed us a patch2020 * from standard input. This is somewhat unreliable -- stdin2021 * could be /dev/null for example and the caller did not2022 * intend to feed us a patch but wanted to continue2023 * unattended.2024 */2025if(argc || (resume == RESUME_FALSE && !isatty(0)))2026die(_("previous rebase directory%sstill exists but mbox given."),2027 state.dir);20282029if(resume == RESUME_FALSE)2030 resume = RESUME_APPLY;20312032am_load(&state);2033}else{2034struct argv_array paths = ARGV_ARRAY_INIT;2035int i;20362037/*2038 * Handle stray state directory in the independent-run case. In2039 * the --rebasing case, it is up to the caller to take care of2040 * stray directories.2041 */2042if(file_exists(state.dir) && !state.rebasing) {2043if(resume == RESUME_ABORT) {2044am_destroy(&state);2045am_state_release(&state);2046return0;2047}20482049die(_("Stray%sdirectory found.\n"2050"Use\"git am --abort\"to remove it."),2051 state.dir);2052}20532054if(resume)2055die(_("Resolve operation not in progress, we are not resuming."));20562057for(i =0; i < argc; i++) {2058if(is_absolute_path(argv[i]) || !prefix)2059argv_array_push(&paths, argv[i]);2060else2061argv_array_push(&paths,mkpath("%s/%s", prefix, argv[i]));2062}20632064am_setup(&state, patch_format, paths.argv, keep_cr);20652066argv_array_clear(&paths);2067}20682069switch(resume) {2070case RESUME_FALSE:2071am_run(&state,0);2072break;2073case RESUME_APPLY:2074am_run(&state,1);2075break;2076case RESUME_RESOLVED:2077am_resolve(&state);2078break;2079case RESUME_SKIP:2080am_skip(&state);2081break;2082case RESUME_ABORT:2083am_abort(&state);2084break;2085default:2086die("BUG: invalid resume value");2087}20882089am_state_release(&state);20902091return0;2092}