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.

DfsRefDatabase.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. /*
  2. * Copyright (C) 2011, 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.internal.storage.dfs;
  44. import static org.eclipse.jgit.lib.Ref.UNDEFINED_UPDATE_INDEX;
  45. import static org.eclipse.jgit.lib.Ref.Storage.NEW;
  46. import java.io.IOException;
  47. import java.util.Collections;
  48. import java.util.List;
  49. import java.util.Map;
  50. import java.util.concurrent.atomic.AtomicReference;
  51. import org.eclipse.jgit.errors.MissingObjectException;
  52. import org.eclipse.jgit.lib.ObjectIdRef;
  53. import org.eclipse.jgit.lib.Ref;
  54. import org.eclipse.jgit.lib.RefDatabase;
  55. import org.eclipse.jgit.lib.RefRename;
  56. import org.eclipse.jgit.lib.RefUpdate;
  57. import org.eclipse.jgit.lib.SymbolicRef;
  58. import org.eclipse.jgit.revwalk.RevObject;
  59. import org.eclipse.jgit.revwalk.RevTag;
  60. import org.eclipse.jgit.revwalk.RevWalk;
  61. import org.eclipse.jgit.util.RefList;
  62. import org.eclipse.jgit.util.RefMap;
  63. /**
  64. * Abstract DfsRefDatabase class.
  65. *
  66. */
  67. public abstract class DfsRefDatabase extends RefDatabase {
  68. private final DfsRepository repository;
  69. private final AtomicReference<RefCache> cache;
  70. /**
  71. * Initialize the reference database for a repository.
  72. *
  73. * @param repository
  74. * the repository this database instance manages references for.
  75. */
  76. protected DfsRefDatabase(DfsRepository repository) {
  77. this.repository = repository;
  78. this.cache = new AtomicReference<>();
  79. }
  80. /**
  81. * Get the repository the database holds the references of.
  82. *
  83. * @return the repository the database holds the references of.
  84. */
  85. protected DfsRepository getRepository() {
  86. return repository;
  87. }
  88. boolean exists() throws IOException {
  89. return 0 < read().size();
  90. }
  91. /** {@inheritDoc} */
  92. @Override
  93. public Ref exactRef(String name) throws IOException {
  94. RefCache curr = read();
  95. Ref ref = curr.ids.get(name);
  96. return ref != null ? resolve(ref, 0, curr.ids) : null;
  97. }
  98. /** {@inheritDoc} */
  99. @Override
  100. public List<Ref> getAdditionalRefs() {
  101. return Collections.emptyList();
  102. }
  103. /** {@inheritDoc} */
  104. @Override
  105. public Map<String, Ref> getRefs(String prefix) throws IOException {
  106. RefCache curr = read();
  107. RefList<Ref> packed = RefList.emptyList();
  108. RefList<Ref> loose = curr.ids;
  109. RefList.Builder<Ref> sym = new RefList.Builder<>(curr.sym.size());
  110. for (int idx = 0; idx < curr.sym.size(); idx++) {
  111. Ref ref = curr.sym.get(idx);
  112. String name = ref.getName();
  113. ref = resolve(ref, 0, loose);
  114. if (ref != null && ref.getObjectId() != null) {
  115. sym.add(ref);
  116. } else {
  117. // A broken symbolic reference, we have to drop it from the
  118. // collections the client is about to receive. Should be a
  119. // rare occurrence so pay a copy penalty.
  120. int toRemove = loose.find(name);
  121. if (0 <= toRemove)
  122. loose = loose.remove(toRemove);
  123. }
  124. }
  125. return new RefMap(prefix, packed, loose, sym.toRefList());
  126. }
  127. private Ref resolve(Ref ref, int depth, RefList<Ref> loose)
  128. throws IOException {
  129. if (!ref.isSymbolic())
  130. return ref;
  131. Ref dst = ref.getTarget();
  132. if (MAX_SYMBOLIC_REF_DEPTH <= depth)
  133. return null; // claim it doesn't exist
  134. dst = loose.get(dst.getName());
  135. if (dst == null)
  136. return ref;
  137. dst = resolve(dst, depth + 1, loose);
  138. if (dst == null)
  139. return null;
  140. return new SymbolicRef(ref.getName(), dst);
  141. }
  142. /** {@inheritDoc} */
  143. @Override
  144. public Ref peel(Ref ref) throws IOException {
  145. final Ref oldLeaf = ref.getLeaf();
  146. if (oldLeaf.isPeeled() || oldLeaf.getObjectId() == null)
  147. return ref;
  148. Ref newLeaf = doPeel(oldLeaf);
  149. RefCache cur = read();
  150. int idx = cur.ids.find(oldLeaf.getName());
  151. if (0 <= idx && cur.ids.get(idx) == oldLeaf) {
  152. RefList<Ref> newList = cur.ids.set(idx, newLeaf);
  153. cache.compareAndSet(cur, new RefCache(newList, cur));
  154. cachePeeledState(oldLeaf, newLeaf);
  155. }
  156. return recreate(ref, newLeaf, hasVersioning());
  157. }
  158. Ref doPeel(Ref leaf) throws MissingObjectException,
  159. IOException {
  160. try (RevWalk rw = new RevWalk(repository)) {
  161. RevObject obj = rw.parseAny(leaf.getObjectId());
  162. if (obj instanceof RevTag) {
  163. return new ObjectIdRef.PeeledTag(
  164. leaf.getStorage(),
  165. leaf.getName(),
  166. leaf.getObjectId(),
  167. rw.peel(obj).copy(),
  168. hasVersioning() ? leaf.getUpdateIndex()
  169. : UNDEFINED_UPDATE_INDEX);
  170. }
  171. return new ObjectIdRef.PeeledNonTag(leaf.getStorage(),
  172. leaf.getName(), leaf.getObjectId(),
  173. hasVersioning() ? leaf.getUpdateIndex()
  174. : UNDEFINED_UPDATE_INDEX);
  175. }
  176. }
  177. static Ref recreate(Ref old, Ref leaf, boolean hasVersioning) {
  178. if (old.isSymbolic()) {
  179. Ref dst = recreate(old.getTarget(), leaf, hasVersioning);
  180. return new SymbolicRef(old.getName(), dst,
  181. hasVersioning ? old.getUpdateIndex()
  182. : UNDEFINED_UPDATE_INDEX);
  183. }
  184. return leaf;
  185. }
  186. /** {@inheritDoc} */
  187. @Override
  188. public RefUpdate newUpdate(String refName, boolean detach)
  189. throws IOException {
  190. boolean detachingSymbolicRef = false;
  191. Ref ref = exactRef(refName);
  192. if (ref == null)
  193. ref = new ObjectIdRef.Unpeeled(NEW, refName, null);
  194. else
  195. detachingSymbolicRef = detach && ref.isSymbolic();
  196. DfsRefUpdate update = new DfsRefUpdate(this, ref);
  197. if (detachingSymbolicRef)
  198. update.setDetachingSymbolicRef();
  199. return update;
  200. }
  201. /** {@inheritDoc} */
  202. @Override
  203. public RefRename newRename(String fromName, String toName)
  204. throws IOException {
  205. RefUpdate src = newUpdate(fromName, true);
  206. RefUpdate dst = newUpdate(toName, true);
  207. return new DfsRefRename(src, dst);
  208. }
  209. /** {@inheritDoc} */
  210. @Override
  211. public boolean isNameConflicting(String refName) throws IOException {
  212. RefList<Ref> all = read().ids;
  213. // Cannot be nested within an existing reference.
  214. int lastSlash = refName.lastIndexOf('/');
  215. while (0 < lastSlash) {
  216. String needle = refName.substring(0, lastSlash);
  217. if (all.contains(needle))
  218. return true;
  219. lastSlash = refName.lastIndexOf('/', lastSlash - 1);
  220. }
  221. // Cannot be the container of an existing reference.
  222. String prefix = refName + '/';
  223. int idx = -(all.find(prefix) + 1);
  224. if (idx < all.size() && all.get(idx).getName().startsWith(prefix))
  225. return true;
  226. return false;
  227. }
  228. /** {@inheritDoc} */
  229. @Override
  230. public void create() {
  231. // Nothing to do.
  232. }
  233. /** {@inheritDoc} */
  234. @Override
  235. public void refresh() {
  236. clearCache();
  237. }
  238. /** {@inheritDoc} */
  239. @Override
  240. public void close() {
  241. clearCache();
  242. }
  243. void clearCache() {
  244. cache.set(null);
  245. }
  246. void stored(Ref ref) {
  247. RefCache oldCache, newCache;
  248. do {
  249. oldCache = cache.get();
  250. if (oldCache == null)
  251. return;
  252. newCache = oldCache.put(ref);
  253. } while (!cache.compareAndSet(oldCache, newCache));
  254. }
  255. void removed(String refName) {
  256. RefCache oldCache, newCache;
  257. do {
  258. oldCache = cache.get();
  259. if (oldCache == null)
  260. return;
  261. newCache = oldCache.remove(refName);
  262. } while (!cache.compareAndSet(oldCache, newCache));
  263. }
  264. private RefCache read() throws IOException {
  265. RefCache c = cache.get();
  266. if (c == null) {
  267. c = scanAllRefs();
  268. cache.set(c);
  269. }
  270. return c;
  271. }
  272. /**
  273. * Read all known references in the repository.
  274. *
  275. * @return all current references of the repository.
  276. * @throws java.io.IOException
  277. * references cannot be accessed.
  278. */
  279. protected abstract RefCache scanAllRefs() throws IOException;
  280. /**
  281. * Compare a reference, and put if it matches.
  282. * <p>
  283. * Two reference match if and only if they satisfy the following:
  284. *
  285. * <ul>
  286. * <li>If one reference is a symbolic ref, the other one should be a symbolic
  287. * ref.
  288. * <li>If both are symbolic refs, the target names should be same.
  289. * <li>If both are object ID refs, the object IDs should be same.
  290. * </ul>
  291. *
  292. * @param oldRef
  293. * old value to compare to. If the reference is expected to not
  294. * exist the old value has a storage of
  295. * {@link org.eclipse.jgit.lib.Ref.Storage#NEW} and an ObjectId
  296. * value of {@code null}.
  297. * @param newRef
  298. * new reference to store.
  299. * @return true if the put was successful; false otherwise.
  300. * @throws java.io.IOException
  301. * the reference cannot be put due to a system error.
  302. */
  303. protected abstract boolean compareAndPut(Ref oldRef, Ref newRef)
  304. throws IOException;
  305. /**
  306. * Compare a reference, and delete if it matches.
  307. *
  308. * @param oldRef
  309. * the old reference information that was previously read.
  310. * @return true if the remove was successful; false otherwise.
  311. * @throws java.io.IOException
  312. * the reference could not be removed due to a system error.
  313. */
  314. protected abstract boolean compareAndRemove(Ref oldRef) throws IOException;
  315. /**
  316. * Update the cached peeled state of a reference
  317. * <p>
  318. * The ref database invokes this method after it peels a reference that had
  319. * not been peeled before. This allows the storage to cache the peel state
  320. * of the reference, and if it is actually peelable, the target that it
  321. * peels to, so that on-the-fly peeling doesn't have to happen on the next
  322. * reference read.
  323. *
  324. * @param oldLeaf
  325. * the old reference.
  326. * @param newLeaf
  327. * the new reference, with peel information.
  328. */
  329. protected void cachePeeledState(Ref oldLeaf, Ref newLeaf) {
  330. try {
  331. compareAndPut(oldLeaf, newLeaf);
  332. } catch (IOException e) {
  333. // Ignore an exception during caching.
  334. }
  335. }
  336. /** Collection of references managed by this database. */
  337. public static class RefCache {
  338. final RefList<Ref> ids;
  339. final RefList<Ref> sym;
  340. /**
  341. * Initialize a new reference cache.
  342. * <p>
  343. * The two reference lists supplied must be sorted in correct order
  344. * (string compare order) by name.
  345. *
  346. * @param ids
  347. * references that carry an ObjectId, and all of {@code sym}.
  348. * @param sym
  349. * references that are symbolic references to others.
  350. */
  351. public RefCache(RefList<Ref> ids, RefList<Ref> sym) {
  352. this.ids = ids;
  353. this.sym = sym;
  354. }
  355. RefCache(RefList<Ref> ids, RefCache old) {
  356. this(ids, old.sym);
  357. }
  358. /** @return number of references in this cache. */
  359. public int size() {
  360. return ids.size();
  361. }
  362. /**
  363. * Find a reference by name.
  364. *
  365. * @param name
  366. * full name of the reference.
  367. * @return the reference, if it exists, otherwise null.
  368. */
  369. public Ref get(String name) {
  370. return ids.get(name);
  371. }
  372. /**
  373. * Obtain a modified copy of the cache with a ref stored.
  374. * <p>
  375. * This cache instance is not modified by this method.
  376. *
  377. * @param ref
  378. * reference to add or replace.
  379. * @return a copy of this cache, with the reference added or replaced.
  380. */
  381. public RefCache put(Ref ref) {
  382. RefList<Ref> newIds = this.ids.put(ref);
  383. RefList<Ref> newSym = this.sym;
  384. if (ref.isSymbolic()) {
  385. newSym = newSym.put(ref);
  386. } else {
  387. int p = newSym.find(ref.getName());
  388. if (0 <= p)
  389. newSym = newSym.remove(p);
  390. }
  391. return new RefCache(newIds, newSym);
  392. }
  393. /**
  394. * Obtain a modified copy of the cache with the ref removed.
  395. * <p>
  396. * This cache instance is not modified by this method.
  397. *
  398. * @param refName
  399. * reference to remove, if it exists.
  400. * @return a copy of this cache, with the reference removed.
  401. */
  402. public RefCache remove(String refName) {
  403. RefList<Ref> newIds = this.ids;
  404. int p = newIds.find(refName);
  405. if (0 <= p)
  406. newIds = newIds.remove(p);
  407. RefList<Ref> newSym = this.sym;
  408. p = newSym.find(refName);
  409. if (0 <= p)
  410. newSym = newSym.remove(p);
  411. return new RefCache(newIds, newSym);
  412. }
  413. }
  414. }