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

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