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