RefMap.java

  1. /*
  2.  * Copyright (C) 2010, Google Inc. and others
  3.  *
  4.  * This program and the accompanying materials are made available under the
  5.  * terms of the Eclipse Distribution License v. 1.0 which is available at
  6.  * https://www.eclipse.org/org/documents/edl-v10.php.
  7.  *
  8.  * SPDX-License-Identifier: BSD-3-Clause
  9.  */

  10. package org.eclipse.jgit.util;

  11. import java.util.AbstractMap;
  12. import java.util.AbstractSet;
  13. import java.util.Iterator;
  14. import java.util.Map;
  15. import java.util.NoSuchElementException;
  16. import java.util.Set;
  17. import java.util.function.BinaryOperator;
  18. import java.util.stream.Collector;
  19. import java.util.stream.Collectors;

  20. import org.eclipse.jgit.lib.AnyObjectId;
  21. import org.eclipse.jgit.lib.ObjectId;
  22. import org.eclipse.jgit.lib.Ref;
  23. import org.eclipse.jgit.lib.RefComparator;

  24. /**
  25.  * Specialized Map to present a {@code RefDatabase} namespace.
  26.  * <p>
  27.  * Although not declared as a {@link java.util.SortedMap}, iterators from this
  28.  * map's projections always return references in
  29.  * {@link org.eclipse.jgit.lib.RefComparator} ordering. The map's internal
  30.  * representation is a sorted array of {@link org.eclipse.jgit.lib.Ref} objects,
  31.  * which means lookup and replacement is O(log N), while insertion and removal
  32.  * can be as expensive as O(N + log N) while the list expands or contracts.
  33.  * Since this is not a general map implementation, all entries must be keyed by
  34.  * the reference name.
  35.  * <p>
  36.  * This class is really intended as a helper for {@code RefDatabase}, which
  37.  * needs to perform a merge-join of three sorted
  38.  * {@link org.eclipse.jgit.util.RefList}s in order to present the unified
  39.  * namespace of the packed-refs file, the loose refs/ directory tree, and the
  40.  * resolved form of any symbolic references.
  41.  */
  42. public class RefMap extends AbstractMap<String, Ref> {
  43.     /**
  44.      * Prefix denoting the reference subspace this map contains.
  45.      * <p>
  46.      * All reference names in this map must start with this prefix. If the
  47.      * prefix is not the empty string, it must end with a '/'.
  48.      */
  49.     final String prefix;

  50.     /** Immutable collection of the packed references at construction time. */
  51.     RefList<Ref> packed;

  52.     /**
  53.      * Immutable collection of the loose references at construction time.
  54.      * <p>
  55.      * If an entry appears here and in {@link #packed}, this entry must take
  56.      * precedence, as its more current. Symbolic references in this collection
  57.      * are typically unresolved, so they only tell us who their target is, but
  58.      * not the current value of the target.
  59.      */
  60.     RefList<Ref> loose;

  61.     /**
  62.      * Immutable collection of resolved symbolic references.
  63.      * <p>
  64.      * This collection contains only the symbolic references we were able to
  65.      * resolve at map construction time. Other loose references must be read
  66.      * from {@link #loose}. Every entry in this list must be matched by an entry
  67.      * in {@code loose}, otherwise it might be omitted by the map.
  68.      */
  69.     RefList<Ref> resolved;

  70.     int size;

  71.     boolean sizeIsValid;

  72.     private Set<Entry<String, Ref>> entrySet;

  73.     /**
  74.      * Construct an empty map with a small initial capacity.
  75.      */
  76.     public RefMap() {
  77.         prefix = ""; //$NON-NLS-1$
  78.         packed = RefList.emptyList();
  79.         loose = RefList.emptyList();
  80.         resolved = RefList.emptyList();
  81.     }

  82.     /**
  83.      * Construct a map to merge 3 collections together.
  84.      *
  85.      * @param prefix
  86.      *            prefix used to slice the lists down. Only references whose
  87.      *            names start with this prefix will appear to reside in the map.
  88.      *            Must not be null, use {@code ""} (the empty string) to select
  89.      *            all list items.
  90.      * @param packed
  91.      *            items from the packed reference list, this is the last list
  92.      *            searched.
  93.      * @param loose
  94.      *            items from the loose reference list, this list overrides
  95.      *            {@code packed} if a name appears in both.
  96.      * @param resolved
  97.      *            resolved symbolic references. This list overrides the prior
  98.      *            list {@code loose}, if an item appears in both. Items in this
  99.      *            list <b>must</b> also appear in {@code loose}.
  100.      */
  101.     @SuppressWarnings("unchecked")
  102.     public RefMap(String prefix, RefList<? extends Ref> packed,
  103.             RefList<? extends Ref> loose, RefList<? extends Ref> resolved) {
  104.         this.prefix = prefix;
  105.         this.packed = (RefList<Ref>) packed;
  106.         this.loose = (RefList<Ref>) loose;
  107.         this.resolved = (RefList<Ref>) resolved;
  108.     }

  109.     /** {@inheritDoc} */
  110.     @Override
  111.     public boolean containsKey(Object name) {
  112.         return get(name) != null;
  113.     }

  114.     /** {@inheritDoc} */
  115.     @Override
  116.     public Ref get(Object key) {
  117.         String name = toRefName((String) key);
  118.         Ref ref = resolved.get(name);
  119.         if (ref == null)
  120.             ref = loose.get(name);
  121.         if (ref == null)
  122.             ref = packed.get(name);
  123.         return ref;
  124.     }

  125.     /** {@inheritDoc} */
  126.     @Override
  127.     public Ref put(String keyName, Ref value) {
  128.         String name = toRefName(keyName);

  129.         if (!name.equals(value.getName()))
  130.             throw new IllegalArgumentException();

  131.         if (!resolved.isEmpty()) {
  132.             // Collapse the resolved list into the loose list so we
  133.             // can discard it and stop joining the two together.
  134.             for (Ref ref : resolved)
  135.                 loose = loose.put(ref);
  136.             resolved = RefList.emptyList();
  137.         }

  138.         int idx = loose.find(name);
  139.         if (0 <= idx) {
  140.             Ref prior = loose.get(name);
  141.             loose = loose.set(idx, value);
  142.             return prior;
  143.         }
  144.         Ref prior = get(keyName);
  145.         loose = loose.add(idx, value);
  146.         sizeIsValid = false;
  147.         return prior;
  148.     }

  149.     /** {@inheritDoc} */
  150.     @Override
  151.     public Ref remove(Object key) {
  152.         String name = toRefName((String) key);
  153.         Ref res = null;
  154.         int idx;
  155.         if (0 <= (idx = packed.find(name))) {
  156.             res = packed.get(name);
  157.             packed = packed.remove(idx);
  158.             sizeIsValid = false;
  159.         }
  160.         if (0 <= (idx = loose.find(name))) {
  161.             res = loose.get(name);
  162.             loose = loose.remove(idx);
  163.             sizeIsValid = false;
  164.         }
  165.         if (0 <= (idx = resolved.find(name))) {
  166.             res = resolved.get(name);
  167.             resolved = resolved.remove(idx);
  168.             sizeIsValid = false;
  169.         }
  170.         return res;
  171.     }

  172.     /** {@inheritDoc} */
  173.     @Override
  174.     public boolean isEmpty() {
  175.         return entrySet().isEmpty();
  176.     }

  177.     /** {@inheritDoc} */
  178.     @Override
  179.     public Set<Entry<String, Ref>> entrySet() {
  180.         if (entrySet == null) {
  181.             entrySet = new AbstractSet<Entry<String, Ref>>() {
  182.                 @Override
  183.                 public Iterator<Entry<String, Ref>> iterator() {
  184.                     return new SetIterator();
  185.                 }

  186.                 @Override
  187.                 public int size() {
  188.                     if (!sizeIsValid) {
  189.                         size = 0;
  190.                         Iterator<?> i = entrySet().iterator();
  191.                         for (; i.hasNext(); i.next())
  192.                             size++;
  193.                         sizeIsValid = true;
  194.                     }
  195.                     return size;
  196.                 }

  197.                 @Override
  198.                 public boolean isEmpty() {
  199.                     if (sizeIsValid)
  200.                         return 0 == size;
  201.                     return !iterator().hasNext();
  202.                 }

  203.                 @Override
  204.                 public void clear() {
  205.                     packed = RefList.emptyList();
  206.                     loose = RefList.emptyList();
  207.                     resolved = RefList.emptyList();
  208.                     size = 0;
  209.                     sizeIsValid = true;
  210.                 }
  211.             };
  212.         }
  213.         return entrySet;
  214.     }

  215.     /** {@inheritDoc} */
  216.     @Override
  217.     public String toString() {
  218.         StringBuilder r = new StringBuilder();
  219.         boolean first = true;
  220.         r.append('[');
  221.         for (Ref ref : values()) {
  222.             if (first)
  223.                 first = false;
  224.             else
  225.                 r.append(", "); //$NON-NLS-1$
  226.             r.append(ref);
  227.         }
  228.         r.append(']');
  229.         return r.toString();
  230.     }

  231.     /**
  232.      * Create a {@link Collector} for {@link Ref}.
  233.      *
  234.      * @param mergeFunction
  235.      * @return {@link Collector} for {@link Ref}
  236.      * @since 5.4
  237.      */
  238.     public static Collector<Ref, ?, RefMap> toRefMap(
  239.             BinaryOperator<Ref> mergeFunction) {
  240.         return Collectors.collectingAndThen(RefList.toRefList(mergeFunction),
  241.                 (refs) -> new RefMap("", //$NON-NLS-1$
  242.                             refs, RefList.emptyList(),
  243.                         RefList.emptyList()));
  244.     }

  245.     private String toRefName(String name) {
  246.         if (0 < prefix.length())
  247.             name = prefix + name;
  248.         return name;
  249.     }

  250.     String toMapKey(Ref ref) {
  251.         String name = ref.getName();
  252.         if (0 < prefix.length())
  253.             name = name.substring(prefix.length());
  254.         return name;
  255.     }

  256.     private class SetIterator implements Iterator<Entry<String, Ref>> {
  257.         private int packedIdx;

  258.         private int looseIdx;

  259.         private int resolvedIdx;

  260.         private Entry<String, Ref> next;

  261.         SetIterator() {
  262.             if (0 < prefix.length()) {
  263.                 packedIdx = -(packed.find(prefix) + 1);
  264.                 looseIdx = -(loose.find(prefix) + 1);
  265.                 resolvedIdx = -(resolved.find(prefix) + 1);
  266.             }
  267.         }

  268.         @Override
  269.         public boolean hasNext() {
  270.             if (next == null)
  271.                 next = peek();
  272.             return next != null;
  273.         }

  274.         @Override
  275.         public Entry<String, Ref> next() {
  276.             if (hasNext()) {
  277.                 Entry<String, Ref> r = next;
  278.                 next = peek();
  279.                 return r;
  280.             }
  281.             throw new NoSuchElementException();
  282.         }

  283.         public Entry<String, Ref> peek() {
  284.             if (packedIdx < packed.size() && looseIdx < loose.size()) {
  285.                 Ref p = packed.get(packedIdx);
  286.                 Ref l = loose.get(looseIdx);
  287.                 int cmp = RefComparator.compareTo(p, l);
  288.                 if (cmp < 0) {
  289.                     packedIdx++;
  290.                     return toEntry(p);
  291.                 }

  292.                 if (cmp == 0)
  293.                     packedIdx++;
  294.                 looseIdx++;
  295.                 return toEntry(resolveLoose(l));
  296.             }

  297.             if (looseIdx < loose.size())
  298.                 return toEntry(resolveLoose(loose.get(looseIdx++)));
  299.             if (packedIdx < packed.size())
  300.                 return toEntry(packed.get(packedIdx++));
  301.             return null;
  302.         }

  303.         private Ref resolveLoose(Ref l) {
  304.             if (resolvedIdx < resolved.size()) {
  305.                 Ref r = resolved.get(resolvedIdx);
  306.                 int cmp = RefComparator.compareTo(l, r);
  307.                 if (cmp == 0) {
  308.                     resolvedIdx++;
  309.                     return r;
  310.                 } else if (cmp > 0) {
  311.                     // WTF, we have a symbolic entry but no match
  312.                     // in the loose collection. That's an error.
  313.                     throw new IllegalStateException();
  314.                 }
  315.             }
  316.             return l;
  317.         }

  318.         private Ent toEntry(Ref p) {
  319.             if (p.getName().startsWith(prefix))
  320.                 return new Ent(p);
  321.             packedIdx = packed.size();
  322.             looseIdx = loose.size();
  323.             resolvedIdx = resolved.size();
  324.             return null;
  325.         }

  326.         @Override
  327.         public void remove() {
  328.             throw new UnsupportedOperationException();
  329.         }
  330.     }

  331.     private class Ent implements Entry<String, Ref> {
  332.         private Ref ref;

  333.         Ent(Ref ref) {
  334.             this.ref = ref;
  335.         }

  336.         @Override
  337.         public String getKey() {
  338.             return toMapKey(ref);
  339.         }

  340.         @Override
  341.         public Ref getValue() {
  342.             return ref;
  343.         }

  344.         @Override
  345.         public Ref setValue(Ref value) {
  346.             Ref prior = put(getKey(), value);
  347.             ref = value;
  348.             return prior;
  349.         }

  350.         @Override
  351.         public int hashCode() {
  352.             return getKey().hashCode();
  353.         }

  354.         @Override
  355.         public boolean equals(Object obj) {
  356.             if (obj instanceof Map.Entry) {
  357.                 final Object key = ((Map.Entry) obj).getKey();
  358.                 final Object val = ((Map.Entry) obj).getValue();
  359.                 if (key instanceof String && val instanceof Ref) {
  360.                     final Ref r = (Ref) val;
  361.                     if (r.getName().equals(ref.getName())) {
  362.                         final ObjectId a = r.getObjectId();
  363.                         final ObjectId b = ref.getObjectId();
  364.                         if (a != null && b != null
  365.                                 && AnyObjectId.isEqual(a, b)) {
  366.                             return true;
  367.                         }
  368.                     }
  369.                 }
  370.             }
  371.             return false;
  372.         }

  373.         @Override
  374.         public String toString() {
  375.             return ref.toString();
  376.         }
  377.     }
  378. }