am.c 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438
  1. /*
  2. * Builtin "git am"
  3. *
  4. * Based on git-am.sh by Junio C Hamano.
  5. */
  6. #define USE_THE_INDEX_COMPATIBILITY_MACROS
  7. #include "cache.h"
  8. #include "config.h"
  9. #include "builtin.h"
  10. #include "exec-cmd.h"
  11. #include "parse-options.h"
  12. #include "dir.h"
  13. #include "run-command.h"
  14. #include "quote.h"
  15. #include "tempfile.h"
  16. #include "lockfile.h"
  17. #include "cache-tree.h"
  18. #include "refs.h"
  19. #include "commit.h"
  20. #include "diff.h"
  21. #include "diffcore.h"
  22. #include "unpack-trees.h"
  23. #include "branch.h"
  24. #include "sequencer.h"
  25. #include "revision.h"
  26. #include "merge-recursive.h"
  27. #include "log-tree.h"
  28. #include "notes-utils.h"
  29. #include "rerere.h"
  30. #include "prompt.h"
  31. #include "mailinfo.h"
  32. #include "apply.h"
  33. #include "string-list.h"
  34. #include "packfile.h"
  35. #include "repository.h"
  36. /**
  37. * Returns the length of the first line of msg.
  38. */
  39. static int linelen(const char *msg)
  40. {
  41. return strchrnul(msg, '\n') - msg;
  42. }
  43. /**
  44. * Returns true if `str` consists of only whitespace, false otherwise.
  45. */
  46. static int str_isspace(const char *str)
  47. {
  48. for (; *str; str++)
  49. if (!isspace(*str))
  50. return 0;
  51. return 1;
  52. }
  53. enum patch_format {
  54. PATCH_FORMAT_UNKNOWN = 0,
  55. PATCH_FORMAT_MBOX,
  56. PATCH_FORMAT_STGIT,
  57. PATCH_FORMAT_STGIT_SERIES,
  58. PATCH_FORMAT_HG,
  59. PATCH_FORMAT_MBOXRD
  60. };
  61. enum keep_type {
  62. KEEP_FALSE = 0,
  63. KEEP_TRUE, /* pass -k flag to git-mailinfo */
  64. KEEP_NON_PATCH /* pass -b flag to git-mailinfo */
  65. };
  66. enum scissors_type {
  67. SCISSORS_UNSET = -1,
  68. SCISSORS_FALSE = 0, /* pass --no-scissors to git-mailinfo */
  69. SCISSORS_TRUE /* pass --scissors to git-mailinfo */
  70. };
  71. enum signoff_type {
  72. SIGNOFF_FALSE = 0,
  73. SIGNOFF_TRUE = 1,
  74. SIGNOFF_EXPLICIT /* --signoff was set on the command-line */
  75. };
  76. enum show_patch_type {
  77. SHOW_PATCH_RAW = 0,
  78. SHOW_PATCH_DIFF = 1,
  79. };
  80. struct am_state {
  81. /* state directory path */
  82. char *dir;
  83. /* current and last patch numbers, 1-indexed */
  84. int cur;
  85. int last;
  86. /* commit metadata and message */
  87. char *author_name;
  88. char *author_email;
  89. char *author_date;
  90. char *committer_name;
  91. char *committer_email;
  92. char *msg;
  93. size_t msg_len;
  94. /* when --rebasing, records the original commit the patch came from */
  95. struct object_id orig_commit;
  96. /* number of digits in patch filename */
  97. int prec;
  98. /* various operating modes and command line options */
  99. int interactive;
  100. int threeway;
  101. int quiet;
  102. int signoff; /* enum signoff_type */
  103. int utf8;
  104. int keep; /* enum keep_type */
  105. int message_id;
  106. int scissors; /* enum scissors_type */
  107. struct strvec git_apply_opts;
  108. const char *resolvemsg;
  109. int committer_date_is_author_date;
  110. int ignore_date;
  111. int allow_rerere_autoupdate;
  112. const char *sign_commit;
  113. int rebasing;
  114. };
  115. /**
  116. * Initializes am_state with the default values.
  117. */
  118. static void am_state_init(struct am_state *state)
  119. {
  120. const char *committer;
  121. struct ident_split id;
  122. int gpgsign;
  123. memset(state, 0, sizeof(*state));
  124. state->dir = git_pathdup("rebase-apply");
  125. state->prec = 4;
  126. git_config_get_bool("am.threeway", &state->threeway);
  127. state->utf8 = 1;
  128. git_config_get_bool("am.messageid", &state->message_id);
  129. state->scissors = SCISSORS_UNSET;
  130. strvec_init(&state->git_apply_opts);
  131. if (!git_config_get_bool("commit.gpgsign", &gpgsign))
  132. state->sign_commit = gpgsign ? "" : NULL;
  133. committer = git_committer_info(IDENT_STRICT);
  134. if (split_ident_line(&id, committer, strlen(committer)) < 0)
  135. die(_("invalid committer: %s"), committer);
  136. state->committer_name =
  137. xmemdupz(id.name_begin, id.name_end - id.name_begin);
  138. state->committer_email =
  139. xmemdupz(id.mail_begin, id.mail_end - id.mail_end);
  140. }
  141. /**
  142. * Releases memory allocated by an am_state.
  143. */
  144. static void am_state_release(struct am_state *state)
  145. {
  146. free(state->dir);
  147. free(state->author_name);
  148. free(state->author_email);
  149. free(state->author_date);
  150. free(state->committer_name);
  151. free(state->committer_email);
  152. free(state->msg);
  153. strvec_clear(&state->git_apply_opts);
  154. }
  155. /**
  156. * Returns path relative to the am_state directory.
  157. */
  158. static inline const char *am_path(const struct am_state *state, const char *path)
  159. {
  160. return mkpath("%s/%s", state->dir, path);
  161. }
  162. /**
  163. * For convenience to call write_file()
  164. */
  165. static void write_state_text(const struct am_state *state,
  166. const char *name, const char *string)
  167. {
  168. write_file(am_path(state, name), "%s", string);
  169. }
  170. static void write_state_count(const struct am_state *state,
  171. const char *name, int value)
  172. {
  173. write_file(am_path(state, name), "%d", value);
  174. }
  175. static void write_state_bool(const struct am_state *state,
  176. const char *name, int value)
  177. {
  178. write_state_text(state, name, value ? "t" : "f");
  179. }
  180. /**
  181. * If state->quiet is false, calls fprintf(fp, fmt, ...), and appends a newline
  182. * at the end.
  183. */
  184. static void say(const struct am_state *state, FILE *fp, const char *fmt, ...)
  185. {
  186. va_list ap;
  187. va_start(ap, fmt);
  188. if (!state->quiet) {
  189. vfprintf(fp, fmt, ap);
  190. putc('\n', fp);
  191. }
  192. va_end(ap);
  193. }
  194. /**
  195. * Returns 1 if there is an am session in progress, 0 otherwise.
  196. */
  197. static int am_in_progress(const struct am_state *state)
  198. {
  199. struct stat st;
  200. if (lstat(state->dir, &st) < 0 || !S_ISDIR(st.st_mode))
  201. return 0;
  202. if (lstat(am_path(state, "last"), &st) || !S_ISREG(st.st_mode))
  203. return 0;
  204. if (lstat(am_path(state, "next"), &st) || !S_ISREG(st.st_mode))
  205. return 0;
  206. return 1;
  207. }
  208. /**
  209. * Reads the contents of `file` in the `state` directory into `sb`. Returns the
  210. * number of bytes read on success, -1 if the file does not exist. If `trim` is
  211. * set, trailing whitespace will be removed.
  212. */
  213. static int read_state_file(struct strbuf *sb, const struct am_state *state,
  214. const char *file, int trim)
  215. {
  216. strbuf_reset(sb);
  217. if (strbuf_read_file(sb, am_path(state, file), 0) >= 0) {
  218. if (trim)
  219. strbuf_trim(sb);
  220. return sb->len;
  221. }
  222. if (errno == ENOENT)
  223. return -1;
  224. die_errno(_("could not read '%s'"), am_path(state, file));
  225. }
  226. /**
  227. * Reads and parses the state directory's "author-script" file, and sets
  228. * state->author_name, state->author_email and state->author_date accordingly.
  229. * Returns 0 on success, -1 if the file could not be parsed.
  230. *
  231. * The author script is of the format:
  232. *
  233. * GIT_AUTHOR_NAME='$author_name'
  234. * GIT_AUTHOR_EMAIL='$author_email'
  235. * GIT_AUTHOR_DATE='$author_date'
  236. *
  237. * where $author_name, $author_email and $author_date are quoted. We are strict
  238. * with our parsing, as the file was meant to be eval'd in the old git-am.sh
  239. * script, and thus if the file differs from what this function expects, it is
  240. * better to bail out than to do something that the user does not expect.
  241. */
  242. static int read_am_author_script(struct am_state *state)
  243. {
  244. const char *filename = am_path(state, "author-script");
  245. assert(!state->author_name);
  246. assert(!state->author_email);
  247. assert(!state->author_date);
  248. return read_author_script(filename, &state->author_name,
  249. &state->author_email, &state->author_date, 1);
  250. }
  251. /**
  252. * Saves state->author_name, state->author_email and state->author_date in the
  253. * state directory's "author-script" file.
  254. */
  255. static void write_author_script(const struct am_state *state)
  256. {
  257. struct strbuf sb = STRBUF_INIT;
  258. strbuf_addstr(&sb, "GIT_AUTHOR_NAME=");
  259. sq_quote_buf(&sb, state->author_name);
  260. strbuf_addch(&sb, '\n');
  261. strbuf_addstr(&sb, "GIT_AUTHOR_EMAIL=");
  262. sq_quote_buf(&sb, state->author_email);
  263. strbuf_addch(&sb, '\n');
  264. strbuf_addstr(&sb, "GIT_AUTHOR_DATE=");
  265. sq_quote_buf(&sb, state->author_date);
  266. strbuf_addch(&sb, '\n');
  267. write_state_text(state, "author-script", sb.buf);
  268. strbuf_release(&sb);
  269. }
  270. /**
  271. * Reads the commit message from the state directory's "final-commit" file,
  272. * setting state->msg to its contents and state->msg_len to the length of its
  273. * contents in bytes.
  274. *
  275. * Returns 0 on success, -1 if the file does not exist.
  276. */
  277. static int read_commit_msg(struct am_state *state)
  278. {
  279. struct strbuf sb = STRBUF_INIT;
  280. assert(!state->msg);
  281. if (read_state_file(&sb, state, "final-commit", 0) < 0) {
  282. strbuf_release(&sb);
  283. return -1;
  284. }
  285. state->msg = strbuf_detach(&sb, &state->msg_len);
  286. return 0;
  287. }
  288. /**
  289. * Saves state->msg in the state directory's "final-commit" file.
  290. */
  291. static void write_commit_msg(const struct am_state *state)
  292. {
  293. const char *filename = am_path(state, "final-commit");
  294. write_file_buf(filename, state->msg, state->msg_len);
  295. }
  296. /**
  297. * Loads state from disk.
  298. */
  299. static void am_load(struct am_state *state)
  300. {
  301. struct strbuf sb = STRBUF_INIT;
  302. if (read_state_file(&sb, state, "next", 1) < 0)
  303. BUG("state file 'next' does not exist");
  304. state->cur = strtol(sb.buf, NULL, 10);
  305. if (read_state_file(&sb, state, "last", 1) < 0)
  306. BUG("state file 'last' does not exist");
  307. state->last = strtol(sb.buf, NULL, 10);
  308. if (read_am_author_script(state) < 0)
  309. die(_("could not parse author script"));
  310. read_commit_msg(state);
  311. if (read_state_file(&sb, state, "original-commit", 1) < 0)
  312. oidclr(&state->orig_commit);
  313. else if (get_oid_hex(sb.buf, &state->orig_commit) < 0)
  314. die(_("could not parse %s"), am_path(state, "original-commit"));
  315. read_state_file(&sb, state, "threeway", 1);
  316. state->threeway = !strcmp(sb.buf, "t");
  317. read_state_file(&sb, state, "quiet", 1);
  318. state->quiet = !strcmp(sb.buf, "t");
  319. read_state_file(&sb, state, "sign", 1);
  320. state->signoff = !strcmp(sb.buf, "t");
  321. read_state_file(&sb, state, "utf8", 1);
  322. state->utf8 = !strcmp(sb.buf, "t");
  323. if (file_exists(am_path(state, "rerere-autoupdate"))) {
  324. read_state_file(&sb, state, "rerere-autoupdate", 1);
  325. state->allow_rerere_autoupdate = strcmp(sb.buf, "t") ?
  326. RERERE_NOAUTOUPDATE : RERERE_AUTOUPDATE;
  327. } else {
  328. state->allow_rerere_autoupdate = 0;
  329. }
  330. read_state_file(&sb, state, "keep", 1);
  331. if (!strcmp(sb.buf, "t"))
  332. state->keep = KEEP_TRUE;
  333. else if (!strcmp(sb.buf, "b"))
  334. state->keep = KEEP_NON_PATCH;
  335. else
  336. state->keep = KEEP_FALSE;
  337. read_state_file(&sb, state, "messageid", 1);
  338. state->message_id = !strcmp(sb.buf, "t");
  339. read_state_file(&sb, state, "scissors", 1);
  340. if (!strcmp(sb.buf, "t"))
  341. state->scissors = SCISSORS_TRUE;
  342. else if (!strcmp(sb.buf, "f"))
  343. state->scissors = SCISSORS_FALSE;
  344. else
  345. state->scissors = SCISSORS_UNSET;
  346. read_state_file(&sb, state, "apply-opt", 1);
  347. strvec_clear(&state->git_apply_opts);
  348. if (sq_dequote_to_strvec(sb.buf, &state->git_apply_opts) < 0)
  349. die(_("could not parse %s"), am_path(state, "apply-opt"));
  350. state->rebasing = !!file_exists(am_path(state, "rebasing"));
  351. strbuf_release(&sb);
  352. }
  353. /**
  354. * Removes the am_state directory, forcefully terminating the current am
  355. * session.
  356. */
  357. static void am_destroy(const struct am_state *state)
  358. {
  359. struct strbuf sb = STRBUF_INIT;
  360. strbuf_addstr(&sb, state->dir);
  361. remove_dir_recursively(&sb, 0);
  362. strbuf_release(&sb);
  363. }
  364. /**
  365. * Runs applypatch-msg hook. Returns its exit code.
  366. */
  367. static int run_applypatch_msg_hook(struct am_state *state)
  368. {
  369. int ret;
  370. assert(state->msg);
  371. ret = run_hook_le(NULL, "applypatch-msg", am_path(state, "final-commit"), NULL);
  372. if (!ret) {
  373. FREE_AND_NULL(state->msg);
  374. if (read_commit_msg(state) < 0)
  375. die(_("'%s' was deleted by the applypatch-msg hook"),
  376. am_path(state, "final-commit"));
  377. }
  378. return ret;
  379. }
  380. /**
  381. * Runs post-rewrite hook. Returns it exit code.
  382. */
  383. static int run_post_rewrite_hook(const struct am_state *state)
  384. {
  385. struct child_process cp = CHILD_PROCESS_INIT;
  386. const char *hook = find_hook("post-rewrite");
  387. int ret;
  388. if (!hook)
  389. return 0;
  390. strvec_push(&cp.args, hook);
  391. strvec_push(&cp.args, "rebase");
  392. cp.in = xopen(am_path(state, "rewritten"), O_RDONLY);
  393. cp.stdout_to_stderr = 1;
  394. cp.trace2_hook_name = "post-rewrite";
  395. ret = run_command(&cp);
  396. close(cp.in);
  397. return ret;
  398. }
  399. /**
  400. * Reads the state directory's "rewritten" file, and copies notes from the old
  401. * commits listed in the file to their rewritten commits.
  402. *
  403. * Returns 0 on success, -1 on failure.
  404. */
  405. static int copy_notes_for_rebase(const struct am_state *state)
  406. {
  407. struct notes_rewrite_cfg *c;
  408. struct strbuf sb = STRBUF_INIT;
  409. const char *invalid_line = _("Malformed input line: '%s'.");
  410. const char *msg = "Notes added by 'git rebase'";
  411. FILE *fp;
  412. int ret = 0;
  413. assert(state->rebasing);
  414. c = init_copy_notes_for_rewrite("rebase");
  415. if (!c)
  416. return 0;
  417. fp = xfopen(am_path(state, "rewritten"), "r");
  418. while (!strbuf_getline_lf(&sb, fp)) {
  419. struct object_id from_obj, to_obj;
  420. const char *p;
  421. if (sb.len != the_hash_algo->hexsz * 2 + 1) {
  422. ret = error(invalid_line, sb.buf);
  423. goto finish;
  424. }
  425. if (parse_oid_hex(sb.buf, &from_obj, &p)) {
  426. ret = error(invalid_line, sb.buf);
  427. goto finish;
  428. }
  429. if (*p != ' ') {
  430. ret = error(invalid_line, sb.buf);
  431. goto finish;
  432. }
  433. if (get_oid_hex(p + 1, &to_obj)) {
  434. ret = error(invalid_line, sb.buf);
  435. goto finish;
  436. }
  437. if (copy_note_for_rewrite(c, &from_obj, &to_obj))
  438. ret = error(_("Failed to copy notes from '%s' to '%s'"),
  439. oid_to_hex(&from_obj), oid_to_hex(&to_obj));
  440. }
  441. finish:
  442. finish_copy_notes_for_rewrite(the_repository, c, msg);
  443. fclose(fp);
  444. strbuf_release(&sb);
  445. return ret;
  446. }
  447. /**
  448. * Determines if the file looks like a piece of RFC2822 mail by grabbing all
  449. * non-indented lines and checking if they look like they begin with valid
  450. * header field names.
  451. *
  452. * Returns 1 if the file looks like a piece of mail, 0 otherwise.
  453. */
  454. static int is_mail(FILE *fp)
  455. {
  456. const char *header_regex = "^[!-9;-~]+:";
  457. struct strbuf sb = STRBUF_INIT;
  458. regex_t regex;
  459. int ret = 1;
  460. if (fseek(fp, 0L, SEEK_SET))
  461. die_errno(_("fseek failed"));
  462. if (regcomp(&regex, header_regex, REG_NOSUB | REG_EXTENDED))
  463. die("invalid pattern: %s", header_regex);
  464. while (!strbuf_getline(&sb, fp)) {
  465. if (!sb.len)
  466. break; /* End of header */
  467. /* Ignore indented folded lines */
  468. if (*sb.buf == '\t' || *sb.buf == ' ')
  469. continue;
  470. /* It's a header if it matches header_regex */
  471. if (regexec(&regex, sb.buf, 0, NULL, 0)) {
  472. ret = 0;
  473. goto done;
  474. }
  475. }
  476. done:
  477. regfree(&regex);
  478. strbuf_release(&sb);
  479. return ret;
  480. }
  481. /**
  482. * Attempts to detect the patch_format of the patches contained in `paths`,
  483. * returning the PATCH_FORMAT_* enum value. Returns PATCH_FORMAT_UNKNOWN if
  484. * detection fails.
  485. */
  486. static int detect_patch_format(const char **paths)
  487. {
  488. enum patch_format ret = PATCH_FORMAT_UNKNOWN;
  489. struct strbuf l1 = STRBUF_INIT;
  490. struct strbuf l2 = STRBUF_INIT;
  491. struct strbuf l3 = STRBUF_INIT;
  492. FILE *fp;
  493. /*
  494. * We default to mbox format if input is from stdin and for directories
  495. */
  496. if (!*paths || !strcmp(*paths, "-") || is_directory(*paths))
  497. return PATCH_FORMAT_MBOX;
  498. /*
  499. * Otherwise, check the first few lines of the first patch, starting
  500. * from the first non-blank line, to try to detect its format.
  501. */
  502. fp = xfopen(*paths, "r");
  503. while (!strbuf_getline(&l1, fp)) {
  504. if (l1.len)
  505. break;
  506. }
  507. if (starts_with(l1.buf, "From ") || starts_with(l1.buf, "From: ")) {
  508. ret = PATCH_FORMAT_MBOX;
  509. goto done;
  510. }
  511. if (starts_with(l1.buf, "# This series applies on GIT commit")) {
  512. ret = PATCH_FORMAT_STGIT_SERIES;
  513. goto done;
  514. }
  515. if (!strcmp(l1.buf, "# HG changeset patch")) {
  516. ret = PATCH_FORMAT_HG;
  517. goto done;
  518. }
  519. strbuf_getline(&l2, fp);
  520. strbuf_getline(&l3, fp);
  521. /*
  522. * If the second line is empty and the third is a From, Author or Date
  523. * entry, this is likely an StGit patch.
  524. */
  525. if (l1.len && !l2.len &&
  526. (starts_with(l3.buf, "From:") ||
  527. starts_with(l3.buf, "Author:") ||
  528. starts_with(l3.buf, "Date:"))) {
  529. ret = PATCH_FORMAT_STGIT;
  530. goto done;
  531. }
  532. if (l1.len && is_mail(fp)) {
  533. ret = PATCH_FORMAT_MBOX;
  534. goto done;
  535. }
  536. done:
  537. fclose(fp);
  538. strbuf_release(&l1);
  539. strbuf_release(&l2);
  540. strbuf_release(&l3);
  541. return ret;
  542. }
  543. /**
  544. * Splits out individual email patches from `paths`, where each path is either
  545. * a mbox file or a Maildir. Returns 0 on success, -1 on failure.
  546. */
  547. static int split_mail_mbox(struct am_state *state, const char **paths,
  548. int keep_cr, int mboxrd)
  549. {
  550. struct child_process cp = CHILD_PROCESS_INIT;
  551. struct strbuf last = STRBUF_INIT;
  552. int ret;
  553. cp.git_cmd = 1;
  554. strvec_push(&cp.args, "mailsplit");
  555. strvec_pushf(&cp.args, "-d%d", state->prec);
  556. strvec_pushf(&cp.args, "-o%s", state->dir);
  557. strvec_push(&cp.args, "-b");
  558. if (keep_cr)
  559. strvec_push(&cp.args, "--keep-cr");
  560. if (mboxrd)
  561. strvec_push(&cp.args, "--mboxrd");
  562. strvec_push(&cp.args, "--");
  563. strvec_pushv(&cp.args, paths);
  564. ret = capture_command(&cp, &last, 8);
  565. if (ret)
  566. goto exit;
  567. state->cur = 1;
  568. state->last = strtol(last.buf, NULL, 10);
  569. exit:
  570. strbuf_release(&last);
  571. return ret ? -1 : 0;
  572. }
  573. /**
  574. * Callback signature for split_mail_conv(). The foreign patch should be
  575. * read from `in`, and the converted patch (in RFC2822 mail format) should be
  576. * written to `out`. Return 0 on success, or -1 on failure.
  577. */
  578. typedef int (*mail_conv_fn)(FILE *out, FILE *in, int keep_cr);
  579. /**
  580. * Calls `fn` for each file in `paths` to convert the foreign patch to the
  581. * RFC2822 mail format suitable for parsing with git-mailinfo.
  582. *
  583. * Returns 0 on success, -1 on failure.
  584. */
  585. static int split_mail_conv(mail_conv_fn fn, struct am_state *state,
  586. const char **paths, int keep_cr)
  587. {
  588. static const char *stdin_only[] = {"-", NULL};
  589. int i;
  590. if (!*paths)
  591. paths = stdin_only;
  592. for (i = 0; *paths; paths++, i++) {
  593. FILE *in, *out;
  594. const char *mail;
  595. int ret;
  596. if (!strcmp(*paths, "-"))
  597. in = stdin;
  598. else
  599. in = fopen(*paths, "r");
  600. if (!in)
  601. return error_errno(_("could not open '%s' for reading"),
  602. *paths);
  603. mail = mkpath("%s/%0*d", state->dir, state->prec, i + 1);
  604. out = fopen(mail, "w");
  605. if (!out) {
  606. if (in != stdin)
  607. fclose(in);
  608. return error_errno(_("could not open '%s' for writing"),
  609. mail);
  610. }
  611. ret = fn(out, in, keep_cr);
  612. fclose(out);
  613. if (in != stdin)
  614. fclose(in);
  615. if (ret)
  616. return error(_("could not parse patch '%s'"), *paths);
  617. }
  618. state->cur = 1;
  619. state->last = i;
  620. return 0;
  621. }
  622. /**
  623. * A split_mail_conv() callback that converts an StGit patch to an RFC2822
  624. * message suitable for parsing with git-mailinfo.
  625. */
  626. static int stgit_patch_to_mail(FILE *out, FILE *in, int keep_cr)
  627. {
  628. struct strbuf sb = STRBUF_INIT;
  629. int subject_printed = 0;
  630. while (!strbuf_getline_lf(&sb, in)) {
  631. const char *str;
  632. if (str_isspace(sb.buf))
  633. continue;
  634. else if (skip_prefix(sb.buf, "Author:", &str))
  635. fprintf(out, "From:%s\n", str);
  636. else if (starts_with(sb.buf, "From") || starts_with(sb.buf, "Date"))
  637. fprintf(out, "%s\n", sb.buf);
  638. else if (!subject_printed) {
  639. fprintf(out, "Subject: %s\n", sb.buf);
  640. subject_printed = 1;
  641. } else {
  642. fprintf(out, "\n%s\n", sb.buf);
  643. break;
  644. }
  645. }
  646. strbuf_reset(&sb);
  647. while (strbuf_fread(&sb, 8192, in) > 0) {
  648. fwrite(sb.buf, 1, sb.len, out);
  649. strbuf_reset(&sb);
  650. }
  651. strbuf_release(&sb);
  652. return 0;
  653. }
  654. /**
  655. * This function only supports a single StGit series file in `paths`.
  656. *
  657. * Given an StGit series file, converts the StGit patches in the series into
  658. * RFC2822 messages suitable for parsing with git-mailinfo, and queues them in
  659. * the state directory.
  660. *
  661. * Returns 0 on success, -1 on failure.
  662. */
  663. static int split_mail_stgit_series(struct am_state *state, const char **paths,
  664. int keep_cr)
  665. {
  666. const char *series_dir;
  667. char *series_dir_buf;
  668. FILE *fp;
  669. struct strvec patches = STRVEC_INIT;
  670. struct strbuf sb = STRBUF_INIT;
  671. int ret;
  672. if (!paths[0] || paths[1])
  673. return error(_("Only one StGIT patch series can be applied at once"));
  674. series_dir_buf = xstrdup(*paths);
  675. series_dir = dirname(series_dir_buf);
  676. fp = fopen(*paths, "r");
  677. if (!fp)
  678. return error_errno(_("could not open '%s' for reading"), *paths);
  679. while (!strbuf_getline_lf(&sb, fp)) {
  680. if (*sb.buf == '#')
  681. continue; /* skip comment lines */
  682. strvec_push(&patches, mkpath("%s/%s", series_dir, sb.buf));
  683. }
  684. fclose(fp);
  685. strbuf_release(&sb);
  686. free(series_dir_buf);
  687. ret = split_mail_conv(stgit_patch_to_mail, state, patches.v, keep_cr);
  688. strvec_clear(&patches);
  689. return ret;
  690. }
  691. /**
  692. * A split_patches_conv() callback that converts a mercurial patch to a RFC2822
  693. * message suitable for parsing with git-mailinfo.
  694. */
  695. static int hg_patch_to_mail(FILE *out, FILE *in, int keep_cr)
  696. {
  697. struct strbuf sb = STRBUF_INIT;
  698. int rc = 0;
  699. while (!strbuf_getline_lf(&sb, in)) {
  700. const char *str;
  701. if (skip_prefix(sb.buf, "# User ", &str))
  702. fprintf(out, "From: %s\n", str);
  703. else if (skip_prefix(sb.buf, "# Date ", &str)) {
  704. timestamp_t timestamp;
  705. long tz, tz2;
  706. char *end;
  707. errno = 0;
  708. timestamp = parse_timestamp(str, &end, 10);
  709. if (errno) {
  710. rc = error(_("invalid timestamp"));
  711. goto exit;
  712. }
  713. if (!skip_prefix(end, " ", &str)) {
  714. rc = error(_("invalid Date line"));
  715. goto exit;
  716. }
  717. errno = 0;
  718. tz = strtol(str, &end, 10);
  719. if (errno) {
  720. rc = error(_("invalid timezone offset"));
  721. goto exit;
  722. }
  723. if (*end) {
  724. rc = error(_("invalid Date line"));
  725. goto exit;
  726. }
  727. /*
  728. * mercurial's timezone is in seconds west of UTC,
  729. * however git's timezone is in hours + minutes east of
  730. * UTC. Convert it.
  731. */
  732. tz2 = labs(tz) / 3600 * 100 + labs(tz) % 3600 / 60;
  733. if (tz > 0)
  734. tz2 = -tz2;
  735. fprintf(out, "Date: %s\n", show_date(timestamp, tz2, DATE_MODE(RFC2822)));
  736. } else if (starts_with(sb.buf, "# ")) {
  737. continue;
  738. } else {
  739. fprintf(out, "\n%s\n", sb.buf);
  740. break;
  741. }
  742. }
  743. strbuf_reset(&sb);
  744. while (strbuf_fread(&sb, 8192, in) > 0) {
  745. fwrite(sb.buf, 1, sb.len, out);
  746. strbuf_reset(&sb);
  747. }
  748. exit:
  749. strbuf_release(&sb);
  750. return rc;
  751. }
  752. /**
  753. * Splits a list of files/directories into individual email patches. Each path
  754. * in `paths` must be a file/directory that is formatted according to
  755. * `patch_format`.
  756. *
  757. * Once split out, the individual email patches will be stored in the state
  758. * directory, with each patch's filename being its index, padded to state->prec
  759. * digits.
  760. *
  761. * state->cur will be set to the index of the first mail, and state->last will
  762. * be set to the index of the last mail.
  763. *
  764. * Set keep_cr to 0 to convert all lines ending with \r\n to end with \n, 1
  765. * to disable this behavior, -1 to use the default configured setting.
  766. *
  767. * Returns 0 on success, -1 on failure.
  768. */
  769. static int split_mail(struct am_state *state, enum patch_format patch_format,
  770. const char **paths, int keep_cr)
  771. {
  772. if (keep_cr < 0) {
  773. keep_cr = 0;
  774. git_config_get_bool("am.keepcr", &keep_cr);
  775. }
  776. switch (patch_format) {
  777. case PATCH_FORMAT_MBOX:
  778. return split_mail_mbox(state, paths, keep_cr, 0);
  779. case PATCH_FORMAT_STGIT:
  780. return split_mail_conv(stgit_patch_to_mail, state, paths, keep_cr);
  781. case PATCH_FORMAT_STGIT_SERIES:
  782. return split_mail_stgit_series(state, paths, keep_cr);
  783. case PATCH_FORMAT_HG:
  784. return split_mail_conv(hg_patch_to_mail, state, paths, keep_cr);
  785. case PATCH_FORMAT_MBOXRD:
  786. return split_mail_mbox(state, paths, keep_cr, 1);
  787. default:
  788. BUG("invalid patch_format");
  789. }
  790. return -1;
  791. }
  792. /**
  793. * Setup a new am session for applying patches
  794. */
  795. static void am_setup(struct am_state *state, enum patch_format patch_format,
  796. const char **paths, int keep_cr)
  797. {
  798. struct object_id curr_head;
  799. const char *str;
  800. struct strbuf sb = STRBUF_INIT;
  801. if (!patch_format)
  802. patch_format = detect_patch_format(paths);
  803. if (!patch_format) {
  804. fprintf_ln(stderr, _("Patch format detection failed."));
  805. exit(128);
  806. }
  807. if (mkdir(state->dir, 0777) < 0 && errno != EEXIST)
  808. die_errno(_("failed to create directory '%s'"), state->dir);
  809. delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
  810. if (split_mail(state, patch_format, paths, keep_cr) < 0) {
  811. am_destroy(state);
  812. die(_("Failed to split patches."));
  813. }
  814. if (state->rebasing)
  815. state->threeway = 1;
  816. write_state_bool(state, "threeway", state->threeway);
  817. write_state_bool(state, "quiet", state->quiet);
  818. write_state_bool(state, "sign", state->signoff);
  819. write_state_bool(state, "utf8", state->utf8);
  820. if (state->allow_rerere_autoupdate)
  821. write_state_bool(state, "rerere-autoupdate",
  822. state->allow_rerere_autoupdate == RERERE_AUTOUPDATE);
  823. switch (state->keep) {
  824. case KEEP_FALSE:
  825. str = "f";
  826. break;
  827. case KEEP_TRUE:
  828. str = "t";
  829. break;
  830. case KEEP_NON_PATCH:
  831. str = "b";
  832. break;
  833. default:
  834. BUG("invalid value for state->keep");
  835. }
  836. write_state_text(state, "keep", str);
  837. write_state_bool(state, "messageid", state->message_id);
  838. switch (state->scissors) {
  839. case SCISSORS_UNSET:
  840. str = "";
  841. break;
  842. case SCISSORS_FALSE:
  843. str = "f";
  844. break;
  845. case SCISSORS_TRUE:
  846. str = "t";
  847. break;
  848. default:
  849. BUG("invalid value for state->scissors");
  850. }
  851. write_state_text(state, "scissors", str);
  852. sq_quote_argv(&sb, state->git_apply_opts.v);
  853. write_state_text(state, "apply-opt", sb.buf);
  854. if (state->rebasing)
  855. write_state_text(state, "rebasing", "");
  856. else
  857. write_state_text(state, "applying", "");
  858. if (!get_oid("HEAD", &curr_head)) {
  859. write_state_text(state, "abort-safety", oid_to_hex(&curr_head));
  860. if (!state->rebasing)
  861. update_ref("am", "ORIG_HEAD", &curr_head, NULL, 0,
  862. UPDATE_REFS_DIE_ON_ERR);
  863. } else {
  864. write_state_text(state, "abort-safety", "");
  865. if (!state->rebasing)
  866. delete_ref(NULL, "ORIG_HEAD", NULL, 0);
  867. }
  868. /*
  869. * NOTE: Since the "next" and "last" files determine if an am_state
  870. * session is in progress, they should be written last.
  871. */
  872. write_state_count(state, "next", state->cur);
  873. write_state_count(state, "last", state->last);
  874. strbuf_release(&sb);
  875. }
  876. /**
  877. * Increments the patch pointer, and cleans am_state for the application of the
  878. * next patch.
  879. */
  880. static void am_next(struct am_state *state)
  881. {
  882. struct object_id head;
  883. FREE_AND_NULL(state->author_name);
  884. FREE_AND_NULL(state->author_email);
  885. FREE_AND_NULL(state->author_date);
  886. FREE_AND_NULL(state->msg);
  887. state->msg_len = 0;
  888. unlink(am_path(state, "author-script"));
  889. unlink(am_path(state, "final-commit"));
  890. oidclr(&state->orig_commit);
  891. unlink(am_path(state, "original-commit"));
  892. delete_ref(NULL, "REBASE_HEAD", NULL, REF_NO_DEREF);
  893. if (!get_oid("HEAD", &head))
  894. write_state_text(state, "abort-safety", oid_to_hex(&head));
  895. else
  896. write_state_text(state, "abort-safety", "");
  897. state->cur++;
  898. write_state_count(state, "next", state->cur);
  899. }
  900. /**
  901. * Returns the filename of the current patch email.
  902. */
  903. static const char *msgnum(const struct am_state *state)
  904. {
  905. static struct strbuf sb = STRBUF_INIT;
  906. strbuf_reset(&sb);
  907. strbuf_addf(&sb, "%0*d", state->prec, state->cur);
  908. return sb.buf;
  909. }
  910. /**
  911. * Dies with a user-friendly message on how to proceed after resolving the
  912. * problem. This message can be overridden with state->resolvemsg.
  913. */
  914. static void NORETURN die_user_resolve(const struct am_state *state)
  915. {
  916. if (state->resolvemsg) {
  917. printf_ln("%s", state->resolvemsg);
  918. } else {
  919. const char *cmdline = state->interactive ? "git am -i" : "git am";
  920. printf_ln(_("When you have resolved this problem, run \"%s --continue\"."), cmdline);
  921. printf_ln(_("If you prefer to skip this patch, run \"%s --skip\" instead."), cmdline);
  922. printf_ln(_("To restore the original branch and stop patching, run \"%s --abort\"."), cmdline);
  923. }
  924. exit(128);
  925. }
  926. /**
  927. * Appends signoff to the "msg" field of the am_state.
  928. */
  929. static void am_append_signoff(struct am_state *state)
  930. {
  931. struct strbuf sb = STRBUF_INIT;
  932. strbuf_attach(&sb, state->msg, state->msg_len, state->msg_len);
  933. append_signoff(&sb, 0, 0);
  934. state->msg = strbuf_detach(&sb, &state->msg_len);
  935. }
  936. /**
  937. * Parses `mail` using git-mailinfo, extracting its patch and authorship info.
  938. * state->msg will be set to the patch message. state->author_name,
  939. * state->author_email and state->author_date will be set to the patch author's
  940. * name, email and date respectively. The patch body will be written to the
  941. * state directory's "patch" file.
  942. *
  943. * Returns 1 if the patch should be skipped, 0 otherwise.
  944. */
  945. static int parse_mail(struct am_state *state, const char *mail)
  946. {
  947. FILE *fp;
  948. struct strbuf sb = STRBUF_INIT;
  949. struct strbuf msg = STRBUF_INIT;
  950. struct strbuf author_name = STRBUF_INIT;
  951. struct strbuf author_date = STRBUF_INIT;
  952. struct strbuf author_email = STRBUF_INIT;
  953. int ret = 0;
  954. struct mailinfo mi;
  955. setup_mailinfo(&mi);
  956. if (state->utf8)
  957. mi.metainfo_charset = get_commit_output_encoding();
  958. else
  959. mi.metainfo_charset = NULL;
  960. switch (state->keep) {
  961. case KEEP_FALSE:
  962. break;
  963. case KEEP_TRUE:
  964. mi.keep_subject = 1;
  965. break;
  966. case KEEP_NON_PATCH:
  967. mi.keep_non_patch_brackets_in_subject = 1;
  968. break;
  969. default:
  970. BUG("invalid value for state->keep");
  971. }
  972. if (state->message_id)
  973. mi.add_message_id = 1;
  974. switch (state->scissors) {
  975. case SCISSORS_UNSET:
  976. break;
  977. case SCISSORS_FALSE:
  978. mi.use_scissors = 0;
  979. break;
  980. case SCISSORS_TRUE:
  981. mi.use_scissors = 1;
  982. break;
  983. default:
  984. BUG("invalid value for state->scissors");
  985. }
  986. mi.input = xfopen(mail, "r");
  987. mi.output = xfopen(am_path(state, "info"), "w");
  988. if (mailinfo(&mi, am_path(state, "msg"), am_path(state, "patch")))
  989. die("could not parse patch");
  990. fclose(mi.input);
  991. fclose(mi.output);
  992. if (mi.format_flowed)
  993. warning(_("Patch sent with format=flowed; "
  994. "space at the end of lines might be lost."));
  995. /* Extract message and author information */
  996. fp = xfopen(am_path(state, "info"), "r");
  997. while (!strbuf_getline_lf(&sb, fp)) {
  998. const char *x;
  999. if (skip_prefix(sb.buf, "Subject: ", &x)) {
  1000. if (msg.len)
  1001. strbuf_addch(&msg, '\n');
  1002. strbuf_addstr(&msg, x);
  1003. } else if (skip_prefix(sb.buf, "Author: ", &x))
  1004. strbuf_addstr(&author_name, x);
  1005. else if (skip_prefix(sb.buf, "Email: ", &x))
  1006. strbuf_addstr(&author_email, x);
  1007. else if (skip_prefix(sb.buf, "Date: ", &x))
  1008. strbuf_addstr(&author_date, x);
  1009. }
  1010. fclose(fp);
  1011. /* Skip pine's internal folder data */
  1012. if (!strcmp(author_name.buf, "Mail System Internal Data")) {
  1013. ret = 1;
  1014. goto finish;
  1015. }
  1016. if (is_empty_or_missing_file(am_path(state, "patch"))) {
  1017. printf_ln(_("Patch is empty."));
  1018. die_user_resolve(state);
  1019. }
  1020. strbuf_addstr(&msg, "\n\n");
  1021. strbuf_addbuf(&msg, &mi.log_message);
  1022. strbuf_stripspace(&msg, 0);
  1023. assert(!state->author_name);
  1024. state->author_name = strbuf_detach(&author_name, NULL);
  1025. assert(!state->author_email);
  1026. state->author_email = strbuf_detach(&author_email, NULL);
  1027. assert(!state->author_date);
  1028. state->author_date = strbuf_detach(&author_date, NULL);
  1029. assert(!state->msg);
  1030. state->msg = strbuf_detach(&msg, &state->msg_len);
  1031. finish:
  1032. strbuf_release(&msg);
  1033. strbuf_release(&author_date);
  1034. strbuf_release(&author_email);
  1035. strbuf_release(&author_name);
  1036. strbuf_release(&sb);
  1037. clear_mailinfo(&mi);
  1038. return ret;
  1039. }
  1040. /**
  1041. * Sets commit_id to the commit hash where the mail was generated from.
  1042. * Returns 0 on success, -1 on failure.
  1043. */
  1044. static int get_mail_commit_oid(struct object_id *commit_id, const char *mail)
  1045. {
  1046. struct strbuf sb = STRBUF_INIT;
  1047. FILE *fp = xfopen(mail, "r");
  1048. const char *x;
  1049. int ret = 0;
  1050. if (strbuf_getline_lf(&sb, fp) ||
  1051. !skip_prefix(sb.buf, "From ", &x) ||
  1052. get_oid_hex(x, commit_id) < 0)
  1053. ret = -1;
  1054. strbuf_release(&sb);
  1055. fclose(fp);
  1056. return ret;
  1057. }
  1058. /**
  1059. * Sets state->msg, state->author_name, state->author_email, state->author_date
  1060. * to the commit's respective info.
  1061. */
  1062. static void get_commit_info(struct am_state *state, struct commit *commit)
  1063. {
  1064. const char *buffer, *ident_line, *msg;
  1065. size_t ident_len;
  1066. struct ident_split id;
  1067. buffer = logmsg_reencode(commit, NULL, get_commit_output_encoding());
  1068. ident_line = find_commit_header(buffer, "author", &ident_len);
  1069. if (!ident_line)
  1070. die(_("missing author line in commit %s"),
  1071. oid_to_hex(&commit->object.oid));
  1072. if (split_ident_line(&id, ident_line, ident_len) < 0)
  1073. die(_("invalid ident line: %.*s"), (int)ident_len, ident_line);
  1074. assert(!state->author_name);
  1075. if (id.name_begin)
  1076. state->author_name =
  1077. xmemdupz(id.name_begin, id.name_end - id.name_begin);
  1078. else
  1079. state->author_name = xstrdup("");
  1080. assert(!state->author_email);
  1081. if (id.mail_begin)
  1082. state->author_email =
  1083. xmemdupz(id.mail_begin, id.mail_end - id.mail_begin);
  1084. else
  1085. state->author_email = xstrdup("");
  1086. assert(!state->author_date);
  1087. state->author_date = xstrdup(show_ident_date(&id, DATE_MODE(NORMAL)));
  1088. assert(!state->msg);
  1089. msg = strstr(buffer, "\n\n");
  1090. if (!msg)
  1091. die(_("unable to parse commit %s"), oid_to_hex(&commit->object.oid));
  1092. state->msg = xstrdup(msg + 2);
  1093. state->msg_len = strlen(state->msg);
  1094. unuse_commit_buffer(commit, buffer);
  1095. }
  1096. /**
  1097. * Writes `commit` as a patch to the state directory's "patch" file.
  1098. */
  1099. static void write_commit_patch(const struct am_state *state, struct commit *commit)
  1100. {
  1101. struct rev_info rev_info;
  1102. FILE *fp;
  1103. fp = xfopen(am_path(state, "patch"), "w");
  1104. repo_init_revisions(the_repository, &rev_info, NULL);
  1105. rev_info.diff = 1;
  1106. rev_info.abbrev = 0;
  1107. rev_info.disable_stdin = 1;
  1108. rev_info.show_root_diff = 1;
  1109. rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
  1110. rev_info.no_commit_id = 1;
  1111. rev_info.diffopt.flags.binary = 1;
  1112. rev_info.diffopt.flags.full_index = 1;
  1113. rev_info.diffopt.use_color = 0;
  1114. rev_info.diffopt.file = fp;
  1115. rev_info.diffopt.close_file = 1;
  1116. add_pending_object(&rev_info, &commit->object, "");
  1117. diff_setup_done(&rev_info.diffopt);
  1118. log_tree_commit(&rev_info, commit);
  1119. }
  1120. /**
  1121. * Writes the diff of the index against HEAD as a patch to the state
  1122. * directory's "patch" file.
  1123. */
  1124. static void write_index_patch(const struct am_state *state)
  1125. {
  1126. struct tree *tree;
  1127. struct object_id head;
  1128. struct rev_info rev_info;
  1129. FILE *fp;
  1130. if (!get_oid("HEAD", &head)) {
  1131. struct commit *commit = lookup_commit_or_die(&head, "HEAD");
  1132. tree = get_commit_tree(commit);
  1133. } else
  1134. tree = lookup_tree(the_repository,
  1135. the_repository->hash_algo->empty_tree);
  1136. fp = xfopen(am_path(state, "patch"), "w");
  1137. repo_init_revisions(the_repository, &rev_info, NULL);
  1138. rev_info.diff = 1;
  1139. rev_info.disable_stdin = 1;
  1140. rev_info.no_commit_id = 1;
  1141. rev_info.diffopt.output_format = DIFF_FORMAT_PATCH;
  1142. rev_info.diffopt.use_color = 0;
  1143. rev_info.diffopt.file = fp;
  1144. rev_info.diffopt.close_file = 1;
  1145. add_pending_object(&rev_info, &tree->object, "");
  1146. diff_setup_done(&rev_info.diffopt);
  1147. run_diff_index(&rev_info, 1);
  1148. }
  1149. /**
  1150. * Like parse_mail(), but parses the mail by looking up its commit ID
  1151. * directly. This is used in --rebasing mode to bypass git-mailinfo's munging
  1152. * of patches.
  1153. *
  1154. * state->orig_commit will be set to the original commit ID.
  1155. *
  1156. * Will always return 0 as the patch should never be skipped.
  1157. */
  1158. static int parse_mail_rebase(struct am_state *state, const char *mail)
  1159. {
  1160. struct commit *commit;
  1161. struct object_id commit_oid;
  1162. if (get_mail_commit_oid(&commit_oid, mail) < 0)
  1163. die(_("could not parse %s"), mail);
  1164. commit = lookup_commit_or_die(&commit_oid, mail);
  1165. get_commit_info(state, commit);
  1166. write_commit_patch(state, commit);
  1167. oidcpy(&state->orig_commit, &commit_oid);
  1168. write_state_text(state, "original-commit", oid_to_hex(&commit_oid));
  1169. update_ref("am", "REBASE_HEAD", &commit_oid,
  1170. NULL, REF_NO_DEREF, UPDATE_REFS_DIE_ON_ERR);
  1171. return 0;
  1172. }
  1173. /**
  1174. * Applies current patch with git-apply. Returns 0 on success, -1 otherwise. If
  1175. * `index_file` is not NULL, the patch will be applied to that index.
  1176. */
  1177. static int run_apply(const struct am_state *state, const char *index_file)
  1178. {
  1179. struct strvec apply_paths = STRVEC_INIT;
  1180. struct strvec apply_opts = STRVEC_INIT;
  1181. struct apply_state apply_state;
  1182. int res, opts_left;
  1183. int force_apply = 0;
  1184. int options = 0;
  1185. if (init_apply_state(&apply_state, the_repository, NULL))
  1186. BUG("init_apply_state() failed");
  1187. strvec_push(&apply_opts, "apply");
  1188. strvec_pushv(&apply_opts, state->git_apply_opts.v);
  1189. opts_left = apply_parse_options(apply_opts.nr, apply_opts.v,
  1190. &apply_state, &force_apply, &options,
  1191. NULL);
  1192. if (opts_left != 0)
  1193. die("unknown option passed through to git apply");
  1194. if (index_file) {
  1195. apply_state.index_file = index_file;
  1196. apply_state.cached = 1;
  1197. } else
  1198. apply_state.check_index = 1;
  1199. /*
  1200. * If we are allowed to fall back on 3-way merge, don't give false
  1201. * errors during the initial attempt.
  1202. */
  1203. if (state->threeway && !index_file)
  1204. apply_state.apply_verbosity = verbosity_silent;
  1205. if (check_apply_state(&apply_state, force_apply))
  1206. BUG("check_apply_state() failed");
  1207. strvec_push(&apply_paths, am_path(state, "patch"));
  1208. res = apply_all_patches(&apply_state, apply_paths.nr, apply_paths.v, options);
  1209. strvec_clear(&apply_paths);
  1210. strvec_clear(&apply_opts);
  1211. clear_apply_state(&apply_state);
  1212. if (res)
  1213. return res;
  1214. if (index_file) {
  1215. /* Reload index as apply_all_patches() will have modified it. */
  1216. discard_cache();
  1217. read_cache_from(index_file);
  1218. }
  1219. return 0;
  1220. }
  1221. /**
  1222. * Builds an index that contains just the blobs needed for a 3way merge.
  1223. */
  1224. static int build_fake_ancestor(const struct am_state *state, const char *index_file)
  1225. {
  1226. struct child_process cp = CHILD_PROCESS_INIT;
  1227. cp.git_cmd = 1;
  1228. strvec_push(&cp.args, "apply");
  1229. strvec_pushv(&cp.args, state->git_apply_opts.v);
  1230. strvec_pushf(&cp.args, "--build-fake-ancestor=%s", index_file);
  1231. strvec_push(&cp.args, am_path(state, "patch"));
  1232. if (run_command(&cp))
  1233. return -1;
  1234. return 0;
  1235. }
  1236. /**
  1237. * Attempt a threeway merge, using index_path as the temporary index.
  1238. */
  1239. static int fall_back_threeway(const struct am_state *state, const char *index_path)
  1240. {
  1241. struct object_id orig_tree, their_tree, our_tree;
  1242. const struct object_id *bases[1] = { &orig_tree };
  1243. struct merge_options o;
  1244. struct commit *result;
  1245. char *their_tree_name;
  1246. if (get_oid("HEAD", &our_tree) < 0)
  1247. oidcpy(&our_tree, the_hash_algo->empty_tree);
  1248. if (build_fake_ancestor(state, index_path))
  1249. return error("could not build fake ancestor");
  1250. discard_cache();
  1251. read_cache_from(index_path);
  1252. if (write_index_as_tree(&orig_tree, &the_index, index_path, 0, NULL))
  1253. return error(_("Repository lacks necessary blobs to fall back on 3-way merge."));
  1254. say(state, stdout, _("Using index info to reconstruct a base tree..."));
  1255. if (!state->quiet) {
  1256. /*
  1257. * List paths that needed 3-way fallback, so that the user can
  1258. * review them with extra care to spot mismerges.
  1259. */
  1260. struct rev_info rev_info;
  1261. repo_init_revisions(the_repository, &rev_info, NULL);
  1262. rev_info.diffopt.output_format = DIFF_FORMAT_NAME_STATUS;
  1263. rev_info.diffopt.filter |= diff_filter_bit('A');
  1264. rev_info.diffopt.filter |= diff_filter_bit('M');
  1265. add_pending_oid(&rev_info, "HEAD", &our_tree, 0);
  1266. diff_setup_done(&rev_info.diffopt);
  1267. run_diff_index(&rev_info, 1);
  1268. }
  1269. if (run_apply(state, index_path))
  1270. return error(_("Did you hand edit your patch?\n"
  1271. "It does not apply to blobs recorded in its index."));
  1272. if (write_index_as_tree(&their_tree, &the_index, index_path, 0, NULL))
  1273. return error("could not write tree");
  1274. say(state, stdout, _("Falling back to patching base and 3-way merge..."));
  1275. discard_cache();
  1276. read_cache();
  1277. /*
  1278. * This is not so wrong. Depending on which base we picked, orig_tree
  1279. * may be wildly different from ours, but their_tree has the same set of
  1280. * wildly different changes in parts the patch did not touch, so
  1281. * recursive ends up canceling them, saying that we reverted all those
  1282. * changes.
  1283. */
  1284. init_merge_options(&o, the_repository);
  1285. o.branch1 = "HEAD";
  1286. their_tree_name = xstrfmt("%.*s", linelen(state->msg), state->msg);
  1287. o.branch2 = their_tree_name;
  1288. o.detect_directory_renames = MERGE_DIRECTORY_RENAMES_NONE;
  1289. if (state->quiet)
  1290. o.verbosity = 0;
  1291. if (merge_recursive_generic(&o, &our_tree, &their_tree, 1, bases, &result)) {
  1292. repo_rerere(the_repository, state->allow_rerere_autoupdate);
  1293. free(their_tree_name);
  1294. return error(_("Failed to merge in the changes."));
  1295. }
  1296. free(their_tree_name);
  1297. return 0;
  1298. }
  1299. /**
  1300. * Commits the current index with state->msg as the commit message and
  1301. * state->author_name, state->author_email and state->author_date as the author
  1302. * information.
  1303. */
  1304. static void do_commit(const struct am_state *state)
  1305. {
  1306. struct object_id tree, parent, commit;
  1307. const struct object_id *old_oid;
  1308. struct commit_list *parents = NULL;
  1309. const char *reflog_msg, *author, *committer = NULL;
  1310. struct strbuf sb = STRBUF_INIT;
  1311. if (run_hook_le(NULL, "pre-applypatch", NULL))
  1312. exit(1);
  1313. if (write_cache_as_tree(&tree, 0, NULL))
  1314. die(_("git write-tree failed to write a tree"));
  1315. if (!get_oid_commit("HEAD", &parent)) {
  1316. old_oid = &parent;
  1317. commit_list_insert(lookup_commit(the_repository, &parent),
  1318. &parents);
  1319. } else {
  1320. old_oid = NULL;
  1321. say(state, stderr, _("applying to an empty history"));
  1322. }
  1323. author = fmt_ident(state->author_name, state->author_email,
  1324. WANT_AUTHOR_IDENT,
  1325. state->ignore_date ? NULL : state->author_date,
  1326. IDENT_STRICT);
  1327. if (state->committer_date_is_author_date)
  1328. committer = fmt_ident(state->committer_name,
  1329. state->author_email, WANT_COMMITTER_IDENT,
  1330. state->ignore_date ? NULL
  1331. : state->author_date,
  1332. IDENT_STRICT);
  1333. if (commit_tree_extended(state->msg, state->msg_len, &tree, parents,
  1334. &commit, author, committer, state->sign_commit,
  1335. NULL))
  1336. die(_("failed to write commit object"));
  1337. reflog_msg = getenv("GIT_REFLOG_ACTION");
  1338. if (!reflog_msg)
  1339. reflog_msg = "am";
  1340. strbuf_addf(&sb, "%s: %.*s", reflog_msg, linelen(state->msg),
  1341. state->msg);
  1342. update_ref(sb.buf, "HEAD", &commit, old_oid, 0,
  1343. UPDATE_REFS_DIE_ON_ERR);
  1344. if (state->rebasing) {
  1345. FILE *fp = xfopen(am_path(state, "rewritten"), "a");
  1346. assert(!is_null_oid(&state->orig_commit));
  1347. fprintf(fp, "%s ", oid_to_hex(&state->orig_commit));
  1348. fprintf(fp, "%s\n", oid_to_hex(&commit));
  1349. fclose(fp);
  1350. }
  1351. run_hook_le(NULL, "post-applypatch", NULL);
  1352. strbuf_release(&sb);
  1353. }
  1354. /**
  1355. * Validates the am_state for resuming -- the "msg" and authorship fields must
  1356. * be filled up.
  1357. */
  1358. static void validate_resume_state(const struct am_state *state)
  1359. {
  1360. if (!state->msg)
  1361. die(_("cannot resume: %s does not exist."),
  1362. am_path(state, "final-commit"));
  1363. if (!state->author_name || !state->author_email || !state->author_date)
  1364. die(_("cannot resume: %s does not exist."),
  1365. am_path(state, "author-script"));
  1366. }
  1367. /**
  1368. * Interactively prompt the user on whether the current patch should be
  1369. * applied.
  1370. *
  1371. * Returns 0 if the user chooses to apply the patch, 1 if the user chooses to
  1372. * skip it.
  1373. */
  1374. static int do_interactive(struct am_state *state)
  1375. {
  1376. assert(state->msg);
  1377. for (;;) {
  1378. char reply[64];
  1379. puts(_("Commit Body is:"));
  1380. puts("--------------------------");
  1381. printf("%s", state->msg);
  1382. puts("--------------------------");
  1383. /*
  1384. * TRANSLATORS: Make sure to include [y], [n], [e], [v] and [a]
  1385. * in your translation. The program will only accept English
  1386. * input at this point.
  1387. */
  1388. printf(_("Apply? [y]es/[n]o/[e]dit/[v]iew patch/[a]ccept all: "));
  1389. if (!fgets(reply, sizeof(reply), stdin))
  1390. die("unable to read from stdin; aborting");
  1391. if (*reply == 'y' || *reply == 'Y') {
  1392. return 0;
  1393. } else if (*reply == 'a' || *reply == 'A') {
  1394. state->interactive = 0;
  1395. return 0;
  1396. } else if (*reply == 'n' || *reply == 'N') {
  1397. return 1;
  1398. } else if (*reply == 'e' || *reply == 'E') {
  1399. struct strbuf msg = STRBUF_INIT;
  1400. if (!launch_editor(am_path(state, "final-commit"), &msg, NULL)) {
  1401. free(state->msg);
  1402. state->msg = strbuf_detach(&msg, &state->msg_len);
  1403. }
  1404. strbuf_release(&msg);
  1405. } else if (*reply == 'v' || *reply == 'V') {
  1406. const char *pager = git_pager(1);
  1407. struct child_process cp = CHILD_PROCESS_INIT;
  1408. if (!pager)
  1409. pager = "cat";
  1410. prepare_pager_args(&cp, pager);
  1411. strvec_push(&cp.args, am_path(state, "patch"));
  1412. run_command(&cp);
  1413. }
  1414. }
  1415. }
  1416. /**
  1417. * Applies all queued mail.
  1418. *
  1419. * If `resume` is true, we are "resuming". The "msg" and authorship fields, as
  1420. * well as the state directory's "patch" file is used as-is for applying the
  1421. * patch and committing it.
  1422. */
  1423. static void am_run(struct am_state *state, int resume)
  1424. {
  1425. struct strbuf sb = STRBUF_INIT;
  1426. unlink(am_path(state, "dirtyindex"));
  1427. if (refresh_and_write_cache(REFRESH_QUIET, 0, 0) < 0)
  1428. die(_("unable to write index file"));
  1429. if (repo_index_has_changes(the_repository, NULL, &sb)) {
  1430. write_state_bool(state, "dirtyindex", 1);
  1431. die(_("Dirty index: cannot apply patches (dirty: %s)"), sb.buf);
  1432. }
  1433. strbuf_release(&sb);
  1434. while (state->cur <= state->last) {
  1435. const char *mail = am_path(state, msgnum(state));
  1436. int apply_status;
  1437. reset_ident_date();
  1438. if (!file_exists(mail))
  1439. goto next;
  1440. if (resume) {
  1441. validate_resume_state(state);
  1442. } else {
  1443. int skip;
  1444. if (state->rebasing)
  1445. skip = parse_mail_rebase(state, mail);
  1446. else
  1447. skip = parse_mail(state, mail);
  1448. if (skip)
  1449. goto next; /* mail should be skipped */
  1450. if (state->signoff)
  1451. am_append_signoff(state);
  1452. write_author_script(state);
  1453. write_commit_msg(state);
  1454. }
  1455. if (state->interactive && do_interactive(state))
  1456. goto next;
  1457. if (run_applypatch_msg_hook(state))
  1458. exit(1);
  1459. say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
  1460. apply_status = run_apply(state, NULL);
  1461. if (apply_status && state->threeway) {
  1462. struct strbuf sb = STRBUF_INIT;
  1463. strbuf_addstr(&sb, am_path(state, "patch-merge-index"));
  1464. apply_status = fall_back_threeway(state, sb.buf);
  1465. strbuf_release(&sb);
  1466. /*
  1467. * Applying the patch to an earlier tree and merging
  1468. * the result may have produced the same tree as ours.
  1469. */
  1470. if (!apply_status &&
  1471. !repo_index_has_changes(the_repository, NULL, NULL)) {
  1472. say(state, stdout, _("No changes -- Patch already applied."));
  1473. goto next;
  1474. }
  1475. }
  1476. if (apply_status) {
  1477. printf_ln(_("Patch failed at %s %.*s"), msgnum(state),
  1478. linelen(state->msg), state->msg);
  1479. if (advice_amworkdir)
  1480. advise(_("Use 'git am --show-current-patch=diff' to see the failed patch"));
  1481. die_user_resolve(state);
  1482. }
  1483. do_commit(state);
  1484. next:
  1485. am_next(state);
  1486. if (resume)
  1487. am_load(state);
  1488. resume = 0;
  1489. }
  1490. if (!is_empty_or_missing_file(am_path(state, "rewritten"))) {
  1491. assert(state->rebasing);
  1492. copy_notes_for_rebase(state);
  1493. run_post_rewrite_hook(state);
  1494. }
  1495. /*
  1496. * In rebasing mode, it's up to the caller to take care of
  1497. * housekeeping.
  1498. */
  1499. if (!state->rebasing) {
  1500. am_destroy(state);
  1501. close_object_store(the_repository->objects);
  1502. run_auto_maintenance(state->quiet);
  1503. }
  1504. }
  1505. /**
  1506. * Resume the current am session after patch application failure. The user did
  1507. * all the hard work, and we do not have to do any patch application. Just
  1508. * trust and commit what the user has in the index and working tree.
  1509. */
  1510. static void am_resolve(struct am_state *state)
  1511. {
  1512. validate_resume_state(state);
  1513. say(state, stdout, _("Applying: %.*s"), linelen(state->msg), state->msg);
  1514. if (!repo_index_has_changes(the_repository, NULL, NULL)) {
  1515. printf_ln(_("No changes - did you forget to use 'git add'?\n"
  1516. "If there is nothing left to stage, chances are that something else\n"
  1517. "already introduced the same changes; you might want to skip this patch."));
  1518. die_user_resolve(state);
  1519. }
  1520. if (unmerged_cache()) {
  1521. printf_ln(_("You still have unmerged paths in your index.\n"
  1522. "You should 'git add' each file with resolved conflicts to mark them as such.\n"
  1523. "You might run `git rm` on a file to accept \"deleted by them\" for it."));
  1524. die_user_resolve(state);
  1525. }
  1526. if (state->interactive) {
  1527. write_index_patch(state);
  1528. if (do_interactive(state))
  1529. goto next;
  1530. }
  1531. repo_rerere(the_repository, 0);
  1532. do_commit(state);
  1533. next:
  1534. am_next(state);
  1535. am_load(state);
  1536. am_run(state, 0);
  1537. }
  1538. /**
  1539. * Performs a checkout fast-forward from `head` to `remote`. If `reset` is
  1540. * true, any unmerged entries will be discarded. Returns 0 on success, -1 on
  1541. * failure.
  1542. */
  1543. static int fast_forward_to(struct tree *head, struct tree *remote, int reset)
  1544. {
  1545. struct lock_file lock_file = LOCK_INIT;
  1546. struct unpack_trees_options opts;
  1547. struct tree_desc t[2];
  1548. if (parse_tree(head) || parse_tree(remote))
  1549. return -1;
  1550. hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
  1551. refresh_cache(REFRESH_QUIET);
  1552. memset(&opts, 0, sizeof(opts));
  1553. opts.head_idx = 1;
  1554. opts.src_index = &the_index;
  1555. opts.dst_index = &the_index;
  1556. opts.update = 1;
  1557. opts.merge = 1;
  1558. opts.reset = reset;
  1559. opts.fn = twoway_merge;
  1560. init_tree_desc(&t[0], head->buffer, head->size);
  1561. init_tree_desc(&t[1], remote->buffer, remote->size);
  1562. if (unpack_trees(2, t, &opts)) {
  1563. rollback_lock_file(&lock_file);
  1564. return -1;
  1565. }
  1566. if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
  1567. die(_("unable to write new index file"));
  1568. return 0;
  1569. }
  1570. /**
  1571. * Merges a tree into the index. The index's stat info will take precedence
  1572. * over the merged tree's. Returns 0 on success, -1 on failure.
  1573. */
  1574. static int merge_tree(struct tree *tree)
  1575. {
  1576. struct lock_file lock_file = LOCK_INIT;
  1577. struct unpack_trees_options opts;
  1578. struct tree_desc t[1];
  1579. if (parse_tree(tree))
  1580. return -1;
  1581. hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
  1582. memset(&opts, 0, sizeof(opts));
  1583. opts.head_idx = 1;
  1584. opts.src_index = &the_index;
  1585. opts.dst_index = &the_index;
  1586. opts.merge = 1;
  1587. opts.fn = oneway_merge;
  1588. init_tree_desc(&t[0], tree->buffer, tree->size);
  1589. if (unpack_trees(1, t, &opts)) {
  1590. rollback_lock_file(&lock_file);
  1591. return -1;
  1592. }
  1593. if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
  1594. die(_("unable to write new index file"));
  1595. return 0;
  1596. }
  1597. /**
  1598. * Clean the index without touching entries that are not modified between
  1599. * `head` and `remote`.
  1600. */
  1601. static int clean_index(const struct object_id *head, const struct object_id *remote)
  1602. {
  1603. struct tree *head_tree, *remote_tree, *index_tree;
  1604. struct object_id index;
  1605. head_tree = parse_tree_indirect(head);
  1606. if (!head_tree)
  1607. return error(_("Could not parse object '%s'."), oid_to_hex(head));
  1608. remote_tree = parse_tree_indirect(remote);
  1609. if (!remote_tree)
  1610. return error(_("Could not parse object '%s'."), oid_to_hex(remote));
  1611. read_cache_unmerged();
  1612. if (fast_forward_to(head_tree, head_tree, 1))
  1613. return -1;
  1614. if (write_cache_as_tree(&index, 0, NULL))
  1615. return -1;
  1616. index_tree = parse_tree_indirect(&index);
  1617. if (!index_tree)
  1618. return error(_("Could not parse object '%s'."), oid_to_hex(&index));
  1619. if (fast_forward_to(index_tree, remote_tree, 0))
  1620. return -1;
  1621. if (merge_tree(remote_tree))
  1622. return -1;
  1623. remove_branch_state(the_repository, 0);
  1624. return 0;
  1625. }
  1626. /**
  1627. * Resets rerere's merge resolution metadata.
  1628. */
  1629. static void am_rerere_clear(void)
  1630. {
  1631. struct string_list merge_rr = STRING_LIST_INIT_DUP;
  1632. rerere_clear(the_repository, &merge_rr);
  1633. string_list_clear(&merge_rr, 1);
  1634. }
  1635. /**
  1636. * Resume the current am session by skipping the current patch.
  1637. */
  1638. static void am_skip(struct am_state *state)
  1639. {
  1640. struct object_id head;
  1641. am_rerere_clear();
  1642. if (get_oid("HEAD", &head))
  1643. oidcpy(&head, the_hash_algo->empty_tree);
  1644. if (clean_index(&head, &head))
  1645. die(_("failed to clean index"));
  1646. if (state->rebasing) {
  1647. FILE *fp = xfopen(am_path(state, "rewritten"), "a");
  1648. assert(!is_null_oid(&state->orig_commit));
  1649. fprintf(fp, "%s ", oid_to_hex(&state->orig_commit));
  1650. fprintf(fp, "%s\n", oid_to_hex(&head));
  1651. fclose(fp);
  1652. }
  1653. am_next(state);
  1654. am_load(state);
  1655. am_run(state, 0);
  1656. }
  1657. /**
  1658. * Returns true if it is safe to reset HEAD to the ORIG_HEAD, false otherwise.
  1659. *
  1660. * It is not safe to reset HEAD when:
  1661. * 1. git-am previously failed because the index was dirty.
  1662. * 2. HEAD has moved since git-am previously failed.
  1663. */
  1664. static int safe_to_abort(const struct am_state *state)
  1665. {
  1666. struct strbuf sb = STRBUF_INIT;
  1667. struct object_id abort_safety, head;
  1668. if (file_exists(am_path(state, "dirtyindex")))
  1669. return 0;
  1670. if (read_state_file(&sb, state, "abort-safety", 1) > 0) {
  1671. if (get_oid_hex(sb.buf, &abort_safety))
  1672. die(_("could not parse %s"), am_path(state, "abort-safety"));
  1673. } else
  1674. oidclr(&abort_safety);
  1675. strbuf_release(&sb);
  1676. if (get_oid("HEAD", &head))
  1677. oidclr(&head);
  1678. if (oideq(&head, &abort_safety))
  1679. return 1;
  1680. warning(_("You seem to have moved HEAD since the last 'am' failure.\n"
  1681. "Not rewinding to ORIG_HEAD"));
  1682. return 0;
  1683. }
  1684. /**
  1685. * Aborts the current am session if it is safe to do so.
  1686. */
  1687. static void am_abort(struct am_state *state)
  1688. {
  1689. struct object_id curr_head, orig_head;
  1690. int has_curr_head, has_orig_head;
  1691. char *curr_branch;
  1692. if (!safe_to_abort(state)) {
  1693. am_destroy(state);
  1694. return;
  1695. }
  1696. am_rerere_clear();
  1697. curr_branch = resolve_refdup("HEAD", 0, &curr_head, NULL);
  1698. has_curr_head = curr_branch && !is_null_oid(&curr_head);
  1699. if (!has_curr_head)
  1700. oidcpy(&curr_head, the_hash_algo->empty_tree);
  1701. has_orig_head = !get_oid("ORIG_HEAD", &orig_head);
  1702. if (!has_orig_head)
  1703. oidcpy(&orig_head, the_hash_algo->empty_tree);
  1704. clean_index(&curr_head, &orig_head);
  1705. if (has_orig_head)
  1706. update_ref("am --abort", "HEAD", &orig_head,
  1707. has_curr_head ? &curr_head : NULL, 0,
  1708. UPDATE_REFS_DIE_ON_ERR);
  1709. else if (curr_branch)
  1710. delete_ref(NULL, curr_branch, NULL, REF_NO_DEREF);
  1711. free(curr_branch);
  1712. am_destroy(state);
  1713. }
  1714. static int show_patch(struct am_state *state, enum show_patch_type sub_mode)
  1715. {
  1716. struct strbuf sb = STRBUF_INIT;
  1717. const char *patch_path;
  1718. int len;
  1719. if (!is_null_oid(&state->orig_commit)) {
  1720. const char *av[4] = { "show", NULL, "--", NULL };
  1721. char *new_oid_str;
  1722. int ret;
  1723. av[1] = new_oid_str = xstrdup(oid_to_hex(&state->orig_commit));
  1724. ret = run_command_v_opt(av, RUN_GIT_CMD);
  1725. free(new_oid_str);
  1726. return ret;
  1727. }
  1728. switch (sub_mode) {
  1729. case SHOW_PATCH_RAW:
  1730. patch_path = am_path(state, msgnum(state));
  1731. break;
  1732. case SHOW_PATCH_DIFF:
  1733. patch_path = am_path(state, "patch");
  1734. break;
  1735. default:
  1736. BUG("invalid mode for --show-current-patch");
  1737. }
  1738. len = strbuf_read_file(&sb, patch_path, 0);
  1739. if (len < 0)
  1740. die_errno(_("failed to read '%s'"), patch_path);
  1741. setup_pager();
  1742. write_in_full(1, sb.buf, sb.len);
  1743. strbuf_release(&sb);
  1744. return 0;
  1745. }
  1746. /**
  1747. * parse_options() callback that validates and sets opt->value to the
  1748. * PATCH_FORMAT_* enum value corresponding to `arg`.
  1749. */
  1750. static int parse_opt_patchformat(const struct option *opt, const char *arg, int unset)
  1751. {
  1752. int *opt_value = opt->value;
  1753. if (unset)
  1754. *opt_value = PATCH_FORMAT_UNKNOWN;
  1755. else if (!strcmp(arg, "mbox"))
  1756. *opt_value = PATCH_FORMAT_MBOX;
  1757. else if (!strcmp(arg, "stgit"))
  1758. *opt_value = PATCH_FORMAT_STGIT;
  1759. else if (!strcmp(arg, "stgit-series"))
  1760. *opt_value = PATCH_FORMAT_STGIT_SERIES;
  1761. else if (!strcmp(arg, "hg"))
  1762. *opt_value = PATCH_FORMAT_HG;
  1763. else if (!strcmp(arg, "mboxrd"))
  1764. *opt_value = PATCH_FORMAT_MBOXRD;
  1765. /*
  1766. * Please update $__git_patchformat in git-completion.bash
  1767. * when you add new options
  1768. */
  1769. else
  1770. return error(_("Invalid value for --patch-format: %s"), arg);
  1771. return 0;
  1772. }
  1773. enum resume_type {
  1774. RESUME_FALSE = 0,
  1775. RESUME_APPLY,
  1776. RESUME_RESOLVED,
  1777. RESUME_SKIP,
  1778. RESUME_ABORT,
  1779. RESUME_QUIT,
  1780. RESUME_SHOW_PATCH
  1781. };
  1782. struct resume_mode {
  1783. enum resume_type mode;
  1784. enum show_patch_type sub_mode;
  1785. };
  1786. static int parse_opt_show_current_patch(const struct option *opt, const char *arg, int unset)
  1787. {
  1788. int *opt_value = opt->value;
  1789. struct resume_mode *resume = container_of(opt_value, struct resume_mode, mode);
  1790. /*
  1791. * Please update $__git_showcurrentpatch in git-completion.bash
  1792. * when you add new options
  1793. */
  1794. const char *valid_modes[] = {
  1795. [SHOW_PATCH_DIFF] = "diff",
  1796. [SHOW_PATCH_RAW] = "raw"
  1797. };
  1798. int new_value = SHOW_PATCH_RAW;
  1799. BUG_ON_OPT_NEG(unset);
  1800. if (arg) {
  1801. for (new_value = 0; new_value < ARRAY_SIZE(valid_modes); new_value++) {
  1802. if (!strcmp(arg, valid_modes[new_value]))
  1803. break;
  1804. }
  1805. if (new_value >= ARRAY_SIZE(valid_modes))
  1806. return error(_("Invalid value for --show-current-patch: %s"), arg);
  1807. }
  1808. if (resume->mode == RESUME_SHOW_PATCH && new_value != resume->sub_mode)
  1809. return error(_("--show-current-patch=%s is incompatible with "
  1810. "--show-current-patch=%s"),
  1811. arg, valid_modes[resume->sub_mode]);
  1812. resume->mode = RESUME_SHOW_PATCH;
  1813. resume->sub_mode = new_value;
  1814. return 0;
  1815. }
  1816. static int git_am_config(const char *k, const char *v, void *cb)
  1817. {
  1818. int status;
  1819. status = git_gpg_config(k, v, NULL);
  1820. if (status)
  1821. return status;
  1822. return git_default_config(k, v, NULL);
  1823. }
  1824. int cmd_am(int argc, const char **argv, const char *prefix)
  1825. {
  1826. struct am_state state;
  1827. int binary = -1;
  1828. int keep_cr = -1;
  1829. int patch_format = PATCH_FORMAT_UNKNOWN;
  1830. struct resume_mode resume = { .mode = RESUME_FALSE };
  1831. int in_progress;
  1832. int ret = 0;
  1833. const char * const usage[] = {
  1834. N_("git am [<options>] [(<mbox> | <Maildir>)...]"),
  1835. N_("git am [<options>] (--continue | --skip | --abort)"),
  1836. NULL
  1837. };
  1838. struct option options[] = {
  1839. OPT_BOOL('i', "interactive", &state.interactive,
  1840. N_("run interactively")),
  1841. OPT_HIDDEN_BOOL('b', "binary", &binary,
  1842. N_("historical option -- no-op")),
  1843. OPT_BOOL('3', "3way", &state.threeway,
  1844. N_("allow fall back on 3way merging if needed")),
  1845. OPT__QUIET(&state.quiet, N_("be quiet")),
  1846. OPT_SET_INT('s', "signoff", &state.signoff,
  1847. N_("add a Signed-off-by line to the commit message"),
  1848. SIGNOFF_EXPLICIT),
  1849. OPT_BOOL('u', "utf8", &state.utf8,
  1850. N_("recode into utf8 (default)")),
  1851. OPT_SET_INT('k', "keep", &state.keep,
  1852. N_("pass -k flag to git-mailinfo"), KEEP_TRUE),
  1853. OPT_SET_INT(0, "keep-non-patch", &state.keep,
  1854. N_("pass -b flag to git-mailinfo"), KEEP_NON_PATCH),
  1855. OPT_BOOL('m', "message-id", &state.message_id,
  1856. N_("pass -m flag to git-mailinfo")),
  1857. OPT_SET_INT_F(0, "keep-cr", &keep_cr,
  1858. N_("pass --keep-cr flag to git-mailsplit for mbox format"),
  1859. 1, PARSE_OPT_NONEG),
  1860. OPT_SET_INT_F(0, "no-keep-cr", &keep_cr,
  1861. N_("do not pass --keep-cr flag to git-mailsplit independent of am.keepcr"),
  1862. 0, PARSE_OPT_NONEG),
  1863. OPT_BOOL('c', "scissors", &state.scissors,
  1864. N_("strip everything before a scissors line")),
  1865. OPT_PASSTHRU_ARGV(0, "whitespace", &state.git_apply_opts, N_("action"),
  1866. N_("pass it through git-apply"),
  1867. 0),
  1868. OPT_PASSTHRU_ARGV(0, "ignore-space-change", &state.git_apply_opts, NULL,
  1869. N_("pass it through git-apply"),
  1870. PARSE_OPT_NOARG),
  1871. OPT_PASSTHRU_ARGV(0, "ignore-whitespace", &state.git_apply_opts, NULL,
  1872. N_("pass it through git-apply"),
  1873. PARSE_OPT_NOARG),
  1874. OPT_PASSTHRU_ARGV(0, "directory", &state.git_apply_opts, N_("root"),
  1875. N_("pass it through git-apply"),
  1876. 0),
  1877. OPT_PASSTHRU_ARGV(0, "exclude", &state.git_apply_opts, N_("path"),
  1878. N_("pass it through git-apply"),
  1879. 0),
  1880. OPT_PASSTHRU_ARGV(0, "include", &state.git_apply_opts, N_("path"),
  1881. N_("pass it through git-apply"),
  1882. 0),
  1883. OPT_PASSTHRU_ARGV('C', NULL, &state.git_apply_opts, N_("n"),
  1884. N_("pass it through git-apply"),
  1885. 0),
  1886. OPT_PASSTHRU_ARGV('p', NULL, &state.git_apply_opts, N_("num"),
  1887. N_("pass it through git-apply"),
  1888. 0),
  1889. OPT_CALLBACK(0, "patch-format", &patch_format, N_("format"),
  1890. N_("format the patch(es) are in"),
  1891. parse_opt_patchformat),
  1892. OPT_PASSTHRU_ARGV(0, "reject", &state.git_apply_opts, NULL,
  1893. N_("pass it through git-apply"),
  1894. PARSE_OPT_NOARG),
  1895. OPT_STRING(0, "resolvemsg", &state.resolvemsg, NULL,
  1896. N_("override error message when patch failure occurs")),
  1897. OPT_CMDMODE(0, "continue", &resume.mode,
  1898. N_("continue applying patches after resolving a conflict"),
  1899. RESUME_RESOLVED),
  1900. OPT_CMDMODE('r', "resolved", &resume.mode,
  1901. N_("synonyms for --continue"),
  1902. RESUME_RESOLVED),
  1903. OPT_CMDMODE(0, "skip", &resume.mode,
  1904. N_("skip the current patch"),
  1905. RESUME_SKIP),
  1906. OPT_CMDMODE(0, "abort", &resume.mode,
  1907. N_("restore the original branch and abort the patching operation."),
  1908. RESUME_ABORT),
  1909. OPT_CMDMODE(0, "quit", &resume.mode,
  1910. N_("abort the patching operation but keep HEAD where it is."),
  1911. RESUME_QUIT),
  1912. { OPTION_CALLBACK, 0, "show-current-patch", &resume.mode,
  1913. "(diff|raw)",
  1914. N_("show the patch being applied"),
  1915. PARSE_OPT_CMDMODE | PARSE_OPT_OPTARG | PARSE_OPT_NONEG | PARSE_OPT_LITERAL_ARGHELP,
  1916. parse_opt_show_current_patch, RESUME_SHOW_PATCH },
  1917. OPT_BOOL(0, "committer-date-is-author-date",
  1918. &state.committer_date_is_author_date,
  1919. N_("lie about committer date")),
  1920. OPT_BOOL(0, "ignore-date", &state.ignore_date,
  1921. N_("use current timestamp for author date")),
  1922. OPT_RERERE_AUTOUPDATE(&state.allow_rerere_autoupdate),
  1923. { OPTION_STRING, 'S', "gpg-sign", &state.sign_commit, N_("key-id"),
  1924. N_("GPG-sign commits"),
  1925. PARSE_OPT_OPTARG, NULL, (intptr_t) "" },
  1926. OPT_HIDDEN_BOOL(0, "rebasing", &state.rebasing,
  1927. N_("(internal use for git-rebase)")),
  1928. OPT_END()
  1929. };
  1930. if (argc == 2 && !strcmp(argv[1], "-h"))
  1931. usage_with_options(usage, options);
  1932. git_config(git_am_config, NULL);
  1933. am_state_init(&state);
  1934. in_progress = am_in_progress(&state);
  1935. if (in_progress)
  1936. am_load(&state);
  1937. argc = parse_options(argc, argv, prefix, options, usage, 0);
  1938. if (binary >= 0)
  1939. fprintf_ln(stderr, _("The -b/--binary option has been a no-op for long time, and\n"
  1940. "it will be removed. Please do not use it anymore."));
  1941. /* Ensure a valid committer ident can be constructed */
  1942. git_committer_info(IDENT_STRICT);
  1943. if (repo_read_index_preload(the_repository, NULL, 0) < 0)
  1944. die(_("failed to read the index"));
  1945. if (in_progress) {
  1946. /*
  1947. * Catch user error to feed us patches when there is a session
  1948. * in progress:
  1949. *
  1950. * 1. mbox path(s) are provided on the command-line.
  1951. * 2. stdin is not a tty: the user is trying to feed us a patch
  1952. * from standard input. This is somewhat unreliable -- stdin
  1953. * could be /dev/null for example and the caller did not
  1954. * intend to feed us a patch but wanted to continue
  1955. * unattended.
  1956. */
  1957. if (argc || (resume.mode == RESUME_FALSE && !isatty(0)))
  1958. die(_("previous rebase directory %s still exists but mbox given."),
  1959. state.dir);
  1960. if (resume.mode == RESUME_FALSE)
  1961. resume.mode = RESUME_APPLY;
  1962. if (state.signoff == SIGNOFF_EXPLICIT)
  1963. am_append_signoff(&state);
  1964. } else {
  1965. struct strvec paths = STRVEC_INIT;
  1966. int i;
  1967. /*
  1968. * Handle stray state directory in the independent-run case. In
  1969. * the --rebasing case, it is up to the caller to take care of
  1970. * stray directories.
  1971. */
  1972. if (file_exists(state.dir) && !state.rebasing) {
  1973. if (resume.mode == RESUME_ABORT || resume.mode == RESUME_QUIT) {
  1974. am_destroy(&state);
  1975. am_state_release(&state);
  1976. return 0;
  1977. }
  1978. die(_("Stray %s directory found.\n"
  1979. "Use \"git am --abort\" to remove it."),
  1980. state.dir);
  1981. }
  1982. if (resume.mode)
  1983. die(_("Resolve operation not in progress, we are not resuming."));
  1984. for (i = 0; i < argc; i++) {
  1985. if (is_absolute_path(argv[i]) || !prefix)
  1986. strvec_push(&paths, argv[i]);
  1987. else
  1988. strvec_push(&paths, mkpath("%s/%s", prefix, argv[i]));
  1989. }
  1990. if (state.interactive && !paths.nr)
  1991. die(_("interactive mode requires patches on the command line"));
  1992. am_setup(&state, patch_format, paths.v, keep_cr);
  1993. strvec_clear(&paths);
  1994. }
  1995. switch (resume.mode) {
  1996. case RESUME_FALSE:
  1997. am_run(&state, 0);
  1998. break;
  1999. case RESUME_APPLY:
  2000. am_run(&state, 1);
  2001. break;
  2002. case RESUME_RESOLVED:
  2003. am_resolve(&state);
  2004. break;
  2005. case RESUME_SKIP:
  2006. am_skip(&state);
  2007. break;
  2008. case RESUME_ABORT:
  2009. am_abort(&state);
  2010. break;
  2011. case RESUME_QUIT:
  2012. am_rerere_clear();
  2013. am_destroy(&state);
  2014. break;
  2015. case RESUME_SHOW_PATCH:
  2016. ret = show_patch(&state, resume.sub_mode);
  2017. break;
  2018. default:
  2019. BUG("invalid resume value");
  2020. }
  2021. am_state_release(&state);
  2022. return ret;
  2023. }