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.

RepositoryCache.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. /*
  2. * Copyright (C) 2009, 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.lib;
  44. import java.io.File;
  45. import java.io.IOException;
  46. import java.lang.ref.Reference;
  47. import java.lang.ref.SoftReference;
  48. import java.util.Iterator;
  49. import java.util.Map;
  50. import java.util.concurrent.ConcurrentHashMap;
  51. import org.eclipse.jgit.errors.RepositoryNotFoundException;
  52. import org.eclipse.jgit.util.FS;
  53. import org.eclipse.jgit.util.IO;
  54. import org.eclipse.jgit.util.RawParseUtils;
  55. /** Cache of active {@link Repository} instances. */
  56. public class RepositoryCache {
  57. private static final RepositoryCache cache = new RepositoryCache();
  58. /**
  59. * Open an existing repository, reusing a cached instance if possible.
  60. * <p>
  61. * When done with the repository, the caller must call
  62. * {@link Repository#close()} to decrement the repository's usage counter.
  63. *
  64. * @param location
  65. * where the local repository is. Typically a {@link FileKey}.
  66. * @return the repository instance requested; caller must close when done.
  67. * @throws IOException
  68. * the repository could not be read (likely its core.version
  69. * property is not supported).
  70. * @throws RepositoryNotFoundException
  71. * there is no repository at the given location.
  72. */
  73. public static Repository open(final Key location) throws IOException,
  74. RepositoryNotFoundException {
  75. return open(location, true);
  76. }
  77. /**
  78. * Open a repository, reusing a cached instance if possible.
  79. * <p>
  80. * When done with the repository, the caller must call
  81. * {@link Repository#close()} to decrement the repository's usage counter.
  82. *
  83. * @param location
  84. * where the local repository is. Typically a {@link FileKey}.
  85. * @param mustExist
  86. * If true, and the repository is not found, throws {@code
  87. * RepositoryNotFoundException}. If false, a repository instance
  88. * is created and registered anyway.
  89. * @return the repository instance requested; caller must close when done.
  90. * @throws IOException
  91. * the repository could not be read (likely its core.version
  92. * property is not supported).
  93. * @throws RepositoryNotFoundException
  94. * There is no repository at the given location, only thrown if
  95. * {@code mustExist} is true.
  96. */
  97. public static Repository open(final Key location, final boolean mustExist)
  98. throws IOException {
  99. return cache.openRepository(location, mustExist);
  100. }
  101. /**
  102. * Register one repository into the cache.
  103. * <p>
  104. * During registration the cache automatically increments the usage counter,
  105. * permitting it to retain the reference. A {@link FileKey} for the
  106. * repository's {@link Repository#getDirectory()} is used to index the
  107. * repository in the cache.
  108. * <p>
  109. * If another repository already is registered in the cache at this
  110. * location, the other instance is closed.
  111. *
  112. * @param db
  113. * repository to register.
  114. */
  115. public static void register(final Repository db) {
  116. cache.registerRepository(FileKey.exact(db.getDirectory()), db);
  117. }
  118. /**
  119. * Remove a repository from the cache.
  120. * <p>
  121. * Removes a repository from the cache, if it is still registered here,
  122. * permitting it to close.
  123. *
  124. * @param db
  125. * repository to unregister.
  126. */
  127. public static void close(final Repository db) {
  128. cache.unregisterRepository(FileKey.exact(db.getDirectory()));
  129. }
  130. /** Unregister all repositories from the cache. */
  131. public static void clear() {
  132. cache.clearAll();
  133. }
  134. private final ConcurrentHashMap<Key, Reference<Repository>> cacheMap;
  135. private final Lock[] openLocks;
  136. private RepositoryCache() {
  137. cacheMap = new ConcurrentHashMap<Key, Reference<Repository>>();
  138. openLocks = new Lock[4];
  139. for (int i = 0; i < openLocks.length; i++)
  140. openLocks[i] = new Lock();
  141. }
  142. private Repository openRepository(final Key location,
  143. final boolean mustExist) throws IOException {
  144. Reference<Repository> ref = cacheMap.get(location);
  145. Repository db = ref != null ? ref.get() : null;
  146. if (db == null) {
  147. synchronized (lockFor(location)) {
  148. ref = cacheMap.get(location);
  149. db = ref != null ? ref.get() : null;
  150. if (db == null) {
  151. db = location.open(mustExist);
  152. ref = new SoftReference<Repository>(db);
  153. cacheMap.put(location, ref);
  154. }
  155. }
  156. }
  157. db.incrementOpen();
  158. return db;
  159. }
  160. private void registerRepository(final Key location, final Repository db) {
  161. db.incrementOpen();
  162. SoftReference<Repository> newRef = new SoftReference<Repository>(db);
  163. Reference<Repository> oldRef = cacheMap.put(location, newRef);
  164. Repository oldDb = oldRef != null ? oldRef.get() : null;
  165. if (oldDb != null)
  166. oldDb.close();
  167. }
  168. private void unregisterRepository(final Key location) {
  169. Reference<Repository> oldRef = cacheMap.remove(location);
  170. Repository oldDb = oldRef != null ? oldRef.get() : null;
  171. if (oldDb != null)
  172. oldDb.close();
  173. }
  174. private void clearAll() {
  175. for (int stage = 0; stage < 2; stage++) {
  176. for (Iterator<Map.Entry<Key, Reference<Repository>>> i = cacheMap
  177. .entrySet().iterator(); i.hasNext();) {
  178. final Map.Entry<Key, Reference<Repository>> e = i.next();
  179. final Repository db = e.getValue().get();
  180. if (db != null)
  181. db.close();
  182. i.remove();
  183. }
  184. }
  185. }
  186. private Lock lockFor(final Key location) {
  187. return openLocks[(location.hashCode() >>> 1) % openLocks.length];
  188. }
  189. private static class Lock {
  190. // Used only for its monitor.
  191. }
  192. /**
  193. * Abstract hash key for {@link RepositoryCache} entries.
  194. * <p>
  195. * A Key instance should be lightweight, and implement hashCode() and
  196. * equals() such that two Key instances are equal if they represent the same
  197. * Repository location.
  198. */
  199. public static interface Key {
  200. /**
  201. * Called by {@link RepositoryCache#open(Key)} if it doesn't exist yet.
  202. * <p>
  203. * If a repository does not exist yet in the cache, the cache will call
  204. * this method to acquire a handle to it.
  205. *
  206. * @param mustExist
  207. * true if the repository must exist in order to be opened;
  208. * false if a new non-existent repository is permitted to be
  209. * created (the caller is responsible for calling create).
  210. * @return the new repository instance.
  211. * @throws IOException
  212. * the repository could not be read (likely its core.version
  213. * property is not supported).
  214. * @throws RepositoryNotFoundException
  215. * There is no repository at the given location, only thrown
  216. * if {@code mustExist} is true.
  217. */
  218. Repository open(boolean mustExist) throws IOException,
  219. RepositoryNotFoundException;
  220. }
  221. /** Location of a Repository, using the standard java.io.File API. */
  222. public static class FileKey implements Key {
  223. /**
  224. * Obtain a pointer to an exact location on disk.
  225. * <p>
  226. * No guessing is performed, the given location is exactly the GIT_DIR
  227. * directory of the repository.
  228. *
  229. * @param directory
  230. * location where the repository database is.
  231. * @return a key for the given directory.
  232. * @see #lenient(File)
  233. */
  234. public static FileKey exact(final File directory) {
  235. return new FileKey(directory);
  236. }
  237. /**
  238. * Obtain a pointer to a location on disk.
  239. * <p>
  240. * The method performs some basic guessing to locate the repository.
  241. * Searched paths are:
  242. * <ol>
  243. * <li>{@code directory} // assume exact match</li>
  244. * <li>{@code directory} + "/.git" // assume working directory</li>
  245. * <li>{@code directory} + ".git" // assume bare</li>
  246. * </ol>
  247. *
  248. * @param directory
  249. * location where the repository database might be.
  250. * @return a key for the given directory.
  251. * @see #exact(File)
  252. */
  253. public static FileKey lenient(final File directory) {
  254. final File gitdir = resolve(directory);
  255. return new FileKey(gitdir != null ? gitdir : directory);
  256. }
  257. private final File path;
  258. /**
  259. * @param directory
  260. * exact location of the repository.
  261. */
  262. protected FileKey(final File directory) {
  263. path = canonical(directory);
  264. }
  265. private static File canonical(final File path) {
  266. try {
  267. return path.getCanonicalFile();
  268. } catch (IOException e) {
  269. return path.getAbsoluteFile();
  270. }
  271. }
  272. /** @return location supplied to the constructor. */
  273. public final File getFile() {
  274. return path;
  275. }
  276. public Repository open(final boolean mustExist) throws IOException {
  277. if (mustExist && !isGitRepository(path))
  278. throw new RepositoryNotFoundException(path);
  279. return new Repository(path);
  280. }
  281. @Override
  282. public int hashCode() {
  283. return path.hashCode();
  284. }
  285. @Override
  286. public boolean equals(final Object o) {
  287. return o instanceof FileKey && path.equals(((FileKey) o).path);
  288. }
  289. @Override
  290. public String toString() {
  291. return path.toString();
  292. }
  293. /**
  294. * Guess if a directory contains a Git repository.
  295. * <p>
  296. * This method guesses by looking for the existence of some key files
  297. * and directories.
  298. *
  299. * @param dir
  300. * the location of the directory to examine.
  301. * @return true if the directory "looks like" a Git repository; false if
  302. * it doesn't look enough like a Git directory to really be a
  303. * Git directory.
  304. */
  305. public static boolean isGitRepository(final File dir) {
  306. return FS.resolve(dir, "objects").exists()
  307. && FS.resolve(dir, "refs").exists()
  308. && isValidHead(new File(dir, Constants.HEAD));
  309. }
  310. private static boolean isValidHead(final File head) {
  311. final String ref = readFirstLine(head);
  312. return ref != null
  313. && (ref.startsWith("ref: refs/") || ObjectId.isId(ref));
  314. }
  315. private static String readFirstLine(final File head) {
  316. try {
  317. final byte[] buf = IO.readFully(head, 4096);
  318. int n = buf.length;
  319. if (n == 0)
  320. return null;
  321. if (buf[n - 1] == '\n')
  322. n--;
  323. return RawParseUtils.decode(buf, 0, n);
  324. } catch (IOException e) {
  325. return null;
  326. }
  327. }
  328. /**
  329. * Guess the proper path for a Git repository.
  330. * <p>
  331. * The method performs some basic guessing to locate the repository.
  332. * Searched paths are:
  333. * <ol>
  334. * <li>{@code directory} // assume exact match</li>
  335. * <li>{@code directory} + "/.git" // assume working directory</li>
  336. * <li>{@code directory} + ".git" // assume bare</li>
  337. * </ol>
  338. *
  339. * @param directory
  340. * location to guess from. Several permutations are tried.
  341. * @return the actual directory location if a better match is found;
  342. * null if there is no suitable match.
  343. */
  344. public static File resolve(final File directory) {
  345. if (isGitRepository(directory))
  346. return directory;
  347. if (isGitRepository(new File(directory, Constants.DOT_GIT)))
  348. return new File(directory, Constants.DOT_GIT);
  349. final String name = directory.getName();
  350. final File parent = directory.getParentFile();
  351. if (isGitRepository(new File(parent, name + Constants.DOT_GIT_EXT)))
  352. return new File(parent, name + Constants.DOT_GIT_EXT);
  353. return null;
  354. }
  355. }
  356. }