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.

PullCommandWithRebaseTest.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. /*
  2. * Copyright (C) 2011, Mathias Kinzler <mathias.kinzler@sap.com>
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.api;
  44. import static java.nio.charset.StandardCharsets.UTF_8;
  45. import static org.junit.Assert.assertEquals;
  46. import static org.junit.Assert.assertFalse;
  47. import static org.junit.Assert.assertNotNull;
  48. import static org.junit.Assert.assertNull;
  49. import static org.junit.Assert.assertTrue;
  50. import java.io.ByteArrayOutputStream;
  51. import java.io.File;
  52. import java.io.FileInputStream;
  53. import java.io.FileOutputStream;
  54. import java.io.IOException;
  55. import org.eclipse.jgit.api.CreateBranchCommand.SetupUpstreamMode;
  56. import org.eclipse.jgit.api.MergeResult.MergeStatus;
  57. import org.eclipse.jgit.api.RebaseResult.Status;
  58. import org.eclipse.jgit.junit.RepositoryTestCase;
  59. import org.eclipse.jgit.lib.ConfigConstants;
  60. import org.eclipse.jgit.lib.Constants;
  61. import org.eclipse.jgit.lib.ObjectId;
  62. import org.eclipse.jgit.lib.Ref;
  63. import org.eclipse.jgit.lib.Repository;
  64. import org.eclipse.jgit.lib.RepositoryState;
  65. import org.eclipse.jgit.lib.StoredConfig;
  66. import org.eclipse.jgit.merge.MergeStrategy;
  67. import org.eclipse.jgit.revwalk.RevCommit;
  68. import org.eclipse.jgit.revwalk.RevWalk;
  69. import org.eclipse.jgit.transport.RefSpec;
  70. import org.eclipse.jgit.transport.RemoteConfig;
  71. import org.eclipse.jgit.transport.URIish;
  72. import org.junit.Before;
  73. import org.junit.Test;
  74. public class PullCommandWithRebaseTest extends RepositoryTestCase {
  75. /** Second Test repository */
  76. protected Repository dbTarget;
  77. private Git source;
  78. private Git target;
  79. private File sourceFile;
  80. private File targetFile;
  81. @Test
  82. public void testPullFastForward() throws Exception {
  83. PullResult res = target.pull().call();
  84. // nothing to update since we don't have different data yet
  85. assertTrue(res.getFetchResult().getTrackingRefUpdates().isEmpty());
  86. assertEquals(Status.UP_TO_DATE, res.getRebaseResult().getStatus());
  87. assertFileContentsEqual(targetFile, "Hello world");
  88. // change the source file
  89. writeToFile(sourceFile, "Another change");
  90. source.add().addFilepattern("SomeFile.txt").call();
  91. source.commit().setMessage("Some change in remote").call();
  92. res = target.pull().call();
  93. assertFalse(res.getFetchResult().getTrackingRefUpdates().isEmpty());
  94. assertEquals(Status.FAST_FORWARD, res.getRebaseResult().getStatus());
  95. assertFileContentsEqual(targetFile, "Another change");
  96. assertEquals(RepositoryState.SAFE, target.getRepository()
  97. .getRepositoryState());
  98. res = target.pull().call();
  99. assertEquals(Status.UP_TO_DATE, res.getRebaseResult().getStatus());
  100. }
  101. @Test
  102. public void testPullFastForwardWithBranchInSource() throws Exception {
  103. PullResult res = target.pull().call();
  104. // nothing to update since we don't have different data yet
  105. assertTrue(res.getFetchResult().getTrackingRefUpdates().isEmpty());
  106. assertEquals(Status.UP_TO_DATE, res.getRebaseResult().getStatus());
  107. assertFileContentsEqual(targetFile, "Hello world");
  108. // change the source file
  109. writeToFile(sourceFile, "Another change\n\n\n\nFoo");
  110. source.add().addFilepattern("SomeFile.txt").call();
  111. RevCommit initialCommit = source.commit()
  112. .setMessage("Some change in remote").call();
  113. // modify the source file in a branch
  114. createBranch(initialCommit, "refs/heads/side");
  115. checkoutBranch("refs/heads/side");
  116. writeToFile(sourceFile, "Another change\n\n\n\nBoo");
  117. source.add().addFilepattern("SomeFile.txt").call();
  118. RevCommit sideCommit = source.commit()
  119. .setMessage("Some change in remote").call();
  120. // modify the source file on master
  121. checkoutBranch("refs/heads/master");
  122. writeToFile(sourceFile, "More change\n\n\n\nFoo");
  123. source.add().addFilepattern("SomeFile.txt").call();
  124. source.commit().setMessage("Some change in remote").call();
  125. // merge side into master
  126. MergeResult result = source.merge().include(sideCommit.getId())
  127. .setStrategy(MergeStrategy.RESOLVE).call();
  128. assertEquals(MergeStatus.MERGED, result.getMergeStatus());
  129. }
  130. @Test
  131. public void testPullFastForwardDetachedHead() throws Exception {
  132. Repository repository = source.getRepository();
  133. writeToFile(sourceFile, "2nd commit");
  134. source.add().addFilepattern("SomeFile.txt").call();
  135. source.commit().setMessage("2nd commit").call();
  136. try (RevWalk revWalk = new RevWalk(repository)) {
  137. // git checkout HEAD^
  138. String initialBranch = repository.getBranch();
  139. Ref initialRef = repository.findRef(Constants.HEAD);
  140. RevCommit initialCommit = revWalk
  141. .parseCommit(initialRef.getObjectId());
  142. assertEquals("this test need linear history", 1,
  143. initialCommit.getParentCount());
  144. source.checkout().setName(initialCommit.getParent(0).getName())
  145. .call();
  146. assertFalse("expected detached HEAD",
  147. repository.getFullBranch().startsWith(Constants.R_HEADS));
  148. // change and commit another file
  149. File otherFile = new File(sourceFile.getParentFile(),
  150. System.currentTimeMillis() + ".tst");
  151. writeToFile(otherFile, "other 2nd commit");
  152. source.add().addFilepattern(otherFile.getName()).call();
  153. RevCommit newCommit = source.commit().setMessage("other 2nd commit")
  154. .call();
  155. // git pull --rebase initialBranch
  156. source.pull().setRebase(true).setRemote(".")
  157. .setRemoteBranchName(initialBranch)
  158. .call();
  159. assertEquals(RepositoryState.SAFE,
  160. source.getRepository().getRepositoryState());
  161. Ref head = source.getRepository().findRef(Constants.HEAD);
  162. RevCommit headCommit = revWalk.parseCommit(head.getObjectId());
  163. // HEAD^ == initialCommit, no merge commit
  164. assertEquals(1, headCommit.getParentCount());
  165. assertEquals(initialCommit, headCommit.getParent(0));
  166. // both contributions for both commits are available
  167. assertFileContentsEqual(sourceFile, "2nd commit");
  168. assertFileContentsEqual(otherFile, "other 2nd commit");
  169. // HEAD has same message as rebased commit
  170. assertEquals(newCommit.getShortMessage(),
  171. headCommit.getShortMessage());
  172. }
  173. }
  174. @Test
  175. public void testPullConflict() throws Exception {
  176. PullResult res = target.pull().call();
  177. // nothing to update since we don't have different data yet
  178. assertTrue(res.getFetchResult().getTrackingRefUpdates().isEmpty());
  179. assertEquals(Status.UP_TO_DATE, res.getRebaseResult().getStatus());
  180. assertFileContentsEqual(targetFile, "Hello world");
  181. // change the source file
  182. writeToFile(sourceFile, "Source change");
  183. source.add().addFilepattern("SomeFile.txt").call();
  184. source.commit().setMessage("Source change in remote").call();
  185. // change the target file
  186. writeToFile(targetFile, "Target change");
  187. target.add().addFilepattern("SomeFile.txt").call();
  188. target.commit().setMessage("Target change in local").call();
  189. res = target.pull().call();
  190. String remoteUri = target
  191. .getRepository()
  192. .getConfig()
  193. .getString(ConfigConstants.CONFIG_REMOTE_SECTION, "origin",
  194. ConfigConstants.CONFIG_KEY_URL);
  195. assertFalse(res.getFetchResult().getTrackingRefUpdates().isEmpty());
  196. assertEquals(Status.STOPPED, res.getRebaseResult().getStatus());
  197. String result = "<<<<<<< Upstream, based on branch 'master' of "
  198. + remoteUri
  199. + "\nSource change\n=======\nTarget change\n>>>>>>> 42453fd Target change in local\n";
  200. assertFileContentsEqual(targetFile, result);
  201. assertEquals(RepositoryState.REBASING_MERGE, target
  202. .getRepository().getRepositoryState());
  203. }
  204. @Test
  205. public void testPullLocalConflict() throws Exception {
  206. target.branchCreate().setName("basedOnMaster").setStartPoint(
  207. "refs/heads/master").setUpstreamMode(SetupUpstreamMode.NOTRACK)
  208. .call();
  209. StoredConfig config = target.getRepository().getConfig();
  210. config.setString("branch", "basedOnMaster", "remote", ".");
  211. config.setString("branch", "basedOnMaster", "merge",
  212. "refs/heads/master");
  213. config.setBoolean("branch", "basedOnMaster", "rebase", true);
  214. config.save();
  215. target.getRepository().updateRef(Constants.HEAD).link(
  216. "refs/heads/basedOnMaster");
  217. PullResult res = target.pull().call();
  218. // nothing to update since we don't have different data yet
  219. assertNull(res.getFetchResult());
  220. assertEquals(Status.UP_TO_DATE, res.getRebaseResult().getStatus());
  221. assertFileContentsEqual(targetFile, "Hello world");
  222. // change the file in master
  223. target.getRepository().updateRef(Constants.HEAD).link(
  224. "refs/heads/master");
  225. writeToFile(targetFile, "Master change");
  226. target.add().addFilepattern("SomeFile.txt").call();
  227. target.commit().setMessage("Source change in master").call();
  228. // change the file in slave
  229. target.getRepository().updateRef(Constants.HEAD).link(
  230. "refs/heads/basedOnMaster");
  231. writeToFile(targetFile, "Slave change");
  232. target.add().addFilepattern("SomeFile.txt").call();
  233. target.commit().setMessage("Source change in based on master").call();
  234. res = target.pull().call();
  235. assertNull(res.getFetchResult());
  236. assertEquals(Status.STOPPED, res.getRebaseResult().getStatus());
  237. String result = "<<<<<<< Upstream, based on branch 'master' of local repository\n"
  238. + "Master change\n=======\nSlave change\n>>>>>>> 4049c9e Source change in based on master\n";
  239. assertFileContentsEqual(targetFile, result);
  240. assertEquals(RepositoryState.REBASING_MERGE, target
  241. .getRepository().getRepositoryState());
  242. }
  243. @Test
  244. public void testPullFastForwardWithLocalCommitAndRebaseFlagSet() throws Exception {
  245. final String SOURCE_COMMIT_MESSAGE = "Source commit message for rebase flag test";
  246. final String TARGET_COMMIT_MESSAGE = "Target commit message for rebase flag test";
  247. assertFalse(SOURCE_COMMIT_MESSAGE.equals(TARGET_COMMIT_MESSAGE));
  248. final String SOURCE_FILE_CONTENTS = "Source change";
  249. final String NEW_FILE_CONTENTS = "New file from target";
  250. // make sure the config for target says we should pull with merge
  251. // we will override this later with the setRebase method
  252. StoredConfig targetConfig = dbTarget.getConfig();
  253. targetConfig.setBoolean("branch", "master", "rebase", false);
  254. targetConfig.save();
  255. // create commit in source
  256. writeToFile(sourceFile, SOURCE_FILE_CONTENTS);
  257. source.add().addFilepattern(sourceFile.getName()).call();
  258. source.commit().setMessage(SOURCE_COMMIT_MESSAGE).call();
  259. // create commit in target, not conflicting with the new commit in source
  260. File newFile = new File(dbTarget.getWorkTree().getPath() + "/newFile.txt");
  261. writeToFile(newFile, NEW_FILE_CONTENTS);
  262. target.add().addFilepattern(newFile.getName()).call();
  263. target.commit().setMessage(TARGET_COMMIT_MESSAGE).call();
  264. // verify that rebase is set to false in the config
  265. assertFalse(targetConfig.getBoolean("branch", "master", "rebase", true));
  266. // pull with rebase - local commit in target should be on top
  267. PullResult pullResult = target.pull().setRebase(true).call();
  268. // make sure pull is considered successful
  269. assertTrue(pullResult.isSuccessful());
  270. // verify rebase result is ok
  271. RebaseResult rebaseResult = pullResult.getRebaseResult();
  272. assertNotNull(rebaseResult);
  273. assertNull(rebaseResult.getFailingPaths());
  274. assertEquals(Status.OK, rebaseResult.getStatus());
  275. // Get the HEAD and HEAD~1 commits
  276. Repository targetRepo = target.getRepository();
  277. try (RevWalk revWalk = new RevWalk(targetRepo)) {
  278. ObjectId headId = targetRepo.resolve(Constants.HEAD);
  279. RevCommit root = revWalk.parseCommit(headId);
  280. revWalk.markStart(root);
  281. // HEAD
  282. RevCommit head = revWalk.next();
  283. // HEAD~1
  284. RevCommit beforeHead = revWalk.next();
  285. // verify the commit message on the HEAD commit
  286. assertEquals(TARGET_COMMIT_MESSAGE, head.getFullMessage());
  287. // verify the commit just before HEAD
  288. assertEquals(SOURCE_COMMIT_MESSAGE, beforeHead.getFullMessage());
  289. // verify file states
  290. assertFileContentsEqual(sourceFile, SOURCE_FILE_CONTENTS);
  291. assertFileContentsEqual(newFile, NEW_FILE_CONTENTS);
  292. // verify repository state
  293. assertEquals(RepositoryState.SAFE, target
  294. .getRepository().getRepositoryState());
  295. }
  296. }
  297. @Override
  298. @Before
  299. public void setUp() throws Exception {
  300. super.setUp();
  301. dbTarget = createWorkRepository();
  302. source = new Git(db);
  303. target = new Git(dbTarget);
  304. // put some file in the source repo
  305. sourceFile = new File(db.getWorkTree(), "SomeFile.txt");
  306. writeToFile(sourceFile, "Hello world");
  307. // and commit it
  308. source.add().addFilepattern("SomeFile.txt").call();
  309. source.commit().setMessage("Initial commit for source").call();
  310. // configure the target repo to connect to the source via "origin"
  311. StoredConfig targetConfig = dbTarget.getConfig();
  312. targetConfig.setString("branch", "master", "remote", "origin");
  313. targetConfig
  314. .setString("branch", "master", "merge", "refs/heads/master");
  315. RemoteConfig config = new RemoteConfig(targetConfig, "origin");
  316. config
  317. .addURI(new URIish(source.getRepository().getWorkTree()
  318. .getAbsolutePath()));
  319. config.addFetchRefSpec(new RefSpec(
  320. "+refs/heads/*:refs/remotes/origin/*"));
  321. config.update(targetConfig);
  322. targetConfig.save();
  323. targetFile = new File(dbTarget.getWorkTree(), "SomeFile.txt");
  324. // make sure we have the same content
  325. target.pull().call();
  326. target.checkout().setStartPoint("refs/remotes/origin/master").setName(
  327. "master").call();
  328. targetConfig
  329. .setString("branch", "master", "merge", "refs/heads/master");
  330. targetConfig.setBoolean("branch", "master", "rebase", true);
  331. targetConfig.save();
  332. assertFileContentsEqual(targetFile, "Hello world");
  333. }
  334. private static void writeToFile(File actFile, String string)
  335. throws IOException {
  336. try (FileOutputStream fos = new FileOutputStream(actFile)) {
  337. fos.write(string.getBytes(UTF_8));
  338. }
  339. }
  340. private static void assertFileContentsEqual(File actFile, String string)
  341. throws IOException {
  342. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  343. byte[] buffer = new byte[100];
  344. try (FileInputStream fis = new FileInputStream(actFile)) {
  345. int read = fis.read(buffer);
  346. while (read > 0) {
  347. bos.write(buffer, 0, read);
  348. read = fis.read(buffer);
  349. }
  350. String content = new String(bos.toByteArray(), UTF_8);
  351. assertEquals(string, content);
  352. }
  353. }
  354. }