Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

CloneCommand.java 17KB

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