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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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.FileInputStream;
  45. import java.io.FileOutputStream;
  46. import java.io.IOException;
  47. import java.net.URI;
  48. import java.net.URISyntaxException;
  49. import java.nio.channels.FileChannel;
  50. import java.nio.charset.Charset;
  51. import java.text.MessageFormat;
  52. import java.util.ArrayList;
  53. import java.util.Arrays;
  54. import java.util.Collection;
  55. import java.util.HashMap;
  56. import java.util.HashSet;
  57. import java.util.List;
  58. import java.util.Map;
  59. import java.util.Set;
  60. import org.eclipse.jgit.api.AddCommand;
  61. import org.eclipse.jgit.api.LsRemoteCommand;
  62. import org.eclipse.jgit.api.Git;
  63. import org.eclipse.jgit.api.GitCommand;
  64. import org.eclipse.jgit.api.SubmoduleAddCommand;
  65. import org.eclipse.jgit.api.errors.ConcurrentRefUpdateException;
  66. import org.eclipse.jgit.api.errors.GitAPIException;
  67. import org.eclipse.jgit.api.errors.JGitInternalException;
  68. import org.eclipse.jgit.dircache.DirCache;
  69. import org.eclipse.jgit.dircache.DirCacheBuilder;
  70. import org.eclipse.jgit.dircache.DirCacheEntry;
  71. import org.eclipse.jgit.gitrepo.internal.RepoText;
  72. import org.eclipse.jgit.internal.JGitText;
  73. import org.eclipse.jgit.lib.CommitBuilder;
  74. import org.eclipse.jgit.lib.Config;
  75. import org.eclipse.jgit.lib.Constants;
  76. import org.eclipse.jgit.lib.FileMode;
  77. import org.eclipse.jgit.lib.ObjectId;
  78. import org.eclipse.jgit.lib.ObjectInserter;
  79. import org.eclipse.jgit.lib.PersonIdent;
  80. import org.eclipse.jgit.lib.ProgressMonitor;
  81. import org.eclipse.jgit.lib.Ref;
  82. import org.eclipse.jgit.lib.RefUpdate;
  83. import org.eclipse.jgit.lib.RefUpdate.Result;
  84. import org.eclipse.jgit.lib.Repository;
  85. import org.eclipse.jgit.revwalk.RevCommit;
  86. import org.eclipse.jgit.revwalk.RevWalk;
  87. import org.xml.sax.Attributes;
  88. import org.xml.sax.InputSource;
  89. import org.xml.sax.SAXException;
  90. import org.xml.sax.XMLReader;
  91. import org.xml.sax.helpers.DefaultHandler;
  92. import org.xml.sax.helpers.XMLReaderFactory;
  93. /**
  94. * A class used to execute a repo command.
  95. *
  96. * This will parse a repo XML manifest, convert it into .gitmodules file and the
  97. * repository config file.
  98. *
  99. * @see <a href="https://code.google.com/p/git-repo/">git-repo project page</a>
  100. * @since 3.4
  101. */
  102. public class RepoCommand extends GitCommand<RevCommit> {
  103. private String path;
  104. private String uri;
  105. private String groups;
  106. private PersonIdent author;
  107. private RemoteReader callback;
  108. private List<Project> bareProjects;
  109. private Git git;
  110. private ProgressMonitor monitor;
  111. /**
  112. * A callback to get head 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. Callers may
  116. * have their own quicker implementation.
  117. */
  118. public interface RemoteReader {
  119. /**
  120. * Read a remote repository's HEAD sha1.
  121. *
  122. * @param uri
  123. * The URI of the remote repository
  124. * @return the sha1 of the HEAD of the remote repository
  125. */
  126. public ObjectId sha1(String uri) throws GitAPIException;
  127. }
  128. /** A default implementation of {@link RemoteReader} callback. */
  129. public static class DefaultRemoteReader implements RemoteReader {
  130. public ObjectId sha1(String uri) throws GitAPIException {
  131. Collection<Ref> refs = Git
  132. .lsRemoteRepository()
  133. .setRemote(uri)
  134. .call();
  135. for (Ref ref : refs) {
  136. if (Constants.HEAD.equals(ref.getName()))
  137. return ref.getObjectId();
  138. }
  139. return null;
  140. }
  141. }
  142. private static class CopyFile {
  143. final String src;
  144. final String dest;
  145. final String relativeDest;
  146. CopyFile(Repository repo, String path, String src, String dest) {
  147. this.src = repo.getWorkTree() + "/" + path + "/" + src; //$NON-NLS-1$ //$NON-NLS-2$
  148. this.relativeDest = dest;
  149. this.dest = repo.getWorkTree() + "/" + dest; //$NON-NLS-1$
  150. }
  151. void copy() throws IOException {
  152. FileInputStream input = new FileInputStream(src);
  153. try {
  154. FileOutputStream output = new FileOutputStream(dest);
  155. try {
  156. FileChannel channel = input.getChannel();
  157. output.getChannel().transferFrom(channel, 0, channel.size());
  158. } finally {
  159. output.close();
  160. }
  161. } finally {
  162. input.close();
  163. }
  164. }
  165. }
  166. private static class Project {
  167. final String name;
  168. final String path;
  169. final Set<String> groups;
  170. final List<CopyFile> copyfiles;
  171. Project(String name, String path, String groups) {
  172. this.name = name;
  173. this.path = path;
  174. this.groups = new HashSet<String>();
  175. if (groups != null && groups.length() > 0)
  176. this.groups.addAll(Arrays.asList(groups.split(","))); //$NON-NLS-1$
  177. copyfiles = new ArrayList<CopyFile>();
  178. }
  179. void addCopyFile(CopyFile copyfile) {
  180. copyfiles.add(copyfile);
  181. }
  182. }
  183. private static class XmlManifest extends DefaultHandler {
  184. private final RepoCommand command;
  185. private final String filename;
  186. private final String baseUrl;
  187. private final Map<String, String> remotes;
  188. private final List<Project> projects;
  189. private final Set<String> plusGroups;
  190. private final Set<String> minusGroups;
  191. private String defaultRemote;
  192. private Project currentProject;
  193. XmlManifest(RepoCommand command, String filename, String baseUrl, String groups) {
  194. this.command = command;
  195. this.filename = filename;
  196. this.baseUrl = baseUrl;
  197. remotes = new HashMap<String, String>();
  198. projects = new ArrayList<Project>();
  199. plusGroups = new HashSet<String>();
  200. minusGroups = new HashSet<String>();
  201. if (groups == null || groups.length() == 0 || groups.equals("default")) { //$NON-NLS-1$
  202. // default means "all,-notdefault"
  203. minusGroups.add("notdefault"); //$NON-NLS-1$
  204. } else {
  205. for (String group : groups.split(",")) { //$NON-NLS-1$
  206. if (group.startsWith("-")) //$NON-NLS-1$
  207. minusGroups.add(group.substring(1));
  208. else
  209. plusGroups.add(group);
  210. }
  211. }
  212. }
  213. void read() throws IOException {
  214. final XMLReader xr;
  215. try {
  216. xr = XMLReaderFactory.createXMLReader();
  217. } catch (SAXException e) {
  218. throw new IOException(JGitText.get().noXMLParserAvailable);
  219. }
  220. xr.setContentHandler(this);
  221. final FileInputStream in = new FileInputStream(filename);
  222. try {
  223. xr.parse(new InputSource(in));
  224. } catch (SAXException e) {
  225. IOException error = new IOException(MessageFormat.format(
  226. RepoText.get().errorParsingManifestFile, filename));
  227. error.initCause(e);
  228. throw error;
  229. } finally {
  230. in.close();
  231. }
  232. }
  233. @Override
  234. public void startElement(
  235. String uri,
  236. String localName,
  237. String qName,
  238. Attributes attributes) throws SAXException {
  239. if ("project".equals(qName)) { //$NON-NLS-1$
  240. currentProject = new Project( //$NON-NLS-1$
  241. attributes.getValue("name"), //$NON-NLS-1$
  242. attributes.getValue("path"), //$NON-NLS-1$
  243. attributes.getValue("groups")); //$NON-NLS-1$
  244. } else if ("remote".equals(qName)) { //$NON-NLS-1$
  245. remotes.put(attributes.getValue("name"), //$NON-NLS-1$
  246. attributes.getValue("fetch")); //$NON-NLS-1$
  247. } else if ("default".equals(qName)) { //$NON-NLS-1$
  248. defaultRemote = attributes.getValue("remote"); //$NON-NLS-1$
  249. } else if ("copyfile".equals(qName)) { //$NON-NLS-1$
  250. if (currentProject == null)
  251. throw new SAXException(RepoText.get().invalidManifest);
  252. currentProject.addCopyFile(new CopyFile(
  253. command.repo,
  254. currentProject.path,
  255. attributes.getValue("src"), //$NON-NLS-1$
  256. attributes.getValue("dest"))); //$NON-NLS-1$
  257. }
  258. }
  259. @Override
  260. public void endElement(
  261. String uri,
  262. String localName,
  263. String qName) throws SAXException {
  264. if ("project".equals(qName)) { //$NON-NLS-1$
  265. projects.add(currentProject);
  266. currentProject = null;
  267. }
  268. }
  269. @Override
  270. public void endDocument() throws SAXException {
  271. if (defaultRemote == null) {
  272. throw new SAXException(MessageFormat.format(
  273. RepoText.get().errorNoDefault, filename));
  274. }
  275. final String remoteUrl;
  276. try {
  277. URI uri = new URI(String.format("%s/%s/", baseUrl, remotes.get(defaultRemote))); //$NON-NLS-1$
  278. remoteUrl = uri.normalize().toString();
  279. } catch (URISyntaxException e) {
  280. throw new SAXException(e);
  281. }
  282. for (Project proj : projects) {
  283. if (inGroups(proj)) {
  284. String url = remoteUrl + proj.name;
  285. command.addSubmodule(url, proj.path);
  286. for (CopyFile copyfile : proj.copyfiles) {
  287. try {
  288. copyfile.copy();
  289. } catch (IOException e) {
  290. throw new SAXException(
  291. RepoText.get().copyFileFailed, e);
  292. }
  293. AddCommand add = command.git
  294. .add()
  295. .addFilepattern(copyfile.relativeDest);
  296. try {
  297. add.call();
  298. } catch (GitAPIException e) {
  299. throw new SAXException(e);
  300. }
  301. }
  302. }
  303. }
  304. }
  305. boolean inGroups(Project proj) {
  306. for (String group : minusGroups) {
  307. if (proj.groups.contains(group)) {
  308. // minus groups have highest priority.
  309. return false;
  310. }
  311. }
  312. if (plusGroups.isEmpty() || plusGroups.contains("all")) { //$NON-NLS-1$
  313. // empty plus groups means "all"
  314. return true;
  315. }
  316. for (String group : plusGroups) {
  317. if (proj.groups.contains(group))
  318. return true;
  319. }
  320. return false;
  321. }
  322. }
  323. private static class ManifestErrorException extends GitAPIException {
  324. ManifestErrorException(Throwable cause) {
  325. super(RepoText.get().invalidManifest, cause);
  326. }
  327. }
  328. private static class RemoteUnavailableException extends GitAPIException {
  329. RemoteUnavailableException(String uri, Throwable cause) {
  330. super(MessageFormat.format(RepoText.get().errorRemoteUnavailable, uri), cause);
  331. }
  332. }
  333. /**
  334. * @param repo
  335. */
  336. public RepoCommand(final Repository repo) {
  337. super(repo);
  338. }
  339. /**
  340. * Set path to the manifest XML file
  341. *
  342. * @param path
  343. * (with <code>/</code> as separator)
  344. * @return this command
  345. */
  346. public RepoCommand setPath(final String path) {
  347. this.path = path;
  348. return this;
  349. }
  350. /**
  351. * Set base URI of the pathes inside the XML
  352. *
  353. * @param uri
  354. * @return this command
  355. */
  356. public RepoCommand setURI(final String uri) {
  357. this.uri = uri;
  358. return this;
  359. }
  360. /**
  361. * Set groups to sync
  362. *
  363. * @param groups groups separated by comma, examples: default|all|G1,-G2,-G3
  364. * @return this command
  365. */
  366. public RepoCommand setGroups(final String groups) {
  367. this.groups = groups;
  368. return this;
  369. }
  370. /**
  371. * The progress monitor associated with the clone operation. By default,
  372. * this is set to <code>NullProgressMonitor</code>
  373. *
  374. * @see org.eclipse.jgit.lib.NullProgressMonitor
  375. * @param monitor
  376. * @return this command
  377. */
  378. public RepoCommand setProgressMonitor(final ProgressMonitor monitor) {
  379. this.monitor = monitor;
  380. return this;
  381. }
  382. /**
  383. * Set the author/committer for the bare repository commit.
  384. *
  385. * For non-bare repositories, the current user will be used and this will be ignored.
  386. *
  387. * @param author
  388. * @return this command
  389. */
  390. public RepoCommand setAuthor(final PersonIdent author) {
  391. this.author = author;
  392. return this;
  393. }
  394. /**
  395. * Set the GetHeadFromUri callback.
  396. *
  397. * This is only used in bare repositories.
  398. *
  399. * @param callback
  400. * @return this command
  401. */
  402. public RepoCommand setRemoteReader(final RemoteReader callback) {
  403. this.callback = callback;
  404. return this;
  405. }
  406. @Override
  407. public RevCommit call() throws GitAPIException {
  408. checkCallable();
  409. if (path == null || path.length() == 0)
  410. throw new IllegalArgumentException(JGitText.get().pathNotConfigured);
  411. if (uri == null || uri.length() == 0)
  412. throw new IllegalArgumentException(JGitText.get().uriNotConfigured);
  413. if (repo.isBare()) {
  414. bareProjects = new ArrayList<Project>();
  415. if (author == null)
  416. author = new PersonIdent(repo);
  417. if (callback == null)
  418. callback = new DefaultRemoteReader();
  419. } else
  420. git = new Git(repo);
  421. XmlManifest manifest = new XmlManifest(this, path, uri, groups);
  422. try {
  423. manifest.read();
  424. } catch (IOException e) {
  425. throw new ManifestErrorException(e);
  426. }
  427. if (repo.isBare()) {
  428. DirCache index = DirCache.newInCore();
  429. DirCacheBuilder builder = index.builder();
  430. ObjectInserter inserter = repo.newObjectInserter();
  431. RevWalk rw = new RevWalk(repo);
  432. try {
  433. Config cfg = new Config();
  434. for (Project proj : bareProjects) {
  435. String name = proj.path;
  436. String uri = proj.name;
  437. cfg.setString("submodule", name, "path", name); //$NON-NLS-1$ //$NON-NLS-2$
  438. cfg.setString("submodule", name, "url", uri); //$NON-NLS-1$ //$NON-NLS-2$
  439. // create gitlink
  440. final DirCacheEntry dcEntry = new DirCacheEntry(name);
  441. ObjectId objectId;
  442. try {
  443. objectId = callback.sha1(uri);
  444. } catch (GitAPIException e) {
  445. // Something wrong getting the head sha1
  446. throw new RemoteUnavailableException(uri, e);
  447. } catch (IllegalArgumentException e) {
  448. // The revision from the manifest is malformed.
  449. throw new ManifestErrorException(e);
  450. }
  451. if (objectId == null)
  452. throw new RemoteUnavailableException(uri, null);
  453. dcEntry.setObjectId(objectId);
  454. dcEntry.setFileMode(FileMode.GITLINK);
  455. builder.add(dcEntry);
  456. }
  457. String content = cfg.toText();
  458. // create a new DirCacheEntry for .gitmodules file.
  459. final DirCacheEntry dcEntry = new DirCacheEntry(Constants.DOT_GIT_MODULES);
  460. ObjectId objectId = inserter.insert(Constants.OBJ_BLOB,
  461. content.getBytes(Constants.CHARACTER_ENCODING));
  462. dcEntry.setObjectId(objectId);
  463. dcEntry.setFileMode(FileMode.REGULAR_FILE);
  464. builder.add(dcEntry);
  465. builder.finish();
  466. ObjectId treeId = index.writeTree(inserter);
  467. // Create a Commit object, populate it and write it
  468. ObjectId headId = repo.resolve(Constants.HEAD + "^{commit}"); //$NON-NLS-1$
  469. CommitBuilder commit = new CommitBuilder();
  470. commit.setTreeId(treeId);
  471. if (headId != null)
  472. commit.setParentIds(headId);
  473. commit.setAuthor(author);
  474. commit.setCommitter(author);
  475. commit.setMessage(RepoText.get().repoCommitMessage);
  476. ObjectId commitId = inserter.insert(commit);
  477. inserter.flush();
  478. RefUpdate ru = repo.updateRef(Constants.HEAD);
  479. ru.setNewObjectId(commitId);
  480. ru.setExpectedOldObjectId(headId != null ? headId : ObjectId.zeroId());
  481. Result rc = ru.update(rw);
  482. switch (rc) {
  483. case NEW:
  484. case FORCED:
  485. case FAST_FORWARD:
  486. // Successful. Do nothing.
  487. break;
  488. case REJECTED:
  489. case LOCK_FAILURE:
  490. throw new ConcurrentRefUpdateException(
  491. JGitText.get().couldNotLockHEAD, ru.getRef(),
  492. rc);
  493. default:
  494. throw new JGitInternalException(MessageFormat.format(
  495. JGitText.get().updatingRefFailed,
  496. Constants.HEAD, commitId.name(), rc));
  497. }
  498. return rw.parseCommit(commitId);
  499. } catch (IOException e) {
  500. throw new ManifestErrorException(e);
  501. } finally {
  502. rw.release();
  503. }
  504. } else {
  505. return git
  506. .commit()
  507. .setMessage(RepoText.get().repoCommitMessage)
  508. .call();
  509. }
  510. }
  511. private void addSubmodule(String url, String name) throws SAXException {
  512. if (repo.isBare()) {
  513. Project proj = new Project(url, name, null);
  514. bareProjects.add(proj);
  515. } else {
  516. SubmoduleAddCommand add = git
  517. .submoduleAdd()
  518. .setPath(name)
  519. .setURI(url);
  520. if (monitor != null)
  521. add.setProgressMonitor(monitor);
  522. try {
  523. add.call();
  524. } catch (GitAPIException e) {
  525. throw new SAXException(e);
  526. }
  527. }
  528. }
  529. }