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.List;
51 import java.util.Map;
52
53 /**
54 * Abstraction of name to {@link ObjectId} mapping.
55 * <p>
56 * A reference database stores a mapping of reference names to {@link ObjectId}.
57 * Every {@link Repository} has a single reference database, mapping names to
58 * the tips of the object graph contained by the {@link ObjectDatabase}.
59 */
60 public abstract class RefDatabase {
61 /**
62 * Order of prefixes to search when using non-absolute references.
63 * <p>
64 * The implementation's {@link #getRef(String)} method must take this search
65 * space into consideration when locating a reference by name. The first
66 * entry in the path is always {@code ""}, ensuring that absolute references
67 * are resolved without further mangling.
68 */
69 protected static final String[] SEARCH_PATH = { "", //$NON-NLS-1$
70 Constants.R_REFS, //
71 Constants.R_TAGS, //
72 Constants.R_HEADS, //
73 Constants.R_REMOTES //
74 };
75
76 /**
77 * Maximum number of times a {@link SymbolicRef} can be traversed.
78 * <p>
79 * If the reference is nested deeper than this depth, the implementation
80 * should either fail, or at least claim the reference does not exist.
81 */
82 protected static final int MAX_SYMBOLIC_REF_DEPTH = 5;
83
84 /** Magic value for {@link #getRefs(String)} to return all references. */
85 public static final String ALL = "";//$NON-NLS-1$
86
87 /**
88 * Initialize a new reference database at this location.
89 *
90 * @throws IOException
91 * the database could not be created.
92 */
93 public abstract void create() throws IOException;
94
95 /** Close any resources held by this database. */
96 public abstract void close();
97
98 /**
99 * Determine if a proposed reference name overlaps with an existing one.
100 * <p>
101 * Reference names use '/' as a component separator, and may be stored in a
102 * hierarchical storage such as a directory on the local filesystem.
103 * <p>
104 * If the reference "refs/heads/foo" exists then "refs/heads/foo/bar" must
105 * not exist, as a reference cannot have a value and also be a container for
106 * other references at the same time.
107 * <p>
108 * If the reference "refs/heads/foo/bar" exists than the reference
109 * "refs/heads/foo" cannot exist, for the same reason.
110 *
111 * @param name
112 * proposed name.
113 * @return true if the name overlaps with an existing reference; false if
114 * using this name right now would be safe.
115 * @throws IOException
116 * the database could not be read to check for conflicts.
117 * @see #getConflictingNames(String)
118 */
119 public abstract boolean isNameConflicting(String name) throws IOException;
120
121 /**
122 * Determine if a proposed reference cannot coexist with existing ones. If
123 * the passed name already exists, it's not considered a conflict.
124 *
125 * @param name
126 * proposed name to check for conflicts against
127 * @return a collection of full names of existing refs which would conflict
128 * with the passed ref name; empty collection when there are no
129 * conflicts
130 * @throws IOException
131 * @since 2.3
132 * @see #isNameConflicting(String)
133 */
134 public Collection<String> getConflictingNames(String name)
135 throws IOException {
136 Map<String, Ref> allRefs = getRefs(ALL);
137 // Cannot be nested within an existing reference.
138 int lastSlash = name.lastIndexOf('/');
139 while (0 < lastSlash) {
140 String needle = name.substring(0, lastSlash);
141 if (allRefs.containsKey(needle))
142 return Collections.singletonList(needle);
143 lastSlash = name.lastIndexOf('/', lastSlash - 1);
144 }
145
146 List<String> conflicting = new ArrayList<String>();
147 // Cannot be the container of an existing reference.
148 String prefix = name + '/';
149 for (String existing : allRefs.keySet())
150 if (existing.startsWith(prefix))
151 conflicting.add(existing);
152
153 return conflicting;
154 }
155
156 /**
157 * Create a new update command to create, modify or delete a reference.
158 *
159 * @param name
160 * the name of the reference.
161 * @param detach
162 * if {@code true} and {@code name} is currently a
163 * {@link SymbolicRef}, the update will replace it with an
164 * {@link ObjectIdRef}. Otherwise, the update will recursively
165 * traverse {@link SymbolicRef}s and operate on the leaf
166 * {@link ObjectIdRef}.
167 * @return a new update for the requested name; never null.
168 * @throws IOException
169 * the reference space cannot be accessed.
170 */
171 public abstract RefUpdate newUpdate(String name, boolean detach)
172 throws IOException;
173
174 /**
175 * Create a new update command to rename a reference.
176 *
177 * @param fromName
178 * name of reference to rename from
179 * @param toName
180 * name of reference to rename to
181 * @return an update command that knows how to rename a branch to another.
182 * @throws IOException
183 * the reference space cannot be accessed.
184 */
185 public abstract RefRename newRename(String fromName, String toName)
186 throws IOException;
187
188 /**
189 * Create a new batch update to attempt on this database.
190 * <p>
191 * The default implementation performs a sequential update of each command.
192 *
193 * @return a new batch update object.
194 */
195 public BatchRefUpdate newBatchUpdate() {
196 return new BatchRefUpdate(this);
197 }
198
199 /**
200 * @return if the database performs {@code newBatchUpdate()} as an atomic
201 * transaction.
202 * @since 3.6
203 */
204 public boolean performsAtomicTransactions() {
205 return false;
206 }
207
208 /**
209 * Read a single reference.
210 * <p>
211 * Aside from taking advantage of {@link #SEARCH_PATH}, this method may be
212 * able to more quickly resolve a single reference name than obtaining the
213 * complete namespace by {@code getRefs(ALL).get(name)}.
214 *
215 * @param name
216 * the name of the reference. May be a short name which must be
217 * searched for using the standard {@link #SEARCH_PATH}.
218 * @return the reference (if it exists); else {@code null}.
219 * @throws IOException
220 * the reference space cannot be accessed.
221 */
222 public abstract Ref getRef(String name) throws IOException;
223
224 /**
225 * Get a section of the reference namespace.
226 *
227 * @param prefix
228 * prefix to search the namespace with; must end with {@code /}.
229 * If the empty string ({@link #ALL}), obtain a complete snapshot
230 * of all references.
231 * @return modifiable map that is a complete snapshot of the current
232 * reference namespace, with {@code prefix} removed from the start
233 * of each key. The map can be an unsorted map.
234 * @throws IOException
235 * the reference space cannot be accessed.
236 */
237 public abstract Map<String, Ref> getRefs(String prefix) throws IOException;
238
239 /**
240 * Get the additional reference-like entities from the repository.
241 * <p>
242 * The result list includes non-ref items such as MERGE_HEAD and
243 * FETCH_RESULT cast to be refs. The names of these refs are not returned by
244 * <code>getRefs(ALL)</code> but are accepted by {@link #getRef(String)}
245 *
246 * @return a list of additional refs
247 * @throws IOException
248 * the reference space cannot be accessed.
249 */
250 public abstract List<Ref> getAdditionalRefs() throws IOException;
251
252 /**
253 * Peel a possibly unpeeled reference by traversing the annotated tags.
254 * <p>
255 * If the reference cannot be peeled (as it does not refer to an annotated
256 * tag) the peeled id stays null, but {@link Ref#isPeeled()} will be true.
257 * <p>
258 * Implementors should check {@link Ref#isPeeled()} before performing any
259 * additional work effort.
260 *
261 * @param ref
262 * The reference to peel
263 * @return {@code ref} if {@code ref.isPeeled()} is true; otherwise a new
264 * Ref object representing the same data as Ref, but isPeeled() will
265 * be true and getPeeledObjectId() will contain the peeled object
266 * (or null).
267 * @throws IOException
268 * the reference space or object space cannot be accessed.
269 */
270 public abstract Ref peel(Ref ref) throws IOException;
271
272 /**
273 * Triggers a refresh of all internal data structures.
274 * <p>
275 * In case the RefDatabase implementation has internal caches this method
276 * will trigger that all these caches are cleared.
277 * <p>
278 * Implementors should overwrite this method if they use any kind of caches.
279 */
280 public void refresh() {
281 // nothing
282 }
283
284 /**
285 * Try to find the specified name in the ref map using {@link #SEARCH_PATH}.
286 *
287 * @param map
288 * map of refs to search within. Names should be fully qualified,
289 * e.g. "refs/heads/master".
290 * @param name
291 * short name of ref to find, e.g. "master" to find
292 * "refs/heads/master" in map.
293 * @return The first ref matching the name, or null if not found.
294 * @since 3.4
295 */
296 public static Ref findRef(Map<String, Ref> map, String name) {
297 for (String prefix : SEARCH_PATH) {
298 String fullname = prefix + name;
299 Ref ref = map.get(fullname);
300 if (ref != null)
301 return ref;
302 }
303 return null;
304 }
305 }