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 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  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.FileUtils;
  79. import org.eclipse.jgit.util.FS;
  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 boolean cloneAllBranches;
  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. /**
  103. * Callback for status of clone operation.
  104. *
  105. * @since 4.8
  106. */
  107. public interface Callback {
  108. /**
  109. * Notify initialized submodules.
  110. *
  111. * @param submodules
  112. * the submodules
  113. *
  114. */
  115. void initializedSubmodules(Collection<String> submodules);
  116. /**
  117. * Notify starting to clone a submodule.
  118. *
  119. * @param path
  120. * the submodule path
  121. */
  122. void cloningSubmodule(String path);
  123. /**
  124. * Notify checkout of commit
  125. *
  126. * @param commit
  127. * the id of the commit being checked out
  128. * @param path
  129. * the submodule path
  130. */
  131. void checkingOut(AnyObjectId commit, String path);
  132. }
  133. /**
  134. * Create clone command with no repository set
  135. */
  136. public CloneCommand() {
  137. super(null);
  138. }
  139. /**
  140. * Get the git directory. This is primarily used for tests.
  141. *
  142. * @return the git directory
  143. */
  144. @Nullable
  145. File getDirectory() {
  146. return directory;
  147. }
  148. /**
  149. * {@inheritDoc}
  150. * <p>
  151. * Executes the {@code Clone} command.
  152. *
  153. * The Git instance returned by this command needs to be closed by the
  154. * caller to free resources held by the underlying {@link Repository}
  155. * instance. It is recommended to call this method as soon as you don't need
  156. * a reference to this {@link Git} instance and the underlying
  157. * {@link Repository} instance anymore.
  158. */
  159. @Override
  160. public Git call() throws GitAPIException, InvalidRemoteException,
  161. org.eclipse.jgit.api.errors.TransportException {
  162. URIish u = null;
  163. try {
  164. u = new URIish(uri);
  165. verifyDirectories(u);
  166. } catch (URISyntaxException e) {
  167. throw new InvalidRemoteException(
  168. MessageFormat.format(JGitText.get().invalidURL, uri));
  169. }
  170. @SuppressWarnings("resource") // Closed by caller
  171. Repository repository = init();
  172. FetchResult fetchResult = null;
  173. Thread cleanupHook = new Thread(() -> cleanup());
  174. Runtime.getRuntime().addShutdownHook(cleanupHook);
  175. try {
  176. fetchResult = fetch(repository, u);
  177. } catch (IOException ioe) {
  178. if (repository != null) {
  179. repository.close();
  180. }
  181. cleanup();
  182. throw new JGitInternalException(ioe.getMessage(), ioe);
  183. } catch (URISyntaxException e) {
  184. if (repository != null) {
  185. repository.close();
  186. }
  187. cleanup();
  188. throw new InvalidRemoteException(MessageFormat.format(
  189. JGitText.get().invalidRemote, remote));
  190. } catch (GitAPIException | RuntimeException e) {
  191. if (repository != null) {
  192. repository.close();
  193. }
  194. cleanup();
  195. throw e;
  196. } finally {
  197. Runtime.getRuntime().removeShutdownHook(cleanupHook);
  198. }
  199. if (!noCheckout) {
  200. try {
  201. checkout(repository, fetchResult);
  202. } catch (IOException ioe) {
  203. repository.close();
  204. throw new JGitInternalException(ioe.getMessage(), ioe);
  205. } catch (GitAPIException | RuntimeException e) {
  206. repository.close();
  207. throw e;
  208. }
  209. }
  210. return new Git(repository, true);
  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. final String dst = (bare ? Constants.R_HEADS : Constants.R_REMOTES
  257. + config.getName() + '/') + '*';
  258. boolean fetchAll = cloneAllBranches || branchesToClone == null
  259. || branchesToClone.isEmpty();
  260. config.setFetchRefSpecs(calculateRefSpecs(fetchAll, dst));
  261. config.update(clonedRepo.getConfig());
  262. clonedRepo.getConfig().save();
  263. // run the fetch command
  264. FetchCommand command = new FetchCommand(clonedRepo);
  265. command.setRemote(remote);
  266. command.setProgressMonitor(monitor);
  267. command.setTagOpt(fetchAll ? TagOpt.FETCH_TAGS : TagOpt.AUTO_FOLLOW);
  268. configure(command);
  269. return command.call();
  270. }
  271. private List<RefSpec> calculateRefSpecs(boolean fetchAll, String dst) {
  272. RefSpec wcrs = new RefSpec();
  273. wcrs = wcrs.setForceUpdate(true);
  274. wcrs = wcrs.setSourceDestination(Constants.R_HEADS + '*', dst);
  275. List<RefSpec> specs = new ArrayList<>();
  276. if (!fetchAll) {
  277. for (String selectedRef : branchesToClone) {
  278. if (wcrs.matchSource(selectedRef)) {
  279. specs.add(wcrs.expandFromSource(selectedRef));
  280. }
  281. }
  282. } else {
  283. specs.add(wcrs);
  284. }
  285. return specs;
  286. }
  287. private void checkout(Repository clonedRepo, FetchResult result)
  288. throws MissingObjectException, IncorrectObjectTypeException,
  289. IOException, GitAPIException {
  290. Ref head = null;
  291. if (branch.equals(Constants.HEAD)) {
  292. Ref foundBranch = findBranchToCheckout(result);
  293. if (foundBranch != null)
  294. head = foundBranch;
  295. }
  296. if (head == null) {
  297. head = result.getAdvertisedRef(branch);
  298. if (head == null)
  299. head = result.getAdvertisedRef(Constants.R_HEADS + branch);
  300. if (head == null)
  301. head = result.getAdvertisedRef(Constants.R_TAGS + branch);
  302. }
  303. if (head == null || head.getObjectId() == null)
  304. return; // TODO throw exception?
  305. if (head.getName().startsWith(Constants.R_HEADS)) {
  306. final RefUpdate newHead = clonedRepo.updateRef(Constants.HEAD);
  307. newHead.disableRefLog();
  308. newHead.link(head.getName());
  309. addMergeConfig(clonedRepo, head);
  310. }
  311. final RevCommit commit = parseCommit(clonedRepo, head);
  312. boolean detached = !head.getName().startsWith(Constants.R_HEADS);
  313. RefUpdate u = clonedRepo.updateRef(Constants.HEAD, detached);
  314. u.setNewObjectId(commit.getId());
  315. u.forceUpdate();
  316. if (!bare) {
  317. DirCache dc = clonedRepo.lockDirCache();
  318. DirCacheCheckout co = new DirCacheCheckout(clonedRepo, dc,
  319. commit.getTree());
  320. co.setProgressMonitor(monitor);
  321. co.checkout();
  322. if (cloneSubmodules)
  323. cloneSubmodules(clonedRepo);
  324. }
  325. }
  326. private void cloneSubmodules(Repository clonedRepo) throws IOException,
  327. GitAPIException {
  328. SubmoduleInitCommand init = new SubmoduleInitCommand(clonedRepo);
  329. Collection<String> submodules = init.call();
  330. if (submodules.isEmpty()) {
  331. return;
  332. }
  333. if (callback != null) {
  334. callback.initializedSubmodules(submodules);
  335. }
  336. SubmoduleUpdateCommand update = new SubmoduleUpdateCommand(clonedRepo);
  337. configure(update);
  338. update.setProgressMonitor(monitor);
  339. update.setCallback(callback);
  340. if (!update.call().isEmpty()) {
  341. SubmoduleWalk walk = SubmoduleWalk.forIndex(clonedRepo);
  342. while (walk.next()) {
  343. try (Repository subRepo = walk.getRepository()) {
  344. if (subRepo != null) {
  345. cloneSubmodules(subRepo);
  346. }
  347. }
  348. }
  349. }
  350. }
  351. private Ref findBranchToCheckout(FetchResult result) {
  352. final Ref idHEAD = result.getAdvertisedRef(Constants.HEAD);
  353. ObjectId headId = idHEAD != null ? idHEAD.getObjectId() : null;
  354. if (headId == null) {
  355. return null;
  356. }
  357. Ref master = result.getAdvertisedRef(Constants.R_HEADS
  358. + Constants.MASTER);
  359. ObjectId objectId = master != null ? master.getObjectId() : null;
  360. if (headId.equals(objectId)) {
  361. return master;
  362. }
  363. Ref foundBranch = null;
  364. for (Ref r : result.getAdvertisedRefs()) {
  365. final String n = r.getName();
  366. if (!n.startsWith(Constants.R_HEADS))
  367. continue;
  368. if (headId.equals(r.getObjectId())) {
  369. foundBranch = r;
  370. break;
  371. }
  372. }
  373. return foundBranch;
  374. }
  375. private void addMergeConfig(Repository clonedRepo, Ref head)
  376. throws IOException {
  377. String branchName = Repository.shortenRefName(head.getName());
  378. clonedRepo.getConfig().setString(ConfigConstants.CONFIG_BRANCH_SECTION,
  379. branchName, ConfigConstants.CONFIG_KEY_REMOTE, remote);
  380. clonedRepo.getConfig().setString(ConfigConstants.CONFIG_BRANCH_SECTION,
  381. branchName, ConfigConstants.CONFIG_KEY_MERGE, head.getName());
  382. String autosetupRebase = clonedRepo.getConfig().getString(
  383. ConfigConstants.CONFIG_BRANCH_SECTION, null,
  384. ConfigConstants.CONFIG_KEY_AUTOSETUPREBASE);
  385. if (ConfigConstants.CONFIG_KEY_ALWAYS.equals(autosetupRebase)
  386. || ConfigConstants.CONFIG_KEY_REMOTE.equals(autosetupRebase))
  387. clonedRepo.getConfig().setEnum(
  388. ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
  389. ConfigConstants.CONFIG_KEY_REBASE, BranchRebaseMode.REBASE);
  390. clonedRepo.getConfig().save();
  391. }
  392. private RevCommit parseCommit(Repository clonedRepo, Ref ref)
  393. throws MissingObjectException, IncorrectObjectTypeException,
  394. IOException {
  395. final RevCommit commit;
  396. try (RevWalk rw = new RevWalk(clonedRepo)) {
  397. commit = rw.parseCommit(ref.getObjectId());
  398. }
  399. return commit;
  400. }
  401. /**
  402. * Set the URI to clone from
  403. *
  404. * @param uri
  405. * the URI to clone from, or {@code null} to unset the URI. The
  406. * URI must be set before {@link #call} is called.
  407. * @return this instance
  408. */
  409. public CloneCommand setURI(String uri) {
  410. this.uri = uri;
  411. return this;
  412. }
  413. /**
  414. * The optional directory associated with the clone operation. If the
  415. * directory isn't set, a name associated with the source uri will be used.
  416. *
  417. * @see URIish#getHumanishName()
  418. * @param directory
  419. * the directory to clone to, or {@code null} if the directory
  420. * name should be taken from the source uri
  421. * @return this instance
  422. * @throws java.lang.IllegalStateException
  423. * if the combination of directory, gitDir and bare is illegal.
  424. * E.g. if for a non-bare repository directory and gitDir point
  425. * to the same directory of if for a bare repository both
  426. * directory and gitDir are specified
  427. */
  428. public CloneCommand setDirectory(File directory) {
  429. validateDirs(directory, gitDir, bare);
  430. this.directory = directory;
  431. return this;
  432. }
  433. /**
  434. * Set the repository meta directory (.git)
  435. *
  436. * @param gitDir
  437. * the repository meta directory, or {@code null} to choose one
  438. * automatically at clone time
  439. * @return this instance
  440. * @throws java.lang.IllegalStateException
  441. * if the combination of directory, gitDir and bare is illegal.
  442. * E.g. if for a non-bare repository directory and gitDir point
  443. * to the same directory of if for a bare repository both
  444. * directory and gitDir are specified
  445. * @since 3.6
  446. */
  447. public CloneCommand setGitDir(File gitDir) {
  448. validateDirs(directory, gitDir, bare);
  449. this.gitDir = gitDir;
  450. return this;
  451. }
  452. /**
  453. * Set whether the cloned repository shall be bare
  454. *
  455. * @param bare
  456. * whether the cloned repository is bare or not
  457. * @return this instance
  458. * @throws java.lang.IllegalStateException
  459. * if the combination of directory, gitDir and bare is illegal.
  460. * E.g. if for a non-bare repository directory and gitDir point
  461. * to the same directory of if for a bare repository both
  462. * directory and gitDir are specified
  463. */
  464. public CloneCommand setBare(boolean bare) throws IllegalStateException {
  465. validateDirs(directory, gitDir, bare);
  466. this.bare = bare;
  467. return this;
  468. }
  469. /**
  470. * Set the file system abstraction to be used for repositories created by
  471. * this command.
  472. *
  473. * @param fs
  474. * the abstraction.
  475. * @return {@code this} (for chaining calls).
  476. * @since 4.10
  477. */
  478. public CloneCommand setFs(FS fs) {
  479. this.fs = fs;
  480. return this;
  481. }
  482. /**
  483. * The remote name used to keep track of the upstream repository for the
  484. * clone operation. If no remote name is set, the default value of
  485. * <code>Constants.DEFAULT_REMOTE_NAME</code> will be used.
  486. *
  487. * @see Constants#DEFAULT_REMOTE_NAME
  488. * @param remote
  489. * name that keeps track of the upstream repository.
  490. * {@code null} means to use DEFAULT_REMOTE_NAME.
  491. * @return this instance
  492. */
  493. public CloneCommand setRemote(String remote) {
  494. if (remote == null) {
  495. remote = Constants.DEFAULT_REMOTE_NAME;
  496. }
  497. this.remote = remote;
  498. return this;
  499. }
  500. /**
  501. * Set the initial branch
  502. *
  503. * @param branch
  504. * the initial branch to check out when cloning the repository.
  505. * Can be specified as ref name (<code>refs/heads/master</code>),
  506. * branch name (<code>master</code>) or tag name
  507. * (<code>v1.2.3</code>). The default is to use the branch
  508. * pointed to by the cloned repository's HEAD and can be
  509. * requested by passing {@code null} or <code>HEAD</code>.
  510. * @return this instance
  511. */
  512. public CloneCommand setBranch(String branch) {
  513. if (branch == null) {
  514. branch = Constants.HEAD;
  515. }
  516. this.branch = branch;
  517. return this;
  518. }
  519. /**
  520. * The progress monitor associated with the clone operation. By default,
  521. * this is set to <code>NullProgressMonitor</code>
  522. *
  523. * @see NullProgressMonitor
  524. * @param monitor
  525. * a {@link org.eclipse.jgit.lib.ProgressMonitor}
  526. * @return {@code this}
  527. */
  528. public CloneCommand setProgressMonitor(ProgressMonitor monitor) {
  529. if (monitor == null) {
  530. monitor = NullProgressMonitor.INSTANCE;
  531. }
  532. this.monitor = monitor;
  533. return this;
  534. }
  535. /**
  536. * Set whether all branches have to be fetched
  537. *
  538. * @param cloneAllBranches
  539. * true when all branches have to be fetched (indicates wildcard
  540. * in created fetch refspec), false otherwise.
  541. * @return {@code this}
  542. */
  543. public CloneCommand setCloneAllBranches(boolean cloneAllBranches) {
  544. this.cloneAllBranches = cloneAllBranches;
  545. return this;
  546. }
  547. /**
  548. * Set whether to clone submodules
  549. *
  550. * @param cloneSubmodules
  551. * true to initialize and update submodules. Ignored when
  552. * {@link #setBare(boolean)} is set to true.
  553. * @return {@code this}
  554. */
  555. public CloneCommand setCloneSubmodules(boolean cloneSubmodules) {
  556. this.cloneSubmodules = cloneSubmodules;
  557. return this;
  558. }
  559. /**
  560. * Set branches to clone
  561. *
  562. * @param branchesToClone
  563. * collection of branches to clone. Ignored when allSelected is
  564. * true. Must be specified as full ref names (e.g.
  565. * <code>refs/heads/master</code>).
  566. * @return {@code this}
  567. */
  568. public CloneCommand setBranchesToClone(Collection<String> branchesToClone) {
  569. this.branchesToClone = branchesToClone;
  570. return this;
  571. }
  572. /**
  573. * Set whether to skip checking out a branch
  574. *
  575. * @param noCheckout
  576. * if set to <code>true</code> no branch will be checked out
  577. * after the clone. This enhances performance of the clone
  578. * command when there is no need for a checked out branch.
  579. * @return {@code this}
  580. */
  581. public CloneCommand setNoCheckout(boolean noCheckout) {
  582. this.noCheckout = noCheckout;
  583. return this;
  584. }
  585. /**
  586. * Register a progress callback.
  587. *
  588. * @param callback
  589. * the callback
  590. * @return {@code this}
  591. * @since 4.8
  592. */
  593. public CloneCommand setCallback(Callback callback) {
  594. this.callback = callback;
  595. return this;
  596. }
  597. private static void validateDirs(File directory, File gitDir, boolean bare)
  598. throws IllegalStateException {
  599. if (directory != null) {
  600. if (directory.exists() && !directory.isDirectory()) {
  601. throw new IllegalStateException(MessageFormat.format(
  602. JGitText.get().initFailedDirIsNoDirectory, directory));
  603. }
  604. if (gitDir != null && gitDir.exists() && !gitDir.isDirectory()) {
  605. throw new IllegalStateException(MessageFormat.format(
  606. JGitText.get().initFailedGitDirIsNoDirectory,
  607. gitDir));
  608. }
  609. if (bare) {
  610. if (gitDir != null && !gitDir.equals(directory))
  611. throw new IllegalStateException(MessageFormat.format(
  612. JGitText.get().initFailedBareRepoDifferentDirs,
  613. gitDir, directory));
  614. } else {
  615. if (gitDir != null && gitDir.equals(directory))
  616. throw new IllegalStateException(MessageFormat.format(
  617. JGitText.get().initFailedNonBareRepoSameDirs,
  618. gitDir, directory));
  619. }
  620. }
  621. }
  622. private void cleanup() {
  623. try {
  624. if (directory != null) {
  625. if (!directoryExistsInitially) {
  626. FileUtils.delete(directory, FileUtils.RECURSIVE
  627. | FileUtils.SKIP_MISSING | FileUtils.IGNORE_ERRORS);
  628. } else {
  629. deleteChildren(directory);
  630. }
  631. }
  632. if (gitDir != null) {
  633. if (!gitDirExistsInitially) {
  634. FileUtils.delete(gitDir, FileUtils.RECURSIVE
  635. | FileUtils.SKIP_MISSING | FileUtils.IGNORE_ERRORS);
  636. } else {
  637. deleteChildren(directory);
  638. }
  639. }
  640. } catch (IOException e) {
  641. // Ignore; this is a best-effort cleanup in error cases, and
  642. // IOException should not be raised anyway
  643. }
  644. }
  645. private void deleteChildren(File file) throws IOException {
  646. File[] files = file.listFiles();
  647. if (files == null) {
  648. return;
  649. }
  650. for (File child : files) {
  651. FileUtils.delete(child, FileUtils.RECURSIVE | FileUtils.SKIP_MISSING
  652. | FileUtils.IGNORE_ERRORS);
  653. }
  654. }
  655. }