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

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