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

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