com.xlrit.gears.runner.utils.GraphQLUtils Maven / Gradle / Ivy
package com.xlrit.gears.runner.utils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import java.io.File;
import java.io.FileFilter;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Stream;
public class GraphQLUtils {
private static final FileFilter ENTER_DIR = file -> !file.getName().endsWith("ignore");
public static Optional findInChoices(ArrayNode choices, String match, String key) {
for (JsonNode node : choices) {
if (node.get(key).asText().equals(match)) return Optional.of(node);
}
return Optional.empty();
}
public static List listFilteredFiles(File dir, String pattern, String ... extensions) {
FileFilter includeFile = globPatternToFilter(dir, pattern, extensions);
return walk(dir, includeFile)
.sorted(Comparator.comparing(File::getName))
.toList();
}
private static Stream walk(File dir, FileFilter includeFile) {
return Arrays.stream(Objects.requireNonNull(dir.listFiles())).flatMap(entry -> {
if (entry.isDirectory() && ENTER_DIR.accept(entry)) return walk(entry, includeFile);
if (entry.isFile() && includeFile.accept(entry)) return Stream.of(entry);
else return Stream.empty();
});
}
private static FileFilter globPatternToFilter(File dir, String pattern, String ... extensions) {
Path basePath = Paths.get(dir.getPath());
PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
return file -> {
Path relPath = basePath.relativize(Paths.get(file.getPath()));
return pathMatcher.matches(relPath)
&& Arrays.stream(extensions).anyMatch(extension -> relPath.toString().endsWith("." + extension));
};
}
}