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