import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
+import java.util.List;
import java.util.Map;
import java.util.TreeSet;
assertSame(dst.getPeeledObjectId(), ref.getPeeledObjectId());
assertEquals(dst.isPeeled(), ref.isPeeled());
}
+
+ private static void checkContainsRef(List<Ref> haystack, Ref needle) {
+ for (Ref ref : haystack) {
+ if (ref.getName().equals(needle.getName()) &&
+ ref.getObjectId().equals(needle.getObjectId())) {
+ return;
+ }
+ }
+ fail("list " + haystack + " does not contain ref " + needle);
+ }
+
+ @Test
+ public void testGetRefsByPrefix() throws IOException {
+ List<Ref> refs = db.getRefDatabase().getRefsByPrefix("refs/heads/g");
+ assertEquals(2, refs.size());
+ checkContainsRef(refs, db.exactRef("refs/heads/g"));
+ checkContainsRef(refs, db.exactRef("refs/heads/gitlink"));
+
+ refs = db.getRefDatabase().getRefsByPrefix("refs/heads/prefix/");
+ assertEquals(1, refs.size());
+ checkContainsRef(refs, db.exactRef("refs/heads/prefix/a"));
+ }
}
package org.eclipse.jgit.lib;
+import static java.util.stream.Collectors.toList;
+
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
* of each key. The map can be an unsorted map.
* @throws java.io.IOException
* the reference space cannot be accessed.
+ * @deprecated use {@link #getRefsByPrefix} instead
*/
@NonNull
+ @Deprecated
public abstract Map<String, Ref> getRefs(String prefix) throws IOException;
+ /**
+ * Returns refs whose names start with a given prefix.
+ * <p>
+ * The default implementation uses {@link #getRefs}. Implementors of
+ * {@link RefDatabase} should override this method directly if a better
+ * implementation is possible.
+ *
+ * @param prefix string that names of refs should start with; may be
+ * empty (to return all refs).
+ * @return immutable list of refs whose names start with {@code prefix}.
+ * @throws java.io.IOException
+ * the reference space cannot be accessed.
+ * @since 5.0
+ */
+ @NonNull
+ public List<Ref> getRefsByPrefix(String prefix) throws IOException {
+ Map<String, Ref> coarseRefs;
+ int lastSlash = prefix.lastIndexOf('/');
+ if (lastSlash == -1) {
+ coarseRefs = getRefs(ALL);
+ } else {
+ coarseRefs = getRefs(prefix.substring(0, lastSlash + 1));
+ }
+
+ List<Ref> result;
+ if (lastSlash + 1 == prefix.length()) {
+ result = coarseRefs.values().stream().collect(toList());
+ } else {
+ String p = prefix.substring(lastSlash + 1);
+ result = coarseRefs.entrySet().stream()
+ .filter(e -> e.getKey().startsWith(p))
+ .map(e -> e.getValue())
+ .collect(toList());
+ }
+ return Collections.unmodifiableList(result);
+ }
+
/**
* Get the additional reference-like entities from the repository.
* <p>