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.filter.PathFilterGroup;

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

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

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

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

  115.         private final int number;

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

  120.     private String name;

  121.     private boolean forceRefUpdate = false;

  122.     private boolean forced = false;

  123.     private boolean createBranch = false;

  124.     private boolean orphan = false;

  125.     private CreateBranchCommand.SetupUpstreamMode upstreamMode;

  126.     private String startPoint = null;

  127.     private RevCommit startCommit;

  128.     private Stage checkoutStage = null;

  129.     private CheckoutResult status;

  130.     private List<String> paths;

  131.     private boolean checkoutAllPaths;

  132.     private Set<String> actuallyModifiedPaths;

  133.     private ProgressMonitor monitor = NullProgressMonitor.INSTANCE;

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

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

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

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

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

  246.             setCallable(false);

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

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


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

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

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

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

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

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

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

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

  401.     private void checkoutPathsFromIndex(TreeWalk treeWalk, DirCache dc)
  402.             throws IOException {
  403.         DirCacheIterator dci = new DirCacheIterator(dc);
  404.         treeWalk.addTree(dci);

  405.         String previousPath = null;

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

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

  440.             previousPath = path;
  441.         }
  442.         editor.commit();
  443.     }

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

  475.     private void checkoutPath(DirCacheEntry entry, ObjectReader reader,
  476.             CheckoutMetadata checkoutMetadata) {
  477.         try {
  478.             DirCacheCheckout.checkoutEntry(repo, entry, reader, true,
  479.                     checkoutMetadata);
  480.         } catch (IOException e) {
  481.             throw new JGitInternalException(MessageFormat.format(
  482.                     JGitText.get().checkoutConflictWithFile,
  483.                     entry.getPathString()), e);
  484.         }
  485.     }

  486.     private boolean isCheckoutIndex() {
  487.         return startCommit == null && startPoint == null;
  488.     }

  489.     private ObjectId getStartPointObjectId() throws AmbiguousObjectException,
  490.             RefNotFoundException, IOException {
  491.         if (startCommit != null)
  492.             return startCommit.getId();

  493.         String startPointOrHead = (startPoint != null) ? startPoint
  494.                 : Constants.HEAD;
  495.         ObjectId result = repo.resolve(startPointOrHead);
  496.         if (result == null)
  497.             throw new RefNotFoundException(MessageFormat.format(
  498.                     JGitText.get().refNotResolved, startPointOrHead));
  499.         return result;
  500.     }

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

  508.         if (orphan) {
  509.             Ref refToCheck = repo.exactRef(getBranchName());
  510.             if (refToCheck != null)
  511.                 throw new RefAlreadyExistsException(MessageFormat.format(
  512.                         JGitText.get().refAlreadyExists, name));
  513.         }
  514.     }

  515.     private String getBranchName() {
  516.         if (name.startsWith(Constants.R_REFS))
  517.             return name;

  518.         return Constants.R_HEADS + name;
  519.     }

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

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

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

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

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

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

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

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

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

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

  709.     /**
  710.      * Get the result, never <code>null</code>
  711.      *
  712.      * @return the result, never <code>null</code>
  713.      */
  714.     public CheckoutResult getResult() {
  715.         if (status == null)
  716.             return CheckoutResult.NOT_TRIED_RESULT;
  717.         return status;
  718.     }

  719.     private void checkOptions() {
  720.         if (checkoutStage != null && !isCheckoutIndex())
  721.             throw new IllegalStateException(
  722.                     JGitText.get().cannotCheckoutOursSwitchBranch);
  723.     }
  724. }