PageRenderTime 24ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/org.eclipse.jgit/src/org/eclipse/jgit/api/CloneCommand.java

https://bitbucket.org/cofarrell/jgit
Java | 431 lines | 253 code | 48 blank | 130 comment | 38 complexity | 1815c56e75c7303efd9c151f761e620d MD5 | raw file
  1. /*
  2. * Copyright (C) 2011, 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.ProgressMonitor;
  63. import org.eclipse.jgit.lib.Ref;
  64. import org.eclipse.jgit.lib.RefUpdate;
  65. import org.eclipse.jgit.lib.Repository;
  66. import org.eclipse.jgit.revwalk.RevCommit;
  67. import org.eclipse.jgit.revwalk.RevWalk;
  68. import org.eclipse.jgit.submodule.SubmoduleWalk;
  69. import org.eclipse.jgit.transport.FetchResult;
  70. import org.eclipse.jgit.transport.RefSpec;
  71. import org.eclipse.jgit.transport.RemoteConfig;
  72. import org.eclipse.jgit.transport.TagOpt;
  73. import org.eclipse.jgit.transport.URIish;
  74. /**
  75. * Clone a repository into a new working directory
  76. *
  77. * @see <a href="http://www.kernel.org/pub/software/scm/git/docs/git-clone.html"
  78. * >Git documentation about Clone</a>
  79. */
  80. public class CloneCommand extends TransportCommand<CloneCommand, Git> {
  81. private String uri;
  82. private File directory;
  83. private boolean bare;
  84. private String remote = Constants.DEFAULT_REMOTE_NAME;
  85. private String branch = Constants.HEAD;
  86. private ProgressMonitor monitor = NullProgressMonitor.INSTANCE;
  87. private boolean cloneAllBranches;
  88. private boolean cloneSubmodules;
  89. private boolean noCheckout;
  90. private Collection<String> branchesToClone;
  91. /**
  92. * Create clone command with no repository set
  93. */
  94. public CloneCommand() {
  95. super(null);
  96. }
  97. /**
  98. * Executes the {@code Clone} command.
  99. *
  100. * @return the newly created {@code Git} object with associated repository
  101. * @throws InvalidRemoteException
  102. * @throws org.eclipse.jgit.api.errors.TransportException
  103. * @throws GitAPIException
  104. */
  105. public Git call() throws GitAPIException, InvalidRemoteException,
  106. org.eclipse.jgit.api.errors.TransportException {
  107. try {
  108. URIish u = new URIish(uri);
  109. Repository repository = init(u);
  110. FetchResult result = fetch(repository, u);
  111. if (!noCheckout)
  112. checkout(repository, result);
  113. return new Git(repository);
  114. } catch (IOException ioe) {
  115. throw new JGitInternalException(ioe.getMessage(), ioe);
  116. } catch (URISyntaxException e) {
  117. throw new InvalidRemoteException(MessageFormat.format(
  118. JGitText.get().invalidRemote, remote));
  119. }
  120. }
  121. private Repository init(URIish u) throws GitAPIException {
  122. InitCommand command = Git.init();
  123. command.setBare(bare);
  124. if (directory == null)
  125. directory = new File(u.getHumanishName(), Constants.DOT_GIT);
  126. if (directory.exists() && directory.listFiles().length != 0)
  127. throw new JGitInternalException(MessageFormat.format(
  128. JGitText.get().cloneNonEmptyDirectory, directory.getName()));
  129. command.setDirectory(directory);
  130. return command.call().getRepository();
  131. }
  132. private FetchResult fetch(Repository clonedRepo, URIish u)
  133. throws URISyntaxException,
  134. org.eclipse.jgit.api.errors.TransportException, IOException,
  135. GitAPIException {
  136. // create the remote config and save it
  137. RemoteConfig config = new RemoteConfig(clonedRepo.getConfig(), remote);
  138. config.addURI(u);
  139. final String dst = (bare ? Constants.R_HEADS : Constants.R_REMOTES
  140. + config.getName() + "/") + "*"; //$NON-NLS-1$//$NON-NLS-2$
  141. RefSpec refSpec = new RefSpec();
  142. refSpec = refSpec.setForceUpdate(true);
  143. refSpec = refSpec.setSourceDestination(Constants.R_HEADS + "*", dst); //$NON-NLS-1$
  144. config.addFetchRefSpec(refSpec);
  145. config.update(clonedRepo.getConfig());
  146. clonedRepo.getConfig().save();
  147. // run the fetch command
  148. FetchCommand command = new FetchCommand(clonedRepo);
  149. command.setRemote(remote);
  150. command.setProgressMonitor(monitor);
  151. command.setTagOpt(TagOpt.FETCH_TAGS);
  152. configure(command);
  153. List<RefSpec> specs = calculateRefSpecs(dst);
  154. command.setRefSpecs(specs);
  155. return command.call();
  156. }
  157. private List<RefSpec> calculateRefSpecs(final String dst) {
  158. RefSpec wcrs = new RefSpec();
  159. wcrs = wcrs.setForceUpdate(true);
  160. wcrs = wcrs.setSourceDestination(Constants.R_HEADS + "*", dst); //$NON-NLS-1$
  161. List<RefSpec> specs = new ArrayList<RefSpec>();
  162. if (cloneAllBranches)
  163. specs.add(wcrs);
  164. else if (branchesToClone != null
  165. && branchesToClone.size() > 0) {
  166. for (final String selectedRef : branchesToClone)
  167. if (wcrs.matchSource(selectedRef))
  168. specs.add(wcrs.expandFromSource(selectedRef));
  169. }
  170. return specs;
  171. }
  172. private void checkout(Repository clonedRepo, FetchResult result)
  173. throws MissingObjectException, IncorrectObjectTypeException,
  174. IOException, GitAPIException {
  175. Ref head = result.getAdvertisedRef(branch);
  176. if (branch.equals(Constants.HEAD)) {
  177. Ref foundBranch = findBranchToCheckout(result);
  178. if (foundBranch != null)
  179. head = foundBranch;
  180. }
  181. if (head == null || head.getObjectId() == null)
  182. return; // throw exception?
  183. if (head.getName().startsWith(Constants.R_HEADS)) {
  184. final RefUpdate newHead = clonedRepo.updateRef(Constants.HEAD);
  185. newHead.disableRefLog();
  186. newHead.link(head.getName());
  187. addMergeConfig(clonedRepo, head);
  188. }
  189. final RevCommit commit = parseCommit(clonedRepo, head);
  190. boolean detached = !head.getName().startsWith(Constants.R_HEADS);
  191. RefUpdate u = clonedRepo.updateRef(Constants.HEAD, detached);
  192. u.setNewObjectId(commit.getId());
  193. u.forceUpdate();
  194. if (!bare) {
  195. DirCache dc = clonedRepo.lockDirCache();
  196. DirCacheCheckout co = new DirCacheCheckout(clonedRepo, dc,
  197. commit.getTree());
  198. co.checkout();
  199. if (cloneSubmodules)
  200. cloneSubmodules(clonedRepo);
  201. }
  202. }
  203. private void cloneSubmodules(Repository clonedRepo) throws IOException,
  204. GitAPIException {
  205. SubmoduleInitCommand init = new SubmoduleInitCommand(clonedRepo);
  206. if (init.call().isEmpty())
  207. return;
  208. SubmoduleUpdateCommand update = new SubmoduleUpdateCommand(clonedRepo);
  209. configure(update);
  210. update.setProgressMonitor(monitor);
  211. if (!update.call().isEmpty()) {
  212. SubmoduleWalk walk = SubmoduleWalk.forIndex(clonedRepo);
  213. while (walk.next()) {
  214. Repository subRepo = walk.getRepository();
  215. if (subRepo != null) {
  216. try {
  217. cloneSubmodules(subRepo);
  218. } finally {
  219. subRepo.close();
  220. }
  221. }
  222. }
  223. }
  224. }
  225. private Ref findBranchToCheckout(FetchResult result) {
  226. final Ref idHEAD = result.getAdvertisedRef(Constants.HEAD);
  227. if (idHEAD == null)
  228. return null;
  229. Ref master = result.getAdvertisedRef(Constants.R_HEADS
  230. + Constants.MASTER);
  231. if (master != null && master.getObjectId().equals(idHEAD.getObjectId()))
  232. return master;
  233. Ref foundBranch = null;
  234. for (final Ref r : result.getAdvertisedRefs()) {
  235. final String n = r.getName();
  236. if (!n.startsWith(Constants.R_HEADS))
  237. continue;
  238. if (r.getObjectId().equals(idHEAD.getObjectId())) {
  239. foundBranch = r;
  240. break;
  241. }
  242. }
  243. return foundBranch;
  244. }
  245. private void addMergeConfig(Repository clonedRepo, Ref head)
  246. throws IOException {
  247. String branchName = Repository.shortenRefName(head.getName());
  248. clonedRepo.getConfig().setString(ConfigConstants.CONFIG_BRANCH_SECTION,
  249. branchName, ConfigConstants.CONFIG_KEY_REMOTE, remote);
  250. clonedRepo.getConfig().setString(ConfigConstants.CONFIG_BRANCH_SECTION,
  251. branchName, ConfigConstants.CONFIG_KEY_MERGE, head.getName());
  252. String autosetupRebase = clonedRepo.getConfig().getString(
  253. ConfigConstants.CONFIG_BRANCH_SECTION, null,
  254. ConfigConstants.CONFIG_KEY_AUTOSETUPREBASE);
  255. if (ConfigConstants.CONFIG_KEY_ALWAYS.equals(autosetupRebase)
  256. || ConfigConstants.CONFIG_KEY_REMOTE.equals(autosetupRebase))
  257. clonedRepo.getConfig().setBoolean(
  258. ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
  259. ConfigConstants.CONFIG_KEY_REBASE, true);
  260. clonedRepo.getConfig().save();
  261. }
  262. private RevCommit parseCommit(final Repository clonedRepo, final Ref ref)
  263. throws MissingObjectException, IncorrectObjectTypeException,
  264. IOException {
  265. final RevWalk rw = new RevWalk(clonedRepo);
  266. final RevCommit commit;
  267. try {
  268. commit = rw.parseCommit(ref.getObjectId());
  269. } finally {
  270. rw.release();
  271. }
  272. return commit;
  273. }
  274. /**
  275. * @param uri
  276. * the uri to clone from
  277. * @return this instance
  278. */
  279. public CloneCommand setURI(String uri) {
  280. this.uri = uri;
  281. return this;
  282. }
  283. /**
  284. * The optional directory associated with the clone operation. If the
  285. * directory isn't set, a name associated with the source uri will be used.
  286. *
  287. * @see URIish#getHumanishName()
  288. *
  289. * @param directory
  290. * the directory to clone to
  291. * @return this instance
  292. */
  293. public CloneCommand setDirectory(File directory) {
  294. this.directory = directory;
  295. return this;
  296. }
  297. /**
  298. * @param bare
  299. * whether the cloned repository is bare or not
  300. * @return this instance
  301. */
  302. public CloneCommand setBare(boolean bare) {
  303. this.bare = bare;
  304. return this;
  305. }
  306. /**
  307. * The remote name used to keep track of the upstream repository for the
  308. * clone operation. If no remote name is set, the default value of
  309. * <code>Constants.DEFAULT_REMOTE_NAME</code> will be used.
  310. *
  311. * @see Constants#DEFAULT_REMOTE_NAME
  312. * @param remote
  313. * name that keeps track of the upstream repository
  314. * @return this instance
  315. */
  316. public CloneCommand setRemote(String remote) {
  317. this.remote = remote;
  318. return this;
  319. }
  320. /**
  321. * @param branch
  322. * the initial branch to check out when cloning the repository
  323. * @return this instance
  324. */
  325. public CloneCommand setBranch(String branch) {
  326. this.branch = branch;
  327. return this;
  328. }
  329. /**
  330. * The progress monitor associated with the clone operation. By default,
  331. * this is set to <code>NullProgressMonitor</code>
  332. *
  333. * @see NullProgressMonitor
  334. *
  335. * @param monitor
  336. * @return {@code this}
  337. */
  338. public CloneCommand setProgressMonitor(ProgressMonitor monitor) {
  339. this.monitor = monitor;
  340. return this;
  341. }
  342. /**
  343. * @param cloneAllBranches
  344. * true when all branches have to be fetched (indicates wildcard
  345. * in created fetch refspec), false otherwise.
  346. * @return {@code this}
  347. */
  348. public CloneCommand setCloneAllBranches(boolean cloneAllBranches) {
  349. this.cloneAllBranches = cloneAllBranches;
  350. return this;
  351. }
  352. /**
  353. * @param cloneSubmodules
  354. * true to initialize and update submodules. Ignored when
  355. * {@link #setBare(boolean)} is set to true.
  356. * @return {@code this}
  357. */
  358. public CloneCommand setCloneSubmodules(boolean cloneSubmodules) {
  359. this.cloneSubmodules = cloneSubmodules;
  360. return this;
  361. }
  362. /**
  363. * @param branchesToClone
  364. * collection of branches to clone. Ignored when allSelected is
  365. * true.
  366. * @return {@code this}
  367. */
  368. public CloneCommand setBranchesToClone(Collection<String> branchesToClone) {
  369. this.branchesToClone = branchesToClone;
  370. return this;
  371. }
  372. /**
  373. * @param noCheckout
  374. * if set to <code>true</code> no branch will be checked out
  375. * after the clone. This enhances performance of the clone
  376. * command when there is no need for a checked out branch.
  377. * @return {@code this}
  378. */
  379. public CloneCommand setNoCheckout(boolean noCheckout) {
  380. this.noCheckout = noCheckout;
  381. return this;
  382. }
  383. }