You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CloneCommand.java 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775
  1. /*
  2. * Copyright (C) 2011, 2017 Chris Aniszczyk <caniszczyk@gmail.com>
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.api;
  44. import java.io.File;
  45. import java.io.IOException;
  46. import java.net.URISyntaxException;
  47. import java.text.MessageFormat;
  48. import java.util.ArrayList;
  49. import java.util.Collection;
  50. import java.util.List;
  51. import org.eclipse.jgit.annotations.Nullable;
  52. import org.eclipse.jgit.api.errors.GitAPIException;
  53. import org.eclipse.jgit.api.errors.InvalidRemoteException;
  54. import org.eclipse.jgit.api.errors.JGitInternalException;
  55. import org.eclipse.jgit.dircache.DirCache;
  56. import org.eclipse.jgit.dircache.DirCacheCheckout;
  57. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  58. import org.eclipse.jgit.errors.MissingObjectException;
  59. import org.eclipse.jgit.internal.JGitText;
  60. import org.eclipse.jgit.lib.AnyObjectId;
  61. import org.eclipse.jgit.lib.BranchConfig.BranchRebaseMode;
  62. import org.eclipse.jgit.lib.ConfigConstants;
  63. import org.eclipse.jgit.lib.Constants;
  64. import org.eclipse.jgit.lib.NullProgressMonitor;
  65. import org.eclipse.jgit.lib.ObjectId;
  66. import org.eclipse.jgit.lib.ProgressMonitor;
  67. import org.eclipse.jgit.lib.Ref;
  68. import org.eclipse.jgit.lib.RefUpdate;
  69. import org.eclipse.jgit.lib.Repository;
  70. import org.eclipse.jgit.revwalk.RevCommit;
  71. import org.eclipse.jgit.revwalk.RevWalk;
  72. import org.eclipse.jgit.submodule.SubmoduleWalk;
  73. import org.eclipse.jgit.transport.FetchResult;
  74. import org.eclipse.jgit.transport.RefSpec;
  75. import org.eclipse.jgit.transport.RemoteConfig;
  76. import org.eclipse.jgit.transport.TagOpt;
  77. import org.eclipse.jgit.transport.URIish;
  78. import org.eclipse.jgit.util.FS;
  79. import org.eclipse.jgit.util.FileUtils;
  80. /**
  81. * Clone a repository into a new working directory
  82. *
  83. * @see <a href="http://www.kernel.org/pub/software/scm/git/docs/git-clone.html"
  84. * >Git documentation about Clone</a>
  85. */
  86. public class CloneCommand extends TransportCommand<CloneCommand, Git> {
  87. private String uri;
  88. private File directory;
  89. private File gitDir;
  90. private boolean bare;
  91. private FS fs;
  92. private String remote = Constants.DEFAULT_REMOTE_NAME;
  93. private String branch = Constants.HEAD;
  94. private ProgressMonitor monitor = NullProgressMonitor.INSTANCE;
  95. private FETCH_TYPE fetchType = FETCH_TYPE.ALL_BRANCHES;
  96. private boolean cloneSubmodules;
  97. private boolean noCheckout;
  98. private Collection<String> branchesToClone;
  99. private Callback callback;
  100. private boolean directoryExistsInitially;
  101. private boolean gitDirExistsInitially;
  102. private enum FETCH_TYPE {
  103. MULTIPLE_BRANCHES, ALL_BRANCHES, MIRROR
  104. }
  105. /**
  106. * Callback for status of clone operation.
  107. *
  108. * @since 4.8
  109. */
  110. public interface Callback {
  111. /**
  112. * Notify initialized submodules.
  113. *
  114. * @param submodules
  115. * the submodules
  116. *
  117. */
  118. void initializedSubmodules(Collection<String> submodules);
  119. /**
  120. * Notify starting to clone a submodule.
  121. *
  122. * @param path
  123. * the submodule path
  124. */
  125. void cloningSubmodule(String path);
  126. /**
  127. * Notify checkout of commit
  128. *
  129. * @param commit
  130. * the id of the commit being checked out
  131. * @param path
  132. * the submodule path
  133. */
  134. void checkingOut(AnyObjectId commit, String path);
  135. }
  136. /**
  137. * Create clone command with no repository set
  138. */
  139. public CloneCommand() {
  140. super(null);
  141. }
  142. /**
  143. * Get the git directory. This is primarily used for tests.
  144. *
  145. * @return the git directory
  146. */
  147. @Nullable
  148. File getDirectory() {
  149. return directory;
  150. }
  151. /**
  152. * {@inheritDoc}
  153. * <p>
  154. * Executes the {@code Clone} command.
  155. *
  156. * The Git instance returned by this command needs to be closed by the
  157. * caller to free resources held by the underlying {@link Repository}
  158. * instance. It is recommended to call this method as soon as you don't need
  159. * a reference to this {@link Git} instance and the underlying
  160. * {@link Repository} instance anymore.
  161. */
  162. @Override
  163. public Git call() throws GitAPIException, InvalidRemoteException,
  164. org.eclipse.jgit.api.errors.TransportException {
  165. URIish u = null;
  166. try {
  167. u = new URIish(uri);
  168. verifyDirectories(u);
  169. } catch (URISyntaxException e) {
  170. throw new InvalidRemoteException(
  171. MessageFormat.format(JGitText.get().invalidURL, uri));
  172. }
  173. @SuppressWarnings("resource") // Closed by caller
  174. Repository repository = init();
  175. FetchResult fetchResult = null;
  176. Thread cleanupHook = new Thread(() -> cleanup());
  177. Runtime.getRuntime().addShutdownHook(cleanupHook);
  178. try {
  179. fetchResult = fetch(repository, u);
  180. } catch (IOException ioe) {
  181. if (repository != null) {
  182. repository.close();
  183. }
  184. cleanup();
  185. throw new JGitInternalException(ioe.getMessage(), ioe);
  186. } catch (URISyntaxException e) {
  187. if (repository != null) {
  188. repository.close();
  189. }
  190. cleanup();
  191. throw new InvalidRemoteException(MessageFormat.format(
  192. JGitText.get().invalidRemote, remote));
  193. } catch (GitAPIException | RuntimeException e) {
  194. if (repository != null) {
  195. repository.close();
  196. }
  197. cleanup();
  198. throw e;
  199. } finally {
  200. Runtime.getRuntime().removeShutdownHook(cleanupHook);
  201. }
  202. if (!noCheckout) {
  203. try {
  204. checkout(repository, fetchResult);
  205. } catch (IOException ioe) {
  206. repository.close();
  207. throw new JGitInternalException(ioe.getMessage(), ioe);
  208. } catch (GitAPIException | RuntimeException e) {
  209. repository.close();
  210. throw e;
  211. }
  212. }
  213. return new Git(repository, true);
  214. }
  215. private static boolean isNonEmptyDirectory(File dir) {
  216. if (dir != null && dir.exists()) {
  217. File[] files = dir.listFiles();
  218. return files != null && files.length != 0;
  219. }
  220. return false;
  221. }
  222. void verifyDirectories(URIish u) {
  223. if (directory == null && gitDir == null) {
  224. directory = new File(u.getHumanishName() + (bare ? Constants.DOT_GIT_EXT : "")); //$NON-NLS-1$
  225. }
  226. directoryExistsInitially = directory != null && directory.exists();
  227. gitDirExistsInitially = gitDir != null && gitDir.exists();
  228. validateDirs(directory, gitDir, bare);
  229. if (isNonEmptyDirectory(directory)) {
  230. throw new JGitInternalException(MessageFormat.format(
  231. JGitText.get().cloneNonEmptyDirectory, directory.getName()));
  232. }
  233. if (isNonEmptyDirectory(gitDir)) {
  234. throw new JGitInternalException(MessageFormat.format(
  235. JGitText.get().cloneNonEmptyDirectory, gitDir.getName()));
  236. }
  237. }
  238. private Repository init() throws GitAPIException {
  239. InitCommand command = Git.init();
  240. command.setBare(bare);
  241. if (fs != null) {
  242. command.setFs(fs);
  243. }
  244. if (directory != null) {
  245. command.setDirectory(directory);
  246. }
  247. if (gitDir != null) {
  248. command.setGitDir(gitDir);
  249. }
  250. return command.call().getRepository();
  251. }
  252. private FetchResult fetch(Repository clonedRepo, URIish u)
  253. throws URISyntaxException,
  254. org.eclipse.jgit.api.errors.TransportException, IOException,
  255. GitAPIException {
  256. // create the remote config and save it
  257. RemoteConfig config = new RemoteConfig(clonedRepo.getConfig(), remote);
  258. config.addURI(u);
  259. boolean fetchAll = fetchType == FETCH_TYPE.ALL_BRANCHES
  260. || fetchType == FETCH_TYPE.MIRROR;
  261. config.setFetchRefSpecs(calculateRefSpecs(fetchType, config.getName()));
  262. config.setMirror(fetchType == FETCH_TYPE.MIRROR);
  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. command.setTagOpt(fetchAll ? TagOpt.FETCH_TAGS : TagOpt.AUTO_FOLLOW);
  270. configure(command);
  271. return command.call();
  272. }
  273. private List<RefSpec> calculateRefSpecs(FETCH_TYPE type,
  274. String remoteName) {
  275. List<RefSpec> specs = new ArrayList<>();
  276. if (type == FETCH_TYPE.MIRROR) {
  277. specs.add(new RefSpec().setForceUpdate(true).setSourceDestination(
  278. Constants.R_REFS + '*', Constants.R_REFS + '*'));
  279. } else {
  280. RefSpec heads = new RefSpec();
  281. heads = heads.setForceUpdate(true);
  282. final String dst = (bare ? Constants.R_HEADS
  283. : Constants.R_REMOTES + remoteName + '/') + '*';
  284. heads = heads.setSourceDestination(Constants.R_HEADS + '*', dst);
  285. if (type == FETCH_TYPE.MULTIPLE_BRANCHES) {
  286. RefSpec tags = new RefSpec().setForceUpdate(true)
  287. .setSourceDestination(Constants.R_TAGS + '*',
  288. Constants.R_TAGS + '*');
  289. for (String selectedRef : branchesToClone) {
  290. if (heads.matchSource(selectedRef)) {
  291. specs.add(heads.expandFromSource(selectedRef));
  292. } else if (tags.matchSource(selectedRef)) {
  293. specs.add(tags.expandFromSource(selectedRef));
  294. }
  295. }
  296. } else {
  297. // We'll fetch the tags anyway.
  298. specs.add(heads);
  299. }
  300. }
  301. return specs;
  302. }
  303. private void checkout(Repository clonedRepo, FetchResult result)
  304. throws MissingObjectException, IncorrectObjectTypeException,
  305. IOException, GitAPIException {
  306. Ref head = null;
  307. if (branch.equals(Constants.HEAD)) {
  308. Ref foundBranch = findBranchToCheckout(result);
  309. if (foundBranch != null)
  310. head = foundBranch;
  311. }
  312. if (head == null) {
  313. head = result.getAdvertisedRef(branch);
  314. if (head == null)
  315. head = result.getAdvertisedRef(Constants.R_HEADS + branch);
  316. if (head == null)
  317. head = result.getAdvertisedRef(Constants.R_TAGS + branch);
  318. }
  319. if (head == null || head.getObjectId() == null)
  320. return; // TODO throw exception?
  321. if (head.getName().startsWith(Constants.R_HEADS)) {
  322. final RefUpdate newHead = clonedRepo.updateRef(Constants.HEAD);
  323. newHead.disableRefLog();
  324. newHead.link(head.getName());
  325. addMergeConfig(clonedRepo, head);
  326. }
  327. final RevCommit commit = parseCommit(clonedRepo, head);
  328. boolean detached = !head.getName().startsWith(Constants.R_HEADS);
  329. RefUpdate u = clonedRepo.updateRef(Constants.HEAD, detached);
  330. u.setNewObjectId(commit.getId());
  331. u.forceUpdate();
  332. if (!bare) {
  333. DirCache dc = clonedRepo.lockDirCache();
  334. DirCacheCheckout co = new DirCacheCheckout(clonedRepo, dc,
  335. commit.getTree());
  336. co.setProgressMonitor(monitor);
  337. co.checkout();
  338. if (cloneSubmodules)
  339. cloneSubmodules(clonedRepo);
  340. }
  341. }
  342. private void cloneSubmodules(Repository clonedRepo) throws IOException,
  343. GitAPIException {
  344. SubmoduleInitCommand init = new SubmoduleInitCommand(clonedRepo);
  345. Collection<String> submodules = init.call();
  346. if (submodules.isEmpty()) {
  347. return;
  348. }
  349. if (callback != null) {
  350. callback.initializedSubmodules(submodules);
  351. }
  352. SubmoduleUpdateCommand update = new SubmoduleUpdateCommand(clonedRepo);
  353. configure(update);
  354. update.setProgressMonitor(monitor);
  355. update.setCallback(callback);
  356. if (!update.call().isEmpty()) {
  357. SubmoduleWalk walk = SubmoduleWalk.forIndex(clonedRepo);
  358. while (walk.next()) {
  359. try (Repository subRepo = walk.getRepository()) {
  360. if (subRepo != null) {
  361. cloneSubmodules(subRepo);
  362. }
  363. }
  364. }
  365. }
  366. }
  367. private Ref findBranchToCheckout(FetchResult result) {
  368. final Ref idHEAD = result.getAdvertisedRef(Constants.HEAD);
  369. ObjectId headId = idHEAD != null ? idHEAD.getObjectId() : null;
  370. if (headId == null) {
  371. return null;
  372. }
  373. Ref master = result.getAdvertisedRef(Constants.R_HEADS
  374. + Constants.MASTER);
  375. ObjectId objectId = master != null ? master.getObjectId() : null;
  376. if (headId.equals(objectId)) {
  377. return master;
  378. }
  379. Ref foundBranch = null;
  380. for (Ref r : result.getAdvertisedRefs()) {
  381. final String n = r.getName();
  382. if (!n.startsWith(Constants.R_HEADS))
  383. continue;
  384. if (headId.equals(r.getObjectId())) {
  385. foundBranch = r;
  386. break;
  387. }
  388. }
  389. return foundBranch;
  390. }
  391. private void addMergeConfig(Repository clonedRepo, Ref head)
  392. throws IOException {
  393. String branchName = Repository.shortenRefName(head.getName());
  394. clonedRepo.getConfig().setString(ConfigConstants.CONFIG_BRANCH_SECTION,
  395. branchName, ConfigConstants.CONFIG_KEY_REMOTE, remote);
  396. clonedRepo.getConfig().setString(ConfigConstants.CONFIG_BRANCH_SECTION,
  397. branchName, ConfigConstants.CONFIG_KEY_MERGE, head.getName());
  398. String autosetupRebase = clonedRepo.getConfig().getString(
  399. ConfigConstants.CONFIG_BRANCH_SECTION, null,
  400. ConfigConstants.CONFIG_KEY_AUTOSETUPREBASE);
  401. if (ConfigConstants.CONFIG_KEY_ALWAYS.equals(autosetupRebase)
  402. || ConfigConstants.CONFIG_KEY_REMOTE.equals(autosetupRebase))
  403. clonedRepo.getConfig().setEnum(
  404. ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
  405. ConfigConstants.CONFIG_KEY_REBASE, BranchRebaseMode.REBASE);
  406. clonedRepo.getConfig().save();
  407. }
  408. private RevCommit parseCommit(Repository clonedRepo, Ref ref)
  409. throws MissingObjectException, IncorrectObjectTypeException,
  410. IOException {
  411. final RevCommit commit;
  412. try (RevWalk rw = new RevWalk(clonedRepo)) {
  413. commit = rw.parseCommit(ref.getObjectId());
  414. }
  415. return commit;
  416. }
  417. /**
  418. * Set the URI to clone from
  419. *
  420. * @param uri
  421. * the URI to clone from, or {@code null} to unset the URI. The
  422. * URI must be set before {@link #call} is called.
  423. * @return this instance
  424. */
  425. public CloneCommand setURI(String uri) {
  426. this.uri = uri;
  427. return this;
  428. }
  429. /**
  430. * The optional directory associated with the clone operation. If the
  431. * directory isn't set, a name associated with the source uri will be used.
  432. *
  433. * @see URIish#getHumanishName()
  434. * @param directory
  435. * the directory to clone to, or {@code null} if the directory
  436. * name should be taken from the source uri
  437. * @return this instance
  438. * @throws java.lang.IllegalStateException
  439. * if the combination of directory, gitDir and bare is illegal.
  440. * E.g. if for a non-bare repository directory and gitDir point
  441. * to the same directory of if for a bare repository both
  442. * directory and gitDir are specified
  443. */
  444. public CloneCommand setDirectory(File directory) {
  445. validateDirs(directory, gitDir, bare);
  446. this.directory = directory;
  447. return this;
  448. }
  449. /**
  450. * Set the repository meta directory (.git)
  451. *
  452. * @param gitDir
  453. * the repository meta directory, or {@code null} to choose one
  454. * automatically at clone time
  455. * @return this instance
  456. * @throws java.lang.IllegalStateException
  457. * if the combination of directory, gitDir and bare is illegal.
  458. * E.g. if for a non-bare repository directory and gitDir point
  459. * to the same directory of if for a bare repository both
  460. * directory and gitDir are specified
  461. * @since 3.6
  462. */
  463. public CloneCommand setGitDir(File gitDir) {
  464. validateDirs(directory, gitDir, bare);
  465. this.gitDir = gitDir;
  466. return this;
  467. }
  468. /**
  469. * Set whether the cloned repository shall be bare
  470. *
  471. * @param bare
  472. * whether the cloned repository is bare or not
  473. * @return this instance
  474. * @throws java.lang.IllegalStateException
  475. * if the combination of directory, gitDir and bare is illegal.
  476. * E.g. if for a non-bare repository directory and gitDir point
  477. * to the same directory of if for a bare repository both
  478. * directory and gitDir are specified
  479. */
  480. public CloneCommand setBare(boolean bare) throws IllegalStateException {
  481. validateDirs(directory, gitDir, bare);
  482. this.bare = bare;
  483. return this;
  484. }
  485. /**
  486. * Set the file system abstraction to be used for repositories created by
  487. * this command.
  488. *
  489. * @param fs
  490. * the abstraction.
  491. * @return {@code this} (for chaining calls).
  492. * @since 4.10
  493. */
  494. public CloneCommand setFs(FS fs) {
  495. this.fs = fs;
  496. return this;
  497. }
  498. /**
  499. * The remote name used to keep track of the upstream repository for the
  500. * clone operation. If no remote name is set, the default value of
  501. * <code>Constants.DEFAULT_REMOTE_NAME</code> will be used.
  502. *
  503. * @see Constants#DEFAULT_REMOTE_NAME
  504. * @param remote
  505. * name that keeps track of the upstream repository.
  506. * {@code null} means to use DEFAULT_REMOTE_NAME.
  507. * @return this instance
  508. */
  509. public CloneCommand setRemote(String remote) {
  510. if (remote == null) {
  511. remote = Constants.DEFAULT_REMOTE_NAME;
  512. }
  513. this.remote = remote;
  514. return this;
  515. }
  516. /**
  517. * Set the initial branch
  518. *
  519. * @param branch
  520. * the initial branch to check out when cloning the repository.
  521. * Can be specified as ref name (<code>refs/heads/master</code>),
  522. * branch name (<code>master</code>) or tag name
  523. * (<code>v1.2.3</code>). The default is to use the branch
  524. * pointed to by the cloned repository's HEAD and can be
  525. * requested by passing {@code null} or <code>HEAD</code>.
  526. * @return this instance
  527. */
  528. public CloneCommand setBranch(String branch) {
  529. if (branch == null) {
  530. branch = Constants.HEAD;
  531. }
  532. this.branch = branch;
  533. return this;
  534. }
  535. /**
  536. * The progress monitor associated with the clone operation. By default,
  537. * this is set to <code>NullProgressMonitor</code>
  538. *
  539. * @see NullProgressMonitor
  540. * @param monitor
  541. * a {@link org.eclipse.jgit.lib.ProgressMonitor}
  542. * @return {@code this}
  543. */
  544. public CloneCommand setProgressMonitor(ProgressMonitor monitor) {
  545. if (monitor == null) {
  546. monitor = NullProgressMonitor.INSTANCE;
  547. }
  548. this.monitor = monitor;
  549. return this;
  550. }
  551. /**
  552. * Set whether all branches have to be fetched.
  553. * <p>
  554. * If {@code false}, use {@link #setBranchesToClone(Collection)} to define
  555. * what will be cloned. If neither are set, all branches will be cloned.
  556. * </p>
  557. *
  558. * @param cloneAllBranches
  559. * {@code true} when all branches have to be fetched (indicates
  560. * wildcard in created fetch refspec), {@code false} otherwise.
  561. * @return {@code this}
  562. */
  563. public CloneCommand setCloneAllBranches(boolean cloneAllBranches) {
  564. this.fetchType = cloneAllBranches ? FETCH_TYPE.ALL_BRANCHES
  565. : this.fetchType;
  566. return this;
  567. }
  568. /**
  569. * Set up a mirror of the source repository. This implies that a bare
  570. * repository will be created. Compared to {@link #setBare},
  571. * {@code #setMirror} not only maps local branches of the source to local
  572. * branches of the target, it maps all refs (including remote-tracking
  573. * branches, notes etc.) and sets up a refspec configuration such that all
  574. * these refs are overwritten by a git remote update in the target
  575. * repository.
  576. *
  577. * @param mirror
  578. * whether to mirror all refs from the source repository
  579. *
  580. * @return {@code this}
  581. * @since 5.6
  582. */
  583. public CloneCommand setMirror(boolean mirror) {
  584. if (mirror) {
  585. this.fetchType = FETCH_TYPE.MIRROR;
  586. setBare(true);
  587. }
  588. return this;
  589. }
  590. /**
  591. * Set whether to clone submodules
  592. *
  593. * @param cloneSubmodules
  594. * true to initialize and update submodules. Ignored when
  595. * {@link #setBare(boolean)} is set to true.
  596. * @return {@code this}
  597. */
  598. public CloneCommand setCloneSubmodules(boolean cloneSubmodules) {
  599. this.cloneSubmodules = cloneSubmodules;
  600. return this;
  601. }
  602. /**
  603. * Set the branches or tags to clone.
  604. * <p>
  605. * This is ignored if {@link #setCloneAllBranches(boolean)
  606. * setCloneAllBranches(true)} is used. If {@code branchesToClone} is
  607. * {@code null} or empty, it's also ignored and all branches will be cloned.
  608. * </p>
  609. *
  610. * @param branchesToClone
  611. * collection of branches to clone. Must be specified as full ref
  612. * names (e.g. {@code refs/heads/master} or
  613. * {@code refs/tags/v1.0.0}).
  614. * @return {@code this}
  615. */
  616. public CloneCommand setBranchesToClone(Collection<String> branchesToClone) {
  617. if (branchesToClone == null || branchesToClone.isEmpty()) {
  618. // fallback to default
  619. fetchType = FETCH_TYPE.ALL_BRANCHES;
  620. } else {
  621. this.fetchType = FETCH_TYPE.MULTIPLE_BRANCHES;
  622. this.branchesToClone = branchesToClone;
  623. }
  624. return this;
  625. }
  626. /**
  627. * Set whether to skip checking out a branch
  628. *
  629. * @param noCheckout
  630. * if set to <code>true</code> no branch will be checked out
  631. * after the clone. This enhances performance of the clone
  632. * command when there is no need for a checked out branch.
  633. * @return {@code this}
  634. */
  635. public CloneCommand setNoCheckout(boolean noCheckout) {
  636. this.noCheckout = noCheckout;
  637. return this;
  638. }
  639. /**
  640. * Register a progress callback.
  641. *
  642. * @param callback
  643. * the callback
  644. * @return {@code this}
  645. * @since 4.8
  646. */
  647. public CloneCommand setCallback(Callback callback) {
  648. this.callback = callback;
  649. return this;
  650. }
  651. private static void validateDirs(File directory, File gitDir, boolean bare)
  652. throws IllegalStateException {
  653. if (directory != null) {
  654. if (directory.exists() && !directory.isDirectory()) {
  655. throw new IllegalStateException(MessageFormat.format(
  656. JGitText.get().initFailedDirIsNoDirectory, directory));
  657. }
  658. if (gitDir != null && gitDir.exists() && !gitDir.isDirectory()) {
  659. throw new IllegalStateException(MessageFormat.format(
  660. JGitText.get().initFailedGitDirIsNoDirectory,
  661. gitDir));
  662. }
  663. if (bare) {
  664. if (gitDir != null && !gitDir.equals(directory))
  665. throw new IllegalStateException(MessageFormat.format(
  666. JGitText.get().initFailedBareRepoDifferentDirs,
  667. gitDir, directory));
  668. } else {
  669. if (gitDir != null && gitDir.equals(directory))
  670. throw new IllegalStateException(MessageFormat.format(
  671. JGitText.get().initFailedNonBareRepoSameDirs,
  672. gitDir, directory));
  673. }
  674. }
  675. }
  676. private void cleanup() {
  677. try {
  678. if (directory != null) {
  679. if (!directoryExistsInitially) {
  680. FileUtils.delete(directory, FileUtils.RECURSIVE
  681. | FileUtils.SKIP_MISSING | FileUtils.IGNORE_ERRORS);
  682. } else {
  683. deleteChildren(directory);
  684. }
  685. }
  686. if (gitDir != null) {
  687. if (!gitDirExistsInitially) {
  688. FileUtils.delete(gitDir, FileUtils.RECURSIVE
  689. | FileUtils.SKIP_MISSING | FileUtils.IGNORE_ERRORS);
  690. } else {
  691. deleteChildren(gitDir);
  692. }
  693. }
  694. } catch (IOException e) {
  695. // Ignore; this is a best-effort cleanup in error cases, and
  696. // IOException should not be raised anyway
  697. }
  698. }
  699. private void deleteChildren(File file) throws IOException {
  700. File[] files = file.listFiles();
  701. if (files == null) {
  702. return;
  703. }
  704. for (File child : files) {
  705. FileUtils.delete(child, FileUtils.RECURSIVE | FileUtils.SKIP_MISSING
  706. | FileUtils.IGNORE_ERRORS);
  707. }
  708. }
  709. }