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.

PullCommandTest.java 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. /*
  2. * Copyright (C) 2010, Mathias Kinzler <mathias.kinzler@sap.com> and others
  3. *
  4. * This program and the accompanying materials are made available under the
  5. * terms of the Eclipse Distribution License v. 1.0 which is available at
  6. * https://www.eclipse.org/org/documents/edl-v10.php.
  7. *
  8. * SPDX-License-Identifier: BSD-3-Clause
  9. */
  10. package org.eclipse.jgit.api;
  11. import static java.nio.charset.StandardCharsets.UTF_8;
  12. import static org.junit.Assert.assertEquals;
  13. import static org.junit.Assert.assertFalse;
  14. import static org.junit.Assert.assertNotNull;
  15. import static org.junit.Assert.assertNull;
  16. import static org.junit.Assert.assertTrue;
  17. import java.io.ByteArrayOutputStream;
  18. import java.io.File;
  19. import java.io.FileInputStream;
  20. import java.io.FileOutputStream;
  21. import java.io.IOException;
  22. import java.util.concurrent.Callable;
  23. import org.eclipse.jgit.api.CreateBranchCommand.SetupUpstreamMode;
  24. import org.eclipse.jgit.api.MergeResult.MergeStatus;
  25. import org.eclipse.jgit.api.errors.NoHeadException;
  26. import org.eclipse.jgit.junit.JGitTestUtil;
  27. import org.eclipse.jgit.junit.RepositoryTestCase;
  28. import org.eclipse.jgit.lib.Constants;
  29. import org.eclipse.jgit.lib.ObjectId;
  30. import org.eclipse.jgit.lib.RefUpdate;
  31. import org.eclipse.jgit.lib.Repository;
  32. import org.eclipse.jgit.lib.RepositoryState;
  33. import org.eclipse.jgit.lib.StoredConfig;
  34. import org.eclipse.jgit.revwalk.RevCommit;
  35. import org.eclipse.jgit.revwalk.RevSort;
  36. import org.eclipse.jgit.revwalk.RevWalk;
  37. import org.eclipse.jgit.transport.RefSpec;
  38. import org.eclipse.jgit.transport.RemoteConfig;
  39. import org.eclipse.jgit.transport.URIish;
  40. import org.junit.Before;
  41. import org.junit.Test;
  42. public class PullCommandTest extends RepositoryTestCase {
  43. /** Second Test repository */
  44. protected Repository dbTarget;
  45. private Git source;
  46. private Git target;
  47. private File sourceFile;
  48. private File targetFile;
  49. @Test
  50. public void testPullFastForward() throws Exception {
  51. PullResult res = target.pull().call();
  52. // nothing to update since we don't have different data yet
  53. assertTrue(res.getFetchResult().getTrackingRefUpdates().isEmpty());
  54. assertTrue(res.getMergeResult().getMergeStatus().equals(
  55. MergeStatus.ALREADY_UP_TO_DATE));
  56. assertFileContentsEqual(targetFile, "Hello world");
  57. // change the source file
  58. writeToFile(sourceFile, "Another change");
  59. source.add().addFilepattern("SomeFile.txt").call();
  60. source.commit().setMessage("Some change in remote").call();
  61. res = target.pull().call();
  62. assertFalse(res.getFetchResult().getTrackingRefUpdates().isEmpty());
  63. assertEquals(res.getMergeResult().getMergeStatus(),
  64. MergeStatus.FAST_FORWARD);
  65. assertFileContentsEqual(targetFile, "Another change");
  66. assertEquals(RepositoryState.SAFE, target.getRepository()
  67. .getRepositoryState());
  68. res = target.pull().call();
  69. assertEquals(res.getMergeResult().getMergeStatus(),
  70. MergeStatus.ALREADY_UP_TO_DATE);
  71. }
  72. @Test
  73. public void testPullMerge() throws Exception {
  74. PullResult res = target.pull().call();
  75. // nothing to update since we don't have different data yet
  76. assertTrue(res.getFetchResult().getTrackingRefUpdates().isEmpty());
  77. assertTrue(res.getMergeResult().getMergeStatus()
  78. .equals(MergeStatus.ALREADY_UP_TO_DATE));
  79. writeToFile(sourceFile, "Source change");
  80. source.add().addFilepattern("SomeFile.txt");
  81. RevCommit sourceCommit = source.commit()
  82. .setMessage("Source change in remote").call();
  83. File targetFile2 = new File(dbTarget.getWorkTree(), "OtherFile.txt");
  84. writeToFile(targetFile2, "Unconflicting change");
  85. target.add().addFilepattern("OtherFile.txt").call();
  86. RevCommit targetCommit = target.commit()
  87. .setMessage("Unconflicting change in local").call();
  88. res = target.pull().call();
  89. MergeResult mergeResult = res.getMergeResult();
  90. ObjectId[] mergedCommits = mergeResult.getMergedCommits();
  91. assertEquals(targetCommit.getId(), mergedCommits[0]);
  92. assertEquals(sourceCommit.getId(), mergedCommits[1]);
  93. try (RevWalk rw = new RevWalk(dbTarget)) {
  94. RevCommit mergeCommit = rw.parseCommit(mergeResult.getNewHead());
  95. String message = "Merge branch 'master' of "
  96. + db.getWorkTree().getAbsolutePath();
  97. assertEquals(message, mergeCommit.getShortMessage());
  98. }
  99. }
  100. @Test
  101. public void testPullConflict() throws Exception {
  102. PullResult res = target.pull().call();
  103. // nothing to update since we don't have different data yet
  104. assertTrue(res.getFetchResult().getTrackingRefUpdates().isEmpty());
  105. assertTrue(res.getMergeResult().getMergeStatus().equals(
  106. MergeStatus.ALREADY_UP_TO_DATE));
  107. assertFileContentsEqual(targetFile, "Hello world");
  108. // change the source file
  109. writeToFile(sourceFile, "Source change");
  110. source.add().addFilepattern("SomeFile.txt").call();
  111. source.commit().setMessage("Source change in remote").call();
  112. // change the target file
  113. writeToFile(targetFile, "Target change");
  114. target.add().addFilepattern("SomeFile.txt").call();
  115. target.commit().setMessage("Target change in local").call();
  116. res = target.pull().call();
  117. String sourceChangeString = "Source change\n>>>>>>> branch 'master' of "
  118. + target.getRepository().getConfig().getString("remote",
  119. "origin", "url");
  120. assertFalse(res.getFetchResult().getTrackingRefUpdates().isEmpty());
  121. assertEquals(res.getMergeResult().getMergeStatus(),
  122. MergeStatus.CONFLICTING);
  123. String result = "<<<<<<< HEAD\nTarget change\n=======\n"
  124. + sourceChangeString + "\n";
  125. assertFileContentsEqual(targetFile, result);
  126. assertEquals(RepositoryState.MERGING, target.getRepository()
  127. .getRepositoryState());
  128. }
  129. @Test
  130. public void testPullWithUntrackedStash() throws Exception {
  131. target.pull().call();
  132. // change the source file
  133. writeToFile(sourceFile, "Source change");
  134. source.add().addFilepattern("SomeFile.txt").call();
  135. source.commit().setMessage("Source change in remote").call();
  136. // write untracked file
  137. writeToFile(new File(dbTarget.getWorkTree(), "untracked.txt"),
  138. "untracked");
  139. RevCommit stash = target.stashCreate().setIndexMessage("message here")
  140. .setIncludeUntracked(true).call();
  141. assertNotNull(stash);
  142. assertTrue(target.status().call().isClean());
  143. // pull from source
  144. assertTrue(target.pull().call().isSuccessful());
  145. assertEquals("[SomeFile.txt, mode:100644, content:Source change]",
  146. indexState(dbTarget, CONTENT));
  147. assertFalse(JGitTestUtil.check(dbTarget, "untracked.txt"));
  148. assertEquals("Source change",
  149. JGitTestUtil.read(dbTarget, "SomeFile.txt"));
  150. // apply the stash
  151. target.stashApply().setStashRef(stash.getName()).call();
  152. assertEquals("[SomeFile.txt, mode:100644, content:Source change]",
  153. indexState(dbTarget, CONTENT));
  154. assertEquals("untracked", JGitTestUtil.read(dbTarget, "untracked.txt"));
  155. assertEquals("Source change",
  156. JGitTestUtil.read(dbTarget, "SomeFile.txt"));
  157. }
  158. @Test
  159. public void testPullLocalConflict() throws Exception {
  160. target.branchCreate().setName("basedOnMaster").setStartPoint(
  161. "refs/heads/master").setUpstreamMode(SetupUpstreamMode.TRACK)
  162. .call();
  163. target.getRepository().updateRef(Constants.HEAD).link(
  164. "refs/heads/basedOnMaster");
  165. PullResult res = target.pull().call();
  166. // nothing to update since we don't have different data yet
  167. assertNull(res.getFetchResult());
  168. assertTrue(res.getMergeResult().getMergeStatus().equals(
  169. MergeStatus.ALREADY_UP_TO_DATE));
  170. assertFileContentsEqual(targetFile, "Hello world");
  171. // change the file in master
  172. target.getRepository().updateRef(Constants.HEAD).link(
  173. "refs/heads/master");
  174. writeToFile(targetFile, "Master change");
  175. target.add().addFilepattern("SomeFile.txt").call();
  176. target.commit().setMessage("Source change in master").call();
  177. // change the file in slave
  178. target.getRepository().updateRef(Constants.HEAD).link(
  179. "refs/heads/basedOnMaster");
  180. writeToFile(targetFile, "Slave change");
  181. target.add().addFilepattern("SomeFile.txt").call();
  182. target.commit().setMessage("Source change in based on master").call();
  183. res = target.pull().call();
  184. String sourceChangeString = "Master change\n>>>>>>> branch 'master' of local repository";
  185. assertNull(res.getFetchResult());
  186. assertEquals(res.getMergeResult().getMergeStatus(),
  187. MergeStatus.CONFLICTING);
  188. String result = "<<<<<<< HEAD\nSlave change\n=======\n"
  189. + sourceChangeString + "\n";
  190. assertFileContentsEqual(targetFile, result);
  191. assertEquals(RepositoryState.MERGING, target.getRepository()
  192. .getRepositoryState());
  193. }
  194. @Test(expected = NoHeadException.class)
  195. public void testPullEmptyRepository() throws Exception {
  196. Repository empty = createWorkRepository();
  197. RefUpdate delete = empty.updateRef(Constants.HEAD, true);
  198. delete.setForceUpdate(true);
  199. delete.delete();
  200. Git.wrap(empty).pull().call();
  201. }
  202. @Test
  203. public void testPullMergeProgrammaticConfiguration() throws Exception {
  204. // create another commit on another branch in source
  205. source.checkout().setCreateBranch(true).setName("other").call();
  206. sourceFile = new File(db.getWorkTree(), "file2.txt");
  207. writeToFile(sourceFile, "content");
  208. source.add().addFilepattern("file2.txt").call();
  209. RevCommit sourceCommit = source.commit()
  210. .setMessage("source commit on branch other").call();
  211. File targetFile2 = new File(dbTarget.getWorkTree(), "OtherFile.txt");
  212. writeToFile(targetFile2, "Unconflicting change");
  213. target.add().addFilepattern("OtherFile.txt").call();
  214. RevCommit targetCommit = target.commit()
  215. .setMessage("Unconflicting change in local").call();
  216. PullResult res = target.pull().setRemote("origin")
  217. .setRemoteBranchName("other")
  218. .setRebase(false).call();
  219. MergeResult mergeResult = res.getMergeResult();
  220. ObjectId[] mergedCommits = mergeResult.getMergedCommits();
  221. assertEquals(targetCommit.getId(), mergedCommits[0]);
  222. assertEquals(sourceCommit.getId(), mergedCommits[1]);
  223. try (RevWalk rw = new RevWalk(dbTarget)) {
  224. RevCommit mergeCommit = rw.parseCommit(mergeResult.getNewHead());
  225. String message = "Merge branch 'other' of "
  226. + db.getWorkTree().getAbsolutePath();
  227. assertEquals(message, mergeCommit.getShortMessage());
  228. }
  229. }
  230. @Test
  231. public void testPullMergeProgrammaticConfigurationImpliedTargetBranch()
  232. throws Exception {
  233. // create another commit on another branch in source
  234. source.checkout().setCreateBranch(true).setName("other").call();
  235. sourceFile = new File(db.getWorkTree(), "file2.txt");
  236. writeToFile(sourceFile, "content");
  237. source.add().addFilepattern("file2.txt").call();
  238. RevCommit sourceCommit = source.commit()
  239. .setMessage("source commit on branch other").call();
  240. target.checkout().setCreateBranch(true).setName("other").call();
  241. File targetFile2 = new File(dbTarget.getWorkTree(), "OtherFile.txt");
  242. writeToFile(targetFile2, "Unconflicting change");
  243. target.add().addFilepattern("OtherFile.txt").call();
  244. RevCommit targetCommit = target.commit()
  245. .setMessage("Unconflicting change in local").call();
  246. // the source branch "other" matching the target branch should be
  247. // implied
  248. PullResult res = target.pull().setRemote("origin").setRebase(false)
  249. .call();
  250. MergeResult mergeResult = res.getMergeResult();
  251. ObjectId[] mergedCommits = mergeResult.getMergedCommits();
  252. assertEquals(targetCommit.getId(), mergedCommits[0]);
  253. assertEquals(sourceCommit.getId(), mergedCommits[1]);
  254. try (RevWalk rw = new RevWalk(dbTarget)) {
  255. RevCommit mergeCommit = rw.parseCommit(mergeResult.getNewHead());
  256. String message = "Merge branch 'other' of "
  257. + db.getWorkTree().getAbsolutePath() + " into other";
  258. assertEquals(message, mergeCommit.getShortMessage());
  259. }
  260. }
  261. private enum TestPullMode {
  262. MERGE, REBASE, REBASE_PREASERVE
  263. }
  264. @Test
  265. /** global rebase config should be respected */
  266. public void testPullWithRebasePreserve1Config() throws Exception {
  267. Callable<PullResult> setup = () -> {
  268. StoredConfig config = dbTarget.getConfig();
  269. config.setString("pull", null, "rebase", "preserve");
  270. config.save();
  271. return target.pull().call();
  272. };
  273. doTestPullWithRebase(setup, TestPullMode.REBASE_PREASERVE);
  274. }
  275. @Test
  276. /** the branch-local config should win over the global config */
  277. public void testPullWithRebasePreserveConfig2() throws Exception {
  278. Callable<PullResult> setup = () -> {
  279. StoredConfig config = dbTarget.getConfig();
  280. config.setString("pull", null, "rebase", "false");
  281. config.setString("branch", "master", "rebase", "preserve");
  282. config.save();
  283. return target.pull().call();
  284. };
  285. doTestPullWithRebase(setup, TestPullMode.REBASE_PREASERVE);
  286. }
  287. @Test
  288. /** the branch-local config should be respected */
  289. public void testPullWithRebasePreserveConfig3() throws Exception {
  290. Callable<PullResult> setup = () -> {
  291. StoredConfig config = dbTarget.getConfig();
  292. config.setString("branch", "master", "rebase", "preserve");
  293. config.save();
  294. return target.pull().call();
  295. };
  296. doTestPullWithRebase(setup, TestPullMode.REBASE_PREASERVE);
  297. }
  298. @Test
  299. /** global rebase config should be respected */
  300. public void testPullWithRebaseConfig1() throws Exception {
  301. Callable<PullResult> setup = () -> {
  302. StoredConfig config = dbTarget.getConfig();
  303. config.setString("pull", null, "rebase", "true");
  304. config.save();
  305. return target.pull().call();
  306. };
  307. doTestPullWithRebase(setup, TestPullMode.REBASE);
  308. }
  309. @Test
  310. /** the branch-local config should win over the global config */
  311. public void testPullWithRebaseConfig2() throws Exception {
  312. Callable<PullResult> setup = () -> {
  313. StoredConfig config = dbTarget.getConfig();
  314. config.setString("pull", null, "rebase", "preserve");
  315. config.setString("branch", "master", "rebase", "true");
  316. config.save();
  317. return target.pull().call();
  318. };
  319. doTestPullWithRebase(setup, TestPullMode.REBASE);
  320. }
  321. @Test
  322. /** the branch-local config should be respected */
  323. public void testPullWithRebaseConfig3() throws Exception {
  324. Callable<PullResult> setup = () -> {
  325. StoredConfig config = dbTarget.getConfig();
  326. config.setString("branch", "master", "rebase", "true");
  327. config.save();
  328. return target.pull().call();
  329. };
  330. doTestPullWithRebase(setup, TestPullMode.REBASE);
  331. }
  332. @Test
  333. /** without config it should merge */
  334. public void testPullWithoutConfig() throws Exception {
  335. Callable<PullResult> setup = target.pull()::call;
  336. doTestPullWithRebase(setup, TestPullMode.MERGE);
  337. }
  338. @Test
  339. /** the branch local config should win over the global config */
  340. public void testPullWithMergeConfig() throws Exception {
  341. Callable<PullResult> setup = () -> {
  342. StoredConfig config = dbTarget.getConfig();
  343. config.setString("pull", null, "rebase", "true");
  344. config.setString("branch", "master", "rebase", "false");
  345. config.save();
  346. return target.pull().call();
  347. };
  348. doTestPullWithRebase(setup, TestPullMode.MERGE);
  349. }
  350. @Test
  351. /** the branch local config should win over the global config */
  352. public void testPullWithMergeConfig2() throws Exception {
  353. Callable<PullResult> setup = () -> {
  354. StoredConfig config = dbTarget.getConfig();
  355. config.setString("pull", null, "rebase", "false");
  356. config.save();
  357. return target.pull().call();
  358. };
  359. doTestPullWithRebase(setup, TestPullMode.MERGE);
  360. }
  361. private void doTestPullWithRebase(Callable<PullResult> pullSetup,
  362. TestPullMode expectedPullMode) throws Exception {
  363. // simple upstream change
  364. writeToFile(sourceFile, "content");
  365. source.add().addFilepattern(sourceFile.getName()).call();
  366. RevCommit sourceCommit = source.commit().setMessage("source commit")
  367. .call();
  368. // create a merge commit in target
  369. File loxalFile = new File(dbTarget.getWorkTree(), "local.txt");
  370. writeToFile(loxalFile, "initial\n");
  371. target.add().addFilepattern("local.txt").call();
  372. RevCommit t1 = target.commit().setMessage("target commit 1").call();
  373. target.checkout().setCreateBranch(true).setName("side").call();
  374. String newContent = "initial\n" + "and more\n";
  375. writeToFile(loxalFile, newContent);
  376. target.add().addFilepattern("local.txt").call();
  377. RevCommit t2 = target.commit().setMessage("target commit 2").call();
  378. target.checkout().setName("master").call();
  379. MergeResult mergeResult = target.merge()
  380. .setFastForward(MergeCommand.FastForwardMode.NO_FF).include(t2)
  381. .call();
  382. assertEquals(MergeStatus.MERGED, mergeResult.getMergeStatus());
  383. assertFileContentsEqual(loxalFile, newContent);
  384. ObjectId merge = mergeResult.getNewHead();
  385. // pull
  386. PullResult res = pullSetup.call();
  387. assertNotNull(res.getFetchResult());
  388. if (expectedPullMode == TestPullMode.MERGE) {
  389. assertEquals(MergeStatus.MERGED, res.getMergeResult()
  390. .getMergeStatus());
  391. assertNull(res.getRebaseResult());
  392. } else {
  393. assertNull(res.getMergeResult());
  394. assertEquals(RebaseResult.OK_RESULT, res.getRebaseResult());
  395. }
  396. assertFileContentsEqual(sourceFile, "content");
  397. try (RevWalk rw = new RevWalk(dbTarget)) {
  398. rw.sort(RevSort.TOPO);
  399. rw.markStart(rw.parseCommit(dbTarget.resolve("refs/heads/master")));
  400. RevCommit next;
  401. if (expectedPullMode == TestPullMode.MERGE) {
  402. next = rw.next();
  403. assertEquals(2, next.getParentCount());
  404. assertEquals(merge, next.getParent(0));
  405. assertEquals(sourceCommit, next.getParent(1));
  406. // since both parents are known do no further checks here
  407. } else {
  408. if (expectedPullMode == TestPullMode.REBASE_PREASERVE) {
  409. next = rw.next();
  410. assertEquals(2, next.getParentCount());
  411. }
  412. next = rw.next();
  413. assertEquals(t2.getShortMessage(), next.getShortMessage());
  414. next = rw.next();
  415. assertEquals(t1.getShortMessage(), next.getShortMessage());
  416. next = rw.next();
  417. assertEquals(sourceCommit, next);
  418. next = rw.next();
  419. assertEquals("Initial commit for source",
  420. next.getShortMessage());
  421. next = rw.next();
  422. assertNull(next);
  423. }
  424. }
  425. }
  426. @Override
  427. @Before
  428. public void setUp() throws Exception {
  429. super.setUp();
  430. dbTarget = createWorkRepository();
  431. source = new Git(db);
  432. target = new Git(dbTarget);
  433. // put some file in the source repo
  434. sourceFile = new File(db.getWorkTree(), "SomeFile.txt");
  435. writeToFile(sourceFile, "Hello world");
  436. // and commit it
  437. source.add().addFilepattern("SomeFile.txt").call();
  438. source.commit().setMessage("Initial commit for source").call();
  439. // configure the target repo to connect to the source via "origin"
  440. StoredConfig targetConfig = dbTarget.getConfig();
  441. targetConfig.setString("branch", "master", "remote", "origin");
  442. targetConfig
  443. .setString("branch", "master", "merge", "refs/heads/master");
  444. RemoteConfig config = new RemoteConfig(targetConfig, "origin");
  445. config
  446. .addURI(new URIish(source.getRepository().getWorkTree()
  447. .getAbsolutePath()));
  448. config.addFetchRefSpec(new RefSpec(
  449. "+refs/heads/*:refs/remotes/origin/*"));
  450. config.update(targetConfig);
  451. targetConfig.save();
  452. targetFile = new File(dbTarget.getWorkTree(), "SomeFile.txt");
  453. // make sure we have the same content
  454. target.pull().call();
  455. assertFileContentsEqual(targetFile, "Hello world");
  456. }
  457. private static void writeToFile(File actFile, String string)
  458. throws IOException {
  459. try (FileOutputStream fos = new FileOutputStream(actFile)) {
  460. fos.write(string.getBytes(UTF_8));
  461. }
  462. }
  463. private static void assertFileContentsEqual(File actFile, String string)
  464. throws IOException {
  465. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  466. byte[] buffer = new byte[100];
  467. try (FileInputStream fis = new FileInputStream(actFile)) {
  468. int read = fis.read(buffer);
  469. while (read > 0) {
  470. bos.write(buffer, 0, read);
  471. read = fis.read(buffer);
  472. }
  473. String content = new String(bos.toByteArray(), UTF_8);
  474. assertEquals(string, content);
  475. }
  476. }
  477. }