merge-recursive.c 116 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909
  1. /*
  2. * Recursive Merge algorithm stolen from git-merge-recursive.py by
  3. * Fredrik Kuivinen.
  4. * The thieves were Alex Riesen and Johannes Schindelin, in June/July 2006
  5. */
  6. #include "cache.h"
  7. #include "merge-recursive.h"
  8. #include "advice.h"
  9. #include "alloc.h"
  10. #include "attr.h"
  11. #include "blob.h"
  12. #include "builtin.h"
  13. #include "cache-tree.h"
  14. #include "commit.h"
  15. #include "commit-reach.h"
  16. #include "config.h"
  17. #include "diff.h"
  18. #include "diffcore.h"
  19. #include "dir.h"
  20. #include "ll-merge.h"
  21. #include "lockfile.h"
  22. #include "object-store.h"
  23. #include "repository.h"
  24. #include "revision.h"
  25. #include "string-list.h"
  26. #include "submodule.h"
  27. #include "tag.h"
  28. #include "tree-walk.h"
  29. #include "unpack-trees.h"
  30. #include "xdiff-interface.h"
  31. struct merge_options_internal {
  32. int call_depth;
  33. int needed_rename_limit;
  34. struct hashmap current_file_dir_set;
  35. struct string_list df_conflict_file_set;
  36. struct unpack_trees_options unpack_opts;
  37. struct index_state orig_index;
  38. };
  39. struct path_hashmap_entry {
  40. struct hashmap_entry e;
  41. char path[FLEX_ARRAY];
  42. };
  43. static int path_hashmap_cmp(const void *cmp_data,
  44. const struct hashmap_entry *eptr,
  45. const struct hashmap_entry *entry_or_key,
  46. const void *keydata)
  47. {
  48. const struct path_hashmap_entry *a, *b;
  49. const char *key = keydata;
  50. a = container_of(eptr, const struct path_hashmap_entry, e);
  51. b = container_of(entry_or_key, const struct path_hashmap_entry, e);
  52. if (ignore_case)
  53. return strcasecmp(a->path, key ? key : b->path);
  54. else
  55. return strcmp(a->path, key ? key : b->path);
  56. }
  57. static unsigned int path_hash(const char *path)
  58. {
  59. return ignore_case ? strihash(path) : strhash(path);
  60. }
  61. /*
  62. * For dir_rename_entry, directory names are stored as a full path from the
  63. * toplevel of the repository and do not include a trailing '/'. Also:
  64. *
  65. * dir: original name of directory being renamed
  66. * non_unique_new_dir: if true, could not determine new_dir
  67. * new_dir: final name of directory being renamed
  68. * possible_new_dirs: temporary used to help determine new_dir; see comments
  69. * in get_directory_renames() for details
  70. */
  71. struct dir_rename_entry {
  72. struct hashmap_entry ent;
  73. char *dir;
  74. unsigned non_unique_new_dir:1;
  75. struct strbuf new_dir;
  76. struct string_list possible_new_dirs;
  77. };
  78. static struct dir_rename_entry *dir_rename_find_entry(struct hashmap *hashmap,
  79. char *dir)
  80. {
  81. struct dir_rename_entry key;
  82. if (dir == NULL)
  83. return NULL;
  84. hashmap_entry_init(&key.ent, strhash(dir));
  85. key.dir = dir;
  86. return hashmap_get_entry(hashmap, &key, ent, NULL);
  87. }
  88. static int dir_rename_cmp(const void *unused_cmp_data,
  89. const struct hashmap_entry *eptr,
  90. const struct hashmap_entry *entry_or_key,
  91. const void *unused_keydata)
  92. {
  93. const struct dir_rename_entry *e1, *e2;
  94. e1 = container_of(eptr, const struct dir_rename_entry, ent);
  95. e2 = container_of(entry_or_key, const struct dir_rename_entry, ent);
  96. return strcmp(e1->dir, e2->dir);
  97. }
  98. static void dir_rename_init(struct hashmap *map)
  99. {
  100. hashmap_init(map, dir_rename_cmp, NULL, 0);
  101. }
  102. static void dir_rename_entry_init(struct dir_rename_entry *entry,
  103. char *directory)
  104. {
  105. hashmap_entry_init(&entry->ent, strhash(directory));
  106. entry->dir = directory;
  107. entry->non_unique_new_dir = 0;
  108. strbuf_init(&entry->new_dir, 0);
  109. string_list_init(&entry->possible_new_dirs, 0);
  110. }
  111. struct collision_entry {
  112. struct hashmap_entry ent;
  113. char *target_file;
  114. struct string_list source_files;
  115. unsigned reported_already:1;
  116. };
  117. static struct collision_entry *collision_find_entry(struct hashmap *hashmap,
  118. char *target_file)
  119. {
  120. struct collision_entry key;
  121. hashmap_entry_init(&key.ent, strhash(target_file));
  122. key.target_file = target_file;
  123. return hashmap_get_entry(hashmap, &key, ent, NULL);
  124. }
  125. static int collision_cmp(const void *unused_cmp_data,
  126. const struct hashmap_entry *eptr,
  127. const struct hashmap_entry *entry_or_key,
  128. const void *unused_keydata)
  129. {
  130. const struct collision_entry *e1, *e2;
  131. e1 = container_of(eptr, const struct collision_entry, ent);
  132. e2 = container_of(entry_or_key, const struct collision_entry, ent);
  133. return strcmp(e1->target_file, e2->target_file);
  134. }
  135. static void collision_init(struct hashmap *map)
  136. {
  137. hashmap_init(map, collision_cmp, NULL, 0);
  138. }
  139. static void flush_output(struct merge_options *opt)
  140. {
  141. if (opt->buffer_output < 2 && opt->obuf.len) {
  142. fputs(opt->obuf.buf, stdout);
  143. strbuf_reset(&opt->obuf);
  144. }
  145. }
  146. static int err(struct merge_options *opt, const char *err, ...)
  147. {
  148. va_list params;
  149. if (opt->buffer_output < 2)
  150. flush_output(opt);
  151. else {
  152. strbuf_complete(&opt->obuf, '\n');
  153. strbuf_addstr(&opt->obuf, "error: ");
  154. }
  155. va_start(params, err);
  156. strbuf_vaddf(&opt->obuf, err, params);
  157. va_end(params);
  158. if (opt->buffer_output > 1)
  159. strbuf_addch(&opt->obuf, '\n');
  160. else {
  161. error("%s", opt->obuf.buf);
  162. strbuf_reset(&opt->obuf);
  163. }
  164. return -1;
  165. }
  166. static struct tree *shift_tree_object(struct repository *repo,
  167. struct tree *one, struct tree *two,
  168. const char *subtree_shift)
  169. {
  170. struct object_id shifted;
  171. if (!*subtree_shift) {
  172. shift_tree(repo, &one->object.oid, &two->object.oid, &shifted, 0);
  173. } else {
  174. shift_tree_by(repo, &one->object.oid, &two->object.oid, &shifted,
  175. subtree_shift);
  176. }
  177. if (oideq(&two->object.oid, &shifted))
  178. return two;
  179. return lookup_tree(repo, &shifted);
  180. }
  181. static inline void set_commit_tree(struct commit *c, struct tree *t)
  182. {
  183. c->maybe_tree = t;
  184. }
  185. static struct commit *make_virtual_commit(struct repository *repo,
  186. struct tree *tree,
  187. const char *comment)
  188. {
  189. struct commit *commit = alloc_commit_node(repo);
  190. set_merge_remote_desc(commit, comment, (struct object *)commit);
  191. set_commit_tree(commit, tree);
  192. commit->object.parsed = 1;
  193. return commit;
  194. }
  195. enum rename_type {
  196. RENAME_NORMAL = 0,
  197. RENAME_VIA_DIR,
  198. RENAME_ADD,
  199. RENAME_DELETE,
  200. RENAME_ONE_FILE_TO_ONE,
  201. RENAME_ONE_FILE_TO_TWO,
  202. RENAME_TWO_FILES_TO_ONE
  203. };
  204. /*
  205. * Since we want to write the index eventually, we cannot reuse the index
  206. * for these (temporary) data.
  207. */
  208. struct stage_data {
  209. struct diff_filespec stages[4]; /* mostly for oid & mode; maybe path */
  210. struct rename_conflict_info *rename_conflict_info;
  211. unsigned processed:1;
  212. };
  213. struct rename {
  214. unsigned processed:1;
  215. struct diff_filepair *pair;
  216. const char *branch; /* branch that the rename occurred on */
  217. /*
  218. * If directory rename detection affected this rename, what was its
  219. * original type ('A' or 'R') and it's original destination before
  220. * the directory rename (otherwise, '\0' and NULL for these two vars).
  221. */
  222. char dir_rename_original_type;
  223. char *dir_rename_original_dest;
  224. /*
  225. * Purpose of src_entry and dst_entry:
  226. *
  227. * If 'before' is renamed to 'after' then src_entry will contain
  228. * the versions of 'before' from the merge_base, HEAD, and MERGE in
  229. * stages 1, 2, and 3; dst_entry will contain the respective
  230. * versions of 'after' in corresponding locations. Thus, we have a
  231. * total of six modes and oids, though some will be null. (Stage 0
  232. * is ignored; we're interested in handling conflicts.)
  233. *
  234. * Since we don't turn on break-rewrites by default, neither
  235. * src_entry nor dst_entry can have all three of their stages have
  236. * non-null oids, meaning at most four of the six will be non-null.
  237. * Also, since this is a rename, both src_entry and dst_entry will
  238. * have at least one non-null oid, meaning at least two will be
  239. * non-null. Of the six oids, a typical rename will have three be
  240. * non-null. Only two implies a rename/delete, and four implies a
  241. * rename/add.
  242. */
  243. struct stage_data *src_entry;
  244. struct stage_data *dst_entry;
  245. };
  246. struct rename_conflict_info {
  247. enum rename_type rename_type;
  248. struct rename *ren1;
  249. struct rename *ren2;
  250. };
  251. static inline void setup_rename_conflict_info(enum rename_type rename_type,
  252. struct merge_options *opt,
  253. struct rename *ren1,
  254. struct rename *ren2)
  255. {
  256. struct rename_conflict_info *ci;
  257. /*
  258. * When we have two renames involved, it's easiest to get the
  259. * correct things into stage 2 and 3, and to make sure that the
  260. * content merge puts HEAD before the other branch if we just
  261. * ensure that branch1 == opt->branch1. So, simply flip arguments
  262. * around if we don't have that.
  263. */
  264. if (ren2 && ren1->branch != opt->branch1) {
  265. setup_rename_conflict_info(rename_type, opt, ren2, ren1);
  266. return;
  267. }
  268. ci = xcalloc(1, sizeof(struct rename_conflict_info));
  269. ci->rename_type = rename_type;
  270. ci->ren1 = ren1;
  271. ci->ren2 = ren2;
  272. ci->ren1->dst_entry->processed = 0;
  273. ci->ren1->dst_entry->rename_conflict_info = ci;
  274. if (ren2) {
  275. ci->ren2->dst_entry->rename_conflict_info = ci;
  276. }
  277. }
  278. static int show(struct merge_options *opt, int v)
  279. {
  280. return (!opt->priv->call_depth && opt->verbosity >= v) ||
  281. opt->verbosity >= 5;
  282. }
  283. __attribute__((format (printf, 3, 4)))
  284. static void output(struct merge_options *opt, int v, const char *fmt, ...)
  285. {
  286. va_list ap;
  287. if (!show(opt, v))
  288. return;
  289. strbuf_addchars(&opt->obuf, ' ', opt->priv->call_depth * 2);
  290. va_start(ap, fmt);
  291. strbuf_vaddf(&opt->obuf, fmt, ap);
  292. va_end(ap);
  293. strbuf_addch(&opt->obuf, '\n');
  294. if (!opt->buffer_output)
  295. flush_output(opt);
  296. }
  297. static void output_commit_title(struct merge_options *opt, struct commit *commit)
  298. {
  299. struct merge_remote_desc *desc;
  300. strbuf_addchars(&opt->obuf, ' ', opt->priv->call_depth * 2);
  301. desc = merge_remote_util(commit);
  302. if (desc)
  303. strbuf_addf(&opt->obuf, "virtual %s\n", desc->name);
  304. else {
  305. strbuf_add_unique_abbrev(&opt->obuf, &commit->object.oid,
  306. DEFAULT_ABBREV);
  307. strbuf_addch(&opt->obuf, ' ');
  308. if (parse_commit(commit) != 0)
  309. strbuf_addstr(&opt->obuf, _("(bad commit)\n"));
  310. else {
  311. const char *title;
  312. const char *msg = get_commit_buffer(commit, NULL);
  313. int len = find_commit_subject(msg, &title);
  314. if (len)
  315. strbuf_addf(&opt->obuf, "%.*s\n", len, title);
  316. unuse_commit_buffer(commit, msg);
  317. }
  318. }
  319. flush_output(opt);
  320. }
  321. static int add_cacheinfo(struct merge_options *opt,
  322. const struct diff_filespec *blob,
  323. const char *path, int stage, int refresh, int options)
  324. {
  325. struct index_state *istate = opt->repo->index;
  326. struct cache_entry *ce;
  327. int ret;
  328. ce = make_cache_entry(istate, blob->mode, &blob->oid, path, stage, 0);
  329. if (!ce)
  330. return err(opt, _("add_cacheinfo failed for path '%s'; merge aborting."), path);
  331. ret = add_index_entry(istate, ce, options);
  332. if (refresh) {
  333. struct cache_entry *nce;
  334. nce = refresh_cache_entry(istate, ce,
  335. CE_MATCH_REFRESH | CE_MATCH_IGNORE_MISSING);
  336. if (!nce)
  337. return err(opt, _("add_cacheinfo failed to refresh for path '%s'; merge aborting."), path);
  338. if (nce != ce)
  339. ret = add_index_entry(istate, nce, options);
  340. }
  341. return ret;
  342. }
  343. static inline int merge_detect_rename(struct merge_options *opt)
  344. {
  345. return (opt->detect_renames >= 0) ? opt->detect_renames : 1;
  346. }
  347. static void init_tree_desc_from_tree(struct tree_desc *desc, struct tree *tree)
  348. {
  349. parse_tree(tree);
  350. init_tree_desc(desc, tree->buffer, tree->size);
  351. }
  352. static int unpack_trees_start(struct merge_options *opt,
  353. struct tree *common,
  354. struct tree *head,
  355. struct tree *merge)
  356. {
  357. int rc;
  358. struct tree_desc t[3];
  359. struct index_state tmp_index = { NULL };
  360. memset(&opt->priv->unpack_opts, 0, sizeof(opt->priv->unpack_opts));
  361. if (opt->priv->call_depth)
  362. opt->priv->unpack_opts.index_only = 1;
  363. else
  364. opt->priv->unpack_opts.update = 1;
  365. opt->priv->unpack_opts.merge = 1;
  366. opt->priv->unpack_opts.head_idx = 2;
  367. opt->priv->unpack_opts.fn = threeway_merge;
  368. opt->priv->unpack_opts.src_index = opt->repo->index;
  369. opt->priv->unpack_opts.dst_index = &tmp_index;
  370. opt->priv->unpack_opts.aggressive = !merge_detect_rename(opt);
  371. setup_unpack_trees_porcelain(&opt->priv->unpack_opts, "merge");
  372. init_tree_desc_from_tree(t+0, common);
  373. init_tree_desc_from_tree(t+1, head);
  374. init_tree_desc_from_tree(t+2, merge);
  375. rc = unpack_trees(3, t, &opt->priv->unpack_opts);
  376. cache_tree_free(&opt->repo->index->cache_tree);
  377. /*
  378. * Update opt->repo->index to match the new results, AFTER saving a
  379. * copy in opt->priv->orig_index. Update src_index to point to the
  380. * saved copy. (verify_uptodate() checks src_index, and the original
  381. * index is the one that had the necessary modification timestamps.)
  382. */
  383. opt->priv->orig_index = *opt->repo->index;
  384. *opt->repo->index = tmp_index;
  385. opt->priv->unpack_opts.src_index = &opt->priv->orig_index;
  386. return rc;
  387. }
  388. static void unpack_trees_finish(struct merge_options *opt)
  389. {
  390. discard_index(&opt->priv->orig_index);
  391. clear_unpack_trees_porcelain(&opt->priv->unpack_opts);
  392. }
  393. static int save_files_dirs(const struct object_id *oid,
  394. struct strbuf *base, const char *path,
  395. unsigned int mode, int stage, void *context)
  396. {
  397. struct path_hashmap_entry *entry;
  398. int baselen = base->len;
  399. struct merge_options *opt = context;
  400. strbuf_addstr(base, path);
  401. FLEX_ALLOC_MEM(entry, path, base->buf, base->len);
  402. hashmap_entry_init(&entry->e, path_hash(entry->path));
  403. hashmap_add(&opt->priv->current_file_dir_set, &entry->e);
  404. strbuf_setlen(base, baselen);
  405. return (S_ISDIR(mode) ? READ_TREE_RECURSIVE : 0);
  406. }
  407. static void get_files_dirs(struct merge_options *opt, struct tree *tree)
  408. {
  409. struct pathspec match_all;
  410. memset(&match_all, 0, sizeof(match_all));
  411. read_tree_recursive(opt->repo, tree, "", 0, 0,
  412. &match_all, save_files_dirs, opt);
  413. }
  414. static int get_tree_entry_if_blob(struct repository *r,
  415. const struct object_id *tree,
  416. const char *path,
  417. struct diff_filespec *dfs)
  418. {
  419. int ret;
  420. ret = get_tree_entry(r, tree, path, &dfs->oid, &dfs->mode);
  421. if (S_ISDIR(dfs->mode)) {
  422. oidcpy(&dfs->oid, &null_oid);
  423. dfs->mode = 0;
  424. }
  425. return ret;
  426. }
  427. /*
  428. * Returns an index_entry instance which doesn't have to correspond to
  429. * a real cache entry in Git's index.
  430. */
  431. static struct stage_data *insert_stage_data(struct repository *r,
  432. const char *path,
  433. struct tree *o, struct tree *a, struct tree *b,
  434. struct string_list *entries)
  435. {
  436. struct string_list_item *item;
  437. struct stage_data *e = xcalloc(1, sizeof(struct stage_data));
  438. get_tree_entry_if_blob(r, &o->object.oid, path, &e->stages[1]);
  439. get_tree_entry_if_blob(r, &a->object.oid, path, &e->stages[2]);
  440. get_tree_entry_if_blob(r, &b->object.oid, path, &e->stages[3]);
  441. item = string_list_insert(entries, path);
  442. item->util = e;
  443. return e;
  444. }
  445. /*
  446. * Create a dictionary mapping file names to stage_data objects. The
  447. * dictionary contains one entry for every path with a non-zero stage entry.
  448. */
  449. static struct string_list *get_unmerged(struct index_state *istate)
  450. {
  451. struct string_list *unmerged = xcalloc(1, sizeof(struct string_list));
  452. int i;
  453. unmerged->strdup_strings = 1;
  454. for (i = 0; i < istate->cache_nr; i++) {
  455. struct string_list_item *item;
  456. struct stage_data *e;
  457. const struct cache_entry *ce = istate->cache[i];
  458. if (!ce_stage(ce))
  459. continue;
  460. item = string_list_lookup(unmerged, ce->name);
  461. if (!item) {
  462. item = string_list_insert(unmerged, ce->name);
  463. item->util = xcalloc(1, sizeof(struct stage_data));
  464. }
  465. e = item->util;
  466. e->stages[ce_stage(ce)].mode = ce->ce_mode;
  467. oidcpy(&e->stages[ce_stage(ce)].oid, &ce->oid);
  468. }
  469. return unmerged;
  470. }
  471. static int string_list_df_name_compare(const char *one, const char *two)
  472. {
  473. int onelen = strlen(one);
  474. int twolen = strlen(two);
  475. /*
  476. * Here we only care that entries for D/F conflicts are
  477. * adjacent, in particular with the file of the D/F conflict
  478. * appearing before files below the corresponding directory.
  479. * The order of the rest of the list is irrelevant for us.
  480. *
  481. * To achieve this, we sort with df_name_compare and provide
  482. * the mode S_IFDIR so that D/F conflicts will sort correctly.
  483. * We use the mode S_IFDIR for everything else for simplicity,
  484. * since in other cases any changes in their order due to
  485. * sorting cause no problems for us.
  486. */
  487. int cmp = df_name_compare(one, onelen, S_IFDIR,
  488. two, twolen, S_IFDIR);
  489. /*
  490. * Now that 'foo' and 'foo/bar' compare equal, we have to make sure
  491. * that 'foo' comes before 'foo/bar'.
  492. */
  493. if (cmp)
  494. return cmp;
  495. return onelen - twolen;
  496. }
  497. static void record_df_conflict_files(struct merge_options *opt,
  498. struct string_list *entries)
  499. {
  500. /* If there is a D/F conflict and the file for such a conflict
  501. * currently exists in the working tree, we want to allow it to be
  502. * removed to make room for the corresponding directory if needed.
  503. * The files underneath the directories of such D/F conflicts will
  504. * be processed before the corresponding file involved in the D/F
  505. * conflict. If the D/F directory ends up being removed by the
  506. * merge, then we won't have to touch the D/F file. If the D/F
  507. * directory needs to be written to the working copy, then the D/F
  508. * file will simply be removed (in make_room_for_path()) to make
  509. * room for the necessary paths. Note that if both the directory
  510. * and the file need to be present, then the D/F file will be
  511. * reinstated with a new unique name at the time it is processed.
  512. */
  513. struct string_list df_sorted_entries = STRING_LIST_INIT_NODUP;
  514. const char *last_file = NULL;
  515. int last_len = 0;
  516. int i;
  517. /*
  518. * If we're merging merge-bases, we don't want to bother with
  519. * any working directory changes.
  520. */
  521. if (opt->priv->call_depth)
  522. return;
  523. /* Ensure D/F conflicts are adjacent in the entries list. */
  524. for (i = 0; i < entries->nr; i++) {
  525. struct string_list_item *next = &entries->items[i];
  526. string_list_append(&df_sorted_entries, next->string)->util =
  527. next->util;
  528. }
  529. df_sorted_entries.cmp = string_list_df_name_compare;
  530. string_list_sort(&df_sorted_entries);
  531. string_list_clear(&opt->priv->df_conflict_file_set, 1);
  532. for (i = 0; i < df_sorted_entries.nr; i++) {
  533. const char *path = df_sorted_entries.items[i].string;
  534. int len = strlen(path);
  535. struct stage_data *e = df_sorted_entries.items[i].util;
  536. /*
  537. * Check if last_file & path correspond to a D/F conflict;
  538. * i.e. whether path is last_file+'/'+<something>.
  539. * If so, record that it's okay to remove last_file to make
  540. * room for path and friends if needed.
  541. */
  542. if (last_file &&
  543. len > last_len &&
  544. memcmp(path, last_file, last_len) == 0 &&
  545. path[last_len] == '/') {
  546. string_list_insert(&opt->priv->df_conflict_file_set, last_file);
  547. }
  548. /*
  549. * Determine whether path could exist as a file in the
  550. * working directory as a possible D/F conflict. This
  551. * will only occur when it exists in stage 2 as a
  552. * file.
  553. */
  554. if (S_ISREG(e->stages[2].mode) || S_ISLNK(e->stages[2].mode)) {
  555. last_file = path;
  556. last_len = len;
  557. } else {
  558. last_file = NULL;
  559. }
  560. }
  561. string_list_clear(&df_sorted_entries, 0);
  562. }
  563. static int update_stages(struct merge_options *opt, const char *path,
  564. const struct diff_filespec *o,
  565. const struct diff_filespec *a,
  566. const struct diff_filespec *b)
  567. {
  568. /*
  569. * NOTE: It is usually a bad idea to call update_stages on a path
  570. * before calling update_file on that same path, since it can
  571. * sometimes lead to spurious "refusing to lose untracked file..."
  572. * messages from update_file (via make_room_for path via
  573. * would_lose_untracked). Instead, reverse the order of the calls
  574. * (executing update_file first and then update_stages).
  575. */
  576. int clear = 1;
  577. int options = ADD_CACHE_OK_TO_ADD | ADD_CACHE_SKIP_DFCHECK;
  578. if (clear)
  579. if (remove_file_from_index(opt->repo->index, path))
  580. return -1;
  581. if (o)
  582. if (add_cacheinfo(opt, o, path, 1, 0, options))
  583. return -1;
  584. if (a)
  585. if (add_cacheinfo(opt, a, path, 2, 0, options))
  586. return -1;
  587. if (b)
  588. if (add_cacheinfo(opt, b, path, 3, 0, options))
  589. return -1;
  590. return 0;
  591. }
  592. static void update_entry(struct stage_data *entry,
  593. struct diff_filespec *o,
  594. struct diff_filespec *a,
  595. struct diff_filespec *b)
  596. {
  597. entry->processed = 0;
  598. entry->stages[1].mode = o->mode;
  599. entry->stages[2].mode = a->mode;
  600. entry->stages[3].mode = b->mode;
  601. oidcpy(&entry->stages[1].oid, &o->oid);
  602. oidcpy(&entry->stages[2].oid, &a->oid);
  603. oidcpy(&entry->stages[3].oid, &b->oid);
  604. }
  605. static int remove_file(struct merge_options *opt, int clean,
  606. const char *path, int no_wd)
  607. {
  608. int update_cache = opt->priv->call_depth || clean;
  609. int update_working_directory = !opt->priv->call_depth && !no_wd;
  610. if (update_cache) {
  611. if (remove_file_from_index(opt->repo->index, path))
  612. return -1;
  613. }
  614. if (update_working_directory) {
  615. if (ignore_case) {
  616. struct cache_entry *ce;
  617. ce = index_file_exists(opt->repo->index, path, strlen(path),
  618. ignore_case);
  619. if (ce && ce_stage(ce) == 0 && strcmp(path, ce->name))
  620. return 0;
  621. }
  622. if (remove_path(path))
  623. return -1;
  624. }
  625. return 0;
  626. }
  627. /* add a string to a strbuf, but converting "/" to "_" */
  628. static void add_flattened_path(struct strbuf *out, const char *s)
  629. {
  630. size_t i = out->len;
  631. strbuf_addstr(out, s);
  632. for (; i < out->len; i++)
  633. if (out->buf[i] == '/')
  634. out->buf[i] = '_';
  635. }
  636. static char *unique_path(struct merge_options *opt,
  637. const char *path,
  638. const char *branch)
  639. {
  640. struct path_hashmap_entry *entry;
  641. struct strbuf newpath = STRBUF_INIT;
  642. int suffix = 0;
  643. size_t base_len;
  644. strbuf_addf(&newpath, "%s~", path);
  645. add_flattened_path(&newpath, branch);
  646. base_len = newpath.len;
  647. while (hashmap_get_from_hash(&opt->priv->current_file_dir_set,
  648. path_hash(newpath.buf), newpath.buf) ||
  649. (!opt->priv->call_depth && file_exists(newpath.buf))) {
  650. strbuf_setlen(&newpath, base_len);
  651. strbuf_addf(&newpath, "_%d", suffix++);
  652. }
  653. FLEX_ALLOC_MEM(entry, path, newpath.buf, newpath.len);
  654. hashmap_entry_init(&entry->e, path_hash(entry->path));
  655. hashmap_add(&opt->priv->current_file_dir_set, &entry->e);
  656. return strbuf_detach(&newpath, NULL);
  657. }
  658. /**
  659. * Check whether a directory in the index is in the way of an incoming
  660. * file. Return 1 if so. If check_working_copy is non-zero, also
  661. * check the working directory. If empty_ok is non-zero, also return
  662. * 0 in the case where the working-tree dir exists but is empty.
  663. */
  664. static int dir_in_way(struct index_state *istate, const char *path,
  665. int check_working_copy, int empty_ok)
  666. {
  667. int pos;
  668. struct strbuf dirpath = STRBUF_INIT;
  669. struct stat st;
  670. strbuf_addstr(&dirpath, path);
  671. strbuf_addch(&dirpath, '/');
  672. pos = index_name_pos(istate, dirpath.buf, dirpath.len);
  673. if (pos < 0)
  674. pos = -1 - pos;
  675. if (pos < istate->cache_nr &&
  676. !strncmp(dirpath.buf, istate->cache[pos]->name, dirpath.len)) {
  677. strbuf_release(&dirpath);
  678. return 1;
  679. }
  680. strbuf_release(&dirpath);
  681. return check_working_copy && !lstat(path, &st) && S_ISDIR(st.st_mode) &&
  682. !(empty_ok && is_empty_dir(path)) &&
  683. !has_symlink_leading_path(path, strlen(path));
  684. }
  685. /*
  686. * Returns whether path was tracked in the index before the merge started,
  687. * and its oid and mode match the specified values
  688. */
  689. static int was_tracked_and_matches(struct merge_options *opt, const char *path,
  690. const struct diff_filespec *blob)
  691. {
  692. int pos = index_name_pos(&opt->priv->orig_index, path, strlen(path));
  693. struct cache_entry *ce;
  694. if (0 > pos)
  695. /* we were not tracking this path before the merge */
  696. return 0;
  697. /* See if the file we were tracking before matches */
  698. ce = opt->priv->orig_index.cache[pos];
  699. return (oideq(&ce->oid, &blob->oid) && ce->ce_mode == blob->mode);
  700. }
  701. /*
  702. * Returns whether path was tracked in the index before the merge started
  703. */
  704. static int was_tracked(struct merge_options *opt, const char *path)
  705. {
  706. int pos = index_name_pos(&opt->priv->orig_index, path, strlen(path));
  707. if (0 <= pos)
  708. /* we were tracking this path before the merge */
  709. return 1;
  710. return 0;
  711. }
  712. static int would_lose_untracked(struct merge_options *opt, const char *path)
  713. {
  714. struct index_state *istate = opt->repo->index;
  715. /*
  716. * This may look like it can be simplified to:
  717. * return !was_tracked(opt, path) && file_exists(path)
  718. * but it can't. This function needs to know whether path was in
  719. * the working tree due to EITHER having been tracked in the index
  720. * before the merge OR having been put into the working copy and
  721. * index by unpack_trees(). Due to that either-or requirement, we
  722. * check the current index instead of the original one.
  723. *
  724. * Note that we do not need to worry about merge-recursive itself
  725. * updating the index after unpack_trees() and before calling this
  726. * function, because we strictly require all code paths in
  727. * merge-recursive to update the working tree first and the index
  728. * second. Doing otherwise would break
  729. * update_file()/would_lose_untracked(); see every comment in this
  730. * file which mentions "update_stages".
  731. */
  732. int pos = index_name_pos(istate, path, strlen(path));
  733. if (pos < 0)
  734. pos = -1 - pos;
  735. while (pos < istate->cache_nr &&
  736. !strcmp(path, istate->cache[pos]->name)) {
  737. /*
  738. * If stage #0, it is definitely tracked.
  739. * If it has stage #2 then it was tracked
  740. * before this merge started. All other
  741. * cases the path was not tracked.
  742. */
  743. switch (ce_stage(istate->cache[pos])) {
  744. case 0:
  745. case 2:
  746. return 0;
  747. }
  748. pos++;
  749. }
  750. return file_exists(path);
  751. }
  752. static int was_dirty(struct merge_options *opt, const char *path)
  753. {
  754. struct cache_entry *ce;
  755. int dirty = 1;
  756. if (opt->priv->call_depth || !was_tracked(opt, path))
  757. return !dirty;
  758. ce = index_file_exists(opt->priv->unpack_opts.src_index,
  759. path, strlen(path), ignore_case);
  760. dirty = verify_uptodate(ce, &opt->priv->unpack_opts) != 0;
  761. return dirty;
  762. }
  763. static int make_room_for_path(struct merge_options *opt, const char *path)
  764. {
  765. int status, i;
  766. const char *msg = _("failed to create path '%s'%s");
  767. /* Unlink any D/F conflict files that are in the way */
  768. for (i = 0; i < opt->priv->df_conflict_file_set.nr; i++) {
  769. const char *df_path = opt->priv->df_conflict_file_set.items[i].string;
  770. size_t pathlen = strlen(path);
  771. size_t df_pathlen = strlen(df_path);
  772. if (df_pathlen < pathlen &&
  773. path[df_pathlen] == '/' &&
  774. strncmp(path, df_path, df_pathlen) == 0) {
  775. output(opt, 3,
  776. _("Removing %s to make room for subdirectory\n"),
  777. df_path);
  778. unlink(df_path);
  779. unsorted_string_list_delete_item(&opt->priv->df_conflict_file_set,
  780. i, 0);
  781. break;
  782. }
  783. }
  784. /* Make sure leading directories are created */
  785. status = safe_create_leading_directories_const(path);
  786. if (status) {
  787. if (status == SCLD_EXISTS)
  788. /* something else exists */
  789. return err(opt, msg, path, _(": perhaps a D/F conflict?"));
  790. return err(opt, msg, path, "");
  791. }
  792. /*
  793. * Do not unlink a file in the work tree if we are not
  794. * tracking it.
  795. */
  796. if (would_lose_untracked(opt, path))
  797. return err(opt, _("refusing to lose untracked file at '%s'"),
  798. path);
  799. /* Successful unlink is good.. */
  800. if (!unlink(path))
  801. return 0;
  802. /* .. and so is no existing file */
  803. if (errno == ENOENT)
  804. return 0;
  805. /* .. but not some other error (who really cares what?) */
  806. return err(opt, msg, path, _(": perhaps a D/F conflict?"));
  807. }
  808. static int update_file_flags(struct merge_options *opt,
  809. const struct diff_filespec *contents,
  810. const char *path,
  811. int update_cache,
  812. int update_wd)
  813. {
  814. int ret = 0;
  815. if (opt->priv->call_depth)
  816. update_wd = 0;
  817. if (update_wd) {
  818. enum object_type type;
  819. void *buf;
  820. unsigned long size;
  821. if (S_ISGITLINK(contents->mode)) {
  822. /*
  823. * We may later decide to recursively descend into
  824. * the submodule directory and update its index
  825. * and/or work tree, but we do not do that now.
  826. */
  827. update_wd = 0;
  828. goto update_index;
  829. }
  830. buf = read_object_file(&contents->oid, &type, &size);
  831. if (!buf) {
  832. ret = err(opt, _("cannot read object %s '%s'"),
  833. oid_to_hex(&contents->oid), path);
  834. goto free_buf;
  835. }
  836. if (type != OBJ_BLOB) {
  837. ret = err(opt, _("blob expected for %s '%s'"),
  838. oid_to_hex(&contents->oid), path);
  839. goto free_buf;
  840. }
  841. if (S_ISREG(contents->mode)) {
  842. struct strbuf strbuf = STRBUF_INIT;
  843. if (convert_to_working_tree(opt->repo->index,
  844. path, buf, size, &strbuf, NULL)) {
  845. free(buf);
  846. size = strbuf.len;
  847. buf = strbuf_detach(&strbuf, NULL);
  848. }
  849. }
  850. if (make_room_for_path(opt, path) < 0) {
  851. update_wd = 0;
  852. goto free_buf;
  853. }
  854. if (S_ISREG(contents->mode) ||
  855. (!has_symlinks && S_ISLNK(contents->mode))) {
  856. int fd;
  857. int mode = (contents->mode & 0100 ? 0777 : 0666);
  858. fd = open(path, O_WRONLY | O_TRUNC | O_CREAT, mode);
  859. if (fd < 0) {
  860. ret = err(opt, _("failed to open '%s': %s"),
  861. path, strerror(errno));
  862. goto free_buf;
  863. }
  864. write_in_full(fd, buf, size);
  865. close(fd);
  866. } else if (S_ISLNK(contents->mode)) {
  867. char *lnk = xmemdupz(buf, size);
  868. safe_create_leading_directories_const(path);
  869. unlink(path);
  870. if (symlink(lnk, path))
  871. ret = err(opt, _("failed to symlink '%s': %s"),
  872. path, strerror(errno));
  873. free(lnk);
  874. } else
  875. ret = err(opt,
  876. _("do not know what to do with %06o %s '%s'"),
  877. contents->mode, oid_to_hex(&contents->oid), path);
  878. free_buf:
  879. free(buf);
  880. }
  881. update_index:
  882. if (!ret && update_cache) {
  883. int refresh = (!opt->priv->call_depth &&
  884. contents->mode != S_IFGITLINK);
  885. if (add_cacheinfo(opt, contents, path, 0, refresh,
  886. ADD_CACHE_OK_TO_ADD))
  887. return -1;
  888. }
  889. return ret;
  890. }
  891. static int update_file(struct merge_options *opt,
  892. int clean,
  893. const struct diff_filespec *contents,
  894. const char *path)
  895. {
  896. return update_file_flags(opt, contents, path,
  897. opt->priv->call_depth || clean, !opt->priv->call_depth);
  898. }
  899. /* Low level file merging, update and removal */
  900. struct merge_file_info {
  901. struct diff_filespec blob; /* mostly use oid & mode; sometimes path */
  902. unsigned clean:1,
  903. merge:1;
  904. };
  905. static int merge_3way(struct merge_options *opt,
  906. mmbuffer_t *result_buf,
  907. const struct diff_filespec *o,
  908. const struct diff_filespec *a,
  909. const struct diff_filespec *b,
  910. const char *branch1,
  911. const char *branch2,
  912. const int extra_marker_size)
  913. {
  914. mmfile_t orig, src1, src2;
  915. struct ll_merge_options ll_opts = {0};
  916. char *base, *name1, *name2;
  917. int merge_status;
  918. ll_opts.renormalize = opt->renormalize;
  919. ll_opts.extra_marker_size = extra_marker_size;
  920. ll_opts.xdl_opts = opt->xdl_opts;
  921. if (opt->priv->call_depth) {
  922. ll_opts.virtual_ancestor = 1;
  923. ll_opts.variant = 0;
  924. } else {
  925. switch (opt->recursive_variant) {
  926. case MERGE_VARIANT_OURS:
  927. ll_opts.variant = XDL_MERGE_FAVOR_OURS;
  928. break;
  929. case MERGE_VARIANT_THEIRS:
  930. ll_opts.variant = XDL_MERGE_FAVOR_THEIRS;
  931. break;
  932. default:
  933. ll_opts.variant = 0;
  934. break;
  935. }
  936. }
  937. assert(a->path && b->path && o->path && opt->ancestor);
  938. if (strcmp(a->path, b->path) || strcmp(a->path, o->path) != 0) {
  939. base = mkpathdup("%s:%s", opt->ancestor, o->path);
  940. name1 = mkpathdup("%s:%s", branch1, a->path);
  941. name2 = mkpathdup("%s:%s", branch2, b->path);
  942. } else {
  943. base = mkpathdup("%s", opt->ancestor);
  944. name1 = mkpathdup("%s", branch1);
  945. name2 = mkpathdup("%s", branch2);
  946. }
  947. read_mmblob(&orig, &o->oid);
  948. read_mmblob(&src1, &a->oid);
  949. read_mmblob(&src2, &b->oid);
  950. merge_status = ll_merge(result_buf, a->path, &orig, base,
  951. &src1, name1, &src2, name2,
  952. opt->repo->index, &ll_opts);
  953. free(base);
  954. free(name1);
  955. free(name2);
  956. free(orig.ptr);
  957. free(src1.ptr);
  958. free(src2.ptr);
  959. return merge_status;
  960. }
  961. static int find_first_merges(struct repository *repo,
  962. struct object_array *result, const char *path,
  963. struct commit *a, struct commit *b)
  964. {
  965. int i, j;
  966. struct object_array merges = OBJECT_ARRAY_INIT;
  967. struct commit *commit;
  968. int contains_another;
  969. char merged_revision[GIT_MAX_HEXSZ + 2];
  970. const char *rev_args[] = { "rev-list", "--merges", "--ancestry-path",
  971. "--all", merged_revision, NULL };
  972. struct rev_info revs;
  973. struct setup_revision_opt rev_opts;
  974. memset(result, 0, sizeof(struct object_array));
  975. memset(&rev_opts, 0, sizeof(rev_opts));
  976. /* get all revisions that merge commit a */
  977. xsnprintf(merged_revision, sizeof(merged_revision), "^%s",
  978. oid_to_hex(&a->object.oid));
  979. repo_init_revisions(repo, &revs, NULL);
  980. rev_opts.submodule = path;
  981. /* FIXME: can't handle linked worktrees in submodules yet */
  982. revs.single_worktree = path != NULL;
  983. setup_revisions(ARRAY_SIZE(rev_args)-1, rev_args, &revs, &rev_opts);
  984. /* save all revisions from the above list that contain b */
  985. if (prepare_revision_walk(&revs))
  986. die("revision walk setup failed");
  987. while ((commit = get_revision(&revs)) != NULL) {
  988. struct object *o = &(commit->object);
  989. if (in_merge_bases(b, commit))
  990. add_object_array(o, NULL, &merges);
  991. }
  992. reset_revision_walk();
  993. /* Now we've got all merges that contain a and b. Prune all
  994. * merges that contain another found merge and save them in
  995. * result.
  996. */
  997. for (i = 0; i < merges.nr; i++) {
  998. struct commit *m1 = (struct commit *) merges.objects[i].item;
  999. contains_another = 0;
  1000. for (j = 0; j < merges.nr; j++) {
  1001. struct commit *m2 = (struct commit *) merges.objects[j].item;
  1002. if (i != j && in_merge_bases(m2, m1)) {
  1003. contains_another = 1;
  1004. break;
  1005. }
  1006. }
  1007. if (!contains_another)
  1008. add_object_array(merges.objects[i].item, NULL, result);
  1009. }
  1010. object_array_clear(&merges);
  1011. return result->nr;
  1012. }
  1013. static void print_commit(struct commit *commit)
  1014. {
  1015. struct strbuf sb = STRBUF_INIT;
  1016. struct pretty_print_context ctx = {0};
  1017. ctx.date_mode.type = DATE_NORMAL;
  1018. format_commit_message(commit, " %h: %m %s", &sb, &ctx);
  1019. fprintf(stderr, "%s\n", sb.buf);
  1020. strbuf_release(&sb);
  1021. }
  1022. static int is_valid(const struct diff_filespec *dfs)
  1023. {
  1024. return dfs->mode != 0 && !is_null_oid(&dfs->oid);
  1025. }
  1026. static int merge_submodule(struct merge_options *opt,
  1027. struct object_id *result, const char *path,
  1028. const struct object_id *base, const struct object_id *a,
  1029. const struct object_id *b)
  1030. {
  1031. struct commit *commit_base, *commit_a, *commit_b;
  1032. int parent_count;
  1033. struct object_array merges;
  1034. int i;
  1035. int search = !opt->priv->call_depth;
  1036. /* store a in result in case we fail */
  1037. oidcpy(result, a);
  1038. /* we can not handle deletion conflicts */
  1039. if (is_null_oid(base))
  1040. return 0;
  1041. if (is_null_oid(a))
  1042. return 0;
  1043. if (is_null_oid(b))
  1044. return 0;
  1045. if (add_submodule_odb(path)) {
  1046. output(opt, 1, _("Failed to merge submodule %s (not checked out)"), path);
  1047. return 0;
  1048. }
  1049. if (!(commit_base = lookup_commit_reference(opt->repo, base)) ||
  1050. !(commit_a = lookup_commit_reference(opt->repo, a)) ||
  1051. !(commit_b = lookup_commit_reference(opt->repo, b))) {
  1052. output(opt, 1, _("Failed to merge submodule %s (commits not present)"), path);
  1053. return 0;
  1054. }
  1055. /* check whether both changes are forward */
  1056. if (!in_merge_bases(commit_base, commit_a) ||
  1057. !in_merge_bases(commit_base, commit_b)) {
  1058. output(opt, 1, _("Failed to merge submodule %s (commits don't follow merge-base)"), path);
  1059. return 0;
  1060. }
  1061. /* Case #1: a is contained in b or vice versa */
  1062. if (in_merge_bases(commit_a, commit_b)) {
  1063. oidcpy(result, b);
  1064. if (show(opt, 3)) {
  1065. output(opt, 3, _("Fast-forwarding submodule %s to the following commit:"), path);
  1066. output_commit_title(opt, commit_b);
  1067. } else if (show(opt, 2))
  1068. output(opt, 2, _("Fast-forwarding submodule %s"), path);
  1069. else
  1070. ; /* no output */
  1071. return 1;
  1072. }
  1073. if (in_merge_bases(commit_b, commit_a)) {
  1074. oidcpy(result, a);
  1075. if (show(opt, 3)) {
  1076. output(opt, 3, _("Fast-forwarding submodule %s to the following commit:"), path);
  1077. output_commit_title(opt, commit_a);
  1078. } else if (show(opt, 2))
  1079. output(opt, 2, _("Fast-forwarding submodule %s"), path);
  1080. else
  1081. ; /* no output */
  1082. return 1;
  1083. }
  1084. /*
  1085. * Case #2: There are one or more merges that contain a and b in
  1086. * the submodule. If there is only one, then present it as a
  1087. * suggestion to the user, but leave it marked unmerged so the
  1088. * user needs to confirm the resolution.
  1089. */
  1090. /* Skip the search if makes no sense to the calling context. */
  1091. if (!search)
  1092. return 0;
  1093. /* find commit which merges them */
  1094. parent_count = find_first_merges(opt->repo, &merges, path,
  1095. commit_a, commit_b);
  1096. switch (parent_count) {
  1097. case 0:
  1098. output(opt, 1, _("Failed to merge submodule %s (merge following commits not found)"), path);
  1099. break;
  1100. case 1:
  1101. output(opt, 1, _("Failed to merge submodule %s (not fast-forward)"), path);
  1102. output(opt, 2, _("Found a possible merge resolution for the submodule:\n"));
  1103. print_commit((struct commit *) merges.objects[0].item);
  1104. output(opt, 2, _(
  1105. "If this is correct simply add it to the index "
  1106. "for example\n"
  1107. "by using:\n\n"
  1108. " git update-index --cacheinfo 160000 %s \"%s\"\n\n"
  1109. "which will accept this suggestion.\n"),
  1110. oid_to_hex(&merges.objects[0].item->oid), path);
  1111. break;
  1112. default:
  1113. output(opt, 1, _("Failed to merge submodule %s (multiple merges found)"), path);
  1114. for (i = 0; i < merges.nr; i++)
  1115. print_commit((struct commit *) merges.objects[i].item);
  1116. }
  1117. object_array_clear(&merges);
  1118. return 0;
  1119. }
  1120. static int merge_mode_and_contents(struct merge_options *opt,
  1121. const struct diff_filespec *o,
  1122. const struct diff_filespec *a,
  1123. const struct diff_filespec *b,
  1124. const char *filename,
  1125. const char *branch1,
  1126. const char *branch2,
  1127. const int extra_marker_size,
  1128. struct merge_file_info *result)
  1129. {
  1130. if (opt->branch1 != branch1) {
  1131. /*
  1132. * It's weird getting a reverse merge with HEAD on the bottom
  1133. * side of the conflict markers and the other branch on the
  1134. * top. Fix that.
  1135. */
  1136. return merge_mode_and_contents(opt, o, b, a,
  1137. filename,
  1138. branch2, branch1,
  1139. extra_marker_size, result);
  1140. }
  1141. result->merge = 0;
  1142. result->clean = 1;
  1143. if ((S_IFMT & a->mode) != (S_IFMT & b->mode)) {
  1144. result->clean = 0;
  1145. if (S_ISREG(a->mode)) {
  1146. result->blob.mode = a->mode;
  1147. oidcpy(&result->blob.oid, &a->oid);
  1148. } else {
  1149. result->blob.mode = b->mode;
  1150. oidcpy(&result->blob.oid, &b->oid);
  1151. }
  1152. } else {
  1153. if (!oideq(&a->oid, &o->oid) && !oideq(&b->oid, &o->oid))
  1154. result->merge = 1;
  1155. /*
  1156. * Merge modes
  1157. */
  1158. if (a->mode == b->mode || a->mode == o->mode)
  1159. result->blob.mode = b->mode;
  1160. else {
  1161. result->blob.mode = a->mode;
  1162. if (b->mode != o->mode) {
  1163. result->clean = 0;
  1164. result->merge = 1;
  1165. }
  1166. }
  1167. if (oideq(&a->oid, &b->oid) || oideq(&a->oid, &o->oid))
  1168. oidcpy(&result->blob.oid, &b->oid);
  1169. else if (oideq(&b->oid, &o->oid))
  1170. oidcpy(&result->blob.oid, &a->oid);
  1171. else if (S_ISREG(a->mode)) {
  1172. mmbuffer_t result_buf;
  1173. int ret = 0, merge_status;
  1174. merge_status = merge_3way(opt, &result_buf, o, a, b,
  1175. branch1, branch2,
  1176. extra_marker_size);
  1177. if ((merge_status < 0) || !result_buf.ptr)
  1178. ret = err(opt, _("Failed to execute internal merge"));
  1179. if (!ret &&
  1180. write_object_file(result_buf.ptr, result_buf.size,
  1181. blob_type, &result->blob.oid))
  1182. ret = err(opt, _("Unable to add %s to database"),
  1183. a->path);
  1184. free(result_buf.ptr);
  1185. if (ret)
  1186. return ret;
  1187. result->clean = (merge_status == 0);
  1188. } else if (S_ISGITLINK(a->mode)) {
  1189. result->clean = merge_submodule(opt, &result->blob.oid,
  1190. o->path,
  1191. &o->oid,
  1192. &a->oid,
  1193. &b->oid);
  1194. } else if (S_ISLNK(a->mode)) {
  1195. switch (opt->recursive_variant) {
  1196. case MERGE_VARIANT_NORMAL:
  1197. oidcpy(&result->blob.oid, &a->oid);
  1198. if (!oideq(&a->oid, &b->oid))
  1199. result->clean = 0;
  1200. break;
  1201. case MERGE_VARIANT_OURS:
  1202. oidcpy(&result->blob.oid, &a->oid);
  1203. break;
  1204. case MERGE_VARIANT_THEIRS:
  1205. oidcpy(&result->blob.oid, &b->oid);
  1206. break;
  1207. }
  1208. } else
  1209. BUG("unsupported object type in the tree");
  1210. }
  1211. if (result->merge)
  1212. output(opt, 2, _("Auto-merging %s"), filename);
  1213. return 0;
  1214. }
  1215. static int handle_rename_via_dir(struct merge_options *opt,
  1216. struct rename_conflict_info *ci)
  1217. {
  1218. /*
  1219. * Handle file adds that need to be renamed due to directory rename
  1220. * detection. This differs from handle_rename_normal, because
  1221. * there is no content merge to do; just move the file into the
  1222. * desired final location.
  1223. */
  1224. const struct rename *ren = ci->ren1;
  1225. const struct diff_filespec *dest = ren->pair->two;
  1226. char *file_path = dest->path;
  1227. int mark_conflicted = (opt->detect_directory_renames ==
  1228. MERGE_DIRECTORY_RENAMES_CONFLICT);
  1229. assert(ren->dir_rename_original_dest);
  1230. if (!opt->priv->call_depth && would_lose_untracked(opt, dest->path)) {
  1231. mark_conflicted = 1;
  1232. file_path = unique_path(opt, dest->path, ren->branch);
  1233. output(opt, 1, _("Error: Refusing to lose untracked file at %s; "
  1234. "writing to %s instead."),
  1235. dest->path, file_path);
  1236. }
  1237. if (mark_conflicted) {
  1238. /*
  1239. * Write the file in worktree at file_path. In the index,
  1240. * only record the file at dest->path in the appropriate
  1241. * higher stage.
  1242. */
  1243. if (update_file(opt, 0, dest, file_path))
  1244. return -1;
  1245. if (file_path != dest->path)
  1246. free(file_path);
  1247. if (update_stages(opt, dest->path, NULL,
  1248. ren->branch == opt->branch1 ? dest : NULL,
  1249. ren->branch == opt->branch1 ? NULL : dest))
  1250. return -1;
  1251. return 0; /* not clean, but conflicted */
  1252. } else {
  1253. /* Update dest->path both in index and in worktree */
  1254. if (update_file(opt, 1, dest, dest->path))
  1255. return -1;
  1256. return 1; /* clean */
  1257. }
  1258. }
  1259. static int handle_change_delete(struct merge_options *opt,
  1260. const char *path, const char *old_path,
  1261. const struct diff_filespec *o,
  1262. const struct diff_filespec *changed,
  1263. const char *change_branch,
  1264. const char *delete_branch,
  1265. const char *change, const char *change_past)
  1266. {
  1267. char *alt_path = NULL;
  1268. const char *update_path = path;
  1269. int ret = 0;
  1270. if (dir_in_way(opt->repo->index, path, !opt->priv->call_depth, 0) ||
  1271. (!opt->priv->call_depth && would_lose_untracked(opt, path))) {
  1272. update_path = alt_path = unique_path(opt, path, change_branch);
  1273. }
  1274. if (opt->priv->call_depth) {
  1275. /*
  1276. * We cannot arbitrarily accept either a_sha or b_sha as
  1277. * correct; since there is no true "middle point" between
  1278. * them, simply reuse the base version for virtual merge base.
  1279. */
  1280. ret = remove_file_from_index(opt->repo->index, path);
  1281. if (!ret)
  1282. ret = update_file(opt, 0, o, update_path);
  1283. } else {
  1284. /*
  1285. * Despite the four nearly duplicate messages and argument
  1286. * lists below and the ugliness of the nested if-statements,
  1287. * having complete messages makes the job easier for
  1288. * translators.
  1289. *
  1290. * The slight variance among the cases is due to the fact
  1291. * that:
  1292. * 1) directory/file conflicts (in effect if
  1293. * !alt_path) could cause us to need to write the
  1294. * file to a different path.
  1295. * 2) renames (in effect if !old_path) could mean that
  1296. * there are two names for the path that the user
  1297. * may know the file by.
  1298. */
  1299. if (!alt_path) {
  1300. if (!old_path) {
  1301. output(opt, 1, _("CONFLICT (%s/delete): %s deleted in %s "
  1302. "and %s in %s. Version %s of %s left in tree."),
  1303. change, path, delete_branch, change_past,
  1304. change_branch, change_branch, path);
  1305. } else {
  1306. output(opt, 1, _("CONFLICT (%s/delete): %s deleted in %s "
  1307. "and %s to %s in %s. Version %s of %s left in tree."),
  1308. change, old_path, delete_branch, change_past, path,
  1309. change_branch, change_branch, path);
  1310. }
  1311. } else {
  1312. if (!old_path) {
  1313. output(opt, 1, _("CONFLICT (%s/delete): %s deleted in %s "
  1314. "and %s in %s. Version %s of %s left in tree at %s."),
  1315. change, path, delete_branch, change_past,
  1316. change_branch, change_branch, path, alt_path);
  1317. } else {
  1318. output(opt, 1, _("CONFLICT (%s/delete): %s deleted in %s "
  1319. "and %s to %s in %s. Version %s of %s left in tree at %s."),
  1320. change, old_path, delete_branch, change_past, path,
  1321. change_branch, change_branch, path, alt_path);
  1322. }
  1323. }
  1324. /*
  1325. * No need to call update_file() on path when change_branch ==
  1326. * opt->branch1 && !alt_path, since that would needlessly touch
  1327. * path. We could call update_file_flags() with update_cache=0
  1328. * and update_wd=0, but that's a no-op.
  1329. */
  1330. if (change_branch != opt->branch1 || alt_path)
  1331. ret = update_file(opt, 0, changed, update_path);
  1332. }
  1333. free(alt_path);
  1334. return ret;
  1335. }
  1336. static int handle_rename_delete(struct merge_options *opt,
  1337. struct rename_conflict_info *ci)
  1338. {
  1339. const struct rename *ren = ci->ren1;
  1340. const struct diff_filespec *orig = ren->pair->one;
  1341. const struct diff_filespec *dest = ren->pair->two;
  1342. const char *rename_branch = ren->branch;
  1343. const char *delete_branch = (opt->branch1 == ren->branch ?
  1344. opt->branch2 : opt->branch1);
  1345. if (handle_change_delete(opt,
  1346. opt->priv->call_depth ? orig->path : dest->path,
  1347. opt->priv->call_depth ? NULL : orig->path,
  1348. orig, dest,
  1349. rename_branch, delete_branch,
  1350. _("rename"), _("renamed")))
  1351. return -1;
  1352. if (opt->priv->call_depth)
  1353. return remove_file_from_index(opt->repo->index, dest->path);
  1354. else
  1355. return update_stages(opt, dest->path, NULL,
  1356. rename_branch == opt->branch1 ? dest : NULL,
  1357. rename_branch == opt->branch1 ? NULL : dest);
  1358. }
  1359. static int handle_file_collision(struct merge_options *opt,
  1360. const char *collide_path,
  1361. const char *prev_path1,
  1362. const char *prev_path2,
  1363. const char *branch1, const char *branch2,
  1364. struct diff_filespec *a,
  1365. struct diff_filespec *b)
  1366. {
  1367. struct merge_file_info mfi;
  1368. struct diff_filespec null;
  1369. char *alt_path = NULL;
  1370. const char *update_path = collide_path;
  1371. /*
  1372. * It's easiest to get the correct things into stage 2 and 3, and
  1373. * to make sure that the content merge puts HEAD before the other
  1374. * branch if we just ensure that branch1 == opt->branch1. So, simply
  1375. * flip arguments around if we don't have that.
  1376. */
  1377. if (branch1 != opt->branch1) {
  1378. return handle_file_collision(opt, collide_path,
  1379. prev_path2, prev_path1,
  1380. branch2, branch1,
  1381. b, a);
  1382. }
  1383. /* Remove rename sources if rename/add or rename/rename(2to1) */
  1384. if (prev_path1)
  1385. remove_file(opt, 1, prev_path1,
  1386. opt->priv->call_depth || would_lose_untracked(opt, prev_path1));
  1387. if (prev_path2)
  1388. remove_file(opt, 1, prev_path2,
  1389. opt->priv->call_depth || would_lose_untracked(opt, prev_path2));
  1390. /*
  1391. * Remove the collision path, if it wouldn't cause dirty contents
  1392. * or an untracked file to get lost. We'll either overwrite with
  1393. * merged contents, or just write out to differently named files.
  1394. */
  1395. if (was_dirty(opt, collide_path)) {
  1396. output(opt, 1, _("Refusing to lose dirty file at %s"),
  1397. collide_path);
  1398. update_path = alt_path = unique_path(opt, collide_path, "merged");
  1399. } else if (would_lose_untracked(opt, collide_path)) {
  1400. /*
  1401. * Only way we get here is if both renames were from
  1402. * a directory rename AND user had an untracked file
  1403. * at the location where both files end up after the
  1404. * two directory renames. See testcase 10d of t6043.
  1405. */
  1406. output(opt, 1, _("Refusing to lose untracked file at "
  1407. "%s, even though it's in the way."),
  1408. collide_path);
  1409. update_path = alt_path = unique_path(opt, collide_path, "merged");
  1410. } else {
  1411. /*
  1412. * FIXME: It's possible that the two files are identical
  1413. * and that the current working copy happens to match, in
  1414. * which case we are unnecessarily touching the working
  1415. * tree file. It's not a likely enough scenario that I
  1416. * want to code up the checks for it and a better fix is
  1417. * available if we restructure how unpack_trees() and
  1418. * merge-recursive interoperate anyway, so punting for
  1419. * now...
  1420. */
  1421. remove_file(opt, 0, collide_path, 0);
  1422. }
  1423. /* Store things in diff_filespecs for functions that need it */
  1424. null.path = (char *)collide_path;
  1425. oidcpy(&null.oid, &null_oid);
  1426. null.mode = 0;
  1427. if (merge_mode_and_contents(opt, &null, a, b, collide_path,
  1428. branch1, branch2, opt->priv->call_depth * 2, &mfi))
  1429. return -1;
  1430. mfi.clean &= !alt_path;
  1431. if (update_file(opt, mfi.clean, &mfi.blob, update_path))
  1432. return -1;
  1433. if (!mfi.clean && !opt->priv->call_depth &&
  1434. update_stages(opt, collide_path, NULL, a, b))
  1435. return -1;
  1436. free(alt_path);
  1437. /*
  1438. * FIXME: If both a & b both started with conflicts (only possible
  1439. * if they came from a rename/rename(2to1)), but had IDENTICAL
  1440. * contents including those conflicts, then in the next line we claim
  1441. * it was clean. If someone cares about this case, we should have the
  1442. * caller notify us if we started with conflicts.
  1443. */
  1444. return mfi.clean;
  1445. }
  1446. static int handle_rename_add(struct merge_options *opt,
  1447. struct rename_conflict_info *ci)
  1448. {
  1449. /* a was renamed to c, and a separate c was added. */
  1450. struct diff_filespec *a = ci->ren1->pair->one;
  1451. struct diff_filespec *c = ci->ren1->pair->two;
  1452. char *path = c->path;
  1453. char *prev_path_desc;
  1454. struct merge_file_info mfi;
  1455. const char *rename_branch = ci->ren1->branch;
  1456. const char *add_branch = (opt->branch1 == rename_branch ?
  1457. opt->branch2 : opt->branch1);
  1458. int other_stage = (ci->ren1->branch == opt->branch1 ? 3 : 2);
  1459. output(opt, 1, _("CONFLICT (rename/add): "
  1460. "Rename %s->%s in %s. Added %s in %s"),
  1461. a->path, c->path, rename_branch,
  1462. c->path, add_branch);
  1463. prev_path_desc = xstrfmt("version of %s from %s", path, a->path);
  1464. ci->ren1->src_entry->stages[other_stage].path = a->path;
  1465. if (merge_mode_and_contents(opt, a, c,
  1466. &ci->ren1->src_entry->stages[other_stage],
  1467. prev_path_desc,
  1468. opt->branch1, opt->branch2,
  1469. 1 + opt->priv->call_depth * 2, &mfi))
  1470. return -1;
  1471. free(prev_path_desc);
  1472. ci->ren1->dst_entry->stages[other_stage].path = mfi.blob.path = c->path;
  1473. return handle_file_collision(opt,
  1474. c->path, a->path, NULL,
  1475. rename_branch, add_branch,
  1476. &mfi.blob,
  1477. &ci->ren1->dst_entry->stages[other_stage]);
  1478. }
  1479. static char *find_path_for_conflict(struct merge_options *opt,
  1480. const char *path,
  1481. const char *branch1,
  1482. const char *branch2)
  1483. {
  1484. char *new_path = NULL;
  1485. if (dir_in_way(opt->repo->index, path, !opt->priv->call_depth, 0)) {
  1486. new_path = unique_path(opt, path, branch1);
  1487. output(opt, 1, _("%s is a directory in %s adding "
  1488. "as %s instead"),
  1489. path, branch2, new_path);
  1490. } else if (would_lose_untracked(opt, path)) {
  1491. new_path = unique_path(opt, path, branch1);
  1492. output(opt, 1, _("Refusing to lose untracked file"
  1493. " at %s; adding as %s instead"),
  1494. path, new_path);
  1495. }
  1496. return new_path;
  1497. }
  1498. /*
  1499. * Toggle the stage number between "ours" and "theirs" (2 and 3).
  1500. */
  1501. static inline int flip_stage(int stage)
  1502. {
  1503. return (2 + 3) - stage;
  1504. }
  1505. static int handle_rename_rename_1to2(struct merge_options *opt,
  1506. struct rename_conflict_info *ci)
  1507. {
  1508. /* One file was renamed in both branches, but to different names. */
  1509. struct merge_file_info mfi;
  1510. struct diff_filespec *add;
  1511. struct diff_filespec *o = ci->ren1->pair->one;
  1512. struct diff_filespec *a = ci->ren1->pair->two;
  1513. struct diff_filespec *b = ci->ren2->pair->two;
  1514. char *path_desc;
  1515. output(opt, 1, _("CONFLICT (rename/rename): "
  1516. "Rename \"%s\"->\"%s\" in branch \"%s\" "
  1517. "rename \"%s\"->\"%s\" in \"%s\"%s"),
  1518. o->path, a->path, ci->ren1->branch,
  1519. o->path, b->path, ci->ren2->branch,
  1520. opt->priv->call_depth ? _(" (left unresolved)") : "");
  1521. path_desc = xstrfmt("%s and %s, both renamed from %s",
  1522. a->path, b->path, o->path);
  1523. if (merge_mode_and_contents(opt, o, a, b, path_desc,
  1524. ci->ren1->branch, ci->ren2->branch,
  1525. opt->priv->call_depth * 2, &mfi))
  1526. return -1;
  1527. free(path_desc);
  1528. if (opt->priv->call_depth)
  1529. remove_file_from_index(opt->repo->index, o->path);
  1530. /*
  1531. * For each destination path, we need to see if there is a
  1532. * rename/add collision. If not, we can write the file out
  1533. * to the specified location.
  1534. */
  1535. add = &ci->ren1->dst_entry->stages[flip_stage(2)];
  1536. if (is_valid(add)) {
  1537. add->path = mfi.blob.path = a->path;
  1538. if (handle_file_collision(opt, a->path,
  1539. NULL, NULL,
  1540. ci->ren1->branch,
  1541. ci->ren2->branch,
  1542. &mfi.blob, add) < 0)
  1543. return -1;
  1544. } else {
  1545. char *new_path = find_path_for_conflict(opt, a->path,
  1546. ci->ren1->branch,
  1547. ci->ren2->branch);
  1548. if (update_file(opt, 0, &mfi.blob,
  1549. new_path ? new_path : a->path))
  1550. return -1;
  1551. free(new_path);
  1552. if (!opt->priv->call_depth &&
  1553. update_stages(opt, a->path, NULL, a, NULL))
  1554. return -1;
  1555. }
  1556. if (!mfi.clean && mfi.blob.mode == a->mode &&
  1557. oideq(&mfi.blob.oid, &a->oid)) {
  1558. /*
  1559. * Getting here means we were attempting to merge a binary
  1560. * blob. Since we can't merge binaries, the merge algorithm
  1561. * just takes one side. But we don't want to copy the
  1562. * contents of one side to both paths; we'd rather use the
  1563. * original content at the given path for each path.
  1564. */
  1565. oidcpy(&mfi.blob.oid, &b->oid);
  1566. mfi.blob.mode = b->mode;
  1567. }
  1568. add = &ci->ren2->dst_entry->stages[flip_stage(3)];
  1569. if (is_valid(add)) {
  1570. add->path = mfi.blob.path = b->path;
  1571. if (handle_file_collision(opt, b->path,
  1572. NULL, NULL,
  1573. ci->ren1->branch,
  1574. ci->ren2->branch,
  1575. add, &mfi.blob) < 0)
  1576. return -1;
  1577. } else {
  1578. char *new_path = find_path_for_conflict(opt, b->path,
  1579. ci->ren2->branch,
  1580. ci->ren1->branch);
  1581. if (update_file(opt, 0, &mfi.blob,
  1582. new_path ? new_path : b->path))
  1583. return -1;
  1584. free(new_path);
  1585. if (!opt->priv->call_depth &&
  1586. update_stages(opt, b->path, NULL, NULL, b))
  1587. return -1;
  1588. }
  1589. return 0;
  1590. }
  1591. static int handle_rename_rename_2to1(struct merge_options *opt,
  1592. struct rename_conflict_info *ci)
  1593. {
  1594. /* Two files, a & b, were renamed to the same thing, c. */
  1595. struct diff_filespec *a = ci->ren1->pair->one;
  1596. struct diff_filespec *b = ci->ren2->pair->one;
  1597. struct diff_filespec *c1 = ci->ren1->pair->two;
  1598. struct diff_filespec *c2 = ci->ren2->pair->two;
  1599. char *path = c1->path; /* == c2->path */
  1600. char *path_side_1_desc;
  1601. char *path_side_2_desc;
  1602. struct merge_file_info mfi_c1;
  1603. struct merge_file_info mfi_c2;
  1604. int ostage1, ostage2;
  1605. output(opt, 1, _("CONFLICT (rename/rename): "
  1606. "Rename %s->%s in %s. "
  1607. "Rename %s->%s in %s"),
  1608. a->path, c1->path, ci->ren1->branch,
  1609. b->path, c2->path, ci->ren2->branch);
  1610. path_side_1_desc = xstrfmt("version of %s from %s", path, a->path);
  1611. path_side_2_desc = xstrfmt("version of %s from %s", path, b->path);
  1612. ostage1 = ci->ren1->branch == opt->branch1 ? 3 : 2;
  1613. ostage2 = flip_stage(ostage1);
  1614. ci->ren1->src_entry->stages[ostage1].path = a->path;
  1615. ci->ren2->src_entry->stages[ostage2].path = b->path;
  1616. if (merge_mode_and_contents(opt, a, c1,
  1617. &ci->ren1->src_entry->stages[ostage1],
  1618. path_side_1_desc,
  1619. opt->branch1, opt->branch2,
  1620. 1 + opt->priv->call_depth * 2, &mfi_c1) ||
  1621. merge_mode_and_contents(opt, b,
  1622. &ci->ren2->src_entry->stages[ostage2],
  1623. c2, path_side_2_desc,
  1624. opt->branch1, opt->branch2,
  1625. 1 + opt->priv->call_depth * 2, &mfi_c2))
  1626. return -1;
  1627. free(path_side_1_desc);
  1628. free(path_side_2_desc);
  1629. mfi_c1.blob.path = path;
  1630. mfi_c2.blob.path = path;
  1631. return handle_file_collision(opt, path, a->path, b->path,
  1632. ci->ren1->branch, ci->ren2->branch,
  1633. &mfi_c1.blob, &mfi_c2.blob);
  1634. }
  1635. /*
  1636. * Get the diff_filepairs changed between o_tree and tree.
  1637. */
  1638. static struct diff_queue_struct *get_diffpairs(struct merge_options *opt,
  1639. struct tree *o_tree,
  1640. struct tree *tree)
  1641. {
  1642. struct diff_queue_struct *ret;
  1643. struct diff_options opts;
  1644. repo_diff_setup(opt->repo, &opts);
  1645. opts.flags.recursive = 1;
  1646. opts.flags.rename_empty = 0;
  1647. opts.detect_rename = merge_detect_rename(opt);
  1648. /*
  1649. * We do not have logic to handle the detection of copies. In
  1650. * fact, it may not even make sense to add such logic: would we
  1651. * really want a change to a base file to be propagated through
  1652. * multiple other files by a merge?
  1653. */
  1654. if (opts.detect_rename > DIFF_DETECT_RENAME)
  1655. opts.detect_rename = DIFF_DETECT_RENAME;
  1656. opts.rename_limit = (opt->rename_limit >= 0) ? opt->rename_limit : 1000;
  1657. opts.rename_score = opt->rename_score;
  1658. opts.show_rename_progress = opt->show_rename_progress;
  1659. opts.output_format = DIFF_FORMAT_NO_OUTPUT;
  1660. diff_setup_done(&opts);
  1661. diff_tree_oid(&o_tree->object.oid, &tree->object.oid, "", &opts);
  1662. diffcore_std(&opts);
  1663. if (opts.needed_rename_limit > opt->priv->needed_rename_limit)
  1664. opt->priv->needed_rename_limit = opts.needed_rename_limit;
  1665. ret = xmalloc(sizeof(*ret));
  1666. *ret = diff_queued_diff;
  1667. opts.output_format = DIFF_FORMAT_NO_OUTPUT;
  1668. diff_queued_diff.nr = 0;
  1669. diff_queued_diff.queue = NULL;
  1670. diff_flush(&opts);
  1671. return ret;
  1672. }
  1673. static int tree_has_path(struct repository *r, struct tree *tree,
  1674. const char *path)
  1675. {
  1676. struct object_id hashy;
  1677. unsigned short mode_o;
  1678. return !get_tree_entry(r,
  1679. &tree->object.oid, path,
  1680. &hashy, &mode_o);
  1681. }
  1682. /*
  1683. * Return a new string that replaces the beginning portion (which matches
  1684. * entry->dir), with entry->new_dir. In perl-speak:
  1685. * new_path_name = (old_path =~ s/entry->dir/entry->new_dir/);
  1686. * NOTE:
  1687. * Caller must ensure that old_path starts with entry->dir + '/'.
  1688. */
  1689. static char *apply_dir_rename(struct dir_rename_entry *entry,
  1690. const char *old_path)
  1691. {
  1692. struct strbuf new_path = STRBUF_INIT;
  1693. int oldlen, newlen;
  1694. if (entry->non_unique_new_dir)
  1695. return NULL;
  1696. oldlen = strlen(entry->dir);
  1697. if (entry->new_dir.len == 0)
  1698. /*
  1699. * If someone renamed/merged a subdirectory into the root
  1700. * directory (e.g. 'some/subdir' -> ''), then we want to
  1701. * avoid returning
  1702. * '' + '/filename'
  1703. * as the rename; we need to make old_path + oldlen advance
  1704. * past the '/' character.
  1705. */
  1706. oldlen++;
  1707. newlen = entry->new_dir.len + (strlen(old_path) - oldlen) + 1;
  1708. strbuf_grow(&new_path, newlen);
  1709. strbuf_addbuf(&new_path, &entry->new_dir);
  1710. strbuf_addstr(&new_path, &old_path[oldlen]);
  1711. return strbuf_detach(&new_path, NULL);
  1712. }
  1713. static void get_renamed_dir_portion(const char *old_path, const char *new_path,
  1714. char **old_dir, char **new_dir)
  1715. {
  1716. char *end_of_old, *end_of_new;
  1717. /* Default return values: NULL, meaning no rename */
  1718. *old_dir = NULL;
  1719. *new_dir = NULL;
  1720. /*
  1721. * For
  1722. * "a/b/c/d/e/foo.c" -> "a/b/some/thing/else/e/foo.c"
  1723. * the "e/foo.c" part is the same, we just want to know that
  1724. * "a/b/c/d" was renamed to "a/b/some/thing/else"
  1725. * so, for this example, this function returns "a/b/c/d" in
  1726. * *old_dir and "a/b/some/thing/else" in *new_dir.
  1727. */
  1728. /*
  1729. * If the basename of the file changed, we don't care. We want
  1730. * to know which portion of the directory, if any, changed.
  1731. */
  1732. end_of_old = strrchr(old_path, '/');
  1733. end_of_new = strrchr(new_path, '/');
  1734. /*
  1735. * If end_of_old is NULL, old_path wasn't in a directory, so there
  1736. * could not be a directory rename (our rule elsewhere that a
  1737. * directory which still exists is not considered to have been
  1738. * renamed means the root directory can never be renamed -- because
  1739. * the root directory always exists).
  1740. */
  1741. if (end_of_old == NULL)
  1742. return; /* Note: *old_dir and *new_dir are still NULL */
  1743. /*
  1744. * If new_path contains no directory (end_of_new is NULL), then we
  1745. * have a rename of old_path's directory to the root directory.
  1746. */
  1747. if (end_of_new == NULL) {
  1748. *old_dir = xstrndup(old_path, end_of_old - old_path);
  1749. *new_dir = xstrdup("");
  1750. return;
  1751. }
  1752. /* Find the first non-matching character traversing backwards */
  1753. while (*--end_of_new == *--end_of_old &&
  1754. end_of_old != old_path &&
  1755. end_of_new != new_path)
  1756. ; /* Do nothing; all in the while loop */
  1757. /*
  1758. * If both got back to the beginning of their strings, then the
  1759. * directory didn't change at all, only the basename did.
  1760. */
  1761. if (end_of_old == old_path && end_of_new == new_path &&
  1762. *end_of_old == *end_of_new)
  1763. return; /* Note: *old_dir and *new_dir are still NULL */
  1764. /*
  1765. * If end_of_new got back to the beginning of its string, and
  1766. * end_of_old got back to the beginning of some subdirectory, then
  1767. * we have a rename/merge of a subdirectory into the root, which
  1768. * needs slightly special handling.
  1769. *
  1770. * Note: There is no need to consider the opposite case, with a
  1771. * rename/merge of the root directory into some subdirectory
  1772. * because as noted above the root directory always exists so it
  1773. * cannot be considered to be renamed.
  1774. */
  1775. if (end_of_new == new_path &&
  1776. end_of_old != old_path && end_of_old[-1] == '/') {
  1777. *old_dir = xstrndup(old_path, --end_of_old - old_path);
  1778. *new_dir = xstrdup("");
  1779. return;
  1780. }
  1781. /*
  1782. * We've found the first non-matching character in the directory
  1783. * paths. That means the current characters we were looking at
  1784. * were part of the first non-matching subdir name going back from
  1785. * the end of the strings. Get the whole name by advancing both
  1786. * end_of_old and end_of_new to the NEXT '/' character. That will
  1787. * represent the entire directory rename.
  1788. *
  1789. * The reason for the increment is cases like
  1790. * a/b/star/foo/whatever.c -> a/b/tar/foo/random.c
  1791. * After dropping the basename and going back to the first
  1792. * non-matching character, we're now comparing:
  1793. * a/b/s and a/b/
  1794. * and we want to be comparing:
  1795. * a/b/star/ and a/b/tar/
  1796. * but without the pre-increment, the one on the right would stay
  1797. * a/b/.
  1798. */
  1799. end_of_old = strchr(++end_of_old, '/');
  1800. end_of_new = strchr(++end_of_new, '/');
  1801. /* Copy the old and new directories into *old_dir and *new_dir. */
  1802. *old_dir = xstrndup(old_path, end_of_old - old_path);
  1803. *new_dir = xstrndup(new_path, end_of_new - new_path);
  1804. }
  1805. static void remove_hashmap_entries(struct hashmap *dir_renames,
  1806. struct string_list *items_to_remove)
  1807. {
  1808. int i;
  1809. struct dir_rename_entry *entry;
  1810. for (i = 0; i < items_to_remove->nr; i++) {
  1811. entry = items_to_remove->items[i].util;
  1812. hashmap_remove(dir_renames, &entry->ent, NULL);
  1813. }
  1814. string_list_clear(items_to_remove, 0);
  1815. }
  1816. /*
  1817. * See if there is a directory rename for path, and if there are any file
  1818. * level conflicts for the renamed location. If there is a rename and
  1819. * there are no conflicts, return the new name. Otherwise, return NULL.
  1820. */
  1821. static char *handle_path_level_conflicts(struct merge_options *opt,
  1822. const char *path,
  1823. struct dir_rename_entry *entry,
  1824. struct hashmap *collisions,
  1825. struct tree *tree)
  1826. {
  1827. char *new_path = NULL;
  1828. struct collision_entry *collision_ent;
  1829. int clean = 1;
  1830. struct strbuf collision_paths = STRBUF_INIT;
  1831. /*
  1832. * entry has the mapping of old directory name to new directory name
  1833. * that we want to apply to path.
  1834. */
  1835. new_path = apply_dir_rename(entry, path);
  1836. if (!new_path) {
  1837. /* This should only happen when entry->non_unique_new_dir set */
  1838. if (!entry->non_unique_new_dir)
  1839. BUG("entry->non_unqiue_dir not set and !new_path");
  1840. output(opt, 1, _("CONFLICT (directory rename split): "
  1841. "Unclear where to place %s because directory "
  1842. "%s was renamed to multiple other directories, "
  1843. "with no destination getting a majority of the "
  1844. "files."),
  1845. path, entry->dir);
  1846. clean = 0;
  1847. return NULL;
  1848. }
  1849. /*
  1850. * The caller needs to have ensured that it has pre-populated
  1851. * collisions with all paths that map to new_path. Do a quick check
  1852. * to ensure that's the case.
  1853. */
  1854. collision_ent = collision_find_entry(collisions, new_path);
  1855. if (collision_ent == NULL)
  1856. BUG("collision_ent is NULL");
  1857. /*
  1858. * Check for one-sided add/add/.../add conflicts, i.e.
  1859. * where implicit renames from the other side doing
  1860. * directory rename(s) can affect this side of history
  1861. * to put multiple paths into the same location. Warn
  1862. * and bail on directory renames for such paths.
  1863. */
  1864. if (collision_ent->reported_already) {
  1865. clean = 0;
  1866. } else if (tree_has_path(opt->repo, tree, new_path)) {
  1867. collision_ent->reported_already = 1;
  1868. strbuf_add_separated_string_list(&collision_paths, ", ",
  1869. &collision_ent->source_files);
  1870. output(opt, 1, _("CONFLICT (implicit dir rename): Existing "
  1871. "file/dir at %s in the way of implicit "
  1872. "directory rename(s) putting the following "
  1873. "path(s) there: %s."),
  1874. new_path, collision_paths.buf);
  1875. clean = 0;
  1876. } else if (collision_ent->source_files.nr > 1) {
  1877. collision_ent->reported_already = 1;
  1878. strbuf_add_separated_string_list(&collision_paths, ", ",
  1879. &collision_ent->source_files);
  1880. output(opt, 1, _("CONFLICT (implicit dir rename): Cannot map "
  1881. "more than one path to %s; implicit directory "
  1882. "renames tried to put these paths there: %s"),
  1883. new_path, collision_paths.buf);
  1884. clean = 0;
  1885. }
  1886. /* Free memory we no longer need */
  1887. strbuf_release(&collision_paths);
  1888. if (!clean && new_path) {
  1889. free(new_path);
  1890. return NULL;
  1891. }
  1892. return new_path;
  1893. }
  1894. /*
  1895. * There are a couple things we want to do at the directory level:
  1896. * 1. Check for both sides renaming to the same thing, in order to avoid
  1897. * implicit renaming of files that should be left in place. (See
  1898. * testcase 6b in t6043 for details.)
  1899. * 2. Prune directory renames if there are still files left in the
  1900. * the original directory. These represent a partial directory rename,
  1901. * i.e. a rename where only some of the files within the directory
  1902. * were renamed elsewhere. (Technically, this could be done earlier
  1903. * in get_directory_renames(), except that would prevent us from
  1904. * doing the previous check and thus failing testcase 6b.)
  1905. * 3. Check for rename/rename(1to2) conflicts (at the directory level).
  1906. * In the future, we could potentially record this info as well and
  1907. * omit reporting rename/rename(1to2) conflicts for each path within
  1908. * the affected directories, thus cleaning up the merge output.
  1909. * NOTE: We do NOT check for rename/rename(2to1) conflicts at the
  1910. * directory level, because merging directories is fine. If it
  1911. * causes conflicts for files within those merged directories, then
  1912. * that should be detected at the individual path level.
  1913. */
  1914. static void handle_directory_level_conflicts(struct merge_options *opt,
  1915. struct hashmap *dir_re_head,
  1916. struct tree *head,
  1917. struct hashmap *dir_re_merge,
  1918. struct tree *merge)
  1919. {
  1920. struct hashmap_iter iter;
  1921. struct dir_rename_entry *head_ent;
  1922. struct dir_rename_entry *merge_ent;
  1923. struct string_list remove_from_head = STRING_LIST_INIT_NODUP;
  1924. struct string_list remove_from_merge = STRING_LIST_INIT_NODUP;
  1925. hashmap_for_each_entry(dir_re_head, &iter, head_ent,
  1926. ent /* member name */) {
  1927. merge_ent = dir_rename_find_entry(dir_re_merge, head_ent->dir);
  1928. if (merge_ent &&
  1929. !head_ent->non_unique_new_dir &&
  1930. !merge_ent->non_unique_new_dir &&
  1931. !strbuf_cmp(&head_ent->new_dir, &merge_ent->new_dir)) {
  1932. /* 1. Renamed identically; remove it from both sides */
  1933. string_list_append(&remove_from_head,
  1934. head_ent->dir)->util = head_ent;
  1935. strbuf_release(&head_ent->new_dir);
  1936. string_list_append(&remove_from_merge,
  1937. merge_ent->dir)->util = merge_ent;
  1938. strbuf_release(&merge_ent->new_dir);
  1939. } else if (tree_has_path(opt->repo, head, head_ent->dir)) {
  1940. /* 2. This wasn't a directory rename after all */
  1941. string_list_append(&remove_from_head,
  1942. head_ent->dir)->util = head_ent;
  1943. strbuf_release(&head_ent->new_dir);
  1944. }
  1945. }
  1946. remove_hashmap_entries(dir_re_head, &remove_from_head);
  1947. remove_hashmap_entries(dir_re_merge, &remove_from_merge);
  1948. hashmap_for_each_entry(dir_re_merge, &iter, merge_ent,
  1949. ent /* member name */) {
  1950. head_ent = dir_rename_find_entry(dir_re_head, merge_ent->dir);
  1951. if (tree_has_path(opt->repo, merge, merge_ent->dir)) {
  1952. /* 2. This wasn't a directory rename after all */
  1953. string_list_append(&remove_from_merge,
  1954. merge_ent->dir)->util = merge_ent;
  1955. } else if (head_ent &&
  1956. !head_ent->non_unique_new_dir &&
  1957. !merge_ent->non_unique_new_dir) {
  1958. /* 3. rename/rename(1to2) */
  1959. /*
  1960. * We can assume it's not rename/rename(1to1) because
  1961. * that was case (1), already checked above. So we
  1962. * know that head_ent->new_dir and merge_ent->new_dir
  1963. * are different strings.
  1964. */
  1965. output(opt, 1, _("CONFLICT (rename/rename): "
  1966. "Rename directory %s->%s in %s. "
  1967. "Rename directory %s->%s in %s"),
  1968. head_ent->dir, head_ent->new_dir.buf, opt->branch1,
  1969. head_ent->dir, merge_ent->new_dir.buf, opt->branch2);
  1970. string_list_append(&remove_from_head,
  1971. head_ent->dir)->util = head_ent;
  1972. strbuf_release(&head_ent->new_dir);
  1973. string_list_append(&remove_from_merge,
  1974. merge_ent->dir)->util = merge_ent;
  1975. strbuf_release(&merge_ent->new_dir);
  1976. }
  1977. }
  1978. remove_hashmap_entries(dir_re_head, &remove_from_head);
  1979. remove_hashmap_entries(dir_re_merge, &remove_from_merge);
  1980. }
  1981. static struct hashmap *get_directory_renames(struct diff_queue_struct *pairs)
  1982. {
  1983. struct hashmap *dir_renames;
  1984. struct hashmap_iter iter;
  1985. struct dir_rename_entry *entry;
  1986. int i;
  1987. /*
  1988. * Typically, we think of a directory rename as all files from a
  1989. * certain directory being moved to a target directory. However,
  1990. * what if someone first moved two files from the original
  1991. * directory in one commit, and then renamed the directory
  1992. * somewhere else in a later commit? At merge time, we just know
  1993. * that files from the original directory went to two different
  1994. * places, and that the bulk of them ended up in the same place.
  1995. * We want each directory rename to represent where the bulk of the
  1996. * files from that directory end up; this function exists to find
  1997. * where the bulk of the files went.
  1998. *
  1999. * The first loop below simply iterates through the list of file
  2000. * renames, finding out how often each directory rename pair
  2001. * possibility occurs.
  2002. */
  2003. dir_renames = xmalloc(sizeof(*dir_renames));
  2004. dir_rename_init(dir_renames);
  2005. for (i = 0; i < pairs->nr; ++i) {
  2006. struct string_list_item *item;
  2007. int *count;
  2008. struct diff_filepair *pair = pairs->queue[i];
  2009. char *old_dir, *new_dir;
  2010. /* File not part of directory rename if it wasn't renamed */
  2011. if (pair->status != 'R')
  2012. continue;
  2013. get_renamed_dir_portion(pair->one->path, pair->two->path,
  2014. &old_dir, &new_dir);
  2015. if (!old_dir)
  2016. /* Directory didn't change at all; ignore this one. */
  2017. continue;
  2018. entry = dir_rename_find_entry(dir_renames, old_dir);
  2019. if (!entry) {
  2020. entry = xmalloc(sizeof(*entry));
  2021. dir_rename_entry_init(entry, old_dir);
  2022. hashmap_put(dir_renames, &entry->ent);
  2023. } else {
  2024. free(old_dir);
  2025. }
  2026. item = string_list_lookup(&entry->possible_new_dirs, new_dir);
  2027. if (!item) {
  2028. item = string_list_insert(&entry->possible_new_dirs,
  2029. new_dir);
  2030. item->util = xcalloc(1, sizeof(int));
  2031. } else {
  2032. free(new_dir);
  2033. }
  2034. count = item->util;
  2035. *count += 1;
  2036. }
  2037. /*
  2038. * For each directory with files moved out of it, we find out which
  2039. * target directory received the most files so we can declare it to
  2040. * be the "winning" target location for the directory rename. This
  2041. * winner gets recorded in new_dir. If there is no winner
  2042. * (multiple target directories received the same number of files),
  2043. * we set non_unique_new_dir. Once we've determined the winner (or
  2044. * that there is no winner), we no longer need possible_new_dirs.
  2045. */
  2046. hashmap_for_each_entry(dir_renames, &iter, entry,
  2047. ent /* member name */) {
  2048. int max = 0;
  2049. int bad_max = 0;
  2050. char *best = NULL;
  2051. for (i = 0; i < entry->possible_new_dirs.nr; i++) {
  2052. int *count = entry->possible_new_dirs.items[i].util;
  2053. if (*count == max)
  2054. bad_max = max;
  2055. else if (*count > max) {
  2056. max = *count;
  2057. best = entry->possible_new_dirs.items[i].string;
  2058. }
  2059. }
  2060. if (bad_max == max)
  2061. entry->non_unique_new_dir = 1;
  2062. else {
  2063. assert(entry->new_dir.len == 0);
  2064. strbuf_addstr(&entry->new_dir, best);
  2065. }
  2066. /*
  2067. * The relevant directory sub-portion of the original full
  2068. * filepaths were xstrndup'ed before inserting into
  2069. * possible_new_dirs, and instead of manually iterating the
  2070. * list and free'ing each, just lie and tell
  2071. * possible_new_dirs that it did the strdup'ing so that it
  2072. * will free them for us.
  2073. */
  2074. entry->possible_new_dirs.strdup_strings = 1;
  2075. string_list_clear(&entry->possible_new_dirs, 1);
  2076. }
  2077. return dir_renames;
  2078. }
  2079. static struct dir_rename_entry *check_dir_renamed(const char *path,
  2080. struct hashmap *dir_renames)
  2081. {
  2082. char *temp = xstrdup(path);
  2083. char *end;
  2084. struct dir_rename_entry *entry = NULL;
  2085. while ((end = strrchr(temp, '/'))) {
  2086. *end = '\0';
  2087. entry = dir_rename_find_entry(dir_renames, temp);
  2088. if (entry)
  2089. break;
  2090. }
  2091. free(temp);
  2092. return entry;
  2093. }
  2094. static void compute_collisions(struct hashmap *collisions,
  2095. struct hashmap *dir_renames,
  2096. struct diff_queue_struct *pairs)
  2097. {
  2098. int i;
  2099. /*
  2100. * Multiple files can be mapped to the same path due to directory
  2101. * renames done by the other side of history. Since that other
  2102. * side of history could have merged multiple directories into one,
  2103. * if our side of history added the same file basename to each of
  2104. * those directories, then all N of them would get implicitly
  2105. * renamed by the directory rename detection into the same path,
  2106. * and we'd get an add/add/.../add conflict, and all those adds
  2107. * from *this* side of history. This is not representable in the
  2108. * index, and users aren't going to easily be able to make sense of
  2109. * it. So we need to provide a good warning about what's
  2110. * happening, and fall back to no-directory-rename detection
  2111. * behavior for those paths.
  2112. *
  2113. * See testcases 9e and all of section 5 from t6043 for examples.
  2114. */
  2115. collision_init(collisions);
  2116. for (i = 0; i < pairs->nr; ++i) {
  2117. struct dir_rename_entry *dir_rename_ent;
  2118. struct collision_entry *collision_ent;
  2119. char *new_path;
  2120. struct diff_filepair *pair = pairs->queue[i];
  2121. if (pair->status != 'A' && pair->status != 'R')
  2122. continue;
  2123. dir_rename_ent = check_dir_renamed(pair->two->path,
  2124. dir_renames);
  2125. if (!dir_rename_ent)
  2126. continue;
  2127. new_path = apply_dir_rename(dir_rename_ent, pair->two->path);
  2128. if (!new_path)
  2129. /*
  2130. * dir_rename_ent->non_unique_new_path is true, which
  2131. * means there is no directory rename for us to use,
  2132. * which means it won't cause us any additional
  2133. * collisions.
  2134. */
  2135. continue;
  2136. collision_ent = collision_find_entry(collisions, new_path);
  2137. if (!collision_ent) {
  2138. collision_ent = xcalloc(1,
  2139. sizeof(struct collision_entry));
  2140. hashmap_entry_init(&collision_ent->ent,
  2141. strhash(new_path));
  2142. hashmap_put(collisions, &collision_ent->ent);
  2143. collision_ent->target_file = new_path;
  2144. } else {
  2145. free(new_path);
  2146. }
  2147. string_list_insert(&collision_ent->source_files,
  2148. pair->two->path);
  2149. }
  2150. }
  2151. static char *check_for_directory_rename(struct merge_options *opt,
  2152. const char *path,
  2153. struct tree *tree,
  2154. struct hashmap *dir_renames,
  2155. struct hashmap *dir_rename_exclusions,
  2156. struct hashmap *collisions,
  2157. int *clean_merge)
  2158. {
  2159. char *new_path = NULL;
  2160. struct dir_rename_entry *entry = check_dir_renamed(path, dir_renames);
  2161. struct dir_rename_entry *oentry = NULL;
  2162. if (!entry)
  2163. return new_path;
  2164. /*
  2165. * This next part is a little weird. We do not want to do an
  2166. * implicit rename into a directory we renamed on our side, because
  2167. * that will result in a spurious rename/rename(1to2) conflict. An
  2168. * example:
  2169. * Base commit: dumbdir/afile, otherdir/bfile
  2170. * Side 1: smrtdir/afile, otherdir/bfile
  2171. * Side 2: dumbdir/afile, dumbdir/bfile
  2172. * Here, while working on Side 1, we could notice that otherdir was
  2173. * renamed/merged to dumbdir, and change the diff_filepair for
  2174. * otherdir/bfile into a rename into dumbdir/bfile. However, Side
  2175. * 2 will notice the rename from dumbdir to smrtdir, and do the
  2176. * transitive rename to move it from dumbdir/bfile to
  2177. * smrtdir/bfile. That gives us bfile in dumbdir vs being in
  2178. * smrtdir, a rename/rename(1to2) conflict. We really just want
  2179. * the file to end up in smrtdir. And the way to achieve that is
  2180. * to not let Side1 do the rename to dumbdir, since we know that is
  2181. * the source of one of our directory renames.
  2182. *
  2183. * That's why oentry and dir_rename_exclusions is here.
  2184. *
  2185. * As it turns out, this also prevents N-way transient rename
  2186. * confusion; See testcases 9c and 9d of t6043.
  2187. */
  2188. oentry = dir_rename_find_entry(dir_rename_exclusions, entry->new_dir.buf);
  2189. if (oentry) {
  2190. output(opt, 1, _("WARNING: Avoiding applying %s -> %s rename "
  2191. "to %s, because %s itself was renamed."),
  2192. entry->dir, entry->new_dir.buf, path, entry->new_dir.buf);
  2193. } else {
  2194. new_path = handle_path_level_conflicts(opt, path, entry,
  2195. collisions, tree);
  2196. *clean_merge &= (new_path != NULL);
  2197. }
  2198. return new_path;
  2199. }
  2200. static void apply_directory_rename_modifications(struct merge_options *opt,
  2201. struct diff_filepair *pair,
  2202. char *new_path,
  2203. struct rename *re,
  2204. struct tree *tree,
  2205. struct tree *o_tree,
  2206. struct tree *a_tree,
  2207. struct tree *b_tree,
  2208. struct string_list *entries)
  2209. {
  2210. struct string_list_item *item;
  2211. int stage = (tree == a_tree ? 2 : 3);
  2212. int update_wd;
  2213. /*
  2214. * In all cases where we can do directory rename detection,
  2215. * unpack_trees() will have read pair->two->path into the
  2216. * index and the working copy. We need to remove it so that
  2217. * we can instead place it at new_path. It is guaranteed to
  2218. * not be untracked (unpack_trees() would have errored out
  2219. * saying the file would have been overwritten), but it might
  2220. * be dirty, though.
  2221. */
  2222. update_wd = !was_dirty(opt, pair->two->path);
  2223. if (!update_wd)
  2224. output(opt, 1, _("Refusing to lose dirty file at %s"),
  2225. pair->two->path);
  2226. remove_file(opt, 1, pair->two->path, !update_wd);
  2227. /* Find or create a new re->dst_entry */
  2228. item = string_list_lookup(entries, new_path);
  2229. if (item) {
  2230. /*
  2231. * Since we're renaming on this side of history, and it's
  2232. * due to a directory rename on the other side of history
  2233. * (which we only allow when the directory in question no
  2234. * longer exists on the other side of history), the
  2235. * original entry for re->dst_entry is no longer
  2236. * necessary...
  2237. */
  2238. re->dst_entry->processed = 1;
  2239. /*
  2240. * ...because we'll be using this new one.
  2241. */
  2242. re->dst_entry = item->util;
  2243. } else {
  2244. /*
  2245. * re->dst_entry is for the before-dir-rename path, and we
  2246. * need it to hold information for the after-dir-rename
  2247. * path. Before creating a new entry, we need to mark the
  2248. * old one as unnecessary (...unless it is shared by
  2249. * src_entry, i.e. this didn't use to be a rename, in which
  2250. * case we can just allow the normal processing to happen
  2251. * for it).
  2252. */
  2253. if (pair->status == 'R')
  2254. re->dst_entry->processed = 1;
  2255. re->dst_entry = insert_stage_data(opt->repo, new_path,
  2256. o_tree, a_tree, b_tree,
  2257. entries);
  2258. item = string_list_insert(entries, new_path);
  2259. item->util = re->dst_entry;
  2260. }
  2261. /*
  2262. * Update the stage_data with the information about the path we are
  2263. * moving into place. That slot will be empty and available for us
  2264. * to write to because of the collision checks in
  2265. * handle_path_level_conflicts(). In other words,
  2266. * re->dst_entry->stages[stage].oid will be the null_oid, so it's
  2267. * open for us to write to.
  2268. *
  2269. * It may be tempting to actually update the index at this point as
  2270. * well, using update_stages_for_stage_data(), but as per the big
  2271. * "NOTE" in update_stages(), doing so will modify the current
  2272. * in-memory index which will break calls to would_lose_untracked()
  2273. * that we need to make. Instead, we need to just make sure that
  2274. * the various handle_rename_*() functions update the index
  2275. * explicitly rather than relying on unpack_trees() to have done it.
  2276. */
  2277. get_tree_entry(opt->repo,
  2278. &tree->object.oid,
  2279. pair->two->path,
  2280. &re->dst_entry->stages[stage].oid,
  2281. &re->dst_entry->stages[stage].mode);
  2282. /*
  2283. * Record the original change status (or 'type' of change). If it
  2284. * was originally an add ('A'), this lets us differentiate later
  2285. * between a RENAME_DELETE conflict and RENAME_VIA_DIR (they
  2286. * otherwise look the same). If it was originally a rename ('R'),
  2287. * this lets us remember and report accurately about the transitive
  2288. * renaming that occurred via the directory rename detection. Also,
  2289. * record the original destination name.
  2290. */
  2291. re->dir_rename_original_type = pair->status;
  2292. re->dir_rename_original_dest = pair->two->path;
  2293. /*
  2294. * We don't actually look at pair->status again, but it seems
  2295. * pedagogically correct to adjust it.
  2296. */
  2297. pair->status = 'R';
  2298. /*
  2299. * Finally, record the new location.
  2300. */
  2301. pair->two->path = new_path;
  2302. }
  2303. /*
  2304. * Get information of all renames which occurred in 'pairs', making use of
  2305. * any implicit directory renames inferred from the other side of history.
  2306. * We need the three trees in the merge ('o_tree', 'a_tree' and 'b_tree')
  2307. * to be able to associate the correct cache entries with the rename
  2308. * information; tree is always equal to either a_tree or b_tree.
  2309. */
  2310. static struct string_list *get_renames(struct merge_options *opt,
  2311. const char *branch,
  2312. struct diff_queue_struct *pairs,
  2313. struct hashmap *dir_renames,
  2314. struct hashmap *dir_rename_exclusions,
  2315. struct tree *tree,
  2316. struct tree *o_tree,
  2317. struct tree *a_tree,
  2318. struct tree *b_tree,
  2319. struct string_list *entries,
  2320. int *clean_merge)
  2321. {
  2322. int i;
  2323. struct hashmap collisions;
  2324. struct hashmap_iter iter;
  2325. struct collision_entry *e;
  2326. struct string_list *renames;
  2327. compute_collisions(&collisions, dir_renames, pairs);
  2328. renames = xcalloc(1, sizeof(struct string_list));
  2329. for (i = 0; i < pairs->nr; ++i) {
  2330. struct string_list_item *item;
  2331. struct rename *re;
  2332. struct diff_filepair *pair = pairs->queue[i];
  2333. char *new_path; /* non-NULL only with directory renames */
  2334. if (pair->status != 'A' && pair->status != 'R') {
  2335. diff_free_filepair(pair);
  2336. continue;
  2337. }
  2338. new_path = check_for_directory_rename(opt, pair->two->path, tree,
  2339. dir_renames,
  2340. dir_rename_exclusions,
  2341. &collisions,
  2342. clean_merge);
  2343. if (pair->status != 'R' && !new_path) {
  2344. diff_free_filepair(pair);
  2345. continue;
  2346. }
  2347. re = xmalloc(sizeof(*re));
  2348. re->processed = 0;
  2349. re->pair = pair;
  2350. re->branch = branch;
  2351. re->dir_rename_original_type = '\0';
  2352. re->dir_rename_original_dest = NULL;
  2353. item = string_list_lookup(entries, re->pair->one->path);
  2354. if (!item)
  2355. re->src_entry = insert_stage_data(opt->repo,
  2356. re->pair->one->path,
  2357. o_tree, a_tree, b_tree, entries);
  2358. else
  2359. re->src_entry = item->util;
  2360. item = string_list_lookup(entries, re->pair->two->path);
  2361. if (!item)
  2362. re->dst_entry = insert_stage_data(opt->repo,
  2363. re->pair->two->path,
  2364. o_tree, a_tree, b_tree, entries);
  2365. else
  2366. re->dst_entry = item->util;
  2367. item = string_list_insert(renames, pair->one->path);
  2368. item->util = re;
  2369. if (new_path)
  2370. apply_directory_rename_modifications(opt, pair, new_path,
  2371. re, tree, o_tree,
  2372. a_tree, b_tree,
  2373. entries);
  2374. }
  2375. hashmap_for_each_entry(&collisions, &iter, e,
  2376. ent /* member name */) {
  2377. free(e->target_file);
  2378. string_list_clear(&e->source_files, 0);
  2379. }
  2380. hashmap_free_entries(&collisions, struct collision_entry, ent);
  2381. return renames;
  2382. }
  2383. static int process_renames(struct merge_options *opt,
  2384. struct string_list *a_renames,
  2385. struct string_list *b_renames)
  2386. {
  2387. int clean_merge = 1, i, j;
  2388. struct string_list a_by_dst = STRING_LIST_INIT_NODUP;
  2389. struct string_list b_by_dst = STRING_LIST_INIT_NODUP;
  2390. const struct rename *sre;
  2391. for (i = 0; i < a_renames->nr; i++) {
  2392. sre = a_renames->items[i].util;
  2393. string_list_insert(&a_by_dst, sre->pair->two->path)->util
  2394. = (void *)sre;
  2395. }
  2396. for (i = 0; i < b_renames->nr; i++) {
  2397. sre = b_renames->items[i].util;
  2398. string_list_insert(&b_by_dst, sre->pair->two->path)->util
  2399. = (void *)sre;
  2400. }
  2401. for (i = 0, j = 0; i < a_renames->nr || j < b_renames->nr;) {
  2402. struct string_list *renames1, *renames2Dst;
  2403. struct rename *ren1 = NULL, *ren2 = NULL;
  2404. const char *ren1_src, *ren1_dst;
  2405. struct string_list_item *lookup;
  2406. if (i >= a_renames->nr) {
  2407. ren2 = b_renames->items[j++].util;
  2408. } else if (j >= b_renames->nr) {
  2409. ren1 = a_renames->items[i++].util;
  2410. } else {
  2411. int compare = strcmp(a_renames->items[i].string,
  2412. b_renames->items[j].string);
  2413. if (compare <= 0)
  2414. ren1 = a_renames->items[i++].util;
  2415. if (compare >= 0)
  2416. ren2 = b_renames->items[j++].util;
  2417. }
  2418. /* TODO: refactor, so that 1/2 are not needed */
  2419. if (ren1) {
  2420. renames1 = a_renames;
  2421. renames2Dst = &b_by_dst;
  2422. } else {
  2423. renames1 = b_renames;
  2424. renames2Dst = &a_by_dst;
  2425. SWAP(ren2, ren1);
  2426. }
  2427. if (ren1->processed)
  2428. continue;
  2429. ren1->processed = 1;
  2430. ren1->dst_entry->processed = 1;
  2431. /* BUG: We should only mark src_entry as processed if we
  2432. * are not dealing with a rename + add-source case.
  2433. */
  2434. ren1->src_entry->processed = 1;
  2435. ren1_src = ren1->pair->one->path;
  2436. ren1_dst = ren1->pair->two->path;
  2437. if (ren2) {
  2438. /* One file renamed on both sides */
  2439. const char *ren2_src = ren2->pair->one->path;
  2440. const char *ren2_dst = ren2->pair->two->path;
  2441. enum rename_type rename_type;
  2442. if (strcmp(ren1_src, ren2_src) != 0)
  2443. BUG("ren1_src != ren2_src");
  2444. ren2->dst_entry->processed = 1;
  2445. ren2->processed = 1;
  2446. if (strcmp(ren1_dst, ren2_dst) != 0) {
  2447. rename_type = RENAME_ONE_FILE_TO_TWO;
  2448. clean_merge = 0;
  2449. } else {
  2450. rename_type = RENAME_ONE_FILE_TO_ONE;
  2451. /* BUG: We should only remove ren1_src in
  2452. * the base stage (think of rename +
  2453. * add-source cases).
  2454. */
  2455. remove_file(opt, 1, ren1_src, 1);
  2456. update_entry(ren1->dst_entry,
  2457. ren1->pair->one,
  2458. ren1->pair->two,
  2459. ren2->pair->two);
  2460. }
  2461. setup_rename_conflict_info(rename_type, opt, ren1, ren2);
  2462. } else if ((lookup = string_list_lookup(renames2Dst, ren1_dst))) {
  2463. /* Two different files renamed to the same thing */
  2464. char *ren2_dst;
  2465. ren2 = lookup->util;
  2466. ren2_dst = ren2->pair->two->path;
  2467. if (strcmp(ren1_dst, ren2_dst) != 0)
  2468. BUG("ren1_dst != ren2_dst");
  2469. clean_merge = 0;
  2470. ren2->processed = 1;
  2471. /*
  2472. * BUG: We should only mark src_entry as processed
  2473. * if we are not dealing with a rename + add-source
  2474. * case.
  2475. */
  2476. ren2->src_entry->processed = 1;
  2477. setup_rename_conflict_info(RENAME_TWO_FILES_TO_ONE,
  2478. opt, ren1, ren2);
  2479. } else {
  2480. /* Renamed in 1, maybe changed in 2 */
  2481. /* we only use sha1 and mode of these */
  2482. struct diff_filespec src_other, dst_other;
  2483. int try_merge;
  2484. /*
  2485. * unpack_trees loads entries from common-commit
  2486. * into stage 1, from head-commit into stage 2, and
  2487. * from merge-commit into stage 3. We keep track
  2488. * of which side corresponds to the rename.
  2489. */
  2490. int renamed_stage = a_renames == renames1 ? 2 : 3;
  2491. int other_stage = a_renames == renames1 ? 3 : 2;
  2492. /* BUG: We should only remove ren1_src in the base
  2493. * stage and in other_stage (think of rename +
  2494. * add-source case).
  2495. */
  2496. remove_file(opt, 1, ren1_src,
  2497. renamed_stage == 2 || !was_tracked(opt, ren1_src));
  2498. oidcpy(&src_other.oid,
  2499. &ren1->src_entry->stages[other_stage].oid);
  2500. src_other.mode = ren1->src_entry->stages[other_stage].mode;
  2501. oidcpy(&dst_other.oid,
  2502. &ren1->dst_entry->stages[other_stage].oid);
  2503. dst_other.mode = ren1->dst_entry->stages[other_stage].mode;
  2504. try_merge = 0;
  2505. if (oideq(&src_other.oid, &null_oid) &&
  2506. ren1->dir_rename_original_type == 'A') {
  2507. setup_rename_conflict_info(RENAME_VIA_DIR,
  2508. opt, ren1, NULL);
  2509. } else if (oideq(&src_other.oid, &null_oid)) {
  2510. setup_rename_conflict_info(RENAME_DELETE,
  2511. opt, ren1, NULL);
  2512. } else if ((dst_other.mode == ren1->pair->two->mode) &&
  2513. oideq(&dst_other.oid, &ren1->pair->two->oid)) {
  2514. /*
  2515. * Added file on the other side identical to
  2516. * the file being renamed: clean merge.
  2517. * Also, there is no need to overwrite the
  2518. * file already in the working copy, so call
  2519. * update_file_flags() instead of
  2520. * update_file().
  2521. */
  2522. if (update_file_flags(opt,
  2523. ren1->pair->two,
  2524. ren1_dst,
  2525. 1, /* update_cache */
  2526. 0 /* update_wd */))
  2527. clean_merge = -1;
  2528. } else if (!oideq(&dst_other.oid, &null_oid)) {
  2529. /*
  2530. * Probably not a clean merge, but it's
  2531. * premature to set clean_merge to 0 here,
  2532. * because if the rename merges cleanly and
  2533. * the merge exactly matches the newly added
  2534. * file, then the merge will be clean.
  2535. */
  2536. setup_rename_conflict_info(RENAME_ADD,
  2537. opt, ren1, NULL);
  2538. } else
  2539. try_merge = 1;
  2540. if (clean_merge < 0)
  2541. goto cleanup_and_return;
  2542. if (try_merge) {
  2543. struct diff_filespec *o, *a, *b;
  2544. src_other.path = (char *)ren1_src;
  2545. o = ren1->pair->one;
  2546. if (a_renames == renames1) {
  2547. a = ren1->pair->two;
  2548. b = &src_other;
  2549. } else {
  2550. b = ren1->pair->two;
  2551. a = &src_other;
  2552. }
  2553. update_entry(ren1->dst_entry, o, a, b);
  2554. setup_rename_conflict_info(RENAME_NORMAL,
  2555. opt, ren1, NULL);
  2556. }
  2557. }
  2558. }
  2559. cleanup_and_return:
  2560. string_list_clear(&a_by_dst, 0);
  2561. string_list_clear(&b_by_dst, 0);
  2562. return clean_merge;
  2563. }
  2564. struct rename_info {
  2565. struct string_list *head_renames;
  2566. struct string_list *merge_renames;
  2567. };
  2568. static void initial_cleanup_rename(struct diff_queue_struct *pairs,
  2569. struct hashmap *dir_renames)
  2570. {
  2571. struct hashmap_iter iter;
  2572. struct dir_rename_entry *e;
  2573. hashmap_for_each_entry(dir_renames, &iter, e,
  2574. ent /* member name */) {
  2575. free(e->dir);
  2576. strbuf_release(&e->new_dir);
  2577. /* possible_new_dirs already cleared in get_directory_renames */
  2578. }
  2579. hashmap_free_entries(dir_renames, struct dir_rename_entry, ent);
  2580. free(dir_renames);
  2581. free(pairs->queue);
  2582. free(pairs);
  2583. }
  2584. static int detect_and_process_renames(struct merge_options *opt,
  2585. struct tree *common,
  2586. struct tree *head,
  2587. struct tree *merge,
  2588. struct string_list *entries,
  2589. struct rename_info *ri)
  2590. {
  2591. struct diff_queue_struct *head_pairs, *merge_pairs;
  2592. struct hashmap *dir_re_head, *dir_re_merge;
  2593. int clean = 1;
  2594. ri->head_renames = NULL;
  2595. ri->merge_renames = NULL;
  2596. if (!merge_detect_rename(opt))
  2597. return 1;
  2598. head_pairs = get_diffpairs(opt, common, head);
  2599. merge_pairs = get_diffpairs(opt, common, merge);
  2600. if ((opt->detect_directory_renames == MERGE_DIRECTORY_RENAMES_TRUE) ||
  2601. (opt->detect_directory_renames == MERGE_DIRECTORY_RENAMES_CONFLICT &&
  2602. !opt->priv->call_depth)) {
  2603. dir_re_head = get_directory_renames(head_pairs);
  2604. dir_re_merge = get_directory_renames(merge_pairs);
  2605. handle_directory_level_conflicts(opt,
  2606. dir_re_head, head,
  2607. dir_re_merge, merge);
  2608. } else {
  2609. dir_re_head = xmalloc(sizeof(*dir_re_head));
  2610. dir_re_merge = xmalloc(sizeof(*dir_re_merge));
  2611. dir_rename_init(dir_re_head);
  2612. dir_rename_init(dir_re_merge);
  2613. }
  2614. ri->head_renames = get_renames(opt, opt->branch1, head_pairs,
  2615. dir_re_merge, dir_re_head, head,
  2616. common, head, merge, entries,
  2617. &clean);
  2618. if (clean < 0)
  2619. goto cleanup;
  2620. ri->merge_renames = get_renames(opt, opt->branch2, merge_pairs,
  2621. dir_re_head, dir_re_merge, merge,
  2622. common, head, merge, entries,
  2623. &clean);
  2624. if (clean < 0)
  2625. goto cleanup;
  2626. clean &= process_renames(opt, ri->head_renames, ri->merge_renames);
  2627. cleanup:
  2628. /*
  2629. * Some cleanup is deferred until cleanup_renames() because the
  2630. * data structures are still needed and referenced in
  2631. * process_entry(). But there are a few things we can free now.
  2632. */
  2633. initial_cleanup_rename(head_pairs, dir_re_head);
  2634. initial_cleanup_rename(merge_pairs, dir_re_merge);
  2635. return clean;
  2636. }
  2637. static void final_cleanup_rename(struct string_list *rename)
  2638. {
  2639. const struct rename *re;
  2640. int i;
  2641. if (rename == NULL)
  2642. return;
  2643. for (i = 0; i < rename->nr; i++) {
  2644. re = rename->items[i].util;
  2645. diff_free_filepair(re->pair);
  2646. }
  2647. string_list_clear(rename, 1);
  2648. free(rename);
  2649. }
  2650. static void final_cleanup_renames(struct rename_info *re_info)
  2651. {
  2652. final_cleanup_rename(re_info->head_renames);
  2653. final_cleanup_rename(re_info->merge_renames);
  2654. }
  2655. static int read_oid_strbuf(struct merge_options *opt,
  2656. const struct object_id *oid,
  2657. struct strbuf *dst)
  2658. {
  2659. void *buf;
  2660. enum object_type type;
  2661. unsigned long size;
  2662. buf = read_object_file(oid, &type, &size);
  2663. if (!buf)
  2664. return err(opt, _("cannot read object %s"), oid_to_hex(oid));
  2665. if (type != OBJ_BLOB) {
  2666. free(buf);
  2667. return err(opt, _("object %s is not a blob"), oid_to_hex(oid));
  2668. }
  2669. strbuf_attach(dst, buf, size, size + 1);
  2670. return 0;
  2671. }
  2672. static int blob_unchanged(struct merge_options *opt,
  2673. const struct diff_filespec *o,
  2674. const struct diff_filespec *a,
  2675. int renormalize, const char *path)
  2676. {
  2677. struct strbuf obuf = STRBUF_INIT;
  2678. struct strbuf abuf = STRBUF_INIT;
  2679. int ret = 0; /* assume changed for safety */
  2680. const struct index_state *idx = opt->repo->index;
  2681. if (a->mode != o->mode)
  2682. return 0;
  2683. if (oideq(&o->oid, &a->oid))
  2684. return 1;
  2685. if (!renormalize)
  2686. return 0;
  2687. if (read_oid_strbuf(opt, &o->oid, &obuf) ||
  2688. read_oid_strbuf(opt, &a->oid, &abuf))
  2689. goto error_return;
  2690. /*
  2691. * Note: binary | is used so that both renormalizations are
  2692. * performed. Comparison can be skipped if both files are
  2693. * unchanged since their sha1s have already been compared.
  2694. */
  2695. if (renormalize_buffer(idx, path, obuf.buf, obuf.len, &obuf) |
  2696. renormalize_buffer(idx, path, abuf.buf, abuf.len, &abuf))
  2697. ret = (obuf.len == abuf.len && !memcmp(obuf.buf, abuf.buf, obuf.len));
  2698. error_return:
  2699. strbuf_release(&obuf);
  2700. strbuf_release(&abuf);
  2701. return ret;
  2702. }
  2703. static int handle_modify_delete(struct merge_options *opt,
  2704. const char *path,
  2705. const struct diff_filespec *o,
  2706. const struct diff_filespec *a,
  2707. const struct diff_filespec *b)
  2708. {
  2709. const char *modify_branch, *delete_branch;
  2710. const struct diff_filespec *changed;
  2711. if (is_valid(a)) {
  2712. modify_branch = opt->branch1;
  2713. delete_branch = opt->branch2;
  2714. changed = a;
  2715. } else {
  2716. modify_branch = opt->branch2;
  2717. delete_branch = opt->branch1;
  2718. changed = b;
  2719. }
  2720. return handle_change_delete(opt,
  2721. path, NULL,
  2722. o, changed,
  2723. modify_branch, delete_branch,
  2724. _("modify"), _("modified"));
  2725. }
  2726. static int handle_content_merge(struct merge_file_info *mfi,
  2727. struct merge_options *opt,
  2728. const char *path,
  2729. int is_dirty,
  2730. const struct diff_filespec *o,
  2731. const struct diff_filespec *a,
  2732. const struct diff_filespec *b,
  2733. struct rename_conflict_info *ci)
  2734. {
  2735. const char *reason = _("content");
  2736. unsigned df_conflict_remains = 0;
  2737. if (!is_valid(o))
  2738. reason = _("add/add");
  2739. assert(o->path && a->path && b->path);
  2740. if (ci && dir_in_way(opt->repo->index, path, !opt->priv->call_depth,
  2741. S_ISGITLINK(ci->ren1->pair->two->mode)))
  2742. df_conflict_remains = 1;
  2743. if (merge_mode_and_contents(opt, o, a, b, path,
  2744. opt->branch1, opt->branch2,
  2745. opt->priv->call_depth * 2, mfi))
  2746. return -1;
  2747. /*
  2748. * We can skip updating the working tree file iff:
  2749. * a) The merge is clean
  2750. * b) The merge matches what was in HEAD (content, mode, pathname)
  2751. * c) The target path is usable (i.e. not involved in D/F conflict)
  2752. */
  2753. if (mfi->clean && was_tracked_and_matches(opt, path, &mfi->blob) &&
  2754. !df_conflict_remains) {
  2755. int pos;
  2756. struct cache_entry *ce;
  2757. output(opt, 3, _("Skipped %s (merged same as existing)"), path);
  2758. if (add_cacheinfo(opt, &mfi->blob, path,
  2759. 0, (!opt->priv->call_depth && !is_dirty), 0))
  2760. return -1;
  2761. /*
  2762. * However, add_cacheinfo() will delete the old cache entry
  2763. * and add a new one. We need to copy over any skip_worktree
  2764. * flag to avoid making the file appear as if it were
  2765. * deleted by the user.
  2766. */
  2767. pos = index_name_pos(&opt->priv->orig_index, path, strlen(path));
  2768. ce = opt->priv->orig_index.cache[pos];
  2769. if (ce_skip_worktree(ce)) {
  2770. pos = index_name_pos(opt->repo->index, path, strlen(path));
  2771. ce = opt->repo->index->cache[pos];
  2772. ce->ce_flags |= CE_SKIP_WORKTREE;
  2773. }
  2774. return mfi->clean;
  2775. }
  2776. if (!mfi->clean) {
  2777. if (S_ISGITLINK(mfi->blob.mode))
  2778. reason = _("submodule");
  2779. output(opt, 1, _("CONFLICT (%s): Merge conflict in %s"),
  2780. reason, path);
  2781. if (ci && !df_conflict_remains)
  2782. if (update_stages(opt, path, o, a, b))
  2783. return -1;
  2784. }
  2785. if (df_conflict_remains || is_dirty) {
  2786. char *new_path;
  2787. if (opt->priv->call_depth) {
  2788. remove_file_from_index(opt->repo->index, path);
  2789. } else {
  2790. if (!mfi->clean) {
  2791. if (update_stages(opt, path, o, a, b))
  2792. return -1;
  2793. } else {
  2794. int file_from_stage2 = was_tracked(opt, path);
  2795. if (update_stages(opt, path, NULL,
  2796. file_from_stage2 ? &mfi->blob : NULL,
  2797. file_from_stage2 ? NULL : &mfi->blob))
  2798. return -1;
  2799. }
  2800. }
  2801. new_path = unique_path(opt, path, ci->ren1->branch);
  2802. if (is_dirty) {
  2803. output(opt, 1, _("Refusing to lose dirty file at %s"),
  2804. path);
  2805. }
  2806. output(opt, 1, _("Adding as %s instead"), new_path);
  2807. if (update_file(opt, 0, &mfi->blob, new_path)) {
  2808. free(new_path);
  2809. return -1;
  2810. }
  2811. free(new_path);
  2812. mfi->clean = 0;
  2813. } else if (update_file(opt, mfi->clean, &mfi->blob, path))
  2814. return -1;
  2815. return !is_dirty && mfi->clean;
  2816. }
  2817. static int handle_rename_normal(struct merge_options *opt,
  2818. const char *path,
  2819. const struct diff_filespec *o,
  2820. const struct diff_filespec *a,
  2821. const struct diff_filespec *b,
  2822. struct rename_conflict_info *ci)
  2823. {
  2824. struct rename *ren = ci->ren1;
  2825. struct merge_file_info mfi;
  2826. int clean;
  2827. int side = (ren->branch == opt->branch1 ? 2 : 3);
  2828. /* Merge the content and write it out */
  2829. clean = handle_content_merge(&mfi, opt, path, was_dirty(opt, path),
  2830. o, a, b, ci);
  2831. if (clean &&
  2832. opt->detect_directory_renames == MERGE_DIRECTORY_RENAMES_CONFLICT &&
  2833. ren->dir_rename_original_dest) {
  2834. if (update_stages(opt, path,
  2835. NULL,
  2836. side == 2 ? &mfi.blob : NULL,
  2837. side == 2 ? NULL : &mfi.blob))
  2838. return -1;
  2839. clean = 0; /* not clean, but conflicted */
  2840. }
  2841. return clean;
  2842. }
  2843. static void dir_rename_warning(const char *msg,
  2844. int is_add,
  2845. int clean,
  2846. struct merge_options *opt,
  2847. struct rename *ren)
  2848. {
  2849. const char *other_branch;
  2850. other_branch = (ren->branch == opt->branch1 ?
  2851. opt->branch2 : opt->branch1);
  2852. if (is_add) {
  2853. output(opt, clean ? 2 : 1, msg,
  2854. ren->pair->one->path, ren->branch,
  2855. other_branch, ren->pair->two->path);
  2856. return;
  2857. }
  2858. output(opt, clean ? 2 : 1, msg,
  2859. ren->pair->one->path, ren->dir_rename_original_dest, ren->branch,
  2860. other_branch, ren->pair->two->path);
  2861. }
  2862. static int warn_about_dir_renamed_entries(struct merge_options *opt,
  2863. struct rename *ren)
  2864. {
  2865. const char *msg;
  2866. int clean = 1, is_add;
  2867. if (!ren)
  2868. return clean;
  2869. /* Return early if ren was not affected/created by a directory rename */
  2870. if (!ren->dir_rename_original_dest)
  2871. return clean;
  2872. /* Sanity checks */
  2873. assert(opt->detect_directory_renames > MERGE_DIRECTORY_RENAMES_NONE);
  2874. assert(ren->dir_rename_original_type == 'A' ||
  2875. ren->dir_rename_original_type == 'R');
  2876. /* Check whether to treat directory renames as a conflict */
  2877. clean = (opt->detect_directory_renames == MERGE_DIRECTORY_RENAMES_TRUE);
  2878. is_add = (ren->dir_rename_original_type == 'A');
  2879. if (ren->dir_rename_original_type == 'A' && clean) {
  2880. msg = _("Path updated: %s added in %s inside a "
  2881. "directory that was renamed in %s; moving it to %s.");
  2882. } else if (ren->dir_rename_original_type == 'A' && !clean) {
  2883. msg = _("CONFLICT (file location): %s added in %s "
  2884. "inside a directory that was renamed in %s, "
  2885. "suggesting it should perhaps be moved to %s.");
  2886. } else if (ren->dir_rename_original_type == 'R' && clean) {
  2887. msg = _("Path updated: %s renamed to %s in %s, inside a "
  2888. "directory that was renamed in %s; moving it to %s.");
  2889. } else if (ren->dir_rename_original_type == 'R' && !clean) {
  2890. msg = _("CONFLICT (file location): %s renamed to %s in %s, "
  2891. "inside a directory that was renamed in %s, "
  2892. "suggesting it should perhaps be moved to %s.");
  2893. } else {
  2894. BUG("Impossible dir_rename_original_type/clean combination");
  2895. }
  2896. dir_rename_warning(msg, is_add, clean, opt, ren);
  2897. return clean;
  2898. }
  2899. /* Per entry merge function */
  2900. static int process_entry(struct merge_options *opt,
  2901. const char *path, struct stage_data *entry)
  2902. {
  2903. int clean_merge = 1;
  2904. int normalize = opt->renormalize;
  2905. struct diff_filespec *o = &entry->stages[1];
  2906. struct diff_filespec *a = &entry->stages[2];
  2907. struct diff_filespec *b = &entry->stages[3];
  2908. int o_valid = is_valid(o);
  2909. int a_valid = is_valid(a);
  2910. int b_valid = is_valid(b);
  2911. o->path = a->path = b->path = (char*)path;
  2912. entry->processed = 1;
  2913. if (entry->rename_conflict_info) {
  2914. struct rename_conflict_info *ci = entry->rename_conflict_info;
  2915. struct diff_filespec *temp;
  2916. int path_clean;
  2917. path_clean = warn_about_dir_renamed_entries(opt, ci->ren1);
  2918. path_clean &= warn_about_dir_renamed_entries(opt, ci->ren2);
  2919. /*
  2920. * For cases with a single rename, {o,a,b}->path have all been
  2921. * set to the rename target path; we need to set two of these
  2922. * back to the rename source.
  2923. * For rename/rename conflicts, we'll manually fix paths below.
  2924. */
  2925. temp = (opt->branch1 == ci->ren1->branch) ? b : a;
  2926. o->path = temp->path = ci->ren1->pair->one->path;
  2927. if (ci->ren2) {
  2928. assert(opt->branch1 == ci->ren1->branch);
  2929. }
  2930. switch (ci->rename_type) {
  2931. case RENAME_NORMAL:
  2932. case RENAME_ONE_FILE_TO_ONE:
  2933. clean_merge = handle_rename_normal(opt, path, o, a, b,
  2934. ci);
  2935. break;
  2936. case RENAME_VIA_DIR:
  2937. clean_merge = handle_rename_via_dir(opt, ci);
  2938. break;
  2939. case RENAME_ADD:
  2940. /*
  2941. * Probably unclean merge, but if the renamed file
  2942. * merges cleanly and the result can then be
  2943. * two-way merged cleanly with the added file, I
  2944. * guess it's a clean merge?
  2945. */
  2946. clean_merge = handle_rename_add(opt, ci);
  2947. break;
  2948. case RENAME_DELETE:
  2949. clean_merge = 0;
  2950. if (handle_rename_delete(opt, ci))
  2951. clean_merge = -1;
  2952. break;
  2953. case RENAME_ONE_FILE_TO_TWO:
  2954. /*
  2955. * Manually fix up paths; note:
  2956. * ren[12]->pair->one->path are equal.
  2957. */
  2958. o->path = ci->ren1->pair->one->path;
  2959. a->path = ci->ren1->pair->two->path;
  2960. b->path = ci->ren2->pair->two->path;
  2961. clean_merge = 0;
  2962. if (handle_rename_rename_1to2(opt, ci))
  2963. clean_merge = -1;
  2964. break;
  2965. case RENAME_TWO_FILES_TO_ONE:
  2966. /*
  2967. * Manually fix up paths; note,
  2968. * ren[12]->pair->two->path are actually equal.
  2969. */
  2970. o->path = NULL;
  2971. a->path = ci->ren1->pair->two->path;
  2972. b->path = ci->ren2->pair->two->path;
  2973. /*
  2974. * Probably unclean merge, but if the two renamed
  2975. * files merge cleanly and the two resulting files
  2976. * can then be two-way merged cleanly, I guess it's
  2977. * a clean merge?
  2978. */
  2979. clean_merge = handle_rename_rename_2to1(opt, ci);
  2980. break;
  2981. default:
  2982. entry->processed = 0;
  2983. break;
  2984. }
  2985. if (path_clean < clean_merge)
  2986. clean_merge = path_clean;
  2987. } else if (o_valid && (!a_valid || !b_valid)) {
  2988. /* Case A: Deleted in one */
  2989. if ((!a_valid && !b_valid) ||
  2990. (!b_valid && blob_unchanged(opt, o, a, normalize, path)) ||
  2991. (!a_valid && blob_unchanged(opt, o, b, normalize, path))) {
  2992. /* Deleted in both or deleted in one and
  2993. * unchanged in the other */
  2994. if (a_valid)
  2995. output(opt, 2, _("Removing %s"), path);
  2996. /* do not touch working file if it did not exist */
  2997. remove_file(opt, 1, path, !a_valid);
  2998. } else {
  2999. /* Modify/delete; deleted side may have put a directory in the way */
  3000. clean_merge = 0;
  3001. if (handle_modify_delete(opt, path, o, a, b))
  3002. clean_merge = -1;
  3003. }
  3004. } else if ((!o_valid && a_valid && !b_valid) ||
  3005. (!o_valid && !a_valid && b_valid)) {
  3006. /* Case B: Added in one. */
  3007. /* [nothing|directory] -> ([nothing|directory], file) */
  3008. const char *add_branch;
  3009. const char *other_branch;
  3010. const char *conf;
  3011. const struct diff_filespec *contents;
  3012. if (a_valid) {
  3013. add_branch = opt->branch1;
  3014. other_branch = opt->branch2;
  3015. contents = a;
  3016. conf = _("file/directory");
  3017. } else {
  3018. add_branch = opt->branch2;
  3019. other_branch = opt->branch1;
  3020. contents = b;
  3021. conf = _("directory/file");
  3022. }
  3023. if (dir_in_way(opt->repo->index, path,
  3024. !opt->priv->call_depth && !S_ISGITLINK(a->mode),
  3025. 0)) {
  3026. char *new_path = unique_path(opt, path, add_branch);
  3027. clean_merge = 0;
  3028. output(opt, 1, _("CONFLICT (%s): There is a directory with name %s in %s. "
  3029. "Adding %s as %s"),
  3030. conf, path, other_branch, path, new_path);
  3031. if (update_file(opt, 0, contents, new_path))
  3032. clean_merge = -1;
  3033. else if (opt->priv->call_depth)
  3034. remove_file_from_index(opt->repo->index, path);
  3035. free(new_path);
  3036. } else {
  3037. output(opt, 2, _("Adding %s"), path);
  3038. /* do not overwrite file if already present */
  3039. if (update_file_flags(opt, contents, path, 1, !a_valid))
  3040. clean_merge = -1;
  3041. }
  3042. } else if (a_valid && b_valid) {
  3043. if (!o_valid) {
  3044. /* Case C: Added in both (check for same permissions) */
  3045. output(opt, 1,
  3046. _("CONFLICT (add/add): Merge conflict in %s"),
  3047. path);
  3048. clean_merge = handle_file_collision(opt,
  3049. path, NULL, NULL,
  3050. opt->branch1,
  3051. opt->branch2,
  3052. a, b);
  3053. } else {
  3054. /* case D: Modified in both, but differently. */
  3055. struct merge_file_info mfi;
  3056. int is_dirty = 0; /* unpack_trees would have bailed if dirty */
  3057. clean_merge = handle_content_merge(&mfi, opt, path,
  3058. is_dirty,
  3059. o, a, b, NULL);
  3060. }
  3061. } else if (!o_valid && !a_valid && !b_valid) {
  3062. /*
  3063. * this entry was deleted altogether. a_mode == 0 means
  3064. * we had that path and want to actively remove it.
  3065. */
  3066. remove_file(opt, 1, path, !a->mode);
  3067. } else
  3068. BUG("fatal merge failure, shouldn't happen.");
  3069. return clean_merge;
  3070. }
  3071. static int merge_trees_internal(struct merge_options *opt,
  3072. struct tree *head,
  3073. struct tree *merge,
  3074. struct tree *merge_base,
  3075. struct tree **result)
  3076. {
  3077. struct index_state *istate = opt->repo->index;
  3078. int code, clean;
  3079. if (opt->subtree_shift) {
  3080. merge = shift_tree_object(opt->repo, head, merge,
  3081. opt->subtree_shift);
  3082. merge_base = shift_tree_object(opt->repo, head, merge_base,
  3083. opt->subtree_shift);
  3084. }
  3085. if (oideq(&merge_base->object.oid, &merge->object.oid)) {
  3086. output(opt, 0, _("Already up to date!"));
  3087. *result = head;
  3088. return 1;
  3089. }
  3090. code = unpack_trees_start(opt, merge_base, head, merge);
  3091. if (code != 0) {
  3092. if (show(opt, 4) || opt->priv->call_depth)
  3093. err(opt, _("merging of trees %s and %s failed"),
  3094. oid_to_hex(&head->object.oid),
  3095. oid_to_hex(&merge->object.oid));
  3096. unpack_trees_finish(opt);
  3097. return -1;
  3098. }
  3099. if (unmerged_index(istate)) {
  3100. struct string_list *entries;
  3101. struct rename_info re_info;
  3102. int i;
  3103. /*
  3104. * Only need the hashmap while processing entries, so
  3105. * initialize it here and free it when we are done running
  3106. * through the entries. Keeping it in the merge_options as
  3107. * opposed to decaring a local hashmap is for convenience
  3108. * so that we don't have to pass it to around.
  3109. */
  3110. hashmap_init(&opt->priv->current_file_dir_set, path_hashmap_cmp,
  3111. NULL, 512);
  3112. get_files_dirs(opt, head);
  3113. get_files_dirs(opt, merge);
  3114. entries = get_unmerged(opt->repo->index);
  3115. clean = detect_and_process_renames(opt, merge_base, head, merge,
  3116. entries, &re_info);
  3117. record_df_conflict_files(opt, entries);
  3118. if (clean < 0)
  3119. goto cleanup;
  3120. for (i = entries->nr-1; 0 <= i; i--) {
  3121. const char *path = entries->items[i].string;
  3122. struct stage_data *e = entries->items[i].util;
  3123. if (!e->processed) {
  3124. int ret = process_entry(opt, path, e);
  3125. if (!ret)
  3126. clean = 0;
  3127. else if (ret < 0) {
  3128. clean = ret;
  3129. goto cleanup;
  3130. }
  3131. }
  3132. }
  3133. for (i = 0; i < entries->nr; i++) {
  3134. struct stage_data *e = entries->items[i].util;
  3135. if (!e->processed)
  3136. BUG("unprocessed path??? %s",
  3137. entries->items[i].string);
  3138. }
  3139. cleanup:
  3140. final_cleanup_renames(&re_info);
  3141. string_list_clear(entries, 1);
  3142. free(entries);
  3143. hashmap_free_entries(&opt->priv->current_file_dir_set,
  3144. struct path_hashmap_entry, e);
  3145. if (clean < 0) {
  3146. unpack_trees_finish(opt);
  3147. return clean;
  3148. }
  3149. }
  3150. else
  3151. clean = 1;
  3152. unpack_trees_finish(opt);
  3153. if (opt->priv->call_depth &&
  3154. !(*result = write_in_core_index_as_tree(opt->repo)))
  3155. return -1;
  3156. return clean;
  3157. }
  3158. static struct commit_list *reverse_commit_list(struct commit_list *list)
  3159. {
  3160. struct commit_list *next = NULL, *current, *backup;
  3161. for (current = list; current; current = backup) {
  3162. backup = current->next;
  3163. current->next = next;
  3164. next = current;
  3165. }
  3166. return next;
  3167. }
  3168. /*
  3169. * Merge the commits h1 and h2, returning a flag (int) indicating the
  3170. * cleanness of the merge. Also, if opt->priv->call_depth, create a
  3171. * virtual commit and write its location to *result.
  3172. */
  3173. static int merge_recursive_internal(struct merge_options *opt,
  3174. struct commit *h1,
  3175. struct commit *h2,
  3176. struct commit_list *merge_bases,
  3177. struct commit **result)
  3178. {
  3179. struct commit_list *iter;
  3180. struct commit *merged_merge_bases;
  3181. struct tree *result_tree;
  3182. int clean;
  3183. const char *ancestor_name;
  3184. struct strbuf merge_base_abbrev = STRBUF_INIT;
  3185. if (show(opt, 4)) {
  3186. output(opt, 4, _("Merging:"));
  3187. output_commit_title(opt, h1);
  3188. output_commit_title(opt, h2);
  3189. }
  3190. if (!merge_bases) {
  3191. merge_bases = get_merge_bases(h1, h2);
  3192. merge_bases = reverse_commit_list(merge_bases);
  3193. }
  3194. if (show(opt, 5)) {
  3195. unsigned cnt = commit_list_count(merge_bases);
  3196. output(opt, 5, Q_("found %u common ancestor:",
  3197. "found %u common ancestors:", cnt), cnt);
  3198. for (iter = merge_bases; iter; iter = iter->next)
  3199. output_commit_title(opt, iter->item);
  3200. }
  3201. merged_merge_bases = pop_commit(&merge_bases);
  3202. if (merged_merge_bases == NULL) {
  3203. /* if there is no common ancestor, use an empty tree */
  3204. struct tree *tree;
  3205. tree = lookup_tree(opt->repo, opt->repo->hash_algo->empty_tree);
  3206. merged_merge_bases = make_virtual_commit(opt->repo, tree,
  3207. "ancestor");
  3208. ancestor_name = "empty tree";
  3209. } else if (opt->ancestor && !opt->priv->call_depth) {
  3210. ancestor_name = opt->ancestor;
  3211. } else if (merge_bases) {
  3212. ancestor_name = "merged common ancestors";
  3213. } else {
  3214. strbuf_add_unique_abbrev(&merge_base_abbrev,
  3215. &merged_merge_bases->object.oid,
  3216. DEFAULT_ABBREV);
  3217. ancestor_name = merge_base_abbrev.buf;
  3218. }
  3219. for (iter = merge_bases; iter; iter = iter->next) {
  3220. const char *saved_b1, *saved_b2;
  3221. opt->priv->call_depth++;
  3222. /*
  3223. * When the merge fails, the result contains files
  3224. * with conflict markers. The cleanness flag is
  3225. * ignored (unless indicating an error), it was never
  3226. * actually used, as result of merge_trees has always
  3227. * overwritten it: the committed "conflicts" were
  3228. * already resolved.
  3229. */
  3230. discard_index(opt->repo->index);
  3231. saved_b1 = opt->branch1;
  3232. saved_b2 = opt->branch2;
  3233. opt->branch1 = "Temporary merge branch 1";
  3234. opt->branch2 = "Temporary merge branch 2";
  3235. if (merge_recursive_internal(opt, merged_merge_bases, iter->item,
  3236. NULL, &merged_merge_bases) < 0)
  3237. return -1;
  3238. opt->branch1 = saved_b1;
  3239. opt->branch2 = saved_b2;
  3240. opt->priv->call_depth--;
  3241. if (!merged_merge_bases)
  3242. return err(opt, _("merge returned no commit"));
  3243. }
  3244. discard_index(opt->repo->index);
  3245. if (!opt->priv->call_depth)
  3246. repo_read_index(opt->repo);
  3247. opt->ancestor = ancestor_name;
  3248. clean = merge_trees_internal(opt,
  3249. repo_get_commit_tree(opt->repo, h1),
  3250. repo_get_commit_tree(opt->repo, h2),
  3251. repo_get_commit_tree(opt->repo,
  3252. merged_merge_bases),
  3253. &result_tree);
  3254. strbuf_release(&merge_base_abbrev);
  3255. opt->ancestor = NULL; /* avoid accidental re-use of opt->ancestor */
  3256. if (clean < 0) {
  3257. flush_output(opt);
  3258. return clean;
  3259. }
  3260. if (opt->priv->call_depth) {
  3261. *result = make_virtual_commit(opt->repo, result_tree,
  3262. "merged tree");
  3263. commit_list_insert(h1, &(*result)->parents);
  3264. commit_list_insert(h2, &(*result)->parents->next);
  3265. }
  3266. return clean;
  3267. }
  3268. static int merge_start(struct merge_options *opt, struct tree *head)
  3269. {
  3270. struct strbuf sb = STRBUF_INIT;
  3271. /* Sanity checks on opt */
  3272. assert(opt->repo);
  3273. assert(opt->branch1 && opt->branch2);
  3274. assert(opt->detect_renames >= -1 &&
  3275. opt->detect_renames <= DIFF_DETECT_COPY);
  3276. assert(opt->detect_directory_renames >= MERGE_DIRECTORY_RENAMES_NONE &&
  3277. opt->detect_directory_renames <= MERGE_DIRECTORY_RENAMES_TRUE);
  3278. assert(opt->rename_limit >= -1);
  3279. assert(opt->rename_score >= 0 && opt->rename_score <= MAX_SCORE);
  3280. assert(opt->show_rename_progress >= 0 && opt->show_rename_progress <= 1);
  3281. assert(opt->xdl_opts >= 0);
  3282. assert(opt->recursive_variant >= MERGE_VARIANT_NORMAL &&
  3283. opt->recursive_variant <= MERGE_VARIANT_THEIRS);
  3284. assert(opt->verbosity >= 0 && opt->verbosity <= 5);
  3285. assert(opt->buffer_output <= 2);
  3286. assert(opt->obuf.len == 0);
  3287. assert(opt->priv == NULL);
  3288. /* Sanity check on repo state; index must match head */
  3289. if (repo_index_has_changes(opt->repo, head, &sb)) {
  3290. err(opt, _("Your local changes to the following files would be overwritten by merge:\n %s"),
  3291. sb.buf);
  3292. strbuf_release(&sb);
  3293. return -1;
  3294. }
  3295. opt->priv = xcalloc(1, sizeof(*opt->priv));
  3296. string_list_init(&opt->priv->df_conflict_file_set, 1);
  3297. return 0;
  3298. }
  3299. static void merge_finalize(struct merge_options *opt)
  3300. {
  3301. flush_output(opt);
  3302. if (!opt->priv->call_depth && opt->buffer_output < 2)
  3303. strbuf_release(&opt->obuf);
  3304. if (show(opt, 2))
  3305. diff_warn_rename_limit("merge.renamelimit",
  3306. opt->priv->needed_rename_limit, 0);
  3307. FREE_AND_NULL(opt->priv);
  3308. }
  3309. int merge_trees(struct merge_options *opt,
  3310. struct tree *head,
  3311. struct tree *merge,
  3312. struct tree *merge_base)
  3313. {
  3314. int clean;
  3315. struct tree *ignored;
  3316. assert(opt->ancestor != NULL);
  3317. if (merge_start(opt, head))
  3318. return -1;
  3319. clean = merge_trees_internal(opt, head, merge, merge_base, &ignored);
  3320. merge_finalize(opt);
  3321. return clean;
  3322. }
  3323. int merge_recursive(struct merge_options *opt,
  3324. struct commit *h1,
  3325. struct commit *h2,
  3326. struct commit_list *merge_bases,
  3327. struct commit **result)
  3328. {
  3329. int clean;
  3330. assert(opt->ancestor == NULL ||
  3331. !strcmp(opt->ancestor, "constructed merge base"));
  3332. if (merge_start(opt, repo_get_commit_tree(opt->repo, h1)))
  3333. return -1;
  3334. clean = merge_recursive_internal(opt, h1, h2, merge_bases, result);
  3335. merge_finalize(opt);
  3336. return clean;
  3337. }
  3338. static struct commit *get_ref(struct repository *repo,
  3339. const struct object_id *oid,
  3340. const char *name)
  3341. {
  3342. struct object *object;
  3343. object = deref_tag(repo, parse_object(repo, oid),
  3344. name, strlen(name));
  3345. if (!object)
  3346. return NULL;
  3347. if (object->type == OBJ_TREE)
  3348. return make_virtual_commit(repo, (struct tree*)object, name);
  3349. if (object->type != OBJ_COMMIT)
  3350. return NULL;
  3351. if (parse_commit((struct commit *)object))
  3352. return NULL;
  3353. return (struct commit *)object;
  3354. }
  3355. int merge_recursive_generic(struct merge_options *opt,
  3356. const struct object_id *head,
  3357. const struct object_id *merge,
  3358. int num_merge_bases,
  3359. const struct object_id **merge_bases,
  3360. struct commit **result)
  3361. {
  3362. int clean;
  3363. struct lock_file lock = LOCK_INIT;
  3364. struct commit *head_commit = get_ref(opt->repo, head, opt->branch1);
  3365. struct commit *next_commit = get_ref(opt->repo, merge, opt->branch2);
  3366. struct commit_list *ca = NULL;
  3367. if (merge_bases) {
  3368. int i;
  3369. for (i = 0; i < num_merge_bases; ++i) {
  3370. struct commit *base;
  3371. if (!(base = get_ref(opt->repo, merge_bases[i],
  3372. oid_to_hex(merge_bases[i]))))
  3373. return err(opt, _("Could not parse object '%s'"),
  3374. oid_to_hex(merge_bases[i]));
  3375. commit_list_insert(base, &ca);
  3376. }
  3377. if (num_merge_bases == 1)
  3378. opt->ancestor = "constructed merge base";
  3379. }
  3380. repo_hold_locked_index(opt->repo, &lock, LOCK_DIE_ON_ERROR);
  3381. clean = merge_recursive(opt, head_commit, next_commit, ca,
  3382. result);
  3383. if (clean < 0) {
  3384. rollback_lock_file(&lock);
  3385. return clean;
  3386. }
  3387. if (write_locked_index(opt->repo->index, &lock,
  3388. COMMIT_LOCK | SKIP_IF_UNCHANGED))
  3389. return err(opt, _("Unable to write index."));
  3390. return clean ? 0 : 1;
  3391. }
  3392. static void merge_recursive_config(struct merge_options *opt)
  3393. {
  3394. char *value = NULL;
  3395. int renormalize = 0;
  3396. git_config_get_int("merge.verbosity", &opt->verbosity);
  3397. git_config_get_int("diff.renamelimit", &opt->rename_limit);
  3398. git_config_get_int("merge.renamelimit", &opt->rename_limit);
  3399. git_config_get_bool("merge.renormalize", &renormalize);
  3400. opt->renormalize = renormalize;
  3401. if (!git_config_get_string("diff.renames", &value)) {
  3402. opt->detect_renames = git_config_rename("diff.renames", value);
  3403. free(value);
  3404. }
  3405. if (!git_config_get_string("merge.renames", &value)) {
  3406. opt->detect_renames = git_config_rename("merge.renames", value);
  3407. free(value);
  3408. }
  3409. if (!git_config_get_string("merge.directoryrenames", &value)) {
  3410. int boolval = git_parse_maybe_bool(value);
  3411. if (0 <= boolval) {
  3412. opt->detect_directory_renames = boolval ?
  3413. MERGE_DIRECTORY_RENAMES_TRUE :
  3414. MERGE_DIRECTORY_RENAMES_NONE;
  3415. } else if (!strcasecmp(value, "conflict")) {
  3416. opt->detect_directory_renames =
  3417. MERGE_DIRECTORY_RENAMES_CONFLICT;
  3418. } /* avoid erroring on values from future versions of git */
  3419. free(value);
  3420. }
  3421. git_config(git_xmerge_config, NULL);
  3422. }
  3423. void init_merge_options(struct merge_options *opt,
  3424. struct repository *repo)
  3425. {
  3426. const char *merge_verbosity;
  3427. memset(opt, 0, sizeof(struct merge_options));
  3428. opt->repo = repo;
  3429. opt->detect_renames = -1;
  3430. opt->detect_directory_renames = MERGE_DIRECTORY_RENAMES_CONFLICT;
  3431. opt->rename_limit = -1;
  3432. opt->verbosity = 2;
  3433. opt->buffer_output = 1;
  3434. strbuf_init(&opt->obuf, 0);
  3435. opt->renormalize = 0;
  3436. merge_recursive_config(opt);
  3437. merge_verbosity = getenv("GIT_MERGE_VERBOSITY");
  3438. if (merge_verbosity)
  3439. opt->verbosity = strtol(merge_verbosity, NULL, 10);
  3440. if (opt->verbosity >= 5)
  3441. opt->buffer_output = 0;
  3442. }
  3443. int parse_merge_opt(struct merge_options *opt, const char *s)
  3444. {
  3445. const char *arg;
  3446. if (!s || !*s)
  3447. return -1;
  3448. if (!strcmp(s, "ours"))
  3449. opt->recursive_variant = MERGE_VARIANT_OURS;
  3450. else if (!strcmp(s, "theirs"))
  3451. opt->recursive_variant = MERGE_VARIANT_THEIRS;
  3452. else if (!strcmp(s, "subtree"))
  3453. opt->subtree_shift = "";
  3454. else if (skip_prefix(s, "subtree=", &arg))
  3455. opt->subtree_shift = arg;
  3456. else if (!strcmp(s, "patience"))
  3457. opt->xdl_opts = DIFF_WITH_ALG(opt, PATIENCE_DIFF);
  3458. else if (!strcmp(s, "histogram"))
  3459. opt->xdl_opts = DIFF_WITH_ALG(opt, HISTOGRAM_DIFF);
  3460. else if (skip_prefix(s, "diff-algorithm=", &arg)) {
  3461. long value = parse_algorithm_value(arg);
  3462. if (value < 0)
  3463. return -1;
  3464. /* clear out previous settings */
  3465. DIFF_XDL_CLR(opt, NEED_MINIMAL);
  3466. opt->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
  3467. opt->xdl_opts |= value;
  3468. }
  3469. else if (!strcmp(s, "ignore-space-change"))
  3470. DIFF_XDL_SET(opt, IGNORE_WHITESPACE_CHANGE);
  3471. else if (!strcmp(s, "ignore-all-space"))
  3472. DIFF_XDL_SET(opt, IGNORE_WHITESPACE);
  3473. else if (!strcmp(s, "ignore-space-at-eol"))
  3474. DIFF_XDL_SET(opt, IGNORE_WHITESPACE_AT_EOL);
  3475. else if (!strcmp(s, "ignore-cr-at-eol"))
  3476. DIFF_XDL_SET(opt, IGNORE_CR_AT_EOL);
  3477. else if (!strcmp(s, "renormalize"))
  3478. opt->renormalize = 1;
  3479. else if (!strcmp(s, "no-renormalize"))
  3480. opt->renormalize = 0;
  3481. else if (!strcmp(s, "no-renames"))
  3482. opt->detect_renames = 0;
  3483. else if (!strcmp(s, "find-renames")) {
  3484. opt->detect_renames = 1;
  3485. opt->rename_score = 0;
  3486. }
  3487. else if (skip_prefix(s, "find-renames=", &arg) ||
  3488. skip_prefix(s, "rename-threshold=", &arg)) {
  3489. if ((opt->rename_score = parse_rename_score(&arg)) == -1 || *arg != 0)
  3490. return -1;
  3491. opt->detect_renames = 1;
  3492. }
  3493. /*
  3494. * Please update $__git_merge_strategy_options in
  3495. * git-completion.bash when you add new options
  3496. */
  3497. else
  3498. return -1;
  3499. return 0;
  3500. }