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