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.

SubmoduleWalk.java 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. /*
  2. * Copyright (C) 2011, GitHub 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.submodule;
  44. import java.io.File;
  45. import java.io.IOException;
  46. import java.text.MessageFormat;
  47. import org.eclipse.jgit.dircache.DirCacheIterator;
  48. import org.eclipse.jgit.errors.ConfigInvalidException;
  49. import org.eclipse.jgit.errors.CorruptObjectException;
  50. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  51. import org.eclipse.jgit.errors.MissingObjectException;
  52. import org.eclipse.jgit.errors.RepositoryNotFoundException;
  53. import org.eclipse.jgit.internal.JGitText;
  54. import org.eclipse.jgit.lib.AnyObjectId;
  55. import org.eclipse.jgit.lib.ConfigConstants;
  56. import org.eclipse.jgit.lib.Constants;
  57. import org.eclipse.jgit.lib.FileMode;
  58. import org.eclipse.jgit.lib.ObjectId;
  59. import org.eclipse.jgit.lib.Ref;
  60. import org.eclipse.jgit.lib.Repository;
  61. import org.eclipse.jgit.lib.RepositoryBuilder;
  62. import org.eclipse.jgit.lib.StoredConfig;
  63. import org.eclipse.jgit.storage.file.FileBasedConfig;
  64. import org.eclipse.jgit.treewalk.AbstractTreeIterator;
  65. import org.eclipse.jgit.treewalk.TreeWalk;
  66. import org.eclipse.jgit.treewalk.filter.PathFilter;
  67. import org.eclipse.jgit.treewalk.filter.TreeFilter;
  68. import org.eclipse.jgit.util.FS;
  69. /**
  70. * Walker that visits all submodule entries found in a tree
  71. */
  72. public class SubmoduleWalk {
  73. /**
  74. * Create a generator to walk over the submodule entries currently in the
  75. * index
  76. *
  77. * @param repository
  78. * @return generator over submodule index entries
  79. * @throws IOException
  80. */
  81. public static SubmoduleWalk forIndex(Repository repository)
  82. throws IOException {
  83. SubmoduleWalk generator = new SubmoduleWalk(repository);
  84. generator.setTree(new DirCacheIterator(repository.readDirCache()));
  85. return generator;
  86. }
  87. /**
  88. * Create a generator and advance it to the submodule entry at the given
  89. * path
  90. *
  91. * @param repository
  92. * @param treeId
  93. * @param path
  94. * @return generator at given path, null if no submodule at given path
  95. * @throws IOException
  96. */
  97. public static SubmoduleWalk forPath(Repository repository,
  98. AnyObjectId treeId, String path) throws IOException {
  99. SubmoduleWalk generator = new SubmoduleWalk(repository);
  100. generator.setTree(treeId);
  101. PathFilter filter = PathFilter.create(path);
  102. generator.setFilter(filter);
  103. while (generator.next())
  104. if (filter.isDone(generator.walk))
  105. return generator;
  106. return null;
  107. }
  108. /**
  109. * Create a generator and advance it to the submodule entry at the given
  110. * path
  111. *
  112. * @param repository
  113. * @param iterator
  114. * @param path
  115. * @return generator at given path, null if no submodule at given path
  116. * @throws IOException
  117. */
  118. public static SubmoduleWalk forPath(Repository repository,
  119. AbstractTreeIterator iterator, String path) throws IOException {
  120. SubmoduleWalk generator = new SubmoduleWalk(repository);
  121. generator.setTree(iterator);
  122. PathFilter filter = PathFilter.create(path);
  123. generator.setFilter(filter);
  124. while (generator.next())
  125. if (filter.isDone(generator.walk))
  126. return generator;
  127. return null;
  128. }
  129. /**
  130. * Get submodule directory
  131. *
  132. * @param parent
  133. * @param path
  134. * @return directory
  135. */
  136. public static File getSubmoduleDirectory(final Repository parent,
  137. final String path) {
  138. return new File(parent.getWorkTree(), path);
  139. }
  140. /**
  141. * Get submodule repository
  142. *
  143. * @param parent
  144. * @param path
  145. * @return repository or null if repository doesn't exist
  146. * @throws IOException
  147. */
  148. public static Repository getSubmoduleRepository(final Repository parent,
  149. final String path) throws IOException {
  150. return getSubmoduleRepository(parent.getWorkTree(), path);
  151. }
  152. /**
  153. * Get submodule repository at path
  154. *
  155. * @param parent
  156. * @param path
  157. * @return repository or null if repository doesn't exist
  158. * @throws IOException
  159. */
  160. public static Repository getSubmoduleRepository(final File parent,
  161. final String path) throws IOException {
  162. File subWorkTree = new File(parent, path);
  163. if (!subWorkTree.isDirectory())
  164. return null;
  165. File workTree = new File(parent, path);
  166. try {
  167. return new RepositoryBuilder() //
  168. .setMustExist(true) //
  169. .setFS(FS.DETECTED) //
  170. .setWorkTree(workTree) //
  171. .build();
  172. } catch (RepositoryNotFoundException e) {
  173. return null;
  174. }
  175. }
  176. /**
  177. * Resolve submodule repository URL.
  178. * <p>
  179. * This handles relative URLs that are typically specified in the
  180. * '.gitmodules' file by resolving them against the remote URL of the parent
  181. * repository.
  182. * <p>
  183. * Relative URLs will be resolved against the parent repository's working
  184. * directory if the parent repository has no configured remote URL.
  185. *
  186. * @param parent
  187. * parent repository
  188. * @param url
  189. * absolute or relative URL of the submodule repository
  190. * @return resolved URL
  191. * @throws IOException
  192. */
  193. public static String getSubmoduleRemoteUrl(final Repository parent,
  194. final String url) throws IOException {
  195. if (!url.startsWith("./") && !url.startsWith("../"))
  196. return url;
  197. String remoteName = null;
  198. // Look up remote URL associated wit HEAD ref
  199. Ref ref = parent.getRef(Constants.HEAD);
  200. if (ref != null) {
  201. if (ref.isSymbolic())
  202. ref = ref.getLeaf();
  203. remoteName = parent.getConfig().getString(
  204. ConfigConstants.CONFIG_BRANCH_SECTION,
  205. Repository.shortenRefName(ref.getName()),
  206. ConfigConstants.CONFIG_KEY_REMOTE);
  207. }
  208. // Fall back to 'origin' if current HEAD ref has no remote URL
  209. if (remoteName == null)
  210. remoteName = Constants.DEFAULT_REMOTE_NAME;
  211. String remoteUrl = parent.getConfig().getString(
  212. ConfigConstants.CONFIG_REMOTE_SECTION, remoteName,
  213. ConfigConstants.CONFIG_KEY_URL);
  214. // Fall back to parent repository's working directory if no remote URL
  215. if (remoteUrl == null) {
  216. remoteUrl = parent.getWorkTree().getAbsolutePath();
  217. // Normalize slashes to '/'
  218. if ('\\' == File.separatorChar)
  219. remoteUrl = remoteUrl.replace('\\', '/');
  220. }
  221. // Remove trailing '/'
  222. if (remoteUrl.charAt(remoteUrl.length() - 1) == '/')
  223. remoteUrl = remoteUrl.substring(0, remoteUrl.length() - 1);
  224. char separator = '/';
  225. String submoduleUrl = url;
  226. while (submoduleUrl.length() > 0) {
  227. if (submoduleUrl.startsWith("./"))
  228. submoduleUrl = submoduleUrl.substring(2);
  229. else if (submoduleUrl.startsWith("../")) {
  230. int lastSeparator = remoteUrl.lastIndexOf('/');
  231. if (lastSeparator < 1) {
  232. lastSeparator = remoteUrl.lastIndexOf(':');
  233. separator = ':';
  234. }
  235. if (lastSeparator < 1)
  236. throw new IOException(MessageFormat.format(
  237. JGitText.get().submoduleParentRemoteUrlInvalid,
  238. remoteUrl));
  239. remoteUrl = remoteUrl.substring(0, lastSeparator);
  240. submoduleUrl = submoduleUrl.substring(3);
  241. } else
  242. break;
  243. }
  244. return remoteUrl + separator + submoduleUrl;
  245. }
  246. private final Repository repository;
  247. private final TreeWalk walk;
  248. private StoredConfig repoConfig;
  249. private FileBasedConfig modulesConfig;
  250. private String path;
  251. /**
  252. * Create submodule generator
  253. *
  254. * @param repository
  255. * @throws IOException
  256. */
  257. public SubmoduleWalk(final Repository repository) throws IOException {
  258. this.repository = repository;
  259. repoConfig = repository.getConfig();
  260. walk = new TreeWalk(repository);
  261. walk.setRecursive(true);
  262. }
  263. private void loadModulesConfig() throws IOException, ConfigInvalidException {
  264. if (modulesConfig == null) {
  265. File modulesFile = new File(repository.getWorkTree(),
  266. Constants.DOT_GIT_MODULES);
  267. FileBasedConfig config = new FileBasedConfig(modulesFile,
  268. repository.getFS());
  269. config.load();
  270. modulesConfig = config;
  271. }
  272. }
  273. /**
  274. * Set tree filter
  275. *
  276. * @param filter
  277. * @return this generator
  278. */
  279. public SubmoduleWalk setFilter(TreeFilter filter) {
  280. walk.setFilter(filter);
  281. return this;
  282. }
  283. /**
  284. * Set the tree iterator used for finding submodule entries
  285. *
  286. * @param iterator
  287. * @return this generator
  288. * @throws CorruptObjectException
  289. */
  290. public SubmoduleWalk setTree(final AbstractTreeIterator iterator)
  291. throws CorruptObjectException {
  292. walk.addTree(iterator);
  293. return this;
  294. }
  295. /**
  296. * Set the tree used for finding submodule entries
  297. *
  298. * @param treeId
  299. * @return this generator
  300. * @throws IOException
  301. * @throws IncorrectObjectTypeException
  302. * @throws MissingObjectException
  303. */
  304. public SubmoduleWalk setTree(final AnyObjectId treeId) throws IOException {
  305. walk.addTree(treeId);
  306. return this;
  307. }
  308. /**
  309. * Reset generator and start new submodule walk
  310. *
  311. * @return this generator
  312. */
  313. public SubmoduleWalk reset() {
  314. repoConfig = repository.getConfig();
  315. modulesConfig = null;
  316. walk.reset();
  317. return this;
  318. }
  319. /**
  320. * Get directory that will be the root of the submodule's local repository
  321. *
  322. * @return submodule repository directory
  323. */
  324. public File getDirectory() {
  325. return getSubmoduleDirectory(repository, path);
  326. }
  327. /**
  328. * Advance to next submodule in the index tree.
  329. *
  330. * The object id and path of the next entry can be obtained by calling
  331. * {@link #getObjectId()} and {@link #getPath()}.
  332. *
  333. * @return true if entry found, false otherwise
  334. * @throws IOException
  335. */
  336. public boolean next() throws IOException {
  337. while (walk.next()) {
  338. if (FileMode.GITLINK != walk.getFileMode(0))
  339. continue;
  340. path = walk.getPathString();
  341. return true;
  342. }
  343. path = null;
  344. return false;
  345. }
  346. /**
  347. * Get path of current submodule entry
  348. *
  349. * @return path
  350. */
  351. public String getPath() {
  352. return path;
  353. }
  354. /**
  355. * Get object id of current submodule entry
  356. *
  357. * @return object id
  358. */
  359. public ObjectId getObjectId() {
  360. return walk.getObjectId(0);
  361. }
  362. /**
  363. * Get the configured path for current entry. This will be the value from
  364. * the .gitmodules file in the current repository's working tree.
  365. *
  366. * @return configured path
  367. * @throws ConfigInvalidException
  368. * @throws IOException
  369. */
  370. public String getModulesPath() throws IOException, ConfigInvalidException {
  371. loadModulesConfig();
  372. return modulesConfig.getString(
  373. ConfigConstants.CONFIG_SUBMODULE_SECTION, path,
  374. ConfigConstants.CONFIG_KEY_PATH);
  375. }
  376. /**
  377. * Get the configured remote URL for current entry. This will be the value
  378. * from the repository's config.
  379. *
  380. * @return configured URL
  381. * @throws ConfigInvalidException
  382. * @throws IOException
  383. */
  384. public String getConfigUrl() throws IOException, ConfigInvalidException {
  385. return repoConfig.getString(ConfigConstants.CONFIG_SUBMODULE_SECTION,
  386. path, ConfigConstants.CONFIG_KEY_URL);
  387. }
  388. /**
  389. * Get the configured remote URL for current entry. This will be the value
  390. * from the .gitmodules file in the current repository's working tree.
  391. *
  392. * @return configured URL
  393. * @throws ConfigInvalidException
  394. * @throws IOException
  395. */
  396. public String getModulesUrl() throws IOException, ConfigInvalidException {
  397. loadModulesConfig();
  398. return modulesConfig.getString(
  399. ConfigConstants.CONFIG_SUBMODULE_SECTION, path,
  400. ConfigConstants.CONFIG_KEY_URL);
  401. }
  402. /**
  403. * Get the configured update field for current entry. This will be the value
  404. * from the repository's config.
  405. *
  406. * @return update value
  407. * @throws ConfigInvalidException
  408. * @throws IOException
  409. */
  410. public String getConfigUpdate() throws IOException, ConfigInvalidException {
  411. return repoConfig.getString(ConfigConstants.CONFIG_SUBMODULE_SECTION,
  412. path, ConfigConstants.CONFIG_KEY_UPDATE);
  413. }
  414. /**
  415. * Get the configured update field for current entry. This will be the value
  416. * from the .gitmodules file in the current repository's working tree.
  417. *
  418. * @return update value
  419. * @throws ConfigInvalidException
  420. * @throws IOException
  421. */
  422. public String getModulesUpdate() throws IOException, ConfigInvalidException {
  423. loadModulesConfig();
  424. return modulesConfig.getString(
  425. ConfigConstants.CONFIG_SUBMODULE_SECTION, path,
  426. ConfigConstants.CONFIG_KEY_UPDATE);
  427. }
  428. /**
  429. * Get repository for current submodule entry
  430. *
  431. * @return repository or null if non-existent
  432. * @throws IOException
  433. */
  434. public Repository getRepository() throws IOException {
  435. return getSubmoduleRepository(repository, path);
  436. }
  437. /**
  438. * Get commit id that HEAD points to in the current submodule's repository
  439. *
  440. * @return object id of HEAD reference
  441. * @throws IOException
  442. */
  443. public ObjectId getHead() throws IOException {
  444. Repository subRepo = getRepository();
  445. return subRepo != null ? subRepo.resolve(Constants.HEAD) : null;
  446. }
  447. /**
  448. * Get ref that HEAD points to in the current submodule's repository
  449. *
  450. * @return ref name, null on failures
  451. * @throws IOException
  452. */
  453. public String getHeadRef() throws IOException {
  454. Repository subRepo = getRepository();
  455. if (subRepo == null)
  456. return null;
  457. Ref head = subRepo.getRef(Constants.HEAD);
  458. return head != null ? head.getLeaf().getName() : null;
  459. }
  460. /**
  461. * Get the resolved remote URL for the current submodule.
  462. * <p>
  463. * This method resolves the value of {@link #getModulesUrl()} to an absolute
  464. * URL
  465. *
  466. * @return resolved remote URL
  467. * @throws IOException
  468. * @throws ConfigInvalidException
  469. */
  470. public String getRemoteUrl() throws IOException, ConfigInvalidException {
  471. String url = getModulesUrl();
  472. return url != null ? getSubmoduleRemoteUrl(repository, url) : null;
  473. }
  474. }