您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

CloneCommand.java 13KB

Enable full Transport configuration for JGit API commands Add a TransportConfigCallback parameter to JGit API commands, to allow consumers of the JGit command API to perform custom Transport configuration that would be otherwise difficult to anticipate & expose on the API command builders. My specific use-case is configuring additional properties on SshTransport - I need to take over the SshSessionFactory used by the transport. Using TransportConfigCallback I can simply do this (rather than reimplement the API command classes): public void configure(Transport tn) { if (tn instanceof SshTransport) { ((SshTransport) tn).setSshSessionFactory(factoryProvider.get()); } } Adding an explicit setSshSessionFactory() method to the JGit command classes would bloat the API. Also, creating the replacement SshSessionFactory is unnecessary if the transport is not SSH, but the type of the Transport is only known once the remote has been resolved and the URI parsed - consequently it makes sense to perform this step in a callback, where the transport instance can be inspected to determine if it's of a relevant type. A note about where this leaves the API - there are now 4 commands: CloneCommand PullCommand FetchCommand PushCommand -that share 3 identical transport-related parameters: timeout credentialsProvider transportConfigurator I think there's potential for introducing an interface or val-object to identify/encapsulate this repetition, which I'd be happy to do in a subsequent commit. Change-Id: I8983c3627cdd7d7b2aeb0b6a3dadee553378b951 Signed-off-by: Roberto Tyley <roberto.tyley@gmail.com>
12 年前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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();
  141. RefSpec refSpec = new RefSpec();
  142. refSpec = refSpec.setForceUpdate(true);
  143. refSpec = refSpec.setSourceDestination(Constants.R_HEADS + "*", dst + "/*"); //$NON-NLS-1$ //$NON-NLS-2$
  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$ //$NON-NLS-2$
  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. cloneSubmodules(subRepo);
  217. }
  218. }
  219. }
  220. private Ref findBranchToCheckout(FetchResult result) {
  221. final Ref idHEAD = result.getAdvertisedRef(Constants.HEAD);
  222. if (idHEAD == null)
  223. return null;
  224. Ref master = result.getAdvertisedRef(Constants.R_HEADS
  225. + Constants.MASTER);
  226. if (master != null && master.getObjectId().equals(idHEAD.getObjectId()))
  227. return master;
  228. Ref foundBranch = null;
  229. for (final Ref r : result.getAdvertisedRefs()) {
  230. final String n = r.getName();
  231. if (!n.startsWith(Constants.R_HEADS))
  232. continue;
  233. if (r.getObjectId().equals(idHEAD.getObjectId())) {
  234. foundBranch = r;
  235. break;
  236. }
  237. }
  238. return foundBranch;
  239. }
  240. private void addMergeConfig(Repository clonedRepo, Ref head)
  241. throws IOException {
  242. String branchName = Repository.shortenRefName(head.getName());
  243. clonedRepo.getConfig().setString(ConfigConstants.CONFIG_BRANCH_SECTION,
  244. branchName, ConfigConstants.CONFIG_KEY_REMOTE, remote);
  245. clonedRepo.getConfig().setString(ConfigConstants.CONFIG_BRANCH_SECTION,
  246. branchName, ConfigConstants.CONFIG_KEY_MERGE, head.getName());
  247. String autosetupRebase = clonedRepo.getConfig().getString(
  248. ConfigConstants.CONFIG_BRANCH_SECTION, null,
  249. ConfigConstants.CONFIG_KEY_AUTOSETUPREBASE);
  250. if (ConfigConstants.CONFIG_KEY_ALWAYS.equals(autosetupRebase)
  251. || ConfigConstants.CONFIG_KEY_REMOTE.equals(autosetupRebase))
  252. clonedRepo.getConfig().setBoolean(
  253. ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
  254. ConfigConstants.CONFIG_KEY_REBASE, true);
  255. clonedRepo.getConfig().save();
  256. }
  257. private RevCommit parseCommit(final Repository clonedRepo, final Ref ref)
  258. throws MissingObjectException, IncorrectObjectTypeException,
  259. IOException {
  260. final RevWalk rw = new RevWalk(clonedRepo);
  261. final RevCommit commit;
  262. try {
  263. commit = rw.parseCommit(ref.getObjectId());
  264. } finally {
  265. rw.release();
  266. }
  267. return commit;
  268. }
  269. /**
  270. * @param uri
  271. * the uri to clone from
  272. * @return this instance
  273. */
  274. public CloneCommand setURI(String uri) {
  275. this.uri = uri;
  276. return this;
  277. }
  278. /**
  279. * The optional directory associated with the clone operation. If the
  280. * directory isn't set, a name associated with the source uri will be used.
  281. *
  282. * @see URIish#getHumanishName()
  283. *
  284. * @param directory
  285. * the directory to clone to
  286. * @return this instance
  287. */
  288. public CloneCommand setDirectory(File directory) {
  289. this.directory = directory;
  290. return this;
  291. }
  292. /**
  293. * @param bare
  294. * whether the cloned repository is bare or not
  295. * @return this instance
  296. */
  297. public CloneCommand setBare(boolean bare) {
  298. this.bare = bare;
  299. return this;
  300. }
  301. /**
  302. * The remote name used to keep track of the upstream repository for the
  303. * clone operation. If no remote name is set, the default value of
  304. * <code>Constants.DEFAULT_REMOTE_NAME</code> will be used.
  305. *
  306. * @see Constants#DEFAULT_REMOTE_NAME
  307. * @param remote
  308. * name that keeps track of the upstream repository
  309. * @return this instance
  310. */
  311. public CloneCommand setRemote(String remote) {
  312. this.remote = remote;
  313. return this;
  314. }
  315. /**
  316. * @param branch
  317. * the initial branch to check out when cloning the repository
  318. * @return this instance
  319. */
  320. public CloneCommand setBranch(String branch) {
  321. this.branch = branch;
  322. return this;
  323. }
  324. /**
  325. * The progress monitor associated with the clone operation. By default,
  326. * this is set to <code>NullProgressMonitor</code>
  327. *
  328. * @see NullProgressMonitor
  329. *
  330. * @param monitor
  331. * @return {@code this}
  332. */
  333. public CloneCommand setProgressMonitor(ProgressMonitor monitor) {
  334. this.monitor = monitor;
  335. return this;
  336. }
  337. /**
  338. * @param cloneAllBranches
  339. * true when all branches have to be fetched (indicates wildcard
  340. * in created fetch refspec), false otherwise.
  341. * @return {@code this}
  342. */
  343. public CloneCommand setCloneAllBranches(boolean cloneAllBranches) {
  344. this.cloneAllBranches = cloneAllBranches;
  345. return this;
  346. }
  347. /**
  348. * @param cloneSubmodules
  349. * true to initialize and update submodules. Ignored when
  350. * {@link #setBare(boolean)} is set to true.
  351. * @return {@code this}
  352. */
  353. public CloneCommand setCloneSubmodules(boolean cloneSubmodules) {
  354. this.cloneSubmodules = cloneSubmodules;
  355. return this;
  356. }
  357. /**
  358. * @param branchesToClone
  359. * collection of branches to clone. Ignored when allSelected is
  360. * true.
  361. * @return {@code this}
  362. */
  363. public CloneCommand setBranchesToClone(Collection<String> branchesToClone) {
  364. this.branchesToClone = branchesToClone;
  365. return this;
  366. }
  367. /**
  368. * @param noCheckout
  369. * if set to <code>true</code> no branch will be checked out
  370. * after the clone. This enhances performance of the clone
  371. * command when there is no need for a checked out branch.
  372. * @return {@code this}
  373. */
  374. public CloneCommand setNoCheckout(boolean noCheckout) {
  375. this.noCheckout = noCheckout;
  376. return this;
  377. }
  378. }