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 java.io.IOException;
47 import java.util.ArrayList;
48 import java.util.Collection;
49 import java.util.Collections;
50 import java.util.HashMap;
51 import java.util.List;
52 import java.util.Map;
53
54 import org.eclipse.jgit.annotations.NonNull;
55 import org.eclipse.jgit.annotations.Nullable;
56
57 /**
58 * Abstraction of name to {@link org.eclipse.jgit.lib.ObjectId} mapping.
59 * <p>
60 * A reference database stores a mapping of reference names to
61 * {@link org.eclipse.jgit.lib.ObjectId}. Every
62 * {@link org.eclipse.jgit.lib.Repository} has a single reference database,
63 * mapping names to the tips of the object graph contained by the
64 * {@link org.eclipse.jgit.lib.ObjectDatabase}.
65 */
66 public abstract class RefDatabase {
67 /**
68 * Order of prefixes to search when using non-absolute references.
69 * <p>
70 * The implementation's {@link #getRef(String)} method must take this search
71 * space into consideration when locating a reference by name. The first
72 * entry in the path is always {@code ""}, ensuring that absolute references
73 * are resolved without further mangling.
74 */
75 protected static final String[] SEARCH_PATH = { "", //$NON-NLS-1$
76 Constants.R_REFS, //
77 Constants.R_TAGS, //
78 Constants.R_HEADS, //
79 Constants.R_REMOTES //
80 };
81
82 /**
83 * Maximum number of times a {@link SymbolicRef} can be traversed.
84 * <p>
85 * If the reference is nested deeper than this depth, the implementation
86 * should either fail, or at least claim the reference does not exist.
87 *
88 * @since 4.2
89 */
90 public static final int MAX_SYMBOLIC_REF_DEPTH = 5;
91
92 /** Magic value for {@link #getRefs(String)} to return all references. */
93 public static final String ALL = "";//$NON-NLS-1$
94
95 /**
96 * Initialize a new reference database at this location.
97 *
98 * @throws java.io.IOException
99 * the database could not be created.
100 */
101 public abstract void create() throws IOException;
102
103 /**
104 * Close any resources held by this database.
105 */
106 public abstract void close();
107
108 /**
109 * Determine if a proposed reference name overlaps with an existing one.
110 * <p>
111 * Reference names use '/' as a component separator, and may be stored in a
112 * hierarchical storage such as a directory on the local filesystem.
113 * <p>
114 * If the reference "refs/heads/foo" exists then "refs/heads/foo/bar" must
115 * not exist, as a reference cannot have a value and also be a container for
116 * other references at the same time.
117 * <p>
118 * If the reference "refs/heads/foo/bar" exists than the reference
119 * "refs/heads/foo" cannot exist, for the same reason.
120 *
121 * @param name
122 * proposed name.
123 * @return true if the name overlaps with an existing reference; false if
124 * using this name right now would be safe.
125 * @throws java.io.IOException
126 * the database could not be read to check for conflicts.
127 * @see #getConflictingNames(String)
128 */
129 public abstract boolean isNameConflicting(String name) throws IOException;
130
131 /**
132 * Determine if a proposed reference cannot coexist with existing ones. If
133 * the passed name already exists, it's not considered a conflict.
134 *
135 * @param name
136 * proposed name to check for conflicts against
137 * @return a collection of full names of existing refs which would conflict
138 * with the passed ref name; empty collection when there are no
139 * conflicts
140 * @throws java.io.IOException
141 * @since 2.3
142 * @see #isNameConflicting(String)
143 */
144 @NonNull
145 public Collection<String> getConflictingNames(String name)
146 throws IOException {
147 Map<String, Ref> allRefs = getRefs(ALL);
148 // Cannot be nested within an existing reference.
149 int lastSlash = name.lastIndexOf('/');
150 while (0 < lastSlash) {
151 String needle = name.substring(0, lastSlash);
152 if (allRefs.containsKey(needle))
153 return Collections.singletonList(needle);
154 lastSlash = name.lastIndexOf('/', lastSlash - 1);
155 }
156
157 List<String> conflicting = new ArrayList<>();
158 // Cannot be the container of an existing reference.
159 String prefix = name + '/';
160 for (String existing : allRefs.keySet())
161 if (existing.startsWith(prefix))
162 conflicting.add(existing);
163
164 return conflicting;
165 }
166
167 /**
168 * Create a new update command to create, modify or delete a reference.
169 *
170 * @param name
171 * the name of the reference.
172 * @param detach
173 * if {@code true} and {@code name} is currently a
174 * {@link org.eclipse.jgit.lib.SymbolicRef}, the update will
175 * replace it with an {@link org.eclipse.jgit.lib.ObjectIdRef}.
176 * Otherwise, the update will recursively traverse
177 * {@link org.eclipse.jgit.lib.SymbolicRef}s and operate on the
178 * leaf {@link org.eclipse.jgit.lib.ObjectIdRef}.
179 * @return a new update for the requested name; never null.
180 * @throws java.io.IOException
181 * the reference space cannot be accessed.
182 */
183 @NonNull
184 public abstract RefUpdate newUpdate(String name, boolean detach)
185 throws IOException;
186
187 /**
188 * Create a new update command to rename a reference.
189 *
190 * @param fromName
191 * name of reference to rename from
192 * @param toName
193 * name of reference to rename to
194 * @return an update command that knows how to rename a branch to another.
195 * @throws java.io.IOException
196 * the reference space cannot be accessed.
197 */
198 @NonNull
199 public abstract RefRename newRename(String fromName, String toName)
200 throws IOException;
201
202 /**
203 * Create a new batch update to attempt on this database.
204 * <p>
205 * The default implementation performs a sequential update of each command.
206 *
207 * @return a new batch update object.
208 */
209 @NonNull
210 public BatchRefUpdate newBatchUpdate() {
211 return new BatchRefUpdate(this);
212 }
213
214 /**
215 * Whether the database is capable of performing batch updates as atomic
216 * transactions.
217 * <p>
218 * If true, by default {@link org.eclipse.jgit.lib.BatchRefUpdate} instances
219 * will perform updates atomically, meaning either all updates will succeed,
220 * or all updates will fail. It is still possible to turn off this behavior
221 * on a per-batch basis by calling {@code update.setAtomic(false)}.
222 * <p>
223 * If false, {@link org.eclipse.jgit.lib.BatchRefUpdate} instances will
224 * never perform updates atomically, and calling
225 * {@code update.setAtomic(true)} will cause the entire batch to fail with
226 * {@code REJECTED_OTHER_REASON}.
227 * <p>
228 * This definition of atomicity is stronger than what is provided by
229 * {@link org.eclipse.jgit.transport.ReceivePack}. {@code ReceivePack} will
230 * attempt to reject all commands if it knows in advance some commands may
231 * fail, even if the storage layer does not support atomic transactions.
232 * Here, atomicity applies even in the case of unforeseeable errors.
233 *
234 * @return whether transactions are atomic by default.
235 * @since 3.6
236 */
237 public boolean performsAtomicTransactions() {
238 return false;
239 }
240
241 /**
242 * Read a single reference.
243 * <p>
244 * Aside from taking advantage of {@link #SEARCH_PATH}, this method may be
245 * able to more quickly resolve a single reference name than obtaining the
246 * complete namespace by {@code getRefs(ALL).get(name)}.
247 * <p>
248 * To read a specific reference without using @{link #SEARCH_PATH}, see
249 * {@link #exactRef(String)}.
250 *
251 * @param name
252 * the name of the reference. May be a short name which must be
253 * searched for using the standard {@link #SEARCH_PATH}.
254 * @return the reference (if it exists); else {@code null}.
255 * @throws java.io.IOException
256 * the reference space cannot be accessed.
257 */
258 @Nullable
259 public abstract Ref getRef(String name) throws IOException;
260
261 /**
262 * Read a single reference.
263 * <p>
264 * Unlike {@link #getRef}, this method expects an unshortened reference
265 * name and does not search using the standard {@link #SEARCH_PATH}.
266 *
267 * @param name
268 * the unabbreviated name of the reference.
269 * @return the reference (if it exists); else {@code null}.
270 * @throws java.io.IOException
271 * the reference space cannot be accessed.
272 * @since 4.1
273 */
274 @Nullable
275 public Ref exactRef(String name) throws IOException {
276 Ref ref = getRef(name);
277 if (ref == null || !name.equals(ref.getName())) {
278 return null;
279 }
280 return ref;
281 }
282
283 /**
284 * Read the specified references.
285 * <p>
286 * This method expects a list of unshortened reference names and returns
287 * a map from reference names to refs. Any named references that do not
288 * exist will not be included in the returned map.
289 *
290 * @param refs
291 * the unabbreviated names of references to look up.
292 * @return modifiable map describing any refs that exist among the ref
293 * ref names supplied. The map can be an unsorted map.
294 * @throws java.io.IOException
295 * the reference space cannot be accessed.
296 * @since 4.1
297 */
298 @NonNull
299 public Map<String, Ref> exactRef(String... refs) throws IOException {
300 Map<String, Ref> result = new HashMap<>(refs.length);
301 for (String name : refs) {
302 Ref ref = exactRef(name);
303 if (ref != null) {
304 result.put(name, ref);
305 }
306 }
307 return result;
308 }
309
310 /**
311 * Find the first named reference.
312 * <p>
313 * This method expects a list of unshortened reference names and returns
314 * the first that exists.
315 *
316 * @param refs
317 * the unabbreviated names of references to look up.
318 * @return the first named reference that exists (if any); else {@code null}.
319 * @throws java.io.IOException
320 * the reference space cannot be accessed.
321 * @since 4.1
322 */
323 @Nullable
324 public Ref firstExactRef(String... refs) throws IOException {
325 for (String name : refs) {
326 Ref ref = exactRef(name);
327 if (ref != null) {
328 return ref;
329 }
330 }
331 return null;
332 }
333
334 /**
335 * Get a section of the reference namespace.
336 *
337 * @param prefix
338 * prefix to search the namespace with; must end with {@code /}.
339 * If the empty string ({@link #ALL}), obtain a complete snapshot
340 * of all references.
341 * @return modifiable map that is a complete snapshot of the current
342 * reference namespace, with {@code prefix} removed from the start
343 * of each key. The map can be an unsorted map.
344 * @throws java.io.IOException
345 * the reference space cannot be accessed.
346 */
347 @NonNull
348 public abstract Map<String, Ref> getRefs(String prefix) throws IOException;
349
350 /**
351 * Get the additional reference-like entities from the repository.
352 * <p>
353 * The result list includes non-ref items such as MERGE_HEAD and
354 * FETCH_RESULT cast to be refs. The names of these refs are not returned by
355 * <code>getRefs(ALL)</code> but are accepted by {@link #getRef(String)}
356 * and {@link #exactRef(String)}.
357 *
358 * @return a list of additional refs
359 * @throws java.io.IOException
360 * the reference space cannot be accessed.
361 */
362 @NonNull
363 public abstract List<Ref> getAdditionalRefs() throws IOException;
364
365 /**
366 * Peel a possibly unpeeled reference by traversing the annotated tags.
367 * <p>
368 * If the reference cannot be peeled (as it does not refer to an annotated
369 * tag) the peeled id stays null, but
370 * {@link org.eclipse.jgit.lib.Ref#isPeeled()} will be true.
371 * <p>
372 * Implementors should check {@link org.eclipse.jgit.lib.Ref#isPeeled()}
373 * before performing any additional work effort.
374 *
375 * @param ref
376 * The reference to peel
377 * @return {@code ref} if {@code ref.isPeeled()} is true; otherwise a new
378 * Ref object representing the same data as Ref, but isPeeled() will
379 * be true and getPeeledObjectId() will contain the peeled object
380 * (or {@code null}).
381 * @throws java.io.IOException
382 * the reference space or object space cannot be accessed.
383 */
384 @NonNull
385 public abstract Ref peel(Ref ref) throws IOException;
386
387 /**
388 * Triggers a refresh of all internal data structures.
389 * <p>
390 * In case the RefDatabase implementation has internal caches this method
391 * will trigger that all these caches are cleared.
392 * <p>
393 * Implementors should overwrite this method if they use any kind of caches.
394 */
395 public void refresh() {
396 // nothing
397 }
398
399 /**
400 * Try to find the specified name in the ref map using {@link #SEARCH_PATH}.
401 *
402 * @param map
403 * map of refs to search within. Names should be fully qualified,
404 * e.g. "refs/heads/master".
405 * @param name
406 * short name of ref to find, e.g. "master" to find
407 * "refs/heads/master" in map.
408 * @return The first ref matching the name, or {@code null} if not found.
409 * @since 3.4
410 */
411 @Nullable
412 public static Ref findRef(Map<String, Ref> map, String name) {
413 for (String prefix : SEARCH_PATH) {
414 String fullname = prefix + name;
415 Ref ref = map.get(fullname);
416 if (ref != null)
417 return ref;
418 }
419 return null;
420 }
421 }