Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

RefDatabase.java 19KB

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