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; 93int utf8; 94const char*resolvemsg; 95int rebasing; 96}; 97 98/** 99 * Initializes am_state with the default values. The state directory is set to 100 * dir. 101 */ 102static voidam_state_init(struct am_state *state,const char*dir) 103{ 104memset(state,0,sizeof(*state)); 105 106assert(dir); 107 state->dir =xstrdup(dir); 108 109 state->prec =4; 110 111 state->utf8 =1; 112} 113 114/** 115 * Releases memory allocated by an am_state. 116 */ 117static voidam_state_release(struct am_state *state) 118{ 119free(state->dir); 120free(state->author_name); 121free(state->author_email); 122free(state->author_date); 123free(state->msg); 124} 125 126/** 127 * Returns path relative to the am_state directory. 128 */ 129staticinlineconst char*am_path(const struct am_state *state,const char*path) 130{ 131returnmkpath("%s/%s", state->dir, path); 132} 133 134/** 135 * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline 136 * at the end. 137 */ 138static voidsay(const struct am_state *state,FILE*fp,const char*fmt, ...) 139{ 140va_list ap; 141 142va_start(ap, fmt); 143if(!state->quiet) { 144vfprintf(fp, fmt, ap); 145putc('\n', fp); 146} 147va_end(ap); 148} 149 150/** 151 * Returns 1 if there is an am session in progress, 0 otherwise. 152 */ 153static intam_in_progress(const struct am_state *state) 154{ 155struct stat st; 156 157if(lstat(state->dir, &st) <0|| !S_ISDIR(st.st_mode)) 158return0; 159if(lstat(am_path(state,"last"), &st) || !S_ISREG(st.st_mode)) 160return0; 161if(lstat(am_path(state,"next"), &st) || !S_ISREG(st.st_mode)) 162return0; 163return1; 164} 165 166/** 167 * Reads the contents of `file` in the `state` directory into `sb`. Returns the 168 * number of bytes read on success, -1 if the file does not exist. If `trim` is 169 * set, trailing whitespace will be removed. 170 */ 171static intread_state_file(struct strbuf *sb,const struct am_state *state, 172const char*file,int trim) 173{ 174strbuf_reset(sb); 175 176if(strbuf_read_file(sb,am_path(state, file),0) >=0) { 177if(trim) 178strbuf_trim(sb); 179 180return sb->len; 181} 182 183if(errno == ENOENT) 184return-1; 185 186die_errno(_("could not read '%s'"),am_path(state, file)); 187} 188 189/** 190 * Reads a KEY=VALUE shell variable assignment from `fp`, returning the VALUE 191 * as a newly-allocated string. VALUE must be a quoted string, and the KEY must 192 * match `key`. Returns NULL on failure. 193 * 194 * This is used by read_author_script() to read the GIT_AUTHOR_* variables from 195 * the author-script. 196 */ 197static char*read_shell_var(FILE*fp,const char*key) 198{ 199struct strbuf sb = STRBUF_INIT; 200const char*str; 201 202if(strbuf_getline(&sb, fp,'\n')) 203goto fail; 204 205if(!skip_prefix(sb.buf, key, &str)) 206goto fail; 207 208if(!skip_prefix(str,"=", &str)) 209goto fail; 210 211strbuf_remove(&sb,0, str - sb.buf); 212 213 str =sq_dequote(sb.buf); 214if(!str) 215goto fail; 216 217returnstrbuf_detach(&sb, NULL); 218 219fail: 220strbuf_release(&sb); 221return NULL; 222} 223 224/** 225 * Reads and parses the state directory's "author-script" file, and sets 226 * state->author_name, state->author_email and state->author_date accordingly. 227 * Returns 0 on success, -1 if the file could not be parsed. 228 * 229 * The author script is of the format: 230 * 231 * GIT_AUTHOR_NAME='$author_name' 232 * GIT_AUTHOR_EMAIL='$author_email' 233 * GIT_AUTHOR_DATE='$author_date' 234 * 235 * where $author_name, $author_email and $author_date are quoted. We are strict 236 * with our parsing, as the file was meant to be eval'd in the old git-am.sh 237 * script, and thus if the file differs from what this function expects, it is 238 * better to bail out than to do something that the user does not expect. 239 */ 240static intread_author_script(struct am_state *state) 241{ 242const char*filename =am_path(state,"author-script"); 243FILE*fp; 244 245assert(!state->author_name); 246assert(!state->author_email); 247assert(!state->author_date); 248 249 fp =fopen(filename,"r"); 250if(!fp) { 251if(errno == ENOENT) 252return0; 253die_errno(_("could not open '%s' for reading"), filename); 254} 255 256 state->author_name =read_shell_var(fp,"GIT_AUTHOR_NAME"); 257if(!state->author_name) { 258fclose(fp); 259return-1; 260} 261 262 state->author_email =read_shell_var(fp,"GIT_AUTHOR_EMAIL"); 263if(!state->author_email) { 264fclose(fp); 265return-1; 266} 267 268 state->author_date =read_shell_var(fp,"GIT_AUTHOR_DATE"); 269if(!state->author_date) { 270fclose(fp); 271return-1; 272} 273 274if(fgetc(fp) != EOF) { 275fclose(fp); 276return-1; 277} 278 279fclose(fp); 280return0; 281} 282 283/** 284 * Saves state->author_name, state->author_email and state->author_date in the 285 * state directory's "author-script" file. 286 */ 287static voidwrite_author_script(const struct am_state *state) 288{ 289struct strbuf sb = STRBUF_INIT; 290 291strbuf_addstr(&sb,"GIT_AUTHOR_NAME="); 292sq_quote_buf(&sb, state->author_name); 293strbuf_addch(&sb,'\n'); 294 295strbuf_addstr(&sb,"GIT_AUTHOR_EMAIL="); 296sq_quote_buf(&sb, state->author_email); 297strbuf_addch(&sb,'\n'); 298 299strbuf_addstr(&sb,"GIT_AUTHOR_DATE="); 300sq_quote_buf(&sb, state->author_date); 301strbuf_addch(&sb,'\n'); 302 303write_file(am_path(state,"author-script"),1,"%s", sb.buf); 304 305strbuf_release(&sb); 306} 307 308/** 309 * Reads the commit message from the state directory's "final-commit" file, 310 * setting state->msg to its contents and state->msg_len to the length of its 311 * contents in bytes. 312 * 313 * Returns 0 on success, -1 if the file does not exist. 314 */ 315static intread_commit_msg(struct am_state *state) 316{ 317struct strbuf sb = STRBUF_INIT; 318 319assert(!state->msg); 320 321if(read_state_file(&sb, state,"final-commit",0) <0) { 322strbuf_release(&sb); 323return-1; 324} 325 326 state->msg =strbuf_detach(&sb, &state->msg_len); 327return0; 328} 329 330/** 331 * Saves state->msg in the state directory's "final-commit" file. 332 */ 333static voidwrite_commit_msg(const struct am_state *state) 334{ 335int fd; 336const char*filename =am_path(state,"final-commit"); 337 338 fd =xopen(filename, O_WRONLY | O_CREAT,0666); 339if(write_in_full(fd, state->msg, state->msg_len) <0) 340die_errno(_("could not write to%s"), filename); 341close(fd); 342} 343 344/** 345 * Loads state from disk. 346 */ 347static voidam_load(struct am_state *state) 348{ 349struct strbuf sb = STRBUF_INIT; 350 351if(read_state_file(&sb, state,"next",1) <0) 352die("BUG: state file 'next' does not exist"); 353 state->cur =strtol(sb.buf, NULL,10); 354 355if(read_state_file(&sb, state,"last",1) <0) 356die("BUG: state file 'last' does not exist"); 357 state->last =strtol(sb.buf, NULL,10); 358 359if(read_author_script(state) <0) 360die(_("could not parse author script")); 361 362read_commit_msg(state); 363 364read_state_file(&sb, state,"threeway",1); 365 state->threeway = !strcmp(sb.buf,"t"); 366 367read_state_file(&sb, state,"quiet",1); 368 state->quiet = !strcmp(sb.buf,"t"); 369 370read_state_file(&sb, state,"sign",1); 371 state->signoff = !strcmp(sb.buf,"t"); 372 373read_state_file(&sb, state,"utf8",1); 374 state->utf8 = !strcmp(sb.buf,"t"); 375 376 state->rebasing = !!file_exists(am_path(state,"rebasing")); 377 378strbuf_release(&sb); 379} 380 381/** 382 * Removes the am_state directory, forcefully terminating the current am 383 * session. 384 */ 385static voidam_destroy(const struct am_state *state) 386{ 387struct strbuf sb = STRBUF_INIT; 388 389strbuf_addstr(&sb, state->dir); 390remove_dir_recursively(&sb,0); 391strbuf_release(&sb); 392} 393 394/** 395 * Determines if the file looks like a piece of RFC2822 mail by grabbing all 396 * non-indented lines and checking if they look like they begin with valid 397 * header field names. 398 * 399 * Returns 1 if the file looks like a piece of mail, 0 otherwise. 400 */ 401static intis_mail(FILE*fp) 402{ 403const char*header_regex ="^[!-9;-~]+:"; 404struct strbuf sb = STRBUF_INIT; 405 regex_t regex; 406int ret =1; 407 408if(fseek(fp,0L, SEEK_SET)) 409die_errno(_("fseek failed")); 410 411if(regcomp(®ex, header_regex, REG_NOSUB | REG_EXTENDED)) 412die("invalid pattern:%s", header_regex); 413 414while(!strbuf_getline_crlf(&sb, fp)) { 415if(!sb.len) 416break;/* End of header */ 417 418/* Ignore indented folded lines */ 419if(*sb.buf =='\t'|| *sb.buf ==' ') 420continue; 421 422/* It's a header if it matches header_regex */ 423if(regexec(®ex, sb.buf,0, NULL,0)) { 424 ret =0; 425goto done; 426} 427} 428 429done: 430regfree(®ex); 431strbuf_release(&sb); 432return ret; 433} 434 435/** 436 * Attempts to detect the patch_format of the patches contained in `paths`, 437 * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if 438 * detection fails. 439 */ 440static intdetect_patch_format(const char**paths) 441{ 442enum patch_format ret = PATCH_FORMAT_UNKNOWN; 443struct strbuf l1 = STRBUF_INIT; 444FILE*fp; 445 446/* 447 * We default to mbox format if input is from stdin and for directories 448 */ 449if(!*paths || !strcmp(*paths,"-") ||is_directory(*paths)) 450return PATCH_FORMAT_MBOX; 451 452/* 453 * Otherwise, check the first few lines of the first patch, starting 454 * from the first non-blank line, to try to detect its format. 455 */ 456 457 fp =xfopen(*paths,"r"); 458 459while(!strbuf_getline_crlf(&l1, fp)) { 460if(l1.len) 461break; 462} 463 464if(starts_with(l1.buf,"From ") ||starts_with(l1.buf,"From: ")) { 465 ret = PATCH_FORMAT_MBOX; 466goto done; 467} 468 469if(l1.len &&is_mail(fp)) { 470 ret = PATCH_FORMAT_MBOX; 471goto done; 472} 473 474done: 475fclose(fp); 476strbuf_release(&l1); 477return ret; 478} 479 480/** 481 * Splits out individual email patches from `paths`, where each path is either 482 * a mbox file or a Maildir. Returns 0 on success, -1 on failure. 483 */ 484static intsplit_mail_mbox(struct am_state *state,const char**paths) 485{ 486struct child_process cp = CHILD_PROCESS_INIT; 487struct strbuf last = STRBUF_INIT; 488 489 cp.git_cmd =1; 490argv_array_push(&cp.args,"mailsplit"); 491argv_array_pushf(&cp.args,"-d%d", state->prec); 492argv_array_pushf(&cp.args,"-o%s", state->dir); 493argv_array_push(&cp.args,"-b"); 494argv_array_push(&cp.args,"--"); 495argv_array_pushv(&cp.args, paths); 496 497if(capture_command(&cp, &last,8)) 498return-1; 499 500 state->cur =1; 501 state->last =strtol(last.buf, NULL,10); 502 503return0; 504} 505 506/** 507 * Splits a list of files/directories into individual email patches. Each path 508 * in `paths` must be a file/directory that is formatted according to 509 * `patch_format`. 510 * 511 * Once split out, the individual email patches will be stored in the state 512 * directory, with each patch's filename being its index, padded to state->prec 513 * digits. 514 * 515 * state->cur will be set to the index of the first mail, and state->last will 516 * be set to the index of the last mail. 517 * 518 * Returns 0 on success, -1 on failure. 519 */ 520static intsplit_mail(struct am_state *state,enum patch_format patch_format, 521const char**paths) 522{ 523switch(patch_format) { 524case PATCH_FORMAT_MBOX: 525returnsplit_mail_mbox(state, paths); 526default: 527die("BUG: invalid patch_format"); 528} 529return-1; 530} 531 532/** 533 * Setup a new am session for applying patches 534 */ 535static voidam_setup(struct am_state *state,enum patch_format patch_format, 536const char**paths) 537{ 538unsigned char curr_head[GIT_SHA1_RAWSZ]; 539 540if(!patch_format) 541 patch_format =detect_patch_format(paths); 542 543if(!patch_format) { 544fprintf_ln(stderr,_("Patch format detection failed.")); 545exit(128); 546} 547 548if(mkdir(state->dir,0777) <0&& errno != EEXIST) 549die_errno(_("failed to create directory '%s'"), state->dir); 550 551if(split_mail(state, patch_format, paths) <0) { 552am_destroy(state); 553die(_("Failed to split patches.")); 554} 555 556if(state->rebasing) 557 state->threeway =1; 558 559write_file(am_path(state,"threeway"),1, state->threeway ?"t":"f"); 560 561write_file(am_path(state,"quiet"),1, state->quiet ?"t":"f"); 562 563write_file(am_path(state,"sign"),1, state->signoff ?"t":"f"); 564 565write_file(am_path(state,"utf8"),1, state->utf8 ?"t":"f"); 566 567if(state->rebasing) 568write_file(am_path(state,"rebasing"),1,"%s",""); 569else 570write_file(am_path(state,"applying"),1,"%s",""); 571 572if(!get_sha1("HEAD", curr_head)) { 573write_file(am_path(state,"abort-safety"),1,"%s",sha1_to_hex(curr_head)); 574if(!state->rebasing) 575update_ref("am","ORIG_HEAD", curr_head, NULL,0, 576 UPDATE_REFS_DIE_ON_ERR); 577}else{ 578write_file(am_path(state,"abort-safety"),1,"%s",""); 579if(!state->rebasing) 580delete_ref("ORIG_HEAD", NULL,0); 581} 582 583/* 584 * NOTE: Since the "next" and "last" files determine if an am_state 585 * session is in progress, they should be written last. 586 */ 587 588write_file(am_path(state,"next"),1,"%d", state->cur); 589 590write_file(am_path(state,"last"),1,"%d", state->last); 591} 592 593/** 594 * Increments the patch pointer, and cleans am_state for the application of the 595 * next patch. 596 */ 597static voidam_next(struct am_state *state) 598{ 599unsigned char head[GIT_SHA1_RAWSZ]; 600 601free(state->author_name); 602 state->author_name = NULL; 603 604free(state->author_email); 605 state->author_email = NULL; 606 607free(state->author_date); 608 state->author_date = NULL; 609 610free(state->msg); 611 state->msg = NULL; 612 state->msg_len =0; 613 614unlink(am_path(state,"author-script")); 615unlink(am_path(state,"final-commit")); 616 617if(!get_sha1("HEAD", head)) 618write_file(am_path(state,"abort-safety"),1,"%s",sha1_to_hex(head)); 619else 620write_file(am_path(state,"abort-safety"),1,"%s",""); 621 622 state->cur++; 623write_file(am_path(state,"next"),1,"%d", state->cur); 624} 625 626/** 627 * Returns the filename of the current patch email. 628 */ 629static const char*msgnum(const struct am_state *state) 630{ 631static struct strbuf sb = STRBUF_INIT; 632 633strbuf_reset(&sb); 634strbuf_addf(&sb,"%0*d", state->prec, state->cur); 635 636return sb.buf; 637} 638 639/** 640 * Refresh and write index. 641 */ 642static voidrefresh_and_write_cache(void) 643{ 644struct lock_file *lock_file =xcalloc(1,sizeof(struct lock_file)); 645 646hold_locked_index(lock_file,1); 647refresh_cache(REFRESH_QUIET); 648if(write_locked_index(&the_index, lock_file, COMMIT_LOCK)) 649die(_("unable to write index file")); 650} 651 652/** 653 * Returns 1 if the index differs from HEAD, 0 otherwise. When on an unborn 654 * branch, returns 1 if there are entries in the index, 0 otherwise. If an 655 * strbuf is provided, the space-separated list of files that differ will be 656 * appended to it. 657 */ 658static intindex_has_changes(struct strbuf *sb) 659{ 660unsigned char head[GIT_SHA1_RAWSZ]; 661int i; 662 663if(!get_sha1_tree("HEAD", head)) { 664struct diff_options opt; 665 666diff_setup(&opt); 667DIFF_OPT_SET(&opt, EXIT_WITH_STATUS); 668if(!sb) 669DIFF_OPT_SET(&opt, QUICK); 670do_diff_cache(head, &opt); 671diffcore_std(&opt); 672for(i =0; sb && i < diff_queued_diff.nr; i++) { 673if(i) 674strbuf_addch(sb,' '); 675strbuf_addstr(sb, diff_queued_diff.queue[i]->two->path); 676} 677diff_flush(&opt); 678returnDIFF_OPT_TST(&opt, HAS_CHANGES) !=0; 679}else{ 680for(i =0; sb && i < active_nr; i++) { 681if(i) 682strbuf_addch(sb,' '); 683strbuf_addstr(sb, active_cache[i]->name); 684} 685return!!active_nr; 686} 687} 688 689/** 690 * Dies with a user-friendly message on how to proceed after resolving the 691 * problem. This message can be overridden with state->resolvemsg. 692 */ 693static void NORETURN die_user_resolve(const struct am_state *state) 694{ 695if(state->resolvemsg) { 696printf_ln("%s", state->resolvemsg); 697}else{ 698const char*cmdline ="git am"; 699 700printf_ln(_("When you have resolved this problem, run\"%s--continue\"."), cmdline); 701printf_ln(_("If you prefer to skip this patch, run\"%s--skip\"instead."), cmdline); 702printf_ln(_("To restore the original branch and stop patching, run\"%s--abort\"."), cmdline); 703} 704 705exit(128); 706} 707 708/** 709 * Parses `mail` using git-mailinfo, extracting its patch and authorship info. 710 * state->msg will be set to the patch message. state->author_name, 711 * state->author_email and state->author_date will be set to the patch author's 712 * name, email and date respectively. The patch body will be written to the 713 * state directory's "patch" file. 714 * 715 * Returns 1 if the patch should be skipped, 0 otherwise. 716 */ 717static intparse_mail(struct am_state *state,const char*mail) 718{ 719FILE*fp; 720struct child_process cp = CHILD_PROCESS_INIT; 721struct strbuf sb = STRBUF_INIT; 722struct strbuf msg = STRBUF_INIT; 723struct strbuf author_name = STRBUF_INIT; 724struct strbuf author_date = STRBUF_INIT; 725struct strbuf author_email = STRBUF_INIT; 726int ret =0; 727 728 cp.git_cmd =1; 729 cp.in =xopen(mail, O_RDONLY,0); 730 cp.out =xopen(am_path(state,"info"), O_WRONLY | O_CREAT,0777); 731 732argv_array_push(&cp.args,"mailinfo"); 733argv_array_push(&cp.args, state->utf8 ?"-u":"-n"); 734argv_array_push(&cp.args,am_path(state,"msg")); 735argv_array_push(&cp.args,am_path(state,"patch")); 736 737if(run_command(&cp) <0) 738die("could not parse patch"); 739 740close(cp.in); 741close(cp.out); 742 743/* Extract message and author information */ 744 fp =xfopen(am_path(state,"info"),"r"); 745while(!strbuf_getline(&sb, fp,'\n')) { 746const char*x; 747 748if(skip_prefix(sb.buf,"Subject: ", &x)) { 749if(msg.len) 750strbuf_addch(&msg,'\n'); 751strbuf_addstr(&msg, x); 752}else if(skip_prefix(sb.buf,"Author: ", &x)) 753strbuf_addstr(&author_name, x); 754else if(skip_prefix(sb.buf,"Email: ", &x)) 755strbuf_addstr(&author_email, x); 756else if(skip_prefix(sb.buf,"Date: ", &x)) 757strbuf_addstr(&author_date, x); 758} 759fclose(fp); 760 761/* Skip pine's internal folder data */ 762if(!strcmp(author_name.buf,"Mail System Internal Data")) { 763 ret =1; 764goto finish; 765} 766 767if(is_empty_file(am_path(state,"patch"))) { 768printf_ln(_("Patch is empty. Was it split wrong?")); 769die_user_resolve(state); 770} 771 772strbuf_addstr(&msg,"\n\n"); 773if(strbuf_read_file(&msg,am_path(state,"msg"),0) <0) 774die_errno(_("could not read '%s'"),am_path(state,"msg")); 775stripspace(&msg,0); 776 777if(state->signoff) 778append_signoff(&msg,0,0); 779 780assert(!state->author_name); 781 state->author_name =strbuf_detach(&author_name, NULL); 782 783assert(!state->author_email); 784 state->author_email =strbuf_detach(&author_email, NULL); 785 786assert(!state->author_date); 787 state->author_date =strbuf_detach(&author_date, NULL); 788 789assert(!state->msg); 790 state->msg =strbuf_detach(&msg, &state->msg_len); 791 792finish: 793strbuf_release(&msg); 794strbuf_release(&author_date); 795strbuf_release(&author_email); 796strbuf_release(&author_name); 797strbuf_release(&sb); 798return ret; 799} 800 801/** 802 * Sets commit_id to the commit hash where the mail was generated from. 803 * Returns 0 on success, -1 on failure. 804 */ 805static intget_mail_commit_sha1(unsigned char*commit_id,const char*mail) 806{ 807struct strbuf sb = STRBUF_INIT; 808FILE*fp =xfopen(mail,"r"); 809const char*x; 810 811if(strbuf_getline(&sb, fp,'\n')) 812return-1; 813 814if(!skip_prefix(sb.buf,"From ", &x)) 815return-1; 816 817if(get_sha1_hex(x, commit_id) <0) 818return-1; 819 820strbuf_release(&sb); 821fclose(fp); 822return0; 823} 824 825/** 826 * Sets state->msg, state->author_name, state->author_email, state->author_date 827 * to the commit's respective info. 828 */ 829static voidget_commit_info(struct am_state *state,struct commit *commit) 830{ 831const char*buffer, *ident_line, *author_date, *msg; 832size_t ident_len; 833struct ident_split ident_split; 834struct strbuf sb = STRBUF_INIT; 835 836 buffer =logmsg_reencode(commit, NULL,get_commit_output_encoding()); 837 838 ident_line =find_commit_header(buffer,"author", &ident_len); 839 840if(split_ident_line(&ident_split, ident_line, ident_len) <0) { 841strbuf_add(&sb, ident_line, ident_len); 842die(_("invalid ident line:%s"), sb.buf); 843} 844 845assert(!state->author_name); 846if(ident_split.name_begin) { 847strbuf_add(&sb, ident_split.name_begin, 848 ident_split.name_end - ident_split.name_begin); 849 state->author_name =strbuf_detach(&sb, NULL); 850}else 851 state->author_name =xstrdup(""); 852 853assert(!state->author_email); 854if(ident_split.mail_begin) { 855strbuf_add(&sb, ident_split.mail_begin, 856 ident_split.mail_end - ident_split.mail_begin); 857 state->author_email =strbuf_detach(&sb, NULL); 858}else 859 state->author_email =xstrdup(""); 860 861 author_date =show_ident_date(&ident_split,DATE_MODE(NORMAL)); 862strbuf_addstr(&sb, author_date); 863assert(!state->author_date); 864 state->author_date =strbuf_detach(&sb, NULL); 865 866assert(!state->msg); 867 msg =strstr(buffer,"\n\n"); 868if(!msg) 869die(_("unable to parse commit%s"),sha1_to_hex(commit->object.sha1)); 870 state->msg =xstrdup(msg +2); 871 state->msg_len =strlen(state->msg); 872} 873 874/** 875 * Writes `commit` as a patch to the state directory's "patch" file. 876 */ 877static voidwrite_commit_patch(const struct am_state *state,struct commit *commit) 878{ 879struct rev_info rev_info; 880FILE*fp; 881 882 fp =xfopen(am_path(state,"patch"),"w"); 883init_revisions(&rev_info, NULL); 884 rev_info.diff =1; 885 rev_info.abbrev =0; 886 rev_info.disable_stdin =1; 887 rev_info.show_root_diff =1; 888 rev_info.diffopt.output_format = DIFF_FORMAT_PATCH; 889 rev_info.no_commit_id =1; 890DIFF_OPT_SET(&rev_info.diffopt, BINARY); 891DIFF_OPT_SET(&rev_info.diffopt, FULL_INDEX); 892 rev_info.diffopt.use_color =0; 893 rev_info.diffopt.file = fp; 894 rev_info.diffopt.close_file =1; 895add_pending_object(&rev_info, &commit->object,""); 896diff_setup_done(&rev_info.diffopt); 897log_tree_commit(&rev_info, commit); 898} 899 900/** 901 * Like parse_mail(), but parses the mail by looking up its commit ID 902 * directly. This is used in --rebasing mode to bypass git-mailinfo's munging 903 * of patches. 904 * 905 * Will always return 0 as the patch should never be skipped. 906 */ 907static intparse_mail_rebase(struct am_state *state,const char*mail) 908{ 909struct commit *commit; 910unsigned char commit_sha1[GIT_SHA1_RAWSZ]; 911 912if(get_mail_commit_sha1(commit_sha1, mail) <0) 913die(_("could not parse%s"), mail); 914 915 commit =lookup_commit_or_die(commit_sha1, mail); 916 917get_commit_info(state, commit); 918 919write_commit_patch(state, commit); 920 921return0; 922} 923 924/** 925 * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If 926 * `index_file` is not NULL, the patch will be applied to that index. 927 */ 928static intrun_apply(const struct am_state *state,const char*index_file) 929{ 930struct child_process cp = CHILD_PROCESS_INIT; 931 932 cp.git_cmd =1; 933 934if(index_file) 935argv_array_pushf(&cp.env_array,"GIT_INDEX_FILE=%s", index_file); 936 937/* 938 * If we are allowed to fall back on 3-way merge, don't give false 939 * errors during the initial attempt. 940 */ 941if(state->threeway && !index_file) { 942 cp.no_stdout =1; 943 cp.no_stderr =1; 944} 945 946argv_array_push(&cp.args,"apply"); 947 948if(index_file) 949argv_array_push(&cp.args,"--cached"); 950else 951argv_array_push(&cp.args,"--index"); 952 953argv_array_push(&cp.args,am_path(state,"patch")); 954 955if(run_command(&cp)) 956return-1; 957 958/* Reload index as git-apply will have modified it. */ 959discard_cache(); 960read_cache_from(index_file ? index_file :get_index_file()); 961 962return0; 963} 964 965/** 966 * Builds an index that contains just the blobs needed for a 3way merge. 967 */ 968static intbuild_fake_ancestor(const struct am_state *state,const char*index_file) 969{ 970struct child_process cp = CHILD_PROCESS_INIT; 971 972 cp.git_cmd =1; 973argv_array_push(&cp.args,"apply"); 974argv_array_pushf(&cp.args,"--build-fake-ancestor=%s", index_file); 975argv_array_push(&cp.args,am_path(state,"patch")); 976 977if(run_command(&cp)) 978return-1; 979 980return0; 981} 982 983/** 984 * Attempt a threeway merge, using index_path as the temporary index. 985 */ 986static intfall_back_threeway(const struct am_state *state,const char*index_path) 987{ 988unsigned char orig_tree[GIT_SHA1_RAWSZ], his_tree[GIT_SHA1_RAWSZ], 989 our_tree[GIT_SHA1_RAWSZ]; 990const unsigned char*bases[1] = {orig_tree}; 991struct merge_options o; 992struct commit *result; 993char*his_tree_name; 994 995if(get_sha1("HEAD", our_tree) <0) 996hashcpy(our_tree, EMPTY_TREE_SHA1_BIN); 997 998if(build_fake_ancestor(state, index_path)) 999returnerror("could not build fake ancestor");10001001discard_cache();1002read_cache_from(index_path);10031004if(write_index_as_tree(orig_tree, &the_index, index_path,0, NULL))1005returnerror(_("Repository lacks necessary blobs to fall back on 3-way merge."));10061007say(state, stdout,_("Using index info to reconstruct a base tree..."));10081009if(!state->quiet) {1010/*1011 * List paths that needed 3-way fallback, so that the user can1012 * review them with extra care to spot mismerges.1013 */1014struct rev_info rev_info;1015const char*diff_filter_str ="--diff-filter=AM";10161017init_revisions(&rev_info, NULL);1018 rev_info.diffopt.output_format = DIFF_FORMAT_NAME_STATUS;1019diff_opt_parse(&rev_info.diffopt, &diff_filter_str,1);1020add_pending_sha1(&rev_info,"HEAD", our_tree,0);1021diff_setup_done(&rev_info.diffopt);1022run_diff_index(&rev_info,1);1023}10241025if(run_apply(state, index_path))1026returnerror(_("Did you hand edit your patch?\n"1027"It does not apply to blobs recorded in its index."));10281029if(write_index_as_tree(his_tree, &the_index, index_path,0, NULL))1030returnerror("could not write tree");10311032say(state, stdout,_("Falling back to patching base and 3-way merge..."));10331034discard_cache();1035read_cache();10361037/*1038 * This is not so wrong. Depending on which base we picked, orig_tree1039 * may be wildly different from ours, but his_tree has the same set of1040 * wildly different changes in parts the patch did not touch, so1041 * recursive ends up canceling them, saying that we reverted all those1042 * changes.1043 */10441045init_merge_options(&o);10461047 o.branch1 ="HEAD";1048 his_tree_name =xstrfmt("%.*s",linelen(state->msg), state->msg);1049 o.branch2 = his_tree_name;10501051if(state->quiet)1052 o.verbosity =0;10531054if(merge_recursive_generic(&o, our_tree, his_tree,1, bases, &result)) {1055free(his_tree_name);1056returnerror(_("Failed to merge in the changes."));1057}10581059free(his_tree_name);1060return0;1061}10621063/**1064 * Commits the current index with state->msg as the commit message and1065 * state->author_name, state->author_email and state->author_date as the author1066 * information.1067 */1068static voiddo_commit(const struct am_state *state)1069{1070unsigned char tree[GIT_SHA1_RAWSZ], parent[GIT_SHA1_RAWSZ],1071 commit[GIT_SHA1_RAWSZ];1072unsigned char*ptr;1073struct commit_list *parents = NULL;1074const char*reflog_msg, *author;1075struct strbuf sb = STRBUF_INIT;10761077if(write_cache_as_tree(tree,0, NULL))1078die(_("git write-tree failed to write a tree"));10791080if(!get_sha1_commit("HEAD", parent)) {1081 ptr = parent;1082commit_list_insert(lookup_commit(parent), &parents);1083}else{1084 ptr = NULL;1085say(state, stderr,_("applying to an empty history"));1086}10871088 author =fmt_ident(state->author_name, state->author_email,1089 state->author_date, IDENT_STRICT);10901091if(commit_tree(state->msg, state->msg_len, tree, parents, commit,1092 author, NULL))1093die(_("failed to write commit object"));10941095 reflog_msg =getenv("GIT_REFLOG_ACTION");1096if(!reflog_msg)1097 reflog_msg ="am";10981099strbuf_addf(&sb,"%s: %.*s", reflog_msg,linelen(state->msg),1100 state->msg);11011102update_ref(sb.buf,"HEAD", commit, ptr,0, UPDATE_REFS_DIE_ON_ERR);11031104strbuf_release(&sb);1105}11061107/**1108 * Validates the am_state for resuming -- the "msg" and authorship fields must1109 * be filled up.1110 */1111static voidvalidate_resume_state(const struct am_state *state)1112{1113if(!state->msg)1114die(_("cannot resume:%sdoes not exist."),1115am_path(state,"final-commit"));11161117if(!state->author_name || !state->author_email || !state->author_date)1118die(_("cannot resume:%sdoes not exist."),1119am_path(state,"author-script"));1120}11211122/**1123 * Applies all queued mail.1124 *1125 * If `resume` is true, we are "resuming". The "msg" and authorship fields, as1126 * well as the state directory's "patch" file is used as-is for applying the1127 * patch and committing it.1128 */1129static voidam_run(struct am_state *state,int resume)1130{1131const char*argv_gc_auto[] = {"gc","--auto", NULL};1132struct strbuf sb = STRBUF_INIT;11331134unlink(am_path(state,"dirtyindex"));11351136refresh_and_write_cache();11371138if(index_has_changes(&sb)) {1139write_file(am_path(state,"dirtyindex"),1,"t");1140die(_("Dirty index: cannot apply patches (dirty:%s)"), sb.buf);1141}11421143strbuf_release(&sb);11441145while(state->cur <= state->last) {1146const char*mail =am_path(state,msgnum(state));1147int apply_status;11481149if(!file_exists(mail))1150goto next;11511152if(resume) {1153validate_resume_state(state);1154 resume =0;1155}else{1156int skip;11571158if(state->rebasing)1159 skip =parse_mail_rebase(state, mail);1160else1161 skip =parse_mail(state, mail);11621163if(skip)1164goto next;/* mail should be skipped */11651166write_author_script(state);1167write_commit_msg(state);1168}11691170say(state, stdout,_("Applying: %.*s"),linelen(state->msg), state->msg);11711172 apply_status =run_apply(state, NULL);11731174if(apply_status && state->threeway) {1175struct strbuf sb = STRBUF_INIT;11761177strbuf_addstr(&sb,am_path(state,"patch-merge-index"));1178 apply_status =fall_back_threeway(state, sb.buf);1179strbuf_release(&sb);11801181/*1182 * Applying the patch to an earlier tree and merging1183 * the result may have produced the same tree as ours.1184 */1185if(!apply_status && !index_has_changes(NULL)) {1186say(state, stdout,_("No changes -- Patch already applied."));1187goto next;1188}1189}11901191if(apply_status) {1192int advice_amworkdir =1;11931194printf_ln(_("Patch failed at%s%.*s"),msgnum(state),1195linelen(state->msg), state->msg);11961197git_config_get_bool("advice.amworkdir", &advice_amworkdir);11981199if(advice_amworkdir)1200printf_ln(_("The copy of the patch that failed is found in:%s"),1201am_path(state,"patch"));12021203die_user_resolve(state);1204}12051206do_commit(state);12071208next:1209am_next(state);1210}12111212/*1213 * In rebasing mode, it's up to the caller to take care of1214 * housekeeping.1215 */1216if(!state->rebasing) {1217am_destroy(state);1218run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);1219}1220}12211222/**1223 * Resume the current am session after patch application failure. The user did1224 * all the hard work, and we do not have to do any patch application. Just1225 * trust and commit what the user has in the index and working tree.1226 */1227static voidam_resolve(struct am_state *state)1228{1229validate_resume_state(state);12301231say(state, stdout,_("Applying: %.*s"),linelen(state->msg), state->msg);12321233if(!index_has_changes(NULL)) {1234printf_ln(_("No changes - did you forget to use 'git add'?\n"1235"If there is nothing left to stage, chances are that something else\n"1236"already introduced the same changes; you might want to skip this patch."));1237die_user_resolve(state);1238}12391240if(unmerged_cache()) {1241printf_ln(_("You still have unmerged paths in your index.\n"1242"Did you forget to use 'git add'?"));1243die_user_resolve(state);1244}12451246do_commit(state);12471248am_next(state);1249am_run(state,0);1250}12511252/**1253 * Performs a checkout fast-forward from `head` to `remote`. If `reset` is1254 * true, any unmerged entries will be discarded. Returns 0 on success, -1 on1255 * failure.1256 */1257static intfast_forward_to(struct tree *head,struct tree *remote,int reset)1258{1259struct lock_file *lock_file;1260struct unpack_trees_options opts;1261struct tree_desc t[2];12621263if(parse_tree(head) ||parse_tree(remote))1264return-1;12651266 lock_file =xcalloc(1,sizeof(struct lock_file));1267hold_locked_index(lock_file,1);12681269refresh_cache(REFRESH_QUIET);12701271memset(&opts,0,sizeof(opts));1272 opts.head_idx =1;1273 opts.src_index = &the_index;1274 opts.dst_index = &the_index;1275 opts.update =1;1276 opts.merge =1;1277 opts.reset = reset;1278 opts.fn = twoway_merge;1279init_tree_desc(&t[0], head->buffer, head->size);1280init_tree_desc(&t[1], remote->buffer, remote->size);12811282if(unpack_trees(2, t, &opts)) {1283rollback_lock_file(lock_file);1284return-1;1285}12861287if(write_locked_index(&the_index, lock_file, COMMIT_LOCK))1288die(_("unable to write new index file"));12891290return0;1291}12921293/**1294 * Clean the index without touching entries that are not modified between1295 * `head` and `remote`.1296 */1297static intclean_index(const unsigned char*head,const unsigned char*remote)1298{1299struct lock_file *lock_file;1300struct tree *head_tree, *remote_tree, *index_tree;1301unsigned char index[GIT_SHA1_RAWSZ];1302struct pathspec pathspec;13031304 head_tree =parse_tree_indirect(head);1305if(!head_tree)1306returnerror(_("Could not parse object '%s'."),sha1_to_hex(head));13071308 remote_tree =parse_tree_indirect(remote);1309if(!remote_tree)1310returnerror(_("Could not parse object '%s'."),sha1_to_hex(remote));13111312read_cache_unmerged();13131314if(fast_forward_to(head_tree, head_tree,1))1315return-1;13161317if(write_cache_as_tree(index,0, NULL))1318return-1;13191320 index_tree =parse_tree_indirect(index);1321if(!index_tree)1322returnerror(_("Could not parse object '%s'."),sha1_to_hex(index));13231324if(fast_forward_to(index_tree, remote_tree,0))1325return-1;13261327memset(&pathspec,0,sizeof(pathspec));13281329 lock_file =xcalloc(1,sizeof(struct lock_file));1330hold_locked_index(lock_file,1);13311332if(read_tree(remote_tree,0, &pathspec)) {1333rollback_lock_file(lock_file);1334return-1;1335}13361337if(write_locked_index(&the_index, lock_file, COMMIT_LOCK))1338die(_("unable to write new index file"));13391340remove_branch_state();13411342return0;1343}13441345/**1346 * Resume the current am session by skipping the current patch.1347 */1348static voidam_skip(struct am_state *state)1349{1350unsigned char head[GIT_SHA1_RAWSZ];13511352if(get_sha1("HEAD", head))1353hashcpy(head, EMPTY_TREE_SHA1_BIN);13541355if(clean_index(head, head))1356die(_("failed to clean index"));13571358am_next(state);1359am_run(state,0);1360}13611362/**1363 * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.1364 *1365 * It is not safe to reset HEAD when:1366 * 1. git-am previously failed because the index was dirty.1367 * 2. HEAD has moved since git-am previously failed.1368 */1369static intsafe_to_abort(const struct am_state *state)1370{1371struct strbuf sb = STRBUF_INIT;1372unsigned char abort_safety[GIT_SHA1_RAWSZ], head[GIT_SHA1_RAWSZ];13731374if(file_exists(am_path(state,"dirtyindex")))1375return0;13761377if(read_state_file(&sb, state,"abort-safety",1) >0) {1378if(get_sha1_hex(sb.buf, abort_safety))1379die(_("could not parse%s"),am_path(state,"abort_safety"));1380}else1381hashclr(abort_safety);13821383if(get_sha1("HEAD", head))1384hashclr(head);13851386if(!hashcmp(head, abort_safety))1387return1;13881389error(_("You seem to have moved HEAD since the last 'am' failure.\n"1390"Not rewinding to ORIG_HEAD"));13911392return0;1393}13941395/**1396 * Aborts the current am session if it is safe to do so.1397 */1398static voidam_abort(struct am_state *state)1399{1400unsigned char curr_head[GIT_SHA1_RAWSZ], orig_head[GIT_SHA1_RAWSZ];1401int has_curr_head, has_orig_head;1402char*curr_branch;14031404if(!safe_to_abort(state)) {1405am_destroy(state);1406return;1407}14081409 curr_branch =resolve_refdup("HEAD",0, curr_head, NULL);1410 has_curr_head = !is_null_sha1(curr_head);1411if(!has_curr_head)1412hashcpy(curr_head, EMPTY_TREE_SHA1_BIN);14131414 has_orig_head = !get_sha1("ORIG_HEAD", orig_head);1415if(!has_orig_head)1416hashcpy(orig_head, EMPTY_TREE_SHA1_BIN);14171418clean_index(curr_head, orig_head);14191420if(has_orig_head)1421update_ref("am --abort","HEAD", orig_head,1422 has_curr_head ? curr_head : NULL,0,1423 UPDATE_REFS_DIE_ON_ERR);1424else if(curr_branch)1425delete_ref(curr_branch, NULL, REF_NODEREF);14261427free(curr_branch);1428am_destroy(state);1429}14301431/**1432 * parse_options() callback that validates and sets opt->value to the1433 * PATCH_FORMAT_* enum value corresponding to `arg`.1434 */1435static intparse_opt_patchformat(const struct option *opt,const char*arg,int unset)1436{1437int*opt_value = opt->value;14381439if(!strcmp(arg,"mbox"))1440*opt_value = PATCH_FORMAT_MBOX;1441else1442returnerror(_("Invalid value for --patch-format:%s"), arg);1443return0;1444}14451446enum resume_mode {1447 RESUME_FALSE =0,1448 RESUME_APPLY,1449 RESUME_RESOLVED,1450 RESUME_SKIP,1451 RESUME_ABORT1452};14531454intcmd_am(int argc,const char**argv,const char*prefix)1455{1456struct am_state state;1457int patch_format = PATCH_FORMAT_UNKNOWN;1458enum resume_mode resume = RESUME_FALSE;14591460const char*const usage[] = {1461N_("git am [options] [(<mbox>|<Maildir>)...]"),1462N_("git am [options] (--continue | --skip | --abort)"),1463 NULL1464};14651466struct option options[] = {1467OPT_BOOL('3',"3way", &state.threeway,1468N_("allow fall back on 3way merging if needed")),1469OPT__QUIET(&state.quiet,N_("be quiet")),1470OPT_BOOL('s',"signoff", &state.signoff,1471N_("add a Signed-off-by line to the commit message")),1472OPT_BOOL('u',"utf8", &state.utf8,1473N_("recode into utf8 (default)")),1474OPT_CALLBACK(0,"patch-format", &patch_format,N_("format"),1475N_("format the patch(es) are in"),1476 parse_opt_patchformat),1477OPT_STRING(0,"resolvemsg", &state.resolvemsg, NULL,1478N_("override error message when patch failure occurs")),1479OPT_CMDMODE(0,"continue", &resume,1480N_("continue applying patches after resolving a conflict"),1481 RESUME_RESOLVED),1482OPT_CMDMODE('r',"resolved", &resume,1483N_("synonyms for --continue"),1484 RESUME_RESOLVED),1485OPT_CMDMODE(0,"skip", &resume,1486N_("skip the current patch"),1487 RESUME_SKIP),1488OPT_CMDMODE(0,"abort", &resume,1489N_("restore the original branch and abort the patching operation."),1490 RESUME_ABORT),1491OPT_HIDDEN_BOOL(0,"rebasing", &state.rebasing,1492N_("(internal use for git-rebase)")),1493OPT_END()1494};14951496/*1497 * NEEDSWORK: Once all the features of git-am.sh have been1498 * re-implemented in builtin/am.c, this preamble can be removed.1499 */1500if(!getenv("_GIT_USE_BUILTIN_AM")) {1501const char*path =mkpath("%s/git-am",git_exec_path());15021503if(sane_execvp(path, (char**)argv) <0)1504die_errno("could not exec%s", path);1505}else{1506 prefix =setup_git_directory();1507trace_repo_setup(prefix);1508setup_work_tree();1509}15101511git_config(git_default_config, NULL);15121513am_state_init(&state,git_path("rebase-apply"));15141515 argc =parse_options(argc, argv, prefix, options, usage,0);15161517if(read_index_preload(&the_index, NULL) <0)1518die(_("failed to read the index"));15191520if(am_in_progress(&state)) {1521/*1522 * Catch user error to feed us patches when there is a session1523 * in progress:1524 *1525 * 1. mbox path(s) are provided on the command-line.1526 * 2. stdin is not a tty: the user is trying to feed us a patch1527 * from standard input. This is somewhat unreliable -- stdin1528 * could be /dev/null for example and the caller did not1529 * intend to feed us a patch but wanted to continue1530 * unattended.1531 */1532if(argc || (resume == RESUME_FALSE && !isatty(0)))1533die(_("previous rebase directory%sstill exists but mbox given."),1534 state.dir);15351536if(resume == RESUME_FALSE)1537 resume = RESUME_APPLY;15381539am_load(&state);1540}else{1541struct argv_array paths = ARGV_ARRAY_INIT;1542int i;15431544/*1545 * Handle stray state directory in the independent-run case. In1546 * the --rebasing case, it is up to the caller to take care of1547 * stray directories.1548 */1549if(file_exists(state.dir) && !state.rebasing) {1550if(resume == RESUME_ABORT) {1551am_destroy(&state);1552am_state_release(&state);1553return0;1554}15551556die(_("Stray%sdirectory found.\n"1557"Use\"git am --abort\"to remove it."),1558 state.dir);1559}15601561if(resume)1562die(_("Resolve operation not in progress, we are not resuming."));15631564for(i =0; i < argc; i++) {1565if(is_absolute_path(argv[i]) || !prefix)1566argv_array_push(&paths, argv[i]);1567else1568argv_array_push(&paths,mkpath("%s/%s", prefix, argv[i]));1569}15701571am_setup(&state, patch_format, paths.argv);15721573argv_array_clear(&paths);1574}15751576switch(resume) {1577case RESUME_FALSE:1578am_run(&state,0);1579break;1580case RESUME_APPLY:1581am_run(&state,1);1582break;1583case RESUME_RESOLVED:1584am_resolve(&state);1585break;1586case RESUME_SKIP:1587am_skip(&state);1588break;1589case RESUME_ABORT:1590am_abort(&state);1591break;1592default:1593die("BUG: invalid resume value");1594}15951596am_state_release(&state);15971598return0;1599}