Search in sources :

Example 76 with Path

use of org.apache.tools.ant.types.Path in project groovy by apache.

the class Groovyc method extractJointOptions.

/**
 * If {@code groovyc} task includes a nested {@code javac} task, check for
 * shareable configuration.  {@code FileSystemCompiler} supports several
 * command-line arguments for configuring joint compilation:
 * <ul>
 * <li><tt>-j</tt> enables joint compile
 * <li><tt>-F</tt> is used to pass flags
 * <li><tt>-J</tt> is used to pass name=value pairs
 * </ul>
 * Joint compilation options are transferred from {@link FileSystemCompiler}
 * to {@link CompilerConfiguration}'s jointCompileOptions property.  Flags
 * are saved to key "flags" (with the inclusion of "parameters" if enabled
 * on groovyc), pairs are saved to key "namedValues" and the key "memStub"
 * may also be set to {@link Boolean#TRUE} to influence joint compilation.
 *
 * @see org.codehaus.groovy.tools.javac.JavacJavaCompiler
 * @see javax.tools.JavaCompiler
 */
private List<String> extractJointOptions(Path classpath) {
    List<String> jointOptions = new ArrayList<>();
    if (!jointCompilation)
        return jointOptions;
    // map "debug" and "debuglevel" to "-Fg"
    if (javac.getDebug()) {
        jointOptions.add("-Fg" + Optional.ofNullable(javac.getDebugLevel()).map(level -> ":" + level).orElse(""));
    } else {
        jointOptions.add("-Fg:none");
    }
    // map "deprecation" to "-Fdeprecation"
    if (javac.getDeprecation()) {
        jointOptions.add("-Fdeprecation");
    }
    // map "nowarn" to "-Fnowarn"
    if (javac.getNowarn()) {
        jointOptions.add("-Fnowarn");
    }
    // map "verbose" to "-Fverbose"
    if (javac.getVerbose()) {
        jointOptions.add("-Fverbose");
    }
    RuntimeConfigurable rc = javac.getRuntimeConfigurableWrapper();
    for (Map.Entry<String, Object> e : rc.getAttributeMap().entrySet()) {
        String key = e.getKey();
        if (key.equals("depend") || key.equals("encoding") || key.equals("extdirs") || key.equals("nativeheaderdir") || key.equals("release") || key.equals("source") || key.equals("target")) {
            switch(key) {
                case "nativeheaderdir":
                    key = "h";
                    break;
                case "release":
                    // to get "--" when passed to javac
                    key = "-" + key;
                    break;
                default:
            }
            // map "depend", "encoding", etc. to "-Jkey=val"
            jointOptions.add("-J" + key + "=" + getProject().replaceProperties(e.getValue().toString()));
        } else if (key.contains("classpath")) {
            if (key.startsWith("boot")) {
                // map "bootclasspath" or "bootclasspathref" to "-Jbootclasspath="
                jointOptions.add("-Jbootclasspath=" + javac.getBootclasspath());
            } else {
                // map "classpath" or "classpathref" to "--classpath"
                classpath.add(javac.getClasspath());
            }
        } else if (key.contains("module") && key.contains("path")) {
            if (key.startsWith("upgrade")) {
                // map "upgrademodulepath" or "upgrademodulepathref" to "-J-upgrade-module-path="
                jointOptions.add("-J-upgrade-module-path=" + javac.getUpgrademodulepath());
            } else if (key.contains("source")) {
                // map "modulesourcepath" or "modulesourcepathref" to "-J-module-source-path="
                jointOptions.add("-J-module-source-path=" + javac.getModulesourcepath());
            } else {
                // map "modulepath" or "modulepathref" to "-J-module-path="
                jointOptions.add("-J-module-path=" + javac.getModulepath());
            }
        } else if (!key.contains("debug") && !key.equals("deprecation") && !key.equals("nowarn") && !key.equals("verbose")) {
            log.warn("The option " + key + " cannot be set on the contained <javac> element. The option will be ignored.");
        }
    // TODO: defaultexcludes, excludes(file)?, includes(file)?, includeDestClasses, tempdir
    }
    // can be multiple of them) for additional options to be passed to javac.
    for (RuntimeConfigurable childrc : Collections.list(rc.getChildren())) {
        if (childrc.getElementTag().equals("compilerarg")) {
            for (Map.Entry<String, Object> e : childrc.getAttributeMap().entrySet()) {
                String key = e.getKey();
                if (key.equals("value")) {
                    String value = getProject().replaceProperties(e.getValue().toString());
                    StringTokenizer st = new StringTokenizer(value, " ");
                    while (st.hasMoreTokens()) {
                        String option = st.nextToken();
                        // GROOVY-5063: map "-Werror", etc. to "-FWerror"
                        jointOptions.add(option.replaceFirst("^-(W|X|proc:)", "-F$1"));
                    }
                }
            }
        }
    }
    return jointOptions;
}
Also used : Arrays(java.util.Arrays) AntClassLoader(org.apache.tools.ant.AntClassLoader) Execute(org.apache.tools.ant.taskdefs.Execute) URISyntaxException(java.net.URISyntaxException) Javac(org.apache.tools.ant.taskdefs.Javac) FileSystemCompiler(org.codehaus.groovy.tools.FileSystemCompiler) JavaAwareCompilationUnit(org.codehaus.groovy.tools.javac.JavaAwareCompilationUnit) ParseTreeVisitor(org.antlr.v4.runtime.tree.ParseTreeVisitor) Path(org.apache.tools.ant.types.Path) ArrayList(java.util.ArrayList) SourceFileScanner(org.apache.tools.ant.util.SourceFileScanner) Charset(java.nio.charset.Charset) CompilationUnit(org.codehaus.groovy.control.CompilationUnit) StringTokenizer(java.util.StringTokenizer) Map(java.util.Map) StringBuilderWriter(org.apache.groovy.io.StringBuilderWriter) DefaultGroovyStaticMethods(org.codehaus.groovy.runtime.DefaultGroovyStaticMethods) URI(java.net.URI) ClassVisitor(org.objectweb.asm.ClassVisitor) CommandLine(picocli.CommandLine) LinkedHashSet(java.util.LinkedHashSet) PrintWriter(java.io.PrintWriter) GlobPatternMapper(org.apache.tools.ant.util.GlobPatternMapper) FileWriter(java.io.FileWriter) DefaultGroovyMethods(org.codehaus.groovy.runtime.DefaultGroovyMethods) Set(java.util.Set) BuildException(org.apache.tools.ant.BuildException) IOException(java.io.IOException) DirectoryScanner(org.apache.tools.ant.DirectoryScanner) MatchingTask(org.apache.tools.ant.taskdefs.MatchingTask) CompilerConfiguration(org.codehaus.groovy.control.CompilerConfiguration) PrivilegedAction(java.security.PrivilegedAction) File(java.io.File) GroovyBugError(org.codehaus.groovy.GroovyBugError) List(java.util.List) RuntimeConfigurable(org.apache.tools.ant.RuntimeConfigurable) SourceExtensionHandler(org.codehaus.groovy.control.SourceExtensionHandler) VMPluginFactory(org.codehaus.groovy.vmplugin.VMPluginFactory) Writer(java.io.Writer) Optional(java.util.Optional) GroovyClassLoader(groovy.lang.GroovyClassLoader) Collections(java.util.Collections) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings) Reference(org.apache.tools.ant.types.Reference) ErrorReporter(org.codehaus.groovy.tools.ErrorReporter) StringTokenizer(java.util.StringTokenizer) RuntimeConfigurable(org.apache.tools.ant.RuntimeConfigurable) ArrayList(java.util.ArrayList) Map(java.util.Map)

Example 77 with Path

use of org.apache.tools.ant.types.Path in project groovy by apache.

the class Groovydoc method execute.

@Override
public void execute() throws BuildException {
    List<String> packagesToDoc = new ArrayList<>();
    Path sourceDirs = new Path(getProject());
    Properties properties = new Properties();
    properties.setProperty("windowTitle", windowTitle);
    properties.setProperty("docTitle", docTitle);
    properties.setProperty("footer", footer);
    properties.setProperty("header", header);
    checkScopeProperties(properties);
    properties.setProperty("publicScope", publicScope.toString());
    properties.setProperty("protectedScope", protectedScope.toString());
    properties.setProperty("packageScope", packageScope.toString());
    properties.setProperty("privateScope", privateScope.toString());
    properties.setProperty("author", author.toString());
    properties.setProperty("processScripts", processScripts.toString());
    properties.setProperty("includeMainForScripts", includeMainForScripts.toString());
    properties.setProperty("overviewFile", overviewFile != null ? overviewFile.getAbsolutePath() : "");
    properties.setProperty("charset", charset != null ? charset : "");
    properties.setProperty("fileEncoding", fileEncoding != null ? fileEncoding : "");
    properties.setProperty("timestamp", Boolean.valueOf(!noTimestamp).toString());
    properties.setProperty("versionStamp", Boolean.valueOf(!noVersionStamp).toString());
    if (sourcePath != null) {
        sourceDirs.addExisting(sourcePath);
    }
    parsePackages(packagesToDoc, sourceDirs);
    GroovyDocTool htmlTool = new GroovyDocTool(// we're gonna get the default templates out of the dist jar file
    new ClasspathResourceManager(), sourcePath.list(), getDocTemplates(), getPackageTemplates(), getClassTemplates(), links, properties);
    try {
        htmlTool.add(sourceFilesToDoc);
        FileOutputTool output = new FileOutputTool();
        // TODO push destDir through APIs?
        htmlTool.renderToOutput(output, destDir.getCanonicalPath());
    } catch (Exception e) {
        e.printStackTrace();
    }
    // try to override the default stylesheet with custom specified one if needed
    if (styleSheetFile != null) {
        try {
            String css = ResourceGroovyMethods.getText(styleSheetFile);
            File outfile = new File(destDir, "stylesheet.css");
            ResourceGroovyMethods.setText(outfile, css);
        } catch (IOException e) {
            System.out.println("Warning: Unable to copy specified stylesheet '" + styleSheetFile.getAbsolutePath() + "'. Using default stylesheet instead. Due to: " + e.getMessage());
        }
    }
}
Also used : Path(org.apache.tools.ant.types.Path) FileOutputTool(org.codehaus.groovy.tools.groovydoc.FileOutputTool) ArrayList(java.util.ArrayList) ClasspathResourceManager(org.codehaus.groovy.tools.groovydoc.ClasspathResourceManager) GroovyDocTool(org.codehaus.groovy.tools.groovydoc.GroovyDocTool) IOException(java.io.IOException) Properties(java.util.Properties) File(java.io.File) BuildException(org.apache.tools.ant.BuildException) IOException(java.io.IOException)

Example 78 with Path

use of org.apache.tools.ant.types.Path in project groovy by apache.

the class CompileTaskSupport method createClassLoader.

protected GroovyClassLoader createClassLoader() {
    GroovyClassLoader gcl = VMPluginFactory.getPlugin().doPrivileged((PrivilegedAction<GroovyClassLoader>) () -> new GroovyClassLoader(ClassLoader.getSystemClassLoader(), config));
    Path path = getClasspath();
    if (path != null) {
        final String[] filePaths = path.list();
        for (String filePath : filePaths) {
            gcl.addClasspath(filePath);
        }
    }
    return gcl;
}
Also used : GroovyClassLoader(groovy.lang.GroovyClassLoader) Path(org.apache.tools.ant.types.Path)

Example 79 with Path

use of org.apache.tools.ant.types.Path in project groovy by apache.

the class Groovy method createClasspathParts.

private void createClasspathParts() {
    Path path;
    if (classpath != null) {
        path = super.createClasspath();
        path.setPath(classpath.toString());
    }
    if (includeAntRuntime) {
        path = super.createClasspath();
        path.setPath(System.getProperty("java.class.path"));
    }
    String groovyHome = null;
    final String[] strings = getSysProperties().getVariables();
    if (strings != null) {
        for (String prop : strings) {
            if (prop.startsWith("-Dgroovy.home=")) {
                groovyHome = prop.substring("-Dgroovy.home=".length());
            }
        }
    }
    if (groovyHome == null) {
        groovyHome = System.getProperty("groovy.home");
    }
    if (groovyHome == null) {
        groovyHome = System.getenv("GROOVY_HOME");
    }
    if (groovyHome == null) {
        throw new IllegalStateException("Neither ${groovy.home} nor GROOVY_HOME defined.");
    }
    File jarDir = new File(groovyHome, "lib");
    if (!jarDir.exists()) {
        throw new IllegalStateException("GROOVY_HOME incorrectly defined. No lib directory found in: " + groovyHome);
    }
    final File[] files = jarDir.listFiles();
    if (files != null) {
        for (File file : files) {
            try {
                log.debug("Adding jar to classpath: " + file.getCanonicalPath());
            } catch (IOException e) {
            // ignore
            }
            path = super.createClasspath();
            path.setLocation(file);
        }
    }
}
Also used : Path(org.apache.tools.ant.types.Path) IOException(java.io.IOException) File(java.io.File)

Example 80 with Path

use of org.apache.tools.ant.types.Path in project hive by apache.

the class CompileProcessor method compile.

@VisibleForTesting
/**
 * Method converts statement into a file, compiles the file and then packages the file.
 * @param ss
 * @return Response code of 0 for success 1 for failure
 * @throws CompileProcessorException
 */
CommandProcessorResponse compile(SessionState ss) throws CommandProcessorException {
    String lockout = "rwx------";
    Project proj = new Project();
    String ioTempDir = System.getProperty(IO_TMP_DIR);
    File ioTempFile = new File(ioTempDir);
    if (!ioTempFile.exists()) {
        throw new CommandProcessorException(ioTempDir + " does not exists");
    }
    if (!ioTempFile.isDirectory() || !ioTempFile.canWrite()) {
        throw new CommandProcessorException(ioTempDir + " is not a writable directory");
    }
    long runStamp = System.currentTimeMillis();
    String user = (ss != null) ? ss.getUserName() : "anonymous";
    File sessionTempFile = new File(ioTempDir, user + "_" + runStamp);
    if (!sessionTempFile.exists()) {
        sessionTempFile.mkdir();
        setPosixFilePermissions(sessionTempFile, lockout, true);
    }
    Groovyc g = new Groovyc();
    String jarId = myId + "_" + runStamp;
    g.setProject(proj);
    Path sourcePath = new Path(proj);
    File destination = new File(sessionTempFile, jarId + "out");
    g.setDestdir(destination);
    File input = new File(sessionTempFile, jarId + "in");
    sourcePath.setLocation(input);
    g.setSrcdir(sourcePath);
    input.mkdir();
    File fileToWrite = new File(input, this.named);
    try {
        Files.write(Paths.get(fileToWrite.toURI()), code.getBytes(Charset.forName("UTF-8")), StandardOpenOption.CREATE_NEW);
    } catch (IOException e1) {
        throw new CommandProcessorException("writing file", e1);
    }
    destination.mkdir();
    try {
        g.execute();
    } catch (BuildException ex) {
        throw new CommandProcessorException("Problem compiling", ex);
    }
    File testArchive = new File(sessionTempFile, jarId + ".jar");
    JarArchiveOutputStream out = null;
    try {
        out = new JarArchiveOutputStream(new FileOutputStream(testArchive));
        for (File f : destination.listFiles()) {
            JarArchiveEntry jentry = new JarArchiveEntry(f.getName());
            FileInputStream fis = new FileInputStream(f);
            out.putArchiveEntry(jentry);
            IOUtils.copy(fis, out);
            fis.close();
            out.closeArchiveEntry();
        }
        out.finish();
        setPosixFilePermissions(testArchive, lockout, false);
    } catch (IOException e) {
        throw new CommandProcessorException("Exception while writing jar", e);
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException WhatCanYouDo) {
            }
            try {
                if (input.exists())
                    FileUtils.forceDeleteOnExit(input);
            } catch (IOException WhatCanYouDo) {
            /* ignore */
            }
            try {
                if (destination.exists())
                    FileUtils.forceDeleteOnExit(destination);
            } catch (IOException WhatCanYouDo) {
            /* ignore */
            }
            try {
                if (testArchive != null && testArchive.exists())
                    testArchive.deleteOnExit();
            } catch (Exception WhatCanYouDo) {
            /* ignore */
            }
        }
    }
    if (ss != null) {
        ss.add_resource(ResourceType.JAR, testArchive.getAbsolutePath());
    }
    CommandProcessorResponse good = new CommandProcessorResponse(null, testArchive.getAbsolutePath());
    return good;
}
Also used : Path(org.apache.tools.ant.types.Path) JarArchiveEntry(org.apache.commons.compress.archivers.jar.JarArchiveEntry) JarArchiveOutputStream(org.apache.commons.compress.archivers.jar.JarArchiveOutputStream) Groovyc(org.codehaus.groovy.ant.Groovyc) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) IOException(java.io.IOException) BuildException(org.apache.tools.ant.BuildException) Project(org.apache.tools.ant.Project) FileOutputStream(java.io.FileOutputStream) BuildException(org.apache.tools.ant.BuildException) File(java.io.File) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Aggregations

Path (org.apache.tools.ant.types.Path)175 File (java.io.File)81 BuildException (org.apache.tools.ant.BuildException)57 Test (org.junit.Test)49 Project (org.apache.tools.ant.Project)28 IOException (java.io.IOException)27 Commandline (org.apache.tools.ant.types.Commandline)21 ArrayList (java.util.ArrayList)15 DirectoryScanner (org.apache.tools.ant.DirectoryScanner)12 AntClassLoader (org.apache.tools.ant.AntClassLoader)9 GroovyClassLoader (groovy.lang.GroovyClassLoader)8 URL (java.net.URL)8 StringTokenizer (java.util.StringTokenizer)8 Reference (org.apache.tools.ant.types.Reference)8 Java (org.apache.tools.ant.taskdefs.Java)7 FileSet (org.apache.tools.ant.types.FileSet)7 Resource (org.apache.tools.ant.types.Resource)7 FileWriter (java.io.FileWriter)6 List (java.util.List)6 Execute (org.apache.tools.ant.taskdefs.Execute)6