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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  1. /*
  2. * Copyright (C) 2011, 2017 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.util.ArrayList;
  16. import java.util.Collection;
  17. import java.util.List;
  18. import org.eclipse.jgit.annotations.Nullable;
  19. import org.eclipse.jgit.api.errors.GitAPIException;
  20. import org.eclipse.jgit.api.errors.InvalidRemoteException;
  21. import org.eclipse.jgit.api.errors.JGitInternalException;
  22. import org.eclipse.jgit.dircache.DirCache;
  23. import org.eclipse.jgit.dircache.DirCacheCheckout;
  24. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  25. import org.eclipse.jgit.errors.MissingObjectException;
  26. import org.eclipse.jgit.internal.JGitText;
  27. import org.eclipse.jgit.lib.AnyObjectId;
  28. import org.eclipse.jgit.lib.BranchConfig.BranchRebaseMode;
  29. import org.eclipse.jgit.lib.ConfigConstants;
  30. import org.eclipse.jgit.lib.Constants;
  31. import org.eclipse.jgit.lib.NullProgressMonitor;
  32. import org.eclipse.jgit.lib.ObjectId;
  33. import org.eclipse.jgit.lib.ProgressMonitor;
  34. import org.eclipse.jgit.lib.Ref;
  35. import org.eclipse.jgit.lib.RefUpdate;
  36. import org.eclipse.jgit.lib.Repository;
  37. import org.eclipse.jgit.revwalk.RevCommit;
  38. import org.eclipse.jgit.revwalk.RevWalk;
  39. import org.eclipse.jgit.submodule.SubmoduleWalk;
  40. import org.eclipse.jgit.transport.FetchResult;
  41. import org.eclipse.jgit.transport.RefSpec;
  42. import org.eclipse.jgit.transport.RemoteConfig;
  43. import org.eclipse.jgit.transport.TagOpt;
  44. import org.eclipse.jgit.transport.URIish;
  45. import org.eclipse.jgit.util.FS;
  46. import org.eclipse.jgit.util.FileUtils;
  47. /**
  48. * Clone a repository into a new working directory
  49. *
  50. * @see <a href="http://www.kernel.org/pub/software/scm/git/docs/git-clone.html"
  51. * >Git documentation about Clone</a>
  52. */
  53. public class CloneCommand extends TransportCommand<CloneCommand, Git> {
  54. private String uri;
  55. private File directory;
  56. private File gitDir;
  57. private boolean bare;
  58. private FS fs;
  59. private String remote = Constants.DEFAULT_REMOTE_NAME;
  60. private String branch = Constants.HEAD;
  61. private ProgressMonitor monitor = NullProgressMonitor.INSTANCE;
  62. private boolean cloneAllBranches;
  63. private boolean mirror;
  64. private boolean cloneSubmodules;
  65. private boolean noCheckout;
  66. private Collection<String> branchesToClone;
  67. private Callback callback;
  68. private boolean directoryExistsInitially;
  69. private boolean gitDirExistsInitially;
  70. private FETCH_TYPE fetchType;
  71. private enum FETCH_TYPE {
  72. MULTIPLE_BRANCHES, ALL_BRANCHES, MIRROR
  73. }
  74. /**
  75. * Callback for status of clone operation.
  76. *
  77. * @since 4.8
  78. */
  79. public interface Callback {
  80. /**
  81. * Notify initialized submodules.
  82. *
  83. * @param submodules
  84. * the submodules
  85. *
  86. */
  87. void initializedSubmodules(Collection<String> submodules);
  88. /**
  89. * Notify starting to clone a submodule.
  90. *
  91. * @param path
  92. * the submodule path
  93. */
  94. void cloningSubmodule(String path);
  95. /**
  96. * Notify checkout of commit
  97. *
  98. * @param commit
  99. * the id of the commit being checked out
  100. * @param path
  101. * the submodule path
  102. */
  103. void checkingOut(AnyObjectId commit, String path);
  104. }
  105. /**
  106. * Create clone command with no repository set
  107. */
  108. public CloneCommand() {
  109. super(null);
  110. }
  111. /**
  112. * Get the git directory. This is primarily used for tests.
  113. *
  114. * @return the git directory
  115. */
  116. @Nullable
  117. File getDirectory() {
  118. return directory;
  119. }
  120. /**
  121. * {@inheritDoc}
  122. * <p>
  123. * Executes the {@code Clone} command.
  124. *
  125. * The Git instance returned by this command needs to be closed by the
  126. * caller to free resources held by the underlying {@link Repository}
  127. * instance. It is recommended to call this method as soon as you don't need
  128. * a reference to this {@link Git} instance and the underlying
  129. * {@link Repository} instance anymore.
  130. */
  131. @Override
  132. public Git call() throws GitAPIException, InvalidRemoteException,
  133. org.eclipse.jgit.api.errors.TransportException {
  134. URIish u = null;
  135. try {
  136. u = new URIish(uri);
  137. verifyDirectories(u);
  138. } catch (URISyntaxException e) {
  139. throw new InvalidRemoteException(
  140. MessageFormat.format(JGitText.get().invalidURL, uri), e);
  141. }
  142. setFetchType();
  143. @SuppressWarnings("resource") // Closed by caller
  144. Repository repository = init();
  145. FetchResult fetchResult = null;
  146. Thread cleanupHook = new Thread(() -> cleanup());
  147. Runtime.getRuntime().addShutdownHook(cleanupHook);
  148. try {
  149. fetchResult = fetch(repository, u);
  150. } catch (IOException ioe) {
  151. if (repository != null) {
  152. repository.close();
  153. }
  154. cleanup();
  155. throw new JGitInternalException(ioe.getMessage(), ioe);
  156. } catch (URISyntaxException e) {
  157. if (repository != null) {
  158. repository.close();
  159. }
  160. cleanup();
  161. throw new InvalidRemoteException(
  162. MessageFormat.format(JGitText.get().invalidRemote, remote),
  163. e);
  164. } catch (GitAPIException | RuntimeException e) {
  165. if (repository != null) {
  166. repository.close();
  167. }
  168. cleanup();
  169. throw e;
  170. } finally {
  171. Runtime.getRuntime().removeShutdownHook(cleanupHook);
  172. }
  173. if (!noCheckout) {
  174. try {
  175. checkout(repository, fetchResult);
  176. } catch (IOException ioe) {
  177. repository.close();
  178. throw new JGitInternalException(ioe.getMessage(), ioe);
  179. } catch (GitAPIException | RuntimeException e) {
  180. repository.close();
  181. throw e;
  182. }
  183. }
  184. return new Git(repository, true);
  185. }
  186. private void setFetchType() {
  187. if (mirror) {
  188. fetchType = FETCH_TYPE.MIRROR;
  189. setBare(true);
  190. } else if (cloneAllBranches) {
  191. fetchType = FETCH_TYPE.ALL_BRANCHES;
  192. } else if (branchesToClone != null && !branchesToClone.isEmpty()) {
  193. fetchType = FETCH_TYPE.MULTIPLE_BRANCHES;
  194. } else {
  195. // Default: neither mirror nor all nor specific refs given
  196. fetchType = FETCH_TYPE.ALL_BRANCHES;
  197. }
  198. }
  199. private static boolean isNonEmptyDirectory(File dir) {
  200. if (dir != null && dir.exists()) {
  201. File[] files = dir.listFiles();
  202. return files != null && files.length != 0;
  203. }
  204. return false;
  205. }
  206. void verifyDirectories(URIish u) {
  207. if (directory == null && gitDir == null) {
  208. directory = new File(u.getHumanishName() + (bare ? Constants.DOT_GIT_EXT : "")); //$NON-NLS-1$
  209. }
  210. directoryExistsInitially = directory != null && directory.exists();
  211. gitDirExistsInitially = gitDir != null && gitDir.exists();
  212. validateDirs(directory, gitDir, bare);
  213. if (isNonEmptyDirectory(directory)) {
  214. throw new JGitInternalException(MessageFormat.format(
  215. JGitText.get().cloneNonEmptyDirectory, directory.getName()));
  216. }
  217. if (isNonEmptyDirectory(gitDir)) {
  218. throw new JGitInternalException(MessageFormat.format(
  219. JGitText.get().cloneNonEmptyDirectory, gitDir.getName()));
  220. }
  221. }
  222. private Repository init() throws GitAPIException {
  223. InitCommand command = Git.init();
  224. command.setBare(bare);
  225. if (fs != null) {
  226. command.setFs(fs);
  227. }
  228. if (directory != null) {
  229. command.setDirectory(directory);
  230. }
  231. if (gitDir != null) {
  232. command.setGitDir(gitDir);
  233. }
  234. return command.call().getRepository();
  235. }
  236. private FetchResult fetch(Repository clonedRepo, URIish u)
  237. throws URISyntaxException,
  238. org.eclipse.jgit.api.errors.TransportException, IOException,
  239. GitAPIException {
  240. // create the remote config and save it
  241. RemoteConfig config = new RemoteConfig(clonedRepo.getConfig(), remote);
  242. config.addURI(u);
  243. boolean fetchAll = fetchType == FETCH_TYPE.ALL_BRANCHES
  244. || fetchType == FETCH_TYPE.MIRROR;
  245. config.setFetchRefSpecs(calculateRefSpecs(fetchType, config.getName()));
  246. config.setMirror(fetchType == FETCH_TYPE.MIRROR);
  247. config.update(clonedRepo.getConfig());
  248. clonedRepo.getConfig().save();
  249. // run the fetch command
  250. FetchCommand command = new FetchCommand(clonedRepo);
  251. command.setRemote(remote);
  252. command.setProgressMonitor(monitor);
  253. command.setTagOpt(fetchAll ? TagOpt.FETCH_TAGS : TagOpt.AUTO_FOLLOW);
  254. configure(command);
  255. return command.call();
  256. }
  257. private List<RefSpec> calculateRefSpecs(FETCH_TYPE type,
  258. String remoteName) {
  259. List<RefSpec> specs = new ArrayList<>();
  260. if (type == FETCH_TYPE.MIRROR) {
  261. specs.add(new RefSpec().setForceUpdate(true).setSourceDestination(
  262. Constants.R_REFS + '*', Constants.R_REFS + '*'));
  263. } else {
  264. RefSpec heads = new RefSpec();
  265. heads = heads.setForceUpdate(true);
  266. final String dst = (bare ? Constants.R_HEADS
  267. : Constants.R_REMOTES + remoteName + '/') + '*';
  268. heads = heads.setSourceDestination(Constants.R_HEADS + '*', dst);
  269. if (type == FETCH_TYPE.MULTIPLE_BRANCHES) {
  270. RefSpec tags = new RefSpec().setForceUpdate(true)
  271. .setSourceDestination(Constants.R_TAGS + '*',
  272. Constants.R_TAGS + '*');
  273. for (String selectedRef : branchesToClone) {
  274. if (heads.matchSource(selectedRef)) {
  275. specs.add(heads.expandFromSource(selectedRef));
  276. } else if (tags.matchSource(selectedRef)) {
  277. specs.add(tags.expandFromSource(selectedRef));
  278. }
  279. }
  280. } else {
  281. // We'll fetch the tags anyway.
  282. specs.add(heads);
  283. }
  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. * <p>
  538. * If {@code false}, use {@link #setBranchesToClone(Collection)} to define
  539. * what will be cloned. If neither are set, all branches will be cloned.
  540. * </p>
  541. *
  542. * @param cloneAllBranches
  543. * {@code true} when all branches have to be fetched (indicates
  544. * wildcard in created fetch refspec), {@code false} otherwise.
  545. * @return {@code this}
  546. */
  547. public CloneCommand setCloneAllBranches(boolean cloneAllBranches) {
  548. this.cloneAllBranches = cloneAllBranches;
  549. return this;
  550. }
  551. /**
  552. * Set up a mirror of the source repository. This implies that a bare
  553. * repository will be created. Compared to {@link #setBare},
  554. * {@code #setMirror} not only maps local branches of the source to local
  555. * branches of the target, it maps all refs (including remote-tracking
  556. * branches, notes etc.) and sets up a refspec configuration such that all
  557. * these refs are overwritten by a git remote update in the target
  558. * repository.
  559. *
  560. * @param mirror
  561. * whether to mirror all refs from the source repository
  562. *
  563. * @return {@code this}
  564. * @since 5.6
  565. */
  566. public CloneCommand setMirror(boolean mirror) {
  567. this.mirror = mirror;
  568. return this;
  569. }
  570. /**
  571. * Set whether to clone submodules
  572. *
  573. * @param cloneSubmodules
  574. * true to initialize and update submodules. Ignored when
  575. * {@link #setBare(boolean)} is set to true.
  576. * @return {@code this}
  577. */
  578. public CloneCommand setCloneSubmodules(boolean cloneSubmodules) {
  579. this.cloneSubmodules = cloneSubmodules;
  580. return this;
  581. }
  582. /**
  583. * Set the branches or tags to clone.
  584. * <p>
  585. * This is ignored if {@link #setCloneAllBranches(boolean)
  586. * setCloneAllBranches(true)} or {@link #setMirror(boolean) setMirror(true)}
  587. * is used. If {@code branchesToClone} is {@code null} or empty, it's also
  588. * ignored.
  589. * </p>
  590. *
  591. * @param branchesToClone
  592. * collection of branches to clone. Must be specified as full ref
  593. * names (e.g. {@code refs/heads/master} or
  594. * {@code refs/tags/v1.0.0}).
  595. * @return {@code this}
  596. */
  597. public CloneCommand setBranchesToClone(Collection<String> branchesToClone) {
  598. this.branchesToClone = branchesToClone;
  599. return this;
  600. }
  601. /**
  602. * Set whether to skip checking out a branch
  603. *
  604. * @param noCheckout
  605. * if set to <code>true</code> no branch will be checked out
  606. * after the clone. This enhances performance of the clone
  607. * command when there is no need for a checked out branch.
  608. * @return {@code this}
  609. */
  610. public CloneCommand setNoCheckout(boolean noCheckout) {
  611. this.noCheckout = noCheckout;
  612. return this;
  613. }
  614. /**
  615. * Register a progress callback.
  616. *
  617. * @param callback
  618. * the callback
  619. * @return {@code this}
  620. * @since 4.8
  621. */
  622. public CloneCommand setCallback(Callback callback) {
  623. this.callback = callback;
  624. return this;
  625. }
  626. private static void validateDirs(File directory, File gitDir, boolean bare)
  627. throws IllegalStateException {
  628. if (directory != null) {
  629. if (directory.exists() && !directory.isDirectory()) {
  630. throw new IllegalStateException(MessageFormat.format(
  631. JGitText.get().initFailedDirIsNoDirectory, directory));
  632. }
  633. if (gitDir != null && gitDir.exists() && !gitDir.isDirectory()) {
  634. throw new IllegalStateException(MessageFormat.format(
  635. JGitText.get().initFailedGitDirIsNoDirectory,
  636. gitDir));
  637. }
  638. if (bare) {
  639. if (gitDir != null && !gitDir.equals(directory))
  640. throw new IllegalStateException(MessageFormat.format(
  641. JGitText.get().initFailedBareRepoDifferentDirs,
  642. gitDir, directory));
  643. } else {
  644. if (gitDir != null && gitDir.equals(directory))
  645. throw new IllegalStateException(MessageFormat.format(
  646. JGitText.get().initFailedNonBareRepoSameDirs,
  647. gitDir, directory));
  648. }
  649. }
  650. }
  651. private void cleanup() {
  652. try {
  653. if (directory != null) {
  654. if (!directoryExistsInitially) {
  655. FileUtils.delete(directory, FileUtils.RECURSIVE
  656. | FileUtils.SKIP_MISSING | FileUtils.IGNORE_ERRORS);
  657. } else {
  658. deleteChildren(directory);
  659. }
  660. }
  661. if (gitDir != null) {
  662. if (!gitDirExistsInitially) {
  663. FileUtils.delete(gitDir, FileUtils.RECURSIVE
  664. | FileUtils.SKIP_MISSING | FileUtils.IGNORE_ERRORS);
  665. } else {
  666. deleteChildren(gitDir);
  667. }
  668. }
  669. } catch (IOException e) {
  670. // Ignore; this is a best-effort cleanup in error cases, and
  671. // IOException should not be raised anyway
  672. }
  673. }
  674. private void deleteChildren(File file) throws IOException {
  675. File[] files = file.listFiles();
  676. if (files == null) {
  677. return;
  678. }
  679. for (File child : files) {
  680. FileUtils.delete(child, FileUtils.RECURSIVE | FileUtils.SKIP_MISSING
  681. | FileUtils.IGNORE_ERRORS);
  682. }
  683. }
  684. }