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 28/** 29 * Returns 1 if the file is empty or does not exist, 0 otherwise. 30 */ 31static intis_empty_file(const char*filename) 32{ 33struct stat st; 34 35if(stat(filename, &st) <0) { 36if(errno == ENOENT) 37return1; 38die_errno(_("could not stat%s"), filename); 39} 40 41return!st.st_size; 42} 43 44/** 45 * Like strbuf_getline(), but treats both '\n' and "\r\n" as line terminators. 46 */ 47static intstrbuf_getline_crlf(struct strbuf *sb,FILE*fp) 48{ 49if(strbuf_getwholeline(sb, fp,'\n')) 50return EOF; 51if(sb->buf[sb->len -1] =='\n') { 52strbuf_setlen(sb, sb->len -1); 53if(sb->len >0&& sb->buf[sb->len -1] =='\r') 54strbuf_setlen(sb, sb->len -1); 55} 56return0; 57} 58 59/** 60 * Returns the length of the first line of msg. 61 */ 62static intlinelen(const char*msg) 63{ 64returnstrchrnul(msg,'\n') - msg; 65} 66 67enum patch_format { 68 PATCH_FORMAT_UNKNOWN =0, 69 PATCH_FORMAT_MBOX 70}; 71 72enum keep_type { 73 KEEP_FALSE =0, 74 KEEP_TRUE,/* pass -k flag to git-mailinfo */ 75 KEEP_NON_PATCH /* pass -b flag to git-mailinfo */ 76}; 77 78enum scissors_type { 79 SCISSORS_UNSET = -1, 80 SCISSORS_FALSE =0,/* pass --no-scissors to git-mailinfo */ 81 SCISSORS_TRUE /* pass --scissors to git-mailinfo */ 82}; 83 84struct am_state { 85/* state directory path */ 86char*dir; 87 88/* current and last patch numbers, 1-indexed */ 89int cur; 90int last; 91 92/* commit metadata and message */ 93char*author_name; 94char*author_email; 95char*author_date; 96char*msg; 97size_t msg_len; 98 99/* when --rebasing, records the original commit the patch came from */ 100unsigned char orig_commit[GIT_SHA1_RAWSZ]; 101 102/* number of digits in patch filename */ 103int prec; 104 105/* various operating modes and command line options */ 106int threeway; 107int quiet; 108int signoff; 109int utf8; 110int keep;/* enum keep_type */ 111int message_id; 112int scissors;/* enum scissors_type */ 113struct argv_array git_apply_opts; 114const char*resolvemsg; 115int committer_date_is_author_date; 116int ignore_date; 117const char*sign_commit; 118int rebasing; 119}; 120 121/** 122 * Initializes am_state with the default values. The state directory is set to 123 * dir. 124 */ 125static voidam_state_init(struct am_state *state,const char*dir) 126{ 127int gpgsign; 128 129memset(state,0,sizeof(*state)); 130 131assert(dir); 132 state->dir =xstrdup(dir); 133 134 state->prec =4; 135 136 state->utf8 =1; 137 138git_config_get_bool("am.messageid", &state->message_id); 139 140 state->scissors = SCISSORS_UNSET; 141 142argv_array_init(&state->git_apply_opts); 143 144if(!git_config_get_bool("commit.gpgsign", &gpgsign)) 145 state->sign_commit = gpgsign ?"": NULL; 146} 147 148/** 149 * Releases memory allocated by an am_state. 150 */ 151static voidam_state_release(struct am_state *state) 152{ 153free(state->dir); 154free(state->author_name); 155free(state->author_email); 156free(state->author_date); 157free(state->msg); 158argv_array_clear(&state->git_apply_opts); 159} 160 161/** 162 * Returns path relative to the am_state directory. 163 */ 164staticinlineconst char*am_path(const struct am_state *state,const char*path) 165{ 166returnmkpath("%s/%s", state->dir, path); 167} 168 169/** 170 * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline 171 * at the end. 172 */ 173static voidsay(const struct am_state *state,FILE*fp,const char*fmt, ...) 174{ 175va_list ap; 176 177va_start(ap, fmt); 178if(!state->quiet) { 179vfprintf(fp, fmt, ap); 180putc('\n', fp); 181} 182va_end(ap); 183} 184 185/** 186 * Returns 1 if there is an am session in progress, 0 otherwise. 187 */ 188static intam_in_progress(const struct am_state *state) 189{ 190struct stat st; 191 192if(lstat(state->dir, &st) <0|| !S_ISDIR(st.st_mode)) 193return0; 194if(lstat(am_path(state,"last"), &st) || !S_ISREG(st.st_mode)) 195return0; 196if(lstat(am_path(state,"next"), &st) || !S_ISREG(st.st_mode)) 197return0; 198return1; 199} 200 201/** 202 * Reads the contents of `file` in the `state` directory into `sb`. Returns the 203 * number of bytes read on success, -1 if the file does not exist. If `trim` is 204 * set, trailing whitespace will be removed. 205 */ 206static intread_state_file(struct strbuf *sb,const struct am_state *state, 207const char*file,int trim) 208{ 209strbuf_reset(sb); 210 211if(strbuf_read_file(sb,am_path(state, file),0) >=0) { 212if(trim) 213strbuf_trim(sb); 214 215return sb->len; 216} 217 218if(errno == ENOENT) 219return-1; 220 221die_errno(_("could not read '%s'"),am_path(state, file)); 222} 223 224/** 225 * Reads a KEY=VALUE shell variable assignment from `fp`, returning the VALUE 226 * as a newly-allocated string. VALUE must be a quoted string, and the KEY must 227 * match `key`. Returns NULL on failure. 228 * 229 * This is used by read_author_script() to read the GIT_AUTHOR_* variables from 230 * the author-script. 231 */ 232static char*read_shell_var(FILE*fp,const char*key) 233{ 234struct strbuf sb = STRBUF_INIT; 235const char*str; 236 237if(strbuf_getline(&sb, fp,'\n')) 238goto fail; 239 240if(!skip_prefix(sb.buf, key, &str)) 241goto fail; 242 243if(!skip_prefix(str,"=", &str)) 244goto fail; 245 246strbuf_remove(&sb,0, str - sb.buf); 247 248 str =sq_dequote(sb.buf); 249if(!str) 250goto fail; 251 252returnstrbuf_detach(&sb, NULL); 253 254fail: 255strbuf_release(&sb); 256return NULL; 257} 258 259/** 260 * Reads and parses the state directory's "author-script" file, and sets 261 * state->author_name, state->author_email and state->author_date accordingly. 262 * Returns 0 on success, -1 if the file could not be parsed. 263 * 264 * The author script is of the format: 265 * 266 * GIT_AUTHOR_NAME='$author_name' 267 * GIT_AUTHOR_EMAIL='$author_email' 268 * GIT_AUTHOR_DATE='$author_date' 269 * 270 * where $author_name, $author_email and $author_date are quoted. We are strict 271 * with our parsing, as the file was meant to be eval'd in the old git-am.sh 272 * script, and thus if the file differs from what this function expects, it is 273 * better to bail out than to do something that the user does not expect. 274 */ 275static intread_author_script(struct am_state *state) 276{ 277const char*filename =am_path(state,"author-script"); 278FILE*fp; 279 280assert(!state->author_name); 281assert(!state->author_email); 282assert(!state->author_date); 283 284 fp =fopen(filename,"r"); 285if(!fp) { 286if(errno == ENOENT) 287return0; 288die_errno(_("could not open '%s' for reading"), filename); 289} 290 291 state->author_name =read_shell_var(fp,"GIT_AUTHOR_NAME"); 292if(!state->author_name) { 293fclose(fp); 294return-1; 295} 296 297 state->author_email =read_shell_var(fp,"GIT_AUTHOR_EMAIL"); 298if(!state->author_email) { 299fclose(fp); 300return-1; 301} 302 303 state->author_date =read_shell_var(fp,"GIT_AUTHOR_DATE"); 304if(!state->author_date) { 305fclose(fp); 306return-1; 307} 308 309if(fgetc(fp) != EOF) { 310fclose(fp); 311return-1; 312} 313 314fclose(fp); 315return0; 316} 317 318/** 319 * Saves state->author_name, state->author_email and state->author_date in the 320 * state directory's "author-script" file. 321 */ 322static voidwrite_author_script(const struct am_state *state) 323{ 324struct strbuf sb = STRBUF_INIT; 325 326strbuf_addstr(&sb,"GIT_AUTHOR_NAME="); 327sq_quote_buf(&sb, state->author_name); 328strbuf_addch(&sb,'\n'); 329 330strbuf_addstr(&sb,"GIT_AUTHOR_EMAIL="); 331sq_quote_buf(&sb, state->author_email); 332strbuf_addch(&sb,'\n'); 333 334strbuf_addstr(&sb,"GIT_AUTHOR_DATE="); 335sq_quote_buf(&sb, state->author_date); 336strbuf_addch(&sb,'\n'); 337 338write_file(am_path(state,"author-script"),1,"%s", sb.buf); 339 340strbuf_release(&sb); 341} 342 343/** 344 * Reads the commit message from the state directory's "final-commit" file, 345 * setting state->msg to its contents and state->msg_len to the length of its 346 * contents in bytes. 347 * 348 * Returns 0 on success, -1 if the file does not exist. 349 */ 350static intread_commit_msg(struct am_state *state) 351{ 352struct strbuf sb = STRBUF_INIT; 353 354assert(!state->msg); 355 356if(read_state_file(&sb, state,"final-commit",0) <0) { 357strbuf_release(&sb); 358return-1; 359} 360 361 state->msg =strbuf_detach(&sb, &state->msg_len); 362return0; 363} 364 365/** 366 * Saves state->msg in the state directory's "final-commit" file. 367 */ 368static voidwrite_commit_msg(const struct am_state *state) 369{ 370int fd; 371const char*filename =am_path(state,"final-commit"); 372 373 fd =xopen(filename, O_WRONLY | O_CREAT,0666); 374if(write_in_full(fd, state->msg, state->msg_len) <0) 375die_errno(_("could not write to%s"), filename); 376close(fd); 377} 378 379/** 380 * Loads state from disk. 381 */ 382static voidam_load(struct am_state *state) 383{ 384struct strbuf sb = STRBUF_INIT; 385 386if(read_state_file(&sb, state,"next",1) <0) 387die("BUG: state file 'next' does not exist"); 388 state->cur =strtol(sb.buf, NULL,10); 389 390if(read_state_file(&sb, state,"last",1) <0) 391die("BUG: state file 'last' does not exist"); 392 state->last =strtol(sb.buf, NULL,10); 393 394if(read_author_script(state) <0) 395die(_("could not parse author script")); 396 397read_commit_msg(state); 398 399if(read_state_file(&sb, state,"original-commit",1) <0) 400hashclr(state->orig_commit); 401else if(get_sha1_hex(sb.buf, state->orig_commit) <0) 402die(_("could not parse%s"),am_path(state,"original-commit")); 403 404read_state_file(&sb, state,"threeway",1); 405 state->threeway = !strcmp(sb.buf,"t"); 406 407read_state_file(&sb, state,"quiet",1); 408 state->quiet = !strcmp(sb.buf,"t"); 409 410read_state_file(&sb, state,"sign",1); 411 state->signoff = !strcmp(sb.buf,"t"); 412 413read_state_file(&sb, state,"utf8",1); 414 state->utf8 = !strcmp(sb.buf,"t"); 415 416read_state_file(&sb, state,"keep",1); 417if(!strcmp(sb.buf,"t")) 418 state->keep = KEEP_TRUE; 419else if(!strcmp(sb.buf,"b")) 420 state->keep = KEEP_NON_PATCH; 421else 422 state->keep = KEEP_FALSE; 423 424read_state_file(&sb, state,"messageid",1); 425 state->message_id = !strcmp(sb.buf,"t"); 426 427read_state_file(&sb, state,"scissors",1); 428if(!strcmp(sb.buf,"t")) 429 state->scissors = SCISSORS_TRUE; 430else if(!strcmp(sb.buf,"f")) 431 state->scissors = SCISSORS_FALSE; 432else 433 state->scissors = SCISSORS_UNSET; 434 435read_state_file(&sb, state,"apply-opt",1); 436argv_array_clear(&state->git_apply_opts); 437if(sq_dequote_to_argv_array(sb.buf, &state->git_apply_opts) <0) 438die(_("could not parse%s"),am_path(state,"apply-opt")); 439 440 state->rebasing = !!file_exists(am_path(state,"rebasing")); 441 442strbuf_release(&sb); 443} 444 445/** 446 * Removes the am_state directory, forcefully terminating the current am 447 * session. 448 */ 449static voidam_destroy(const struct am_state *state) 450{ 451struct strbuf sb = STRBUF_INIT; 452 453strbuf_addstr(&sb, state->dir); 454remove_dir_recursively(&sb,0); 455strbuf_release(&sb); 456} 457 458/** 459 * Runs post-rewrite hook. Returns it exit code. 460 */ 461static intrun_post_rewrite_hook(const struct am_state *state) 462{ 463struct child_process cp = CHILD_PROCESS_INIT; 464const char*hook =find_hook("post-rewrite"); 465int ret; 466 467if(!hook) 468return0; 469 470argv_array_push(&cp.args, hook); 471argv_array_push(&cp.args,"rebase"); 472 473 cp.in =xopen(am_path(state,"rewritten"), O_RDONLY); 474 cp.stdout_to_stderr =1; 475 476 ret =run_command(&cp); 477 478close(cp.in); 479return ret; 480} 481 482/** 483 * Reads the state directory's "rewritten" file, and copies notes from the old 484 * commits listed in the file to their rewritten commits. 485 * 486 * Returns 0 on success, -1 on failure. 487 */ 488static intcopy_notes_for_rebase(const struct am_state *state) 489{ 490struct notes_rewrite_cfg *c; 491struct strbuf sb = STRBUF_INIT; 492const char*invalid_line =_("Malformed input line: '%s'."); 493const char*msg ="Notes added by 'git rebase'"; 494FILE*fp; 495int ret =0; 496 497assert(state->rebasing); 498 499 c =init_copy_notes_for_rewrite("rebase"); 500if(!c) 501return0; 502 503 fp =xfopen(am_path(state,"rewritten"),"r"); 504 505while(!strbuf_getline(&sb, fp,'\n')) { 506unsigned char from_obj[GIT_SHA1_RAWSZ], to_obj[GIT_SHA1_RAWSZ]; 507 508if(sb.len != GIT_SHA1_HEXSZ *2+1) { 509 ret =error(invalid_line, sb.buf); 510goto finish; 511} 512 513if(get_sha1_hex(sb.buf, from_obj)) { 514 ret =error(invalid_line, sb.buf); 515goto finish; 516} 517 518if(sb.buf[GIT_SHA1_HEXSZ] !=' ') { 519 ret =error(invalid_line, sb.buf); 520goto finish; 521} 522 523if(get_sha1_hex(sb.buf + GIT_SHA1_HEXSZ +1, to_obj)) { 524 ret =error(invalid_line, sb.buf); 525goto finish; 526} 527 528if(copy_note_for_rewrite(c, from_obj, to_obj)) 529 ret =error(_("Failed to copy notes from '%s' to '%s'"), 530sha1_to_hex(from_obj),sha1_to_hex(to_obj)); 531} 532 533finish: 534finish_copy_notes_for_rewrite(c, msg); 535fclose(fp); 536strbuf_release(&sb); 537return ret; 538} 539 540/** 541 * Determines if the file looks like a piece of RFC2822 mail by grabbing all 542 * non-indented lines and checking if they look like they begin with valid 543 * header field names. 544 * 545 * Returns 1 if the file looks like a piece of mail, 0 otherwise. 546 */ 547static intis_mail(FILE*fp) 548{ 549const char*header_regex ="^[!-9;-~]+:"; 550struct strbuf sb = STRBUF_INIT; 551 regex_t regex; 552int ret =1; 553 554if(fseek(fp,0L, SEEK_SET)) 555die_errno(_("fseek failed")); 556 557if(regcomp(®ex, header_regex, REG_NOSUB | REG_EXTENDED)) 558die("invalid pattern:%s", header_regex); 559 560while(!strbuf_getline_crlf(&sb, fp)) { 561if(!sb.len) 562break;/* End of header */ 563 564/* Ignore indented folded lines */ 565if(*sb.buf =='\t'|| *sb.buf ==' ') 566continue; 567 568/* It's a header if it matches header_regex */ 569if(regexec(®ex, sb.buf,0, NULL,0)) { 570 ret =0; 571goto done; 572} 573} 574 575done: 576regfree(®ex); 577strbuf_release(&sb); 578return ret; 579} 580 581/** 582 * Attempts to detect the patch_format of the patches contained in `paths`, 583 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if 584 * detection fails. 585 */ 586static intdetect_patch_format(const char**paths) 587{ 588enum patch_format ret = PATCH_FORMAT_UNKNOWN; 589struct strbuf l1 = STRBUF_INIT; 590FILE*fp; 591 592/* 593 * We default to mbox format if input is from stdin and for directories 594 */ 595if(!*paths || !strcmp(*paths,"-") ||is_directory(*paths)) 596return PATCH_FORMAT_MBOX; 597 598/* 599 * Otherwise, check the first few lines of the first patch, starting 600 * from the first non-blank line, to try to detect its format. 601 */ 602 603 fp =xfopen(*paths,"r"); 604 605while(!strbuf_getline_crlf(&l1, fp)) { 606if(l1.len) 607break; 608} 609 610if(starts_with(l1.buf,"From ") ||starts_with(l1.buf,"From: ")) { 611 ret = PATCH_FORMAT_MBOX; 612goto done; 613} 614 615if(l1.len &&is_mail(fp)) { 616 ret = PATCH_FORMAT_MBOX; 617goto done; 618} 619 620done: 621fclose(fp); 622strbuf_release(&l1); 623return ret; 624} 625 626/** 627 * Splits out individual email patches from `paths`, where each path is either 628 * a mbox file or a Maildir. Returns 0 on success, -1 on failure. 629 */ 630static intsplit_mail_mbox(struct am_state *state,const char**paths,int keep_cr) 631{ 632struct child_process cp = CHILD_PROCESS_INIT; 633struct strbuf last = STRBUF_INIT; 634 635 cp.git_cmd =1; 636argv_array_push(&cp.args,"mailsplit"); 637argv_array_pushf(&cp.args,"-d%d", state->prec); 638argv_array_pushf(&cp.args,"-o%s", state->dir); 639argv_array_push(&cp.args,"-b"); 640if(keep_cr) 641argv_array_push(&cp.args,"--keep-cr"); 642argv_array_push(&cp.args,"--"); 643argv_array_pushv(&cp.args, paths); 644 645if(capture_command(&cp, &last,8)) 646return-1; 647 648 state->cur =1; 649 state->last =strtol(last.buf, NULL,10); 650 651return0; 652} 653 654/** 655 * Splits a list of files/directories into individual email patches. Each path 656 * in `paths` must be a file/directory that is formatted according to 657 * `patch_format`. 658 * 659 * Once split out, the individual email patches will be stored in the state 660 * directory, with each patch's filename being its index, padded to state->prec 661 * digits. 662 * 663 * state->cur will be set to the index of the first mail, and state->last will 664 * be set to the index of the last mail. 665 * 666 * Set keep_cr to 0 to convert all lines ending with \r\n to end with \n, 1 667 * to disable this behavior, -1 to use the default configured setting. 668 * 669 * Returns 0 on success, -1 on failure. 670 */ 671static intsplit_mail(struct am_state *state,enum patch_format patch_format, 672const char**paths,int keep_cr) 673{ 674if(keep_cr <0) { 675 keep_cr =0; 676git_config_get_bool("am.keepcr", &keep_cr); 677} 678 679switch(patch_format) { 680case PATCH_FORMAT_MBOX: 681returnsplit_mail_mbox(state, paths, keep_cr); 682default: 683die("BUG: invalid patch_format"); 684} 685return-1; 686} 687 688/** 689 * Setup a new am session for applying patches 690 */ 691static voidam_setup(struct am_state *state,enum patch_format patch_format, 692const char**paths,int keep_cr) 693{ 694unsigned char curr_head[GIT_SHA1_RAWSZ]; 695const char*str; 696struct strbuf sb = STRBUF_INIT; 697 698if(!patch_format) 699 patch_format =detect_patch_format(paths); 700 701if(!patch_format) { 702fprintf_ln(stderr,_("Patch format detection failed.")); 703exit(128); 704} 705 706if(mkdir(state->dir,0777) <0&& errno != EEXIST) 707die_errno(_("failed to create directory '%s'"), state->dir); 708 709if(split_mail(state, patch_format, paths, keep_cr) <0) { 710am_destroy(state); 711die(_("Failed to split patches.")); 712} 713 714if(state->rebasing) 715 state->threeway =1; 716 717write_file(am_path(state,"threeway"),1, state->threeway ?"t":"f"); 718 719write_file(am_path(state,"quiet"),1, state->quiet ?"t":"f"); 720 721write_file(am_path(state,"sign"),1, state->signoff ?"t":"f"); 722 723write_file(am_path(state,"utf8"),1, state->utf8 ?"t":"f"); 724 725switch(state->keep) { 726case KEEP_FALSE: 727 str ="f"; 728break; 729case KEEP_TRUE: 730 str ="t"; 731break; 732case KEEP_NON_PATCH: 733 str ="b"; 734break; 735default: 736die("BUG: invalid value for state->keep"); 737} 738 739write_file(am_path(state,"keep"),1,"%s", str); 740 741write_file(am_path(state,"messageid"),1, state->message_id ?"t":"f"); 742 743switch(state->scissors) { 744case SCISSORS_UNSET: 745 str =""; 746break; 747case SCISSORS_FALSE: 748 str ="f"; 749break; 750case SCISSORS_TRUE: 751 str ="t"; 752break; 753default: 754die("BUG: invalid value for state->scissors"); 755} 756 757write_file(am_path(state,"scissors"),1,"%s", str); 758 759sq_quote_argv(&sb, state->git_apply_opts.argv,0); 760write_file(am_path(state,"apply-opt"),1,"%s", sb.buf); 761 762if(state->rebasing) 763write_file(am_path(state,"rebasing"),1,"%s",""); 764else 765write_file(am_path(state,"applying"),1,"%s",""); 766 767if(!get_sha1("HEAD", curr_head)) { 768write_file(am_path(state,"abort-safety"),1,"%s",sha1_to_hex(curr_head)); 769if(!state->rebasing) 770update_ref("am","ORIG_HEAD", curr_head, NULL,0, 771 UPDATE_REFS_DIE_ON_ERR); 772}else{ 773write_file(am_path(state,"abort-safety"),1,"%s",""); 774if(!state->rebasing) 775delete_ref("ORIG_HEAD", NULL,0); 776} 777 778/* 779 * NOTE: Since the "next" and "last" files determine if an am_state 780 * session is in progress, they should be written last. 781 */ 782 783write_file(am_path(state,"next"),1,"%d", state->cur); 784 785write_file(am_path(state,"last"),1,"%d", state->last); 786 787strbuf_release(&sb); 788} 789 790/** 791 * Increments the patch pointer, and cleans am_state for the application of the 792 * next patch. 793 */ 794static voidam_next(struct am_state *state) 795{ 796unsigned char head[GIT_SHA1_RAWSZ]; 797 798free(state->author_name); 799 state->author_name = NULL; 800 801free(state->author_email); 802 state->author_email = NULL; 803 804free(state->author_date); 805 state->author_date = NULL; 806 807free(state->msg); 808 state->msg = NULL; 809 state->msg_len =0; 810 811unlink(am_path(state,"author-script")); 812unlink(am_path(state,"final-commit")); 813 814hashclr(state->orig_commit); 815unlink(am_path(state,"original-commit")); 816 817if(!get_sha1("HEAD", head)) 818write_file(am_path(state,"abort-safety"),1,"%s",sha1_to_hex(head)); 819else 820write_file(am_path(state,"abort-safety"),1,"%s",""); 821 822 state->cur++; 823write_file(am_path(state,"next"),1,"%d", state->cur); 824} 825 826/** 827 * Returns the filename of the current patch email. 828 */ 829static const char*msgnum(const struct am_state *state) 830{ 831static struct strbuf sb = STRBUF_INIT; 832 833strbuf_reset(&sb); 834strbuf_addf(&sb,"%0*d", state->prec, state->cur); 835 836return sb.buf; 837} 838 839/** 840 * Refresh and write index. 841 */ 842static voidrefresh_and_write_cache(void) 843{ 844struct lock_file *lock_file =xcalloc(1,sizeof(struct lock_file)); 845 846hold_locked_index(lock_file,1); 847refresh_cache(REFRESH_QUIET); 848if(write_locked_index(&the_index, lock_file, COMMIT_LOCK)) 849die(_("unable to write index file")); 850} 851 852/** 853 * Returns 1 if the index differs from HEAD, 0 otherwise. When on an unborn 854 * branch, returns 1 if there are entries in the index, 0 otherwise. If an 855 * strbuf is provided, the space-separated list of files that differ will be 856 * appended to it. 857 */ 858static intindex_has_changes(struct strbuf *sb) 859{ 860unsigned char head[GIT_SHA1_RAWSZ]; 861int i; 862 863if(!get_sha1_tree("HEAD", head)) { 864struct diff_options opt; 865 866diff_setup(&opt); 867DIFF_OPT_SET(&opt, EXIT_WITH_STATUS); 868if(!sb) 869DIFF_OPT_SET(&opt, QUICK); 870do_diff_cache(head, &opt); 871diffcore_std(&opt); 872for(i =0; sb && i < diff_queued_diff.nr; i++) { 873if(i) 874strbuf_addch(sb,' '); 875strbuf_addstr(sb, diff_queued_diff.queue[i]->two->path); 876} 877diff_flush(&opt); 878returnDIFF_OPT_TST(&opt, HAS_CHANGES) !=0; 879}else{ 880for(i =0; sb && i < active_nr; i++) { 881if(i) 882strbuf_addch(sb,' '); 883strbuf_addstr(sb, active_cache[i]->name); 884} 885return!!active_nr; 886} 887} 888 889/** 890 * Dies with a user-friendly message on how to proceed after resolving the 891 * problem. This message can be overridden with state->resolvemsg. 892 */ 893static void NORETURN die_user_resolve(const struct am_state *state) 894{ 895if(state->resolvemsg) { 896printf_ln("%s", state->resolvemsg); 897}else{ 898const char*cmdline ="git am"; 899 900printf_ln(_("When you have resolved this problem, run\"%s--continue\"."), cmdline); 901printf_ln(_("If you prefer to skip this patch, run\"%s--skip\"instead."), cmdline); 902printf_ln(_("To restore the original branch and stop patching, run\"%s--abort\"."), cmdline); 903} 904 905exit(128); 906} 907 908/** 909 * Parses `mail` using git-mailinfo, extracting its patch and authorship info. 910 * state->msg will be set to the patch message. state->author_name, 911 * state->author_email and state->author_date will be set to the patch author's 912 * name, email and date respectively. The patch body will be written to the 913 * state directory's "patch" file. 914 * 915 * Returns 1 if the patch should be skipped, 0 otherwise. 916 */ 917static intparse_mail(struct am_state *state,const char*mail) 918{ 919FILE*fp; 920struct child_process cp = CHILD_PROCESS_INIT; 921struct strbuf sb = STRBUF_INIT; 922struct strbuf msg = STRBUF_INIT; 923struct strbuf author_name = STRBUF_INIT; 924struct strbuf author_date = STRBUF_INIT; 925struct strbuf author_email = STRBUF_INIT; 926int ret =0; 927 928 cp.git_cmd =1; 929 cp.in =xopen(mail, O_RDONLY,0); 930 cp.out =xopen(am_path(state,"info"), O_WRONLY | O_CREAT,0777); 931 932argv_array_push(&cp.args,"mailinfo"); 933argv_array_push(&cp.args, state->utf8 ?"-u":"-n"); 934 935switch(state->keep) { 936case KEEP_FALSE: 937break; 938case KEEP_TRUE: 939argv_array_push(&cp.args,"-k"); 940break; 941case KEEP_NON_PATCH: 942argv_array_push(&cp.args,"-b"); 943break; 944default: 945die("BUG: invalid value for state->keep"); 946} 947 948if(state->message_id) 949argv_array_push(&cp.args,"-m"); 950 951switch(state->scissors) { 952case SCISSORS_UNSET: 953break; 954case SCISSORS_FALSE: 955argv_array_push(&cp.args,"--no-scissors"); 956break; 957case SCISSORS_TRUE: 958argv_array_push(&cp.args,"--scissors"); 959break; 960default: 961die("BUG: invalid value for state->scissors"); 962} 963 964argv_array_push(&cp.args,am_path(state,"msg")); 965argv_array_push(&cp.args,am_path(state,"patch")); 966 967if(run_command(&cp) <0) 968die("could not parse patch"); 969 970close(cp.in); 971close(cp.out); 972 973/* Extract message and author information */ 974 fp =xfopen(am_path(state,"info"),"r"); 975while(!strbuf_getline(&sb, fp,'\n')) { 976const char*x; 977 978if(skip_prefix(sb.buf,"Subject: ", &x)) { 979if(msg.len) 980strbuf_addch(&msg,'\n'); 981strbuf_addstr(&msg, x); 982}else if(skip_prefix(sb.buf,"Author: ", &x)) 983strbuf_addstr(&author_name, x); 984else if(skip_prefix(sb.buf,"Email: ", &x)) 985strbuf_addstr(&author_email, x); 986else if(skip_prefix(sb.buf,"Date: ", &x)) 987strbuf_addstr(&author_date, x); 988} 989fclose(fp); 990 991/* Skip pine's internal folder data */ 992if(!strcmp(author_name.buf,"Mail System Internal Data")) { 993 ret =1; 994goto finish; 995} 996 997if(is_empty_file(am_path(state,"patch"))) { 998printf_ln(_("Patch is empty. Was it split wrong?")); 999die_user_resolve(state);1000}10011002strbuf_addstr(&msg,"\n\n");1003if(strbuf_read_file(&msg,am_path(state,"msg"),0) <0)1004die_errno(_("could not read '%s'"),am_path(state,"msg"));1005stripspace(&msg,0);10061007if(state->signoff)1008append_signoff(&msg,0,0);10091010assert(!state->author_name);1011 state->author_name =strbuf_detach(&author_name, NULL);10121013assert(!state->author_email);1014 state->author_email =strbuf_detach(&author_email, NULL);10151016assert(!state->author_date);1017 state->author_date =strbuf_detach(&author_date, NULL);10181019assert(!state->msg);1020 state->msg =strbuf_detach(&msg, &state->msg_len);10211022finish:1023strbuf_release(&msg);1024strbuf_release(&author_date);1025strbuf_release(&author_email);1026strbuf_release(&author_name);1027strbuf_release(&sb);1028return ret;1029}10301031/**1032 * Sets commit_id to the commit hash where the mail was generated from.1033 * Returns 0 on success, -1 on failure.1034 */1035static intget_mail_commit_sha1(unsigned char*commit_id,const char*mail)1036{1037struct strbuf sb = STRBUF_INIT;1038FILE*fp =xfopen(mail,"r");1039const char*x;10401041if(strbuf_getline(&sb, fp,'\n'))1042return-1;10431044if(!skip_prefix(sb.buf,"From ", &x))1045return-1;10461047if(get_sha1_hex(x, commit_id) <0)1048return-1;10491050strbuf_release(&sb);1051fclose(fp);1052return0;1053}10541055/**1056 * Sets state->msg, state->author_name, state->author_email, state->author_date1057 * to the commit's respective info.1058 */1059static voidget_commit_info(struct am_state *state,struct commit *commit)1060{1061const char*buffer, *ident_line, *author_date, *msg;1062size_t ident_len;1063struct ident_split ident_split;1064struct strbuf sb = STRBUF_INIT;10651066 buffer =logmsg_reencode(commit, NULL,get_commit_output_encoding());10671068 ident_line =find_commit_header(buffer,"author", &ident_len);10691070if(split_ident_line(&ident_split, ident_line, ident_len) <0) {1071strbuf_add(&sb, ident_line, ident_len);1072die(_("invalid ident line:%s"), sb.buf);1073}10741075assert(!state->author_name);1076if(ident_split.name_begin) {1077strbuf_add(&sb, ident_split.name_begin,1078 ident_split.name_end - ident_split.name_begin);1079 state->author_name =strbuf_detach(&sb, NULL);1080}else1081 state->author_name =xstrdup("");10821083assert(!state->author_email);1084if(ident_split.mail_begin) {1085strbuf_add(&sb, ident_split.mail_begin,1086 ident_split.mail_end - ident_split.mail_begin);1087 state->author_email =strbuf_detach(&sb, NULL);1088}else1089 state->author_email =xstrdup("");10901091 author_date =show_ident_date(&ident_split,DATE_MODE(NORMAL));1092strbuf_addstr(&sb, author_date);1093assert(!state->author_date);1094 state->author_date =strbuf_detach(&sb, NULL);10951096assert(!state->msg);1097 msg =strstr(buffer,"\n\n");1098if(!msg)1099die(_("unable to parse commit%s"),sha1_to_hex(commit->object.sha1));1100 state->msg =xstrdup(msg +2);1101 state->msg_len =strlen(state->msg);1102}11031104/**1105 * Writes `commit` as a patch to the state directory's "patch" file.1106 */1107static voidwrite_commit_patch(const struct am_state *state,struct commit *commit)1108{1109struct rev_info rev_info;1110FILE*fp;11111112 fp =xfopen(am_path(state,"patch"),"w");1113init_revisions(&rev_info, NULL);1114 rev_info.diff =1;1115 rev_info.abbrev =0;1116 rev_info.disable_stdin =1;1117 rev_info.show_root_diff =1;1118 rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;1119 rev_info.no_commit_id =1;1120DIFF_OPT_SET(&rev_info.diffopt, BINARY);1121DIFF_OPT_SET(&rev_info.diffopt, FULL_INDEX);1122 rev_info.diffopt.use_color =0;1123 rev_info.diffopt.file = fp;1124 rev_info.diffopt.close_file =1;1125add_pending_object(&rev_info, &commit->object,"");1126diff_setup_done(&rev_info.diffopt);1127log_tree_commit(&rev_info, commit);1128}11291130/**1131 * Like parse_mail(), but parses the mail by looking up its commit ID1132 * directly. This is used in --rebasing mode to bypass git-mailinfo's munging1133 * of patches.1134 *1135 * state->orig_commit will be set to the original commit ID.1136 *1137 * Will always return 0 as the patch should never be skipped.1138 */1139static intparse_mail_rebase(struct am_state *state,const char*mail)1140{1141struct commit *commit;1142unsigned char commit_sha1[GIT_SHA1_RAWSZ];11431144if(get_mail_commit_sha1(commit_sha1, mail) <0)1145die(_("could not parse%s"), mail);11461147 commit =lookup_commit_or_die(commit_sha1, mail);11481149get_commit_info(state, commit);11501151write_commit_patch(state, commit);11521153hashcpy(state->orig_commit, commit_sha1);1154write_file(am_path(state,"original-commit"),1,"%s",1155sha1_to_hex(commit_sha1));11561157return0;1158}11591160/**1161 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If1162 * `index_file` is not NULL, the patch will be applied to that index.1163 */1164static intrun_apply(const struct am_state *state,const char*index_file)1165{1166struct child_process cp = CHILD_PROCESS_INIT;11671168 cp.git_cmd =1;11691170if(index_file)1171argv_array_pushf(&cp.env_array,"GIT_INDEX_FILE=%s", index_file);11721173/*1174 * If we are allowed to fall back on 3-way merge, don't give false1175 * errors during the initial attempt.1176 */1177if(state->threeway && !index_file) {1178 cp.no_stdout =1;1179 cp.no_stderr =1;1180}11811182argv_array_push(&cp.args,"apply");11831184argv_array_pushv(&cp.args, state->git_apply_opts.argv);11851186if(index_file)1187argv_array_push(&cp.args,"--cached");1188else1189argv_array_push(&cp.args,"--index");11901191argv_array_push(&cp.args,am_path(state,"patch"));11921193if(run_command(&cp))1194return-1;11951196/* Reload index as git-apply will have modified it. */1197discard_cache();1198read_cache_from(index_file ? index_file :get_index_file());11991200return0;1201}12021203/**1204 * Builds an index that contains just the blobs needed for a 3way merge.1205 */1206static intbuild_fake_ancestor(const struct am_state *state,const char*index_file)1207{1208struct child_process cp = CHILD_PROCESS_INIT;12091210 cp.git_cmd =1;1211argv_array_push(&cp.args,"apply");1212argv_array_pushv(&cp.args, state->git_apply_opts.argv);1213argv_array_pushf(&cp.args,"--build-fake-ancestor=%s", index_file);1214argv_array_push(&cp.args,am_path(state,"patch"));12151216if(run_command(&cp))1217return-1;12181219return0;1220}12211222/**1223 * Attempt a threeway merge, using index_path as the temporary index.1224 */1225static intfall_back_threeway(const struct am_state *state,const char*index_path)1226{1227unsigned char orig_tree[GIT_SHA1_RAWSZ], his_tree[GIT_SHA1_RAWSZ],1228 our_tree[GIT_SHA1_RAWSZ];1229const unsigned char*bases[1] = {orig_tree};1230struct merge_options o;1231struct commit *result;1232char*his_tree_name;12331234if(get_sha1("HEAD", our_tree) <0)1235hashcpy(our_tree, EMPTY_TREE_SHA1_BIN);12361237if(build_fake_ancestor(state, index_path))1238returnerror("could not build fake ancestor");12391240discard_cache();1241read_cache_from(index_path);12421243if(write_index_as_tree(orig_tree, &the_index, index_path,0, NULL))1244returnerror(_("Repository lacks necessary blobs to fall back on 3-way merge."));12451246say(state, stdout,_("Using index info to reconstruct a base tree..."));12471248if(!state->quiet) {1249/*1250 * List paths that needed 3-way fallback, so that the user can1251 * review them with extra care to spot mismerges.1252 */1253struct rev_info rev_info;1254const char*diff_filter_str ="--diff-filter=AM";12551256init_revisions(&rev_info, NULL);1257 rev_info.diffopt.output_format = DIFF_FORMAT_NAME_STATUS;1258diff_opt_parse(&rev_info.diffopt, &diff_filter_str,1);1259add_pending_sha1(&rev_info,"HEAD", our_tree,0);1260diff_setup_done(&rev_info.diffopt);1261run_diff_index(&rev_info,1);1262}12631264if(run_apply(state, index_path))1265returnerror(_("Did you hand edit your patch?\n"1266"It does not apply to blobs recorded in its index."));12671268if(write_index_as_tree(his_tree, &the_index, index_path,0, NULL))1269returnerror("could not write tree");12701271say(state, stdout,_("Falling back to patching base and 3-way merge..."));12721273discard_cache();1274read_cache();12751276/*1277 * This is not so wrong. Depending on which base we picked, orig_tree1278 * may be wildly different from ours, but his_tree has the same set of1279 * wildly different changes in parts the patch did not touch, so1280 * recursive ends up canceling them, saying that we reverted all those1281 * changes.1282 */12831284init_merge_options(&o);12851286 o.branch1 ="HEAD";1287 his_tree_name =xstrfmt("%.*s",linelen(state->msg), state->msg);1288 o.branch2 = his_tree_name;12891290if(state->quiet)1291 o.verbosity =0;12921293if(merge_recursive_generic(&o, our_tree, his_tree,1, bases, &result)) {1294free(his_tree_name);1295returnerror(_("Failed to merge in the changes."));1296}12971298free(his_tree_name);1299return0;1300}13011302/**1303 * Commits the current index with state->msg as the commit message and1304 * state->author_name, state->author_email and state->author_date as the author1305 * information.1306 */1307static voiddo_commit(const struct am_state *state)1308{1309unsigned char tree[GIT_SHA1_RAWSZ], parent[GIT_SHA1_RAWSZ],1310 commit[GIT_SHA1_RAWSZ];1311unsigned char*ptr;1312struct commit_list *parents = NULL;1313const char*reflog_msg, *author;1314struct strbuf sb = STRBUF_INIT;13151316if(write_cache_as_tree(tree,0, NULL))1317die(_("git write-tree failed to write a tree"));13181319if(!get_sha1_commit("HEAD", parent)) {1320 ptr = parent;1321commit_list_insert(lookup_commit(parent), &parents);1322}else{1323 ptr = NULL;1324say(state, stderr,_("applying to an empty history"));1325}13261327 author =fmt_ident(state->author_name, state->author_email,1328 state->ignore_date ? NULL : state->author_date,1329 IDENT_STRICT);13301331if(state->committer_date_is_author_date)1332setenv("GIT_COMMITTER_DATE",1333 state->ignore_date ?"": state->author_date,1);13341335if(commit_tree(state->msg, state->msg_len, tree, parents, commit,1336 author, state->sign_commit))1337die(_("failed to write commit object"));13381339 reflog_msg =getenv("GIT_REFLOG_ACTION");1340if(!reflog_msg)1341 reflog_msg ="am";13421343strbuf_addf(&sb,"%s: %.*s", reflog_msg,linelen(state->msg),1344 state->msg);13451346update_ref(sb.buf,"HEAD", commit, ptr,0, UPDATE_REFS_DIE_ON_ERR);13471348if(state->rebasing) {1349FILE*fp =xfopen(am_path(state,"rewritten"),"a");13501351assert(!is_null_sha1(state->orig_commit));1352fprintf(fp,"%s",sha1_to_hex(state->orig_commit));1353fprintf(fp,"%s\n",sha1_to_hex(commit));1354fclose(fp);1355}13561357strbuf_release(&sb);1358}13591360/**1361 * Validates the am_state for resuming -- the "msg" and authorship fields must1362 * be filled up.1363 */1364static voidvalidate_resume_state(const struct am_state *state)1365{1366if(!state->msg)1367die(_("cannot resume:%sdoes not exist."),1368am_path(state,"final-commit"));13691370if(!state->author_name || !state->author_email || !state->author_date)1371die(_("cannot resume:%sdoes not exist."),1372am_path(state,"author-script"));1373}13741375/**1376 * Applies all queued mail.1377 *1378 * If `resume` is true, we are "resuming". The "msg" and authorship fields, as1379 * well as the state directory's "patch" file is used as-is for applying the1380 * patch and committing it.1381 */1382static voidam_run(struct am_state *state,int resume)1383{1384const char*argv_gc_auto[] = {"gc","--auto", NULL};1385struct strbuf sb = STRBUF_INIT;13861387unlink(am_path(state,"dirtyindex"));13881389refresh_and_write_cache();13901391if(index_has_changes(&sb)) {1392write_file(am_path(state,"dirtyindex"),1,"t");1393die(_("Dirty index: cannot apply patches (dirty:%s)"), sb.buf);1394}13951396strbuf_release(&sb);13971398while(state->cur <= state->last) {1399const char*mail =am_path(state,msgnum(state));1400int apply_status;14011402if(!file_exists(mail))1403goto next;14041405if(resume) {1406validate_resume_state(state);1407 resume =0;1408}else{1409int skip;14101411if(state->rebasing)1412 skip =parse_mail_rebase(state, mail);1413else1414 skip =parse_mail(state, mail);14151416if(skip)1417goto next;/* mail should be skipped */14181419write_author_script(state);1420write_commit_msg(state);1421}14221423say(state, stdout,_("Applying: %.*s"),linelen(state->msg), state->msg);14241425 apply_status =run_apply(state, NULL);14261427if(apply_status && state->threeway) {1428struct strbuf sb = STRBUF_INIT;14291430strbuf_addstr(&sb,am_path(state,"patch-merge-index"));1431 apply_status =fall_back_threeway(state, sb.buf);1432strbuf_release(&sb);14331434/*1435 * Applying the patch to an earlier tree and merging1436 * the result may have produced the same tree as ours.1437 */1438if(!apply_status && !index_has_changes(NULL)) {1439say(state, stdout,_("No changes -- Patch already applied."));1440goto next;1441}1442}14431444if(apply_status) {1445int advice_amworkdir =1;14461447printf_ln(_("Patch failed at%s%.*s"),msgnum(state),1448linelen(state->msg), state->msg);14491450git_config_get_bool("advice.amworkdir", &advice_amworkdir);14511452if(advice_amworkdir)1453printf_ln(_("The copy of the patch that failed is found in:%s"),1454am_path(state,"patch"));14551456die_user_resolve(state);1457}14581459do_commit(state);14601461next:1462am_next(state);1463}14641465if(!is_empty_file(am_path(state,"rewritten"))) {1466assert(state->rebasing);1467copy_notes_for_rebase(state);1468run_post_rewrite_hook(state);1469}14701471/*1472 * In rebasing mode, it's up to the caller to take care of1473 * housekeeping.1474 */1475if(!state->rebasing) {1476am_destroy(state);1477run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);1478}1479}14801481/**1482 * Resume the current am session after patch application failure. The user did1483 * all the hard work, and we do not have to do any patch application. Just1484 * trust and commit what the user has in the index and working tree.1485 */1486static voidam_resolve(struct am_state *state)1487{1488validate_resume_state(state);14891490say(state, stdout,_("Applying: %.*s"),linelen(state->msg), state->msg);14911492if(!index_has_changes(NULL)) {1493printf_ln(_("No changes - did you forget to use 'git add'?\n"1494"If there is nothing left to stage, chances are that something else\n"1495"already introduced the same changes; you might want to skip this patch."));1496die_user_resolve(state);1497}14981499if(unmerged_cache()) {1500printf_ln(_("You still have unmerged paths in your index.\n"1501"Did you forget to use 'git add'?"));1502die_user_resolve(state);1503}15041505do_commit(state);15061507am_next(state);1508am_run(state,0);1509}15101511/**1512 * Performs a checkout fast-forward from `head` to `remote`. If `reset` is1513 * true, any unmerged entries will be discarded. Returns 0 on success, -1 on1514 * failure.1515 */1516static intfast_forward_to(struct tree *head,struct tree *remote,int reset)1517{1518struct lock_file *lock_file;1519struct unpack_trees_options opts;1520struct tree_desc t[2];15211522if(parse_tree(head) ||parse_tree(remote))1523return-1;15241525 lock_file =xcalloc(1,sizeof(struct lock_file));1526hold_locked_index(lock_file,1);15271528refresh_cache(REFRESH_QUIET);15291530memset(&opts,0,sizeof(opts));1531 opts.head_idx =1;1532 opts.src_index = &the_index;1533 opts.dst_index = &the_index;1534 opts.update =1;1535 opts.merge =1;1536 opts.reset = reset;1537 opts.fn = twoway_merge;1538init_tree_desc(&t[0], head->buffer, head->size);1539init_tree_desc(&t[1], remote->buffer, remote->size);15401541if(unpack_trees(2, t, &opts)) {1542rollback_lock_file(lock_file);1543return-1;1544}15451546if(write_locked_index(&the_index, lock_file, COMMIT_LOCK))1547die(_("unable to write new index file"));15481549return0;1550}15511552/**1553 * Clean the index without touching entries that are not modified between1554 * `head` and `remote`.1555 */1556static intclean_index(const unsigned char*head,const unsigned char*remote)1557{1558struct lock_file *lock_file;1559struct tree *head_tree, *remote_tree, *index_tree;1560unsigned char index[GIT_SHA1_RAWSZ];1561struct pathspec pathspec;15621563 head_tree =parse_tree_indirect(head);1564if(!head_tree)1565returnerror(_("Could not parse object '%s'."),sha1_to_hex(head));15661567 remote_tree =parse_tree_indirect(remote);1568if(!remote_tree)1569returnerror(_("Could not parse object '%s'."),sha1_to_hex(remote));15701571read_cache_unmerged();15721573if(fast_forward_to(head_tree, head_tree,1))1574return-1;15751576if(write_cache_as_tree(index,0, NULL))1577return-1;15781579 index_tree =parse_tree_indirect(index);1580if(!index_tree)1581returnerror(_("Could not parse object '%s'."),sha1_to_hex(index));15821583if(fast_forward_to(index_tree, remote_tree,0))1584return-1;15851586memset(&pathspec,0,sizeof(pathspec));15871588 lock_file =xcalloc(1,sizeof(struct lock_file));1589hold_locked_index(lock_file,1);15901591if(read_tree(remote_tree,0, &pathspec)) {1592rollback_lock_file(lock_file);1593return-1;1594}15951596if(write_locked_index(&the_index, lock_file, COMMIT_LOCK))1597die(_("unable to write new index file"));15981599remove_branch_state();16001601return0;1602}16031604/**1605 * Resume the current am session by skipping the current patch.1606 */1607static voidam_skip(struct am_state *state)1608{1609unsigned char head[GIT_SHA1_RAWSZ];16101611if(get_sha1("HEAD", head))1612hashcpy(head, EMPTY_TREE_SHA1_BIN);16131614if(clean_index(head, head))1615die(_("failed to clean index"));16161617am_next(state);1618am_run(state,0);1619}16201621/**1622 * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.1623 *1624 * It is not safe to reset HEAD when:1625 * 1. git-am previously failed because the index was dirty.1626 * 2. HEAD has moved since git-am previously failed.1627 */1628static intsafe_to_abort(const struct am_state *state)1629{1630struct strbuf sb = STRBUF_INIT;1631unsigned char abort_safety[GIT_SHA1_RAWSZ], head[GIT_SHA1_RAWSZ];16321633if(file_exists(am_path(state,"dirtyindex")))1634return0;16351636if(read_state_file(&sb, state,"abort-safety",1) >0) {1637if(get_sha1_hex(sb.buf, abort_safety))1638die(_("could not parse%s"),am_path(state,"abort_safety"));1639}else1640hashclr(abort_safety);16411642if(get_sha1("HEAD", head))1643hashclr(head);16441645if(!hashcmp(head, abort_safety))1646return1;16471648error(_("You seem to have moved HEAD since the last 'am' failure.\n"1649"Not rewinding to ORIG_HEAD"));16501651return0;1652}16531654/**1655 * Aborts the current am session if it is safe to do so.1656 */1657static voidam_abort(struct am_state *state)1658{1659unsigned char curr_head[GIT_SHA1_RAWSZ], orig_head[GIT_SHA1_RAWSZ];1660int has_curr_head, has_orig_head;1661char*curr_branch;16621663if(!safe_to_abort(state)) {1664am_destroy(state);1665return;1666}16671668 curr_branch =resolve_refdup("HEAD",0, curr_head, NULL);1669 has_curr_head = !is_null_sha1(curr_head);1670if(!has_curr_head)1671hashcpy(curr_head, EMPTY_TREE_SHA1_BIN);16721673 has_orig_head = !get_sha1("ORIG_HEAD", orig_head);1674if(!has_orig_head)1675hashcpy(orig_head, EMPTY_TREE_SHA1_BIN);16761677clean_index(curr_head, orig_head);16781679if(has_orig_head)1680update_ref("am --abort","HEAD", orig_head,1681 has_curr_head ? curr_head : NULL,0,1682 UPDATE_REFS_DIE_ON_ERR);1683else if(curr_branch)1684delete_ref(curr_branch, NULL, REF_NODEREF);16851686free(curr_branch);1687am_destroy(state);1688}16891690/**1691 * parse_options() callback that validates and sets opt->value to the1692 * PATCH_FORMAT_* enum value corresponding to `arg`.1693 */1694static intparse_opt_patchformat(const struct option *opt,const char*arg,int unset)1695{1696int*opt_value = opt->value;16971698if(!strcmp(arg,"mbox"))1699*opt_value = PATCH_FORMAT_MBOX;1700else1701returnerror(_("Invalid value for --patch-format:%s"), arg);1702return0;1703}17041705enum resume_mode {1706 RESUME_FALSE =0,1707 RESUME_APPLY,1708 RESUME_RESOLVED,1709 RESUME_SKIP,1710 RESUME_ABORT1711};17121713intcmd_am(int argc,const char**argv,const char*prefix)1714{1715struct am_state state;1716int keep_cr = -1;1717int patch_format = PATCH_FORMAT_UNKNOWN;1718enum resume_mode resume = RESUME_FALSE;17191720const char*const usage[] = {1721N_("git am [options] [(<mbox>|<Maildir>)...]"),1722N_("git am [options] (--continue | --skip | --abort)"),1723 NULL1724};17251726struct option options[] = {1727OPT_BOOL('3',"3way", &state.threeway,1728N_("allow fall back on 3way merging if needed")),1729OPT__QUIET(&state.quiet,N_("be quiet")),1730OPT_BOOL('s',"signoff", &state.signoff,1731N_("add a Signed-off-by line to the commit message")),1732OPT_BOOL('u',"utf8", &state.utf8,1733N_("recode into utf8 (default)")),1734OPT_SET_INT('k',"keep", &state.keep,1735N_("pass -k flag to git-mailinfo"), KEEP_TRUE),1736OPT_SET_INT(0,"keep-non-patch", &state.keep,1737N_("pass -b flag to git-mailinfo"), KEEP_NON_PATCH),1738OPT_BOOL('m',"message-id", &state.message_id,1739N_("pass -m flag to git-mailinfo")),1740{ OPTION_SET_INT,0,"keep-cr", &keep_cr, NULL,1741N_("pass --keep-cr flag to git-mailsplit for mbox format"),1742 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL,1},1743{ OPTION_SET_INT,0,"no-keep-cr", &keep_cr, NULL,1744N_("do not pass --keep-cr flag to git-mailsplit independent of am.keepcr"),1745 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL,0},1746OPT_BOOL('c',"scissors", &state.scissors,1747N_("strip everything before a scissors line")),1748OPT_PASSTHRU_ARGV(0,"whitespace", &state.git_apply_opts,N_("action"),1749N_("pass it through git-apply"),17500),1751OPT_PASSTHRU_ARGV(0,"ignore-space-change", &state.git_apply_opts, NULL,1752N_("pass it through git-apply"),1753 PARSE_OPT_NOARG),1754OPT_PASSTHRU_ARGV(0,"ignore-whitespace", &state.git_apply_opts, NULL,1755N_("pass it through git-apply"),1756 PARSE_OPT_NOARG),1757OPT_PASSTHRU_ARGV(0,"directory", &state.git_apply_opts,N_("root"),1758N_("pass it through git-apply"),17590),1760OPT_PASSTHRU_ARGV(0,"exclude", &state.git_apply_opts,N_("path"),1761N_("pass it through git-apply"),17620),1763OPT_PASSTHRU_ARGV(0,"include", &state.git_apply_opts,N_("path"),1764N_("pass it through git-apply"),17650),1766OPT_PASSTHRU_ARGV('C', NULL, &state.git_apply_opts,N_("n"),1767N_("pass it through git-apply"),17680),1769OPT_PASSTHRU_ARGV('p', NULL, &state.git_apply_opts,N_("num"),1770N_("pass it through git-apply"),17710),1772OPT_CALLBACK(0,"patch-format", &patch_format,N_("format"),1773N_("format the patch(es) are in"),1774 parse_opt_patchformat),1775OPT_PASSTHRU_ARGV(0,"reject", &state.git_apply_opts, NULL,1776N_("pass it through git-apply"),1777 PARSE_OPT_NOARG),1778OPT_STRING(0,"resolvemsg", &state.resolvemsg, NULL,1779N_("override error message when patch failure occurs")),1780OPT_CMDMODE(0,"continue", &resume,1781N_("continue applying patches after resolving a conflict"),1782 RESUME_RESOLVED),1783OPT_CMDMODE('r',"resolved", &resume,1784N_("synonyms for --continue"),1785 RESUME_RESOLVED),1786OPT_CMDMODE(0,"skip", &resume,1787N_("skip the current patch"),1788 RESUME_SKIP),1789OPT_CMDMODE(0,"abort", &resume,1790N_("restore the original branch and abort the patching operation."),1791 RESUME_ABORT),1792OPT_BOOL(0,"committer-date-is-author-date",1793&state.committer_date_is_author_date,1794N_("lie about committer date")),1795OPT_BOOL(0,"ignore-date", &state.ignore_date,1796N_("use current timestamp for author date")),1797{ OPTION_STRING,'S',"gpg-sign", &state.sign_commit,N_("key-id"),1798N_("GPG-sign commits"),1799 PARSE_OPT_OPTARG, NULL, (intptr_t)""},1800OPT_HIDDEN_BOOL(0,"rebasing", &state.rebasing,1801N_("(internal use for git-rebase)")),1802OPT_END()1803};18041805/*1806 * NEEDSWORK: Once all the features of git-am.sh have been1807 * re-implemented in builtin/am.c, this preamble can be removed.1808 */1809if(!getenv("_GIT_USE_BUILTIN_AM")) {1810const char*path =mkpath("%s/git-am",git_exec_path());18111812if(sane_execvp(path, (char**)argv) <0)1813die_errno("could not exec%s", path);1814}else{1815 prefix =setup_git_directory();1816trace_repo_setup(prefix);1817setup_work_tree();1818}18191820git_config(git_default_config, NULL);18211822am_state_init(&state,git_path("rebase-apply"));18231824 argc =parse_options(argc, argv, prefix, options, usage,0);18251826if(read_index_preload(&the_index, NULL) <0)1827die(_("failed to read the index"));18281829if(am_in_progress(&state)) {1830/*1831 * Catch user error to feed us patches when there is a session1832 * in progress:1833 *1834 * 1. mbox path(s) are provided on the command-line.1835 * 2. stdin is not a tty: the user is trying to feed us a patch1836 * from standard input. This is somewhat unreliable -- stdin1837 * could be /dev/null for example and the caller did not1838 * intend to feed us a patch but wanted to continue1839 * unattended.1840 */1841if(argc || (resume == RESUME_FALSE && !isatty(0)))1842die(_("previous rebase directory%sstill exists but mbox given."),1843 state.dir);18441845if(resume == RESUME_FALSE)1846 resume = RESUME_APPLY;18471848am_load(&state);1849}else{1850struct argv_array paths = ARGV_ARRAY_INIT;1851int i;18521853/*1854 * Handle stray state directory in the independent-run case. In1855 * the --rebasing case, it is up to the caller to take care of1856 * stray directories.1857 */1858if(file_exists(state.dir) && !state.rebasing) {1859if(resume == RESUME_ABORT) {1860am_destroy(&state);1861am_state_release(&state);1862return0;1863}18641865die(_("Stray%sdirectory found.\n"1866"Use\"git am --abort\"to remove it."),1867 state.dir);1868}18691870if(resume)1871die(_("Resolve operation not in progress, we are not resuming."));18721873for(i =0; i < argc; i++) {1874if(is_absolute_path(argv[i]) || !prefix)1875argv_array_push(&paths, argv[i]);1876else1877argv_array_push(&paths,mkpath("%s/%s", prefix, argv[i]));1878}18791880am_setup(&state, patch_format, paths.argv, keep_cr);18811882argv_array_clear(&paths);1883}18841885switch(resume) {1886case RESUME_FALSE:1887am_run(&state,0);1888break;1889case RESUME_APPLY:1890am_run(&state,1);1891break;1892case RESUME_RESOLVED:1893am_resolve(&state);1894break;1895case RESUME_SKIP:1896am_skip(&state);1897break;1898case RESUME_ABORT:1899am_abort(&state);1900break;1901default:1902die("BUG: invalid resume value");1903}19041905am_state_release(&state);19061907return0;1908}