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.

RepoCommand.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. /*
  2. * Copyright (C) 2014, Google Inc.
  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.gitrepo;
  44. import java.io.File;
  45. import java.io.FileInputStream;
  46. import java.io.IOException;
  47. import java.io.InputStream;
  48. import java.text.MessageFormat;
  49. import java.util.ArrayList;
  50. import java.util.List;
  51. import java.util.Map;
  52. import org.eclipse.jgit.api.Git;
  53. import org.eclipse.jgit.api.GitCommand;
  54. import org.eclipse.jgit.api.SubmoduleAddCommand;
  55. import org.eclipse.jgit.api.errors.ConcurrentRefUpdateException;
  56. import org.eclipse.jgit.api.errors.GitAPIException;
  57. import org.eclipse.jgit.api.errors.JGitInternalException;
  58. import org.eclipse.jgit.dircache.DirCache;
  59. import org.eclipse.jgit.dircache.DirCacheBuilder;
  60. import org.eclipse.jgit.dircache.DirCacheEntry;
  61. import org.eclipse.jgit.gitrepo.ManifestParser.IncludedFileReader;
  62. import org.eclipse.jgit.gitrepo.RepoProject.CopyFile;
  63. import org.eclipse.jgit.gitrepo.internal.RepoText;
  64. import org.eclipse.jgit.internal.JGitText;
  65. import org.eclipse.jgit.lib.CommitBuilder;
  66. import org.eclipse.jgit.lib.Config;
  67. import org.eclipse.jgit.lib.Constants;
  68. import org.eclipse.jgit.lib.FileMode;
  69. import org.eclipse.jgit.lib.ObjectId;
  70. import org.eclipse.jgit.lib.ObjectInserter;
  71. import org.eclipse.jgit.lib.ObjectReader;
  72. import org.eclipse.jgit.lib.PersonIdent;
  73. import org.eclipse.jgit.lib.ProgressMonitor;
  74. import org.eclipse.jgit.lib.Ref;
  75. import org.eclipse.jgit.lib.RefDatabase;
  76. import org.eclipse.jgit.lib.RefUpdate;
  77. import org.eclipse.jgit.lib.RefUpdate.Result;
  78. import org.eclipse.jgit.lib.Repository;
  79. import org.eclipse.jgit.revwalk.RevCommit;
  80. import org.eclipse.jgit.revwalk.RevWalk;
  81. import org.eclipse.jgit.util.FileUtils;
  82. /**
  83. * A class used to execute a repo command.
  84. *
  85. * This will parse a repo XML manifest, convert it into .gitmodules file and the
  86. * repository config file.
  87. *
  88. * If called against a bare repository, it will replace all the existing content
  89. * of the repository with the contents populated from the manifest.
  90. *
  91. * repo manifest allows projects overlapping, e.g. one project's path is
  92. * "foo" and another project's path is "foo/bar". This won't
  93. * work in git submodule, so we'll skip all the sub projects
  94. * ("foo/bar" in the example) while converting.
  95. *
  96. * @see <a href="https://code.google.com/p/git-repo/">git-repo project page</a>
  97. * @since 3.4
  98. */
  99. public class RepoCommand extends GitCommand<RevCommit> {
  100. private String path;
  101. private String uri;
  102. private String groups;
  103. private String branch;
  104. private PersonIdent author;
  105. private RemoteReader callback;
  106. private InputStream inputStream;
  107. private IncludedFileReader includedReader;
  108. private List<RepoProject> bareProjects;
  109. private Git git;
  110. private ProgressMonitor monitor;
  111. /**
  112. * A callback to get ref sha1 of a repository from its uri.
  113. *
  114. * We provided a default implementation {@link DefaultRemoteReader} to
  115. * use ls-remote command to read the sha1 from the repository and clone the
  116. * repository to read the file. Callers may have their own quicker
  117. * implementation.
  118. *
  119. * @since 3.4
  120. */
  121. public interface RemoteReader {
  122. /**
  123. * Read a remote ref sha1.
  124. *
  125. * @param uri
  126. * The URI of the remote repository
  127. * @param ref
  128. * The ref (branch/tag/etc.) to read
  129. * @return the sha1 of the remote repository
  130. * @throws GitAPIException
  131. */
  132. public ObjectId sha1(String uri, String ref) throws GitAPIException;
  133. /**
  134. * Read a file from a remote repository.
  135. *
  136. * @param uri
  137. * The URI of the remote repository
  138. * @param ref
  139. * The ref (branch/tag/etc.) to read
  140. * @param path
  141. * The relative path (inside the repo) to the file to read
  142. * @return the file content.
  143. * @throws GitAPIException
  144. * @throws IOException
  145. * @since 3.5
  146. */
  147. public byte[] readFile(String uri, String ref, String path)
  148. throws GitAPIException, IOException;
  149. }
  150. /** A default implementation of {@link RemoteReader} callback. */
  151. public static class DefaultRemoteReader implements RemoteReader {
  152. public ObjectId sha1(String uri, String ref) throws GitAPIException {
  153. Map<String, Ref> map = Git
  154. .lsRemoteRepository()
  155. .setRemote(uri)
  156. .callAsMap();
  157. Ref r = RefDatabase.findRef(map, ref);
  158. return r != null ? r.getObjectId() : null;
  159. }
  160. public byte[] readFile(String uri, String ref, String path)
  161. throws GitAPIException, IOException {
  162. File dir = FileUtils.createTempDir("jgit_", ".git", null); //$NON-NLS-1$ //$NON-NLS-2$
  163. Repository repo = Git
  164. .cloneRepository()
  165. .setBare(true)
  166. .setDirectory(dir)
  167. .setURI(uri)
  168. .call()
  169. .getRepository();
  170. try {
  171. return readFileFromRepo(repo, ref, path);
  172. } finally {
  173. repo.close();
  174. FileUtils.delete(dir, FileUtils.RECURSIVE);
  175. }
  176. }
  177. /**
  178. * Read a file from the repository
  179. *
  180. * @param repo
  181. * The repository containing the file
  182. * @param ref
  183. * The ref (branch/tag/etc.) to read
  184. * @param path
  185. * The relative path (inside the repo) to the file to read
  186. * @return the file's content
  187. * @throws GitAPIException
  188. * @throws IOException
  189. * @since 3.5
  190. */
  191. protected byte[] readFileFromRepo(Repository repo,
  192. String ref, String path) throws GitAPIException, IOException {
  193. try (ObjectReader reader = repo.newObjectReader()) {
  194. ObjectId oid = repo.resolve(ref + ":" + path); //$NON-NLS-1$
  195. return reader.open(oid).getBytes(Integer.MAX_VALUE);
  196. }
  197. }
  198. }
  199. @SuppressWarnings("serial")
  200. private static class ManifestErrorException extends GitAPIException {
  201. ManifestErrorException(Throwable cause) {
  202. super(RepoText.get().invalidManifest, cause);
  203. }
  204. }
  205. @SuppressWarnings("serial")
  206. private static class RemoteUnavailableException extends GitAPIException {
  207. RemoteUnavailableException(String uri) {
  208. super(MessageFormat.format(RepoText.get().errorRemoteUnavailable, uri));
  209. }
  210. }
  211. /**
  212. * @param repo
  213. */
  214. public RepoCommand(final Repository repo) {
  215. super(repo);
  216. }
  217. /**
  218. * Set path to the manifest XML file.
  219. *
  220. * Calling {@link #setInputStream} will ignore the path set here.
  221. *
  222. * @param path
  223. * (with <code>/</code> as separator)
  224. * @return this command
  225. */
  226. public RepoCommand setPath(final String path) {
  227. this.path = path;
  228. return this;
  229. }
  230. /**
  231. * Set the input stream to the manifest XML.
  232. *
  233. * Setting inputStream will ignore the path set. It will be closed in
  234. * {@link #call}.
  235. *
  236. * @param inputStream
  237. * @return this command
  238. * @since 3.5
  239. */
  240. public RepoCommand setInputStream(final InputStream inputStream) {
  241. this.inputStream = inputStream;
  242. return this;
  243. }
  244. /**
  245. * Set base URI of the pathes inside the XML
  246. *
  247. * @param uri
  248. * @return this command
  249. */
  250. public RepoCommand setURI(final String uri) {
  251. this.uri = uri;
  252. return this;
  253. }
  254. /**
  255. * Set groups to sync
  256. *
  257. * @param groups groups separated by comma, examples: default|all|G1,-G2,-G3
  258. * @return this command
  259. */
  260. public RepoCommand setGroups(final String groups) {
  261. this.groups = groups;
  262. return this;
  263. }
  264. /**
  265. * Set default branch.
  266. *
  267. * This is generally the name of the branch the manifest file was in. If
  268. * there's no default revision (branch) specified in manifest and no
  269. * revision specified in project, this branch will be used.
  270. *
  271. * @param branch
  272. * @return this command
  273. */
  274. public RepoCommand setBranch(final String branch) {
  275. this.branch = branch;
  276. return this;
  277. }
  278. /**
  279. * The progress monitor associated with the clone operation. By default,
  280. * this is set to <code>NullProgressMonitor</code>
  281. *
  282. * @see org.eclipse.jgit.lib.NullProgressMonitor
  283. * @param monitor
  284. * @return this command
  285. */
  286. public RepoCommand setProgressMonitor(final ProgressMonitor monitor) {
  287. this.monitor = monitor;
  288. return this;
  289. }
  290. /**
  291. * Set the author/committer for the bare repository commit.
  292. *
  293. * For non-bare repositories, the current user will be used and this will be
  294. * ignored.
  295. *
  296. * @param author
  297. * @return this command
  298. */
  299. public RepoCommand setAuthor(final PersonIdent author) {
  300. this.author = author;
  301. return this;
  302. }
  303. /**
  304. * Set the GetHeadFromUri callback.
  305. *
  306. * This is only used in bare repositories.
  307. *
  308. * @param callback
  309. * @return this command
  310. */
  311. public RepoCommand setRemoteReader(final RemoteReader callback) {
  312. this.callback = callback;
  313. return this;
  314. }
  315. /**
  316. * Set the IncludedFileReader callback.
  317. *
  318. * @param reader
  319. * @return this command
  320. * @since 4.0
  321. */
  322. public RepoCommand setIncludedFileReader(IncludedFileReader reader) {
  323. this.includedReader = reader;
  324. return this;
  325. }
  326. @Override
  327. public RevCommit call() throws GitAPIException {
  328. try {
  329. checkCallable();
  330. if (uri == null || uri.length() == 0)
  331. throw new IllegalArgumentException(
  332. JGitText.get().uriNotConfigured);
  333. if (inputStream == null) {
  334. if (path == null || path.length() == 0)
  335. throw new IllegalArgumentException(
  336. JGitText.get().pathNotConfigured);
  337. try {
  338. inputStream = new FileInputStream(path);
  339. } catch (IOException e) {
  340. throw new IllegalArgumentException(
  341. JGitText.get().pathNotConfigured);
  342. }
  343. }
  344. if (repo.isBare()) {
  345. bareProjects = new ArrayList<RepoProject>();
  346. if (author == null)
  347. author = new PersonIdent(repo);
  348. if (callback == null)
  349. callback = new DefaultRemoteReader();
  350. } else
  351. git = new Git(repo);
  352. ManifestParser parser = new ManifestParser(
  353. includedReader, path, branch, uri, groups, repo);
  354. try {
  355. parser.read(inputStream);
  356. for (RepoProject proj : parser.getFilteredProjects()) {
  357. addSubmodule(proj.getUrl(),
  358. proj.getPath(),
  359. proj.getRevision(),
  360. proj.getCopyFiles());
  361. }
  362. } catch (GitAPIException | IOException e) {
  363. throw new ManifestErrorException(e);
  364. }
  365. } finally {
  366. try {
  367. if (inputStream != null)
  368. inputStream.close();
  369. } catch (IOException e) {
  370. // Just ignore it, it's not important.
  371. }
  372. }
  373. if (repo.isBare()) {
  374. DirCache index = DirCache.newInCore();
  375. DirCacheBuilder builder = index.builder();
  376. ObjectInserter inserter = repo.newObjectInserter();
  377. try (RevWalk rw = new RevWalk(repo)) {
  378. Config cfg = new Config();
  379. for (RepoProject proj : bareProjects) {
  380. String name = proj.getPath();
  381. String nameUri = proj.getName();
  382. cfg.setString("submodule", name, "path", name); //$NON-NLS-1$ //$NON-NLS-2$
  383. cfg.setString("submodule", name, "url", nameUri); //$NON-NLS-1$ //$NON-NLS-2$
  384. // create gitlink
  385. DirCacheEntry dcEntry = new DirCacheEntry(name);
  386. ObjectId objectId;
  387. if (ObjectId.isId(proj.getRevision()))
  388. objectId = ObjectId.fromString(proj.getRevision());
  389. else {
  390. objectId = callback.sha1(nameUri, proj.getRevision());
  391. }
  392. if (objectId == null)
  393. throw new RemoteUnavailableException(nameUri);
  394. dcEntry.setObjectId(objectId);
  395. dcEntry.setFileMode(FileMode.GITLINK);
  396. builder.add(dcEntry);
  397. for (CopyFile copyfile : proj.getCopyFiles()) {
  398. byte[] src = callback.readFile(
  399. nameUri, proj.getRevision(), copyfile.src);
  400. objectId = inserter.insert(Constants.OBJ_BLOB, src);
  401. dcEntry = new DirCacheEntry(copyfile.dest);
  402. dcEntry.setObjectId(objectId);
  403. dcEntry.setFileMode(FileMode.REGULAR_FILE);
  404. builder.add(dcEntry);
  405. }
  406. }
  407. String content = cfg.toText();
  408. // create a new DirCacheEntry for .gitmodules file.
  409. final DirCacheEntry dcEntry = new DirCacheEntry(Constants.DOT_GIT_MODULES);
  410. ObjectId objectId = inserter.insert(Constants.OBJ_BLOB,
  411. content.getBytes(Constants.CHARACTER_ENCODING));
  412. dcEntry.setObjectId(objectId);
  413. dcEntry.setFileMode(FileMode.REGULAR_FILE);
  414. builder.add(dcEntry);
  415. builder.finish();
  416. ObjectId treeId = index.writeTree(inserter);
  417. // Create a Commit object, populate it and write it
  418. ObjectId headId = repo.resolve(Constants.HEAD + "^{commit}"); //$NON-NLS-1$
  419. CommitBuilder commit = new CommitBuilder();
  420. commit.setTreeId(treeId);
  421. if (headId != null)
  422. commit.setParentIds(headId);
  423. commit.setAuthor(author);
  424. commit.setCommitter(author);
  425. commit.setMessage(RepoText.get().repoCommitMessage);
  426. ObjectId commitId = inserter.insert(commit);
  427. inserter.flush();
  428. RefUpdate ru = repo.updateRef(Constants.HEAD);
  429. ru.setNewObjectId(commitId);
  430. ru.setExpectedOldObjectId(headId != null ? headId : ObjectId.zeroId());
  431. Result rc = ru.update(rw);
  432. switch (rc) {
  433. case NEW:
  434. case FORCED:
  435. case FAST_FORWARD:
  436. // Successful. Do nothing.
  437. break;
  438. case REJECTED:
  439. case LOCK_FAILURE:
  440. throw new ConcurrentRefUpdateException(
  441. JGitText.get().couldNotLockHEAD, ru.getRef(),
  442. rc);
  443. default:
  444. throw new JGitInternalException(MessageFormat.format(
  445. JGitText.get().updatingRefFailed,
  446. Constants.HEAD, commitId.name(), rc));
  447. }
  448. return rw.parseCommit(commitId);
  449. } catch (IOException e) {
  450. throw new ManifestErrorException(e);
  451. }
  452. } else {
  453. return git
  454. .commit()
  455. .setMessage(RepoText.get().repoCommitMessage)
  456. .call();
  457. }
  458. }
  459. private void addSubmodule(String url, String name, String revision,
  460. List<CopyFile> copyfiles) throws GitAPIException, IOException {
  461. if (repo.isBare()) {
  462. RepoProject proj = new RepoProject(url, name, revision, null, null);
  463. proj.addCopyFiles(copyfiles);
  464. bareProjects.add(proj);
  465. } else {
  466. SubmoduleAddCommand add = git
  467. .submoduleAdd()
  468. .setPath(name)
  469. .setURI(url);
  470. if (monitor != null)
  471. add.setProgressMonitor(monitor);
  472. Repository subRepo = add.call();
  473. if (revision != null) {
  474. try (Git sub = new Git(subRepo)) {
  475. sub.checkout().setName(findRef(revision, subRepo))
  476. .call();
  477. }
  478. subRepo.close();
  479. git.add().addFilepattern(name).call();
  480. }
  481. for (CopyFile copyfile : copyfiles) {
  482. copyfile.copy();
  483. git.add().addFilepattern(copyfile.dest).call();
  484. }
  485. }
  486. }
  487. private static String findRef(String ref, Repository repo)
  488. throws IOException {
  489. if (!ObjectId.isId(ref)) {
  490. Ref r = repo.getRef(Constants.DEFAULT_REMOTE_NAME + "/" + ref); //$NON-NLS-1$
  491. if (r != null)
  492. return r.getName();
  493. }
  494. return ref;
  495. }
  496. }