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

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