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