This is an automated email from the ASF dual-hosted git repository. slachiewicz pushed a commit to branch master in repository https://gitbox.apache.org/repos/asf/maven-surefire.git
commit b24b5cf4ae82b7aba7e147808544812855c9f66c Author: Sylwester Lachiewicz <[email protected]> AuthorDate: Sun Nov 8 20:23:06 2026 +0000 Carry the directory scanner and selector utilities in surefire-api surefire-api ends up on the test class path of every project, so it can take no dependency; DirectoryScanner, SelectorUtils, MatchPatterns and their helpers are copied verbatim from maven-shared-utils instead of being reached through the shaded copy. Nothing in Surefire's own code uses the shaded io package any more. Part of #3574. --- .../plugin/surefire/util/SpecificFileFilter.java | 2 +- .../api/filter/SpecificTestClassFilter.java | 2 +- .../maven/surefire/api/testset/ResolvedTest.java | 10 +- .../surefire/api/testset/TestListResolver.java | 4 +- .../surefire/api/util/DefaultDirectoryScanner.java | 4 +- .../api/util/internal/DirectoryScanResult.java | 55 ++ .../api/util/internal/DirectoryScanner.java | 822 +++++++++++++++++++++ .../surefire/api/util/internal/MatchPattern.java | 133 ++++ .../surefire/api/util/internal/MatchPatterns.java | 81 ++ .../surefire/api/util/internal/ScanConductor.java | 81 ++ .../surefire/api/util/internal/SelectorUtils.java | 690 +++++++++++++++++ 11 files changed, 1873 insertions(+), 11 deletions(-) diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/SpecificFileFilter.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/SpecificFileFilter.java index 5c933741a..0167b23a3 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/SpecificFileFilter.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/util/SpecificFileFilter.java @@ -23,7 +23,7 @@ import java.util.HashSet; import java.util.Set; -import org.apache.maven.surefire.shared.utils.io.SelectorUtils; +import org.apache.maven.surefire.api.util.internal.SelectorUtils; import static org.apache.maven.plugin.surefire.util.ScannerUtil.convertSlashToSystemFileSeparator; diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/filter/SpecificTestClassFilter.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/filter/SpecificTestClassFilter.java index b07a23b97..532633f40 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/filter/SpecificTestClassFilter.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/filter/SpecificTestClassFilter.java @@ -23,7 +23,7 @@ import java.util.Set; import org.apache.maven.surefire.api.util.ScannerFilter; -import org.apache.maven.surefire.shared.utils.io.SelectorUtils; +import org.apache.maven.surefire.api.util.internal.SelectorUtils; /** * Filter for test class files. diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/ResolvedTest.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/ResolvedTest.java index 74fb74664..3c6b0244b 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/ResolvedTest.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/ResolvedTest.java @@ -20,16 +20,16 @@ import java.util.regex.Pattern; +import org.apache.maven.surefire.api.util.internal.MatchPatterns; import org.apache.maven.surefire.shared.lang3.StringUtils; -import org.apache.maven.surefire.shared.utils.io.MatchPatterns; import static java.io.File.separatorChar; import static java.util.regex.Pattern.compile; +import static org.apache.maven.surefire.api.util.internal.MatchPatterns.from; +import static org.apache.maven.surefire.api.util.internal.SelectorUtils.PATTERN_HANDLER_SUFFIX; +import static org.apache.maven.surefire.api.util.internal.SelectorUtils.REGEX_HANDLER_PREFIX; +import static org.apache.maven.surefire.api.util.internal.SelectorUtils.matchPath; import static org.apache.maven.surefire.shared.lang3.StringUtils.isBlank; -import static org.apache.maven.surefire.shared.utils.io.MatchPatterns.from; -import static org.apache.maven.surefire.shared.utils.io.SelectorUtils.PATTERN_HANDLER_SUFFIX; -import static org.apache.maven.surefire.shared.utils.io.SelectorUtils.REGEX_HANDLER_PREFIX; -import static org.apache.maven.surefire.shared.utils.io.SelectorUtils.matchPath; /** * Single pattern test filter resolved from multi pattern filter -Dtest=MyTest#test,AnotherTest#otherTest. diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/TestListResolver.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/TestListResolver.java index 7b51a8552..262582f62 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/TestListResolver.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/testset/TestListResolver.java @@ -28,11 +28,11 @@ import static java.util.Collections.unmodifiableSet; import static org.apache.maven.surefire.api.testset.ResolvedTest.Type.CLASS; import static org.apache.maven.surefire.api.testset.ResolvedTest.Type.METHOD; +import static org.apache.maven.surefire.api.util.internal.SelectorUtils.PATTERN_HANDLER_SUFFIX; +import static org.apache.maven.surefire.api.util.internal.SelectorUtils.REGEX_HANDLER_PREFIX; import static org.apache.maven.surefire.shared.lang3.StringUtils.isBlank; import static org.apache.maven.surefire.shared.lang3.StringUtils.isNotBlank; import static org.apache.maven.surefire.shared.lang3.StringUtils.split; -import static org.apache.maven.surefire.shared.utils.io.SelectorUtils.PATTERN_HANDLER_SUFFIX; -import static org.apache.maven.surefire.shared.utils.io.SelectorUtils.REGEX_HANDLER_PREFIX; // TODO In Surefire 3.0 see SUREFIRE-1309 and use normal fully qualified class name regex instead. /** diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/DefaultDirectoryScanner.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/DefaultDirectoryScanner.java index c4d4bb342..976c4a31b 100644 --- a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/DefaultDirectoryScanner.java +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/DefaultDirectoryScanner.java @@ -95,8 +95,8 @@ private static Class<?> loadClass(ClassLoader classLoader, String className) { String[] collectTests() { String[] tests = EMPTY_STRING_ARRAY; if (basedir.exists()) { - org.apache.maven.surefire.shared.utils.io.DirectoryScanner scanner = - new org.apache.maven.surefire.shared.utils.io.DirectoryScanner(); + org.apache.maven.surefire.api.util.internal.DirectoryScanner scanner = + new org.apache.maven.surefire.api.util.internal.DirectoryScanner(); scanner.setBasedir(basedir); diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/DirectoryScanResult.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/DirectoryScanResult.java new file mode 100644 index 000000000..088d92e90 --- /dev/null +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/DirectoryScanResult.java @@ -0,0 +1,55 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.surefire.api.util.internal; + +/** + * Scan for files in a directory at a given time and reports removed and added files + * between captures. + * + * <p>Copied from maven-shared-utils, so that surefire-api, which ends up on the test class path, needs no + * dependency for it. + */ +public class DirectoryScanResult { + private final String[] filesAdded; + + private final String[] filesRemoved; + + /** + * @param filesAdded added files + * @param filesRemoved removed files + */ + public DirectoryScanResult(String[] filesAdded, String[] filesRemoved) { + this.filesAdded = filesAdded; + this.filesRemoved = filesRemoved; + } + + /** + * @return all files which got detected as being added between 2 capture calls + */ + public String[] getFilesAdded() { + return filesAdded; + } + + /** + * @return all files which got detected as being removed between 2 capture calls + */ + public String[] getFilesRemoved() { + return filesRemoved; + } +} diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/DirectoryScanner.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/DirectoryScanner.java new file mode 100644 index 000000000..8d8fbe164 --- /dev/null +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/DirectoryScanner.java @@ -0,0 +1,822 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.surefire.api.util.internal; + +import java.io.File; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * <p>Class for scanning a directory for files/directories which match certain criteria.</p> + * <p> + * These criteria consist of selectors and patterns which have been specified. With the selectors you can select which + * files you want to have included. Files which are not selected are excluded. With patterns you can include or exclude + * files based on their filename. + * </p> + * <p> + * The idea is simple. A given directory is recursively scanned for all files and directories. Each file/directory is + * matched against a set of selectors, including special support for matching against filenames with include and and + * exclude patterns. Only files/directories which match at least one pattern of the include pattern list or other file + * selector, and don't match any pattern of the exclude pattern list or fail to match against a required selector will + * be placed in the list of files/directories found. + * </p> + * <p> + * When no list of include patterns is supplied, "**" will be used, which means that everything will be matched. When no + * list of exclude patterns is supplied, an empty list is used, such that nothing will be excluded. When no selectors + * are supplied, none are applied. + * </p> + * <p> + * The filename pattern matching is done as follows: The name to be matched is split up in path segments. A path segment + * is the name of a directory or file, which is bounded by <code>File.separator</code> ('/' under UNIX, '\' under + * Windows). For example, "abc/def/ghi/xyz.java" is split up in the segments "abc", "def","ghi" and "xyz.java". The same + * is done for the pattern against which should be matched. + * </p> + * <p> + * The segments of the name and the pattern are then matched against each other. When '**' is used for a path segment in + * the pattern, it matches zero or more path segments of the name. + * </p> + * <p> + * There is a special case regarding the use of <code>File.separator</code>s at the beginning of the pattern and the + * string to match:<br> + * When a pattern starts with a <code>File.separator</code>, the string to match must also start with a + * <code>File.separator</code>. When a pattern does not start with a <code>File.separator</code>, the string to match + * may not start with a <code>File.separator</code>. When one of these rules is not obeyed, the string will not match. + * </p> + * <p> + * When a name path segment is matched against a pattern path segment, the following special characters can be used:<br> + * '*' matches zero or more characters<br> + * '?' matches one character. + * </p> + * <p> + * Examples: + * <ul> + * <li>"**\*.class" matches all .class files/dirs in a directory tree.</li> + * <li>"test\a??.java" matches all files/dirs which start with an 'a', then two more characters and then ".java", in a + * directory called test.</li> + * <li>"**" matches everything in a directory tree.</li> + * <li>"**\test\**\XYZ*" matches all files/dirs which start with "XYZ" and where there is a parent directory called test + * (e.g. "abc\test\def\ghi\XYZ123").</li> + * </ul> + * <p> + * Case sensitivity may be turned off if necessary. By default, it is turned on. + * </p> + * <p> + * Example of usage: + * </p> + * <pre> + * String[] includes = { "**\\*.class" }; + * String[] excludes = { "modules\\*\\**" }; + * ds.setIncludes( includes ); + * ds.setExcludes( excludes ); + * ds.setBasedir( new File( "test" ) ); + * ds.setCaseSensitive( true ); + * ds.scan(); + * + * System.out.println( "FILES:" ); + * String[] files = ds.getIncludedFiles(); + * for ( int i = 0; i < files.length; i++ ) + * { + * System.out.println( files[i] ); + * } + * </pre> + * <p> + * This will scan a directory called test for .class files, but excludes all files in all proper subdirectories of a + * directory called "modules" + * </p> + * <p> + * This class must not be used from multiple Threads concurrently! + * </p> + * + * @author Arnout J. Kuiper <a href="mailto:[email protected]">[email protected]</a> + * @author Magesh Umasankar + * @author <a href="mailto:[email protected]">Bruce Atherton</a> + * @author <a href="mailto:[email protected]">Antoine Levy-Lambert</a> + * <p>Copied from maven-shared-utils, so that surefire-api, which ends up on the test class path, needs no + * dependency for it. + */ +public class DirectoryScanner { + /** + * Patterns which should be excluded by default. + * + * @see #addDefaultExcludes() + */ + public static final String[] DEFAULTEXCLUDES = { + // Miscellaneous typical temporary files + "**/*~", + "**/#*#", + "**/.#*", + "**/%*%", + "**/._*", + + // CVS + "**/CVS", + "**/CVS/**", + "**/.cvsignore", + + // Subversion + "**/.svn", + "**/.svn/**", + + // Arch + "**/.arch-ids", + "**/.arch-ids/**", + + // Bazaar + "**/.bzr", + "**/.bzr/**", + + // SurroundSCM + "**/.MySCMServerInfo", + + // Mac + "**/.DS_Store", + + // Serena Dimensions Version 10 + "**/.metadata", + "**/.metadata/**", + + // Mercurial + "**/.hg", + "**/.hg/**", + + // git + "**/.git", + "**/.git/**", + + // BitKeeper + "**/BitKeeper", + "**/BitKeeper/**", + "**/ChangeSet", + "**/ChangeSet/**", + + // darcs + "**/_darcs", + "**/_darcs/**", + "**/.darcsrepo", + "**/.darcsrepo/**", + "**/-darcs-backup*", + "**/.darcs-temp-mail" + }; + + /** + * The base directory to be scanned. + */ + private File basedir; + + /** + * The patterns for the files to be included. + */ + private String[] includes; + + /** + * The patterns for the files to be excluded. + */ + private String[] excludes; + + private MatchPatterns excludesPatterns; + + private MatchPatterns includesPatterns; + + /** + * The files which matched at least one include and no excludes and were selected. + */ + private List<String> filesIncluded; + + /** + * The files which did not match any includes or selectors. + */ + private List<String> filesNotIncluded; + + /** + * The files which matched at least one include and at least one exclude. + */ + private List<String> filesExcluded; + + /** + * The directories which matched at least one include and no excludes and were selected. + */ + private List<String> dirsIncluded; + + /** + * The directories which were found and did not match any includes. + */ + private List<String> dirsNotIncluded; + + /** + * The directories which matched at least one include and at least one exclude. + */ + private List<String> dirsExcluded; + + /** + * Whether or not our results were built by a slow scan. + */ + private boolean haveSlowResults = false; + + /** + * Whether or not the file system should be treated as a case sensitive one. + */ + private boolean isCaseSensitive = true; + + /** + * Whether or not symbolic links should be followed. + */ + private boolean followSymlinks = true; + + /** + * A {@link ScanConductor} an control the scanning process. + */ + private ScanConductor scanConductor = null; + + /** + * The last ScanAction. We need to store this in the instance as the scan() method doesn't return. + */ + private ScanConductor.ScanAction scanAction = null; + + /** + * Sole constructor. + */ + public DirectoryScanner() {} + + /** + * Sets the base directory to be scanned. This is the directory which is scanned recursively. All '/' and '\' + * characters are replaced by <code>File.separatorChar</code>, so the separator used need not match + * <code>File.separatorChar</code>. + * + * @param basedir the base directory to scan. Must not be <code>null</code>. + */ + public void setBasedir(final String basedir) { + setBasedir(new File(basedir.replace('/', File.separatorChar).replace('\\', File.separatorChar))); + } + + /** + * Sets the base directory to be scanned. This is the directory which is scanned recursively. + * + * @param basedir the base directory for scanning. Should not be <code>null</code>. + */ + public void setBasedir(final File basedir) { + this.basedir = basedir; + } + + /** + * Returns the base directory to be scanned. This is the directory which is scanned recursively. + * + * @return the base directory to be scanned + */ + public File getBasedir() { + return basedir; + } + + /** + * Sets whether or not the file system should be regarded as case sensitive. + * + * @param isCaseSensitiveParameter whether or not the file system should be regarded as a case sensitive one + */ + public void setCaseSensitive(final boolean isCaseSensitiveParameter) { + this.isCaseSensitive = isCaseSensitiveParameter; + } + + /** + * Sets whether or not symbolic links should be followed. + * + * @param followSymlinks whether or not symbolic links should be followed + */ + public void setFollowSymlinks(final boolean followSymlinks) { + this.followSymlinks = followSymlinks; + } + + /** + * Sets the list of include patterns to use. All '/' and '\' characters are replaced by + * <code>File.separatorChar</code>, so the separator used need not match <code>File.separatorChar</code>. + * <p> + * When a pattern ends with a '/' or '\', "**" is appended. + * </p> + * + * @param includes a list of include patterns. May be <code>null</code>, indicating that all files should be + * included. If a non-<code>null</code> list is given, all elements must be non-<code>null</code>. + */ + public void setIncludes(final String... includes) { + if (includes == null) { + this.includes = null; + } else { + this.includes = new String[includes.length]; + for (int i = 0; i < includes.length; i++) { + if (includes[i] == null) { + throw new NullPointerException(messageForNullListElement("includes")); + } + String pattern; + pattern = includes[i].trim().replace('/', File.separatorChar).replace('\\', File.separatorChar); + if (pattern.endsWith(File.separator)) { + pattern += "**"; + } + this.includes[i] = pattern; + } + } + } + + /** + * Sets the list of exclude patterns to use. All '/' and '\' characters are replaced by + * <code>File.separatorChar</code>, so the separator used need not match <code>File.separatorChar</code>. + * <p> + * When a pattern ends with a '/' or '\', "**" is appended. + * </p> + * + * @param excludes a list of exclude patterns. May be <code>null</code>, indicating that no files should be + * excluded. If a non-<code>null</code> list is given, all elements must be non-<code>null</code>. + */ + public void setExcludes(final String... excludes) { + if (excludes == null) { + this.excludes = null; + } else { + this.excludes = new String[excludes.length]; + for (int i = 0; i < excludes.length; i++) { + if (excludes[i] == null) { + throw new NullPointerException(messageForNullListElement("excludes")); + } + String pattern; + pattern = excludes[i].trim().replace('/', File.separatorChar).replace('\\', File.separatorChar); + if (pattern.endsWith(File.separator)) { + pattern += "**"; + } + this.excludes[i] = pattern; + } + } + } + + private static String messageForNullListElement(String listName) { + return "If a non-null " + listName + " list is given, all elements must be non-null"; + } + + /** + * @param scanConductor {@link #scanConductor} + */ + public void setScanConductor(final ScanConductor scanConductor) { + this.scanConductor = scanConductor; + } + + /** + * Scans the base directory for files which match at least one include pattern and don't match any exclude patterns. + * If there are selectors then the files must pass muster there, as well. + * + * @throws IllegalStateException if the base directory was set incorrectly (i.e. if it is <code>null</code>, + * doesn't exist, or isn't a directory). + */ + public void scan() throws IllegalStateException { + if (basedir == null) { + throw new IllegalStateException("No basedir set"); + } + if (!basedir.exists()) { + throw new IllegalStateException("basedir " + basedir + " does not exist"); + } + if (!basedir.isDirectory()) { + throw new IllegalStateException("basedir " + basedir + " is not a directory"); + } + + setupDefaultFilters(); + setupMatchPatterns(); + + filesIncluded = new ArrayList<>(); + filesNotIncluded = new ArrayList<>(); + filesExcluded = new ArrayList<>(); + dirsIncluded = new ArrayList<>(); + dirsNotIncluded = new ArrayList<>(); + dirsExcluded = new ArrayList<>(); + scanAction = ScanConductor.ScanAction.CONTINUE; + + if (isIncluded("")) { + if (!isExcluded("")) { + if (scanConductor != null) { + scanAction = scanConductor.visitDirectory("", basedir); + + if (ScanConductor.ScanAction.ABORT.equals(scanAction) + || ScanConductor.ScanAction.ABORT_DIRECTORY.equals(scanAction) + || ScanConductor.ScanAction.NO_RECURSE.equals(scanAction)) { + return; + } + } + + dirsIncluded.add(""); + } else { + dirsExcluded.add(""); + } + } else { + dirsNotIncluded.add(""); + } + scandir(basedir, "", true); + } + + /** + * Determine the file differences between the currently included files and + * a previously captured list of files. + * This method will not look for a changed in content but sole in the + * list of files given. + * <p> + * The method will compare the given array of file Strings with the result + * of the last directory scan. It will execute a {@link #scan()} if no + * result of a previous scan could be found. + * </p> + * <p> + * The result of the diff can be queried by the methods + * {@link DirectoryScanResult#getFilesAdded()} and {@link DirectoryScanResult#getFilesRemoved()} + * </p> + * + * @param oldFiles the list of previously captured files names + * @return the result of the directory scan + */ + public DirectoryScanResult diffIncludedFiles(String... oldFiles) { + if (filesIncluded == null) { + // perform a scan if the directory didn't get scanned yet + scan(); + } + + return diffFiles(oldFiles, filesIncluded.toArray(new String[0])); + } + + /** + * @param oldFiles array of old files + * @param newFiles array of new files + * @return calculated difference + */ + public static DirectoryScanResult diffFiles(String[] oldFiles, String[] newFiles) { + Set<String> oldFileSet = arrayAsHashSet(oldFiles); + Set<String> newFileSet = arrayAsHashSet(newFiles); + + List<String> added = new ArrayList<>(); + List<String> removed = new ArrayList<>(); + + for (String oldFile : oldFileSet) { + if (!newFileSet.contains(oldFile)) { + removed.add(oldFile); + } + } + + for (String newFile : newFileSet) { + if (!oldFileSet.contains(newFile)) { + added.add(newFile); + } + } + + String[] filesAdded = added.toArray(new String[0]); + String[] filesRemoved = removed.toArray(new String[0]); + + return new DirectoryScanResult(filesAdded, filesRemoved); + } + + /** + * Take an array of type T and convert it into a HashSet of type T. + * If <code>null</code> or an empty array gets passed, an empty Set will be returned. + * + * @param array the array + * @return the filled HashSet of type T + */ + private static <T> Set<T> arrayAsHashSet(T[] array) { + if (array == null || array.length == 0) { + return Collections.emptySet(); + } + + Set<T> set = new HashSet<>(array.length); + Collections.addAll(set, array); + + return set; + } + + /** + * Top level invocation for a slow scan. A slow scan builds up a full list of excluded/included files/directories, + * whereas a fast scan will only have full results for included files, as it ignores directories which can't + * possibly hold any included files/directories. + * <p> + * Returns immediately if a slow scan has already been completed. + */ + private void slowScan() { + if (haveSlowResults) { + return; + } + + final String[] excl = dirsExcluded.toArray(new String[0]); + + final String[] notIncl = dirsNotIncluded.toArray(new String[0]); + + for (String anExcl : excl) { + if (!couldHoldIncluded(anExcl)) { + scandir(new File(basedir, anExcl), anExcl + File.separator, false); + } + } + + for (String aNotIncl : notIncl) { + if (!couldHoldIncluded(aNotIncl)) { + scandir(new File(basedir, aNotIncl), aNotIncl + File.separator, false); + } + } + + haveSlowResults = true; + } + + /** + * Scans the given directory for files and directories. Found files and directories are placed in their respective + * collections, based on the matching of includes, excludes, and the selectors. When a directory is found, it is + * scanned recursively. + * + * @param dir the directory to scan. Must not be <code>null</code>. + * @param vpath the path relative to the base directory (needed to prevent problems with an absolute path when using + * dir). Must not be <code>null</code>. + * @param fast whether this call is part of a fast scan + * @see #filesIncluded + * @see #filesNotIncluded + * @see #filesExcluded + * @see #dirsIncluded + * @see #dirsNotIncluded + * @see #dirsExcluded + * @see #slowScan + */ + private void scandir(final File dir, final String vpath, final boolean fast) { + String[] newfiles = dir.list(); + + if (newfiles == null) { + /* + * two reasons are mentioned in the API docs for File.list (1) dir is not a directory. This is impossible as + * we wouldn't get here in this case. (2) an IO error occurred (why doesn't it throw an exception then???) + */ + + /* + * [jdcasey] (2) is apparently happening to me, as this is killing one of my tests... this is affecting the + * assembly plugin, fwiw. I will initialize the newfiles array as zero-length for now. NOTE: I can't find + * the problematic code, as it appears to come from a native method in UnixFileSystem... + */ + newfiles = new String[0]; + } + + if (!followSymlinks) { + newfiles = doNotFollowSymbolicLinks(dir, vpath, newfiles); + } + + for (final String newfile : newfiles) { + final String name = vpath + newfile; + final File file = new File(dir, newfile); + if (file.isDirectory()) { + if (isIncluded(name)) { + if (!isExcluded(name)) { + if (scanConductor != null) { + scanAction = scanConductor.visitDirectory(name, file); + + if (ScanConductor.ScanAction.ABORT.equals(scanAction) + || ScanConductor.ScanAction.ABORT_DIRECTORY.equals(scanAction)) { + return; + } + } + + if (!ScanConductor.ScanAction.NO_RECURSE.equals(scanAction)) { + dirsIncluded.add(name); + if (fast) { + scandir(file, name + File.separator, fast); + + if (ScanConductor.ScanAction.ABORT.equals(scanAction)) { + return; + } + } + } + scanAction = null; + + } else { + dirsExcluded.add(name); + if (fast && couldHoldIncluded(name)) { + scandir(file, name + File.separator, fast); + if (ScanConductor.ScanAction.ABORT.equals(scanAction)) { + return; + } + scanAction = null; + } + } + } else { + if (fast && couldHoldIncluded(name)) { + if (scanConductor != null) { + scanAction = scanConductor.visitDirectory(name, file); + + if (ScanConductor.ScanAction.ABORT.equals(scanAction) + || ScanConductor.ScanAction.ABORT_DIRECTORY.equals(scanAction)) { + return; + } + } + if (!ScanConductor.ScanAction.NO_RECURSE.equals(scanAction)) { + dirsNotIncluded.add(name); + + scandir(file, name + File.separator, fast); + if (ScanConductor.ScanAction.ABORT.equals(scanAction)) { + return; + } + } + scanAction = null; + } + } + if (!fast) { + scandir(file, name + File.separator, fast); + if (ScanConductor.ScanAction.ABORT.equals(scanAction)) { + return; + } + scanAction = null; + } + } else if (file.isFile()) { + if (isIncluded(name)) { + if (!isExcluded(name)) { + if (scanConductor != null) { + scanAction = scanConductor.visitFile(name, file); + } + + if (ScanConductor.ScanAction.ABORT.equals(scanAction) + || ScanConductor.ScanAction.ABORT_DIRECTORY.equals(scanAction)) { + return; + } + + filesIncluded.add(name); + } else { + filesExcluded.add(name); + } + } else { + filesNotIncluded.add(name); + } + } + } + } + + private String[] doNotFollowSymbolicLinks(final File dir, final String vpath, final String[] newfiles) { + final List<String> noLinks = new ArrayList<>(); + for (final String newfile : newfiles) { + if (Files.isSymbolicLink(dir.toPath())) { + final String name = vpath + newfile; + final File file = new File(dir, newfile); + if (file.isDirectory()) { + dirsExcluded.add(name); + } else { + filesExcluded.add(name); + } + } else { + noLinks.add(newfile); + } + } + return noLinks.toArray(new String[0]); + } + + /** + * Tests whether or not a name matches at least one include pattern. + * + * @param name the name to match. Must not be <code>null</code>. + * @return <code>true</code> when the name matches at least one include pattern, or <code>false</code> + * otherwise + */ + private boolean isIncluded(final String name) { + return includesPatterns.matches(name, isCaseSensitive); + } + + /** + * Tests whether or not a name matches the start of at least one include pattern. + * + * @param name the name to match. Must not be <code>null</code>. + * @return <code>true</code> when the name matches against the start of at least one include pattern, or + * <code>false</code> otherwise + */ + private boolean couldHoldIncluded(final String name) { + return includesPatterns.matchesPatternStart(name, isCaseSensitive); + } + + /** + * Tests whether or not a name matches against at least one exclude pattern. + * + * @param name the name to match. Must not be <code>null</code>. + * @return <code>true</code> when the name matches against at least one exclude pattern, or <code>false</code> + * otherwise + */ + private boolean isExcluded(final String name) { + return excludesPatterns.matches(name, isCaseSensitive); + } + + /** + * Returns the names of the files which matched at least one of the include patterns and none of the exclude + * patterns. The names are relative to the base directory. + * + * @return the names of the files which matched at least one of the include patterns and none of the exclude + * patterns. May also contain symbolic links to files. + * @deprecated this method does not work correctly on Windows. + */ + @Deprecated + public String[] getIncludedFiles() { + if (filesIncluded == null) { + return new String[0]; + } + return filesIncluded.toArray(new String[0]); + } + + /** + * Returns the names of the files which matched none of the include patterns. The names are relative to the base + * directory. This involves performing a slow scan if one has not already been completed. + * + * @return the names of the files which matched none of the include patterns + * @see #slowScan + */ + public String[] getNotIncludedFiles() { + slowScan(); + return filesNotIncluded.toArray(new String[0]); + } + + /** + * Returns the names of the files which matched at least one of the include patterns and at least one of the exclude + * patterns. The names are relative to the base directory. This involves performing a slow scan if one has not + * already been completed. + * + * @return the names of the files which matched at least one of the include patterns and at at least one of the + * exclude patterns + * @see #slowScan + */ + public String[] getExcludedFiles() { + slowScan(); + return filesExcluded.toArray(new String[0]); + } + + /** + * Returns the names of the directories which matched at least one of the include patterns and none of the exclude + * patterns. The names are relative to the base directory. + * + * @return the names of the directories which matched at least one of the include patterns and none of the exclude + * patterns. May also contain symbolic links to directories. + * @deprecated this method is buggy. Do not depend on it. + */ + @Deprecated + public String[] getIncludedDirectories() { + return dirsIncluded.toArray(new String[0]); + } + + /** + * Returns the names of the directories which matched none of the include patterns. The names are relative to the + * base directory. This involves performing a slow scan if one has not already been completed. + * + * @return the names of the directories which matched none of the include patterns + * @see #slowScan + */ + public String[] getNotIncludedDirectories() { + slowScan(); + return dirsNotIncluded.toArray(new String[0]); + } + + /** + * Returns the names of the directories which matched at least one of the include patterns and at least one of the + * exclude patterns. The names are relative to the base directory. This involves performing a slow scan if one has + * not already been completed. + * + * @return the names of the directories which matched at least one of the include patterns and at least one of the + * exclude patterns + * @see #slowScan + */ + public String[] getExcludedDirectories() { + slowScan(); + return dirsExcluded.toArray(new String[0]); + } + + /** + * Adds default exclusions to the current exclusions set. + */ + public void addDefaultExcludes() { + final int excludesLength = excludes == null ? 0 : excludes.length; + String[] newExcludes = new String[excludesLength + DEFAULTEXCLUDES.length]; + if (excludesLength > 0) { + System.arraycopy(excludes, 0, newExcludes, 0, excludesLength); + } + for (int i = 0; i < DEFAULTEXCLUDES.length; i++) { + newExcludes[i + excludesLength] = + DEFAULTEXCLUDES[i].replace('/', File.separatorChar).replace('\\', File.separatorChar); + } + excludes = newExcludes; + } + + private void setupDefaultFilters() { + if (includes == null) { + // No includes supplied, so set it to 'matches all' + includes = new String[1]; + includes[0] = "**"; + } + if (excludes == null) { + excludes = new String[0]; + } + } + + private void setupMatchPatterns() { + includesPatterns = MatchPatterns.from(includes); + excludesPatterns = MatchPatterns.from(excludes); + } +} diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/MatchPattern.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/MatchPattern.java new file mode 100644 index 000000000..357d55b1b --- /dev/null +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/MatchPattern.java @@ -0,0 +1,133 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.surefire.api.util.internal; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.StringTokenizer; +import java.util.regex.Pattern; + +/** + * <p>Describes a match target for SelectorUtils.</p> + * <p> + * Significantly more efficient than using strings, since re-evaluation and re-tokenizing is avoided.</p> + * + * @author Kristian Rosenvold + * <p>Copied from maven-shared-utils, so that surefire-api, which ends up on the test class path, needs no + * dependency for it. + */ +public class MatchPattern { + private final String source; + + private final String regexPattern; + + private final Pattern regexPatternRegex; + + private final String separator; + + private final String[] tokenized; + + private MatchPattern(String source, String separator) { + regexPattern = SelectorUtils.isRegexPrefixedPattern(source) + ? source.substring( + SelectorUtils.REGEX_HANDLER_PREFIX.length(), + source.length() - SelectorUtils.PATTERN_HANDLER_SUFFIX.length()) + : null; + regexPatternRegex = regexPattern != null ? Pattern.compile(regexPattern) : null; + this.source = SelectorUtils.isAntPrefixedPattern(source) + ? source.substring( + SelectorUtils.ANT_HANDLER_PREFIX.length(), + source.length() - SelectorUtils.PATTERN_HANDLER_SUFFIX.length()) + : source; + this.separator = separator; + tokenized = tokenizePathToString(this.source, separator); + } + + /** + * @param str the string to match for + * @param isCaseSensitive case sensitive true false otherwise + * @return true if matches false otherwise + */ + public boolean matchPath(String str, boolean isCaseSensitive) { + if (regexPattern != null) { + return regexPatternRegex.matcher(str).matches(); + } else { + return SelectorUtils.matchAntPathPattern(this, str, separator, isCaseSensitive); + } + } + + boolean matchPath(String str, String[] strDirs, boolean isCaseSensitive) { + if (regexPattern != null) { + return regexPatternRegex.matcher(str).matches(); + } else { + return SelectorUtils.matchAntPathPattern(getTokenizedPathString(), strDirs, isCaseSensitive); + } + } + + /** + * @param str the string to check + * @param isCaseSensitive check case sensitive or not + * @return true in case of matching pattern + */ + public boolean matchPatternStart(String str, boolean isCaseSensitive) { + if (regexPattern != null) { + // FIXME: ICK! But we can't do partial matches for regex, so we have to reserve judgment until we have + // a file to deal with, or we can definitely say this is an exclusion... + return true; + } else { + String altStr = source.replace('\\', '/'); + + return SelectorUtils.matchAntPathPatternStart(this, str, File.separator, isCaseSensitive) + || SelectorUtils.matchAntPathPatternStart(this, altStr, "/", isCaseSensitive); + } + } + + /** + * @return tokenized string + */ + public String[] getTokenizedPathString() { + return tokenized; + } + + /** + * @param string the part which will be checked to start with + * @return true in case of starting with the string false otherwise + */ + public boolean startsWith(String string) { + return source.startsWith(string); + } + + static String[] tokenizePathToString(String path, String separator) { + List<String> ret = new ArrayList<>(); + StringTokenizer st = new StringTokenizer(path, separator); + while (st.hasMoreTokens()) { + ret.add(st.nextToken()); + } + return ret.toArray(new String[ret.size()]); + } + + /** + * @param source the source + * @return the match pattern + */ + public static MatchPattern fromString(String source) { + return new MatchPattern(source, File.separator); + } +} diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/MatchPatterns.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/MatchPatterns.java new file mode 100644 index 000000000..426377709 --- /dev/null +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/MatchPatterns.java @@ -0,0 +1,81 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.surefire.api.util.internal; + +import java.io.File; + +/** + * A list of patterns to be matched. + * + * @author Kristian Rosenvold + * <p>Copied from maven-shared-utils, so that surefire-api, which ends up on the test class path, needs no + * dependency for it. + */ +public class MatchPatterns { + private final MatchPattern[] patterns; + + private MatchPatterns(MatchPattern... patterns) { + this.patterns = patterns; + } + + /** + * <p>Checks these MatchPatterns against a specified string.</p> + * <p>Uses far less string tokenization than any of the alternatives.</p> + * + * @param name the name to look for + * @param isCaseSensitive if the comparison is case sensitive + * @return true if any of the supplied patterns match + */ + public boolean matches(String name, boolean isCaseSensitive) { + String[] tokenized = MatchPattern.tokenizePathToString(name, File.separator); + for (MatchPattern pattern : patterns) { + if (pattern.matchPath(name, tokenized, isCaseSensitive)) { + return true; + } + } + return false; + } + + /** + * @param name the name + * @param isCaseSensitive being case sensetive + * @return true if any of the supplied patterns match start + */ + public boolean matchesPatternStart(String name, boolean isCaseSensitive) { + for (MatchPattern includesPattern : patterns) { + if (includesPattern.matchPatternStart(name, isCaseSensitive)) { + return true; + } + } + return false; + } + + /** + * @param sources the sources + * @return converted match patterns + */ + public static MatchPatterns from(String... sources) { + final int length = sources.length; + MatchPattern[] result = new MatchPattern[length]; + for (int i = 0; i < length; i++) { + result[i] = MatchPattern.fromString(sources[i]); + } + return new MatchPatterns(result); + } +} diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/ScanConductor.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/ScanConductor.java new file mode 100644 index 000000000..430746b61 --- /dev/null +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/ScanConductor.java @@ -0,0 +1,81 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.surefire.api.util.internal; + +import java.io.File; + +/** + * <p>Visitor pattern for the DirectoryScanner. A ScanConductor controls the scanning process.</p> + * <p>Create an instance and pass it to + * {@link org.apache.maven.surefire.api.util.internal.DirectoryScanner#setScanConductor(ScanConductor)}. + * You will get notified about every visited directory and file. You can use the {@link ScanAction} + * to control what should happen next.</p> + * <p>A ScanConductor might also store own information but users must make sure that the state gets + * cleaned between two scan() invocations.</p> + * + * @author <a href="mailto:[email protected]">Mark Struberg</a> + * <p>Copied from maven-shared-utils, so that surefire-api, which ends up on the test class path, needs no + * dependency for it. + */ +public interface ScanConductor { + enum ScanAction { + /** + * Abort the whole scanning process. The current file will not + * be added anymore. + */ + ABORT, + + /** + * Continue the scanning with the next item in the list. + */ + CONTINUE, + + /** + * This response is only valid for {@link ScanConductor#visitDirectory(String, java.io.File)}. + * Do not recurse into the current directory. The current directory will not be added + * and the processing will be continued with the next item in the list. + */ + NO_RECURSE, + + /** + * Abort processing the current directory. + * The current file will not be added. + * The processing will continue it's scan in the parent directory if any. + */ + ABORT_DIRECTORY + } + + /** + * This method will get invoked for every detected directory. + * + * @param name the directory name (contains parent folders up to the pwd) + * @param directory the directory + * @return the ScanAction to control how to proceed with the scanning + */ + ScanAction visitDirectory(String name, File directory); + + /** + * This method will get invoked for every detected file. + * + * @param name the file name (contains parent folders up to the pwd) + * @param file the file + * @return the ScanAction to control how to proceed with the scanning + */ + ScanAction visitFile(String name, File file); +} diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/SelectorUtils.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/SelectorUtils.java new file mode 100644 index 000000000..1b2344143 --- /dev/null +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/SelectorUtils.java @@ -0,0 +1,690 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.surefire.api.util.internal; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.StringTokenizer; + +/** + * <p>This is a utility class used by selectors and DirectoryScanner. The + * functionality more properly belongs just to selectors, but unfortunately + * DirectoryScanner exposed these as protected methods. Thus we have to + * support any subclasses of DirectoryScanner that may access these methods. + * </p> + * <p>This is a Singleton.</p> + * + * @author Arnout J. Kuiper + * <a href="mailto:[email protected]">[email protected]</a> + * @author Magesh Umasankar + * @author <a href="mailto:[email protected]">Bruce Atherton</a> + * <p>Copied from maven-shared-utils, so that surefire-api, which ends up on the test class path, needs no + * dependency for it. + */ +public final class SelectorUtils { + + /** + * Pattern handler prefix. + */ + private static final String PATTERN_HANDLER_PREFIX = "["; + + /** + * Pattern handler suffix. + */ + public static final String PATTERN_HANDLER_SUFFIX = "]"; + + /** + * Regex start pattern. + */ + public static final String REGEX_HANDLER_PREFIX = "%regex" + PATTERN_HANDLER_PREFIX; + + /** + * ANT pattern prefix. + */ + public static final String ANT_HANDLER_PREFIX = "%ant" + PATTERN_HANDLER_PREFIX; + + /** + * Private Constructor. + */ + private SelectorUtils() {} + + /** + * <p>Tests whether or not a given path matches the start of a given + * pattern up to the first "**".</p> + * <p> + * This is not a general purpose test and should only be used if you + * can live with false positives. For example, <code>pattern=**\a</code> + * and <code>str=b</code> will yield <code>true</code>.</p> + * + * @param pattern the pattern to match against. Must not be + * <code>null</code>. + * @param str the path to match, as a String. Must not be + * <code>null</code>. + * @return whether or not a given path matches the start of a given + * pattern up to the first "**" + */ + public static boolean matchPatternStart(String pattern, String str) { + return matchPatternStart(pattern, str, true); + } + + /** + * <p>Tests whether or not a given path matches the start of a given + * pattern up to the first "**".</p> + * <p>This is not a general purpose test and should only be used if you + * can live with false positives. For example, <code>pattern=**\a</code> + * and <code>str=b</code> will yield <code>true</code>.</p> + * + * @param pattern the pattern to match against. Must not be + * <code>null</code>. + * @param str the path to match, as a String. Must not be + * <code>null</code>. + * @param isCaseSensitive whether or not matching should be performed + * case sensitively + * @return whether or not a given path matches the start of a given + * pattern up to the first "**" + */ + public static boolean matchPatternStart(String pattern, String str, boolean isCaseSensitive) { + if (isRegexPrefixedPattern(pattern)) { + // FIXME: ICK! But we can't do partial matches for regex, so we have to reserve judgement until we have + // a file to deal with, or we can definitely say this is an exclusion... + return true; + } else { + if (isAntPrefixedPattern(pattern)) { + pattern = pattern.substring( + ANT_HANDLER_PREFIX.length(), pattern.length() - PATTERN_HANDLER_SUFFIX.length()); + } + + String altPattern = pattern.replace('\\', '/'); + String altStr = str.replace('\\', '/'); + + return matchAntPathPatternStart(altPattern, altStr, "/", isCaseSensitive); + } + } + + private static boolean matchAntPathPatternStart( + String pattern, String str, String separator, boolean isCaseSensitive) { + // When str starts with a File.separator, pattern has to start with a + // File.separator. + // When pattern starts with a File.separator, str has to start with a + // File.separator. + if (separatorPatternStartSlashMismatch(pattern, str, separator)) { + return false; + } + + List<String> patDirs = tokenizePath(pattern, separator); + List<String> strDirs = tokenizePath(str, separator); + + int patIdxStart = 0; + int patIdxEnd = patDirs.size() - 1; + int strIdxStart = 0; + int strIdxEnd = strDirs.size() - 1; + + // up to first '**' + while (patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd) { + String patDir = patDirs.get(patIdxStart); + if ("**".equals(patDir)) { + break; + } + if (!match(patDir, strDirs.get(strIdxStart), isCaseSensitive)) { + return false; + } + patIdxStart++; + strIdxStart++; + } + + return strIdxStart > strIdxEnd || patIdxStart <= patIdxEnd; + } + + /** + * Tests whether or not a given path matches a given pattern. + * + * @param pattern the pattern to match against. Must not be + * <code>null</code>. + * @param str the path to match, as a String. Must not be + * <code>null</code>. + * @return <code>true</code> if the pattern matches against the string, + * or <code>false</code> otherwise + */ + public static boolean matchPath(String pattern, String str) { + return matchPath(pattern, str, true); + } + + /** + * Tests whether or not a given path matches a given pattern. + * + * @param pattern the pattern to match against. Must not be + * <code>null</code>. + * @param str the path to match, as a String. Must not be + * <code>null</code>. + * @param isCaseSensitive whether or not matching should be performed + * case sensitively + * @return <code>true</code> if the pattern matches against the string, + * or <code>false</code> otherwise + */ + public static boolean matchPath(String pattern, String str, boolean isCaseSensitive) { + if (pattern.length() > (REGEX_HANDLER_PREFIX.length() + PATTERN_HANDLER_SUFFIX.length() + 1) + && pattern.startsWith(REGEX_HANDLER_PREFIX) + && pattern.endsWith(PATTERN_HANDLER_SUFFIX)) { + pattern = pattern.substring( + REGEX_HANDLER_PREFIX.length(), pattern.length() - PATTERN_HANDLER_SUFFIX.length()); + + return str.matches(pattern); + } else { + if (pattern.length() > (ANT_HANDLER_PREFIX.length() + PATTERN_HANDLER_SUFFIX.length() + 1) + && pattern.startsWith(ANT_HANDLER_PREFIX) + && pattern.endsWith(PATTERN_HANDLER_SUFFIX)) { + pattern = pattern.substring( + ANT_HANDLER_PREFIX.length(), pattern.length() - PATTERN_HANDLER_SUFFIX.length()); + } + + return matchAntPathPattern(pattern, str, isCaseSensitive); + } + } + + private static boolean matchAntPathPattern(String pattern, String str, boolean isCaseSensitive) { + // When str starts with a File.separator, pattern has to start with a + // File.separator. + // When pattern starts with a File.separator, str has to start with a + // File.separator. + if (str.startsWith(File.separator) != pattern.startsWith(File.separator)) { + return false; + } + + List<String> patDirs = tokenizePath(pattern, File.separator); + List<String> strDirs = tokenizePath(str, File.separator); + + int patIdxStart = 0; + int patIdxEnd = patDirs.size() - 1; + int strIdxStart = 0; + int strIdxEnd = strDirs.size() - 1; + + // up to first '**' + while (patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd) { + String patDir = patDirs.get(patIdxStart); + if ("**".equals(patDir)) { + break; + } + if (!match(patDir, strDirs.get(strIdxStart), isCaseSensitive)) { + return false; + } + patIdxStart++; + strIdxStart++; + } + if (strIdxStart > strIdxEnd) { + // String is exhausted + for (int i = patIdxStart; i <= patIdxEnd; i++) { + if (!"**".equals(patDirs.get(i))) { + return false; + } + } + return true; + } else { + if (patIdxStart > patIdxEnd) { + // String not exhausted, but pattern is. Failure. + return false; + } + } + + // up to last '**' + while (patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd) { + String patDir = patDirs.get(patIdxEnd); + if ("**".equals(patDir)) { + break; + } + if (!match(patDir, strDirs.get(strIdxEnd), isCaseSensitive)) { + return false; + } + patIdxEnd--; + strIdxEnd--; + } + if (strIdxStart > strIdxEnd) { + // String is exhausted + for (int i = patIdxStart; i <= patIdxEnd; i++) { + if (!"**".equals(patDirs.get(i))) { + return false; + } + } + return true; + } + + while (patIdxStart != patIdxEnd && strIdxStart <= strIdxEnd) { + int patIdxTmp = -1; + for (int i = patIdxStart + 1; i <= patIdxEnd; i++) { + if ("**".equals(patDirs.get(i))) { + patIdxTmp = i; + break; + } + } + if (patIdxTmp == patIdxStart + 1) { + // '**/**' situation, so skip one + patIdxStart++; + continue; + } + // Find the pattern between padIdxStart & padIdxTmp in str between + // strIdxStart & strIdxEnd + int patLength = (patIdxTmp - patIdxStart - 1); + int strLength = (strIdxEnd - strIdxStart + 1); + int foundIdx = -1; + strLoop: + for (int i = 0; i <= strLength - patLength; i++) { + for (int j = 0; j < patLength; j++) { + String subPat = patDirs.get(patIdxStart + j + 1); + String subStr = strDirs.get(strIdxStart + i + j); + if (!match(subPat, subStr, isCaseSensitive)) { + continue strLoop; + } + } + + foundIdx = strIdxStart + i; + break; + } + + if (foundIdx == -1) { + return false; + } + + patIdxStart = patIdxTmp; + strIdxStart = foundIdx + patLength; + } + + for (int i = patIdxStart; i <= patIdxEnd; i++) { + if (!"**".equals(patDirs.get(i))) { + return false; + } + } + + return true; + } + + /** + * Tests whether or not a string matches against a pattern. + * The pattern may contain two special characters:<br> + * '*' means zero or more characters<br> + * '?' means one and only one character. + * + * @param pattern the pattern to match against. + * Must not be <code>null</code>. + * @param str the string which must be matched against the pattern. + * Must not be <code>null</code>. + * @return <code>true</code> if the string matches against the pattern, + * or <code>false</code> otherwise + */ + public static boolean match(String pattern, String str) { + return match(pattern, str, true); + } + + /** + * Tests whether or not a string matches against a pattern. + * The pattern may contain two special characters:<br> + * '*' means zero or more characters<br> + * '?' means one and only one character. + * + * @param pattern the pattern to match against. + * Must not be <code>null</code>. + * @param str the string which must be matched against the pattern. + * Must not be <code>null</code>. + * @param isCaseSensitive whether or not matching should be performed + * case sensitively + * @return <code>true</code> if the string matches against the pattern, + * or <code>false</code> otherwise + */ + public static boolean match(String pattern, String str, boolean isCaseSensitive) { + char[] patArr = pattern.toCharArray(); + char[] strArr = str.toCharArray(); + int patIdxStart = 0; + int patIdxEnd = patArr.length - 1; + int strIdxStart = 0; + int strIdxEnd = strArr.length - 1; + char ch; + + boolean containsStar = false; + for (char aPatArr : patArr) { + if (aPatArr == '*') { + containsStar = true; + break; + } + } + + if (!containsStar) { + // No '*'s, so we make a shortcut + if (patIdxEnd != strIdxEnd) { + return false; // Pattern and string do not have the same size + } + for (int i = 0; i <= patIdxEnd; i++) { + ch = patArr[i]; + if (ch != '?' && !equals(ch, strArr[i], isCaseSensitive)) { + return false; // Character mismatch + } + } + return true; // String matches against pattern + } + + if (patIdxEnd == 0) { + return true; // Pattern contains only '*', which matches anything + } + + // Process characters before first star + // CHECKSTYLE_OFF: InnerAssignment + while ((ch = patArr[patIdxStart]) != '*' && strIdxStart <= strIdxEnd) + // CHECKSTYLE_ON: InnerAssignment + { + if (ch != '?' && !equals(ch, strArr[strIdxStart], isCaseSensitive)) { + return false; // Character mismatch + } + patIdxStart++; + strIdxStart++; + } + if (strIdxStart > strIdxEnd) { + // All characters in the string are used. Check if only '*'s are + // left in the pattern. If so, we succeeded. Otherwise failure. + for (int i = patIdxStart; i <= patIdxEnd; i++) { + if (patArr[i] != '*') { + return false; + } + } + return true; + } + + // Process characters after last star + // CHECKSTYLE_OFF: InnerAssignment + while ((ch = patArr[patIdxEnd]) != '*' && strIdxStart <= strIdxEnd) + // CHECKSTYLE_ON: InnerAssignment + { + if (ch != '?' && !equals(ch, strArr[strIdxEnd], isCaseSensitive)) { + return false; // Character mismatch + } + patIdxEnd--; + strIdxEnd--; + } + if (strIdxStart > strIdxEnd) { + // All characters in the string are used. Check if only '*'s are + // left in the pattern. If so, we succeeded. Otherwise failure. + for (int i = patIdxStart; i <= patIdxEnd; i++) { + if (patArr[i] != '*') { + return false; + } + } + return true; + } + + // process pattern between stars. padIdxStart and patIdxEnd point + // always to a '*'. + while (patIdxStart != patIdxEnd && strIdxStart <= strIdxEnd) { + int patIdxTmp = -1; + for (int i = patIdxStart + 1; i <= patIdxEnd; i++) { + if (patArr[i] == '*') { + patIdxTmp = i; + break; + } + } + if (patIdxTmp == patIdxStart + 1) { + // Two stars next to each other, skip the first one. + patIdxStart++; + continue; + } + // Find the pattern between padIdxStart & padIdxTmp in str between + // strIdxStart & strIdxEnd + int patLength = (patIdxTmp - patIdxStart - 1); + int strLength = (strIdxEnd - strIdxStart + 1); + int foundIdx = -1; + strLoop: + for (int i = 0; i <= strLength - patLength; i++) { + for (int j = 0; j < patLength; j++) { + ch = patArr[patIdxStart + j + 1]; + if (ch != '?' && !equals(ch, strArr[strIdxStart + i + j], isCaseSensitive)) { + continue strLoop; + } + } + + foundIdx = strIdxStart + i; + break; + } + + if (foundIdx == -1) { + return false; + } + + patIdxStart = patIdxTmp; + strIdxStart = foundIdx + patLength; + } + + // All characters in the string are used. Check if only '*'s are left + // in the pattern. If so, we succeeded. Otherwise failure. + for (int i = patIdxStart; i <= patIdxEnd; i++) { + if (patArr[i] != '*') { + return false; + } + } + return true; + } + + /** + * Tests whether two characters are equal. + */ + private static boolean equals(char c1, char c2, boolean isCaseSensitive) { + if (c1 == c2) { + return true; + } + if (!isCaseSensitive) { + // NOTE: Try both upper case and lower case as done by String.equalsIgnoreCase() + if (Character.toUpperCase(c1) == Character.toUpperCase(c2) + || Character.toLowerCase(c1) == Character.toLowerCase(c2)) { + return true; + } + } + return false; + } + + /** + * Breaks a path up into a List of path elements, tokenizing on + * <code>File.separator</code>. + * + * @param path path to tokenize. Must not be <code>null</code>. + * @param separator the separator to use + * @return a List of path elements from the tokenized path + */ + private static List<String> tokenizePath(String path, String separator) { + List<String> ret = new ArrayList<>(); + StringTokenizer st = new StringTokenizer(path, separator); + while (st.hasMoreTokens()) { + ret.add(st.nextToken()); + } + return ret; + } + + static boolean matchAntPathPatternStart( + MatchPattern pattern, String str, String separator, boolean isCaseSensitive) { + return !separatorPatternStartSlashMismatch(pattern, str, separator) + && matchAntPathPatternStart(pattern.getTokenizedPathString(), str, separator, isCaseSensitive); + } + + private static String[] tokenizePathToString(String path, String separator) { + List<String> ret = new ArrayList<>(); + StringTokenizer st = new StringTokenizer(path, separator); + while (st.hasMoreTokens()) { + ret.add(st.nextToken()); + } + return ret.toArray(new String[ret.size()]); + } + + private static boolean matchAntPathPatternStart( + String[] patDirs, String str, String separator, boolean isCaseSensitive) { + String[] strDirs = tokenizePathToString(str, separator); + return matchAntPathPatternStart(patDirs, strDirs, isCaseSensitive); + } + + private static boolean matchAntPathPatternStart( + String[] patDirs, String[] tokenizedFileName, boolean isCaseSensitive) { + + int patIdxStart = 0; + int patIdxEnd = patDirs.length - 1; + int strIdxStart = 0; + int strIdxEnd = tokenizedFileName.length - 1; + + // up to first '**' + while (patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd) { + String patDir = patDirs[patIdxStart]; + if (patDir.equals("**")) { + break; + } + if (!match(patDir, tokenizedFileName[strIdxStart], isCaseSensitive)) { + return false; + } + patIdxStart++; + strIdxStart++; + } + + return strIdxStart > strIdxEnd || patIdxStart <= patIdxEnd; + } + + private static boolean separatorPatternStartSlashMismatch(MatchPattern matchPattern, String str, String separator) { + return str.startsWith(separator) != matchPattern.startsWith(separator); + } + + private static boolean separatorPatternStartSlashMismatch(String pattern, String str, String separator) { + return str.startsWith(separator) != pattern.startsWith(separator); + } + + static boolean matchAntPathPattern(String[] patDirs, String[] strDirs, boolean isCaseSensitive) { + int patIdxStart = 0; + int patIdxEnd = patDirs.length - 1; + int strIdxStart = 0; + int strIdxEnd = strDirs.length - 1; + + // up to first '**' + while (patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd) { + String patDir = patDirs[patIdxStart]; + if (patDir.equals("**")) { + break; + } + if (!match(patDir, strDirs[strIdxStart], isCaseSensitive)) { + return false; + } + patIdxStart++; + strIdxStart++; + } + if (strIdxStart > strIdxEnd) { + // String is exhausted + for (int i = patIdxStart; i <= patIdxEnd; i++) { + if (!patDirs[i].equals("**")) { + return false; + } + } + return true; + } else { + if (patIdxStart > patIdxEnd) { + // String not exhausted, but pattern is. Failure. + return false; + } + } + + // up to last '**' + while (patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd) { + String patDir = patDirs[patIdxEnd]; + if (patDir.equals("**")) { + break; + } + if (!match(patDir, strDirs[strIdxEnd], isCaseSensitive)) { + return false; + } + patIdxEnd--; + strIdxEnd--; + } + if (strIdxStart > strIdxEnd) { + // String is exhausted + for (int i = patIdxStart; i <= patIdxEnd; i++) { + if (!patDirs[i].equals("**")) { + return false; + } + } + return true; + } + + while (patIdxStart != patIdxEnd && strIdxStart <= strIdxEnd) { + int patIdxTmp = -1; + for (int i = patIdxStart + 1; i <= patIdxEnd; i++) { + if (patDirs[i].equals("**")) { + patIdxTmp = i; + break; + } + } + if (patIdxTmp == patIdxStart + 1) { + // '**/**' situation, so skip one + patIdxStart++; + continue; + } + // Find the pattern between padIdxStart & padIdxTmp in str between + // strIdxStart & strIdxEnd + int patLength = (patIdxTmp - patIdxStart - 1); + int strLength = (strIdxEnd - strIdxStart + 1); + int foundIdx = -1; + strLoop: + for (int i = 0; i <= strLength - patLength; i++) { + for (int j = 0; j < patLength; j++) { + String subPat = patDirs[patIdxStart + j + 1]; + String subStr = strDirs[strIdxStart + i + j]; + if (!match(subPat, subStr, isCaseSensitive)) { + continue strLoop; + } + } + + foundIdx = strIdxStart + i; + break; + } + + if (foundIdx == -1) { + return false; + } + + patIdxStart = patIdxTmp; + strIdxStart = foundIdx + patLength; + } + + for (int i = patIdxStart; i <= patIdxEnd; i++) { + if (!patDirs[i].equals("**")) { + return false; + } + } + + return true; + } + + static boolean isRegexPrefixedPattern(String pattern) { + return pattern.length() > (REGEX_HANDLER_PREFIX.length() + PATTERN_HANDLER_SUFFIX.length() + 1) + && pattern.startsWith(REGEX_HANDLER_PREFIX) + && pattern.endsWith(PATTERN_HANDLER_SUFFIX); + } + + static boolean isAntPrefixedPattern(String pattern) { + return pattern.length() > (ANT_HANDLER_PREFIX.length() + PATTERN_HANDLER_SUFFIX.length() + 1) + && pattern.startsWith(ANT_HANDLER_PREFIX) + && pattern.endsWith(PATTERN_HANDLER_SUFFIX); + } + + static boolean matchAntPathPattern( + MatchPattern matchPattern, String str, String separator, boolean isCaseSensitive) { + if (separatorPatternStartSlashMismatch(matchPattern, str, separator)) { + return false; + } + String[] patDirs = matchPattern.getTokenizedPathString(); + String[] strDirs = tokenizePathToString(str, separator); + return matchAntPathPattern(patDirs, strDirs, isCaseSensitive); + } +}
