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 20KB

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