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.

ManifestParser.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. /*
  2. * Copyright (C) 2015, 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.IOException;
  46. import java.io.InputStream;
  47. import java.net.URI;
  48. import java.net.URISyntaxException;
  49. import java.text.MessageFormat;
  50. import java.util.ArrayList;
  51. import java.util.Collections;
  52. import java.util.HashMap;
  53. import java.util.HashSet;
  54. import java.util.Iterator;
  55. import java.util.List;
  56. import java.util.Map;
  57. import java.util.Set;
  58. import org.eclipse.jgit.annotations.NonNull;
  59. import org.eclipse.jgit.api.errors.GitAPIException;
  60. import org.eclipse.jgit.gitrepo.RepoProject.CopyFile;
  61. import org.eclipse.jgit.gitrepo.internal.RepoText;
  62. import org.eclipse.jgit.internal.JGitText;
  63. import org.eclipse.jgit.lib.Repository;
  64. import org.xml.sax.Attributes;
  65. import org.xml.sax.InputSource;
  66. import org.xml.sax.SAXException;
  67. import org.xml.sax.XMLReader;
  68. import org.xml.sax.helpers.DefaultHandler;
  69. import org.xml.sax.helpers.XMLReaderFactory;
  70. /**
  71. * Repo XML manifest parser.
  72. *
  73. * @see <a href="https://code.google.com/p/git-repo/">git-repo project page</a>
  74. * @since 4.0
  75. */
  76. public class ManifestParser extends DefaultHandler {
  77. private final String filename;
  78. private final URI baseUrl;
  79. private final String defaultBranch;
  80. private final Repository rootRepo;
  81. private final Map<String, Remote> remotes;
  82. private final Set<String> plusGroups;
  83. private final Set<String> minusGroups;
  84. private final List<RepoProject> projects;
  85. private final List<RepoProject> filteredProjects;
  86. private final IncludedFileReader includedReader;
  87. private String defaultRemote;
  88. private String defaultRevision;
  89. private int xmlInRead;
  90. private RepoProject currentProject;
  91. /**
  92. * A callback to read included xml files.
  93. */
  94. public interface IncludedFileReader {
  95. /**
  96. * Read a file from the same base dir of the manifest xml file.
  97. *
  98. * @param path
  99. * The relative path to the file to read
  100. * @return the {@code InputStream} of the file.
  101. * @throws GitAPIException
  102. * @throws IOException
  103. */
  104. public InputStream readIncludeFile(String path)
  105. throws GitAPIException, IOException;
  106. }
  107. /**
  108. * @param includedReader
  109. * @param filename
  110. * @param defaultBranch
  111. * @param baseUrl
  112. * @param groups
  113. * @param rootRepo
  114. */
  115. public ManifestParser(IncludedFileReader includedReader, String filename,
  116. String defaultBranch, String baseUrl, String groups,
  117. Repository rootRepo) {
  118. this.includedReader = includedReader;
  119. this.filename = filename;
  120. this.defaultBranch = defaultBranch;
  121. this.rootRepo = rootRepo;
  122. this.baseUrl = normalizeEmptyPath(URI.create(baseUrl));
  123. plusGroups = new HashSet<>();
  124. minusGroups = new HashSet<>();
  125. if (groups == null || groups.length() == 0
  126. || groups.equals("default")) { //$NON-NLS-1$
  127. // default means "all,-notdefault"
  128. minusGroups.add("notdefault"); //$NON-NLS-1$
  129. } else {
  130. for (String group : groups.split(",")) { //$NON-NLS-1$
  131. if (group.startsWith("-")) //$NON-NLS-1$
  132. minusGroups.add(group.substring(1));
  133. else
  134. plusGroups.add(group);
  135. }
  136. }
  137. remotes = new HashMap<>();
  138. projects = new ArrayList<>();
  139. filteredProjects = new ArrayList<>();
  140. }
  141. /**
  142. * Read the xml file.
  143. *
  144. * @param inputStream
  145. * @throws IOException
  146. */
  147. public void read(InputStream inputStream) throws IOException {
  148. xmlInRead++;
  149. final XMLReader xr;
  150. try {
  151. xr = XMLReaderFactory.createXMLReader();
  152. } catch (SAXException e) {
  153. throw new IOException(JGitText.get().noXMLParserAvailable);
  154. }
  155. xr.setContentHandler(this);
  156. try {
  157. xr.parse(new InputSource(inputStream));
  158. } catch (SAXException e) {
  159. IOException error = new IOException(
  160. RepoText.get().errorParsingManifestFile);
  161. error.initCause(e);
  162. throw error;
  163. }
  164. }
  165. @Override
  166. public void startElement(
  167. String uri,
  168. String localName,
  169. String qName,
  170. Attributes attributes) throws SAXException {
  171. if ("project".equals(qName)) { //$NON-NLS-1$
  172. if (attributes.getValue("name") == null) { //$NON-NLS-1$
  173. throw new SAXException(RepoText.get().invalidManifest);
  174. }
  175. currentProject = new RepoProject(
  176. attributes.getValue("name"), //$NON-NLS-1$
  177. attributes.getValue("path"), //$NON-NLS-1$
  178. attributes.getValue("revision"), //$NON-NLS-1$
  179. attributes.getValue("remote"), //$NON-NLS-1$
  180. attributes.getValue("groups")); //$NON-NLS-1$
  181. currentProject.setRecommendShallow(
  182. attributes.getValue("clone-depth")); //$NON-NLS-1$
  183. } else if ("remote".equals(qName)) { //$NON-NLS-1$
  184. String alias = attributes.getValue("alias"); //$NON-NLS-1$
  185. String fetch = attributes.getValue("fetch"); //$NON-NLS-1$
  186. String revision = attributes.getValue("revision"); //$NON-NLS-1$
  187. Remote remote = new Remote(fetch, revision);
  188. remotes.put(attributes.getValue("name"), remote); //$NON-NLS-1$
  189. if (alias != null)
  190. remotes.put(alias, remote);
  191. } else if ("default".equals(qName)) { //$NON-NLS-1$
  192. defaultRemote = attributes.getValue("remote"); //$NON-NLS-1$
  193. defaultRevision = attributes.getValue("revision"); //$NON-NLS-1$
  194. } else if ("copyfile".equals(qName)) { //$NON-NLS-1$
  195. if (currentProject == null)
  196. throw new SAXException(RepoText.get().invalidManifest);
  197. currentProject.addCopyFile(new CopyFile(
  198. rootRepo,
  199. currentProject.getPath(),
  200. attributes.getValue("src"), //$NON-NLS-1$
  201. attributes.getValue("dest"))); //$NON-NLS-1$
  202. } else if ("include".equals(qName)) { //$NON-NLS-1$
  203. String name = attributes.getValue("name"); //$NON-NLS-1$
  204. if (includedReader != null) {
  205. try (InputStream is = includedReader.readIncludeFile(name)) {
  206. if (is == null) {
  207. throw new SAXException(
  208. RepoText.get().errorIncludeNotImplemented);
  209. }
  210. read(is);
  211. } catch (Exception e) {
  212. throw new SAXException(MessageFormat.format(
  213. RepoText.get().errorIncludeFile, name), e);
  214. }
  215. } else if (filename != null) {
  216. int index = filename.lastIndexOf('/');
  217. String path = filename.substring(0, index + 1) + name;
  218. try (InputStream is = new FileInputStream(path)) {
  219. read(is);
  220. } catch (IOException e) {
  221. throw new SAXException(MessageFormat.format(
  222. RepoText.get().errorIncludeFile, path), e);
  223. }
  224. }
  225. }
  226. }
  227. @Override
  228. public void endElement(
  229. String uri,
  230. String localName,
  231. String qName) throws SAXException {
  232. if ("project".equals(qName)) { //$NON-NLS-1$
  233. projects.add(currentProject);
  234. currentProject = null;
  235. }
  236. }
  237. @Override
  238. public void endDocument() throws SAXException {
  239. xmlInRead--;
  240. if (xmlInRead != 0)
  241. return;
  242. // Only do the following after we finished reading everything.
  243. Map<String, URI> remoteUrls = new HashMap<>();
  244. if (defaultRevision == null && defaultRemote != null) {
  245. Remote remote = remotes.get(defaultRemote);
  246. if (remote != null) {
  247. defaultRevision = remote.revision;
  248. }
  249. if (defaultRevision == null) {
  250. defaultRevision = defaultBranch;
  251. }
  252. }
  253. for (RepoProject proj : projects) {
  254. String remote = proj.getRemote();
  255. String revision = defaultRevision;
  256. if (remote == null) {
  257. if (defaultRemote == null) {
  258. if (filename != null)
  259. throw new SAXException(MessageFormat.format(
  260. RepoText.get().errorNoDefaultFilename,
  261. filename));
  262. else
  263. throw new SAXException(
  264. RepoText.get().errorNoDefault);
  265. }
  266. remote = defaultRemote;
  267. } else {
  268. Remote r = remotes.get(remote);
  269. if (r != null && r.revision != null) {
  270. revision = r.revision;
  271. }
  272. }
  273. URI remoteUrl = remoteUrls.get(remote);
  274. if (remoteUrl == null) {
  275. String fetch = remotes.get(remote).fetch;
  276. if (fetch == null) {
  277. throw new SAXException(MessageFormat
  278. .format(RepoText.get().errorNoFetch, remote));
  279. }
  280. remoteUrl = normalizeEmptyPath(baseUrl.resolve(fetch));
  281. remoteUrls.put(remote, remoteUrl);
  282. }
  283. proj.setUrl(remoteUrl.resolve(proj.getName()).toString())
  284. .setDefaultRevision(revision);
  285. }
  286. filteredProjects.addAll(projects);
  287. removeNotInGroup();
  288. removeOverlaps();
  289. }
  290. static URI normalizeEmptyPath(URI u) {
  291. // URI.create("scheme://host").resolve("a/b") => "scheme://hosta/b"
  292. // That seems like bug https://bugs.openjdk.java.net/browse/JDK-4666701.
  293. // We workaround this by special casing the empty path case.
  294. if (u.getHost() != null && !u.getHost().isEmpty() &&
  295. (u.getPath() == null || u.getPath().isEmpty())) {
  296. try {
  297. return new URI(u.getScheme(),
  298. u.getUserInfo(), u.getHost(), u.getPort(),
  299. "/", u.getQuery(), u.getFragment()); //$NON-NLS-1$
  300. } catch (URISyntaxException x) {
  301. throw new IllegalArgumentException(x.getMessage(), x);
  302. }
  303. }
  304. return u;
  305. }
  306. /**
  307. * Getter for projects.
  308. *
  309. * @return projects list reference, never null
  310. */
  311. public List<RepoProject> getProjects() {
  312. return projects;
  313. }
  314. /**
  315. * Getter for filterdProjects.
  316. *
  317. * @return filtered projects list reference, never null
  318. */
  319. public @NonNull List<RepoProject> getFilteredProjects() {
  320. return filteredProjects;
  321. }
  322. /** Remove projects that are not in our desired groups. */
  323. void removeNotInGroup() {
  324. Iterator<RepoProject> iter = filteredProjects.iterator();
  325. while (iter.hasNext())
  326. if (!inGroups(iter.next()))
  327. iter.remove();
  328. }
  329. /** Remove projects that sits in a subdirectory of any other project. */
  330. void removeOverlaps() {
  331. Collections.sort(filteredProjects);
  332. Iterator<RepoProject> iter = filteredProjects.iterator();
  333. if (!iter.hasNext())
  334. return;
  335. RepoProject last = iter.next();
  336. while (iter.hasNext()) {
  337. RepoProject p = iter.next();
  338. if (last.isAncestorOf(p))
  339. iter.remove();
  340. else
  341. last = p;
  342. }
  343. removeNestedCopyfiles();
  344. }
  345. /** Remove copyfiles that sit in a subdirectory of any other project. */
  346. void removeNestedCopyfiles() {
  347. for (RepoProject proj : filteredProjects) {
  348. List<CopyFile> copyfiles = new ArrayList<>(proj.getCopyFiles());
  349. proj.clearCopyFiles();
  350. for (CopyFile copyfile : copyfiles) {
  351. if (!isNestedCopyfile(copyfile)) {
  352. proj.addCopyFile(copyfile);
  353. }
  354. }
  355. }
  356. }
  357. boolean inGroups(RepoProject proj) {
  358. for (String group : minusGroups) {
  359. if (proj.inGroup(group)) {
  360. // minus groups have highest priority.
  361. return false;
  362. }
  363. }
  364. if (plusGroups.isEmpty() || plusGroups.contains("all")) { //$NON-NLS-1$
  365. // empty plus groups means "all"
  366. return true;
  367. }
  368. for (String group : plusGroups) {
  369. if (proj.inGroup(group))
  370. return true;
  371. }
  372. return false;
  373. }
  374. private boolean isNestedCopyfile(CopyFile copyfile) {
  375. if (copyfile.dest.indexOf('/') == -1) {
  376. // If the copyfile is at root level then it won't be nested.
  377. return false;
  378. }
  379. for (RepoProject proj : filteredProjects) {
  380. if (proj.getPath().compareTo(copyfile.dest) > 0) {
  381. // Early return as remaining projects can't be ancestor of this
  382. // copyfile config (filteredProjects is sorted).
  383. return false;
  384. }
  385. if (proj.isAncestorOf(copyfile.dest)) {
  386. return true;
  387. }
  388. }
  389. return false;
  390. }
  391. private static class Remote {
  392. final String fetch;
  393. final String revision;
  394. Remote(String fetch, String revision) {
  395. this.fetch = fetch;
  396. this.revision = revision;
  397. }
  398. }
  399. }