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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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 org.junit.Assert.assertEquals;
  45. import static org.junit.Assert.assertFalse;
  46. import static org.junit.Assert.assertNotNull;
  47. import static org.junit.Assert.assertNull;
  48. import static org.junit.Assert.assertTrue;
  49. import java.io.ByteArrayOutputStream;
  50. import java.io.File;
  51. import java.io.FileInputStream;
  52. import java.io.FileOutputStream;
  53. import java.io.IOException;
  54. import org.eclipse.jgit.api.CreateBranchCommand.SetupUpstreamMode;
  55. import org.eclipse.jgit.api.MergeResult.MergeStatus;
  56. import org.eclipse.jgit.api.RebaseResult.Status;
  57. import org.eclipse.jgit.junit.RepositoryTestCase;
  58. import org.eclipse.jgit.lib.ConfigConstants;
  59. import org.eclipse.jgit.lib.Constants;
  60. import org.eclipse.jgit.lib.ObjectId;
  61. import org.eclipse.jgit.lib.Ref;
  62. import org.eclipse.jgit.lib.Repository;
  63. import org.eclipse.jgit.lib.RepositoryState;
  64. import org.eclipse.jgit.lib.StoredConfig;
  65. import org.eclipse.jgit.merge.MergeStrategy;
  66. import org.eclipse.jgit.revwalk.RevCommit;
  67. import org.eclipse.jgit.revwalk.RevWalk;
  68. import org.eclipse.jgit.transport.RefSpec;
  69. import org.eclipse.jgit.transport.RemoteConfig;
  70. import org.eclipse.jgit.transport.URIish;
  71. import org.junit.Before;
  72. import org.junit.Test;
  73. public class PullCommandWithRebaseTest extends RepositoryTestCase {
  74. /** Second Test repository */
  75. protected Repository dbTarget;
  76. private Git source;
  77. private Git target;
  78. private File sourceFile;
  79. private File targetFile;
  80. @Test
  81. public void testPullFastForward() throws Exception {
  82. PullResult res = target.pull().call();
  83. // nothing to update since we don't have different data yet
  84. assertTrue(res.getFetchResult().getTrackingRefUpdates().isEmpty());
  85. assertEquals(Status.UP_TO_DATE, res.getRebaseResult().getStatus());
  86. assertFileContentsEqual(targetFile, "Hello world");
  87. // change the source file
  88. writeToFile(sourceFile, "Another change");
  89. source.add().addFilepattern("SomeFile.txt").call();
  90. source.commit().setMessage("Some change in remote").call();
  91. res = target.pull().call();
  92. assertFalse(res.getFetchResult().getTrackingRefUpdates().isEmpty());
  93. assertEquals(Status.FAST_FORWARD, res.getRebaseResult().getStatus());
  94. assertFileContentsEqual(targetFile, "Another change");
  95. assertEquals(RepositoryState.SAFE, target.getRepository()
  96. .getRepositoryState());
  97. res = target.pull().call();
  98. assertEquals(Status.UP_TO_DATE, res.getRebaseResult().getStatus());
  99. }
  100. @Test
  101. public void testPullFastForwardWithBranchInSource() 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. assertEquals(Status.UP_TO_DATE, res.getRebaseResult().getStatus());
  106. assertFileContentsEqual(targetFile, "Hello world");
  107. // change the source file
  108. writeToFile(sourceFile, "Another change\n\n\n\nFoo");
  109. source.add().addFilepattern("SomeFile.txt").call();
  110. RevCommit initialCommit = source.commit()
  111. .setMessage("Some change in remote").call();
  112. // modify the source file in a branch
  113. createBranch(initialCommit, "refs/heads/side");
  114. checkoutBranch("refs/heads/side");
  115. writeToFile(sourceFile, "Another change\n\n\n\nBoo");
  116. source.add().addFilepattern("SomeFile.txt").call();
  117. RevCommit sideCommit = source.commit()
  118. .setMessage("Some change in remote").call();
  119. // modify the source file on master
  120. checkoutBranch("refs/heads/master");
  121. writeToFile(sourceFile, "More change\n\n\n\nFoo");
  122. source.add().addFilepattern("SomeFile.txt").call();
  123. source.commit().setMessage("Some change in remote").call();
  124. // merge side into master
  125. MergeResult result = source.merge().include(sideCommit.getId())
  126. .setStrategy(MergeStrategy.RESOLVE).call();
  127. assertEquals(MergeStatus.MERGED, result.getMergeStatus());
  128. }
  129. @Test
  130. public void testPullFastForwardDetachedHead() throws Exception {
  131. Repository repository = source.getRepository();
  132. writeToFile(sourceFile, "2nd commit");
  133. source.add().addFilepattern("SomeFile.txt").call();
  134. source.commit().setMessage("2nd commit").call();
  135. try (RevWalk revWalk = new RevWalk(repository)) {
  136. // git checkout HEAD^
  137. String initialBranch = repository.getBranch();
  138. Ref initialRef = repository.findRef(Constants.HEAD);
  139. RevCommit initialCommit = revWalk
  140. .parseCommit(initialRef.getObjectId());
  141. assertEquals("this test need linear history", 1,
  142. initialCommit.getParentCount());
  143. source.checkout().setName(initialCommit.getParent(0).getName())
  144. .call();
  145. assertFalse("expected detached HEAD",
  146. repository.getFullBranch().startsWith(Constants.R_HEADS));
  147. // change and commit another file
  148. File otherFile = new File(sourceFile.getParentFile(),
  149. System.currentTimeMillis() + ".tst");
  150. writeToFile(otherFile, "other 2nd commit");
  151. source.add().addFilepattern(otherFile.getName()).call();
  152. RevCommit newCommit = source.commit().setMessage("other 2nd commit")
  153. .call();
  154. // git pull --rebase initialBranch
  155. source.pull().setRebase(true).setRemote(".")
  156. .setRemoteBranchName(initialBranch)
  157. .call();
  158. assertEquals(RepositoryState.SAFE,
  159. source.getRepository().getRepositoryState());
  160. Ref head = source.getRepository().findRef(Constants.HEAD);
  161. RevCommit headCommit = revWalk.parseCommit(head.getObjectId());
  162. // HEAD^ == initialCommit, no merge commit
  163. assertEquals(1, headCommit.getParentCount());
  164. assertEquals(initialCommit, headCommit.getParent(0));
  165. // both contributions for both commits are available
  166. assertFileContentsEqual(sourceFile, "2nd commit");
  167. assertFileContentsEqual(otherFile, "other 2nd commit");
  168. // HEAD has same message as rebased commit
  169. assertEquals(newCommit.getShortMessage(),
  170. headCommit.getShortMessage());
  171. }
  172. }
  173. @Test
  174. public void testPullConflict() throws Exception {
  175. PullResult res = target.pull().call();
  176. // nothing to update since we don't have different data yet
  177. assertTrue(res.getFetchResult().getTrackingRefUpdates().isEmpty());
  178. assertEquals(Status.UP_TO_DATE, res.getRebaseResult().getStatus());
  179. assertFileContentsEqual(targetFile, "Hello world");
  180. // change the source file
  181. writeToFile(sourceFile, "Source change");
  182. source.add().addFilepattern("SomeFile.txt").call();
  183. source.commit().setMessage("Source change in remote").call();
  184. // change the target file
  185. writeToFile(targetFile, "Target change");
  186. target.add().addFilepattern("SomeFile.txt").call();
  187. target.commit().setMessage("Target change in local").call();
  188. res = target.pull().call();
  189. String remoteUri = target
  190. .getRepository()
  191. .getConfig()
  192. .getString(ConfigConstants.CONFIG_REMOTE_SECTION, "origin",
  193. ConfigConstants.CONFIG_KEY_URL);
  194. assertFalse(res.getFetchResult().getTrackingRefUpdates().isEmpty());
  195. assertEquals(Status.STOPPED, res.getRebaseResult().getStatus());
  196. String result = "<<<<<<< Upstream, based on branch 'master' of "
  197. + remoteUri
  198. + "\nSource change\n=======\nTarget change\n>>>>>>> 42453fd Target change in local\n";
  199. assertFileContentsEqual(targetFile, result);
  200. assertEquals(RepositoryState.REBASING_MERGE, target
  201. .getRepository().getRepositoryState());
  202. }
  203. @Test
  204. public void testPullLocalConflict() throws Exception {
  205. target.branchCreate().setName("basedOnMaster").setStartPoint(
  206. "refs/heads/master").setUpstreamMode(SetupUpstreamMode.NOTRACK)
  207. .call();
  208. StoredConfig config = target.getRepository().getConfig();
  209. config.setString("branch", "basedOnMaster", "remote", ".");
  210. config.setString("branch", "basedOnMaster", "merge",
  211. "refs/heads/master");
  212. config.setBoolean("branch", "basedOnMaster", "rebase", true);
  213. config.save();
  214. target.getRepository().updateRef(Constants.HEAD).link(
  215. "refs/heads/basedOnMaster");
  216. PullResult res = target.pull().call();
  217. // nothing to update since we don't have different data yet
  218. assertNull(res.getFetchResult());
  219. assertEquals(Status.UP_TO_DATE, res.getRebaseResult().getStatus());
  220. assertFileContentsEqual(targetFile, "Hello world");
  221. // change the file in master
  222. target.getRepository().updateRef(Constants.HEAD).link(
  223. "refs/heads/master");
  224. writeToFile(targetFile, "Master change");
  225. target.add().addFilepattern("SomeFile.txt").call();
  226. target.commit().setMessage("Source change in master").call();
  227. // change the file in slave
  228. target.getRepository().updateRef(Constants.HEAD).link(
  229. "refs/heads/basedOnMaster");
  230. writeToFile(targetFile, "Slave change");
  231. target.add().addFilepattern("SomeFile.txt").call();
  232. target.commit().setMessage("Source change in based on master").call();
  233. res = target.pull().call();
  234. assertNull(res.getFetchResult());
  235. assertEquals(Status.STOPPED, res.getRebaseResult().getStatus());
  236. String result = "<<<<<<< Upstream, based on branch 'master' of local repository\n"
  237. + "Master change\n=======\nSlave change\n>>>>>>> 4049c9e Source change in based on master\n";
  238. assertFileContentsEqual(targetFile, result);
  239. assertEquals(RepositoryState.REBASING_MERGE, target
  240. .getRepository().getRepositoryState());
  241. }
  242. @Test
  243. public void testPullFastForwardWithLocalCommitAndRebaseFlagSet() throws Exception {
  244. final String SOURCE_COMMIT_MESSAGE = "Source commit message for rebase flag test";
  245. final String TARGET_COMMIT_MESSAGE = "Target commit message for rebase flag test";
  246. assertFalse(SOURCE_COMMIT_MESSAGE.equals(TARGET_COMMIT_MESSAGE));
  247. final String SOURCE_FILE_CONTENTS = "Source change";
  248. final String NEW_FILE_CONTENTS = "New file from target";
  249. // make sure the config for target says we should pull with merge
  250. // we will override this later with the setRebase method
  251. StoredConfig targetConfig = dbTarget.getConfig();
  252. targetConfig.setBoolean("branch", "master", "rebase", false);
  253. targetConfig.save();
  254. // create commit in source
  255. writeToFile(sourceFile, SOURCE_FILE_CONTENTS);
  256. source.add().addFilepattern(sourceFile.getName()).call();
  257. source.commit().setMessage(SOURCE_COMMIT_MESSAGE).call();
  258. // create commit in target, not conflicting with the new commit in source
  259. File newFile = new File(dbTarget.getWorkTree().getPath() + "/newFile.txt");
  260. writeToFile(newFile, NEW_FILE_CONTENTS);
  261. target.add().addFilepattern(newFile.getName()).call();
  262. target.commit().setMessage(TARGET_COMMIT_MESSAGE).call();
  263. // verify that rebase is set to false in the config
  264. assertFalse(targetConfig.getBoolean("branch", "master", "rebase", true));
  265. // pull with rebase - local commit in target should be on top
  266. PullResult pullResult = target.pull().setRebase(true).call();
  267. // make sure pull is considered successful
  268. assertTrue(pullResult.isSuccessful());
  269. // verify rebase result is ok
  270. RebaseResult rebaseResult = pullResult.getRebaseResult();
  271. assertNotNull(rebaseResult);
  272. assertNull(rebaseResult.getFailingPaths());
  273. assertEquals(Status.OK, rebaseResult.getStatus());
  274. // Get the HEAD and HEAD~1 commits
  275. Repository targetRepo = target.getRepository();
  276. try (RevWalk revWalk = new RevWalk(targetRepo)) {
  277. ObjectId headId = targetRepo.resolve(Constants.HEAD);
  278. RevCommit root = revWalk.parseCommit(headId);
  279. revWalk.markStart(root);
  280. // HEAD
  281. RevCommit head = revWalk.next();
  282. // HEAD~1
  283. RevCommit beforeHead = revWalk.next();
  284. // verify the commit message on the HEAD commit
  285. assertEquals(TARGET_COMMIT_MESSAGE, head.getFullMessage());
  286. // verify the commit just before HEAD
  287. assertEquals(SOURCE_COMMIT_MESSAGE, beforeHead.getFullMessage());
  288. // verify file states
  289. assertFileContentsEqual(sourceFile, SOURCE_FILE_CONTENTS);
  290. assertFileContentsEqual(newFile, NEW_FILE_CONTENTS);
  291. // verify repository state
  292. assertEquals(RepositoryState.SAFE, target
  293. .getRepository().getRepositoryState());
  294. }
  295. }
  296. @Override
  297. @Before
  298. public void setUp() throws Exception {
  299. super.setUp();
  300. dbTarget = createWorkRepository();
  301. source = new Git(db);
  302. target = new Git(dbTarget);
  303. // put some file in the source repo
  304. sourceFile = new File(db.getWorkTree(), "SomeFile.txt");
  305. writeToFile(sourceFile, "Hello world");
  306. // and commit it
  307. source.add().addFilepattern("SomeFile.txt").call();
  308. source.commit().setMessage("Initial commit for source").call();
  309. // configure the target repo to connect to the source via "origin"
  310. StoredConfig targetConfig = dbTarget.getConfig();
  311. targetConfig.setString("branch", "master", "remote", "origin");
  312. targetConfig
  313. .setString("branch", "master", "merge", "refs/heads/master");
  314. RemoteConfig config = new RemoteConfig(targetConfig, "origin");
  315. config
  316. .addURI(new URIish(source.getRepository().getWorkTree()
  317. .getAbsolutePath()));
  318. config.addFetchRefSpec(new RefSpec(
  319. "+refs/heads/*:refs/remotes/origin/*"));
  320. config.update(targetConfig);
  321. targetConfig.save();
  322. targetFile = new File(dbTarget.getWorkTree(), "SomeFile.txt");
  323. // make sure we have the same content
  324. target.pull().call();
  325. target.checkout().setStartPoint("refs/remotes/origin/master").setName(
  326. "master").call();
  327. targetConfig
  328. .setString("branch", "master", "merge", "refs/heads/master");
  329. targetConfig.setBoolean("branch", "master", "rebase", true);
  330. targetConfig.save();
  331. assertFileContentsEqual(targetFile, "Hello world");
  332. }
  333. private static void writeToFile(File actFile, String string)
  334. throws IOException {
  335. FileOutputStream fos = null;
  336. try {
  337. fos = new FileOutputStream(actFile);
  338. fos.write(string.getBytes("UTF-8"));
  339. fos.close();
  340. } finally {
  341. if (fos != null)
  342. fos.close();
  343. }
  344. }
  345. private static void assertFileContentsEqual(File actFile, String string)
  346. throws IOException {
  347. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  348. FileInputStream fis = null;
  349. byte[] buffer = new byte[100];
  350. try {
  351. fis = new FileInputStream(actFile);
  352. int read = fis.read(buffer);
  353. while (read > 0) {
  354. bos.write(buffer, 0, read);
  355. read = fis.read(buffer);
  356. }
  357. String content = new String(bos.toByteArray(), "UTF-8");
  358. assertEquals(string, content);
  359. } finally {
  360. if (fis != null)
  361. fis.close();
  362. }
  363. }
  364. }