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.

RefDatabase.java 18KB

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