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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. /*
  2. * Copyright (C) 2011, 2013 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.api.errors.GitAPIException;
  52. import org.eclipse.jgit.api.errors.InvalidRemoteException;
  53. import org.eclipse.jgit.api.errors.JGitInternalException;
  54. import org.eclipse.jgit.dircache.DirCache;
  55. import org.eclipse.jgit.dircache.DirCacheCheckout;
  56. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  57. import org.eclipse.jgit.errors.MissingObjectException;
  58. import org.eclipse.jgit.internal.JGitText;
  59. import org.eclipse.jgit.lib.ConfigConstants;
  60. import org.eclipse.jgit.lib.Constants;
  61. import org.eclipse.jgit.lib.NullProgressMonitor;
  62. import org.eclipse.jgit.lib.ObjectId;
  63. import org.eclipse.jgit.lib.ProgressMonitor;
  64. import org.eclipse.jgit.lib.Ref;
  65. import org.eclipse.jgit.lib.RefUpdate;
  66. import org.eclipse.jgit.lib.Repository;
  67. import org.eclipse.jgit.revwalk.RevCommit;
  68. import org.eclipse.jgit.revwalk.RevWalk;
  69. import org.eclipse.jgit.submodule.SubmoduleWalk;
  70. import org.eclipse.jgit.transport.FetchResult;
  71. import org.eclipse.jgit.transport.RefSpec;
  72. import org.eclipse.jgit.transport.RemoteConfig;
  73. import org.eclipse.jgit.transport.TagOpt;
  74. import org.eclipse.jgit.transport.URIish;
  75. /**
  76. * Clone a repository into a new working directory
  77. *
  78. * @see <a href="http://www.kernel.org/pub/software/scm/git/docs/git-clone.html"
  79. * >Git documentation about Clone</a>
  80. */
  81. public class CloneCommand extends TransportCommand<CloneCommand, Git> {
  82. private String uri;
  83. private File directory;
  84. private File gitDir;
  85. private boolean bare;
  86. private String remote = Constants.DEFAULT_REMOTE_NAME;
  87. private String branch = Constants.HEAD;
  88. private ProgressMonitor monitor = NullProgressMonitor.INSTANCE;
  89. private boolean cloneAllBranches;
  90. private boolean cloneSubmodules;
  91. private boolean noCheckout;
  92. private Collection<String> branchesToClone;
  93. /**
  94. * Create clone command with no repository set
  95. */
  96. public CloneCommand() {
  97. super(null);
  98. }
  99. /**
  100. * Executes the {@code Clone} command.
  101. *
  102. * The Git instance returned by this command needs to be closed by the
  103. * caller to free resources held by the underlying {@link Repository}
  104. * instance. It is recommended to call this method as soon as you don't need
  105. * a reference to this {@link Git} instance and the underlying
  106. * {@link Repository} instance anymore.
  107. *
  108. * @return the newly created {@code Git} object with associated repository
  109. * @throws InvalidRemoteException
  110. * @throws org.eclipse.jgit.api.errors.TransportException
  111. * @throws GitAPIException
  112. */
  113. public Git call() throws GitAPIException, InvalidRemoteException,
  114. org.eclipse.jgit.api.errors.TransportException {
  115. Repository repository = null;
  116. try {
  117. URIish u = new URIish(uri);
  118. repository = init(u);
  119. FetchResult result = fetch(repository, u);
  120. if (!noCheckout)
  121. checkout(repository, result);
  122. return new Git(repository, true);
  123. } catch (IOException ioe) {
  124. if (repository != null) {
  125. repository.close();
  126. }
  127. throw new JGitInternalException(ioe.getMessage(), ioe);
  128. } catch (URISyntaxException e) {
  129. if (repository != null) {
  130. repository.close();
  131. }
  132. throw new InvalidRemoteException(MessageFormat.format(
  133. JGitText.get().invalidRemote, remote));
  134. }
  135. }
  136. private Repository init(URIish u) throws GitAPIException {
  137. InitCommand command = Git.init();
  138. command.setBare(bare);
  139. if (directory == null && gitDir == null)
  140. directory = new File(u.getHumanishName(), Constants.DOT_GIT);
  141. validateDirs(directory, gitDir, bare);
  142. if (directory != null && directory.exists()
  143. && directory.listFiles().length != 0)
  144. throw new JGitInternalException(MessageFormat.format(
  145. JGitText.get().cloneNonEmptyDirectory, directory.getName()));
  146. if (gitDir != null && gitDir.exists() && gitDir.listFiles().length != 0)
  147. throw new JGitInternalException(MessageFormat.format(
  148. JGitText.get().cloneNonEmptyDirectory, gitDir.getName()));
  149. if (directory != null)
  150. command.setDirectory(directory);
  151. if (gitDir != null)
  152. command.setGitDir(gitDir);
  153. return command.call().getRepository();
  154. }
  155. private FetchResult fetch(Repository clonedRepo, URIish u)
  156. throws URISyntaxException,
  157. org.eclipse.jgit.api.errors.TransportException, IOException,
  158. GitAPIException {
  159. // create the remote config and save it
  160. RemoteConfig config = new RemoteConfig(clonedRepo.getConfig(), remote);
  161. config.addURI(u);
  162. final String dst = (bare ? Constants.R_HEADS : Constants.R_REMOTES
  163. + config.getName() + "/") + "*"; //$NON-NLS-1$//$NON-NLS-2$
  164. RefSpec refSpec = new RefSpec();
  165. refSpec = refSpec.setForceUpdate(true);
  166. refSpec = refSpec.setSourceDestination(Constants.R_HEADS + "*", dst); //$NON-NLS-1$
  167. config.addFetchRefSpec(refSpec);
  168. config.update(clonedRepo.getConfig());
  169. clonedRepo.getConfig().save();
  170. // run the fetch command
  171. FetchCommand command = new FetchCommand(clonedRepo);
  172. command.setRemote(remote);
  173. command.setProgressMonitor(monitor);
  174. command.setTagOpt(TagOpt.FETCH_TAGS);
  175. configure(command);
  176. List<RefSpec> specs = calculateRefSpecs(dst);
  177. command.setRefSpecs(specs);
  178. return command.call();
  179. }
  180. private List<RefSpec> calculateRefSpecs(final String dst) {
  181. RefSpec wcrs = new RefSpec();
  182. wcrs = wcrs.setForceUpdate(true);
  183. wcrs = wcrs.setSourceDestination(Constants.R_HEADS + "*", dst); //$NON-NLS-1$
  184. List<RefSpec> specs = new ArrayList<RefSpec>();
  185. if (cloneAllBranches)
  186. specs.add(wcrs);
  187. else if (branchesToClone != null
  188. && branchesToClone.size() > 0) {
  189. for (final String selectedRef : branchesToClone)
  190. if (wcrs.matchSource(selectedRef))
  191. specs.add(wcrs.expandFromSource(selectedRef));
  192. }
  193. return specs;
  194. }
  195. private void checkout(Repository clonedRepo, FetchResult result)
  196. throws MissingObjectException, IncorrectObjectTypeException,
  197. IOException, GitAPIException {
  198. Ref head = null;
  199. if (branch.equals(Constants.HEAD)) {
  200. Ref foundBranch = findBranchToCheckout(result);
  201. if (foundBranch != null)
  202. head = foundBranch;
  203. }
  204. if (head == null) {
  205. head = result.getAdvertisedRef(branch);
  206. if (head == null)
  207. head = result.getAdvertisedRef(Constants.R_HEADS + branch);
  208. if (head == null)
  209. head = result.getAdvertisedRef(Constants.R_TAGS + branch);
  210. }
  211. if (head == null || head.getObjectId() == null)
  212. return; // TODO throw exception?
  213. if (head.getName().startsWith(Constants.R_HEADS)) {
  214. final RefUpdate newHead = clonedRepo.updateRef(Constants.HEAD);
  215. newHead.disableRefLog();
  216. newHead.link(head.getName());
  217. addMergeConfig(clonedRepo, head);
  218. }
  219. final RevCommit commit = parseCommit(clonedRepo, head);
  220. boolean detached = !head.getName().startsWith(Constants.R_HEADS);
  221. RefUpdate u = clonedRepo.updateRef(Constants.HEAD, detached);
  222. u.setNewObjectId(commit.getId());
  223. u.forceUpdate();
  224. if (!bare) {
  225. DirCache dc = clonedRepo.lockDirCache();
  226. DirCacheCheckout co = new DirCacheCheckout(clonedRepo, dc,
  227. commit.getTree());
  228. co.checkout();
  229. if (cloneSubmodules)
  230. cloneSubmodules(clonedRepo);
  231. }
  232. }
  233. private void cloneSubmodules(Repository clonedRepo) throws IOException,
  234. GitAPIException {
  235. SubmoduleInitCommand init = new SubmoduleInitCommand(clonedRepo);
  236. if (init.call().isEmpty())
  237. return;
  238. SubmoduleUpdateCommand update = new SubmoduleUpdateCommand(clonedRepo);
  239. configure(update);
  240. update.setProgressMonitor(monitor);
  241. if (!update.call().isEmpty()) {
  242. SubmoduleWalk walk = SubmoduleWalk.forIndex(clonedRepo);
  243. while (walk.next()) {
  244. Repository subRepo = walk.getRepository();
  245. if (subRepo != null) {
  246. try {
  247. cloneSubmodules(subRepo);
  248. } finally {
  249. subRepo.close();
  250. }
  251. }
  252. }
  253. }
  254. }
  255. private Ref findBranchToCheckout(FetchResult result) {
  256. final Ref idHEAD = result.getAdvertisedRef(Constants.HEAD);
  257. ObjectId headId = idHEAD != null ? idHEAD.getObjectId() : null;
  258. if (headId == null) {
  259. return null;
  260. }
  261. Ref master = result.getAdvertisedRef(Constants.R_HEADS
  262. + Constants.MASTER);
  263. ObjectId objectId = master != null ? master.getObjectId() : null;
  264. if (headId.equals(objectId)) {
  265. return master;
  266. }
  267. Ref foundBranch = null;
  268. for (final Ref r : result.getAdvertisedRefs()) {
  269. final String n = r.getName();
  270. if (!n.startsWith(Constants.R_HEADS))
  271. continue;
  272. if (headId.equals(r.getObjectId())) {
  273. foundBranch = r;
  274. break;
  275. }
  276. }
  277. return foundBranch;
  278. }
  279. private void addMergeConfig(Repository clonedRepo, Ref head)
  280. throws IOException {
  281. String branchName = Repository.shortenRefName(head.getName());
  282. clonedRepo.getConfig().setString(ConfigConstants.CONFIG_BRANCH_SECTION,
  283. branchName, ConfigConstants.CONFIG_KEY_REMOTE, remote);
  284. clonedRepo.getConfig().setString(ConfigConstants.CONFIG_BRANCH_SECTION,
  285. branchName, ConfigConstants.CONFIG_KEY_MERGE, head.getName());
  286. String autosetupRebase = clonedRepo.getConfig().getString(
  287. ConfigConstants.CONFIG_BRANCH_SECTION, null,
  288. ConfigConstants.CONFIG_KEY_AUTOSETUPREBASE);
  289. if (ConfigConstants.CONFIG_KEY_ALWAYS.equals(autosetupRebase)
  290. || ConfigConstants.CONFIG_KEY_REMOTE.equals(autosetupRebase))
  291. clonedRepo.getConfig().setBoolean(
  292. ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
  293. ConfigConstants.CONFIG_KEY_REBASE, true);
  294. clonedRepo.getConfig().save();
  295. }
  296. private RevCommit parseCommit(final Repository clonedRepo, final Ref ref)
  297. throws MissingObjectException, IncorrectObjectTypeException,
  298. IOException {
  299. final RevCommit commit;
  300. try (final RevWalk rw = new RevWalk(clonedRepo)) {
  301. commit = rw.parseCommit(ref.getObjectId());
  302. }
  303. return commit;
  304. }
  305. /**
  306. * @param uri
  307. * the URI to clone from, or {@code null} to unset the URI.
  308. * The URI must be set before {@link #call} is called.
  309. * @return this instance
  310. */
  311. public CloneCommand setURI(String uri) {
  312. this.uri = uri;
  313. return this;
  314. }
  315. /**
  316. * The optional directory associated with the clone operation. If the
  317. * directory isn't set, a name associated with the source uri will be used.
  318. *
  319. * @see URIish#getHumanishName()
  320. *
  321. * @param directory
  322. * the directory to clone to, or {@code null} if the directory
  323. * name should be taken from the source uri
  324. * @return this instance
  325. * @throws IllegalStateException
  326. * if the combination of directory, gitDir and bare is illegal.
  327. * E.g. if for a non-bare repository directory and gitDir point
  328. * to the same directory of if for a bare repository both
  329. * directory and gitDir are specified
  330. */
  331. public CloneCommand setDirectory(File directory) {
  332. validateDirs(directory, gitDir, bare);
  333. this.directory = directory;
  334. return this;
  335. }
  336. /**
  337. * @param gitDir
  338. * the repository meta directory, or {@code null} to choose one
  339. * automatically at clone time
  340. * @return this instance
  341. * @throws IllegalStateException
  342. * if the combination of directory, gitDir and bare is illegal.
  343. * E.g. if for a non-bare repository directory and gitDir point
  344. * to the same directory of if for a bare repository both
  345. * directory and gitDir are specified
  346. * @since 3.6
  347. */
  348. public CloneCommand setGitDir(File gitDir) {
  349. validateDirs(directory, gitDir, bare);
  350. this.gitDir = gitDir;
  351. return this;
  352. }
  353. /**
  354. * @param bare
  355. * whether the cloned repository is bare or not
  356. * @return this instance
  357. * @throws IllegalStateException
  358. * if the combination of directory, gitDir and bare is illegal.
  359. * E.g. if for a non-bare repository directory and gitDir point
  360. * to the same directory of if for a bare repository both
  361. * directory and gitDir are specified
  362. */
  363. public CloneCommand setBare(boolean bare) throws IllegalStateException {
  364. validateDirs(directory, gitDir, bare);
  365. this.bare = bare;
  366. return this;
  367. }
  368. /**
  369. * The remote name used to keep track of the upstream repository for the
  370. * clone operation. If no remote name is set, the default value of
  371. * <code>Constants.DEFAULT_REMOTE_NAME</code> will be used.
  372. *
  373. * @see Constants#DEFAULT_REMOTE_NAME
  374. * @param remote
  375. * name that keeps track of the upstream repository.
  376. * {@code null} means to use DEFAULT_REMOTE_NAME.
  377. * @return this instance
  378. */
  379. public CloneCommand setRemote(String remote) {
  380. if (remote == null) {
  381. remote = Constants.DEFAULT_REMOTE_NAME;
  382. }
  383. this.remote = remote;
  384. return this;
  385. }
  386. /**
  387. * @param branch
  388. * the initial branch to check out when cloning the repository.
  389. * Can be specified as ref name (<code>refs/heads/master</code>),
  390. * branch name (<code>master</code>) or tag name (<code>v1.2.3</code>).
  391. * The default is to use the branch pointed to by the cloned
  392. * repository's HEAD and can be requested by passing {@code null}
  393. * or <code>HEAD</code>.
  394. * @return this instance
  395. */
  396. public CloneCommand setBranch(String branch) {
  397. if (branch == null) {
  398. branch = Constants.HEAD;
  399. }
  400. this.branch = branch;
  401. return this;
  402. }
  403. /**
  404. * The progress monitor associated with the clone operation. By default,
  405. * this is set to <code>NullProgressMonitor</code>
  406. *
  407. * @see NullProgressMonitor
  408. *
  409. * @param monitor
  410. * @return {@code this}
  411. */
  412. public CloneCommand setProgressMonitor(ProgressMonitor monitor) {
  413. if (monitor == null) {
  414. monitor = NullProgressMonitor.INSTANCE;
  415. }
  416. this.monitor = monitor;
  417. return this;
  418. }
  419. /**
  420. * @param cloneAllBranches
  421. * true when all branches have to be fetched (indicates wildcard
  422. * in created fetch refspec), false otherwise.
  423. * @return {@code this}
  424. */
  425. public CloneCommand setCloneAllBranches(boolean cloneAllBranches) {
  426. this.cloneAllBranches = cloneAllBranches;
  427. return this;
  428. }
  429. /**
  430. * @param cloneSubmodules
  431. * true to initialize and update submodules. Ignored when
  432. * {@link #setBare(boolean)} is set to true.
  433. * @return {@code this}
  434. */
  435. public CloneCommand setCloneSubmodules(boolean cloneSubmodules) {
  436. this.cloneSubmodules = cloneSubmodules;
  437. return this;
  438. }
  439. /**
  440. * @param branchesToClone
  441. * collection of branches to clone. Ignored when allSelected is
  442. * true. Must be specified as full ref names (e.g.
  443. * <code>refs/heads/master</code>).
  444. * @return {@code this}
  445. */
  446. public CloneCommand setBranchesToClone(Collection<String> branchesToClone) {
  447. this.branchesToClone = branchesToClone;
  448. return this;
  449. }
  450. /**
  451. * @param noCheckout
  452. * if set to <code>true</code> no branch will be checked out
  453. * after the clone. This enhances performance of the clone
  454. * command when there is no need for a checked out branch.
  455. * @return {@code this}
  456. */
  457. public CloneCommand setNoCheckout(boolean noCheckout) {
  458. this.noCheckout = noCheckout;
  459. return this;
  460. }
  461. private static void validateDirs(File directory, File gitDir, boolean bare)
  462. throws IllegalStateException {
  463. if (directory != null) {
  464. if (directory.exists() && !directory.isDirectory()) {
  465. throw new IllegalStateException(MessageFormat.format(
  466. JGitText.get().initFailedDirIsNoDirectory, directory));
  467. }
  468. if (gitDir != null && gitDir.exists() && !gitDir.isDirectory()) {
  469. throw new IllegalStateException(MessageFormat.format(
  470. JGitText.get().initFailedGitDirIsNoDirectory,
  471. gitDir));
  472. }
  473. if (bare) {
  474. if (gitDir != null && !gitDir.equals(directory))
  475. throw new IllegalStateException(MessageFormat.format(
  476. JGitText.get().initFailedBareRepoDifferentDirs,
  477. gitDir, directory));
  478. } else {
  479. if (gitDir != null && gitDir.equals(directory))
  480. throw new IllegalStateException(MessageFormat.format(
  481. JGitText.get().initFailedNonBareRepoSameDirs,
  482. gitDir, directory));
  483. }
  484. }
  485. }
  486. }