CheckoutCommand.java

  1. /*
  2.  * Copyright (C) 2010, Chris Aniszczyk <caniszczyk@gmail.com>
  3.  * Copyright (C) 2011, 2020 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. import static org.eclipse.jgit.treewalk.TreeWalk.OperationType.CHECKOUT_OP;

  13. import java.io.IOException;
  14. import java.text.MessageFormat;
  15. import java.util.ArrayList;
  16. import java.util.EnumSet;
  17. import java.util.HashSet;
  18. import java.util.LinkedList;
  19. import java.util.List;
  20. import java.util.Set;

  21. import org.eclipse.jgit.api.CheckoutResult.Status;
  22. import org.eclipse.jgit.api.errors.CheckoutConflictException;
  23. import org.eclipse.jgit.api.errors.GitAPIException;
  24. import org.eclipse.jgit.api.errors.InvalidRefNameException;
  25. import org.eclipse.jgit.api.errors.JGitInternalException;
  26. import org.eclipse.jgit.api.errors.RefAlreadyExistsException;
  27. import org.eclipse.jgit.api.errors.RefNotFoundException;
  28. import org.eclipse.jgit.dircache.DirCache;
  29. import org.eclipse.jgit.dircache.DirCacheCheckout;
  30. import org.eclipse.jgit.dircache.DirCacheCheckout.CheckoutMetadata;
  31. import org.eclipse.jgit.dircache.DirCacheEditor;
  32. import org.eclipse.jgit.dircache.DirCacheEditor.PathEdit;
  33. import org.eclipse.jgit.dircache.DirCacheEntry;
  34. import org.eclipse.jgit.dircache.DirCacheIterator;
  35. import org.eclipse.jgit.errors.AmbiguousObjectException;
  36. import org.eclipse.jgit.errors.UnmergedPathException;
  37. import org.eclipse.jgit.events.WorkingTreeModifiedEvent;
  38. import org.eclipse.jgit.internal.JGitText;
  39. import org.eclipse.jgit.lib.AnyObjectId;
  40. import org.eclipse.jgit.lib.Constants;
  41. import org.eclipse.jgit.lib.CoreConfig.EolStreamType;
  42. import org.eclipse.jgit.lib.FileMode;
  43. import org.eclipse.jgit.lib.NullProgressMonitor;
  44. import org.eclipse.jgit.lib.ObjectId;
  45. import org.eclipse.jgit.lib.ObjectReader;
  46. import org.eclipse.jgit.lib.ProgressMonitor;
  47. import org.eclipse.jgit.lib.Ref;
  48. import org.eclipse.jgit.lib.RefUpdate;
  49. import org.eclipse.jgit.lib.RefUpdate.Result;
  50. import org.eclipse.jgit.lib.Repository;
  51. import org.eclipse.jgit.revwalk.RevCommit;
  52. import org.eclipse.jgit.revwalk.RevTree;
  53. import org.eclipse.jgit.revwalk.RevWalk;
  54. import org.eclipse.jgit.treewalk.TreeWalk;
  55. import org.eclipse.jgit.treewalk.WorkingTreeOptions;
  56. import org.eclipse.jgit.treewalk.filter.PathFilterGroup;

  57. /**
  58.  * Checkout a branch to the working tree.
  59.  * <p>
  60.  * Examples (<code>git</code> is a {@link org.eclipse.jgit.api.Git} instance):
  61.  * <p>
  62.  * Check out an existing branch:
  63.  *
  64.  * <pre>
  65.  * git.checkout().setName(&quot;feature&quot;).call();
  66.  * </pre>
  67.  * <p>
  68.  * Check out paths from the index:
  69.  *
  70.  * <pre>
  71.  * git.checkout().addPath(&quot;file1.txt&quot;).addPath(&quot;file2.txt&quot;).call();
  72.  * </pre>
  73.  * <p>
  74.  * Check out a path from a commit:
  75.  *
  76.  * <pre>
  77.  * git.checkout().setStartPoint(&quot;HEAD&circ;&quot;).addPath(&quot;file1.txt&quot;).call();
  78.  * </pre>
  79.  *
  80.  * <p>
  81.  * Create a new branch and check it out:
  82.  *
  83.  * <pre>
  84.  * git.checkout().setCreateBranch(true).setName(&quot;newbranch&quot;).call();
  85.  * </pre>
  86.  * <p>
  87.  * Create a new tracking branch for a remote branch and check it out:
  88.  *
  89.  * <pre>
  90.  * git.checkout().setCreateBranch(true).setName(&quot;stable&quot;)
  91.  *      .setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM)
  92.  *      .setStartPoint(&quot;origin/stable&quot;).call();
  93.  * </pre>
  94.  *
  95.  * @see <a href=
  96.  *      "http://www.kernel.org/pub/software/scm/git/docs/git-checkout.html" >Git
  97.  *      documentation about Checkout</a>
  98.  */
  99. public class CheckoutCommand extends GitCommand<Ref> {

  100.     /**
  101.      * Stage to check out, see {@link CheckoutCommand#setStage(Stage)}.
  102.      */
  103.     public enum Stage {
  104.         /**
  105.          * Base stage (#1)
  106.          */
  107.         BASE(DirCacheEntry.STAGE_1),

  108.         /**
  109.          * Ours stage (#2)
  110.          */
  111.         OURS(DirCacheEntry.STAGE_2),

  112.         /**
  113.          * Theirs stage (#3)
  114.          */
  115.         THEIRS(DirCacheEntry.STAGE_3);

  116.         private final int number;

  117.         private Stage(int number) {
  118.             this.number = number;
  119.         }
  120.     }

  121.     private String name;

  122.     private boolean forceRefUpdate = false;

  123.     private boolean forced = false;

  124.     private boolean createBranch = false;

  125.     private boolean orphan = false;

  126.     private CreateBranchCommand.SetupUpstreamMode upstreamMode;

  127.     private String startPoint = null;

  128.     private RevCommit startCommit;

  129.     private Stage checkoutStage = null;

  130.     private CheckoutResult status;

  131.     private List<String> paths;

  132.     private boolean checkoutAllPaths;

  133.     private Set<String> actuallyModifiedPaths;

  134.     private ProgressMonitor monitor = NullProgressMonitor.INSTANCE;

  135.     /**
  136.      * Constructor for CheckoutCommand
  137.      *
  138.      * @param repo
  139.      *            the {@link org.eclipse.jgit.lib.Repository}
  140.      */
  141.     protected CheckoutCommand(Repository repo) {
  142.         super(repo);
  143.         this.paths = new LinkedList<>();
  144.     }

  145.     /** {@inheritDoc} */
  146.     @Override
  147.     public Ref call() throws GitAPIException, RefAlreadyExistsException,
  148.             RefNotFoundException, InvalidRefNameException,
  149.             CheckoutConflictException {
  150.         checkCallable();
  151.         try {
  152.             processOptions();
  153.             if (checkoutAllPaths || !paths.isEmpty()) {
  154.                 checkoutPaths();
  155.                 status = new CheckoutResult(Status.OK, paths);
  156.                 setCallable(false);
  157.                 return null;
  158.             }

  159.             if (createBranch) {
  160.                 try (Git git = new Git(repo)) {
  161.                     CreateBranchCommand command = git.branchCreate();
  162.                     command.setName(name);
  163.                     if (startCommit != null)
  164.                         command.setStartPoint(startCommit);
  165.                     else
  166.                         command.setStartPoint(startPoint);
  167.                     if (upstreamMode != null)
  168.                         command.setUpstreamMode(upstreamMode);
  169.                     command.call();
  170.                 }
  171.             }

  172.             Ref headRef = repo.exactRef(Constants.HEAD);
  173.             if (headRef == null) {
  174.                 // TODO Git CLI supports checkout from unborn branch, we should
  175.                 // also allow this
  176.                 throw new UnsupportedOperationException(
  177.                         JGitText.get().cannotCheckoutFromUnbornBranch);
  178.             }
  179.             String shortHeadRef = getShortBranchName(headRef);
  180.             String refLogMessage = "checkout: moving from " + shortHeadRef; //$NON-NLS-1$
  181.             ObjectId branch;
  182.             if (orphan) {
  183.                 if (startPoint == null && startCommit == null) {
  184.                     Result r = repo.updateRef(Constants.HEAD).link(
  185.                             getBranchName());
  186.                     if (!EnumSet.of(Result.NEW, Result.FORCED).contains(r))
  187.                         throw new JGitInternalException(MessageFormat.format(
  188.                                 JGitText.get().checkoutUnexpectedResult,
  189.                                 r.name()));
  190.                     this.status = CheckoutResult.NOT_TRIED_RESULT;
  191.                     return repo.exactRef(Constants.HEAD);
  192.                 }
  193.                 branch = getStartPointObjectId();
  194.             } else {
  195.                 branch = repo.resolve(name);
  196.                 if (branch == null)
  197.                     throw new RefNotFoundException(MessageFormat.format(
  198.                             JGitText.get().refNotResolved, name));
  199.             }

  200.             RevCommit headCommit = null;
  201.             RevCommit newCommit = null;
  202.             try (RevWalk revWalk = new RevWalk(repo)) {
  203.                 AnyObjectId headId = headRef.getObjectId();
  204.                 headCommit = headId == null ? null
  205.                         : revWalk.parseCommit(headId);
  206.                 newCommit = revWalk.parseCommit(branch);
  207.             }
  208.             RevTree headTree = headCommit == null ? null : headCommit.getTree();
  209.             DirCacheCheckout dco;
  210.             DirCache dc = repo.lockDirCache();
  211.             try {
  212.                 dco = new DirCacheCheckout(repo, headTree, dc,
  213.                         newCommit.getTree());
  214.                 dco.setFailOnConflict(true);
  215.                 dco.setForce(forced);
  216.                 if (forced) {
  217.                     dco.setFailOnConflict(false);
  218.                 }
  219.                 dco.setProgressMonitor(monitor);
  220.                 try {
  221.                     dco.checkout();
  222.                 } catch (org.eclipse.jgit.errors.CheckoutConflictException e) {
  223.                     status = new CheckoutResult(Status.CONFLICTS,
  224.                             dco.getConflicts());
  225.                     throw new CheckoutConflictException(dco.getConflicts(), e);
  226.                 }
  227.             } finally {
  228.                 dc.unlock();
  229.             }
  230.             Ref ref = repo.findRef(name);
  231.             if (ref != null && !ref.getName().startsWith(Constants.R_HEADS))
  232.                 ref = null;
  233.             String toName = Repository.shortenRefName(name);
  234.             RefUpdate refUpdate = repo.updateRef(Constants.HEAD, ref == null);
  235.             refUpdate.setForceUpdate(forceRefUpdate);
  236.             refUpdate.setRefLogMessage(refLogMessage + " to " + toName, false); //$NON-NLS-1$
  237.             Result updateResult;
  238.             if (ref != null)
  239.                 updateResult = refUpdate.link(ref.getName());
  240.             else if (orphan) {
  241.                 updateResult = refUpdate.link(getBranchName());
  242.                 ref = repo.exactRef(Constants.HEAD);
  243.             } else {
  244.                 refUpdate.setNewObjectId(newCommit);
  245.                 updateResult = refUpdate.forceUpdate();
  246.             }

  247.             setCallable(false);

  248.             boolean ok = false;
  249.             switch (updateResult) {
  250.             case NEW:
  251.                 ok = true;
  252.                 break;
  253.             case NO_CHANGE:
  254.             case FAST_FORWARD:
  255.             case FORCED:
  256.                 ok = true;
  257.                 break;
  258.             default:
  259.                 break;
  260.             }

  261.             if (!ok)
  262.                 throw new JGitInternalException(MessageFormat.format(JGitText
  263.                         .get().checkoutUnexpectedResult, updateResult.name()));


  264.             if (!dco.getToBeDeleted().isEmpty()) {
  265.                 status = new CheckoutResult(Status.NONDELETED,
  266.                         dco.getToBeDeleted(),
  267.                         new ArrayList<>(dco.getUpdated().keySet()),
  268.                         dco.getRemoved());
  269.             } else
  270.                 status = new CheckoutResult(new ArrayList<>(dco
  271.                         .getUpdated().keySet()), dco.getRemoved());

  272.             return ref;
  273.         } catch (IOException ioe) {
  274.             throw new JGitInternalException(ioe.getMessage(), ioe);
  275.         } finally {
  276.             if (status == null)
  277.                 status = CheckoutResult.ERROR_RESULT;
  278.         }
  279.     }

  280.     private String getShortBranchName(Ref headRef) {
  281.         if (headRef.isSymbolic()) {
  282.             return Repository.shortenRefName(headRef.getTarget().getName());
  283.         }
  284.         // Detached HEAD. Every non-symbolic ref in the ref database has an
  285.         // object id, so this cannot be null.
  286.         ObjectId id = headRef.getObjectId();
  287.         if (id == null) {
  288.             throw new NullPointerException();
  289.         }
  290.         return id.getName();
  291.     }

  292.     /**
  293.      * @param monitor
  294.      *            a progress monitor
  295.      * @return this instance
  296.      * @since 4.11
  297.      */
  298.     public CheckoutCommand setProgressMonitor(ProgressMonitor monitor) {
  299.         if (monitor == null) {
  300.             monitor = NullProgressMonitor.INSTANCE;
  301.         }
  302.         this.monitor = monitor;
  303.         return this;
  304.     }

  305.     /**
  306.      * Add a single slash-separated path to the list of paths to check out. To
  307.      * check out all paths, use {@link #setAllPaths(boolean)}.
  308.      * <p>
  309.      * If this option is set, neither the {@link #setCreateBranch(boolean)} nor
  310.      * {@link #setName(String)} option is considered. In other words, these
  311.      * options are exclusive.
  312.      *
  313.      * @param path
  314.      *            path to update in the working tree and index (with
  315.      *            <code>/</code> as separator)
  316.      * @return {@code this}
  317.      */
  318.     public CheckoutCommand addPath(String path) {
  319.         checkCallable();
  320.         this.paths.add(path);
  321.         return this;
  322.     }

  323.     /**
  324.      * Add multiple slash-separated paths to the list of paths to check out. To
  325.      * check out all paths, use {@link #setAllPaths(boolean)}.
  326.      * <p>
  327.      * If this option is set, neither the {@link #setCreateBranch(boolean)} nor
  328.      * {@link #setName(String)} option is considered. In other words, these
  329.      * options are exclusive.
  330.      *
  331.      * @param p
  332.      *            paths to update in the working tree and index (with
  333.      *            <code>/</code> as separator)
  334.      * @return {@code this}
  335.      * @since 4.6
  336.      */
  337.     public CheckoutCommand addPaths(List<String> p) {
  338.         checkCallable();
  339.         this.paths.addAll(p);
  340.         return this;
  341.     }

  342.     /**
  343.      * Set whether to checkout all paths.
  344.      * <p>
  345.      * This options should be used when you want to do a path checkout on the
  346.      * entire repository and so calling {@link #addPath(String)} is not possible
  347.      * since empty paths are not allowed.
  348.      * <p>
  349.      * If this option is set, neither the {@link #setCreateBranch(boolean)} nor
  350.      * {@link #setName(String)} option is considered. In other words, these
  351.      * options are exclusive.
  352.      *
  353.      * @param all
  354.      *            <code>true</code> to checkout all paths, <code>false</code>
  355.      *            otherwise
  356.      * @return {@code this}
  357.      * @since 2.0
  358.      */
  359.     public CheckoutCommand setAllPaths(boolean all) {
  360.         checkoutAllPaths = all;
  361.         return this;
  362.     }

  363.     /**
  364.      * Checkout paths into index and working directory, firing a
  365.      * {@link org.eclipse.jgit.events.WorkingTreeModifiedEvent} if the working
  366.      * tree was modified.
  367.      *
  368.      * @return this instance
  369.      * @throws java.io.IOException
  370.      * @throws org.eclipse.jgit.api.errors.RefNotFoundException
  371.      */
  372.     protected CheckoutCommand checkoutPaths() throws IOException,
  373.             RefNotFoundException {
  374.         actuallyModifiedPaths = new HashSet<>();
  375.         WorkingTreeOptions options = repo.getConfig()
  376.                 .get(WorkingTreeOptions.KEY);
  377.         DirCache dc = repo.lockDirCache();
  378.         try (RevWalk revWalk = new RevWalk(repo);
  379.                 TreeWalk treeWalk = new TreeWalk(repo,
  380.                         revWalk.getObjectReader())) {
  381.             treeWalk.setRecursive(true);
  382.             if (!checkoutAllPaths)
  383.                 treeWalk.setFilter(PathFilterGroup.createFromStrings(paths));
  384.             if (isCheckoutIndex())
  385.                 checkoutPathsFromIndex(treeWalk, dc, options);
  386.             else {
  387.                 RevCommit commit = revWalk.parseCommit(getStartPointObjectId());
  388.                 checkoutPathsFromCommit(treeWalk, dc, commit, options);
  389.             }
  390.         } finally {
  391.             try {
  392.                 dc.unlock();
  393.             } finally {
  394.                 WorkingTreeModifiedEvent event = new WorkingTreeModifiedEvent(
  395.                         actuallyModifiedPaths, null);
  396.                 actuallyModifiedPaths = null;
  397.                 if (!event.isEmpty()) {
  398.                     repo.fireEvent(event);
  399.                 }
  400.             }
  401.         }
  402.         return this;
  403.     }

  404.     private void checkoutPathsFromIndex(TreeWalk treeWalk, DirCache dc,
  405.             WorkingTreeOptions options)
  406.             throws IOException {
  407.         DirCacheIterator dci = new DirCacheIterator(dc);
  408.         treeWalk.addTree(dci);

  409.         String previousPath = null;

  410.         final ObjectReader r = treeWalk.getObjectReader();
  411.         DirCacheEditor editor = dc.editor();
  412.         while (treeWalk.next()) {
  413.             String path = treeWalk.getPathString();
  414.             // Only add one edit per path
  415.             if (path.equals(previousPath))
  416.                 continue;

  417.             final EolStreamType eolStreamType = treeWalk
  418.                     .getEolStreamType(CHECKOUT_OP);
  419.             final String filterCommand = treeWalk
  420.                     .getFilterCommand(Constants.ATTR_FILTER_TYPE_SMUDGE);
  421.             editor.add(new PathEdit(path) {
  422.                 @Override
  423.                 public void apply(DirCacheEntry ent) {
  424.                     int stage = ent.getStage();
  425.                     if (stage > DirCacheEntry.STAGE_0) {
  426.                         if (checkoutStage != null) {
  427.                             if (stage == checkoutStage.number) {
  428.                                 checkoutPath(ent, r, options,
  429.                                         new CheckoutMetadata(eolStreamType,
  430.                                                 filterCommand));
  431.                                 actuallyModifiedPaths.add(path);
  432.                             }
  433.                         } else {
  434.                             UnmergedPathException e = new UnmergedPathException(
  435.                                     ent);
  436.                             throw new JGitInternalException(e.getMessage(), e);
  437.                         }
  438.                     } else {
  439.                         checkoutPath(ent, r, options,
  440.                                 new CheckoutMetadata(eolStreamType,
  441.                                         filterCommand));
  442.                         actuallyModifiedPaths.add(path);
  443.                     }
  444.                 }
  445.             });

  446.             previousPath = path;
  447.         }
  448.         editor.commit();
  449.     }

  450.     private void checkoutPathsFromCommit(TreeWalk treeWalk, DirCache dc,
  451.             RevCommit commit, WorkingTreeOptions options) throws IOException {
  452.         treeWalk.addTree(commit.getTree());
  453.         final ObjectReader r = treeWalk.getObjectReader();
  454.         DirCacheEditor editor = dc.editor();
  455.         while (treeWalk.next()) {
  456.             final ObjectId blobId = treeWalk.getObjectId(0);
  457.             final FileMode mode = treeWalk.getFileMode(0);
  458.             final EolStreamType eolStreamType = treeWalk
  459.                     .getEolStreamType(CHECKOUT_OP);
  460.             final String filterCommand = treeWalk
  461.                     .getFilterCommand(Constants.ATTR_FILTER_TYPE_SMUDGE);
  462.             final String path = treeWalk.getPathString();
  463.             editor.add(new PathEdit(path) {
  464.                 @Override
  465.                 public void apply(DirCacheEntry ent) {
  466.                     if (ent.getStage() != DirCacheEntry.STAGE_0) {
  467.                         // A checkout on a conflicting file stages the checked
  468.                         // out file and resolves the conflict.
  469.                         ent.setStage(DirCacheEntry.STAGE_0);
  470.                     }
  471.                     ent.setObjectId(blobId);
  472.                     ent.setFileMode(mode);
  473.                     checkoutPath(ent, r, options,
  474.                             new CheckoutMetadata(eolStreamType, filterCommand));
  475.                     actuallyModifiedPaths.add(path);
  476.                 }
  477.             });
  478.         }
  479.         editor.commit();
  480.     }

  481.     private void checkoutPath(DirCacheEntry entry, ObjectReader reader,
  482.             WorkingTreeOptions options, CheckoutMetadata checkoutMetadata) {
  483.         try {
  484.             DirCacheCheckout.checkoutEntry(repo, entry, reader, true,
  485.                     checkoutMetadata, options);
  486.         } catch (IOException e) {
  487.             throw new JGitInternalException(MessageFormat.format(
  488.                     JGitText.get().checkoutConflictWithFile,
  489.                     entry.getPathString()), e);
  490.         }
  491.     }

  492.     private boolean isCheckoutIndex() {
  493.         return startCommit == null && startPoint == null;
  494.     }

  495.     private ObjectId getStartPointObjectId() throws AmbiguousObjectException,
  496.             RefNotFoundException, IOException {
  497.         if (startCommit != null)
  498.             return startCommit.getId();

  499.         String startPointOrHead = (startPoint != null) ? startPoint
  500.                 : Constants.HEAD;
  501.         ObjectId result = repo.resolve(startPointOrHead);
  502.         if (result == null)
  503.             throw new RefNotFoundException(MessageFormat.format(
  504.                     JGitText.get().refNotResolved, startPointOrHead));
  505.         return result;
  506.     }

  507.     private void processOptions() throws InvalidRefNameException,
  508.             RefAlreadyExistsException, IOException {
  509.         if (((!checkoutAllPaths && paths.isEmpty()) || orphan)
  510.                 && (name == null || !Repository
  511.                         .isValidRefName(Constants.R_HEADS + name)))
  512.             throw new InvalidRefNameException(MessageFormat.format(JGitText
  513.                     .get().branchNameInvalid, name == null ? "<null>" : name)); //$NON-NLS-1$

  514.         if (orphan) {
  515.             Ref refToCheck = repo.exactRef(getBranchName());
  516.             if (refToCheck != null)
  517.                 throw new RefAlreadyExistsException(MessageFormat.format(
  518.                         JGitText.get().refAlreadyExists, name));
  519.         }
  520.     }

  521.     private String getBranchName() {
  522.         if (name.startsWith(Constants.R_REFS))
  523.             return name;

  524.         return Constants.R_HEADS + name;
  525.     }

  526.     /**
  527.      * Specify the name of the branch or commit to check out, or the new branch
  528.      * name.
  529.      * <p>
  530.      * When only checking out paths and not switching branches, use
  531.      * {@link #setStartPoint(String)} or {@link #setStartPoint(RevCommit)} to
  532.      * specify from which branch or commit to check out files.
  533.      * <p>
  534.      * When {@link #setCreateBranch(boolean)} is set to <code>true</code>, use
  535.      * this method to set the name of the new branch to create and
  536.      * {@link #setStartPoint(String)} or {@link #setStartPoint(RevCommit)} to
  537.      * specify the start point of the branch.
  538.      *
  539.      * @param name
  540.      *            the name of the branch or commit
  541.      * @return this instance
  542.      */
  543.     public CheckoutCommand setName(String name) {
  544.         checkCallable();
  545.         this.name = name;
  546.         return this;
  547.     }

  548.     /**
  549.      * Specify whether to create a new branch.
  550.      * <p>
  551.      * If <code>true</code> is used, the name of the new branch must be set
  552.      * using {@link #setName(String)}. The commit at which to start the new
  553.      * branch can be set using {@link #setStartPoint(String)} or
  554.      * {@link #setStartPoint(RevCommit)}; if not specified, HEAD is used. Also
  555.      * see {@link #setUpstreamMode} for setting up branch tracking.
  556.      *
  557.      * @param createBranch
  558.      *            if <code>true</code> a branch will be created as part of the
  559.      *            checkout and set to the specified start point
  560.      * @return this instance
  561.      */
  562.     public CheckoutCommand setCreateBranch(boolean createBranch) {
  563.         checkCallable();
  564.         this.createBranch = createBranch;
  565.         return this;
  566.     }

  567.     /**
  568.      * Specify whether to create a new orphan branch.
  569.      * <p>
  570.      * If <code>true</code> is used, the name of the new orphan branch must be
  571.      * set using {@link #setName(String)}. The commit at which to start the new
  572.      * orphan branch can be set using {@link #setStartPoint(String)} or
  573.      * {@link #setStartPoint(RevCommit)}; if not specified, HEAD is used.
  574.      *
  575.      * @param orphan
  576.      *            if <code>true</code> a orphan branch will be created as part
  577.      *            of the checkout to the specified start point
  578.      * @return this instance
  579.      * @since 3.3
  580.      */
  581.     public CheckoutCommand setOrphan(boolean orphan) {
  582.         checkCallable();
  583.         this.orphan = orphan;
  584.         return this;
  585.     }

  586.     /**
  587.      * Specify to force the ref update in case of a branch switch.
  588.      *
  589.      * @param force
  590.      *            if <code>true</code> and the branch with the given name
  591.      *            already exists, the start-point of an existing branch will be
  592.      *            set to a new start-point; if false, the existing branch will
  593.      *            not be changed
  594.      * @return this instance
  595.      * @deprecated this method was badly named comparing its semantics to native
  596.      *             git's checkout --force option, use
  597.      *             {@link #setForceRefUpdate(boolean)} instead
  598.      */
  599.     @Deprecated
  600.     public CheckoutCommand setForce(boolean force) {
  601.         return setForceRefUpdate(force);
  602.     }

  603.     /**
  604.      * Specify to force the ref update in case of a branch switch.
  605.      *
  606.      * In releases prior to 5.2 this method was called setForce() but this name
  607.      * was misunderstood to implement native git's --force option, which is not
  608.      * true.
  609.      *
  610.      * @param forceRefUpdate
  611.      *            if <code>true</code> and the branch with the given name
  612.      *            already exists, the start-point of an existing branch will be
  613.      *            set to a new start-point; if false, the existing branch will
  614.      *            not be changed
  615.      * @return this instance
  616.      * @since 5.3
  617.      */
  618.     public CheckoutCommand setForceRefUpdate(boolean forceRefUpdate) {
  619.         checkCallable();
  620.         this.forceRefUpdate = forceRefUpdate;
  621.         return this;
  622.     }

  623.     /**
  624.      * Allow a checkout even if the workingtree or index differs from HEAD. This
  625.      * matches native git's '--force' option.
  626.      *
  627.      * JGit releases before 5.2 had a method <code>setForce()</code> offering
  628.      * semantics different from this new <code>setForced()</code>. This old
  629.      * semantic can now be found in {@link #setForceRefUpdate(boolean)}
  630.      *
  631.      * @param forced
  632.      *            if set to <code>true</code> then allow the checkout even if
  633.      *            workingtree or index doesn't match HEAD. Overwrite workingtree
  634.      *            files and index content with the new content in this case.
  635.      * @return this instance
  636.      * @since 5.3
  637.      */
  638.     public CheckoutCommand setForced(boolean forced) {
  639.         checkCallable();
  640.         this.forced = forced;
  641.         return this;
  642.     }

  643.     /**
  644.      * Set the name of the commit that should be checked out.
  645.      * <p>
  646.      * When checking out files and this is not specified or <code>null</code>,
  647.      * the index is used.
  648.      * <p>
  649.      * When creating a new branch, this will be used as the start point. If not
  650.      * specified or <code>null</code>, the current HEAD is used.
  651.      *
  652.      * @param startPoint
  653.      *            commit name to check out
  654.      * @return this instance
  655.      */
  656.     public CheckoutCommand setStartPoint(String startPoint) {
  657.         checkCallable();
  658.         this.startPoint = startPoint;
  659.         this.startCommit = null;
  660.         checkOptions();
  661.         return this;
  662.     }

  663.     /**
  664.      * Set the commit that should be checked out.
  665.      * <p>
  666.      * When creating a new branch, this will be used as the start point. If not
  667.      * specified or <code>null</code>, the current HEAD is used.
  668.      * <p>
  669.      * When checking out files and this is not specified or <code>null</code>,
  670.      * the index is used.
  671.      *
  672.      * @param startCommit
  673.      *            commit to check out
  674.      * @return this instance
  675.      */
  676.     public CheckoutCommand setStartPoint(RevCommit startCommit) {
  677.         checkCallable();
  678.         this.startCommit = startCommit;
  679.         this.startPoint = null;
  680.         checkOptions();
  681.         return this;
  682.     }

  683.     /**
  684.      * When creating a branch with {@link #setCreateBranch(boolean)}, this can
  685.      * be used to configure branch tracking.
  686.      *
  687.      * @param mode
  688.      *            corresponds to the --track/--no-track options; may be
  689.      *            <code>null</code>
  690.      * @return this instance
  691.      */
  692.     public CheckoutCommand setUpstreamMode(
  693.             CreateBranchCommand.SetupUpstreamMode mode) {
  694.         checkCallable();
  695.         this.upstreamMode = mode;
  696.         return this;
  697.     }

  698.     /**
  699.      * When checking out the index, check out the specified stage (ours or
  700.      * theirs) for unmerged paths.
  701.      * <p>
  702.      * This can not be used when checking out a branch, only when checking out
  703.      * the index.
  704.      *
  705.      * @param stage
  706.      *            the stage to check out
  707.      * @return this
  708.      */
  709.     public CheckoutCommand setStage(Stage stage) {
  710.         checkCallable();
  711.         this.checkoutStage = stage;
  712.         checkOptions();
  713.         return this;
  714.     }

  715.     /**
  716.      * Get the result, never <code>null</code>
  717.      *
  718.      * @return the result, never <code>null</code>
  719.      */
  720.     public CheckoutResult getResult() {
  721.         if (status == null)
  722.             return CheckoutResult.NOT_TRIED_RESULT;
  723.         return status;
  724.     }

  725.     private void checkOptions() {
  726.         if (checkoutStage != null && !isCheckoutIndex())
  727.             throw new IllegalStateException(
  728.                     JGitText.get().cannotCheckoutOursSwitchBranch);
  729.     }
  730. }