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

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