Search in sources :

Example 31 with DirectoryScanner

use of org.apache.tools.ant.DirectoryScanner in project groovy-core by groovy.

the class Groovy method execute.

/**
     * Load the file and then execute it
     */
public void execute() throws BuildException {
    log.debug("execute()");
    command = command.trim();
    if (srcFile == null && command.length() == 0 && filesets.isEmpty()) {
        throw new BuildException("Source file does not exist!", getLocation());
    }
    if (srcFile != null && !srcFile.exists()) {
        throw new BuildException("Source file does not exist!", getLocation());
    }
    // deal with the filesets
    for (int i = 0; i < filesets.size(); i++) {
        FileSet fs = filesets.elementAt(i);
        DirectoryScanner ds = fs.getDirectoryScanner(getProject());
        File srcDir = fs.getDir(getProject());
        String[] srcFiles = ds.getIncludedFiles();
    }
    try {
        PrintStream out = System.out;
        try {
            if (output != null) {
                log.verbose("Opening PrintStream to output file " + output);
                out = new PrintStream(new BufferedOutputStream(new FileOutputStream(output.getAbsolutePath(), append)));
            }
            // then read groovy statements in from a text file using the src attribute
            if (command == null || command.trim().length() == 0) {
                createClasspath().add(new Path(getProject(), srcFile.getParentFile().getCanonicalPath()));
                command = getText(new BufferedReader(new FileReader(srcFile)));
            }
            if (command != null) {
                execGroovy(command, out);
            } else {
                throw new BuildException("Source file does not exist!", getLocation());
            }
        } finally {
            if (out != null && out != System.out) {
                out.close();
            }
        }
    } catch (IOException e) {
        throw new BuildException(e, getLocation());
    }
    log.verbose("statements executed successfully");
}
Also used : Path(org.apache.tools.ant.types.Path) PrintStream(java.io.PrintStream) FileSet(org.apache.tools.ant.types.FileSet) IOException(java.io.IOException) DirectoryScanner(org.apache.tools.ant.DirectoryScanner) FileOutputStream(java.io.FileOutputStream) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) BuildException(org.apache.tools.ant.BuildException) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream)

Example 32 with DirectoryScanner

use of org.apache.tools.ant.DirectoryScanner in project groovy-core by groovy.

the class GroovycTask method compile.

protected void compile() {
    Path path = getClasspath();
    if (path != null) {
        config.setClasspath(path.toString());
    }
    config.setTargetDirectory(destdir);
    GroovyClassLoader gcl = createClassLoader();
    CompilationUnit compilation = new CompilationUnit(config, null, gcl);
    GlobPatternMapper mapper = new GlobPatternMapper();
    mapper.setFrom("*.groovy");
    mapper.setTo("*.class");
    int count = 0;
    String[] list = src.list();
    for (int i = 0; i < list.length; i++) {
        File basedir = getProject().resolveFile(list[i]);
        if (!basedir.exists()) {
            throw new BuildException("Source directory does not exist: " + basedir, getLocation());
        }
        DirectoryScanner scanner = getDirectoryScanner(basedir);
        String[] includes = scanner.getIncludedFiles();
        if (force) {
            log.debug("Forcefully including all files from: " + basedir);
            for (int j = 0; j < includes.length; j++) {
                File file = new File(basedir, includes[j]);
                log.debug("    " + file);
                compilation.addSource(file);
                count++;
            }
        } else {
            log.debug("Including changed files from: " + basedir);
            SourceFileScanner sourceScanner = new SourceFileScanner(this);
            File[] files = sourceScanner.restrictAsFiles(includes, basedir, destdir, mapper);
            for (int j = 0; j < files.length; j++) {
                log.debug("    " + files[j]);
                compilation.addSource(files[j]);
                count++;
            }
        }
    }
    if (count > 0) {
        log.info("Compiling " + count + " source file" + (count > 1 ? "s" : "") + " to " + destdir);
        compilation.compile();
    } else {
        log.info("No sources found to compile");
    }
}
Also used : Path(org.apache.tools.ant.types.Path) GroovyClassLoader(groovy.lang.GroovyClassLoader) CompilationUnit(org.codehaus.groovy.control.CompilationUnit) GlobPatternMapper(org.apache.tools.ant.util.GlobPatternMapper) DirectoryScanner(org.apache.tools.ant.DirectoryScanner) BuildException(org.apache.tools.ant.BuildException) SourceFileScanner(org.apache.tools.ant.util.SourceFileScanner) File(java.io.File)

Example 33 with DirectoryScanner

use of org.apache.tools.ant.DirectoryScanner in project hudson-2.x by hudson.

the class FilePath method validateAntFileMask.

/**
     * Validates the ant file mask (like "foo/bar/*.txt, zot/*.jar")
     * against this directory, and try to point out the problem.
     *
     * <p>
     * This is useful in conjunction with {@link FormValidation}.
     *
     * @return
     *      null if no error was found. Otherwise returns a human readable error message.
     * @since 1.90
     * @see #validateFileMask(FilePath, String)
     */
public String validateAntFileMask(final String fileMasks) throws IOException, InterruptedException {
    return act(new FileCallable<String>() {

        public String invoke(File dir, VirtualChannel channel) throws IOException {
            if (fileMasks.startsWith("~"))
                return Messages.FilePath_TildaDoesntWork();
            StringTokenizer tokens = new StringTokenizer(fileMasks, ",");
            while (tokens.hasMoreTokens()) {
                final String fileMask = tokens.nextToken().trim();
                if (hasMatch(dir, fileMask))
                    // no error on this portion
                    continue;
                // so see if we can match by using ' ' as the separator
                if (fileMask.contains(" ")) {
                    boolean matched = true;
                    for (String token : Util.tokenize(fileMask)) matched &= hasMatch(dir, token);
                    if (matched)
                        return Messages.FilePath_validateAntFileMask_whitespaceSeprator();
                }
                // a common mistake is to assume the wrong base dir, and there are two variations
                // to this: (1) the user gave us aa/bb/cc/dd where cc/dd was correct
                // and (2) the user gave us cc/dd where aa/bb/cc/dd was correct.
                {
                    // check the (1) above first
                    String f = fileMask;
                    while (true) {
                        int idx = findSeparator(f);
                        if (idx == -1)
                            break;
                        f = f.substring(idx + 1);
                        if (hasMatch(dir, f))
                            return Messages.FilePath_validateAntFileMask_doesntMatchAndSuggest(fileMask, f);
                    }
                }
                {
                    // check the (2) above next as this is more expensive.
                    // Try prepending "**/" to see if that results in a match
                    FileSet fs = Util.createFileSet(dir, "**/" + fileMask);
                    DirectoryScanner ds = fs.getDirectoryScanner(new Project());
                    if (ds.getIncludedFilesCount() != 0) {
                        // try shorter name first so that the suggestion results in least amount of changes
                        String[] names = ds.getIncludedFiles();
                        Arrays.sort(names, SHORTER_STRING_FIRST);
                        for (String f : names) {
                            // now we want to decompose f to the leading portion that matched "**"
                            // and the trailing portion that matched the file mask, so that
                            // we can suggest the user error.
                            //
                            // this is not a very efficient/clever way to do it, but it's relatively simple
                            String prefix = "";
                            while (true) {
                                int idx = findSeparator(f);
                                if (idx == -1)
                                    break;
                                prefix += f.substring(0, idx) + '/';
                                f = f.substring(idx + 1);
                                if (hasMatch(dir, prefix + fileMask))
                                    return Messages.FilePath_validateAntFileMask_doesntMatchAndSuggest(fileMask, prefix + fileMask);
                            }
                        }
                    }
                }
                {
                    // finally, see if we can identify any sub portion that's valid. Otherwise bail out
                    String previous = null;
                    String pattern = fileMask;
                    while (true) {
                        if (hasMatch(dir, pattern)) {
                            // found a match
                            if (previous == null)
                                return Messages.FilePath_validateAntFileMask_portionMatchAndSuggest(fileMask, pattern);
                            else
                                return Messages.FilePath_validateAntFileMask_portionMatchButPreviousNotMatchAndSuggest(fileMask, pattern, previous);
                        }
                        int idx = findSeparator(pattern);
                        if (idx < 0) {
                            // no more path component left to go back
                            if (pattern.equals(fileMask))
                                return Messages.FilePath_validateAntFileMask_doesntMatchAnything(fileMask);
                            else
                                return Messages.FilePath_validateAntFileMask_doesntMatchAnythingAndSuggest(fileMask, pattern);
                        }
                        // cut off the trailing component and try again
                        previous = pattern;
                        pattern = pattern.substring(0, idx);
                    }
                }
            }
            // no error
            return null;
        }

        private boolean hasMatch(File dir, String pattern) {
            FileSet fs = Util.createFileSet(dir, pattern);
            DirectoryScanner ds = fs.getDirectoryScanner(new Project());
            return ds.getIncludedFilesCount() != 0 || ds.getIncludedDirsCount() != 0;
        }

        /**
             * Finds the position of the first path separator.
             */
        private int findSeparator(String pattern) {
            int idx1 = pattern.indexOf('\\');
            int idx2 = pattern.indexOf('/');
            if (idx1 == -1)
                return idx2;
            if (idx2 == -1)
                return idx1;
            return Math.min(idx1, idx2);
        }
    });
}
Also used : Project(org.apache.tools.ant.Project) AbstractProject(hudson.model.AbstractProject) StringTokenizer(java.util.StringTokenizer) FileSet(org.apache.tools.ant.types.FileSet) VirtualChannel(hudson.remoting.VirtualChannel) DirectoryScanner(org.apache.tools.ant.DirectoryScanner) IOException(java.io.IOException) File(java.io.File)

Example 34 with DirectoryScanner

use of org.apache.tools.ant.DirectoryScanner in project tomcat by apache.

the class CheckEol method execute.

/**
     * Perform the check
     *
     * @throws BuildException if an error occurs during execution of
     *    this task.
     */
@Override
public void execute() throws BuildException {
    Mode mode = null;
    if ("\n".equals(System.lineSeparator())) {
        mode = Mode.LF;
    } else if ("\r\n".equals(System.lineSeparator())) {
        mode = Mode.CRLF;
    } else {
        log("Line ends check skipped, because OS line ends setting is neither LF nor CRLF.", Project.MSG_VERBOSE);
        return;
    }
    int count = 0;
    List<CheckFailure> errors = new ArrayList<>();
    // Step through each file and check.
    for (FileSet fs : filesets) {
        DirectoryScanner ds = fs.getDirectoryScanner(getProject());
        File basedir = ds.getBasedir();
        String[] files = ds.getIncludedFiles();
        if (files.length > 0) {
            log("Checking line ends in " + files.length + " file(s)");
            for (int i = 0; i < files.length; i++) {
                File file = new File(basedir, files[i]);
                log("Checking file '" + file + "' for correct line ends", Project.MSG_DEBUG);
                try {
                    check(file, errors, mode);
                } catch (IOException e) {
                    throw new BuildException("Could not check file '" + file.getAbsolutePath() + "'", e);
                }
                count++;
            }
        }
    }
    if (count > 0) {
        log("Done line ends check in " + count + " file(s), " + errors.size() + " error(s) found.");
    }
    if (errors.size() > 0) {
        String message = "The following files have wrong line ends: " + errors;
        // We need to explicitly write the message to the log, because
        // long BuildException messages may be trimmed. E.g. I observed
        // this problem with Eclipse IDE 3.7.
        log(message, Project.MSG_ERR);
        throw new BuildException(message);
    }
}
Also used : FileSet(org.apache.tools.ant.types.FileSet) DirectoryScanner(org.apache.tools.ant.DirectoryScanner) ArrayList(java.util.ArrayList) IOException(java.io.IOException) BuildException(org.apache.tools.ant.BuildException) File(java.io.File)

Example 35 with DirectoryScanner

use of org.apache.tools.ant.DirectoryScanner in project jetty.project by eclipse.

the class FileMatchingConfiguration method getBaseDirectories.

/**
     * @return a list of base directories denoted by a list of directory
     *         scanners.
     */
public List getBaseDirectories() {
    List baseDirs = new ArrayList();
    Iterator scanners = directoryScanners.iterator();
    while (scanners.hasNext()) {
        DirectoryScanner scanner = (DirectoryScanner) scanners.next();
        baseDirs.add(scanner.getBasedir());
    }
    return baseDirs;
}
Also used : DirectoryScanner(org.apache.tools.ant.DirectoryScanner) ArrayList(java.util.ArrayList) Iterator(java.util.Iterator) List(java.util.List) ArrayList(java.util.ArrayList)

Aggregations

DirectoryScanner (org.apache.tools.ant.DirectoryScanner)57 File (java.io.File)52 BuildException (org.apache.tools.ant.BuildException)26 FileSet (org.apache.tools.ant.types.FileSet)26 IOException (java.io.IOException)18 ArrayList (java.util.ArrayList)12 GroovyClassLoader (groovy.lang.GroovyClassLoader)4 FileInputStream (java.io.FileInputStream)4 FilenameFilter (java.io.FilenameFilter)4 Project (org.apache.tools.ant.Project)4 DirSet (org.apache.tools.ant.types.DirSet)4 PatternSet (org.apache.tools.ant.types.PatternSet)4 LinkedList (java.util.LinkedList)3 Path (org.apache.tools.ant.types.Path)3 AbstractProject (hudson.model.AbstractProject)2 VirtualChannel (hudson.remoting.VirtualChannel)2 OutputStream (java.io.OutputStream)2 URI (java.net.URI)2 URL (java.net.URL)2 URLClassLoader (java.net.URLClassLoader)2