CheckoutCommand.java

  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. 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.                     ent.setObjectId(blobId);
  461.                     ent.setFileMode(mode);
  462.                     checkoutPath(ent, r,
  463.                             new CheckoutMetadata(eolStreamType, filterCommand));
  464.                     actuallyModifiedPaths.add(path);
  465.                 }
  466.             });
  467.         }
  468.         editor.commit();
  469.     }

  470.     private void checkoutPath(DirCacheEntry entry, ObjectReader reader,
  471.             CheckoutMetadata checkoutMetadata) {
  472.         try {
  473.             DirCacheCheckout.checkoutEntry(repo, entry, reader, true,
  474.                     checkoutMetadata);
  475.         } catch (IOException e) {
  476.             throw new JGitInternalException(MessageFormat.format(
  477.                     JGitText.get().checkoutConflictWithFile,
  478.                     entry.getPathString()), e);
  479.         }
  480.     }

  481.     private boolean isCheckoutIndex() {
  482.         return startCommit == null && startPoint == null;
  483.     }

  484.     private ObjectId getStartPointObjectId() throws AmbiguousObjectException,
  485.             RefNotFoundException, IOException {
  486.         if (startCommit != null)
  487.             return startCommit.getId();

  488.         String startPointOrHead = (startPoint != null) ? startPoint
  489.                 : Constants.HEAD;
  490.         ObjectId result = repo.resolve(startPointOrHead);
  491.         if (result == null)
  492.             throw new RefNotFoundException(MessageFormat.format(
  493.                     JGitText.get().refNotResolved, startPointOrHead));
  494.         return result;
  495.     }

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

  503.         if (orphan) {
  504.             Ref refToCheck = repo.exactRef(getBranchName());
  505.             if (refToCheck != null)
  506.                 throw new RefAlreadyExistsException(MessageFormat.format(
  507.                         JGitText.get().refAlreadyExists, name));
  508.         }
  509.     }

  510.     private String getBranchName() {
  511.         if (name.startsWith(Constants.R_REFS))
  512.             return name;

  513.         return Constants.R_HEADS + name;
  514.     }

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

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

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

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

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

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

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

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

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

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

  704.     /**
  705.      * Get the result, never <code>null</code>
  706.      *
  707.      * @return the result, never <code>null</code>
  708.      */
  709.     public CheckoutResult getResult() {
  710.         if (status == null)
  711.             return CheckoutResult.NOT_TRIED_RESULT;
  712.         return status;
  713.     }

  714.     private void checkOptions() {
  715.         if (checkoutStage != null && !isCheckoutIndex())
  716.             throw new IllegalStateException(
  717.                     JGitText.get().cannotCheckoutOursSwitchBranch);
  718.     }
  719. }