Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

CloneCommand.java 23KB

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