Search in sources :

Example 1 with PatternSet

use of org.apache.tools.ant.types.PatternSet in project gcontracts by andresteingress.

the class ContractGroovyDoc method parsePackages.

/**
 * Add the directories matched by the nested dirsets to the resulting
 * packages list and the base directories of the dirsets to the Path.
 * It also handles the packages and excludepackages attributes and
 * elements.
 *
 * @param resultantPackages a list to which we add the packages found
 * @param sourcePath a path to which we add each basedir found
 * @since 1.5
 */
private void parsePackages(List<String> resultantPackages, Path sourcePath) {
    List<String> addedPackages = new ArrayList<String>();
    List<DirSet> dirSets = new ArrayList<DirSet>(packageSets);
    // and nested excludepackage elements
    if (this.sourcePath != null) {
        PatternSet ps = new PatternSet();
        if (packageNames.size() > 0) {
            for (String pn : packageNames) {
                String pkg = pn.replace('.', '/');
                if (pkg.endsWith("*")) {
                    pkg += "*";
                }
                ps.createInclude().setName(pkg);
            }
        } else {
            ps.createInclude().setName("**");
        }
        for (String epn : excludePackageNames) {
            String pkg = epn.replace('.', '/');
            if (pkg.endsWith("*")) {
                pkg += "*";
            }
            ps.createExclude().setName(pkg);
        }
        String[] pathElements = this.sourcePath.list();
        for (String pathElement : pathElements) {
            File dir = new File(pathElement);
            if (dir.isDirectory()) {
                DirSet ds = new DirSet();
                ds.setDefaultexcludes(useDefaultExcludes);
                ds.setDir(dir);
                ds.createPatternSet().addConfiguredPatternset(ps);
                dirSets.add(ds);
            } else {
                log.warn("Skipping " + pathElement + " since it is no directory.");
            }
        }
    }
    for (DirSet ds : dirSets) {
        File baseDir = ds.getDir(getProject());
        log.debug("scanning " + baseDir + " for packages.");
        DirectoryScanner dsc = ds.getDirectoryScanner(getProject());
        String[] dirs = dsc.getIncludedDirectories();
        boolean containsPackages = false;
        for (String dir : dirs) {
            // are there any groovy or java files in this directory?
            File pd = new File(baseDir, dir);
            String[] files = pd.list(new FilenameFilter() {

                public boolean accept(File dir1, String name) {
                    if (!includeNoSourcePackages && name.equals("package.html"))
                        return true;
                    final StringTokenizer tokenizer = new StringTokenizer(extensions, ":");
                    while (tokenizer.hasMoreTokens()) {
                        String ext = tokenizer.nextToken();
                        if (name.endsWith(ext))
                            return true;
                    }
                    return false;
                }
            });
            for (String filename : Arrays.asList(files)) {
                sourceFilesToDoc.add(dir + File.separator + filename);
            }
            if (files.length > 0) {
                if ("".equals(dir)) {
                    log.warn(baseDir + " contains source files in the default package," + " you must specify them as source files not packages.");
                } else {
                    containsPackages = true;
                    String pn = dir.replace(File.separatorChar, '.');
                    if (!addedPackages.contains(pn)) {
                        addedPackages.add(pn);
                        resultantPackages.add(pn);
                    }
                }
            }
        }
        if (containsPackages) {
            // We don't need to care for duplicates here,
            // Path.list does it for us.
            sourcePath.createPathElement().setLocation(baseDir);
        } else {
            log.verbose(baseDir + " doesn't contain any packages, dropping it.");
        }
    }
}
Also used : FilenameFilter(java.io.FilenameFilter) DirSet(org.apache.tools.ant.types.DirSet) DirectoryScanner(org.apache.tools.ant.DirectoryScanner) PatternSet(org.apache.tools.ant.types.PatternSet) File(java.io.File)

Example 2 with PatternSet

use of org.apache.tools.ant.types.PatternSet in project ant by apache.

the class Files method mergePatterns.

/**
 * Get the merged patterns for this Files collection.
 * @param p Project instance.
 * @return the default patternset merged with the additional sets
 * in a new PatternSet instance.
 */
public synchronized PatternSet mergePatterns(Project p) {
    if (isReference()) {
        return getRef().mergePatterns(p);
    }
    dieOnCircularReference();
    PatternSet ps = new PatternSet();
    ps.append(defaultPatterns, p);
    additionalPatterns.forEach(pat -> ps.append(pat, p));
    return ps;
}
Also used : PatternSet(org.apache.tools.ant.types.PatternSet)

Example 3 with PatternSet

use of org.apache.tools.ant.types.PatternSet in project ant by apache.

the class Files method ensureDirectoryScannerSetup.

private synchronized void ensureDirectoryScannerSetup() {
    dieOnCircularReference();
    if (ds == null) {
        ds = new DirectoryScanner();
        PatternSet ps = mergePatterns(getProject());
        ds.setIncludes(ps.getIncludePatterns(getProject()));
        ds.setExcludes(ps.getExcludePatterns(getProject()));
        ds.setSelectors(getSelectors(getProject()));
        if (useDefaultExcludes) {
            ds.addDefaultExcludes();
        }
        ds.setCaseSensitive(caseSensitive);
        ds.setFollowSymlinks(followSymlinks);
    }
}
Also used : DirectoryScanner(org.apache.tools.ant.DirectoryScanner) PatternSet(org.apache.tools.ant.types.PatternSet)

Example 4 with PatternSet

use of org.apache.tools.ant.types.PatternSet in project ant by apache.

the class Expand method extractFile.

// CheckStyle:ParameterNumberCheck OFF - bc
/**
 * extract a file to a directory
 * @param fileUtils             a fileUtils object
 * @param srcF                  the source file
 * @param dir                   the destination directory
 * @param compressedInputStream the input stream
 * @param entryName             the name of the entry
 * @param entryDate             the date of the entry
 * @param isDirectory           if this is true the entry is a directory
 * @param mapper                the filename mapper to use
 * @throws IOException on error
 */
protected void extractFile(FileUtils fileUtils, File srcF, File dir, InputStream compressedInputStream, String entryName, Date entryDate, boolean isDirectory, FileNameMapper mapper) throws IOException {
    if (stripAbsolutePathSpec && !entryName.isEmpty() && (entryName.charAt(0) == File.separatorChar || entryName.charAt(0) == '/' || entryName.charAt(0) == '\\')) {
        log("stripped absolute path spec from " + entryName, Project.MSG_VERBOSE);
        entryName = entryName.substring(1);
    }
    if (patternsets != null && !patternsets.isEmpty()) {
        String name = entryName.replace('/', File.separatorChar).replace('\\', File.separatorChar);
        boolean included = false;
        Set<String> includePatterns = new HashSet<>();
        Set<String> excludePatterns = new HashSet<>();
        for (PatternSet p : patternsets) {
            String[] incls = p.getIncludePatterns(getProject());
            if (incls == null || incls.length == 0) {
                // no include pattern implicitly means includes="**"
                incls = new String[] { "**" };
            }
            for (String incl : incls) {
                String pattern = incl.replace('/', File.separatorChar).replace('\\', File.separatorChar);
                if (pattern.endsWith(File.separator)) {
                    pattern += "**";
                }
                includePatterns.add(pattern);
            }
            String[] excls = p.getExcludePatterns(getProject());
            if (excls != null) {
                for (String excl : excls) {
                    String pattern = excl.replace('/', File.separatorChar).replace('\\', File.separatorChar);
                    if (pattern.endsWith(File.separator)) {
                        pattern += "**";
                    }
                    excludePatterns.add(pattern);
                }
            }
        }
        for (Iterator<String> iter = includePatterns.iterator(); !included && iter.hasNext(); ) {
            String pattern = iter.next();
            included = SelectorUtils.matchPath(pattern, name);
        }
        for (Iterator<String> iter = excludePatterns.iterator(); included && iter.hasNext(); ) {
            String pattern = iter.next();
            included = !SelectorUtils.matchPath(pattern, name);
        }
        if (!included) {
            // Do not process this file
            log("skipping " + entryName + " as it is excluded or not included.", Project.MSG_VERBOSE);
            return;
        }
    }
    String[] mappedNames = mapper.mapFileName(entryName);
    if (mappedNames == null || mappedNames.length == 0) {
        mappedNames = new String[] { entryName };
    }
    File f = fileUtils.resolveFile(dir, mappedNames[0]);
    try {
        if (!overwrite && f.exists() && f.lastModified() >= entryDate.getTime()) {
            log("Skipping " + f + " as it is up-to-date", Project.MSG_DEBUG);
            return;
        }
        log("expanding " + entryName + " to " + f, Project.MSG_VERBOSE);
        // create intermediary directories - sometimes zip don't add them
        File dirF = f.getParentFile();
        if (dirF != null) {
            dirF.mkdirs();
        }
        if (isDirectory) {
            f.mkdirs();
        } else {
            byte[] buffer = new byte[BUFFER_SIZE];
            try (OutputStream fos = Files.newOutputStream(f.toPath())) {
                int length;
                while ((length = compressedInputStream.read(buffer)) >= 0) {
                    fos.write(buffer, 0, length);
                }
            }
        }
        fileUtils.setFileLastModified(f, entryDate.getTime());
    } catch (FileNotFoundException ex) {
        log("Unable to expand to file " + f.getPath(), ex, Project.MSG_WARN);
    }
}
Also used : OutputStream(java.io.OutputStream) FileNotFoundException(java.io.FileNotFoundException) PatternSet(org.apache.tools.ant.types.PatternSet) ZipFile(org.apache.tools.zip.ZipFile) File(java.io.File) HashSet(java.util.HashSet)

Example 5 with PatternSet

use of org.apache.tools.ant.types.PatternSet in project ant by apache.

the class Sync method removeOrphanFiles.

/**
 * Removes all files and folders not found as keys of a table
 * (used as a set!).
 *
 * <p>If the provided file is a directory, it is recursively
 * scanned for orphaned files which will be removed as well.</p>
 *
 * <p>If the directory is an orphan, it will also be removed.</p>
 *
 * @param  nonOrphans the table of all non-orphan <code>File</code>s.
 * @param  toDir the initial file or directory to scan or test.
 * @param  preservedDirectories will be filled with the directories
 *         matched by preserveInTarget - if any.  Will not be
 *         filled unless preserveEmptyDirs and includeEmptyDirs
 *         conflict.
 * @return the number of orphaned files and directories actually removed.
 * Position 0 of the array is the number of orphaned directories.
 * Position 1 of the array is the number or orphaned files.
 */
private int[] removeOrphanFiles(Set<String> nonOrphans, File toDir, Set<File> preservedDirectories) {
    int[] removedCount = new int[] { 0, 0 };
    String[] excls = nonOrphans.toArray(new String[nonOrphans.size() + 1]);
    // want to keep toDir itself
    excls[nonOrphans.size()] = "";
    DirectoryScanner ds;
    if (syncTarget != null) {
        FileSet fs = syncTarget.toFileSet(false);
        fs.setDir(toDir);
        // preserveInTarget would find all files we want to keep,
        // but we need to find all that we want to delete - so the
        // meaning of all patterns and selectors must be inverted
        PatternSet ps = syncTarget.mergePatterns(getProject());
        fs.appendExcludes(ps.getIncludePatterns(getProject()));
        fs.appendIncludes(ps.getExcludePatterns(getProject()));
        fs.setDefaultexcludes(!syncTarget.getDefaultexcludes());
        // selectors are implicitly ANDed in DirectoryScanner.  To
        // revert their logic we wrap them into a <none> selector
        // instead.
        FileSelector[] s = syncTarget.getSelectors(getProject());
        if (s.length > 0) {
            NoneSelector ns = new NoneSelector();
            for (FileSelector element : s) {
                ns.appendSelector(element);
            }
            fs.appendSelector(ns);
        }
        ds = fs.getDirectoryScanner(getProject());
    } else {
        ds = new DirectoryScanner();
        ds.setBasedir(toDir);
    }
    ds.addExcludes(excls);
    ds.scan();
    for (String file : ds.getIncludedFiles()) {
        File f = new File(toDir, file);
        log("Removing orphan file: " + f, Project.MSG_DEBUG);
        f.delete();
        ++removedCount[1];
    }
    String[] dirs = ds.getIncludedDirectories();
    // ds returns the directories in lexicographic order.
    // iterating through the array backwards means we are deleting
    // leaves before their parent nodes - thus making sure (well,
    // more likely) that the directories are empty when we try to
    // delete them.
    Arrays.sort(dirs, Comparator.reverseOrder());
    for (String dir : dirs) {
        File f = new File(toDir, dir);
        String[] children = f.list();
        if (children == null || children.length < 1) {
            log("Removing orphan directory: " + f, Project.MSG_DEBUG);
            f.delete();
            ++removedCount[0];
        }
    }
    Boolean ped = getExplicitPreserveEmptyDirs();
    if (ped != null && ped != myCopy.getIncludeEmptyDirs()) {
        FileSet fs = syncTarget.toFileSet(true);
        fs.setDir(toDir);
        String[] preservedDirs = fs.getDirectoryScanner(getProject()).getIncludedDirectories();
        Arrays.sort(preservedDirs, Comparator.reverseOrder());
        for (String dir : preservedDirs) {
            preservedDirectories.add(new File(toDir, dir));
        }
    }
    return removedCount;
}
Also used : AbstractFileSet(org.apache.tools.ant.types.AbstractFileSet) FileSet(org.apache.tools.ant.types.FileSet) DirectoryScanner(org.apache.tools.ant.DirectoryScanner) FileSelector(org.apache.tools.ant.types.selectors.FileSelector) PatternSet(org.apache.tools.ant.types.PatternSet) File(java.io.File) NoneSelector(org.apache.tools.ant.types.selectors.NoneSelector)

Aggregations

PatternSet (org.apache.tools.ant.types.PatternSet)14 File (java.io.File)8 DirectoryScanner (org.apache.tools.ant.DirectoryScanner)7 DirSet (org.apache.tools.ant.types.DirSet)5 FilenameFilter (java.io.FilenameFilter)3 HashSet (java.util.HashSet)3 FileNotFoundException (java.io.FileNotFoundException)2 ArrayList (java.util.ArrayList)2 Enumeration (java.util.Enumeration)2 StringTokenizer (java.util.StringTokenizer)2 Vector (java.util.Vector)2 Project (org.apache.tools.ant.Project)2 FileSet (org.apache.tools.ant.types.FileSet)2 BufferedReader (java.io.BufferedReader)1 BufferedWriter (java.io.BufferedWriter)1 FileReader (java.io.FileReader)1 FileWriter (java.io.FileWriter)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 InputStreamReader (java.io.InputStreamReader)1