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