FileDocCategorySizeDatePackage
DotnetCompile.javaAPI DocApache Ant 1.7026215Wed Dec 13 06:16:20 GMT 2006org.apache.tools.ant.taskdefs.optional.dotnet

DotnetCompile

public abstract class DotnetCompile extends DotnetBaseMatchingTask
Abstract superclass for dotnet compiler tasks. History
0.1 First creation Most of the code here was copied verbatim from v0.3 of Steve Loughran's CSharp optional task. Abstracted functionality to allow subclassing of other dotnet compiler types.
version
0.1

Fields Summary
private String
references
list of reference classes. (pretty much a classpath equivalent)
private boolean
includeDefaultReferences
flag to enable automatic reference inclusion
private File
win32icon
icon for incorporation into apps
private File
win32res
icon for incorporation into apps
private boolean
failOnError
flag to control action on execution trouble
private org.apache.tools.ant.types.Path
referenceFiles
using the path approach didn't work as it could not handle the implicit execution path. Perhaps that could be extracted from the runtime and then the path approach would be viable
private boolean
optimize
optimise flag
protected Vector
definitionList
a list of definitions to support;
protected Vector
resources
our resources
protected String
executable
executable
protected static final String
REFERENCE_OPTION
protected boolean
debug
debug flag. Controls generation of debug information.
private int
warnLevel
warning level: 0-4, with 4 being most verbose
protected String
mainClass
main class (or null for automatic choice)
protected String
extraOptions
any extra command options?
protected String
targetType
type of target. Should be one of exe|library|module|winexe|(null) default is exe; the actual value (if not null) is fed to the command line.
See /target
protected boolean
utf8output
utf out flag
protected String
additionalModules
list of extra modules to refer to
protected Vector
referenceFilesets
filesets of references
private boolean
useResponseFile
flag to set to to use @file based command cache
private static final int
AUTOMATIC_RESPONSE_FILE_THRESHOLD
Constructors Summary
public DotnetCompile()
constructor inits everything and set up the search pattern


    // CheckStyle:VisibilityModifier ON

                   

      
        clear();
        setIncludes(getFilePattern());
    
Methods Summary
protected abstract voidaddCompilerSpecificOptions(NetCommand command)
add any compiler specifics

param
command the command to use.

public voidaddDefine(DotnetDefine define)
add a define to the list of definitions

param
define the define value.

        definitionList.addElement(define);
    
public voidaddReference(org.apache.tools.ant.types.FileSet reference)
add a new reference fileset to the compilation

param
reference the files to use.

        referenceFilesets.add(reference);
    
protected intaddReferenceFilesets(NetCommand command, long outputTimestamp)
run through the list of reference files and add them to the command

param
command the command to use.
param
outputTimestamp timestamp to compare against
return
number of files out of date

        int filesOutOfDate = 0;
        Hashtable filesToBuild = new Hashtable();
        for (int i = 0; i < referenceFilesets.size(); i++) {
            FileSet fs = (FileSet) referenceFilesets.elementAt(i);
            filesOutOfDate += command.scanOneFileset(
                    fs.getDirectoryScanner(getProject()),
                    filesToBuild,
                    outputTimestamp);
        }
        //bail out early if there were no files
        if (filesToBuild.size() == 0) {
            return 0;
        }
        //now scan the hashtable and add the files
        Enumeration files = filesToBuild.elements();
        while (files.hasMoreElements()) {
            File file = (File) files.nextElement();
            if (isFileManagedBinary(file)) {
                if (isWindows) {
                    command.addArgument(
                    '"" + REFERENCE_OPTION + file.toString() + '"");
                } else {
                    command.addArgument(REFERENCE_OPTION + file.toString());
                }
            } else {
                log("ignoring " + file + " as it is not a managed executable",
                        Project.MSG_VERBOSE);
            }

        }

        return filesOutOfDate;
    
public voidaddResource(DotnetResource resource)
link or embed a resource

param
resource the resource to use.

        resources.add(resource);
    
protected voidaddResources(NetCommand command)
for every resource declared, we get the (language specific) resource setting

param
command the net command.

        Enumeration e = resources.elements();
        while (e.hasMoreElements()) {
            DotnetResource resource = (DotnetResource) e.nextElement();
            createResourceParameter(command, resource);
        }
    
public voidclear()
reset all contents.

        targetType = null;
        win32icon = null;
        srcDir = null;
        mainClass = null;
        warnLevel = 3;
        optimize = false;
        debug = true;
        references = null;
        failOnError = true;
        additionalModules = null;
        includeDefaultReferences = true;
        extraOptions = null;
    
protected NetCommandcreateNetCommand()
create our helper command

return
a command prefilled with the exe name and task name

        NetCommand command = new NetCommand(this, getTaskName(), getExecutable());
        return command;
    
protected abstract voidcreateResourceParameter(NetCommand command, DotnetResource resource)
Build a C# style parameter.

param
command the command.
param
resource the resource.

public voidexecute()
do the work by building the command line and then calling it

throws
BuildException if validation or execution failed

        log("This task is deprecated and will be removed in a future version\n"
            + "of Ant.  It is now part of the .NET Antlib:\n"
            + "http://ant.apache.org/antlibs/dotnet/index.html",
            Project.MSG_WARN);

        validate();
        NetCommand command = createNetCommand();
        //set up response file options
        command.setAutomaticResponseFileThreshold(AUTOMATIC_RESPONSE_FILE_THRESHOLD);
        command.setUseResponseFile(useResponseFile);
        //fill in args
        fillInSharedParameters(command);
        addResources(command);
        addCompilerSpecificOptions(command);
        int referencesOutOfDate
            = addReferenceFilesets(command, getOutputFileTimestamp());
        //if the refs are out of date, force a build.
        boolean forceBuild = referencesOutOfDate > 0;
        addFilesAndExecute(command, forceBuild);

    
protected voidfillInSharedParameters(NetCommand command)
fill in the common information

param
command the net command.

        command.setFailOnError(getFailOnError());
        //fill in args
        command.addArgument("/nologo");
        command.addArgument(getAdditionalModulesParameter());
        command.addArgument(getDebugParameter());
        command.addArgument(getDefinitionsParameter());
        command.addArguments(getExtraOptionsParameters());
        command.addArgument(getMainClassParameter());
        command.addArgument(getOptimizeParameter());
        command.addArgument(getDestFileParameter());
        command.addArgument(getReferencesParameter());
        command.addArgument(getTargetTypeParameter());
        command.addArgument(getUtf8OutputParameter());
        command.addArgument(getWin32IconParameter());
        command.addArgument(getWin32ResParameter());
    
protected java.lang.StringgetAdditionalModulesParameter()
get the argument or null for no argument needed

return
The AdditionalModules Parameter to CSC

        if (notEmpty(additionalModules)) {
            return "/addmodule:" + additionalModules;
        } else {
            return null;
        }
    
public booleangetDebug()
query the debug flag

return
true if debug is turned on

        return debug;
    
protected java.lang.StringgetDebugParameter()
get the debug switch argument

return
The Debug Parameter to CSC

        return "/debug" + (debug ? "+" : "-");
    
public java.lang.StringgetDefinitionsDelimiter()
override point for delimiting definitions.

return
The definitions limiter, i.e., ";"

        return ";";
    
protected java.lang.StringgetDefinitionsParameter()
get a list of definitions or null

return
a string beginning /D: or null for no definitions
throws
BuildException if there is an error.

        StringBuffer defines = new StringBuffer();
        Enumeration defEnum = definitionList.elements();
        boolean firstDefinition = true;
        while (defEnum.hasMoreElements()) {
            //loop through all definitions
            DotnetDefine define = (DotnetDefine) defEnum.nextElement();
            if (define.isSet(this)) {
                //add those that are set, and a delimiter
                if (!firstDefinition) {
                    defines.append(getDefinitionsDelimiter());
                }
                defines.append(define.getValue(this));
                firstDefinition = false;
            }
        }
        if (defines.length() == 0) {
            return null;
        } else {
            return "/d:" + defines;
        }
    
protected java.lang.StringgetDestFileParameter()
get the argument or null for no argument needed

return
The OutputFile Parameter to CSC

        if (outputFile != null) {
            return "/out:" + outputFile.toString();
        } else {
            return null;
        }
    
protected java.lang.StringgetExecutable()
This method gets the name of the executable.

return
the name of the executable

        return executable;
    
public java.lang.StringgetExtraOptions()
Gets the ExtraOptions attribute

return
The ExtraOptions value

        return this.extraOptions;
    
protected java.lang.StringgetExtraOptionsParameter()
get any extra options or null for no argument needed

return
The ExtraOptions Parameter to CSC

        if (extraOptions != null && extraOptions.length() != 0) {
            return extraOptions;
        } else {
            return null;
        }
    
protected java.lang.String[]getExtraOptionsParameters()
get any extra options or null for no argument needed, split them if they represent multiple options.

return
The ExtraOptions Parameter to CSC

        String extra = getExtraOptionsParameter();
        return extra == null ? null : Commandline.translateCommandline(extra);
    
public booleangetFailOnError()
query fail on error flag

return
The FailFailOnError value

        return failOnError;
    
public abstract java.lang.StringgetFileExtension()
Get the extension of filenames to compile.

return
The string extension of files to compile.

public java.lang.StringgetFilePattern()
Get the pattern for files to compile.

return
The compilation file pattern.

        return "**/*." + getFileExtension();
    
public booleangetIncludeDefaultReferences()
query automatic reference inclusion flag

return
true if flag is turned on

        return includeDefaultReferences;
    
protected java.lang.StringgetIncludeDefaultReferencesParameter()
get the include default references flag or null for no argument needed

return
The Parameter to CSC

        return "/nostdlib" + (includeDefaultReferences ? "-" : "+");
    
public java.lang.StringgetMainClass()
Gets the MainClass attribute

return
The MainClass value

        return this.mainClass;
    
protected java.lang.StringgetMainClassParameter()
get the /main argument or null for no argument needed

return
The MainClass Parameter to CSC

        if (mainClass != null && mainClass.length() != 0) {
            return "/main:" + mainClass;
        } else {
            return null;
        }
    
public booleangetOptimize()
query the optimise flag

return
true if optimise is turned on

        return optimize;
    
protected java.lang.StringgetOptimizeParameter()
get the optimise flag or null for no argument needed

return
The Optimize Parameter to CSC

        return "/optimize" + (optimize ? "+" : "-");
    
public abstract java.lang.StringgetReferenceDelimiter()
Get the delimiter that the compiler uses between references. For example, c# will return ";"; VB.NET will return ","

return
The string delimiter for the reference string.

protected java.lang.StringgetReferenceFilesParameter()
turn the path list into a list of files and a /references argument

return
null or a string of references.

        //bail on no references
        if (references == null) {
            return null;
        }
        //iterate through the ref list & generate an entry for each
        //or just rely on the fact that the toString operator does this, but
        //noting that the separator is ';' on windows, ':' on unix

        //bail on no references listed
        if (references.length() == 0) {
            return null;
        }

        StringBuffer s = new StringBuffer(REFERENCE_OPTION);
        if (isWindows) {
            s.append('\"");
        }
        s.append(references);
        if (isWindows) {
            s.append('\"");
        }
        return s.toString();
    
protected java.lang.StringgetReferencesParameter()
get the reference string or null for no argument needed

return
The References Parameter to CSC

        //bail on no references
        if (notEmpty(references)) {
            if (isWindows) {
                return '\"" + REFERENCE_OPTION + references + '\"";
            } else {
                return REFERENCE_OPTION + references;
            }
        } else {
            return null;
        }
    
public java.lang.StringgetTargetType()
Gets the TargetType attribute

return
The TargetType value

        return targetType;
    
protected java.lang.StringgetTargetTypeParameter()
get the argument or null for no argument needed

return
The TargetType Parameter to CSC

        if (notEmpty(targetType)) {
            return "/target:" + targetType;
        } else {
            return null;
        }
    
protected java.lang.StringgetUtf8OutputParameter()
Gets the utf8OutpuParameter attribute of the CSharp object

return
The utf8OutpuParameter value

        return utf8output ? "/utf8output" : null;
    
public intgetWarnLevel()
query warn level

return
current value

        return warnLevel;
    
protected java.lang.StringgetWarnLevelParameter()
get the warn level switch

return
The WarnLevel Parameter to CSC

        return "/warn:" + warnLevel;
    
protected java.lang.StringgetWin32IconParameter()
get the argument or null for no argument needed

return
The Win32Icon Parameter to CSC

        if (win32icon != null) {
            return "/win32icon:" + win32icon.toString();
        } else {
            return null;
        }
    
public java.io.FilegetWin32Res()
Gets the file of the win32 .res file to include.

return
path to the file.

        return win32res;
    
protected java.lang.StringgetWin32ResParameter()
get the argument or null for no argument needed

return
The Win32Res Parameter to CSC

        if (win32res != null) {
            return "/win32res:" + win32res.toString();
        } else {
            return null;
        }
    
protected static booleanisFileManagedBinary(java.io.File file)
test for a file being managed or not

param
file the file to test.
return
true if we think this is a managed executable, and thus OK for linking
todo
look at the PE header of the exe and see if it is managed or not.

        String filename = file.toString().toLowerCase();
        return filename.endsWith(".exe") || filename.endsWith(".dll")
                || filename.endsWith(".netmodule");
    
public booleanisUseResponseFile()
getter for flag

return
The flag indicating whether the compilation is using a response file.

        return useResponseFile;
    
protected booleannotEmpty(java.lang.String s)
test for a string containing something useful

param
s string in
return
true if the argument is not null or empty

        return s != null && s.length() != 0;
    
public voidsetAdditionalModules(java.lang.String params)
Semicolon separated list of modules to refer to.

param
params The new additionalModules value

        additionalModules = params;
    
public voidsetDebug(boolean f)
set the debug flag on or off.

param
f on/off flag

        debug = f;
    
public voidsetDestDir(java.io.File dirName)
Set the destination directory of files to be compiled.

param
dirName The new DestDir value

        log("DestDir currently unused", Project.MSG_WARN);
    
public voidsetExecutable(java.lang.String executable)
set the name of the program, overriding the defaults. Can be used to set the full path to a program, or to switch to an alternate implementation of the command, such as the Mono or Rotor versions -provided they use the same command line arguments as the .NET framework edition

param
executable the name of the program.

        this.executable = executable;
    
public voidsetExtraOptions(java.lang.String extraOptions)
Any extra options which are not explicitly supported by this task.

param
extraOptions The new ExtraOptions value

        this.extraOptions = extraOptions;
    
public voidsetFailOnError(boolean b)
If true, fail on compilation errors.

param
b The new FailOnError value

        failOnError = b;
    
public voidsetIncludeDefaultReferences(boolean f)
If true, automatically includes the common assemblies in dotnet, and tells the compiler to link in mscore.dll. set the automatic reference inclusion flag on or off this flag controls the /nostdlib option in CSC

param
f on/off flag

        includeDefaultReferences = f;
    
public voidsetMainClass(java.lang.String mainClass)
Sets the name of main class for executables.

param
mainClass The new MainClass value

        this.mainClass = mainClass;
    
public voidsetOptimize(boolean f)
If true, enables optimization flag.

param
f on/off flag

        optimize = f;
    
public voidsetReferenceFiles(org.apache.tools.ant.types.Path path)
Path of references to include. Wildcards should work.

param
path another path to append

        //demand create pathlist
        if (referenceFiles == null) {
            referenceFiles = new Path(this.getProject());
        }
        referenceFiles.append(path);
    
public voidsetReferences(java.lang.String s)
Semicolon separated list of DLLs to refer to.

param
s The new References value

        references = s;
    
public voidsetTargetType(org.apache.tools.ant.taskdefs.optional.dotnet.DotnetCompile$TargetTypes targetType)
set the target type to one of exe|library|module|winexe

param
targetType the enumerated value.

        this.targetType = targetType.getValue();
    
public voidsetTargetType(java.lang.String ttype)
Set the type of target.

param
ttype The new TargetType value
exception
BuildException if target is not one of exe|library|module|winexe

        ttype = ttype.toLowerCase();
        if (ttype.equals("exe") || ttype.equals("library")
            || ttype.equals("module") || ttype.equals("winexe")) {
            targetType = ttype;
        } else {
            throw new BuildException("targetType " + ttype
                    + " is not one of 'exe', 'module', 'winexe' or 'library'");
        }
    
public voidsetUseResponseFile(boolean useResponseFile)
Flag to turn on response file use; default=false. When set the command params are saved to a file and this is passed in with @file. The task automatically switches to this mode with big commands; this option is here for testing and emergencies

param
useResponseFile a boolean value.

        this.useResponseFile = useResponseFile;
    
public voidsetUtf8Output(boolean enabled)
If true, require all compiler output to be in UTF8 format.

param
enabled The new utf8Output value

        utf8output = enabled;
    
public voidsetWarnLevel(int warnLevel)
Level of warning currently between 1 and 4 with 4 being the strictest.

param
warnLevel warn level -see .net docs for valid range (probably 0-4)

        this.warnLevel = warnLevel;
    
public voidsetWin32Icon(java.io.File fileName)
Set the filename of icon to include.

param
fileName path to the file. Can be relative, absolute, whatever.

        win32icon = fileName;
    
public voidsetWin32Res(java.io.File fileName)
Sets the filename of a win32 resource (.RES) file to include. This is not a .NET resource, but what Windows is used to.

param
fileName path to the file. Can be relative, absolute, whatever.

        win32res = fileName;
    
protected voidvalidate()
validation code

throws
BuildException if validation failed

        if (outputFile != null && outputFile.isDirectory()) {
            throw new BuildException("destFile cannot be a directory");
        }
        if (getExecutable() == null) {
            throw new BuildException("There is no executable defined for this task");
        }