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 27/** 28 * Returns 1 if the file is empty or does not exist, 0 otherwise. 29 */ 30static intis_empty_file(const char*filename) 31{ 32struct stat st; 33 34if(stat(filename, &st) <0) { 35if(errno == ENOENT) 36return1; 37die_errno(_("could not stat%s"), filename); 38} 39 40return!st.st_size; 41} 42 43/** 44 * Like strbuf_getline(), but treats both '\n' and "\r\n" as line terminators. 45 */ 46static intstrbuf_getline_crlf(struct strbuf *sb,FILE*fp) 47{ 48if(strbuf_getwholeline(sb, fp,'\n')) 49return EOF; 50if(sb->buf[sb->len -1] =='\n') { 51strbuf_setlen(sb, sb->len -1); 52if(sb->len >0&& sb->buf[sb->len -1] =='\r') 53strbuf_setlen(sb, sb->len -1); 54} 55return0; 56} 57 58/** 59 * Returns the length of the first line of msg. 60 */ 61static intlinelen(const char*msg) 62{ 63returnstrchrnul(msg,'\n') - msg; 64} 65 66enum patch_format { 67 PATCH_FORMAT_UNKNOWN =0, 68 PATCH_FORMAT_MBOX 69}; 70 71enum keep_type { 72 KEEP_FALSE =0, 73 KEEP_TRUE,/* pass -k flag to git-mailinfo */ 74 KEEP_NON_PATCH /* pass -b flag to git-mailinfo */ 75}; 76 77struct am_state { 78/* state directory path */ 79char*dir; 80 81/* current and last patch numbers, 1-indexed */ 82int cur; 83int last; 84 85/* commit metadata and message */ 86char*author_name; 87char*author_email; 88char*author_date; 89char*msg; 90size_t msg_len; 91 92/* number of digits in patch filename */ 93int prec; 94 95/* various operating modes and command line options */ 96int threeway; 97int quiet; 98int signoff; 99int utf8; 100int keep;/* enum keep_type */ 101int message_id; 102const char*resolvemsg; 103int rebasing; 104}; 105 106/** 107 * Initializes am_state with the default values. The state directory is set to 108 * dir. 109 */ 110static voidam_state_init(struct am_state *state,const char*dir) 111{ 112memset(state,0,sizeof(*state)); 113 114assert(dir); 115 state->dir =xstrdup(dir); 116 117 state->prec =4; 118 119 state->utf8 =1; 120 121git_config_get_bool("am.messageid", &state->message_id); 122} 123 124/** 125 * Releases memory allocated by an am_state. 126 */ 127static voidam_state_release(struct am_state *state) 128{ 129free(state->dir); 130free(state->author_name); 131free(state->author_email); 132free(state->author_date); 133free(state->msg); 134} 135 136/** 137 * Returns path relative to the am_state directory. 138 */ 139staticinlineconst char*am_path(const struct am_state *state,const char*path) 140{ 141returnmkpath("%s/%s", state->dir, path); 142} 143 144/** 145 * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline 146 * at the end. 147 */ 148static voidsay(const struct am_state *state,FILE*fp,const char*fmt, ...) 149{ 150va_list ap; 151 152va_start(ap, fmt); 153if(!state->quiet) { 154vfprintf(fp, fmt, ap); 155putc('\n', fp); 156} 157va_end(ap); 158} 159 160/** 161 * Returns 1 if there is an am session in progress, 0 otherwise. 162 */ 163static intam_in_progress(const struct am_state *state) 164{ 165struct stat st; 166 167if(lstat(state->dir, &st) <0|| !S_ISDIR(st.st_mode)) 168return0; 169if(lstat(am_path(state,"last"), &st) || !S_ISREG(st.st_mode)) 170return0; 171if(lstat(am_path(state,"next"), &st) || !S_ISREG(st.st_mode)) 172return0; 173return1; 174} 175 176/** 177 * Reads the contents of `file` in the `state` directory into `sb`. Returns the 178 * number of bytes read on success, -1 if the file does not exist. If `trim` is 179 * set, trailing whitespace will be removed. 180 */ 181static intread_state_file(struct strbuf *sb,const struct am_state *state, 182const char*file,int trim) 183{ 184strbuf_reset(sb); 185 186if(strbuf_read_file(sb,am_path(state, file),0) >=0) { 187if(trim) 188strbuf_trim(sb); 189 190return sb->len; 191} 192 193if(errno == ENOENT) 194return-1; 195 196die_errno(_("could not read '%s'"),am_path(state, file)); 197} 198 199/** 200 * Reads a KEY=VALUE shell variable assignment from `fp`, returning the VALUE 201 * as a newly-allocated string. VALUE must be a quoted string, and the KEY must 202 * match `key`. Returns NULL on failure. 203 * 204 * This is used by read_author_script() to read the GIT_AUTHOR_* variables from 205 * the author-script. 206 */ 207static char*read_shell_var(FILE*fp,const char*key) 208{ 209struct strbuf sb = STRBUF_INIT; 210const char*str; 211 212if(strbuf_getline(&sb, fp,'\n')) 213goto fail; 214 215if(!skip_prefix(sb.buf, key, &str)) 216goto fail; 217 218if(!skip_prefix(str,"=", &str)) 219goto fail; 220 221strbuf_remove(&sb,0, str - sb.buf); 222 223 str =sq_dequote(sb.buf); 224if(!str) 225goto fail; 226 227returnstrbuf_detach(&sb, NULL); 228 229fail: 230strbuf_release(&sb); 231return NULL; 232} 233 234/** 235 * Reads and parses the state directory's "author-script" file, and sets 236 * state->author_name, state->author_email and state->author_date accordingly. 237 * Returns 0 on success, -1 if the file could not be parsed. 238 * 239 * The author script is of the format: 240 * 241 * GIT_AUTHOR_NAME='$author_name' 242 * GIT_AUTHOR_EMAIL='$author_email' 243 * GIT_AUTHOR_DATE='$author_date' 244 * 245 * where $author_name, $author_email and $author_date are quoted. We are strict 246 * with our parsing, as the file was meant to be eval'd in the old git-am.sh 247 * script, and thus if the file differs from what this function expects, it is 248 * better to bail out than to do something that the user does not expect. 249 */ 250static intread_author_script(struct am_state *state) 251{ 252const char*filename =am_path(state,"author-script"); 253FILE*fp; 254 255assert(!state->author_name); 256assert(!state->author_email); 257assert(!state->author_date); 258 259 fp =fopen(filename,"r"); 260if(!fp) { 261if(errno == ENOENT) 262return0; 263die_errno(_("could not open '%s' for reading"), filename); 264} 265 266 state->author_name =read_shell_var(fp,"GIT_AUTHOR_NAME"); 267if(!state->author_name) { 268fclose(fp); 269return-1; 270} 271 272 state->author_email =read_shell_var(fp,"GIT_AUTHOR_EMAIL"); 273if(!state->author_email) { 274fclose(fp); 275return-1; 276} 277 278 state->author_date =read_shell_var(fp,"GIT_AUTHOR_DATE"); 279if(!state->author_date) { 280fclose(fp); 281return-1; 282} 283 284if(fgetc(fp) != EOF) { 285fclose(fp); 286return-1; 287} 288 289fclose(fp); 290return0; 291} 292 293/** 294 * Saves state->author_name, state->author_email and state->author_date in the 295 * state directory's "author-script" file. 296 */ 297static voidwrite_author_script(const struct am_state *state) 298{ 299struct strbuf sb = STRBUF_INIT; 300 301strbuf_addstr(&sb,"GIT_AUTHOR_NAME="); 302sq_quote_buf(&sb, state->author_name); 303strbuf_addch(&sb,'\n'); 304 305strbuf_addstr(&sb,"GIT_AUTHOR_EMAIL="); 306sq_quote_buf(&sb, state->author_email); 307strbuf_addch(&sb,'\n'); 308 309strbuf_addstr(&sb,"GIT_AUTHOR_DATE="); 310sq_quote_buf(&sb, state->author_date); 311strbuf_addch(&sb,'\n'); 312 313write_file(am_path(state,"author-script"),1,"%s", sb.buf); 314 315strbuf_release(&sb); 316} 317 318/** 319 * Reads the commit message from the state directory's "final-commit" file, 320 * setting state->msg to its contents and state->msg_len to the length of its 321 * contents in bytes. 322 * 323 * Returns 0 on success, -1 if the file does not exist. 324 */ 325static intread_commit_msg(struct am_state *state) 326{ 327struct strbuf sb = STRBUF_INIT; 328 329assert(!state->msg); 330 331if(read_state_file(&sb, state,"final-commit",0) <0) { 332strbuf_release(&sb); 333return-1; 334} 335 336 state->msg =strbuf_detach(&sb, &state->msg_len); 337return0; 338} 339 340/** 341 * Saves state->msg in the state directory's "final-commit" file. 342 */ 343static voidwrite_commit_msg(const struct am_state *state) 344{ 345int fd; 346const char*filename =am_path(state,"final-commit"); 347 348 fd =xopen(filename, O_WRONLY | O_CREAT,0666); 349if(write_in_full(fd, state->msg, state->msg_len) <0) 350die_errno(_("could not write to%s"), filename); 351close(fd); 352} 353 354/** 355 * Loads state from disk. 356 */ 357static voidam_load(struct am_state *state) 358{ 359struct strbuf sb = STRBUF_INIT; 360 361if(read_state_file(&sb, state,"next",1) <0) 362die("BUG: state file 'next' does not exist"); 363 state->cur =strtol(sb.buf, NULL,10); 364 365if(read_state_file(&sb, state,"last",1) <0) 366die("BUG: state file 'last' does not exist"); 367 state->last =strtol(sb.buf, NULL,10); 368 369if(read_author_script(state) <0) 370die(_("could not parse author script")); 371 372read_commit_msg(state); 373 374read_state_file(&sb, state,"threeway",1); 375 state->threeway = !strcmp(sb.buf,"t"); 376 377read_state_file(&sb, state,"quiet",1); 378 state->quiet = !strcmp(sb.buf,"t"); 379 380read_state_file(&sb, state,"sign",1); 381 state->signoff = !strcmp(sb.buf,"t"); 382 383read_state_file(&sb, state,"utf8",1); 384 state->utf8 = !strcmp(sb.buf,"t"); 385 386read_state_file(&sb, state,"keep",1); 387if(!strcmp(sb.buf,"t")) 388 state->keep = KEEP_TRUE; 389else if(!strcmp(sb.buf,"b")) 390 state->keep = KEEP_NON_PATCH; 391else 392 state->keep = KEEP_FALSE; 393 394read_state_file(&sb, state,"messageid",1); 395 state->message_id = !strcmp(sb.buf,"t"); 396 397 state->rebasing = !!file_exists(am_path(state,"rebasing")); 398 399strbuf_release(&sb); 400} 401 402/** 403 * Removes the am_state directory, forcefully terminating the current am 404 * session. 405 */ 406static voidam_destroy(const struct am_state *state) 407{ 408struct strbuf sb = STRBUF_INIT; 409 410strbuf_addstr(&sb, state->dir); 411remove_dir_recursively(&sb,0); 412strbuf_release(&sb); 413} 414 415/** 416 * Determines if the file looks like a piece of RFC2822 mail by grabbing all 417 * non-indented lines and checking if they look like they begin with valid 418 * header field names. 419 * 420 * Returns 1 if the file looks like a piece of mail, 0 otherwise. 421 */ 422static intis_mail(FILE*fp) 423{ 424const char*header_regex ="^[!-9;-~]+:"; 425struct strbuf sb = STRBUF_INIT; 426 regex_t regex; 427int ret =1; 428 429if(fseek(fp,0L, SEEK_SET)) 430die_errno(_("fseek failed")); 431 432if(regcomp(®ex, header_regex, REG_NOSUB | REG_EXTENDED)) 433die("invalid pattern:%s", header_regex); 434 435while(!strbuf_getline_crlf(&sb, fp)) { 436if(!sb.len) 437break;/* End of header */ 438 439/* Ignore indented folded lines */ 440if(*sb.buf =='\t'|| *sb.buf ==' ') 441continue; 442 443/* It's a header if it matches header_regex */ 444if(regexec(®ex, sb.buf,0, NULL,0)) { 445 ret =0; 446goto done; 447} 448} 449 450done: 451regfree(®ex); 452strbuf_release(&sb); 453return ret; 454} 455 456/** 457 * Attempts to detect the patch_format of the patches contained in `paths`, 458 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if 459 * detection fails. 460 */ 461static intdetect_patch_format(const char**paths) 462{ 463enum patch_format ret = PATCH_FORMAT_UNKNOWN; 464struct strbuf l1 = STRBUF_INIT; 465FILE*fp; 466 467/* 468 * We default to mbox format if input is from stdin and for directories 469 */ 470if(!*paths || !strcmp(*paths,"-") ||is_directory(*paths)) 471return PATCH_FORMAT_MBOX; 472 473/* 474 * Otherwise, check the first few lines of the first patch, starting 475 * from the first non-blank line, to try to detect its format. 476 */ 477 478 fp =xfopen(*paths,"r"); 479 480while(!strbuf_getline_crlf(&l1, fp)) { 481if(l1.len) 482break; 483} 484 485if(starts_with(l1.buf,"From ") ||starts_with(l1.buf,"From: ")) { 486 ret = PATCH_FORMAT_MBOX; 487goto done; 488} 489 490if(l1.len &&is_mail(fp)) { 491 ret = PATCH_FORMAT_MBOX; 492goto done; 493} 494 495done: 496fclose(fp); 497strbuf_release(&l1); 498return ret; 499} 500 501/** 502 * Splits out individual email patches from `paths`, where each path is either 503 * a mbox file or a Maildir. Returns 0 on success, -1 on failure. 504 */ 505static intsplit_mail_mbox(struct am_state *state,const char**paths) 506{ 507struct child_process cp = CHILD_PROCESS_INIT; 508struct strbuf last = STRBUF_INIT; 509 510 cp.git_cmd =1; 511argv_array_push(&cp.args,"mailsplit"); 512argv_array_pushf(&cp.args,"-d%d", state->prec); 513argv_array_pushf(&cp.args,"-o%s", state->dir); 514argv_array_push(&cp.args,"-b"); 515argv_array_push(&cp.args,"--"); 516argv_array_pushv(&cp.args, paths); 517 518if(capture_command(&cp, &last,8)) 519return-1; 520 521 state->cur =1; 522 state->last =strtol(last.buf, NULL,10); 523 524return0; 525} 526 527/** 528 * Splits a list of files/directories into individual email patches. Each path 529 * in `paths` must be a file/directory that is formatted according to 530 * `patch_format`. 531 * 532 * Once split out, the individual email patches will be stored in the state 533 * directory, with each patch's filename being its index, padded to state->prec 534 * digits. 535 * 536 * state->cur will be set to the index of the first mail, and state->last will 537 * be set to the index of the last mail. 538 * 539 * Returns 0 on success, -1 on failure. 540 */ 541static intsplit_mail(struct am_state *state,enum patch_format patch_format, 542const char**paths) 543{ 544switch(patch_format) { 545case PATCH_FORMAT_MBOX: 546returnsplit_mail_mbox(state, paths); 547default: 548die("BUG: invalid patch_format"); 549} 550return-1; 551} 552 553/** 554 * Setup a new am session for applying patches 555 */ 556static voidam_setup(struct am_state *state,enum patch_format patch_format, 557const char**paths) 558{ 559unsigned char curr_head[GIT_SHA1_RAWSZ]; 560const char*str; 561 562if(!patch_format) 563 patch_format =detect_patch_format(paths); 564 565if(!patch_format) { 566fprintf_ln(stderr,_("Patch format detection failed.")); 567exit(128); 568} 569 570if(mkdir(state->dir,0777) <0&& errno != EEXIST) 571die_errno(_("failed to create directory '%s'"), state->dir); 572 573if(split_mail(state, patch_format, paths) <0) { 574am_destroy(state); 575die(_("Failed to split patches.")); 576} 577 578if(state->rebasing) 579 state->threeway =1; 580 581write_file(am_path(state,"threeway"),1, state->threeway ?"t":"f"); 582 583write_file(am_path(state,"quiet"),1, state->quiet ?"t":"f"); 584 585write_file(am_path(state,"sign"),1, state->signoff ?"t":"f"); 586 587write_file(am_path(state,"utf8"),1, state->utf8 ?"t":"f"); 588 589switch(state->keep) { 590case KEEP_FALSE: 591 str ="f"; 592break; 593case KEEP_TRUE: 594 str ="t"; 595break; 596case KEEP_NON_PATCH: 597 str ="b"; 598break; 599default: 600die("BUG: invalid value for state->keep"); 601} 602 603write_file(am_path(state,"keep"),1,"%s", str); 604 605write_file(am_path(state,"messageid"),1, state->message_id ?"t":"f"); 606 607if(state->rebasing) 608write_file(am_path(state,"rebasing"),1,"%s",""); 609else 610write_file(am_path(state,"applying"),1,"%s",""); 611 612if(!get_sha1("HEAD", curr_head)) { 613write_file(am_path(state,"abort-safety"),1,"%s",sha1_to_hex(curr_head)); 614if(!state->rebasing) 615update_ref("am","ORIG_HEAD", curr_head, NULL,0, 616 UPDATE_REFS_DIE_ON_ERR); 617}else{ 618write_file(am_path(state,"abort-safety"),1,"%s",""); 619if(!state->rebasing) 620delete_ref("ORIG_HEAD", NULL,0); 621} 622 623/* 624 * NOTE: Since the "next" and "last" files determine if an am_state 625 * session is in progress, they should be written last. 626 */ 627 628write_file(am_path(state,"next"),1,"%d", state->cur); 629 630write_file(am_path(state,"last"),1,"%d", state->last); 631} 632 633/** 634 * Increments the patch pointer, and cleans am_state for the application of the 635 * next patch. 636 */ 637static voidam_next(struct am_state *state) 638{ 639unsigned char head[GIT_SHA1_RAWSZ]; 640 641free(state->author_name); 642 state->author_name = NULL; 643 644free(state->author_email); 645 state->author_email = NULL; 646 647free(state->author_date); 648 state->author_date = NULL; 649 650free(state->msg); 651 state->msg = NULL; 652 state->msg_len =0; 653 654unlink(am_path(state,"author-script")); 655unlink(am_path(state,"final-commit")); 656 657if(!get_sha1("HEAD", head)) 658write_file(am_path(state,"abort-safety"),1,"%s",sha1_to_hex(head)); 659else 660write_file(am_path(state,"abort-safety"),1,"%s",""); 661 662 state->cur++; 663write_file(am_path(state,"next"),1,"%d", state->cur); 664} 665 666/** 667 * Returns the filename of the current patch email. 668 */ 669static const char*msgnum(const struct am_state *state) 670{ 671static struct strbuf sb = STRBUF_INIT; 672 673strbuf_reset(&sb); 674strbuf_addf(&sb,"%0*d", state->prec, state->cur); 675 676return sb.buf; 677} 678 679/** 680 * Refresh and write index. 681 */ 682static voidrefresh_and_write_cache(void) 683{ 684struct lock_file *lock_file =xcalloc(1,sizeof(struct lock_file)); 685 686hold_locked_index(lock_file,1); 687refresh_cache(REFRESH_QUIET); 688if(write_locked_index(&the_index, lock_file, COMMIT_LOCK)) 689die(_("unable to write index file")); 690} 691 692/** 693 * Returns 1 if the index differs from HEAD, 0 otherwise. When on an unborn 694 * branch, returns 1 if there are entries in the index, 0 otherwise. If an 695 * strbuf is provided, the space-separated list of files that differ will be 696 * appended to it. 697 */ 698static intindex_has_changes(struct strbuf *sb) 699{ 700unsigned char head[GIT_SHA1_RAWSZ]; 701int i; 702 703if(!get_sha1_tree("HEAD", head)) { 704struct diff_options opt; 705 706diff_setup(&opt); 707DIFF_OPT_SET(&opt, EXIT_WITH_STATUS); 708if(!sb) 709DIFF_OPT_SET(&opt, QUICK); 710do_diff_cache(head, &opt); 711diffcore_std(&opt); 712for(i =0; sb && i < diff_queued_diff.nr; i++) { 713if(i) 714strbuf_addch(sb,' '); 715strbuf_addstr(sb, diff_queued_diff.queue[i]->two->path); 716} 717diff_flush(&opt); 718returnDIFF_OPT_TST(&opt, HAS_CHANGES) !=0; 719}else{ 720for(i =0; sb && i < active_nr; i++) { 721if(i) 722strbuf_addch(sb,' '); 723strbuf_addstr(sb, active_cache[i]->name); 724} 725return!!active_nr; 726} 727} 728 729/** 730 * Dies with a user-friendly message on how to proceed after resolving the 731 * problem. This message can be overridden with state->resolvemsg. 732 */ 733static void NORETURN die_user_resolve(const struct am_state *state) 734{ 735if(state->resolvemsg) { 736printf_ln("%s", state->resolvemsg); 737}else{ 738const char*cmdline ="git am"; 739 740printf_ln(_("When you have resolved this problem, run\"%s--continue\"."), cmdline); 741printf_ln(_("If you prefer to skip this patch, run\"%s--skip\"instead."), cmdline); 742printf_ln(_("To restore the original branch and stop patching, run\"%s--abort\"."), cmdline); 743} 744 745exit(128); 746} 747 748/** 749 * Parses `mail` using git-mailinfo, extracting its patch and authorship info. 750 * state->msg will be set to the patch message. state->author_name, 751 * state->author_email and state->author_date will be set to the patch author's 752 * name, email and date respectively. The patch body will be written to the 753 * state directory's "patch" file. 754 * 755 * Returns 1 if the patch should be skipped, 0 otherwise. 756 */ 757static intparse_mail(struct am_state *state,const char*mail) 758{ 759FILE*fp; 760struct child_process cp = CHILD_PROCESS_INIT; 761struct strbuf sb = STRBUF_INIT; 762struct strbuf msg = STRBUF_INIT; 763struct strbuf author_name = STRBUF_INIT; 764struct strbuf author_date = STRBUF_INIT; 765struct strbuf author_email = STRBUF_INIT; 766int ret =0; 767 768 cp.git_cmd =1; 769 cp.in =xopen(mail, O_RDONLY,0); 770 cp.out =xopen(am_path(state,"info"), O_WRONLY | O_CREAT,0777); 771 772argv_array_push(&cp.args,"mailinfo"); 773argv_array_push(&cp.args, state->utf8 ?"-u":"-n"); 774 775switch(state->keep) { 776case KEEP_FALSE: 777break; 778case KEEP_TRUE: 779argv_array_push(&cp.args,"-k"); 780break; 781case KEEP_NON_PATCH: 782argv_array_push(&cp.args,"-b"); 783break; 784default: 785die("BUG: invalid value for state->keep"); 786} 787 788if(state->message_id) 789argv_array_push(&cp.args,"-m"); 790 791argv_array_push(&cp.args,am_path(state,"msg")); 792argv_array_push(&cp.args,am_path(state,"patch")); 793 794if(run_command(&cp) <0) 795die("could not parse patch"); 796 797close(cp.in); 798close(cp.out); 799 800/* Extract message and author information */ 801 fp =xfopen(am_path(state,"info"),"r"); 802while(!strbuf_getline(&sb, fp,'\n')) { 803const char*x; 804 805if(skip_prefix(sb.buf,"Subject: ", &x)) { 806if(msg.len) 807strbuf_addch(&msg,'\n'); 808strbuf_addstr(&msg, x); 809}else if(skip_prefix(sb.buf,"Author: ", &x)) 810strbuf_addstr(&author_name, x); 811else if(skip_prefix(sb.buf,"Email: ", &x)) 812strbuf_addstr(&author_email, x); 813else if(skip_prefix(sb.buf,"Date: ", &x)) 814strbuf_addstr(&author_date, x); 815} 816fclose(fp); 817 818/* Skip pine's internal folder data */ 819if(!strcmp(author_name.buf,"Mail System Internal Data")) { 820 ret =1; 821goto finish; 822} 823 824if(is_empty_file(am_path(state,"patch"))) { 825printf_ln(_("Patch is empty. Was it split wrong?")); 826die_user_resolve(state); 827} 828 829strbuf_addstr(&msg,"\n\n"); 830if(strbuf_read_file(&msg,am_path(state,"msg"),0) <0) 831die_errno(_("could not read '%s'"),am_path(state,"msg")); 832stripspace(&msg,0); 833 834if(state->signoff) 835append_signoff(&msg,0,0); 836 837assert(!state->author_name); 838 state->author_name =strbuf_detach(&author_name, NULL); 839 840assert(!state->author_email); 841 state->author_email =strbuf_detach(&author_email, NULL); 842 843assert(!state->author_date); 844 state->author_date =strbuf_detach(&author_date, NULL); 845 846assert(!state->msg); 847 state->msg =strbuf_detach(&msg, &state->msg_len); 848 849finish: 850strbuf_release(&msg); 851strbuf_release(&author_date); 852strbuf_release(&author_email); 853strbuf_release(&author_name); 854strbuf_release(&sb); 855return ret; 856} 857 858/** 859 * Sets commit_id to the commit hash where the mail was generated from. 860 * Returns 0 on success, -1 on failure. 861 */ 862static intget_mail_commit_sha1(unsigned char*commit_id,const char*mail) 863{ 864struct strbuf sb = STRBUF_INIT; 865FILE*fp =xfopen(mail,"r"); 866const char*x; 867 868if(strbuf_getline(&sb, fp,'\n')) 869return-1; 870 871if(!skip_prefix(sb.buf,"From ", &x)) 872return-1; 873 874if(get_sha1_hex(x, commit_id) <0) 875return-1; 876 877strbuf_release(&sb); 878fclose(fp); 879return0; 880} 881 882/** 883 * Sets state->msg, state->author_name, state->author_email, state->author_date 884 * to the commit's respective info. 885 */ 886static voidget_commit_info(struct am_state *state,struct commit *commit) 887{ 888const char*buffer, *ident_line, *author_date, *msg; 889size_t ident_len; 890struct ident_split ident_split; 891struct strbuf sb = STRBUF_INIT; 892 893 buffer =logmsg_reencode(commit, NULL,get_commit_output_encoding()); 894 895 ident_line =find_commit_header(buffer,"author", &ident_len); 896 897if(split_ident_line(&ident_split, ident_line, ident_len) <0) { 898strbuf_add(&sb, ident_line, ident_len); 899die(_("invalid ident line:%s"), sb.buf); 900} 901 902assert(!state->author_name); 903if(ident_split.name_begin) { 904strbuf_add(&sb, ident_split.name_begin, 905 ident_split.name_end - ident_split.name_begin); 906 state->author_name =strbuf_detach(&sb, NULL); 907}else 908 state->author_name =xstrdup(""); 909 910assert(!state->author_email); 911if(ident_split.mail_begin) { 912strbuf_add(&sb, ident_split.mail_begin, 913 ident_split.mail_end - ident_split.mail_begin); 914 state->author_email =strbuf_detach(&sb, NULL); 915}else 916 state->author_email =xstrdup(""); 917 918 author_date =show_ident_date(&ident_split,DATE_MODE(NORMAL)); 919strbuf_addstr(&sb, author_date); 920assert(!state->author_date); 921 state->author_date =strbuf_detach(&sb, NULL); 922 923assert(!state->msg); 924 msg =strstr(buffer,"\n\n"); 925if(!msg) 926die(_("unable to parse commit%s"),sha1_to_hex(commit->object.sha1)); 927 state->msg =xstrdup(msg +2); 928 state->msg_len =strlen(state->msg); 929} 930 931/** 932 * Writes `commit` as a patch to the state directory's "patch" file. 933 */ 934static voidwrite_commit_patch(const struct am_state *state,struct commit *commit) 935{ 936struct rev_info rev_info; 937FILE*fp; 938 939 fp =xfopen(am_path(state,"patch"),"w"); 940init_revisions(&rev_info, NULL); 941 rev_info.diff =1; 942 rev_info.abbrev =0; 943 rev_info.disable_stdin =1; 944 rev_info.show_root_diff =1; 945 rev_info.diffopt.output_format = DIFF_FORMAT_PATCH; 946 rev_info.no_commit_id =1; 947DIFF_OPT_SET(&rev_info.diffopt, BINARY); 948DIFF_OPT_SET(&rev_info.diffopt, FULL_INDEX); 949 rev_info.diffopt.use_color =0; 950 rev_info.diffopt.file = fp; 951 rev_info.diffopt.close_file =1; 952add_pending_object(&rev_info, &commit->object,""); 953diff_setup_done(&rev_info.diffopt); 954log_tree_commit(&rev_info, commit); 955} 956 957/** 958 * Like parse_mail(), but parses the mail by looking up its commit ID 959 * directly. This is used in --rebasing mode to bypass git-mailinfo's munging 960 * of patches. 961 * 962 * Will always return 0 as the patch should never be skipped. 963 */ 964static intparse_mail_rebase(struct am_state *state,const char*mail) 965{ 966struct commit *commit; 967unsigned char commit_sha1[GIT_SHA1_RAWSZ]; 968 969if(get_mail_commit_sha1(commit_sha1, mail) <0) 970die(_("could not parse%s"), mail); 971 972 commit =lookup_commit_or_die(commit_sha1, mail); 973 974get_commit_info(state, commit); 975 976write_commit_patch(state, commit); 977 978return0; 979} 980 981/** 982 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If 983 * `index_file` is not NULL, the patch will be applied to that index. 984 */ 985static intrun_apply(const struct am_state *state,const char*index_file) 986{ 987struct child_process cp = CHILD_PROCESS_INIT; 988 989 cp.git_cmd =1; 990 991if(index_file) 992argv_array_pushf(&cp.env_array,"GIT_INDEX_FILE=%s", index_file); 993 994/* 995 * If we are allowed to fall back on 3-way merge, don't give false 996 * errors during the initial attempt. 997 */ 998if(state->threeway && !index_file) { 999 cp.no_stdout =1;1000 cp.no_stderr =1;1001}10021003argv_array_push(&cp.args,"apply");10041005if(index_file)1006argv_array_push(&cp.args,"--cached");1007else1008argv_array_push(&cp.args,"--index");10091010argv_array_push(&cp.args,am_path(state,"patch"));10111012if(run_command(&cp))1013return-1;10141015/* Reload index as git-apply will have modified it. */1016discard_cache();1017read_cache_from(index_file ? index_file :get_index_file());10181019return0;1020}10211022/**1023 * Builds an index that contains just the blobs needed for a 3way merge.1024 */1025static intbuild_fake_ancestor(const struct am_state *state,const char*index_file)1026{1027struct child_process cp = CHILD_PROCESS_INIT;10281029 cp.git_cmd =1;1030argv_array_push(&cp.args,"apply");1031argv_array_pushf(&cp.args,"--build-fake-ancestor=%s", index_file);1032argv_array_push(&cp.args,am_path(state,"patch"));10331034if(run_command(&cp))1035return-1;10361037return0;1038}10391040/**1041 * Attempt a threeway merge, using index_path as the temporary index.1042 */1043static intfall_back_threeway(const struct am_state *state,const char*index_path)1044{1045unsigned char orig_tree[GIT_SHA1_RAWSZ], his_tree[GIT_SHA1_RAWSZ],1046 our_tree[GIT_SHA1_RAWSZ];1047const unsigned char*bases[1] = {orig_tree};1048struct merge_options o;1049struct commit *result;1050char*his_tree_name;10511052if(get_sha1("HEAD", our_tree) <0)1053hashcpy(our_tree, EMPTY_TREE_SHA1_BIN);10541055if(build_fake_ancestor(state, index_path))1056returnerror("could not build fake ancestor");10571058discard_cache();1059read_cache_from(index_path);10601061if(write_index_as_tree(orig_tree, &the_index, index_path,0, NULL))1062returnerror(_("Repository lacks necessary blobs to fall back on 3-way merge."));10631064say(state, stdout,_("Using index info to reconstruct a base tree..."));10651066if(!state->quiet) {1067/*1068 * List paths that needed 3-way fallback, so that the user can1069 * review them with extra care to spot mismerges.1070 */1071struct rev_info rev_info;1072const char*diff_filter_str ="--diff-filter=AM";10731074init_revisions(&rev_info, NULL);1075 rev_info.diffopt.output_format = DIFF_FORMAT_NAME_STATUS;1076diff_opt_parse(&rev_info.diffopt, &diff_filter_str,1);1077add_pending_sha1(&rev_info,"HEAD", our_tree,0);1078diff_setup_done(&rev_info.diffopt);1079run_diff_index(&rev_info,1);1080}10811082if(run_apply(state, index_path))1083returnerror(_("Did you hand edit your patch?\n"1084"It does not apply to blobs recorded in its index."));10851086if(write_index_as_tree(his_tree, &the_index, index_path,0, NULL))1087returnerror("could not write tree");10881089say(state, stdout,_("Falling back to patching base and 3-way merge..."));10901091discard_cache();1092read_cache();10931094/*1095 * This is not so wrong. Depending on which base we picked, orig_tree1096 * may be wildly different from ours, but his_tree has the same set of1097 * wildly different changes in parts the patch did not touch, so1098 * recursive ends up canceling them, saying that we reverted all those1099 * changes.1100 */11011102init_merge_options(&o);11031104 o.branch1 ="HEAD";1105 his_tree_name =xstrfmt("%.*s",linelen(state->msg), state->msg);1106 o.branch2 = his_tree_name;11071108if(state->quiet)1109 o.verbosity =0;11101111if(merge_recursive_generic(&o, our_tree, his_tree,1, bases, &result)) {1112free(his_tree_name);1113returnerror(_("Failed to merge in the changes."));1114}11151116free(his_tree_name);1117return0;1118}11191120/**1121 * Commits the current index with state->msg as the commit message and1122 * state->author_name, state->author_email and state->author_date as the author1123 * information.1124 */1125static voiddo_commit(const struct am_state *state)1126{1127unsigned char tree[GIT_SHA1_RAWSZ], parent[GIT_SHA1_RAWSZ],1128 commit[GIT_SHA1_RAWSZ];1129unsigned char*ptr;1130struct commit_list *parents = NULL;1131const char*reflog_msg, *author;1132struct strbuf sb = STRBUF_INIT;11331134if(write_cache_as_tree(tree,0, NULL))1135die(_("git write-tree failed to write a tree"));11361137if(!get_sha1_commit("HEAD", parent)) {1138 ptr = parent;1139commit_list_insert(lookup_commit(parent), &parents);1140}else{1141 ptr = NULL;1142say(state, stderr,_("applying to an empty history"));1143}11441145 author =fmt_ident(state->author_name, state->author_email,1146 state->author_date, IDENT_STRICT);11471148if(commit_tree(state->msg, state->msg_len, tree, parents, commit,1149 author, NULL))1150die(_("failed to write commit object"));11511152 reflog_msg =getenv("GIT_REFLOG_ACTION");1153if(!reflog_msg)1154 reflog_msg ="am";11551156strbuf_addf(&sb,"%s: %.*s", reflog_msg,linelen(state->msg),1157 state->msg);11581159update_ref(sb.buf,"HEAD", commit, ptr,0, UPDATE_REFS_DIE_ON_ERR);11601161strbuf_release(&sb);1162}11631164/**1165 * Validates the am_state for resuming -- the "msg" and authorship fields must1166 * be filled up.1167 */1168static voidvalidate_resume_state(const struct am_state *state)1169{1170if(!state->msg)1171die(_("cannot resume:%sdoes not exist."),1172am_path(state,"final-commit"));11731174if(!state->author_name || !state->author_email || !state->author_date)1175die(_("cannot resume:%sdoes not exist."),1176am_path(state,"author-script"));1177}11781179/**1180 * Applies all queued mail.1181 *1182 * If `resume` is true, we are "resuming". The "msg" and authorship fields, as1183 * well as the state directory's "patch" file is used as-is for applying the1184 * patch and committing it.1185 */1186static voidam_run(struct am_state *state,int resume)1187{1188const char*argv_gc_auto[] = {"gc","--auto", NULL};1189struct strbuf sb = STRBUF_INIT;11901191unlink(am_path(state,"dirtyindex"));11921193refresh_and_write_cache();11941195if(index_has_changes(&sb)) {1196write_file(am_path(state,"dirtyindex"),1,"t");1197die(_("Dirty index: cannot apply patches (dirty:%s)"), sb.buf);1198}11991200strbuf_release(&sb);12011202while(state->cur <= state->last) {1203const char*mail =am_path(state,msgnum(state));1204int apply_status;12051206if(!file_exists(mail))1207goto next;12081209if(resume) {1210validate_resume_state(state);1211 resume =0;1212}else{1213int skip;12141215if(state->rebasing)1216 skip =parse_mail_rebase(state, mail);1217else1218 skip =parse_mail(state, mail);12191220if(skip)1221goto next;/* mail should be skipped */12221223write_author_script(state);1224write_commit_msg(state);1225}12261227say(state, stdout,_("Applying: %.*s"),linelen(state->msg), state->msg);12281229 apply_status =run_apply(state, NULL);12301231if(apply_status && state->threeway) {1232struct strbuf sb = STRBUF_INIT;12331234strbuf_addstr(&sb,am_path(state,"patch-merge-index"));1235 apply_status =fall_back_threeway(state, sb.buf);1236strbuf_release(&sb);12371238/*1239 * Applying the patch to an earlier tree and merging1240 * the result may have produced the same tree as ours.1241 */1242if(!apply_status && !index_has_changes(NULL)) {1243say(state, stdout,_("No changes -- Patch already applied."));1244goto next;1245}1246}12471248if(apply_status) {1249int advice_amworkdir =1;12501251printf_ln(_("Patch failed at%s%.*s"),msgnum(state),1252linelen(state->msg), state->msg);12531254git_config_get_bool("advice.amworkdir", &advice_amworkdir);12551256if(advice_amworkdir)1257printf_ln(_("The copy of the patch that failed is found in:%s"),1258am_path(state,"patch"));12591260die_user_resolve(state);1261}12621263do_commit(state);12641265next:1266am_next(state);1267}12681269/*1270 * In rebasing mode, it's up to the caller to take care of1271 * housekeeping.1272 */1273if(!state->rebasing) {1274am_destroy(state);1275run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);1276}1277}12781279/**1280 * Resume the current am session after patch application failure. The user did1281 * all the hard work, and we do not have to do any patch application. Just1282 * trust and commit what the user has in the index and working tree.1283 */1284static voidam_resolve(struct am_state *state)1285{1286validate_resume_state(state);12871288say(state, stdout,_("Applying: %.*s"),linelen(state->msg), state->msg);12891290if(!index_has_changes(NULL)) {1291printf_ln(_("No changes - did you forget to use 'git add'?\n"1292"If there is nothing left to stage, chances are that something else\n"1293"already introduced the same changes; you might want to skip this patch."));1294die_user_resolve(state);1295}12961297if(unmerged_cache()) {1298printf_ln(_("You still have unmerged paths in your index.\n"1299"Did you forget to use 'git add'?"));1300die_user_resolve(state);1301}13021303do_commit(state);13041305am_next(state);1306am_run(state,0);1307}13081309/**1310 * Performs a checkout fast-forward from `head` to `remote`. If `reset` is1311 * true, any unmerged entries will be discarded. Returns 0 on success, -1 on1312 * failure.1313 */1314static intfast_forward_to(struct tree *head,struct tree *remote,int reset)1315{1316struct lock_file *lock_file;1317struct unpack_trees_options opts;1318struct tree_desc t[2];13191320if(parse_tree(head) ||parse_tree(remote))1321return-1;13221323 lock_file =xcalloc(1,sizeof(struct lock_file));1324hold_locked_index(lock_file,1);13251326refresh_cache(REFRESH_QUIET);13271328memset(&opts,0,sizeof(opts));1329 opts.head_idx =1;1330 opts.src_index = &the_index;1331 opts.dst_index = &the_index;1332 opts.update =1;1333 opts.merge =1;1334 opts.reset = reset;1335 opts.fn = twoway_merge;1336init_tree_desc(&t[0], head->buffer, head->size);1337init_tree_desc(&t[1], remote->buffer, remote->size);13381339if(unpack_trees(2, t, &opts)) {1340rollback_lock_file(lock_file);1341return-1;1342}13431344if(write_locked_index(&the_index, lock_file, COMMIT_LOCK))1345die(_("unable to write new index file"));13461347return0;1348}13491350/**1351 * Clean the index without touching entries that are not modified between1352 * `head` and `remote`.1353 */1354static intclean_index(const unsigned char*head,const unsigned char*remote)1355{1356struct lock_file *lock_file;1357struct tree *head_tree, *remote_tree, *index_tree;1358unsigned char index[GIT_SHA1_RAWSZ];1359struct pathspec pathspec;13601361 head_tree =parse_tree_indirect(head);1362if(!head_tree)1363returnerror(_("Could not parse object '%s'."),sha1_to_hex(head));13641365 remote_tree =parse_tree_indirect(remote);1366if(!remote_tree)1367returnerror(_("Could not parse object '%s'."),sha1_to_hex(remote));13681369read_cache_unmerged();13701371if(fast_forward_to(head_tree, head_tree,1))1372return-1;13731374if(write_cache_as_tree(index,0, NULL))1375return-1;13761377 index_tree =parse_tree_indirect(index);1378if(!index_tree)1379returnerror(_("Could not parse object '%s'."),sha1_to_hex(index));13801381if(fast_forward_to(index_tree, remote_tree,0))1382return-1;13831384memset(&pathspec,0,sizeof(pathspec));13851386 lock_file =xcalloc(1,sizeof(struct lock_file));1387hold_locked_index(lock_file,1);13881389if(read_tree(remote_tree,0, &pathspec)) {1390rollback_lock_file(lock_file);1391return-1;1392}13931394if(write_locked_index(&the_index, lock_file, COMMIT_LOCK))1395die(_("unable to write new index file"));13961397remove_branch_state();13981399return0;1400}14011402/**1403 * Resume the current am session by skipping the current patch.1404 */1405static voidam_skip(struct am_state *state)1406{1407unsigned char head[GIT_SHA1_RAWSZ];14081409if(get_sha1("HEAD", head))1410hashcpy(head, EMPTY_TREE_SHA1_BIN);14111412if(clean_index(head, head))1413die(_("failed to clean index"));14141415am_next(state);1416am_run(state,0);1417}14181419/**1420 * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.1421 *1422 * It is not safe to reset HEAD when:1423 * 1. git-am previously failed because the index was dirty.1424 * 2. HEAD has moved since git-am previously failed.1425 */1426static intsafe_to_abort(const struct am_state *state)1427{1428struct strbuf sb = STRBUF_INIT;1429unsigned char abort_safety[GIT_SHA1_RAWSZ], head[GIT_SHA1_RAWSZ];14301431if(file_exists(am_path(state,"dirtyindex")))1432return0;14331434if(read_state_file(&sb, state,"abort-safety",1) >0) {1435if(get_sha1_hex(sb.buf, abort_safety))1436die(_("could not parse%s"),am_path(state,"abort_safety"));1437}else1438hashclr(abort_safety);14391440if(get_sha1("HEAD", head))1441hashclr(head);14421443if(!hashcmp(head, abort_safety))1444return1;14451446error(_("You seem to have moved HEAD since the last 'am' failure.\n"1447"Not rewinding to ORIG_HEAD"));14481449return0;1450}14511452/**1453 * Aborts the current am session if it is safe to do so.1454 */1455static voidam_abort(struct am_state *state)1456{1457unsigned char curr_head[GIT_SHA1_RAWSZ], orig_head[GIT_SHA1_RAWSZ];1458int has_curr_head, has_orig_head;1459char*curr_branch;14601461if(!safe_to_abort(state)) {1462am_destroy(state);1463return;1464}14651466 curr_branch =resolve_refdup("HEAD",0, curr_head, NULL);1467 has_curr_head = !is_null_sha1(curr_head);1468if(!has_curr_head)1469hashcpy(curr_head, EMPTY_TREE_SHA1_BIN);14701471 has_orig_head = !get_sha1("ORIG_HEAD", orig_head);1472if(!has_orig_head)1473hashcpy(orig_head, EMPTY_TREE_SHA1_BIN);14741475clean_index(curr_head, orig_head);14761477if(has_orig_head)1478update_ref("am --abort","HEAD", orig_head,1479 has_curr_head ? curr_head : NULL,0,1480 UPDATE_REFS_DIE_ON_ERR);1481else if(curr_branch)1482delete_ref(curr_branch, NULL, REF_NODEREF);14831484free(curr_branch);1485am_destroy(state);1486}14871488/**1489 * parse_options() callback that validates and sets opt->value to the1490 * PATCH_FORMAT_* enum value corresponding to `arg`.1491 */1492static intparse_opt_patchformat(const struct option *opt,const char*arg,int unset)1493{1494int*opt_value = opt->value;14951496if(!strcmp(arg,"mbox"))1497*opt_value = PATCH_FORMAT_MBOX;1498else1499returnerror(_("Invalid value for --patch-format:%s"), arg);1500return0;1501}15021503enum resume_mode {1504 RESUME_FALSE =0,1505 RESUME_APPLY,1506 RESUME_RESOLVED,1507 RESUME_SKIP,1508 RESUME_ABORT1509};15101511intcmd_am(int argc,const char**argv,const char*prefix)1512{1513struct am_state state;1514int patch_format = PATCH_FORMAT_UNKNOWN;1515enum resume_mode resume = RESUME_FALSE;15161517const char*const usage[] = {1518N_("git am [options] [(<mbox>|<Maildir>)...]"),1519N_("git am [options] (--continue | --skip | --abort)"),1520 NULL1521};15221523struct option options[] = {1524OPT_BOOL('3',"3way", &state.threeway,1525N_("allow fall back on 3way merging if needed")),1526OPT__QUIET(&state.quiet,N_("be quiet")),1527OPT_BOOL('s',"signoff", &state.signoff,1528N_("add a Signed-off-by line to the commit message")),1529OPT_BOOL('u',"utf8", &state.utf8,1530N_("recode into utf8 (default)")),1531OPT_SET_INT('k',"keep", &state.keep,1532N_("pass -k flag to git-mailinfo"), KEEP_TRUE),1533OPT_SET_INT(0,"keep-non-patch", &state.keep,1534N_("pass -b flag to git-mailinfo"), KEEP_NON_PATCH),1535OPT_BOOL('m',"message-id", &state.message_id,1536N_("pass -m flag to git-mailinfo")),1537OPT_CALLBACK(0,"patch-format", &patch_format,N_("format"),1538N_("format the patch(es) are in"),1539 parse_opt_patchformat),1540OPT_STRING(0,"resolvemsg", &state.resolvemsg, NULL,1541N_("override error message when patch failure occurs")),1542OPT_CMDMODE(0,"continue", &resume,1543N_("continue applying patches after resolving a conflict"),1544 RESUME_RESOLVED),1545OPT_CMDMODE('r',"resolved", &resume,1546N_("synonyms for --continue"),1547 RESUME_RESOLVED),1548OPT_CMDMODE(0,"skip", &resume,1549N_("skip the current patch"),1550 RESUME_SKIP),1551OPT_CMDMODE(0,"abort", &resume,1552N_("restore the original branch and abort the patching operation."),1553 RESUME_ABORT),1554OPT_HIDDEN_BOOL(0,"rebasing", &state.rebasing,1555N_("(internal use for git-rebase)")),1556OPT_END()1557};15581559/*1560 * NEEDSWORK: Once all the features of git-am.sh have been1561 * re-implemented in builtin/am.c, this preamble can be removed.1562 */1563if(!getenv("_GIT_USE_BUILTIN_AM")) {1564const char*path =mkpath("%s/git-am",git_exec_path());15651566if(sane_execvp(path, (char**)argv) <0)1567die_errno("could not exec%s", path);1568}else{1569 prefix =setup_git_directory();1570trace_repo_setup(prefix);1571setup_work_tree();1572}15731574git_config(git_default_config, NULL);15751576am_state_init(&state,git_path("rebase-apply"));15771578 argc =parse_options(argc, argv, prefix, options, usage,0);15791580if(read_index_preload(&the_index, NULL) <0)1581die(_("failed to read the index"));15821583if(am_in_progress(&state)) {1584/*1585 * Catch user error to feed us patches when there is a session1586 * in progress:1587 *1588 * 1. mbox path(s) are provided on the command-line.1589 * 2. stdin is not a tty: the user is trying to feed us a patch1590 * from standard input. This is somewhat unreliable -- stdin1591 * could be /dev/null for example and the caller did not1592 * intend to feed us a patch but wanted to continue1593 * unattended.1594 */1595if(argc || (resume == RESUME_FALSE && !isatty(0)))1596die(_("previous rebase directory%sstill exists but mbox given."),1597 state.dir);15981599if(resume == RESUME_FALSE)1600 resume = RESUME_APPLY;16011602am_load(&state);1603}else{1604struct argv_array paths = ARGV_ARRAY_INIT;1605int i;16061607/*1608 * Handle stray state directory in the independent-run case. In1609 * the --rebasing case, it is up to the caller to take care of1610 * stray directories.1611 */1612if(file_exists(state.dir) && !state.rebasing) {1613if(resume == RESUME_ABORT) {1614am_destroy(&state);1615am_state_release(&state);1616return0;1617}16181619die(_("Stray%sdirectory found.\n"1620"Use\"git am --abort\"to remove it."),1621 state.dir);1622}16231624if(resume)1625die(_("Resolve operation not in progress, we are not resuming."));16261627for(i =0; i < argc; i++) {1628if(is_absolute_path(argv[i]) || !prefix)1629argv_array_push(&paths, argv[i]);1630else1631argv_array_push(&paths,mkpath("%s/%s", prefix, argv[i]));1632}16331634am_setup(&state, patch_format, paths.argv);16351636argv_array_clear(&paths);1637}16381639switch(resume) {1640case RESUME_FALSE:1641am_run(&state,0);1642break;1643case RESUME_APPLY:1644am_run(&state,1);1645break;1646case RESUME_RESOLVED:1647am_resolve(&state);1648break;1649case RESUME_SKIP:1650am_skip(&state);1651break;1652case RESUME_ABORT:1653am_abort(&state);1654break;1655default:1656die("BUG: invalid resume value");1657}16581659am_state_release(&state);16601661return0;1662}