View Javadoc
1   /*
2    * Copyright (C) 2010, 2013 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.lib;
45  
46  import static java.util.stream.Collectors.toList;
47  import static java.util.stream.Collectors.toSet;
48  
49  import java.io.IOException;
50  import java.util.ArrayList;
51  import java.util.Collection;
52  import java.util.Collections;
53  import java.util.HashMap;
54  import java.util.List;
55  import java.util.Map;
56  import java.util.Set;
57  import org.eclipse.jgit.annotations.NonNull;
58  import org.eclipse.jgit.annotations.Nullable;
59  
60  /**
61   * Abstraction of name to {@link org.eclipse.jgit.lib.ObjectId} mapping.
62   * <p>
63   * A reference database stores a mapping of reference names to
64   * {@link org.eclipse.jgit.lib.ObjectId}. Every
65   * {@link org.eclipse.jgit.lib.Repository} has a single reference database,
66   * mapping names to the tips of the object graph contained by the
67   * {@link org.eclipse.jgit.lib.ObjectDatabase}.
68   */
69  public abstract class RefDatabase {
70  	/**
71  	 * Order of prefixes to search when using non-absolute references.
72  	 * <p>
73  	 * {@link #findRef(String)} takes this search space into consideration
74  	 * when locating a reference by name. The first entry in the path is
75  	 * always {@code ""}, ensuring that absolute references are resolved
76  	 * without further mangling.
77  	 */
78  	protected static final String[] SEARCH_PATH = { "", //$NON-NLS-1$
79  			Constants.R_REFS, //
80  			Constants.R_TAGS, //
81  			Constants.R_HEADS, //
82  			Constants.R_REMOTES //
83  	};
84  
85  	/**
86  	 * Maximum number of times a {@link SymbolicRef} can be traversed.
87  	 * <p>
88  	 * If the reference is nested deeper than this depth, the implementation
89  	 * should either fail, or at least claim the reference does not exist.
90  	 *
91  	 * @since 4.2
92  	 */
93  	public static final int MAX_SYMBOLIC_REF_DEPTH = 5;
94  
95  	/**
96  	 * Magic value for {@link #getRefsByPrefix(String)} to return all
97  	 * references.
98  	 */
99  	public static final String ALL = "";//$NON-NLS-1$
100 
101 	/**
102 	 * Initialize a new reference database at this location.
103 	 *
104 	 * @throws java.io.IOException
105 	 *             the database could not be created.
106 	 */
107 	public abstract void create() throws IOException;
108 
109 	/**
110 	 * Close any resources held by this database.
111 	 */
112 	public abstract void close();
113 
114 	/**
115 	 * With versioning, each reference has a version number that increases on
116 	 * update. See {@link Ref#getUpdateIndex()}.
117 	 *
118 	 * @implSpec This method returns false by default. Implementations
119 	 *           supporting versioning must override it to return true.
120 	 * @return true if the implementation assigns update indices to references.
121 	 * @since 5.3
122 	 */
123 	public boolean hasVersioning() {
124 		return false;
125 	}
126 
127 	/**
128 	 * Determine if a proposed reference name overlaps with an existing one.
129 	 * <p>
130 	 * Reference names use '/' as a component separator, and may be stored in a
131 	 * hierarchical storage such as a directory on the local filesystem.
132 	 * <p>
133 	 * If the reference "refs/heads/foo" exists then "refs/heads/foo/bar" must
134 	 * not exist, as a reference cannot have a value and also be a container for
135 	 * other references at the same time.
136 	 * <p>
137 	 * If the reference "refs/heads/foo/bar" exists than the reference
138 	 * "refs/heads/foo" cannot exist, for the same reason.
139 	 *
140 	 * @param name
141 	 *            proposed name.
142 	 * @return true if the name overlaps with an existing reference; false if
143 	 *         using this name right now would be safe.
144 	 * @throws java.io.IOException
145 	 *             the database could not be read to check for conflicts.
146 	 * @see #getConflictingNames(String)
147 	 */
148 	public abstract boolean isNameConflicting(String name) throws IOException;
149 
150 	/**
151 	 * Determine if a proposed reference cannot coexist with existing ones. If
152 	 * the passed name already exists, it's not considered a conflict.
153 	 *
154 	 * @param name
155 	 *            proposed name to check for conflicts against
156 	 * @return a collection of full names of existing refs which would conflict
157 	 *         with the passed ref name; empty collection when there are no
158 	 *         conflicts
159 	 * @throws java.io.IOException
160 	 * @since 2.3
161 	 * @see #isNameConflicting(String)
162 	 */
163 	@NonNull
164 	public Collection<String> getConflictingNames(String name)
165 			throws IOException {
166 		Map<String, Ref> allRefs = getRefs(ALL);
167 		// Cannot be nested within an existing reference.
168 		int lastSlash = name.lastIndexOf('/');
169 		while (0 < lastSlash) {
170 			String needle = name.substring(0, lastSlash);
171 			if (allRefs.containsKey(needle))
172 				return Collections.singletonList(needle);
173 			lastSlash = name.lastIndexOf('/', lastSlash - 1);
174 		}
175 
176 		List<String> conflicting = new ArrayList<>();
177 		// Cannot be the container of an existing reference.
178 		String prefix = name + '/';
179 		for (String existing : allRefs.keySet())
180 			if (existing.startsWith(prefix))
181 				conflicting.add(existing);
182 
183 		return conflicting;
184 	}
185 
186 	/**
187 	 * Create a new update command to create, modify or delete a reference.
188 	 *
189 	 * @param name
190 	 *            the name of the reference.
191 	 * @param detach
192 	 *            if {@code true} and {@code name} is currently a
193 	 *            {@link org.eclipse.jgit.lib.SymbolicRef}, the update will
194 	 *            replace it with an {@link org.eclipse.jgit.lib.ObjectIdRef}.
195 	 *            Otherwise, the update will recursively traverse
196 	 *            {@link org.eclipse.jgit.lib.SymbolicRef}s and operate on the
197 	 *            leaf {@link org.eclipse.jgit.lib.ObjectIdRef}.
198 	 * @return a new update for the requested name; never null.
199 	 * @throws java.io.IOException
200 	 *             the reference space cannot be accessed.
201 	 */
202 	@NonNull
203 	public abstract RefUpdate newUpdate(String name, boolean detach)
204 			throws IOException;
205 
206 	/**
207 	 * Create a new update command to rename a reference.
208 	 *
209 	 * @param fromName
210 	 *            name of reference to rename from
211 	 * @param toName
212 	 *            name of reference to rename to
213 	 * @return an update command that knows how to rename a branch to another.
214 	 * @throws java.io.IOException
215 	 *             the reference space cannot be accessed.
216 	 */
217 	@NonNull
218 	public abstract RefRename newRename(String fromName, String toName)
219 			throws IOException;
220 
221 	/**
222 	 * Create a new batch update to attempt on this database.
223 	 * <p>
224 	 * The default implementation performs a sequential update of each command.
225 	 *
226 	 * @return a new batch update object.
227 	 */
228 	@NonNull
229 	public BatchRefUpdate newBatchUpdate() {
230 		return new BatchRefUpdate(this);
231 	}
232 
233 	/**
234 	 * Whether the database is capable of performing batch updates as atomic
235 	 * transactions.
236 	 * <p>
237 	 * If true, by default {@link org.eclipse.jgit.lib.BatchRefUpdate} instances
238 	 * will perform updates atomically, meaning either all updates will succeed,
239 	 * or all updates will fail. It is still possible to turn off this behavior
240 	 * on a per-batch basis by calling {@code update.setAtomic(false)}.
241 	 * <p>
242 	 * If false, {@link org.eclipse.jgit.lib.BatchRefUpdate} instances will
243 	 * never perform updates atomically, and calling
244 	 * {@code update.setAtomic(true)} will cause the entire batch to fail with
245 	 * {@code REJECTED_OTHER_REASON}.
246 	 * <p>
247 	 * This definition of atomicity is stronger than what is provided by
248 	 * {@link org.eclipse.jgit.transport.ReceivePack}. {@code ReceivePack} will
249 	 * attempt to reject all commands if it knows in advance some commands may
250 	 * fail, even if the storage layer does not support atomic transactions.
251 	 * Here, atomicity applies even in the case of unforeseeable errors.
252 	 *
253 	 * @return whether transactions are atomic by default.
254 	 * @since 3.6
255 	 */
256 	public boolean performsAtomicTransactions() {
257 		return false;
258 	}
259 
260 	/**
261 	 * Compatibility synonym for {@link #findRef(String)}.
262 	 *
263 	 * @param name
264 	 *            the name of the reference. May be a short name which must be
265 	 *            searched for using the standard {@link #SEARCH_PATH}.
266 	 * @return the reference (if it exists); else {@code null}.
267 	 * @throws IOException
268 	 *             the reference space cannot be accessed.
269 	 * @deprecated Use {@link #findRef(String)} instead.
270 	 */
271 	@Deprecated
272 	@Nullable
273 	public final Ref getRef(String name) throws IOException {
274 		return findRef(name);
275 	}
276 
277 	/**
278 	 * Read a single reference.
279 	 * <p>
280 	 * Aside from taking advantage of {@link #SEARCH_PATH}, this method may be
281 	 * able to more quickly resolve a single reference name than obtaining the
282 	 * complete namespace by {@code getRefs(ALL).get(name)}.
283 	 * <p>
284 	 * To read a specific reference without using @{link #SEARCH_PATH}, see
285 	 * {@link #exactRef(String)}.
286 	 *
287 	 * @param name
288 	 *            the name of the reference. May be a short name which must be
289 	 *            searched for using the standard {@link #SEARCH_PATH}.
290 	 * @return the reference (if it exists); else {@code null}.
291 	 * @throws java.io.IOException
292 	 *             the reference space cannot be accessed.
293 	 * @since 5.3
294 	 */
295 	@Nullable
296 	public final Ref findRef(String name) throws IOException {
297 		String[] names = new String[SEARCH_PATH.length];
298 		for (int i = 0; i < SEARCH_PATH.length; i++) {
299 			names[i] = SEARCH_PATH[i] + name;
300 		}
301 		return firstExactRef(names);
302 	}
303 
304 	/**
305 	 * Read a single reference.
306 	 * <p>
307 	 * Unlike {@link #findRef}, this method expects an unshortened reference
308 	 * name and does not search using the standard {@link #SEARCH_PATH}.
309 	 *
310 	 * @param name
311 	 *             the unabbreviated name of the reference.
312 	 * @return the reference (if it exists); else {@code null}.
313 	 * @throws java.io.IOException
314 	 *             the reference space cannot be accessed.
315 	 * @since 4.1
316 	 */
317 	@Nullable
318 	public abstract Ref exactRef(String name) throws IOException;
319 
320 	/**
321 	 * Read the specified references.
322 	 * <p>
323 	 * This method expects a list of unshortened reference names and returns
324 	 * a map from reference names to refs.  Any named references that do not
325 	 * exist will not be included in the returned map.
326 	 *
327 	 * @param refs
328 	 *             the unabbreviated names of references to look up.
329 	 * @return modifiable map describing any refs that exist among the ref
330 	 *         ref names supplied. The map can be an unsorted map.
331 	 * @throws java.io.IOException
332 	 *             the reference space cannot be accessed.
333 	 * @since 4.1
334 	 */
335 	@NonNull
336 	public Map<String, Ref> exactRef(String... refs) throws IOException {
337 		Map<String, Ref> result = new HashMap<>(refs.length);
338 		for (String name : refs) {
339 			Ref ref = exactRef(name);
340 			if (ref != null) {
341 				result.put(name, ref);
342 			}
343 		}
344 		return result;
345 	}
346 
347 	/**
348 	 * Find the first named reference.
349 	 * <p>
350 	 * This method expects a list of unshortened reference names and returns
351 	 * the first that exists.
352 	 *
353 	 * @param refs
354 	 *             the unabbreviated names of references to look up.
355 	 * @return the first named reference that exists (if any); else {@code null}.
356 	 * @throws java.io.IOException
357 	 *             the reference space cannot be accessed.
358 	 * @since 4.1
359 	 */
360 	@Nullable
361 	public Ref firstExactRef(String... refs) throws IOException {
362 		for (String name : refs) {
363 			Ref ref = exactRef(name);
364 			if (ref != null) {
365 				return ref;
366 			}
367 		}
368 		return null;
369 	}
370 
371 	/**
372 	 * Returns all refs.
373 	 * <p>
374 	 * This includes {@code HEAD}, branches under {@code ref/heads/}, tags
375 	 * under {@code refs/tags/}, etc. It does not include pseudo-refs like
376 	 * {@code FETCH_HEAD}; for those, see {@link #getAdditionalRefs}.
377 	 * <p>
378 	 * Symbolic references to a non-existent ref (for example,
379 	 * {@code HEAD} pointing to a branch yet to be born) are not included.
380 	 * <p>
381 	 * Callers interested in only a portion of the ref hierarchy can call
382 	 * {@link #getRefsByPrefix} instead.
383 	 *
384 	 * @return immutable list of all refs.
385 	 * @throws java.io.IOException
386 	 *             the reference space cannot be accessed.
387 	 * @since 5.0
388 	 */
389 	@NonNull
390 	public List<Ref> getRefs() throws IOException {
391 		return getRefsByPrefix(ALL);
392 	}
393 
394 	/**
395 	 * Get a section of the reference namespace.
396 	 *
397 	 * @param prefix
398 	 *            prefix to search the namespace with; must end with {@code /}.
399 	 *            If the empty string ({@link #ALL}), obtain a complete snapshot
400 	 *            of all references.
401 	 * @return modifiable map that is a complete snapshot of the current
402 	 *         reference namespace, with {@code prefix} removed from the start
403 	 *         of each key. The map can be an unsorted map.
404 	 * @throws java.io.IOException
405 	 *             the reference space cannot be accessed.
406 	 * @deprecated use {@link #getRefsByPrefix} instead
407 	 */
408 	@NonNull
409 	@Deprecated
410 	public abstract Map<String, Ref> getRefs(String prefix) throws IOException;
411 
412 	/**
413 	 * Returns refs whose names start with a given prefix.
414 	 * <p>
415 	 * The default implementation uses {@link #getRefs(String)}. Implementors of
416 	 * {@link RefDatabase} should override this method directly if a better
417 	 * implementation is possible.
418 	 *
419 	 * @param prefix string that names of refs should start with; may be
420 	 *             empty (to return all refs).
421 	 * @return immutable list of refs whose names start with {@code prefix}.
422 	 * @throws java.io.IOException
423 	 *             the reference space cannot be accessed.
424 	 * @since 5.0
425 	 */
426 	@NonNull
427 	public List<Ref> getRefsByPrefix(String prefix) throws IOException {
428 		Map<String, Ref> coarseRefs;
429 		int lastSlash = prefix.lastIndexOf('/');
430 		if (lastSlash == -1) {
431 			coarseRefs = getRefs(ALL);
432 		} else {
433 			coarseRefs = getRefs(prefix.substring(0, lastSlash + 1));
434 		}
435 
436 		List<Ref> result;
437 		if (lastSlash + 1 == prefix.length()) {
438 			result = coarseRefs.values().stream().collect(toList());
439 		} else {
440 			String p = prefix.substring(lastSlash + 1);
441 			result = coarseRefs.entrySet().stream()
442 					.filter(e -> e.getKey().startsWith(p))
443 					.map(e -> e.getValue())
444 					.collect(toList());
445 		}
446 		return Collections.unmodifiableList(result);
447 	}
448 
449 	/**
450 	 * Returns refs whose names start with one of the given prefixes.
451 	 * <p>
452 	 * The default implementation uses {@link #getRefsByPrefix(String)}.
453 	 * Implementors of {@link RefDatabase} should override this method directly
454 	 * if a better implementation is possible.
455 	 *
456 	 * @param prefixes
457 	 *            strings that names of refs should start with.
458 	 * @return immutable list of refs whose names start with one of
459 	 *         {@code prefixes}. Refs can be unsorted and may contain duplicates
460 	 *         if the prefixes overlap.
461 	 * @throws java.io.IOException
462 	 *             the reference space cannot be accessed.
463 	 * @since 5.2
464 	 */
465 	@NonNull
466 	public List<Ref> getRefsByPrefix(String... prefixes) throws IOException {
467 		List<Ref> result = new ArrayList<>();
468 		for (String prefix : prefixes) {
469 			result.addAll(getRefsByPrefix(prefix));
470 		}
471 		return Collections.unmodifiableList(result);
472 	}
473 
474 
475 	/**
476 	 * Returns all refs that resolve directly to the given {@link ObjectId}.
477 	 * Includes peeled {@linkObjectId}s. This is the inverse lookup of
478 	 * {@link #exactRef(String...)}.
479 	 *
480 	 * <p>
481 	 * The default implementation uses a linear scan. Implementors of
482 	 * {@link RefDatabase} should override this method directly if a better
483 	 * implementation is possible.
484 	 *
485 	 * @param id
486 	 *            {@link ObjectId} to resolve
487 	 * @return a {@link Set} of {@link Ref}s whose tips point to the provided
488 	 *         id.
489 	 * @throws java.io.IOException
490 	 *             the reference space cannot be accessed.
491 	 * @since 5.4
492 	 */
493 	@NonNull
494 	public Set<Ref> getTipsWithSha1(ObjectId id) throws IOException {
495 		return getRefs().stream().filter(r -> id.equals(r.getObjectId())
496 				|| id.equals(r.getPeeledObjectId())).collect(toSet());
497 	}
498 
499 	/**
500 	 * Check if any refs exist in the ref database.
501 	 * <p>
502 	 * This uses the same definition of refs as {@link #getRefs()}. In
503 	 * particular, returns {@code false} in a new repository with no refs
504 	 * under {@code refs/} and {@code HEAD} pointing to a branch yet to be
505 	 * born, and returns {@code true} in a repository with no refs under
506 	 * {@code refs/} and a detached {@code HEAD} pointing to history.
507 	 *
508 	 * @return true if the database has refs.
509 	 * @throws java.io.IOException
510 	 *             the reference space cannot be accessed.
511 	 * @since 5.0
512 	 */
513 	public boolean hasRefs() throws IOException {
514 		return !getRefs().isEmpty();
515 	}
516 
517 	/**
518 	 * Get the additional reference-like entities from the repository.
519 	 * <p>
520 	 * The result list includes non-ref items such as MERGE_HEAD and
521 	 * FETCH_RESULT cast to be refs. The names of these refs are not returned by
522 	 * <code>getRefs()</code> but are accepted by {@link #findRef(String)}
523 	 * and {@link #exactRef(String)}.
524 	 *
525 	 * @return a list of additional refs
526 	 * @throws java.io.IOException
527 	 *             the reference space cannot be accessed.
528 	 */
529 	@NonNull
530 	public abstract List<Ref> getAdditionalRefs() throws IOException;
531 
532 	/**
533 	 * Peel a possibly unpeeled reference by traversing the annotated tags.
534 	 * <p>
535 	 * If the reference cannot be peeled (as it does not refer to an annotated
536 	 * tag) the peeled id stays null, but
537 	 * {@link org.eclipse.jgit.lib.Ref#isPeeled()} will be true.
538 	 * <p>
539 	 * Implementors should check {@link org.eclipse.jgit.lib.Ref#isPeeled()}
540 	 * before performing any additional work effort.
541 	 *
542 	 * @param ref
543 	 *            The reference to peel
544 	 * @return {@code ref} if {@code ref.isPeeled()} is true; otherwise a new
545 	 *         Ref object representing the same data as Ref, but isPeeled() will
546 	 *         be true and getPeeledObjectId() will contain the peeled object
547 	 *         (or {@code null}).
548 	 * @throws java.io.IOException
549 	 *             the reference space or object space cannot be accessed.
550 	 */
551 	@NonNull
552 	public abstract Ref" href="../../../../org/eclipse/jgit/lib/Ref.html#Ref">Ref peel(Ref ref) throws IOException;
553 
554 	/**
555 	 * Triggers a refresh of all internal data structures.
556 	 * <p>
557 	 * In case the RefDatabase implementation has internal caches this method
558 	 * will trigger that all these caches are cleared.
559 	 * <p>
560 	 * Implementors should overwrite this method if they use any kind of caches.
561 	 */
562 	public void refresh() {
563 		// nothing
564 	}
565 
566 	/**
567 	 * Try to find the specified name in the ref map using {@link #SEARCH_PATH}.
568 	 *
569 	 * @param map
570 	 *            map of refs to search within. Names should be fully qualified,
571 	 *            e.g. "refs/heads/master".
572 	 * @param name
573 	 *            short name of ref to find, e.g. "master" to find
574 	 *            "refs/heads/master" in map.
575 	 * @return The first ref matching the name, or {@code null} if not found.
576 	 * @since 3.4
577 	 */
578 	@Nullable
579 	public static Ref findRef(Map<String, Ref> map, String name) {
580 		for (String prefix : SEARCH_PATH) {
581 			String fullname = prefix + name;
582 			Ref ref = map.get(fullname);
583 			if (ref != null)
584 				return ref;
585 		}
586 		return null;
587 	}
588 }