1/* 2 * Builtin "git am" 3 * 4 * Based on git-am.sh by Junio C Hamano. 5 */ 6#include"cache.h" 7#include"builtin.h" 8#include"exec_cmd.h" 9#include"parse-options.h" 10#include"dir.h" 11#include"run-command.h" 12#include"quote.h" 13#include"lockfile.h" 14#include"cache-tree.h" 15#include"refs.h" 16#include"commit.h" 17#include"diff.h" 18#include"diffcore.h" 19#include"unpack-trees.h" 20#include"branch.h" 21#include"sequencer.h" 22#include"revision.h" 23#include"merge-recursive.h" 24#include"revision.h" 25#include"log-tree.h" 26 27/** 28 * Returns 1 if the file is empty or does not exist, 0 otherwise. 29 */ 30static intis_empty_file(const char*filename) 31{ 32struct stat st; 33 34if(stat(filename, &st) <0) { 35if(errno == ENOENT) 36return1; 37die_errno(_("could not stat%s"), filename); 38} 39 40return!st.st_size; 41} 42 43/** 44 * Like strbuf_getline(), but treats both '\n' and "\r\n" as line terminators. 45 */ 46static intstrbuf_getline_crlf(struct strbuf *sb,FILE*fp) 47{ 48if(strbuf_getwholeline(sb, fp,'\n')) 49return EOF; 50if(sb->buf[sb->len -1] =='\n') { 51strbuf_setlen(sb, sb->len -1); 52if(sb->len >0&& sb->buf[sb->len -1] =='\r') 53strbuf_setlen(sb, sb->len -1); 54} 55return0; 56} 57 58/** 59 * Returns the length of the first line of msg. 60 */ 61static intlinelen(const char*msg) 62{ 63returnstrchrnul(msg,'\n') - msg; 64} 65 66enum patch_format { 67 PATCH_FORMAT_UNKNOWN =0, 68 PATCH_FORMAT_MBOX 69}; 70 71struct am_state { 72/* state directory path */ 73char*dir; 74 75/* current and last patch numbers, 1-indexed */ 76int cur; 77int last; 78 79/* commit metadata and message */ 80char*author_name; 81char*author_email; 82char*author_date; 83char*msg; 84size_t msg_len; 85 86/* number of digits in patch filename */ 87int prec; 88 89/* various operating modes and command line options */ 90int threeway; 91int quiet; 92int signoff; 93const char*resolvemsg; 94int rebasing; 95}; 96 97/** 98 * Initializes am_state with the default values. The state directory is set to 99 * dir. 100 */ 101static voidam_state_init(struct am_state *state,const char*dir) 102{ 103memset(state,0,sizeof(*state)); 104 105assert(dir); 106 state->dir =xstrdup(dir); 107 108 state->prec =4; 109} 110 111/** 112 * Releases memory allocated by an am_state. 113 */ 114static voidam_state_release(struct am_state *state) 115{ 116free(state->dir); 117free(state->author_name); 118free(state->author_email); 119free(state->author_date); 120free(state->msg); 121} 122 123/** 124 * Returns path relative to the am_state directory. 125 */ 126staticinlineconst char*am_path(const struct am_state *state,const char*path) 127{ 128returnmkpath("%s/%s", state->dir, path); 129} 130 131/** 132 * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline 133 * at the end. 134 */ 135static voidsay(const struct am_state *state,FILE*fp,const char*fmt, ...) 136{ 137va_list ap; 138 139va_start(ap, fmt); 140if(!state->quiet) { 141vfprintf(fp, fmt, ap); 142putc('\n', fp); 143} 144va_end(ap); 145} 146 147/** 148 * Returns 1 if there is an am session in progress, 0 otherwise. 149 */ 150static intam_in_progress(const struct am_state *state) 151{ 152struct stat st; 153 154if(lstat(state->dir, &st) <0|| !S_ISDIR(st.st_mode)) 155return0; 156if(lstat(am_path(state,"last"), &st) || !S_ISREG(st.st_mode)) 157return0; 158if(lstat(am_path(state,"next"), &st) || !S_ISREG(st.st_mode)) 159return0; 160return1; 161} 162 163/** 164 * Reads the contents of `file` in the `state` directory into `sb`. Returns the 165 * number of bytes read on success, -1 if the file does not exist. If `trim` is 166 * set, trailing whitespace will be removed. 167 */ 168static intread_state_file(struct strbuf *sb,const struct am_state *state, 169const char*file,int trim) 170{ 171strbuf_reset(sb); 172 173if(strbuf_read_file(sb,am_path(state, file),0) >=0) { 174if(trim) 175strbuf_trim(sb); 176 177return sb->len; 178} 179 180if(errno == ENOENT) 181return-1; 182 183die_errno(_("could not read '%s'"),am_path(state, file)); 184} 185 186/** 187 * Reads a KEY=VALUE shell variable assignment from `fp`, returning the VALUE 188 * as a newly-allocated string. VALUE must be a quoted string, and the KEY must 189 * match `key`. Returns NULL on failure. 190 * 191 * This is used by read_author_script() to read the GIT_AUTHOR_* variables from 192 * the author-script. 193 */ 194static char*read_shell_var(FILE*fp,const char*key) 195{ 196struct strbuf sb = STRBUF_INIT; 197const char*str; 198 199if(strbuf_getline(&sb, fp,'\n')) 200goto fail; 201 202if(!skip_prefix(sb.buf, key, &str)) 203goto fail; 204 205if(!skip_prefix(str,"=", &str)) 206goto fail; 207 208strbuf_remove(&sb,0, str - sb.buf); 209 210 str =sq_dequote(sb.buf); 211if(!str) 212goto fail; 213 214returnstrbuf_detach(&sb, NULL); 215 216fail: 217strbuf_release(&sb); 218return NULL; 219} 220 221/** 222 * Reads and parses the state directory's "author-script" file, and sets 223 * state->author_name, state->author_email and state->author_date accordingly. 224 * Returns 0 on success, -1 if the file could not be parsed. 225 * 226 * The author script is of the format: 227 * 228 * GIT_AUTHOR_NAME='$author_name' 229 * GIT_AUTHOR_EMAIL='$author_email' 230 * GIT_AUTHOR_DATE='$author_date' 231 * 232 * where $author_name, $author_email and $author_date are quoted. We are strict 233 * with our parsing, as the file was meant to be eval'd in the old git-am.sh 234 * script, and thus if the file differs from what this function expects, it is 235 * better to bail out than to do something that the user does not expect. 236 */ 237static intread_author_script(struct am_state *state) 238{ 239const char*filename =am_path(state,"author-script"); 240FILE*fp; 241 242assert(!state->author_name); 243assert(!state->author_email); 244assert(!state->author_date); 245 246 fp =fopen(filename,"r"); 247if(!fp) { 248if(errno == ENOENT) 249return0; 250die_errno(_("could not open '%s' for reading"), filename); 251} 252 253 state->author_name =read_shell_var(fp,"GIT_AUTHOR_NAME"); 254if(!state->author_name) { 255fclose(fp); 256return-1; 257} 258 259 state->author_email =read_shell_var(fp,"GIT_AUTHOR_EMAIL"); 260if(!state->author_email) { 261fclose(fp); 262return-1; 263} 264 265 state->author_date =read_shell_var(fp,"GIT_AUTHOR_DATE"); 266if(!state->author_date) { 267fclose(fp); 268return-1; 269} 270 271if(fgetc(fp) != EOF) { 272fclose(fp); 273return-1; 274} 275 276fclose(fp); 277return0; 278} 279 280/** 281 * Saves state->author_name, state->author_email and state->author_date in the 282 * state directory's "author-script" file. 283 */ 284static voidwrite_author_script(const struct am_state *state) 285{ 286struct strbuf sb = STRBUF_INIT; 287 288strbuf_addstr(&sb,"GIT_AUTHOR_NAME="); 289sq_quote_buf(&sb, state->author_name); 290strbuf_addch(&sb,'\n'); 291 292strbuf_addstr(&sb,"GIT_AUTHOR_EMAIL="); 293sq_quote_buf(&sb, state->author_email); 294strbuf_addch(&sb,'\n'); 295 296strbuf_addstr(&sb,"GIT_AUTHOR_DATE="); 297sq_quote_buf(&sb, state->author_date); 298strbuf_addch(&sb,'\n'); 299 300write_file(am_path(state,"author-script"),1,"%s", sb.buf); 301 302strbuf_release(&sb); 303} 304 305/** 306 * Reads the commit message from the state directory's "final-commit" file, 307 * setting state->msg to its contents and state->msg_len to the length of its 308 * contents in bytes. 309 * 310 * Returns 0 on success, -1 if the file does not exist. 311 */ 312static intread_commit_msg(struct am_state *state) 313{ 314struct strbuf sb = STRBUF_INIT; 315 316assert(!state->msg); 317 318if(read_state_file(&sb, state,"final-commit",0) <0) { 319strbuf_release(&sb); 320return-1; 321} 322 323 state->msg =strbuf_detach(&sb, &state->msg_len); 324return0; 325} 326 327/** 328 * Saves state->msg in the state directory's "final-commit" file. 329 */ 330static voidwrite_commit_msg(const struct am_state *state) 331{ 332int fd; 333const char*filename =am_path(state,"final-commit"); 334 335 fd =xopen(filename, O_WRONLY | O_CREAT,0666); 336if(write_in_full(fd, state->msg, state->msg_len) <0) 337die_errno(_("could not write to%s"), filename); 338close(fd); 339} 340 341/** 342 * Loads state from disk. 343 */ 344static voidam_load(struct am_state *state) 345{ 346struct strbuf sb = STRBUF_INIT; 347 348if(read_state_file(&sb, state,"next",1) <0) 349die("BUG: state file 'next' does not exist"); 350 state->cur =strtol(sb.buf, NULL,10); 351 352if(read_state_file(&sb, state,"last",1) <0) 353die("BUG: state file 'last' does not exist"); 354 state->last =strtol(sb.buf, NULL,10); 355 356if(read_author_script(state) <0) 357die(_("could not parse author script")); 358 359read_commit_msg(state); 360 361read_state_file(&sb, state,"threeway",1); 362 state->threeway = !strcmp(sb.buf,"t"); 363 364read_state_file(&sb, state,"quiet",1); 365 state->quiet = !strcmp(sb.buf,"t"); 366 367read_state_file(&sb, state,"sign",1); 368 state->signoff = !strcmp(sb.buf,"t"); 369 370 state->rebasing = !!file_exists(am_path(state,"rebasing")); 371 372strbuf_release(&sb); 373} 374 375/** 376 * Removes the am_state directory, forcefully terminating the current am 377 * session. 378 */ 379static voidam_destroy(const struct am_state *state) 380{ 381struct strbuf sb = STRBUF_INIT; 382 383strbuf_addstr(&sb, state->dir); 384remove_dir_recursively(&sb,0); 385strbuf_release(&sb); 386} 387 388/** 389 * Determines if the file looks like a piece of RFC2822 mail by grabbing all 390 * non-indented lines and checking if they look like they begin with valid 391 * header field names. 392 * 393 * Returns 1 if the file looks like a piece of mail, 0 otherwise. 394 */ 395static intis_mail(FILE*fp) 396{ 397const char*header_regex ="^[!-9;-~]+:"; 398struct strbuf sb = STRBUF_INIT; 399 regex_t regex; 400int ret =1; 401 402if(fseek(fp,0L, SEEK_SET)) 403die_errno(_("fseek failed")); 404 405if(regcomp(®ex, header_regex, REG_NOSUB | REG_EXTENDED)) 406die("invalid pattern:%s", header_regex); 407 408while(!strbuf_getline_crlf(&sb, fp)) { 409if(!sb.len) 410break;/* End of header */ 411 412/* Ignore indented folded lines */ 413if(*sb.buf =='\t'|| *sb.buf ==' ') 414continue; 415 416/* It's a header if it matches header_regex */ 417if(regexec(®ex, sb.buf,0, NULL,0)) { 418 ret =0; 419goto done; 420} 421} 422 423done: 424regfree(®ex); 425strbuf_release(&sb); 426return ret; 427} 428 429/** 430 * Attempts to detect the patch_format of the patches contained in `paths`, 431 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if 432 * detection fails. 433 */ 434static intdetect_patch_format(const char**paths) 435{ 436enum patch_format ret = PATCH_FORMAT_UNKNOWN; 437struct strbuf l1 = STRBUF_INIT; 438FILE*fp; 439 440/* 441 * We default to mbox format if input is from stdin and for directories 442 */ 443if(!*paths || !strcmp(*paths,"-") ||is_directory(*paths)) 444return PATCH_FORMAT_MBOX; 445 446/* 447 * Otherwise, check the first few lines of the first patch, starting 448 * from the first non-blank line, to try to detect its format. 449 */ 450 451 fp =xfopen(*paths,"r"); 452 453while(!strbuf_getline_crlf(&l1, fp)) { 454if(l1.len) 455break; 456} 457 458if(starts_with(l1.buf,"From ") ||starts_with(l1.buf,"From: ")) { 459 ret = PATCH_FORMAT_MBOX; 460goto done; 461} 462 463if(l1.len &&is_mail(fp)) { 464 ret = PATCH_FORMAT_MBOX; 465goto done; 466} 467 468done: 469fclose(fp); 470strbuf_release(&l1); 471return ret; 472} 473 474/** 475 * Splits out individual email patches from `paths`, where each path is either 476 * a mbox file or a Maildir. Returns 0 on success, -1 on failure. 477 */ 478static intsplit_mail_mbox(struct am_state *state,const char**paths) 479{ 480struct child_process cp = CHILD_PROCESS_INIT; 481struct strbuf last = STRBUF_INIT; 482 483 cp.git_cmd =1; 484argv_array_push(&cp.args,"mailsplit"); 485argv_array_pushf(&cp.args,"-d%d", state->prec); 486argv_array_pushf(&cp.args,"-o%s", state->dir); 487argv_array_push(&cp.args,"-b"); 488argv_array_push(&cp.args,"--"); 489argv_array_pushv(&cp.args, paths); 490 491if(capture_command(&cp, &last,8)) 492return-1; 493 494 state->cur =1; 495 state->last =strtol(last.buf, NULL,10); 496 497return0; 498} 499 500/** 501 * Splits a list of files/directories into individual email patches. Each path 502 * in `paths` must be a file/directory that is formatted according to 503 * `patch_format`. 504 * 505 * Once split out, the individual email patches will be stored in the state 506 * directory, with each patch's filename being its index, padded to state->prec 507 * digits. 508 * 509 * state->cur will be set to the index of the first mail, and state->last will 510 * be set to the index of the last mail. 511 * 512 * Returns 0 on success, -1 on failure. 513 */ 514static intsplit_mail(struct am_state *state,enum patch_format patch_format, 515const char**paths) 516{ 517switch(patch_format) { 518case PATCH_FORMAT_MBOX: 519returnsplit_mail_mbox(state, paths); 520default: 521die("BUG: invalid patch_format"); 522} 523return-1; 524} 525 526/** 527 * Setup a new am session for applying patches 528 */ 529static voidam_setup(struct am_state *state,enum patch_format patch_format, 530const char**paths) 531{ 532unsigned char curr_head[GIT_SHA1_RAWSZ]; 533 534if(!patch_format) 535 patch_format =detect_patch_format(paths); 536 537if(!patch_format) { 538fprintf_ln(stderr,_("Patch format detection failed.")); 539exit(128); 540} 541 542if(mkdir(state->dir,0777) <0&& errno != EEXIST) 543die_errno(_("failed to create directory '%s'"), state->dir); 544 545if(split_mail(state, patch_format, paths) <0) { 546am_destroy(state); 547die(_("Failed to split patches.")); 548} 549 550if(state->rebasing) 551 state->threeway =1; 552 553write_file(am_path(state,"threeway"),1, state->threeway ?"t":"f"); 554 555write_file(am_path(state,"quiet"),1, state->quiet ?"t":"f"); 556 557write_file(am_path(state,"sign"),1, state->signoff ?"t":"f"); 558 559if(state->rebasing) 560write_file(am_path(state,"rebasing"),1,"%s",""); 561else 562write_file(am_path(state,"applying"),1,"%s",""); 563 564if(!get_sha1("HEAD", curr_head)) { 565write_file(am_path(state,"abort-safety"),1,"%s",sha1_to_hex(curr_head)); 566if(!state->rebasing) 567update_ref("am","ORIG_HEAD", curr_head, NULL,0, 568 UPDATE_REFS_DIE_ON_ERR); 569}else{ 570write_file(am_path(state,"abort-safety"),1,"%s",""); 571if(!state->rebasing) 572delete_ref("ORIG_HEAD", NULL,0); 573} 574 575/* 576 * NOTE: Since the "next" and "last" files determine if an am_state 577 * session is in progress, they should be written last. 578 */ 579 580write_file(am_path(state,"next"),1,"%d", state->cur); 581 582write_file(am_path(state,"last"),1,"%d", state->last); 583} 584 585/** 586 * Increments the patch pointer, and cleans am_state for the application of the 587 * next patch. 588 */ 589static voidam_next(struct am_state *state) 590{ 591unsigned char head[GIT_SHA1_RAWSZ]; 592 593free(state->author_name); 594 state->author_name = NULL; 595 596free(state->author_email); 597 state->author_email = NULL; 598 599free(state->author_date); 600 state->author_date = NULL; 601 602free(state->msg); 603 state->msg = NULL; 604 state->msg_len =0; 605 606unlink(am_path(state,"author-script")); 607unlink(am_path(state,"final-commit")); 608 609if(!get_sha1("HEAD", head)) 610write_file(am_path(state,"abort-safety"),1,"%s",sha1_to_hex(head)); 611else 612write_file(am_path(state,"abort-safety"),1,"%s",""); 613 614 state->cur++; 615write_file(am_path(state,"next"),1,"%d", state->cur); 616} 617 618/** 619 * Returns the filename of the current patch email. 620 */ 621static const char*msgnum(const struct am_state *state) 622{ 623static struct strbuf sb = STRBUF_INIT; 624 625strbuf_reset(&sb); 626strbuf_addf(&sb,"%0*d", state->prec, state->cur); 627 628return sb.buf; 629} 630 631/** 632 * Refresh and write index. 633 */ 634static voidrefresh_and_write_cache(void) 635{ 636struct lock_file *lock_file =xcalloc(1,sizeof(struct lock_file)); 637 638hold_locked_index(lock_file,1); 639refresh_cache(REFRESH_QUIET); 640if(write_locked_index(&the_index, lock_file, COMMIT_LOCK)) 641die(_("unable to write index file")); 642} 643 644/** 645 * Returns 1 if the index differs from HEAD, 0 otherwise. When on an unborn 646 * branch, returns 1 if there are entries in the index, 0 otherwise. If an 647 * strbuf is provided, the space-separated list of files that differ will be 648 * appended to it. 649 */ 650static intindex_has_changes(struct strbuf *sb) 651{ 652unsigned char head[GIT_SHA1_RAWSZ]; 653int i; 654 655if(!get_sha1_tree("HEAD", head)) { 656struct diff_options opt; 657 658diff_setup(&opt); 659DIFF_OPT_SET(&opt, EXIT_WITH_STATUS); 660if(!sb) 661DIFF_OPT_SET(&opt, QUICK); 662do_diff_cache(head, &opt); 663diffcore_std(&opt); 664for(i =0; sb && i < diff_queued_diff.nr; i++) { 665if(i) 666strbuf_addch(sb,' '); 667strbuf_addstr(sb, diff_queued_diff.queue[i]->two->path); 668} 669diff_flush(&opt); 670returnDIFF_OPT_TST(&opt, HAS_CHANGES) !=0; 671}else{ 672for(i =0; sb && i < active_nr; i++) { 673if(i) 674strbuf_addch(sb,' '); 675strbuf_addstr(sb, active_cache[i]->name); 676} 677return!!active_nr; 678} 679} 680 681/** 682 * Dies with a user-friendly message on how to proceed after resolving the 683 * problem. This message can be overridden with state->resolvemsg. 684 */ 685static void NORETURN die_user_resolve(const struct am_state *state) 686{ 687if(state->resolvemsg) { 688printf_ln("%s", state->resolvemsg); 689}else{ 690const char*cmdline ="git am"; 691 692printf_ln(_("When you have resolved this problem, run\"%s--continue\"."), cmdline); 693printf_ln(_("If you prefer to skip this patch, run\"%s--skip\"instead."), cmdline); 694printf_ln(_("To restore the original branch and stop patching, run\"%s--abort\"."), cmdline); 695} 696 697exit(128); 698} 699 700/** 701 * Parses `mail` using git-mailinfo, extracting its patch and authorship info. 702 * state->msg will be set to the patch message. state->author_name, 703 * state->author_email and state->author_date will be set to the patch author's 704 * name, email and date respectively. The patch body will be written to the 705 * state directory's "patch" file. 706 * 707 * Returns 1 if the patch should be skipped, 0 otherwise. 708 */ 709static intparse_mail(struct am_state *state,const char*mail) 710{ 711FILE*fp; 712struct child_process cp = CHILD_PROCESS_INIT; 713struct strbuf sb = STRBUF_INIT; 714struct strbuf msg = STRBUF_INIT; 715struct strbuf author_name = STRBUF_INIT; 716struct strbuf author_date = STRBUF_INIT; 717struct strbuf author_email = STRBUF_INIT; 718int ret =0; 719 720 cp.git_cmd =1; 721 cp.in =xopen(mail, O_RDONLY,0); 722 cp.out =xopen(am_path(state,"info"), O_WRONLY | O_CREAT,0777); 723 724argv_array_push(&cp.args,"mailinfo"); 725argv_array_push(&cp.args,am_path(state,"msg")); 726argv_array_push(&cp.args,am_path(state,"patch")); 727 728if(run_command(&cp) <0) 729die("could not parse patch"); 730 731close(cp.in); 732close(cp.out); 733 734/* Extract message and author information */ 735 fp =xfopen(am_path(state,"info"),"r"); 736while(!strbuf_getline(&sb, fp,'\n')) { 737const char*x; 738 739if(skip_prefix(sb.buf,"Subject: ", &x)) { 740if(msg.len) 741strbuf_addch(&msg,'\n'); 742strbuf_addstr(&msg, x); 743}else if(skip_prefix(sb.buf,"Author: ", &x)) 744strbuf_addstr(&author_name, x); 745else if(skip_prefix(sb.buf,"Email: ", &x)) 746strbuf_addstr(&author_email, x); 747else if(skip_prefix(sb.buf,"Date: ", &x)) 748strbuf_addstr(&author_date, x); 749} 750fclose(fp); 751 752/* Skip pine's internal folder data */ 753if(!strcmp(author_name.buf,"Mail System Internal Data")) { 754 ret =1; 755goto finish; 756} 757 758if(is_empty_file(am_path(state,"patch"))) { 759printf_ln(_("Patch is empty. Was it split wrong?")); 760die_user_resolve(state); 761} 762 763strbuf_addstr(&msg,"\n\n"); 764if(strbuf_read_file(&msg,am_path(state,"msg"),0) <0) 765die_errno(_("could not read '%s'"),am_path(state,"msg")); 766stripspace(&msg,0); 767 768if(state->signoff) 769append_signoff(&msg,0,0); 770 771assert(!state->author_name); 772 state->author_name =strbuf_detach(&author_name, NULL); 773 774assert(!state->author_email); 775 state->author_email =strbuf_detach(&author_email, NULL); 776 777assert(!state->author_date); 778 state->author_date =strbuf_detach(&author_date, NULL); 779 780assert(!state->msg); 781 state->msg =strbuf_detach(&msg, &state->msg_len); 782 783finish: 784strbuf_release(&msg); 785strbuf_release(&author_date); 786strbuf_release(&author_email); 787strbuf_release(&author_name); 788strbuf_release(&sb); 789return ret; 790} 791 792/** 793 * Sets commit_id to the commit hash where the mail was generated from. 794 * Returns 0 on success, -1 on failure. 795 */ 796static intget_mail_commit_sha1(unsigned char*commit_id,const char*mail) 797{ 798struct strbuf sb = STRBUF_INIT; 799FILE*fp =xfopen(mail,"r"); 800const char*x; 801 802if(strbuf_getline(&sb, fp,'\n')) 803return-1; 804 805if(!skip_prefix(sb.buf,"From ", &x)) 806return-1; 807 808if(get_sha1_hex(x, commit_id) <0) 809return-1; 810 811strbuf_release(&sb); 812fclose(fp); 813return0; 814} 815 816/** 817 * Sets state->msg, state->author_name, state->author_email, state->author_date 818 * to the commit's respective info. 819 */ 820static voidget_commit_info(struct am_state *state,struct commit *commit) 821{ 822const char*buffer, *ident_line, *author_date, *msg; 823size_t ident_len; 824struct ident_split ident_split; 825struct strbuf sb = STRBUF_INIT; 826 827 buffer =logmsg_reencode(commit, NULL,get_commit_output_encoding()); 828 829 ident_line =find_commit_header(buffer,"author", &ident_len); 830 831if(split_ident_line(&ident_split, ident_line, ident_len) <0) { 832strbuf_add(&sb, ident_line, ident_len); 833die(_("invalid ident line:%s"), sb.buf); 834} 835 836assert(!state->author_name); 837if(ident_split.name_begin) { 838strbuf_add(&sb, ident_split.name_begin, 839 ident_split.name_end - ident_split.name_begin); 840 state->author_name =strbuf_detach(&sb, NULL); 841}else 842 state->author_name =xstrdup(""); 843 844assert(!state->author_email); 845if(ident_split.mail_begin) { 846strbuf_add(&sb, ident_split.mail_begin, 847 ident_split.mail_end - ident_split.mail_begin); 848 state->author_email =strbuf_detach(&sb, NULL); 849}else 850 state->author_email =xstrdup(""); 851 852 author_date =show_ident_date(&ident_split,DATE_MODE(NORMAL)); 853strbuf_addstr(&sb, author_date); 854assert(!state->author_date); 855 state->author_date =strbuf_detach(&sb, NULL); 856 857assert(!state->msg); 858 msg =strstr(buffer,"\n\n"); 859if(!msg) 860die(_("unable to parse commit%s"),sha1_to_hex(commit->object.sha1)); 861 state->msg =xstrdup(msg +2); 862 state->msg_len =strlen(state->msg); 863} 864 865/** 866 * Writes `commit` as a patch to the state directory's "patch" file. 867 */ 868static voidwrite_commit_patch(const struct am_state *state,struct commit *commit) 869{ 870struct rev_info rev_info; 871FILE*fp; 872 873 fp =xfopen(am_path(state,"patch"),"w"); 874init_revisions(&rev_info, NULL); 875 rev_info.diff =1; 876 rev_info.abbrev =0; 877 rev_info.disable_stdin =1; 878 rev_info.show_root_diff =1; 879 rev_info.diffopt.output_format = DIFF_FORMAT_PATCH; 880 rev_info.no_commit_id =1; 881DIFF_OPT_SET(&rev_info.diffopt, BINARY); 882DIFF_OPT_SET(&rev_info.diffopt, FULL_INDEX); 883 rev_info.diffopt.use_color =0; 884 rev_info.diffopt.file = fp; 885 rev_info.diffopt.close_file =1; 886add_pending_object(&rev_info, &commit->object,""); 887diff_setup_done(&rev_info.diffopt); 888log_tree_commit(&rev_info, commit); 889} 890 891/** 892 * Like parse_mail(), but parses the mail by looking up its commit ID 893 * directly. This is used in --rebasing mode to bypass git-mailinfo's munging 894 * of patches. 895 * 896 * Will always return 0 as the patch should never be skipped. 897 */ 898static intparse_mail_rebase(struct am_state *state,const char*mail) 899{ 900struct commit *commit; 901unsigned char commit_sha1[GIT_SHA1_RAWSZ]; 902 903if(get_mail_commit_sha1(commit_sha1, mail) <0) 904die(_("could not parse%s"), mail); 905 906 commit =lookup_commit_or_die(commit_sha1, mail); 907 908get_commit_info(state, commit); 909 910write_commit_patch(state, commit); 911 912return0; 913} 914 915/** 916 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If 917 * `index_file` is not NULL, the patch will be applied to that index. 918 */ 919static intrun_apply(const struct am_state *state,const char*index_file) 920{ 921struct child_process cp = CHILD_PROCESS_INIT; 922 923 cp.git_cmd =1; 924 925if(index_file) 926argv_array_pushf(&cp.env_array,"GIT_INDEX_FILE=%s", index_file); 927 928/* 929 * If we are allowed to fall back on 3-way merge, don't give false 930 * errors during the initial attempt. 931 */ 932if(state->threeway && !index_file) { 933 cp.no_stdout =1; 934 cp.no_stderr =1; 935} 936 937argv_array_push(&cp.args,"apply"); 938 939if(index_file) 940argv_array_push(&cp.args,"--cached"); 941else 942argv_array_push(&cp.args,"--index"); 943 944argv_array_push(&cp.args,am_path(state,"patch")); 945 946if(run_command(&cp)) 947return-1; 948 949/* Reload index as git-apply will have modified it. */ 950discard_cache(); 951read_cache_from(index_file ? index_file :get_index_file()); 952 953return0; 954} 955 956/** 957 * Builds an index that contains just the blobs needed for a 3way merge. 958 */ 959static intbuild_fake_ancestor(const struct am_state *state,const char*index_file) 960{ 961struct child_process cp = CHILD_PROCESS_INIT; 962 963 cp.git_cmd =1; 964argv_array_push(&cp.args,"apply"); 965argv_array_pushf(&cp.args,"--build-fake-ancestor=%s", index_file); 966argv_array_push(&cp.args,am_path(state,"patch")); 967 968if(run_command(&cp)) 969return-1; 970 971return0; 972} 973 974/** 975 * Attempt a threeway merge, using index_path as the temporary index. 976 */ 977static intfall_back_threeway(const struct am_state *state,const char*index_path) 978{ 979unsigned char orig_tree[GIT_SHA1_RAWSZ], his_tree[GIT_SHA1_RAWSZ], 980 our_tree[GIT_SHA1_RAWSZ]; 981const unsigned char*bases[1] = {orig_tree}; 982struct merge_options o; 983struct commit *result; 984char*his_tree_name; 985 986if(get_sha1("HEAD", our_tree) <0) 987hashcpy(our_tree, EMPTY_TREE_SHA1_BIN); 988 989if(build_fake_ancestor(state, index_path)) 990returnerror("could not build fake ancestor"); 991 992discard_cache(); 993read_cache_from(index_path); 994 995if(write_index_as_tree(orig_tree, &the_index, index_path,0, NULL)) 996returnerror(_("Repository lacks necessary blobs to fall back on 3-way merge.")); 997 998say(state, stdout,_("Using index info to reconstruct a base tree...")); 9991000if(!state->quiet) {1001/*1002 * List paths that needed 3-way fallback, so that the user can1003 * review them with extra care to spot mismerges.1004 */1005struct rev_info rev_info;1006const char*diff_filter_str ="--diff-filter=AM";10071008init_revisions(&rev_info, NULL);1009 rev_info.diffopt.output_format = DIFF_FORMAT_NAME_STATUS;1010diff_opt_parse(&rev_info.diffopt, &diff_filter_str,1);1011add_pending_sha1(&rev_info,"HEAD", our_tree,0);1012diff_setup_done(&rev_info.diffopt);1013run_diff_index(&rev_info,1);1014}10151016if(run_apply(state, index_path))1017returnerror(_("Did you hand edit your patch?\n"1018"It does not apply to blobs recorded in its index."));10191020if(write_index_as_tree(his_tree, &the_index, index_path,0, NULL))1021returnerror("could not write tree");10221023say(state, stdout,_("Falling back to patching base and 3-way merge..."));10241025discard_cache();1026read_cache();10271028/*1029 * This is not so wrong. Depending on which base we picked, orig_tree1030 * may be wildly different from ours, but his_tree has the same set of1031 * wildly different changes in parts the patch did not touch, so1032 * recursive ends up canceling them, saying that we reverted all those1033 * changes.1034 */10351036init_merge_options(&o);10371038 o.branch1 ="HEAD";1039 his_tree_name =xstrfmt("%.*s",linelen(state->msg), state->msg);1040 o.branch2 = his_tree_name;10411042if(state->quiet)1043 o.verbosity =0;10441045if(merge_recursive_generic(&o, our_tree, his_tree,1, bases, &result)) {1046free(his_tree_name);1047returnerror(_("Failed to merge in the changes."));1048}10491050free(his_tree_name);1051return0;1052}10531054/**1055 * Commits the current index with state->msg as the commit message and1056 * state->author_name, state->author_email and state->author_date as the author1057 * information.1058 */1059static voiddo_commit(const struct am_state *state)1060{1061unsigned char tree[GIT_SHA1_RAWSZ], parent[GIT_SHA1_RAWSZ],1062 commit[GIT_SHA1_RAWSZ];1063unsigned char*ptr;1064struct commit_list *parents = NULL;1065const char*reflog_msg, *author;1066struct strbuf sb = STRBUF_INIT;10671068if(write_cache_as_tree(tree,0, NULL))1069die(_("git write-tree failed to write a tree"));10701071if(!get_sha1_commit("HEAD", parent)) {1072 ptr = parent;1073commit_list_insert(lookup_commit(parent), &parents);1074}else{1075 ptr = NULL;1076say(state, stderr,_("applying to an empty history"));1077}10781079 author =fmt_ident(state->author_name, state->author_email,1080 state->author_date, IDENT_STRICT);10811082if(commit_tree(state->msg, state->msg_len, tree, parents, commit,1083 author, NULL))1084die(_("failed to write commit object"));10851086 reflog_msg =getenv("GIT_REFLOG_ACTION");1087if(!reflog_msg)1088 reflog_msg ="am";10891090strbuf_addf(&sb,"%s: %.*s", reflog_msg,linelen(state->msg),1091 state->msg);10921093update_ref(sb.buf,"HEAD", commit, ptr,0, UPDATE_REFS_DIE_ON_ERR);10941095strbuf_release(&sb);1096}10971098/**1099 * Validates the am_state for resuming -- the "msg" and authorship fields must1100 * be filled up.1101 */1102static voidvalidate_resume_state(const struct am_state *state)1103{1104if(!state->msg)1105die(_("cannot resume:%sdoes not exist."),1106am_path(state,"final-commit"));11071108if(!state->author_name || !state->author_email || !state->author_date)1109die(_("cannot resume:%sdoes not exist."),1110am_path(state,"author-script"));1111}11121113/**1114 * Applies all queued mail.1115 *1116 * If `resume` is true, we are "resuming". The "msg" and authorship fields, as1117 * well as the state directory's "patch" file is used as-is for applying the1118 * patch and committing it.1119 */1120static voidam_run(struct am_state *state,int resume)1121{1122const char*argv_gc_auto[] = {"gc","--auto", NULL};1123struct strbuf sb = STRBUF_INIT;11241125unlink(am_path(state,"dirtyindex"));11261127refresh_and_write_cache();11281129if(index_has_changes(&sb)) {1130write_file(am_path(state,"dirtyindex"),1,"t");1131die(_("Dirty index: cannot apply patches (dirty:%s)"), sb.buf);1132}11331134strbuf_release(&sb);11351136while(state->cur <= state->last) {1137const char*mail =am_path(state,msgnum(state));1138int apply_status;11391140if(!file_exists(mail))1141goto next;11421143if(resume) {1144validate_resume_state(state);1145 resume =0;1146}else{1147int skip;11481149if(state->rebasing)1150 skip =parse_mail_rebase(state, mail);1151else1152 skip =parse_mail(state, mail);11531154if(skip)1155goto next;/* mail should be skipped */11561157write_author_script(state);1158write_commit_msg(state);1159}11601161say(state, stdout,_("Applying: %.*s"),linelen(state->msg), state->msg);11621163 apply_status =run_apply(state, NULL);11641165if(apply_status && state->threeway) {1166struct strbuf sb = STRBUF_INIT;11671168strbuf_addstr(&sb,am_path(state,"patch-merge-index"));1169 apply_status =fall_back_threeway(state, sb.buf);1170strbuf_release(&sb);11711172/*1173 * Applying the patch to an earlier tree and merging1174 * the result may have produced the same tree as ours.1175 */1176if(!apply_status && !index_has_changes(NULL)) {1177say(state, stdout,_("No changes -- Patch already applied."));1178goto next;1179}1180}11811182if(apply_status) {1183int advice_amworkdir =1;11841185printf_ln(_("Patch failed at%s%.*s"),msgnum(state),1186linelen(state->msg), state->msg);11871188git_config_get_bool("advice.amworkdir", &advice_amworkdir);11891190if(advice_amworkdir)1191printf_ln(_("The copy of the patch that failed is found in:%s"),1192am_path(state,"patch"));11931194die_user_resolve(state);1195}11961197do_commit(state);11981199next:1200am_next(state);1201}12021203/*1204 * In rebasing mode, it's up to the caller to take care of1205 * housekeeping.1206 */1207if(!state->rebasing) {1208am_destroy(state);1209run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);1210}1211}12121213/**1214 * Resume the current am session after patch application failure. The user did1215 * all the hard work, and we do not have to do any patch application. Just1216 * trust and commit what the user has in the index and working tree.1217 */1218static voidam_resolve(struct am_state *state)1219{1220validate_resume_state(state);12211222say(state, stdout,_("Applying: %.*s"),linelen(state->msg), state->msg);12231224if(!index_has_changes(NULL)) {1225printf_ln(_("No changes - did you forget to use 'git add'?\n"1226"If there is nothing left to stage, chances are that something else\n"1227"already introduced the same changes; you might want to skip this patch."));1228die_user_resolve(state);1229}12301231if(unmerged_cache()) {1232printf_ln(_("You still have unmerged paths in your index.\n"1233"Did you forget to use 'git add'?"));1234die_user_resolve(state);1235}12361237do_commit(state);12381239am_next(state);1240am_run(state,0);1241}12421243/**1244 * Performs a checkout fast-forward from `head` to `remote`. If `reset` is1245 * true, any unmerged entries will be discarded. Returns 0 on success, -1 on1246 * failure.1247 */1248static intfast_forward_to(struct tree *head,struct tree *remote,int reset)1249{1250struct lock_file *lock_file;1251struct unpack_trees_options opts;1252struct tree_desc t[2];12531254if(parse_tree(head) ||parse_tree(remote))1255return-1;12561257 lock_file =xcalloc(1,sizeof(struct lock_file));1258hold_locked_index(lock_file,1);12591260refresh_cache(REFRESH_QUIET);12611262memset(&opts,0,sizeof(opts));1263 opts.head_idx =1;1264 opts.src_index = &the_index;1265 opts.dst_index = &the_index;1266 opts.update =1;1267 opts.merge =1;1268 opts.reset = reset;1269 opts.fn = twoway_merge;1270init_tree_desc(&t[0], head->buffer, head->size);1271init_tree_desc(&t[1], remote->buffer, remote->size);12721273if(unpack_trees(2, t, &opts)) {1274rollback_lock_file(lock_file);1275return-1;1276}12771278if(write_locked_index(&the_index, lock_file, COMMIT_LOCK))1279die(_("unable to write new index file"));12801281return0;1282}12831284/**1285 * Clean the index without touching entries that are not modified between1286 * `head` and `remote`.1287 */1288static intclean_index(const unsigned char*head,const unsigned char*remote)1289{1290struct lock_file *lock_file;1291struct tree *head_tree, *remote_tree, *index_tree;1292unsigned char index[GIT_SHA1_RAWSZ];1293struct pathspec pathspec;12941295 head_tree =parse_tree_indirect(head);1296if(!head_tree)1297returnerror(_("Could not parse object '%s'."),sha1_to_hex(head));12981299 remote_tree =parse_tree_indirect(remote);1300if(!remote_tree)1301returnerror(_("Could not parse object '%s'."),sha1_to_hex(remote));13021303read_cache_unmerged();13041305if(fast_forward_to(head_tree, head_tree,1))1306return-1;13071308if(write_cache_as_tree(index,0, NULL))1309return-1;13101311 index_tree =parse_tree_indirect(index);1312if(!index_tree)1313returnerror(_("Could not parse object '%s'."),sha1_to_hex(index));13141315if(fast_forward_to(index_tree, remote_tree,0))1316return-1;13171318memset(&pathspec,0,sizeof(pathspec));13191320 lock_file =xcalloc(1,sizeof(struct lock_file));1321hold_locked_index(lock_file,1);13221323if(read_tree(remote_tree,0, &pathspec)) {1324rollback_lock_file(lock_file);1325return-1;1326}13271328if(write_locked_index(&the_index, lock_file, COMMIT_LOCK))1329die(_("unable to write new index file"));13301331remove_branch_state();13321333return0;1334}13351336/**1337 * Resume the current am session by skipping the current patch.1338 */1339static voidam_skip(struct am_state *state)1340{1341unsigned char head[GIT_SHA1_RAWSZ];13421343if(get_sha1("HEAD", head))1344hashcpy(head, EMPTY_TREE_SHA1_BIN);13451346if(clean_index(head, head))1347die(_("failed to clean index"));13481349am_next(state);1350am_run(state,0);1351}13521353/**1354 * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.1355 *1356 * It is not safe to reset HEAD when:1357 * 1. git-am previously failed because the index was dirty.1358 * 2. HEAD has moved since git-am previously failed.1359 */1360static intsafe_to_abort(const struct am_state *state)1361{1362struct strbuf sb = STRBUF_INIT;1363unsigned char abort_safety[GIT_SHA1_RAWSZ], head[GIT_SHA1_RAWSZ];13641365if(file_exists(am_path(state,"dirtyindex")))1366return0;13671368if(read_state_file(&sb, state,"abort-safety",1) >0) {1369if(get_sha1_hex(sb.buf, abort_safety))1370die(_("could not parse%s"),am_path(state,"abort_safety"));1371}else1372hashclr(abort_safety);13731374if(get_sha1("HEAD", head))1375hashclr(head);13761377if(!hashcmp(head, abort_safety))1378return1;13791380error(_("You seem to have moved HEAD since the last 'am' failure.\n"1381"Not rewinding to ORIG_HEAD"));13821383return0;1384}13851386/**1387 * Aborts the current am session if it is safe to do so.1388 */1389static voidam_abort(struct am_state *state)1390{1391unsigned char curr_head[GIT_SHA1_RAWSZ], orig_head[GIT_SHA1_RAWSZ];1392int has_curr_head, has_orig_head;1393char*curr_branch;13941395if(!safe_to_abort(state)) {1396am_destroy(state);1397return;1398}13991400 curr_branch =resolve_refdup("HEAD",0, curr_head, NULL);1401 has_curr_head = !is_null_sha1(curr_head);1402if(!has_curr_head)1403hashcpy(curr_head, EMPTY_TREE_SHA1_BIN);14041405 has_orig_head = !get_sha1("ORIG_HEAD", orig_head);1406if(!has_orig_head)1407hashcpy(orig_head, EMPTY_TREE_SHA1_BIN);14081409clean_index(curr_head, orig_head);14101411if(has_orig_head)1412update_ref("am --abort","HEAD", orig_head,1413 has_curr_head ? curr_head : NULL,0,1414 UPDATE_REFS_DIE_ON_ERR);1415else if(curr_branch)1416delete_ref(curr_branch, NULL, REF_NODEREF);14171418free(curr_branch);1419am_destroy(state);1420}14211422/**1423 * parse_options() callback that validates and sets opt->value to the1424 * PATCH_FORMAT_* enum value corresponding to `arg`.1425 */1426static intparse_opt_patchformat(const struct option *opt,const char*arg,int unset)1427{1428int*opt_value = opt->value;14291430if(!strcmp(arg,"mbox"))1431*opt_value = PATCH_FORMAT_MBOX;1432else1433returnerror(_("Invalid value for --patch-format:%s"), arg);1434return0;1435}14361437enum resume_mode {1438 RESUME_FALSE =0,1439 RESUME_APPLY,1440 RESUME_RESOLVED,1441 RESUME_SKIP,1442 RESUME_ABORT1443};14441445intcmd_am(int argc,const char**argv,const char*prefix)1446{1447struct am_state state;1448int patch_format = PATCH_FORMAT_UNKNOWN;1449enum resume_mode resume = RESUME_FALSE;14501451const char*const usage[] = {1452N_("git am [options] [(<mbox>|<Maildir>)...]"),1453N_("git am [options] (--continue | --skip | --abort)"),1454 NULL1455};14561457struct option options[] = {1458OPT_BOOL('3',"3way", &state.threeway,1459N_("allow fall back on 3way merging if needed")),1460OPT__QUIET(&state.quiet,N_("be quiet")),1461OPT_BOOL('s',"signoff", &state.signoff,1462N_("add a Signed-off-by line to the commit message")),1463OPT_CALLBACK(0,"patch-format", &patch_format,N_("format"),1464N_("format the patch(es) are in"),1465 parse_opt_patchformat),1466OPT_STRING(0,"resolvemsg", &state.resolvemsg, NULL,1467N_("override error message when patch failure occurs")),1468OPT_CMDMODE(0,"continue", &resume,1469N_("continue applying patches after resolving a conflict"),1470 RESUME_RESOLVED),1471OPT_CMDMODE('r',"resolved", &resume,1472N_("synonyms for --continue"),1473 RESUME_RESOLVED),1474OPT_CMDMODE(0,"skip", &resume,1475N_("skip the current patch"),1476 RESUME_SKIP),1477OPT_CMDMODE(0,"abort", &resume,1478N_("restore the original branch and abort the patching operation."),1479 RESUME_ABORT),1480OPT_HIDDEN_BOOL(0,"rebasing", &state.rebasing,1481N_("(internal use for git-rebase)")),1482OPT_END()1483};14841485/*1486 * NEEDSWORK: Once all the features of git-am.sh have been1487 * re-implemented in builtin/am.c, this preamble can be removed.1488 */1489if(!getenv("_GIT_USE_BUILTIN_AM")) {1490const char*path =mkpath("%s/git-am",git_exec_path());14911492if(sane_execvp(path, (char**)argv) <0)1493die_errno("could not exec%s", path);1494}else{1495 prefix =setup_git_directory();1496trace_repo_setup(prefix);1497setup_work_tree();1498}14991500git_config(git_default_config, NULL);15011502am_state_init(&state,git_path("rebase-apply"));15031504 argc =parse_options(argc, argv, prefix, options, usage,0);15051506if(read_index_preload(&the_index, NULL) <0)1507die(_("failed to read the index"));15081509if(am_in_progress(&state)) {1510/*1511 * Catch user error to feed us patches when there is a session1512 * in progress:1513 *1514 * 1. mbox path(s) are provided on the command-line.1515 * 2. stdin is not a tty: the user is trying to feed us a patch1516 * from standard input. This is somewhat unreliable -- stdin1517 * could be /dev/null for example and the caller did not1518 * intend to feed us a patch but wanted to continue1519 * unattended.1520 */1521if(argc || (resume == RESUME_FALSE && !isatty(0)))1522die(_("previous rebase directory%sstill exists but mbox given."),1523 state.dir);15241525if(resume == RESUME_FALSE)1526 resume = RESUME_APPLY;15271528am_load(&state);1529}else{1530struct argv_array paths = ARGV_ARRAY_INIT;1531int i;15321533/*1534 * Handle stray state directory in the independent-run case. In1535 * the --rebasing case, it is up to the caller to take care of1536 * stray directories.1537 */1538if(file_exists(state.dir) && !state.rebasing) {1539if(resume == RESUME_ABORT) {1540am_destroy(&state);1541am_state_release(&state);1542return0;1543}15441545die(_("Stray%sdirectory found.\n"1546"Use\"git am --abort\"to remove it."),1547 state.dir);1548}15491550if(resume)1551die(_("Resolve operation not in progress, we are not resuming."));15521553for(i =0; i < argc; i++) {1554if(is_absolute_path(argv[i]) || !prefix)1555argv_array_push(&paths, argv[i]);1556else1557argv_array_push(&paths,mkpath("%s/%s", prefix, argv[i]));1558}15591560am_setup(&state, patch_format, paths.argv);15611562argv_array_clear(&paths);1563}15641565switch(resume) {1566case RESUME_FALSE:1567am_run(&state,0);1568break;1569case RESUME_APPLY:1570am_run(&state,1);1571break;1572case RESUME_RESOLVED:1573am_resolve(&state);1574break;1575case RESUME_SKIP:1576am_skip(&state);1577break;1578case RESUME_ABORT:1579am_abort(&state);1580break;1581default:1582die("BUG: invalid resume value");1583}15841585am_state_release(&state);15861587return0;1588}