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 applypatch-msg hook. Returns its exit code. 460 */ 461static intrun_applypatch_msg_hook(struct am_state *state) 462{ 463int ret; 464 465assert(state->msg); 466 ret =run_hook_le(NULL,"applypatch-msg",am_path(state,"final-commit"), NULL); 467 468if(!ret) { 469free(state->msg); 470 state->msg = NULL; 471if(read_commit_msg(state) <0) 472die(_("'%s' was deleted by the applypatch-msg hook"), 473am_path(state,"final-commit")); 474} 475 476return ret; 477} 478 479/** 480 * Runs post-rewrite hook. Returns it exit code. 481 */ 482static intrun_post_rewrite_hook(const struct am_state *state) 483{ 484struct child_process cp = CHILD_PROCESS_INIT; 485const char*hook =find_hook("post-rewrite"); 486int ret; 487 488if(!hook) 489return0; 490 491argv_array_push(&cp.args, hook); 492argv_array_push(&cp.args,"rebase"); 493 494 cp.in =xopen(am_path(state,"rewritten"), O_RDONLY); 495 cp.stdout_to_stderr =1; 496 497 ret =run_command(&cp); 498 499close(cp.in); 500return ret; 501} 502 503/** 504 * Reads the state directory's "rewritten" file, and copies notes from the old 505 * commits listed in the file to their rewritten commits. 506 * 507 * Returns 0 on success, -1 on failure. 508 */ 509static intcopy_notes_for_rebase(const struct am_state *state) 510{ 511struct notes_rewrite_cfg *c; 512struct strbuf sb = STRBUF_INIT; 513const char*invalid_line =_("Malformed input line: '%s'."); 514const char*msg ="Notes added by 'git rebase'"; 515FILE*fp; 516int ret =0; 517 518assert(state->rebasing); 519 520 c =init_copy_notes_for_rewrite("rebase"); 521if(!c) 522return0; 523 524 fp =xfopen(am_path(state,"rewritten"),"r"); 525 526while(!strbuf_getline(&sb, fp,'\n')) { 527unsigned char from_obj[GIT_SHA1_RAWSZ], to_obj[GIT_SHA1_RAWSZ]; 528 529if(sb.len != GIT_SHA1_HEXSZ *2+1) { 530 ret =error(invalid_line, sb.buf); 531goto finish; 532} 533 534if(get_sha1_hex(sb.buf, from_obj)) { 535 ret =error(invalid_line, sb.buf); 536goto finish; 537} 538 539if(sb.buf[GIT_SHA1_HEXSZ] !=' ') { 540 ret =error(invalid_line, sb.buf); 541goto finish; 542} 543 544if(get_sha1_hex(sb.buf + GIT_SHA1_HEXSZ +1, to_obj)) { 545 ret =error(invalid_line, sb.buf); 546goto finish; 547} 548 549if(copy_note_for_rewrite(c, from_obj, to_obj)) 550 ret =error(_("Failed to copy notes from '%s' to '%s'"), 551sha1_to_hex(from_obj),sha1_to_hex(to_obj)); 552} 553 554finish: 555finish_copy_notes_for_rewrite(c, msg); 556fclose(fp); 557strbuf_release(&sb); 558return ret; 559} 560 561/** 562 * Determines if the file looks like a piece of RFC2822 mail by grabbing all 563 * non-indented lines and checking if they look like they begin with valid 564 * header field names. 565 * 566 * Returns 1 if the file looks like a piece of mail, 0 otherwise. 567 */ 568static intis_mail(FILE*fp) 569{ 570const char*header_regex ="^[!-9;-~]+:"; 571struct strbuf sb = STRBUF_INIT; 572 regex_t regex; 573int ret =1; 574 575if(fseek(fp,0L, SEEK_SET)) 576die_errno(_("fseek failed")); 577 578if(regcomp(®ex, header_regex, REG_NOSUB | REG_EXTENDED)) 579die("invalid pattern:%s", header_regex); 580 581while(!strbuf_getline_crlf(&sb, fp)) { 582if(!sb.len) 583break;/* End of header */ 584 585/* Ignore indented folded lines */ 586if(*sb.buf =='\t'|| *sb.buf ==' ') 587continue; 588 589/* It's a header if it matches header_regex */ 590if(regexec(®ex, sb.buf,0, NULL,0)) { 591 ret =0; 592goto done; 593} 594} 595 596done: 597regfree(®ex); 598strbuf_release(&sb); 599return ret; 600} 601 602/** 603 * Attempts to detect the patch_format of the patches contained in `paths`, 604 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if 605 * detection fails. 606 */ 607static intdetect_patch_format(const char**paths) 608{ 609enum patch_format ret = PATCH_FORMAT_UNKNOWN; 610struct strbuf l1 = STRBUF_INIT; 611FILE*fp; 612 613/* 614 * We default to mbox format if input is from stdin and for directories 615 */ 616if(!*paths || !strcmp(*paths,"-") ||is_directory(*paths)) 617return PATCH_FORMAT_MBOX; 618 619/* 620 * Otherwise, check the first few lines of the first patch, starting 621 * from the first non-blank line, to try to detect its format. 622 */ 623 624 fp =xfopen(*paths,"r"); 625 626while(!strbuf_getline_crlf(&l1, fp)) { 627if(l1.len) 628break; 629} 630 631if(starts_with(l1.buf,"From ") ||starts_with(l1.buf,"From: ")) { 632 ret = PATCH_FORMAT_MBOX; 633goto done; 634} 635 636if(l1.len &&is_mail(fp)) { 637 ret = PATCH_FORMAT_MBOX; 638goto done; 639} 640 641done: 642fclose(fp); 643strbuf_release(&l1); 644return ret; 645} 646 647/** 648 * Splits out individual email patches from `paths`, where each path is either 649 * a mbox file or a Maildir. Returns 0 on success, -1 on failure. 650 */ 651static intsplit_mail_mbox(struct am_state *state,const char**paths,int keep_cr) 652{ 653struct child_process cp = CHILD_PROCESS_INIT; 654struct strbuf last = STRBUF_INIT; 655 656 cp.git_cmd =1; 657argv_array_push(&cp.args,"mailsplit"); 658argv_array_pushf(&cp.args,"-d%d", state->prec); 659argv_array_pushf(&cp.args,"-o%s", state->dir); 660argv_array_push(&cp.args,"-b"); 661if(keep_cr) 662argv_array_push(&cp.args,"--keep-cr"); 663argv_array_push(&cp.args,"--"); 664argv_array_pushv(&cp.args, paths); 665 666if(capture_command(&cp, &last,8)) 667return-1; 668 669 state->cur =1; 670 state->last =strtol(last.buf, NULL,10); 671 672return0; 673} 674 675/** 676 * Splits a list of files/directories into individual email patches. Each path 677 * in `paths` must be a file/directory that is formatted according to 678 * `patch_format`. 679 * 680 * Once split out, the individual email patches will be stored in the state 681 * directory, with each patch's filename being its index, padded to state->prec 682 * digits. 683 * 684 * state->cur will be set to the index of the first mail, and state->last will 685 * be set to the index of the last mail. 686 * 687 * Set keep_cr to 0 to convert all lines ending with \r\n to end with \n, 1 688 * to disable this behavior, -1 to use the default configured setting. 689 * 690 * Returns 0 on success, -1 on failure. 691 */ 692static intsplit_mail(struct am_state *state,enum patch_format patch_format, 693const char**paths,int keep_cr) 694{ 695if(keep_cr <0) { 696 keep_cr =0; 697git_config_get_bool("am.keepcr", &keep_cr); 698} 699 700switch(patch_format) { 701case PATCH_FORMAT_MBOX: 702returnsplit_mail_mbox(state, paths, keep_cr); 703default: 704die("BUG: invalid patch_format"); 705} 706return-1; 707} 708 709/** 710 * Setup a new am session for applying patches 711 */ 712static voidam_setup(struct am_state *state,enum patch_format patch_format, 713const char**paths,int keep_cr) 714{ 715unsigned char curr_head[GIT_SHA1_RAWSZ]; 716const char*str; 717struct strbuf sb = STRBUF_INIT; 718 719if(!patch_format) 720 patch_format =detect_patch_format(paths); 721 722if(!patch_format) { 723fprintf_ln(stderr,_("Patch format detection failed.")); 724exit(128); 725} 726 727if(mkdir(state->dir,0777) <0&& errno != EEXIST) 728die_errno(_("failed to create directory '%s'"), state->dir); 729 730if(split_mail(state, patch_format, paths, keep_cr) <0) { 731am_destroy(state); 732die(_("Failed to split patches.")); 733} 734 735if(state->rebasing) 736 state->threeway =1; 737 738write_file(am_path(state,"threeway"),1, state->threeway ?"t":"f"); 739 740write_file(am_path(state,"quiet"),1, state->quiet ?"t":"f"); 741 742write_file(am_path(state,"sign"),1, state->signoff ?"t":"f"); 743 744write_file(am_path(state,"utf8"),1, state->utf8 ?"t":"f"); 745 746switch(state->keep) { 747case KEEP_FALSE: 748 str ="f"; 749break; 750case KEEP_TRUE: 751 str ="t"; 752break; 753case KEEP_NON_PATCH: 754 str ="b"; 755break; 756default: 757die("BUG: invalid value for state->keep"); 758} 759 760write_file(am_path(state,"keep"),1,"%s", str); 761 762write_file(am_path(state,"messageid"),1, state->message_id ?"t":"f"); 763 764switch(state->scissors) { 765case SCISSORS_UNSET: 766 str =""; 767break; 768case SCISSORS_FALSE: 769 str ="f"; 770break; 771case SCISSORS_TRUE: 772 str ="t"; 773break; 774default: 775die("BUG: invalid value for state->scissors"); 776} 777 778write_file(am_path(state,"scissors"),1,"%s", str); 779 780sq_quote_argv(&sb, state->git_apply_opts.argv,0); 781write_file(am_path(state,"apply-opt"),1,"%s", sb.buf); 782 783if(state->rebasing) 784write_file(am_path(state,"rebasing"),1,"%s",""); 785else 786write_file(am_path(state,"applying"),1,"%s",""); 787 788if(!get_sha1("HEAD", curr_head)) { 789write_file(am_path(state,"abort-safety"),1,"%s",sha1_to_hex(curr_head)); 790if(!state->rebasing) 791update_ref("am","ORIG_HEAD", curr_head, NULL,0, 792 UPDATE_REFS_DIE_ON_ERR); 793}else{ 794write_file(am_path(state,"abort-safety"),1,"%s",""); 795if(!state->rebasing) 796delete_ref("ORIG_HEAD", NULL,0); 797} 798 799/* 800 * NOTE: Since the "next" and "last" files determine if an am_state 801 * session is in progress, they should be written last. 802 */ 803 804write_file(am_path(state,"next"),1,"%d", state->cur); 805 806write_file(am_path(state,"last"),1,"%d", state->last); 807 808strbuf_release(&sb); 809} 810 811/** 812 * Increments the patch pointer, and cleans am_state for the application of the 813 * next patch. 814 */ 815static voidam_next(struct am_state *state) 816{ 817unsigned char head[GIT_SHA1_RAWSZ]; 818 819free(state->author_name); 820 state->author_name = NULL; 821 822free(state->author_email); 823 state->author_email = NULL; 824 825free(state->author_date); 826 state->author_date = NULL; 827 828free(state->msg); 829 state->msg = NULL; 830 state->msg_len =0; 831 832unlink(am_path(state,"author-script")); 833unlink(am_path(state,"final-commit")); 834 835hashclr(state->orig_commit); 836unlink(am_path(state,"original-commit")); 837 838if(!get_sha1("HEAD", head)) 839write_file(am_path(state,"abort-safety"),1,"%s",sha1_to_hex(head)); 840else 841write_file(am_path(state,"abort-safety"),1,"%s",""); 842 843 state->cur++; 844write_file(am_path(state,"next"),1,"%d", state->cur); 845} 846 847/** 848 * Returns the filename of the current patch email. 849 */ 850static const char*msgnum(const struct am_state *state) 851{ 852static struct strbuf sb = STRBUF_INIT; 853 854strbuf_reset(&sb); 855strbuf_addf(&sb,"%0*d", state->prec, state->cur); 856 857return sb.buf; 858} 859 860/** 861 * Refresh and write index. 862 */ 863static voidrefresh_and_write_cache(void) 864{ 865struct lock_file *lock_file =xcalloc(1,sizeof(struct lock_file)); 866 867hold_locked_index(lock_file,1); 868refresh_cache(REFRESH_QUIET); 869if(write_locked_index(&the_index, lock_file, COMMIT_LOCK)) 870die(_("unable to write index file")); 871} 872 873/** 874 * Returns 1 if the index differs from HEAD, 0 otherwise. When on an unborn 875 * branch, returns 1 if there are entries in the index, 0 otherwise. If an 876 * strbuf is provided, the space-separated list of files that differ will be 877 * appended to it. 878 */ 879static intindex_has_changes(struct strbuf *sb) 880{ 881unsigned char head[GIT_SHA1_RAWSZ]; 882int i; 883 884if(!get_sha1_tree("HEAD", head)) { 885struct diff_options opt; 886 887diff_setup(&opt); 888DIFF_OPT_SET(&opt, EXIT_WITH_STATUS); 889if(!sb) 890DIFF_OPT_SET(&opt, QUICK); 891do_diff_cache(head, &opt); 892diffcore_std(&opt); 893for(i =0; sb && i < diff_queued_diff.nr; i++) { 894if(i) 895strbuf_addch(sb,' '); 896strbuf_addstr(sb, diff_queued_diff.queue[i]->two->path); 897} 898diff_flush(&opt); 899returnDIFF_OPT_TST(&opt, HAS_CHANGES) !=0; 900}else{ 901for(i =0; sb && i < active_nr; i++) { 902if(i) 903strbuf_addch(sb,' '); 904strbuf_addstr(sb, active_cache[i]->name); 905} 906return!!active_nr; 907} 908} 909 910/** 911 * Dies with a user-friendly message on how to proceed after resolving the 912 * problem. This message can be overridden with state->resolvemsg. 913 */ 914static void NORETURN die_user_resolve(const struct am_state *state) 915{ 916if(state->resolvemsg) { 917printf_ln("%s", state->resolvemsg); 918}else{ 919const char*cmdline ="git am"; 920 921printf_ln(_("When you have resolved this problem, run\"%s--continue\"."), cmdline); 922printf_ln(_("If you prefer to skip this patch, run\"%s--skip\"instead."), cmdline); 923printf_ln(_("To restore the original branch and stop patching, run\"%s--abort\"."), cmdline); 924} 925 926exit(128); 927} 928 929/** 930 * Parses `mail` using git-mailinfo, extracting its patch and authorship info. 931 * state->msg will be set to the patch message. state->author_name, 932 * state->author_email and state->author_date will be set to the patch author's 933 * name, email and date respectively. The patch body will be written to the 934 * state directory's "patch" file. 935 * 936 * Returns 1 if the patch should be skipped, 0 otherwise. 937 */ 938static intparse_mail(struct am_state *state,const char*mail) 939{ 940FILE*fp; 941struct child_process cp = CHILD_PROCESS_INIT; 942struct strbuf sb = STRBUF_INIT; 943struct strbuf msg = STRBUF_INIT; 944struct strbuf author_name = STRBUF_INIT; 945struct strbuf author_date = STRBUF_INIT; 946struct strbuf author_email = STRBUF_INIT; 947int ret =0; 948 949 cp.git_cmd =1; 950 cp.in =xopen(mail, O_RDONLY,0); 951 cp.out =xopen(am_path(state,"info"), O_WRONLY | O_CREAT,0777); 952 953argv_array_push(&cp.args,"mailinfo"); 954argv_array_push(&cp.args, state->utf8 ?"-u":"-n"); 955 956switch(state->keep) { 957case KEEP_FALSE: 958break; 959case KEEP_TRUE: 960argv_array_push(&cp.args,"-k"); 961break; 962case KEEP_NON_PATCH: 963argv_array_push(&cp.args,"-b"); 964break; 965default: 966die("BUG: invalid value for state->keep"); 967} 968 969if(state->message_id) 970argv_array_push(&cp.args,"-m"); 971 972switch(state->scissors) { 973case SCISSORS_UNSET: 974break; 975case SCISSORS_FALSE: 976argv_array_push(&cp.args,"--no-scissors"); 977break; 978case SCISSORS_TRUE: 979argv_array_push(&cp.args,"--scissors"); 980break; 981default: 982die("BUG: invalid value for state->scissors"); 983} 984 985argv_array_push(&cp.args,am_path(state,"msg")); 986argv_array_push(&cp.args,am_path(state,"patch")); 987 988if(run_command(&cp) <0) 989die("could not parse patch"); 990 991close(cp.in); 992close(cp.out); 993 994/* Extract message and author information */ 995 fp =xfopen(am_path(state,"info"),"r"); 996while(!strbuf_getline(&sb, fp,'\n')) { 997const char*x; 998 999if(skip_prefix(sb.buf,"Subject: ", &x)) {1000if(msg.len)1001strbuf_addch(&msg,'\n');1002strbuf_addstr(&msg, x);1003}else if(skip_prefix(sb.buf,"Author: ", &x))1004strbuf_addstr(&author_name, x);1005else if(skip_prefix(sb.buf,"Email: ", &x))1006strbuf_addstr(&author_email, x);1007else if(skip_prefix(sb.buf,"Date: ", &x))1008strbuf_addstr(&author_date, x);1009}1010fclose(fp);10111012/* Skip pine's internal folder data */1013if(!strcmp(author_name.buf,"Mail System Internal Data")) {1014 ret =1;1015goto finish;1016}10171018if(is_empty_file(am_path(state,"patch"))) {1019printf_ln(_("Patch is empty. Was it split wrong?"));1020die_user_resolve(state);1021}10221023strbuf_addstr(&msg,"\n\n");1024if(strbuf_read_file(&msg,am_path(state,"msg"),0) <0)1025die_errno(_("could not read '%s'"),am_path(state,"msg"));1026stripspace(&msg,0);10271028if(state->signoff)1029append_signoff(&msg,0,0);10301031assert(!state->author_name);1032 state->author_name =strbuf_detach(&author_name, NULL);10331034assert(!state->author_email);1035 state->author_email =strbuf_detach(&author_email, NULL);10361037assert(!state->author_date);1038 state->author_date =strbuf_detach(&author_date, NULL);10391040assert(!state->msg);1041 state->msg =strbuf_detach(&msg, &state->msg_len);10421043finish:1044strbuf_release(&msg);1045strbuf_release(&author_date);1046strbuf_release(&author_email);1047strbuf_release(&author_name);1048strbuf_release(&sb);1049return ret;1050}10511052/**1053 * Sets commit_id to the commit hash where the mail was generated from.1054 * Returns 0 on success, -1 on failure.1055 */1056static intget_mail_commit_sha1(unsigned char*commit_id,const char*mail)1057{1058struct strbuf sb = STRBUF_INIT;1059FILE*fp =xfopen(mail,"r");1060const char*x;10611062if(strbuf_getline(&sb, fp,'\n'))1063return-1;10641065if(!skip_prefix(sb.buf,"From ", &x))1066return-1;10671068if(get_sha1_hex(x, commit_id) <0)1069return-1;10701071strbuf_release(&sb);1072fclose(fp);1073return0;1074}10751076/**1077 * Sets state->msg, state->author_name, state->author_email, state->author_date1078 * to the commit's respective info.1079 */1080static voidget_commit_info(struct am_state *state,struct commit *commit)1081{1082const char*buffer, *ident_line, *author_date, *msg;1083size_t ident_len;1084struct ident_split ident_split;1085struct strbuf sb = STRBUF_INIT;10861087 buffer =logmsg_reencode(commit, NULL,get_commit_output_encoding());10881089 ident_line =find_commit_header(buffer,"author", &ident_len);10901091if(split_ident_line(&ident_split, ident_line, ident_len) <0) {1092strbuf_add(&sb, ident_line, ident_len);1093die(_("invalid ident line:%s"), sb.buf);1094}10951096assert(!state->author_name);1097if(ident_split.name_begin) {1098strbuf_add(&sb, ident_split.name_begin,1099 ident_split.name_end - ident_split.name_begin);1100 state->author_name =strbuf_detach(&sb, NULL);1101}else1102 state->author_name =xstrdup("");11031104assert(!state->author_email);1105if(ident_split.mail_begin) {1106strbuf_add(&sb, ident_split.mail_begin,1107 ident_split.mail_end - ident_split.mail_begin);1108 state->author_email =strbuf_detach(&sb, NULL);1109}else1110 state->author_email =xstrdup("");11111112 author_date =show_ident_date(&ident_split,DATE_MODE(NORMAL));1113strbuf_addstr(&sb, author_date);1114assert(!state->author_date);1115 state->author_date =strbuf_detach(&sb, NULL);11161117assert(!state->msg);1118 msg =strstr(buffer,"\n\n");1119if(!msg)1120die(_("unable to parse commit%s"),sha1_to_hex(commit->object.sha1));1121 state->msg =xstrdup(msg +2);1122 state->msg_len =strlen(state->msg);1123}11241125/**1126 * Writes `commit` as a patch to the state directory's "patch" file.1127 */1128static voidwrite_commit_patch(const struct am_state *state,struct commit *commit)1129{1130struct rev_info rev_info;1131FILE*fp;11321133 fp =xfopen(am_path(state,"patch"),"w");1134init_revisions(&rev_info, NULL);1135 rev_info.diff =1;1136 rev_info.abbrev =0;1137 rev_info.disable_stdin =1;1138 rev_info.show_root_diff =1;1139 rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;1140 rev_info.no_commit_id =1;1141DIFF_OPT_SET(&rev_info.diffopt, BINARY);1142DIFF_OPT_SET(&rev_info.diffopt, FULL_INDEX);1143 rev_info.diffopt.use_color =0;1144 rev_info.diffopt.file = fp;1145 rev_info.diffopt.close_file =1;1146add_pending_object(&rev_info, &commit->object,"");1147diff_setup_done(&rev_info.diffopt);1148log_tree_commit(&rev_info, commit);1149}11501151/**1152 * Like parse_mail(), but parses the mail by looking up its commit ID1153 * directly. This is used in --rebasing mode to bypass git-mailinfo's munging1154 * of patches.1155 *1156 * state->orig_commit will be set to the original commit ID.1157 *1158 * Will always return 0 as the patch should never be skipped.1159 */1160static intparse_mail_rebase(struct am_state *state,const char*mail)1161{1162struct commit *commit;1163unsigned char commit_sha1[GIT_SHA1_RAWSZ];11641165if(get_mail_commit_sha1(commit_sha1, mail) <0)1166die(_("could not parse%s"), mail);11671168 commit =lookup_commit_or_die(commit_sha1, mail);11691170get_commit_info(state, commit);11711172write_commit_patch(state, commit);11731174hashcpy(state->orig_commit, commit_sha1);1175write_file(am_path(state,"original-commit"),1,"%s",1176sha1_to_hex(commit_sha1));11771178return0;1179}11801181/**1182 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If1183 * `index_file` is not NULL, the patch will be applied to that index.1184 */1185static intrun_apply(const struct am_state *state,const char*index_file)1186{1187struct child_process cp = CHILD_PROCESS_INIT;11881189 cp.git_cmd =1;11901191if(index_file)1192argv_array_pushf(&cp.env_array,"GIT_INDEX_FILE=%s", index_file);11931194/*1195 * If we are allowed to fall back on 3-way merge, don't give false1196 * errors during the initial attempt.1197 */1198if(state->threeway && !index_file) {1199 cp.no_stdout =1;1200 cp.no_stderr =1;1201}12021203argv_array_push(&cp.args,"apply");12041205argv_array_pushv(&cp.args, state->git_apply_opts.argv);12061207if(index_file)1208argv_array_push(&cp.args,"--cached");1209else1210argv_array_push(&cp.args,"--index");12111212argv_array_push(&cp.args,am_path(state,"patch"));12131214if(run_command(&cp))1215return-1;12161217/* Reload index as git-apply will have modified it. */1218discard_cache();1219read_cache_from(index_file ? index_file :get_index_file());12201221return0;1222}12231224/**1225 * Builds an index that contains just the blobs needed for a 3way merge.1226 */1227static intbuild_fake_ancestor(const struct am_state *state,const char*index_file)1228{1229struct child_process cp = CHILD_PROCESS_INIT;12301231 cp.git_cmd =1;1232argv_array_push(&cp.args,"apply");1233argv_array_pushv(&cp.args, state->git_apply_opts.argv);1234argv_array_pushf(&cp.args,"--build-fake-ancestor=%s", index_file);1235argv_array_push(&cp.args,am_path(state,"patch"));12361237if(run_command(&cp))1238return-1;12391240return0;1241}12421243/**1244 * Attempt a threeway merge, using index_path as the temporary index.1245 */1246static intfall_back_threeway(const struct am_state *state,const char*index_path)1247{1248unsigned char orig_tree[GIT_SHA1_RAWSZ], his_tree[GIT_SHA1_RAWSZ],1249 our_tree[GIT_SHA1_RAWSZ];1250const unsigned char*bases[1] = {orig_tree};1251struct merge_options o;1252struct commit *result;1253char*his_tree_name;12541255if(get_sha1("HEAD", our_tree) <0)1256hashcpy(our_tree, EMPTY_TREE_SHA1_BIN);12571258if(build_fake_ancestor(state, index_path))1259returnerror("could not build fake ancestor");12601261discard_cache();1262read_cache_from(index_path);12631264if(write_index_as_tree(orig_tree, &the_index, index_path,0, NULL))1265returnerror(_("Repository lacks necessary blobs to fall back on 3-way merge."));12661267say(state, stdout,_("Using index info to reconstruct a base tree..."));12681269if(!state->quiet) {1270/*1271 * List paths that needed 3-way fallback, so that the user can1272 * review them with extra care to spot mismerges.1273 */1274struct rev_info rev_info;1275const char*diff_filter_str ="--diff-filter=AM";12761277init_revisions(&rev_info, NULL);1278 rev_info.diffopt.output_format = DIFF_FORMAT_NAME_STATUS;1279diff_opt_parse(&rev_info.diffopt, &diff_filter_str,1);1280add_pending_sha1(&rev_info,"HEAD", our_tree,0);1281diff_setup_done(&rev_info.diffopt);1282run_diff_index(&rev_info,1);1283}12841285if(run_apply(state, index_path))1286returnerror(_("Did you hand edit your patch?\n"1287"It does not apply to blobs recorded in its index."));12881289if(write_index_as_tree(his_tree, &the_index, index_path,0, NULL))1290returnerror("could not write tree");12911292say(state, stdout,_("Falling back to patching base and 3-way merge..."));12931294discard_cache();1295read_cache();12961297/*1298 * This is not so wrong. Depending on which base we picked, orig_tree1299 * may be wildly different from ours, but his_tree has the same set of1300 * wildly different changes in parts the patch did not touch, so1301 * recursive ends up canceling them, saying that we reverted all those1302 * changes.1303 */13041305init_merge_options(&o);13061307 o.branch1 ="HEAD";1308 his_tree_name =xstrfmt("%.*s",linelen(state->msg), state->msg);1309 o.branch2 = his_tree_name;13101311if(state->quiet)1312 o.verbosity =0;13131314if(merge_recursive_generic(&o, our_tree, his_tree,1, bases, &result)) {1315free(his_tree_name);1316returnerror(_("Failed to merge in the changes."));1317}13181319free(his_tree_name);1320return0;1321}13221323/**1324 * Commits the current index with state->msg as the commit message and1325 * state->author_name, state->author_email and state->author_date as the author1326 * information.1327 */1328static voiddo_commit(const struct am_state *state)1329{1330unsigned char tree[GIT_SHA1_RAWSZ], parent[GIT_SHA1_RAWSZ],1331 commit[GIT_SHA1_RAWSZ];1332unsigned char*ptr;1333struct commit_list *parents = NULL;1334const char*reflog_msg, *author;1335struct strbuf sb = STRBUF_INIT;13361337if(run_hook_le(NULL,"pre-applypatch", NULL))1338exit(1);13391340if(write_cache_as_tree(tree,0, NULL))1341die(_("git write-tree failed to write a tree"));13421343if(!get_sha1_commit("HEAD", parent)) {1344 ptr = parent;1345commit_list_insert(lookup_commit(parent), &parents);1346}else{1347 ptr = NULL;1348say(state, stderr,_("applying to an empty history"));1349}13501351 author =fmt_ident(state->author_name, state->author_email,1352 state->ignore_date ? NULL : state->author_date,1353 IDENT_STRICT);13541355if(state->committer_date_is_author_date)1356setenv("GIT_COMMITTER_DATE",1357 state->ignore_date ?"": state->author_date,1);13581359if(commit_tree(state->msg, state->msg_len, tree, parents, commit,1360 author, state->sign_commit))1361die(_("failed to write commit object"));13621363 reflog_msg =getenv("GIT_REFLOG_ACTION");1364if(!reflog_msg)1365 reflog_msg ="am";13661367strbuf_addf(&sb,"%s: %.*s", reflog_msg,linelen(state->msg),1368 state->msg);13691370update_ref(sb.buf,"HEAD", commit, ptr,0, UPDATE_REFS_DIE_ON_ERR);13711372if(state->rebasing) {1373FILE*fp =xfopen(am_path(state,"rewritten"),"a");13741375assert(!is_null_sha1(state->orig_commit));1376fprintf(fp,"%s",sha1_to_hex(state->orig_commit));1377fprintf(fp,"%s\n",sha1_to_hex(commit));1378fclose(fp);1379}13801381strbuf_release(&sb);1382}13831384/**1385 * Validates the am_state for resuming -- the "msg" and authorship fields must1386 * be filled up.1387 */1388static voidvalidate_resume_state(const struct am_state *state)1389{1390if(!state->msg)1391die(_("cannot resume:%sdoes not exist."),1392am_path(state,"final-commit"));13931394if(!state->author_name || !state->author_email || !state->author_date)1395die(_("cannot resume:%sdoes not exist."),1396am_path(state,"author-script"));1397}13981399/**1400 * Applies all queued mail.1401 *1402 * If `resume` is true, we are "resuming". The "msg" and authorship fields, as1403 * well as the state directory's "patch" file is used as-is for applying the1404 * patch and committing it.1405 */1406static voidam_run(struct am_state *state,int resume)1407{1408const char*argv_gc_auto[] = {"gc","--auto", NULL};1409struct strbuf sb = STRBUF_INIT;14101411unlink(am_path(state,"dirtyindex"));14121413refresh_and_write_cache();14141415if(index_has_changes(&sb)) {1416write_file(am_path(state,"dirtyindex"),1,"t");1417die(_("Dirty index: cannot apply patches (dirty:%s)"), sb.buf);1418}14191420strbuf_release(&sb);14211422while(state->cur <= state->last) {1423const char*mail =am_path(state,msgnum(state));1424int apply_status;14251426if(!file_exists(mail))1427goto next;14281429if(resume) {1430validate_resume_state(state);1431 resume =0;1432}else{1433int skip;14341435if(state->rebasing)1436 skip =parse_mail_rebase(state, mail);1437else1438 skip =parse_mail(state, mail);14391440if(skip)1441goto next;/* mail should be skipped */14421443write_author_script(state);1444write_commit_msg(state);1445}14461447if(run_applypatch_msg_hook(state))1448exit(1);14491450say(state, stdout,_("Applying: %.*s"),linelen(state->msg), state->msg);14511452 apply_status =run_apply(state, NULL);14531454if(apply_status && state->threeway) {1455struct strbuf sb = STRBUF_INIT;14561457strbuf_addstr(&sb,am_path(state,"patch-merge-index"));1458 apply_status =fall_back_threeway(state, sb.buf);1459strbuf_release(&sb);14601461/*1462 * Applying the patch to an earlier tree and merging1463 * the result may have produced the same tree as ours.1464 */1465if(!apply_status && !index_has_changes(NULL)) {1466say(state, stdout,_("No changes -- Patch already applied."));1467goto next;1468}1469}14701471if(apply_status) {1472int advice_amworkdir =1;14731474printf_ln(_("Patch failed at%s%.*s"),msgnum(state),1475linelen(state->msg), state->msg);14761477git_config_get_bool("advice.amworkdir", &advice_amworkdir);14781479if(advice_amworkdir)1480printf_ln(_("The copy of the patch that failed is found in:%s"),1481am_path(state,"patch"));14821483die_user_resolve(state);1484}14851486do_commit(state);14871488next:1489am_next(state);1490}14911492if(!is_empty_file(am_path(state,"rewritten"))) {1493assert(state->rebasing);1494copy_notes_for_rebase(state);1495run_post_rewrite_hook(state);1496}14971498/*1499 * In rebasing mode, it's up to the caller to take care of1500 * housekeeping.1501 */1502if(!state->rebasing) {1503am_destroy(state);1504run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);1505}1506}15071508/**1509 * Resume the current am session after patch application failure. The user did1510 * all the hard work, and we do not have to do any patch application. Just1511 * trust and commit what the user has in the index and working tree.1512 */1513static voidam_resolve(struct am_state *state)1514{1515validate_resume_state(state);15161517say(state, stdout,_("Applying: %.*s"),linelen(state->msg), state->msg);15181519if(!index_has_changes(NULL)) {1520printf_ln(_("No changes - did you forget to use 'git add'?\n"1521"If there is nothing left to stage, chances are that something else\n"1522"already introduced the same changes; you might want to skip this patch."));1523die_user_resolve(state);1524}15251526if(unmerged_cache()) {1527printf_ln(_("You still have unmerged paths in your index.\n"1528"Did you forget to use 'git add'?"));1529die_user_resolve(state);1530}15311532do_commit(state);15331534am_next(state);1535am_run(state,0);1536}15371538/**1539 * Performs a checkout fast-forward from `head` to `remote`. If `reset` is1540 * true, any unmerged entries will be discarded. Returns 0 on success, -1 on1541 * failure.1542 */1543static intfast_forward_to(struct tree *head,struct tree *remote,int reset)1544{1545struct lock_file *lock_file;1546struct unpack_trees_options opts;1547struct tree_desc t[2];15481549if(parse_tree(head) ||parse_tree(remote))1550return-1;15511552 lock_file =xcalloc(1,sizeof(struct lock_file));1553hold_locked_index(lock_file,1);15541555refresh_cache(REFRESH_QUIET);15561557memset(&opts,0,sizeof(opts));1558 opts.head_idx =1;1559 opts.src_index = &the_index;1560 opts.dst_index = &the_index;1561 opts.update =1;1562 opts.merge =1;1563 opts.reset = reset;1564 opts.fn = twoway_merge;1565init_tree_desc(&t[0], head->buffer, head->size);1566init_tree_desc(&t[1], remote->buffer, remote->size);15671568if(unpack_trees(2, t, &opts)) {1569rollback_lock_file(lock_file);1570return-1;1571}15721573if(write_locked_index(&the_index, lock_file, COMMIT_LOCK))1574die(_("unable to write new index file"));15751576return0;1577}15781579/**1580 * Clean the index without touching entries that are not modified between1581 * `head` and `remote`.1582 */1583static intclean_index(const unsigned char*head,const unsigned char*remote)1584{1585struct lock_file *lock_file;1586struct tree *head_tree, *remote_tree, *index_tree;1587unsigned char index[GIT_SHA1_RAWSZ];1588struct pathspec pathspec;15891590 head_tree =parse_tree_indirect(head);1591if(!head_tree)1592returnerror(_("Could not parse object '%s'."),sha1_to_hex(head));15931594 remote_tree =parse_tree_indirect(remote);1595if(!remote_tree)1596returnerror(_("Could not parse object '%s'."),sha1_to_hex(remote));15971598read_cache_unmerged();15991600if(fast_forward_to(head_tree, head_tree,1))1601return-1;16021603if(write_cache_as_tree(index,0, NULL))1604return-1;16051606 index_tree =parse_tree_indirect(index);1607if(!index_tree)1608returnerror(_("Could not parse object '%s'."),sha1_to_hex(index));16091610if(fast_forward_to(index_tree, remote_tree,0))1611return-1;16121613memset(&pathspec,0,sizeof(pathspec));16141615 lock_file =xcalloc(1,sizeof(struct lock_file));1616hold_locked_index(lock_file,1);16171618if(read_tree(remote_tree,0, &pathspec)) {1619rollback_lock_file(lock_file);1620return-1;1621}16221623if(write_locked_index(&the_index, lock_file, COMMIT_LOCK))1624die(_("unable to write new index file"));16251626remove_branch_state();16271628return0;1629}16301631/**1632 * Resume the current am session by skipping the current patch.1633 */1634static voidam_skip(struct am_state *state)1635{1636unsigned char head[GIT_SHA1_RAWSZ];16371638if(get_sha1("HEAD", head))1639hashcpy(head, EMPTY_TREE_SHA1_BIN);16401641if(clean_index(head, head))1642die(_("failed to clean index"));16431644am_next(state);1645am_run(state,0);1646}16471648/**1649 * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.1650 *1651 * It is not safe to reset HEAD when:1652 * 1. git-am previously failed because the index was dirty.1653 * 2. HEAD has moved since git-am previously failed.1654 */1655static intsafe_to_abort(const struct am_state *state)1656{1657struct strbuf sb = STRBUF_INIT;1658unsigned char abort_safety[GIT_SHA1_RAWSZ], head[GIT_SHA1_RAWSZ];16591660if(file_exists(am_path(state,"dirtyindex")))1661return0;16621663if(read_state_file(&sb, state,"abort-safety",1) >0) {1664if(get_sha1_hex(sb.buf, abort_safety))1665die(_("could not parse%s"),am_path(state,"abort_safety"));1666}else1667hashclr(abort_safety);16681669if(get_sha1("HEAD", head))1670hashclr(head);16711672if(!hashcmp(head, abort_safety))1673return1;16741675error(_("You seem to have moved HEAD since the last 'am' failure.\n"1676"Not rewinding to ORIG_HEAD"));16771678return0;1679}16801681/**1682 * Aborts the current am session if it is safe to do so.1683 */1684static voidam_abort(struct am_state *state)1685{1686unsigned char curr_head[GIT_SHA1_RAWSZ], orig_head[GIT_SHA1_RAWSZ];1687int has_curr_head, has_orig_head;1688char*curr_branch;16891690if(!safe_to_abort(state)) {1691am_destroy(state);1692return;1693}16941695 curr_branch =resolve_refdup("HEAD",0, curr_head, NULL);1696 has_curr_head = !is_null_sha1(curr_head);1697if(!has_curr_head)1698hashcpy(curr_head, EMPTY_TREE_SHA1_BIN);16991700 has_orig_head = !get_sha1("ORIG_HEAD", orig_head);1701if(!has_orig_head)1702hashcpy(orig_head, EMPTY_TREE_SHA1_BIN);17031704clean_index(curr_head, orig_head);17051706if(has_orig_head)1707update_ref("am --abort","HEAD", orig_head,1708 has_curr_head ? curr_head : NULL,0,1709 UPDATE_REFS_DIE_ON_ERR);1710else if(curr_branch)1711delete_ref(curr_branch, NULL, REF_NODEREF);17121713free(curr_branch);1714am_destroy(state);1715}17161717/**1718 * parse_options() callback that validates and sets opt->value to the1719 * PATCH_FORMAT_* enum value corresponding to `arg`.1720 */1721static intparse_opt_patchformat(const struct option *opt,const char*arg,int unset)1722{1723int*opt_value = opt->value;17241725if(!strcmp(arg,"mbox"))1726*opt_value = PATCH_FORMAT_MBOX;1727else1728returnerror(_("Invalid value for --patch-format:%s"), arg);1729return0;1730}17311732enum resume_mode {1733 RESUME_FALSE =0,1734 RESUME_APPLY,1735 RESUME_RESOLVED,1736 RESUME_SKIP,1737 RESUME_ABORT1738};17391740intcmd_am(int argc,const char**argv,const char*prefix)1741{1742struct am_state state;1743int keep_cr = -1;1744int patch_format = PATCH_FORMAT_UNKNOWN;1745enum resume_mode resume = RESUME_FALSE;17461747const char*const usage[] = {1748N_("git am [options] [(<mbox>|<Maildir>)...]"),1749N_("git am [options] (--continue | --skip | --abort)"),1750 NULL1751};17521753struct option options[] = {1754OPT_BOOL('3',"3way", &state.threeway,1755N_("allow fall back on 3way merging if needed")),1756OPT__QUIET(&state.quiet,N_("be quiet")),1757OPT_BOOL('s',"signoff", &state.signoff,1758N_("add a Signed-off-by line to the commit message")),1759OPT_BOOL('u',"utf8", &state.utf8,1760N_("recode into utf8 (default)")),1761OPT_SET_INT('k',"keep", &state.keep,1762N_("pass -k flag to git-mailinfo"), KEEP_TRUE),1763OPT_SET_INT(0,"keep-non-patch", &state.keep,1764N_("pass -b flag to git-mailinfo"), KEEP_NON_PATCH),1765OPT_BOOL('m',"message-id", &state.message_id,1766N_("pass -m flag to git-mailinfo")),1767{ OPTION_SET_INT,0,"keep-cr", &keep_cr, NULL,1768N_("pass --keep-cr flag to git-mailsplit for mbox format"),1769 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL,1},1770{ OPTION_SET_INT,0,"no-keep-cr", &keep_cr, NULL,1771N_("do not pass --keep-cr flag to git-mailsplit independent of am.keepcr"),1772 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL,0},1773OPT_BOOL('c',"scissors", &state.scissors,1774N_("strip everything before a scissors line")),1775OPT_PASSTHRU_ARGV(0,"whitespace", &state.git_apply_opts,N_("action"),1776N_("pass it through git-apply"),17770),1778OPT_PASSTHRU_ARGV(0,"ignore-space-change", &state.git_apply_opts, NULL,1779N_("pass it through git-apply"),1780 PARSE_OPT_NOARG),1781OPT_PASSTHRU_ARGV(0,"ignore-whitespace", &state.git_apply_opts, NULL,1782N_("pass it through git-apply"),1783 PARSE_OPT_NOARG),1784OPT_PASSTHRU_ARGV(0,"directory", &state.git_apply_opts,N_("root"),1785N_("pass it through git-apply"),17860),1787OPT_PASSTHRU_ARGV(0,"exclude", &state.git_apply_opts,N_("path"),1788N_("pass it through git-apply"),17890),1790OPT_PASSTHRU_ARGV(0,"include", &state.git_apply_opts,N_("path"),1791N_("pass it through git-apply"),17920),1793OPT_PASSTHRU_ARGV('C', NULL, &state.git_apply_opts,N_("n"),1794N_("pass it through git-apply"),17950),1796OPT_PASSTHRU_ARGV('p', NULL, &state.git_apply_opts,N_("num"),1797N_("pass it through git-apply"),17980),1799OPT_CALLBACK(0,"patch-format", &patch_format,N_("format"),1800N_("format the patch(es) are in"),1801 parse_opt_patchformat),1802OPT_PASSTHRU_ARGV(0,"reject", &state.git_apply_opts, NULL,1803N_("pass it through git-apply"),1804 PARSE_OPT_NOARG),1805OPT_STRING(0,"resolvemsg", &state.resolvemsg, NULL,1806N_("override error message when patch failure occurs")),1807OPT_CMDMODE(0,"continue", &resume,1808N_("continue applying patches after resolving a conflict"),1809 RESUME_RESOLVED),1810OPT_CMDMODE('r',"resolved", &resume,1811N_("synonyms for --continue"),1812 RESUME_RESOLVED),1813OPT_CMDMODE(0,"skip", &resume,1814N_("skip the current patch"),1815 RESUME_SKIP),1816OPT_CMDMODE(0,"abort", &resume,1817N_("restore the original branch and abort the patching operation."),1818 RESUME_ABORT),1819OPT_BOOL(0,"committer-date-is-author-date",1820&state.committer_date_is_author_date,1821N_("lie about committer date")),1822OPT_BOOL(0,"ignore-date", &state.ignore_date,1823N_("use current timestamp for author date")),1824{ OPTION_STRING,'S',"gpg-sign", &state.sign_commit,N_("key-id"),1825N_("GPG-sign commits"),1826 PARSE_OPT_OPTARG, NULL, (intptr_t)""},1827OPT_HIDDEN_BOOL(0,"rebasing", &state.rebasing,1828N_("(internal use for git-rebase)")),1829OPT_END()1830};18311832/*1833 * NEEDSWORK: Once all the features of git-am.sh have been1834 * re-implemented in builtin/am.c, this preamble can be removed.1835 */1836if(!getenv("_GIT_USE_BUILTIN_AM")) {1837const char*path =mkpath("%s/git-am",git_exec_path());18381839if(sane_execvp(path, (char**)argv) <0)1840die_errno("could not exec%s", path);1841}else{1842 prefix =setup_git_directory();1843trace_repo_setup(prefix);1844setup_work_tree();1845}18461847git_config(git_default_config, NULL);18481849am_state_init(&state,git_path("rebase-apply"));18501851 argc =parse_options(argc, argv, prefix, options, usage,0);18521853if(read_index_preload(&the_index, NULL) <0)1854die(_("failed to read the index"));18551856if(am_in_progress(&state)) {1857/*1858 * Catch user error to feed us patches when there is a session1859 * in progress:1860 *1861 * 1. mbox path(s) are provided on the command-line.1862 * 2. stdin is not a tty: the user is trying to feed us a patch1863 * from standard input. This is somewhat unreliable -- stdin1864 * could be /dev/null for example and the caller did not1865 * intend to feed us a patch but wanted to continue1866 * unattended.1867 */1868if(argc || (resume == RESUME_FALSE && !isatty(0)))1869die(_("previous rebase directory%sstill exists but mbox given."),1870 state.dir);18711872if(resume == RESUME_FALSE)1873 resume = RESUME_APPLY;18741875am_load(&state);1876}else{1877struct argv_array paths = ARGV_ARRAY_INIT;1878int i;18791880/*1881 * Handle stray state directory in the independent-run case. In1882 * the --rebasing case, it is up to the caller to take care of1883 * stray directories.1884 */1885if(file_exists(state.dir) && !state.rebasing) {1886if(resume == RESUME_ABORT) {1887am_destroy(&state);1888am_state_release(&state);1889return0;1890}18911892die(_("Stray%sdirectory found.\n"1893"Use\"git am --abort\"to remove it."),1894 state.dir);1895}18961897if(resume)1898die(_("Resolve operation not in progress, we are not resuming."));18991900for(i =0; i < argc; i++) {1901if(is_absolute_path(argv[i]) || !prefix)1902argv_array_push(&paths, argv[i]);1903else1904argv_array_push(&paths,mkpath("%s/%s", prefix, argv[i]));1905}19061907am_setup(&state, patch_format, paths.argv, keep_cr);19081909argv_array_clear(&paths);1910}19111912switch(resume) {1913case RESUME_FALSE:1914am_run(&state,0);1915break;1916case RESUME_APPLY:1917am_run(&state,1);1918break;1919case RESUME_RESOLVED:1920am_resolve(&state);1921break;1922case RESUME_SKIP:1923am_skip(&state);1924break;1925case RESUME_ABORT:1926am_abort(&state);1927break;1928default:1929die("BUG: invalid resume value");1930}19311932am_state_release(&state);19331934return0;1935}