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 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  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.IOException;
  46. import java.text.MessageFormat;
  47. import java.util.ArrayList;
  48. import java.util.EnumSet;
  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.DirCacheCheckout.CheckoutMetadata;
  61. import org.eclipse.jgit.dircache.DirCacheEditor;
  62. import org.eclipse.jgit.dircache.DirCacheEditor.PathEdit;
  63. import org.eclipse.jgit.dircache.DirCacheEntry;
  64. import org.eclipse.jgit.dircache.DirCacheIterator;
  65. import org.eclipse.jgit.errors.AmbiguousObjectException;
  66. import org.eclipse.jgit.errors.UnmergedPathException;
  67. import org.eclipse.jgit.internal.JGitText;
  68. import org.eclipse.jgit.lib.AnyObjectId;
  69. import org.eclipse.jgit.lib.Constants;
  70. import org.eclipse.jgit.lib.CoreConfig.EolStreamType;
  71. import org.eclipse.jgit.lib.FileMode;
  72. import org.eclipse.jgit.lib.ObjectId;
  73. import org.eclipse.jgit.lib.ObjectReader;
  74. import org.eclipse.jgit.lib.Ref;
  75. import org.eclipse.jgit.lib.RefUpdate;
  76. import org.eclipse.jgit.lib.RefUpdate.Result;
  77. import org.eclipse.jgit.lib.Repository;
  78. import org.eclipse.jgit.revwalk.RevCommit;
  79. import org.eclipse.jgit.revwalk.RevTree;
  80. import org.eclipse.jgit.revwalk.RevWalk;
  81. import org.eclipse.jgit.treewalk.TreeWalk;
  82. import org.eclipse.jgit.treewalk.filter.PathFilterGroup;
  83. /**
  84. * Checkout a branch to the working tree.
  85. * <p>
  86. * Examples (<code>git</code> is a {@link Git} instance):
  87. * <p>
  88. * Check out an existing branch:
  89. *
  90. * <pre>
  91. * git.checkout().setName(&quot;feature&quot;).call();
  92. * </pre>
  93. * <p>
  94. * Check out paths from the index:
  95. *
  96. * <pre>
  97. * git.checkout().addPath(&quot;file1.txt&quot;).addPath(&quot;file2.txt&quot;).call();
  98. * </pre>
  99. * <p>
  100. * Check out a path from a commit:
  101. *
  102. * <pre>
  103. * git.checkout().setStartPoint(&quot;HEAD&circ;&quot;).addPath(&quot;file1.txt&quot;).call();
  104. * </pre>
  105. *
  106. * <p>
  107. * Create a new branch and check it out:
  108. *
  109. * <pre>
  110. * git.checkout().setCreateBranch(true).setName(&quot;newbranch&quot;).call();
  111. * </pre>
  112. * <p>
  113. * Create a new tracking branch for a remote branch and check it out:
  114. *
  115. * <pre>
  116. * git.checkout().setCreateBranch(true).setName(&quot;stable&quot;)
  117. * .setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM)
  118. * .setStartPoint(&quot;origin/stable&quot;).call();
  119. * </pre>
  120. *
  121. * @see <a
  122. * href="http://www.kernel.org/pub/software/scm/git/docs/git-checkout.html"
  123. * >Git documentation about Checkout</a>
  124. */
  125. public class CheckoutCommand extends GitCommand<Ref> {
  126. /**
  127. * Stage to check out, see {@link CheckoutCommand#setStage(Stage)}.
  128. */
  129. public static enum Stage {
  130. /**
  131. * Base stage (#1)
  132. */
  133. BASE(DirCacheEntry.STAGE_1),
  134. /**
  135. * Ours stage (#2)
  136. */
  137. OURS(DirCacheEntry.STAGE_2),
  138. /**
  139. * Theirs stage (#3)
  140. */
  141. THEIRS(DirCacheEntry.STAGE_3);
  142. private final int number;
  143. private Stage(int number) {
  144. this.number = number;
  145. }
  146. }
  147. private String name;
  148. private boolean force = false;
  149. private boolean createBranch = false;
  150. private boolean orphan = false;
  151. private CreateBranchCommand.SetupUpstreamMode upstreamMode;
  152. private String startPoint = null;
  153. private RevCommit startCommit;
  154. private Stage checkoutStage = null;
  155. private CheckoutResult status;
  156. private List<String> paths;
  157. private boolean checkoutAllPaths;
  158. /**
  159. * @param repo
  160. */
  161. protected CheckoutCommand(Repository repo) {
  162. super(repo);
  163. this.paths = new LinkedList<String>();
  164. }
  165. /**
  166. * @throws RefAlreadyExistsException
  167. * when trying to create (without force) a branch with a name
  168. * that already exists
  169. * @throws RefNotFoundException
  170. * if the start point or branch can not be found
  171. * @throws InvalidRefNameException
  172. * if the provided name is <code>null</code> or otherwise
  173. * invalid
  174. * @throws CheckoutConflictException
  175. * if the checkout results in a conflict
  176. * @return the newly created branch
  177. */
  178. public Ref call() throws GitAPIException, RefAlreadyExistsException,
  179. RefNotFoundException, InvalidRefNameException,
  180. CheckoutConflictException {
  181. checkCallable();
  182. try {
  183. processOptions();
  184. if (checkoutAllPaths || !paths.isEmpty()) {
  185. checkoutPaths();
  186. status = new CheckoutResult(Status.OK, paths);
  187. setCallable(false);
  188. return null;
  189. }
  190. if (createBranch) {
  191. try (Git git = new Git(repo)) {
  192. CreateBranchCommand command = git.branchCreate();
  193. command.setName(name);
  194. if (startCommit != null)
  195. command.setStartPoint(startCommit);
  196. else
  197. command.setStartPoint(startPoint);
  198. if (upstreamMode != null)
  199. command.setUpstreamMode(upstreamMode);
  200. command.call();
  201. }
  202. }
  203. Ref headRef = repo.exactRef(Constants.HEAD);
  204. if (headRef == null) {
  205. // TODO Git CLI supports checkout from unborn branch, we should
  206. // also allow this
  207. throw new UnsupportedOperationException(
  208. JGitText.get().cannotCheckoutFromUnbornBranch);
  209. }
  210. String shortHeadRef = getShortBranchName(headRef);
  211. String refLogMessage = "checkout: moving from " + shortHeadRef; //$NON-NLS-1$
  212. ObjectId branch;
  213. if (orphan) {
  214. if (startPoint == null && startCommit == null) {
  215. Result r = repo.updateRef(Constants.HEAD).link(
  216. getBranchName());
  217. if (!EnumSet.of(Result.NEW, Result.FORCED).contains(r))
  218. throw new JGitInternalException(MessageFormat.format(
  219. JGitText.get().checkoutUnexpectedResult,
  220. r.name()));
  221. this.status = CheckoutResult.NOT_TRIED_RESULT;
  222. return repo.exactRef(Constants.HEAD);
  223. }
  224. branch = getStartPointObjectId();
  225. } else {
  226. branch = repo.resolve(name);
  227. if (branch == null)
  228. throw new RefNotFoundException(MessageFormat.format(
  229. JGitText.get().refNotResolved, name));
  230. }
  231. RevCommit headCommit = null;
  232. RevCommit newCommit = null;
  233. try (RevWalk revWalk = new RevWalk(repo)) {
  234. AnyObjectId headId = headRef.getObjectId();
  235. headCommit = headId == null ? null
  236. : revWalk.parseCommit(headId);
  237. newCommit = revWalk.parseCommit(branch);
  238. }
  239. RevTree headTree = headCommit == null ? null : headCommit.getTree();
  240. DirCacheCheckout dco;
  241. DirCache dc = repo.lockDirCache();
  242. try {
  243. dco = new DirCacheCheckout(repo, headTree, dc,
  244. newCommit.getTree());
  245. dco.setFailOnConflict(true);
  246. try {
  247. dco.checkout();
  248. } catch (org.eclipse.jgit.errors.CheckoutConflictException e) {
  249. status = new CheckoutResult(Status.CONFLICTS,
  250. dco.getConflicts());
  251. throw new CheckoutConflictException(dco.getConflicts(), e);
  252. }
  253. } finally {
  254. dc.unlock();
  255. }
  256. Ref ref = repo.findRef(name);
  257. if (ref != null && !ref.getName().startsWith(Constants.R_HEADS))
  258. ref = null;
  259. String toName = Repository.shortenRefName(name);
  260. RefUpdate refUpdate = repo.updateRef(Constants.HEAD, ref == null);
  261. refUpdate.setForceUpdate(force);
  262. refUpdate.setRefLogMessage(refLogMessage + " to " + toName, false); //$NON-NLS-1$
  263. Result updateResult;
  264. if (ref != null)
  265. updateResult = refUpdate.link(ref.getName());
  266. else if (orphan) {
  267. updateResult = refUpdate.link(getBranchName());
  268. ref = repo.exactRef(Constants.HEAD);
  269. } else {
  270. refUpdate.setNewObjectId(newCommit);
  271. updateResult = refUpdate.forceUpdate();
  272. }
  273. setCallable(false);
  274. boolean ok = false;
  275. switch (updateResult) {
  276. case NEW:
  277. ok = true;
  278. break;
  279. case NO_CHANGE:
  280. case FAST_FORWARD:
  281. case FORCED:
  282. ok = true;
  283. break;
  284. default:
  285. break;
  286. }
  287. if (!ok)
  288. throw new JGitInternalException(MessageFormat.format(JGitText
  289. .get().checkoutUnexpectedResult, updateResult.name()));
  290. if (!dco.getToBeDeleted().isEmpty()) {
  291. status = new CheckoutResult(Status.NONDELETED,
  292. dco.getToBeDeleted(),
  293. new ArrayList<String>(dco.getUpdated().keySet()),
  294. dco.getRemoved());
  295. } else
  296. status = new CheckoutResult(new ArrayList<String>(dco
  297. .getUpdated().keySet()), dco.getRemoved());
  298. return ref;
  299. } catch (IOException ioe) {
  300. throw new JGitInternalException(ioe.getMessage(), ioe);
  301. } finally {
  302. if (status == null)
  303. status = CheckoutResult.ERROR_RESULT;
  304. }
  305. }
  306. private String getShortBranchName(Ref headRef) {
  307. if (headRef.isSymbolic()) {
  308. return Repository.shortenRefName(headRef.getTarget().getName());
  309. }
  310. // Detached HEAD. Every non-symbolic ref in the ref database has an
  311. // object id, so this cannot be null.
  312. ObjectId id = headRef.getObjectId();
  313. if (id == null) {
  314. throw new NullPointerException();
  315. }
  316. return id.getName();
  317. }
  318. /**
  319. * Add a single slash-separated path to the list of paths to check out. To
  320. * check out all paths, use {@link #setAllPaths(boolean)}.
  321. * <p>
  322. * If this option is set, neither the {@link #setCreateBranch(boolean)} nor
  323. * {@link #setName(String)} option is considered. In other words, these
  324. * options are exclusive.
  325. *
  326. * @param path
  327. * path to update in the working tree and index (with
  328. * <code>/</code> as separator)
  329. * @return {@code this}
  330. */
  331. public CheckoutCommand addPath(String path) {
  332. checkCallable();
  333. this.paths.add(path);
  334. return this;
  335. }
  336. /**
  337. * Set whether to checkout all paths.
  338. * <p>
  339. * This options should be used when you want to do a path checkout on the
  340. * entire repository and so calling {@link #addPath(String)} is not possible
  341. * since empty paths are not allowed.
  342. * <p>
  343. * If this option is set, neither the {@link #setCreateBranch(boolean)} nor
  344. * {@link #setName(String)} option is considered. In other words, these
  345. * options are exclusive.
  346. *
  347. * @param all
  348. * <code>true</code> to checkout all paths, <code>false</code>
  349. * otherwise
  350. * @return {@code this}
  351. * @since 2.0
  352. */
  353. public CheckoutCommand setAllPaths(boolean all) {
  354. checkoutAllPaths = all;
  355. return this;
  356. }
  357. /**
  358. * Checkout paths into index and working directory
  359. *
  360. * @return this instance
  361. * @throws IOException
  362. * @throws RefNotFoundException
  363. */
  364. protected CheckoutCommand checkoutPaths() throws IOException,
  365. RefNotFoundException {
  366. DirCache dc = repo.lockDirCache();
  367. try (RevWalk revWalk = new RevWalk(repo);
  368. TreeWalk treeWalk = new TreeWalk(repo,
  369. revWalk.getObjectReader())) {
  370. treeWalk.setRecursive(true);
  371. if (!checkoutAllPaths)
  372. treeWalk.setFilter(PathFilterGroup.createFromStrings(paths));
  373. if (isCheckoutIndex())
  374. checkoutPathsFromIndex(treeWalk, dc);
  375. else {
  376. RevCommit commit = revWalk.parseCommit(getStartPointObjectId());
  377. checkoutPathsFromCommit(treeWalk, dc, commit);
  378. }
  379. } finally {
  380. dc.unlock();
  381. }
  382. return this;
  383. }
  384. private void checkoutPathsFromIndex(TreeWalk treeWalk, DirCache dc)
  385. throws IOException {
  386. DirCacheIterator dci = new DirCacheIterator(dc);
  387. treeWalk.addTree(dci);
  388. String previousPath = null;
  389. final ObjectReader r = treeWalk.getObjectReader();
  390. DirCacheEditor editor = dc.editor();
  391. while (treeWalk.next()) {
  392. String path = treeWalk.getPathString();
  393. // Only add one edit per path
  394. if (path.equals(previousPath))
  395. continue;
  396. final EolStreamType eolStreamType = treeWalk.getEolStreamType();
  397. final String filterCommand = treeWalk
  398. .getFilterCommand(Constants.ATTR_FILTER_TYPE_SMUDGE);
  399. editor.add(new PathEdit(path) {
  400. public void apply(DirCacheEntry ent) {
  401. int stage = ent.getStage();
  402. if (stage > DirCacheEntry.STAGE_0) {
  403. if (checkoutStage != null) {
  404. if (stage == checkoutStage.number)
  405. checkoutPath(ent, r, new CheckoutMetadata(
  406. eolStreamType, filterCommand));
  407. } else {
  408. UnmergedPathException e = new UnmergedPathException(
  409. ent);
  410. throw new JGitInternalException(e.getMessage(), e);
  411. }
  412. } else {
  413. checkoutPath(ent, r, new CheckoutMetadata(eolStreamType,
  414. filterCommand));
  415. }
  416. }
  417. });
  418. previousPath = path;
  419. }
  420. editor.commit();
  421. }
  422. private void checkoutPathsFromCommit(TreeWalk treeWalk, DirCache dc,
  423. RevCommit commit) throws IOException {
  424. treeWalk.addTree(commit.getTree());
  425. final ObjectReader r = treeWalk.getObjectReader();
  426. DirCacheEditor editor = dc.editor();
  427. while (treeWalk.next()) {
  428. final ObjectId blobId = treeWalk.getObjectId(0);
  429. final FileMode mode = treeWalk.getFileMode(0);
  430. final EolStreamType eolStreamType = treeWalk.getEolStreamType();
  431. final String filterCommand = treeWalk
  432. .getFilterCommand(Constants.ATTR_FILTER_TYPE_SMUDGE);
  433. editor.add(new PathEdit(treeWalk.getPathString()) {
  434. public void apply(DirCacheEntry ent) {
  435. ent.setObjectId(blobId);
  436. ent.setFileMode(mode);
  437. checkoutPath(ent, r,
  438. new CheckoutMetadata(eolStreamType, filterCommand));
  439. }
  440. });
  441. }
  442. editor.commit();
  443. }
  444. private void checkoutPath(DirCacheEntry entry, ObjectReader reader,
  445. CheckoutMetadata checkoutMetadata) {
  446. try {
  447. DirCacheCheckout.checkoutEntry(repo, entry, reader, true,
  448. checkoutMetadata);
  449. } catch (IOException e) {
  450. throw new JGitInternalException(MessageFormat.format(
  451. JGitText.get().checkoutConflictWithFile,
  452. entry.getPathString()), e);
  453. }
  454. }
  455. private boolean isCheckoutIndex() {
  456. return startCommit == null && startPoint == null;
  457. }
  458. private ObjectId getStartPointObjectId() throws AmbiguousObjectException,
  459. RefNotFoundException, IOException {
  460. if (startCommit != null)
  461. return startCommit.getId();
  462. String startPointOrHead = (startPoint != null) ? startPoint
  463. : Constants.HEAD;
  464. ObjectId result = repo.resolve(startPointOrHead);
  465. if (result == null)
  466. throw new RefNotFoundException(MessageFormat.format(
  467. JGitText.get().refNotResolved, startPointOrHead));
  468. return result;
  469. }
  470. private void processOptions() throws InvalidRefNameException,
  471. RefAlreadyExistsException, IOException {
  472. if (((!checkoutAllPaths && paths.isEmpty()) || orphan)
  473. && (name == null || !Repository
  474. .isValidRefName(Constants.R_HEADS + name)))
  475. throw new InvalidRefNameException(MessageFormat.format(JGitText
  476. .get().branchNameInvalid, name == null ? "<null>" : name)); //$NON-NLS-1$
  477. if (orphan) {
  478. Ref refToCheck = repo.exactRef(getBranchName());
  479. if (refToCheck != null)
  480. throw new RefAlreadyExistsException(MessageFormat.format(
  481. JGitText.get().refAlreadyExists, name));
  482. }
  483. }
  484. private String getBranchName() {
  485. if (name.startsWith(Constants.R_REFS))
  486. return name;
  487. return Constants.R_HEADS + name;
  488. }
  489. /**
  490. * Specify the name of the branch or commit to check out, or the new branch
  491. * name.
  492. * <p>
  493. * When only checking out paths and not switching branches, use
  494. * {@link #setStartPoint(String)} or {@link #setStartPoint(RevCommit)} to
  495. * specify from which branch or commit to check out files.
  496. * <p>
  497. * When {@link #setCreateBranch(boolean)} is set to <code>true</code>, use
  498. * this method to set the name of the new branch to create and
  499. * {@link #setStartPoint(String)} or {@link #setStartPoint(RevCommit)} to
  500. * specify the start point of the branch.
  501. *
  502. * @param name
  503. * the name of the branch or commit
  504. * @return this instance
  505. */
  506. public CheckoutCommand setName(String name) {
  507. checkCallable();
  508. this.name = name;
  509. return this;
  510. }
  511. /**
  512. * Specify whether to create a new branch.
  513. * <p>
  514. * If <code>true</code> is used, the name of the new branch must be set
  515. * using {@link #setName(String)}. The commit at which to start the new
  516. * branch can be set using {@link #setStartPoint(String)} or
  517. * {@link #setStartPoint(RevCommit)}; if not specified, HEAD is used. Also
  518. * see {@link #setUpstreamMode} for setting up branch tracking.
  519. *
  520. * @param createBranch
  521. * if <code>true</code> a branch will be created as part of the
  522. * checkout and set to the specified start point
  523. * @return this instance
  524. */
  525. public CheckoutCommand setCreateBranch(boolean createBranch) {
  526. checkCallable();
  527. this.createBranch = createBranch;
  528. return this;
  529. }
  530. /**
  531. * Specify whether to create a new orphan branch.
  532. * <p>
  533. * If <code>true</code> is used, the name of the new orphan branch must be
  534. * set using {@link #setName(String)}. The commit at which to start the new
  535. * orphan branch can be set using {@link #setStartPoint(String)} or
  536. * {@link #setStartPoint(RevCommit)}; if not specified, HEAD is used.
  537. *
  538. * @param orphan
  539. * if <code>true</code> a orphan branch will be created as part
  540. * of the checkout to the specified start point
  541. * @return this instance
  542. * @since 3.3
  543. */
  544. public CheckoutCommand setOrphan(boolean orphan) {
  545. checkCallable();
  546. this.orphan = orphan;
  547. return this;
  548. }
  549. /**
  550. * Specify to force the ref update in case of a branch switch.
  551. *
  552. * @param force
  553. * if <code>true</code> and the branch with the given name
  554. * already exists, the start-point of an existing branch will be
  555. * set to a new start-point; if false, the existing branch will
  556. * not be changed
  557. * @return this instance
  558. */
  559. public CheckoutCommand setForce(boolean force) {
  560. checkCallable();
  561. this.force = force;
  562. return this;
  563. }
  564. /**
  565. * Set the name of the commit that should be checked out.
  566. * <p>
  567. * When checking out files and this is not specified or <code>null</code>,
  568. * the index is used.
  569. * <p>
  570. * When creating a new branch, this will be used as the start point. If not
  571. * specified or <code>null</code>, the current HEAD is used.
  572. *
  573. * @param startPoint
  574. * commit name to check out
  575. * @return this instance
  576. */
  577. public CheckoutCommand setStartPoint(String startPoint) {
  578. checkCallable();
  579. this.startPoint = startPoint;
  580. this.startCommit = null;
  581. checkOptions();
  582. return this;
  583. }
  584. /**
  585. * Set the commit that should be checked out.
  586. * <p>
  587. * When creating a new branch, this will be used as the start point. If not
  588. * specified or <code>null</code>, the current HEAD is used.
  589. * <p>
  590. * When checking out files and this is not specified or <code>null</code>,
  591. * the index is used.
  592. *
  593. * @param startCommit
  594. * commit to check out
  595. * @return this instance
  596. */
  597. public CheckoutCommand setStartPoint(RevCommit startCommit) {
  598. checkCallable();
  599. this.startCommit = startCommit;
  600. this.startPoint = null;
  601. checkOptions();
  602. return this;
  603. }
  604. /**
  605. * When creating a branch with {@link #setCreateBranch(boolean)}, this can
  606. * be used to configure branch tracking.
  607. *
  608. * @param mode
  609. * corresponds to the --track/--no-track options; may be
  610. * <code>null</code>
  611. * @return this instance
  612. */
  613. public CheckoutCommand setUpstreamMode(
  614. CreateBranchCommand.SetupUpstreamMode mode) {
  615. checkCallable();
  616. this.upstreamMode = mode;
  617. return this;
  618. }
  619. /**
  620. * When checking out the index, check out the specified stage (ours or
  621. * theirs) for unmerged paths.
  622. * <p>
  623. * This can not be used when checking out a branch, only when checking out
  624. * the index.
  625. *
  626. * @param stage
  627. * the stage to check out
  628. * @return this
  629. */
  630. public CheckoutCommand setStage(Stage stage) {
  631. checkCallable();
  632. this.checkoutStage = stage;
  633. checkOptions();
  634. return this;
  635. }
  636. /**
  637. * @return the result, never <code>null</code>
  638. */
  639. public CheckoutResult getResult() {
  640. if (status == null)
  641. return CheckoutResult.NOT_TRIED_RESULT;
  642. return status;
  643. }
  644. private void checkOptions() {
  645. if (checkoutStage != null && !isCheckoutIndex())
  646. throw new IllegalStateException(
  647. JGitText.get().cannotCheckoutOursSwitchBranch);
  648. }
  649. }