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.

BranchCommandTest.java 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. /*
  2. * Copyright (C) 2010, 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.assertNull;
  47. import static org.junit.Assert.fail;
  48. import java.util.List;
  49. import org.eclipse.jgit.api.CreateBranchCommand.SetupUpstreamMode;
  50. import org.eclipse.jgit.api.ListBranchCommand.ListMode;
  51. import org.eclipse.jgit.api.errors.CannotDeleteCurrentBranchException;
  52. import org.eclipse.jgit.api.errors.DetachedHeadException;
  53. import org.eclipse.jgit.api.errors.GitAPIException;
  54. import org.eclipse.jgit.api.errors.InvalidRefNameException;
  55. import org.eclipse.jgit.api.errors.JGitInternalException;
  56. import org.eclipse.jgit.api.errors.NotMergedException;
  57. import org.eclipse.jgit.api.errors.RefAlreadyExistsException;
  58. import org.eclipse.jgit.api.errors.RefNotFoundException;
  59. import org.eclipse.jgit.junit.RepositoryTestCase;
  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.RefUpdate;
  64. import org.eclipse.jgit.lib.Repository;
  65. import org.eclipse.jgit.lib.StoredConfig;
  66. import org.eclipse.jgit.revwalk.RevCommit;
  67. import org.eclipse.jgit.transport.FetchResult;
  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 BranchCommandTest extends RepositoryTestCase {
  74. private Git git;
  75. RevCommit initialCommit;
  76. RevCommit secondCommit;
  77. @Override
  78. @Before
  79. public void setUp() throws Exception {
  80. super.setUp();
  81. git = new Git(db);
  82. // checkout master
  83. git.commit().setMessage("initial commit").call();
  84. // commit something
  85. writeTrashFile("Test.txt", "Hello world");
  86. git.add().addFilepattern("Test.txt").call();
  87. initialCommit = git.commit().setMessage("Initial commit").call();
  88. writeTrashFile("Test.txt", "Some change");
  89. git.add().addFilepattern("Test.txt").call();
  90. secondCommit = git.commit().setMessage("Second commit").call();
  91. // create a master branch
  92. RefUpdate rup = db.updateRef("refs/heads/master");
  93. rup.setNewObjectId(initialCommit.getId());
  94. rup.setForceUpdate(true);
  95. rup.update();
  96. }
  97. private Git setUpRepoWithRemote() throws Exception {
  98. Repository remoteRepository = createWorkRepository();
  99. try (Git remoteGit = new Git(remoteRepository)) {
  100. // commit something
  101. writeTrashFile("Test.txt", "Hello world");
  102. remoteGit.add().addFilepattern("Test.txt").call();
  103. initialCommit = remoteGit.commit().setMessage("Initial commit").call();
  104. writeTrashFile("Test.txt", "Some change");
  105. remoteGit.add().addFilepattern("Test.txt").call();
  106. secondCommit = remoteGit.commit().setMessage("Second commit").call();
  107. // create a master branch
  108. RefUpdate rup = remoteRepository.updateRef("refs/heads/master");
  109. rup.setNewObjectId(initialCommit.getId());
  110. rup.forceUpdate();
  111. Repository localRepository = createWorkRepository();
  112. Git localGit = new Git(localRepository);
  113. StoredConfig config = localRepository.getConfig();
  114. RemoteConfig rc = new RemoteConfig(config, "origin");
  115. rc.addURI(new URIish(remoteRepository.getDirectory().getAbsolutePath()));
  116. rc.addFetchRefSpec(new RefSpec("+refs/heads/*:refs/remotes/origin/*"));
  117. rc.update(config);
  118. config.save();
  119. FetchResult res = localGit.fetch().setRemote("origin").call();
  120. assertFalse(res.getTrackingRefUpdates().isEmpty());
  121. rup = localRepository.updateRef("refs/heads/master");
  122. rup.setNewObjectId(initialCommit.getId());
  123. rup.forceUpdate();
  124. rup = localRepository.updateRef(Constants.HEAD);
  125. rup.link("refs/heads/master");
  126. rup.setNewObjectId(initialCommit.getId());
  127. rup.update();
  128. return localGit;
  129. }
  130. }
  131. @Test
  132. public void testCreateAndList() throws Exception {
  133. int localBefore;
  134. int remoteBefore;
  135. int allBefore;
  136. // invalid name not allowed
  137. try {
  138. git.branchCreate().setName("In va lid").call();
  139. fail("Create branch with invalid ref name should fail");
  140. } catch (InvalidRefNameException e) {
  141. // expected
  142. }
  143. // existing name not allowed w/o force
  144. try {
  145. git.branchCreate().setName("master").call();
  146. fail("Create branch with existing ref name should fail");
  147. } catch (RefAlreadyExistsException e) {
  148. // expected
  149. }
  150. localBefore = git.branchList().call().size();
  151. remoteBefore = git.branchList().setListMode(ListMode.REMOTE).call()
  152. .size();
  153. allBefore = git.branchList().setListMode(ListMode.ALL).call().size();
  154. assertEquals(localBefore + remoteBefore, allBefore);
  155. Ref newBranch = createBranch(git, "NewForTestList", false, "master",
  156. null);
  157. assertEquals("refs/heads/NewForTestList", newBranch.getName());
  158. assertEquals(1, git.branchList().call().size() - localBefore);
  159. assertEquals(0, git.branchList().setListMode(ListMode.REMOTE).call()
  160. .size()
  161. - remoteBefore);
  162. assertEquals(1, git.branchList().setListMode(ListMode.ALL).call()
  163. .size()
  164. - allBefore);
  165. // we can only create local branches
  166. newBranch = createBranch(git,
  167. "refs/remotes/origin/NewRemoteForTestList", false, "master",
  168. null);
  169. assertEquals("refs/heads/refs/remotes/origin/NewRemoteForTestList",
  170. newBranch.getName());
  171. assertEquals(2, git.branchList().call().size() - localBefore);
  172. assertEquals(0, git.branchList().setListMode(ListMode.REMOTE).call()
  173. .size()
  174. - remoteBefore);
  175. assertEquals(2, git.branchList().setListMode(ListMode.ALL).call()
  176. .size()
  177. - allBefore);
  178. }
  179. @Test
  180. public void testListAllBranchesShouldNotDie() throws Exception {
  181. setUpRepoWithRemote().branchList().setListMode(ListMode.ALL).call();
  182. }
  183. @Test
  184. public void testListBranchesWithContains() throws Exception {
  185. git.branchCreate().setName("foo").setStartPoint(secondCommit).call();
  186. List<Ref> refs = git.branchList().call();
  187. assertEquals(2, refs.size());
  188. List<Ref> refsContainingSecond = git.branchList()
  189. .setContains(secondCommit.name()).call();
  190. assertEquals(1, refsContainingSecond.size());
  191. // master is on initial commit, so it should not be returned
  192. assertEquals("refs/heads/foo", refsContainingSecond.get(0).getName());
  193. }
  194. @Test
  195. public void testCreateFromCommit() throws Exception {
  196. Ref branch = git.branchCreate().setName("FromInitial").setStartPoint(
  197. initialCommit).call();
  198. assertEquals(initialCommit.getId(), branch.getObjectId());
  199. branch = git.branchCreate().setName("FromInitial2").setStartPoint(
  200. initialCommit.getId().name()).call();
  201. assertEquals(initialCommit.getId(), branch.getObjectId());
  202. try {
  203. git.branchCreate().setName("FromInitial").setStartPoint(
  204. secondCommit).call();
  205. } catch (RefAlreadyExistsException e) {
  206. // expected
  207. }
  208. branch = git.branchCreate().setName("FromInitial").setStartPoint(
  209. secondCommit).setForce(true).call();
  210. assertEquals(secondCommit.getId(), branch.getObjectId());
  211. }
  212. @Test
  213. public void testCreateForce() throws Exception {
  214. // using commits
  215. Ref newBranch = createBranch(git, "NewForce", false, secondCommit
  216. .getId().name(), null);
  217. assertEquals(newBranch.getTarget().getObjectId(), secondCommit.getId());
  218. try {
  219. newBranch = createBranch(git, "NewForce", false, initialCommit
  220. .getId().name(), null);
  221. fail("Should have failed");
  222. } catch (RefAlreadyExistsException e) {
  223. // expected
  224. }
  225. newBranch = createBranch(git, "NewForce", true, initialCommit.getId()
  226. .name(), null);
  227. assertEquals(newBranch.getTarget().getObjectId(), initialCommit.getId());
  228. git.branchDelete().setBranchNames("NewForce").call();
  229. // using names
  230. git.branchCreate().setName("NewForce").setStartPoint("master").call();
  231. assertEquals(newBranch.getTarget().getObjectId(), initialCommit.getId());
  232. try {
  233. git.branchCreate().setName("NewForce").setStartPoint("master")
  234. .call();
  235. fail("Should have failed");
  236. } catch (RefAlreadyExistsException e) {
  237. // expected
  238. }
  239. git.branchCreate().setName("NewForce").setStartPoint("master")
  240. .setForce(true).call();
  241. assertEquals(newBranch.getTarget().getObjectId(), initialCommit.getId());
  242. }
  243. @Test
  244. public void testCreateFromLightweightTag() throws Exception {
  245. RefUpdate rup = db.updateRef("refs/tags/V10");
  246. rup.setNewObjectId(initialCommit);
  247. rup.setExpectedOldObjectId(ObjectId.zeroId());
  248. rup.update();
  249. Ref branch = git.branchCreate().setName("FromLightweightTag")
  250. .setStartPoint("refs/tags/V10").call();
  251. assertEquals(initialCommit.getId(), branch.getObjectId());
  252. }
  253. @Test
  254. public void testCreateFromAnnotatetdTag() throws Exception {
  255. Ref tagRef = git.tag().setName("V10").setObjectId(secondCommit).call();
  256. Ref branch = git.branchCreate().setName("FromAnnotatedTag")
  257. .setStartPoint("refs/tags/V10").call();
  258. assertFalse(tagRef.getObjectId().equals(branch.getObjectId()));
  259. assertEquals(secondCommit.getId(), branch.getObjectId());
  260. }
  261. @Test
  262. public void testDelete() throws Exception {
  263. createBranch(git, "ForDelete", false, "master", null);
  264. git.branchDelete().setBranchNames("ForDelete").call();
  265. // now point the branch to a non-merged commit
  266. createBranch(git, "ForDelete", false, secondCommit.getId().name(), null);
  267. try {
  268. git.branchDelete().setBranchNames("ForDelete").call();
  269. fail("Deletion of a non-merged branch without force should have failed");
  270. } catch (NotMergedException e) {
  271. // expected
  272. }
  273. List<String> deleted = git.branchDelete().setBranchNames("ForDelete")
  274. .setForce(true).call();
  275. assertEquals(1, deleted.size());
  276. assertEquals(Constants.R_HEADS + "ForDelete", deleted.get(0));
  277. createBranch(git, "ForDelete", false, "master", null);
  278. try {
  279. createBranch(git, "ForDelete", false, "master", null);
  280. fail("Repeated creation of same branch without force should fail");
  281. } catch (RefAlreadyExistsException e) {
  282. // expected
  283. }
  284. // change starting point
  285. Ref newBranch = createBranch(git, "ForDelete", true, initialCommit
  286. .name(), null);
  287. assertEquals(newBranch.getTarget().getObjectId(), initialCommit.getId());
  288. newBranch = createBranch(git, "ForDelete", true, secondCommit.name(),
  289. null);
  290. assertEquals(newBranch.getTarget().getObjectId(), secondCommit.getId());
  291. git.branchDelete().setBranchNames("ForDelete").setForce(true);
  292. try {
  293. git.branchDelete().setBranchNames("master").call();
  294. fail("Deletion of checked out branch without force should have failed");
  295. } catch (CannotDeleteCurrentBranchException e) {
  296. // expected
  297. }
  298. try {
  299. git.branchDelete().setBranchNames("master").setForce(true).call();
  300. fail("Deletion of checked out branch with force should have failed");
  301. } catch (CannotDeleteCurrentBranchException e) {
  302. // expected
  303. }
  304. }
  305. @Test
  306. public void testPullConfigRemoteBranch() throws Exception {
  307. Git localGit = setUpRepoWithRemote();
  308. Ref remote = localGit.branchList().setListMode(ListMode.REMOTE).call()
  309. .get(0);
  310. assertEquals("refs/remotes/origin/master", remote.getName());
  311. // by default, we should create pull configuration
  312. createBranch(localGit, "newFromRemote", false, remote.getName(), null);
  313. assertEquals("origin", localGit.getRepository().getConfig().getString(
  314. "branch", "newFromRemote", "remote"));
  315. localGit.branchDelete().setBranchNames("newFromRemote").call();
  316. // the pull configuration should be gone after deletion
  317. assertNull(localGit.getRepository().getConfig().getString("branch",
  318. "newFromRemote", "remote"));
  319. createBranch(localGit, "newFromRemote", false, remote.getName(), null);
  320. assertEquals("origin", localGit.getRepository().getConfig().getString(
  321. "branch", "newFromRemote", "remote"));
  322. localGit.branchDelete().setBranchNames("refs/heads/newFromRemote")
  323. .call();
  324. // the pull configuration should be gone after deletion
  325. assertNull(localGit.getRepository().getConfig().getString("branch",
  326. "newFromRemote", "remote"));
  327. // use --no-track
  328. createBranch(localGit, "newFromRemote", false, remote.getName(),
  329. SetupUpstreamMode.NOTRACK);
  330. assertNull(localGit.getRepository().getConfig().getString("branch",
  331. "newFromRemote", "remote"));
  332. localGit.branchDelete().setBranchNames("newFromRemote").call();
  333. }
  334. @Test
  335. public void testPullConfigLocalBranch() throws Exception {
  336. Git localGit = setUpRepoWithRemote();
  337. // by default, we should not create pull configuration
  338. createBranch(localGit, "newFromMaster", false, "master", null);
  339. assertNull(localGit.getRepository().getConfig().getString("branch",
  340. "newFromMaster", "remote"));
  341. localGit.branchDelete().setBranchNames("newFromMaster").call();
  342. // use --track
  343. createBranch(localGit, "newFromMaster", false, "master",
  344. SetupUpstreamMode.TRACK);
  345. assertEquals(".", localGit.getRepository().getConfig().getString(
  346. "branch", "newFromMaster", "remote"));
  347. localGit.branchDelete().setBranchNames("refs/heads/newFromMaster")
  348. .call();
  349. // the pull configuration should be gone after deletion
  350. assertNull(localGit.getRepository().getConfig().getString("branch",
  351. "newFromRemote", "remote"));
  352. }
  353. @Test
  354. public void testPullConfigRenameLocalBranch() throws Exception {
  355. Git localGit = setUpRepoWithRemote();
  356. // by default, we should not create pull configuration
  357. createBranch(localGit, "newFromMaster", false, "master", null);
  358. assertNull(localGit.getRepository().getConfig().getString("branch",
  359. "newFromMaster", "remote"));
  360. localGit.branchDelete().setBranchNames("newFromMaster").call();
  361. // use --track
  362. createBranch(localGit, "newFromMaster", false, "master",
  363. SetupUpstreamMode.TRACK);
  364. assertEquals(".", localGit.getRepository().getConfig().getString(
  365. "branch", "newFromMaster", "remote"));
  366. localGit.branchRename().setOldName("newFromMaster").setNewName(
  367. "renamed").call();
  368. assertNull(".", localGit.getRepository().getConfig().getString(
  369. "branch", "newFromMaster", "remote"));
  370. assertEquals(".", localGit.getRepository().getConfig().getString(
  371. "branch", "renamed", "remote"));
  372. localGit.branchDelete().setBranchNames("renamed").call();
  373. // the pull configuration should be gone after deletion
  374. assertNull(localGit.getRepository().getConfig().getString("branch",
  375. "newFromRemote", "remote"));
  376. }
  377. @Test
  378. public void testRenameLocalBranch() throws Exception {
  379. // null newName not allowed
  380. try {
  381. git.branchRename().call();
  382. } catch (InvalidRefNameException e) {
  383. // expected
  384. }
  385. // invalid newName not allowed
  386. try {
  387. git.branchRename().setNewName("In va lid").call();
  388. } catch (InvalidRefNameException e) {
  389. // expected
  390. }
  391. // not existing name not allowed
  392. try {
  393. git.branchRename().setOldName("notexistingbranch").setNewName(
  394. "newname").call();
  395. } catch (RefNotFoundException e) {
  396. // expected
  397. }
  398. // create some branch
  399. createBranch(git, "existing", false, "master", null);
  400. // a local branch
  401. Ref branch = createBranch(git, "fromMasterForRename", false, "master",
  402. null);
  403. assertEquals(Constants.R_HEADS + "fromMasterForRename", branch
  404. .getName());
  405. Ref renamed = git.branchRename().setOldName("fromMasterForRename")
  406. .setNewName("newName").call();
  407. assertEquals(Constants.R_HEADS + "newName", renamed.getName());
  408. try {
  409. git.branchRename().setOldName(renamed.getName()).setNewName(
  410. "existing").call();
  411. fail("Should have failed");
  412. } catch (RefAlreadyExistsException e) {
  413. // expected
  414. }
  415. try {
  416. git.branchRename().setNewName("In va lid").call();
  417. fail("Rename with invalid ref name should fail");
  418. } catch (InvalidRefNameException e) {
  419. // expected
  420. }
  421. // rename without old name and detached head not allowed
  422. RefUpdate rup = git.getRepository().updateRef(Constants.HEAD, true);
  423. rup.setNewObjectId(initialCommit);
  424. rup.forceUpdate();
  425. try {
  426. git.branchRename().setNewName("detached").call();
  427. } catch (DetachedHeadException e) {
  428. // expected
  429. }
  430. }
  431. @Test
  432. public void testRenameRemoteTrackingBranch() throws Exception {
  433. Git localGit = setUpRepoWithRemote();
  434. Ref remoteBranch = localGit.branchList().setListMode(ListMode.REMOTE)
  435. .call().get(0);
  436. Ref renamed = localGit.branchRename()
  437. .setOldName(remoteBranch.getName()).setNewName("newRemote")
  438. .call();
  439. assertEquals(Constants.R_REMOTES + "newRemote", renamed.getName());
  440. }
  441. @Test
  442. public void testCreationImplicitStart() throws Exception {
  443. git.branchCreate().setName("topic").call();
  444. assertEquals(db.resolve("HEAD"), db.resolve("topic"));
  445. }
  446. @Test
  447. public void testCreationNullStartPoint() throws Exception {
  448. String startPoint = null;
  449. git.branchCreate().setName("topic").setStartPoint(startPoint).call();
  450. assertEquals(db.resolve("HEAD"), db.resolve("topic"));
  451. }
  452. public Ref createBranch(Git actGit, String name, boolean force,
  453. String startPoint, SetupUpstreamMode mode)
  454. throws JGitInternalException, GitAPIException {
  455. CreateBranchCommand cmd = actGit.branchCreate();
  456. cmd.setName(name);
  457. cmd.setForce(force);
  458. cmd.setStartPoint(startPoint);
  459. cmd.setUpstreamMode(mode);
  460. return cmd.call();
  461. }
  462. }