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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752
  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));
  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(MessageFormat.format(
  162. JGitText.get().invalidRemote, remote));
  163. } catch (GitAPIException | RuntimeException e) {
  164. if (repository != null) {
  165. repository.close();
  166. }
  167. cleanup();
  168. throw e;
  169. } finally {
  170. Runtime.getRuntime().removeShutdownHook(cleanupHook);
  171. }
  172. if (!noCheckout) {
  173. try {
  174. checkout(repository, fetchResult);
  175. } catch (IOException ioe) {
  176. repository.close();
  177. throw new JGitInternalException(ioe.getMessage(), ioe);
  178. } catch (GitAPIException | RuntimeException e) {
  179. repository.close();
  180. throw e;
  181. }
  182. }
  183. return new Git(repository, true);
  184. }
  185. private void setFetchType() {
  186. if (mirror) {
  187. fetchType = FETCH_TYPE.MIRROR;
  188. setBare(true);
  189. } else if (cloneAllBranches) {
  190. fetchType = FETCH_TYPE.ALL_BRANCHES;
  191. } else if (branchesToClone != null && !branchesToClone.isEmpty()) {
  192. fetchType = FETCH_TYPE.MULTIPLE_BRANCHES;
  193. } else {
  194. // Default: neither mirror nor all nor specific refs given
  195. fetchType = FETCH_TYPE.ALL_BRANCHES;
  196. }
  197. }
  198. private static boolean isNonEmptyDirectory(File dir) {
  199. if (dir != null && dir.exists()) {
  200. File[] files = dir.listFiles();
  201. return files != null && files.length != 0;
  202. }
  203. return false;
  204. }
  205. void verifyDirectories(URIish u) {
  206. if (directory == null && gitDir == null) {
  207. directory = new File(u.getHumanishName() + (bare ? Constants.DOT_GIT_EXT : "")); //$NON-NLS-1$
  208. }
  209. directoryExistsInitially = directory != null && directory.exists();
  210. gitDirExistsInitially = gitDir != null && gitDir.exists();
  211. validateDirs(directory, gitDir, bare);
  212. if (isNonEmptyDirectory(directory)) {
  213. throw new JGitInternalException(MessageFormat.format(
  214. JGitText.get().cloneNonEmptyDirectory, directory.getName()));
  215. }
  216. if (isNonEmptyDirectory(gitDir)) {
  217. throw new JGitInternalException(MessageFormat.format(
  218. JGitText.get().cloneNonEmptyDirectory, gitDir.getName()));
  219. }
  220. }
  221. private Repository init() throws GitAPIException {
  222. InitCommand command = Git.init();
  223. command.setBare(bare);
  224. if (fs != null) {
  225. command.setFs(fs);
  226. }
  227. if (directory != null) {
  228. command.setDirectory(directory);
  229. }
  230. if (gitDir != null) {
  231. command.setGitDir(gitDir);
  232. }
  233. return command.call().getRepository();
  234. }
  235. private FetchResult fetch(Repository clonedRepo, URIish u)
  236. throws URISyntaxException,
  237. org.eclipse.jgit.api.errors.TransportException, IOException,
  238. GitAPIException {
  239. // create the remote config and save it
  240. RemoteConfig config = new RemoteConfig(clonedRepo.getConfig(), remote);
  241. config.addURI(u);
  242. boolean fetchAll = fetchType == FETCH_TYPE.ALL_BRANCHES
  243. || fetchType == FETCH_TYPE.MIRROR;
  244. config.setFetchRefSpecs(calculateRefSpecs(fetchType, config.getName()));
  245. config.setMirror(fetchType == FETCH_TYPE.MIRROR);
  246. config.update(clonedRepo.getConfig());
  247. clonedRepo.getConfig().save();
  248. // run the fetch command
  249. FetchCommand command = new FetchCommand(clonedRepo);
  250. command.setRemote(remote);
  251. command.setProgressMonitor(monitor);
  252. command.setTagOpt(fetchAll ? TagOpt.FETCH_TAGS : TagOpt.AUTO_FOLLOW);
  253. configure(command);
  254. return command.call();
  255. }
  256. private List<RefSpec> calculateRefSpecs(FETCH_TYPE type,
  257. String remoteName) {
  258. List<RefSpec> specs = new ArrayList<>();
  259. if (type == FETCH_TYPE.MIRROR) {
  260. specs.add(new RefSpec().setForceUpdate(true).setSourceDestination(
  261. Constants.R_REFS + '*', Constants.R_REFS + '*'));
  262. } else {
  263. RefSpec heads = new RefSpec();
  264. heads = heads.setForceUpdate(true);
  265. final String dst = (bare ? Constants.R_HEADS
  266. : Constants.R_REMOTES + remoteName + '/') + '*';
  267. heads = heads.setSourceDestination(Constants.R_HEADS + '*', dst);
  268. if (type == FETCH_TYPE.MULTIPLE_BRANCHES) {
  269. RefSpec tags = new RefSpec().setForceUpdate(true)
  270. .setSourceDestination(Constants.R_TAGS + '*',
  271. Constants.R_TAGS + '*');
  272. for (String selectedRef : branchesToClone) {
  273. if (heads.matchSource(selectedRef)) {
  274. specs.add(heads.expandFromSource(selectedRef));
  275. } else if (tags.matchSource(selectedRef)) {
  276. specs.add(tags.expandFromSource(selectedRef));
  277. }
  278. }
  279. } else {
  280. // We'll fetch the tags anyway.
  281. specs.add(heads);
  282. }
  283. }
  284. return specs;
  285. }
  286. private void checkout(Repository clonedRepo, FetchResult result)
  287. throws MissingObjectException, IncorrectObjectTypeException,
  288. IOException, GitAPIException {
  289. Ref head = null;
  290. if (branch.equals(Constants.HEAD)) {
  291. Ref foundBranch = findBranchToCheckout(result);
  292. if (foundBranch != null)
  293. head = foundBranch;
  294. }
  295. if (head == null) {
  296. head = result.getAdvertisedRef(branch);
  297. if (head == null)
  298. head = result.getAdvertisedRef(Constants.R_HEADS + branch);
  299. if (head == null)
  300. head = result.getAdvertisedRef(Constants.R_TAGS + branch);
  301. }
  302. if (head == null || head.getObjectId() == null)
  303. return; // TODO throw exception?
  304. if (head.getName().startsWith(Constants.R_HEADS)) {
  305. final RefUpdate newHead = clonedRepo.updateRef(Constants.HEAD);
  306. newHead.disableRefLog();
  307. newHead.link(head.getName());
  308. addMergeConfig(clonedRepo, head);
  309. }
  310. final RevCommit commit = parseCommit(clonedRepo, head);
  311. boolean detached = !head.getName().startsWith(Constants.R_HEADS);
  312. RefUpdate u = clonedRepo.updateRef(Constants.HEAD, detached);
  313. u.setNewObjectId(commit.getId());
  314. u.forceUpdate();
  315. if (!bare) {
  316. DirCache dc = clonedRepo.lockDirCache();
  317. DirCacheCheckout co = new DirCacheCheckout(clonedRepo, dc,
  318. commit.getTree());
  319. co.setProgressMonitor(monitor);
  320. co.checkout();
  321. if (cloneSubmodules)
  322. cloneSubmodules(clonedRepo);
  323. }
  324. }
  325. private void cloneSubmodules(Repository clonedRepo) throws IOException,
  326. GitAPIException {
  327. SubmoduleInitCommand init = new SubmoduleInitCommand(clonedRepo);
  328. Collection<String> submodules = init.call();
  329. if (submodules.isEmpty()) {
  330. return;
  331. }
  332. if (callback != null) {
  333. callback.initializedSubmodules(submodules);
  334. }
  335. SubmoduleUpdateCommand update = new SubmoduleUpdateCommand(clonedRepo);
  336. configure(update);
  337. update.setProgressMonitor(monitor);
  338. update.setCallback(callback);
  339. if (!update.call().isEmpty()) {
  340. SubmoduleWalk walk = SubmoduleWalk.forIndex(clonedRepo);
  341. while (walk.next()) {
  342. try (Repository subRepo = walk.getRepository()) {
  343. if (subRepo != null) {
  344. cloneSubmodules(subRepo);
  345. }
  346. }
  347. }
  348. }
  349. }
  350. private Ref findBranchToCheckout(FetchResult result) {
  351. final Ref idHEAD = result.getAdvertisedRef(Constants.HEAD);
  352. ObjectId headId = idHEAD != null ? idHEAD.getObjectId() : null;
  353. if (headId == null) {
  354. return null;
  355. }
  356. Ref master = result.getAdvertisedRef(Constants.R_HEADS
  357. + Constants.MASTER);
  358. ObjectId objectId = master != null ? master.getObjectId() : null;
  359. if (headId.equals(objectId)) {
  360. return master;
  361. }
  362. Ref foundBranch = null;
  363. for (Ref r : result.getAdvertisedRefs()) {
  364. final String n = r.getName();
  365. if (!n.startsWith(Constants.R_HEADS))
  366. continue;
  367. if (headId.equals(r.getObjectId())) {
  368. foundBranch = r;
  369. break;
  370. }
  371. }
  372. return foundBranch;
  373. }
  374. private void addMergeConfig(Repository clonedRepo, Ref head)
  375. throws IOException {
  376. String branchName = Repository.shortenRefName(head.getName());
  377. clonedRepo.getConfig().setString(ConfigConstants.CONFIG_BRANCH_SECTION,
  378. branchName, ConfigConstants.CONFIG_KEY_REMOTE, remote);
  379. clonedRepo.getConfig().setString(ConfigConstants.CONFIG_BRANCH_SECTION,
  380. branchName, ConfigConstants.CONFIG_KEY_MERGE, head.getName());
  381. String autosetupRebase = clonedRepo.getConfig().getString(
  382. ConfigConstants.CONFIG_BRANCH_SECTION, null,
  383. ConfigConstants.CONFIG_KEY_AUTOSETUPREBASE);
  384. if (ConfigConstants.CONFIG_KEY_ALWAYS.equals(autosetupRebase)
  385. || ConfigConstants.CONFIG_KEY_REMOTE.equals(autosetupRebase))
  386. clonedRepo.getConfig().setEnum(
  387. ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
  388. ConfigConstants.CONFIG_KEY_REBASE, BranchRebaseMode.REBASE);
  389. clonedRepo.getConfig().save();
  390. }
  391. private RevCommit parseCommit(Repository clonedRepo, Ref ref)
  392. throws MissingObjectException, IncorrectObjectTypeException,
  393. IOException {
  394. final RevCommit commit;
  395. try (RevWalk rw = new RevWalk(clonedRepo)) {
  396. commit = rw.parseCommit(ref.getObjectId());
  397. }
  398. return commit;
  399. }
  400. /**
  401. * Set the URI to clone from
  402. *
  403. * @param uri
  404. * the URI to clone from, or {@code null} to unset the URI. The
  405. * URI must be set before {@link #call} is called.
  406. * @return this instance
  407. */
  408. public CloneCommand setURI(String uri) {
  409. this.uri = uri;
  410. return this;
  411. }
  412. /**
  413. * The optional directory associated with the clone operation. If the
  414. * directory isn't set, a name associated with the source uri will be used.
  415. *
  416. * @see URIish#getHumanishName()
  417. * @param directory
  418. * the directory to clone to, or {@code null} if the directory
  419. * name should be taken from the source uri
  420. * @return this instance
  421. * @throws java.lang.IllegalStateException
  422. * if the combination of directory, gitDir and bare is illegal.
  423. * E.g. if for a non-bare repository directory and gitDir point
  424. * to the same directory of if for a bare repository both
  425. * directory and gitDir are specified
  426. */
  427. public CloneCommand setDirectory(File directory) {
  428. validateDirs(directory, gitDir, bare);
  429. this.directory = directory;
  430. return this;
  431. }
  432. /**
  433. * Set the repository meta directory (.git)
  434. *
  435. * @param gitDir
  436. * the repository meta directory, or {@code null} to choose one
  437. * automatically at clone time
  438. * @return this instance
  439. * @throws java.lang.IllegalStateException
  440. * if the combination of directory, gitDir and bare is illegal.
  441. * E.g. if for a non-bare repository directory and gitDir point
  442. * to the same directory of if for a bare repository both
  443. * directory and gitDir are specified
  444. * @since 3.6
  445. */
  446. public CloneCommand setGitDir(File gitDir) {
  447. validateDirs(directory, gitDir, bare);
  448. this.gitDir = gitDir;
  449. return this;
  450. }
  451. /**
  452. * Set whether the cloned repository shall be bare
  453. *
  454. * @param bare
  455. * whether the cloned repository is bare or not
  456. * @return this instance
  457. * @throws java.lang.IllegalStateException
  458. * if the combination of directory, gitDir and bare is illegal.
  459. * E.g. if for a non-bare repository directory and gitDir point
  460. * to the same directory of if for a bare repository both
  461. * directory and gitDir are specified
  462. */
  463. public CloneCommand setBare(boolean bare) throws IllegalStateException {
  464. validateDirs(directory, gitDir, bare);
  465. this.bare = bare;
  466. return this;
  467. }
  468. /**
  469. * Set the file system abstraction to be used for repositories created by
  470. * this command.
  471. *
  472. * @param fs
  473. * the abstraction.
  474. * @return {@code this} (for chaining calls).
  475. * @since 4.10
  476. */
  477. public CloneCommand setFs(FS fs) {
  478. this.fs = fs;
  479. return this;
  480. }
  481. /**
  482. * The remote name used to keep track of the upstream repository for the
  483. * clone operation. If no remote name is set, the default value of
  484. * <code>Constants.DEFAULT_REMOTE_NAME</code> will be used.
  485. *
  486. * @see Constants#DEFAULT_REMOTE_NAME
  487. * @param remote
  488. * name that keeps track of the upstream repository.
  489. * {@code null} means to use DEFAULT_REMOTE_NAME.
  490. * @return this instance
  491. */
  492. public CloneCommand setRemote(String remote) {
  493. if (remote == null) {
  494. remote = Constants.DEFAULT_REMOTE_NAME;
  495. }
  496. this.remote = remote;
  497. return this;
  498. }
  499. /**
  500. * Set the initial branch
  501. *
  502. * @param branch
  503. * the initial branch to check out when cloning the repository.
  504. * Can be specified as ref name (<code>refs/heads/master</code>),
  505. * branch name (<code>master</code>) or tag name
  506. * (<code>v1.2.3</code>). The default is to use the branch
  507. * pointed to by the cloned repository's HEAD and can be
  508. * requested by passing {@code null} or <code>HEAD</code>.
  509. * @return this instance
  510. */
  511. public CloneCommand setBranch(String branch) {
  512. if (branch == null) {
  513. branch = Constants.HEAD;
  514. }
  515. this.branch = branch;
  516. return this;
  517. }
  518. /**
  519. * The progress monitor associated with the clone operation. By default,
  520. * this is set to <code>NullProgressMonitor</code>
  521. *
  522. * @see NullProgressMonitor
  523. * @param monitor
  524. * a {@link org.eclipse.jgit.lib.ProgressMonitor}
  525. * @return {@code this}
  526. */
  527. public CloneCommand setProgressMonitor(ProgressMonitor monitor) {
  528. if (monitor == null) {
  529. monitor = NullProgressMonitor.INSTANCE;
  530. }
  531. this.monitor = monitor;
  532. return this;
  533. }
  534. /**
  535. * Set whether all branches have to be fetched.
  536. * <p>
  537. * If {@code false}, use {@link #setBranchesToClone(Collection)} to define
  538. * what will be cloned. If neither are set, all branches will be cloned.
  539. * </p>
  540. *
  541. * @param cloneAllBranches
  542. * {@code true} when all branches have to be fetched (indicates
  543. * wildcard in created fetch refspec), {@code false} otherwise.
  544. * @return {@code this}
  545. */
  546. public CloneCommand setCloneAllBranches(boolean cloneAllBranches) {
  547. this.cloneAllBranches = cloneAllBranches;
  548. return this;
  549. }
  550. /**
  551. * Set up a mirror of the source repository. This implies that a bare
  552. * repository will be created. Compared to {@link #setBare},
  553. * {@code #setMirror} not only maps local branches of the source to local
  554. * branches of the target, it maps all refs (including remote-tracking
  555. * branches, notes etc.) and sets up a refspec configuration such that all
  556. * these refs are overwritten by a git remote update in the target
  557. * repository.
  558. *
  559. * @param mirror
  560. * whether to mirror all refs from the source repository
  561. *
  562. * @return {@code this}
  563. * @since 5.6
  564. */
  565. public CloneCommand setMirror(boolean mirror) {
  566. this.mirror = mirror;
  567. return this;
  568. }
  569. /**
  570. * Set whether to clone submodules
  571. *
  572. * @param cloneSubmodules
  573. * true to initialize and update submodules. Ignored when
  574. * {@link #setBare(boolean)} is set to true.
  575. * @return {@code this}
  576. */
  577. public CloneCommand setCloneSubmodules(boolean cloneSubmodules) {
  578. this.cloneSubmodules = cloneSubmodules;
  579. return this;
  580. }
  581. /**
  582. * Set the branches or tags to clone.
  583. * <p>
  584. * This is ignored if {@link #setCloneAllBranches(boolean)
  585. * setCloneAllBranches(true)} or {@link #setMirror(boolean) setMirror(true)}
  586. * is used. If {@code branchesToClone} is {@code null} or empty, it's also
  587. * ignored.
  588. * </p>
  589. *
  590. * @param branchesToClone
  591. * collection of branches to clone. Must be specified as full ref
  592. * names (e.g. {@code refs/heads/master} or
  593. * {@code refs/tags/v1.0.0}).
  594. * @return {@code this}
  595. */
  596. public CloneCommand setBranchesToClone(Collection<String> branchesToClone) {
  597. this.branchesToClone = branchesToClone;
  598. return this;
  599. }
  600. /**
  601. * Set whether to skip checking out a branch
  602. *
  603. * @param noCheckout
  604. * if set to <code>true</code> no branch will be checked out
  605. * after the clone. This enhances performance of the clone
  606. * command when there is no need for a checked out branch.
  607. * @return {@code this}
  608. */
  609. public CloneCommand setNoCheckout(boolean noCheckout) {
  610. this.noCheckout = noCheckout;
  611. return this;
  612. }
  613. /**
  614. * Register a progress callback.
  615. *
  616. * @param callback
  617. * the callback
  618. * @return {@code this}
  619. * @since 4.8
  620. */
  621. public CloneCommand setCallback(Callback callback) {
  622. this.callback = callback;
  623. return this;
  624. }
  625. private static void validateDirs(File directory, File gitDir, boolean bare)
  626. throws IllegalStateException {
  627. if (directory != null) {
  628. if (directory.exists() && !directory.isDirectory()) {
  629. throw new IllegalStateException(MessageFormat.format(
  630. JGitText.get().initFailedDirIsNoDirectory, directory));
  631. }
  632. if (gitDir != null && gitDir.exists() && !gitDir.isDirectory()) {
  633. throw new IllegalStateException(MessageFormat.format(
  634. JGitText.get().initFailedGitDirIsNoDirectory,
  635. gitDir));
  636. }
  637. if (bare) {
  638. if (gitDir != null && !gitDir.equals(directory))
  639. throw new IllegalStateException(MessageFormat.format(
  640. JGitText.get().initFailedBareRepoDifferentDirs,
  641. gitDir, directory));
  642. } else {
  643. if (gitDir != null && gitDir.equals(directory))
  644. throw new IllegalStateException(MessageFormat.format(
  645. JGitText.get().initFailedNonBareRepoSameDirs,
  646. gitDir, directory));
  647. }
  648. }
  649. }
  650. private void cleanup() {
  651. try {
  652. if (directory != null) {
  653. if (!directoryExistsInitially) {
  654. FileUtils.delete(directory, FileUtils.RECURSIVE
  655. | FileUtils.SKIP_MISSING | FileUtils.IGNORE_ERRORS);
  656. } else {
  657. deleteChildren(directory);
  658. }
  659. }
  660. if (gitDir != null) {
  661. if (!gitDirExistsInitially) {
  662. FileUtils.delete(gitDir, FileUtils.RECURSIVE
  663. | FileUtils.SKIP_MISSING | FileUtils.IGNORE_ERRORS);
  664. } else {
  665. deleteChildren(gitDir);
  666. }
  667. }
  668. } catch (IOException e) {
  669. // Ignore; this is a best-effort cleanup in error cases, and
  670. // IOException should not be raised anyway
  671. }
  672. }
  673. private void deleteChildren(File file) throws IOException {
  674. File[] files = file.listFiles();
  675. if (files == null) {
  676. return;
  677. }
  678. for (File child : files) {
  679. FileUtils.delete(child, FileUtils.RECURSIVE | FileUtils.SKIP_MISSING
  680. | FileUtils.IGNORE_ERRORS);
  681. }
  682. }
  683. }