CloneCommand.java

  1. /*
  2.  * Copyright (C) 2011, 2022 Chris Aniszczyk <caniszczyk@gmail.com> and others
  3.  *
  4.  * This program and the accompanying materials are made available under the
  5.  * terms of the Eclipse Distribution License v. 1.0 which is available at
  6.  * https://www.eclipse.org/org/documents/edl-v10.php.
  7.  *
  8.  * SPDX-License-Identifier: BSD-3-Clause
  9.  */
  10. package org.eclipse.jgit.api;

  11. import java.io.File;
  12. import java.io.IOException;
  13. import java.net.URISyntaxException;
  14. import java.text.MessageFormat;
  15. import java.time.Instant;
  16. import java.time.OffsetDateTime;
  17. import java.util.ArrayList;
  18. import java.util.Collection;
  19. import java.util.List;

  20. import org.eclipse.jgit.annotations.NonNull;
  21. import org.eclipse.jgit.annotations.Nullable;
  22. import org.eclipse.jgit.api.errors.GitAPIException;
  23. import org.eclipse.jgit.api.errors.InvalidRemoteException;
  24. import org.eclipse.jgit.api.errors.JGitInternalException;
  25. import org.eclipse.jgit.dircache.DirCache;
  26. import org.eclipse.jgit.dircache.DirCacheCheckout;
  27. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  28. import org.eclipse.jgit.errors.MissingObjectException;
  29. import org.eclipse.jgit.internal.JGitText;
  30. import org.eclipse.jgit.lib.AnyObjectId;
  31. import org.eclipse.jgit.lib.BranchConfig.BranchRebaseMode;
  32. import org.eclipse.jgit.lib.ConfigConstants;
  33. import org.eclipse.jgit.lib.Constants;
  34. import org.eclipse.jgit.lib.NullProgressMonitor;
  35. import org.eclipse.jgit.lib.ObjectId;
  36. import org.eclipse.jgit.lib.ProgressMonitor;
  37. import org.eclipse.jgit.lib.Ref;
  38. import org.eclipse.jgit.lib.RefUpdate;
  39. import org.eclipse.jgit.lib.Repository;
  40. import org.eclipse.jgit.revwalk.RevCommit;
  41. import org.eclipse.jgit.revwalk.RevWalk;
  42. import org.eclipse.jgit.submodule.SubmoduleWalk;
  43. import org.eclipse.jgit.transport.FetchResult;
  44. import org.eclipse.jgit.transport.RefSpec;
  45. import org.eclipse.jgit.transport.RemoteConfig;
  46. import org.eclipse.jgit.transport.TagOpt;
  47. import org.eclipse.jgit.transport.URIish;
  48. import org.eclipse.jgit.util.FS;
  49. import org.eclipse.jgit.util.FileUtils;

  50. /**
  51.  * Clone a repository into a new working directory
  52.  *
  53.  * @see <a href="http://www.kernel.org/pub/software/scm/git/docs/git-clone.html"
  54.  *      >Git documentation about Clone</a>
  55.  */
  56. public class CloneCommand extends TransportCommand<CloneCommand, Git> {

  57.     private String uri;

  58.     private File directory;

  59.     private File gitDir;

  60.     private boolean bare;

  61.     private FS fs;

  62.     private String remote = Constants.DEFAULT_REMOTE_NAME;

  63.     private String branch = Constants.HEAD;

  64.     private ProgressMonitor monitor = NullProgressMonitor.INSTANCE;

  65.     private boolean cloneAllBranches;

  66.     private boolean mirror;

  67.     private boolean cloneSubmodules;

  68.     private boolean noCheckout;

  69.     private Collection<String> branchesToClone;

  70.     private Callback callback;

  71.     private boolean directoryExistsInitially;

  72.     private boolean gitDirExistsInitially;

  73.     private FETCH_TYPE fetchType;

  74.     private TagOpt tagOption;

  75.     private Integer depth;

  76.     private Instant shallowSince;

  77.     private List<String> shallowExcludes = new ArrayList<>();

  78.     private enum FETCH_TYPE {
  79.         MULTIPLE_BRANCHES, ALL_BRANCHES, MIRROR
  80.     }

  81.     /**
  82.      * Callback for status of clone operation.
  83.      *
  84.      * @since 4.8
  85.      */
  86.     public interface Callback {
  87.         /**
  88.          * Notify initialized submodules.
  89.          *
  90.          * @param submodules
  91.          *            the submodules
  92.          *
  93.          */
  94.         void initializedSubmodules(Collection<String> submodules);

  95.         /**
  96.          * Notify starting to clone a submodule.
  97.          *
  98.          * @param path
  99.          *            the submodule path
  100.          */
  101.         void cloningSubmodule(String path);

  102.         /**
  103.          * Notify checkout of commit
  104.          *
  105.          * @param commit
  106.          *            the id of the commit being checked out
  107.          * @param path
  108.          *            the submodule path
  109.          */
  110.         void checkingOut(AnyObjectId commit, String path);
  111.     }

  112.     /**
  113.      * Create clone command with no repository set
  114.      */
  115.     public CloneCommand() {
  116.         super(null);
  117.     }

  118.     /**
  119.      * Get the git directory. This is primarily used for tests.
  120.      *
  121.      * @return the git directory
  122.      */
  123.     @Nullable
  124.     File getDirectory() {
  125.         return directory;
  126.     }

  127.     /**
  128.      * {@inheritDoc}
  129.      * <p>
  130.      * Executes the {@code Clone} command.
  131.      *
  132.      * The Git instance returned by this command needs to be closed by the
  133.      * caller to free resources held by the underlying {@link Repository}
  134.      * instance. It is recommended to call this method as soon as you don't need
  135.      * a reference to this {@link Git} instance and the underlying
  136.      * {@link Repository} instance anymore.
  137.      */
  138.     @Override
  139.     public Git call() throws GitAPIException, InvalidRemoteException,
  140.             org.eclipse.jgit.api.errors.TransportException {
  141.         URIish u = null;
  142.         try {
  143.             u = new URIish(uri);
  144.             verifyDirectories(u);
  145.         } catch (URISyntaxException e) {
  146.             throw new InvalidRemoteException(
  147.                     MessageFormat.format(JGitText.get().invalidURL, uri), e);
  148.         }
  149.         setFetchType();
  150.         @SuppressWarnings("resource") // Closed by caller
  151.         Repository repository = init();
  152.         FetchResult fetchResult = null;
  153.         Thread cleanupHook = new Thread(() -> cleanup());
  154.         try {
  155.             Runtime.getRuntime().addShutdownHook(cleanupHook);
  156.         } catch (IllegalStateException e) {
  157.             // ignore - the VM is already shutting down
  158.         }
  159.         try {
  160.             fetchResult = fetch(repository, u);
  161.         } catch (IOException ioe) {
  162.             if (repository != null) {
  163.                 repository.close();
  164.             }
  165.             cleanup();
  166.             throw new JGitInternalException(ioe.getMessage(), ioe);
  167.         } catch (URISyntaxException e) {
  168.             if (repository != null) {
  169.                 repository.close();
  170.             }
  171.             cleanup();
  172.             throw new InvalidRemoteException(
  173.                     MessageFormat.format(JGitText.get().invalidRemote, remote),
  174.                     e);
  175.         } catch (GitAPIException | RuntimeException e) {
  176.             if (repository != null) {
  177.                 repository.close();
  178.             }
  179.             cleanup();
  180.             throw e;
  181.         } finally {
  182.             try {
  183.                 Runtime.getRuntime().removeShutdownHook(cleanupHook);
  184.             } catch (IllegalStateException e) {
  185.                 // ignore - the VM is already shutting down
  186.             }
  187.         }
  188.         try {
  189.             checkout(repository, fetchResult);
  190.         } catch (IOException ioe) {
  191.             repository.close();
  192.             throw new JGitInternalException(ioe.getMessage(), ioe);
  193.         } catch (GitAPIException | RuntimeException e) {
  194.             repository.close();
  195.             throw e;
  196.         }
  197.         return new Git(repository, true);
  198.     }

  199.     private void setFetchType() {
  200.         if (mirror) {
  201.             fetchType = FETCH_TYPE.MIRROR;
  202.             setBare(true);
  203.         } else if (cloneAllBranches) {
  204.             fetchType = FETCH_TYPE.ALL_BRANCHES;
  205.         } else if (branchesToClone != null && !branchesToClone.isEmpty()) {
  206.             fetchType = FETCH_TYPE.MULTIPLE_BRANCHES;
  207.         } else {
  208.             // Default: neither mirror nor all nor specific refs given
  209.             fetchType = FETCH_TYPE.ALL_BRANCHES;
  210.         }
  211.     }

  212.     private static boolean isNonEmptyDirectory(File dir) {
  213.         if (dir != null && dir.exists()) {
  214.             File[] files = dir.listFiles();
  215.             return files != null && files.length != 0;
  216.         }
  217.         return false;
  218.     }

  219.     void verifyDirectories(URIish u) {
  220.         if (directory == null && gitDir == null) {
  221.             directory = new File(u.getHumanishName() + (bare ? Constants.DOT_GIT_EXT : "")); //$NON-NLS-1$
  222.         }
  223.         directoryExistsInitially = directory != null && directory.exists();
  224.         gitDirExistsInitially = gitDir != null && gitDir.exists();
  225.         validateDirs(directory, gitDir, bare);
  226.         if (isNonEmptyDirectory(directory)) {
  227.             throw new JGitInternalException(MessageFormat.format(
  228.                     JGitText.get().cloneNonEmptyDirectory, directory.getName()));
  229.         }
  230.         if (isNonEmptyDirectory(gitDir)) {
  231.             throw new JGitInternalException(MessageFormat.format(
  232.                     JGitText.get().cloneNonEmptyDirectory, gitDir.getName()));
  233.         }
  234.     }

  235.     private Repository init() throws GitAPIException {
  236.         InitCommand command = Git.init();
  237.         command.setBare(bare);
  238.         if (fs != null) {
  239.             command.setFs(fs);
  240.         }
  241.         if (directory != null) {
  242.             command.setDirectory(directory);
  243.         }
  244.         if (gitDir != null) {
  245.             command.setGitDir(gitDir);
  246.         }
  247.         return command.call().getRepository();
  248.     }

  249.     private FetchResult fetch(Repository clonedRepo, URIish u)
  250.             throws URISyntaxException,
  251.             org.eclipse.jgit.api.errors.TransportException, IOException,
  252.             GitAPIException {
  253.         // create the remote config and save it
  254.         RemoteConfig config = new RemoteConfig(clonedRepo.getConfig(), remote);
  255.         config.addURI(u);

  256.         boolean fetchAll = fetchType == FETCH_TYPE.ALL_BRANCHES
  257.                 || fetchType == FETCH_TYPE.MIRROR;

  258.         config.setFetchRefSpecs(calculateRefSpecs(fetchType, config.getName()));
  259.         config.setMirror(fetchType == FETCH_TYPE.MIRROR);
  260.         if (tagOption != null) {
  261.             config.setTagOpt(tagOption);
  262.         }
  263.         config.update(clonedRepo.getConfig());

  264.         clonedRepo.getConfig().save();

  265.         // run the fetch command
  266.         FetchCommand command = new FetchCommand(clonedRepo);
  267.         command.setRemote(remote);
  268.         command.setProgressMonitor(monitor);
  269.         if (tagOption != null) {
  270.             command.setTagOpt(tagOption);
  271.         } else {
  272.             command.setTagOpt(
  273.                     fetchAll ? TagOpt.FETCH_TAGS : TagOpt.AUTO_FOLLOW);
  274.         }
  275.         command.setInitialBranch(branch);
  276.         if (depth != null) {
  277.             command.setDepth(depth.intValue());
  278.         }
  279.         if (shallowSince != null) {
  280.             command.setShallowSince(shallowSince);
  281.         }
  282.         command.setShallowExcludes(shallowExcludes);
  283.         configure(command);

  284.         return command.call();
  285.     }

  286.     private List<RefSpec> calculateRefSpecs(FETCH_TYPE type,
  287.             String remoteName) {
  288.         List<RefSpec> specs = new ArrayList<>();
  289.         if (type == FETCH_TYPE.MIRROR) {
  290.             specs.add(new RefSpec().setForceUpdate(true).setSourceDestination(
  291.                     Constants.R_REFS + '*', Constants.R_REFS + '*'));
  292.         } else {
  293.             RefSpec heads = new RefSpec();
  294.             heads = heads.setForceUpdate(true);
  295.             final String dst = (bare ? Constants.R_HEADS
  296.                     : Constants.R_REMOTES + remoteName + '/') + '*';
  297.             heads = heads.setSourceDestination(Constants.R_HEADS + '*', dst);
  298.             if (type == FETCH_TYPE.MULTIPLE_BRANCHES) {
  299.                 RefSpec tags = new RefSpec().setForceUpdate(true)
  300.                         .setSourceDestination(Constants.R_TAGS + '*',
  301.                                 Constants.R_TAGS + '*');
  302.                 for (String selectedRef : branchesToClone) {
  303.                     if (heads.matchSource(selectedRef)) {
  304.                         specs.add(heads.expandFromSource(selectedRef));
  305.                     } else if (tags.matchSource(selectedRef)) {
  306.                         specs.add(tags.expandFromSource(selectedRef));
  307.                     }
  308.                 }
  309.             } else {
  310.                 // We'll fetch the tags anyway.
  311.                 specs.add(heads);
  312.             }
  313.         }
  314.         return specs;
  315.     }

  316.     private void checkout(Repository clonedRepo, FetchResult result)
  317.             throws MissingObjectException, IncorrectObjectTypeException,
  318.             IOException, GitAPIException {

  319.         Ref head = null;
  320.         if (branch.equals(Constants.HEAD)) {
  321.             Ref foundBranch = findBranchToCheckout(result);
  322.             if (foundBranch != null)
  323.                 head = foundBranch;
  324.         }
  325.         if (head == null) {
  326.             head = result.getAdvertisedRef(branch);
  327.             if (head == null)
  328.                 head = result.getAdvertisedRef(Constants.R_HEADS + branch);
  329.             if (head == null)
  330.                 head = result.getAdvertisedRef(Constants.R_TAGS + branch);
  331.         }

  332.         if (head == null || head.getObjectId() == null)
  333.             return; // TODO throw exception?

  334.         if (head.getName().startsWith(Constants.R_HEADS)) {
  335.             final RefUpdate newHead = clonedRepo.updateRef(Constants.HEAD);
  336.             newHead.disableRefLog();
  337.             newHead.link(head.getName());
  338.             addMergeConfig(clonedRepo, head);
  339.         }

  340.         final RevCommit commit = parseCommit(clonedRepo, head);

  341.         boolean detached = !head.getName().startsWith(Constants.R_HEADS);
  342.         RefUpdate u = clonedRepo.updateRef(Constants.HEAD, detached);
  343.         u.setNewObjectId(commit.getId());
  344.         u.forceUpdate();

  345.         if (!bare && !noCheckout) {
  346.             DirCache dc = clonedRepo.lockDirCache();
  347.             DirCacheCheckout co = new DirCacheCheckout(clonedRepo, dc,
  348.                     commit.getTree());
  349.             co.setProgressMonitor(monitor);
  350.             co.checkout();
  351.             if (cloneSubmodules)
  352.                 cloneSubmodules(clonedRepo);
  353.         }
  354.     }

  355.     private void cloneSubmodules(Repository clonedRepo) throws IOException,
  356.             GitAPIException {
  357.         SubmoduleInitCommand init = new SubmoduleInitCommand(clonedRepo);
  358.         Collection<String> submodules = init.call();
  359.         if (submodules.isEmpty()) {
  360.             return;
  361.         }
  362.         if (callback != null) {
  363.             callback.initializedSubmodules(submodules);
  364.         }

  365.         SubmoduleUpdateCommand update = new SubmoduleUpdateCommand(clonedRepo);
  366.         configure(update);
  367.         update.setProgressMonitor(monitor);
  368.         update.setCallback(callback);
  369.         if (!update.call().isEmpty()) {
  370.             SubmoduleWalk walk = SubmoduleWalk.forIndex(clonedRepo);
  371.             while (walk.next()) {
  372.                 try (Repository subRepo = walk.getRepository()) {
  373.                     if (subRepo != null) {
  374.                         cloneSubmodules(subRepo);
  375.                     }
  376.                 }
  377.             }
  378.         }
  379.     }

  380.     private Ref findBranchToCheckout(FetchResult result) {
  381.         final Ref idHEAD = result.getAdvertisedRef(Constants.HEAD);
  382.         ObjectId headId = idHEAD != null ? idHEAD.getObjectId() : null;
  383.         if (headId == null) {
  384.             return null;
  385.         }

  386.         if (idHEAD != null && idHEAD.isSymbolic()) {
  387.             return idHEAD.getTarget();
  388.         }

  389.         Ref master = result.getAdvertisedRef(Constants.R_HEADS
  390.                 + Constants.MASTER);
  391.         ObjectId objectId = master != null ? master.getObjectId() : null;
  392.         if (headId.equals(objectId)) {
  393.             return master;
  394.         }

  395.         Ref foundBranch = null;
  396.         for (Ref r : result.getAdvertisedRefs()) {
  397.             final String n = r.getName();
  398.             if (!n.startsWith(Constants.R_HEADS))
  399.                 continue;
  400.             if (headId.equals(r.getObjectId())) {
  401.                 foundBranch = r;
  402.                 break;
  403.             }
  404.         }
  405.         return foundBranch;
  406.     }

  407.     private void addMergeConfig(Repository clonedRepo, Ref head)
  408.             throws IOException {
  409.         String branchName = Repository.shortenRefName(head.getName());
  410.         clonedRepo.getConfig().setString(ConfigConstants.CONFIG_BRANCH_SECTION,
  411.                 branchName, ConfigConstants.CONFIG_KEY_REMOTE, remote);
  412.         clonedRepo.getConfig().setString(ConfigConstants.CONFIG_BRANCH_SECTION,
  413.                 branchName, ConfigConstants.CONFIG_KEY_MERGE, head.getName());
  414.         String autosetupRebase = clonedRepo.getConfig().getString(
  415.                 ConfigConstants.CONFIG_BRANCH_SECTION, null,
  416.                 ConfigConstants.CONFIG_KEY_AUTOSETUPREBASE);
  417.         if (ConfigConstants.CONFIG_KEY_ALWAYS.equals(autosetupRebase)
  418.                 || ConfigConstants.CONFIG_KEY_REMOTE.equals(autosetupRebase))
  419.             clonedRepo.getConfig().setEnum(
  420.                     ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
  421.                     ConfigConstants.CONFIG_KEY_REBASE, BranchRebaseMode.REBASE);
  422.         clonedRepo.getConfig().save();
  423.     }

  424.     private RevCommit parseCommit(Repository clonedRepo, Ref ref)
  425.             throws MissingObjectException, IncorrectObjectTypeException,
  426.             IOException {
  427.         final RevCommit commit;
  428.         try (RevWalk rw = new RevWalk(clonedRepo)) {
  429.             commit = rw.parseCommit(ref.getObjectId());
  430.         }
  431.         return commit;
  432.     }

  433.     /**
  434.      * Set the URI to clone from
  435.      *
  436.      * @param uri
  437.      *            the URI to clone from, or {@code null} to unset the URI. The
  438.      *            URI must be set before {@link #call} is called.
  439.      * @return this instance
  440.      */
  441.     public CloneCommand setURI(String uri) {
  442.         this.uri = uri;
  443.         return this;
  444.     }

  445.     /**
  446.      * The optional directory associated with the clone operation. If the
  447.      * directory isn't set, a name associated with the source uri will be used.
  448.      *
  449.      * @see URIish#getHumanishName()
  450.      * @param directory
  451.      *            the directory to clone to, or {@code null} if the directory
  452.      *            name should be taken from the source uri
  453.      * @return this instance
  454.      * @throws java.lang.IllegalStateException
  455.      *             if the combination of directory, gitDir and bare is illegal.
  456.      *             E.g. if for a non-bare repository directory and gitDir point
  457.      *             to the same directory of if for a bare repository both
  458.      *             directory and gitDir are specified
  459.      */
  460.     public CloneCommand setDirectory(File directory) {
  461.         validateDirs(directory, gitDir, bare);
  462.         this.directory = directory;
  463.         return this;
  464.     }

  465.     /**
  466.      * Set the repository meta directory (.git)
  467.      *
  468.      * @param gitDir
  469.      *            the repository meta directory, or {@code null} to choose one
  470.      *            automatically at clone time
  471.      * @return this instance
  472.      * @throws java.lang.IllegalStateException
  473.      *             if the combination of directory, gitDir and bare is illegal.
  474.      *             E.g. if for a non-bare repository directory and gitDir point
  475.      *             to the same directory of if for a bare repository both
  476.      *             directory and gitDir are specified
  477.      * @since 3.6
  478.      */
  479.     public CloneCommand setGitDir(File gitDir) {
  480.         validateDirs(directory, gitDir, bare);
  481.         this.gitDir = gitDir;
  482.         return this;
  483.     }

  484.     /**
  485.      * Set whether the cloned repository shall be bare
  486.      *
  487.      * @param bare
  488.      *            whether the cloned repository is bare or not
  489.      * @return this instance
  490.      * @throws java.lang.IllegalStateException
  491.      *             if the combination of directory, gitDir and bare is illegal.
  492.      *             E.g. if for a non-bare repository directory and gitDir point
  493.      *             to the same directory of if for a bare repository both
  494.      *             directory and gitDir are specified
  495.      */
  496.     public CloneCommand setBare(boolean bare) throws IllegalStateException {
  497.         validateDirs(directory, gitDir, bare);
  498.         this.bare = bare;
  499.         return this;
  500.     }

  501.     /**
  502.      * Set the file system abstraction to be used for repositories created by
  503.      * this command.
  504.      *
  505.      * @param fs
  506.      *            the abstraction.
  507.      * @return {@code this} (for chaining calls).
  508.      * @since 4.10
  509.      */
  510.     public CloneCommand setFs(FS fs) {
  511.         this.fs = fs;
  512.         return this;
  513.     }

  514.     /**
  515.      * The remote name used to keep track of the upstream repository for the
  516.      * clone operation. If no remote name is set, the default value of
  517.      * <code>Constants.DEFAULT_REMOTE_NAME</code> will be used.
  518.      *
  519.      * @see Constants#DEFAULT_REMOTE_NAME
  520.      * @param remote
  521.      *            name that keeps track of the upstream repository.
  522.      *            {@code null} means to use DEFAULT_REMOTE_NAME.
  523.      * @return this instance
  524.      */
  525.     public CloneCommand setRemote(String remote) {
  526.         if (remote == null) {
  527.             remote = Constants.DEFAULT_REMOTE_NAME;
  528.         }
  529.         this.remote = remote;
  530.         return this;
  531.     }

  532.     /**
  533.      * Set the initial branch
  534.      *
  535.      * @param branch
  536.      *            the initial branch to check out when cloning the repository.
  537.      *            Can be specified as ref name (<code>refs/heads/master</code>),
  538.      *            branch name (<code>master</code>) or tag name
  539.      *            (<code>v1.2.3</code>). The default is to use the branch
  540.      *            pointed to by the cloned repository's HEAD and can be
  541.      *            requested by passing {@code null} or <code>HEAD</code>.
  542.      * @return this instance
  543.      */
  544.     public CloneCommand setBranch(String branch) {
  545.         if (branch == null) {
  546.             branch = Constants.HEAD;
  547.         }
  548.         this.branch = branch;
  549.         return this;
  550.     }

  551.     /**
  552.      * The progress monitor associated with the clone operation. By default,
  553.      * this is set to <code>NullProgressMonitor</code>
  554.      *
  555.      * @see NullProgressMonitor
  556.      * @param monitor
  557.      *            a {@link org.eclipse.jgit.lib.ProgressMonitor}
  558.      * @return {@code this}
  559.      */
  560.     public CloneCommand setProgressMonitor(ProgressMonitor monitor) {
  561.         if (monitor == null) {
  562.             monitor = NullProgressMonitor.INSTANCE;
  563.         }
  564.         this.monitor = monitor;
  565.         return this;
  566.     }

  567.     /**
  568.      * Set whether all branches have to be fetched.
  569.      * <p>
  570.      * If {@code false}, use {@link #setBranchesToClone(Collection)} to define
  571.      * what will be cloned. If neither are set, all branches will be cloned.
  572.      * </p>
  573.      *
  574.      * @param cloneAllBranches
  575.      *            {@code true} when all branches have to be fetched (indicates
  576.      *            wildcard in created fetch refspec), {@code false} otherwise.
  577.      * @return {@code this}
  578.      */
  579.     public CloneCommand setCloneAllBranches(boolean cloneAllBranches) {
  580.         this.cloneAllBranches = cloneAllBranches;
  581.         return this;
  582.     }

  583.     /**
  584.      * Set up a mirror of the source repository. This implies that a bare
  585.      * repository will be created. Compared to {@link #setBare},
  586.      * {@code #setMirror} not only maps local branches of the source to local
  587.      * branches of the target, it maps all refs (including remote-tracking
  588.      * branches, notes etc.) and sets up a refspec configuration such that all
  589.      * these refs are overwritten by a git remote update in the target
  590.      * repository.
  591.      *
  592.      * @param mirror
  593.      *            whether to mirror all refs from the source repository
  594.      *
  595.      * @return {@code this}
  596.      * @since 5.6
  597.      */
  598.     public CloneCommand setMirror(boolean mirror) {
  599.         this.mirror = mirror;
  600.         return this;
  601.     }

  602.     /**
  603.      * Set whether to clone submodules
  604.      *
  605.      * @param cloneSubmodules
  606.      *            true to initialize and update submodules. Ignored when
  607.      *            {@link #setBare(boolean)} is set to true.
  608.      * @return {@code this}
  609.      */
  610.     public CloneCommand setCloneSubmodules(boolean cloneSubmodules) {
  611.         this.cloneSubmodules = cloneSubmodules;
  612.         return this;
  613.     }

  614.     /**
  615.      * Set the branches or tags to clone.
  616.      * <p>
  617.      * This is ignored if {@link #setCloneAllBranches(boolean)
  618.      * setCloneAllBranches(true)} or {@link #setMirror(boolean) setMirror(true)}
  619.      * is used. If {@code branchesToClone} is {@code null} or empty, it's also
  620.      * ignored.
  621.      * </p>
  622.      *
  623.      * @param branchesToClone
  624.      *            collection of branches to clone. Must be specified as full ref
  625.      *            names (e.g. {@code refs/heads/master} or
  626.      *            {@code refs/tags/v1.0.0}).
  627.      * @return {@code this}
  628.      */
  629.     public CloneCommand setBranchesToClone(Collection<String> branchesToClone) {
  630.         this.branchesToClone = branchesToClone;
  631.         return this;
  632.     }

  633.     /**
  634.      * Set the tag option used for the remote configuration explicitly.
  635.      *
  636.      * @param tagOption
  637.      *            tag option to be used for the remote config
  638.      * @return {@code this}
  639.      * @since 5.8
  640.      */
  641.     public CloneCommand setTagOption(TagOpt tagOption) {
  642.         this.tagOption = tagOption;
  643.         return this;
  644.     }

  645.     /**
  646.      * Set the --no-tags option. Tags are not cloned now and the remote
  647.      * configuration is initialized with the --no-tags option as well.
  648.      *
  649.      * @return {@code this}
  650.      * @since 5.8
  651.      */
  652.     public CloneCommand setNoTags() {
  653.         return setTagOption(TagOpt.NO_TAGS);
  654.     }

  655.     /**
  656.      * Set whether to skip checking out a branch
  657.      *
  658.      * @param noCheckout
  659.      *            if set to <code>true</code> no branch will be checked out
  660.      *            after the clone. This enhances performance of the clone
  661.      *            command when there is no need for a checked out branch.
  662.      * @return {@code this}
  663.      */
  664.     public CloneCommand setNoCheckout(boolean noCheckout) {
  665.         this.noCheckout = noCheckout;
  666.         return this;
  667.     }

  668.     /**
  669.      * Register a progress callback.
  670.      *
  671.      * @param callback
  672.      *            the callback
  673.      * @return {@code this}
  674.      * @since 4.8
  675.      */
  676.     public CloneCommand setCallback(Callback callback) {
  677.         this.callback = callback;
  678.         return this;
  679.     }

  680.     /**
  681.      * Creates a shallow clone with a history truncated to the specified number
  682.      * of commits.
  683.      *
  684.      * @param depth
  685.      *            the depth
  686.      * @return {@code this}
  687.      *
  688.      * @since 6.3
  689.      */
  690.     public CloneCommand setDepth(int depth) {
  691.         if (depth < 1) {
  692.             throw new IllegalArgumentException(JGitText.get().depthMustBeAt1);
  693.         }
  694.         this.depth = Integer.valueOf(depth);
  695.         return this;
  696.     }

  697.     /**
  698.      * Creates a shallow clone with a history after the specified time.
  699.      *
  700.      * @param shallowSince
  701.      *            the timestammp; must not be {@code null}
  702.      * @return {@code this}
  703.      *
  704.      * @since 6.3
  705.      */
  706.     public CloneCommand setShallowSince(@NonNull OffsetDateTime shallowSince) {
  707.         this.shallowSince = shallowSince.toInstant();
  708.         return this;
  709.     }

  710.     /**
  711.      * Creates a shallow clone with a history after the specified time.
  712.      *
  713.      * @param shallowSince
  714.      *            the timestammp; must not be {@code null}
  715.      * @return {@code this}
  716.      *
  717.      * @since 6.3
  718.      */
  719.     public CloneCommand setShallowSince(@NonNull Instant shallowSince) {
  720.         this.shallowSince = shallowSince;
  721.         return this;
  722.     }

  723.     /**
  724.      * Creates a shallow clone with a history, excluding commits reachable from
  725.      * a specified remote branch or tag.
  726.      *
  727.      * @param shallowExclude
  728.      *            the ref or commit; must not be {@code null}
  729.      * @return {@code this}
  730.      *
  731.      * @since 6.3
  732.      */
  733.     public CloneCommand addShallowExclude(@NonNull String shallowExclude) {
  734.         shallowExcludes.add(shallowExclude);
  735.         return this;
  736.     }

  737.     /**
  738.      * Creates a shallow clone with a history, excluding commits reachable from
  739.      * a specified remote branch or tag.
  740.      *
  741.      * @param shallowExclude
  742.      *            the commit; must not be {@code null}
  743.      * @return {@code this}
  744.      *
  745.      * @since 6.3
  746.      */
  747.     public CloneCommand addShallowExclude(@NonNull ObjectId shallowExclude) {
  748.         shallowExcludes.add(shallowExclude.name());
  749.         return this;
  750.     }

  751.     private static void validateDirs(File directory, File gitDir, boolean bare)
  752.             throws IllegalStateException {
  753.         if (directory != null) {
  754.             if (directory.exists() && !directory.isDirectory()) {
  755.                 throw new IllegalStateException(MessageFormat.format(
  756.                         JGitText.get().initFailedDirIsNoDirectory, directory));
  757.             }
  758.             if (gitDir != null && gitDir.exists() && !gitDir.isDirectory()) {
  759.                 throw new IllegalStateException(MessageFormat.format(
  760.                         JGitText.get().initFailedGitDirIsNoDirectory,
  761.                         gitDir));
  762.             }
  763.             if (bare) {
  764.                 if (gitDir != null && !gitDir.equals(directory))
  765.                     throw new IllegalStateException(MessageFormat.format(
  766.                             JGitText.get().initFailedBareRepoDifferentDirs,
  767.                             gitDir, directory));
  768.             } else {
  769.                 if (gitDir != null && gitDir.equals(directory))
  770.                     throw new IllegalStateException(MessageFormat.format(
  771.                             JGitText.get().initFailedNonBareRepoSameDirs,
  772.                             gitDir, directory));
  773.             }
  774.         }
  775.     }

  776.     private void cleanup() {
  777.         try {
  778.             if (directory != null) {
  779.                 if (!directoryExistsInitially) {
  780.                     FileUtils.delete(directory, FileUtils.RECURSIVE
  781.                             | FileUtils.SKIP_MISSING | FileUtils.IGNORE_ERRORS);
  782.                 } else {
  783.                     deleteChildren(directory);
  784.                 }
  785.             }
  786.             if (gitDir != null) {
  787.                 if (!gitDirExistsInitially) {
  788.                     FileUtils.delete(gitDir, FileUtils.RECURSIVE
  789.                             | FileUtils.SKIP_MISSING | FileUtils.IGNORE_ERRORS);
  790.                 } else {
  791.                     deleteChildren(gitDir);
  792.                 }
  793.             }
  794.         } catch (IOException e) {
  795.             // Ignore; this is a best-effort cleanup in error cases, and
  796.             // IOException should not be raised anyway
  797.         }
  798.     }

  799.     private void deleteChildren(File file) throws IOException {
  800.         File[] files = file.listFiles();
  801.         if (files == null) {
  802.             return;
  803.         }
  804.         for (File child : files) {
  805.             FileUtils.delete(child, FileUtils.RECURSIVE | FileUtils.SKIP_MISSING
  806.                     | FileUtils.IGNORE_ERRORS);
  807.         }
  808.     }
  809. }