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.

CheckoutCommand.java 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. /*
  2. * Copyright (C) 2010, Chris Aniszczyk <caniszczyk@gmail.com>
  3. * Copyright (C) 2011, Matthias Sohn <matthias.sohn@sap.com>
  4. * and other copyright owners as documented in the project's IP log.
  5. *
  6. * This program and the accompanying materials are made available
  7. * under the terms of the Eclipse Distribution License v1.0 which
  8. * accompanies this distribution, is reproduced below, and is
  9. * available at http://www.eclipse.org/org/documents/edl-v10.php
  10. *
  11. * All rights reserved.
  12. *
  13. * Redistribution and use in source and binary forms, with or
  14. * without modification, are permitted provided that the following
  15. * conditions are met:
  16. *
  17. * - Redistributions of source code must retain the above copyright
  18. * notice, this list of conditions and the following disclaimer.
  19. *
  20. * - Redistributions in binary form must reproduce the above
  21. * copyright notice, this list of conditions and the following
  22. * disclaimer in the documentation and/or other materials provided
  23. * with the distribution.
  24. *
  25. * - Neither the name of the Eclipse Foundation, Inc. nor the
  26. * names of its contributors may be used to endorse or promote
  27. * products derived from this software without specific prior
  28. * written permission.
  29. *
  30. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  31. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  32. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  33. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  34. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  35. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  36. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  37. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  38. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  39. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  40. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  41. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  42. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  43. */
  44. package org.eclipse.jgit.api;
  45. import java.io.File;
  46. import java.io.IOException;
  47. import java.text.MessageFormat;
  48. import java.util.ArrayList;
  49. import java.util.LinkedList;
  50. import java.util.List;
  51. import org.eclipse.jgit.api.CheckoutResult.Status;
  52. import org.eclipse.jgit.api.errors.CheckoutConflictException;
  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.RefAlreadyExistsException;
  57. import org.eclipse.jgit.api.errors.RefNotFoundException;
  58. import org.eclipse.jgit.dircache.DirCache;
  59. import org.eclipse.jgit.dircache.DirCacheCheckout;
  60. import org.eclipse.jgit.dircache.DirCacheEditor;
  61. import org.eclipse.jgit.dircache.DirCacheEditor.PathEdit;
  62. import org.eclipse.jgit.dircache.DirCacheEntry;
  63. import org.eclipse.jgit.dircache.DirCacheIterator;
  64. import org.eclipse.jgit.errors.AmbiguousObjectException;
  65. import org.eclipse.jgit.errors.UnmergedPathException;
  66. import org.eclipse.jgit.internal.JGitText;
  67. import org.eclipse.jgit.lib.AnyObjectId;
  68. import org.eclipse.jgit.lib.Constants;
  69. import org.eclipse.jgit.lib.FileMode;
  70. import org.eclipse.jgit.lib.ObjectId;
  71. import org.eclipse.jgit.lib.ObjectReader;
  72. import org.eclipse.jgit.lib.Ref;
  73. import org.eclipse.jgit.lib.RefUpdate;
  74. import org.eclipse.jgit.lib.RefUpdate.Result;
  75. import org.eclipse.jgit.lib.Repository;
  76. import org.eclipse.jgit.revwalk.RevCommit;
  77. import org.eclipse.jgit.revwalk.RevTree;
  78. import org.eclipse.jgit.revwalk.RevWalk;
  79. import org.eclipse.jgit.treewalk.TreeWalk;
  80. import org.eclipse.jgit.treewalk.filter.PathFilterGroup;
  81. import org.eclipse.jgit.util.FileUtils;
  82. /**
  83. * Checkout a branch to the working tree.
  84. * <p>
  85. * Examples (<code>git</code> is a {@link Git} instance):
  86. * <p>
  87. * Check out an existing branch:
  88. *
  89. * <pre>
  90. * git.checkout().setName(&quot;feature&quot;).call();
  91. * </pre>
  92. * <p>
  93. * Check out paths from the index:
  94. *
  95. * <pre>
  96. * git.checkout().addPath(&quot;file1.txt&quot;).addPath(&quot;file2.txt&quot;).call();
  97. * </pre>
  98. * <p>
  99. * Check out a path from a commit:
  100. *
  101. * <pre>
  102. * git.checkout().setStartPoint(&quot;HEAD&circ;&quot;).addPath(&quot;file1.txt&quot;).call();
  103. * </pre>
  104. *
  105. * <p>
  106. * Create a new branch and check it out:
  107. *
  108. * <pre>
  109. * git.checkout().setCreateBranch(true).setName(&quot;newbranch&quot;).call();
  110. * </pre>
  111. * <p>
  112. * Create a new tracking branch for a remote branch and check it out:
  113. *
  114. * <pre>
  115. * git.checkout().setCreateBranch(true).setName(&quot;stable&quot;)
  116. * .setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM)
  117. * .setStartPoint(&quot;origin/stable&quot;).call();
  118. * </pre>
  119. *
  120. * @see <a
  121. * href="http://www.kernel.org/pub/software/scm/git/docs/git-checkout.html"
  122. * >Git documentation about Checkout</a>
  123. */
  124. public class CheckoutCommand extends GitCommand<Ref> {
  125. /**
  126. * Stage to check out, see {@link CheckoutCommand#setStage(Stage)}.
  127. */
  128. public static enum Stage {
  129. /**
  130. * Base stage (#1)
  131. */
  132. BASE(DirCacheEntry.STAGE_1),
  133. /**
  134. * Ours stage (#2)
  135. */
  136. OURS(DirCacheEntry.STAGE_2),
  137. /**
  138. * Theirs stage (#3)
  139. */
  140. THEIRS(DirCacheEntry.STAGE_3);
  141. private final int number;
  142. private Stage(int number) {
  143. this.number = number;
  144. }
  145. }
  146. private String name;
  147. private boolean force = false;
  148. private boolean createBranch = false;
  149. private CreateBranchCommand.SetupUpstreamMode upstreamMode;
  150. private String startPoint = null;
  151. private RevCommit startCommit;
  152. private Stage checkoutStage = null;
  153. private CheckoutResult status;
  154. private List<String> paths;
  155. private boolean checkoutAllPaths;
  156. /**
  157. * @param repo
  158. */
  159. protected CheckoutCommand(Repository repo) {
  160. super(repo);
  161. this.paths = new LinkedList<String>();
  162. }
  163. /**
  164. * @throws RefAlreadyExistsException
  165. * when trying to create (without force) a branch with a name
  166. * that already exists
  167. * @throws RefNotFoundException
  168. * if the start point or branch can not be found
  169. * @throws InvalidRefNameException
  170. * if the provided name is <code>null</code> or otherwise
  171. * invalid
  172. * @throws CheckoutConflictException
  173. * if the checkout results in a conflict
  174. * @return the newly created branch
  175. */
  176. public Ref call() throws GitAPIException, RefAlreadyExistsException,
  177. RefNotFoundException, InvalidRefNameException,
  178. CheckoutConflictException {
  179. checkCallable();
  180. processOptions();
  181. try {
  182. if (checkoutAllPaths || !paths.isEmpty()) {
  183. checkoutPaths();
  184. status = new CheckoutResult(Status.OK, paths);
  185. setCallable(false);
  186. return null;
  187. }
  188. if (createBranch) {
  189. Git git = new Git(repo);
  190. CreateBranchCommand command = git.branchCreate();
  191. command.setName(name);
  192. command.setStartPoint(getStartPoint().name());
  193. if (upstreamMode != null)
  194. command.setUpstreamMode(upstreamMode);
  195. command.call();
  196. }
  197. Ref headRef = repo.getRef(Constants.HEAD);
  198. String shortHeadRef = getShortBranchName(headRef);
  199. String refLogMessage = "checkout: moving from " + shortHeadRef; //$NON-NLS-1$
  200. ObjectId branch = repo.resolve(name);
  201. if (branch == null)
  202. throw new RefNotFoundException(MessageFormat.format(JGitText
  203. .get().refNotResolved, name));
  204. RevWalk revWalk = new RevWalk(repo);
  205. AnyObjectId headId = headRef.getObjectId();
  206. RevCommit headCommit = headId == null ? null : revWalk
  207. .parseCommit(headId);
  208. RevCommit newCommit = revWalk.parseCommit(branch);
  209. RevTree headTree = headCommit == null ? null : headCommit.getTree();
  210. DirCacheCheckout dco;
  211. DirCache dc = repo.lockDirCache();
  212. try {
  213. dco = new DirCacheCheckout(repo, headTree, dc,
  214. newCommit.getTree());
  215. dco.setFailOnConflict(true);
  216. try {
  217. dco.checkout();
  218. } catch (org.eclipse.jgit.errors.CheckoutConflictException e) {
  219. status = new CheckoutResult(Status.CONFLICTS,
  220. dco.getConflicts());
  221. throw new CheckoutConflictException(dco.getConflicts(), e);
  222. }
  223. } finally {
  224. dc.unlock();
  225. }
  226. Ref ref = repo.getRef(name);
  227. if (ref != null && !ref.getName().startsWith(Constants.R_HEADS))
  228. ref = null;
  229. String toName = Repository.shortenRefName(name);
  230. RefUpdate refUpdate = repo.updateRef(Constants.HEAD, ref == null);
  231. refUpdate.setForceUpdate(force);
  232. refUpdate.setRefLogMessage(refLogMessage + " to " + toName, false); //$NON-NLS-1$
  233. Result updateResult;
  234. if (ref != null)
  235. updateResult = refUpdate.link(ref.getName());
  236. else {
  237. refUpdate.setNewObjectId(newCommit);
  238. updateResult = refUpdate.forceUpdate();
  239. }
  240. setCallable(false);
  241. boolean ok = false;
  242. switch (updateResult) {
  243. case NEW:
  244. ok = true;
  245. break;
  246. case NO_CHANGE:
  247. case FAST_FORWARD:
  248. case FORCED:
  249. ok = true;
  250. break;
  251. default:
  252. break;
  253. }
  254. if (!ok)
  255. throw new JGitInternalException(MessageFormat.format(JGitText
  256. .get().checkoutUnexpectedResult, updateResult.name()));
  257. if (!dco.getToBeDeleted().isEmpty()) {
  258. status = new CheckoutResult(Status.NONDELETED,
  259. dco.getToBeDeleted());
  260. } else
  261. status = new CheckoutResult(new ArrayList<String>(dco
  262. .getUpdated().keySet()), dco.getRemoved());
  263. return ref;
  264. } catch (IOException ioe) {
  265. throw new JGitInternalException(ioe.getMessage(), ioe);
  266. } finally {
  267. if (status == null)
  268. status = CheckoutResult.ERROR_RESULT;
  269. }
  270. }
  271. private String getShortBranchName(Ref headRef) {
  272. if (headRef.getTarget().getName().equals(headRef.getName()))
  273. return headRef.getTarget().getObjectId().getName();
  274. return Repository.shortenRefName(headRef.getTarget().getName());
  275. }
  276. /**
  277. * Add a single slash-separated path to the list of paths to check out. To
  278. * check out all paths, use {@link #setAllPaths(boolean)}.
  279. * <p>
  280. * If this option is set, neither the {@link #setCreateBranch(boolean)} nor
  281. * {@link #setName(String)} option is considered. In other words, these
  282. * options are exclusive.
  283. *
  284. * @param path
  285. * path to update in the working tree and index (with
  286. * <code>/</code> as separator)
  287. * @return {@code this}
  288. */
  289. public CheckoutCommand addPath(String path) {
  290. checkCallable();
  291. this.paths.add(path);
  292. return this;
  293. }
  294. /**
  295. * Set whether to checkout all paths.
  296. * <p>
  297. * This options should be used when you want to do a path checkout on the
  298. * entire repository and so calling {@link #addPath(String)} is not possible
  299. * since empty paths are not allowed.
  300. * <p>
  301. * If this option is set, neither the {@link #setCreateBranch(boolean)} nor
  302. * {@link #setName(String)} option is considered. In other words, these
  303. * options are exclusive.
  304. *
  305. * @param all
  306. * <code>true</code> to checkout all paths, <code>false</code>
  307. * otherwise
  308. * @return {@code this}
  309. * @since 2.0
  310. */
  311. public CheckoutCommand setAllPaths(boolean all) {
  312. checkoutAllPaths = all;
  313. return this;
  314. }
  315. /**
  316. * Checkout paths into index and working directory
  317. *
  318. * @return this instance
  319. * @throws IOException
  320. * @throws RefNotFoundException
  321. */
  322. protected CheckoutCommand checkoutPaths() throws IOException,
  323. RefNotFoundException {
  324. RevWalk revWalk = new RevWalk(repo);
  325. DirCache dc = repo.lockDirCache();
  326. try {
  327. TreeWalk treeWalk = new TreeWalk(revWalk.getObjectReader());
  328. treeWalk.setRecursive(true);
  329. if (!checkoutAllPaths)
  330. treeWalk.setFilter(PathFilterGroup.createFromStrings(paths));
  331. try {
  332. if (isCheckoutIndex())
  333. checkoutPathsFromIndex(treeWalk, dc);
  334. else {
  335. RevCommit commit = revWalk.parseCommit(getStartPoint());
  336. checkoutPathsFromCommit(treeWalk, dc, commit);
  337. }
  338. } finally {
  339. treeWalk.release();
  340. }
  341. } finally {
  342. dc.unlock();
  343. revWalk.release();
  344. }
  345. return this;
  346. }
  347. private void checkoutPathsFromIndex(TreeWalk treeWalk, DirCache dc)
  348. throws IOException {
  349. DirCacheIterator dci = new DirCacheIterator(dc);
  350. treeWalk.addTree(dci);
  351. final ObjectReader r = treeWalk.getObjectReader();
  352. DirCacheEditor editor = dc.editor();
  353. while (treeWalk.next()) {
  354. DirCacheEntry entry = dci.getDirCacheEntry();
  355. // Only add one edit per path
  356. if (entry != null && entry.getStage() > DirCacheEntry.STAGE_1)
  357. continue;
  358. editor.add(new PathEdit(treeWalk.getPathString()) {
  359. public void apply(DirCacheEntry ent) {
  360. int stage = ent.getStage();
  361. if (stage > DirCacheEntry.STAGE_0) {
  362. if (checkoutStage != null) {
  363. if (stage == checkoutStage.number)
  364. checkoutPath(ent, r);
  365. } else {
  366. UnmergedPathException e = new UnmergedPathException(
  367. ent);
  368. throw new JGitInternalException(e.getMessage(), e);
  369. }
  370. } else {
  371. checkoutPath(ent, r);
  372. }
  373. }
  374. });
  375. }
  376. editor.commit();
  377. }
  378. private void checkoutPathsFromCommit(TreeWalk treeWalk, DirCache dc,
  379. RevCommit commit) throws IOException {
  380. treeWalk.addTree(commit.getTree());
  381. final ObjectReader r = treeWalk.getObjectReader();
  382. DirCacheEditor editor = dc.editor();
  383. while (treeWalk.next()) {
  384. final ObjectId blobId = treeWalk.getObjectId(0);
  385. final FileMode mode = treeWalk.getFileMode(0);
  386. editor.add(new PathEdit(treeWalk.getPathString()) {
  387. public void apply(DirCacheEntry ent) {
  388. ent.setObjectId(blobId);
  389. ent.setFileMode(mode);
  390. checkoutPath(ent, r);
  391. }
  392. });
  393. }
  394. editor.commit();
  395. }
  396. private void checkoutPath(DirCacheEntry entry, ObjectReader reader) {
  397. File file = new File(repo.getWorkTree(), entry.getPathString());
  398. File parentDir = file.getParentFile();
  399. try {
  400. FileUtils.mkdirs(parentDir, true);
  401. DirCacheCheckout.checkoutEntry(repo, file, entry, reader);
  402. } catch (IOException e) {
  403. throw new JGitInternalException(MessageFormat.format(
  404. JGitText.get().checkoutConflictWithFile,
  405. entry.getPathString()), e);
  406. }
  407. }
  408. private boolean isCheckoutIndex() {
  409. return startCommit == null && startPoint == null;
  410. }
  411. private ObjectId getStartPoint() throws AmbiguousObjectException,
  412. RefNotFoundException, IOException {
  413. if (startCommit != null)
  414. return startCommit.getId();
  415. ObjectId result = null;
  416. try {
  417. result = repo.resolve((startPoint == null) ? Constants.HEAD
  418. : startPoint);
  419. } catch (AmbiguousObjectException e) {
  420. throw e;
  421. }
  422. if (result == null)
  423. throw new RefNotFoundException(MessageFormat.format(
  424. JGitText.get().refNotResolved,
  425. startPoint != null ? startPoint : Constants.HEAD));
  426. return result;
  427. }
  428. private void processOptions() throws InvalidRefNameException {
  429. if ((!checkoutAllPaths && paths.isEmpty())
  430. && (name == null || !Repository
  431. .isValidRefName(Constants.R_HEADS + name)))
  432. throw new InvalidRefNameException(MessageFormat.format(JGitText
  433. .get().branchNameInvalid, name == null ? "<null>" : name)); //$NON-NLS-1$
  434. }
  435. /**
  436. * Specify the name of the branch or commit to check out, or the new branch
  437. * name.
  438. * <p>
  439. * When only checking out paths and not switching branches, use
  440. * {@link #setStartPoint(String)} or {@link #setStartPoint(RevCommit)} to
  441. * specify from which branch or commit to check out files.
  442. * <p>
  443. * When {@link #setCreateBranch(boolean)} is set to <code>true</code>, use
  444. * this method to set the name of the new branch to create and
  445. * {@link #setStartPoint(String)} or {@link #setStartPoint(RevCommit)} to
  446. * specify the start point of the branch.
  447. *
  448. * @param name
  449. * the name of the branch or commit
  450. * @return this instance
  451. */
  452. public CheckoutCommand setName(String name) {
  453. checkCallable();
  454. this.name = name;
  455. return this;
  456. }
  457. /**
  458. * Specify whether to create a new branch.
  459. * <p>
  460. * If <code>true</code> is used, the name of the new branch must be set
  461. * using {@link #setName(String)}. The commit at which to start the new
  462. * branch can be set using {@link #setStartPoint(String)} or
  463. * {@link #setStartPoint(RevCommit)}; if not specified, HEAD is used. Also
  464. * see {@link #setUpstreamMode} for setting up branch tracking.
  465. *
  466. * @param createBranch
  467. * if <code>true</code> a branch will be created as part of the
  468. * checkout and set to the specified start point
  469. * @return this instance
  470. */
  471. public CheckoutCommand setCreateBranch(boolean createBranch) {
  472. checkCallable();
  473. this.createBranch = createBranch;
  474. return this;
  475. }
  476. /**
  477. * Specify to force the ref update in case of a branch switch.
  478. *
  479. * @param force
  480. * if <code>true</code> and the branch with the given name
  481. * already exists, the start-point of an existing branch will be
  482. * set to a new start-point; if false, the existing branch will
  483. * not be changed
  484. * @return this instance
  485. */
  486. public CheckoutCommand setForce(boolean force) {
  487. checkCallable();
  488. this.force = force;
  489. return this;
  490. }
  491. /**
  492. * Set the name of the commit that should be checked out.
  493. * <p>
  494. * When checking out files and this is not specified or <code>null</code>,
  495. * the index is used.
  496. * <p>
  497. * When creating a new branch, this will be used as the start point. If not
  498. * specified or <code>null</code>, the current HEAD is used.
  499. *
  500. * @param startPoint
  501. * commit name to check out
  502. * @return this instance
  503. */
  504. public CheckoutCommand setStartPoint(String startPoint) {
  505. checkCallable();
  506. this.startPoint = startPoint;
  507. this.startCommit = null;
  508. checkOptions();
  509. return this;
  510. }
  511. /**
  512. * Set the commit that should be checked out.
  513. * <p>
  514. * When creating a new branch, this will be used as the start point. If not
  515. * specified or <code>null</code>, the current HEAD is used.
  516. * <p>
  517. * When checking out files and this is not specified or <code>null</code>,
  518. * the index is used.
  519. *
  520. * @param startCommit
  521. * commit to check out
  522. * @return this instance
  523. */
  524. public CheckoutCommand setStartPoint(RevCommit startCommit) {
  525. checkCallable();
  526. this.startCommit = startCommit;
  527. this.startPoint = null;
  528. checkOptions();
  529. return this;
  530. }
  531. /**
  532. * When creating a branch with {@link #setCreateBranch(boolean)}, this can
  533. * be used to configure branch tracking.
  534. *
  535. * @param mode
  536. * corresponds to the --track/--no-track options; may be
  537. * <code>null</code>
  538. * @return this instance
  539. */
  540. public CheckoutCommand setUpstreamMode(
  541. CreateBranchCommand.SetupUpstreamMode mode) {
  542. checkCallable();
  543. this.upstreamMode = mode;
  544. return this;
  545. }
  546. /**
  547. * When checking out the index, check out the specified stage (ours or
  548. * theirs) for unmerged paths.
  549. * <p>
  550. * This can not be used when checking out a branch, only when checking out
  551. * the index.
  552. *
  553. * @param stage
  554. * the stage to check out
  555. * @return this
  556. */
  557. public CheckoutCommand setStage(Stage stage) {
  558. checkCallable();
  559. this.checkoutStage = stage;
  560. checkOptions();
  561. return this;
  562. }
  563. /**
  564. * @return the result, never <code>null</code>
  565. */
  566. public CheckoutResult getResult() {
  567. if (status == null)
  568. return CheckoutResult.NOT_TRIED_RESULT;
  569. return status;
  570. }
  571. private void checkOptions() {
  572. if (checkoutStage != null && !isCheckoutIndex())
  573. throw new IllegalStateException(
  574. "Checking out ours/theirs is only possible when checking out index, "
  575. + "not when switching branches.");
  576. }
  577. }