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

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