下面列出了java.nio.file.PathMatcher#matches ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static SwaggerGenerator getGenerator(File dir, Predicate<Module> toSelect) throws Exception {
final PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:*.yang");
Predicate<Path> acc = p -> matcher.matches(p.getFileName());
final SchemaContext ctx = dir == null ? getFromClasspath(acc) : getFromDir(dir.toPath(), acc);
if(ctx.getModules().isEmpty()) throw new IllegalArgumentException(String.format("No YANG modules found in %s", dir == null ? "classpath" : dir.toString()));
log.info("Context parsed {}", ctx);
final Set<Module> toGenerate = ctx.getModules().stream().filter(toSelect).collect(Collectors.toSet());
return new SwaggerGenerator(ctx, toGenerate)
.defaultConfig()
.format(SwaggerGenerator.Format.YAML)
.consumes("application/xml")
.produces("application/xml")
.host("localhost:1234")
.elements(SwaggerGenerator.Elements.DATA, SwaggerGenerator.Elements.RCP);
}
public static IoCSwaggerGenerator getGenerator(File dir, Predicate<Module> toSelect) throws Exception {
final PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:*.yang");
Predicate<Path> acc = p -> matcher.matches(p.getFileName());
final SchemaContext ctx = dir == null ? getFromClasspath(acc) : getFromDir(dir.toPath(), acc);
if(ctx.getModules().isEmpty()) throw new IllegalArgumentException(String.format("No YANG modules found in %s", dir == null ? "classpath" : dir.toString()));
log.info("Context parsed {}", ctx);
final Set<Module> toGenerate = ctx.getModules().stream().filter(toSelect).collect(Collectors.toSet());
return swaggerGeneratorFactory.createSwaggerGenerator(ctx, toGenerate)
.defaultConfig()
.format(IoCSwaggerGenerator.Format.YAML)
.consumes("application/xml")
.produces("application/xml")
.host("localhost:1234")
.elements(IoCSwaggerGenerator.Elements.DATA, IoCSwaggerGenerator.Elements.RCP);
}
private boolean isExcluded(Path dir) {
if (dir.getFileName() == null) {
return true;
}
boolean excluded = false;
for (String pattern : exclusions) {
boolean includePattern = false;
if (pattern.startsWith("!")) {
includePattern = true;
pattern = pattern.substring(1);
}
PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
if (matcher.matches(dir)) {
excluded = includePattern ? false : true;
}
}
return excluded;
}
/**
* Resolves {@code symlink} recursively until it finds a regular file or directory. It also
* checks that all its intermediate paths jumps are under {@code matcher}.
*/
public static ResolvedSymlink resolveSymlink(PathMatcher matcher, Path symlink)
throws IOException {
// Normalize since matcher glob:foo/bar/file* doesn't match foo/bar/../bar/file*
Path path = symlink.normalize();
checkArgument(matcher.matches(path), "%s doesn't match %s", path, matcher);
Set<Path> visited = new LinkedHashSet<>();
while (Files.isSymbolicLink(path)) {
visited.add(path);
// Avoid 'dot' -> . like traps by capping to a sane limit
if (visited.size() > 50) {
throw new IOException("Symlink cycle detected:\n "
+ Joiner.on("\n ").join(Iterables.concat(visited, ImmutableList.of(symlink))));
}
Path newPath = Files.readSymbolicLink(path);
if (!newPath.isAbsolute()) {
newPath = path.resolveSibling(newPath).toAbsolutePath().normalize();
} else {
newPath = newPath.normalize();
}
if (!matcher.matches(newPath)) {
if (!Files.isDirectory(newPath)
// Special support for symlinks in the form of ROOT/symlink -> '.'. Technically we
// shouldn't allow this because of our glob implementation, but this is a regression
// from the old code and the correct behavior is difficult to understand by our users.
|| !matcher.matches(newPath.resolve("copybara_random_path.txt"))) {
Path realPath = newPath.toRealPath();
return new ResolvedSymlink(realPath, /*allUnderRoot=*/ false);
}
}
path = newPath;
}
return new ResolvedSymlink(path, /*allUnderRoot=*/ true);
}
private boolean shouldExclude(java.nio.file.Path nioPath) {
for (PathMatcher matcher : getExcludeMatchers()) {
if (matcher.matches(nioPath)) {
return true;
}
}
return false;
}
private boolean shouldExclude(java.nio.file.Path nioPath) {
for (PathMatcher matcher : getExcludeMatchers()) {
if (matcher.matches(nioPath)) {
return true;
}
}
return false;
}
/**
* Returns true iff the given change should be skipped based on the origin globs and flags
* provided.
*/
final boolean shouldSkipChange(Change<?> currentChange) {
if (workflow.isMigrateNoopChanges()) {
return false;
}
// We cannot know the files included. Try to migrate then.
if (currentChange.getChangeFiles() == null) {
return false;
}
PathMatcher pathMatcher = getOriginFiles().relativeTo(Paths.get("/"));
for (String changedFile : currentChange.getChangeFiles()) {
if (pathMatcher.matches(Paths.get("/" + changedFile))) {
return false;
}
}
// This is an heuristic for cases where the Copybara configuration is stored in the same
// folder as the origin code but excluded.
//
// The config root can be a subfolder of the files as seen by the origin. For example:
// admin/copy.bara.sky could be present in the origin as root/admin/copy.bara.sky.
// This might give us some false positives but they would be noop migrations.
for (String changesFile : currentChange.getChangeFiles()) {
for (String configPath : getConfigFiles()) {
if (changesFile.endsWith(configPath)) {
workflow.getConsole()
.infoFmt("Migrating %s because %s config file changed at that revision",
currentChange.getRevision().asString(), changesFile);
return false;
}
}
}
return true;
}
/**
* Matches URL
* @param u url
* @param pattern match patter (glob)
* @return <code>true</code> if URL matches the pattern
*/
private boolean matchUrl(URL u, String pattern) {
String[] split = u.getPath().split("(/|\\\\)+");
List<String> items = Arrays.asList(split).stream().filter(s->s!=null && !s.isEmpty()).collect(Collectors.toList());
if (!items.isEmpty()) {
String first = items.get(0);
List<String> subList = items.subList(1, items.size());
Path path = fileSystem.getPath(first, subList.toArray(new String[]{}));
PathMatcher pathMatcher = fileSystem.getPathMatcher("glob:"+pattern);
return pathMatcher.matches(path);
} else {
return false;
}
}
@Override
public PathMatcher getPathMatcher(String syntaxAndPattern) {
final PathMatcher matcher = delegate.getPathMatcher(syntaxAndPattern);
return new PathMatcher() {
@Override
public boolean matches(Path path) {
return matcher.matches(unwrap(path));
}
};
}
@Override
public PathMatcher getPathMatcher(String syntaxAndPattern) {
final PathMatcher matcher = delegate.getPathMatcher(syntaxAndPattern);
return new PathMatcher() {
@Override
public boolean matches(Path path) {
return matcher.matches(unwrap(path));
}
};
}
@Override
public PathMatcher getPathMatcher(String syntaxAndPattern) {
final PathMatcher matcher = delegate.getPathMatcher(syntaxAndPattern);
return new PathMatcher() {
@Override
public boolean matches(Path path) {
return matcher.matches(unwrap(path));
}
};
}
@Override
public PathMatcher getPathMatcher(String syntaxAndPattern) {
final PathMatcher matcher = delegate.getPathMatcher(syntaxAndPattern);
return new PathMatcher() {
@Override
public boolean matches(Path path) {
return matcher.matches(unwrap(path));
}
};
}
/**
* Returns true if the {@code ignoreGlob} is inside the current repository.
* Produces log messages when the invalid {@code ignoreGlob} is skipped.
*/
private static boolean isValidIgnoreGlob(File repoRoot, String ignoreGlob) {
String validPath = ignoreGlob;
FileSystem fileSystem = FileSystems.getDefault();
if (ignoreGlob.isEmpty()) {
return false;
} else if (ignoreGlob.startsWith("/") || ignoreGlob.startsWith("\\")) {
// Ignore globs cannot start with a slash
logger.log(Level.WARNING, ignoreGlob + " cannot start with / or \\.");
return false;
} else if (ignoreGlob.contains("/*") || ignoreGlob.contains("\\*")) {
// contains directories
validPath = ignoreGlob.substring(0, ignoreGlob.indexOf("/*"));
} else if (ignoreGlob.contains("*")) {
// no directories
return true;
}
try {
String fileGlobPath = "glob:" + repoRoot.getCanonicalPath().replaceAll("\\\\+", "\\/") + "/**";
PathMatcher pathMatcher = fileSystem.getPathMatcher(fileGlobPath);
validPath = new File(repoRoot, validPath).getCanonicalPath();
if (pathMatcher.matches(Paths.get(validPath))) {
return true;
}
} catch (IOException ioe) {
logger.log(Level.WARNING, ioe.getMessage(), ioe);
return false;
}
logger.log(Level.WARNING, ignoreGlob + " will be skipped as this glob points to the outside of "
+ "the repository.");
return false;
}
@Override
public PathMatcher getPathMatcher(String syntaxAndPattern) {
final PathMatcher matcher = delegate.getPathMatcher(syntaxAndPattern);
return new PathMatcher() {
@Override
public boolean matches(Path path) {
return matcher.matches(unwrap(path));
}
};
}
private void processInclude(String include) {
if (include.isEmpty()) {
return;
}
for (String filter : include.split(",")) {
final PathMatcher matcher = Utils.getPathMatcher(JRT_FILE_SYSTEM, filter);
Predicate<String> predicate = (path) -> matcher.matches(JRT_FILE_SYSTEM.getPath(path));
includePredicates.add(predicate);
}
}
/**
* Returns {@link PathMatcher} that negates {@code athMatcher}
*/
public static PathMatcher notPathMatcher(PathMatcher pathMatcher) {
return new PathMatcher() {
@Override
public boolean matches(Path path) {
return !pathMatcher.matches(path);
}
@Override
public String toString() {
return "not(" + pathMatcher + ")";
}
};
}
@Override
public boolean test(String name) {
Objects.requireNonNull(name);
Path path = Utils.getJRTFSPath(name);
for (PathMatcher matcher : matchers) {
if (matcher.matches(path)) {
return include;
}
}
return otherwise;
}
@Override
public PathMatcher getPathMatcher(String syntaxAndPattern) {
final PathMatcher matcher = delegate.getPathMatcher(syntaxAndPattern);
return new PathMatcher() {
@Override
public boolean matches(Path path) {
return matcher.matches(unwrap(path));
}
};
}
private static boolean matchPattern(String path, String pattern) {
final PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
return pathMatcher.matches(Paths.get(path));
}
@Override
public void transform(TransformWork work)
throws IOException, ValidationException, RepoException {
Console console = work.getConsole();
boolean fileDebug = false;
if (debugOptions.getDebugFileBreak() != null) {
fileDebug = true;
}
boolean metadataDebug = false;
if (debugOptions.debugMetadataBreak) {
metadataDebug = true;
}
Pattern debugTransformBreak = debugOptions.getDebugTransformBreak();
boolean transformMatch = false;
if (debugTransformBreak != null
&& debugTransformBreak.matcher(this.delegate.describe())
.find()) {
transformMatch = true;
}
if (!fileDebug && !metadataDebug && !transformMatch) {
// Nothing to debug!
delegate.transform(work);
return;
}
TreeMap<String, byte[]> before = readState(work, fileDebug || transformMatch,
work.getTreeState());
delegate.transform(work);
TreeMap<String, byte[]> after = readState(work, fileDebug || transformMatch,
work.getTreeState().newTreeState());
MapDifference<String, byte[]> difference = Maps.difference(before, after,
new Equivalence<byte[]>() {
@Override
protected boolean doEquivalent(byte[] one, byte[] other) {
return Arrays.equals(one, other);
}
@Override
protected int doHash(byte[] bytes) {
return Arrays.hashCode(bytes);
}
});
boolean stop = transformMatch;
if (fileDebug) {
PathMatcher debugFileBreak = debugOptions.getDebugFileBreak()
.relativeTo(Paths.get("/"));
for (String path : Iterables.concat(difference.entriesOnlyOnLeft().keySet(),
difference.entriesOnlyOnRight().keySet(), difference.entriesDiffering().keySet())) {
if (path.equals(COPYBARA_METADATA_FAKE_FILE)) {
continue;
}
if (debugFileBreak.matches(Paths.get("/" + path))) {
stop = true;
console.infoFmt("File '%s' change matched. Stopping", path);
break;
}
}
} else if (metadataDebug && !Arrays.equals(
before.get(COPYBARA_METADATA_FAKE_FILE),
after.get(COPYBARA_METADATA_FAKE_FILE))) {
stop = true;
console.infoFmt("Message, author and/or labels changed");
}
if (!stop) {
return;
}
if (!transformMatch) {
// Stopped because of file/metadata change. Show the diff directly
showDiff(console, difference);
}
while (true) {
String answer = console.ask(
"Debugger stopped after '" + delegate.describe()
+ "' "
+ console.colorize(AnsiColor.PURPLE, delegate.location().toString())
+ ".\n"
+ " Current file state can be checked at " + work.getCheckoutDir() +"\n"
+ "Diff (d), Continue (c), Stop (s): ",
"d",
input -> ImmutableSet.of("d", "c", "s").contains(input));
switch (answer) {
case "d": {
showDiff(console, difference);
break;
}
case "c":
return;
case "s":
throw new ValidationException("Stopped by user");
}
}
}