Search in sources :

Example 86 with FileSet

use of org.apache.tools.ant.types.FileSet in project memory-map-plugin by Praqma.

the class FileFinder method findFile.

public File findFile(File dir, String pattern) throws IOException {
    if (StringUtils.isBlank(pattern)) {
        throw new MemoryMapFileNotFoundError(String.format("Failed to find files as an empty file pattern was provided. Workspace was '%s'", dir.getAbsolutePath()));
    }
    FileSet fileSet = new FileSet();
    org.apache.tools.ant.Project project = new org.apache.tools.ant.Project();
    fileSet.setProject(project);
    fileSet.setDir(dir);
    fileSet.setIncludes(pattern);
    int numberOfFoundFiles = fileSet.getDirectoryScanner(project).getIncludedFiles().length;
    if (numberOfFoundFiles == 0) {
        throw new MemoryMapFileNotFoundError(String.format("Found no files matching '%s' in directory '%s'", pattern, dir.getAbsolutePath()));
    }
    File file = new File(dir.getAbsoluteFile() + System.getProperty("file.separator") + fileSet.getDirectoryScanner(project).getIncludedFiles()[0]);
    if (!file.exists()) {
        throw new MemoryMapFileNotFoundError(String.format("Couldn't find file '%s' in workspace '%s'. Scanner matched '%s' files.", file.getAbsolutePath(), dir.getAbsolutePath(), numberOfFoundFiles));
    }
    return file;
}
Also used : FileSet(org.apache.tools.ant.types.FileSet) File(java.io.File)

Example 87 with FileSet

use of org.apache.tools.ant.types.FileSet in project CFLint by cflint.

the class CFLintTask method execute.

@Override
public void execute() {
    FileInputStream fis = null;
    try {
        CFLintConfiguration config = null;
        if (configFile != null) {
            if (configFile.getName().toLowerCase().endsWith(".xml")) {
                config = ConfigUtils.unmarshal(configFile, CFLintConfig.class);
            } else {
                config = ConfigUtils.unmarshalJson(new FileInputStream(configFile), CFLintConfig.class);
            }
        }
        CFLintConfiguration cmdLineConfig = null;
        if ((excludeRule != null && excludeRule.trim().length() > 0) || (includeRule != null && includeRule.trim().length() > 0)) {
            cmdLineConfig = new CFLintConfig();
            if (includeRule != null && includeRule.trim().length() > 0) {
                for (final String code : includeRule.trim().split(",")) {
                    cmdLineConfig.addInclude(new PluginMessage(code));
                }
            }
            if (excludeRule != null && excludeRule.trim().length() > 0) {
                for (final String code : excludeRule.trim().split(",")) {
                    cmdLineConfig.addExclude(new PluginMessage(code));
                }
            }
        }
        // TODO combine configs
        final CFLint cflint = new CFLint(config);
        cflint.setVerbose(verbose);
        cflint.setQuiet(quiet);
        if (extensions != null && extensions.trim().length() > 0) {
            cflint.setAllowedExtensions(Arrays.asList(extensions.trim().split(",")));
        }
        CFLintFilter filter = CFLintFilter.createFilter(verbose);
        if (filterFile != null) {
            final File ffile = filterFile;
            if (ffile.exists()) {
                fis = new FileInputStream(ffile);
                final byte[] b = new byte[fis.available()];
                if (fis.read(b) > 0) {
                    fis.close();
                    filter = CFLintFilter.createFilter(new String(b), verbose);
                }
            }
        }
        cflint.getBugs().setFilter(filter);
        if (xmlFile == null && htmlFile == null && textFile == null) {
            xmlFile = new File("cflint-result.xml");
        }
        if (xmlFile != null) {
            if (verbose) {
                System.out.println("Style:" + xmlStyle);
            }
            if ("findbugs".equalsIgnoreCase(xmlStyle)) {
                new XMLOutput().outputFindBugs(cflint.getBugs(), createWriter(xmlFile, StandardCharsets.UTF_8), cflint.getStats());
            } else {
                new DefaultCFlintResultMarshaller().output(cflint.getBugs(), createWriter(xmlFile, StandardCharsets.UTF_8), cflint.getStats());
            }
        }
        if (textFile != null) {
            final Writer textwriter = textFile != null ? new FileWriter(textFile) : new OutputStreamWriter(System.out);
            new TextOutput().output(cflint.getBugs(), textwriter, cflint.getStats());
        }
        if (htmlFile != null) {
            try {
                new HTMLOutput(htmlStyle).output(cflint.getBugs(), new FileWriter(htmlFile), cflint.getStats());
            } catch (final TransformerException e) {
                throw new IOException(e);
            }
        }
        for (final FileSet fileset : filesets) {
            int progress = 1;
            // 3
            final DirectoryScanner ds = fileset.getDirectoryScanner(getProject());
            final ProgressMonitor progressMonitor = showProgress && !filesets.isEmpty() ? new ProgressMonitor(null, "CFLint", "", 1, ds.getIncludedFilesCount()) : null;
            final String[] includedFiles = ds.getIncludedFiles();
            for (final String includedFile : includedFiles) {
                if (progressMonitor != null) {
                    if (progressMonitor.isCanceled()) {
                        throw new RuntimeException("CFLint scan cancelled");
                    }
                    final String filename = ds.getBasedir() + File.separator + includedFile;
                    progressMonitor.setNote("scanning " + includedFile);
                    cflint.scan(filename);
                    progressMonitor.setProgress(progress++);
                }
            }
        }
    } catch (final Exception e) {
        throw new RuntimeException(e);
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
        } catch (final IOException e) {
        }
    }
}
Also used : TextOutput(com.cflint.TextOutput) CFLintConfiguration(com.cflint.config.CFLintConfiguration) FileWriter(java.io.FileWriter) XMLOutput(com.cflint.XMLOutput) CFLint(com.cflint.CFLint) DirectoryScanner(org.apache.tools.ant.DirectoryScanner) PluginMessage(com.cflint.config.CFLintPluginInfo.PluginInfoRule.PluginMessage) DefaultCFlintResultMarshaller(com.cflint.xml.stax.DefaultCFlintResultMarshaller) TransformerException(javax.xml.transform.TransformerException) FileSet(org.apache.tools.ant.types.FileSet) HTMLOutput(com.cflint.HTMLOutput) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) CFLint(com.cflint.CFLint) TransformerException(javax.xml.transform.TransformerException) IOException(java.io.IOException) ProgressMonitor(javax.swing.ProgressMonitor) CFLintConfig(com.cflint.config.CFLintConfig) CFLintFilter(com.cflint.tools.CFLintFilter) OutputStreamWriter(java.io.OutputStreamWriter) File(java.io.File) OutputStreamWriter(java.io.OutputStreamWriter) FileWriter(java.io.FileWriter) Writer(java.io.Writer)

Example 88 with FileSet

use of org.apache.tools.ant.types.FileSet in project violations-plugin by jenkinsci.

the class ViolationsCollector method findFiles.

// TO DO : PLACE THESE IN A UTILITY CLASS
/**
 * Returns an array with the filenames of the files that match an Ant
 * pattern using the workspace as the base directory.
 *
 * @param workspaceRoot
 *            root directory of the workspace
 *
 * @return the filenames found.
 */
private String[] findFiles(final File workspaceRoot, String pattern) {
    if (StringUtil.isBlank(pattern)) {
        return NO_STRINGS;
    }
    FileSet fileSet = new FileSet();
    org.apache.tools.ant.Project project = new org.apache.tools.ant.Project();
    fileSet.setProject(project);
    fileSet.setDir(workspaceRoot);
    fileSet.setIncludes(pattern);
    return fileSet.getDirectoryScanner(project).getIncludedFiles();
}
Also used : FileSet(org.apache.tools.ant.types.FileSet)

Example 89 with FileSet

use of org.apache.tools.ant.types.FileSet in project htmlpublisher-plugin by jenkinsci.

the class HtmlPublisher method publishReports.

/**
 * Runs HTML the publishing operation for specified {@link HtmlPublisherTarget}s.
 * @return False if the operation failed
 */
public static boolean publishReports(Run<?, ?> build, FilePath workspace, TaskListener listener, List<HtmlPublisherTarget> reportTargets, Class<?> publisherClass) throws InterruptedException {
    PrintStream logger = listener.getLogger();
    logger.println("[htmlpublisher] Archiving HTML reports...");
    // Grab the contents of the header and footer as arrays
    List<String> headerLines;
    try {
        headerLines = readFile(HEADER, publisherClass);
    } catch (IOException ex) {
        logger.print("Exception occurred reading file " + HEADER + ", message:" + ex.getMessage());
        return false;
    }
    List<String> footerLines;
    try {
        footerLines = readFile(FOOTER, publisherClass);
    } catch (IOException ex) {
        logger.print("Exception occurred reading file " + FOOTER + ", message:" + ex.getMessage());
        return false;
    }
    for (int i = 0; i < reportTargets.size(); i++) {
        // Create an array of lines we will eventually write out, initially the header.
        List<String> reportLines = new ArrayList<>(headerLines);
        HtmlPublisherTarget reportTarget = reportTargets.get(i);
        boolean keepAll = reportTarget.getKeepAll();
        boolean allowMissing = reportTarget.getAllowMissing();
        FilePath archiveDir = workspace.child(resolveParametersInString(build, listener, reportTarget.getReportDir()));
        FilePath targetDir = reportTarget.getArchiveTarget(build);
        String levelString = keepAll ? "BUILD" : "PROJECT";
        logger.println("[htmlpublisher] Archiving at " + levelString + " level " + archiveDir + " to " + targetDir);
        try {
            if (!archiveDir.exists()) {
                listener.error("Specified HTML directory '" + archiveDir + "' does not exist.");
                if (!allowMissing) {
                    build.setResult(Result.FAILURE);
                    return true;
                }
            }
            if (!keepAll) {
                // We are only keeping one copy at the project level, so remove the old one.
                targetDir.deleteRecursive();
            }
            if (archiveDir.copyRecursiveTo(reportTarget.getIncludes(), targetDir) == 0) {
                if (!allowMissing) {
                    listener.error("Directory '" + archiveDir + "' exists but failed copying to '" + targetDir + "'.");
                    final Result buildResult = build.getResult();
                    if (buildResult != null && buildResult.isBetterOrEqualTo(Result.UNSTABLE)) {
                        listener.error("This is especially strange since your build otherwise succeeded.");
                    }
                    build.setResult(Result.FAILURE);
                    return true;
                } else {
                    continue;
                }
            }
        } catch (IOException e) {
            Util.displayIOException(e, listener);
            e.printStackTrace(listener.fatalError("HTML Publisher failure"));
            build.setResult(Result.FAILURE);
            return true;
        }
        // Index files might be a list of ant patterns, e.g. "**/*index.html,**/*otherFile.html"
        // So split them and search for files within the archive directory that match that pattern
        List<String> csvReports = new ArrayList<>();
        File targetDirFile = new File(targetDir.getRemote());
        String[] splitPatterns = resolveParametersInString(build, listener, reportTarget.getReportFiles()).split(",");
        for (String pattern : splitPatterns) {
            FileSet fs = Util.createFileSet(targetDirFile, pattern);
            csvReports.addAll(Arrays.asList(fs.getDirectoryScanner().getIncludedFiles()));
        }
        String[] titles = null;
        if (reportTarget.getReportTitles() != null && reportTarget.getReportTitles().trim().length() > 0) {
            titles = reportTarget.getReportTitles().trim().split("\\s*,\\s*");
            for (int j = 0; j < titles.length; j++) {
                titles[j] = resolveParametersInString(build, listener, titles[j]);
            }
        }
        List<String> reports = new ArrayList<>();
        for (int j = 0; j < csvReports.size(); j++) {
            String report = csvReports.get(j);
            report = report.trim();
            // On windows file paths contains back slashes, but
            // in the HTML file we do not want them, so replace them with forward slash
            report = report.replace("\\", "/");
            // Ignore blank report names caused by trailing or double commas.
            if (report.isEmpty()) {
                continue;
            }
            reports.add(report);
            String tabNo = "tab" + (j + 1);
            // Make the report name the filename without the extension.
            int end = report.lastIndexOf('.');
            String reportFile;
            if (end > 0) {
                reportFile = report.substring(0, end);
            } else {
                reportFile = report;
            }
            String tabItem = "<li id=\"" + tabNo + "\" class=\"unselected\" onclick=\"updateBody('" + tabNo + "');\" value=\"" + report + "\">" + getTitle(reportFile, titles, j) + "</li>";
            reportLines.add(tabItem);
        }
        // Add the JS to change the link as appropriate.
        String hudsonUrl = Jenkins.get().getRootUrl();
        Job job = build.getParent();
        reportLines.add("<script type=\"text/javascript\">document.getElementById(\"hudson_link\").innerHTML=\"Back to " + job.getName() + "\";</script>");
        // If the URL isn't configured in Hudson, the best we can do is attempt to go Back.
        if (hudsonUrl == null) {
            reportLines.add("<script type=\"text/javascript\">document.getElementById(\"hudson_link\").onclick = function() { history.go(-1); return false; };</script>");
        } else {
            String jobUrl = hudsonUrl + job.getUrl();
            reportLines.add("<script type=\"text/javascript\">document.getElementById(\"hudson_link\").href=\"" + jobUrl + "\";</script>");
        }
        reportLines.add("<script type=\"text/javascript\">document.getElementById(\"zip_link\").href=\"*zip*/" + reportTarget.getSanitizedName() + ".zip\";</script>");
        // Now add the footer.
        reportLines.addAll(footerLines);
        // And write this as the index
        File outputFile = new File(targetDir.getRemote(), reportTarget.getWrapperName());
        try {
            if (archiveDir.exists()) {
                String checksum = writeFile(reportLines, outputFile);
                reportTarget.handleAction(build, checksum);
            }
        } catch (IOException e) {
            logger.println("Error: IOException occured writing report to file " + outputFile.getAbsolutePath() + " to archiveDir:" + archiveDir.getName() + ", error:" + e.getMessage());
        } catch (NoSuchAlgorithmException e) {
            // cannot happen because SHA-1 is guaranteed to exist
            logger.println("Error: NoSuchAlgorithmException occured writing report to file " + outputFile.getAbsolutePath() + " to archiveDir:" + archiveDir.getName() + ", error:" + e.getMessage());
        }
    }
    return true;
}
Also used : FilePath(hudson.FilePath) PrintStream(java.io.PrintStream) FileSet(org.apache.tools.ant.types.FileSet) ArrayList(java.util.ArrayList) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Result(hudson.model.Result) Job(hudson.model.Job) File(java.io.File)

Example 90 with FileSet

use of org.apache.tools.ant.types.FileSet in project JessMA by ldcsaa.

the class Zipper method getSourceFileSet.

private FileSet getSourceFileSet() {
    File f = new File(source);
    FileSet fs = new FileSet();
    fillFileSetAttributes(fs, f);
    return fs;
}
Also used : FileSet(org.apache.tools.ant.types.FileSet) File(java.io.File)

Aggregations

FileSet (org.apache.tools.ant.types.FileSet)165 File (java.io.File)124 DirectoryScanner (org.apache.tools.ant.DirectoryScanner)83 BuildException (org.apache.tools.ant.BuildException)49 Test (org.junit.Test)41 IOException (java.io.IOException)36 ArrayList (java.util.ArrayList)29 Project (org.apache.tools.ant.Project)22 Resource (org.apache.tools.ant.types.Resource)12 FileResource (org.apache.tools.ant.types.resources.FileResource)10 URL (java.net.URL)6 Hashtable (java.util.Hashtable)6 ArchiveFileSet (org.apache.tools.ant.types.ArchiveFileSet)6 Path (org.apache.tools.ant.types.Path)6 ResourceCollection (org.apache.tools.ant.types.ResourceCollection)6 PrintStream (java.io.PrintStream)5 HashMap (java.util.HashMap)5 Iterator (java.util.Iterator)5 List (java.util.List)5 ZipFileSet (org.apache.tools.ant.types.ZipFileSet)5