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