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