You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

DirCacheCheckoutTest.java 64KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096
  1. /*
  2. * Copyright (C) 2007, Dave Watson <dwatson@mimvista.com>
  3. * Copyright (C) 2008-2011, Shawn O. Pearce <spearce@spearce.org>
  4. * Copyright (C) 2008-2011, Robin Rosenberg <robin.rosenberg@dewire.com>
  5. * Copyright (C) 2010-2011, Christian Halstrick <christian.halstrick@sap.com>
  6. * and other copyright owners as documented in the project's IP log.
  7. *
  8. * This program and the accompanying materials are made available under the
  9. * terms of the Eclipse Distribution License v1.0 which accompanies this
  10. * distribution, is reproduced below, and is available at
  11. * http://www.eclipse.org/org/documents/edl-v10.php
  12. *
  13. * All rights reserved.
  14. *
  15. * Redistribution and use in source and binary forms, with or without
  16. * modification, are permitted provided that the following conditions are met:
  17. *
  18. * - Redistributions of source code must retain the above copyright notice, this
  19. * list of conditions and the following disclaimer.
  20. *
  21. * - Redistributions in binary form must reproduce the above copyright notice,
  22. * this list of conditions and the following disclaimer in the documentation
  23. * and/or other materials provided with the distribution.
  24. *
  25. * - Neither the name of the Eclipse Foundation, Inc. nor the names of its
  26. * contributors may be used to endorse or promote products derived from this
  27. * software without specific prior written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  30. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  31. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  32. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  33. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  34. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  35. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  36. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  37. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  38. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  39. * POSSIBILITY OF SUCH DAMAGE.
  40. */
  41. package org.eclipse.jgit.lib;
  42. import static java.nio.charset.StandardCharsets.UTF_8;
  43. import static org.junit.Assert.assertArrayEquals;
  44. import static org.junit.Assert.assertEquals;
  45. import static org.junit.Assert.assertFalse;
  46. import static org.junit.Assert.assertNotNull;
  47. import static org.junit.Assert.assertTrue;
  48. import static org.junit.Assert.fail;
  49. import java.io.File;
  50. import java.io.FileInputStream;
  51. import java.io.IOException;
  52. import java.util.Arrays;
  53. import java.util.HashMap;
  54. import java.util.List;
  55. import java.util.Map;
  56. import org.eclipse.jgit.api.CheckoutCommand;
  57. import org.eclipse.jgit.api.CheckoutResult;
  58. import org.eclipse.jgit.api.Git;
  59. import org.eclipse.jgit.api.MergeResult.MergeStatus;
  60. import org.eclipse.jgit.api.ResetCommand.ResetType;
  61. import org.eclipse.jgit.api.Status;
  62. import org.eclipse.jgit.api.errors.GitAPIException;
  63. import org.eclipse.jgit.api.errors.NoFilepatternException;
  64. import org.eclipse.jgit.dircache.DirCache;
  65. import org.eclipse.jgit.dircache.DirCacheCheckout;
  66. import org.eclipse.jgit.dircache.DirCacheCheckout.CheckoutMetadata;
  67. import org.eclipse.jgit.dircache.DirCacheEditor;
  68. import org.eclipse.jgit.dircache.DirCacheEditor.PathEdit;
  69. import org.eclipse.jgit.dircache.DirCacheEntry;
  70. import org.eclipse.jgit.errors.CheckoutConflictException;
  71. import org.eclipse.jgit.errors.CorruptObjectException;
  72. import org.eclipse.jgit.errors.NoWorkTreeException;
  73. import org.eclipse.jgit.events.ChangeRecorder;
  74. import org.eclipse.jgit.events.ListenerHandle;
  75. import org.eclipse.jgit.junit.RepositoryTestCase;
  76. import org.eclipse.jgit.junit.TestRepository;
  77. import org.eclipse.jgit.junit.TestRepository.BranchBuilder;
  78. import org.eclipse.jgit.revwalk.RevCommit;
  79. import org.eclipse.jgit.treewalk.AbstractTreeIterator;
  80. import org.eclipse.jgit.treewalk.FileTreeIterator;
  81. import org.eclipse.jgit.treewalk.TreeWalk;
  82. import org.eclipse.jgit.treewalk.WorkingTreeIterator;
  83. import org.eclipse.jgit.util.FS;
  84. import org.eclipse.jgit.util.FileUtils;
  85. import org.junit.Assume;
  86. import org.junit.Test;
  87. public class DirCacheCheckoutTest extends RepositoryTestCase {
  88. private DirCacheCheckout dco;
  89. protected ObjectId theHead;
  90. protected ObjectId theMerge;
  91. private DirCache dirCache;
  92. private void prescanTwoTrees(ObjectId head, ObjectId merge)
  93. throws IllegalStateException, IOException {
  94. DirCache dc = db.lockDirCache();
  95. try {
  96. dco = new DirCacheCheckout(db, head, dc, merge);
  97. dco.preScanTwoTrees();
  98. } finally {
  99. dc.unlock();
  100. }
  101. }
  102. private void checkout() throws IOException {
  103. DirCache dc = db.lockDirCache();
  104. try {
  105. dco = new DirCacheCheckout(db, theHead, dc, theMerge);
  106. dco.checkout();
  107. } finally {
  108. dc.unlock();
  109. }
  110. }
  111. private List<String> getRemoved() {
  112. return dco.getRemoved();
  113. }
  114. private Map<String, CheckoutMetadata> getUpdated() {
  115. return dco.getUpdated();
  116. }
  117. private List<String> getConflicts() {
  118. return dco.getConflicts();
  119. }
  120. private static HashMap<String, String> mk(String a) {
  121. return mkmap(a, a);
  122. }
  123. private static HashMap<String, String> mkmap(String... args) {
  124. if ((args.length % 2) > 0)
  125. throw new IllegalArgumentException("needs to be pairs");
  126. HashMap<String, String> map = new HashMap<>();
  127. for (int i = 0; i < args.length; i += 2) {
  128. map.put(args[i], args[i + 1]);
  129. }
  130. return map;
  131. }
  132. @Test
  133. public void testResetHard() throws IOException, NoFilepatternException,
  134. GitAPIException {
  135. ChangeRecorder recorder = new ChangeRecorder();
  136. ListenerHandle handle = null;
  137. try (Git git = new Git(db)) {
  138. handle = db.getListenerList()
  139. .addWorkingTreeModifiedListener(recorder);
  140. writeTrashFile("f", "f()");
  141. writeTrashFile("D/g", "g()");
  142. git.add().addFilepattern(".").call();
  143. git.commit().setMessage("inital").call();
  144. assertIndex(mkmap("f", "f()", "D/g", "g()"));
  145. recorder.assertNoEvent();
  146. git.branchCreate().setName("topic").call();
  147. recorder.assertNoEvent();
  148. writeTrashFile("f", "f()\nmaster");
  149. writeTrashFile("D/g", "g()\ng2()");
  150. writeTrashFile("E/h", "h()");
  151. git.add().addFilepattern(".").call();
  152. RevCommit master = git.commit().setMessage("master-1").call();
  153. assertIndex(mkmap("f", "f()\nmaster", "D/g", "g()\ng2()", "E/h", "h()"));
  154. recorder.assertNoEvent();
  155. checkoutBranch("refs/heads/topic");
  156. assertIndex(mkmap("f", "f()", "D/g", "g()"));
  157. recorder.assertEvent(new String[] { "f", "D/g" },
  158. new String[] { "E/h" });
  159. writeTrashFile("f", "f()\nside");
  160. assertTrue(new File(db.getWorkTree(), "D/g").delete());
  161. writeTrashFile("G/i", "i()");
  162. git.add().addFilepattern(".").call();
  163. git.add().addFilepattern(".").setUpdate(true).call();
  164. RevCommit topic = git.commit().setMessage("topic-1").call();
  165. assertIndex(mkmap("f", "f()\nside", "G/i", "i()"));
  166. recorder.assertNoEvent();
  167. writeTrashFile("untracked", "untracked");
  168. resetHard(master);
  169. assertIndex(mkmap("f", "f()\nmaster", "D/g", "g()\ng2()", "E/h", "h()"));
  170. recorder.assertEvent(new String[] { "f", "D/g", "E/h" },
  171. new String[] { "G", "G/i" });
  172. resetHard(topic);
  173. assertIndex(mkmap("f", "f()\nside", "G/i", "i()"));
  174. assertWorkDir(mkmap("f", "f()\nside", "G/i", "i()", "untracked",
  175. "untracked"));
  176. recorder.assertEvent(new String[] { "f", "G/i" },
  177. new String[] { "D", "D/g", "E", "E/h" });
  178. assertEquals(MergeStatus.CONFLICTING, git.merge().include(master)
  179. .call().getMergeStatus());
  180. assertEquals(
  181. "[D/g, mode:100644, stage:1][D/g, mode:100644, stage:3][E/h, mode:100644][G/i, mode:100644][f, mode:100644, stage:1][f, mode:100644, stage:2][f, mode:100644, stage:3]",
  182. indexState(0));
  183. recorder.assertEvent(new String[] { "f", "D/g", "E/h" },
  184. ChangeRecorder.EMPTY);
  185. resetHard(master);
  186. assertIndex(mkmap("f", "f()\nmaster", "D/g", "g()\ng2()", "E/h", "h()"));
  187. assertWorkDir(mkmap("f", "f()\nmaster", "D/g", "g()\ng2()", "E/h",
  188. "h()", "untracked", "untracked"));
  189. recorder.assertEvent(new String[] { "f", "D/g" },
  190. new String[] { "G", "G/i" });
  191. } finally {
  192. if (handle != null) {
  193. handle.remove();
  194. }
  195. }
  196. }
  197. /**
  198. * Reset hard from unclean condition.
  199. * <p>
  200. * WorkDir: Empty <br>
  201. * Index: f/g <br>
  202. * Merge: x
  203. *
  204. * @throws Exception
  205. */
  206. @Test
  207. public void testResetHardFromIndexEntryWithoutFileToTreeWithoutFile()
  208. throws Exception {
  209. ChangeRecorder recorder = new ChangeRecorder();
  210. ListenerHandle handle = null;
  211. try (Git git = new Git(db)) {
  212. handle = db.getListenerList()
  213. .addWorkingTreeModifiedListener(recorder);
  214. writeTrashFile("x", "x");
  215. git.add().addFilepattern("x").call();
  216. RevCommit id1 = git.commit().setMessage("c1").call();
  217. writeTrashFile("f/g", "f/g");
  218. git.rm().addFilepattern("x").call();
  219. recorder.assertEvent(ChangeRecorder.EMPTY, new String[] { "x" });
  220. git.add().addFilepattern("f/g").call();
  221. git.commit().setMessage("c2").call();
  222. deleteTrashFile("f/g");
  223. deleteTrashFile("f");
  224. // The actual test
  225. git.reset().setMode(ResetType.HARD).setRef(id1.getName()).call();
  226. assertIndex(mkmap("x", "x"));
  227. recorder.assertEvent(new String[] { "x" }, ChangeRecorder.EMPTY);
  228. } finally {
  229. if (handle != null) {
  230. handle.remove();
  231. }
  232. }
  233. }
  234. /**
  235. * Test first checkout in a repo
  236. *
  237. * @throws Exception
  238. */
  239. @Test
  240. public void testInitialCheckout() throws Exception {
  241. ChangeRecorder recorder = new ChangeRecorder();
  242. ListenerHandle handle = null;
  243. try (Git git = new Git(db);
  244. TestRepository<Repository> db_t = new TestRepository<>(db)) {
  245. handle = db.getListenerList()
  246. .addWorkingTreeModifiedListener(recorder);
  247. BranchBuilder master = db_t.branch("master");
  248. master.commit().add("f", "1").message("m0").create();
  249. assertFalse(new File(db.getWorkTree(), "f").exists());
  250. git.checkout().setName("master").call();
  251. assertTrue(new File(db.getWorkTree(), "f").exists());
  252. recorder.assertEvent(new String[] { "f" }, ChangeRecorder.EMPTY);
  253. } finally {
  254. if (handle != null) {
  255. handle.remove();
  256. }
  257. }
  258. }
  259. private DirCacheCheckout resetHard(RevCommit commit)
  260. throws NoWorkTreeException,
  261. CorruptObjectException, IOException {
  262. DirCacheCheckout dc;
  263. dc = new DirCacheCheckout(db, null, db.lockDirCache(),
  264. commit.getTree());
  265. dc.setFailOnConflict(true);
  266. assertTrue(dc.checkout());
  267. return dc;
  268. }
  269. private void assertIndex(HashMap<String, String> i)
  270. throws CorruptObjectException, IOException {
  271. String expectedValue;
  272. String path;
  273. DirCache read = DirCache.read(db.getIndexFile(), db.getFS());
  274. assertEquals("Index has not the right size.", i.size(),
  275. read.getEntryCount());
  276. for (int j = 0; j < read.getEntryCount(); j++) {
  277. path = read.getEntry(j).getPathString();
  278. expectedValue = i.get(path);
  279. assertNotNull("found unexpected entry for path " + path
  280. + " in index", expectedValue);
  281. assertTrue("unexpected content for path " + path
  282. + " in index. Expected: <" + expectedValue + ">",
  283. Arrays.equals(db.open(read.getEntry(j).getObjectId())
  284. .getCachedBytes(), i.get(path).getBytes(UTF_8)));
  285. }
  286. }
  287. @Test
  288. public void testRules1thru3_NoIndexEntry() throws IOException {
  289. ObjectId head = buildTree(mk("foo"));
  290. ObjectId merge = db.newObjectInserter().insert(Constants.OBJ_TREE,
  291. new byte[0]);
  292. prescanTwoTrees(head, merge);
  293. assertTrue(getRemoved().contains("foo"));
  294. prescanTwoTrees(merge, head);
  295. assertTrue(getUpdated().containsKey("foo"));
  296. merge = buildTree(mkmap("foo", "a"));
  297. prescanTwoTrees(head, merge);
  298. assertConflict("foo");
  299. }
  300. void setupCase(HashMap<String, String> headEntries, HashMap<String, String> mergeEntries, HashMap<String, String> indexEntries) throws IOException {
  301. theHead = buildTree(headEntries);
  302. theMerge = buildTree(mergeEntries);
  303. buildIndex(indexEntries);
  304. }
  305. private void buildIndex(HashMap<String, String> indexEntries) throws IOException {
  306. dirCache = new DirCache(db.getIndexFile(), db.getFS());
  307. if (indexEntries != null) {
  308. assertTrue(dirCache.lock());
  309. DirCacheEditor editor = dirCache.editor();
  310. for (java.util.Map.Entry<String,String> e : indexEntries.entrySet()) {
  311. writeTrashFile(e.getKey(), e.getValue());
  312. ObjectId id;
  313. try (ObjectInserter inserter = db.newObjectInserter()) {
  314. id = inserter.insert(Constants.OBJ_BLOB,
  315. Constants.encode(e.getValue()));
  316. }
  317. editor.add(new DirCacheEditor.DeletePath(e.getKey()));
  318. editor.add(new DirCacheEditor.PathEdit(e.getKey()) {
  319. @Override
  320. public void apply(DirCacheEntry ent) {
  321. ent.setFileMode(FileMode.REGULAR_FILE);
  322. ent.setObjectId(id);
  323. ent.setUpdateNeeded(false);
  324. }
  325. });
  326. }
  327. assertTrue(editor.commit());
  328. }
  329. }
  330. static final class AddEdit extends PathEdit {
  331. private final ObjectId data;
  332. private final long length;
  333. public AddEdit(String entryPath, ObjectId data, long length) {
  334. super(entryPath);
  335. this.data = data;
  336. this.length = length;
  337. }
  338. @Override
  339. public void apply(DirCacheEntry ent) {
  340. ent.setFileMode(FileMode.REGULAR_FILE);
  341. ent.setLength(length);
  342. ent.setObjectId(data);
  343. }
  344. }
  345. private ObjectId buildTree(HashMap<String, String> headEntries)
  346. throws IOException {
  347. DirCache lockDirCache = DirCache.newInCore();
  348. // assertTrue(lockDirCache.lock());
  349. DirCacheEditor editor = lockDirCache.editor();
  350. if (headEntries != null) {
  351. for (java.util.Map.Entry<String, String> e : headEntries.entrySet()) {
  352. AddEdit addEdit = new AddEdit(e.getKey(),
  353. genSha1(e.getValue()), e.getValue().length());
  354. editor.add(addEdit);
  355. }
  356. }
  357. editor.finish();
  358. return lockDirCache.writeTree(db.newObjectInserter());
  359. }
  360. ObjectId genSha1(String data) {
  361. try (ObjectInserter w = db.newObjectInserter()) {
  362. ObjectId id = w.insert(Constants.OBJ_BLOB, data.getBytes(UTF_8));
  363. w.flush();
  364. return id;
  365. } catch (IOException e) {
  366. fail(e.toString());
  367. }
  368. return null;
  369. }
  370. protected void go() throws IllegalStateException, IOException {
  371. prescanTwoTrees(theHead, theMerge);
  372. }
  373. @Test
  374. public void testRules4thru13_IndexEntryNotInHead() throws IOException {
  375. // rules 4 and 5
  376. HashMap<String, String> idxMap;
  377. idxMap = new HashMap<>();
  378. idxMap.put("foo", "foo");
  379. setupCase(null, null, idxMap);
  380. go();
  381. assertTrue(getUpdated().isEmpty());
  382. assertTrue(getRemoved().isEmpty());
  383. assertTrue(getConflicts().isEmpty());
  384. // rules 6 and 7
  385. idxMap = new HashMap<>();
  386. idxMap.put("foo", "foo");
  387. setupCase(null, idxMap, idxMap);
  388. go();
  389. assertAllEmpty();
  390. // rules 8 and 9
  391. HashMap<String, String> mergeMap;
  392. mergeMap = new HashMap<>();
  393. mergeMap.put("foo", "merge");
  394. setupCase(null, mergeMap, idxMap);
  395. go();
  396. assertTrue(getUpdated().isEmpty());
  397. assertTrue(getRemoved().isEmpty());
  398. assertTrue(getConflicts().contains("foo"));
  399. // rule 10
  400. HashMap<String, String> headMap = new HashMap<>();
  401. headMap.put("foo", "foo");
  402. setupCase(headMap, null, idxMap);
  403. go();
  404. assertTrue(getRemoved().contains("foo"));
  405. assertTrue(getUpdated().isEmpty());
  406. assertTrue(getConflicts().isEmpty());
  407. // rule 11
  408. setupCase(headMap, null, idxMap);
  409. assertTrue(new File(trash, "foo").delete());
  410. writeTrashFile("foo", "bar");
  411. db.readDirCache().getEntry(0).setUpdateNeeded(true);
  412. go();
  413. assertTrue(getRemoved().isEmpty());
  414. assertTrue(getUpdated().isEmpty());
  415. assertTrue(getConflicts().contains("foo"));
  416. // rule 12 & 13
  417. headMap.put("foo", "head");
  418. setupCase(headMap, null, idxMap);
  419. go();
  420. assertTrue(getRemoved().isEmpty());
  421. assertTrue(getUpdated().isEmpty());
  422. assertTrue(getConflicts().contains("foo"));
  423. // rules 14 & 15
  424. setupCase(headMap, headMap, idxMap);
  425. go();
  426. assertAllEmpty();
  427. // rules 16 & 17
  428. setupCase(headMap, mergeMap, idxMap); go();
  429. assertTrue(getConflicts().contains("foo"));
  430. // rules 18 & 19
  431. setupCase(headMap, idxMap, idxMap); go();
  432. assertAllEmpty();
  433. // rule 20
  434. setupCase(idxMap, mergeMap, idxMap); go();
  435. assertTrue(getUpdated().containsKey("foo"));
  436. // rules 21
  437. setupCase(idxMap, mergeMap, idxMap);
  438. assertTrue(new File(trash, "foo").delete());
  439. writeTrashFile("foo", "bar");
  440. db.readDirCache().getEntry(0).setUpdateNeeded(true);
  441. go();
  442. assertTrue(getConflicts().contains("foo"));
  443. }
  444. private void assertAllEmpty() {
  445. assertTrue(getRemoved().isEmpty());
  446. assertTrue(getUpdated().isEmpty());
  447. assertTrue(getConflicts().isEmpty());
  448. }
  449. /*-
  450. * Directory/File Conflict cases:
  451. * It's entirely possible that in practice a number of these may be equivalent
  452. * to the cases described in git-read-tree.txt. As long as it does the right thing,
  453. * that's all I care about. These are basically reverse-engineered from
  454. * what git currently does. If there are tests for these in git, it's kind of
  455. * hard to track them all down...
  456. *
  457. * H I M Clean H==M H==I I==M Result
  458. * ------------------------------------------------------------------
  459. *1 D D F Y N Y N Update
  460. *2 D D F N N Y N Conflict
  461. *3 D F D Y N N Keep
  462. *4 D F D N N N Conflict
  463. *5 D F F Y N N Y Keep
  464. *5b D F F Y N N N Conflict
  465. *6 D F F N N N Y Keep
  466. *6b D F F N N N N Conflict
  467. *7 F D F Y Y N N Update
  468. *8 F D F N Y N N Conflict
  469. *9 F D F Y N N N Update
  470. *10 F D D N N Y Keep
  471. *11 F D D N N N Conflict
  472. *12 F F D Y N Y N Update
  473. *13 F F D N N Y N Conflict
  474. *14 F F D N N N Conflict
  475. *15 0 F D N N N Conflict
  476. *16 0 D F Y N N N Update
  477. *17 0 D F N N N Conflict
  478. *18 F 0 D Update
  479. *19 D 0 F Update
  480. */
  481. @Test
  482. public void testDirectoryFileSimple() throws IOException {
  483. ObjectId treeDF = buildTree(mkmap("DF", "DF"));
  484. ObjectId treeDFDF = buildTree(mkmap("DF/DF", "DF/DF"));
  485. buildIndex(mkmap("DF", "DF"));
  486. prescanTwoTrees(treeDF, treeDFDF);
  487. assertTrue(getRemoved().contains("DF"));
  488. assertTrue(getUpdated().containsKey("DF/DF"));
  489. recursiveDelete(new File(trash, "DF"));
  490. buildIndex(mkmap("DF/DF", "DF/DF"));
  491. prescanTwoTrees(treeDFDF, treeDF);
  492. assertTrue(getRemoved().contains("DF/DF"));
  493. assertTrue(getUpdated().containsKey("DF"));
  494. }
  495. @Test
  496. public void testDirectoryFileConflicts_1() throws Exception {
  497. // 1
  498. doit(mk("DF/DF"), mk("DF"), mk("DF/DF"));
  499. assertNoConflicts();
  500. assertUpdated("DF");
  501. assertRemoved("DF/DF");
  502. }
  503. @Test
  504. public void testDirectoryFileConflicts_2() throws Exception {
  505. // 2
  506. setupCase(mk("DF/DF"), mk("DF"), mk("DF/DF"));
  507. writeTrashFile("DF/DF", "different");
  508. go();
  509. assertConflict("DF/DF");
  510. }
  511. @Test
  512. public void testDirectoryFileConflicts_3() throws Exception {
  513. // 3
  514. doit(mk("DF/DF"), mk("DF/DF"), mk("DF"));
  515. assertNoConflicts();
  516. }
  517. @Test
  518. public void testDirectoryFileConflicts_4() throws Exception {
  519. // 4 (basically same as 3, just with H and M different)
  520. doit(mk("DF/DF"), mkmap("DF/DF", "foo"), mk("DF"));
  521. assertConflict("DF/DF");
  522. }
  523. @Test
  524. public void testDirectoryFileConflicts_5() throws Exception {
  525. // 5
  526. doit(mk("DF/DF"), mk("DF"), mk("DF"));
  527. assertRemoved("DF/DF");
  528. assertEquals(0, dco.getConflicts().size());
  529. assertEquals(0, dco.getUpdated().size());
  530. }
  531. @Test
  532. public void testDirectoryFileConflicts_5b() throws Exception {
  533. // 5
  534. doit(mk("DF/DF"), mkmap("DF", "different"), mk("DF"));
  535. assertRemoved("DF/DF");
  536. assertConflict("DF");
  537. assertEquals(0, dco.getUpdated().size());
  538. }
  539. @Test
  540. public void testDirectoryFileConflicts_6() throws Exception {
  541. // 6
  542. setupCase(mk("DF/DF"), mk("DF"), mk("DF"));
  543. writeTrashFile("DF", "different");
  544. go();
  545. assertRemoved("DF/DF");
  546. assertEquals(0, dco.getConflicts().size());
  547. assertEquals(0, dco.getUpdated().size());
  548. }
  549. @Test
  550. public void testDirectoryFileConflicts_6b() throws Exception {
  551. // 6
  552. setupCase(mk("DF/DF"), mk("DF"), mkmap("DF", "different"));
  553. writeTrashFile("DF", "again different");
  554. go();
  555. assertRemoved("DF/DF");
  556. assertConflict("DF");
  557. assertEquals(0, dco.getUpdated().size());
  558. }
  559. @Test
  560. public void testDirectoryFileConflicts_7() throws Exception {
  561. // 7
  562. doit(mk("DF"), mk("DF"), mk("DF/DF"));
  563. assertUpdated("DF");
  564. assertRemoved("DF/DF");
  565. cleanUpDF();
  566. setupCase(mk("DF/DF"), mk("DF/DF"), mk("DF/DF/DF/DF/DF"));
  567. go();
  568. assertRemoved("DF/DF/DF/DF/DF");
  569. assertUpdated("DF/DF");
  570. cleanUpDF();
  571. setupCase(mk("DF/DF"), mk("DF/DF"), mk("DF/DF/DF/DF/DF"));
  572. writeTrashFile("DF/DF/DF/DF/DF", "diff");
  573. go();
  574. assertConflict("DF/DF/DF/DF/DF");
  575. // assertUpdated("DF/DF");
  576. // Why do we expect an update on DF/DF. H==M,
  577. // H&M are files and index contains a dir, index
  578. // is dirty: that case is not in the table but
  579. // we cannot update DF/DF to a file, this would
  580. // require that we delete DF/DF/DF/DF/DF in workdir
  581. // throwing away unsaved contents.
  582. // This test would fail in DirCacheCheckoutTests.
  583. }
  584. @Test
  585. public void testDirectoryFileConflicts_8() throws Exception {
  586. // 8
  587. setupCase(mk("DF"), mk("DF"), mk("DF/DF"));
  588. recursiveDelete(new File(db.getWorkTree(), "DF"));
  589. writeTrashFile("DF", "xy");
  590. go();
  591. assertConflict("DF/DF");
  592. }
  593. @Test
  594. public void testDirectoryFileConflicts_9() throws Exception {
  595. // 9
  596. doit(mkmap("DF", "QP"), mkmap("DF", "QP"), mkmap("DF/DF", "DF/DF"));
  597. assertRemoved("DF/DF");
  598. assertUpdated("DF");
  599. }
  600. @Test
  601. public void testDirectoryFileConflicts_10() throws Exception {
  602. // 10
  603. cleanUpDF();
  604. doit(mk("DF"), mk("DF/DF"), mk("DF/DF"));
  605. assertNoConflicts();
  606. }
  607. @Test
  608. public void testDirectoryFileConflicts_11() throws Exception {
  609. // 11
  610. doit(mk("DF"), mk("DF/DF"), mkmap("DF/DF", "asdf"));
  611. assertConflict("DF/DF");
  612. }
  613. @Test
  614. public void testDirectoryFileConflicts_12() throws Exception {
  615. // 12
  616. cleanUpDF();
  617. doit(mk("DF"), mk("DF/DF"), mk("DF"));
  618. assertRemoved("DF");
  619. assertUpdated("DF/DF");
  620. }
  621. @Test
  622. public void testDirectoryFileConflicts_13() throws Exception {
  623. // 13
  624. cleanUpDF();
  625. setupCase(mk("DF"), mk("DF/DF"), mk("DF"));
  626. writeTrashFile("DF", "asdfsdf");
  627. go();
  628. assertConflict("DF");
  629. assertUpdated("DF/DF");
  630. }
  631. @Test
  632. public void testDirectoryFileConflicts_14() throws Exception {
  633. // 14
  634. cleanUpDF();
  635. doit(mk("DF"), mk("DF/DF"), mkmap("DF", "Foo"));
  636. assertConflict("DF");
  637. assertUpdated("DF/DF");
  638. }
  639. @Test
  640. public void testDirectoryFileConflicts_15() throws Exception {
  641. // 15
  642. doit(mkmap(), mk("DF/DF"), mk("DF"));
  643. // This test would fail in DirCacheCheckoutTests. I think this test is wrong,
  644. // it should check for conflicts according to rule 15
  645. // assertRemoved("DF");
  646. assertUpdated("DF/DF");
  647. }
  648. @Test
  649. public void testDirectoryFileConflicts_15b() throws Exception {
  650. // 15, take 2, just to check multi-leveled
  651. doit(mkmap(), mk("DF/DF/DF/DF"), mk("DF"));
  652. // I think this test is wrong, it should
  653. // check for conflicts according to rule 15
  654. // This test would fail in DirCacheCheckouts
  655. // assertRemoved("DF");
  656. assertUpdated("DF/DF/DF/DF");
  657. }
  658. @Test
  659. public void testDirectoryFileConflicts_16() throws Exception {
  660. // 16
  661. cleanUpDF();
  662. doit(mkmap(), mk("DF"), mk("DF/DF/DF"));
  663. assertRemoved("DF/DF/DF");
  664. assertUpdated("DF");
  665. }
  666. @Test
  667. public void testDirectoryFileConflicts_17() throws Exception {
  668. // 17
  669. cleanUpDF();
  670. setupCase(mkmap(), mk("DF"), mk("DF/DF/DF"));
  671. writeTrashFile("DF/DF/DF", "asdf");
  672. go();
  673. assertConflict("DF/DF/DF");
  674. // Why do we expect an update on DF. If we really update
  675. // DF and update also the working tree we would have to
  676. // overwrite a dirty file in the work-tree DF/DF/DF
  677. // This test would fail in DirCacheCheckout
  678. // assertUpdated("DF");
  679. }
  680. @Test
  681. public void testDirectoryFileConflicts_18() throws Exception {
  682. // 18
  683. cleanUpDF();
  684. doit(mk("DF/DF"), mk("DF/DF/DF/DF"), null);
  685. assertRemoved("DF/DF");
  686. assertUpdated("DF/DF/DF/DF");
  687. }
  688. @Test
  689. public void testDirectoryFileConflicts_19() throws Exception {
  690. // 19
  691. cleanUpDF();
  692. doit(mk("DF/DF/DF/DF"), mk("DF/DF/DF"), null);
  693. assertRemoved("DF/DF/DF/DF");
  694. assertUpdated("DF/DF/DF");
  695. }
  696. protected void cleanUpDF() throws Exception {
  697. tearDown();
  698. setUp();
  699. recursiveDelete(new File(trash, "DF"));
  700. }
  701. protected void assertConflict(String s) {
  702. assertTrue(getConflicts().contains(s));
  703. }
  704. protected void assertUpdated(String s) {
  705. assertTrue(getUpdated().containsKey(s));
  706. }
  707. protected void assertRemoved(String s) {
  708. assertTrue(getRemoved().contains(s));
  709. }
  710. protected void assertNoConflicts() {
  711. assertTrue(getConflicts().isEmpty());
  712. }
  713. protected void doit(HashMap<String, String> h, HashMap<String, String> m, HashMap<String, String> i)
  714. throws IOException {
  715. setupCase(h, m, i);
  716. go();
  717. }
  718. @Test
  719. public void testUntrackedConflicts() throws IOException {
  720. setupCase(null, mk("foo"), null);
  721. writeTrashFile("foo", "foo");
  722. go();
  723. // test that we don't overwrite untracked files when there is a HEAD
  724. recursiveDelete(new File(trash, "foo"));
  725. setupCase(mk("other"), mkmap("other", "other", "foo", "foo"),
  726. mk("other"));
  727. writeTrashFile("foo", "bar");
  728. try {
  729. checkout();
  730. fail("didn't get the expected exception");
  731. } catch (CheckoutConflictException e) {
  732. assertConflict("foo");
  733. assertEquals("foo", e.getConflictingFiles()[0]);
  734. assertWorkDir(mkmap("foo", "bar", "other", "other"));
  735. assertIndex(mk("other"));
  736. }
  737. // test that we don't overwrite untracked files when there is no HEAD
  738. recursiveDelete(new File(trash, "other"));
  739. recursiveDelete(new File(trash, "foo"));
  740. setupCase(null, mk("foo"), null);
  741. writeTrashFile("foo", "bar");
  742. try {
  743. checkout();
  744. fail("didn't get the expected exception");
  745. } catch (CheckoutConflictException e) {
  746. assertConflict("foo");
  747. assertWorkDir(mkmap("foo", "bar"));
  748. assertIndex(mkmap("other", "other"));
  749. }
  750. // TODO: Why should we expect conflicts here?
  751. // H and M are empty and according to rule #5 of
  752. // the carry-over rules a dirty index is no reason
  753. // for a conflict. (I also feel it should be a
  754. // conflict because we are going to overwrite
  755. // unsaved content in the working tree
  756. // This test would fail in DirCacheCheckoutTest
  757. // assertConflict("foo");
  758. recursiveDelete(new File(trash, "foo"));
  759. recursiveDelete(new File(trash, "other"));
  760. setupCase(null, mk("foo"), null);
  761. writeTrashFile("foo/bar/baz", "");
  762. writeTrashFile("foo/blahblah", "");
  763. go();
  764. assertConflict("foo");
  765. assertConflict("foo/bar/baz");
  766. assertConflict("foo/blahblah");
  767. recursiveDelete(new File(trash, "foo"));
  768. setupCase(mkmap("foo/bar", "", "foo/baz", ""),
  769. mk("foo"), mkmap("foo/bar", "", "foo/baz", ""));
  770. assertTrue(new File(trash, "foo/bar").exists());
  771. go();
  772. assertNoConflicts();
  773. }
  774. @Test
  775. public void testCloseNameConflictsX0() throws IOException {
  776. setupCase(mkmap("a/a", "a/a-c"), mkmap("a/a","a/a", "b.b/b.b","b.b/b.bs"), mkmap("a/a", "a/a-c") );
  777. checkout();
  778. assertIndex(mkmap("a/a", "a/a", "b.b/b.b", "b.b/b.bs"));
  779. assertWorkDir(mkmap("a/a", "a/a", "b.b/b.b", "b.b/b.bs"));
  780. go();
  781. assertIndex(mkmap("a/a", "a/a", "b.b/b.b", "b.b/b.bs"));
  782. assertWorkDir(mkmap("a/a", "a/a", "b.b/b.b", "b.b/b.bs"));
  783. assertNoConflicts();
  784. }
  785. @Test
  786. public void testCloseNameConflicts1() throws IOException {
  787. setupCase(mkmap("a/a", "a/a-c"), mkmap("a/a","a/a", "a.a/a.a","a.a/a.a"), mkmap("a/a", "a/a-c") );
  788. checkout();
  789. assertIndex(mkmap("a/a", "a/a", "a.a/a.a", "a.a/a.a"));
  790. assertWorkDir(mkmap("a/a", "a/a", "a.a/a.a", "a.a/a.a"));
  791. go();
  792. assertIndex(mkmap("a/a", "a/a", "a.a/a.a", "a.a/a.a"));
  793. assertWorkDir(mkmap("a/a", "a/a", "a.a/a.a", "a.a/a.a"));
  794. assertNoConflicts();
  795. }
  796. @Test
  797. public void testCheckoutHierarchy() throws IOException {
  798. setupCase(
  799. mkmap("a", "a", "b/c", "b/c", "d", "d", "e/f", "e/f", "e/g",
  800. "e/g"),
  801. mkmap("a", "a2", "b/c", "b/c", "d", "d", "e/f", "e/f", "e/g",
  802. "e/g2"),
  803. mkmap("a", "a", "b/c", "b/c", "d", "d", "e/f", "e/f", "e/g",
  804. "e/g3"));
  805. try {
  806. checkout();
  807. fail("did not throw CheckoutConflictException");
  808. } catch (CheckoutConflictException e) {
  809. assertWorkDir(mkmap("a", "a", "b/c", "b/c", "d", "d", "e/f",
  810. "e/f", "e/g", "e/g3"));
  811. assertConflict("e/g");
  812. assertEquals("e/g", e.getConflictingFiles()[0]);
  813. }
  814. }
  815. @Test
  816. public void testCheckoutOutChanges() throws IOException {
  817. setupCase(mk("foo"), mk("foo/bar"), mk("foo"));
  818. checkout();
  819. assertIndex(mk("foo/bar"));
  820. assertWorkDir(mk("foo/bar"));
  821. assertFalse(new File(trash, "foo").isFile());
  822. assertTrue(new File(trash, "foo/bar").isFile());
  823. recursiveDelete(new File(trash, "foo"));
  824. assertWorkDir(mkmap());
  825. setupCase(mk("foo/bar"), mk("foo"), mk("foo/bar"));
  826. checkout();
  827. assertIndex(mk("foo"));
  828. assertWorkDir(mk("foo"));
  829. assertFalse(new File(trash, "foo/bar").isFile());
  830. assertTrue(new File(trash, "foo").isFile());
  831. setupCase(mk("foo"), mkmap("foo", "qux"), mkmap("foo", "bar"));
  832. assertIndex(mkmap("foo", "bar"));
  833. assertWorkDir(mkmap("foo", "bar"));
  834. try {
  835. checkout();
  836. fail("did not throw exception");
  837. } catch (CheckoutConflictException e) {
  838. assertIndex(mkmap("foo", "bar"));
  839. assertWorkDir(mkmap("foo", "bar"));
  840. }
  841. }
  842. @Test
  843. public void testCheckoutChangeLinkToEmptyDir() throws Exception {
  844. Assume.assumeTrue(FS.DETECTED.supportsSymlinks());
  845. String fname = "was_file";
  846. ChangeRecorder recorder = new ChangeRecorder();
  847. ListenerHandle handle = null;
  848. try (Git git = new Git(db)) {
  849. handle = db.getListenerList()
  850. .addWorkingTreeModifiedListener(recorder);
  851. // Add a file
  852. writeTrashFile(fname, "a");
  853. git.add().addFilepattern(fname).call();
  854. // Add a link to file
  855. String linkName = "link";
  856. File link = writeLink(linkName, fname).toFile();
  857. git.add().addFilepattern(linkName).call();
  858. git.commit().setMessage("Added file and link").call();
  859. assertWorkDir(mkmap(linkName, "a", fname, "a"));
  860. // replace link with empty directory
  861. FileUtils.delete(link);
  862. FileUtils.mkdir(link);
  863. assertTrue("Link must be a directory now", link.isDirectory());
  864. // modify file
  865. writeTrashFile(fname, "b");
  866. assertWorkDir(mkmap(fname, "b", linkName, "/"));
  867. recorder.assertNoEvent();
  868. // revert both paths to HEAD state
  869. git.checkout().setStartPoint(Constants.HEAD).addPath(fname)
  870. .addPath(linkName).call();
  871. assertWorkDir(mkmap(fname, "a", linkName, "a"));
  872. recorder.assertEvent(new String[] { fname, linkName },
  873. ChangeRecorder.EMPTY);
  874. Status st = git.status().call();
  875. assertTrue(st.isClean());
  876. } finally {
  877. if (handle != null) {
  878. handle.remove();
  879. }
  880. }
  881. }
  882. @Test
  883. public void testCheckoutChangeLinkToEmptyDirs() throws Exception {
  884. Assume.assumeTrue(FS.DETECTED.supportsSymlinks());
  885. String fname = "was_file";
  886. ChangeRecorder recorder = new ChangeRecorder();
  887. ListenerHandle handle = null;
  888. try (Git git = new Git(db)) {
  889. handle = db.getListenerList()
  890. .addWorkingTreeModifiedListener(recorder);
  891. // Add a file
  892. writeTrashFile(fname, "a");
  893. git.add().addFilepattern(fname).call();
  894. // Add a link to file
  895. String linkName = "link";
  896. File link = writeLink(linkName, fname).toFile();
  897. git.add().addFilepattern(linkName).call();
  898. git.commit().setMessage("Added file and link").call();
  899. assertWorkDir(mkmap(linkName, "a", fname, "a"));
  900. // replace link with directory containing only directories, no files
  901. FileUtils.delete(link);
  902. FileUtils.mkdirs(new File(link, "dummyDir"));
  903. assertTrue("Link must be a directory now", link.isDirectory());
  904. assertFalse("Must not delete non empty directory", link.delete());
  905. // modify file
  906. writeTrashFile(fname, "b");
  907. assertWorkDir(mkmap(fname, "b", linkName + "/dummyDir", "/"));
  908. recorder.assertNoEvent();
  909. // revert both paths to HEAD state
  910. git.checkout().setStartPoint(Constants.HEAD).addPath(fname)
  911. .addPath(linkName).call();
  912. assertWorkDir(mkmap(fname, "a", linkName, "a"));
  913. recorder.assertEvent(new String[] { fname, linkName },
  914. ChangeRecorder.EMPTY);
  915. Status st = git.status().call();
  916. assertTrue(st.isClean());
  917. } finally {
  918. if (handle != null) {
  919. handle.remove();
  920. }
  921. }
  922. }
  923. @Test
  924. public void testCheckoutChangeLinkToNonEmptyDirs() throws Exception {
  925. Assume.assumeTrue(FS.DETECTED.supportsSymlinks());
  926. String fname = "file";
  927. ChangeRecorder recorder = new ChangeRecorder();
  928. ListenerHandle handle = null;
  929. try (Git git = new Git(db)) {
  930. handle = db.getListenerList()
  931. .addWorkingTreeModifiedListener(recorder);
  932. // Add a file
  933. writeTrashFile(fname, "a");
  934. git.add().addFilepattern(fname).call();
  935. // Add a link to file
  936. String linkName = "link";
  937. File link = writeLink(linkName, fname).toFile();
  938. git.add().addFilepattern(linkName).call();
  939. git.commit().setMessage("Added file and link").call();
  940. assertWorkDir(mkmap(linkName, "a", fname, "a"));
  941. // replace link with directory containing only directories, no files
  942. FileUtils.delete(link);
  943. // create but do not add a file in the new directory to the index
  944. writeTrashFile(linkName + "/dir1", "file1", "c");
  945. // create but do not add a file in the new directory to the index
  946. writeTrashFile(linkName + "/dir2", "file2", "d");
  947. assertTrue("File must be a directory now", link.isDirectory());
  948. assertFalse("Must not delete non empty directory", link.delete());
  949. // 2 extra files are created
  950. assertWorkDir(mkmap(fname, "a", linkName + "/dir1/file1", "c",
  951. linkName + "/dir2/file2", "d"));
  952. recorder.assertNoEvent();
  953. // revert path to HEAD state
  954. git.checkout().setStartPoint(Constants.HEAD).addPath(linkName)
  955. .call();
  956. // expect only the one added to the index
  957. assertWorkDir(mkmap(linkName, "a", fname, "a"));
  958. recorder.assertEvent(new String[] { linkName },
  959. ChangeRecorder.EMPTY);
  960. Status st = git.status().call();
  961. assertTrue(st.isClean());
  962. } finally {
  963. if (handle != null) {
  964. handle.remove();
  965. }
  966. }
  967. }
  968. @Test
  969. public void testCheckoutChangeLinkToNonEmptyDirsAndNewIndexEntry()
  970. throws Exception {
  971. Assume.assumeTrue(FS.DETECTED.supportsSymlinks());
  972. String fname = "file";
  973. ChangeRecorder recorder = new ChangeRecorder();
  974. ListenerHandle handle = null;
  975. try (Git git = new Git(db)) {
  976. handle = db.getListenerList()
  977. .addWorkingTreeModifiedListener(recorder);
  978. // Add a file
  979. writeTrashFile(fname, "a");
  980. git.add().addFilepattern(fname).call();
  981. // Add a link to file
  982. String linkName = "link";
  983. File link = writeLink(linkName, fname).toFile();
  984. git.add().addFilepattern(linkName).call();
  985. git.commit().setMessage("Added file and link").call();
  986. assertWorkDir(mkmap(linkName, "a", fname, "a"));
  987. // replace link with directory containing only directories, no files
  988. FileUtils.delete(link);
  989. // create and add a file in the new directory to the index
  990. writeTrashFile(linkName + "/dir1", "file1", "c");
  991. git.add().addFilepattern(linkName + "/dir1/file1").call();
  992. // create but do not add a file in the new directory to the index
  993. writeTrashFile(linkName + "/dir2", "file2", "d");
  994. assertTrue("File must be a directory now", link.isDirectory());
  995. assertFalse("Must not delete non empty directory", link.delete());
  996. // 2 extra files are created
  997. assertWorkDir(mkmap(fname, "a", linkName + "/dir1/file1", "c",
  998. linkName + "/dir2/file2", "d"));
  999. recorder.assertNoEvent();
  1000. // revert path to HEAD state
  1001. git.checkout().setStartPoint(Constants.HEAD).addPath(linkName)
  1002. .call();
  1003. // original file and link
  1004. assertWorkDir(mkmap(linkName, "a", fname, "a"));
  1005. recorder.assertEvent(new String[] { linkName },
  1006. ChangeRecorder.EMPTY);
  1007. Status st = git.status().call();
  1008. assertTrue(st.isClean());
  1009. } finally {
  1010. if (handle != null) {
  1011. handle.remove();
  1012. }
  1013. }
  1014. }
  1015. @Test
  1016. public void testCheckoutChangeFileToEmptyDir() throws Exception {
  1017. String fname = "was_file";
  1018. ChangeRecorder recorder = new ChangeRecorder();
  1019. ListenerHandle handle = null;
  1020. try (Git git = new Git(db)) {
  1021. handle = db.getListenerList()
  1022. .addWorkingTreeModifiedListener(recorder);
  1023. // Add a file
  1024. File file = writeTrashFile(fname, "a");
  1025. git.add().addFilepattern(fname).call();
  1026. git.commit().setMessage("Added file").call();
  1027. // replace file with empty directory
  1028. FileUtils.delete(file);
  1029. FileUtils.mkdir(file);
  1030. assertTrue("File must be a directory now", file.isDirectory());
  1031. assertWorkDir(mkmap(fname, "/"));
  1032. recorder.assertNoEvent();
  1033. // revert path to HEAD state
  1034. git.checkout().setStartPoint(Constants.HEAD).addPath(fname).call();
  1035. assertWorkDir(mkmap(fname, "a"));
  1036. recorder.assertEvent(new String[] { fname }, ChangeRecorder.EMPTY);
  1037. Status st = git.status().call();
  1038. assertTrue(st.isClean());
  1039. } finally {
  1040. if (handle != null) {
  1041. handle.remove();
  1042. }
  1043. }
  1044. }
  1045. @Test
  1046. public void testCheckoutChangeFileToEmptyDirs() throws Exception {
  1047. String fname = "was_file";
  1048. ChangeRecorder recorder = new ChangeRecorder();
  1049. ListenerHandle handle = null;
  1050. try (Git git = new Git(db)) {
  1051. handle = db.getListenerList()
  1052. .addWorkingTreeModifiedListener(recorder);
  1053. // Add a file
  1054. File file = writeTrashFile(fname, "a");
  1055. git.add().addFilepattern(fname).call();
  1056. git.commit().setMessage("Added file").call();
  1057. // replace file with directory containing only directories, no files
  1058. FileUtils.delete(file);
  1059. FileUtils.mkdirs(new File(file, "dummyDir"));
  1060. assertTrue("File must be a directory now", file.isDirectory());
  1061. assertFalse("Must not delete non empty directory", file.delete());
  1062. assertWorkDir(mkmap(fname + "/dummyDir", "/"));
  1063. recorder.assertNoEvent();
  1064. // revert path to HEAD state
  1065. git.checkout().setStartPoint(Constants.HEAD).addPath(fname).call();
  1066. assertWorkDir(mkmap(fname, "a"));
  1067. recorder.assertEvent(new String[] { fname }, ChangeRecorder.EMPTY);
  1068. Status st = git.status().call();
  1069. assertTrue(st.isClean());
  1070. } finally {
  1071. if (handle != null) {
  1072. handle.remove();
  1073. }
  1074. }
  1075. }
  1076. @Test
  1077. public void testCheckoutChangeFileToNonEmptyDirs() throws Exception {
  1078. String fname = "was_file";
  1079. ChangeRecorder recorder = new ChangeRecorder();
  1080. ListenerHandle handle = null;
  1081. try (Git git = new Git(db)) {
  1082. handle = db.getListenerList()
  1083. .addWorkingTreeModifiedListener(recorder);
  1084. // Add a file
  1085. File file = writeTrashFile(fname, "a");
  1086. git.add().addFilepattern(fname).call();
  1087. git.commit().setMessage("Added file").call();
  1088. assertWorkDir(mkmap(fname, "a"));
  1089. // replace file with directory containing only directories, no files
  1090. FileUtils.delete(file);
  1091. // create but do not add a file in the new directory to the index
  1092. writeTrashFile(fname + "/dir1", "file1", "c");
  1093. // create but do not add a file in the new directory to the index
  1094. writeTrashFile(fname + "/dir2", "file2", "d");
  1095. assertTrue("File must be a directory now", file.isDirectory());
  1096. assertFalse("Must not delete non empty directory", file.delete());
  1097. // 2 extra files are created
  1098. assertWorkDir(mkmap(fname + "/dir1/file1", "c",
  1099. fname + "/dir2/file2", "d"));
  1100. recorder.assertNoEvent();
  1101. // revert path to HEAD state
  1102. git.checkout().setStartPoint(Constants.HEAD).addPath(fname).call();
  1103. // expect only the one added to the index
  1104. assertWorkDir(mkmap(fname, "a"));
  1105. recorder.assertEvent(new String[] { fname }, ChangeRecorder.EMPTY);
  1106. Status st = git.status().call();
  1107. assertTrue(st.isClean());
  1108. } finally {
  1109. if (handle != null) {
  1110. handle.remove();
  1111. }
  1112. }
  1113. }
  1114. @Test
  1115. public void testCheckoutChangeFileToNonEmptyDirsAndNewIndexEntry()
  1116. throws Exception {
  1117. String fname = "was_file";
  1118. ChangeRecorder recorder = new ChangeRecorder();
  1119. ListenerHandle handle = null;
  1120. try (Git git = new Git(db)) {
  1121. handle = db.getListenerList()
  1122. .addWorkingTreeModifiedListener(recorder);
  1123. // Add a file
  1124. File file = writeTrashFile(fname, "a");
  1125. git.add().addFilepattern(fname).call();
  1126. git.commit().setMessage("Added file").call();
  1127. assertWorkDir(mkmap(fname, "a"));
  1128. // replace file with directory containing only directories, no files
  1129. FileUtils.delete(file);
  1130. // create and add a file in the new directory to the index
  1131. writeTrashFile(fname + "/dir", "file1", "c");
  1132. git.add().addFilepattern(fname + "/dir/file1").call();
  1133. // create but do not add a file in the new directory to the index
  1134. writeTrashFile(fname + "/dir", "file2", "d");
  1135. assertTrue("File must be a directory now", file.isDirectory());
  1136. assertFalse("Must not delete non empty directory", file.delete());
  1137. // 2 extra files are created
  1138. assertWorkDir(mkmap(fname + "/dir/file1", "c", fname + "/dir/file2",
  1139. "d"));
  1140. recorder.assertNoEvent();
  1141. // revert path to HEAD state
  1142. git.checkout().setStartPoint(Constants.HEAD).addPath(fname).call();
  1143. assertWorkDir(mkmap(fname, "a"));
  1144. recorder.assertEvent(new String[] { fname }, ChangeRecorder.EMPTY);
  1145. Status st = git.status().call();
  1146. assertTrue(st.isClean());
  1147. } finally {
  1148. if (handle != null) {
  1149. handle.remove();
  1150. }
  1151. }
  1152. }
  1153. @Test
  1154. public void testCheckoutOutChangesAutoCRLFfalse() throws IOException {
  1155. setupCase(mk("foo"), mkmap("foo/bar", "foo\nbar"), mk("foo"));
  1156. checkout();
  1157. assertIndex(mkmap("foo/bar", "foo\nbar"));
  1158. assertWorkDir(mkmap("foo/bar", "foo\nbar"));
  1159. }
  1160. @Test
  1161. public void testCheckoutOutChangesAutoCRLFInput() throws IOException {
  1162. setupCase(mk("foo"), mkmap("foo/bar", "foo\nbar"), mk("foo"));
  1163. db.getConfig().setString("core", null, "autocrlf", "input");
  1164. checkout();
  1165. assertIndex(mkmap("foo/bar", "foo\nbar"));
  1166. assertWorkDir(mkmap("foo/bar", "foo\nbar"));
  1167. }
  1168. @Test
  1169. public void testCheckoutOutChangesAutoCRLFtrue() throws IOException {
  1170. setupCase(mk("foo"), mkmap("foo/bar", "foo\nbar"), mk("foo"));
  1171. db.getConfig().setString("core", null, "autocrlf", "true");
  1172. checkout();
  1173. assertIndex(mkmap("foo/bar", "foo\nbar"));
  1174. assertWorkDir(mkmap("foo/bar", "foo\r\nbar"));
  1175. }
  1176. @Test
  1177. public void testCheckoutOutChangesAutoCRLFtrueBinary() throws IOException {
  1178. setupCase(mk("foo"), mkmap("foo/bar", "foo\nb\u0000ar"), mk("foo"));
  1179. db.getConfig().setString("core", null, "autocrlf", "true");
  1180. checkout();
  1181. assertIndex(mkmap("foo/bar", "foo\nb\u0000ar"));
  1182. assertWorkDir(mkmap("foo/bar", "foo\nb\u0000ar"));
  1183. }
  1184. @Test
  1185. public void testCheckoutUncachedChanges() throws IOException {
  1186. setupCase(mk("foo"), mk("foo"), mk("foo"));
  1187. writeTrashFile("foo", "otherData");
  1188. checkout();
  1189. assertIndex(mk("foo"));
  1190. assertWorkDir(mkmap("foo", "otherData"));
  1191. assertTrue(new File(trash, "foo").isFile());
  1192. }
  1193. @Test
  1194. public void testDontOverwriteDirtyFile() throws IOException {
  1195. setupCase(mk("foo"), mk("other"), mk("foo"));
  1196. writeTrashFile("foo", "different");
  1197. try {
  1198. checkout();
  1199. fail("Didn't got the expected conflict");
  1200. } catch (CheckoutConflictException e) {
  1201. assertIndex(mk("foo"));
  1202. assertWorkDir(mkmap("foo", "different"));
  1203. assertEquals(Arrays.asList("foo"), getConflicts());
  1204. assertTrue(new File(trash, "foo").isFile());
  1205. }
  1206. }
  1207. @Test
  1208. public void testDontOverwriteEmptyFolder() throws IOException {
  1209. setupCase(mk("foo"), mk("foo"), mk("foo"));
  1210. FileUtils.mkdir(new File(db.getWorkTree(), "d"));
  1211. checkout();
  1212. assertWorkDir(mkmap("foo", "foo", "d", "/"));
  1213. }
  1214. @Test
  1215. public void testOverwriteUntrackedIgnoredFile() throws IOException,
  1216. GitAPIException {
  1217. String fname="file.txt";
  1218. ChangeRecorder recorder = new ChangeRecorder();
  1219. ListenerHandle handle = null;
  1220. try (Git git = new Git(db)) {
  1221. handle = db.getListenerList()
  1222. .addWorkingTreeModifiedListener(recorder);
  1223. // Add a file
  1224. writeTrashFile(fname, "a");
  1225. git.add().addFilepattern(fname).call();
  1226. git.commit().setMessage("create file").call();
  1227. // Create branch
  1228. git.branchCreate().setName("side").call();
  1229. // Modify file
  1230. writeTrashFile(fname, "b");
  1231. git.add().addFilepattern(fname).call();
  1232. git.commit().setMessage("modify file").call();
  1233. recorder.assertNoEvent();
  1234. // Switch branches
  1235. git.checkout().setName("side").call();
  1236. recorder.assertEvent(new String[] { fname }, ChangeRecorder.EMPTY);
  1237. git.rm().addFilepattern(fname).call();
  1238. recorder.assertEvent(ChangeRecorder.EMPTY, new String[] { fname });
  1239. writeTrashFile(".gitignore", fname);
  1240. git.add().addFilepattern(".gitignore").call();
  1241. git.commit().setMessage("delete and ignore file").call();
  1242. writeTrashFile(fname, "Something different");
  1243. recorder.assertNoEvent();
  1244. git.checkout().setName("master").call();
  1245. assertWorkDir(mkmap(fname, "b"));
  1246. recorder.assertEvent(new String[] { fname },
  1247. new String[] { ".gitignore" });
  1248. assertTrue(git.status().call().isClean());
  1249. } finally {
  1250. if (handle != null) {
  1251. handle.remove();
  1252. }
  1253. }
  1254. }
  1255. @Test
  1256. public void testOverwriteUntrackedFileModeChange()
  1257. throws IOException, GitAPIException {
  1258. String fname = "file.txt";
  1259. ChangeRecorder recorder = new ChangeRecorder();
  1260. ListenerHandle handle = null;
  1261. try (Git git = new Git(db)) {
  1262. handle = db.getListenerList()
  1263. .addWorkingTreeModifiedListener(recorder);
  1264. // Add a file
  1265. File file = writeTrashFile(fname, "a");
  1266. git.add().addFilepattern(fname).call();
  1267. git.commit().setMessage("create file").call();
  1268. assertWorkDir(mkmap(fname, "a"));
  1269. // Create branch
  1270. git.branchCreate().setName("side").call();
  1271. // Switch branches
  1272. git.checkout().setName("side").call();
  1273. recorder.assertNoEvent();
  1274. // replace file with directory containing files
  1275. FileUtils.delete(file);
  1276. // create and add a file in the new directory to the index
  1277. writeTrashFile(fname + "/dir1", "file1", "c");
  1278. git.add().addFilepattern(fname + "/dir1/file1").call();
  1279. // create but do not add a file in the new directory to the index
  1280. writeTrashFile(fname + "/dir2", "file2", "d");
  1281. assertTrue("File must be a directory now", file.isDirectory());
  1282. assertFalse("Must not delete non empty directory", file.delete());
  1283. // 2 extra files are created
  1284. assertWorkDir(mkmap(fname + "/dir1/file1", "c",
  1285. fname + "/dir2/file2", "d"));
  1286. try {
  1287. git.checkout().setName("master").call();
  1288. fail("did not throw exception");
  1289. } catch (Exception e) {
  1290. // 2 extra files are still there
  1291. assertWorkDir(mkmap(fname + "/dir1/file1", "c",
  1292. fname + "/dir2/file2", "d"));
  1293. }
  1294. recorder.assertNoEvent();
  1295. } finally {
  1296. if (handle != null) {
  1297. handle.remove();
  1298. }
  1299. }
  1300. }
  1301. @Test
  1302. public void testOverwriteUntrackedLinkModeChange()
  1303. throws Exception {
  1304. Assume.assumeTrue(FS.DETECTED.supportsSymlinks());
  1305. String fname = "file.txt";
  1306. ChangeRecorder recorder = new ChangeRecorder();
  1307. ListenerHandle handle = null;
  1308. try (Git git = new Git(db)) {
  1309. handle = db.getListenerList()
  1310. .addWorkingTreeModifiedListener(recorder);
  1311. // Add a file
  1312. writeTrashFile(fname, "a");
  1313. git.add().addFilepattern(fname).call();
  1314. // Add a link to file
  1315. String linkName = "link";
  1316. File link = writeLink(linkName, fname).toFile();
  1317. git.add().addFilepattern(linkName).call();
  1318. git.commit().setMessage("Added file and link").call();
  1319. assertWorkDir(mkmap(linkName, "a", fname, "a"));
  1320. // Create branch
  1321. git.branchCreate().setName("side").call();
  1322. // Switch branches
  1323. git.checkout().setName("side").call();
  1324. recorder.assertNoEvent();
  1325. // replace link with directory containing files
  1326. FileUtils.delete(link);
  1327. // create and add a file in the new directory to the index
  1328. writeTrashFile(linkName + "/dir1", "file1", "c");
  1329. git.add().addFilepattern(linkName + "/dir1/file1").call();
  1330. // create but do not add a file in the new directory to the index
  1331. writeTrashFile(linkName + "/dir2", "file2", "d");
  1332. assertTrue("Link must be a directory now", link.isDirectory());
  1333. assertFalse("Must not delete non empty directory", link.delete());
  1334. // 2 extra files are created
  1335. assertWorkDir(mkmap(fname, "a", linkName + "/dir1/file1", "c",
  1336. linkName + "/dir2/file2", "d"));
  1337. try {
  1338. git.checkout().setName("master").call();
  1339. fail("did not throw exception");
  1340. } catch (Exception e) {
  1341. // 2 extra files are still there
  1342. assertWorkDir(mkmap(fname, "a", linkName + "/dir1/file1", "c",
  1343. linkName + "/dir2/file2", "d"));
  1344. }
  1345. recorder.assertNoEvent();
  1346. } finally {
  1347. if (handle != null) {
  1348. handle.remove();
  1349. }
  1350. }
  1351. }
  1352. @Test
  1353. public void testFileModeChangeWithNoContentChangeUpdate() throws Exception {
  1354. if (!FS.DETECTED.supportsExecute())
  1355. return;
  1356. ChangeRecorder recorder = new ChangeRecorder();
  1357. ListenerHandle handle = null;
  1358. try (Git git = new Git(db)) {
  1359. handle = db.getListenerList()
  1360. .addWorkingTreeModifiedListener(recorder);
  1361. // Add non-executable file
  1362. File file = writeTrashFile("file.txt", "a");
  1363. git.add().addFilepattern("file.txt").call();
  1364. git.commit().setMessage("commit1").call();
  1365. assertFalse(db.getFS().canExecute(file));
  1366. // Create branch
  1367. git.branchCreate().setName("b1").call();
  1368. // Make file executable
  1369. db.getFS().setExecute(file, true);
  1370. git.add().addFilepattern("file.txt").call();
  1371. git.commit().setMessage("commit2").call();
  1372. recorder.assertNoEvent();
  1373. // Verify executable and working directory is clean
  1374. Status status = git.status().call();
  1375. assertTrue(status.getModified().isEmpty());
  1376. assertTrue(status.getChanged().isEmpty());
  1377. assertTrue(db.getFS().canExecute(file));
  1378. // Switch branches
  1379. git.checkout().setName("b1").call();
  1380. // Verify not executable and working directory is clean
  1381. status = git.status().call();
  1382. assertTrue(status.getModified().isEmpty());
  1383. assertTrue(status.getChanged().isEmpty());
  1384. assertFalse(db.getFS().canExecute(file));
  1385. recorder.assertEvent(new String[] { "file.txt" },
  1386. ChangeRecorder.EMPTY);
  1387. } finally {
  1388. if (handle != null) {
  1389. handle.remove();
  1390. }
  1391. }
  1392. }
  1393. @Test
  1394. public void testFileModeChangeAndContentChangeConflict() throws Exception {
  1395. if (!FS.DETECTED.supportsExecute())
  1396. return;
  1397. ChangeRecorder recorder = new ChangeRecorder();
  1398. ListenerHandle handle = null;
  1399. try (Git git = new Git(db)) {
  1400. handle = db.getListenerList()
  1401. .addWorkingTreeModifiedListener(recorder);
  1402. // Add non-executable file
  1403. File file = writeTrashFile("file.txt", "a");
  1404. git.add().addFilepattern("file.txt").call();
  1405. git.commit().setMessage("commit1").call();
  1406. assertFalse(db.getFS().canExecute(file));
  1407. // Create branch
  1408. git.branchCreate().setName("b1").call();
  1409. // Make file executable
  1410. db.getFS().setExecute(file, true);
  1411. git.add().addFilepattern("file.txt").call();
  1412. git.commit().setMessage("commit2").call();
  1413. // Verify executable and working directory is clean
  1414. Status status = git.status().call();
  1415. assertTrue(status.getModified().isEmpty());
  1416. assertTrue(status.getChanged().isEmpty());
  1417. assertTrue(db.getFS().canExecute(file));
  1418. writeTrashFile("file.txt", "b");
  1419. // Switch branches
  1420. CheckoutCommand checkout = git.checkout().setName("b1");
  1421. try {
  1422. checkout.call();
  1423. fail("Checkout exception not thrown");
  1424. } catch (org.eclipse.jgit.api.errors.CheckoutConflictException e) {
  1425. CheckoutResult result = checkout.getResult();
  1426. assertNotNull(result);
  1427. assertNotNull(result.getConflictList());
  1428. assertEquals(1, result.getConflictList().size());
  1429. assertTrue(result.getConflictList().contains("file.txt"));
  1430. }
  1431. recorder.assertNoEvent();
  1432. } finally {
  1433. if (handle != null) {
  1434. handle.remove();
  1435. }
  1436. }
  1437. }
  1438. @Test
  1439. public void testDirtyFileModeEqualHeadMerge()
  1440. throws Exception {
  1441. if (!FS.DETECTED.supportsExecute())
  1442. return;
  1443. ChangeRecorder recorder = new ChangeRecorder();
  1444. ListenerHandle handle = null;
  1445. try (Git git = new Git(db)) {
  1446. handle = db.getListenerList()
  1447. .addWorkingTreeModifiedListener(recorder);
  1448. // Add non-executable file
  1449. File file = writeTrashFile("file.txt", "a");
  1450. git.add().addFilepattern("file.txt").call();
  1451. git.commit().setMessage("commit1").call();
  1452. assertFalse(db.getFS().canExecute(file));
  1453. // Create branch
  1454. git.branchCreate().setName("b1").call();
  1455. // Create second commit and don't touch file
  1456. writeTrashFile("file2.txt", "");
  1457. git.add().addFilepattern("file2.txt").call();
  1458. git.commit().setMessage("commit2").call();
  1459. // stage a mode change
  1460. writeTrashFile("file.txt", "a");
  1461. db.getFS().setExecute(file, true);
  1462. git.add().addFilepattern("file.txt").call();
  1463. // dirty the file
  1464. writeTrashFile("file.txt", "b");
  1465. assertEquals(
  1466. "[file.txt, mode:100755, content:a][file2.txt, mode:100644, content:]",
  1467. indexState(CONTENT));
  1468. assertWorkDir(mkmap("file.txt", "b", "file2.txt", ""));
  1469. recorder.assertNoEvent();
  1470. // Switch branches and check that the dirty file survived in
  1471. // worktree and index
  1472. git.checkout().setName("b1").call();
  1473. assertEquals("[file.txt, mode:100755, content:a]",
  1474. indexState(CONTENT));
  1475. assertWorkDir(mkmap("file.txt", "b"));
  1476. recorder.assertEvent(ChangeRecorder.EMPTY,
  1477. new String[] { "file2.txt" });
  1478. } finally {
  1479. if (handle != null) {
  1480. handle.remove();
  1481. }
  1482. }
  1483. }
  1484. @Test
  1485. public void testDirtyFileModeEqualIndexMerge()
  1486. throws Exception {
  1487. if (!FS.DETECTED.supportsExecute())
  1488. return;
  1489. ChangeRecorder recorder = new ChangeRecorder();
  1490. ListenerHandle handle = null;
  1491. try (Git git = new Git(db)) {
  1492. handle = db.getListenerList()
  1493. .addWorkingTreeModifiedListener(recorder);
  1494. // Add non-executable file
  1495. File file = writeTrashFile("file.txt", "a");
  1496. git.add().addFilepattern("file.txt").call();
  1497. git.commit().setMessage("commit1").call();
  1498. assertFalse(db.getFS().canExecute(file));
  1499. // Create branch
  1500. git.branchCreate().setName("b1").call();
  1501. // Create second commit with executable file
  1502. file = writeTrashFile("file.txt", "b");
  1503. db.getFS().setExecute(file, true);
  1504. git.add().addFilepattern("file.txt").call();
  1505. git.commit().setMessage("commit2").call();
  1506. // stage the same content as in the branch we want to switch to
  1507. writeTrashFile("file.txt", "a");
  1508. db.getFS().setExecute(file, false);
  1509. git.add().addFilepattern("file.txt").call();
  1510. // dirty the file
  1511. writeTrashFile("file.txt", "c");
  1512. db.getFS().setExecute(file, true);
  1513. assertEquals("[file.txt, mode:100644, content:a]",
  1514. indexState(CONTENT));
  1515. assertWorkDir(mkmap("file.txt", "c"));
  1516. recorder.assertNoEvent();
  1517. // Switch branches and check that the dirty file survived in
  1518. // worktree
  1519. // and index
  1520. git.checkout().setName("b1").call();
  1521. assertEquals("[file.txt, mode:100644, content:a]",
  1522. indexState(CONTENT));
  1523. assertWorkDir(mkmap("file.txt", "c"));
  1524. recorder.assertNoEvent();
  1525. } finally {
  1526. if (handle != null) {
  1527. handle.remove();
  1528. }
  1529. }
  1530. }
  1531. @Test
  1532. public void testFileModeChangeAndContentChangeNoConflict() throws Exception {
  1533. if (!FS.DETECTED.supportsExecute())
  1534. return;
  1535. ChangeRecorder recorder = new ChangeRecorder();
  1536. ListenerHandle handle = null;
  1537. try (Git git = new Git(db)) {
  1538. handle = db.getListenerList()
  1539. .addWorkingTreeModifiedListener(recorder);
  1540. // Add first file
  1541. File file1 = writeTrashFile("file1.txt", "a");
  1542. git.add().addFilepattern("file1.txt").call();
  1543. git.commit().setMessage("commit1").call();
  1544. assertFalse(db.getFS().canExecute(file1));
  1545. // Add second file
  1546. File file2 = writeTrashFile("file2.txt", "b");
  1547. git.add().addFilepattern("file2.txt").call();
  1548. git.commit().setMessage("commit2").call();
  1549. assertFalse(db.getFS().canExecute(file2));
  1550. recorder.assertNoEvent();
  1551. // Create branch from first commit
  1552. assertNotNull(git.checkout().setCreateBranch(true).setName("b1")
  1553. .setStartPoint(Constants.HEAD + "~1").call());
  1554. recorder.assertEvent(ChangeRecorder.EMPTY,
  1555. new String[] { "file2.txt" });
  1556. // Change content and file mode in working directory and index
  1557. file1 = writeTrashFile("file1.txt", "c");
  1558. db.getFS().setExecute(file1, true);
  1559. git.add().addFilepattern("file1.txt").call();
  1560. // Switch back to 'master'
  1561. assertNotNull(git.checkout().setName(Constants.MASTER).call());
  1562. recorder.assertEvent(new String[] { "file2.txt" },
  1563. ChangeRecorder.EMPTY);
  1564. } finally {
  1565. if (handle != null) {
  1566. handle.remove();
  1567. }
  1568. }
  1569. }
  1570. @Test(expected = CheckoutConflictException.class)
  1571. public void testFolderFileConflict() throws Exception {
  1572. RevCommit headCommit = commitFile("f/a", "initial content", "master");
  1573. RevCommit checkoutCommit = commitFile("f/a", "side content", "side");
  1574. FileUtils.delete(new File(db.getWorkTree(), "f"), FileUtils.RECURSIVE);
  1575. writeTrashFile("f", "file instead of folder");
  1576. new DirCacheCheckout(db, headCommit.getTree(), db.lockDirCache(),
  1577. checkoutCommit.getTree()).checkout();
  1578. }
  1579. @Test
  1580. public void testMultipleContentConflicts() throws Exception {
  1581. commitFile("a", "initial content", "master");
  1582. RevCommit headCommit = commitFile("b", "initial content", "master");
  1583. commitFile("a", "side content", "side");
  1584. RevCommit checkoutCommit = commitFile("b", "side content", "side");
  1585. writeTrashFile("a", "changed content");
  1586. writeTrashFile("b", "changed content");
  1587. try {
  1588. new DirCacheCheckout(db, headCommit.getTree(), db.lockDirCache(),
  1589. checkoutCommit.getTree()).checkout();
  1590. fail();
  1591. } catch (CheckoutConflictException expected) {
  1592. assertEquals(2, expected.getConflictingFiles().length);
  1593. assertTrue(Arrays.asList(expected.getConflictingFiles())
  1594. .contains("a"));
  1595. assertTrue(Arrays.asList(expected.getConflictingFiles())
  1596. .contains("b"));
  1597. assertEquals("changed content", read("a"));
  1598. assertEquals("changed content", read("b"));
  1599. }
  1600. }
  1601. @Test
  1602. public void testFolderFileAndContentConflicts() throws Exception {
  1603. RevCommit headCommit = commitFile("f/a", "initial content", "master");
  1604. commitFile("b", "side content", "side");
  1605. RevCommit checkoutCommit = commitFile("f/a", "side content", "side");
  1606. FileUtils.delete(new File(db.getWorkTree(), "f"), FileUtils.RECURSIVE);
  1607. writeTrashFile("f", "file instead of a folder");
  1608. writeTrashFile("b", "changed content");
  1609. try {
  1610. new DirCacheCheckout(db, headCommit.getTree(), db.lockDirCache(),
  1611. checkoutCommit.getTree()).checkout();
  1612. fail();
  1613. } catch (CheckoutConflictException expected) {
  1614. assertEquals(2, expected.getConflictingFiles().length);
  1615. assertTrue(Arrays.asList(expected.getConflictingFiles())
  1616. .contains("b"));
  1617. assertTrue(Arrays.asList(expected.getConflictingFiles())
  1618. .contains("f"));
  1619. assertEquals("file instead of a folder", read("f"));
  1620. assertEquals("changed content", read("b"));
  1621. }
  1622. }
  1623. @Test
  1624. public void testLongFilename() throws Exception {
  1625. char[] bytes = new char[253];
  1626. Arrays.fill(bytes, 'f');
  1627. String longFileName = new String(bytes);
  1628. // 1
  1629. doit(mkmap(longFileName, "a"), mkmap(longFileName, "b"),
  1630. mkmap(longFileName, "a"));
  1631. writeTrashFile(longFileName, "a");
  1632. checkout();
  1633. assertNoConflicts();
  1634. assertUpdated(longFileName);
  1635. }
  1636. @Test
  1637. public void testIgnoredDirectory() throws Exception {
  1638. writeTrashFile(".gitignore", "src/ignored");
  1639. writeTrashFile("src/ignored/sub/foo.txt", "1");
  1640. try (Git git = new Git(db)) {
  1641. git.add().addFilepattern(".").call();
  1642. RevCommit commit = git.commit().setMessage("adding .gitignore")
  1643. .call();
  1644. writeTrashFile("foo.txt", "2");
  1645. writeTrashFile("zzz.txt", "3");
  1646. git.add().addFilepattern("foo.txt").call();
  1647. git.commit().setMessage("add file").call();
  1648. assertEquals("Should not have entered ignored directory", 1,
  1649. resetHardAndCount(commit));
  1650. }
  1651. }
  1652. @Test
  1653. public void testIgnoredDirectoryWithTrackedContent() throws Exception {
  1654. writeTrashFile("src/ignored/sub/foo.txt", "1");
  1655. try (Git git = new Git(db)) {
  1656. git.add().addFilepattern(".").call();
  1657. git.commit().setMessage("adding foo.txt").call();
  1658. writeTrashFile(".gitignore", "src/ignored");
  1659. writeTrashFile("src/ignored/sub/foo.txt", "2");
  1660. writeTrashFile("src/ignored/other/bar.txt", "3");
  1661. git.add().addFilepattern(".").call();
  1662. RevCommit commit = git.commit().setMessage("adding .gitignore")
  1663. .call();
  1664. writeTrashFile("foo.txt", "2");
  1665. writeTrashFile("zzz.txt", "3");
  1666. git.add().addFilepattern("foo.txt").call();
  1667. git.commit().setMessage("add file").call();
  1668. File file = writeTrashFile("src/ignored/sub/foo.txt", "3");
  1669. assertEquals("Should have entered ignored directory", 3,
  1670. resetHardAndCount(commit));
  1671. checkFile(file, "2");
  1672. }
  1673. }
  1674. @Test
  1675. public void testResetWithChangeInGitignore() throws Exception {
  1676. writeTrashFile(".gitignore", "src/ignored");
  1677. writeTrashFile("src/ignored/sub/foo.txt", "1");
  1678. try (Git git = new Git(db)) {
  1679. git.add().addFilepattern(".").call();
  1680. RevCommit initial = git.commit().setMessage("initial").call();
  1681. writeTrashFile("src/newignored/foo.txt", "2");
  1682. writeTrashFile("src/.gitignore", "newignored");
  1683. git.add().addFilepattern(".").call();
  1684. RevCommit commit = git.commit().setMessage("newignored").call();
  1685. assertEquals("Should not have entered src/newignored directory", 1,
  1686. resetHardAndCount(initial));
  1687. assertEquals("Should have entered src/newignored directory", 2,
  1688. resetHardAndCount(commit));
  1689. deleteTrashFile("src/.gitignore");
  1690. git.rm().addFilepattern("src/.gitignore").call();
  1691. RevCommit top = git.commit().setMessage("Unignore newignore")
  1692. .call();
  1693. assertEquals("Should have entered src/newignored directory", 2,
  1694. resetHardAndCount(initial));
  1695. assertEquals("Should have entered src/newignored directory", 2,
  1696. resetHardAndCount(commit));
  1697. assertEquals("Should not have entered src/newignored directory", 1,
  1698. resetHardAndCount(top));
  1699. }
  1700. }
  1701. @Test
  1702. public void testCheckoutWithEmptyIndexDoesntOverwrite() throws Exception {
  1703. try (Git git = new Git(db);
  1704. TestRepository<Repository> db_t = new TestRepository<>(db)) {
  1705. // prepare the commits
  1706. BranchBuilder master = db_t.branch("master");
  1707. RevCommit mergeCommit = master.commit()
  1708. .add("p/x", "headContent")
  1709. .message("m0").create();
  1710. master.commit().add("p/x", "headContent").message("m1").create();
  1711. git.checkout().setName("master").call();
  1712. // empty index and write unsaved data in 'p'
  1713. git.rm().addFilepattern("p").call();
  1714. writeTrashFile("p", "important data");
  1715. git.checkout().setName(mergeCommit.getName()).call();
  1716. assertEquals("", indexState(CONTENT));
  1717. assertEquals("important data", read("p"));
  1718. }
  1719. }
  1720. private static class TestFileTreeIterator extends FileTreeIterator {
  1721. // For assertions only
  1722. private final int[] count;
  1723. public TestFileTreeIterator(Repository repo, int[] count) {
  1724. super(repo);
  1725. this.count = count;
  1726. }
  1727. protected TestFileTreeIterator(final WorkingTreeIterator p,
  1728. final File root, FS fs, FileModeStrategy fileModeStrategy,
  1729. int[] count) {
  1730. super(p, root, fs, fileModeStrategy);
  1731. this.count = count;
  1732. }
  1733. @Override
  1734. protected AbstractTreeIterator enterSubtree() {
  1735. count[0] += 1;
  1736. return new TestFileTreeIterator(this,
  1737. ((FileEntry) current()).getFile(), fs, fileModeStrategy,
  1738. count);
  1739. }
  1740. }
  1741. private int resetHardAndCount(RevCommit commit) throws Exception {
  1742. int[] callCount = { 0 };
  1743. DirCache cache = db.lockDirCache();
  1744. FileTreeIterator workingTreeIterator = new TestFileTreeIterator(db,
  1745. callCount);
  1746. try {
  1747. DirCacheCheckout checkout = new DirCacheCheckout(db, null, cache,
  1748. commit.getTree().getId(), workingTreeIterator);
  1749. checkout.setFailOnConflict(false);
  1750. checkout.checkout();
  1751. } finally {
  1752. cache.unlock();
  1753. }
  1754. return callCount[0];
  1755. }
  1756. public void assertWorkDir(Map<String, String> i)
  1757. throws CorruptObjectException,
  1758. IOException {
  1759. try (TreeWalk walk = new TreeWalk(db)) {
  1760. walk.setRecursive(false);
  1761. walk.addTree(new FileTreeIterator(db));
  1762. String expectedValue;
  1763. String path;
  1764. int nrFiles = 0;
  1765. FileTreeIterator ft;
  1766. while (walk.next()) {
  1767. ft = walk.getTree(0, FileTreeIterator.class);
  1768. path = ft.getEntryPathString();
  1769. expectedValue = i.get(path);
  1770. File file = new File(db.getWorkTree(), path);
  1771. assertTrue(file.exists());
  1772. if (file.isFile()) {
  1773. assertNotNull("found unexpected file for path " + path
  1774. + " in workdir", expectedValue);
  1775. try (FileInputStream is = new FileInputStream(file)) {
  1776. byte[] buffer = new byte[(int) file.length()];
  1777. int offset = 0;
  1778. int numRead = 0;
  1779. while (offset < buffer.length
  1780. && (numRead = is.read(buffer, offset,
  1781. buffer.length - offset)) >= 0) {
  1782. offset += numRead;
  1783. }
  1784. assertArrayEquals(
  1785. "unexpected content for path " + path
  1786. + " in workDir. ",
  1787. buffer, i.get(path).getBytes(UTF_8));
  1788. }
  1789. nrFiles++;
  1790. } else if (file.isDirectory()) {
  1791. String[] files = file.list();
  1792. if (files != null && files.length == 0) {
  1793. assertEquals("found unexpected empty folder for path "
  1794. + path + " in workDir. ", "/", i.get(path));
  1795. nrFiles++;
  1796. }
  1797. }
  1798. if (walk.isSubtree()) {
  1799. walk.enterSubtree();
  1800. }
  1801. }
  1802. assertEquals("WorkDir has not the right size.", i.size(), nrFiles);
  1803. }
  1804. }
  1805. }