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 25/** 26 * Returns 1 if the file is empty or does not exist, 0 otherwise. 27 */ 28static intis_empty_file(const char*filename) 29{ 30struct stat st; 31 32if(stat(filename, &st) <0) { 33if(errno == ENOENT) 34return1; 35die_errno(_("could not stat%s"), filename); 36} 37 38return!st.st_size; 39} 40 41/** 42 * Like strbuf_getline(), but treats both '\n' and "\r\n" as line terminators. 43 */ 44static intstrbuf_getline_crlf(struct strbuf *sb,FILE*fp) 45{ 46if(strbuf_getwholeline(sb, fp,'\n')) 47return EOF; 48if(sb->buf[sb->len -1] =='\n') { 49strbuf_setlen(sb, sb->len -1); 50if(sb->len >0&& sb->buf[sb->len -1] =='\r') 51strbuf_setlen(sb, sb->len -1); 52} 53return0; 54} 55 56/** 57 * Returns the length of the first line of msg. 58 */ 59static intlinelen(const char*msg) 60{ 61returnstrchrnul(msg,'\n') - msg; 62} 63 64enum patch_format { 65 PATCH_FORMAT_UNKNOWN =0, 66 PATCH_FORMAT_MBOX 67}; 68 69struct am_state { 70/* state directory path */ 71char*dir; 72 73/* current and last patch numbers, 1-indexed */ 74int cur; 75int last; 76 77/* commit metadata and message */ 78char*author_name; 79char*author_email; 80char*author_date; 81char*msg; 82size_t msg_len; 83 84/* number of digits in patch filename */ 85int prec; 86 87/* various operating modes and command line options */ 88int threeway; 89int quiet; 90int signoff; 91const char*resolvemsg; 92int rebasing; 93}; 94 95/** 96 * Initializes am_state with the default values. The state directory is set to 97 * dir. 98 */ 99static voidam_state_init(struct am_state *state,const char*dir) 100{ 101memset(state,0,sizeof(*state)); 102 103assert(dir); 104 state->dir =xstrdup(dir); 105 106 state->prec =4; 107} 108 109/** 110 * Releases memory allocated by an am_state. 111 */ 112static voidam_state_release(struct am_state *state) 113{ 114free(state->dir); 115free(state->author_name); 116free(state->author_email); 117free(state->author_date); 118free(state->msg); 119} 120 121/** 122 * Returns path relative to the am_state directory. 123 */ 124staticinlineconst char*am_path(const struct am_state *state,const char*path) 125{ 126returnmkpath("%s/%s", state->dir, path); 127} 128 129/** 130 * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline 131 * at the end. 132 */ 133static voidsay(const struct am_state *state,FILE*fp,const char*fmt, ...) 134{ 135va_list ap; 136 137va_start(ap, fmt); 138if(!state->quiet) { 139vfprintf(fp, fmt, ap); 140putc('\n', fp); 141} 142va_end(ap); 143} 144 145/** 146 * Returns 1 if there is an am session in progress, 0 otherwise. 147 */ 148static intam_in_progress(const struct am_state *state) 149{ 150struct stat st; 151 152if(lstat(state->dir, &st) <0|| !S_ISDIR(st.st_mode)) 153return0; 154if(lstat(am_path(state,"last"), &st) || !S_ISREG(st.st_mode)) 155return0; 156if(lstat(am_path(state,"next"), &st) || !S_ISREG(st.st_mode)) 157return0; 158return1; 159} 160 161/** 162 * Reads the contents of `file` in the `state` directory into `sb`. Returns the 163 * number of bytes read on success, -1 if the file does not exist. If `trim` is 164 * set, trailing whitespace will be removed. 165 */ 166static intread_state_file(struct strbuf *sb,const struct am_state *state, 167const char*file,int trim) 168{ 169strbuf_reset(sb); 170 171if(strbuf_read_file(sb,am_path(state, file),0) >=0) { 172if(trim) 173strbuf_trim(sb); 174 175return sb->len; 176} 177 178if(errno == ENOENT) 179return-1; 180 181die_errno(_("could not read '%s'"),am_path(state, file)); 182} 183 184/** 185 * Reads a KEY=VALUE shell variable assignment from `fp`, returning the VALUE 186 * as a newly-allocated string. VALUE must be a quoted string, and the KEY must 187 * match `key`. Returns NULL on failure. 188 * 189 * This is used by read_author_script() to read the GIT_AUTHOR_* variables from 190 * the author-script. 191 */ 192static char*read_shell_var(FILE*fp,const char*key) 193{ 194struct strbuf sb = STRBUF_INIT; 195const char*str; 196 197if(strbuf_getline(&sb, fp,'\n')) 198goto fail; 199 200if(!skip_prefix(sb.buf, key, &str)) 201goto fail; 202 203if(!skip_prefix(str,"=", &str)) 204goto fail; 205 206strbuf_remove(&sb,0, str - sb.buf); 207 208 str =sq_dequote(sb.buf); 209if(!str) 210goto fail; 211 212returnstrbuf_detach(&sb, NULL); 213 214fail: 215strbuf_release(&sb); 216return NULL; 217} 218 219/** 220 * Reads and parses the state directory's "author-script" file, and sets 221 * state->author_name, state->author_email and state->author_date accordingly. 222 * Returns 0 on success, -1 if the file could not be parsed. 223 * 224 * The author script is of the format: 225 * 226 * GIT_AUTHOR_NAME='$author_name' 227 * GIT_AUTHOR_EMAIL='$author_email' 228 * GIT_AUTHOR_DATE='$author_date' 229 * 230 * where $author_name, $author_email and $author_date are quoted. We are strict 231 * with our parsing, as the file was meant to be eval'd in the old git-am.sh 232 * script, and thus if the file differs from what this function expects, it is 233 * better to bail out than to do something that the user does not expect. 234 */ 235static intread_author_script(struct am_state *state) 236{ 237const char*filename =am_path(state,"author-script"); 238FILE*fp; 239 240assert(!state->author_name); 241assert(!state->author_email); 242assert(!state->author_date); 243 244 fp =fopen(filename,"r"); 245if(!fp) { 246if(errno == ENOENT) 247return0; 248die_errno(_("could not open '%s' for reading"), filename); 249} 250 251 state->author_name =read_shell_var(fp,"GIT_AUTHOR_NAME"); 252if(!state->author_name) { 253fclose(fp); 254return-1; 255} 256 257 state->author_email =read_shell_var(fp,"GIT_AUTHOR_EMAIL"); 258if(!state->author_email) { 259fclose(fp); 260return-1; 261} 262 263 state->author_date =read_shell_var(fp,"GIT_AUTHOR_DATE"); 264if(!state->author_date) { 265fclose(fp); 266return-1; 267} 268 269if(fgetc(fp) != EOF) { 270fclose(fp); 271return-1; 272} 273 274fclose(fp); 275return0; 276} 277 278/** 279 * Saves state->author_name, state->author_email and state->author_date in the 280 * state directory's "author-script" file. 281 */ 282static voidwrite_author_script(const struct am_state *state) 283{ 284struct strbuf sb = STRBUF_INIT; 285 286strbuf_addstr(&sb,"GIT_AUTHOR_NAME="); 287sq_quote_buf(&sb, state->author_name); 288strbuf_addch(&sb,'\n'); 289 290strbuf_addstr(&sb,"GIT_AUTHOR_EMAIL="); 291sq_quote_buf(&sb, state->author_email); 292strbuf_addch(&sb,'\n'); 293 294strbuf_addstr(&sb,"GIT_AUTHOR_DATE="); 295sq_quote_buf(&sb, state->author_date); 296strbuf_addch(&sb,'\n'); 297 298write_file(am_path(state,"author-script"),1,"%s", sb.buf); 299 300strbuf_release(&sb); 301} 302 303/** 304 * Reads the commit message from the state directory's "final-commit" file, 305 * setting state->msg to its contents and state->msg_len to the length of its 306 * contents in bytes. 307 * 308 * Returns 0 on success, -1 if the file does not exist. 309 */ 310static intread_commit_msg(struct am_state *state) 311{ 312struct strbuf sb = STRBUF_INIT; 313 314assert(!state->msg); 315 316if(read_state_file(&sb, state,"final-commit",0) <0) { 317strbuf_release(&sb); 318return-1; 319} 320 321 state->msg =strbuf_detach(&sb, &state->msg_len); 322return0; 323} 324 325/** 326 * Saves state->msg in the state directory's "final-commit" file. 327 */ 328static voidwrite_commit_msg(const struct am_state *state) 329{ 330int fd; 331const char*filename =am_path(state,"final-commit"); 332 333 fd =xopen(filename, O_WRONLY | O_CREAT,0666); 334if(write_in_full(fd, state->msg, state->msg_len) <0) 335die_errno(_("could not write to%s"), filename); 336close(fd); 337} 338 339/** 340 * Loads state from disk. 341 */ 342static voidam_load(struct am_state *state) 343{ 344struct strbuf sb = STRBUF_INIT; 345 346if(read_state_file(&sb, state,"next",1) <0) 347die("BUG: state file 'next' does not exist"); 348 state->cur =strtol(sb.buf, NULL,10); 349 350if(read_state_file(&sb, state,"last",1) <0) 351die("BUG: state file 'last' does not exist"); 352 state->last =strtol(sb.buf, NULL,10); 353 354if(read_author_script(state) <0) 355die(_("could not parse author script")); 356 357read_commit_msg(state); 358 359read_state_file(&sb, state,"threeway",1); 360 state->threeway = !strcmp(sb.buf,"t"); 361 362read_state_file(&sb, state,"quiet",1); 363 state->quiet = !strcmp(sb.buf,"t"); 364 365read_state_file(&sb, state,"sign",1); 366 state->signoff = !strcmp(sb.buf,"t"); 367 368 state->rebasing = !!file_exists(am_path(state,"rebasing")); 369 370strbuf_release(&sb); 371} 372 373/** 374 * Removes the am_state directory, forcefully terminating the current am 375 * session. 376 */ 377static voidam_destroy(const struct am_state *state) 378{ 379struct strbuf sb = STRBUF_INIT; 380 381strbuf_addstr(&sb, state->dir); 382remove_dir_recursively(&sb,0); 383strbuf_release(&sb); 384} 385 386/** 387 * Determines if the file looks like a piece of RFC2822 mail by grabbing all 388 * non-indented lines and checking if they look like they begin with valid 389 * header field names. 390 * 391 * Returns 1 if the file looks like a piece of mail, 0 otherwise. 392 */ 393static intis_mail(FILE*fp) 394{ 395const char*header_regex ="^[!-9;-~]+:"; 396struct strbuf sb = STRBUF_INIT; 397 regex_t regex; 398int ret =1; 399 400if(fseek(fp,0L, SEEK_SET)) 401die_errno(_("fseek failed")); 402 403if(regcomp(®ex, header_regex, REG_NOSUB | REG_EXTENDED)) 404die("invalid pattern:%s", header_regex); 405 406while(!strbuf_getline_crlf(&sb, fp)) { 407if(!sb.len) 408break;/* End of header */ 409 410/* Ignore indented folded lines */ 411if(*sb.buf =='\t'|| *sb.buf ==' ') 412continue; 413 414/* It's a header if it matches header_regex */ 415if(regexec(®ex, sb.buf,0, NULL,0)) { 416 ret =0; 417goto done; 418} 419} 420 421done: 422regfree(®ex); 423strbuf_release(&sb); 424return ret; 425} 426 427/** 428 * Attempts to detect the patch_format of the patches contained in `paths`, 429 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if 430 * detection fails. 431 */ 432static intdetect_patch_format(const char**paths) 433{ 434enum patch_format ret = PATCH_FORMAT_UNKNOWN; 435struct strbuf l1 = STRBUF_INIT; 436FILE*fp; 437 438/* 439 * We default to mbox format if input is from stdin and for directories 440 */ 441if(!*paths || !strcmp(*paths,"-") ||is_directory(*paths)) 442return PATCH_FORMAT_MBOX; 443 444/* 445 * Otherwise, check the first few lines of the first patch, starting 446 * from the first non-blank line, to try to detect its format. 447 */ 448 449 fp =xfopen(*paths,"r"); 450 451while(!strbuf_getline_crlf(&l1, fp)) { 452if(l1.len) 453break; 454} 455 456if(starts_with(l1.buf,"From ") ||starts_with(l1.buf,"From: ")) { 457 ret = PATCH_FORMAT_MBOX; 458goto done; 459} 460 461if(l1.len &&is_mail(fp)) { 462 ret = PATCH_FORMAT_MBOX; 463goto done; 464} 465 466done: 467fclose(fp); 468strbuf_release(&l1); 469return ret; 470} 471 472/** 473 * Splits out individual email patches from `paths`, where each path is either 474 * a mbox file or a Maildir. Returns 0 on success, -1 on failure. 475 */ 476static intsplit_mail_mbox(struct am_state *state,const char**paths) 477{ 478struct child_process cp = CHILD_PROCESS_INIT; 479struct strbuf last = STRBUF_INIT; 480 481 cp.git_cmd =1; 482argv_array_push(&cp.args,"mailsplit"); 483argv_array_pushf(&cp.args,"-d%d", state->prec); 484argv_array_pushf(&cp.args,"-o%s", state->dir); 485argv_array_push(&cp.args,"-b"); 486argv_array_push(&cp.args,"--"); 487argv_array_pushv(&cp.args, paths); 488 489if(capture_command(&cp, &last,8)) 490return-1; 491 492 state->cur =1; 493 state->last =strtol(last.buf, NULL,10); 494 495return0; 496} 497 498/** 499 * Splits a list of files/directories into individual email patches. Each path 500 * in `paths` must be a file/directory that is formatted according to 501 * `patch_format`. 502 * 503 * Once split out, the individual email patches will be stored in the state 504 * directory, with each patch's filename being its index, padded to state->prec 505 * digits. 506 * 507 * state->cur will be set to the index of the first mail, and state->last will 508 * be set to the index of the last mail. 509 * 510 * Returns 0 on success, -1 on failure. 511 */ 512static intsplit_mail(struct am_state *state,enum patch_format patch_format, 513const char**paths) 514{ 515switch(patch_format) { 516case PATCH_FORMAT_MBOX: 517returnsplit_mail_mbox(state, paths); 518default: 519die("BUG: invalid patch_format"); 520} 521return-1; 522} 523 524/** 525 * Setup a new am session for applying patches 526 */ 527static voidam_setup(struct am_state *state,enum patch_format patch_format, 528const char**paths) 529{ 530unsigned char curr_head[GIT_SHA1_RAWSZ]; 531 532if(!patch_format) 533 patch_format =detect_patch_format(paths); 534 535if(!patch_format) { 536fprintf_ln(stderr,_("Patch format detection failed.")); 537exit(128); 538} 539 540if(mkdir(state->dir,0777) <0&& errno != EEXIST) 541die_errno(_("failed to create directory '%s'"), state->dir); 542 543if(split_mail(state, patch_format, paths) <0) { 544am_destroy(state); 545die(_("Failed to split patches.")); 546} 547 548if(state->rebasing) 549 state->threeway =1; 550 551write_file(am_path(state,"threeway"),1, state->threeway ?"t":"f"); 552 553write_file(am_path(state,"quiet"),1, state->quiet ?"t":"f"); 554 555write_file(am_path(state,"sign"),1, state->signoff ?"t":"f"); 556 557if(state->rebasing) 558write_file(am_path(state,"rebasing"),1,"%s",""); 559else 560write_file(am_path(state,"applying"),1,"%s",""); 561 562if(!get_sha1("HEAD", curr_head)) { 563write_file(am_path(state,"abort-safety"),1,"%s",sha1_to_hex(curr_head)); 564if(!state->rebasing) 565update_ref("am","ORIG_HEAD", curr_head, NULL,0, 566 UPDATE_REFS_DIE_ON_ERR); 567}else{ 568write_file(am_path(state,"abort-safety"),1,"%s",""); 569if(!state->rebasing) 570delete_ref("ORIG_HEAD", NULL,0); 571} 572 573/* 574 * NOTE: Since the "next" and "last" files determine if an am_state 575 * session is in progress, they should be written last. 576 */ 577 578write_file(am_path(state,"next"),1,"%d", state->cur); 579 580write_file(am_path(state,"last"),1,"%d", state->last); 581} 582 583/** 584 * Increments the patch pointer, and cleans am_state for the application of the 585 * next patch. 586 */ 587static voidam_next(struct am_state *state) 588{ 589unsigned char head[GIT_SHA1_RAWSZ]; 590 591free(state->author_name); 592 state->author_name = NULL; 593 594free(state->author_email); 595 state->author_email = NULL; 596 597free(state->author_date); 598 state->author_date = NULL; 599 600free(state->msg); 601 state->msg = NULL; 602 state->msg_len =0; 603 604unlink(am_path(state,"author-script")); 605unlink(am_path(state,"final-commit")); 606 607if(!get_sha1("HEAD", head)) 608write_file(am_path(state,"abort-safety"),1,"%s",sha1_to_hex(head)); 609else 610write_file(am_path(state,"abort-safety"),1,"%s",""); 611 612 state->cur++; 613write_file(am_path(state,"next"),1,"%d", state->cur); 614} 615 616/** 617 * Returns the filename of the current patch email. 618 */ 619static const char*msgnum(const struct am_state *state) 620{ 621static struct strbuf sb = STRBUF_INIT; 622 623strbuf_reset(&sb); 624strbuf_addf(&sb,"%0*d", state->prec, state->cur); 625 626return sb.buf; 627} 628 629/** 630 * Refresh and write index. 631 */ 632static voidrefresh_and_write_cache(void) 633{ 634struct lock_file *lock_file =xcalloc(1,sizeof(struct lock_file)); 635 636hold_locked_index(lock_file,1); 637refresh_cache(REFRESH_QUIET); 638if(write_locked_index(&the_index, lock_file, COMMIT_LOCK)) 639die(_("unable to write index file")); 640} 641 642/** 643 * Returns 1 if the index differs from HEAD, 0 otherwise. When on an unborn 644 * branch, returns 1 if there are entries in the index, 0 otherwise. If an 645 * strbuf is provided, the space-separated list of files that differ will be 646 * appended to it. 647 */ 648static intindex_has_changes(struct strbuf *sb) 649{ 650unsigned char head[GIT_SHA1_RAWSZ]; 651int i; 652 653if(!get_sha1_tree("HEAD", head)) { 654struct diff_options opt; 655 656diff_setup(&opt); 657DIFF_OPT_SET(&opt, EXIT_WITH_STATUS); 658if(!sb) 659DIFF_OPT_SET(&opt, QUICK); 660do_diff_cache(head, &opt); 661diffcore_std(&opt); 662for(i =0; sb && i < diff_queued_diff.nr; i++) { 663if(i) 664strbuf_addch(sb,' '); 665strbuf_addstr(sb, diff_queued_diff.queue[i]->two->path); 666} 667diff_flush(&opt); 668returnDIFF_OPT_TST(&opt, HAS_CHANGES) !=0; 669}else{ 670for(i =0; sb && i < active_nr; i++) { 671if(i) 672strbuf_addch(sb,' '); 673strbuf_addstr(sb, active_cache[i]->name); 674} 675return!!active_nr; 676} 677} 678 679/** 680 * Dies with a user-friendly message on how to proceed after resolving the 681 * problem. This message can be overridden with state->resolvemsg. 682 */ 683static void NORETURN die_user_resolve(const struct am_state *state) 684{ 685if(state->resolvemsg) { 686printf_ln("%s", state->resolvemsg); 687}else{ 688const char*cmdline ="git am"; 689 690printf_ln(_("When you have resolved this problem, run\"%s--continue\"."), cmdline); 691printf_ln(_("If you prefer to skip this patch, run\"%s--skip\"instead."), cmdline); 692printf_ln(_("To restore the original branch and stop patching, run\"%s--abort\"."), cmdline); 693} 694 695exit(128); 696} 697 698/** 699 * Parses `mail` using git-mailinfo, extracting its patch and authorship info. 700 * state->msg will be set to the patch message. state->author_name, 701 * state->author_email and state->author_date will be set to the patch author's 702 * name, email and date respectively. The patch body will be written to the 703 * state directory's "patch" file. 704 * 705 * Returns 1 if the patch should be skipped, 0 otherwise. 706 */ 707static intparse_mail(struct am_state *state,const char*mail) 708{ 709FILE*fp; 710struct child_process cp = CHILD_PROCESS_INIT; 711struct strbuf sb = STRBUF_INIT; 712struct strbuf msg = STRBUF_INIT; 713struct strbuf author_name = STRBUF_INIT; 714struct strbuf author_date = STRBUF_INIT; 715struct strbuf author_email = STRBUF_INIT; 716int ret =0; 717 718 cp.git_cmd =1; 719 cp.in =xopen(mail, O_RDONLY,0); 720 cp.out =xopen(am_path(state,"info"), O_WRONLY | O_CREAT,0777); 721 722argv_array_push(&cp.args,"mailinfo"); 723argv_array_push(&cp.args,am_path(state,"msg")); 724argv_array_push(&cp.args,am_path(state,"patch")); 725 726if(run_command(&cp) <0) 727die("could not parse patch"); 728 729close(cp.in); 730close(cp.out); 731 732/* Extract message and author information */ 733 fp =xfopen(am_path(state,"info"),"r"); 734while(!strbuf_getline(&sb, fp,'\n')) { 735const char*x; 736 737if(skip_prefix(sb.buf,"Subject: ", &x)) { 738if(msg.len) 739strbuf_addch(&msg,'\n'); 740strbuf_addstr(&msg, x); 741}else if(skip_prefix(sb.buf,"Author: ", &x)) 742strbuf_addstr(&author_name, x); 743else if(skip_prefix(sb.buf,"Email: ", &x)) 744strbuf_addstr(&author_email, x); 745else if(skip_prefix(sb.buf,"Date: ", &x)) 746strbuf_addstr(&author_date, x); 747} 748fclose(fp); 749 750/* Skip pine's internal folder data */ 751if(!strcmp(author_name.buf,"Mail System Internal Data")) { 752 ret =1; 753goto finish; 754} 755 756if(is_empty_file(am_path(state,"patch"))) { 757printf_ln(_("Patch is empty. Was it split wrong?")); 758die_user_resolve(state); 759} 760 761strbuf_addstr(&msg,"\n\n"); 762if(strbuf_read_file(&msg,am_path(state,"msg"),0) <0) 763die_errno(_("could not read '%s'"),am_path(state,"msg")); 764stripspace(&msg,0); 765 766if(state->signoff) 767append_signoff(&msg,0,0); 768 769assert(!state->author_name); 770 state->author_name =strbuf_detach(&author_name, NULL); 771 772assert(!state->author_email); 773 state->author_email =strbuf_detach(&author_email, NULL); 774 775assert(!state->author_date); 776 state->author_date =strbuf_detach(&author_date, NULL); 777 778assert(!state->msg); 779 state->msg =strbuf_detach(&msg, &state->msg_len); 780 781finish: 782strbuf_release(&msg); 783strbuf_release(&author_date); 784strbuf_release(&author_email); 785strbuf_release(&author_name); 786strbuf_release(&sb); 787return ret; 788} 789 790/** 791 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If 792 * `index_file` is not NULL, the patch will be applied to that index. 793 */ 794static intrun_apply(const struct am_state *state,const char*index_file) 795{ 796struct child_process cp = CHILD_PROCESS_INIT; 797 798 cp.git_cmd =1; 799 800if(index_file) 801argv_array_pushf(&cp.env_array,"GIT_INDEX_FILE=%s", index_file); 802 803/* 804 * If we are allowed to fall back on 3-way merge, don't give false 805 * errors during the initial attempt. 806 */ 807if(state->threeway && !index_file) { 808 cp.no_stdout =1; 809 cp.no_stderr =1; 810} 811 812argv_array_push(&cp.args,"apply"); 813 814if(index_file) 815argv_array_push(&cp.args,"--cached"); 816else 817argv_array_push(&cp.args,"--index"); 818 819argv_array_push(&cp.args,am_path(state,"patch")); 820 821if(run_command(&cp)) 822return-1; 823 824/* Reload index as git-apply will have modified it. */ 825discard_cache(); 826read_cache_from(index_file ? index_file :get_index_file()); 827 828return0; 829} 830 831/** 832 * Builds an index that contains just the blobs needed for a 3way merge. 833 */ 834static intbuild_fake_ancestor(const struct am_state *state,const char*index_file) 835{ 836struct child_process cp = CHILD_PROCESS_INIT; 837 838 cp.git_cmd =1; 839argv_array_push(&cp.args,"apply"); 840argv_array_pushf(&cp.args,"--build-fake-ancestor=%s", index_file); 841argv_array_push(&cp.args,am_path(state,"patch")); 842 843if(run_command(&cp)) 844return-1; 845 846return0; 847} 848 849/** 850 * Attempt a threeway merge, using index_path as the temporary index. 851 */ 852static intfall_back_threeway(const struct am_state *state,const char*index_path) 853{ 854unsigned char orig_tree[GIT_SHA1_RAWSZ], his_tree[GIT_SHA1_RAWSZ], 855 our_tree[GIT_SHA1_RAWSZ]; 856const unsigned char*bases[1] = {orig_tree}; 857struct merge_options o; 858struct commit *result; 859char*his_tree_name; 860 861if(get_sha1("HEAD", our_tree) <0) 862hashcpy(our_tree, EMPTY_TREE_SHA1_BIN); 863 864if(build_fake_ancestor(state, index_path)) 865returnerror("could not build fake ancestor"); 866 867discard_cache(); 868read_cache_from(index_path); 869 870if(write_index_as_tree(orig_tree, &the_index, index_path,0, NULL)) 871returnerror(_("Repository lacks necessary blobs to fall back on 3-way merge.")); 872 873say(state, stdout,_("Using index info to reconstruct a base tree...")); 874 875if(!state->quiet) { 876/* 877 * List paths that needed 3-way fallback, so that the user can 878 * review them with extra care to spot mismerges. 879 */ 880struct rev_info rev_info; 881const char*diff_filter_str ="--diff-filter=AM"; 882 883init_revisions(&rev_info, NULL); 884 rev_info.diffopt.output_format = DIFF_FORMAT_NAME_STATUS; 885diff_opt_parse(&rev_info.diffopt, &diff_filter_str,1); 886add_pending_sha1(&rev_info,"HEAD", our_tree,0); 887diff_setup_done(&rev_info.diffopt); 888run_diff_index(&rev_info,1); 889} 890 891if(run_apply(state, index_path)) 892returnerror(_("Did you hand edit your patch?\n" 893"It does not apply to blobs recorded in its index.")); 894 895if(write_index_as_tree(his_tree, &the_index, index_path,0, NULL)) 896returnerror("could not write tree"); 897 898say(state, stdout,_("Falling back to patching base and 3-way merge...")); 899 900discard_cache(); 901read_cache(); 902 903/* 904 * This is not so wrong. Depending on which base we picked, orig_tree 905 * may be wildly different from ours, but his_tree has the same set of 906 * wildly different changes in parts the patch did not touch, so 907 * recursive ends up canceling them, saying that we reverted all those 908 * changes. 909 */ 910 911init_merge_options(&o); 912 913 o.branch1 ="HEAD"; 914 his_tree_name =xstrfmt("%.*s",linelen(state->msg), state->msg); 915 o.branch2 = his_tree_name; 916 917if(state->quiet) 918 o.verbosity =0; 919 920if(merge_recursive_generic(&o, our_tree, his_tree,1, bases, &result)) { 921free(his_tree_name); 922returnerror(_("Failed to merge in the changes.")); 923} 924 925free(his_tree_name); 926return0; 927} 928 929/** 930 * Commits the current index with state->msg as the commit message and 931 * state->author_name, state->author_email and state->author_date as the author 932 * information. 933 */ 934static voiddo_commit(const struct am_state *state) 935{ 936unsigned char tree[GIT_SHA1_RAWSZ], parent[GIT_SHA1_RAWSZ], 937 commit[GIT_SHA1_RAWSZ]; 938unsigned char*ptr; 939struct commit_list *parents = NULL; 940const char*reflog_msg, *author; 941struct strbuf sb = STRBUF_INIT; 942 943if(write_cache_as_tree(tree,0, NULL)) 944die(_("git write-tree failed to write a tree")); 945 946if(!get_sha1_commit("HEAD", parent)) { 947 ptr = parent; 948commit_list_insert(lookup_commit(parent), &parents); 949}else{ 950 ptr = NULL; 951say(state, stderr,_("applying to an empty history")); 952} 953 954 author =fmt_ident(state->author_name, state->author_email, 955 state->author_date, IDENT_STRICT); 956 957if(commit_tree(state->msg, state->msg_len, tree, parents, commit, 958 author, NULL)) 959die(_("failed to write commit object")); 960 961 reflog_msg =getenv("GIT_REFLOG_ACTION"); 962if(!reflog_msg) 963 reflog_msg ="am"; 964 965strbuf_addf(&sb,"%s: %.*s", reflog_msg,linelen(state->msg), 966 state->msg); 967 968update_ref(sb.buf,"HEAD", commit, ptr,0, UPDATE_REFS_DIE_ON_ERR); 969 970strbuf_release(&sb); 971} 972 973/** 974 * Validates the am_state for resuming -- the "msg" and authorship fields must 975 * be filled up. 976 */ 977static voidvalidate_resume_state(const struct am_state *state) 978{ 979if(!state->msg) 980die(_("cannot resume:%sdoes not exist."), 981am_path(state,"final-commit")); 982 983if(!state->author_name || !state->author_email || !state->author_date) 984die(_("cannot resume:%sdoes not exist."), 985am_path(state,"author-script")); 986} 987 988/** 989 * Applies all queued mail. 990 * 991 * If `resume` is true, we are "resuming". The "msg" and authorship fields, as 992 * well as the state directory's "patch" file is used as-is for applying the 993 * patch and committing it. 994 */ 995static voidam_run(struct am_state *state,int resume) 996{ 997const char*argv_gc_auto[] = {"gc","--auto", NULL}; 998struct strbuf sb = STRBUF_INIT; 9991000unlink(am_path(state,"dirtyindex"));10011002refresh_and_write_cache();10031004if(index_has_changes(&sb)) {1005write_file(am_path(state,"dirtyindex"),1,"t");1006die(_("Dirty index: cannot apply patches (dirty:%s)"), sb.buf);1007}10081009strbuf_release(&sb);10101011while(state->cur <= state->last) {1012const char*mail =am_path(state,msgnum(state));1013int apply_status;10141015if(!file_exists(mail))1016goto next;10171018if(resume) {1019validate_resume_state(state);1020 resume =0;1021}else{1022if(parse_mail(state, mail))1023goto next;/* mail should be skipped */10241025write_author_script(state);1026write_commit_msg(state);1027}10281029say(state, stdout,_("Applying: %.*s"),linelen(state->msg), state->msg);10301031 apply_status =run_apply(state, NULL);10321033if(apply_status && state->threeway) {1034struct strbuf sb = STRBUF_INIT;10351036strbuf_addstr(&sb,am_path(state,"patch-merge-index"));1037 apply_status =fall_back_threeway(state, sb.buf);1038strbuf_release(&sb);10391040/*1041 * Applying the patch to an earlier tree and merging1042 * the result may have produced the same tree as ours.1043 */1044if(!apply_status && !index_has_changes(NULL)) {1045say(state, stdout,_("No changes -- Patch already applied."));1046goto next;1047}1048}10491050if(apply_status) {1051int advice_amworkdir =1;10521053printf_ln(_("Patch failed at%s%.*s"),msgnum(state),1054linelen(state->msg), state->msg);10551056git_config_get_bool("advice.amworkdir", &advice_amworkdir);10571058if(advice_amworkdir)1059printf_ln(_("The copy of the patch that failed is found in:%s"),1060am_path(state,"patch"));10611062die_user_resolve(state);1063}10641065do_commit(state);10661067next:1068am_next(state);1069}10701071/*1072 * In rebasing mode, it's up to the caller to take care of1073 * housekeeping.1074 */1075if(!state->rebasing) {1076am_destroy(state);1077run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);1078}1079}10801081/**1082 * Resume the current am session after patch application failure. The user did1083 * all the hard work, and we do not have to do any patch application. Just1084 * trust and commit what the user has in the index and working tree.1085 */1086static voidam_resolve(struct am_state *state)1087{1088validate_resume_state(state);10891090say(state, stdout,_("Applying: %.*s"),linelen(state->msg), state->msg);10911092if(!index_has_changes(NULL)) {1093printf_ln(_("No changes - did you forget to use 'git add'?\n"1094"If there is nothing left to stage, chances are that something else\n"1095"already introduced the same changes; you might want to skip this patch."));1096die_user_resolve(state);1097}10981099if(unmerged_cache()) {1100printf_ln(_("You still have unmerged paths in your index.\n"1101"Did you forget to use 'git add'?"));1102die_user_resolve(state);1103}11041105do_commit(state);11061107am_next(state);1108am_run(state,0);1109}11101111/**1112 * Performs a checkout fast-forward from `head` to `remote`. If `reset` is1113 * true, any unmerged entries will be discarded. Returns 0 on success, -1 on1114 * failure.1115 */1116static intfast_forward_to(struct tree *head,struct tree *remote,int reset)1117{1118struct lock_file *lock_file;1119struct unpack_trees_options opts;1120struct tree_desc t[2];11211122if(parse_tree(head) ||parse_tree(remote))1123return-1;11241125 lock_file =xcalloc(1,sizeof(struct lock_file));1126hold_locked_index(lock_file,1);11271128refresh_cache(REFRESH_QUIET);11291130memset(&opts,0,sizeof(opts));1131 opts.head_idx =1;1132 opts.src_index = &the_index;1133 opts.dst_index = &the_index;1134 opts.update =1;1135 opts.merge =1;1136 opts.reset = reset;1137 opts.fn = twoway_merge;1138init_tree_desc(&t[0], head->buffer, head->size);1139init_tree_desc(&t[1], remote->buffer, remote->size);11401141if(unpack_trees(2, t, &opts)) {1142rollback_lock_file(lock_file);1143return-1;1144}11451146if(write_locked_index(&the_index, lock_file, COMMIT_LOCK))1147die(_("unable to write new index file"));11481149return0;1150}11511152/**1153 * Clean the index without touching entries that are not modified between1154 * `head` and `remote`.1155 */1156static intclean_index(const unsigned char*head,const unsigned char*remote)1157{1158struct lock_file *lock_file;1159struct tree *head_tree, *remote_tree, *index_tree;1160unsigned char index[GIT_SHA1_RAWSZ];1161struct pathspec pathspec;11621163 head_tree =parse_tree_indirect(head);1164if(!head_tree)1165returnerror(_("Could not parse object '%s'."),sha1_to_hex(head));11661167 remote_tree =parse_tree_indirect(remote);1168if(!remote_tree)1169returnerror(_("Could not parse object '%s'."),sha1_to_hex(remote));11701171read_cache_unmerged();11721173if(fast_forward_to(head_tree, head_tree,1))1174return-1;11751176if(write_cache_as_tree(index,0, NULL))1177return-1;11781179 index_tree =parse_tree_indirect(index);1180if(!index_tree)1181returnerror(_("Could not parse object '%s'."),sha1_to_hex(index));11821183if(fast_forward_to(index_tree, remote_tree,0))1184return-1;11851186memset(&pathspec,0,sizeof(pathspec));11871188 lock_file =xcalloc(1,sizeof(struct lock_file));1189hold_locked_index(lock_file,1);11901191if(read_tree(remote_tree,0, &pathspec)) {1192rollback_lock_file(lock_file);1193return-1;1194}11951196if(write_locked_index(&the_index, lock_file, COMMIT_LOCK))1197die(_("unable to write new index file"));11981199remove_branch_state();12001201return0;1202}12031204/**1205 * Resume the current am session by skipping the current patch.1206 */1207static voidam_skip(struct am_state *state)1208{1209unsigned char head[GIT_SHA1_RAWSZ];12101211if(get_sha1("HEAD", head))1212hashcpy(head, EMPTY_TREE_SHA1_BIN);12131214if(clean_index(head, head))1215die(_("failed to clean index"));12161217am_next(state);1218am_run(state,0);1219}12201221/**1222 * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.1223 *1224 * It is not safe to reset HEAD when:1225 * 1. git-am previously failed because the index was dirty.1226 * 2. HEAD has moved since git-am previously failed.1227 */1228static intsafe_to_abort(const struct am_state *state)1229{1230struct strbuf sb = STRBUF_INIT;1231unsigned char abort_safety[GIT_SHA1_RAWSZ], head[GIT_SHA1_RAWSZ];12321233if(file_exists(am_path(state,"dirtyindex")))1234return0;12351236if(read_state_file(&sb, state,"abort-safety",1) >0) {1237if(get_sha1_hex(sb.buf, abort_safety))1238die(_("could not parse%s"),am_path(state,"abort_safety"));1239}else1240hashclr(abort_safety);12411242if(get_sha1("HEAD", head))1243hashclr(head);12441245if(!hashcmp(head, abort_safety))1246return1;12471248error(_("You seem to have moved HEAD since the last 'am' failure.\n"1249"Not rewinding to ORIG_HEAD"));12501251return0;1252}12531254/**1255 * Aborts the current am session if it is safe to do so.1256 */1257static voidam_abort(struct am_state *state)1258{1259unsigned char curr_head[GIT_SHA1_RAWSZ], orig_head[GIT_SHA1_RAWSZ];1260int has_curr_head, has_orig_head;1261char*curr_branch;12621263if(!safe_to_abort(state)) {1264am_destroy(state);1265return;1266}12671268 curr_branch =resolve_refdup("HEAD",0, curr_head, NULL);1269 has_curr_head = !is_null_sha1(curr_head);1270if(!has_curr_head)1271hashcpy(curr_head, EMPTY_TREE_SHA1_BIN);12721273 has_orig_head = !get_sha1("ORIG_HEAD", orig_head);1274if(!has_orig_head)1275hashcpy(orig_head, EMPTY_TREE_SHA1_BIN);12761277clean_index(curr_head, orig_head);12781279if(has_orig_head)1280update_ref("am --abort","HEAD", orig_head,1281 has_curr_head ? curr_head : NULL,0,1282 UPDATE_REFS_DIE_ON_ERR);1283else if(curr_branch)1284delete_ref(curr_branch, NULL, REF_NODEREF);12851286free(curr_branch);1287am_destroy(state);1288}12891290/**1291 * parse_options() callback that validates and sets opt->value to the1292 * PATCH_FORMAT_* enum value corresponding to `arg`.1293 */1294static intparse_opt_patchformat(const struct option *opt,const char*arg,int unset)1295{1296int*opt_value = opt->value;12971298if(!strcmp(arg,"mbox"))1299*opt_value = PATCH_FORMAT_MBOX;1300else1301returnerror(_("Invalid value for --patch-format:%s"), arg);1302return0;1303}13041305enum resume_mode {1306 RESUME_FALSE =0,1307 RESUME_APPLY,1308 RESUME_RESOLVED,1309 RESUME_SKIP,1310 RESUME_ABORT1311};13121313intcmd_am(int argc,const char**argv,const char*prefix)1314{1315struct am_state state;1316int patch_format = PATCH_FORMAT_UNKNOWN;1317enum resume_mode resume = RESUME_FALSE;13181319const char*const usage[] = {1320N_("git am [options] [(<mbox>|<Maildir>)...]"),1321N_("git am [options] (--continue | --skip | --abort)"),1322 NULL1323};13241325struct option options[] = {1326OPT_BOOL('3',"3way", &state.threeway,1327N_("allow fall back on 3way merging if needed")),1328OPT__QUIET(&state.quiet,N_("be quiet")),1329OPT_BOOL('s',"signoff", &state.signoff,1330N_("add a Signed-off-by line to the commit message")),1331OPT_CALLBACK(0,"patch-format", &patch_format,N_("format"),1332N_("format the patch(es) are in"),1333 parse_opt_patchformat),1334OPT_STRING(0,"resolvemsg", &state.resolvemsg, NULL,1335N_("override error message when patch failure occurs")),1336OPT_CMDMODE(0,"continue", &resume,1337N_("continue applying patches after resolving a conflict"),1338 RESUME_RESOLVED),1339OPT_CMDMODE('r',"resolved", &resume,1340N_("synonyms for --continue"),1341 RESUME_RESOLVED),1342OPT_CMDMODE(0,"skip", &resume,1343N_("skip the current patch"),1344 RESUME_SKIP),1345OPT_CMDMODE(0,"abort", &resume,1346N_("restore the original branch and abort the patching operation."),1347 RESUME_ABORT),1348OPT_HIDDEN_BOOL(0,"rebasing", &state.rebasing,1349N_("(internal use for git-rebase)")),1350OPT_END()1351};13521353/*1354 * NEEDSWORK: Once all the features of git-am.sh have been1355 * re-implemented in builtin/am.c, this preamble can be removed.1356 */1357if(!getenv("_GIT_USE_BUILTIN_AM")) {1358const char*path =mkpath("%s/git-am",git_exec_path());13591360if(sane_execvp(path, (char**)argv) <0)1361die_errno("could not exec%s", path);1362}else{1363 prefix =setup_git_directory();1364trace_repo_setup(prefix);1365setup_work_tree();1366}13671368git_config(git_default_config, NULL);13691370am_state_init(&state,git_path("rebase-apply"));13711372 argc =parse_options(argc, argv, prefix, options, usage,0);13731374if(read_index_preload(&the_index, NULL) <0)1375die(_("failed to read the index"));13761377if(am_in_progress(&state)) {1378/*1379 * Catch user error to feed us patches when there is a session1380 * in progress:1381 *1382 * 1. mbox path(s) are provided on the command-line.1383 * 2. stdin is not a tty: the user is trying to feed us a patch1384 * from standard input. This is somewhat unreliable -- stdin1385 * could be /dev/null for example and the caller did not1386 * intend to feed us a patch but wanted to continue1387 * unattended.1388 */1389if(argc || (resume == RESUME_FALSE && !isatty(0)))1390die(_("previous rebase directory%sstill exists but mbox given."),1391 state.dir);13921393if(resume == RESUME_FALSE)1394 resume = RESUME_APPLY;13951396am_load(&state);1397}else{1398struct argv_array paths = ARGV_ARRAY_INIT;1399int i;14001401if(resume)1402die(_("Resolve operation not in progress, we are not resuming."));14031404for(i =0; i < argc; i++) {1405if(is_absolute_path(argv[i]) || !prefix)1406argv_array_push(&paths, argv[i]);1407else1408argv_array_push(&paths,mkpath("%s/%s", prefix, argv[i]));1409}14101411am_setup(&state, patch_format, paths.argv);14121413argv_array_clear(&paths);1414}14151416switch(resume) {1417case RESUME_FALSE:1418am_run(&state,0);1419break;1420case RESUME_APPLY:1421am_run(&state,1);1422break;1423case RESUME_RESOLVED:1424am_resolve(&state);1425break;1426case RESUME_SKIP:1427am_skip(&state);1428break;1429case RESUME_ABORT:1430am_abort(&state);1431break;1432default:1433die("BUG: invalid resume value");1434}14351436am_state_release(&state);14371438return0;1439}