Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

BranchCommandTest.java 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  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(expected = InvalidRefNameException.class)
  180. public void testInvalidBranchHEAD() throws Exception {
  181. git.branchCreate().setName("HEAD").call();
  182. fail("Create branch with invalid ref name should fail");
  183. }
  184. @Test(expected = InvalidRefNameException.class)
  185. public void testInvalidBranchDash() throws Exception {
  186. git.branchCreate().setName("-x").call();
  187. fail("Create branch with invalid ref name should fail");
  188. }
  189. @Test
  190. public void testListAllBranchesShouldNotDie() throws Exception {
  191. setUpRepoWithRemote().branchList().setListMode(ListMode.ALL).call();
  192. }
  193. @Test
  194. public void testListBranchesWithContains() throws Exception {
  195. git.branchCreate().setName("foo").setStartPoint(secondCommit).call();
  196. List<Ref> refs = git.branchList().call();
  197. assertEquals(2, refs.size());
  198. List<Ref> refsContainingSecond = git.branchList()
  199. .setContains(secondCommit.name()).call();
  200. assertEquals(1, refsContainingSecond.size());
  201. // master is on initial commit, so it should not be returned
  202. assertEquals("refs/heads/foo", refsContainingSecond.get(0).getName());
  203. }
  204. @Test
  205. public void testCreateFromCommit() throws Exception {
  206. Ref branch = git.branchCreate().setName("FromInitial").setStartPoint(
  207. initialCommit).call();
  208. assertEquals(initialCommit.getId(), branch.getObjectId());
  209. branch = git.branchCreate().setName("FromInitial2").setStartPoint(
  210. initialCommit.getId().name()).call();
  211. assertEquals(initialCommit.getId(), branch.getObjectId());
  212. try {
  213. git.branchCreate().setName("FromInitial").setStartPoint(
  214. secondCommit).call();
  215. } catch (RefAlreadyExistsException e) {
  216. // expected
  217. }
  218. branch = git.branchCreate().setName("FromInitial").setStartPoint(
  219. secondCommit).setForce(true).call();
  220. assertEquals(secondCommit.getId(), branch.getObjectId());
  221. }
  222. @Test
  223. public void testCreateForce() throws Exception {
  224. // using commits
  225. Ref newBranch = createBranch(git, "NewForce", false, secondCommit
  226. .getId().name(), null);
  227. assertEquals(newBranch.getTarget().getObjectId(), secondCommit.getId());
  228. try {
  229. newBranch = createBranch(git, "NewForce", false, initialCommit
  230. .getId().name(), null);
  231. fail("Should have failed");
  232. } catch (RefAlreadyExistsException e) {
  233. // expected
  234. }
  235. newBranch = createBranch(git, "NewForce", true, initialCommit.getId()
  236. .name(), null);
  237. assertEquals(newBranch.getTarget().getObjectId(), initialCommit.getId());
  238. git.branchDelete().setBranchNames("NewForce").call();
  239. // using names
  240. git.branchCreate().setName("NewForce").setStartPoint("master").call();
  241. assertEquals(newBranch.getTarget().getObjectId(), initialCommit.getId());
  242. try {
  243. git.branchCreate().setName("NewForce").setStartPoint("master")
  244. .call();
  245. fail("Should have failed");
  246. } catch (RefAlreadyExistsException e) {
  247. // expected
  248. }
  249. git.branchCreate().setName("NewForce").setStartPoint("master")
  250. .setForce(true).call();
  251. assertEquals(newBranch.getTarget().getObjectId(), initialCommit.getId());
  252. }
  253. @Test
  254. public void testCreateFromLightweightTag() throws Exception {
  255. RefUpdate rup = db.updateRef("refs/tags/V10");
  256. rup.setNewObjectId(initialCommit);
  257. rup.setExpectedOldObjectId(ObjectId.zeroId());
  258. rup.update();
  259. Ref branch = git.branchCreate().setName("FromLightweightTag")
  260. .setStartPoint("refs/tags/V10").call();
  261. assertEquals(initialCommit.getId(), branch.getObjectId());
  262. }
  263. @Test
  264. public void testCreateFromAnnotatetdTag() throws Exception {
  265. Ref tagRef = git.tag().setName("V10").setObjectId(secondCommit).call();
  266. Ref branch = git.branchCreate().setName("FromAnnotatedTag")
  267. .setStartPoint("refs/tags/V10").call();
  268. assertFalse(tagRef.getObjectId().equals(branch.getObjectId()));
  269. assertEquals(secondCommit.getId(), branch.getObjectId());
  270. }
  271. @Test
  272. public void testDelete() throws Exception {
  273. createBranch(git, "ForDelete", false, "master", null);
  274. git.branchDelete().setBranchNames("ForDelete").call();
  275. // now point the branch to a non-merged commit
  276. createBranch(git, "ForDelete", false, secondCommit.getId().name(), null);
  277. try {
  278. git.branchDelete().setBranchNames("ForDelete").call();
  279. fail("Deletion of a non-merged branch without force should have failed");
  280. } catch (NotMergedException e) {
  281. // expected
  282. }
  283. List<String> deleted = git.branchDelete().setBranchNames("ForDelete")
  284. .setForce(true).call();
  285. assertEquals(1, deleted.size());
  286. assertEquals(Constants.R_HEADS + "ForDelete", deleted.get(0));
  287. createBranch(git, "ForDelete", false, "master", null);
  288. try {
  289. createBranch(git, "ForDelete", false, "master", null);
  290. fail("Repeated creation of same branch without force should fail");
  291. } catch (RefAlreadyExistsException e) {
  292. // expected
  293. }
  294. // change starting point
  295. Ref newBranch = createBranch(git, "ForDelete", true, initialCommit
  296. .name(), null);
  297. assertEquals(newBranch.getTarget().getObjectId(), initialCommit.getId());
  298. newBranch = createBranch(git, "ForDelete", true, secondCommit.name(),
  299. null);
  300. assertEquals(newBranch.getTarget().getObjectId(), secondCommit.getId());
  301. git.branchDelete().setBranchNames("ForDelete").setForce(true);
  302. try {
  303. git.branchDelete().setBranchNames("master").call();
  304. fail("Deletion of checked out branch without force should have failed");
  305. } catch (CannotDeleteCurrentBranchException e) {
  306. // expected
  307. }
  308. try {
  309. git.branchDelete().setBranchNames("master").setForce(true).call();
  310. fail("Deletion of checked out branch with force should have failed");
  311. } catch (CannotDeleteCurrentBranchException e) {
  312. // expected
  313. }
  314. }
  315. @Test
  316. public void testPullConfigRemoteBranch() throws Exception {
  317. Git localGit = setUpRepoWithRemote();
  318. Ref remote = localGit.branchList().setListMode(ListMode.REMOTE).call()
  319. .get(0);
  320. assertEquals("refs/remotes/origin/master", remote.getName());
  321. // by default, we should create pull configuration
  322. createBranch(localGit, "newFromRemote", false, remote.getName(), null);
  323. assertEquals("origin", localGit.getRepository().getConfig().getString(
  324. "branch", "newFromRemote", "remote"));
  325. localGit.branchDelete().setBranchNames("newFromRemote").call();
  326. // the pull configuration should be gone after deletion
  327. assertNull(localGit.getRepository().getConfig().getString("branch",
  328. "newFromRemote", "remote"));
  329. createBranch(localGit, "newFromRemote", false, remote.getName(), null);
  330. assertEquals("origin", localGit.getRepository().getConfig().getString(
  331. "branch", "newFromRemote", "remote"));
  332. localGit.branchDelete().setBranchNames("refs/heads/newFromRemote")
  333. .call();
  334. // the pull configuration should be gone after deletion
  335. assertNull(localGit.getRepository().getConfig().getString("branch",
  336. "newFromRemote", "remote"));
  337. // use --no-track
  338. createBranch(localGit, "newFromRemote", false, remote.getName(),
  339. SetupUpstreamMode.NOTRACK);
  340. assertNull(localGit.getRepository().getConfig().getString("branch",
  341. "newFromRemote", "remote"));
  342. localGit.branchDelete().setBranchNames("newFromRemote").call();
  343. }
  344. @Test
  345. public void testPullConfigLocalBranch() throws Exception {
  346. Git localGit = setUpRepoWithRemote();
  347. // by default, we should not create pull configuration
  348. createBranch(localGit, "newFromMaster", false, "master", null);
  349. assertNull(localGit.getRepository().getConfig().getString("branch",
  350. "newFromMaster", "remote"));
  351. localGit.branchDelete().setBranchNames("newFromMaster").call();
  352. // use --track
  353. createBranch(localGit, "newFromMaster", false, "master",
  354. SetupUpstreamMode.TRACK);
  355. assertEquals(".", localGit.getRepository().getConfig().getString(
  356. "branch", "newFromMaster", "remote"));
  357. localGit.branchDelete().setBranchNames("refs/heads/newFromMaster")
  358. .call();
  359. // the pull configuration should be gone after deletion
  360. assertNull(localGit.getRepository().getConfig().getString("branch",
  361. "newFromRemote", "remote"));
  362. }
  363. @Test
  364. public void testPullConfigRenameLocalBranch() throws Exception {
  365. Git localGit = setUpRepoWithRemote();
  366. // by default, we should not create pull configuration
  367. createBranch(localGit, "newFromMaster", false, "master", null);
  368. assertNull(localGit.getRepository().getConfig().getString("branch",
  369. "newFromMaster", "remote"));
  370. localGit.branchDelete().setBranchNames("newFromMaster").call();
  371. // use --track
  372. createBranch(localGit, "newFromMaster", false, "master",
  373. SetupUpstreamMode.TRACK);
  374. assertEquals(".", localGit.getRepository().getConfig().getString(
  375. "branch", "newFromMaster", "remote"));
  376. localGit.branchRename().setOldName("newFromMaster").setNewName(
  377. "renamed").call();
  378. assertNull(".", localGit.getRepository().getConfig().getString(
  379. "branch", "newFromMaster", "remote"));
  380. assertEquals(".", localGit.getRepository().getConfig().getString(
  381. "branch", "renamed", "remote"));
  382. localGit.branchDelete().setBranchNames("renamed").call();
  383. // the pull configuration should be gone after deletion
  384. assertNull(localGit.getRepository().getConfig().getString("branch",
  385. "newFromRemote", "remote"));
  386. }
  387. @Test
  388. public void testRenameLocalBranch() throws Exception {
  389. // null newName not allowed
  390. try {
  391. git.branchRename().call();
  392. } catch (InvalidRefNameException e) {
  393. // expected
  394. }
  395. // invalid newName not allowed
  396. try {
  397. git.branchRename().setNewName("In va lid").call();
  398. } catch (InvalidRefNameException e) {
  399. // expected
  400. }
  401. // not existing name not allowed
  402. try {
  403. git.branchRename().setOldName("notexistingbranch").setNewName(
  404. "newname").call();
  405. } catch (RefNotFoundException e) {
  406. // expected
  407. }
  408. // create some branch
  409. createBranch(git, "existing", false, "master", null);
  410. // a local branch
  411. Ref branch = createBranch(git, "fromMasterForRename", false, "master",
  412. null);
  413. assertEquals(Constants.R_HEADS + "fromMasterForRename", branch
  414. .getName());
  415. Ref renamed = git.branchRename().setOldName("fromMasterForRename")
  416. .setNewName("newName").call();
  417. assertEquals(Constants.R_HEADS + "newName", renamed.getName());
  418. try {
  419. git.branchRename().setOldName(renamed.getName()).setNewName(
  420. "existing").call();
  421. fail("Should have failed");
  422. } catch (RefAlreadyExistsException e) {
  423. // expected
  424. }
  425. try {
  426. git.branchRename().setNewName("In va lid").call();
  427. fail("Rename with invalid ref name should fail");
  428. } catch (InvalidRefNameException e) {
  429. // expected
  430. }
  431. // rename without old name and detached head not allowed
  432. RefUpdate rup = git.getRepository().updateRef(Constants.HEAD, true);
  433. rup.setNewObjectId(initialCommit);
  434. rup.forceUpdate();
  435. try {
  436. git.branchRename().setNewName("detached").call();
  437. } catch (DetachedHeadException e) {
  438. // expected
  439. }
  440. }
  441. @Test
  442. public void testRenameRemoteTrackingBranch() throws Exception {
  443. Git localGit = setUpRepoWithRemote();
  444. Ref remoteBranch = localGit.branchList().setListMode(ListMode.REMOTE)
  445. .call().get(0);
  446. Ref renamed = localGit.branchRename()
  447. .setOldName(remoteBranch.getName()).setNewName("newRemote")
  448. .call();
  449. assertEquals(Constants.R_REMOTES + "newRemote", renamed.getName());
  450. }
  451. @Test
  452. public void testCreationImplicitStart() throws Exception {
  453. git.branchCreate().setName("topic").call();
  454. assertEquals(db.resolve("HEAD"), db.resolve("topic"));
  455. }
  456. @Test
  457. public void testCreationNullStartPoint() throws Exception {
  458. String startPoint = null;
  459. git.branchCreate().setName("topic").setStartPoint(startPoint).call();
  460. assertEquals(db.resolve("HEAD"), db.resolve("topic"));
  461. }
  462. public Ref createBranch(Git actGit, String name, boolean force,
  463. String startPoint, SetupUpstreamMode mode)
  464. throws JGitInternalException, GitAPIException {
  465. CreateBranchCommand cmd = actGit.branchCreate();
  466. cmd.setName(name);
  467. cmd.setForce(force);
  468. cmd.setStartPoint(startPoint);
  469. cmd.setUpstreamMode(mode);
  470. return cmd.call();
  471. }
  472. }