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

Enable full Transport configuration for JGit API commands Add a TransportConfigCallback parameter to JGit API commands, to allow consumers of the JGit command API to perform custom Transport configuration that would be otherwise difficult to anticipate & expose on the API command builders. My specific use-case is configuring additional properties on SshTransport - I need to take over the SshSessionFactory used by the transport. Using TransportConfigCallback I can simply do this (rather than reimplement the API command classes): public void configure(Transport tn) { if (tn instanceof SshTransport) { ((SshTransport) tn).setSshSessionFactory(factoryProvider.get()); } } Adding an explicit setSshSessionFactory() method to the JGit command classes would bloat the API. Also, creating the replacement SshSessionFactory is unnecessary if the transport is not SSH, but the type of the Transport is only known once the remote has been resolved and the URI parsed - consequently it makes sense to perform this step in a callback, where the transport instance can be inspected to determine if it's of a relevant type. A note about where this leaves the API - there are now 4 commands: CloneCommand PullCommand FetchCommand PushCommand -that share 3 identical transport-related parameters: timeout credentialsProvider transportConfigurator I think there's potential for introducing an interface or val-object to identify/encapsulate this repetition, which I'd be happy to do in a subsequent commit. Change-Id: I8983c3627cdd7d7b2aeb0b6a3dadee553378b951 Signed-off-by: Roberto Tyley <roberto.tyley@gmail.com>
12 years ago
Fix corrupted CloneCommand bare-repo fetch-refspec (#402031) CloneCommand has been creating fetch refspecs like this on bare clones: [remote "origin"] url = ssh://example.com/my-repo.git fetch = +refs/heads/*:refs/heads//* As you can see, the destination ref pattern has a superfluous slash. It looks like this behaviour has always been the case for CloneCommand, at least since cc2197ed when code catering to bare-clone fetch refspecs was added. That was released with JGit v1.0 almost 2 years ago, so there will probably be some bare repos in the wild which will have been cloned with JGit and have these corrupted refspecs. The effect of the corrupted fetch refspec is quite interesting. Up to and including JGit 2.0, the corrupt refspec was tolerated and fetches would work as intended with no indication to the user that anything was amiss. With JGit 2.1, a change was introduced which made JGit less tolerant, and fetches now attempt to update the non-existing ref "refs/heads//master". No exception is raised, but the real ref - "refs/heads/master" - is not updated. This behaviour was noticed by a user of Agit (which does bare clones by default and recently updated from JGit v2.0 to v2.2), reported here: https://github.com/rtyley/agit/issues/92 If you run C-Git fetch on a bare-repo cloned by JGit, it flat-out rejects the refspec (checked against v1.7.10.4): fatal: Invalid refspec '+refs/heads/*:refs/heads//*' Incidentally, C-Git does not create an explicit fetch refspec at all when performing a bare clone - the full remote config generated by C-Git looks like this: [remote "origin"] url = ssh://example.com/my-repo.git Using JGit on such a repository works fine, so omitting the fetch refspec entirely is also an option. Change-Id: I14b0d359dc69b8908f68e02cea7a756ac34bf881
11 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  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() + "/") + "*"; //$NON-NLS-1$//$NON-NLS-2$
  258. RefSpec refSpec = new RefSpec();
  259. refSpec = refSpec.setForceUpdate(true);
  260. refSpec = refSpec.setSourceDestination(Constants.R_HEADS + "*", dst); //$NON-NLS-1$
  261. config.addFetchRefSpec(refSpec);
  262. config.update(clonedRepo.getConfig());
  263. clonedRepo.getConfig().save();
  264. // run the fetch command
  265. FetchCommand command = new FetchCommand(clonedRepo);
  266. command.setRemote(remote);
  267. command.setProgressMonitor(monitor);
  268. command.setTagOpt(TagOpt.FETCH_TAGS);
  269. configure(command);
  270. List<RefSpec> specs = calculateRefSpecs(dst);
  271. command.setRefSpecs(specs);
  272. return command.call();
  273. }
  274. private List<RefSpec> calculateRefSpecs(String dst) {
  275. RefSpec wcrs = new RefSpec();
  276. wcrs = wcrs.setForceUpdate(true);
  277. wcrs = wcrs.setSourceDestination(Constants.R_HEADS + "*", dst); //$NON-NLS-1$
  278. List<RefSpec> specs = new ArrayList<>();
  279. if (cloneAllBranches)
  280. specs.add(wcrs);
  281. else if (branchesToClone != null
  282. && branchesToClone.size() > 0) {
  283. for (String selectedRef : branchesToClone)
  284. if (wcrs.matchSource(selectedRef))
  285. specs.add(wcrs.expandFromSource(selectedRef));
  286. }
  287. return specs;
  288. }
  289. private void checkout(Repository clonedRepo, FetchResult result)
  290. throws MissingObjectException, IncorrectObjectTypeException,
  291. IOException, GitAPIException {
  292. Ref head = null;
  293. if (branch.equals(Constants.HEAD)) {
  294. Ref foundBranch = findBranchToCheckout(result);
  295. if (foundBranch != null)
  296. head = foundBranch;
  297. }
  298. if (head == null) {
  299. head = result.getAdvertisedRef(branch);
  300. if (head == null)
  301. head = result.getAdvertisedRef(Constants.R_HEADS + branch);
  302. if (head == null)
  303. head = result.getAdvertisedRef(Constants.R_TAGS + branch);
  304. }
  305. if (head == null || head.getObjectId() == null)
  306. return; // TODO throw exception?
  307. if (head.getName().startsWith(Constants.R_HEADS)) {
  308. final RefUpdate newHead = clonedRepo.updateRef(Constants.HEAD);
  309. newHead.disableRefLog();
  310. newHead.link(head.getName());
  311. addMergeConfig(clonedRepo, head);
  312. }
  313. final RevCommit commit = parseCommit(clonedRepo, head);
  314. boolean detached = !head.getName().startsWith(Constants.R_HEADS);
  315. RefUpdate u = clonedRepo.updateRef(Constants.HEAD, detached);
  316. u.setNewObjectId(commit.getId());
  317. u.forceUpdate();
  318. if (!bare) {
  319. DirCache dc = clonedRepo.lockDirCache();
  320. DirCacheCheckout co = new DirCacheCheckout(clonedRepo, dc,
  321. commit.getTree());
  322. co.setProgressMonitor(monitor);
  323. co.checkout();
  324. if (cloneSubmodules)
  325. cloneSubmodules(clonedRepo);
  326. }
  327. }
  328. private void cloneSubmodules(Repository clonedRepo) throws IOException,
  329. GitAPIException {
  330. SubmoduleInitCommand init = new SubmoduleInitCommand(clonedRepo);
  331. Collection<String> submodules = init.call();
  332. if (submodules.isEmpty()) {
  333. return;
  334. }
  335. if (callback != null) {
  336. callback.initializedSubmodules(submodules);
  337. }
  338. SubmoduleUpdateCommand update = new SubmoduleUpdateCommand(clonedRepo);
  339. configure(update);
  340. update.setProgressMonitor(monitor);
  341. update.setCallback(callback);
  342. if (!update.call().isEmpty()) {
  343. SubmoduleWalk walk = SubmoduleWalk.forIndex(clonedRepo);
  344. while (walk.next()) {
  345. try (Repository subRepo = walk.getRepository()) {
  346. if (subRepo != null) {
  347. cloneSubmodules(subRepo);
  348. }
  349. }
  350. }
  351. }
  352. }
  353. private Ref findBranchToCheckout(FetchResult result) {
  354. final Ref idHEAD = result.getAdvertisedRef(Constants.HEAD);
  355. ObjectId headId = idHEAD != null ? idHEAD.getObjectId() : null;
  356. if (headId == null) {
  357. return null;
  358. }
  359. Ref master = result.getAdvertisedRef(Constants.R_HEADS
  360. + Constants.MASTER);
  361. ObjectId objectId = master != null ? master.getObjectId() : null;
  362. if (headId.equals(objectId)) {
  363. return master;
  364. }
  365. Ref foundBranch = null;
  366. for (Ref r : result.getAdvertisedRefs()) {
  367. final String n = r.getName();
  368. if (!n.startsWith(Constants.R_HEADS))
  369. continue;
  370. if (headId.equals(r.getObjectId())) {
  371. foundBranch = r;
  372. break;
  373. }
  374. }
  375. return foundBranch;
  376. }
  377. private void addMergeConfig(Repository clonedRepo, Ref head)
  378. throws IOException {
  379. String branchName = Repository.shortenRefName(head.getName());
  380. clonedRepo.getConfig().setString(ConfigConstants.CONFIG_BRANCH_SECTION,
  381. branchName, ConfigConstants.CONFIG_KEY_REMOTE, remote);
  382. clonedRepo.getConfig().setString(ConfigConstants.CONFIG_BRANCH_SECTION,
  383. branchName, ConfigConstants.CONFIG_KEY_MERGE, head.getName());
  384. String autosetupRebase = clonedRepo.getConfig().getString(
  385. ConfigConstants.CONFIG_BRANCH_SECTION, null,
  386. ConfigConstants.CONFIG_KEY_AUTOSETUPREBASE);
  387. if (ConfigConstants.CONFIG_KEY_ALWAYS.equals(autosetupRebase)
  388. || ConfigConstants.CONFIG_KEY_REMOTE.equals(autosetupRebase))
  389. clonedRepo.getConfig().setEnum(
  390. ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
  391. ConfigConstants.CONFIG_KEY_REBASE, BranchRebaseMode.REBASE);
  392. clonedRepo.getConfig().save();
  393. }
  394. private RevCommit parseCommit(Repository clonedRepo, Ref ref)
  395. throws MissingObjectException, IncorrectObjectTypeException,
  396. IOException {
  397. final RevCommit commit;
  398. try (RevWalk rw = new RevWalk(clonedRepo)) {
  399. commit = rw.parseCommit(ref.getObjectId());
  400. }
  401. return commit;
  402. }
  403. /**
  404. * Set the URI to clone from
  405. *
  406. * @param uri
  407. * the URI to clone from, or {@code null} to unset the URI. The
  408. * URI must be set before {@link #call} is called.
  409. * @return this instance
  410. */
  411. public CloneCommand setURI(String uri) {
  412. this.uri = uri;
  413. return this;
  414. }
  415. /**
  416. * The optional directory associated with the clone operation. If the
  417. * directory isn't set, a name associated with the source uri will be used.
  418. *
  419. * @see URIish#getHumanishName()
  420. * @param directory
  421. * the directory to clone to, or {@code null} if the directory
  422. * name should be taken from the source uri
  423. * @return this instance
  424. * @throws java.lang.IllegalStateException
  425. * if the combination of directory, gitDir and bare is illegal.
  426. * E.g. if for a non-bare repository directory and gitDir point
  427. * to the same directory of if for a bare repository both
  428. * directory and gitDir are specified
  429. */
  430. public CloneCommand setDirectory(File directory) {
  431. validateDirs(directory, gitDir, bare);
  432. this.directory = directory;
  433. return this;
  434. }
  435. /**
  436. * Set the repository meta directory (.git)
  437. *
  438. * @param gitDir
  439. * the repository meta directory, or {@code null} to choose one
  440. * automatically at clone time
  441. * @return this instance
  442. * @throws java.lang.IllegalStateException
  443. * if the combination of directory, gitDir and bare is illegal.
  444. * E.g. if for a non-bare repository directory and gitDir point
  445. * to the same directory of if for a bare repository both
  446. * directory and gitDir are specified
  447. * @since 3.6
  448. */
  449. public CloneCommand setGitDir(File gitDir) {
  450. validateDirs(directory, gitDir, bare);
  451. this.gitDir = gitDir;
  452. return this;
  453. }
  454. /**
  455. * Set whether the cloned repository shall be bare
  456. *
  457. * @param bare
  458. * whether the cloned repository is bare or not
  459. * @return this instance
  460. * @throws java.lang.IllegalStateException
  461. * if the combination of directory, gitDir and bare is illegal.
  462. * E.g. if for a non-bare repository directory and gitDir point
  463. * to the same directory of if for a bare repository both
  464. * directory and gitDir are specified
  465. */
  466. public CloneCommand setBare(boolean bare) throws IllegalStateException {
  467. validateDirs(directory, gitDir, bare);
  468. this.bare = bare;
  469. return this;
  470. }
  471. /**
  472. * Set the file system abstraction to be used for repositories created by
  473. * this command.
  474. *
  475. * @param fs
  476. * the abstraction.
  477. * @return {@code this} (for chaining calls).
  478. * @since 4.10
  479. */
  480. public CloneCommand setFs(FS fs) {
  481. this.fs = fs;
  482. return this;
  483. }
  484. /**
  485. * The remote name used to keep track of the upstream repository for the
  486. * clone operation. If no remote name is set, the default value of
  487. * <code>Constants.DEFAULT_REMOTE_NAME</code> will be used.
  488. *
  489. * @see Constants#DEFAULT_REMOTE_NAME
  490. * @param remote
  491. * name that keeps track of the upstream repository.
  492. * {@code null} means to use DEFAULT_REMOTE_NAME.
  493. * @return this instance
  494. */
  495. public CloneCommand setRemote(String remote) {
  496. if (remote == null) {
  497. remote = Constants.DEFAULT_REMOTE_NAME;
  498. }
  499. this.remote = remote;
  500. return this;
  501. }
  502. /**
  503. * Set the initial branch
  504. *
  505. * @param branch
  506. * the initial branch to check out when cloning the repository.
  507. * Can be specified as ref name (<code>refs/heads/master</code>),
  508. * branch name (<code>master</code>) or tag name
  509. * (<code>v1.2.3</code>). The default is to use the branch
  510. * pointed to by the cloned repository's HEAD and can be
  511. * requested by passing {@code null} or <code>HEAD</code>.
  512. * @return this instance
  513. */
  514. public CloneCommand setBranch(String branch) {
  515. if (branch == null) {
  516. branch = Constants.HEAD;
  517. }
  518. this.branch = branch;
  519. return this;
  520. }
  521. /**
  522. * The progress monitor associated with the clone operation. By default,
  523. * this is set to <code>NullProgressMonitor</code>
  524. *
  525. * @see NullProgressMonitor
  526. * @param monitor
  527. * a {@link org.eclipse.jgit.lib.ProgressMonitor}
  528. * @return {@code this}
  529. */
  530. public CloneCommand setProgressMonitor(ProgressMonitor monitor) {
  531. if (monitor == null) {
  532. monitor = NullProgressMonitor.INSTANCE;
  533. }
  534. this.monitor = monitor;
  535. return this;
  536. }
  537. /**
  538. * Set whether all branches have to be fetched
  539. *
  540. * @param cloneAllBranches
  541. * true when all branches have to be fetched (indicates wildcard
  542. * in created fetch refspec), false otherwise.
  543. * @return {@code this}
  544. */
  545. public CloneCommand setCloneAllBranches(boolean cloneAllBranches) {
  546. this.cloneAllBranches = cloneAllBranches;
  547. return this;
  548. }
  549. /**
  550. * Set whether to clone submodules
  551. *
  552. * @param cloneSubmodules
  553. * true to initialize and update submodules. Ignored when
  554. * {@link #setBare(boolean)} is set to true.
  555. * @return {@code this}
  556. */
  557. public CloneCommand setCloneSubmodules(boolean cloneSubmodules) {
  558. this.cloneSubmodules = cloneSubmodules;
  559. return this;
  560. }
  561. /**
  562. * Set branches to clone
  563. *
  564. * @param branchesToClone
  565. * collection of branches to clone. Ignored when allSelected is
  566. * true. Must be specified as full ref names (e.g.
  567. * <code>refs/heads/master</code>).
  568. * @return {@code this}
  569. */
  570. public CloneCommand setBranchesToClone(Collection<String> branchesToClone) {
  571. this.branchesToClone = branchesToClone;
  572. return this;
  573. }
  574. /**
  575. * Set whether to skip checking out a branch
  576. *
  577. * @param noCheckout
  578. * if set to <code>true</code> no branch will be checked out
  579. * after the clone. This enhances performance of the clone
  580. * command when there is no need for a checked out branch.
  581. * @return {@code this}
  582. */
  583. public CloneCommand setNoCheckout(boolean noCheckout) {
  584. this.noCheckout = noCheckout;
  585. return this;
  586. }
  587. /**
  588. * Register a progress callback.
  589. *
  590. * @param callback
  591. * the callback
  592. * @return {@code this}
  593. * @since 4.8
  594. */
  595. public CloneCommand setCallback(Callback callback) {
  596. this.callback = callback;
  597. return this;
  598. }
  599. private static void validateDirs(File directory, File gitDir, boolean bare)
  600. throws IllegalStateException {
  601. if (directory != null) {
  602. if (directory.exists() && !directory.isDirectory()) {
  603. throw new IllegalStateException(MessageFormat.format(
  604. JGitText.get().initFailedDirIsNoDirectory, directory));
  605. }
  606. if (gitDir != null && gitDir.exists() && !gitDir.isDirectory()) {
  607. throw new IllegalStateException(MessageFormat.format(
  608. JGitText.get().initFailedGitDirIsNoDirectory,
  609. gitDir));
  610. }
  611. if (bare) {
  612. if (gitDir != null && !gitDir.equals(directory))
  613. throw new IllegalStateException(MessageFormat.format(
  614. JGitText.get().initFailedBareRepoDifferentDirs,
  615. gitDir, directory));
  616. } else {
  617. if (gitDir != null && gitDir.equals(directory))
  618. throw new IllegalStateException(MessageFormat.format(
  619. JGitText.get().initFailedNonBareRepoSameDirs,
  620. gitDir, directory));
  621. }
  622. }
  623. }
  624. private void cleanup() {
  625. try {
  626. if (directory != null) {
  627. if (!directoryExistsInitially) {
  628. FileUtils.delete(directory, FileUtils.RECURSIVE
  629. | FileUtils.SKIP_MISSING | FileUtils.IGNORE_ERRORS);
  630. } else {
  631. deleteChildren(directory);
  632. }
  633. }
  634. if (gitDir != null) {
  635. if (!gitDirExistsInitially) {
  636. FileUtils.delete(gitDir, FileUtils.RECURSIVE
  637. | FileUtils.SKIP_MISSING | FileUtils.IGNORE_ERRORS);
  638. } else {
  639. deleteChildren(gitDir);
  640. }
  641. }
  642. } catch (IOException e) {
  643. // Ignore; this is a best-effort cleanup in error cases, and
  644. // IOException should not be raised anyway
  645. }
  646. }
  647. private void deleteChildren(File file) throws IOException {
  648. File[] files = file.listFiles();
  649. if (files == null) {
  650. return;
  651. }
  652. for (File child : files) {
  653. FileUtils.delete(child, FileUtils.RECURSIVE | FileUtils.SKIP_MISSING
  654. | FileUtils.IGNORE_ERRORS);
  655. }
  656. }
  657. }