GitTreeReader.stream: refactor for readability

This commit is contained in:
Paul Campbell 2018-07-11 07:10:49 +01:00
parent 330e87b6a1
commit 2f68bd55d0

View file

@ -26,7 +26,6 @@ import lombok.RequiredArgsConstructor;
import net.kemitix.mon.result.Result;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevTree;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.treewalk.TreeWalk;
@ -35,7 +34,6 @@ import org.eclipse.jgit.treewalk.filter.TreeFilter;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Stream;
@ -58,27 +56,35 @@ class GitTreeReader {
* @return a stream of key/value pairs as NamedRevBlobs
*/
Result<Stream<NamedRevBlob>> stream(final Ref branchRef) {
final TreeWalk treeWalk = new TreeWalk(repository);
final RevWalk revWalk = new RevWalk(repository);
return Result.of(parseBranchCommit(branchRef, revWalk))
.map(RevCommit::getTree)
.flatMap(addTreeTo(treeWalk))
.peek(disableRecursion(treeWalk))
.peek(setTreeFilter(treeWalk))
.flatMap(streamMatching(treeWalk, revWalk));
return Result.of(parseTree(branchRef, revWalk))
.andThen(configureFilter())
.andThen(buildStream(revWalk));
}
private Function<Void, Result<Stream<NamedRevBlob>>> streamMatching(
final TreeWalk treeWalk,
final RevWalk revWalk
) {
return x -> Result.of(() -> {
private Callable<RevTree> parseTree(final Ref branchRef, final RevWalk revWalk) {
return () -> revWalk.parseCommit(branchRef.getObjectId()).getTree();
}
private Function<RevTree, Callable<TreeWalk>> configureFilter() {
return tree -> () -> {
final TreeWalk treeWalk = new TreeWalk(repository);
treeWalk.addTree(tree);
treeWalk.setRecursive(false);
Optional.ofNullable(treeFilter)
.ifPresent(treeWalk::setFilter);
return treeWalk;
};
}
private Function<TreeWalk, Callable<Stream<NamedRevBlob>>> buildStream(final RevWalk revWalk) {
return treeWalk -> () -> {
final Stream.Builder<NamedRevBlob> builder = Stream.builder();
while (treeWalk.next()) {
builder.add(namedRevBlob(treeWalk, revWalk));
}
return builder.build();
});
};
}
private NamedRevBlob namedRevBlob(final TreeWalk treeWalk, final RevWalk revWalk) {
@ -88,25 +94,6 @@ class GitTreeReader {
repository);
}
private Consumer<Void> setTreeFilter(final TreeWalk treeWalk) {
return x -> Optional.ofNullable(treeFilter).ifPresent(treeWalk::setFilter);
}
private Consumer<Void> disableRecursion(final TreeWalk treeWalk) {
return x -> treeWalk.setRecursive(false);
}
private Function<RevTree, Result<Void>> addTreeTo(final TreeWalk treeWalk) {
return tree -> Result.of(() -> {
treeWalk.addTree(tree);
return null;
});
}
private Callable<RevCommit> parseBranchCommit(final Ref branchRef, final RevWalk revWalk) {
return () -> revWalk.parseCommit(branchRef.getObjectId());
}
/**
* Sets a path filter to limit the stream by.
*