Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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.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. private Repository openRepository(final Key location,
  150. final boolean mustExist) throws IOException {
  151. Reference<Repository> ref = cacheMap.get(location);
  152. Repository db = ref != null ? ref.get() : null;
  153. if (db == null) {
  154. synchronized (lockFor(location)) {
  155. ref = cacheMap.get(location);
  156. db = ref != null ? ref.get() : null;
  157. if (db == null) {
  158. db = location.open(mustExist);
  159. ref = new SoftReference<Repository>(db);
  160. cacheMap.put(location, ref);
  161. }
  162. }
  163. }
  164. db.incrementOpen();
  165. return db;
  166. }
  167. private void registerRepository(final Key location, final Repository db) {
  168. db.incrementOpen();
  169. SoftReference<Repository> newRef = new SoftReference<Repository>(db);
  170. Reference<Repository> oldRef = cacheMap.put(location, newRef);
  171. Repository oldDb = oldRef != null ? oldRef.get() : null;
  172. if (oldDb != null)
  173. oldDb.close();
  174. }
  175. private void unregisterRepository(final Key location) {
  176. Reference<Repository> oldRef = cacheMap.remove(location);
  177. Repository oldDb = oldRef != null ? oldRef.get() : null;
  178. if (oldDb != null)
  179. oldDb.close();
  180. }
  181. private void clearAll() {
  182. for (int stage = 0; stage < 2; stage++) {
  183. for (Iterator<Map.Entry<Key, Reference<Repository>>> i = cacheMap
  184. .entrySet().iterator(); i.hasNext();) {
  185. final Map.Entry<Key, Reference<Repository>> e = i.next();
  186. final Repository db = e.getValue().get();
  187. if (db != null)
  188. db.close();
  189. i.remove();
  190. }
  191. }
  192. }
  193. private Lock lockFor(final Key location) {
  194. return openLocks[(location.hashCode() >>> 1) % openLocks.length];
  195. }
  196. private static class Lock {
  197. // Used only for its monitor.
  198. }
  199. /**
  200. * Abstract hash key for {@link RepositoryCache} entries.
  201. * <p>
  202. * A Key instance should be lightweight, and implement hashCode() and
  203. * equals() such that two Key instances are equal if they represent the same
  204. * Repository location.
  205. */
  206. public static interface Key {
  207. /**
  208. * Called by {@link RepositoryCache#open(Key)} if it doesn't exist yet.
  209. * <p>
  210. * If a repository does not exist yet in the cache, the cache will call
  211. * this method to acquire a handle to it.
  212. *
  213. * @param mustExist
  214. * true if the repository must exist in order to be opened;
  215. * false if a new non-existent repository is permitted to be
  216. * created (the caller is responsible for calling create).
  217. * @return the new repository instance.
  218. * @throws IOException
  219. * the repository could not be read (likely its core.version
  220. * property is not supported).
  221. * @throws RepositoryNotFoundException
  222. * There is no repository at the given location, only thrown
  223. * if {@code mustExist} is true.
  224. */
  225. Repository open(boolean mustExist) throws IOException,
  226. RepositoryNotFoundException;
  227. }
  228. /** Location of a Repository, using the standard java.io.File API. */
  229. public static class FileKey implements Key {
  230. /**
  231. * Obtain a pointer to an exact location on disk.
  232. * <p>
  233. * No guessing is performed, the given location is exactly the GIT_DIR
  234. * directory of the repository.
  235. *
  236. * @param directory
  237. * location where the repository database is.
  238. * @param fs
  239. * the file system abstraction which will be necessary to
  240. * perform certain file system operations.
  241. * @return a key for the given directory.
  242. * @see #lenient(File, FS)
  243. */
  244. public static FileKey exact(final File directory, FS fs) {
  245. return new FileKey(directory, fs);
  246. }
  247. /**
  248. * Obtain a pointer to a location on disk.
  249. * <p>
  250. * The method performs some basic guessing to locate the repository.
  251. * Searched paths are:
  252. * <ol>
  253. * <li>{@code directory} // assume exact match</li>
  254. * <li>{@code directory} + "/.git" // assume working directory</li>
  255. * <li>{@code directory} + ".git" // assume bare</li>
  256. * </ol>
  257. *
  258. * @param directory
  259. * location where the repository database might be.
  260. * @param fs
  261. * the file system abstraction which will be necessary to
  262. * perform certain file system operations.
  263. * @return a key for the given directory.
  264. * @see #exact(File, FS)
  265. */
  266. public static FileKey lenient(final File directory, FS fs) {
  267. final File gitdir = resolve(directory, fs);
  268. return new FileKey(gitdir != null ? gitdir : directory, fs);
  269. }
  270. private final File path;
  271. private final FS fs;
  272. /**
  273. * @param directory
  274. * exact location of the repository.
  275. * @param fs
  276. * the file system abstraction which will be necessary to
  277. * perform certain file system operations.
  278. */
  279. protected FileKey(final File directory, FS fs) {
  280. path = canonical(directory);
  281. this.fs = fs;
  282. }
  283. private static File canonical(final File path) {
  284. try {
  285. return path.getCanonicalFile();
  286. } catch (IOException e) {
  287. return path.getAbsoluteFile();
  288. }
  289. }
  290. /** @return location supplied to the constructor. */
  291. public final File getFile() {
  292. return path;
  293. }
  294. public Repository open(final boolean mustExist) throws IOException {
  295. if (mustExist && !isGitRepository(path, fs))
  296. throw new RepositoryNotFoundException(path);
  297. return new FileRepository(path);
  298. }
  299. @Override
  300. public int hashCode() {
  301. return path.hashCode();
  302. }
  303. @Override
  304. public boolean equals(final Object o) {
  305. return o instanceof FileKey && path.equals(((FileKey) o).path);
  306. }
  307. @Override
  308. public String toString() {
  309. return path.toString();
  310. }
  311. /**
  312. * Guess if a directory contains a Git repository.
  313. * <p>
  314. * This method guesses by looking for the existence of some key files
  315. * and directories.
  316. *
  317. * @param dir
  318. * the location of the directory to examine.
  319. * @param fs
  320. * the file system abstraction which will be necessary to
  321. * perform certain file system operations.
  322. * @return true if the directory "looks like" a Git repository; false if
  323. * it doesn't look enough like a Git directory to really be a
  324. * Git directory.
  325. */
  326. public static boolean isGitRepository(final File dir, FS fs) {
  327. return fs.resolve(dir, "objects").exists()
  328. && fs.resolve(dir, "refs").exists()
  329. && isValidHead(new File(dir, Constants.HEAD));
  330. }
  331. private static boolean isValidHead(final File head) {
  332. final String ref = readFirstLine(head);
  333. return ref != null
  334. && (ref.startsWith("ref: refs/") || ObjectId.isId(ref));
  335. }
  336. private static String readFirstLine(final File head) {
  337. try {
  338. final byte[] buf = IO.readFully(head, 4096);
  339. int n = buf.length;
  340. if (n == 0)
  341. return null;
  342. if (buf[n - 1] == '\n')
  343. n--;
  344. return RawParseUtils.decode(buf, 0, n);
  345. } catch (IOException e) {
  346. return null;
  347. }
  348. }
  349. /**
  350. * Guess the proper path for a Git repository.
  351. * <p>
  352. * The method performs some basic guessing to locate the repository.
  353. * Searched paths are:
  354. * <ol>
  355. * <li>{@code directory} // assume exact match</li>
  356. * <li>{@code directory} + "/.git" // assume working directory</li>
  357. * <li>{@code directory} + ".git" // assume bare</li>
  358. * </ol>
  359. *
  360. * @param directory
  361. * location to guess from. Several permutations are tried.
  362. * @param fs
  363. * the file system abstraction which will be necessary to
  364. * perform certain file system operations.
  365. * @return the actual directory location if a better match is found;
  366. * null if there is no suitable match.
  367. */
  368. public static File resolve(final File directory, FS fs) {
  369. if (isGitRepository(directory, fs))
  370. return directory;
  371. if (isGitRepository(new File(directory, Constants.DOT_GIT), fs))
  372. return new File(directory, Constants.DOT_GIT);
  373. final String name = directory.getName();
  374. final File parent = directory.getParentFile();
  375. if (isGitRepository(new File(parent, name + Constants.DOT_GIT_EXT), fs))
  376. return new File(parent, name + Constants.DOT_GIT_EXT);
  377. return null;
  378. }
  379. }
  380. }