nant-0.92-rc1/0000755000175000017500000000000011757310027013024 5ustar jtaylorjtaylornant-0.92-rc1/NAnt.sln0000644000175000017500000002561711757302272014420 0ustar jtaylorjtaylor Microsoft Visual Studio Solution File, Format Version 11.00 # Visual Studio 2010 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NAnt.Console", "src\NAnt.Console\NAnt.Console.csproj", "{859696F8-F405-4018-A155-D34561498A3E}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NAnt.Tests", "tests\NAnt.Tests.csproj", "{F77EA08E-9473-436A-BBA3-880139A341B1}" ProjectSection(ProjectDependencies) = postProject {8F80C098-94A4-44DB-A25D-C9E455FC3120} = {8F80C098-94A4-44DB-A25D-C9E455FC3120} {A154DB17-7263-44E3-838E-1E4C4946B7D8} = {A154DB17-7263-44E3-838E-1E4C4946B7D8} {B50A1067-785B-4686-8FFC-5AF424BEF163} = {B50A1067-785B-4686-8FFC-5AF424BEF163} {8F5F8375-4097-4952-B860-784EB9961ABE} = {8F5F8375-4097-4952-B860-784EB9961ABE} EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NAnt.DotNet", "src\NAnt.DotNet\NAnt.DotNet.csproj", "{B50A1067-785B-4686-8FFC-5AF424BEF163}" ProjectSection(ProjectDependencies) = postProject {8F5F8375-4097-4952-B860-784EB9961ABE} = {8F5F8375-4097-4952-B860-784EB9961ABE} EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NAnt.VisualCpp", "src\NAnt.VisualCpp\NAnt.VisualCpp.csproj", "{A154DB17-7263-44E3-838E-1E4C4946B7D8}" ProjectSection(ProjectDependencies) = postProject {8F5F8375-4097-4952-B860-784EB9961ABE} = {8F5F8375-4097-4952-B860-784EB9961ABE} EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NAnt.Compression", "src\NAnt.Compression\NAnt.Compression.csproj", "{8F80C098-94A4-44DB-A25D-C9E455FC3120}" ProjectSection(ProjectDependencies) = postProject {8F5F8375-4097-4952-B860-784EB9961ABE} = {8F5F8375-4097-4952-B860-784EB9961ABE} EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NDoc.Documenter.NAnt", "src\NDoc.Documenter.NAnt\NDoc.Documenter.NAnt.csproj", "{841FAEBA-4527-410A-B765-E2EDA47ABDCE}" ProjectSection(ProjectDependencies) = postProject {8F5F8375-4097-4952-B860-784EB9961ABE} = {8F5F8375-4097-4952-B860-784EB9961ABE} EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NAnt.Core", "src\NAnt.Core\NAnt.Core.csproj", "{8F5F8375-4097-4952-B860-784EB9961ABE}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NAnt.NUnit", "src\NAnt.NUnit\NAnt.NUnit.csproj", "{00F5C075-9874-4BCE-909A-99C1F600E047}" ProjectSection(ProjectDependencies) = postProject {8F5F8375-4097-4952-B860-784EB9961ABE} = {8F5F8375-4097-4952-B860-784EB9961ABE} EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NAnt.NUnit2", "src\NAnt.NUnit\NUnit2\NAnt.NUnit2.csproj", "{47503BEE-27D9-4D1C-B8E1-6C9CCC19AEAA}" ProjectSection(ProjectDependencies) = postProject {00F5C075-9874-4BCE-909A-99C1F600E047} = {00F5C075-9874-4BCE-909A-99C1F600E047} {8F5F8375-4097-4952-B860-784EB9961ABE} = {8F5F8375-4097-4952-B860-784EB9961ABE} EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NAnt.NUnit1", "src\NAnt.NUnit\NUnit1\NAnt.NUnit1.csproj", "{0F3EA7A9-C5F6-4254-820C-B5E0409B5B9D}" ProjectSection(ProjectDependencies) = postProject {00F5C075-9874-4BCE-909A-99C1F600E047} = {00F5C075-9874-4BCE-909A-99C1F600E047} {8F5F8375-4097-4952-B860-784EB9961ABE} = {8F5F8375-4097-4952-B860-784EB9961ABE} EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NAnt.SourceControl", "src\NAnt.SourceControl\NAnt.SourceControl.csproj", "{6B2EC648-8D69-4096-B4F9-6EDC0B2F98EF}" ProjectSection(ProjectDependencies) = postProject {8F5F8375-4097-4952-B860-784EB9961ABE} = {8F5F8375-4097-4952-B860-784EB9961ABE} EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NAnt.Win32", "src\NAnt.Win32\NAnt.Win32.csproj", "{C66545A2-6FEC-4A38-937A-5B25E61EE8A1}" ProjectSection(ProjectDependencies) = postProject {8F5F8375-4097-4952-B860-784EB9961ABE} = {8F5F8375-4097-4952-B860-784EB9961ABE} EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NAnt.MSNet", "src\NAnt.MSNet\NAnt.MSNet.csproj", "{ED13C268-36DE-49CE-B347-C2BE03F814B9}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NAnt.VSNet", "src\NAnt.VSNet\NAnt.VSNet.csproj", "{DD434690-B4DF-4BF9-91FE-F139A41E2474}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NAnt.MSBuild", "src\NAnt.MSBuild\NAnt.MSBuild.csproj", "{318C04B2-D982-4243-9C6A-CA7E035E927D}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{B4486CE1-FAEA-4B20-B7DA-1A818759EA70}" ProjectSection(SolutionItems) = preProject Makefile = Makefile NAnt.build = NAnt.build EndProjectSection EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {00F5C075-9874-4BCE-909A-99C1F600E047}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {00F5C075-9874-4BCE-909A-99C1F600E047}.Debug|Any CPU.Build.0 = Debug|Any CPU {00F5C075-9874-4BCE-909A-99C1F600E047}.Release|Any CPU.ActiveCfg = Release|Any CPU {00F5C075-9874-4BCE-909A-99C1F600E047}.Release|Any CPU.Build.0 = Release|Any CPU {0F3EA7A9-C5F6-4254-820C-B5E0409B5B9D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {0F3EA7A9-C5F6-4254-820C-B5E0409B5B9D}.Debug|Any CPU.Build.0 = Debug|Any CPU {0F3EA7A9-C5F6-4254-820C-B5E0409B5B9D}.Release|Any CPU.ActiveCfg = Release|Any CPU {0F3EA7A9-C5F6-4254-820C-B5E0409B5B9D}.Release|Any CPU.Build.0 = Release|Any CPU {318C04B2-D982-4243-9C6A-CA7E035E927D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {318C04B2-D982-4243-9C6A-CA7E035E927D}.Debug|Any CPU.Build.0 = Debug|Any CPU {318C04B2-D982-4243-9C6A-CA7E035E927D}.Release|Any CPU.ActiveCfg = Release|Any CPU {318C04B2-D982-4243-9C6A-CA7E035E927D}.Release|Any CPU.Build.0 = Release|Any CPU {47503BEE-27D9-4D1C-B8E1-6C9CCC19AEAA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {47503BEE-27D9-4D1C-B8E1-6C9CCC19AEAA}.Debug|Any CPU.Build.0 = Debug|Any CPU {47503BEE-27D9-4D1C-B8E1-6C9CCC19AEAA}.Release|Any CPU.ActiveCfg = Release|Any CPU {47503BEE-27D9-4D1C-B8E1-6C9CCC19AEAA}.Release|Any CPU.Build.0 = Release|Any CPU {6B2EC648-8D69-4096-B4F9-6EDC0B2F98EF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {6B2EC648-8D69-4096-B4F9-6EDC0B2F98EF}.Debug|Any CPU.Build.0 = Debug|Any CPU {6B2EC648-8D69-4096-B4F9-6EDC0B2F98EF}.Release|Any CPU.ActiveCfg = Release|Any CPU {6B2EC648-8D69-4096-B4F9-6EDC0B2F98EF}.Release|Any CPU.Build.0 = Release|Any CPU {841FAEBA-4527-410A-B765-E2EDA47ABDCE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {841FAEBA-4527-410A-B765-E2EDA47ABDCE}.Debug|Any CPU.Build.0 = Debug|Any CPU {841FAEBA-4527-410A-B765-E2EDA47ABDCE}.Release|Any CPU.ActiveCfg = Release|Any CPU {841FAEBA-4527-410A-B765-E2EDA47ABDCE}.Release|Any CPU.Build.0 = Release|Any CPU {859696F8-F405-4018-A155-D34561498A3E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {859696F8-F405-4018-A155-D34561498A3E}.Debug|Any CPU.Build.0 = Debug|Any CPU {859696F8-F405-4018-A155-D34561498A3E}.Release|Any CPU.ActiveCfg = Release|Any CPU {859696F8-F405-4018-A155-D34561498A3E}.Release|Any CPU.Build.0 = Release|Any CPU {8F5F8375-4097-4952-B860-784EB9961ABE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {8F5F8375-4097-4952-B860-784EB9961ABE}.Debug|Any CPU.Build.0 = Debug|Any CPU {8F5F8375-4097-4952-B860-784EB9961ABE}.Release|Any CPU.ActiveCfg = Release|Any CPU {8F5F8375-4097-4952-B860-784EB9961ABE}.Release|Any CPU.Build.0 = Release|Any CPU {8F80C098-94A4-44DB-A25D-C9E455FC3120}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {8F80C098-94A4-44DB-A25D-C9E455FC3120}.Debug|Any CPU.Build.0 = Debug|Any CPU {8F80C098-94A4-44DB-A25D-C9E455FC3120}.Release|Any CPU.ActiveCfg = Release|Any CPU {8F80C098-94A4-44DB-A25D-C9E455FC3120}.Release|Any CPU.Build.0 = Release|Any CPU {A154DB17-7263-44E3-838E-1E4C4946B7D8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A154DB17-7263-44E3-838E-1E4C4946B7D8}.Debug|Any CPU.Build.0 = Debug|Any CPU {A154DB17-7263-44E3-838E-1E4C4946B7D8}.Release|Any CPU.ActiveCfg = Release|Any CPU {A154DB17-7263-44E3-838E-1E4C4946B7D8}.Release|Any CPU.Build.0 = Release|Any CPU {B50A1067-785B-4686-8FFC-5AF424BEF163}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {B50A1067-785B-4686-8FFC-5AF424BEF163}.Debug|Any CPU.Build.0 = Debug|Any CPU {B50A1067-785B-4686-8FFC-5AF424BEF163}.Release|Any CPU.ActiveCfg = Release|Any CPU {B50A1067-785B-4686-8FFC-5AF424BEF163}.Release|Any CPU.Build.0 = Release|Any CPU {C66545A2-6FEC-4A38-937A-5B25E61EE8A1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C66545A2-6FEC-4A38-937A-5B25E61EE8A1}.Debug|Any CPU.Build.0 = Debug|Any CPU {C66545A2-6FEC-4A38-937A-5B25E61EE8A1}.Release|Any CPU.ActiveCfg = Release|Any CPU {C66545A2-6FEC-4A38-937A-5B25E61EE8A1}.Release|Any CPU.Build.0 = Release|Any CPU {DD434690-B4DF-4BF9-91FE-F139A41E2474}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {DD434690-B4DF-4BF9-91FE-F139A41E2474}.Debug|Any CPU.Build.0 = Debug|Any CPU {DD434690-B4DF-4BF9-91FE-F139A41E2474}.Release|Any CPU.ActiveCfg = Release|Any CPU {DD434690-B4DF-4BF9-91FE-F139A41E2474}.Release|Any CPU.Build.0 = Release|Any CPU {ED13C268-36DE-49CE-B347-C2BE03F814B9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {ED13C268-36DE-49CE-B347-C2BE03F814B9}.Debug|Any CPU.Build.0 = Debug|Any CPU {ED13C268-36DE-49CE-B347-C2BE03F814B9}.Release|Any CPU.ActiveCfg = Release|Any CPU {ED13C268-36DE-49CE-B347-C2BE03F814B9}.Release|Any CPU.Build.0 = Release|Any CPU {F77EA08E-9473-436A-BBA3-880139A341B1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F77EA08E-9473-436A-BBA3-880139A341B1}.Debug|Any CPU.Build.0 = Debug|Any CPU {F77EA08E-9473-436A-BBA3-880139A341B1}.Release|Any CPU.ActiveCfg = Release|Any CPU {F77EA08E-9473-436A-BBA3-880139A341B1}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(NestedProjects) = preSolution EndGlobalSection GlobalSection(MonoDevelopProperties) = preSolution StartupItem = src\NAnt.Console\NAnt.Console.csproj Policies = $0 $0.StandardHeader = $1 $1.Text = @NAnt - A .NET build tool\nCopyright (C) 2001-${Year} Gerry Shaw\n\nThis program is free software; you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation; either version 2 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n${AuthorName} (${AuthorEmail}) $1.IncludeInNewFiles = True EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal nant-0.92-rc1/doc/0000755000175000017500000000000011757310027013571 5ustar jtaylorjtaylornant-0.92-rc1/doc/releasenotes.html0000644000175000017500000061002511757310021017146 0ustar jtaylorjtaylor NAnt Release Notes

NAnt Release Notes

NAnt logo (link to home page)

0.92-rc1 (May 23, 2012)

Breaking changes

Tasks

XmlPoke

Updated XmlPoke task to honor the failonerror attribute. (Issue #44)

Changes

Core

NAnt AppDomains

Updated NAnt to use the Unrestricted permission state when creating AppDomains by default instead of just on .NET/Mono 4.0. (Issue #48)

Tasks

TryCatch

Moved <trycatch> task from NAntContrib to NAnt. (Issue #26)

Choose

Moved <choose> task from NAntContrib to NAnt. (Issue #26)

0.92-beta1 (May 6, 2012)

No Updates since 0.92-alpha1

0.92-alpha1 (April 22, 2012)

Changes

Framework support

Core

NAnt Project Files

Updated NAnt project files to VS2010 format.

NUnit

Upgraded to NUnit 2.6.

App.Config

Added initial support for Silverlight 5

Command Line

Added pause option to pause nant before exit.

Type Factory

Added detailed error messages when type loading exception occurs.

Tasks

Mail

Updated <mail> task to reference System.Net.Mail namespace instead of System.Web.Mail.

Added additional attritbutes for greater control of the <mail> task. Such as:

Zip

Added flatten attribute to <zip> task.

Tar

Added flatten attribute to <tar> task.

Bug fixes

Tasks

Copy/Move tasks

Fixed issues with <copy> and <move> tasks when trying to relocate directories. (Issue #11)

Asminfo

Fixed issue with <asminfo> task when trying to add assembly attributes with default constructors. (Issue #41)

Style

Updated <style> task to preserve singleton tags whenever possible. (Issue #17)

0.91 (October 22, 2011)

Bug fixes

Core

XmlPeek

Fixed issue with XmlPeek not outputting results in xml format. (bugs #3366107 and #3390653)

App.config

Added necessary .NET 4.0 WPF and misc missing .NET 3.5 reference assemblies. (bug 3314793)

0.91-rc1 (October 8, 2011)

Bug fixes

Core

App.config

Fixed issue with NDoc when building NAnt from source. (bug #3416986).

Makefile

Fixed issue when building NAnt with older versions of GNU Make.

0.91-beta1 (September 25, 2011)

Changes

Core

App.Config

Added mono-4.0 target

Added initial support for Silverlight 3 and 4

log4net

Upgraded to log4net 1.2.10.

MSBuild

Added initial support for 2008/2010 MSBuild/VS.NET project files.

Bug fixes

Core

App.config

Added WindowsBase.dll and PresentationFramework.dll to 4.0 target.

NAnt.xsd

Changed the NAnt.Core.Tasks.DescriptionTask task to mixed. (bug #3058913).

BuildException

Display correct registry hives in BuildException when Registry Path not found.

Tasks

ndoc

Fixed ndoc task to find hhc.exe for chm generation on 64 bit machines through reflection.

0.91-alpha2 (August 17, 2010)

Bug fixes

Core

App.config

Fixed typo that prevented System.Management.dll from being included.

Tasks

<include>

Fixed error with the <include> task when different build files include the same file. (bug #3016497).

Functions

NAnt::get-assembly()

Using the NAnt::get-assembly() function causes an "Object must implement IConvertible" error. (bug #3013492).

0.91-alpha1 (May 29, 2010)

Framework support

Bug fixes

Expressions

Coercion

Coercion of arguments is not supported (bug #3013492).

Changes

Tasks

<xmlpeek>

Enhanced the <xmlpeek> task to support more advanced XPath functions and syntax. It is now possible to use functions such as count() and to index the node using XPath directly. (feature request #1560566).

0.90 (May 8, 2010)

Bug fixes

Tasks

<tar>

When the "destfile" attribute specifies a non-existent path, the base directory(ies) will be created. (bug #2997300).

0.90-rc1 (May 2, 2010)

Bug fixes

Core

<PathScanner>

Catch UnauthorizedAccessException in PathScanner to prevent NAnt from crashing when using the Scan() function to search for file(s) in directory with special permissions.

0.90-beta1 (April 17, 2010)

Bug fixes

Tasks

<csc> / <jsc> / <vbc> / <vjc>

When the "output" attribute specifies a non-existent path, the base directory(ies) will be created. (bug #2985057).

ExternalProgramBase

For certain tasks (NDoc, Exec, MSBuild, etc) the console output is unorganized and difficult to read. (bug #2981604).

<script>

Cleanup the output to show assembly information and functions only when "verbose" attribute is set to "true". (bug #2981386).

<zip>

When the "zipfile" attribute specifies a non-existent path, the base directory(ies) will be created. (bug #2981389).

0.90-alpha1 (April 1, 2010)

Breaking changes

Core

Extensibility

Tasks

<script>

As of this release, only the following namespaces are imported by default:

Starting from this release, only NAnt.Core and mscorlib will be referenced by default.

In previous releases, all loaded assemblies would implicitly be referenced.

Bug fixes

Extensibility

DataTypeBaseBuilder / FilterBuilder / TaskBuilder

Changes to constructors break backward compatibility (bug 2782705).

Expressions

Identifiers

Identifiers containing a dot or backslash are falsely rejected.

Framework support

.NET Framework (All)

The target framework cannot be initialized if the .NET Framework SDK is not installed (bug #1859708).

.NET Framework 1.1

Added the following assemblies to the list of reference assemblies:

Fixes bug #1848648.

.NET Framework 3.5

Tasks

<echo>

A newline is implicitly added when writing a message to a file (bug #2807728).

<echo>

When "output" parameter is specified, standard output is redirected properly. (bug #1010223).

ExternalProgramBase

The value of UseRuntimeEngine is not respected when overriden by derived classes (bug #1850383).

<move>

When source file is newer than destination file, then an error is reported if "overwrite" is not set to true.

<solution>

Solution Folders result in build failure (bug #1732361).

<xmlpeek>

"verbose" feature is now worked as documented (bug #1911292).

<zip>

Improved backward compatibility with older unzip implementations.

Types

<fileset>

Files matching the **/vssver2.scc pattern are not excluded by default (bug #2515816).

Additions

Functions

environment::newline()

Gets the newline string defined for this environment.

framework::get-description()

Gets the description of the current target framework.

framework::get-clr-version()

Gets the CLR version of the current target framework.

framework::get-frameworks(NAnt.Core.FrameworkTypes)

Gets a comma-separated list of frameworks filtered by the specified FrameworkTypes.

For example:

    <target name="build-all">
        <foreach item="String" in="${framework::get-frameworks('installed compact')}" delim="," property="framework">
            <property name="nant.settings.currentframework" value="${framework}" />
            <call target="${framework}" />
        </foreach>
    </target>

    <target name="build">
        ...
    </target>
                
framework::get-version()

Gets the version of the current target framework.

platform::is-windows()

Return a value indicating whether NAnt is running on Windows.

Tasks

<untar>

Extracts files from a tar archive.

Changes

Packaging

pkg-config

When installing NAnt from source on Unix (using make install), a nant.pc is now installed in $prefix/lib/pkgconfig.

DESTDIR

To allow for staged installs, our makefile now also supports the DESTDIR variable:

    $ make DESTDIR=/tmp/local install
                

Functions

platform::is-win32()

This function is deprecated, use platform::is-windows() instead.

Tasks

<csc> / <jsc> / <vbc> / <vjc>

Added "winres" attribute to specify a Win32 resource file.

<echo>

The "encoding" attribute can be used to specify the encoding when writing messages to a file.

    <echo file="build.cmd" encoding="ascii">...</echo>
                
<link>

Added "moduledefinition" parameter to allow the name of the module definition file to be set.

<nunit2>

Allow referenced assemblies to be specified using <references> element on <test>:

    <nunit2>
        <test>
            <assemblies basedir="build/tests">
                <include name="Cegeka.HealthCare.DocGen.Tests.dll" />
                <include name="Cegeka.HealthCare.Util.Tests.dll" />
            </assemblies>
            <references basedir="build/lib">
                <include name="Cegeka.HealthCare.Common.dll" />
                <include name="Cegeka.HealthCare.DocGen.dll" />
                <include name="Cegeka.HealthCare.Util.dll" />
            </assemblies>
        </test>
    </nunit2>
                
Previously, all referenced assemblies needed to be either in the GAC, or in the directory containing the test assembly.
<solution>

Introduced support for targeting a specific platform, as defined in the solution or project.

<xmlpoke>

Added "preserveWhitespace" parameter to retain the original format of the XML files.

<unzip>

Added "overwrite" parameter to control whether to overwrite files even if they are newer than corresponding entries in the archive.

Third-Party

#ziplib

Types

<fileset> / <patternset>

For patterns specified using <includesfile> or <excludesfile>, lines that have a number sign (#) as the first non-blank character in a line are now ignored.

0.86-beta1 (December 8, 2007)

Breaking changes

Core

nant.tasks properties

Prior to NAnt 0.85, build authors would use a "nant.tasks.*" property to check whether a given task was available.

With the introduction of expression support in NAnt 0.85, we provided a more powerful alternative through the task::exists function.

As of this release, the "nant.tasks.*" properties are therefore no longer set by NAnt.

nant.failure

Removed support for the "nant.failure" property to set the target that should be executed when the build fails.

This property was deprecated in NAnt 0.83 in favor of the "nant.onfailure" attribute.

As of this release, setting the "nant.failure" attribute will no longer have any effect.

Expressions

= operator

In NAnt 0.85, support for the '=' operator to check for equality was deprecated in favor of the '==' operator.

As from this release, the '=' operator is no longer recognized.

Tasks

<style>

Bug fixes

Core

MailLogger
Response File
Document Type Definition

Framework support

Mono/Cygwin

Tasks

<call>
<csc>
<exec>
<resgen>
<solution>

Third-Party

#ziplib

Types

<fileset>

Additions

Expressions

Version operators

Introduced support for relational operators between version values.

Framework support

Tool paths

Since NAnt 0.84, task authors have been able to specify the location of the command-line tool by applying a ProgramLocationAttribute to classes deriving from ExternalProgramBase.

The ProgramLocationAttribute allows task authors to specify whether the tool is located in the framework directory (eg. C:\WINDOWS\Microsoft.NET\Framework\v1.1.4432) or the SDK directory (eg. C:\Program Files\Microsoft Visual Studio .NET 2003\SDK\v1.1) without actually having to deal with the complexity of knowing the actual path to these directories (for each supported framework).

In NAnt 0.86, we've taken this one step further. Each defined framework now has a (ordered) list of directories that can be scanned to locate a framework tool. The list of directories can be easily tuned for each framework by modifying the <tool-paths> nodes in the NAnt configuration file.

An example of such a node for the Mono 3.5 profile:

    <tool-paths>
        <directory name="${path::combine(prefix, 'lib/mono/3.5')}" />
        <directory name="${path::combine(prefix, 'lib/mono/2.0')}" />
        <directory name="${path::combine(prefix, 'lib/mono/1.0')}" />
    </tool-paths>
                

The directories configured in the <tool-paths> node of the current target framework will be scanned in the order in which they are defined.

The tool paths are implicitly used when a given tool cannot be located on the location specified by the ProgramLocationAttribute. As such, this only applies to tasks deriving from ExternalProgramBase.

To expose this functionality to build authors, we've added a framework::get-tool-path function that can be used to search for a given tool.

For example:

    <exec program="${framework::get-tool-path('gacutil.exe')}" managed="strict">
        <arg value="/i" />
        <arg file="Cegeka.HealthFramework.dll" />
    </exec>
                
Strict execution

Introduced support for forcing a managed application to run on the currently targeted CLR.

This was previously only possible by modifying the <startup> section of the application configuration file or by using constructs specific to each CLR (eg. using COMPLUS_VERSION environment variable for the MS CLR), which made build scripts non-portable.

Developers extending NAnt, can now control this by setting the Managed property for tasks deriving from ExternalProgramBase.

For build authors, forcing a managed application to run on a specific version of a CLR can be done by setting the "managed" attribute of <exec> to strict.

For example:

    <exec program="nunit-console.exe" managed="strict">
        <arg value="/noshadow" />
        <arg file="Cegeka.HealthFramework.Tests.dll" />
    </exec>
                
.NET Framework 3.5

Support for targeting .NET Framework 3.5 and Mono 3.5 Profile is now available.

Note: this does not apply to the <solution> task.

Silverlight 2.0

Added experimental support for targeting Silverlight 2.0 and Moonlight 2.0.

Note: this does not apply to the <solution> task.

Types

<patternset>

Defines a set of patterns, mostly used to include or exclude certain files.

Patterns can be grouped to sets, and later be referenced by their id.

For example:

    <patternset id="binaries">
        <include name="bin/**/*" />
        <exclude name="bin/*.tmp" />
    </patternset>

    <patternset id="docs">
        <include name="requirements/**/*" />
        <exclude name="design/**/*.doc" />
    </patternset>

    <patternset id="client.sources">
        <include name="client/**/*.cs" />
        <exclude name="client/**/*.vb" />
    </patternset>

    <patternset id="server.sources">
        <include name="server/**/*.cs" />
        <exclude name="server/**/*.vb" />
    </patternset>

    <patternset id="sources">
        <patternset refid="client.sources" />
        <patternset refid="server.sources" />
    </patternset>

    <target name="deploy">
        <copy todir="${dist.path}">
            <fileset basedir="${build.path}">
                <patternset refid="binaries" />
                <patternset refid="docs" />
                <patternset refid="sources" />

                <exclude name="**/*.sdf" />
            </fileset>
        </copy>
    </target>
                

Changes

Core

Performance

Initial start-up time and project initialization have been reduced dramatically by lazy configuration of supported target frameworks.

Framework support

.NET Compact Framework 2.0

Compiler options that were introduced in .NET Framework 2.0 are now also available when targeting .NET Compact Framework 2.0.

Tasks

<al>
<csc>
<exec>
<jsc>
<vbc>
<vjc>

Third-Party

#ziplib

Types

<assemblyfileset>

The reference assemblies of a given target framework are no longer limited to the assemblies in, what is known as, the framework assembly directory.

Instead, these are now defined using one or more <reference-assemblies> filesets in the <framework> node of the NAnt configuration file.

<fileset>

Added a "casesensitive" attribute to control whether pattern matching must be case-sensitive.

The default is true on Unix and false on on other platforms.

0.85 (October 14, 2006)

Bug fixes

Framework support

.NET Compact Framework 2.0

Functions

file::is-assembly

Tasks

<aximp>
<csc>
<regen>
<solution>
<unzip>

Changes

Tasks

<tlbimp>
<vbc>

0.85-rc 4 (June 2, 2006)

Framework support

Breaking changes

Tasks

<delete>

Bug fixes

Core

XmlLogger

Filters

<replacetokens>

Tasks

<cl>
<rc>
<script>
<solution>

Additions

Tasks

<regasm>

Changes

Core

log4net
MailLogger
Define types in task containers.

Global types can now be (re)defined in task containers (such a <if> , <foreach>).

For example:

    <project name="container-type" default="build">
        <if test="${platform::is-win32()}">
            <fileset id="sources">
                <include name="**/*.cs" />
                <!-- exclude Unix-specific classes -->
                <exclude name="**/Unix/*.cs" />
            </fileset>
        </if>
        <if test="${platform::is-unix()}">
            <fileset id="sources">
                <include name="**/*.cs" />
                <!-- exclude Win32-specific classes -->
                <exclude name="**/Win32/*.cs" />
            </fileset>
        </if>
        <target name="build">
            <csc output="IvsController.dll">
                <sources refid="sources" />
                <references>
                    <include name="System.dll" />
                    <include name="System.Data.dll" />
                    <include name="System.Xml.dll" />
                </references>
            </csc>
        </target>
    </project>
                

Up until now, only tasks could be executed in these containers.

Tasks

<csc>
<jsc>
<link>
<nunit2>
<unzip>
<vbc>
<vjc>
<zip>

Types

<arg>

0.85-rc 3 (April 16, 2005)

Breaking changes

Tasks

<nant>

Bug fixes

Core

XML Schema

Tasks

<copy> / <move>
<link>
<nant>
<ndoc>
<resgen>
<script>
<servicecontroller>
<call>
<solution>

Types

<fileset>

Changes

Core

MailLogger
Response File
XmlLogger

Tasks

<csc> / <vbc> / <vjc>
<lib>
<midl>

Developer information

API

FileSetAttribute

The NAnt.Core.Attributes.FileSetAttribute is obsolete. Task developers should use the NAnt.Core.Attributes.BuildElementAttribute instead:

For example:

    [FileSetBuildElement("fileset")]
    public FileSet CopyFileSet {
        get { return _fileset; }
        set { _fileset = value; }
    }
                

0.85-rc 2 (February 12, 2005)

General changes

Building NAnt
License

Bug fixes

Core

XML Schema

Functions

target::get-current-target()

Tasks

<cl>
<mail>
<midl>
<solution>
<style>
<sysinfo>

Additions

Tasks

<gunzip>
<setenv>

Types

<categories>

Changes

Expressions

Data Type support

Tasks

<al>
<cl>
<csc>
<lc>
<exec>
<link>
<mail>
<ndoc>
<nunit2>
<resgen>
<solution>
<style>

Types

<import>

0.85-rc 1 (November 28, 2004)

Framework support

Breaking changes

General changes

Commandline changes

New Tasks

<aximp>

<cvs-pass>

<cvs-changelog>

<cvs-export>

<cvs-tag>

<ilasm>

<ildasm>

<loadfile>

<tar>

Task changes

<asminfo>

<attrib>

<available>

<cl>

<csc>

<copy>

<cvs>

<exec>

<get>

<jsc>

<license>

<link>

<move>

<nant>

<ndoc>

<nunit>

<nunit2>

<regex>

<resgen>

<script>

<solution>

<sysinfo>

<vbc>

<vjc>

<xmlpeek> / <xmlpoke>

<zip> / <unzip>

New types

<assemblyfileset>

<warnaserror>

Type changes

<fileset>

Developer information

0.84 (December 26, 2003)

Task changes

<xmlpeek>

<xmlpoke>

0.84-rc 2 (December 21, 2003)

General changes

Task changes

<solution>

<xmlpeek>

<xmlpoke>

0.84-rc 1 (December 6, 2003)

Breaking changes

Some existing build scripts may stop working now or in the next release due to the following changes:

General changes

New Tasks

<asminfo>

<servicecontroller>

<delay-sign>

<mc>,<rc> and <midl>

<xmlpeek>

<xmlpoke>

Task changes

<call>

<cl>

<copy>

<csc>

<cvs-checkout>

<cvs-update>

<echo>

<fail>

<get>

<if>

<include>

<jsc>

<mail>

<move>

<nant>

<nantschema>

<ndoc>

<nunit2>

<property>

<resgen>

<solution>

<style>

<touch>

<vbc>

<vjc>

<zip>

API changes

0.8.3 (September 28, 2003)

User-visible changes

0.8.3-rc3 (August 29, 2003)

User-visible changes

0.8.3-rc2 (July 28, 2003)

User-visible changes

0.8.3-rc1 (July 10, 2003)

User-visible changes

API changes

Command-line client changes

Task changes

<exec>

<vjc>

<jsc>

<csc>

<nantschema>

<mcs>

<nant>

<copy>

<if>

<cl> and <link>

<fileset>

<mail>

0.8.2 (April 24, 2003)

0.8.2-rc3 (April 17, 2003)

0.8.2-rc2 (April 12, 2003)

0.8.2-rc1 (April 12, 2003)

0.8.1 (February 21, 2003)

0.7.9 (June 11, 2002)

0.7.749 (January 19, 2002)

0.6.0 (September 18, 2001)

0.5.0 (August 22, 2001)

0.1.5 (July 22, 2001)

0.1.4 (July 19, 2001)

0.1.3 (July 18, 2001)

0.1.2 (July 16, 2001)

0.1.1 (July 5, 2001)

nant-0.92-rc1/doc/license.html0000644000175000017500000001030211757310021016067 0ustar jtaylorjtaylor NAnt License

NAnt License

Copyright 2001-2008 Gerry Shaw

NAnt logo (link to home page)

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

As a special exception, the copyright holders of this software give you permission to link the assemblies with independent modules to produce new assemblies, regardless of the license terms of these independent modules, and to copy and distribute the resulting assemblies under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on these assemblies. If you modify this software, you may extend this exception to your version of the software, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version.

A copy of the GNU General Public License is available in the COPYING.txt file included with all NAnt distributions.

The GNU Project has more information on the GNU General Public License.

NDoc License

NAnt ships with a prebuilt version of NDoc. The NAnt license does not apply to these components located in the bin folder of the distribution. NDoc is licensed under the GNU General Public License.

NUnit License

NAnt ships with a prebuilt version of NUnit. The NAnt license does not apply to these components located in the bin folder of the distribution. NUnit is licensed under a OSI approved license.

nant-0.92-rc1/doc/help/0000755000175000017500000000000011757310030014513 5ustar jtaylorjtaylornant-0.92-rc1/doc/help/types/0000755000175000017500000000000011757310030015657 5ustar jtaylorjtaylornant-0.92-rc1/doc/help/types/moduleset.html0000644000175000017500000000774711757307467020611 0ustar jtaylorjtaylor <moduleset> Type

<moduleset>

[This is preliminary documentation and subject to change.]

One or more modules to compile into an assembly.

Parameters

Attribute Type Description Required
dir directory The base of the directory of this <moduleset>. The default is the project base directory. False
id string The ID used to be referenced later. False
refid string The ID to use as the reference. False

Nested Elements:

<module>

The modules to add to this <moduleset>.

Represents a metadata file without assembly manifest.

Parameters

AttributeTypeDescriptionRequired
filestring The path of the module. True
targetstring File name where the module should be copied to before it is compiled into an assembly. False

</module>

Examples

Requirements

Assembly: NAnt.DotNetTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/types/tarfileset.html0000644000175000017500000004223611757307422020731 0ustar jtaylorjtaylor <tarfileset> Type

<tarfileset>

[This is preliminary documentation and subject to change.]

A <tarfileset> is a <fileset> with extra attributes useful in the context of the <tar> task.

Parameters

Attribute Type Description Required
dirmode int A 3 digit octal string, specify the user, group and other modes in the standard Unix fashion. Only applies to directories. The default is 755. False
filemode int A 3 digit octal string, specify the user, group and other modes in the standard Unix fashion. Only applies to plain files. The default is 644. False
gid int The group identifier (GID) for the tar entry. False
groupname string The groupname for the tar entry. False
prefix string The top level directory prefix. If set, all file and directory paths in the fileset will have this value prepended. Can either be a single directory name or a "/" separated path. False
uid int The user identifier (UID) for the tar entry. False
username string The username for the tar entry. False
basedir directory The base of the directory of this fileset. The default is the project base directory. False
casesensitive bool Indicates whether include and exclude patterns must be treated in a case-sensitive way. The default is true on Unix; otherwise, false. False
defaultexcludes bool Indicates whether default excludes should be used or not. The default is true. False
failonempty bool When set to true, causes the fileset element to throw a ValidationException when no files match the includes and excludes criteria. The default is false. False
id string The ID used to be referenced later. False
refid string The ID to use as the reference. False

Nested Elements:

<includes>

Deprecated. The items to include in the fileset.

Parameters

AttributeTypeDescriptionRequired
namestring The pattern or file name to include. True
asisbool If true then the file name will be added to the <fileset> without pattern matching or checking if the file exists. The default is false. False
frompathbool If true then the file will be searched for on the path. The default is false. False
ifbool If true then the pattern will be included; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the pattern will be included; otherwise, skipped. The default is false. False

</includes>

<include>

The items to include in the fileset.

Parameters

AttributeTypeDescriptionRequired
namestring The pattern or file name to include. True
asisbool If true then the file name will be added to the <fileset> without pattern matching or checking if the file exists. The default is false. False
frompathbool If true then the file will be searched for on the path. The default is false. False
ifbool If true then the pattern will be included; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the pattern will be included; otherwise, skipped. The default is false. False

</include>

<excludes>

Deprecated. The items to exclude from the fileset.

Parameters

AttributeTypeDescriptionRequired
namestring The pattern or file name to exclude. True
ifbool If true then the pattern will be excluded; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the pattern will be excluded; otherwise, skipped. The default is false. False

</excludes>

<exclude>

The items to exclude from the fileset.

Parameters

AttributeTypeDescriptionRequired
namestring The pattern or file name to exclude. True
ifbool If true then the pattern will be excluded; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the pattern will be excluded; otherwise, skipped. The default is false. False

</exclude>

<includesList>

Deprecated. The files from which a list of patterns or files to include should be obtained.

Parameters

AttributeTypeDescriptionRequired
asisbool If true then the patterns in the include file will be added to the <fileset> without pattern matching or checking if the file exists. The default is false. False
frompathbool If true then the patterns in the include file will be searched for on the path. The default is false. False
ifbool If true then the patterns will be included; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the patterns will be included; otherwise, skipped. The default is false. False
namefile The name of a file; each line of this file is taken to be a pattern. True

</includesList>

<includesfile>

The files from which a list of patterns or files to include should be obtained.

Parameters

AttributeTypeDescriptionRequired
asisbool If true then the patterns in the include file will be added to the <fileset> without pattern matching or checking if the file exists. The default is false. False
frompathbool If true then the patterns in the include file will be searched for on the path. The default is false. False
ifbool If true then the patterns will be included; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the patterns will be included; otherwise, skipped. The default is false. False
namefile The name of a file; each line of this file is taken to be a pattern. True

</includesfile>

<excludesfile>

The files from which a list of patterns or files to exclude should be obtained.

Parameters

AttributeTypeDescriptionRequired
namefile The name of a file; each line of this file is taken to be a pattern. True
ifbool If true then the patterns will be excluded; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the patterns will be excluded; otherwise, skipped. The default is false. False

</excludesfile>

<patternset>

Adds a nested set of patterns, or references a standalone patternset.

</patternset>

Requirements

Assembly: NAnt.CompressionTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/types/credential.html0000644000175000017500000000732711757307441020704 0ustar jtaylorjtaylor <credential> Type

<credential>

[This is preliminary documentation and subject to change.]

Provides credentials for password-based authentication schemes.

Parameters

Attribute Type Description Required
domain string The domain or computer name that verifies the credentials. False
if bool Indicates if the credentials should be used to provide authentication information to the external resource. If true then the credentials will be passed; otherwise, not. The default is true. False
password string The password for the user name associated with the credentials. False
unless bool Indicates if the credentials should not be used to provide authentication information to the external resource. If false then the credentials will be passed; otherwise, not. The default is false. False
username string The user name associated with the credentials. False
id string The ID used to be referenced later. False
refid string The ID to use as the reference. False

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/types/index.html0000644000175000017500000001320311757307413017666 0ustar jtaylorjtaylor Data Type Reference

Type Reference

[This is preliminary documentation and subject to change.]

Type Summary
assemblyfileset Specialized <fileset> class for managing assembly files.
categories Controls the categories of tests to execute using the <nunit2> task.
credential Provides credentials for password-based authentication schemes.
cvsfileset A <cvsfileset> is a <fileset> with extra attributes useful in the context of the <cvs> task.
dirset A specialized <fileset> used for specifying a set of directories.
fileset Filesets are groups of files. These files can be found in a directory tree starting in a base directory and are matched by patterns taken from a number of patterns. Filesets can appear inside tasks that support this feature or at the project level, i.e., as children of <project>.
filterchain Represent a chain of NAnt filters that can be applied to a Task.
moduleset

One or more modules to compile into an assembly.

namespaceimports Contains a collection of NamespaceImport items.
path

Paths are groups of files and/or directories that need to be passed as a single unit. The order in which parts of the path are specified in the build file is retained, and duplicate parts are automatically suppressed.

patternset A set of patterns, mostly used to include or exclude certain files.
proxy Contains HTTP proxy settings used to process requests to Internet resources.
resourcefileset Specialized <fileset> class for managing resource files.
tarfileset A <tarfileset> is a <fileset> with extra attributes useful in the context of the <tar> task.
warnaserror Controls the behaviour of a compiler with regards to the reporting of warnings.
zipfileset A <zipfileset> is a <fileset> with extra attributes useful in the context of the <zip> task.
nant-0.92-rc1/doc/help/types/namespaceimports.html0000644000175000017500000001063311757307462022141 0ustar jtaylorjtaylor <namespaceimports> Type

<namespaceimports>

[This is preliminary documentation and subject to change.]

Contains a collection of NamespaceImport items.

Parameters

Attribute Type Description Required
id string The ID used to be referenced later. False
refid string The ID to use as the reference. False

Nested Elements:

<import>

Adds a NamespaceImport to the end of the collection.

Represents a namespace to import.

Parameters

AttributeTypeDescriptionRequired
ifbool Indicates if the import should be generated. False
namestringDeprecated. The name of the namespace to import. False
namespacestring The name of the namespace to import. False
unlessbool Indicates if the import should be not generated. False

</import>

Examples

Requirements

Assembly: NAnt.DotNetTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/types/proxy.html0000644000175000017500000001015011757307441017737 0ustar jtaylorjtaylor <proxy> Type

<proxy>

[This is preliminary documentation and subject to change.]

Contains HTTP proxy settings used to process requests to Internet resources.

Parameters

Attribute Type Description Required
host string The name of the proxy host. True
port int The port number on host to use. True
bypassonlocal bool Specifies whether to bypass the proxy server for local addresses. The default is false. False
if bool Indicates if the proxy should be used to connect to the external resource. If true then the proxy will be used; otherwise, not. The default is true. False
unless bool Indicates if the proxy should not be used to connect to the external resource. If false then the proxy will be used; otherwise, not. The default is false. False
id string The ID used to be referenced later. False
refid string The ID to use as the reference. False

Nested Elements:

<credentials>

The credentials to submit to the proxy server for authentication.

</credentials>

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/types/assemblyfileset.html0000644000175000017500000007413311757307466021773 0ustar jtaylorjtaylor <assemblyfileset> Type

<assemblyfileset>

[This is preliminary documentation and subject to change.]

Specialized <fileset> class for managing assembly files.

If an include pattern does not contain any wildcard characters then the assembly will be searched for in following locations (in the order listed):

The reference assemblies of a given target framework are defined using <reference-assemblies> filesets in the <framework> node of the NAnt configuration file.

Parameters

Attribute Type Description Required
basedir directory The base of the directory of this fileset. The default is the project base directory. False
casesensitive bool Indicates whether include and exclude patterns must be treated in a case-sensitive way. The default is true on Unix; otherwise, false. False
defaultexcludes bool Indicates whether default excludes should be used or not. The default is true. False
failonempty bool When set to true, causes the fileset element to throw a ValidationException when no files match the includes and excludes criteria. The default is false. False
id string The ID used to be referenced later. False
refid string The ID to use as the reference. False

Nested Elements:

<lib>

Additional directories to search in for assembly references.

A specialized <fileset> used for setting the lib directories.

The primary reason for this class is to allow the BaseDirectory to always be the same value as the parent <assemblyfileset>

Parameters

AttributeTypeDescriptionRequired
casesensitivebool Indicates whether include and exclude patterns must be treated in a case-sensitive way. The default is true on Unix; otherwise, false. False
defaultexcludesbool Indicates whether default excludes should be used or not. The default is true. False
failonemptybool When set to true, causes the fileset element to throw a ValidationException when no files match the includes and excludes criteria. The default is false. False
idstring The ID used to be referenced later. False
refidstring The ID to use as the reference. False

Nested Elements:

<includes>

Deprecated. The items to include in the fileset.

Parameters

AttributeTypeDescriptionRequired
namestring The pattern or file name to include. True
asisbool If true then the file name will be added to the <fileset> without pattern matching or checking if the file exists. The default is false. False
frompathbool If true then the file will be searched for on the path. The default is false. False
ifbool If true then the pattern will be included; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the pattern will be included; otherwise, skipped. The default is false. False

</includes>

<include>

The items to include in the fileset.

Parameters

AttributeTypeDescriptionRequired
namestring The pattern or file name to include. True
asisbool If true then the file name will be added to the <fileset> without pattern matching or checking if the file exists. The default is false. False
frompathbool If true then the file will be searched for on the path. The default is false. False
ifbool If true then the pattern will be included; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the pattern will be included; otherwise, skipped. The default is false. False

</include>

<excludes>

Deprecated. The items to exclude from the fileset.

Parameters

AttributeTypeDescriptionRequired
namestring The pattern or file name to exclude. True
ifbool If true then the pattern will be excluded; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the pattern will be excluded; otherwise, skipped. The default is false. False

</excludes>

<exclude>

The items to exclude from the fileset.

Parameters

AttributeTypeDescriptionRequired
namestring The pattern or file name to exclude. True
ifbool If true then the pattern will be excluded; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the pattern will be excluded; otherwise, skipped. The default is false. False

</exclude>

<includesList>

Deprecated. The files from which a list of patterns or files to include should be obtained.

Parameters

AttributeTypeDescriptionRequired
asisbool If true then the patterns in the include file will be added to the <fileset> without pattern matching or checking if the file exists. The default is false. False
frompathbool If true then the patterns in the include file will be searched for on the path. The default is false. False
ifbool If true then the patterns will be included; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the patterns will be included; otherwise, skipped. The default is false. False
namefile The name of a file; each line of this file is taken to be a pattern. True

</includesList>

<includesfile>

The files from which a list of patterns or files to include should be obtained.

Parameters

AttributeTypeDescriptionRequired
asisbool If true then the patterns in the include file will be added to the <fileset> without pattern matching or checking if the file exists. The default is false. False
frompathbool If true then the patterns in the include file will be searched for on the path. The default is false. False
ifbool If true then the patterns will be included; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the patterns will be included; otherwise, skipped. The default is false. False
namefile The name of a file; each line of this file is taken to be a pattern. True

</includesfile>

<excludesfile>

The files from which a list of patterns or files to exclude should be obtained.

Parameters

AttributeTypeDescriptionRequired
namefile The name of a file; each line of this file is taken to be a pattern. True
ifbool If true then the patterns will be excluded; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the patterns will be excluded; otherwise, skipped. The default is false. False

</excludesfile>

<patternset>

Adds a nested set of patterns, or references a standalone patternset.

</patternset>

</lib>

<includes>

Deprecated. The items to include in the fileset.

Parameters

AttributeTypeDescriptionRequired
namestring The pattern or file name to include. True
asisbool If true then the file name will be added to the <fileset> without pattern matching or checking if the file exists. The default is false. False
frompathbool If true then the file will be searched for on the path. The default is false. False
ifbool If true then the pattern will be included; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the pattern will be included; otherwise, skipped. The default is false. False

</includes>

<include>

The items to include in the fileset.

Parameters

AttributeTypeDescriptionRequired
namestring The pattern or file name to include. True
asisbool If true then the file name will be added to the <fileset> without pattern matching or checking if the file exists. The default is false. False
frompathbool If true then the file will be searched for on the path. The default is false. False
ifbool If true then the pattern will be included; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the pattern will be included; otherwise, skipped. The default is false. False

</include>

<excludes>

Deprecated. The items to exclude from the fileset.

Parameters

AttributeTypeDescriptionRequired
namestring The pattern or file name to exclude. True
ifbool If true then the pattern will be excluded; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the pattern will be excluded; otherwise, skipped. The default is false. False

</excludes>

<exclude>

The items to exclude from the fileset.

Parameters

AttributeTypeDescriptionRequired
namestring The pattern or file name to exclude. True
ifbool If true then the pattern will be excluded; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the pattern will be excluded; otherwise, skipped. The default is false. False

</exclude>

<includesList>

Deprecated. The files from which a list of patterns or files to include should be obtained.

Parameters

AttributeTypeDescriptionRequired
asisbool If true then the patterns in the include file will be added to the <fileset> without pattern matching or checking if the file exists. The default is false. False
frompathbool If true then the patterns in the include file will be searched for on the path. The default is false. False
ifbool If true then the patterns will be included; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the patterns will be included; otherwise, skipped. The default is false. False
namefile The name of a file; each line of this file is taken to be a pattern. True

</includesList>

<includesfile>

The files from which a list of patterns or files to include should be obtained.

Parameters

AttributeTypeDescriptionRequired
asisbool If true then the patterns in the include file will be added to the <fileset> without pattern matching or checking if the file exists. The default is false. False
frompathbool If true then the patterns in the include file will be searched for on the path. The default is false. False
ifbool If true then the patterns will be included; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the patterns will be included; otherwise, skipped. The default is false. False
namefile The name of a file; each line of this file is taken to be a pattern. True

</includesfile>

<excludesfile>

The files from which a list of patterns or files to exclude should be obtained.

Parameters

AttributeTypeDescriptionRequired
namefile The name of a file; each line of this file is taken to be a pattern. True
ifbool If true then the patterns will be excluded; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the patterns will be excluded; otherwise, skipped. The default is false. False

</excludesfile>

<patternset>

Adds a nested set of patterns, or references a standalone patternset.

</patternset>

Examples

Requirements

Assembly: NAnt.DotNetTasks (0.92.4526.0)

See Also

<fileset> nant-0.92-rc1/doc/help/types/warnaserror.html0000644000175000017500000001320711757307471021134 0ustar jtaylorjtaylor <warnaserror> Type

<warnaserror>

[This is preliminary documentation and subject to change.]

Controls the behaviour of a compiler with regards to the reporting of warnings.

Parameters

Attribute Type Description Required
id string The ID used to be referenced later. False
refid string The ID to use as the reference. False

Nested Elements:

<include>

Specifies a list of warnings that the compiler should treat as errors. This overrides the warnaserror attribute. Only supported when targeting .NET 2.0 or higher.

Represents a compiler warning.

Parameters

AttributeTypeDescriptionRequired
numberstring A warning number, or comma-separated list of warnings, that you want the compiler to suppress or report. True
ifbool If true then the element will be processed; otherwise, skipped. The default is true. False
unlessbool If true then the element will be skipped; otherwise, processed. The default is false. False

</include>

<exclude>

Specifies a list of warnings that the compiler should NOT treat as errors. This is only useful if warnaserror is true. Only supported when targeting .NET 2.0 or higher.

Represents a compiler warning.

Parameters

AttributeTypeDescriptionRequired
numberstring A warning number, or comma-separated list of warnings, that you want the compiler to suppress or report. True
ifbool If true then the element will be processed; otherwise, skipped. The default is true. False
unlessbool If true then the element will be skipped; otherwise, processed. The default is false. False

</exclude>

Examples

Requirements

Assembly: NAnt.DotNetTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/types/cvsfileset.html0000644000175000017500000003706011757307530020735 0ustar jtaylorjtaylor <cvsfileset> Type

<cvsfileset>

[This is preliminary documentation and subject to change.]

A <cvsfileset> is a <fileset> with extra attributes useful in the context of the <cvs> task.

Parameters

Attribute Type Description Required
usecvsignore bool Indicates whether the entires in the .cvsignore should be used to limit the file list; true to exclude files in .cvsignore, otherwise false. The default is true. False
basedir directory The base of the directory of this fileset. The default is the project base directory. False
casesensitive bool Indicates whether include and exclude patterns must be treated in a case-sensitive way. The default is true on Unix; otherwise, false. False
defaultexcludes bool Indicates whether default excludes should be used or not. The default is true. False
failonempty bool When set to true, causes the fileset element to throw a ValidationException when no files match the includes and excludes criteria. The default is false. False
id string The ID used to be referenced later. False
refid string The ID to use as the reference. False

Nested Elements:

<includes>

Deprecated. The items to include in the fileset.

Parameters

AttributeTypeDescriptionRequired
namestring The pattern or file name to include. True
asisbool If true then the file name will be added to the <fileset> without pattern matching or checking if the file exists. The default is false. False
frompathbool If true then the file will be searched for on the path. The default is false. False
ifbool If true then the pattern will be included; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the pattern will be included; otherwise, skipped. The default is false. False

</includes>

<include>

The items to include in the fileset.

Parameters

AttributeTypeDescriptionRequired
namestring The pattern or file name to include. True
asisbool If true then the file name will be added to the <fileset> without pattern matching or checking if the file exists. The default is false. False
frompathbool If true then the file will be searched for on the path. The default is false. False
ifbool If true then the pattern will be included; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the pattern will be included; otherwise, skipped. The default is false. False

</include>

<excludes>

Deprecated. The items to exclude from the fileset.

Parameters

AttributeTypeDescriptionRequired
namestring The pattern or file name to exclude. True
ifbool If true then the pattern will be excluded; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the pattern will be excluded; otherwise, skipped. The default is false. False

</excludes>

<exclude>

The items to exclude from the fileset.

Parameters

AttributeTypeDescriptionRequired
namestring The pattern or file name to exclude. True
ifbool If true then the pattern will be excluded; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the pattern will be excluded; otherwise, skipped. The default is false. False

</exclude>

<includesList>

Deprecated. The files from which a list of patterns or files to include should be obtained.

Parameters

AttributeTypeDescriptionRequired
asisbool If true then the patterns in the include file will be added to the <fileset> without pattern matching or checking if the file exists. The default is false. False
frompathbool If true then the patterns in the include file will be searched for on the path. The default is false. False
ifbool If true then the patterns will be included; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the patterns will be included; otherwise, skipped. The default is false. False
namefile The name of a file; each line of this file is taken to be a pattern. True

</includesList>

<includesfile>

The files from which a list of patterns or files to include should be obtained.

Parameters

AttributeTypeDescriptionRequired
asisbool If true then the patterns in the include file will be added to the <fileset> without pattern matching or checking if the file exists. The default is false. False
frompathbool If true then the patterns in the include file will be searched for on the path. The default is false. False
ifbool If true then the patterns will be included; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the patterns will be included; otherwise, skipped. The default is false. False
namefile The name of a file; each line of this file is taken to be a pattern. True

</includesfile>

<excludesfile>

The files from which a list of patterns or files to exclude should be obtained.

Parameters

AttributeTypeDescriptionRequired
namefile The name of a file; each line of this file is taken to be a pattern. True
ifbool If true then the patterns will be excluded; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the patterns will be excluded; otherwise, skipped. The default is false. False

</excludesfile>

<patternset>

Adds a nested set of patterns, or references a standalone patternset.

</patternset>

Requirements

Assembly: NAnt.SourceControlTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/types/resourcefileset.html0000644000175000017500000003737411757307473022007 0ustar jtaylorjtaylor <resourcefileset> Type

<resourcefileset>

[This is preliminary documentation and subject to change.]

Specialized <fileset> class for managing resource files.

Parameters

Attribute Type Description Required
dynamicprefix bool Indicates whether prefixes should be dynamically generated by taking the path of the resource relative to the basedir and appending it to the specified prefix. The default is false. False
prefix string Indicates the prefix to prepend to the actual resource. This is usually the default namspace of the assembly. False
basedir directory The base of the directory of this fileset. The default is the project base directory. False
casesensitive bool Indicates whether include and exclude patterns must be treated in a case-sensitive way. The default is true on Unix; otherwise, false. False
defaultexcludes bool Indicates whether default excludes should be used or not. The default is true. False
failonempty bool When set to true, causes the fileset element to throw a ValidationException when no files match the includes and excludes criteria. The default is false. False
id string The ID used to be referenced later. False
refid string The ID to use as the reference. False

Nested Elements:

<includes>

Deprecated. The items to include in the fileset.

Parameters

AttributeTypeDescriptionRequired
namestring The pattern or file name to include. True
asisbool If true then the file name will be added to the <fileset> without pattern matching or checking if the file exists. The default is false. False
frompathbool If true then the file will be searched for on the path. The default is false. False
ifbool If true then the pattern will be included; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the pattern will be included; otherwise, skipped. The default is false. False

</includes>

<include>

The items to include in the fileset.

Parameters

AttributeTypeDescriptionRequired
namestring The pattern or file name to include. True
asisbool If true then the file name will be added to the <fileset> without pattern matching or checking if the file exists. The default is false. False
frompathbool If true then the file will be searched for on the path. The default is false. False
ifbool If true then the pattern will be included; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the pattern will be included; otherwise, skipped. The default is false. False

</include>

<excludes>

Deprecated. The items to exclude from the fileset.

Parameters

AttributeTypeDescriptionRequired
namestring The pattern or file name to exclude. True
ifbool If true then the pattern will be excluded; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the pattern will be excluded; otherwise, skipped. The default is false. False

</excludes>

<exclude>

The items to exclude from the fileset.

Parameters

AttributeTypeDescriptionRequired
namestring The pattern or file name to exclude. True
ifbool If true then the pattern will be excluded; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the pattern will be excluded; otherwise, skipped. The default is false. False

</exclude>

<includesList>

Deprecated. The files from which a list of patterns or files to include should be obtained.

Parameters

AttributeTypeDescriptionRequired
asisbool If true then the patterns in the include file will be added to the <fileset> without pattern matching or checking if the file exists. The default is false. False
frompathbool If true then the patterns in the include file will be searched for on the path. The default is false. False
ifbool If true then the patterns will be included; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the patterns will be included; otherwise, skipped. The default is false. False
namefile The name of a file; each line of this file is taken to be a pattern. True

</includesList>

<includesfile>

The files from which a list of patterns or files to include should be obtained.

Parameters

AttributeTypeDescriptionRequired
asisbool If true then the patterns in the include file will be added to the <fileset> without pattern matching or checking if the file exists. The default is false. False
frompathbool If true then the patterns in the include file will be searched for on the path. The default is false. False
ifbool If true then the patterns will be included; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the patterns will be included; otherwise, skipped. The default is false. False
namefile The name of a file; each line of this file is taken to be a pattern. True

</includesfile>

<excludesfile>

The files from which a list of patterns or files to exclude should be obtained.

Parameters

AttributeTypeDescriptionRequired
namefile The name of a file; each line of this file is taken to be a pattern. True
ifbool If true then the patterns will be excluded; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the patterns will be excluded; otherwise, skipped. The default is false. False

</excludesfile>

<patternset>

Adds a nested set of patterns, or references a standalone patternset.

</patternset>

Requirements

Assembly: NAnt.DotNetTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/types/categories.html0000644000175000017500000001242411757307524020713 0ustar jtaylorjtaylor <categories> Type

<categories>

[This is preliminary documentation and subject to change.]

Controls the categories of tests to execute using the <nunit2> task.

Parameters

Attribute Type Description Required
id string The ID used to be referenced later. False
refid string The ID to use as the reference. False

Nested Elements:

<include>

Specifies a list of categories to include.

Represents a certain group of test cases or fixtures.

Parameters

AttributeTypeDescriptionRequired
namestring A name of a category, or comma-separated list of names. True
ifbool If true then the category will be processed; otherwise, skipped. The default is true. False
unlessbool If true then the category will be skipped; otherwise, processed. The default is false. False

</include>

<exclude>

Specifies a list of categories to exclude.

Represents a certain group of test cases or fixtures.

Parameters

AttributeTypeDescriptionRequired
namestring A name of a category, or comma-separated list of names. True
ifbool If true then the category will be processed; otherwise, skipped. The default is true. False
unlessbool If true then the category will be skipped; otherwise, processed. The default is false. False

</exclude>

Examples

Requirements

Assembly: NAnt.NUnit2Tasks (0.92.4526.0)
nant-0.92-rc1/doc/help/types/patternset.html0000644000175000017500000003146311757307462020764 0ustar jtaylorjtaylor <patternset> Type

<patternset>

[This is preliminary documentation and subject to change.]

A set of patterns, mostly used to include or exclude certain files.

The individual patterns support if and unless attributes to specify that the element should only be used if or unless a given condition is met.

The includesfile and excludesfile elements load patterns from a file. When the file is a relative path, it will be resolved relative to the project base directory in which the patternset is defined. Each line of this file is taken to be a pattern.

The number sign (#) as the first non-blank character in a line denotes that all text following it is a comment:

     EventLog.cs
     # requires Mono.Posix
     SysLogEventLogImpl.cs
     # uses the win32 eventlog API
     Win32EventLogImpl.cs
  

Patterns can be grouped to sets, and later be referenced by their id.

When used as a standalone element (global type), any properties that are referenced will be resolved when the definition is processed, not when it actually used. Passing a reference to a nested build file will not cause the properties to be re-evaluated.

To improve reuse of globally defined patternsets, avoid referencing any properties altogether.

Parameters

Attribute Type Description Required
id string The ID used to be referenced later. False
refid string The ID to use as the reference. False

Nested Elements:

<include>

Defines a single pattern for files to include.

Parameters

AttributeTypeDescriptionRequired
namestring The name pattern to include/exclude. True
ifbool If true then the pattern will be used; otherwise, skipped. The default is true. False
unlessbool If false then the pattern will be used; otherwise, skipped. The default is false. False

</include>

<includesfile>

Loads multiple patterns of files to include from a given file, set using the name parameter.

Parameters

AttributeTypeDescriptionRequired
namestring The name pattern to include/exclude. True
ifbool If true then the pattern will be used; otherwise, skipped. The default is true. False
unlessbool If false then the pattern will be used; otherwise, skipped. The default is false. False

</includesfile>

<exclude>

Defines a single pattern for files to exclude.

Parameters

AttributeTypeDescriptionRequired
namestring The name pattern to include/exclude. True
ifbool If true then the pattern will be used; otherwise, skipped. The default is true. False
unlessbool If false then the pattern will be used; otherwise, skipped. The default is false. False

</exclude>

<excludesfile>

Loads multiple patterns of files to exclude from a given file, set using the name parameter.

Parameters

AttributeTypeDescriptionRequired
namestring The name pattern to include/exclude. True
ifbool If true then the pattern will be used; otherwise, skipped. The default is true. False
unlessbool If false then the pattern will be used; otherwise, skipped. The default is false. False

</excludesfile>

<patternset>

Adds a nested set of patterns, or references other standalone patternset.

</patternset>

Examples

Requirements

Assembly: NAnt.Core (0.92.4526.0)

See Also

<fileset> nant-0.92-rc1/doc/help/types/fileset.html0000644000175000017500000005271011757307430020217 0ustar jtaylorjtaylor <fileset> Type

<fileset>

[This is preliminary documentation and subject to change.]

Filesets are groups of files. These files can be found in a directory tree starting in a base directory and are matched by patterns taken from a number of patterns. Filesets can appear inside tasks that support this feature or at the project level, i.e., as children of <project>.

Patterns

As described earlier, patterns are used for the inclusion and exclusion. These patterns look very much like the patterns used in DOS and UNIX:

Combinations of *'s and ?'s are allowed.

Matching is done per-directory. This means that first the first directory in the pattern is matched against the first directory in the path to match. Then the second directory is matched, and so on. For example, when we have the pattern /?abc/*/*.cs and the path /xabc/foobar/test.cs, the first ?abc is matched with xabc, then * is matched with foobar, and finally *.cs is matched with test.cs. They all match, so the path matches the pattern.

To make things a bit more flexible, we added one extra feature, which makes it possible to match multiple directory levels. This can be used to match a complete directory tree, or a file anywhere in the directory tree. To do this, ** must be used as the name of a directory. When ** is used as the name of a directory in the pattern, it matches zero or more directories. For example: /test/** matches all files/directories under /test/, such as /test/x.cs, or /test/foo/bar/xyz.html, but not /xyz.xml.

There is one "shorthand" - if a pattern ends with / or \, then ** is appended. For example, mypackage/test/ is interpreted as if it were mypackage/test/**.

Case-Sensitivity

By default, pattern matching is case-sensitive on Unix and case-insensitive on other platforms. The casesensitive parameter can be used to override this.

Default Excludes

There are a set of definitions that are excluded by default from all tasks that use filesets. They are:

If you do not want these default excludes applied, you may disable them by setting defaultexcludes to false.

Parameters

Attribute Type Description Required
basedir directory The base of the directory of this fileset. The default is the project base directory. False
casesensitive bool Indicates whether include and exclude patterns must be treated in a case-sensitive way. The default is true on Unix; otherwise, false. False
defaultexcludes bool Indicates whether default excludes should be used or not. The default is true. False
failonempty bool When set to true, causes the fileset element to throw a ValidationException when no files match the includes and excludes criteria. The default is false. False
id string The ID used to be referenced later. False
refid string The ID to use as the reference. False

Nested Elements:

<includes>

Deprecated. The items to include in the fileset.

Parameters

AttributeTypeDescriptionRequired
namestring The pattern or file name to include. True
asisbool If true then the file name will be added to the <fileset> without pattern matching or checking if the file exists. The default is false. False
frompathbool If true then the file will be searched for on the path. The default is false. False
ifbool If true then the pattern will be included; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the pattern will be included; otherwise, skipped. The default is false. False

</includes>

<include>

The items to include in the fileset.

Parameters

AttributeTypeDescriptionRequired
namestring The pattern or file name to include. True
asisbool If true then the file name will be added to the <fileset> without pattern matching or checking if the file exists. The default is false. False
frompathbool If true then the file will be searched for on the path. The default is false. False
ifbool If true then the pattern will be included; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the pattern will be included; otherwise, skipped. The default is false. False

</include>

<excludes>

Deprecated. The items to exclude from the fileset.

Parameters

AttributeTypeDescriptionRequired
namestring The pattern or file name to exclude. True
ifbool If true then the pattern will be excluded; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the pattern will be excluded; otherwise, skipped. The default is false. False

</excludes>

<exclude>

The items to exclude from the fileset.

Parameters

AttributeTypeDescriptionRequired
namestring The pattern or file name to exclude. True
ifbool If true then the pattern will be excluded; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the pattern will be excluded; otherwise, skipped. The default is false. False

</exclude>

<includesList>

Deprecated. The files from which a list of patterns or files to include should be obtained.

Parameters

AttributeTypeDescriptionRequired
asisbool If true then the patterns in the include file will be added to the <fileset> without pattern matching or checking if the file exists. The default is false. False
frompathbool If true then the patterns in the include file will be searched for on the path. The default is false. False
ifbool If true then the patterns will be included; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the patterns will be included; otherwise, skipped. The default is false. False
namefile The name of a file; each line of this file is taken to be a pattern. True

</includesList>

<includesfile>

The files from which a list of patterns or files to include should be obtained.

Parameters

AttributeTypeDescriptionRequired
asisbool If true then the patterns in the include file will be added to the <fileset> without pattern matching or checking if the file exists. The default is false. False
frompathbool If true then the patterns in the include file will be searched for on the path. The default is false. False
ifbool If true then the patterns will be included; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the patterns will be included; otherwise, skipped. The default is false. False
namefile The name of a file; each line of this file is taken to be a pattern. True

</includesfile>

<excludesfile>

The files from which a list of patterns or files to exclude should be obtained.

Parameters

AttributeTypeDescriptionRequired
namefile The name of a file; each line of this file is taken to be a pattern. True
ifbool If true then the patterns will be excluded; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the patterns will be excluded; otherwise, skipped. The default is false. False

</excludesfile>

<patternset>

Adds a nested set of patterns, or references a standalone patternset.

</patternset>

Examples

Requirements

Assembly: NAnt.Core (0.92.4526.0)

See Also

<patternset> nant-0.92-rc1/doc/help/types/path.html0000644000175000017500000001174111757307435017524 0ustar jtaylorjtaylor <path> Type

<path>

[This is preliminary documentation and subject to change.]

Paths are groups of files and/or directories that need to be passed as a single unit. The order in which parts of the path are specified in the build file is retained, and duplicate parts are automatically suppressed.

Parameters

Attribute Type Description Required
id string The ID used to be referenced later. False
refid string The ID to use as the reference. False

Nested Elements:

<path>

Defines a set of path elements to add to the current path.

</path>

<pathelement>

Defines a path element to add to the current path.

Represents a nested path element.

Parameters

AttributeTypeDescriptionRequired
dirdirectory The name of a directory to add to the path. Will be replaced with the absolute path of the directory. False
filefile The name of a file to add to the path. Will be replaced with the absolute path of the file. False
ifbool If true then the entry will be added to the path; otherwise, skipped. The default is true. False
path<path> A string that will be treated as a path-like string. You can use : or ; as path separators and NAnt will convert it to the platform's local conventions, while resolving references to environment variables. False
unlessbool Opposite of if. If false then the entry will be added to the path; otherwise, skipped. The default is false. False

</pathelement>

Examples

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/types/zipfileset.html0000644000175000017500000003704411757307425020751 0ustar jtaylorjtaylor <zipfileset> Type

<zipfileset>

[This is preliminary documentation and subject to change.]

A <zipfileset> is a <fileset> with extra attributes useful in the context of the <zip> task.

Parameters

Attribute Type Description Required
prefix string The top level directory prefix. If set, all file and directory paths in the fileset will have this value prepended. Can either be a single directory name or a "/" separated path. False
basedir directory The base of the directory of this fileset. The default is the project base directory. False
casesensitive bool Indicates whether include and exclude patterns must be treated in a case-sensitive way. The default is true on Unix; otherwise, false. False
defaultexcludes bool Indicates whether default excludes should be used or not. The default is true. False
failonempty bool When set to true, causes the fileset element to throw a ValidationException when no files match the includes and excludes criteria. The default is false. False
id string The ID used to be referenced later. False
refid string The ID to use as the reference. False

Nested Elements:

<includes>

Deprecated. The items to include in the fileset.

Parameters

AttributeTypeDescriptionRequired
namestring The pattern or file name to include. True
asisbool If true then the file name will be added to the <fileset> without pattern matching or checking if the file exists. The default is false. False
frompathbool If true then the file will be searched for on the path. The default is false. False
ifbool If true then the pattern will be included; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the pattern will be included; otherwise, skipped. The default is false. False

</includes>

<include>

The items to include in the fileset.

Parameters

AttributeTypeDescriptionRequired
namestring The pattern or file name to include. True
asisbool If true then the file name will be added to the <fileset> without pattern matching or checking if the file exists. The default is false. False
frompathbool If true then the file will be searched for on the path. The default is false. False
ifbool If true then the pattern will be included; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the pattern will be included; otherwise, skipped. The default is false. False

</include>

<excludes>

Deprecated. The items to exclude from the fileset.

Parameters

AttributeTypeDescriptionRequired
namestring The pattern or file name to exclude. True
ifbool If true then the pattern will be excluded; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the pattern will be excluded; otherwise, skipped. The default is false. False

</excludes>

<exclude>

The items to exclude from the fileset.

Parameters

AttributeTypeDescriptionRequired
namestring The pattern or file name to exclude. True
ifbool If true then the pattern will be excluded; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the pattern will be excluded; otherwise, skipped. The default is false. False

</exclude>

<includesList>

Deprecated. The files from which a list of patterns or files to include should be obtained.

Parameters

AttributeTypeDescriptionRequired
asisbool If true then the patterns in the include file will be added to the <fileset> without pattern matching or checking if the file exists. The default is false. False
frompathbool If true then the patterns in the include file will be searched for on the path. The default is false. False
ifbool If true then the patterns will be included; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the patterns will be included; otherwise, skipped. The default is false. False
namefile The name of a file; each line of this file is taken to be a pattern. True

</includesList>

<includesfile>

The files from which a list of patterns or files to include should be obtained.

Parameters

AttributeTypeDescriptionRequired
asisbool If true then the patterns in the include file will be added to the <fileset> without pattern matching or checking if the file exists. The default is false. False
frompathbool If true then the patterns in the include file will be searched for on the path. The default is false. False
ifbool If true then the patterns will be included; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the patterns will be included; otherwise, skipped. The default is false. False
namefile The name of a file; each line of this file is taken to be a pattern. True

</includesfile>

<excludesfile>

The files from which a list of patterns or files to exclude should be obtained.

Parameters

AttributeTypeDescriptionRequired
namefile The name of a file; each line of this file is taken to be a pattern. True
ifbool If true then the patterns will be excluded; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the patterns will be excluded; otherwise, skipped. The default is false. False

</excludesfile>

<patternset>

Adds a nested set of patterns, or references a standalone patternset.

</patternset>

Requirements

Assembly: NAnt.CompressionTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/types/filterchain.html0000644000175000017500000001314511757307426021060 0ustar jtaylorjtaylor <filterchain> Type

<filterchain>

[This is preliminary documentation and subject to change.]

Represent a chain of NAnt filters that can be applied to a Task.

A FilterChain represents a collection of one or more filters that can be appled to a Task such as the <copy> task. In the case of the <copy> task, the contents of the copied files are filtered through each filter specified in the filter chain. Filtering occurs in the order the filters are specified with filtered output of one filter feeding into another.

:--------:--->:----------:--->:----------: ... :----------:--->:--------:

:.Source.:--->:.Filter 1.:--->:.Filter 2.: ... :.Filter n.:--->:.target.:

:--------:--->:----------:--->:----------: ... :----------:--->:--------:

A list of all filters that come with NAnt is available here.

The following tasks support filtering with a FilterChain:

Parameters

Attribute Type Description Required
encoding Encoding Deprecated. The encoding to assume when filter-copying files. The default is system's current ANSI code page. False
id string The ID used to be referenced later. False
refid string The ID to use as the reference. False

Nested Elements:

<filter>

The filters to apply.

Allows a file's content to be modified while performing an operation.

Parameters

AttributeTypeDescriptionRequired
ifbool If true then the filter will be used; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the filter will be executed; otherwise, skipped. The default is false. False

</filter>

Examples

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/types/dirset.html0000644000175000017500000003412411757307461020061 0ustar jtaylorjtaylor <dirset> Type

<dirset>

[This is preliminary documentation and subject to change.]

A specialized <fileset> used for specifying a set of directories.

Hint for supporting tasks that the included directories instead of files should be used.

Parameters

AttributeTypeDescriptionRequired
basedirdirectory The base of the directory of this fileset. The default is the project base directory. False
casesensitivebool Indicates whether include and exclude patterns must be treated in a case-sensitive way. The default is true on Unix; otherwise, false. False
defaultexcludesbool Indicates whether default excludes should be used or not. The default is true. False
failonemptybool When set to true, causes the fileset element to throw a ValidationException when no files match the includes and excludes criteria. The default is false. False
idstring The ID used to be referenced later. False
refidstring The ID to use as the reference. False

Nested Elements:

<includes>

Deprecated. The items to include in the fileset.

Parameters

AttributeTypeDescriptionRequired
namestring The pattern or file name to include. True
asisbool If true then the file name will be added to the <fileset> without pattern matching or checking if the file exists. The default is false. False
frompathbool If true then the file will be searched for on the path. The default is false. False
ifbool If true then the pattern will be included; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the pattern will be included; otherwise, skipped. The default is false. False

</includes>

<include>

The items to include in the fileset.

Parameters

AttributeTypeDescriptionRequired
namestring The pattern or file name to include. True
asisbool If true then the file name will be added to the <fileset> without pattern matching or checking if the file exists. The default is false. False
frompathbool If true then the file will be searched for on the path. The default is false. False
ifbool If true then the pattern will be included; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the pattern will be included; otherwise, skipped. The default is false. False

</include>

<excludes>

Deprecated. The items to exclude from the fileset.

Parameters

AttributeTypeDescriptionRequired
namestring The pattern or file name to exclude. True
ifbool If true then the pattern will be excluded; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the pattern will be excluded; otherwise, skipped. The default is false. False

</excludes>

<exclude>

The items to exclude from the fileset.

Parameters

AttributeTypeDescriptionRequired
namestring The pattern or file name to exclude. True
ifbool If true then the pattern will be excluded; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the pattern will be excluded; otherwise, skipped. The default is false. False

</exclude>

<includesList>

Deprecated. The files from which a list of patterns or files to include should be obtained.

Parameters

AttributeTypeDescriptionRequired
asisbool If true then the patterns in the include file will be added to the <fileset> without pattern matching or checking if the file exists. The default is false. False
frompathbool If true then the patterns in the include file will be searched for on the path. The default is false. False
ifbool If true then the patterns will be included; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the patterns will be included; otherwise, skipped. The default is false. False
namefile The name of a file; each line of this file is taken to be a pattern. True

</includesList>

<includesfile>

The files from which a list of patterns or files to include should be obtained.

Parameters

AttributeTypeDescriptionRequired
asisbool If true then the patterns in the include file will be added to the <fileset> without pattern matching or checking if the file exists. The default is false. False
frompathbool If true then the patterns in the include file will be searched for on the path. The default is false. False
ifbool If true then the patterns will be included; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the patterns will be included; otherwise, skipped. The default is false. False
namefile The name of a file; each line of this file is taken to be a pattern. True

</includesfile>

<excludesfile>

The files from which a list of patterns or files to exclude should be obtained.

Parameters

AttributeTypeDescriptionRequired
namefile The name of a file; each line of this file is taken to be a pattern. True
ifbool If true then the patterns will be excluded; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the patterns will be excluded; otherwise, skipped. The default is false. False

</excludesfile>

<patternset>

Adds a nested set of patterns, or references a standalone patternset.

</patternset>

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/index.html0000644000175000017500000000567611757310021016526 0ustar jtaylorjtaylor NAnt Help

NAnt Help

NAnt logo (link to home page)

[This is preliminary documentation and subject to change.]

 > Introduction
Requirements, installation, quick start, history of NAnt and other miscellaneous topics.

 > Fundamentals
The basic concepts needed to understand and use NAnt.

 > Task Reference
List of Tasks.

 > Type Reference
List of global (referencable) Types.

 > Function Reference
List of Functions that can be used in Expressions.

 > Filter Reference
List of Filters that can be used in FilterChains.


Portions of this document have been directly copied from the Apache Ant user manual.

nant-0.92-rc1/doc/help/filters/0000755000175000017500000000000011757310030016163 5ustar jtaylorjtaylornant-0.92-rc1/doc/help/filters/tabstospaces.html0000644000175000017500000000601411757307427021565 0ustar jtaylorjtaylor <tabstospaces> Filter

<tabstospaces>

[This is preliminary documentation and subject to change.]

Converts tabs to spaces.

The <tabstospaces> filter replaces tabs in a text file with spaces.

Filters are intended to be used as a element of a <filterchain>.

Parameters

Attribute Type Description Required
tablength int The number of spaces used when converting a tab. The default is "8". False
if bool If true then the filter will be used; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the filter will be executed; otherwise, skipped. The default is false. False

Examples

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/filters/index.html0000644000175000017500000000415211757307413020175 0ustar jtaylorjtaylor Filter Reference

Filter Reference

[This is preliminary documentation and subject to change.]

Filter Summary
expandproperties Parses NAnt properties and expressions
replacestring Replaces all occurrences of a given string in the original input with user-supplied replacement string.
replacetokens Replaces tokens in the original input with user-supplied values.
tabstospaces Converts tabs to spaces.
nant-0.92-rc1/doc/help/filters/expandproperties.html0000644000175000017500000000513311757307426022466 0ustar jtaylorjtaylor <expandproperties> Filter

<expandproperties>

[This is preliminary documentation and subject to change.]

Parses NAnt properties and expressions

This filter parses any NAnt properties or expressions found in its input, inlining their values in its output.

Note: Due to limitations on buffering, expressions longer than 2048 characters are not guaranteed to be expanded.

Filters are intended to be used as a element of a <filterchain>.

Parameters

AttributeTypeDescriptionRequired
ifbool If true then the filter will be used; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the filter will be executed; otherwise, skipped. The default is false. False

Examples

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/filters/replacestring.html0000644000175000017500000001024111757307427021731 0ustar jtaylorjtaylor <replacestring> Filter

<replacestring>

[This is preliminary documentation and subject to change.]

Replaces all occurrences of a given string in the original input with user-supplied replacement string.

This filter replaces all occurrences of a given string in the original input stream with a user-supplied replacement string. By default string comparisons are case sensitive but this can be changed by setting the optional ignorecase attribute to true.

To use this filter specify the string to be replaced with the from attribute and the string to replace it with using the to attribute.

Filters are intended to be used as a element of a <filterchain>.

Parameters

Attribute Type Description Required
from string The string to be replaced. True
ignorecase bool Determines if case will be ignored. The default is false. False
to string The new value for the replaced string. Am empty string is permissible. False
if bool If true then the filter will be used; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the filter will be executed; otherwise, skipped. The default is false. False

Examples

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/filters/replacetokens.html0000644000175000017500000001363011757307427021733 0ustar jtaylorjtaylor <replacetokens> Filter

<replacetokens>

[This is preliminary documentation and subject to change.]

Replaces tokens in the original input with user-supplied values.

This filter replaces all token surrounded by a beginning and ending token. The default beginning and ending tokens both default to '@'. The optional begintoken and endtoken attributes can be specified to change either token. By default string comparisons are case sensitive but this can be changed by setting the optional ignorecase attribute to true.

Tokens are specified by using the Token element. It is possible to specify from 1 to n tokens and replacement values. Values can be any valid NAnt expression.

Filters are intended to be used as a element of a <filterchain>.

Parameters

Attribute Type Description Required
begintoken char Marks the beginning of a token. The default is "@". False
endtoken char Marks the end of a token. The default is "@". False
ignorecase bool Determines if case will be ignored. The default is false. False
if bool If true then the filter will be used; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the filter will be executed; otherwise, skipped. The default is false. False

Nested Elements:

<token>

Tokens and replacement values.

ReplaceTokens filter token.

Parameters

AttributeTypeDescriptionRequired
keystring Token to be replaced. True
valuestring New value of token. True
ifbool Indicates if the token should be used to replace values. If true then the token will be used; otherwise, not. The default is true. False
unlessbool Indicates if the token should not be used to replace values. If false then the token will be used; otherwise, not. The default is false. False

</token>

Examples

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/0000755000175000017500000000000011757310027016335 5ustar jtaylorjtaylornant-0.92-rc1/doc/help/elements/NAnt.Core.Types.Token.html0000644000175000017500000000543311757307427023153 0ustar jtaylorjtaylor <token> Element

<token>

[This is preliminary documentation and subject to change.]

ReplaceTokens filter token.

Parameters

Attribute Type Description Required
key string Token to be replaced. True
value string New value of token. True
if bool Indicates if the token should be used to replace values. If true then the token will be used; otherwise, not. The default is true. False
unless bool Indicates if the token should not be used to replace values. If false then the token will be used; otherwise, not. The default is false. False

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.VisualCpp.Types.Library.html0000644000175000017500000000471411757307551024514 0ustar jtaylorjtaylor Library Element

Library

[This is preliminary documentation and subject to change.]

Represents a library.

Parameters

Attribute Type Description Required
name string The name of the library. True
if bool If true then the element will be processed; otherwise, skipped. The default is true. False
unless bool If true then the element will be skipped; otherwise, processed. The default is false. False

Requirements

Assembly: NAnt.VisualCppTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.Core.DataTypeBase.html0000644000175000017500000000416211757307425023272 0ustar jtaylorjtaylor DataTypeBase Element

DataTypeBase

[This is preliminary documentation and subject to change.]

Provides the abstract base class for types.

Parameters

Attribute Type Description Required
id string The ID used to be referenced later. False
refid string The ID to use as the reference. False

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.Core.Types.EnvironmentVariable.html0000644000175000017500000001051011757307436026035 0ustar jtaylorjtaylor <env> Element

<env>

[This is preliminary documentation and subject to change.]

Represents an environment variable.

Parameters

Attribute Type Description Required
name string The name of the environment variable. True
dir directory The value for a directory-based environment variable. NAnt will convert it to an absolute path. False
file file The value for a file-based environment variable. NAnt will convert it to an absolute filename. False
if bool Indicates if the environment variable should be passed to the external program. If true then the environment variable will be passed; otherwise, skipped. The default is true. False
path <path> The value for a PATH like environment variable. You can use : or ; as path separators and NAnt will convert it to the platform's local conventions. False
unless bool Indicates if the environment variable should not be passed to the external program. If false then the environment variable will be passed; otherwise, skipped. The default is false. False
value string The literal value for the environment variable. False

Nested Elements:

<path>

Sets a single environment variable and treats it like a PATH - ensures the right separator for the local platform is used.

</path>

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.Core.Tasks.ChooseTask.When.html0000644000175000017500000000370211757307432025010 0ustar jtaylorjtaylor ChooseTask.When Element

ChooseTask.When

[This is preliminary documentation and subject to change.]

Groups a set of tasks to execute when a condition is met.

Parameters

Attribute Type Description Required
test bool Used to test arbitrary boolean expression. True

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.Core.Tasks.TryCatchTask.CatchElement.html0000644000175000017500000000374211757307454026754 0ustar jtaylorjtaylor TryCatchTask.CatchElement Element

TryCatchTask.CatchElement

[This is preliminary documentation and subject to change.]

Parameters

Attribute Type Description Required
property string Defines the name of the property to save the message describing the failure that has been caught. False

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.Core.Task.html0000644000175000017500000000473611757307425021675 0ustar jtaylorjtaylor Task Element

Task

[This is preliminary documentation and subject to change.]

Provides the abstract base class for tasks.

A task is a piece of code that can be executed.

Parameters

AttributeTypeDescriptionRequired
failonerrorbool Determines if task failure stops the build, or is just reported. The default is true. False
ifbool If true then the task will be executed; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbosebool Determines whether the task should report detailed build log messages. The default is false. False

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.Core.Types.RawXml.html0000644000175000017500000000261711757307462023305 0ustar jtaylorjtaylor RawXml Element

RawXml

[This is preliminary documentation and subject to change.]

Represents an element of which the XML is processed by its parent task or type.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.DotNet.Types.Package.html0000644000175000017500000000524511757307472023734 0ustar jtaylorjtaylor Package Element

Package

[This is preliminary documentation and subject to change.]

Represents a package.

Parameters

Attribute Type Description Required
name string Name of the package to reference. Multiple package can be specified with a single element as a semi-colon separated list of package names. True
if bool Indicates if the package should be passed to the task. If true then the package will be passed; otherwise, skipped. The default is true. False
unless bool Indicates if the package should not be passed to the task. If false then the package will be passed; otherwise, skipped. The default is false. False

Requirements

Assembly: NAnt.DotNetTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.NUnit.Types.FormatterElement.html0000644000175000017500000000567511757307523025522 0ustar jtaylorjtaylor <formatter> Element

<formatter>

[This is preliminary documentation and subject to change.]

Represents the FormatterElement of the NUnit task.

Parameters

Attribute Type Description Required
type FormatterType Type of formatter. True
extension string Extension to append to the output filename. False
outputdir directory Specifies the directory where the output file should be written to, if usefile is true. If not specified, the output file will be written to the directory where the test module is located. False
usefile bool Determines whether output should be persisted to a file. The default is false. False

Requirements

Assembly: NAnt.NUnit (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.Core.Types.Argument.html0000644000175000017500000001232011757307435023645 0ustar jtaylorjtaylor <arg> Element

<arg>

[This is preliminary documentation and subject to change.]

Represents a command-line argument.

When passed to an external application, the argument will be quoted when appropriate. This does not apply to the line parameter, which is always passed as is.

Parameters

Attribute Type Description Required
dir directory The value for a directory-based command-line argument; will be replaced with the absolute path of the directory. False
file file The name of a file as a single command-line argument; will be replaced with the absolute filename of the file. False
if bool Indicates if the argument should be passed to the external program. If true then the argument will be passed; otherwise, skipped. The default is true. False
line string List of command-line arguments; will be passed to the executable as is. False
path <path> The value for a PATH-like command-line argument; you can use : or ; as path separators and NAnt will convert it to the platform's local conventions, while resolving references to environment variables. False
unless bool Indicates if the argument should not be passed to the external program. If false then the argument will be passed; otherwise, skipped. The default is false. False
value string A single command-line argument; can contain space characters. False

Nested Elements:

<path>

Sets a single command-line argument and treats it like a PATH - ensures the right separator for the local platform is used.

</path>

Examples

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.NUnit2.Types.NUnit2Test.html0000644000175000017500000001063611757307525024301 0ustar jtaylorjtaylor <test> Element

<test>

[This is preliminary documentation and subject to change.]

Represents a test element of an <nunit2> task.

Parameters

Attribute Type Description Required
appconfig file The application configuration file to use for the NUnit test domain. If not specified, NAnt will try to use a configuration name matching the file name of the assembly with extension ".config". False
assemblyname file Name of the assembly to search for tests. False
haltonfailure bool Build fails on failure. The default is true. False
testname string Name of a specific testfixture to run. If not specified then all testfixtures are run. False
transformfile file XSLT transform file to use when using the Plain formatter. False

Nested Elements:

<assemblies>

Assemblies to include in test.

</assemblies>

<references>

Assemblies to scan for missing assembly references.

</references>

<categories>

Categories of test cases to include or exclude.

</categories>

Requirements

Assembly: NAnt.NUnit2Tasks (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.DotNet.Types.AssemblyAttribute.html0000644000175000017500000000577111757307462026047 0ustar jtaylorjtaylor <attribute> Element

<attribute>

[This is preliminary documentation and subject to change.]

Represents an assembly-level attribute.

Parameters

Attribute Type Description Required
type string Typename of the assembly-level attribute. True
asis bool If true then the value of the attribute will be set as is, without actually looking for a matching constructor or named properties. The default is false. False
if bool Indicates if the attribute should be generated. False
unless bool Indicates if the attribute should be not generated. False
value string Value of the attribute. False

Requirements

Assembly: NAnt.DotNetTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.Core.Types.Option.html0000644000175000017500000000552311757307435023342 0ustar jtaylorjtaylor <option> Element

<option>

[This is preliminary documentation and subject to change.]

Represents an option.

Parameters

Attribute Type Description Required
name string Name of the option. True
if bool Indicates if the option should be passed to the task. If true then the option will be passed; otherwise, skipped. The default is true. False
unless bool Indicates if the option should not be passed to the task. If false then the option will be passed; otherwise, skipped. The default is false. False
value string Value of the option. The default is a null reference (Nothing in Visual Basic). False

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.Core.Types.FileSet.Exclude.html0000644000175000017500000000476411757307420025015 0ustar jtaylorjtaylor FileSet.Exclude Element

FileSet.Exclude

[This is preliminary documentation and subject to change.]

Parameters

Attribute Type Description Required
name string The pattern or file name to exclude. True
if bool If true then the pattern will be excluded; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the pattern will be excluded; otherwise, skipped. The default is false. False

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.Core.Types.XsltParameter.html0000644000175000017500000000620211757307453024660 0ustar jtaylorjtaylor <xsltparameter> Element

<xsltparameter>

[This is preliminary documentation and subject to change.]

Represents an XSLT parameter.

Parameters

Attribute Type Description Required
name string The name of the XSLT parameter. True
value string The value of the XSLT parameter. True
if bool Indicates if the parameter should be added to the XSLT argument list. If true then the parameter will be added; otherwise, skipped. The default is true. False
namespaceuri string The namespace URI to associate with the parameter. False
unless bool Indicates if the parameter should not be added to the XSLT argument list. If false then the parameter will be added; otherwise, skipped. The default is false. False

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.DotNet.Types.DataTypeCollectionBase.html0000644000175000017500000000430011757307521026705 0ustar jtaylorjtaylor DataTypeCollectionBase Element

DataTypeCollectionBase

[This is preliminary documentation and subject to change.]

Base class for collections that needs to be globally referencable.

Parameters

Attribute Type Description Required
id string The ID used to be referenced later. False
refid string The ID to use as the reference. False

Requirements

Assembly: NAnt.DotNetTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.Core.TaskContainer.html0000644000175000017500000000556311757307426023540 0ustar jtaylorjtaylor TaskContainer Element

TaskContainer

[This is preliminary documentation and subject to change.]

Executes embedded tasks in the order in which they are defined.

Parameters

Attribute Type Description Required
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.SourceControl.Tasks.AbstractCvsTask.html0000644000175000017500000003320611757307531027022 0ustar jtaylorjtaylor AbstractCvsTask Element

AbstractCvsTask

[This is preliminary documentation and subject to change.]

A base class for creating tasks for executing CVS client commands on a CVS repository.

Parameters

Attribute Type Description Required
compressionlevel int Compression level to use for all net traffic. This should be a value from 1-9.



NOTE: This is not available on sharpcvslib.
False
cvsfullpath file The full path to the cvs binary used. The cvs tasks will attempt to "guess" the location of your cvs binary based on your path. If the task is unable to resolve the location, or resolves it incorrectly this can be used to manually specify the path. False
cvsroot string

The cvs root variable has the following components:

[protocol]:[username]@[servername]:[server path]
  • protocol: ext, pserver, ssh (sharpcvslib); if you are not using sharpcvslib consult your cvs documentation.
  • username: [username]
  • servername: cvs.sourceforge.net
  • server path: /cvsroot/nant

False
cvsrsh file The executable to use for ssh communication. False
module string The module to perform an operation on. False
quiet bool Indicates if the output from the cvs command should be supressed. The default is false. False
readonly bool true if the sandbox files should be checked out in read only mode. The default is false. False
readwrite bool true if the sandbox files should be checked out in read/write mode. The default is true. False
reallyquiet bool Indicates if the output from the cvs command should be stopped. The default is false. False
usesharpcvslib bool

true if the SharpCvsLib binaries that come bundled with NAnt should be used to perform the cvs commands, false otherwise.

You may also specify an override value for all cvs tasks instead of specifying a value for each. To do this set the property sourcecontrol.usesharpcvslib to false.

If you choose not to use SharpCvsLib to checkout from cvs you will need to include a cvs.exe binary in your path.
False
commandline string Command-line arguments for the program. The command line arguments are used to specify any cvs command options that are not available as attributes. These are appended after the command itself and are additive to whatever attributes are currently specified. False
destination directory Destination directory for the local sandbox. If destination is not specified then the current directory is used. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
passfile file The full path to the cached password file. If not specified then the environment variables are used to try and locate the file. False
password string Deprecated. The password for logging in to the repository. False
timeout int The maximum amount of time the application is allowed to execute, expressed in milliseconds. Defaults to no time-out. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Framework-configurable parameters

Attribute Type Description Required
managed ManagedExecution Specifies whether the external program should be treated as a managed application, possibly forcing it to be executed under the currently targeted version of the CLR. False
useruntimeengine bool Deprecated. Specifies whether the external program is a managed application which should be executed using a runtime engine, if configured. The default is false. False

Nested Elements:

<fileset>

Used to specify the version control system (VCS) files that are going to be acted on.

</fileset>

<arg>

The command-line arguments for the external program.

Represents a command-line argument.

When passed to an external application, the argument will be quoted when appropriate. This does not apply to the line parameter, which is always passed as is.

Parameters

AttributeTypeDescriptionRequired
dirdirectory The value for a directory-based command-line argument; will be replaced with the absolute path of the directory. False
filefile The name of a file as a single command-line argument; will be replaced with the absolute filename of the file. False
ifbool Indicates if the argument should be passed to the external program. If true then the argument will be passed; otherwise, skipped. The default is true. False
linestring List of command-line arguments; will be passed to the executable as is. False
path<path> The value for a PATH-like command-line argument; you can use : or ; as path separators and NAnt will convert it to the platform's local conventions, while resolving references to environment variables. False
unlessbool Indicates if the argument should not be passed to the external program. If false then the argument will be passed; otherwise, skipped. The default is false. False
valuestring A single command-line argument; can contain space characters. False

Nested Elements:

<path>

Sets a single command-line argument and treats it like a PATH - ensures the right separator for the local platform is used.

</path>

Examples

</arg>

Requirements

Assembly: NAnt.SourceControlTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.Core.Types.XsltExtensionObject.html0000644000175000017500000000663111757307453026051 0ustar jtaylorjtaylor <xsltextensionobject> Element

<xsltextensionobject>

[This is preliminary documentation and subject to change.]

Represents an XSLT extension object. The object should have a default parameterless constructor and the return value should be one of the four basic XPath data types of number, string, Boolean or node set.

Parameters

Attribute Type Description Required
assembly file The assembly which contains the XSLT extension object. True
typename string The full type name of the XSLT extension object. True
if bool Indicates if the extension object should be added to the XSLT argument list. If true then the extension object will be added; otherwise, skipped. The default is true. False
namespaceuri string The namespace URI to associate with the extension object. False
unless bool Indicates if the extension object should not be added to the XSLT argument list. If false then the extension object will be added; otherwise, skipped. The default is false. False

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.Core.Types.FileSet.IncludesFile.html0000644000175000017500000000637411757307421025772 0ustar jtaylorjtaylor FileSet.IncludesFile Element

FileSet.IncludesFile

[This is preliminary documentation and subject to change.]

Parameters

Attribute Type Description Required
asis bool If true then the patterns in the include file will be added to the <fileset> without pattern matching or checking if the file exists. The default is false. False
frompath bool If true then the patterns in the include file will be searched for on the path. The default is false. False
if bool If true then the patterns will be included; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the patterns will be included; otherwise, skipped. The default is false. False
name file The name of a file; each line of this file is taken to be a pattern. True

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.Core.Types.Formatter.html0000644000175000017500000000555511757307455024044 0ustar jtaylorjtaylor <formatter> Element

<formatter>

[This is preliminary documentation and subject to change.]

Parameters

Attribute Type Description Required
pattern string The string pattern to use to format the property. True
property string The name of the NAnt property to set. True
if bool Indicates if the formatter should be used to format the timestamp. If true then the formatter will be used; otherwise, skipped. The default is true. False
unless bool Indicates if the formatter should be not used to format the timestamp. If false then the formatter will be used; otherwise, skipped. The default is false. False

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.Core.Tasks.InElement.html0000644000175000017500000000331711757307444023732 0ustar jtaylorjtaylor InElement Element

InElement

[This is preliminary documentation and subject to change.]

Nested Elements:

<items>

</items>

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.Core.Tasks.ExternalProgramBase.html0000644000175000017500000002126311757307435025757 0ustar jtaylorjtaylor ExternalProgramBase Element

ExternalProgramBase

[This is preliminary documentation and subject to change.]

Provides the abstract base class for tasks that execute external applications.

When a ProgramLocationAttribute is applied to the deriving class and exename does not return an absolute path, then the program to execute will first be searched for in the location specified by LocationType.

If the program does not exist in that location, then the list of tool paths of the current target framework will be scanned in the order in which they are defined in the NAnt configuration file.

Parameters

Attribute Type Description Required
timeout int The maximum amount of time the application is allowed to execute, expressed in milliseconds. Defaults to no time-out. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Framework-configurable parameters

Attribute Type Description Required
exename string The name of the executable that should be used to launch the external program. False
managed ManagedExecution Specifies whether the external program should be treated as a managed application, possibly forcing it to be executed under the currently targeted version of the CLR. False
useruntimeengine bool Deprecated. Specifies whether the external program is a managed application which should be executed using a runtime engine, if configured. The default is false. False

Nested Elements:

<arg>

The command-line arguments for the external program.

Represents a command-line argument.

When passed to an external application, the argument will be quoted when appropriate. This does not apply to the line parameter, which is always passed as is.

Parameters

AttributeTypeDescriptionRequired
dirdirectory The value for a directory-based command-line argument; will be replaced with the absolute path of the directory. False
filefile The name of a file as a single command-line argument; will be replaced with the absolute filename of the file. False
ifbool Indicates if the argument should be passed to the external program. If true then the argument will be passed; otherwise, skipped. The default is true. False
linestring List of command-line arguments; will be passed to the executable as is. False
path<path> The value for a PATH-like command-line argument; you can use : or ; as path separators and NAnt will convert it to the platform's local conventions, while resolving references to environment variables. False
unlessbool Indicates if the argument should not be passed to the external program. If false then the argument will be passed; otherwise, skipped. The default is false. False
valuestring A single command-line argument; can contain space characters. False

Nested Elements:

<path>

Sets a single command-line argument and treats it like a PATH - ensures the right separator for the local platform is used.

</path>

Examples

</arg>

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.VSNet.Types.WebMap.html0000644000175000017500000000577311757307557023370 0ustar jtaylorjtaylor WebMap Element

WebMap

[This is preliminary documentation and subject to change.]

Represents a single mapping from URL project path to physical project path.

Parameters

Attribute Type Description Required
path file Specifies the actual path to the project file, or the path fragment to replace. True
url string Specifies the URL of the project file, or a URL fragment to match. True
casesensitive bool Specifies whether the mapping is case-sensitive or not. False
if bool Indicates if the URL of the project file should be mapped. False
unless bool Indicates if the URL of the project file should not be mapped. False

Requirements

Assembly: NAnt.VSNetTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.Core.Filters.ChainableReader.html0000644000175000017500000000327511757307426025371 0ustar jtaylorjtaylor ChainableReader Element

ChainableReader

[This is preliminary documentation and subject to change.]

Functions as a chainable TextReader

Implements a abstraction over a TextReader that allows the class to represent either a TextReader or another ChainableReader to which it is chained. By passing a ChainableReader as a constructor paramater it is possiable to chain many ChainableReaders together. The last ChainableReader in the chain must be based on a TextReader.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.SourceControl.Tasks.AbstractSourceControlTask.html0000644000175000017500000002372011757307527031075 0ustar jtaylorjtaylor AbstractSourceControlTask Element

AbstractSourceControlTask

[This is preliminary documentation and subject to change.]

A base class for creating tasks for executing CVS client commands on a CVS repository.

Parameters

Attribute Type Description Required
commandline string Command-line arguments for the program. The command line arguments are used to specify any cvs command options that are not available as attributes. These are appended after the command itself and are additive to whatever attributes are currently specified. False
destination directory Destination directory for the local sandbox. If destination is not specified then the current directory is used. False
passfile file The full path to the cached password file. If not specified then the environment variables are used to try and locate the file. False
password string Deprecated. The password for logging in to the repository. False
ssh file The executable to use for ssh communication. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
timeout int The maximum amount of time the application is allowed to execute, expressed in milliseconds. Defaults to no time-out. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Framework-configurable parameters

Attribute Type Description Required
managed ManagedExecution Specifies whether the external program should be treated as a managed application, possibly forcing it to be executed under the currently targeted version of the CLR. False
useruntimeengine bool Deprecated. Specifies whether the external program is a managed application which should be executed using a runtime engine, if configured. The default is false. False

Nested Elements:

<fileset>

Used to specify the version control system (VCS) files that are going to be acted on.

</fileset>

<arg>

The command-line arguments for the external program.

Represents a command-line argument.

When passed to an external application, the argument will be quoted when appropriate. This does not apply to the line parameter, which is always passed as is.

Parameters

AttributeTypeDescriptionRequired
dirdirectory The value for a directory-based command-line argument; will be replaced with the absolute path of the directory. False
filefile The name of a file as a single command-line argument; will be replaced with the absolute filename of the file. False
ifbool Indicates if the argument should be passed to the external program. If true then the argument will be passed; otherwise, skipped. The default is true. False
linestring List of command-line arguments; will be passed to the executable as is. False
path<path> The value for a PATH-like command-line argument; you can use : or ; as path separators and NAnt will convert it to the platform's local conventions, while resolving references to environment variables. False
unlessbool Indicates if the argument should not be passed to the external program. If false then the argument will be passed; otherwise, skipped. The default is false. False
valuestring A single command-line argument; can contain space characters. False

Nested Elements:

<path>

Sets a single command-line argument and treats it like a PATH - ensures the right separator for the local platform is used.

</path>

Examples

</arg>

Requirements

Assembly: NAnt.SourceControlTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.NUnit1.Types.NUnitTest.html0000644000175000017500000000760511757307523024216 0ustar jtaylorjtaylor <test> Element

<test>

[This is preliminary documentation and subject to change.]

Represents a test element of an <nunit> task.

Parameters

Attribute Type Description Required
assembly string Assembly to load the test from. True
class string Class name of the test. True
appconfig string The application configuration file to use for the NUnit test domain. False
fork bool Run the tests in a separate AppDomain. False
haltonerror bool Stop the build process if an error occurs during the test run. False
haltonfailure bool Stop the build process if a test fails (errors are considered failures as well). False
outfile string Base name of the test result. The full filename is determined by this attribute and the extension of formatter. False
todir string Directory to write the reports to. False

Requirements

Assembly: NAnt.NUnit1Tasks (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.DotNet.Types.CompilerWarning.html0000644000175000017500000000510111757307471025467 0ustar jtaylorjtaylor CompilerWarning Element

CompilerWarning

[This is preliminary documentation and subject to change.]

Represents a compiler warning.

Parameters

Attribute Type Description Required
number string A warning number, or comma-separated list of warnings, that you want the compiler to suppress or report. True
if bool If true then the element will be processed; otherwise, skipped. The default is true. False
unless bool If true then the element will be skipped; otherwise, processed. The default is false. False

Requirements

Assembly: NAnt.DotNetTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.Compression.Tasks.ExpandBaseTask.html0000644000175000017500000000626011757307417026320 0ustar jtaylorjtaylor ExpandBaseTask Element

ExpandBaseTask

[This is preliminary documentation and subject to change.]

Summary description for ExpandTask.

Parameters

Attribute Type Description Required
overwrite bool Overwrite files, even if they are newer than the corresponding entries in the archive. The default is true. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Requirements

Assembly: NAnt.CompressionTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.DotNet.Types.NamespaceImport.html0000644000175000017500000000522311757307521025457 0ustar jtaylorjtaylor <import> Element

<import>

[This is preliminary documentation and subject to change.]

Represents a namespace to import.

Parameters

Attribute Type Description Required
if bool Indicates if the import should be generated. False
name string Deprecated. The name of the namespace to import. False
namespace string The name of the namespace to import. False
unless bool Indicates if the import should be not generated. False

Requirements

Assembly: NAnt.DotNetTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.DotNet.Tasks.CompilerBase.html0000644000175000017500000004547011757307475024736 0ustar jtaylorjtaylor CompilerBase Element

CompilerBase

[This is preliminary documentation and subject to change.]

Provides the abstract base class for compiler tasks.

Parameters

Attribute Type Description Required
output file The output file created by the compiler. True
target string Output type. Possible values are exe, winexe, library or module. True
debug bool Generate debug output. The default is false. False
define string Define conditional compilation symbol(s). False
delaysign DelaySign Specifies whether to delay sign the assembly using only the public portion of the strong name key. The default is NotSet. False
keycontainer string Specifies the key pair container used to strongname the assembly. False
keyfile file Specifies a strong name key file. False
main string Specifies which type contains the Main method that you want to use as the entry point into the program. False
nowarn string Deprecated. Specifies a comma-separated list of warnings that should be suppressed by the compiler. False
rebuild bool Instructs NAnt to recompile the output file regardless of the file timestamps. False
warnaserror bool Instructs the compiler to treat all warnings as errors. The default is false. False
win32icon file Icon to associate with the application. False
win32res file Specifies a Win32 resource file (.res). False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
timeout int The maximum amount of time the application is allowed to execute, expressed in milliseconds. Defaults to no time-out. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Framework-configurable parameters

Attribute Type Description Required
exename string The name of the executable that should be used to launch the external program. False
managed ManagedExecution Specifies whether the external program should be treated as a managed application, possibly forcing it to be executed under the currently targeted version of the CLR. False
supportsdelaysign bool Indicates whether the compiler for a given target framework supports the "delaysign" option. The default is false. False
supportskeycontainer bool Indicates whether the compiler for a given target framework supports the "keycontainer" option. The default is false. False
supportskeyfile bool Indicates whether the compiler for a given target framework supports the "keyfile" option. The default is false. False
supportsnowarnlist bool Indicates whether the compiler for a given target framework supports a command line option that allows a list of warnings to be suppressed. The default is false. False
supportspackagereferences bool Indicates whether package references are supported by compiler for a given target framework. The default is false. False
supportswarnaserrorlist bool Indicates whether the compiler for a given target framework supports the "warnaserror" option that takes a list of warnings. The default is false. False
useruntimeengine bool Deprecated. Specifies whether the external program is a managed application which should be executed using a runtime engine, if configured. The default is false. False

Nested Elements:

<warnaserror>

Controls which warnings should be reported as errors.

</warnaserror>

<nowarn>

Specifies a list of warnings that you want the compiler to suppress.
<warning>

Represents a compiler warning.

Parameters

AttributeTypeDescriptionRequired
numberstring A warning number, or comma-separated list of warnings, that you want the compiler to suppress or report. True
ifbool If true then the element will be processed; otherwise, skipped. The default is true. False
unlessbool If true then the element will be skipped; otherwise, processed. The default is false. False
</warning>

</nowarn>

<lib>

Deprecated. Additional directories to search in for assembly references.

</lib>

<references>

Reference metadata from the specified assembly files.

</references>

<pkg-references>

Specifies list of packages to reference.
<package>

Represents a package.

Parameters

AttributeTypeDescriptionRequired
namestring Name of the package to reference. Multiple package can be specified with a single element as a semi-colon separated list of package names. True
ifbool Indicates if the package should be passed to the task. If true then the package will be passed; otherwise, skipped. The default is true. False
unlessbool Indicates if the package should not be passed to the task. If false then the package will be passed; otherwise, skipped. The default is false. False
</package>

</pkg-references>

<resources>

Resources to embed.

</resources>

<modules>

Link the specified modules into this assembly.

</modules>

<sources>

The set of source files for compilation.

</sources>

<arg>

The command-line arguments for the external program.

Represents a command-line argument.

When passed to an external application, the argument will be quoted when appropriate. This does not apply to the line parameter, which is always passed as is.

Parameters

AttributeTypeDescriptionRequired
dirdirectory The value for a directory-based command-line argument; will be replaced with the absolute path of the directory. False
filefile The name of a file as a single command-line argument; will be replaced with the absolute filename of the file. False
ifbool Indicates if the argument should be passed to the external program. If true then the argument will be passed; otherwise, skipped. The default is true. False
linestring List of command-line arguments; will be passed to the executable as is. False
path<path> The value for a PATH-like command-line argument; you can use : or ; as path separators and NAnt will convert it to the platform's local conventions, while resolving references to environment variables. False
unlessbool Indicates if the argument should not be passed to the external program. If false then the argument will be passed; otherwise, skipped. The default is false. False
valuestring A single command-line argument; can contain space characters. False

Nested Elements:

<path>

Sets a single command-line argument and treats it like a PATH - ensures the right separator for the local platform is used.

</path>

Examples

</arg>

Requirements

Assembly: NAnt.DotNetTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.Core.Types.XmlNamespace.html0000644000175000017500000000623411757307456024452 0ustar jtaylorjtaylor <namespace> Element

<namespace>

[This is preliminary documentation and subject to change.]

Represents an XML namespace.

Parameters

Attribute Type Description Required
prefix string The prefix to associate with the namespace. True
uri string The associated XML namespace URI. True
if bool Indicates if the namespace should be added to the XmlNamespaceManager. If true then the namespace will be added; otherwise, skipped. The default is true. False
unless bool Indicates if the namespace should not be added to the XmlNamespaceManager. list. If false then the parameter will be added; otherwise, skipped. The default is false. False

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.DotNet.Types.LibDirectorySet.html0000644000175000017500000003403511757307463025447 0ustar jtaylorjtaylor LibDirectorySet Element

LibDirectorySet

[This is preliminary documentation and subject to change.]

A specialized <fileset> used for setting the lib directories.

The primary reason for this class is to allow the BaseDirectory to always be the same value as the parent <assemblyfileset>

Parameters

AttributeTypeDescriptionRequired
casesensitivebool Indicates whether include and exclude patterns must be treated in a case-sensitive way. The default is true on Unix; otherwise, false. False
defaultexcludesbool Indicates whether default excludes should be used or not. The default is true. False
failonemptybool When set to true, causes the fileset element to throw a ValidationException when no files match the includes and excludes criteria. The default is false. False
idstring The ID used to be referenced later. False
refidstring The ID to use as the reference. False

Nested Elements:

<includes>

Deprecated. The items to include in the fileset.

Parameters

AttributeTypeDescriptionRequired
namestring The pattern or file name to include. True
asisbool If true then the file name will be added to the <fileset> without pattern matching or checking if the file exists. The default is false. False
frompathbool If true then the file will be searched for on the path. The default is false. False
ifbool If true then the pattern will be included; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the pattern will be included; otherwise, skipped. The default is false. False

</includes>

<include>

The items to include in the fileset.

Parameters

AttributeTypeDescriptionRequired
namestring The pattern or file name to include. True
asisbool If true then the file name will be added to the <fileset> without pattern matching or checking if the file exists. The default is false. False
frompathbool If true then the file will be searched for on the path. The default is false. False
ifbool If true then the pattern will be included; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the pattern will be included; otherwise, skipped. The default is false. False

</include>

<excludes>

Deprecated. The items to exclude from the fileset.

Parameters

AttributeTypeDescriptionRequired
namestring The pattern or file name to exclude. True
ifbool If true then the pattern will be excluded; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the pattern will be excluded; otherwise, skipped. The default is false. False

</excludes>

<exclude>

The items to exclude from the fileset.

Parameters

AttributeTypeDescriptionRequired
namestring The pattern or file name to exclude. True
ifbool If true then the pattern will be excluded; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the pattern will be excluded; otherwise, skipped. The default is false. False

</exclude>

<includesList>

Deprecated. The files from which a list of patterns or files to include should be obtained.

Parameters

AttributeTypeDescriptionRequired
asisbool If true then the patterns in the include file will be added to the <fileset> without pattern matching or checking if the file exists. The default is false. False
frompathbool If true then the patterns in the include file will be searched for on the path. The default is false. False
ifbool If true then the patterns will be included; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the patterns will be included; otherwise, skipped. The default is false. False
namefile The name of a file; each line of this file is taken to be a pattern. True

</includesList>

<includesfile>

The files from which a list of patterns or files to include should be obtained.

Parameters

AttributeTypeDescriptionRequired
asisbool If true then the patterns in the include file will be added to the <fileset> without pattern matching or checking if the file exists. The default is false. False
frompathbool If true then the patterns in the include file will be searched for on the path. The default is false. False
ifbool If true then the patterns will be included; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the patterns will be included; otherwise, skipped. The default is false. False
namefile The name of a file; each line of this file is taken to be a pattern. True

</includesfile>

<excludesfile>

The files from which a list of patterns or files to exclude should be obtained.

Parameters

AttributeTypeDescriptionRequired
namefile The name of a file; each line of this file is taken to be a pattern. True
ifbool If true then the patterns will be excluded; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the patterns will be excluded; otherwise, skipped. The default is false. False

</excludesfile>

<patternset>

Adds a nested set of patterns, or references a standalone patternset.

</patternset>

Requirements

Assembly: NAnt.DotNetTasks (0.92.4526.0)

See Also

<fileset> nant-0.92-rc1/doc/help/elements/NAnt.VisualCpp.Types.Symbol.html0000644000175000017500000000470611757307550024355 0ustar jtaylorjtaylor Symbol Element

Symbol

[This is preliminary documentation and subject to change.]

Represents a symbol.

Parameters

Attribute Type Description Required
name string The name of the symbol. True
if bool If true then the element will be processed; otherwise, skipped. The default is true. False
unless bool If true then the element will be skipped; otherwise, processed. The default is false. False

Requirements

Assembly: NAnt.VisualCppTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.Core.ElementContainer.html0000644000175000017500000000265211757307425024222 0ustar jtaylorjtaylor ElementContainer Element

ElementContainer

[This is preliminary documentation and subject to change.]

Executes embedded tasks/elements in the order in which they are defined.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.Core.Types.FileSet.ExcludesFile.html0000644000175000017500000000505011757307421025766 0ustar jtaylorjtaylor FileSet.ExcludesFile Element

FileSet.ExcludesFile

[This is preliminary documentation and subject to change.]

Parameters

Attribute Type Description Required
name file The name of a file; each line of this file is taken to be a pattern. True
if bool If true then the patterns will be excluded; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the patterns will be excluded; otherwise, skipped. The default is false. False

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.Core.Types.FileSet.Include.html0000644000175000017500000000623511757307420025002 0ustar jtaylorjtaylor FileSet.Include Element

FileSet.Include

[This is preliminary documentation and subject to change.]

Parameters

Attribute Type Description Required
name string The pattern or file name to include. True
asis bool If true then the file name will be added to the <fileset> without pattern matching or checking if the file exists. The default is false. False
frompath bool If true then the file will be searched for on the path. The default is false. False
if bool If true then the pattern will be included; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the pattern will be included; otherwise, skipped. The default is false. False

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.Core.Filters.Filter.html0000644000175000017500000000442211757307426023620 0ustar jtaylorjtaylor Filter Element

Filter

[This is preliminary documentation and subject to change.]

Allows a file's content to be modified while performing an operation.

Parameters

Attribute Type Description Required
if bool If true then the filter will be used; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the filter will be executed; otherwise, skipped. The default is false. False

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.NUnit2.Types.Category.html0000644000175000017500000000501311757307524024067 0ustar jtaylorjtaylor Category Element

Category

[This is preliminary documentation and subject to change.]

Represents a certain group of test cases or fixtures.

Parameters

Attribute Type Description Required
name string A name of a category, or comma-separated list of names. True
if bool If true then the category will be processed; otherwise, skipped. The default is true. False
unless bool If true then the category will be skipped; otherwise, processed. The default is false. False

Requirements

Assembly: NAnt.NUnit2Tasks (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.Core.Types.PathElement.html0000644000175000017500000000645611757307461024305 0ustar jtaylorjtaylor <pathelement> Element

<pathelement>

[This is preliminary documentation and subject to change.]

Represents a nested path element.

Parameters

Attribute Type Description Required
dir directory The name of a directory to add to the path. Will be replaced with the absolute path of the directory. False
file file The name of a file to add to the path. Will be replaced with the absolute path of the file. False
if bool If true then the entry will be added to the path; otherwise, skipped. The default is true. False
path <path> A string that will be treated as a path-like string. You can use : or ; as path separators and NAnt will convert it to the platform's local conventions, while resolving references to environment variables. False
unless bool Opposite of if. If false then the entry will be added to the path; otherwise, skipped. The default is false. False

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.Core.Types.Pattern.html0000644000175000017500000000465711757307461023515 0ustar jtaylorjtaylor Pattern Element

Pattern

[This is preliminary documentation and subject to change.]

Parameters

Attribute Type Description Required
name string The name pattern to include/exclude. True
if bool If true then the pattern will be used; otherwise, skipped. The default is true. False
unless bool If false then the pattern will be used; otherwise, skipped. The default is false. False

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.Core.Target.html0000644000175000017500000000654511757307426022222 0ustar jtaylorjtaylor Target Element

Target

[This is preliminary documentation and subject to change.]

Parameters

Attribute Type Description Required
name string The name of the target.

This attribute's properties will not be automatically expanded!

True
depends string Space separated list of targets that this target depends on. False
description string The description of the target. False
if string If true then the target will be executed; otherwise, skipped. The default is true.

This attribute's properties will not be automatically expanded!

False
unless string Opposite of IfDefined. If false then the target will be executed; otherwise, skipped. The default is false.

This attribute's properties will not be automatically expanded!

False

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.DotNet.Types.Module.html0000644000175000017500000000426111757307467023627 0ustar jtaylorjtaylor Module Element

Module

[This is preliminary documentation and subject to change.]

Represents a metadata file without assembly manifest.

Parameters

Attribute Type Description Required
file string The path of the module. True
target string File name where the module should be copied to before it is compiled into an assembly. False

Requirements

Assembly: NAnt.DotNetTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.DotNet.Types.EmbeddedResourceCollection.html0000644000175000017500000000404211757307521027603 0ustar jtaylorjtaylor EmbeddedResourceCollection Element

EmbeddedResourceCollection

[This is preliminary documentation and subject to change.]

Contains a collection of EmbeddedResource items.

Do not yet expose this to build authors.

Parameters

AttributeTypeDescriptionRequired
idstring The ID used to be referenced later. False
refidstring The ID to use as the reference. False

Requirements

Assembly: NAnt.DotNetTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/elements/NAnt.Core.Types.EnvironmentSet.html0000644000175000017500000001326611757307436025056 0ustar jtaylorjtaylor <environment> Element

<environment>

[This is preliminary documentation and subject to change.]

A set of environment variables.

Nested Elements:

<option>

Deprecated. Environment variable to pass to a program.

Represents an option.

Parameters

AttributeTypeDescriptionRequired
namestring Name of the option. True
ifbool Indicates if the option should be passed to the task. If true then the option will be passed; otherwise, skipped. The default is true. False
unlessbool Indicates if the option should not be passed to the task. If false then the option will be passed; otherwise, skipped. The default is false. False
valuestring Value of the option. The default is a null reference (Nothing in Visual Basic). False

</option>

<variable>

Environment variable to pass to a program.

Represents an environment variable.

Parameters

AttributeTypeDescriptionRequired
namestring The name of the environment variable. True
dirdirectory The value for a directory-based environment variable. NAnt will convert it to an absolute path. False
filefile The value for a file-based environment variable. NAnt will convert it to an absolute filename. False
ifbool Indicates if the environment variable should be passed to the external program. If true then the environment variable will be passed; otherwise, skipped. The default is true. False
path<path> The value for a PATH like environment variable. You can use : or ; as path separators and NAnt will convert it to the platform's local conventions. False
unlessbool Indicates if the environment variable should not be passed to the external program. If false then the environment variable will be passed; otherwise, skipped. The default is false. False
valuestring The literal value for the environment variable. False

Nested Elements:

<path>

Sets a single environment variable and treats it like a PATH - ensures the right separator for the local platform is used.

</path>

</variable>

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/images/0000755000175000017500000000000011757310030015760 5ustar jtaylorjtaylornant-0.92-rc1/doc/help/images/bullet.gif0000644000175000017500000000010711757302272017745 0ustar jtaylorjtaylorGIF89a ! , @@ A" B$;nant-0.92-rc1/doc/help/images/logo.gif0000644000175000017500000001052411757302272017422 0ustar jtaylorjtaylorGIF89avdfcVXUf@̝@ثAMf乩5לą-<*^ο@rtqsؤ܇@يtM.MګehV;`Zݖ8/ kmjnpmaa`Ϙϡ߯`9Pp]_\V`~}|@:0vxv`yzx@@@iegdc ϧs~pppkqX0#ϜPl 8yϼ!,v@%%C1 I9.Ɣ"HLLލG 9ҷ6׾m !9 ",x`BpK# /B-[G" 2.㝯I$ \ɲvXA͘.`A8m!eM.zL`\*]`%j5)"tahӪ]˶mZ%`Edݴ2qZL02-N[(X %3t+F*aJ7]V*;wGSF+ aX~D! S/Sa|P/'(`@Q]@ ?ؕp@6CsQ% ݧ[ Ho%מ`7B]g YFQ2[o6!% +ad,P*(3 6Ћ$dO&C/D`5q;:׭[[{ş(45F<`^@XA0H9Km P*y"&1ם䔪[@:Hb P RQN`\G›bqa f-P)(b5XI A;g\ Q^uRĕ3,܆s@$xG i0ԉ)xǖYd*C3ViC&- WV,m5]B W*dFRBpo ;h3a)U0@0$+MćRd" 4w + %' Dz`jnQ xHjL@aZja*yH! #z,ym :Tu\.P 4GIēS|PA74щԷ&Xs"5y,Lbk2ϸ7cE Xg[8.)o_$VYgv*; r=iEjtBWWNr Y!w_Ui@Bb,*8Џu= +!>ZR3T L!H=y3!e?pyt*^ŏ}Cm>~B`$g0d&_pB  t s(A8@z e!@ OoTvOo\!] [`9ii|rk PE0"P`yIO5N&tDx.@$AGH VGP01PC@o8'$`gcX c$L Fx ol!aSd\TXq6Aeh23v@[ PTj S}@ PPT%QHqSAa\0SnTNu5axYr0NWL='#>qV[e:%[ȉma(lA? hd x 5wEg nҨf=\`gx02Y?v1hk>S8Fg5v 7GD1@mmĄa]!zAT>9a ?v|9vbcQh! rr`90H'.]XquvgT}gCfpЖia ͅ3p5t إ]GDb)^ny;Wtv6x3]u] AIu>S&apc4c2Y|_`us1_mB5qo%^aQCkD``\as(hX_"r"LA1N,%s"PpIa'P`,^:Y _ h)_عy035b(0g*byZ%b<@ZCp~pdoeGM1\#}!UvpC=%&tfՠl[5Y?)HeYh 1[\p1%q t05$ 6x/[ [P5vy*cr`gOa Z T?PDL+Bp79ؕ#a.EO?#Q6T_MJ`3=Yk@Vj ?C"8H"4 0`jo+4Ь!0Z &"htj$d9DkNi "x~\*`@BT(P ,C@f@}ֱ;{\8^D  f0ZW5mG lױ0(@#LzO{O>1 ߦO0jK==@&%8֢C90z f(QqS8 +N"@&sܠ"]ˌq@+ 8dk`" U$0+9$"(V` AADҵ1 PƻoFkGWP$Pʛ)'Ts(A^2!柠!0Ƚ2)0ĊB)K7w蛿ۿq;nant-0.92-rc1/doc/help/images/arrow.gif0000644000175000017500000000007211757302272017611 0ustar jtaylorjtaylorGIF89a !, М+d1oU;nant-0.92-rc1/doc/help/enums/0000755000175000017500000000000011757310030015642 5ustar jtaylorjtaylornant-0.92-rc1/doc/help/enums/NAnt.DotNet.Tasks.RegsvcsTask.ActionType.html0000644000175000017500000000375111757307507026211 0ustar jtaylorjtaylor RegsvcsTask.ActionType enum

RegsvcsTask.ActionType

[This is preliminary documentation and subject to change.]

Defines the possible actions for a .NET Service.

Fields

Field Description
Create Creates the target application.
FindOrCreate Finds or creates the target application.
Uninstall Uninstalls the target application.

Requirements

Assembly: NAnt.DotNetTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/enums/NAnt.VisualCpp.Tasks.ClTask.PrecompiledHeaderMode.html0000644000175000017500000000407411757307547027751 0ustar jtaylorjtaylor ClTask.PrecompiledHeaderMode enum

ClTask.PrecompiledHeaderMode

[This is preliminary documentation and subject to change.]

Defines the supported modes for the use of precompiled header files.

Fields

Field Description
AutoCreate Automatically create a precompiled header file if necessary.
Create Create a precompiled header file.
Use Use a (previously generated) precompiled header file.

Requirements

Assembly: NAnt.VisualCppTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/enums/NAnt.VisualCpp.Types.CharacterSet.html0000644000175000017500000000370611757307547025000 0ustar jtaylorjtaylor CharacterSet enum

CharacterSet

[This is preliminary documentation and subject to change.]

Defines the character sets that can be used by the C++ compiler.

Fields

Field Description
MultiByte Multi-byte character set.
NotSet Have the compiler determine the character set.
Unicode Unicode character set.

Requirements

Assembly: NAnt.VisualCppTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/enums/NAnt.Core.Tasks.LoopTask.LoopItem.html0000644000175000017500000000365611757307444024656 0ustar jtaylorjtaylor LoopTask.LoopItem enum

LoopTask.LoopItem

[This is preliminary documentation and subject to change.]

Fields

Field Description
File
Folder
Line
String

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/enums/NAnt.MSNet.Tasks.ServiceControllerTask.ActionType.html0000644000175000017500000000430311757307522030021 0ustar jtaylorjtaylor ServiceControllerTask.ActionType enum

ServiceControllerTask.ActionType

[This is preliminary documentation and subject to change.]

Defines the actions that can be performed on a service.

Fields

Field Description
Continue Continues a paused service.
Pause Pauses a running service.
Restart Restarts a service.
Start Starts a service.
Stop Stops a service.

Requirements

Assembly: NAnt.MSNetTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/enums/NAnt.Core.Tasks.AvailableTask.ResourceType.html0000644000175000017500000000421211757307431026507 0ustar jtaylorjtaylor AvailableTask.ResourceType enum

AvailableTask.ResourceType

[This is preliminary documentation and subject to change.]

Defines the possible resource checks.

Fields

Field Description
Directory Determines whether a given directory exists.
File Determines whether a given file exists.
Framework Determines whether a given framework is available.
FrameworkSDK Determines whether a given SDK is available.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/enums/NAnt.DotNet.Types.DelaySign.html0000644000175000017500000000472211757307467023576 0ustar jtaylorjtaylor DelaySign enum

DelaySign

[This is preliminary documentation and subject to change.]

Specifies whether the generated assembly is strongly named and will be signed later.

For backward compatibility, the following string values can also be used in build files:

Value Corresponding field
"true" Yes
"false" No

Fields

Field Description
No Fully sign the assembly.
NotSet Not specified.
Yes Only place the public key in the assembly, allowing the signature to be added later.

Requirements

Assembly: NAnt.DotNetTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/enums/NAnt.Core.Tasks.LoopTask.LoopTrim.html0000644000175000017500000000421011757307444024656 0ustar jtaylorjtaylor LoopTask.LoopTrim enum

LoopTask.LoopTrim

[This is preliminary documentation and subject to change.]

Fields

Field Description
Both Remove all white space characters from the beginning and end of the current item.
End Remove all white space characters from the end of the current item.
None Do not remove any white space characters.
Start Remove all white space characters from the beginning of the current item.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/enums/NAnt.DotNet.Tasks.AssemblyInfoTask.CodeLanguage.html0000644000175000017500000000402511757307462027422 0ustar jtaylorjtaylor AssemblyInfoTask.CodeLanguage enum

AssemblyInfoTask.CodeLanguage

[This is preliminary documentation and subject to change.]

Defines the supported code languages for generating an AssemblyInfo file.

Fields

Field Description
CSharp A value for generating C# code.
JScript A value for generating JScript code.
VB A value for generating Visual Basic code.

Requirements

Assembly: NAnt.DotNetTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/enums/NAnt.NUnit.Types.FormatterType.html0000644000175000017500000000340011757307523024345 0ustar jtaylorjtaylor FormatterType enum

FormatterType

[This is preliminary documentation and subject to change.]

The built-in formatter types.

Fields

Field Description
Plain A plaintext formatter.
Xml An XML formatter.

Requirements

Assembly: NAnt.NUnit (0.92.4526.0)
nant-0.92-rc1/doc/help/enums/NAnt.Core.Tasks.MailTask.MailFormat.html0000644000175000017500000000403311757307445025121 0ustar jtaylorjtaylor MailTask.MailFormat enum

MailTask.MailFormat

[This is preliminary documentation and subject to change.]

Temporary enum replacement of MailFormat to ease transition to newer property flags.

Fields

Field Description
Html Indicates the body of the email is formatted in html.
Text Indicates the body of the email is formatted in plain text.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/enums/NAnt.Compression.Types.TarCompressionMethod.html0000644000175000017500000000401711757307422027120 0ustar jtaylorjtaylor TarCompressionMethod enum

TarCompressionMethod

[This is preliminary documentation and subject to change.]

Specifies the compression methods supported by <tar> task and <untar> task.

Fields

Field Description
BZip2 BZIP2 compression.
GZip GZIP compression.
None No compression.

Requirements

Assembly: NAnt.CompressionTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/enums/NAnt.Core.Types.ManagedExecution.html0000644000175000017500000000561511757307435024627 0ustar jtaylorjtaylor ManagedExecution enum

ManagedExecution

[This is preliminary documentation and subject to change.]

Specifies the execution mode for managed applications.

For backward compatibility, the following string values can also be used in build files:

Value Corresponding field
"true" Auto
"false" Default

Even if set to Default, the operating system can still run the program as a managed application.

On Linux this can be done through binfmt_misc, while on Windows installing the .NET Framework redistributable caused managed applications to run on the MS CLR by default.

Fields

Field Description
Auto Leave it up to the CLR to determine which specific version of the CLR will be used to run the application.
Default Do not threat the program as a managed application.
Strict Forces an application to run against the currently targeted version of a given CLR.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/enums/NAnt.Core.FrameworkTypes.html0000644000175000017500000000537611757307577023301 0ustar jtaylorjtaylor FrameworkTypes enum

FrameworkTypes

[This is preliminary documentation and subject to change.]

Defines the types of frameworks.

Fields

Field Description
All All frameworks supported on the current platform, regarless of their installation state, target device or vendor.
Browser Frameworks that run in a browser.
Compact Frameworks that target compact devices.
Desktop Frameworks that typically target full desktop devices.
Installed Frameworks that are installed on the current system.
Mono Frameworks released as part of the open-source Mono project.
MS Frameworks released by Microsoft.
NotInstalled Frameworks that are supported on the current platform, but are not installed.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/enums/NAnt.Compression.Types.DuplicateHandling.html0000644000175000017500000000377511757307425026403 0ustar jtaylorjtaylor DuplicateHandling enum

DuplicateHandling

[This is preliminary documentation and subject to change.]

Specifies how entries with the same name should be processed.

Fields

Field Description
Add Overwrite existing entry with same name.
Fail Report failure when two entries have the same name.
Preserve Preserve existing entry with the same name.

Requirements

Assembly: NAnt.CompressionTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/enums/NAnt.DotNet.Types.DebugOutput.html0000644000175000017500000000552711757307475024171 0ustar jtaylorjtaylor DebugOutput enum

DebugOutput

[This is preliminary documentation and subject to change.]

Specifies the type of debugging information generated by the compiler.

For backward compatibility, the following string values can also be used in build files:

Value Corresponding field
"true" Enable
"false" None

When set to Enabled then the following conditional compilation symbols will also be defined:

  • DEBUG
  • TRACE

Fields

Field Description
Enable Enable attaching a debugger to the running program.
Full Enable attaching a debugger to the running program.
None Create no debug information.
PdbOnly Only display assembler when the running program is attached to the debugger.

Requirements

Assembly: NAnt.DotNetTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/enums/NAnt.Core.Level.html0000644000175000017500000000465611757307434021356 0ustar jtaylorjtaylor Level enum

Level

[This is preliminary documentation and subject to change.]

Defines the set of levels recognised by the NAnt logging system.

Fields

Field Description
Debug Designates fine-grained informational events that are most useful to debug a build process.
Error Designates error events.
Info Designates informational events that are useful for getting a high-level view of the build process.
None Can be used to suppress all messages.
Verbose Designates events that offer a more detailed view of the build process.
Warning Designates potentionally harmful events.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/introduction/0000755000175000017500000000000011757310030017234 5ustar jtaylorjtaylornant-0.92-rc1/doc/help/introduction/index.html0000644000175000017500000000371011757310021021232 0ustar jtaylorjtaylor NAnt - Introduction

Introduction

[This is preliminary documentation and subject to change.]

Requirements, installation, quick start, history of NAnt and other miscellaneous topics.

> Why NAnt?

> System Requirements

> Installation

> Getting Started

> Ant Users

> History

nant-0.92-rc1/doc/help/introduction/installation.html0000644000175000017500000001732611757310021022634 0ustar jtaylorjtaylor Installation

Installation

[This is preliminary documentation and subject to change.]

NAnt is available in either a source or binary distribution. The binary distribution is all you need to use NAnt to build your projects, including creating your own custom tasks, types and functions.

If you are upgrading NAnt from a previous version, you must never install over the top of your previous installation. Delete or rename the existing installation directory before installing the new version of NAnt.

Installing from binaries

  1. Download the binary distribution archive. Either nant-bin.zip or nant-bin.tar.gz will work, the contents of each archive are the same.
  2. Remove any previous versions of NAnt you may have installed.
  3. Extract the contents of the archive to the location you wish to install NAnt (eg: C:\Program Files\NAnt in windows, or /usr/local/nant in Linux)
  4. Depending on your environment, create a wrapper script to run NAnt:

    Run NAnt using Microsoft.NET

    • Create a file called nant.bat in a directory that is included in the PATH system environment variable. (eg. C:\WINDOWS).
    • Add the following to nant.bat:
      @echo off
      "C:\Program Files\NAnt\bin\NAnt.exe" %*
                              

    Run NAnt using Mono

    • Windows

      • Create a file called nant.bat in a directory that is included in the PATH system environment variable. (eg. C:\WINDOWS).
      • Add the following to nant.bat:
        @echo off
        mono "C:\Program Files\NAnt\bin\NAnt.exe" %*
                                        
    • Linux / Cygwin

      • Create a file called nant in a suitable location in your filesystem (eg. /usr/local/bin).
      • Add the following to nant:
        #!/bin/sh
        exec mono /usr/local/nant/bin/NAnt.exe "$@"
                                
      • Ensure nant has permission to execute, eg:
        chmod a+x /usr/local/bin/nant
                                
  5. Open a new command prompt (shell) and type nant -help. If successful, you should see a usage message displaying available command line options.
  6. (optional) Download and install NAnt-contrib or other third party extensions to NAnt.

Installing from source

  1. Download the source distribution archive. Either nant-src.zip or nant-src.tar.gz will work, the contents of each archive are the same.
  2. Remove any previous versions of NAnt you may have installed.
  3. Extract the contents of the archive to a temporary location. This should not be the location you wish to install NAnt to.
  4. Open a command prompt and change into the folder you extracted the archive to.
  5. Depending on your environment, build the NAnt distribution:

    Install NAnt using Microsoft .NET

    • GNU Make

      make install MONO= MCS=csc prefix=installation-path

      eg. make install MONO= MCS=csc prefix="C:\Program Files"

    • NMake

      nmake -f Makefile.nmake install prefix=installation-path

      eg. nmake -f Makefile.nmake install prefix="C:\Program Files"

    Install NAnt using Mono

    • GNU Make

      make install prefix=installation-path

      eg. make install prefix="C:\Program Files"

    • NMake

      nmake -f Makefile.nmake install MONO=mono CSC=mcs prefix=installation-path

      eg. nmake -f Makefile.nmake install MONO=mono CSC=mcs prefix=/usr/local/

    This will first build a bootstrap version of NAnt, and then use that to build and install the full version to installation-path/NAnt.

  6. Follow the instructions as for a binary release from step 5.
nant-0.92-rc1/doc/help/introduction/fog0000000041.html0000644000175000017500000000454711757310020021653 0ustar jtaylorjtaylor Getting Started

Getting Started

[This is preliminary documentation and subject to change.]

This topic will show you NAnt building itself.  Before you begin make sure your system meets the system requirements.

  1. Download the latest source release.
  2. Unzip the distribution into a new folder.
  3. Open a command prompt and change the directory to the folder where NAnt was installed.
  4. Type bin\nant to build NAnt.
  5. Look at the NAnt.build file to see how it works.

If you did everything correctly you should see something like this:

Console output

nant-0.92-rc1/doc/help/introduction/fog0000000079.html0000644000175000017500000000440211757310021021655 0ustar jtaylorjtaylor Why NAnt?

Why NAnt?

[This is preliminary documentation and subject to change.]

NAnt is different.  Instead of a model where it is extended with shell-based commands, NAnt is extended using task classes.  Instead of writing shell commands, the configuration files are XML-based, calling out a target tree where various tasks get executed.  Each task is run by an object that implements a particular Task interface.

Granted, this removes some of the expressive power that is inherent in being able to construct a shell command such as 'find . -name foo -exec rm {}', but it gives you the ability to be cross-platform - to work anywhere and everywhere. And hey, if you really need to execute a shell command, NAnt has an <exec> task that allows different commands to be executed based on the OS it is executing on.

For more information on why Ant and NAnt were developed read the Ant Introduction.

nant-0.92-rc1/doc/help/introduction/fog0000000042.html0000644000175000017500000000373311757310020021650 0ustar jtaylorjtaylor History

History

[This is preliminary documentation and subject to change.]

The idea for NAnt came from Hazware's XBuild project which in turn was inspired from Apache Ant.  After emailing the author for a beta 2 release of the tool and getting no response Gerry Shaw ported the code to .NET beta 2.  Due to the number of changes from .NET beta 1 to beta 2 the result was a total rewrite.

NAnt was registered at Source Forge on July 18, 2001 with the first public release made that day.

The name NAnt comes from the fact that this tool is Not Ant.

nant-0.92-rc1/doc/help/introduction/getting-started.gif0000644000175000017500000003131111757302272023040 0ustar jtaylorjtaylorGIF89aM9smc91U!u!yq9)1e]9mai)}1BYY))}a)m!}iiuY!y!qe]U)ymq1sqseB!q)B!8Z!uJIJ9Y]{R1]s1i(RRsZkaR)usJR9IZ{B{91}eRkc9]s]1q)ykckR焪BZ9})ui)q1m)}J{!i1y9EZBuI!m9]1uJ)Q9i9!H)@p ` A .`*0R&p ha j#x" p0(#4hԘcAidHNE.KF LYTfy%`,%b~50pfg`PqY't|I@ "行*JF@f Ti*P꫰*H[+ht6Zgfjfl9m0lE+-Gܵ` Qum'u$h@x$nzyО}Ջ_ l @\!#Tzphb("رs1" p&|CEdF$RS.s>ob.04Hn6riTiu<9v׋}顗R:ٛiکpzܩ} ޱ:z¾mƛo'q"we۹tv gvyGz{}{G .ho!6FaLc ȁ䘢Qdˣ |2 _jf>lJ<[R"$ g,єFIjOS6?)k(F@dC*m,-H7ɠxS*]2)Bp 2/3ҠpXHXqNpS-Gsq>qtCu|CeQ_݁~1(B2QlD3QPĢQE7h#IHLFGJ m.o~hzƴy$' Q, Ӳ1RleAX ^z)sNd4&L Y5!tCaⷰS:%&qOTڮwU^ݽZ/@]eT6:zp2d',G#eTIY!?ȟ5hT$&JMP'&SiP%NMiʱljaYTY%TԨ격f1)IP" .vN(YfGhzիs\C]5NIgV:ӿӫ,wLiU(CȋFB6z }C#MuF7$ӒT0cz-Kt?;Tmm괷-ڂ*\KըELTvL˔GȲDhAxE3hjl x h`(hI "$8 bЬ4ͫ 83 :CXSU At)"Gu!At !BL b#b_Ha^-b+όMc 7b6eHiV}dYY6J[MK49hglvx$(GIXdRWnGQuKB+N BEȸ3nO"b V WL Ofnb1LrZ @ r+h@ bN_E U+A5$4DD~ǃ4 p{ L!bs"L|3 g?_ Yg7T3hDzϢ_8"ItMnKmP<&彁)!W=rQ\Fw O>+T.\.OħJ]dBWB=U0W*B3L>W|+mtg <=ḂC;TGD{Cvwb%.&qD6Wxj&qW8 fO&/BX&<sXXl#y#=4(Yv{tm)m%bm6%33bnZL(c4I1%o;VoS[>oWdlC*pJV7d g'} dž7}TX ;`;ppڇa c0g1~  ws0~gxp^x%PuXuPpउv00gS'qH`1p0 p\Pu(0w/OUggpx !j;F@kpp&0Pal< YaS#$݃Q=(z$Fz3b b0&?3{cJwS Cօ$|`XAdgLtwppB ;P5Ywp{ȇ&qUbH,~g{s0 h,OYѲggU(@7`f(pbѱf&Q@i0ˈ$`MP&1tu@EA@0ie&1N0xl#??NFP0ǦXlkv"&mUYyG9Y>mn՜tZennbrI&Y[[c`@J#i\p3KƇpȇp0)]WqAy|8ɓw?r:opsd~ :ᔗhO0 Tsatm :uU'ɡ&j(vp&p& `fi_81wx HwAx@x@xP/Vj'`f jxb!< "-ҏy8#yE#&>%Vz %ǐ[%%bi&wC32u{5@?S=@[Hd^(AHeyuk9ĔUfsh8ٟ6 X~ g(`sjb 'shp&-q(PuP _Li2gwgC@yY.*FOu5 `f\WGx/&1%$2H(XHyi)22řYǹm$Z}FH4H(4iK#oUÝU7oofdBAy\%I s!Jq:u =+08lfg`3`*gkpL0As]@:uLTHlc9dw9ⲁ=?J&:U|i\`fSTKxbf'x`e a8a "a+c#zۖ3>!>z?w5Qh@*dioB%2K\>|ʼ׆j8e2s}wq+``601*t gry֔ZkCfTPt-pv\F1-u w uAH/w?Y A?HH  0걌cWab@Apb4|Ic0[ [?@,0F)yGs17XmɃ)9nYnZKn4Y2՝V/ɫIpeͫȧ<: }h0 2aOk/fpg8,x(еAhO^LtWu+xF 1pwfwڪA ~?Zpaf(:Ag:ᨮcb)0ee Fg^0x"PƏa'tJQ kz~*#%kб7ƻYT Aȋd{ppuuT 8,+%DAB8V+VdUV=TiUv PluNWLmjjWREk#;Ȃ gtu41 {֖2:GmzZ`lE3kɄi,clL?p,@:Efcy,5kK7["-e{Ҙ}٘|H8We8GMuM^T9ђӮ芸vv_s头3"kq`XOxg2ܦ5r]̺eb}>>&z+n\[[]@[ؘ|:|$f8 ]}U+3][U,C-,2CCgBi4@DFVoejEPME,V^EÖatX˖SVܰZm3ņ$Hd|n{xmIj|M[o|[(@V+\xlTz|\7ߎta}߹"^J8$Ք^הM^iMj.NANkTEN`W/Ss - l!i*y\,'x:e'ݩ^(R+/E{B. rїj7pV>$}|Z2=f+tӳa%2VC uNDO=EQWmE|/uN0Ul 0-UG,Zm1^o}qݧs}khz Ac>6\o3 匭K A T/Nٹټ2^ %Nڷaڽ&9eVoKvjeNiNwzNվ ``L܎ac=4&МEݕΧз4n}IMA&驼npr2s_~mӿ~, CN.ǎ@C=8:VNhԎ WἶE ^#O(>*fĹ[6>9>;~놝OfT.I΅fJM Pp|O+١L_ "/fMh̡l/N_vw#Ox;< σNhA` `C"Xb t@1CG3N@dI2,(Â1a.0M9o2؀aO x2 &=T 0:*Un底_-0h՞eqȍK\yU@_ać,fcȑ%KN5 gСE&]iԩUfkرeϦ]mܹumT'^qɕ/gsѥO^uٵow᧯|9ԯg{ϧ_}p@ 4@/~CV"pB +B 3pC;CCqDK4DSTqE[tqFk B{G rH"4H$0UtI'#7/SJ,rK.K$4ML4TsM6t ,L*N3B9IS4PDUtQmPwdtRJ+4M NLCuTRKQ ?NS[uUX- BV-4V\suLlWb55 M3uYhPNq UYQ [ P\i57WjUaUq\ \y^=w_~Lu#^w `Vލ7^Pb%~`^7V[/d7؀?bf5ιsYgpY\ǝx蔓VJkN}egGպkyiӆ1?1jkAk |pm4|Ƨ ‘Iai~\ro;p;\D&}fy4h98ޚ1fvos{9DK,}W~Wt|_L^陷z@Tf߱mvP藽֝װuL  Ňt;Ck3QP?Ν-n ?H܃b>,wX#@u۝ :9cҴVlo{ "xCiQ\-0x3C ݊&Qfc mg@PӡhGB&rB̚ jƌ- v&bF *p{\RC:py$ !=44m'lcC ڌ  |$*F6r}ģ8;;j5i]pru k:jR;S(BFqT_㲅T-m2-s4DvIaRRe^06ͩn [*'wNx)n3_8uf -Ew3^L=o+n q-MGs^o+1ңkiZtfQUZke}ָh W߶þ]]b'{yNŮl[v;lg[['6=mp wm['`xF{X[߈jMzVsc&'/xo9uvxtpVIŰxǷ{R _M%+.Yk5O+09RNP2} x+A|5ҒV*^VZ{S"?k>PRR*{>38{< S.0:D)!ALB xcoY79:S <3:ܖ! #<lB( $(")Y&B3l3;m{[,B3/-?6ZdIϓ7">KB{&#껷 R! ól*s=*>+=BJR?.:7#+ճEl=C=l1QaC3t%G ;*;^lK|LA]&*;"`CUgB?K,[@F<ʾm2|m̿kn<5D(3A >T2Y\FXD@876q|62<t(4@ D3AF;c#.yH&YApGDF̓C%\Iʕ"(!"6-<0,ǙLƠ,J$I 5DäB.dI 2JDcFWA J@CCaZIqʳ8˺Jk1!D; %c?G;ÈcFT$ O\,,OljctNKH5Mr*ʛ$H U JlLNl?bPE\ K-JGu3X.IMPaRZ؇UD=za a[RN Nƛ_If _WY%ԏ\ LĽѸ2a^-IuTZżZ^p}4(Rmʳ% J~\}\5%G*$[@0 e$LXΓ[~IQ36TZ-C,VO']]AF=)B [IWdigoRuK^}>$bm6N^Y-k*/%&l5Lc(Y<D규ڤ%,H ֺk;WEEZwƝg)dd䒻0 mՆ^e6gTޕYfZ/&^FY>mn\~n qnnnTQn^n>o6ono\fo:o~ os BDLb,FnQ}C%oLl)lNlR vAoOq(eM;+qSbS(jߍOB%Ec6? h0z:hVl}&CtABePMj/+WmqJI2&Gg3FWnP`7&GNYaVNP U;rr_^_u1ƃ|a\S%@ r@wjQp&kv44dqT^iZMKmh1/R%5^S/ ueq6W4-yq.w|x.Wy7d]khYRxj7hA&X/ڮ܈YLjǐV\i2Z&9tT5F Mk^ݰD/VLy,:&fVH#ҨTb&FUX=Ekjy*^烌N:M: hCJcD2[jj.Y, ʇ݊;5`䪻|߆.zgb_{/Թlom |ھ: ;< 0pZ1{Ec!3<2)*J%K 35IJ6l J; %݉iL84lz^ѵyeժM{,tA-zd~6rOֵf VQwoEEwiB޶;})W[䤏{^IwV* $UqH类eJ.;h'//|3|C?S=cs?> p>>A>?`-t?OG; M<20=<`8RP=UԹ %>:Dh9|H5Ґ9DT7 de87 X%A|H'P#"ACB1^ 1V\n|#c9ұv#=~# )A<$"E2D")IR$&3Mr$(C)Q<%*SU2; c)YҲ%.s]򲗾%0)a<&2[fl|&4)iRּ&6mr&8)q<':өuL)yҳ'>}'@*Ё=(BЅ2b#D#*щR(F3эr(HC*ґ&=)JSҕN4 ;nant-0.92-rc1/doc/help/introduction/fog0000000081.html0000644000175000017500000000373511757310021021656 0ustar jtaylorjtaylor Ant Users

Ant Users

[This is preliminary documentation and subject to change.]

If you have used Ant before than NAnt should feel comfortable but NAnt is only compatible with Ant in spirit.   Here is a partial list of differences:

  • Tasks do not have to be in a target.  Tasks that appear directly in the project are executed inorder before any tasks in targets are executed.
  • nant.onsuccess and nant.onfailure properties can be defined target names that will be executed at the end of the build.
  • NAnt looks for the first file ending in .build instead of build.xml.
nant-0.92-rc1/doc/help/introduction/fog0000000006.html0000644000175000017500000000477711757310020021661 0ustar jtaylorjtaylor System Requirements

System Requirements

[This is preliminary documentation and subject to change.]

To use NAnt you need one of the following CLR's:

  • Microsoft .NET Framework 1.0
  • Microsoft .NET Framework 1.1
  • Microsoft .NET Framework 2.0
  • Mono 1.x

Note: Additional requirements may apply to individual tasks.

Library Dependencies

NAnt uses a number of open source third party libaries.  Recent versions are included included with the NAnt distribution and no extra work is required to install them.  More information on these libraries are available at:

> NUnit - Required for unit testing

> NDoc - Required for documentation generation

> SharpZipLib - Required for the zip and unzip tasks

nant-0.92-rc1/doc/help/fundamentals/0000755000175000017500000000000011757310030017174 5ustar jtaylorjtaylornant-0.92-rc1/doc/help/fundamentals/tasks.html0000644000175000017500000002732411757310020021216 0ustar jtaylorjtaylor Tasks

Tasks

[This is preliminary documentation and subject to change.]

Contents

1 Introduction

A task is a piece of code that can be executed.

A task can have multiple attributes (or arguments, if you prefer).  The value of an attribute may contain references to a property.  These references will be resolved before the task is executed.

Tasks have a common structure:

<name attribute1="value1" attribute2="value2" ... />

where name is the name of the task, attribute# is the attribute name, and value# is the value for this attribute.

> For more information see the Task Reference.

2 Loading custom extensions

Extensions can be devided in the following categories:

  • Tasks
  • Filters
  • Functions
  • Global Types

NAnt currently provides two mechanisms to make third-party extensions available for use in build scripts:

  • Automatic discovery
  • Forced scan

Both mechanisms use .NET reflection to scan one or more assemblies for the presence of extensions. When found, these extensions are registered in the NAnt type system, and from then on these are available for all build scripts (in the current NAnt instance).

2.1 Automatic discovery

To facilitate registration of extensions that are used in multiple (or even all) build scripts, NAnt supports automatic discovery of extensions.

In this context, automatic discovery means scanning a predefined set of directories and files for extensions.

The actual set of directories and files that is scanned is determined by:

  • Operating system
  • Runtime framework
  • Project

2.1.1 Operating system

When starting NAnt, all assemblies matching the following patterns will be scanned for extensions:

Windows

Pattern Action Description

*Tasks.dll include NAnt Core assemblies
*Tests.dll include NAnt test assemblies
extensions/common/neutral/**/*.dll include Framework and version-neutral assemblies
NAnt.MSNetTasks.dll exclude Microsoft.NET specific assembly
NAnt.MSNet.Tests.dll exclude Microsoft.NET specific test assembly

Unix

Pattern Action Description

*Tasks.dll include NAnt Core assemblies
*Tests.dll include NAnt test assemblies
extensions/common/neutral/**/*.dll include Framework and version-neutral assemblies
NAnt.MSNetTasks.dll exclude Microsoft.NET specific assembly
NAnt.MSNet.Tests.dll exclude Microsoft.NET specific test assembly
NAnt.Win32Tasks.dll exclude Win32 specific assembly
NAnt.Win32.Tests.dll exclude Win32 specific test assembly

NOTE: all patterns are matched relative to the NAnt base directory, which is the directory in which NAnt.exe is located.

2.1.2 Runtime framework

Depending on the runtime framework on which NAnt is running, some additional directories are scanned.

In general, the following include patterns are applied:

extensions/common/<CLR version>/**/*.dll
extensions/<framework family>/neutral/**/*.dll
extensions/<framework family>/<framework version>/**/*.dll

Example:

When running NAnt on Microsoft .NET Framework 1.0, assemblies matching the following pattern would be scanned:

extensions/common/1.0/**/*.dll
extensions/net/neutral/**/*.dll
extensions/net/1.0/**/*.dll

NOTE: the exact set of patterns that are used for a given runtime framework is defined in the NAnt configuration file (NAnt.exe.config).

2.1.3 Project

Whenever a build project is started, NAnt will scan the following directories for assemblies that match the *.dll pattern:

  • <Project Base Directory>/extensions/common/neutral/
  • <Project Base Directory>/extensions/common/<CLR version>/
  • <Project Base Directory>/extensions/<framework family>/neutral/
  • <Project Base Directory>/tasks/<framework family>/<framework version>/

Example:

For a project file located in "c:\projects\log4net" with NAnt running on the Microsoft .NET 2.0 runtime, NAnt would end-up scanning the following project-level directories:

  • c:\projects\log4net\extensions\common\neutral\
  • c:\projects\log4net\extensions\common\2.0\
  • c:\projects\log4net\extensions\net\neutral\
  • c:\projects\log4net\extensions\net\2.0\

2.2 Forced scan

To explicitly instruct NAnt to scan a certain assembly (or set of assemblies) for extensions, build authors can use the <loadtasks> tasks.

nant-0.92-rc1/doc/help/fundamentals/buildfiles.html0000644000175000017500000001035311757310020022205 0ustar jtaylorjtaylor NAnt - Build Files

Build Files

[This is preliminary documentation and subject to change.]

NAnt's build files are written in XML. Each build file contains one project and a number of targets.  Each target contains a number of tasks.

Here is a simple build file that compiles a C# HelloWorld project. 

    <?xml version="1.0"?>
    <project name="Hello World" default="build" basedir=".">
        <description>The Hello World of build files.</description>
        <property name="debug" value="true" overwrite="false" />
        <target name="clean" description="remove all generated files">
            <delete file="HelloWorld.exe" failonerror="false" />
            <delete file="HelloWorld.pdb" failonerror="false" />
        </target>
        <target name="build" description="compiles the source code">
            <csc target="exe" output="HelloWorld.exe" debug="${debug}">
                <sources>
                    <includes name="HelloWorld.cs" />
                </sources>
            </csc>
        </target>
    </project>
        

In this example there are two targets, "clean" and "build".  By default the "build" target will be called.

Examples

You can find the files you need to try out these examples in the examples folder that comes with the NAnt distribution.

nant

Runs NAnt and builds the project in debug mode (the default).

nant clean

Runs NAnt and removes the compiled files if they exist.

nant -D:debug=false

Runs NAnt and builds the project in non-debug mode.  Even though the build file sets the debug property to true, the value that is set on the command line will not be touched, as the "overwrite" attribute on the <property> task is set to "false".

Important: Some tasks like the compiler tasks will only execute if the date stamp of the generated file is older than the source files.  If you compile HelloWorld project in debug mode and then try to compile it again in non-debug mode without first cleaning nothing will happen because NAnt will think the project does not need rebuilding.

nant-0.92-rc1/doc/help/fundamentals/index.html0000644000175000017500000000420011757310020021164 0ustar jtaylorjtaylor NAnt - Fundamentals

Fundamentals

[This is preliminary documentation and subject to change.]

The basic concepts needed to understand and use NAnt.

> Running NAnt

> Build Files

> Projects

> Targets

> Tasks

> Properties

> Loggers & Listeners

> Expressions

> Functions

nant-0.92-rc1/doc/help/fundamentals/targets.html0000644000175000017500000001522411757310020021536 0ustar jtaylorjtaylor NAnt - Targets

Targets

[This is preliminary documentation and subject to change.]

A target has these attributes:

Attribute Description Required
name The name of the target. Yes
depends A comma-separated list of names of targets on which this target depends. No
if An expression that should evaluate to true in order for this target to execute. No
unless An expression that, when evaluated to true, will cause the target to be skipped. No
description A short description of this target's function. No

The optional description attribute can be used to provide a one-line description of this target, which is printed by the -projecthelp command-line option.

Dependencies

A target can depend on other targets.  You might have a target for compiling, for example, and a target for creating a distributable.  You can only build a distributable when you have compiled first, so the distribute target depends on the compile target.  NAnt resolves these dependencies.

NAnt tries to execute the targets in the depends attribute in the order they appear from left to right.  It is possible that a target can get executed earlier when an earlier target depends on it:

    <target name="A"/>
    <target name="B" depends="A" />
    <target name="C" depends="B" />
    <target name="D" depends="C,B,A" />
        

Suppose we want to execute target D.  From its depends attribute, you might think that first target C, then B and then A is executed.  Wrong!  C depends on B, and B depends on A, so first A is executed, then B, then C, and finally D.

A target gets executed only once, even when more than one target depends on it (see the previous example). However, when the <call> task is used to execute a target, both the target and all its dependent targets will be re-executed.

Wild Targets

A target can be marked as wild by setting the name attribute to "*". A build file can contain up to one wild target, and it is executed if and only if the invoked target does not exist in the current build file.  Wild targets let you define how to handle invalid requests, or provide generic behavior for unknown targets. For example:

     <target name="A" />
     <target name="B" />
     <target name="*" />
         

The last target is executed if the invoked target is neither A nor B.

Conditional Execution

A target also has the ability to perform its execution if or unless a property has been set.  This allows, for example, better control on the building process depending on the state of the system (OS, command-line property defines, etc.).  To make a target sense this property, you should add the if or unless attribute with an expression that the target should react to. For example:

    <target name="build-module-A" if="${module-A-present}" />
    <target name="build-own-fake-module-A" unless="${file::exists('fake-module-a.dll')}" />
        

If no if and no unless attribute is present, the target will always be executed.

Note: the dependencies of a target are always executed before testing the target's condition.

nant-0.92-rc1/doc/help/fundamentals/projects.html0000644000175000017500000000673711757310020021727 0ustar jtaylorjtaylor NAnt - Projects

Projects

[This is preliminary documentation and subject to change.]

A project has these attributes:

Attribute Description Required
name The name of the project. No
default The default target to execute when no target is supplied on the command-line. No
basedir The base directory from which all path calculations are done.  If not set, the parent directory of the buildfile will be used. No

Optionally, a description for the project can be provided as a top-level <description> element.  The text contained in the description element is used when the -projecthelp command line option is used.  See the example build file for details.

Each project defines zero or more targets.  A target is a set of tasks to be executed.  When starting NAnt, you can select which target(s) you want to have executed.  When no target is given, the project's default target is used. When no target and no default target are specified, only the global tasks of the project are executed.

nant-0.92-rc1/doc/help/fundamentals/functions.html0000644000175000017500000003414011757310020022073 0ustar jtaylorjtaylor NAnt - Functions

Functions

[This is preliminary documentation and subject to change.]

NAnt provides a rich set of bulitin functions, that allow you to:

  • manipulate strings
  • manipulate date/time values
  • manipulate path names
  • read the properties of files/directories
  • access current build information and more
  • and more

For a full list of supported functions, click here.

Function Call Syntax

To call functions, use prefix::function-name(argument1, ..., argumentN) syntax within expressions. NAnt will (implicitly) try to convert the arguments you pass to functions to correct types and will report an error in case of failure.

For example, assuming you would like to call string::contains('0123456789',1) which expects two string parameters, but you want to pass the second parameter which is an integer. NAnt would attempt to convert the second parameter from int to string, which succeeds and function is called as if it was written as string::contains('0123456789','1').

The following table shows the possible type conversions:

From Type To Type Allowed Remarks
int string Yes The conversion is always possible.
int double Yes The conversion is always possible.
int boolean No Can be done with the if() conditional operator or simply as (value <> 0)
int datetime No You cannot convert from int to datetime.
int timespan No You can use the timespan::from-xxx functions to construct a timespan from a given number of days, months, ....
string int Yes If the string doesn't represent an integer value, an error is reported.
string double Yes If the string doesn't represent a floating point value, an error is reported.
string boolean Yes If the string isn't either true or false (case insensitive), an error is reported.
string datetime Yes If the string doesn't represent a valid date/time, an error is reported. Date/time string format is MM/DD/YYYY HH:MI:SS
string timespan No You can use timespan::parse to construct a timespan from a time indicated by a given string. If the string doesn't represent a valid timespan, an error is reported.
double int Yes If the string doesn't represent an integer value, an error is reported.
double string Yes The converted string uses dot as a fractional part separator so the result looks like 0.1234567
double boolean No You cannot convert from double to boolean.
double datetime No You cannot convert from double to datetime.
double timespan No You can use the timespan::from-xxx functions to construct a timespan from a given number of days, months, ....
boolean int No You cannot convert from boolean to int. You may want to use if(boolvalue,1,0) instead.
boolean string Yes The result is 'True' or 'False' string.
boolean double No You cannot convert from boolean to double.
boolean datetime No You cannot convert from boolean to datetime.
boolean timespan No You cannot convert from boolean to timespan.
datetime int No You cannot convert from datetime to int.
datetime string Yes The result is a datetime string with the following format: MM/DD/YYYY HH:MI:SS
datetime double No You cannot convert from datetime to double.
datetime boolean No You cannot convert from datetime to boolean.
datetime timespan No You can use the value of datetime::get-ticks to construct a timespan using timespan::from-ticks.
timespan int No You cannot convert from timespan to int.
timespan double No You can use timespan::get-ticks to convert from timespan to double.
timespan boolean No You cannot convert from timespan to boolean.
timespan string No You can use timespan::to-string to obtain the string representation of a timespan.
timespan datetime No You cannot convert from timespan to datetime.

Custom Functions

Just as you can extend NAnt with your own tasks it is also possible to implement your own functions for use in build files.

Functions can be implemented in any .NET language and are loaded in the same manner as tasks. ie either by locating your custom function assembly in the NAnt bin directory or using the <loadtasks> task. Example C# code for a Hello World function :

Define a custom function using C#.

                    
[FunctionSet("hello", "Hello")]
public class HelloFunctions : FunctionSetBase {        
    public HelloFunctions(Project project, PropertyDictionary properties) : base(project, properties) {
    }
    [Function("hello-world")]
    public static string HelloWorldfunc() {
        return "Hello World!!";
    }
}
        

and call that function from a build file.

       
<echo message="${hello::hello-world()}" />
        

A quick and easy way to develop new functions is to use the <script> task. This allows you to create and test new functions without the overhead of building an external assembly. The <script> task documentation contains examples of custom function definitions.

nant-0.92-rc1/doc/help/fundamentals/listeners.html0000644000175000017500000004644411757310020022105 0ustar jtaylorjtaylor NAnt - Loggers & Listeners

Loggers & Listeners

[This is preliminary documentation and subject to change.]

Overview

NAnt has two related features to allow the build process to be monitored: listeners and loggers.

Listeners

A listener is alerted of the following events:

  • build started
  • build finished
  • target started
  • target finished
  • task started
  • task finished
  • message logged

Loggers

Loggers extend the capabilities of listeners and add the following features:

  • Receives a handle to the standard output and error print streams and therefore can log information to the console or the -logfile specified file.
  • Logging level (-quiet, -verbose, -debug) aware.
  • Emacs-mode aware. This still needs to be implemented.

Built-in Listeners/Loggers

Class Description Type
NAnt.Core.DefaultLogger The logger used implicitly unless overridden with the -logger command-line switch. IBuildLogger
NAnt.Core.MailLogger Extends DefaultLogger such that output is still generated the same, and when the build is finished an e-mail can be sent. IBuildLogger
NAnt.Core.XmlLogger Generates output in XML format. IBuildLogger

DefaultLogger

Simply run NAnt normally, or:

NAnt.exe -logger:NAnt.Core.DefaultLogger

MailLogger

The MailLogger captures all output logged through DefaultLogger (standard NAnt output) and will send success and failure messages to unique e-mail lists, with control for turning off success or failure messages individually.

Properties controlling the operation of MailLogger are:

Property Description Required
MailLogger.mailhost The SMTP server to use. No, default is "localhost"
MailLogger.from The address of the e-mail sender. Yes, if mail needs to be sent.
MailLogger.failure.notify Send build failure e-mails ? No, default is "true".
MailLogger.success.notify Send build success e-mails ? No, default is "true".
MailLogger.failure.to The address to send build failure messages to. Yes, if failure mail is to be sent.
MailLogger.success.to The address to send build success messages to. Yes, if success mail is to be sent.
MailLogger.failure.subject The subject of build failure messages. No, default is "Build Failure".
MailLogger.success.subject The subject of build success messages. No, default is "Build Success".
MailLogger.failure.attachments The ID of a fileset representing a set of files to attach when the build fails. No.
MailLogger.success.attachments The ID of a fileset representing a set of files to attach when the build is successful. No.
MailLogger.body.encoding The encoding type of the body of the e-mail message. No, default is system's ANSI code page.
MailLogger.smtp.username1 The name of the user to login to the SMTP server. No.
MailLogger.smtp.password1 The password of the specified user. No.
MailLogger.smtp.enablessl1 Specifies whether to use SSL to encrypt the connection. No, default is "false".
MailLogger.smtp.port1 The SMTP server port to connect to. No, default is "25".

1 Only available when NAnt is built targeting .NET Framework 1.1 (or equivalent) or higher.

Usage:

NAnt.exe -logger:NAnt.Core.MailLogger

Example:

    <project name="MailLogger Test" default="build">
        <property name="MailLogger.mailhost" value="smtp.wherever.be" />
        <property name="MailLogger.from" value="me@telenet.be" />
        <property name="MailLogger.failure.notify" value="true" />
        <property name="MailLogger.success.notify" value="true" />
        <property name="MailLogger.failure.to" value="support@home.be" />
        <property name="MailLogger.success.to" value="support@home.be" />
        <property name="MailLogger.failure.subject" value="Nightly build failure !" />
        <property name="MailLogger.success.subject" value="Nightly build successful" />
        <property name="MailLogger.failure.attachments" value="MailLogger.failure.files" />
        <property name="MailLogger.success.attachments" value="MailLogger.success.files" />

        <!-- set of files to attach when build fails -->
        <fileset id="MailLogger.failure.files">
            <include name="dump.log" />
            <include name="trace.txt" />
        </fileset>

        <!-- set of files to attach when build is successful -->
        <fileset id="MailLogger.success.files">
            <include name="trace.txt" />
        </fileset>
    
        <target name="build">
            <echo message="Starting build" />
            ....
            <echo message="Finished build" />
        </target>
    </project>
        

XmlLogger

Writes all build information out to an XML file named log.xml, or the value of the XmlLogger.file property if present, when used as a listener. When used as a logger, it writes all output to either the console or to the value of -logfile.

Whether used as a listener or logger, the output is not generated until the build is complete.

Usage:

NAnt.exe -listener:NAnt.Core.XmlLogger
NAnt.exe -logger:NAnt.Core.XmlLogger -logfile:buildlog.xml

Example:

    <buildresults project="test">
        <message level="Info"><![CDATA[Buildfile: file:///D:/nant-test/xmlpeek/default.build]]></message>
        <message level="Info"><![CDATA[Target framework: Microsoft .NET Framework 1.1]]></message>
        <message level="Info"><![CDATA[Target(s) specified: build]]></message>
        <target name="build">
            <task name="xmlpeek">
                <message level="Info"><![CDATA[Peeking at 'D:\nant-test\xmlpeek\input.xml' with XPath expression 'x:parameters/x:param'.]]></message>
                <message level="Info"><![CDATA[Found '1' nodes with the XPath expression 'x:parameters/x:param'.]]></message>
                <duration>15.625</duration>
            </task>
            <duration>15.625</duration>
        </target>
        <duration>31.25</duration>
    </buildresults>
        
nant-0.92-rc1/doc/help/fundamentals/running-nant.html0000644000175000017500000001135411757310020022503 0ustar jtaylorjtaylor NAnt - Running NAnt

Running NAnt

[This is preliminary documentation and subject to change.]

Running NAnt is simple once you have it installed, just type NAnt.  Type NAnt -help to get usage information.

Specifying the Build File

When nothing is specified, NAnt looks for a file ending with .build, e.g., NAnt.build, in the current directory.  If found, it uses that file as the build file.  If more than one file is found you need to specify the build file using the -buildfile option (see below).

If you use the -find option, NAnt will search for a build file in the parent directory, and so on, until the root of the file system has been reached.  To make NAnt use another build file, use the command-line option -buildfile:file, where file is the build file you want to use.

Specifying Targets

You can specify one or more targets that should be executed. When omitted, the target that is specified in the default attribute of the <project> tag is used.

The -projecthelp option prints out the description of the project, if it exists, followed by a list of the project's targets. First those with a description, then those without one.

Setting Properties

To override properties specified in the build file use the -D:property=value option, where property is the name of the property, and value is the value for that property. 

Examples

NAnt

Runs NAnt using the file ending in *.build.xml file in the current directory, on the default target.

NAnt -buildfile:..\ProjectName.build

Runs NAnt using the ProjectName.build file in the parent directory, on the default target.

NAnt clean

Runs NAnt using the default build file in the current directory, on a target called clean.

NAnt -D:debug=false clean dist

Runs NAnt using the default build file in the current directory, first on the clean target and then on the dist target while setting the debug property to false.  This could, for example, make a release distribution from scratch.

nant-0.92-rc1/doc/help/fundamentals/expressions.html0000644000175000017500000022714011757310020022451 0ustar jtaylorjtaylor NAnt - Expressions

Expressions

[This is preliminary documentation and subject to change.]

Contents

1 Introduction
2 Expression syntax
3 Data types
4 Operators

1 Introduction

Expressions are simple, yet powerful mechanism that allows you to write advanced formulas to be used in task arguments and conditions that direct the build process. Expressions can access project properties and call builtin or user-defined functions.

NAnt provides a rich set of bulitin functions, that allow you to:

  • manipulate strings
  • manipulate date/time values
  • manipulate path names
  • read the properties of files/directories
  • access current build information and more
  • and more

For a full list of supported functions, click here.

2 Expression Syntax

Expressions can be used in all task arguments, by using ${...} notation. You may use standard syntax for arithmetical (addition, subtraction, multiplication, division, modulus), logical (negation, conjunction, alternative) and relational operators (equality, inequality). To call functions, use prefix::function-name(argument1, ..., argumentN) syntax. To access properties, you simply use their names without any prefix or suffix. See the examples section below for more information.

NOTE: Expressions are often used in XML attributes. The grammar specified in this section applies to the attribute value after XML 1.0 normalization. So, for example, if the grammar uses the character <, this must not appear in the XML source as < but must be quoted according to XML 1.0 rules by, for example, entering it as &lt;.

Examples:

  1. Accessing a property:

    <property name="build.version" value="3" />
    <echo message="The current date is: ${build.version}" />

    This will output the current value of build.version property.

  2. Calling a function

    <echo message="The current date is: ${datetime::now()}" />

    This will output the current date and time.

  3. Storing the result of an expression

    To store the result of an expression in a property, use the <property> task:

    <property name="autoexec-present" value="${file::exists('c:\autoexec.bat')}" />

    This will set the property autoexec-present to either true or false depending on whether the specified file exists or not.

  4. Real-life expression use

    <property name="myprj.basedir" value="c:\" />
    <property name="filename" value="${path::combine(myprj.basedir,'version.txt')}" />

    <if test="${not file::exists(filename) or file::get-length(filename) = 0}">
        <echo message="The version file ${filename} doesn't exist or is empty!" />
    </if>

    This will check for the existence of a file version.txt in a directory specified by myprj.basedir. Note that this makes use of the short-circuit evaluation supported by NAnt, so you can test for the existence of the file and check its length in the same expression. ( ie like C, NAnt will not evaluate the second part of an 'or' expression if the first evaluates to true )

  5. Using expressions to conditionally execute tasks

    All tasks support if and unless attributes. Expressions can be used there to control which tasks get executed:

    <property name="myprj.basedir" value="c:\" unless="property::exists('myprj.basedir')" />
    <csc target="library" output="out.dll" ...
         if="${datetime::now() - file::get-last-write-time('out.dll')) > timespan::from-hours(1)}">
    ...
    </csc>

    This will rebuild the C# library only if it was last rebuilt more than an hour ago.

3 Data types

Expressions can access, pass and return values of the following types:

Type Allowed values
int 32-bit signed integer value
long 64-bit signed integer value
double 64-bit signed double precision floating point value
boolean true or false
string strings of characters of any length.
datetime values represeting date & time (range is from 00:00:00, January 1, 1 AD to 23:59:59, December 31, 9999 AD)
timespan represents a time interval.
version represents a version number consisting of two to four components.

In addition, the expression evaluation engine allows you to return and pass values of any CLI type through the use of custom functions. Note that there's no support for implicit type conversions.

4 Operators

4.1 Operator precedence

NAnt expressions support standard ( c style ) operator precedence, that we're accustomed to:

  • and is evaluated before or, left to right. For example false or true and true and false evaluates as false or ((true and true) and false)
  • multiplication,division and modulus are evaluated before addition and subtraction, left to right. For example 1 + 2 * 3 / 4 evaluates as 1 + ((2 * 3) / 4)
  • parentheses can be used to override the default operator precedence. For example (1 + 2) * 3 evaluates as written, even though the multiplication has precedence over addition

NOTE: Because NAnt supports properties whose names can contain dashes, there's a possible ambiguity between the subtraction of two properties and accessing a single property with a name containing a dash:

aaa-bbb - this is ambiguous. It could either be property aaa MINUS property bbb or property aaa-bbb.

To avoid confusion, it's recommended to surround the subtraction operator (or even better, all binary operators) with spaces. The expression aaa - bbb always evaluates as a subtraction.

4.2 Operators on Numeric Values

The following operators are supported on numeric values:

  • + operator
  • - operator
  • * operator
  • / operator
  • % operator
  • == operator
  • != operator
  • > operator
  • >= operator
  • < operator
  • <= operator
  • unary plus
  • unary minus (negation)

4.2.1 Add

Summary

Returns the arithmetic sum of its operands.

Operands
Left Operand Right Operand Example
int int 1 + 5 evaluates to 6
int long 1 + 6666666667 evaluates to 6666666668
int double 1 + 5.0 evaluates to 6.0
long long 6666666667 + 11111111111 evaluates to 17777777778
long int 6666666667 + 1 evaluates to 6666666668
long double 6666666667 + 1.5 evaluates to 6666666668.5
double double 1.5 + 5.0 evaluates to 6.5
double int 1.0 + 5 evaluates to 6.0
double long 1.5 + 6666666667 evaluates to 6666666668.5

4.2.2 Subtract

Summary

Returns the arithmetic difference of its operands.

Operands
Left Operand Right Operand Example
int int 5 - 1 evaluates to 4
int long 5 - 6666666667 evaluates to -6666666662
int double 5.0 - 1 evaluates to 4.0
long long 11111111111 - 6666666667 evaluates to 4444444444
long int 6666666667 - 5 evaluates to 6666666662
long double 6666666667 - 1.5 evaluates to 6666666665.5
double double 5.0 - 1.0 evaluates to 4.0
double int 5.0 - 1 evaluates to 4.0
double long 1.5 - 6666666667 evaluates to -6666666665.5

4.2.3 Multiply

Summary

Returns the arithmetic product of its operands.

Operands
Left Operand Right Operand Example
int int 5 * 2 evaluates to 10
int long 2 * 6666666667 evaluates to 13333333334
int double 5 * 2.0 evaluates to 10.0
long long 6666666667 * long::parse('2') evaluates to 13333333334
long int 6666666667 * 2 evaluates to 13333333334
long double 6666666667 * 1.7 evaluates to 11333333333.9
double double 5.0 * 2.0 evaluates to 10.0
double int 5.0 * 2 evaluates to 10.0
double long 1.7 * 6666666667 evaluates to 11333333333.9

4.2.4 Divide

Summary

Returns the arithmetic quotient of its operands.

Operands
Left Operand Right Operand Example
int int 10 / 2 evaluates to 5
int long 10 / 10000000000 evaluates to 0.000000001
int double 8 / 2.0 evaluates to 4.0
long long 13333333334 / 6666666667 evaluates to 2
long int 13333333334 / 2 evaluates to 6666666667
long double 13333333334 / 2.0 evaluates to 6666666667.0
double double 9.0 / 2.0 evaluates to 4.5
double int 6.0 / 3 evaluates to 2.0
double long 20000000000.0 / 10000000000 evaluates to 2.0
Remarks

If the divisor is zero, then an error is raised.

4.2.5 Mod

Summary

Returns the remainder after dividing its first operand by its second.

Operands
Left Operand Right Operand Example
int int 5 % 3 evaluates to 2
int long 10 % 6666666667 evaluates to 10
int double 5 % 3.5 evaluates to 1.5
long long 13333333334 % 6666666667 evaluates to 0
long int 6666666667 % 10 evaluates to 7
long double 6666666667 % 3.5 evaluates to 3.0
double double 9.0 % 4.7 evaluates to 4.3
double int 8.5 % 2 evaluates to 0.5
double long 20000000000.0 % 6666666667 evaluates to 6666666666.0
Remarks

If the divisor is zero, then an error is raised.

4.2.6 Equal

Summary

Returns true if and only if the value of the first operand is equal to the value of the second operand.

Operands
Left Operand Right Operand Example
int int 5 == 3 evaluates to false
int long 5 == 6666666667 evaluates to false
int double 6 == 6.0 evaluates to true
long long 6666666667 == 6666666667 evaluates to true
long int 6666666667 == 665 evaluates to false
long double 6666666667 == 6666666667.0 evaluates to true
double double 9.5 == 6.7 evaluates to false
double int 8.5 == 8 evaluates to false
double long 8.5 == 6666666667 evaluates to false

4.2.7 Inequal

Summary

Returns true if and only if the value of the first operand is not equal to the value of the second operand.

Operands
Left Operand Right Operand Example
int int 5 != 3 evaluates to true
int long 5 != 6666666667 evaluates to true
int double 6 != 6.0 evaluates to false
long long 6666666667 != 6666666667 evaluates to false
long int 6666666667 != 665 evaluates to true
long double 6666666667 != 6666666667.0 evaluates to false
double double 9.5 != 6.7 evaluates to true
double int 8.5 != 8 evaluates to true
double long 8.5 != 6666666667 evaluates to true

4.2.8 Greater than

Summary

Returns true if and only if the first operand is greater than the second operand.

Operands
Left Operand Right Operand Example
int int 5 > 3 evaluates to false
int long 5 > 6666666667 evaluates to false
int double 6 > 4.0 evaluates to true
long long 6666666667 > 6666666667 evaluates to false
long int 6666666667 > 665 evaluates to true
long double 6666666667 > 6666666667.0 evaluates to false
double double 9.5 > 9.5 evaluates to false
double int 8.3 > 9 evaluates to false
double long 8.5 > 6666666667 evaluates to false

4.2.9 Greater than or equal

Summary

Returns true if and only if the first operand is greater than or equal to second operand.

Operands
Left Operand Right Operand Example
int int 5 >= 3 evaluates to false
int long 5 >= 6666666667 evaluates to false
int double 6 >= 4.0 evaluates to true
long long 6666666667 >= 6666666667 evaluates to true
long int 6666666667 >= 665 evaluates to true
long double 6666666667 >= 6666666667.0 evaluates to true
double double 9.5 >= 9.5 evaluates to true
double int 8.3 >= 9 evaluates to false
double long 8.5 >= 6666666667 evaluates to false

4.2.10 Less than

Summary

Returns true if and only if the first operand is less than the second operand.

Operands
Left Operand Right Operand Example
int int 5 < 3 evaluates to false
int long 5 < 6666666667 evaluates to true
int double 6 < 7.0 evaluates to true
long long 6666666667 < 6666666667 evaluates to false
long int 6666666667 < 665 evaluates to false
long double 6666666667 < 6666666667.0 evaluates to false
double double 9.5 < 9.5 evaluates to false
double int 8.3 < 9 evaluates to true
double long 8.5 < 6666666667 evaluates to true

4.2.11 Less than or equal

Summary

Returns true if and only if the first operand is less than or equal to second operand.

Operands
Left Operand Right Operand Example
int int 5 <= 3 evaluates to false
int long 5 <= 6666666667 evaluates to true
int double 6 <= 7.0 evaluates to true
long long 6666666667 <= 6666666667 evaluates to true
long int 6666666667 <= 665 evaluates to false
long double 6666666667 <= 6666666667.0 evaluates to true
double double 9.5 <= 9.5 evaluates to true
double int 8.3 <= 9 evaluates to true
double long 8.5 <= 6666666667 evaluates to true

4.2.12 Unary plus

Summary

Returns its operand with the sign unchanged. Semantically, this operation performs no operation.

Operands
Operand Example
int (+1) evaluates to 1
long (+6666666667) evaluates to 6666666667
double (+1.5) evaluates to 1.5

4.2.13 Unary minus

Summary

Returns its operand with the sign reversed.

If the operand is positive, its negative is returned; if it is negative, its positive is returned.

Operands
Operand Example
int (-1) evaluates to -1
long (-6666666667) evaluates to -6666666667
double (-9.6) evaluates to -9.6

4.3 Operators on Boolean Values

The following operators are supported on boolean values:

  • == operator
  • != operator
  • > operator
  • >= operator
  • < operator
  • <= operator
  • and operator
  • or operator

4.3.1 Equal

Summary

Returns true if both operands are true or if both operands are false.

Examples

4.3.2 Inequal

Summary

Returns true if the first operand is true and the second operand is false, or the first operand is false and the second operand is true.

Examples

4.3.3 Greater than

Summary

Returns true if the first operand is true and the second operand is false; otherwise, returns false.

Examples

4.3.4 Greater than or equal

Summary

Returns true if the first operand is true and the second operand is false, or both operands are either true or false.

Examples

4.3.5 Less than

Summary

Returns true if the first operand is false and the second operand is true; otherwise, returns false.

Examples

4.3.6 Less than or equal

Summary

Returns true if the first operand is false and the second operand is true, or both operands are either true or false.

Examples

4.3.7 Logical and

Summary

Returns true if both operands are true, otherwise returns false.

Examples

<if test="${A and B}">

4.3.8 Logical or

Summary

Returns true if either operand is true, otherwise returns false.

Examples

<if test="${A or B}">

4.4 Operators on String Values

The following operators are supported on string values:

  • + operator
  • == operator
  • != operator
  • > operator
  • >= operator
  • < operator
  • <= operator

4.4.1 Concat

Summary

Returns the concatenation of both string operands.

Examples

4.4.2 Equal

Summary

Returns true if the value of the left operand is the same as the value of the right operand.

Remarks

The comparison is case-sensitive and culture-insensitive.

4.4.3 Inequal

Summary

Returns true if the value of the first operand is not the same as the value of the second operand.

Remarks

The comparison is case-sensitive and culture-insensitive.

4.4.4 Greater than

Summary

Returns true if the first operand is greater than the seconds operand.

Remarks

The comparison is case-sensitive and culture-insensitive.

4.4.5 Greater than or equal

Summary

Returns true if the first operand is greater than or equal to the seconds operand.

Remarks

The comparison is case-sensitive and culture-insensitive.

4.4.6 Less than

Summary

Returns true if the first operand is less than the seconds operand.

Remarks

The comparison is case-sensitive and culture-insensitive.

4.4.7 Less than or equal

Summary

Returns true if the first operand is less than or equal to the seconds operand.

Remarks

The comparison is case-sensitive and culture-insensitive.

4.5 Operators on TimeSpan and DateTime Values

The following operators are supported on timespan and datetime values:

  • + operator
  • - operator
  • == operator
  • != operator
  • > operator
  • >= operator
  • < operator
  • <= operator

4.5.1 Add

Summary

Returns the result of adding the value of the left operand to the value of the right operand.

Operands
Left Operand Right Operand Example
datetime timespan datetime::now() + timespan::from-days(10) evaluates to a datetime 10 days in the future
timespan timespan timespan::from-seconds(30) + timespan::from-minutes(10) evaluates to a timespan representing a duratio of 10 minutes and 30 seconds

4.5.2 Subtract

Summary

Returns the result of subtracting the value of the right operand from the value of the left operand.

Operands
Left Operand Right Operand Example
datetime datetime (datetime::now() + timespan::from-days(10)) - datetime::now evaluates to a timespan representing a duration of 10 days
datetime timespan datetime::now() - timespan::from-days(3) evaluates to a datetime 3 days in the past
timespan timespan timespan::from-minutes(15) - timespan::from-minutes(10) evaluates to a timespan representing 5 minutes

4.5.3 Equal

Summary

Returns true if the value of the left operand is the same as the value of the right operand.

Operands
Left Operand Right Operand Example
datetime datetime datetime::now() == (datetime::now() + timespan::from-days(10)) evaluates to false
timespan timespan timespan::from-seconds(30) == timespan::from-seconds(30) evaluates to true

4.5.4 Inequal

Summary

Returns true if the value of the left operand is not the same as the value of the right operand.

Operands
Left Operand Right Operand Example
datetime datetime datetime::now() != (datetime::now() + timespan::from-days(10)) evaluates to true
timespan timespan timespan::from-seconds(30) != timespan::from-seconds(30) evaluates to false

4.5.5 Greater than

Summary

Returns true if the value of the left operand is greater than the value of the right operand.

Operands
Left Operand Right Operand Example
datetime datetime datetime::now() > (datetime::now() + timespan::from-days(10)) evaluates to false
timespan timespan timespan::from-seconds(30) > timespan::from-seconds(30) evaluates to false

4.5.6 Greater than or equal

Summary

Returns true if the value of the left operand is greater than or equal to the value of the right operand.

Operands
Left Operand Right Operand Example
datetime datetime datetime::now() >= (datetime::now() + timespan::from-days(10)) evaluates to false
timespan timespan timespan::from-seconds(30) >= timespan::from-seconds(30) evaluates to true

4.5.7 Less than

Summary

Returns true if the value of the left operand is less than the value of the right operand.

Operands
Left Operand Right Operand Example
datetime datetime datetime::now() < (datetime::now() + timespan::from-days(10)) evaluates to true
timespan timespan timespan::from-seconds(30) < timespan::from-seconds(30) evaluates to false

4.5.8 Less than or equal

Summary

Returns true if the value of the left operand is less than the value of the right operand.

Operands
Left Operand Right Operand Example
datetime datetime datetime::now() <= (datetime::now() + timespan::from-days(10)) evaluates to true
timespan timespan timespan::from-seconds(30) <= timespan::from-seconds(30) evaluates to true

4.6 Operators on Version Values

The following operators are supported on version values:

  • == operator
  • != operator
  • > operator
  • >= operator
  • < operator
  • <= operator

4.6.1 Equal

Summary

Returns true if the value of the left operand is the same as the value of the right operand.

Operands
Left Operand Right Operand Example
version version version::parse('1.2') == version::parse('1.2') evaluates to true

4.6.2 Inequal

Summary

Returns true if the value of the left operand is not the same as the value of the right operand.

Operands
Left Operand Right Operand Example
version version version::parse('1.2') != version::parse('1.3.1') evaluates to true

4.6.3 Greater than

Summary

Returns true if the value of the left operand is greater than the value of the right operand.

Operands
Left Operand Right Operand Example
version version version::parse('1.2') > version::parse('1.3.1') evaluates to false

4.6.4 Greater than or equal

Summary

Returns true if the value of the left operand is greater than or equal to the value of the right operand.

Operands
Left Operand Right Operand Example
version version version::parse('1.2') >= version::parse('1.2') evaluates to true

4.6.5 Less than

Summary

Returns true if the value of the left operand is less than the value of the right operand.

Operands
Left Operand Right Operand Example
version version version::parse('1.2') < version::parse('1.3.1') evaluates to true

4.6.6 Less than or equal

Summary

Returns true if the value of the left operand is less than or equal to the value of the right operand.

Operands
Left Operand Right Operand Example
version version version::parse('1.2') <= version::parse('1.2') evaluates to true
nant-0.92-rc1/doc/help/fundamentals/properties.html0000644000175000017500000003367111757310020022267 0ustar jtaylorjtaylor NAnt - Properties

Properties

[This is preliminary documentation and subject to change.]

Contents

1 Introduction

A project can have a set of properties.  These might be set in the buildfile by the <property> task, or might be set outside NAnt.  A property has a name and a value. Properties may be used in the value of task attributes. This is done by placing the property name between "${" and "}" in the attribute value. Properties may also be used in expressions.

2 Naming rules

A property name is a string of the following characters:

  • letters (A-Z, a-z),
  • digits (0-9),
  • underscore characters (_),
  • dash characters (-),
  • dot characters (.),

In addition, a valid property name must start with a letter or an underscore and must end with a letter, digit or an uderscore.

Examples of valid property names include:

  • propertyname
  • property.name.with.dots
  • property-name-with-dashes
  • property.name-with.both-dots.and-dashes
  • __prop---3-erty__
  • __prop.1...erty__
  • property1
  • property1.0
  • property2.0.0
  • _property-2-1__
  • property-1-name_
  • property-1.0-name

The following property names are not valid in NAnt:

  • !@#!@$!@ (contains illegal characters)
  • .aaaaa (starts with a dot)
  • -aaaaa (starts with a dash)
  • 1aaaaa (starts with a digit)
  • aaaaa.aaa.a.a.a.a- (ends with a dash)
  • aaaaa.aaa.a.a.a.a. (ends with a dot)

3 Built-in Properties

NAnt has these built-in properties:

Property Description
nant.version Deprecated. The version of NAnt.
nant.filename Deprecated. The full path to the NAnt assembly.
nant.location Deprecated. The base directory of the NAnt assembly.
nant.project.basedir Deprecated. The absolute path of the project's basedir.
nant.project.buildfile Deprecated. The absolute path of the buildfile.
nant.project.name Deprecated. The name of the project.
nant.project.default Deprecated. The name of the project's default target.
nant.onsuccess The name of a target to be executed when the build succeeds.
nant.onfailure The name of a target to be executed when the build fails.

3.1 Framework related Properties:

Property Description
nant.settings.currentframework The current target framework, eg. 'net-1.0'.
nant.settings.currentframework.description Deprecated. Description of the current target framework.
nant.settings.currentframework.frameworkdirectory Deprecated. The framework directory of the current target framework.
nant.settings.currentframework.sdkdirectory Deprecated. The framework SDK directory of the current target framework.
nant.settings.currentframework.frameworkassemblydirectory Deprecated. The framework assembly directory of the current target framework.
nant.settings.currentframework.runtimeengine Deprecated. The runtime engine of the current target framework if used eg. mono.exe.

3.2 Platform related Properties:

Property Description
nant.platform.name Deprecated. The name of the platform on which NAnt is currently running - either win32 or unix.
nant.platform.win32 Deprecated. Holds the value true if NAnt is running on the win32 platform; otherwise, false.
nant.platform.unix Deprecated. Holds the value true if NAnt is running on the unix platform; otherwise, false.

4 Read-only Properties

A property can be explicitly marked read-only by setting the "readonly" attribute on the <property> task to true.

The value of a read-only property cannot be modified after it has been set.

When attempting to override a read-only property using the <property> task, the new value will be ignored and a warning message will be output in the build log. Attempting to override read-only properties using any other means (eg. other tasks) will result in a build failure.

Note: properties set on the command-line are always read-only.

5 Global Properties

Properties that should be accessible to all build files on a system can be defined in the <properties> node of the NAnt configuration file (NAnt.exe.config).

By changing the value of the property in the NAnt configuration file, the updated value will be accessible to all build files on the system:

    <?xml version="1.0"?>
    <configuration>
        ...
        <nant>
            ...
            <properties>
                <!-- properties defined here are accessible to all build files -->
                <property name="company.name" value="Foo Ltd." readonly="true" />
            </properties>
        </nant>
    </configuration>
        

Individual build files can then use this property:

    <?xml version="1.0"?>
    <project name="test">
        <echo message="Company: ${company.name}" />
    </project>
        

The output of this build is:

    [echo] Company: Foo Ltd.
        

6 Examples

The following build file demonstrates the use of property expansion:

    <?xml version="1.0"?>
    <project name="Property Test" default="test" basedir=".">
        <property name="project.name" value="PropertyTest"/>
        <property name="project.version" value="1.0.0"/>
        <target name="test">
            <echo message="Building ${project.name}-${project.version}"/>
        </target>
    </project>
        

The output of this build is:

    [echo] Building PropertyTest-1.0.0
        

The following build file demonstrates the use of properties in expressions. It evaluates the length of the property project.name and displays it.

    <?xml version="1.0"?>
    <project name="Expression Test" default="test" basedir=".">
        <property name="project.name" value="Expression Test"/>
        <target name="test">
            <echo message="Project name consists of ${string::get-length(project.name)} characters."/>
        </target>
    </project>
        

The output of this build is:

   [echo] Project name consists of 15 characters.
        

See Also

nant-0.92-rc1/doc/help/tasks/0000755000175000017500000000000011757310030015640 5ustar jtaylorjtaylornant-0.92-rc1/doc/help/tasks/fail.html0000644000175000017500000000773611757307440017471 0ustar jtaylorjtaylor <fail> Task

<fail>

[This is preliminary documentation and subject to change.]

Exits the current build by throwing a BuildException, optionally printing additional information.

The cause of the build failure can be specified using the message attribute or as inline content.

Macros in the message will be expanded.

Parameters

Attribute Type Description Required
message string A message giving further information on why the build exited. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Examples

  • Exits the current build without giving further information.

    <fail />
        
  • Exits the current build and writes a message to the build log.

    <fail message="Something wrong here." />
        
  • Functionally equivalent to the previous example.

    <fail>Something wrong here.</fail>
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/asminfo.html0000644000175000017500000001774311757307467020222 0ustar jtaylorjtaylor <asminfo> Task

<asminfo>

[This is preliminary documentation and subject to change.]

Generates an AssemblyInfo file using the attributes given.

Parameters

Attribute Type Description Required
language CodeLanguage The code language in which the AssemblyInfo file should be generated. True
output file Name of the AssemblyInfo file to generate. True
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Nested Elements:

<attributes>

The assembly-level attributes to generate.
<attribute>

Represents an assembly-level attribute.

Parameters

AttributeTypeDescriptionRequired
typestring Typename of the assembly-level attribute. True
asisbool If true then the value of the attribute will be set as is, without actually looking for a matching constructor or named properties. The default is false. False
ifbool Indicates if the attribute should be generated. False
unlessbool Indicates if the attribute should be not generated. False
valuestring Value of the attribute. False
</attribute>

</attributes>

<imports>

The namespaces to import.

</imports>

<references>

Assembly files used to locate the types of the specified attributes.

</references>

Examples

  • Create a C# AssemblyInfo file containing the specified assembly-level attributes.

    <asminfo output="AssemblyInfo.cs" language="CSharp">
        <imports>
            <import namespace="System" />
            <import namespace="System.Reflection" />
            <import namespace="System.EnterpriseServices" />
            <import namespace="System.Runtime.InteropServices" />
        </imports>
        <attributes>
            <attribute type="ComVisibleAttribute" value="false" />
            <attribute type="CLSCompliantAttribute" value="true" />
            <attribute type="AssemblyVersionAttribute" value="1.0.0.0" />
            <attribute type="AssemblyTitleAttribute" value="My fun assembly" />
            <attribute type="AssemblyDescriptionAttribute" value="More fun than a barrel of monkeys" />
            <attribute type="AssemblyCopyrightAttribute" value="Copyright (c) 2002, Monkeyboy, Inc." />
            <attribute type="ApplicationNameAttribute" value="FunAssembly" />
        </attributes>
        <references>
            <include name="System.EnterpriseServices.dll" />
        </references>
    </asminfo>
        
  • Create a C# AssemblyInfo file containing an attribute with multiple named properties by setting the asis attribute on the AssemblyAttribute element to true.

    <asminfo output="AssemblyInfo.cs" language="CSharp">
        <imports>
            <import namespace="log4net.Config" />
        </imports>
        <attributes>
            <attribute type="DOMConfiguratorAttribute" value="ConfigFile=&quot;config.log4net&quot;,Watch=true" asis="true" />
        </attributes>
        <references>
            <include name="log4net.dll" />
        </references>
    </asminfo>
        

Requirements

Assembly: NAnt.DotNetTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/property.html0000644000175000017500000001360411757307451020433 0ustar jtaylorjtaylor <property> Task

<property>

[This is preliminary documentation and subject to change.]

Sets a property in the current project.

Note: NAnt uses a number of predefined properties.

Parameters

Attribute Type Description Required
name string The name of the NAnt property to set. True
value string The value to assign to the NAnt property.

This attribute's properties will not be automatically expanded!

True
dynamic bool Specifies whether references to other properties should not be expanded when the value of the property is set, but expanded when the property is actually used. By default, properties will be expanded when set. False
overwrite bool Specifies whether the value of a property should be overwritten if the property already exists (unless the property is read-only). The default is true. False
readonly bool Specifies whether the property is read-only or not. The default is false. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Examples

  • Define a debug property with value true.

    <property name="debug" value="true" />
        
  • Use the user-defined debug property.

    <property name="trace" value="${debug}" />
        
  • Define a read-only property. This is just like passing in the param on the command line.

    <property name="do_not_touch_ME" value="hammer" readonly="true" />
        
  • Define a property, but do not overwrite the value if the property already exists (eg. it was specified on the command line).

    <project name="property-example">
      <property name="debug" value="true" overwrite="false" />
      <echo message="debug: ${debug}" />
    </project>
        

    Executing this build file with the command line option -D:debug=false, would cause the value specified on the command line to remain unaltered.

    [echo] debug: false
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/ifnot.html0000644000175000017500000001440311757307443017665 0ustar jtaylorjtaylor <ifnot> Task

<ifnot>

[This is preliminary documentation and subject to change.]

(Deprecated)

The opposite of the if task.

Parameters

Attribute Type Description Required
comparefile string Deprecated. The file to check against for the uptodate file. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
propertyexists string Deprecated. Used to test whether a property exists. False
propertytrue string Deprecated. Used to test whether a property is true. False
targetexists string Deprecated. Used to test whether a target exists. False
test string Used to test arbitrary boolean expression. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
uptodatefile string Deprecated. The file to compare if uptodate. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Nested Elements:

<comparefiles>

Deprecated. The <fileset> that contains the comparison files for the uptodatefile(s) check.

</comparefiles>

<uptodatefiles>

Deprecated. The <fileset> that contains the uptodate files for the comparefile(s) check.

</uptodatefiles>

Examples

  • Check that a property does not exist.

    <ifnot propertyexists="myProp">
        <echo message="myProp does not exist."/>
    </if>
        

    Check that a property value is not true.

    <ifnot propertytrue="myProp">
        <echo message="myProp is not true."/>
    </if>
        
  • Check that a target does not exist.

    <ifnot targetexists="myTarget">
        <echo message="myTarget does not exist."/>
    </if>
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/ildasm.html0000644000175000017500000003017511757307522020021 0ustar jtaylorjtaylor <ildasm> Task

<ildasm>

[This is preliminary documentation and subject to change.]

Disassembles any portable executable (PE) file that contains intermediate language (IL) code.

Files are only disassembled if the input file is newer than the output file, or if the output file does not exist. However, you can explicitly force files to be disassembled with the rebuild attribute.

A <fileset> can be used to select files to disassemble. To use a <fileset>, the todir attribute must be set. The file name of the output file will be equal to the file name of the input file, but with extension ".il".

Parameters

Attribute Type Description Required
all bool Specifies whether or not the disassembler should combine the /HEADER, /BYTE, and /TOKENS options. The default is false. False
bytes bool Specifies whether or not the disassembler should generate the IL stream bytes (in hexadecimal notation) as instruction comments. The default is false. False
header bool Specifies whether or not the disassembler should include PE header information and runtime header information in the output. The default is false. False
input file Specifies the PE file to disassemble. False
item string Instructs the disassembler to disassemble the specified item only. False
linenumbers bool Specifies whether or not the disassembler should include references to original source lines. The default is false. False
noil bool Specifies whether or not the disassembler should suppress ILASM code output. The default is false. False
output file Specifies the name of the output file created by the disassembler. False
publiconly bool Specifies whether or not the disassembler should disassemble public items only. This is a shortcut for visibility="pub". The default is false. False
quoteallnames bool Specifies whether or not the disassembler should enclose all names in single quotation marks. By default, only names that don't match the ILASM definition of a simple name are quoted. The default is false. False
rawexceptionhandling bool Specifies whether or not the disassembler should generate structured exception handling clauses in canonical (label) form. The default is false. False
rebuild bool Instructs NAnt to rebuild the output file regardless of the file timestamps. The default is false. False
source bool Specifies whether or not the disassembler should generate original source lines as comments. The default is false. False
todir directory Specifies the directory to which outputs will be stored. False
tokens bool Specifies whether or not the disassembler should generate metadata token values as comments. The default is false. False
unicode bool Specifies whether or not the disassembler should use the UNICODE encoding when generating the output. The default is ANSI. False
utf8 bool Specifies whether or not the disassembler should use the UTF-8 encoding when generating the output. The default is ANSI. False
visibility string Instructs the disassembler to disassemble only the items with the specified visibility. Possible values are PUB, PRI, FAM, ASM, FAA, FOA, PSC, or any combination of them separated by +. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
timeout int The maximum amount of time the application is allowed to execute, expressed in milliseconds. Defaults to no time-out. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Framework-configurable parameters

Attribute Type Description Required
exename string The name of the executable that should be used to launch the external program. False
managed ManagedExecution Specifies whether the external program should be treated as a managed application, possibly forcing it to be executed under the currently targeted version of the CLR. False
useruntimeengine bool Deprecated. Specifies whether the external program is a managed application which should be executed using a runtime engine, if configured. The default is false. False

Nested Elements:

<assemblies>

Specifies a list of PE files to disassemble. To use a <fileset>, the todir attribute must be specified.

</assemblies>

Examples

  • Disassembles helloworld.exe to helloworld.il.

    <ildasm input="helloworld.exe" output="helloworld.il" />
        
  • Disassembles a set of PE files into the specified directory.

    <ildasm todir=".">
        <assemblies>
            <include name="*.exe" />
            <include name="*.dll" />
        </assemblies>
    </ildasm>
        

Requirements

Assembly: NAnt.MSNetTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/zip.html0000644000175000017500000001502111757307425017345 0ustar jtaylorjtaylor <zip> Task

<zip>

[This is preliminary documentation and subject to change.]

Creates a zip file from the specified filesets.

Uses #ziplib (SharpZipLib), an open source Tar/Zip/GZip library written entirely in C#.

Parameters

Attribute Type Description Required
zipfile file The zip file to create. True
comment string The comment for the file. False
duplicate DuplicateHandling Specifies the behaviour when a duplicate file is found. The default is Add. False
encoding Encoding The character encoding to use for filenames and comment inside the zip file. The default is the system's OEM code page. False
flatten bool Ignore directory structure of source directory, compress all files into a single directory. The default value is false. False
includeemptydirs bool Include empty directories in the generated zip file. The default is false. False
stampdatetime datetime Date/time stamp for the files in the format MM/DD/YYYY HH:MM:SS. False
ziplevel int Desired level of compression. Possible values are 0 (STORE only) to 9 (highest). The default is 6. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Nested Elements:

<fileset>

The set of files to be included in the archive.

</fileset>

Examples

  • Zip all files in ${build.dir} and ${doc.dir} into a file called "backup.zip".

    <zip zipfile="backup.zip">
        <fileset basedir="${bin.dir}" prefix="bin">
            <include name="**/*" />
        </fileset>
        <fileset basedir="${doc.dir}" prefix="doc">
            <include name="**/*" />
        </fileset>
    </zip>
        

Requirements

Assembly: NAnt.CompressionTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/loadfile.html0000644000175000017500000001267711757307444020341 0ustar jtaylorjtaylor <loadfile> Task

<loadfile>

[This is preliminary documentation and subject to change.]

Load a text file into a single property.

Unless an encoding is specified, the encoding associated with the system's current ANSI code page is used.

An UTF-8, little-endian Unicode, and big-endian Unicode encoded text file is automatically recognized, if the file starts with the appropriate byte order marks.

Parameters

Attribute Type Description Required
file file The file to load. True
property string The name of the property to save the content to. True
encoding Encoding The encoding to use when loading the file. The default is the encoding associated with the system's current ANSI code page. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Nested Elements:

<filterchain>

The filterchain definition to use.

</filterchain>

Examples

  • Load file message.txt into property "message".

    <loadfile
        file="message.txt"
        property="message" />
        
  • Load a file using the "latin-1" encoding.

    <loadfile
        file="loadfile.xml"
        property="encoded-file"
        encoding="iso-8859-1" />
        
  • Load a file, replacing all @NOW@ tokens with the current date/time.

    <loadfile file="token.txt" property="token-file">
        <filterchain>
            <replacetokens>
                <token key="NOW" value="${datetime::now()}" />
            </replacetokens>
        </filterchain>
    </loadfile>
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/choose.html0000644000175000017500000001503311757307432020024 0ustar jtaylorjtaylor <choose> Task

<choose>

[This is preliminary documentation and subject to change.]

Executes an alternate set of task or type definition depending on conditions that are individually set on each group.

The <choose> task selects one among a number of possible alternatives. It consists of a sequence of <when> elements followed by an optional <otherwise> element.

Each <when> element has a single attribute, test, which specifies an expression. The content of the <when> and <otherwise> elements is a set of nested tasks.

The content of the first, and only the first, <when> element whose test is true is executed. If no <when> element is true, the content of the <otherwise> element is executed. If no <when> element is true, and no <otherwise> element is present, nothing is done.

Parameters

Attribute Type Description Required
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Nested Elements:

<when>

One or more alternative sets of tasks to execute.

Groups a set of tasks to execute when a condition is met.

Parameters

AttributeTypeDescriptionRequired
testbool Used to test arbitrary boolean expression. True

</when>

<otherwise>

The set of tasks to execute if none of the When elements are true.

Executes embedded tasks/elements in the order in which they are defined.

</otherwise>

Examples

  • Execute alternate set of tasks depending on the configuration being built.

    <choose>
        <when test="${build.config == 'Debug'}">
            <!-- compile app in debug configuration -->
            ...
        </when>
        <when test="${build.config == 'Release'}">
            <!-- compile app in release configuration -->
            ...
        </when>
        <otherwise>
            <fail>Build configuration '${build.config}' is not supported!</fail>
        </otherwise>
    </choose>
        
  • Define a sources patternset holding an alternate set of patterns depending on the configuration being built.

    <choose>
        <when test="${build.config == 'Debug'}">
            <patternset id="sources">
                <include name="**/*.cs" />
            </patternset>
        </when>
        <when test="${build.config == 'Release'}">
            <patternset id="sources">
                <include name="**/*.cs" />
                <exclude name="**/Instrumentation/*.cs" />
            </patternset>
        </when>
        <otherwise>
            <fail>Build configuration '${build.config}' is not supported!</fail>
        </otherwise>
    </choose>
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/index.html0000644000175000017500000003773411757307412017665 0ustar jtaylorjtaylor Task Reference

Task Reference

[This is preliminary documentation and subject to change.]

Task Summary
al Wraps al.exe, the assembly linker for the .NET Framework.
asminfo Generates an AssemblyInfo file using the attributes given.
attrib Changes the file attributes of a file or set of files and directories.
available Checks if a resource is available at runtime.
aximp Generates a Windows Forms Control that wraps ActiveX Controls defined in an OCX.
call Calls a NAnt target in the current project.
choose

Executes an alternate set of task or type definition depending on conditions that are individually set on each group.

cl Compiles C/C++ programs using cl.exe, Microsoft's C/C++ compiler.
copy Copies a file, a directory, or set of files to a new file or directory.
csc Compiles C# programs.
cvs Executes the cvs command specified by the command attribute.
cvs-changelog Produces an XML report that represents the cvs changes from the given start day, to a given end date.
cvs-checkout Checks out a CVS module to the required directory.
cvs-export Exports a cvs module in preperation for a release (i.e. the CVS version folders are not exported).
cvs-pass Executes the cvs login command which appends or updates an entry to the specified .cvspass file.
cvs-rtag Tags all sources in the remote repository with a given tag.
cvs-tag Tags all local sources with the specified tag.
cvs-update Updates a CVS module in a local working directory.
delay-sign Signs delay-signed .NET Assemblies, or re-signs existing assemblies.
delete Deletes a file, fileset or directory.
description An empty task that allows a build file to contain a description.
echo Writes a message to the build log or a specified file.
exec Executes a system command.
fail Exits the current build by throwing a BuildException, optionally printing additional information.
foreach Loops over a set of items.
get Gets a particular file from a URL source.
gunzip Expands a file packed using GZip compression.
if Checks the conditional attributes and executes the children if true.
ifnot The opposite of the if task.
ilasm Compiles ILASM programs.
ildasm Disassembles any portable executable (PE) file that contains intermediate language (IL) code.
include Includes an external build file.
jsc Compiles JScript.NET programs.
lib Run lib.exe, Microsoft's Library Manager.
license Generates a .licence file from a .licx file.
link Links files using link.exe, Microsoft's Incremental Linker.
loadfile Load a text file into a single property.
loadtasks Loads tasks form a given assembly or all assemblies in a given directory or <fileset>.
mail Sends an SMTP message.
mc Compiles messages using mc.exe, Microsoft's Win32 message compiler.
midl This tasks allows you to run MIDL.exe.
mkdir Creates a directory and any non-existent parent directory if necessary.
move Moves a file, a directory, or set of files to a new file or directory.
nant Runs NAnt on a supplied build file, or a set of build files.
nantschema Creates an XSD File for all available tasks.
ndoc Runs NDoc V1.3.1 to create documentation.
nunit Runs tests using the NUnit V1.0 framework.
nunit2 Runs tests using the NUnit V2.6 framework.
property Sets a property in the current project.
rc Compiles resources using rc.exe, Microsoft's Win32 resource compiler.
readregistry Reads a value or set of values from the Windows Registry into one or more NAnt properties.
regasm Registers an assembly, or set of assemblies for use from COM clients.
regex Sets project properties based on the evaluatuion of a regular expression.
regsvcs Installs or removes .NET Services.
resgen Converts files from one resource format to another.
script Executes the code contained within the task.
servicecontroller Allows a Windows service to be controlled.
setenv Sets an environment variable or a whole collection of them. Use an empty value attribute to clear a variable.
sleep A task for sleeping a specified period of time, useful when a build or deployment process requires an interval between tasks.
solution Compiles VS.NET solutions (or sets of projects), automatically determining project dependencies from inter-project references.
style Processes a document via XSLT.
sysinfo Sets properties with system information.
tar Creates a tar file from the specified filesets.
tlbexp Exports a .NET assembly to a type library that can be used from unmanaged code (wraps Microsoft's tlbexp.exe).
tlbimp Imports a type library to a .NET assembly (wraps Microsoft's tlbimp.exe).
touch Touches a file or set of files -- corresponds to the Unix touch command.
trycatch Executes a set of tasks, and optionally catches a build exception to allow recovery or rollback steps to be taken, or to define some steps to be taken regardless if the tasks succeed or fail, or both.
tstamp Sets properties with the current date and time.
untar Extracts files from a tar archive.
unzip Extracts files from a zip archive.
uptodate Check modification dates on groups of files.
vbc Compiles Visual Basic.NET programs.
vjc Compiles Visual J# programs using vjc, Microsoft's J# compiler.
xmlpeek Extracts text from an XML file at the location specified by an XPath expression.
xmlpoke Replaces text in an XML file at the location specified by an XPath expression.
zip Creates a zip file from the specified filesets.
nant-0.92-rc1/doc/help/tasks/cvs-export.html0000644000175000017500000004114611757307541020663 0ustar jtaylorjtaylor <cvs-export> Task

<cvs-export>

[This is preliminary documentation and subject to change.]

Exports a cvs module in preperation for a release (i.e. the CVS version folders are not exported).

Parameters

Attribute Type Description Required
date datetime Specify the revision date to update to. The version of the file that existed at the date specified is retrieved. False
force-head bool Indicates whether the head revision should be used if the revison specified by revision or the date tags are not found. The default is false. False
no-shortening bool No shortening. Do not shorten module paths if -d specified. False
overridedir string Specify a directory name to replace the module name. Valid names include any valid filename, excluding path information. False
recursive bool If a directory is specified indicates whether sub-directories should also be processed. False
revision string Specify the revision to update the file to. This corresponds to the "sticky-tag" of the file. False
commandline string Command-line arguments for the program. The command line arguments are used to specify any cvs command options that are not available as attributes. These are appended after the command itself and are additive to whatever attributes are currently specified. False
compressionlevel int Compression level to use for all net traffic. This should be a value from 1-9.



NOTE: This is not available on sharpcvslib.
False
cvsfullpath file The full path to the cvs binary used. The cvs tasks will attempt to "guess" the location of your cvs binary based on your path. If the task is unable to resolve the location, or resolves it incorrectly this can be used to manually specify the path. False
cvsroot string

The cvs root variable has the following components:

[protocol]:[username]@[servername]:[server path]
  • protocol: ext, pserver, ssh (sharpcvslib); if you are not using sharpcvslib consult your cvs documentation.
  • username: [username]
  • servername: cvs.sourceforge.net
  • server path: /cvsroot/nant

False
cvsrsh file The executable to use for ssh communication. False
destination directory Destination directory for the local sandbox. If destination is not specified then the current directory is used. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
module string The module to perform an operation on. False
passfile file The full path to the cached password file. If not specified then the environment variables are used to try and locate the file. False
password string Deprecated. The password for logging in to the repository. False
quiet bool Indicates if the output from the cvs command should be supressed. The default is false. False
readonly bool true if the sandbox files should be checked out in read only mode. The default is false. False
readwrite bool true if the sandbox files should be checked out in read/write mode. The default is true. False
reallyquiet bool Indicates if the output from the cvs command should be stopped. The default is false. False
timeout int The maximum amount of time the application is allowed to execute, expressed in milliseconds. Defaults to no time-out. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
usesharpcvslib bool

true if the SharpCvsLib binaries that come bundled with NAnt should be used to perform the cvs commands, false otherwise.

You may also specify an override value for all cvs tasks instead of specifying a value for each. To do this set the property sourcecontrol.usesharpcvslib to false.

If you choose not to use SharpCvsLib to checkout from cvs you will need to include a cvs.exe binary in your path.
False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Framework-configurable parameters

Attribute Type Description Required
managed ManagedExecution Specifies whether the external program should be treated as a managed application, possibly forcing it to be executed under the currently targeted version of the CLR. False
useruntimeengine bool Deprecated. Specifies whether the external program is a managed application which should be executed using a runtime engine, if configured. The default is false. False

Nested Elements:

<fileset>

Used to specify the version control system (VCS) files that are going to be acted on.

</fileset>

<arg>

The command-line arguments for the external program.

Represents a command-line argument.

When passed to an external application, the argument will be quoted when appropriate. This does not apply to the line parameter, which is always passed as is.

Parameters

AttributeTypeDescriptionRequired
dirdirectory The value for a directory-based command-line argument; will be replaced with the absolute path of the directory. False
filefile The name of a file as a single command-line argument; will be replaced with the absolute filename of the file. False
ifbool Indicates if the argument should be passed to the external program. If true then the argument will be passed; otherwise, skipped. The default is true. False
linestring List of command-line arguments; will be passed to the executable as is. False
path<path> The value for a PATH-like command-line argument; you can use : or ; as path separators and NAnt will convert it to the platform's local conventions, while resolving references to environment variables. False
unlessbool Indicates if the argument should not be passed to the external program. If false then the argument will be passed; otherwise, skipped. The default is false. False
valuestring A single command-line argument; can contain space characters. False

Nested Elements:

<path>

Sets a single command-line argument and treats it like a PATH - ensures the right separator for the local platform is used.

</path>

Examples

  • A single command-line argument containing a space character.

    <arg value="-l -a" />
        
  • Two separate command-line arguments.

    <arg line="-l -a" />
        
  • A single command-line argument with the value \dir;\dir2;\dir3 on DOS-based systems and /dir:/dir2:/dir3 on Unix-like systems.

    <arg path="/dir;/dir2:\dir3" />
        

</arg>

Examples

  • Export the most recent NAnt sources from cvs.

    <cvs-export 
        destination="c:\src\nant\" 
        cvsroot=":pserver:anonymous@cvs.sourceforge.net:/cvsroot/nant"  
        module="nant" />
        
  • Export NAnt revision named your_favorite_revision_here to the folder c:\src\nant\replacement_for_module_directory_name. **NOTE**: filesets names for the export task must be prefixed with the module name. This is different than other tasks.

    <cvs-export 
        destination="c:\src\nant\" 
        cvsroot=":pserver:anonymous@cvs.sourceforge.net:/cvsroot/nant" 
        module="nant"
        revision="your_favorite_revision_here"
        overridedir="replacement_for_module_directory_name"
        recursive="false">
        <fileset>
            <include name="nant/bin/NAnt.exe"/>
            <include name="nant/bin/NAnt.exe.config"/>
        </fileset>
    </cvs-export>
        

Requirements

Assembly: NAnt.SourceControlTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/script.html0000644000175000017500000002653311757307512020056 0ustar jtaylorjtaylor <script> Task

<script>

[This is preliminary documentation and subject to change.]

Executes the code contained within the task.

Code

The <script> task must contain a single code element, which in turn contains the script code.

This code can include extensions such as functions, or tasks. Once the script task has executed those extensions will be available for use in the buildfile.

If no extensions have been defined, a static entry point named ScriptMain - which must have a single Project argument - is required.

Namespaces

The following namespaces are imported by default:

  • System
  • System.Collections
  • System.IO
  • System.Text
  • NAnt.Core
  • NAnt.Core.Attributes
Assembly References

The assembly references that are specified will be used to compile the script, and will be loaded into the NAnt appdomain.

By default, only the NAnt.Core and mscorlib assemblies are referenced.

Parameters

Attribute Type Description Required
language string The language of the script block. Possible values are "VB", "vb", "VISUALBASIC", "C#", "c#", "CSHARP". "JS", "js", "JSCRIPT" "VJS", "vjs", "JSHARP" or a fully-qualified name for a class implementing CodeDomProvider. True
mainclass string The name of the main class containing the static ScriptMain entry point. False
prefix string The namespace prefix for any custom functions defined in the script. If ommitted the prefix will default to 'script' False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Nested Elements:

<references>

Any required references.

</references>

<imports>

The namespaces to import.

</imports>

<code>

The code to execute.

Represents an element of which the XML is processed by its parent task or type.

</code>

Examples

  • Run C# code that writes a message to the build log.

          <script language="C#">
              <code>
                <![CDATA[
                  public static void ScriptMain(Project project) {
                      project.Log(Level.Info, "Hello World from a script task using C#");
                  }
                ]]>
              </code>
          </script>
    
  • Define a custom function and call it using C#.

          <script language="C#" prefix="test" >
              <code>
                <![CDATA[
                  [Function("test-func")]
                  public static string Testfunc(  ) {
                      return "some result !!!!!!!!";
                  }
                ]]>
              </code>
          </script>
          <echo message='${test::test-func()}'/>
    
  • Use a custom namespace in C# to create a database

          <script language="C#" >
              <references>
                  <include name="System.Data.dll" />
              </references>
              <imports>
                  <import namespace="System.Data.SqlClient" />
              </imports>
              <code>
                <![CDATA[
                  public static void ScriptMain(Project project) {
                      string dbUserName = "nant";
                      string dbPassword = "nant";
                      string dbServer = "(local)";
                      string dbDatabaseName = "NAntSample";
                      string connectionString = String.Format("Server={0};uid={1};pwd={2};", dbServer, dbUserName, dbPassword);
                      
                      SqlConnection connection = new SqlConnection(connectionString);
                      string createDbQuery = "CREATE DATABASE " + dbDatabaseName;
                      SqlCommand createDatabaseCommand = new SqlCommand(createDbQuery);
                      createDatabaseCommand.Connection = connection;
                      
                      connection.Open();
                      
                      try {
                          createDatabaseCommand.ExecuteNonQuery();
                          project.Log(Level.Info, "Database added successfully: " + dbDatabaseName);
                      } catch (Exception e) {
                          project.Log(Level.Error, e.ToString());
                      } finally {
                          connection.Close();
                      }
                  }
                ]]>
              </code>
          </script>
    
  • Run Visual Basic.NET code that writes a message to the build log.

          <script language="VB">
              <code>
                <![CDATA[
                  Public Shared Sub ScriptMain(project As Project)
                      project.Log(Level.Info, "Hello World from a script task using Visual Basic.NET")
                  End Sub
                ]]>
              </code>
          </script>
    
  • Define a custom task and call it using C#.

             <script language="C#" prefix="test" >
                 <code>
                   <![CDATA[
                     [TaskName("usertask")]
                     public class TestTask : Task {
                       #region Private Instance Fields
    
                       private string _message;
    
                       #endregion Private Instance Fields
    
                       #region Public Instance Properties
    
                       [TaskAttribute("message", Required=true)]
                       public string FileName {
                           get { return _message; }
                           set { _message = value; }
                       }
    
                       #endregion Public Instance Properties
    
                       #region Override implementation of Task
    
                       protected override void ExecuteTask() {
                           Log(Level.Info, _message.ToUpper());
                       }
                       #endregion Override implementation of Task
                     }
                   ]]>
                 </code>
             </script>
             <usertask message='Hello from UserTask'/>
       
  • Define a custom function and call it using Boo.

          <script language="Boo.CodeDom.BooCodeProvider, Boo.CodeDom, Version=1.0.0.0, Culture=neutral, PublicKeyToken=32c39770e9a21a67"
              failonerror="true">
              <code>
                <![CDATA[
                 
                  [Function("test-func")]
                  def MyFunc():
                      return "Hello from Boo !!!!!!"
                ]]>
              </code>
          </script>
          <echo message='${script::test-func()}'/>
    

Requirements

Assembly: NAnt.DotNetTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/copy.html0000644000175000017500000002317111757307433017521 0ustar jtaylorjtaylor <copy> Task

<copy>

[This is preliminary documentation and subject to change.]

Copies a file, a directory, or set of files to a new file or directory.

Files are only copied if the source file is newer than the destination file, or if the destination file does not exist. However, you can explicitly overwrite files with the overwrite attribute.

Entire directory structures can be copied to a new location. For this to happen, the following criteria must be met:

  • Everything in the fileset is included
  • The directory structure is not flattened
  • Empty directories are included
  • Destination directory does not exist

If any of these items are not met, then the files within the source directory will be copied over instead of the entire directory structure.

When a <fileset> is used to select files or directories to copy, the todir attribute must be set. Files that are located under the base directory of the <fileset> will be copied to a directory under the destination directory matching the path relative to the base directory of the <fileset>, unless the flatten attribute is set to true.

Files that are not located under the the base directory of the <fileset> will be copied directly under to the destination directory, regardless of the value of the flatten attribute.

Encoding

Unless an encoding is specified, the encoding associated with the system's current ANSI code page is used.

An UTF-8, little-endian Unicode, and big-endian Unicode encoded text file is automatically recognized, if the file starts with the appropriate byte order marks.

Note: If you employ filters in your copy operation, you should limit the copy to text files. Binary files will be corrupted by the copy operation.

Parameters

Attribute Type Description Required
file file The file to copy. False
flatten bool Ignore directory structure of source directory, copy all files into a single directory, specified by the todir attribute. The default is false. False
includeemptydirs bool Copy any empty directories included in the <fileset>. The default is true. False
inputencoding Encoding The encoding to use when reading files. The default is the system's current ANSI code page. False
outputencoding Encoding The encoding to use when writing the files. The default is the encoding of the input file. False
overwrite bool Overwrite existing files even if the destination files are newer. The default is false. False
todir directory The directory to copy to. False
tofile file The file to copy to. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Nested Elements:

<fileset>

Used to select the files to copy. To use a <fileset>, the todir attribute must be set.

</fileset>

<filterchain>

Chain of filters used to alter the file's content as it is copied.

</filterchain>

Examples

  • Copy a single file while changing its encoding from "latin1" to "utf-8".

    <copy 
        file="myfile.txt"
        tofile="mycopy.txt"
        inputencoding="latin1"
        outputencoding="utf-8" />
        
  • Copy a set of files to a new directory.

    <copy todir="${build.dir}">
        <fileset basedir="bin">
            <include name="*.dll" />
        </fileset>
    </copy>
        
  • Copy a set of files to a directory, replacing @TITLE@ with "Foo Bar" in all files.

    <copy todir="../backup/dir">
        <fileset basedir="src_dir">
            <include name="**/*" />
        </fileset>
        <filterchain>
            <replacetokens>
                <token key="TITLE" value="Foo Bar" />
            </replacetokens>
        </filterchain>
    </copy>
        
  • Copy an entire directory and its contents.

    <copy todir="target/dir">
      <fileset basedir="source/dir"/>
    </copy>
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/ilasm.html0000644000175000017500000003134311757307503017652 0ustar jtaylorjtaylor <ilasm> Task

<ilasm>

[This is preliminary documentation and subject to change.]

Compiles ILASM programs.

Parameters

Attribute Type Description Required
output file Specifies the name of the output file created by the compiler. True
target string Specifies which output type should be generated. True
alignment int Instructs the compiler to set the FileAlignment value in the PE header. False
base int Instructs the compiler to set the ImageBase value in the PE header. False
clock bool Specifies whether or not the compiler should measure and report the compilation times. False
debug bool Specifies whether or not the compiler should generate debug information. False
error bool Specifies whether or not the compiler should attempt to create a PE file even if compilation errors have been reported. False
flags int Instructs the compiler to set the Flags value in the CLR header. False
keyfile file Instructs the compiler to generate a strong signature of the PE file. False
keysource string Instructs the compiler to generate a strong signature of the PE file. False
listing bool Specifies whether or not the compiler should type a formatted listing of the compilation result. False
rebuild bool Instructs NAnt to recompile the output file regardless of the file timestamps. False
resourcefile file Instructs the compiler to link the specified unmanaged resource file into the resulting PE file. False
subsystem int Instructs the compiler to set the Subsystem value in the PE header. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
timeout int The maximum amount of time the application is allowed to execute, expressed in milliseconds. Defaults to no time-out. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Framework-configurable parameters

Attribute Type Description Required
exename string The name of the executable that should be used to launch the external program. False
managed ManagedExecution Specifies whether the external program should be treated as a managed application, possibly forcing it to be executed under the currently targeted version of the CLR. False
useruntimeengine bool Deprecated. Specifies whether the external program is a managed application which should be executed using a runtime engine, if configured. The default is false. False

Nested Elements:

<sources>

Specifies the set of source files to compile.

</sources>

<arg>

The command-line arguments for the external program.

Represents a command-line argument.

When passed to an external application, the argument will be quoted when appropriate. This does not apply to the line parameter, which is always passed as is.

Parameters

AttributeTypeDescriptionRequired
dirdirectory The value for a directory-based command-line argument; will be replaced with the absolute path of the directory. False
filefile The name of a file as a single command-line argument; will be replaced with the absolute filename of the file. False
ifbool Indicates if the argument should be passed to the external program. If true then the argument will be passed; otherwise, skipped. The default is true. False
linestring List of command-line arguments; will be passed to the executable as is. False
path<path> The value for a PATH-like command-line argument; you can use : or ; as path separators and NAnt will convert it to the platform's local conventions, while resolving references to environment variables. False
unlessbool Indicates if the argument should not be passed to the external program. If false then the argument will be passed; otherwise, skipped. The default is false. False
valuestring A single command-line argument; can contain space characters. False

Nested Elements:

<path>

Sets a single command-line argument and treats it like a PATH - ensures the right separator for the local platform is used.

</path>

Examples

  • A single command-line argument containing a space character.

    <arg value="-l -a" />
        
  • Two separate command-line arguments.

    <arg line="-l -a" />
        
  • A single command-line argument with the value \dir;\dir2;\dir3 on DOS-based systems and /dir:/dir2:/dir3 on Unix-like systems.

    <arg path="/dir;/dir2:\dir3" />
        

</arg>

Examples

  • Compiles helloworld.il to helloworld.exe.

    <ilasm target="exe" output="helloworld.exe" debug="true">
        <sources>
            <include name="helloworld.il" />
        </sources>
    </ilasm>
        

Requirements

Assembly: NAnt.DotNetTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/sleep.html0000644000175000017500000001037611757307452017663 0ustar jtaylorjtaylor <sleep> Task

<sleep>

[This is preliminary documentation and subject to change.]

A task for sleeping a specified period of time, useful when a build or deployment process requires an interval between tasks.

Parameters

Attribute Type Description Required
hours int Hours to add to the sleep time. False
milliseconds int Milliseconds to add to the sleep time. False
minutes int Minutes to add to the sleep time. False
seconds int Seconds to add to the sleep time. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Examples

  • Sleep 1 hour, 2 minutes, 3 seconds and 4 milliseconds.

    <sleep hours="1" minutes="2" seconds="3" milliseconds="4" />
        
  • Sleep 123 milliseconds.

    <sleep milliseconds="123" />
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/regsvcs.html0000644000175000017500000003075611757307510020226 0ustar jtaylorjtaylor <regsvcs> Task

<regsvcs>

[This is preliminary documentation and subject to change.]

Installs or removes .NET Services.

This tasks provides the same functionality as the regsvcs tool provided in the .NET SDK.

It performs the following actions:

  • Loads and registers an assembly.
  • Generates, registers, and installs a type library into a specified COM+ application.
  • Configures services that are added programmatically to your class.

Refer to the .NET Services Installation Tool (Regsvcs.exe) for more information.

Parameters

Attribute Type Description Required
assembly file The source assembly file. True
action ActionType Defines the action to take with the assembly. The default is FindOrCreate. False
application string Specifies the name of the COM+ application to either find or create. False
componentsonly bool Configures components only; ignores methods and interfaces. The default is false. False
existingapp bool Expect an existing application. The default is false. False
existingtlb bool Uses an existing type library. The default is false. False
noreconfig bool Do not reconfigure an existing target application. The default is false. False
partition string Specifies the name or id of the COM+ application to either find or create. False
tlb file Specifies the type library file to install. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
timeout int The maximum amount of time the application is allowed to execute, expressed in milliseconds. Defaults to no time-out. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Framework-configurable parameters

Attribute Type Description Required
exename string The name of the executable that should be used to launch the external program. False
managed ManagedExecution Specifies whether the external program should be treated as a managed application, possibly forcing it to be executed under the currently targeted version of the CLR. False
useruntimeengine bool Deprecated. Specifies whether the external program is a managed application which should be executed using a runtime engine, if configured. The default is false. False

Nested Elements:

<arg>

The command-line arguments for the external program.

Represents a command-line argument.

When passed to an external application, the argument will be quoted when appropriate. This does not apply to the line parameter, which is always passed as is.

Parameters

AttributeTypeDescriptionRequired
dirdirectory The value for a directory-based command-line argument; will be replaced with the absolute path of the directory. False
filefile The name of a file as a single command-line argument; will be replaced with the absolute filename of the file. False
ifbool Indicates if the argument should be passed to the external program. If true then the argument will be passed; otherwise, skipped. The default is true. False
linestring List of command-line arguments; will be passed to the executable as is. False
path<path> The value for a PATH-like command-line argument; you can use : or ; as path separators and NAnt will convert it to the platform's local conventions, while resolving references to environment variables. False
unlessbool Indicates if the argument should not be passed to the external program. If false then the argument will be passed; otherwise, skipped. The default is false. False
valuestring A single command-line argument; can contain space characters. False

Nested Elements:

<path>

Sets a single command-line argument and treats it like a PATH - ensures the right separator for the local platform is used.

</path>

Examples

  • A single command-line argument containing a space character.

    <arg value="-l -a" />
        
  • Two separate command-line arguments.

    <arg line="-l -a" />
        
  • A single command-line argument with the value \dir;\dir2;\dir3 on DOS-based systems and /dir:/dir2:/dir3 on Unix-like systems.

    <arg path="/dir;/dir2:\dir3" />
        

</arg>

Examples

  • Adds all public classes contained in myTest.dll to a COM+ application and produces the myTest.tlb type library. If the application already exists, it is overwritten.

    <regsvcs action="FindOrCreate" assembly="myTest.dll" />
        
  • Adds all public classes contained in myTest.dll to myTargetApp and produces the myTest.tlb type library. If the application already exists, it is overwritten.

    <regsvcs action="FindOrCreate" assembly="myTest.dll" application="myTargetApp" />
        
  • Adds all public classes contained in myTest.dll to a COM+ application and produces the myTest.tlb type library. A new application is always created.

    <regsvcs action="Create" assembly="myTest.dll" />
        
  • Uninstalls the COM+ application contained in myTest.dll.

    <regsvcs action="Uninstall" assembly="myTest.dll" />
        

Requirements

Assembly: NAnt.DotNetTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/al.html0000644000175000017500000004130711757307471017146 0ustar jtaylorjtaylor <al> Task

<al>

[This is preliminary documentation and subject to change.]

Wraps al.exe, the assembly linker for the .NET Framework.

All specified sources will be embedded using the /embed flag. Other source types are not supported.

Parameters

Attribute Type Description Required
output file The name of the output file for the assembly manifest. True
target string The target type (one of lib, exe, or winexe). True
algid string Specifies an algorithm (in hexadecimal) to hash all files in a multifile assembly except the file that contains the assembly manifest. The default algorithm is CALG_SHA1. False
company string Specifies a string for the Company field in the assembly. False
configuration string Specifies a string for the Configuration field in the assembly. False
copyright string Specifies a string for the Copyright field in the assembly. False
culture string The culture string associated with the output assembly. The string must be in RFC 1766 format, such as "en-US". False
delaysign DelaySign Specifies whether the assembly should be partially signed. The default is NAnt.DotNet.Types.DelaySign.NotSet. False
description string Specifies a string for the Description field in the assembly. False
evidence file Security evidence file to embed. False
fileversion string Specifies a string for the File Version field in the assembly. False
flags string Specifies a value (in hexadecimal) for the Flags field in the assembly. False
keycontainer string Specifies a container that holds a key pair. False
keyfile file Specifies a file (filename) that contains a key pair or just a public key to sign an assembly. False
main string Specifies the fully-qualified name (class.method) of the method to use as an entry point when converting a module to an executable file. False
product string Specifies a string for the Product field in the assembly. False
productversion string Specifies a string for the Product Version field in the assembly. False
template file Specifies an assembly from which to get all options except the culture field. False
title string Specifies a string for the Title field in the assembly. False
trademark string Specifies a string for the Trademark field in the assembly. False
version string Specifies version information for the assembly. The format of the version string is major.minor.build.revision. False
win32icon file Icon to associate with the assembly. False
win32res file Inserts a Win32 resource (.res file) in the output file. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
timeout int The maximum amount of time the application is allowed to execute, expressed in milliseconds. Defaults to no time-out. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Framework-configurable parameters

Attribute Type Description Required
exename string The name of the executable that should be used to launch the external program. False
managed ManagedExecution Specifies whether the external program should be treated as a managed application, possibly forcing it to be executed under the currently targeted version of the CLR. False
supportstemplate bool Indicates whether the assembly linker for a given target framework supports the "template" option, which takes an assembly from which to get all options except the culture field. The default is true. False
useruntimeengine bool Deprecated. Specifies whether the external program is a managed application which should be executed using a runtime engine, if configured. The default is false. False

Nested Elements:

<modules>

One or more modules to be compiled into an assembly.

</modules>

<sources>

The set of resources to embed.

</sources>

<arg>

The command-line arguments for the external program.

Represents a command-line argument.

When passed to an external application, the argument will be quoted when appropriate. This does not apply to the line parameter, which is always passed as is.

Parameters

AttributeTypeDescriptionRequired
dirdirectory The value for a directory-based command-line argument; will be replaced with the absolute path of the directory. False
filefile The name of a file as a single command-line argument; will be replaced with the absolute filename of the file. False
ifbool Indicates if the argument should be passed to the external program. If true then the argument will be passed; otherwise, skipped. The default is true. False
linestring List of command-line arguments; will be passed to the executable as is. False
path<path> The value for a PATH-like command-line argument; you can use : or ; as path separators and NAnt will convert it to the platform's local conventions, while resolving references to environment variables. False
unlessbool Indicates if the argument should not be passed to the external program. If false then the argument will be passed; otherwise, skipped. The default is false. False
valuestring A single command-line argument; can contain space characters. False

Nested Elements:

<path>

Sets a single command-line argument and treats it like a PATH - ensures the right separator for the local platform is used.

</path>

Examples

  • A single command-line argument containing a space character.

    <arg value="-l -a" />
        
  • Two separate command-line arguments.

    <arg line="-l -a" />
        
  • A single command-line argument with the value \dir;\dir2;\dir3 on DOS-based systems and /dir:/dir2:/dir3 on Unix-like systems.

    <arg path="/dir;/dir2:\dir3" />
        

</arg>

Examples

  • Create a library containing all icon files in the current directory.

    <al output="MyIcons.dll" target="lib">
        <sources>
            <include name="*.ico" />
        </sources>
    </al>
        
  • Create an executable assembly manifest from modules.

    <al output="Client.exe" target="exe" main="Program.Main">
        <modules>
            <include name="Client.netmodule" />
            <include name="Common.netmodule" />
        </modules>
    </al>
        

Requirements

Assembly: NAnt.DotNetTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/link.html0000644000175000017500000003375411757307553017517 0ustar jtaylorjtaylor <link> Task

<link>

[This is preliminary documentation and subject to change.]

Links files using link.exe, Microsoft's Incremental Linker.

This task is intended for version 7.00.9466 of link.exe.

Parameters

Attribute Type Description Required
output file The output file. True
moduledefinition file The name of a module-definition file (.def) to be passed to the linker. False
options string Options to pass to the compiler. False
pdbfile file A user-specified name for the program database (PDB) that the linker creates. The default file name for the PDB has the base name of the output and the extension .pdb. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
timeout int The maximum amount of time the application is allowed to execute, expressed in milliseconds. Defaults to no time-out. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Framework-configurable parameters

Attribute Type Description Required
exename string The name of the executable that should be used to launch the external program. False
managed ManagedExecution Specifies whether the external program should be treated as a managed application, possibly forcing it to be executed under the currently targeted version of the CLR. False
useruntimeengine bool Deprecated. Specifies whether the external program is a managed application which should be executed using a runtime engine, if configured. The default is false. False

Nested Elements:

<delayloaded>

Specified DLLs for delay loading.

</delayloaded>

<sources>

The list of files to combine into the output file.

</sources>

<libdirs>

The list of additional library directories to search.

</libdirs>

<modules>

Link the specified modules into this assembly.

</modules>

<embeddedresources>

Embed the specified resources into this assembly.

</embeddedresources>

<symbols>

Symbols to add to the symbol table.
<symbol>

Represents a symbol.

Parameters

AttributeTypeDescriptionRequired
namestring The name of the symbol. True
ifbool If true then the element will be processed; otherwise, skipped. The default is true. False
unlessbool If true then the element will be skipped; otherwise, processed. The default is false. False
</symbol>

</symbols>

<ignorelibraries>

Names of libraries that you want the linker to ignore when it resolves external references.
<library>

Represents a library.

Parameters

AttributeTypeDescriptionRequired
namestring The name of the library. True
ifbool If true then the element will be processed; otherwise, skipped. The default is true. False
unlessbool If true then the element will be skipped; otherwise, processed. The default is false. False
</library>

</ignorelibraries>

<arg>

The command-line arguments for the external program.

Represents a command-line argument.

When passed to an external application, the argument will be quoted when appropriate. This does not apply to the line parameter, which is always passed as is.

Parameters

AttributeTypeDescriptionRequired
dirdirectory The value for a directory-based command-line argument; will be replaced with the absolute path of the directory. False
filefile The name of a file as a single command-line argument; will be replaced with the absolute filename of the file. False
ifbool Indicates if the argument should be passed to the external program. If true then the argument will be passed; otherwise, skipped. The default is true. False
linestring List of command-line arguments; will be passed to the executable as is. False
path<path> The value for a PATH-like command-line argument; you can use : or ; as path separators and NAnt will convert it to the platform's local conventions, while resolving references to environment variables. False
unlessbool Indicates if the argument should not be passed to the external program. If false then the argument will be passed; otherwise, skipped. The default is false. False
valuestring A single command-line argument; can contain space characters. False

Nested Elements:

<path>

Sets a single command-line argument and treats it like a PATH - ensures the right separator for the local platform is used.

</path>

Examples

  • A single command-line argument containing a space character.

    <arg value="-l -a" />
        
  • Two separate command-line arguments.

    <arg line="-l -a" />
        
  • A single command-line argument with the value \dir;\dir2;\dir3 on DOS-based systems and /dir:/dir2:/dir3 on Unix-like systems.

    <arg path="/dir;/dir2:\dir3" />
        

</arg>

Examples

  • Combine all object files in the current directory into helloworld.exe.

    <link output="helloworld.exe">
        <sources>
            <include name="*.obj" />
        </sources>
    </link>
        

Requirements

Assembly: NAnt.VisualCppTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/solution.html0000644000175000017500000004044311757307560020425 0ustar jtaylorjtaylor <solution> Task

<solution>

[This is preliminary documentation and subject to change.]

Compiles VS.NET solutions (or sets of projects), automatically determining project dependencies from inter-project references.

This task support the following projects:

  • Visual Basic .NET
  • Visual C# .NET
  • Visual J# .NET
  • Visual C++ .NET

Note: Right now, only Microsoft Visual Studio .NET 2002 and 2003 solutions and projects are supported. Support for .NET Compact Framework projects is also not available at this time.

The <solution> task also supports the model of referencing projects by their output filenames, rather than referencing them inside the solution. It will automatically detect the existance of a file reference and convert it to a project reference. For example, if project "A" references the file in the release output directory of project "B", the <solution> task will automatically convert this to a project dependency on project "B" and will reference the appropriate configuration output directory at the final build time (ie: reference the debug version of "B" if the solution is built as debug).

Note: The <solution> task expects all project files to be valid XML files.

Resx Files

When building a project for a down-level target framework, special care should be given to resx files. Resx files (can) contain references to a specific version of CLR types, and as such are only upward compatible.

For example: if you want to be able to build a project both as a .NET 1.0 and .NET 1.1 assembly, the resx files should only contain references to .NET 1.0 CLR types. Failure to do this may result in a InvalidCastException failure at runtime on machines with only the .NET Framework 1.0 installed.

Parameters

Attribute Type Description Required
configuration string The name of the solution configuration to build. True
enablewebdav bool Allow the task to use WebDAV for retrieving/compiling the projects within solution. Use of WebMap is preferred over WebDAV. The default is false. False
includevsfolders bool Includes Visual Studio search folders in reference search path. The default is true. False
outputdir directory The directory where compiled targets will be placed. This overrides path settings contained in the solution/project. False
platform string The name of platform to build the solution for. False
solutionfile file The name of the VS.NET solution file to build. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Nested Elements:

<projects>

The projects to build.

</projects>

<referenceprojects>

The projects to scan, but not build.

</referenceprojects>

<webmap>

WebMap of URL's to project references.
<map>

Represents a single mapping from URL project path to physical project path.

Parameters

AttributeTypeDescriptionRequired
pathfile Specifies the actual path to the project file, or the path fragment to replace. True
urlstring Specifies the URL of the project file, or a URL fragment to match. True
casesensitivebool Specifies whether the mapping is case-sensitive or not. False
ifbool Indicates if the URL of the project file should be mapped. False
unlessbool Indicates if the URL of the project file should not be mapped. False
</map>

</webmap>

<excludeprojects>

Fileset of projects to exclude.

</excludeprojects>

<assemblyfolders>

Set of folders where references are searched when not found in path from project file (HintPath).

</assemblyfolders>

<property>

Set of properties set at solution level. Builders for projects in solution may or may not use them.

Sets a property in the current project.

Note: NAnt uses a number of predefined properties.

Parameters

AttributeTypeDescriptionRequired
namestring The name of the NAnt property to set. True
valuestring The value to assign to the NAnt property.

This attribute's properties will not be automatically expanded!

True
dynamicbool Specifies whether references to other properties should not be expanded when the value of the property is set, but expanded when the property is actually used. By default, properties will be expanded when set. False
overwritebool Specifies whether the value of a property should be overwritten if the property already exists (unless the property is read-only). The default is true. False
readonlybool Specifies whether the property is read-only or not. The default is false. False
failonerrorbool Determines if task failure stops the build, or is just reported. The default is true. False
ifbool If true then the task will be executed; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbosebool Determines whether the task should report detailed build log messages. The default is false. False

Examples

  • Define a debug property with value true.

    <property name="debug" value="true" />
        
  • Use the user-defined debug property.

    <property name="trace" value="${debug}" />
        
  • Define a read-only property. This is just like passing in the param on the command line.

    <property name="do_not_touch_ME" value="hammer" readonly="true" />
        
  • Define a property, but do not overwrite the value if the property already exists (eg. it was specified on the command line).

    <project name="property-example">
      <property name="debug" value="true" overwrite="false" />
      <echo message="debug: ${debug}" />
    </project>
        

    Executing this build file with the command line option -D:debug=false, would cause the value specified on the command line to remain unaltered.

    [echo] debug: false
        

</property>

Examples

  • Compiles all of the projects in test.sln, in release mode, in the proper order.

    <solution configuration="release" solutionfile="test.sln" />
        
  • Compiles all of the projects in projects.txt, in the proper order.

    <solution configuration="release">
        <projects>
            <includesfile name="projects.txt" />
       </projects>
    </solution>
        
  • Compiles projects A, B and C, using the output of project X as a reference.

    <solution configuration="release">
        <projects>
            <include name="A\A.csproj" />
            <include name="B\b.vbproj" />
            <include name="C\c.csproj" />
        </projects>
        <referenceprojects>
            <include name="X\x.csproj" />
        </referenceprojects>
    </solution>
        
  • Compiles all of the projects in the solution except for project A.

    <solution solutionfile="test.sln" configuration="release">
        <excludeprojects>
            <include name="A\A.csproj" />
        </excludeprojects>
    </solution>
        
  • Compiles all of the projects in the solution mapping the specific project at http://localhost/A/A.csproj to c:\inetpub\wwwroot\A\A.csproj and any URLs under http://localhost/B/[remainder] to c:\other\B\[remainder]. This allows the build to work without WebDAV.

    <solution solutionfile="test.sln" configuration="release">
        <webmap>
            <map url="http://localhost/A/A.csproj" path="c:\inetpub\wwwroot\A\A.csproj" />
            <map url="http://localhost/B" path="c:\other\B" />
        </webmap>
    </solution>
        
  • Compiles all of the projects in the solution placing compiled outputs in c:\temp.

    <solution solutionfile="test.sln" configuration="release" outputdir="c:\temp" />
        

Requirements

Assembly: NAnt.VSNetTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/description.html0000644000175000017500000000617511757307434021100 0ustar jtaylorjtaylor <description> Task

<description>

[This is preliminary documentation and subject to change.]

An empty task that allows a build file to contain a description.

Parameters

Attribute Type Description Required
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Examples

  • Set a description.

    <description>This is a description.</description>
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/tlbexp.html0000644000175000017500000002272211757307563020052 0ustar jtaylorjtaylor <tlbexp> Task

<tlbexp>

[This is preliminary documentation and subject to change.]

Exports a .NET assembly to a type library that can be used from unmanaged code (wraps Microsoft's tlbexp.exe).

See the Microsoft.NET Framework SDK documentation for details.

Parameters

Attribute Type Description Required
assembly file Specifies the assembly for which to export a type library. True
output file Specifies the name of the type library file to generate. True
names file Specifies the file used to determine capitalization of names in a type library. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
timeout int The maximum amount of time the application is allowed to execute, expressed in milliseconds. Defaults to no time-out. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Framework-configurable parameters

Attribute Type Description Required
exename string The name of the executable that should be used to launch the external program. False
managed ManagedExecution Specifies whether the external program should be treated as a managed application, possibly forcing it to be executed under the currently targeted version of the CLR. False
useruntimeengine bool Deprecated. Specifies whether the external program is a managed application which should be executed using a runtime engine, if configured. The default is false. False

Nested Elements:

<arg>

The command-line arguments for the external program.

Represents a command-line argument.

When passed to an external application, the argument will be quoted when appropriate. This does not apply to the line parameter, which is always passed as is.

Parameters

AttributeTypeDescriptionRequired
dirdirectory The value for a directory-based command-line argument; will be replaced with the absolute path of the directory. False
filefile The name of a file as a single command-line argument; will be replaced with the absolute filename of the file. False
ifbool Indicates if the argument should be passed to the external program. If true then the argument will be passed; otherwise, skipped. The default is true. False
linestring List of command-line arguments; will be passed to the executable as is. False
path<path> The value for a PATH-like command-line argument; you can use : or ; as path separators and NAnt will convert it to the platform's local conventions, while resolving references to environment variables. False
unlessbool Indicates if the argument should not be passed to the external program. If false then the argument will be passed; otherwise, skipped. The default is false. False
valuestring A single command-line argument; can contain space characters. False

Nested Elements:

<path>

Sets a single command-line argument and treats it like a PATH - ensures the right separator for the local platform is used.

</path>

Examples

  • A single command-line argument containing a space character.

    <arg value="-l -a" />
        
  • Two separate command-line arguments.

    <arg line="-l -a" />
        
  • A single command-line argument with the value \dir;\dir2;\dir3 on DOS-based systems and /dir:/dir2:/dir3 on Unix-like systems.

    <arg path="/dir;/dir2:\dir3" />
        

</arg>

Examples

  • Export DotNetAssembly.dll to LegacyCOM.dll.

    <tlbexp assembly="DotNetAssembly.dll" output="LegacyCOM.dll" />
        

Requirements

Assembly: NAnt.Win32Tasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/available.html0000644000175000017500000001505311757307431020465 0ustar jtaylorjtaylor <available> Task

<available>

[This is preliminary documentation and subject to change.]

(Deprecated)

Checks if a resource is available at runtime.

The specified property is set to true if the requested resource is available at runtime, and false if the resource is not available.

Note: we advise you to use the following functions instead:

Function Description
file::exists() Determines whether the specified file exists.
directory::exists() Determines whether the given path refers to an existing directory on disk.
framework::exists() Checks whether the specified framework exists..
framework::sdk-exists() Checks whether the SDK for the specified framework is installed.

Parameters

Attribute Type Description Required
property string The property that must be set if the resource is available. True
resource string The resource which must be available. True
type ResourceType The type of resource which must be present. True
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Examples

  • Sets the myfile.present property to true if the file is available on the filesystem and false if the file is not available.

    <available type="File" resource="myfile.txt" property="myfile.present" />
        
  • Sets the build.dir.present property to true if the directory is available on the filesystem and false if the directory is not available.

    <available type="Directory" resource="build" property="build.dir.present" />
        
  • Sets the mono-0.21.framework.present property to true if the Mono 0.21 framework is available on the current system and false if the framework is not available.

    <available type="Framework" resource="mono-0.21" property="mono-0.21.framework.present" />
        
  • Sets the net-1.1.frameworksdk.present property to true if the .NET 1.1 Framework SDK is available on the current system and false if the SDK is not available.

    <available type="FrameworkSDK" resource="net-1.1" property="net-1.1.frameworksdk.present" />
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/style.html0000644000175000017500000002514611757307453017715 0ustar jtaylorjtaylor <style> Task

<style>

[This is preliminary documentation and subject to change.]

Processes a document via XSLT.

Parameters

Attribute Type Description Required
style Uri URI or path that points to the stylesheet to use. If given as path, it can be relative to the project's basedir or absolute. True
destdir directory Directory in which to store the results. The default is the project base directory. False
extension string Desired file extension to be used for the targets. The default is html. False
in file Specifies a single XML document to be styled. Should be used with the out attribute. False
out file Specifies the output name for the styled result from the in attribute. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Nested Elements:

<infiles>

Specifies a group of input files to which to apply the stylesheet.

</infiles>

<parameters>

XSLT parameters to be passed to the XSLT transformation.
<parameter>

Represents an XSLT parameter.

Parameters

AttributeTypeDescriptionRequired
namestring The name of the XSLT parameter. True
valuestring The value of the XSLT parameter. True
ifbool Indicates if the parameter should be added to the XSLT argument list. If true then the parameter will be added; otherwise, skipped. The default is true. False
namespaceuristring The namespace URI to associate with the parameter. False
unlessbool Indicates if the parameter should not be added to the XSLT argument list. If false then the parameter will be added; otherwise, skipped. The default is false. False
</parameter>

</parameters>

<extensionobjects>

XSLT extension objects to be passed to the XSLT transformation.
<extensionobject>

Represents an XSLT extension object. The object should have a default parameterless constructor and the return value should be one of the four basic XPath data types of number, string, Boolean or node set.

Parameters

AttributeTypeDescriptionRequired
assemblyfile The assembly which contains the XSLT extension object. True
typenamestring The full type name of the XSLT extension object. True
ifbool Indicates if the extension object should be added to the XSLT argument list. If true then the extension object will be added; otherwise, skipped. The default is true. False
namespaceuristring The namespace URI to associate with the extension object. False
unlessbool Indicates if the extension object should not be added to the XSLT argument list. If false then the extension object will be added; otherwise, skipped. The default is false. False
</extensionobject>

</extensionobjects>

<proxy>

The network proxy to use to access the Internet resource.

</proxy>

Examples

  • Create a report in HTML.

    <style style="report.xsl" in="data.xml" out="report.html" />
        
  • Create a report in HTML, with a param.

    <style style="report.xsl" in="data.xml" out="report.html">
        <parameters>
            <parameter name="reportType" namespaceuri="" value="Plain" />
        </parameters>
    </style>
        
  • Create a report in HTML, with a expanded param.

    <style style="report.xsl" in="data.xml" out="report.html">
        <parameters>
            <parameter name="reportType" namespaceuri="" value="${report.type}" />
        </parameters>
    </style>
        
  • Create some code based on a directory of templates.

    <style style="CodeGenerator.xsl" extension="java">
        <infiles>
            <include name="*.xml" />
        </infiles>
        <parameters>
            <parameter name="reportType" namespaceuri="" value="Plain" if="${report.plain}" />
        </parameters>
    <style>
        
  • Create a report in HTML, with an extension object.

    <style style="report.xsl" in="data.xml" out="report.html">
        <extensionobjects>
            <extensionobject namespaceuri="urn:Formatter" typename="XsltExtensionObjects.Formatter" assembly="XsltExtensionObjects.dll" />
        </extensionobjects>
    </style>
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/touch.html0000644000175000017500000001131411757307454017670 0ustar jtaylorjtaylor <touch> Task

<touch>

[This is preliminary documentation and subject to change.]

Touches a file or set of files -- corresponds to the Unix touch command.

If the file specified does not exist, the task will create it.

Parameters

Attribute Type Description Required
datetime datetime Specifies the new modification time of the file in the format MM/DD/YYYY HH:MM:SS. False
file file The file to touch. False
millis long Specifies the new modification time of the file(s) in milliseconds since midnight Jan 1 1970. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Nested Elements:

<fileset>

Used to select files that should be touched.

</fileset>

Examples

  • Touch the Main.cs file. The current time is used.

    <touch file="Main.cs" />
        
  • Touch all executable files in the project base directory and its subdirectories.

    <touch>
        <fileset>
            <include name="**/*.exe" />
            <include name="**/*.dll" />
        </fileset>
    </touch>
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/sysinfo.html0000644000175000017500000001746411757307454020254 0ustar jtaylorjtaylor <sysinfo> Task

<sysinfo>

[This is preliminary documentation and subject to change.]

Sets properties with system information.

Sets a number of properties with information about the system environment. The intent of this task is for nightly build logs to have a record of system information so that the build was performed on.

Property Value
<prefix>.clr.version Common Language Runtime version number.
<prefix>.env.* Environment variables (e.g., <prefix>.env.PATH).
<prefix>.os.platform Operating system platform ID.
<prefix>.os.version Operating system version.
<prefix>.os Operating system version string.
<prefix>.os.folder.applicationdata The directory that serves as a common repository for application-specific data for the current roaming user.
<prefix>.os.folder.commonapplicationdata The directory that serves as a common repository for application-specific data that is used by all users.
<prefix>.os.folder.commonprogramfiles The directory for components that are shared across applications.
<prefix>.os.folder.desktopdirectory The directory used to physically store file objects on the desktop. Do not confuse this directory with the desktop folder itself, which is a virtual folder.
<prefix>.os.folder.programfiles The Program Files directory.
<prefix>.os.folder.system The System directory.
<prefix>.os.folder.temp The temporary directory.

When the name of an environment variable is not a valid property name, the task will fail. In that case, set failonerror to true to allow that environment variable to be skipped.

Note: we advise you to use the following functions instead:

Function Description
environment::get-operating-system() Gets a OperatingSystem object that identifies this operating system.
environment::get-folder-path() Gets the path to a system special folder.
environment::get-variable() Returns the value of a environment variable.
path::get-temp-path() Gets the path to the temporary directory.
environment::get-version() Gets the Common Language Runtime version.

Parameters

Attribute Type Description Required
prefix string The string to prefix the property names with. The default is "sys.". False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Examples

  • Register the properties with the default property prefix.

    <sysinfo />
        
  • Register the properties without a prefix.

    <sysinfo prefix="" />
        
  • Register properties and display a summary.

    <sysinfo verbose="true" />
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/nunit2.html0000644000175000017500000001453011757307526017770 0ustar jtaylorjtaylor <nunit2> Task

<nunit2>

[This is preliminary documentation and subject to change.]

Runs tests using the NUnit V2.6 framework.

The haltonfailure attribute is only useful when more than one test suite is used, and you want to continue running other test suites although a test failed.

Set failonerror to false to ignore any errors and continue the build.

In order to run a test assembly built with NUnit 2.0 or 2.1 using <nunit2> task, you must add the following node to your test config file :

<configuration>
    ...
    <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="nunit.framework" publicKeyToken="96d09a1eb7f44a77" culture="Neutral" /> 
                <bindingRedirect oldVersion="2.0.6.0" newVersion="2.2.8.0" /> 
                <bindingRedirect oldVersion="2.1.4.0" newVersion="2.2.8.0" /> 
            </dependentAssembly>
        </assemblyBinding>
    </runtime>
    ...
</configuration>
    

See the NUnit home page for more information.

Parameters

Attribute Type Description Required
haltonfailure bool Stop the test run if a test fails. The default is false. False
labels bool Indicate whether or not to label the text output as the tests run. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Nested Elements:

<test>

Tests to run.

</test>

<formatter>

Formatters to output results of unit tests.

</formatter>

Examples

  • Run tests in the MyProject.Tests.dll assembly.

    <nunit2>
        <formatter type="Plain" />
        <test assemblyname="MyProject.Tests.dll" appconfig="MyProject.Tests.dll.config" />
    </nunit2>
        
  • Only run tests that are not known to fail in files listed in the tests.txt file.

    <nunit2>
        <formatter type="Xml" usefile="true" extension=".xml" outputdir="${build.dir}/results" />
        <test>
            <assemblies>
                <includesfile name="tests.txt" />
            </assemblies>
            <categories>
                <exclude name="NotWorking" />
            </categories>
            <references basedir="build">
                <include name="Cegeka.Income.Services.dll" />
                <include name="Cegeka.Util.dll" />
            </references>
        </test>
    </nunit2>
        

Requirements

Assembly: NAnt.NUnit2Tasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/vjc.html0000644000175000017500000004667611757307521017346 0ustar jtaylorjtaylor <vjc> Task

<vjc>

[This is preliminary documentation and subject to change.]

Compiles Visual J# programs using vjc, Microsoft's J# compiler.

Note: In order to have <vjc> task generate manifest resource names that match those generated by Microsoft Visual Studio.NET, the value of the prefix attribute of the <resources> element should match the "Default Package" of the J#.NET project, and the value of the dynamicprefix attribute should be set to "true".

Parameters

Attribute Type Description Required
codepage string Specifies the code page to use for all source code files in the compilation. False
debug DebugOutput Specifies the type of debugging information generated by the compiler. The default is None. False
jcpa string Associate Java-language/COM package names. False
libpath string Specifies the location of assemblies referenced by way of the /reference flag. False
securescoping bool Specifies whether package-scoped members are accessible outside of the assembly. In other words, package scope is treated as assembly scope when emitting metadata. The default is false. False
warninglevel string Specifies the warning level for the compiler to display. Valid values are 0-4. The default is 4. False
x string Specifies whether to disable language extensions. False
output file The output file created by the compiler. True
target string Output type. Possible values are exe, winexe, library or module. True
define string Define conditional compilation symbol(s). False
delaysign DelaySign Specifies whether to delay sign the assembly using only the public portion of the strong name key. The default is NotSet. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
keycontainer string Specifies the key pair container used to strongname the assembly. False
keyfile file Specifies a strong name key file. False
main string Specifies which type contains the Main method that you want to use as the entry point into the program. False
nowarn string Deprecated. Specifies a comma-separated list of warnings that should be suppressed by the compiler. False
rebuild bool Instructs NAnt to recompile the output file regardless of the file timestamps. False
timeout int The maximum amount of time the application is allowed to execute, expressed in milliseconds. Defaults to no time-out. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False
warnaserror bool Instructs the compiler to treat all warnings as errors. The default is false. False
win32icon file Icon to associate with the application. False
win32res file Specifies a Win32 resource file (.res). False

Framework-configurable parameters

Attribute Type Description Required
exename string The name of the executable that should be used to launch the external program. False
managed ManagedExecution Specifies whether the external program should be treated as a managed application, possibly forcing it to be executed under the currently targeted version of the CLR. False
supportsdelaysign bool Indicates whether the compiler for a given target framework supports the "delaysign" option. The default is false. False
supportskeycontainer bool Indicates whether the compiler for a given target framework supports the "keycontainer" option. The default is false. False
supportskeyfile bool Indicates whether the compiler for a given target framework supports the "keyfile" option. The default is false. False
supportsnowarnlist bool Indicates whether the compiler for a given target framework supports a command line option that allows a list of warnings to be suppressed. The default is false. False
supportswarnaserrorlist bool Indicates whether the compiler for a given target framework supports the "warnaserror" option that takes a list of warnings. The default is false. False
useruntimeengine bool Deprecated. Specifies whether the external program is a managed application which should be executed using a runtime engine, if configured. The default is false. False

Nested Elements:

<nowarn>

Specifies a list of warnings that you want the compiler to suppress.
<warning>

Represents a compiler warning.

Parameters

AttributeTypeDescriptionRequired
numberstring A warning number, or comma-separated list of warnings, that you want the compiler to suppress or report. True
ifbool If true then the element will be processed; otherwise, skipped. The default is true. False
unlessbool If true then the element will be skipped; otherwise, processed. The default is false. False
</warning>

</nowarn>

<lib>

Deprecated. Additional directories to search in for assembly references.

</lib>

<references>

Reference metadata from the specified assembly files.

</references>

<resources>

Resources to embed.

</resources>

<sources>

The set of source files for compilation.

</sources>

<arg>

The command-line arguments for the external program.

Represents a command-line argument.

When passed to an external application, the argument will be quoted when appropriate. This does not apply to the line parameter, which is always passed as is.

Parameters

AttributeTypeDescriptionRequired
dirdirectory The value for a directory-based command-line argument; will be replaced with the absolute path of the directory. False
filefile The name of a file as a single command-line argument; will be replaced with the absolute filename of the file. False
ifbool Indicates if the argument should be passed to the external program. If true then the argument will be passed; otherwise, skipped. The default is true. False
linestring List of command-line arguments; will be passed to the executable as is. False
path<path> The value for a PATH-like command-line argument; you can use : or ; as path separators and NAnt will convert it to the platform's local conventions, while resolving references to environment variables. False
unlessbool Indicates if the argument should not be passed to the external program. If false then the argument will be passed; otherwise, skipped. The default is false. False
valuestring A single command-line argument; can contain space characters. False

Nested Elements:

<path>

Sets a single command-line argument and treats it like a PATH - ensures the right separator for the local platform is used.

</path>

Examples

  • A single command-line argument containing a space character.

    <arg value="-l -a" />
        
  • Two separate command-line arguments.

    <arg line="-l -a" />
        
  • A single command-line argument with the value \dir;\dir2;\dir3 on DOS-based systems and /dir:/dir2:/dir3 on Unix-like systems.

    <arg path="/dir;/dir2:\dir3" />
        

</arg>

Examples

  • Compile a "HelloWorld" application, including embedded resources.

    <vjc target="exe" output="helloworld.exe" debug="true">
        <sources>
            <include name="helloworld.jsl" />
        </sources>
        <resources prefix="HelloWorld" dynamicprefix="true">
            <include name="**/*.resx" />
        </resources>
        <references>
            <include name="System.dll" />
            <include name="System.Data.dll" />
            <include name="System.Drawing.dll" />
            <include name="System.Windows.Forms.dll" />
            <include name="System.Xml.dll" />
        </references>
    </vjc>
        

Requirements

Assembly: NAnt.DotNetTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/call.html0000644000175000017500000001451511757307432017463 0ustar jtaylorjtaylor <call> Task

<call>

[This is preliminary documentation and subject to change.]

Calls a NAnt target in the current project.

When the <call> task is used to execute a target, both that target and all its dependent targets will be re-executed.

To avoid dependent targets from being executed more than once, two options are available:

  • Add an "unless" attribute with value "${target::has-executed('<target name>')}" to the dependent targets.
  • Set the cascade attribute on the <call> task to false (recommended).

Parameters

Attribute Type Description Required
target string NAnt target to call. True
cascade bool Execute the specified targets dependencies -- even if they have been previously executed. The default is true. False
force bool Deprecated. Force an execute even if the target has already been executed. The default is false. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Examples

  • Call the target "build".

    <call target="build" />
        
  • This shows how a project could 'compile' a debug and release build using a common compile target.

    <project default="build">
        <property name="debug" value="false" />
        <target name="init">
            <echo message="initializing" />
        </target>
        <target name="compile" depends="init">
            <echo message="compiling with debug = ${debug}" />
        </target>
        <target name="build">
            <property name="debug" value="false" />
            <call target="compile" />
            <property name="debug" value="true" />
            <call target="compile" />
        </target>
    </project>
        

    The cascade parameter of the <call> task defaults to true, causing the "init" target to be executed for both the "debug" and "release" build.

    This results in the following build log:

     build:
       
     init:
    
         [echo] initializing
         
     compile:
     
         [echo] compiling with debug = false
         
     init:
     
         [echo] initializing
         
     compile:
     
         [echo] compiling with debug = true
         
     BUILD SUCCEEDED
       

    If the "init" should only be executed once, set the cascade attribute of the <call> task to false.

    The build log would then look like this:

     build:
       
     init:
    
         [echo] initializing
         
     compile:
     
         [echo] compiling with debug = false
         
     compile:
     
         [echo] compiling with debug = true
         
     BUILD SUCCEEDED
       

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/attrib.html0000644000175000017500000001440611757307431020033 0ustar jtaylorjtaylor <attrib> Task

<attrib>

[This is preliminary documentation and subject to change.]

Changes the file attributes of a file or set of files and directories.

<attrib> task does not have the concept of turning attributes off. Instead you specify all the attributes that you want turned on and the rest are turned off by default.

Refer to the FileAttributes enumeration in the .NET SDK for more information about file attributes.

Parameters

Attribute Type Description Required
archive bool Set the archive attribute. The default is false. False
file file The name of the file which will have its attributes set. This is provided as an alternate to using the task's fileset. False
hidden bool Set the hidden attribute. The default is false. False
normal bool Set the normal file attributes. This attribute is only valid if used alone. The default is false. False
readonly bool Set the read-only attribute. The default is false. False
system bool Set the system attribute. The default is false. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Nested Elements:

<fileset>

All the matching files and directories in this fileset will have their attributes set.

</fileset>

Examples

  • Set the read-only file attribute for the specified file in the project directory.

    <attrib file="myfile.txt" readonly="true" />
        
  • Set the normal file attribute for the specified file.

    <attrib file="myfile.txt" normal="true" />
        
  • Set the normal file attribute for all executable files in the current project directory and sub-directories.

    <attrib normal="true">
        <fileset>
            <include name="**/*.exe" />
            <include name="bin" />
        </fileset>
    </attrib>
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/tlbimp.html0000644000175000017500000003414111757307564020042 0ustar jtaylorjtaylor <tlbimp> Task

<tlbimp>

[This is preliminary documentation and subject to change.]

Imports a type library to a .NET assembly (wraps Microsoft's tlbimp.exe).

This task lets you easily create interop assemblies. By default, it will not reimport if the underlying COM TypeLib or reference has not changed.

See the Microsoft.NET Framework SDK documentation for details.

Parameters

Attribute Type Description Required
output file Specifies the name of the output file. True
typelib file Specifies the source type library that gets passed to the type library importer. True
asmversion string Specifies the version number of the assembly to produce. False
delaysign bool Specifies whether the resulting assembly should be signed with a strong name using delayed signing. The default is false. False
keycontainer string Specifies the key container in which the public/private key pair should be found that should be used to sign the resulting assembly with a strong name. False
keyfile file Specifies the publisher's official public/private key pair with which the resulting assembly should be signed with a strong name. False
namespace string Specifies the namespace in which to produce the assembly. False
primary bool Specifies whether a primary interop assembly should be produced for the specified type library. The default is false. False
publickey file Specifies the file containing the public key to use to sign the resulting assembly. False
strictref bool Specifies whether a type library should not be imported if all references within the current assembly or the reference assemblies cannot be resolved. The default is false. False
sysarray bool Specifies whether to import a COM style SafeArray as a managed Array class type. The default is false. False
transform string Specifies how to transform the metadata [.NET 1.1 or higher]. False
unsafe bool Specifies whether interfaces should be produced without .NET Framework security checks. The default is false. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
timeout int The maximum amount of time the application is allowed to execute, expressed in milliseconds. Defaults to no time-out. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Framework-configurable parameters

Attribute Type Description Required
exename string The name of the executable that should be used to launch the external program. False
managed ManagedExecution Specifies whether the external program should be treated as a managed application, possibly forcing it to be executed under the currently targeted version of the CLR. False
supportstransform bool Indicates whether tlbimp supports transforming metadata for a given target framework. The default is true. False
useruntimeengine bool Deprecated. Specifies whether the external program is a managed application which should be executed using a runtime engine, if configured. The default is false. False

Nested Elements:

<references>

Specifies the assembly files to use to resolve references to types defined outside the current type library.

</references>

<arg>

The command-line arguments for the external program.

Represents a command-line argument.

When passed to an external application, the argument will be quoted when appropriate. This does not apply to the line parameter, which is always passed as is.

Parameters

AttributeTypeDescriptionRequired
dirdirectory The value for a directory-based command-line argument; will be replaced with the absolute path of the directory. False
filefile The name of a file as a single command-line argument; will be replaced with the absolute filename of the file. False
ifbool Indicates if the argument should be passed to the external program. If true then the argument will be passed; otherwise, skipped. The default is true. False
linestring List of command-line arguments; will be passed to the executable as is. False
path<path> The value for a PATH-like command-line argument; you can use : or ; as path separators and NAnt will convert it to the platform's local conventions, while resolving references to environment variables. False
unlessbool Indicates if the argument should not be passed to the external program. If false then the argument will be passed; otherwise, skipped. The default is false. False
valuestring A single command-line argument; can contain space characters. False

Nested Elements:

<path>

Sets a single command-line argument and treats it like a PATH - ensures the right separator for the local platform is used.

</path>

Examples

  • A single command-line argument containing a space character.

    <arg value="-l -a" />
        
  • Two separate command-line arguments.

    <arg line="-l -a" />
        
  • A single command-line argument with the value \dir;\dir2;\dir3 on DOS-based systems and /dir:/dir2:/dir3 on Unix-like systems.

    <arg path="/dir;/dir2:\dir3" />
        

</arg>

Examples

  • Import LegacyCOM.dll to DotNetAssembly.dll.

    <tlbimp typelib="LegacyCOM.dll" output="DotNetAssembly.dll" />
        
  • Generate an assembly named "Interop.MSVidCtlLib.dll" for the MS Video Control 1.0 Type Library, transforming any [out, retval] parameters of methods on dispinterfaces in the type library into return values in the managed library.

    <tlbimp typelib="msvidctl.dll" output="Interop.MSVidCtlLib.dll" transform="dispret">
        <references basedir="Interop">
            <include name="Interop.TunerLib.dll" />
        </references>
    </tlbimp>
        

Requirements

Assembly: NAnt.Win32Tasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/include.html0000644000175000017500000001010411757307443020163 0ustar jtaylorjtaylor <include> Task

<include>

[This is preliminary documentation and subject to change.]

Includes an external build file.

This task is used to break your build file into smaller chunks. You can load a partial build file and have it included into the build file.

Note: Any global (project level) tasks in the included build file are executed when this task is executed. Tasks in target elements are only executed if that target is executed.

Note: The project element attributes are ignored.

Note: This task can only be in the global (project level) section of the build file.

Note: This task can only include files from the file system.

Parameters

Attribute Type Description Required
buildfile string Build file to include. True
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Examples

  • Include a task that fetches the project version from the GetProjectVersion.include build file.

    <include buildfile="GetProjectVersion.include" />
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/cvs-update.html0000644000175000017500000004115411757307547020631 0ustar jtaylorjtaylor <cvs-update> Task

<cvs-update>

[This is preliminary documentation and subject to change.]

Updates a CVS module in a local working directory.

Parameters

Attribute Type Description Required
builddirs bool If true. new directories will be created on the local sandbox. The default is true. False
date datetime Specify the revision date to update to. The version of the file that existed at the date specified is retrieved. False
overwritelocal bool If true the local copy of the file will be overwritten with the copy from the remote repository. The default is false. False
pruneempty bool If true empty directories copied down from the remote repository will be removed from the local sandbox. The default is true. False
recursive bool Specifies if the command should be executed recursively. The default is true. False
revision string Specify the revision to update the file to. This corresponds to the "sticky-tag" of the file. False
sticky-tag string Sticky tag or revision to update the local file to. False
commandline string Command-line arguments for the program. The command line arguments are used to specify any cvs command options that are not available as attributes. These are appended after the command itself and are additive to whatever attributes are currently specified. False
compressionlevel int Compression level to use for all net traffic. This should be a value from 1-9.



NOTE: This is not available on sharpcvslib.
False
cvsfullpath file The full path to the cvs binary used. The cvs tasks will attempt to "guess" the location of your cvs binary based on your path. If the task is unable to resolve the location, or resolves it incorrectly this can be used to manually specify the path. False
cvsroot string

The cvs root variable has the following components:

[protocol]:[username]@[servername]:[server path]
  • protocol: ext, pserver, ssh (sharpcvslib); if you are not using sharpcvslib consult your cvs documentation.
  • username: [username]
  • servername: cvs.sourceforge.net
  • server path: /cvsroot/nant

False
cvsrsh file The executable to use for ssh communication. False
destination directory Destination directory for the local sandbox. If destination is not specified then the current directory is used. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
module string The module to perform an operation on. False
passfile file The full path to the cached password file. If not specified then the environment variables are used to try and locate the file. False
password string Deprecated. The password for logging in to the repository. False
quiet bool Indicates if the output from the cvs command should be supressed. The default is false. False
readonly bool true if the sandbox files should be checked out in read only mode. The default is false. False
readwrite bool true if the sandbox files should be checked out in read/write mode. The default is true. False
reallyquiet bool Indicates if the output from the cvs command should be stopped. The default is false. False
timeout int The maximum amount of time the application is allowed to execute, expressed in milliseconds. Defaults to no time-out. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
usesharpcvslib bool

true if the SharpCvsLib binaries that come bundled with NAnt should be used to perform the cvs commands, false otherwise.

You may also specify an override value for all cvs tasks instead of specifying a value for each. To do this set the property sourcecontrol.usesharpcvslib to false.

If you choose not to use SharpCvsLib to checkout from cvs you will need to include a cvs.exe binary in your path.
False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Framework-configurable parameters

Attribute Type Description Required
managed ManagedExecution Specifies whether the external program should be treated as a managed application, possibly forcing it to be executed under the currently targeted version of the CLR. False
useruntimeengine bool Deprecated. Specifies whether the external program is a managed application which should be executed using a runtime engine, if configured. The default is false. False

Nested Elements:

<fileset>

Used to specify the version control system (VCS) files that are going to be acted on.

</fileset>

<arg>

The command-line arguments for the external program.

Represents a command-line argument.

When passed to an external application, the argument will be quoted when appropriate. This does not apply to the line parameter, which is always passed as is.

Parameters

AttributeTypeDescriptionRequired
dirdirectory The value for a directory-based command-line argument; will be replaced with the absolute path of the directory. False
filefile The name of a file as a single command-line argument; will be replaced with the absolute filename of the file. False
ifbool Indicates if the argument should be passed to the external program. If true then the argument will be passed; otherwise, skipped. The default is true. False
linestring List of command-line arguments; will be passed to the executable as is. False
path<path> The value for a PATH-like command-line argument; you can use : or ; as path separators and NAnt will convert it to the platform's local conventions, while resolving references to environment variables. False
unlessbool Indicates if the argument should not be passed to the external program. If false then the argument will be passed; otherwise, skipped. The default is false. False
valuestring A single command-line argument; can contain space characters. False

Nested Elements:

<path>

Sets a single command-line argument and treats it like a PATH - ensures the right separator for the local platform is used.

</path>

Examples

  • A single command-line argument containing a space character.

    <arg value="-l -a" />
        
  • Two separate command-line arguments.

    <arg line="-l -a" />
        
  • A single command-line argument with the value \dir;\dir2;\dir3 on DOS-based systems and /dir:/dir2:/dir3 on Unix-like systems.

    <arg path="/dir;/dir2:\dir3" />
        

</arg>

Examples

  • Update nant.

    <cvs-update 
        destination="c:\src\nant\" 
        cvsroot=":pserver:anonymous@cvs.sourceforge.net:/cvsroot/nant" 
        password="" 
        module="nant" />
        
  • Update your NAnt revision named your_favorite_revision_here in the folder c:\src\nant\replacement_for_module_directory_name.

    <cvs-update 
        destination="c:\src\nant\" 
        cvsroot=":pserver:anonymous@cvs.sourceforge.net:/cvsroot/nant" 
        module="nant"
        revision="your_favorite_revision_here"
        overridedir="replacement_for_module_directory_name"
        usesharpcvslib="false">
        <fileset>
            <include name="build.number"/>
        </fileset>
    </cvs-update>
        

Requirements

Assembly: NAnt.SourceControlTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/cvs-pass.html0000644000175000017500000001002011757307535020276 0ustar jtaylorjtaylor <cvs-pass> Task

<cvs-pass>

[This is preliminary documentation and subject to change.]

Executes the cvs login command which appends or updates an entry to the specified .cvspass file.

Parameters

Attribute Type Description Required
password string Password to append or update to the .cvspass file. True
cvsroot string The repository root string. False
passfile file The full path to the .cvspass file. The default is ~/.cvspass. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Examples

  • Update .cvspass file to include the NAnt anonymous login.

    <cvs-pass cvsroot=":pserver:anonymous@cvs.sourceforge.net:/cvsroot/nant" 
         password="anonymous"
         passfile="C:\.cvspass" />
        

Requirements

Assembly: NAnt.SourceControlTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/gunzip.html0000644000175000017500000000707611757307417020073 0ustar jtaylorjtaylor <gunzip> Task

<gunzip>

[This is preliminary documentation and subject to change.]

Expands a file packed using GZip compression.

Parameters

Attribute Type Description Required
dest file The destination file. True
src file The file to expand. True
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Examples

  • Expands "test.tar.gz" to "test2.tar".

    <gunzip src="test.tar.gz" dest="test.tar" />
        

Requirements

Assembly: NAnt.CompressionTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/nant.html0000644000175000017500000002503611757307450017510 0ustar jtaylorjtaylor <nant> Task

<nant>

[This is preliminary documentation and subject to change.]

Runs NAnt on a supplied build file, or a set of build files.

By default, all the properties of the current project will be available in the new project. Alternatively, you can set inheritall to false to not copy any properties to the new project.

You can also set properties in the new project from the old project by using nested property tags. These properties are always passed to the new project regardless of the setting of inheritall. This allows you to parameterize your subprojects.

References to data types can also be passed to the new project, but by default they are not. If you set the inheritrefs to true, all references will be copied.

Parameters

Attribute Type Description Required
buildfile file The build file to build. False
inheritall bool Specifies whether current property values should be inherited by the executed project. The default is true. False
inheritrefs bool Specifies whether all references will be copied to the new project. The default is false. False
target string The target to execute. To specify more than one target seperate targets with a space. Targets are executed in order if possible. The default is to use target specified in the project's default attribute. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Nested Elements:

<buildfiles>

Used to specify a set of build files to process.

</buildfiles>

<properties>

Specifies a collection of properties that should be created in the executed project. Note, existing properties with identical names that are not read-only will be overwritten.
<property>

Sets a property in the current project.

Note: NAnt uses a number of predefined properties.

Parameters

AttributeTypeDescriptionRequired
namestring The name of the NAnt property to set. True
valuestring The value to assign to the NAnt property.

This attribute's properties will not be automatically expanded!

True
dynamicbool Specifies whether references to other properties should not be expanded when the value of the property is set, but expanded when the property is actually used. By default, properties will be expanded when set. False
overwritebool Specifies whether the value of a property should be overwritten if the property already exists (unless the property is read-only). The default is true. False
readonlybool Specifies whether the property is read-only or not. The default is false. False
failonerrorbool Determines if task failure stops the build, or is just reported. The default is true. False
ifbool If true then the task will be executed; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbosebool Determines whether the task should report detailed build log messages. The default is false. False

Examples

  • Define a debug property with value true.

    <property name="debug" value="true" />
        
  • Use the user-defined debug property.

    <property name="trace" value="${debug}" />
        
  • Define a read-only property. This is just like passing in the param on the command line.

    <property name="do_not_touch_ME" value="hammer" readonly="true" />
        
  • Define a property, but do not overwrite the value if the property already exists (eg. it was specified on the command line).

    <project name="property-example">
      <property name="debug" value="true" overwrite="false" />
      <echo message="debug: ${debug}" />
    </project>
        

    Executing this build file with the command line option -D:debug=false, would cause the value specified on the command line to remain unaltered.

    [echo] debug: false
        
</property>

</properties>

Examples

  • Build a project located in a different directory if the debug property is not true.

    <nant buildfile="${src.dir}/Extras/BuildServer/BuildServer.build" unless="${debug}" />
        
  • Build a project while adding a set of properties to that project.

    <nant buildfile="${src.dir}/Extras/BuildServer/BuildServer.build">
        <properties>
            <property name="build.dir" value="c:/buildserver" />
            <property name="build.debug" value="false" />
            <property name="lib.dir" value="c:/shared/lib" readonly="true" />
        </properties>
    </nant>
        
  • Build all projects named default.build located anywhere under the project base directory.

    <nant>
        <buildfiles>
            <include name="**/default.build" />
            <!-- avoid recursive execution of current build file -->
            <exclude name="${project::get-buildfile-path()}" />
        </buildfiles>
    </nant>
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/tstamp.html0000644000175000017500000001562211757307455020065 0ustar jtaylorjtaylor <tstamp> Task

<tstamp>

[This is preliminary documentation and subject to change.]

Sets properties with the current date and time.

By default the <tstamp> task displays the current date and time and sets the following properties:

  • tstamp.date to yyyyMMdd
  • tstamp.time to HHmm
  • tstamp.now using the default DateTime.ToString() method

To set an additional property with a custom date/time use the property and pattern attributes. To set a number of additional properties with the exact same date and time use the formatter nested element (see example).

The date and time string displayed by the <tstamp> task uses the computer's default long date and time string format. You might consider setting these to the ISO 8601 standard for date and time notation.

Parameters

Attribute Type Description Required
pattern string The date/time pattern to be used. False
property string The property to receive the date/time string in the given pattern. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Nested Elements:

<formatter>

Parameters

Attribute Type Description Required
pattern string The string pattern to use to format the property. True
property string The name of the NAnt property to set. True
if bool Indicates if the formatter should be used to format the timestamp. If true then the formatter will be used; otherwise, skipped. The default is true. False
unless bool Indicates if the formatter should be not used to format the timestamp. If false then the formatter will be used; otherwise, skipped. The default is false. False

</formatter>

Examples

  • Set the build.date property.

    <tstamp property="build.date" pattern="yyyyMMdd" verbose="true" />
        
  • Set a number of properties for Ant like compatibility.

    <tstamp verbose="true">
        <formatter property="TODAY" pattern="dd MMM yyyy"/>
        <formatter property="DSTAMP" pattern="yyyyMMdd" unless="${date.not.needed}" />
        <formatter property="TSTAMP" pattern="HHmm" if="${need.hours}" />
    </tstamp>
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/csc.html0000644000175000017500000006272311757307501017321 0ustar jtaylorjtaylor <csc> Task

<csc>

[This is preliminary documentation and subject to change.]

Compiles C# programs.

Note: In order to have <csc> task generate manifest resource names that match those generated by Microsoft Visual Studio.NET, the value of the prefix attribute of the <resources> element should match the "Default Namespace" of the C# project, and the value of the dynamicprefix attribute should be set to "true".

Parameters

Attribute Type Description Required
baseaddress string The preferred base address at which to load a DLL. The default base address for a DLL is set by the .NET Framework common language runtime. False
checked bool Specifies whether an integer arithmetic statement that is not in the scope of the checked or unchecked keywords and that results in a value outside the range of the data type should cause a run-time exception. The default is false. False
codepage string Specifies the code page to use for all source code files in the compilation. False
debug DebugOutput Specifies the type of debugging information generated by the compiler. The default is None. False
doc file The name of the XML documentation file to generate. False
filealign int Specifies the size of sections in the output file. Valid values are 512, 1024, 2048, 4096, and 8192. False
langversion string Causes the compiler to only accept syntax that is included in a given specification. False
noconfig bool Instructs the compiler not to use implicit references to assemblies. The default is false. False
nostdlib bool Instructs the compiler not to import mscorlib.dll. The default is false. False
optimize bool Specifies whether the compiler should perform optimizations to the make output files smaller, faster, and more effecient. The default is false. False
platform string Specifies which platform version of common language runtime (CLR) can run the output file. False
unsafe bool Instructs the compiler to allow code that uses the unsafe keyword. The default is false. False
warninglevel string Specifies the warning level for the compiler to display. Valid values are 0-4. The default is 4. False
output file The output file created by the compiler. True
target string Output type. Possible values are exe, winexe, library or module. True
define string Define conditional compilation symbol(s). False
delaysign DelaySign Specifies whether to delay sign the assembly using only the public portion of the strong name key. The default is NotSet. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
keycontainer string Specifies the key pair container used to strongname the assembly. False
keyfile file Specifies a strong name key file. False
main string Specifies which type contains the Main method that you want to use as the entry point into the program. False
nowarn string Deprecated. Specifies a comma-separated list of warnings that should be suppressed by the compiler. False
rebuild bool Instructs NAnt to recompile the output file regardless of the file timestamps. False
timeout int The maximum amount of time the application is allowed to execute, expressed in milliseconds. Defaults to no time-out. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False
warnaserror bool Instructs the compiler to treat all warnings as errors. The default is false. False
win32icon file Icon to associate with the application. False
win32res file Specifies a Win32 resource file (.res). False

Framework-configurable parameters

Attribute Type Description Required
exename string The name of the executable that should be used to launch the external program. False
managed ManagedExecution Specifies whether the external program should be treated as a managed application, possibly forcing it to be executed under the currently targeted version of the CLR. False
noconfig bool Instructs the compiler not to use implicit references to assemblies. The default is false. False
nostdlib bool Instructs the compiler not to import mscorlib.dll. The default is false. False
supportsdelaysign bool Indicates whether the compiler for a given target framework supports the "delaysign" option. The default is false. False
supportsdocgeneration bool Specifies whether the compiler for the active target framework supports generation of XML Documentation file. The default is true. False
supportskeycontainer bool Indicates whether the compiler for a given target framework supports the "keycontainer" option. The default is false. False
supportskeyfile bool Indicates whether the compiler for a given target framework supports the "keyfile" option. The default is false. False
supportslangversion bool Specifies whether the compiler for the active target framework supports accepting only a specific language syntax. The default is false. False
supportsnowarnlist bool Indicates whether the compiler for a given target framework supports a command line option that allows a list of warnings to be suppressed. The default is false. False
supportspackagereferences bool Indicates whether package references are supported by compiler for a given target framework. The default is false. False
supportsplatform bool Specifies whether the compiler for the active target framework supports limiting the platform on which the compiled code can run. The default is false. False
supportswarnaserrorlist bool Indicates whether the compiler for a given target framework supports the "warnaserror" option that takes a list of warnings. The default is false. False
useruntimeengine bool Deprecated. Specifies whether the external program is a managed application which should be executed using a runtime engine, if configured. The default is false. False

Nested Elements:

<warnaserror>

Controls which warnings should be reported as errors.

</warnaserror>

<nowarn>

Specifies a list of warnings that you want the compiler to suppress.
<warning>

Represents a compiler warning.

Parameters

AttributeTypeDescriptionRequired
numberstring A warning number, or comma-separated list of warnings, that you want the compiler to suppress or report. True
ifbool If true then the element will be processed; otherwise, skipped. The default is true. False
unlessbool If true then the element will be skipped; otherwise, processed. The default is false. False
</warning>

</nowarn>

<lib>

Deprecated. Additional directories to search in for assembly references.

</lib>

<references>

Reference metadata from the specified assembly files.

</references>

<pkg-references>

Specifies list of packages to reference.
<package>

Represents a package.

Parameters

AttributeTypeDescriptionRequired
namestring Name of the package to reference. Multiple package can be specified with a single element as a semi-colon separated list of package names. True
ifbool Indicates if the package should be passed to the task. If true then the package will be passed; otherwise, skipped. The default is true. False
unlessbool Indicates if the package should not be passed to the task. If false then the package will be passed; otherwise, skipped. The default is false. False
</package>

</pkg-references>

<resources>

Resources to embed.

</resources>

<modules>

Link the specified modules into this assembly.

</modules>

<sources>

The set of source files for compilation.

</sources>

<arg>

The command-line arguments for the external program.

Represents a command-line argument.

When passed to an external application, the argument will be quoted when appropriate. This does not apply to the line parameter, which is always passed as is.

Parameters

AttributeTypeDescriptionRequired
dirdirectory The value for a directory-based command-line argument; will be replaced with the absolute path of the directory. False
filefile The name of a file as a single command-line argument; will be replaced with the absolute filename of the file. False
ifbool Indicates if the argument should be passed to the external program. If true then the argument will be passed; otherwise, skipped. The default is true. False
linestring List of command-line arguments; will be passed to the executable as is. False
path<path> The value for a PATH-like command-line argument; you can use : or ; as path separators and NAnt will convert it to the platform's local conventions, while resolving references to environment variables. False
unlessbool Indicates if the argument should not be passed to the external program. If false then the argument will be passed; otherwise, skipped. The default is false. False
valuestring A single command-line argument; can contain space characters. False

Nested Elements:

<path>

Sets a single command-line argument and treats it like a PATH - ensures the right separator for the local platform is used.

</path>

Examples

  • A single command-line argument containing a space character.

    <arg value="-l -a" />
        
  • Two separate command-line arguments.

    <arg line="-l -a" />
        
  • A single command-line argument with the value \dir;\dir2;\dir3 on DOS-based systems and /dir:/dir2:/dir3 on Unix-like systems.

    <arg path="/dir;/dir2:\dir3" />
        

</arg>

Examples

  • Compile a "HelloWorld" application, including embedded resources.

    <csc target="exe" output="HelloWorld.exe" debug="true">
        <nowarn>
            <!-- do not report warnings for missing XML comments -->
            <warning number="0519" />
        </nowarn>
        <sources>
            <include name="**/*.cs" />
        </sources>
        <resources dynamicprefix="true" prefix="HelloWorld">
            <include name="**/*.resx" />
        </resources>
        <references>
            <include name="System.dll" />
            <include name="System.Data.dll" />
        </references>
    </csc>
        

Requirements

Assembly: NAnt.DotNetTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/delay-sign.html0000644000175000017500000002313511757307502020600 0ustar jtaylorjtaylor <delay-sign> Task

<delay-sign>

[This is preliminary documentation and subject to change.]

Signs delay-signed .NET Assemblies, or re-signs existing assemblies.

The delay-signing mechanism takes a fileset (named targets) and either a keyfile attribute for a file containing the public and private keys, or keycontainer to name a key container.

Parameters

Attribute Type Description Required
keycontainer string Specifies the key container. False
keyfile file Specifies the filesystem path to the signing key. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
timeout int The maximum amount of time the application is allowed to execute, expressed in milliseconds. Defaults to no time-out. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Framework-configurable parameters

Attribute Type Description Required
exename string The name of the executable that should be used to launch the external program. False
managed ManagedExecution Specifies whether the external program should be treated as a managed application, possibly forcing it to be executed under the currently targeted version of the CLR. False
useruntimeengine bool Deprecated. Specifies whether the external program is a managed application which should be executed using a runtime engine, if configured. The default is false. False

Nested Elements:

<targets>

List of assemblies/executables to sign.

</targets>

<arg>

The command-line arguments for the external program.

Represents a command-line argument.

When passed to an external application, the argument will be quoted when appropriate. This does not apply to the line parameter, which is always passed as is.

Parameters

AttributeTypeDescriptionRequired
dirdirectory The value for a directory-based command-line argument; will be replaced with the absolute path of the directory. False
filefile The name of a file as a single command-line argument; will be replaced with the absolute filename of the file. False
ifbool Indicates if the argument should be passed to the external program. If true then the argument will be passed; otherwise, skipped. The default is true. False
linestring List of command-line arguments; will be passed to the executable as is. False
path<path> The value for a PATH-like command-line argument; you can use : or ; as path separators and NAnt will convert it to the platform's local conventions, while resolving references to environment variables. False
unlessbool Indicates if the argument should not be passed to the external program. If false then the argument will be passed; otherwise, skipped. The default is false. False
valuestring A single command-line argument; can contain space characters. False

Nested Elements:

<path>

Sets a single command-line argument and treats it like a PATH - ensures the right separator for the local platform is used.

</path>

Examples

  • A single command-line argument containing a space character.

    <arg value="-l -a" />
        
  • Two separate command-line arguments.

    <arg line="-l -a" />
        
  • A single command-line argument with the value \dir;\dir2;\dir3 on DOS-based systems and /dir:/dir2:/dir3 on Unix-like systems.

    <arg path="/dir;/dir2:\dir3" />
        

</arg>

Examples

  • Sign partially-signed foo.dll with bar.snk.

    <delay-sign keyfile="bar.snk" verbose="false">
        <targets>
            <include name="foo.dll" />
        </targets>
    </delay-sign>
        

Requirements

Assembly: NAnt.DotNetTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/if.html0000644000175000017500000002302211757307442017140 0ustar jtaylorjtaylor <if> Task

<if>

[This is preliminary documentation and subject to change.]

Checks the conditional attributes and executes the children if true.

If no conditions are checked, all child tasks are executed.

If more than one attribute is used, they are &&'d. The first to fail stops the check.

The order of condition evaluation is, targetexists, propertyexists, propertytrue, uptodatefile.

Note: instead of using the deprecated attributes, we advise you to use the following functions in combination with the test attribute:

Function Description
property::exists() Checks whether the specified property exists.
target::exists() Checks whether the specified target exists.

Parameters

Attribute Type Description Required
comparefile string Deprecated. The file to check against for the uptodate file. False
propertyexists string Deprecated. Used to test whether a property exists. False
propertytrue string Deprecated. Used to test whether a property is true. False
targetexists string Deprecated. Used to test whether a target exists. False
test string Used to test arbitrary boolean expression. False
uptodatefile string Deprecated. The file to compare if uptodate. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Nested Elements:

<comparefiles>

Deprecated. The <fileset> that contains the comparison files for the uptodatefile(s) check.

</comparefiles>

<uptodatefiles>

Deprecated. The <fileset> that contains the uptodate files for the comparefile(s) check.

</uptodatefiles>

Examples

  • Tests the value of a property using expressions.

    <if test="${build.configuration=='release'}">
        <echo>Build release configuration</echo>
    </if>
        
  • Tests the the output of a function.

    <if test="${not file::exists(filename) or file::get-length(filename) = 0}">
        <echo message="The version file ${filename} doesn't exist or is empty!" />
    </if>
        
  • (Deprecated) Check that a target exists.

    <target name="myTarget" />
    <if targetexists="myTarget">
        <echo message="myTarget exists" />
    </if>
        
  • (Deprecated) Check existence of a property.

    <if propertyexists="myProp">
        <echo message="myProp Exists. Value='${myProp}'" />
    </if>
        
  • (Deprecated) Check that a property value is true.

    <if propertytrue="myProp">
        <echo message="myProp is true. Value='${myProp}'" />
    </if>
        
  • (Deprecated) Check that a property exists and is true (uses multiple conditions).

    <if propertyexists="myProp" propertytrue="myProp">
        <echo message="myProp is '${myProp}'" />
    </if>
        

    which is the same as

    <if propertyexists="myProp">
        <if propertytrue="myProp">
            <echo message="myProp is '${myProp}'" />
        </if>
    </if>
        
  • (Deprecated) Check file dates. If myfile.dll is uptodate, then do stuff.

    <if uptodatefile="myfile.dll" comparefile="myfile.cs">
        <echo message="myfile.dll is newer/same-date as myfile.cs" />
    </if>
        

    or

    <if uptodatefile="myfile.dll">
        <comparefiles>
            <include name="*.cs" />
        </comparefiles>
        <echo message="myfile.dll is newer/same-date as myfile.cs" />
    </if>
        

    or

    <if>
        <uptodatefiles>
            <include name="myfile.dll" />
        </uptodatefiles>
        <comparefiles>
            <include name="*.cs" />
        </comparefiles>
        <echo message="myfile.dll is newer/same-date as myfile.cs" />
    </if>
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/vbc.html0000644000175000017500000006351011757307516017324 0ustar jtaylorjtaylor <vbc> Task

<vbc>

[This is preliminary documentation and subject to change.]

Compiles Visual Basic.NET programs.

Note: In order to have <vbc> task generate manifest resource names that match those generated by Microsoft Visual Studio.NET, the value of the prefix attribute of the <resources> element should match the "Root namespace" of the VB.NET project, and the value of the dynamicprefix attribute should be set to "false".

Parameters

Attribute Type Description Required
baseaddress string The preferred base address at which to load a DLL. The default base address for a DLL is set by the .NET Framework common language runtime. False
debug DebugOutput Specifies the type of debugging information generated by the compiler. The default is None. False
doc file The name of the XML documentation file to generate. Only supported when targeting .NET 2.0 (or higher). False
imports string Deprecated. Specifies whether the /imports option gets passed to the compiler. False
nostdlib bool Instructs the compiler not to reference standard libraries (system.dll and VBC.RSP). The default is false. Only supported when targeting .NET 2.0 (or higher). False
optioncompare string Specifies whether /optioncompare option gets passed to the compiler. False
optionexplicit bool Specifies whether the /optionexplicit option gets passed to the compiler. The default is false. False
optionoptimize bool Specifies whether the /optimize option gets passed to the compiler. The default is false. False
optionstrict bool Specifies whether the /optionstrict option gets passed to the compiler. The default is false. False
platform string Specifies which platform version of common language runtime (CLR) can run the output file. False
removeintchecks bool Specifies whether the /removeintchecks option gets passed to the compiler. The default is false. False
rootnamespace string Specifies whether the /rootnamespace option gets passed to the compiler. False
output file The output file created by the compiler. True
target string Output type. Possible values are exe, winexe, library or module. True
define string Define conditional compilation symbol(s). False
delaysign DelaySign Specifies whether to delay sign the assembly using only the public portion of the strong name key. The default is NotSet. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
keycontainer string Specifies the key pair container used to strongname the assembly. False
keyfile file Specifies a strong name key file. False
main string Specifies which type contains the Main method that you want to use as the entry point into the program. False
nowarn string Deprecated. Specifies a comma-separated list of warnings that should be suppressed by the compiler. False
rebuild bool Instructs NAnt to recompile the output file regardless of the file timestamps. False
timeout int The maximum amount of time the application is allowed to execute, expressed in milliseconds. Defaults to no time-out. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False
warnaserror bool Instructs the compiler to treat all warnings as errors. The default is false. False
win32icon file Icon to associate with the application. False
win32res file Specifies a Win32 resource file (.res). False

Framework-configurable parameters

Attribute Type Description Required
exename string The name of the executable that should be used to launch the external program. False
managed ManagedExecution Specifies whether the external program should be treated as a managed application, possibly forcing it to be executed under the currently targeted version of the CLR. False
nostdlib bool Instructs the compiler not to reference standard libraries (system.dll and VBC.RSP). The default is false. Only supported when targeting .NET 2.0 (or higher). False
supportsdelaysign bool Indicates whether the compiler for a given target framework supports the "delaysign" option. The default is false. False
supportsdocgeneration bool Specifies whether the compiler for the active target framework supports generation of XML Documentation file. The default is false. False
supportskeycontainer bool Indicates whether the compiler for a given target framework supports the "keycontainer" option. The default is false. False
supportskeyfile bool Indicates whether the compiler for a given target framework supports the "keyfile" option. The default is false. False
supportsnostdlib bool Specifies whether the compiler for the active target framework supports NOT referencing standard libraries (system.dll and VBC.RSP). The default is false. False
supportsnowarnlist bool Indicates whether the compiler for a given target framework supports a command line option that allows a list of warnings to be suppressed. The default is false. False
supportspackagereferences bool Indicates whether package references are supported by compiler for a given target framework. The default is false. False
supportsplatform bool Specifies whether the compiler for the active target framework supports limiting the platform on which the compiled code can run. The default is false. False
supportswarnaserrorlist bool Indicates whether the compiler for a given target framework supports the "warnaserror" option that takes a list of warnings. The default is false. False
useruntimeengine bool Deprecated. Specifies whether the external program is a managed application which should be executed using a runtime engine, if configured. The default is false. False

Nested Elements:

<imports>

The namespaces to import.

</imports>

<warnaserror>

Controls which warnings should be reported as errors.

</warnaserror>

<nowarn>

Specifies a list of warnings that you want the compiler to suppress.
<warning>

Represents a compiler warning.

Parameters

AttributeTypeDescriptionRequired
numberstring A warning number, or comma-separated list of warnings, that you want the compiler to suppress or report. True
ifbool If true then the element will be processed; otherwise, skipped. The default is true. False
unlessbool If true then the element will be skipped; otherwise, processed. The default is false. False
</warning>

</nowarn>

<lib>

Deprecated. Additional directories to search in for assembly references.

</lib>

<references>

Reference metadata from the specified assembly files.

</references>

<pkg-references>

Specifies list of packages to reference.
<package>

Represents a package.

Parameters

AttributeTypeDescriptionRequired
namestring Name of the package to reference. Multiple package can be specified with a single element as a semi-colon separated list of package names. True
ifbool Indicates if the package should be passed to the task. If true then the package will be passed; otherwise, skipped. The default is true. False
unlessbool Indicates if the package should not be passed to the task. If false then the package will be passed; otherwise, skipped. The default is false. False
</package>

</pkg-references>

<resources>

Resources to embed.

</resources>

<modules>

Link the specified modules into this assembly.

</modules>

<sources>

The set of source files for compilation.

</sources>

<arg>

The command-line arguments for the external program.

Represents a command-line argument.

When passed to an external application, the argument will be quoted when appropriate. This does not apply to the line parameter, which is always passed as is.

Parameters

AttributeTypeDescriptionRequired
dirdirectory The value for a directory-based command-line argument; will be replaced with the absolute path of the directory. False
filefile The name of a file as a single command-line argument; will be replaced with the absolute filename of the file. False
ifbool Indicates if the argument should be passed to the external program. If true then the argument will be passed; otherwise, skipped. The default is true. False
linestring List of command-line arguments; will be passed to the executable as is. False
path<path> The value for a PATH-like command-line argument; you can use : or ; as path separators and NAnt will convert it to the platform's local conventions, while resolving references to environment variables. False
unlessbool Indicates if the argument should not be passed to the external program. If false then the argument will be passed; otherwise, skipped. The default is false. False
valuestring A single command-line argument; can contain space characters. False

Nested Elements:

<path>

Sets a single command-line argument and treats it like a PATH - ensures the right separator for the local platform is used.

</path>

Examples

  • A single command-line argument containing a space character.

    <arg value="-l -a" />
        
  • Two separate command-line arguments.

    <arg line="-l -a" />
        
  • A single command-line argument with the value \dir;\dir2;\dir3 on DOS-based systems and /dir:/dir2:/dir3 on Unix-like systems.

    <arg path="/dir;/dir2:\dir3" />
        

</arg>

Examples

  • Example build file using this task.

    <project name="Hello World" default="build" basedir=".">
      <property name="basename" value="HelloWorld" />
      <target name="clean">
         <delete file="${basename}-vb.exe" failonerror="false" />
         <delete file="${basename}-vb.pdb" failonerror="false" />
      </target>
      <target name="build">
         <vbc target="exe" output="${basename}-vb.exe" rootnamespace="${basename}">
            <imports>
                <import namespace="System" />
                <import namespace="System.Data" />
            </imports>
            <sources>
               <include name="${basename}.vb" />
            </sources>
            <resources prefix="${basename}" dynamicprefix="true">
                <include name="**/*.resx" />
            </resources>
            <references>
                <include name="System.dll" />
                <include name="System.Data.dll" />
            </references>
         </vbc>
      </target>
      <target name="rebuild" depends="clean, build" />
    </project>
       

Requirements

Assembly: NAnt.DotNetTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/xmlpoke.html0000644000175000017500000001706011757307457020234 0ustar jtaylorjtaylor <xmlpoke> Task

<xmlpoke>

[This is preliminary documentation and subject to change.]

Replaces text in an XML file at the location specified by an XPath expression.

The location specified by the XPath expression must exist, it will not create the parent elements for you. However, provided you have a root element you could use a series of the tasks to build the XML file up if necessary.

Parameters

Attribute Type Description Required
file file The name of the file that contains the XML document that is going to be poked. True
value string The value that replaces the contents of the selected nodes. True
xpath string The XPath expression used to select which nodes are to be modified. True
preserveWhitespace bool If true then the whitespace in the resulting document will be preserved; otherwise the whitespace will be removed. The default is false. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Nested Elements:

<namespaces>

Namespace definitions to resolve prefixes in the XPath expression.
<namespace>

Represents an XML namespace.

Parameters

AttributeTypeDescriptionRequired
prefixstring The prefix to associate with the namespace. True
uristring The associated XML namespace URI. True
ifbool Indicates if the namespace should be added to the XmlNamespaceManager. If true then the namespace will be added; otherwise, skipped. The default is true. False
unlessbool Indicates if the namespace should not be added to the XmlNamespaceManager. list. If false then the parameter will be added; otherwise, skipped. The default is false. False
</namespace>

</namespaces>

Examples

  • Change the server setting in the configuration from testhost.somecompany.com to productionhost.somecompany.com.

    XML file:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
        <appSettings>
            <add key="server" value="testhost.somecompany.com" />
        </appSettings>
    </configuration>
        

    Build fragment:

    <xmlpoke
        file="App.config"
        xpath="/configuration/appSettings/add[@key = 'server']/@value"
        value="productionhost.somecompany.com" />
        
  • Modify the noNamespaceSchemaLocation in an XML file.

    XML file:

    <?xml version="1.0" encoding="utf-8" ?>
    <Commands xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Path Value">
    </Commands>
        

    Build fragment:

    <xmlpoke file="test.xml" xpath="/Commands/@xsi:noNamespaceSchemaLocation" value="d:\Commands.xsd">
        <namespaces>
            <namespace prefix="xsi" uri="http://www.w3.org/2001/XMLSchema-instance" />
        </namespaces>
    </xmlpoke>
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/midl.html0000644000175000017500000004372411757307555017507 0ustar jtaylorjtaylor <midl> Task

<midl>

[This is preliminary documentation and subject to change.]

This tasks allows you to run MIDL.exe.

This task only supports a small subset of the MIDL.EXE command line switches, but you can use the options element to specify any other unsupported commands you want to specify.

Parameters

Attribute Type Description Required
filename file Name of .IDL file to process. True
acf string The /acf switch allows the user to supply an explicit ACF file name. The switch also allows the use of different interface names in the IDL and ACF files. False
align string The /align switch is functionally the same as the MIDL /Zp option and is recognized by the MIDL compiler solely for backward compatibility with MkTypLib. False
app_config bool The /app_config switch selects application-configuration mode, which allows you to use some ACF keywords in the IDL file. With this MIDL compiler switch, you can omit the ACF and specify an interface in a single IDL file. False
char string The /char switch helps to ensure that the MIDL compiler and C compiler operate together correctly for all char and small types. False
client string The /client switch directs the MIDL compiler to generate client-side C source files for an RPC interface False
cstub string The /cstub switch specifies the name of the client stub file for an RPC interface. False
dlldata file Specifies the file name for the generated dlldata file for a proxy DLL. The default file name Dlldata.c is used if dlldata is not specified. False
env string The /env switch selects the environment in which the application runs. False
header file Specifies the name of the header file. False
iid file Specifies the name of the interface identifier file for a COM interface, overriding the default name obtained by adding _i.c to the IDL file name. False
Oi string The /Oi switch directs the MIDL compiler to use a fully-interpreted marshaling method. The /Oic and /Oicf switches provide additional performance enhancements. False
proxy file Specifies the name of the interface proxy file for a COM interface. False
tlb file Specifies a file name for the type library generated by the MIDL compiler. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
timeout int The maximum amount of time the application is allowed to execute, expressed in milliseconds. Defaults to no time-out. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Framework-configurable parameters

Attribute Type Description Required
exename string The name of the executable that should be used to launch the external program. False
managed ManagedExecution Specifies whether the external program should be treated as a managed application, possibly forcing it to be executed under the currently targeted version of the CLR. False
useruntimeengine bool Deprecated. Specifies whether the external program is a managed application which should be executed using a runtime engine, if configured. The default is false. False

Nested Elements:

<options>

Additional options to pass to midl.exe.
<option>

Represents an option.

Parameters

AttributeTypeDescriptionRequired
namestring Name of the option. True
ifbool Indicates if the option should be passed to the task. If true then the option will be passed; otherwise, skipped. The default is true. False
unlessbool Indicates if the option should not be passed to the task. If false then the option will be passed; otherwise, skipped. The default is false. False
valuestring Value of the option. The default is a null reference (Nothing in Visual Basic). False
</option>

</options>

<defines>

Macro definitions to pass to mdil.exe. Each entry will generate a /D
<define>

Represents an option.

Parameters

AttributeTypeDescriptionRequired
namestring Name of the option. True
ifbool Indicates if the option should be passed to the task. If true then the option will be passed; otherwise, skipped. The default is true. False
unlessbool Indicates if the option should not be passed to the task. If false then the option will be passed; otherwise, skipped. The default is false. False
valuestring Value of the option. The default is a null reference (Nothing in Visual Basic). False
</define>

</defines>

<undefines>

Macro undefines (/U) to pass to mdil.
<undefine>

Represents an option.

Parameters

AttributeTypeDescriptionRequired
namestring Name of the option. True
ifbool Indicates if the option should be passed to the task. If true then the option will be passed; otherwise, skipped. The default is true. False
unlessbool Indicates if the option should not be passed to the task. If false then the option will be passed; otherwise, skipped. The default is false. False
valuestring Value of the option. The default is a null reference (Nothing in Visual Basic). False
</undefine>

</undefines>

<includedirs>

The list of directories in which to search for include files.

</includedirs>

<arg>

The command-line arguments for the external program.

Represents a command-line argument.

When passed to an external application, the argument will be quoted when appropriate. This does not apply to the line parameter, which is always passed as is.

Parameters

AttributeTypeDescriptionRequired
dirdirectory The value for a directory-based command-line argument; will be replaced with the absolute path of the directory. False
filefile The name of a file as a single command-line argument; will be replaced with the absolute filename of the file. False
ifbool Indicates if the argument should be passed to the external program. If true then the argument will be passed; otherwise, skipped. The default is true. False
linestring List of command-line arguments; will be passed to the executable as is. False
path<path> The value for a PATH-like command-line argument; you can use : or ; as path separators and NAnt will convert it to the platform's local conventions, while resolving references to environment variables. False
unlessbool Indicates if the argument should not be passed to the external program. If false then the argument will be passed; otherwise, skipped. The default is false. False
valuestring A single command-line argument; can contain space characters. False

Nested Elements:

<path>

Sets a single command-line argument and treats it like a PATH - ensures the right separator for the local platform is used.

</path>

Examples

  • A single command-line argument containing a space character.

    <arg value="-l -a" />
        
  • Two separate command-line arguments.

    <arg line="-l -a" />
        
  • A single command-line argument with the value \dir;\dir2;\dir3 on DOS-based systems and /dir:/dir2:/dir3 on Unix-like systems.

    <arg path="/dir;/dir2:\dir3" />
        

</arg>

Examples

  • <midl
        env="win32"
        Oi="cf"
        tlb="${outputdir}\TempAtl.tlb"
        header="${outputdir}\TempAtl.h"
        iid="${outputdir}\TempAtl_i.c"
        proxy="${outputdir}\TempAtl_p.c"
        filename="TempAtl.idl"
    >
        <defines>
            <define name="_DEBUG"/>
            <define name="WIN32" value="1"/>
        </defines>
        <options>
            <option name="/mktyplib203"/>
            <option name="/error" value="allocation"/>
        </options>
    </midl>
        

Requirements

Assembly: NAnt.VisualCppTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/servicecontroller.html0000644000175000017500000001116011757307523022306 0ustar jtaylorjtaylor <servicecontroller> Task

<servicecontroller>

[This is preliminary documentation and subject to change.]

Allows a Windows service to be controlled.

Parameters

Attribute Type Description Required
action ActionType The action that should be performed on the service. True
service string The name of the service that should be controlled. True
machine string The name of the computer on which the service resides. The default is the local computer. False
timeout double The time, in milliseconds, the task will wait for the service to reach the desired status. The default is 5000 milliseconds. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Examples

  • Starts the World Wide Web Publishing Service on the local computer.

    <servicecontroller action="Start" service="w3svc" />
        
  • Stops the Alerter service on computer 'MOTHER'.

    <servicecontroller action="Stop" service="Alerter" machine="MOTHER" />
        

Requirements

Assembly: NAnt.MSNetTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/mkdir.html0000644000175000017500000000677511757307446017674 0ustar jtaylorjtaylor <mkdir> Task

<mkdir>

[This is preliminary documentation and subject to change.]

Creates a directory and any non-existent parent directory if necessary.

Parameters

Attribute Type Description Required
dir directory The directory to create. True
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Examples

  • Create the directory build.

    <mkdir dir="build" />
        
  • Create the directory tree one/two/three.

    <mkdir dir="one/two/three" />
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/xmlpeek.html0000644000175000017500000001576411757307457020233 0ustar jtaylorjtaylor <xmlpeek> Task

<xmlpeek>

[This is preliminary documentation and subject to change.]

Extracts text from an XML file at the location specified by an XPath expression.

If the XPath expression specifies multiple nodes the node index is used to determine which of the nodes' text is returned.

Parameters

Attribute Type Description Required
file file The name of the file that contains the XML document that is going to be peeked at. True
property string The property that receives the text representation of the XML inside the node returned from the XPath expression. True
xpath string The XPath expression used to select which node to read. True
nodeindex int The index of the node that gets its text returned when the query returns multiple nodes. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Nested Elements:

<namespaces>

Namespace definitions to resolve prefixes in the XPath expression.
<namespace>

Represents an XML namespace.

Parameters

AttributeTypeDescriptionRequired
prefixstring The prefix to associate with the namespace. True
uristring The associated XML namespace URI. True
ifbool Indicates if the namespace should be added to the XmlNamespaceManager. If true then the namespace will be added; otherwise, skipped. The default is true. False
unlessbool Indicates if the namespace should not be added to the XmlNamespaceManager. list. If false then the parameter will be added; otherwise, skipped. The default is false. False
</namespace>

</namespaces>

Examples

  • The example provided assumes that the following XML file (App.config) exists in the current build directory.

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration xmlns="http://www.gordic.cz/shared/project-config/v_1.0.0.0">
        <appSettings>
            <add key="server" value="testhost.somecompany.com" />
        </appSettings>
    </configuration>
        
  • The example will read the server value from the above configuration file.

    <xmlpeek
        file="App.config"
        xpath="/x:configuration/x:appSettings/x:add[@key = 'server']/@value"
        property="configuration.server">
        <namespaces>
            <namespace prefix="x" uri="http://www.gordic.cz/shared/project-config/v_1.0.0.0" />
        </namespaces>
    </xmlpeek>
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/cvs-rtag.html0000644000175000017500000004137311757307543020303 0ustar jtaylorjtaylor <cvs-rtag> Task

<cvs-rtag>

[This is preliminary documentation and subject to change.]

Tags all sources in the remote repository with a given tag.

Unlike tag, the rtag command acts only on sources that are in the repository. Any modified sources on the local file system will NOT be tagged with this command, so a commit should be performed before an rtag is done.

NOTE: Although a working directory is not necessary to perform the command one must be specified in order to remain in compliance with the cvs library.

Parameters

Attribute Type Description Required
tag string The name of the tag to assign or remove. True
act-on-date datetime Indicates the revision date of the file that the tag should be applied to. False
act-on-tag string Indicates the repository tag that is acted on for the tag command. Note if move-if-exists is true then the tag specified is moved to the revision of the file on the HEAD of the branch specified. False
force-head bool Indicates whether the head revision should be used if the act-on-tag or the act-on-date tags are not found. False
move-if-exists bool Indicates whether the tag specified in tag should be moved to the current file revision. If the tag does not exist then it is created. False
recursive bool If a directory is specified indicates whether sub-directories should also be processed. False
remove bool Indicates whether the tag specified in tag should be removed or not. False
commandline string Command-line arguments for the program. The command line arguments are used to specify any cvs command options that are not available as attributes. These are appended after the command itself and are additive to whatever attributes are currently specified. False
compressionlevel int Compression level to use for all net traffic. This should be a value from 1-9.



NOTE: This is not available on sharpcvslib.
False
cvsfullpath file The full path to the cvs binary used. The cvs tasks will attempt to "guess" the location of your cvs binary based on your path. If the task is unable to resolve the location, or resolves it incorrectly this can be used to manually specify the path. False
cvsroot string

The cvs root variable has the following components:

[protocol]:[username]@[servername]:[server path]
  • protocol: ext, pserver, ssh (sharpcvslib); if you are not using sharpcvslib consult your cvs documentation.
  • username: [username]
  • servername: cvs.sourceforge.net
  • server path: /cvsroot/nant

False
cvsrsh file The executable to use for ssh communication. False
destination directory Destination directory for the local sandbox. If destination is not specified then the current directory is used. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
module string The module to perform an operation on. False
passfile file The full path to the cached password file. If not specified then the environment variables are used to try and locate the file. False
password string Deprecated. The password for logging in to the repository. False
quiet bool Indicates if the output from the cvs command should be supressed. The default is false. False
readonly bool true if the sandbox files should be checked out in read only mode. The default is false. False
readwrite bool true if the sandbox files should be checked out in read/write mode. The default is true. False
reallyquiet bool Indicates if the output from the cvs command should be stopped. The default is false. False
timeout int The maximum amount of time the application is allowed to execute, expressed in milliseconds. Defaults to no time-out. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
usesharpcvslib bool

true if the SharpCvsLib binaries that come bundled with NAnt should be used to perform the cvs commands, false otherwise.

You may also specify an override value for all cvs tasks instead of specifying a value for each. To do this set the property sourcecontrol.usesharpcvslib to false.

If you choose not to use SharpCvsLib to checkout from cvs you will need to include a cvs.exe binary in your path.
False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Framework-configurable parameters

Attribute Type Description Required
managed ManagedExecution Specifies whether the external program should be treated as a managed application, possibly forcing it to be executed under the currently targeted version of the CLR. False
useruntimeengine bool Deprecated. Specifies whether the external program is a managed application which should be executed using a runtime engine, if configured. The default is false. False

Nested Elements:

<fileset>

Used to specify the version control system (VCS) files that are going to be acted on.

</fileset>

<arg>

The command-line arguments for the external program.

Represents a command-line argument.

When passed to an external application, the argument will be quoted when appropriate. This does not apply to the line parameter, which is always passed as is.

Parameters

AttributeTypeDescriptionRequired
dirdirectory The value for a directory-based command-line argument; will be replaced with the absolute path of the directory. False
filefile The name of a file as a single command-line argument; will be replaced with the absolute filename of the file. False
ifbool Indicates if the argument should be passed to the external program. If true then the argument will be passed; otherwise, skipped. The default is true. False
linestring List of command-line arguments; will be passed to the executable as is. False
path<path> The value for a PATH-like command-line argument; you can use : or ; as path separators and NAnt will convert it to the platform's local conventions, while resolving references to environment variables. False
unlessbool Indicates if the argument should not be passed to the external program. If false then the argument will be passed; otherwise, skipped. The default is false. False
valuestring A single command-line argument; can contain space characters. False

Nested Elements:

<path>

Sets a single command-line argument and treats it like a PATH - ensures the right separator for the local platform is used.

</path>

Examples

  • A single command-line argument containing a space character.

    <arg value="-l -a" />
        
  • Two separate command-line arguments.

    <arg line="-l -a" />
        
  • A single command-line argument with the value \dir;\dir2;\dir3 on DOS-based systems and /dir:/dir2:/dir3 on Unix-like systems.

    <arg path="/dir;/dir2:\dir3" />
        

</arg>

Examples

  • Tag NAnt sources remotely.

    <cvs-rtag 
        cvsroot=":pserver:anonymous@cvs.sourceforge.net:/cvsroot/nant" 
        destination="."
        tag="v0_8_4"
         />
        
  • Remove a tag from the remote repository.

    <cvs-rtag 
        cvsroot=":pserver:anonymous@cvs.sourceforge.net:/cvsroot/nant" 
        destination="."
        tag="v0_8_4"
        remove="true"
         />
        

Requirements

Assembly: NAnt.SourceControlTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/echo.html0000644000175000017500000001450111757307434017463 0ustar jtaylorjtaylor <echo> Task

<echo>

[This is preliminary documentation and subject to change.]

Writes a message to the build log or a specified file.

The message can be specified using the message attribute or as inline content. If neither is included - or the message contains only whitespace - then an empty message will be emitted in the output.

Macros in the message will be expanded.

When writing to a file, the level attribute is ignored.

Note: Since NAnt 0.86, a newline will no longer be implictly added when writing a message to a file.

Parameters

Attribute Type Description Required
append bool Determines whether the <echo> task should append to the file, or overwrite it. By default, the file will be overwritten. False
encoding Encoding The encoding to use when writing message to a file. The default is UTF-8 encoding without a Byte Order Mark (BOM). False
file file The file to write the message to. False
level Level The logging level with which the message should be output. The default is Info. False
message string The message to output. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Examples

  • Writes a message with level Debug to the build log.

    <echo message="Hello, World!" level="Debug" />
        
  • Writes a two-line message to the build log using inline content.

    <echo>First line
    Second line</echo>
        
  • Writes a two-line message to the build log using the message attribute.

    <echo message='First line
    Second line</echo>
        
  • Writes a message with expanded macro to the build log.

    <echo message="Base build directory = ${nant.project.basedir}" />
        
  • Functionally equivalent to the previous example.

    <echo>Base build directory = ${nant.project.basedir}</echo>
        
  • Writes the previous message to a file in the project directory, overwriting the file if it exists.

    <echo file="buildmessage.txt">Base build directory = ${nant.project.basedir}</echo>
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/readregistry.html0000644000175000017500000001170311757307561021253 0ustar jtaylorjtaylor <readregistry> Task

<readregistry>

[This is preliminary documentation and subject to change.]

Reads a value or set of values from the Windows Registry into one or more NAnt properties.

Parameters

Attribute Type Description Required
key string The registry key to read, including the path. True
hive string Space separated list of registry hives to search for key. For a list of possible values, see RegistryHive. The default is LocalMachine. False
prefix string

The prefix to use for the specified registry key values.

If this attribute is used then all registry values will be read and stored as properties with this prefix.

False
property string

The property to set to the specified registry key value.

If this attribute is used then a single value will be read.

False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Examples

  • Read a single value from the registry.

    <readregistry property="sdkRoot" key="SOFTWARE\Microsoft\.NETFramework\sdkInstallRoot" hive="LocalMachine" />
        

    Read all the registry values in a key.

    <readregistry prefix="dotNetFX" key="SOFTWARE\Microsoft\.NETFramework\sdkInstallRoot" hive="LocalMachine" />
        

Requirements

Assembly: NAnt.Win32Tasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/ndoc.html0000644000175000017500000001701111757307507017470 0ustar jtaylorjtaylor <ndoc> Task

<ndoc>

[This is preliminary documentation and subject to change.]

Runs NDoc V1.3.1 to create documentation.

See the NDoc home page for more information.

Note: By default, only the NDoc MSDN documenter ships as part of the NAnt distribution. To make another NDoc documenter from the NDoc V1.3.1 distribution available to the <ndoc> task, copy the documenter assembly (and possible dependencies) to the "lib" directory corresponding with the CLR you're running NAnt on (eg. <nant root>/bin/lib/net/1.1).

Parameters

Attribute Type Description Required
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Nested Elements:

<assemblies>

The set of assemblies to document.

</assemblies>

<summaries>

The set of namespace summary files.

</summaries>

<documenters>

Specifies the formats in which the documentation should be generated.

Represents an element of which the XML is processed by its parent task or type.

</documenters>

<referencepaths>

Collection of additional directories to search for referenced assemblies.

</referencepaths>

Examples

  • Document two assemblies using the MSDN documenter. The namespaces are documented in NamespaceSummary.xml.

    <ndoc>
        <assemblies basedir="${build.dir}">
            <include name="NAnt.exe" />
            <include name="NAnt.Core.dll" />
        </assemblies>
        <summaries basedir="${build.dir}">
            <include name="NamespaceSummary.xml" />
        </summaries>
        <documenters>
            <documenter name="MSDN">
                <property name="OutputDirectory" value="doc\MSDN" />
                <property name="HtmlHelpName" value="NAnt" />
                <property name="IncludeFavorites" value="False" />
                <property name="Title" value="An NDoc Documented Class Library" />
                <property name="SplitTOCs" value="False" />
                <property name="DefaulTOC" value="" />
                <property name="ShowVisualBasic" value="True" />
                <property name="ShowMissingSummaries" value="True" />
                <property name="ShowMissingRemarks" value="True" />
                <property name="ShowMissingParams" value="True" />
                <property name="ShowMissingReturns" value="True" />
                <property name="ShowMissingValues" value="True" />
                <property name="DocumentInternals" value="False" />
                <property name="DocumentProtected" value="True" />
                <property name="DocumentPrivates" value="False" />
                <property name="DocumentEmptyNamespaces" value="False" />
                <property name="IncludeAssemblyVersion" value="False" />
                <property name="CopyrightText" value="" />
                <property name="CopyrightHref" value="" />
             </documenter>
        </documenters> 
    </ndoc>
        

    Content of NamespaceSummary.xml :

    <namespaces>
        <namespace name="Foo.Bar">
            The <b>Foo.Bar</b> namespace reinvents the wheel.
        </namespace>
        <namespace name="Foo.Bar.Tests">
            The <b>Foo.Bar.Tests</b> namespace ensures that the Foo.Bar namespace reinvents the wheel correctly.
        </namespace>
    </namespaces>
        

Requirements

Assembly: NAnt.DotNetTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/cvs-changelog.html0000644000175000017500000003455011757307533021273 0ustar jtaylorjtaylor <cvs-changelog> Task

<cvs-changelog>

[This is preliminary documentation and subject to change.]

Produces an XML report that represents the cvs changes from the given start day, to a given end date.

Parameters

Attribute Type Description Required
end datetime The latest date to use in the cvs log command. True
start datetime The earliest change to use in the cvs log command. True
xmlfile file Name of the xml file that will contain the cvs log information. True
cvsroot string

The cvs root variable has the following components:

[protocol]:[username]@[servername]:[server path]
  • protocol: ext, pserver, ssh (sharpcvslib); if you are not using sharpcvslib consult your cvs documentation.
  • username: [username]
  • servername: cvs.sourceforge.net
  • server path: /cvsroot/nant

If the cvsroot is not specified then the directory specified by the destination attribute is searched for CVS\Root.

False
commandline string Command-line arguments for the program. The command line arguments are used to specify any cvs command options that are not available as attributes. These are appended after the command itself and are additive to whatever attributes are currently specified. False
compressionlevel int Compression level to use for all net traffic. This should be a value from 1-9.



NOTE: This is not available on sharpcvslib.
False
cvsfullpath file The full path to the cvs binary used. The cvs tasks will attempt to "guess" the location of your cvs binary based on your path. If the task is unable to resolve the location, or resolves it incorrectly this can be used to manually specify the path. False
cvsrsh file The executable to use for ssh communication. False
destination directory Destination directory for the local sandbox. If destination is not specified then the current directory is used. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
module string The module to perform an operation on. False
passfile file The full path to the cached password file. If not specified then the environment variables are used to try and locate the file. False
password string Deprecated. The password for logging in to the repository. False
quiet bool Indicates if the output from the cvs command should be supressed. The default is false. False
readonly bool true if the sandbox files should be checked out in read only mode. The default is false. False
readwrite bool true if the sandbox files should be checked out in read/write mode. The default is true. False
reallyquiet bool Indicates if the output from the cvs command should be stopped. The default is false. False
timeout int The maximum amount of time the application is allowed to execute, expressed in milliseconds. Defaults to no time-out. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Framework-configurable parameters

Attribute Type Description Required
managed ManagedExecution Specifies whether the external program should be treated as a managed application, possibly forcing it to be executed under the currently targeted version of the CLR. False
useruntimeengine bool Deprecated. Specifies whether the external program is a managed application which should be executed using a runtime engine, if configured. The default is false. False

Nested Elements:

<fileset>

Used to specify the version control system (VCS) files that are going to be acted on.

</fileset>

<arg>

The command-line arguments for the external program.

Represents a command-line argument.

When passed to an external application, the argument will be quoted when appropriate. This does not apply to the line parameter, which is always passed as is.

Parameters

AttributeTypeDescriptionRequired
dirdirectory The value for a directory-based command-line argument; will be replaced with the absolute path of the directory. False
filefile The name of a file as a single command-line argument; will be replaced with the absolute filename of the file. False
ifbool Indicates if the argument should be passed to the external program. If true then the argument will be passed; otherwise, skipped. The default is true. False
linestring List of command-line arguments; will be passed to the executable as is. False
path<path> The value for a PATH-like command-line argument; you can use : or ; as path separators and NAnt will convert it to the platform's local conventions, while resolving references to environment variables. False
unlessbool Indicates if the argument should not be passed to the external program. If false then the argument will be passed; otherwise, skipped. The default is false. False
valuestring A single command-line argument; can contain space characters. False

Nested Elements:

<path>

Sets a single command-line argument and treats it like a PATH - ensures the right separator for the local platform is used.

</path>

Examples

  • A single command-line argument containing a space character.

    <arg value="-l -a" />
        
  • Two separate command-line arguments.

    <arg line="-l -a" />
        
  • A single command-line argument with the value \dir;\dir2;\dir3 on DOS-based systems and /dir:/dir2:/dir3 on Unix-like systems.

    <arg path="/dir;/dir2:\dir3" />
        

</arg>

Examples

  • Report changes in NAnt from 1st of June 2004 until 25th of July 2004.

    <cvs-changelog
        destination="e:/test/nant/sourcecontrol/"
        cvsroot=":pserver:anonymous@cvs.sourceforge.net:/cvsroot/nant"
        module="nant"
        start="2004/06/01"
        end="2004/07/25"
        xmlfile="e:/test/nant/sourcecontrol/changelog-nant.xml"
    />
        

Requirements

Assembly: NAnt.SourceControlTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/license.html0000644000175000017500000001634211757307506020174 0ustar jtaylorjtaylor <license> Task

<license>

[This is preliminary documentation and subject to change.]

Generates a .licence file from a .licx file.

If no output file is specified, the default filename is the name of the target file with the extension .licenses appended.

Parameters

Attribute Type Description Required
input file Input file to process. True
licensetarget string Deprecated. Specifies the executable for which the .licenses file is generated. False
output file Name of the license file to output. False
target string Specifies the executable for which the .licenses file is generated. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
timeout int The maximum amount of time the application is allowed to execute, expressed in milliseconds. Defaults to no time-out. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Framework-configurable parameters

Attribute Type Description Required
exename string The name of the executable that should be used to launch the external program. False
hascommandlinecompiler bool Indicates whether the current target framework has a command line tool for compiling licenses files. The default is true. False
managed ManagedExecution Specifies whether the external program should be treated as a managed application, possibly forcing it to be executed under the currently targeted version of the CLR. False
supportsassemblyreferences bool Indicates whether assembly references are supported by the current target framework. The default is false. False
useruntimeengine bool Deprecated. Specifies whether the external program is a managed application which should be executed using a runtime engine, if configured. The default is false. False

Nested Elements:

<assemblies>

Names of the references to scan for the licensed component.

</assemblies>

Examples

  • Generate the file component.exe.licenses file from component.licx.

    <license input="component.licx" licensetarget="component.exe" />
        

Requirements

Assembly: NAnt.DotNetTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/regex.html0000644000175000017500000001277611757307451017672 0ustar jtaylorjtaylor <regex> Task

<regex>

[This is preliminary documentation and subject to change.]

Sets project properties based on the evaluatuion of a regular expression.

The pattern attribute must contain one or more named grouping constructs, which represents the names of the properties to be set. These named grouping constructs can be enclosed by angle brackets (?<name>) or single quotes (?'name').

Note: In the build file, use the XML element &lt; to specify <, and &gt; to specify >.

Note: The named grouping construct must not contain any punctuation and it cannot begin with a number.

Parameters

Attribute Type Description Required
input string Represents the input for the regular expression. True
pattern string Represents the regular expression to be evalued. True
options RegexOptions A comma separated list of options to pass to the regex engine. The default is None. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Examples

  • Find the last word in the given string and stores it in the property lastword.

    <regex pattern="(?'lastword'\w+)$" input="This is a test sentence" />
    <echo message="${lastword}" />
        
  • Split the full filename and extension of a filename.

    <regex pattern="^(?'filename'.*)\.(?'extension'\w+)$" input="d:\Temp\SomeDir\SomeDir\bla.xml" />
        
  • Split the path and the filename. (This checks for / or \ as the path separator).

    <regex pattern="^(?'path'.*(\\|/)|(/|\\))(?'file'.*)$" input="d:\Temp\SomeDir\SomeDir\bla.xml" />
        

    Results in path=d:\Temp\SomeDir\SomeDir\ and file=bla.xml.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/resgen.html0000644000175000017500000002742111757307511020031 0ustar jtaylorjtaylor <resgen> Task

<resgen>

[This is preliminary documentation and subject to change.]

Converts files from one resource format to another.

Note: If no todir is specified, the resource file will be created next to the input file.

Parameters

Attribute Type Description Required
input file Input file to process. False
output file The resource file to output. False
target string The target type. The default is resources. False
todir directory The directory to which outputs will be stored. False
usesourcepath bool Use each source file's directory as the current directory for resolving relative file paths. The default is false. Only supported when targeting .NET 2.0 (or higher). False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
timeout int The maximum amount of time the application is allowed to execute, expressed in milliseconds. Defaults to no time-out. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Framework-configurable parameters

Attribute Type Description Required
exename string The name of the executable that should be used to launch the external program. False
managed ManagedExecution Specifies whether the external program should be treated as a managed application, possibly forcing it to be executed under the currently targeted version of the CLR. False
supportsassemblyreferences bool Indicates whether assembly references are supported by the resgen tool for the current target framework. The default is false. False
supportsexternalfilereferences bool Indicates whether external file references are supported by the resgen tool for the current target framework. The default is false. False
useruntimeengine bool Deprecated. Specifies whether the external program is a managed application which should be executed using a runtime engine, if configured. The default is false. False

Nested Elements:

<resources>

Takes a list of .resx or .txt files to convert to .resources files.

</resources>

<assemblies>

Reference metadata from the specified assembly files.

</assemblies>

<arg>

The command-line arguments for the external program.

Represents a command-line argument.

When passed to an external application, the argument will be quoted when appropriate. This does not apply to the line parameter, which is always passed as is.

Parameters

AttributeTypeDescriptionRequired
dirdirectory The value for a directory-based command-line argument; will be replaced with the absolute path of the directory. False
filefile The name of a file as a single command-line argument; will be replaced with the absolute filename of the file. False
ifbool Indicates if the argument should be passed to the external program. If true then the argument will be passed; otherwise, skipped. The default is true. False
linestring List of command-line arguments; will be passed to the executable as is. False
path<path> The value for a PATH-like command-line argument; you can use : or ; as path separators and NAnt will convert it to the platform's local conventions, while resolving references to environment variables. False
unlessbool Indicates if the argument should not be passed to the external program. If false then the argument will be passed; otherwise, skipped. The default is false. False
valuestring A single command-line argument; can contain space characters. False

Nested Elements:

<path>

Sets a single command-line argument and treats it like a PATH - ensures the right separator for the local platform is used.

</path>

Examples

  • A single command-line argument containing a space character.

    <arg value="-l -a" />
        
  • Two separate command-line arguments.

    <arg line="-l -a" />
        
  • A single command-line argument with the value \dir;\dir2;\dir3 on DOS-based systems and /dir:/dir2:/dir3 on Unix-like systems.

    <arg path="/dir;/dir2:\dir3" />
        

</arg>

Examples

  • Convert a resource file from the .resx to the .resources format.

    <resgen input="translations.resx" output="translations.resources" />
        
  • Convert a set of .resx files to the .resources format.

    <resgen todir=".">
        <resources>
            <include name="*.resx" />
        </resources>
    </resgen>
        

Requirements

Assembly: NAnt.DotNetTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/nunit.html0000644000175000017500000002126111757307524017703 0ustar jtaylorjtaylor <nunit> Task

<nunit>

[This is preliminary documentation and subject to change.]

(Deprecated)

Runs tests using the NUnit V1.0 framework.

See the NUnit home page for more information.

The haltonfailure or haltonerror attributes are only used to stop more than one test suite to stop running. If any test suite fails a build error will be thrown. Set failonerror to false to ignore test errors and continue build.

Parameters

Attribute Type Description Required
haltonerror bool Stops running tests when a test causes an error. The default is false. False
haltonfailure bool Stops running tests if a test fails (errors are considered failures as well). The default is false. False
timeout int Cancel the individual tests if they do not finish in the specified time (measured in milliseconds). Ignored if fork is disabled. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Nested Elements:

<test>

Tests to run.

Represents a test element of an <nunit> task.

Parameters

AttributeTypeDescriptionRequired
assemblystring Assembly to load the test from. True
classstring Class name of the test. True
appconfigstring The application configuration file to use for the NUnit test domain. False
forkbool Run the tests in a separate AppDomain. False
haltonerrorbool Stop the build process if an error occurs during the test run. False
haltonfailurebool Stop the build process if a test fails (errors are considered failures as well). False
outfilestring Base name of the test result. The full filename is determined by this attribute and the extension of formatter. False
todirstring Directory to write the reports to. False

</test>

<formatter>

Formatters to output results of unit tests.

Represents the FormatterElement of the NUnit task.

Parameters

AttributeTypeDescriptionRequired
typeFormatterType Type of formatter. True
extensionstring Extension to append to the output filename. False
outputdirdirectory Specifies the directory where the output file should be written to, if usefile is true. If not specified, the output file will be written to the directory where the test module is located. False
usefilebool Determines whether output should be persisted to a file. The default is false. False

</formatter>

Examples

  • Run tests in the MyProject.Tests.dll assembly.

    The test results are logged in results.xml and results.txt using the Xml and Plain formatters, respectively.

    <nunit basedir="build" verbose="false" haltonerror="true" haltonfailure="true">
        <formatter type="Xml" />
        <formatter type="Plain" />
        <test name="MyProject.Tests.AllTests" assembly="MyProject.Tests.dll" outfile="results"/>
    </nunit>
        

Requirements

Assembly: NAnt.NUnit1Tasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/aximp.html0000644000175000017500000002570711757307561017676 0ustar jtaylorjtaylor <aximp> Task

<aximp>

[This is preliminary documentation and subject to change.]

Generates a Windows Forms Control that wraps ActiveX Controls defined in an OCX.

Parameters

Attribute Type Description Required
ocx file Filename of the .ocx file. True
delaysign bool Specifies to sign the resulting control using delayed signing. False
generatesource bool Determines whether C# source code for the Windows Form wrapper should be generated. The default is false. False
keycontainer string Specifies the key container in which the public/private key pair should be found that should be used to sign the resulting assembly with a strong name. False
keyfile file Specifies the publisher's official public/private key pair with which the resulting assembly should be signed with a strong name. False
output file Filename of the generated assembly. False
publickey file Specifies the file containing the public key to use to sign the resulting assembly. False
rcw file Assembly to use for Runtime Callable Wrapper rather than generating new one [.NET 1.1 or higher]. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
timeout int The maximum amount of time the application is allowed to execute, expressed in milliseconds. Defaults to no time-out. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Framework-configurable parameters

Attribute Type Description Required
exename string The name of the executable that should be used to launch the external program. False
managed ManagedExecution Specifies whether the external program should be treated as a managed application, possibly forcing it to be executed under the currently targeted version of the CLR. False
supportsrcw bool Indicates whether aximp supports using an existing Runtime Callable Wrapper for a given target framework. The default is true. False
useruntimeengine bool Deprecated. Specifies whether the external program is a managed application which should be executed using a runtime engine, if configured. The default is false. False

Nested Elements:

<arg>

The command-line arguments for the external program.

Represents a command-line argument.

When passed to an external application, the argument will be quoted when appropriate. This does not apply to the line parameter, which is always passed as is.

Parameters

AttributeTypeDescriptionRequired
dirdirectory The value for a directory-based command-line argument; will be replaced with the absolute path of the directory. False
filefile The name of a file as a single command-line argument; will be replaced with the absolute filename of the file. False
ifbool Indicates if the argument should be passed to the external program. If true then the argument will be passed; otherwise, skipped. The default is true. False
linestring List of command-line arguments; will be passed to the executable as is. False
path<path> The value for a PATH-like command-line argument; you can use : or ; as path separators and NAnt will convert it to the platform's local conventions, while resolving references to environment variables. False
unlessbool Indicates if the argument should not be passed to the external program. If false then the argument will be passed; otherwise, skipped. The default is false. False
valuestring A single command-line argument; can contain space characters. False

Nested Elements:

<path>

Sets a single command-line argument and treats it like a PATH - ensures the right separator for the local platform is used.

</path>

Examples

  • A single command-line argument containing a space character.

    <arg value="-l -a" />
        
  • Two separate command-line arguments.

    <arg line="-l -a" />
        
  • A single command-line argument with the value \dir;\dir2;\dir3 on DOS-based systems and /dir:/dir2:/dir3 on Unix-like systems.

    <arg path="/dir;/dir2:\dir3" />
        

</arg>

Examples

  • <aximp ocx="MyControl.ocx" output="MyFormsControl.dll" />
        

Requirements

Assembly: NAnt.Win32Tasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/regasm.html0000644000175000017500000002725611757307562020040 0ustar jtaylorjtaylor <regasm> Task

<regasm>

[This is preliminary documentation and subject to change.]

Registers an assembly, or set of assemblies for use from COM clients.

Refer to the Regasm documentation for more information on the regasm tool.

Parameters

Attribute Type Description Required
assembly file The name of the file to register. This is provided as an alternate to using the task's assemblies. False
codebase bool Set the code base registry setting. False
regfile file Registry file to export to instead of entering the types directly into the registry. False
registered bool Only refer to already registered type libraries. False
typelib file Export the assemblies to the specified type library and register it. False
unregister bool Unregister the assembly. The default is false. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
timeout int The maximum amount of time the application is allowed to execute, expressed in milliseconds. Defaults to no time-out. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Framework-configurable parameters

Attribute Type Description Required
exename string The name of the executable that should be used to launch the external program. False
managed ManagedExecution Specifies whether the external program should be treated as a managed application, possibly forcing it to be executed under the currently targeted version of the CLR. False
useruntimeengine bool Deprecated. Specifies whether the external program is a managed application which should be executed using a runtime engine, if configured. The default is false. False

Nested Elements:

<assemblies>

The set of assemblies to register, or unregister.

</assemblies>

<references>

The set of assembly references.

</references>

<arg>

The command-line arguments for the external program.

Represents a command-line argument.

When passed to an external application, the argument will be quoted when appropriate. This does not apply to the line parameter, which is always passed as is.

Parameters

AttributeTypeDescriptionRequired
dirdirectory The value for a directory-based command-line argument; will be replaced with the absolute path of the directory. False
filefile The name of a file as a single command-line argument; will be replaced with the absolute filename of the file. False
ifbool Indicates if the argument should be passed to the external program. If true then the argument will be passed; otherwise, skipped. The default is true. False
linestring List of command-line arguments; will be passed to the executable as is. False
path<path> The value for a PATH-like command-line argument; you can use : or ; as path separators and NAnt will convert it to the platform's local conventions, while resolving references to environment variables. False
unlessbool Indicates if the argument should not be passed to the external program. If false then the argument will be passed; otherwise, skipped. The default is false. False
valuestring A single command-line argument; can contain space characters. False

Nested Elements:

<path>

Sets a single command-line argument and treats it like a PATH - ensures the right separator for the local platform is used.

</path>

Examples

  • A single command-line argument containing a space character.

    <arg value="-l -a" />
        
  • Two separate command-line arguments.

    <arg line="-l -a" />
        
  • A single command-line argument with the value \dir;\dir2;\dir3 on DOS-based systems and /dir:/dir2:/dir3 on Unix-like systems.

    <arg path="/dir;/dir2:\dir3" />
        

</arg>

Examples

  • Register types in a single assembly.

    <regasm assembly="myAssembly.dll" />
        
  • Register types of an assembly and generate a type library containing definitions of accessible types defined within the assembly.

    <regasm assembly="myAssembly.dll" typelib="myAssembly.tlb" />
        
  • Register types of set of assemblies at once, while specifying a set of reference assemblies.

    <regasm codebase="true">
        <assemblies>
            <include name="OutlookAddin.dll" />
            <include name="OfficeCoreAddin.dll" />
        </assemblies>
        <references>
            <include name="CommonTypes.dll" />
        </references>
    </regasm>
        

Requirements

Assembly: NAnt.Win32Tasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/loadtasks.html0000644000175000017500000001117311757307444020535 0ustar jtaylorjtaylor <loadtasks> Task

<loadtasks>

[This is preliminary documentation and subject to change.]

Loads tasks form a given assembly or all assemblies in a given directory or <fileset>.

Parameters

Attribute Type Description Required
assembly file An assembly to load tasks from. False
path directory A directory to scan for task assemblies. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Nested Elements:

<fileset>

Used to select which directories or individual assemblies to scan.

</fileset>

Examples

  • Load tasks from a single assembly.

    <loadtasks assembly="c:foo\NAnt.Contrib.Tasks.dll" />
        
  • Scan a single directory for task assemblies.

    <loadtasks path="c:\foo" />
        
  • Use a fileset containing both a directory and an assembly.

     <loadtasks>
        <fileset>
            <include name="C:\cvs\NAntContrib\build" />
            <include name="C:\cvs\NAntContrib\build\NAnt.Contrib.Tasks.dll" />
        </fileset>
    </loadtasks>
         

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/nantschema.html0000644000175000017500000001034211757307450020663 0ustar jtaylorjtaylor <nantschema> Task

<nantschema>

[This is preliminary documentation and subject to change.]

Creates an XSD File for all available tasks.

This can be used in conjuntion with the command-line option to do XSD Schema validation on the build file.

Parameters

Attribute Type Description Required
output file The name of the output file to which the XSD should be written. True
class string The Type for which an XSD should be created. If not specified, an XSD will be created for all available tasks. False
target-ns string The target namespace for the output. Defaults to "http://tempuri.org/nant-donotuse.xsd" False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Examples

  • Creates a NAnt.xsd file in the current project directory.

    <nantschema output="NAnt.xsd" />
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/get.html0000644000175000017500000001665411757307441017335 0ustar jtaylorjtaylor <get> Task

<get>

[This is preliminary documentation and subject to change.]

Gets a particular file from a URL source.

Options include verbose reporting and timestamp based fetches.

Currently, only HTTP and UNC protocols are supported. FTP support may be added when more pluggable protocols are added to the System.Net assembly.

The usetimestamp option enables you to control downloads so that the remote file is only fetched if newer than the local copy. If there is no local copy, the download always takes place. When a file is downloaded, the timestamp of the downloaded file is set to the remote timestamp.

Note: This timestamp facility only works on downloads using the HTTP protocol.

Parameters

Attribute Type Description Required
dest file The file where to store the retrieved file. True
src string The URL from which to retrieve a file. True
httpproxy string Deprecated. If inside a firewall, proxy server/port information Format: {proxy server name}:{port number} Example: proxy.mycompany.com:8080 False
ignoreerrors bool Deprecated. Log errors but don't treat as fatal. The default is false. False
timeout int The length of time, in milliseconds, until the request times out. The default is 100000 milliseconds. False
usetimestamp bool Conditionally download a file based on the timestamp of the local copy. HTTP only. The default is false. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Nested Elements:

<proxy>

The network proxy to use to access the Internet resource.

</proxy>

<credentials>

The network credentials used for authenticating the request with the Internet resource.

</credentials>

<certificates>

The security certificates to associate with the request.

</certificates>

Examples

  • Gets the index page of the NAnt home page, and stores it in the file help/index.html relative to the project base directory.

    <get src="http://nant.sourceforge.org/" dest="help/index.html" />
        
  • Gets the index page of a secured web site using the given credentials, while connecting using the specified password-protected proxy server.

    <get src="http://password.protected.site/index.html" dest="secure/index.html">
        <credentials username="user" password="guess" domain="mydomain" />
        <proxy host="proxy.company.com" port="8080">
            <credentials username="proxyuser" password="dunno" />
        </proxy>
    </get>
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/jsc.html0000644000175000017500000004222011757307506017323 0ustar jtaylorjtaylor <jsc> Task

<jsc>

[This is preliminary documentation and subject to change.]

Compiles JScript.NET programs.

Parameters

Attribute Type Description Required
autoref bool Automatically references assemblies if they have the same name as an imported namespace or as a type annotation when declaring a variable. The default is false. False
codepage string Specifies the code page to use for all source code files in the compilation. False
nostdlib bool Instructs the compiler not to import standard library, and changes autoref to false. The default is false. False
platform string Specifies which platform version of common language runtime (CLR) can run the output file. False
versionsafe bool Causes the compiler to generate errors for implicit method overrides. The default is false. False
warninglevel string Specifies the warning level for the compiler to display. Valid values are 0-4. The default is 4. False
output file The output file created by the compiler. True
target string Output type. Possible values are exe, winexe, library or module. True
debug bool Generate debug output. The default is false. False
define string Define conditional compilation symbol(s). False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
main string Specifies which type contains the Main method that you want to use as the entry point into the program. False
rebuild bool Instructs NAnt to recompile the output file regardless of the file timestamps. False
timeout int The maximum amount of time the application is allowed to execute, expressed in milliseconds. Defaults to no time-out. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False
warnaserror bool Instructs the compiler to treat all warnings as errors. The default is false. False
win32icon file Icon to associate with the application. False
win32res file Specifies a Win32 resource file (.res). False

Framework-configurable parameters

Attribute Type Description Required
exename string The name of the executable that should be used to launch the external program. False
managed ManagedExecution Specifies whether the external program should be treated as a managed application, possibly forcing it to be executed under the currently targeted version of the CLR. False
supportsnowarnlist bool Indicates whether the compiler for a given target framework supports a command line option that allows a list of warnings to be suppressed. The default is false. False
supportspackagereferences bool Indicates whether package references are supported by compiler for a given target framework. The default is false. False
supportsplatform bool Specifies whether the compiler for the active target framework supports limiting the platform on which the compiled code can run. The default is false. False
supportswarnaserrorlist bool Indicates whether the compiler for a given target framework supports the "warnaserror" option that takes a list of warnings. The default is false. False
useruntimeengine bool Deprecated. Specifies whether the external program is a managed application which should be executed using a runtime engine, if configured. The default is false. False

Nested Elements:

<lib>

Deprecated. Additional directories to search in for assembly references.

</lib>

<references>

Reference metadata from the specified assembly files.

</references>

<pkg-references>

Specifies list of packages to reference.
<package>

Represents a package.

Parameters

AttributeTypeDescriptionRequired
namestring Name of the package to reference. Multiple package can be specified with a single element as a semi-colon separated list of package names. True
ifbool Indicates if the package should be passed to the task. If true then the package will be passed; otherwise, skipped. The default is true. False
unlessbool Indicates if the package should not be passed to the task. If false then the package will be passed; otherwise, skipped. The default is false. False
</package>

</pkg-references>

<resources>

Resources to embed.

</resources>

<sources>

The set of source files for compilation.

</sources>

<arg>

The command-line arguments for the external program.

Represents a command-line argument.

When passed to an external application, the argument will be quoted when appropriate. This does not apply to the line parameter, which is always passed as is.

Parameters

AttributeTypeDescriptionRequired
dirdirectory The value for a directory-based command-line argument; will be replaced with the absolute path of the directory. False
filefile The name of a file as a single command-line argument; will be replaced with the absolute filename of the file. False
ifbool Indicates if the argument should be passed to the external program. If true then the argument will be passed; otherwise, skipped. The default is true. False
linestring List of command-line arguments; will be passed to the executable as is. False
path<path> The value for a PATH-like command-line argument; you can use : or ; as path separators and NAnt will convert it to the platform's local conventions, while resolving references to environment variables. False
unlessbool Indicates if the argument should not be passed to the external program. If false then the argument will be passed; otherwise, skipped. The default is false. False
valuestring A single command-line argument; can contain space characters. False

Nested Elements:

<path>

Sets a single command-line argument and treats it like a PATH - ensures the right separator for the local platform is used.

</path>

Examples

  • A single command-line argument containing a space character.

    <arg value="-l -a" />
        
  • Two separate command-line arguments.

    <arg line="-l -a" />
        
  • A single command-line argument with the value \dir;\dir2;\dir3 on DOS-based systems and /dir:/dir2:/dir3 on Unix-like systems.

    <arg path="/dir;/dir2:\dir3" />
        

</arg>

Examples

  • Compile helloworld.js to helloworld.exe.

    <jsc target="exe" output="helloworld.exe" debug="true">
        <sources>
            <include name="helloworld.js" />
        </sources>
    </jsc>
        

Requirements

Assembly: NAnt.DotNetTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/cvs-tag.html0000644000175000017500000004152211757307545020117 0ustar jtaylorjtaylor <cvs-tag> Task

<cvs-tag>

[This is preliminary documentation and subject to change.]

Tags all local sources with the specified tag.

This differs from the <cvs-rtag> task in that it acts on references to the cvs files contained in your local filesystem. As such the sticky tags and local revisions can be considered in commits. It also allows you to verify that all local files have been checked in before a tag is performed.

Parameters

Attribute Type Description Required
tag string The name of the tag to assign or remove. True
act-on-date datetime Indicates the revision date of the file that the tag should be applied to. False
act-on-tag string Indicates the repository tag that is acted on for the tag command. Note if move-if-exists is true then the tag specified is moved to the revision of the file on the HEAD of the branch specified. False
fail-if-modified bool Indicates whether the head revision should be used if the act-on-tag or the act-on-date tags are not found. False
force-head bool Indicates whether the head revision should be used if the revision specified by act-on-tag or the act-on-date tags are not found. False
move-if-exists bool Indicates whether the tag specified in tag should be moved to the current file revision. If the tag does not exist then it is created. False
recursive bool If a directory is specified indicates whether sub-directories should also be processed. False
remove bool Indicates whether the tag specified in tag should be removed or not. False
commandline string Command-line arguments for the program. The command line arguments are used to specify any cvs command options that are not available as attributes. These are appended after the command itself and are additive to whatever attributes are currently specified. False
compressionlevel int Compression level to use for all net traffic. This should be a value from 1-9.



NOTE: This is not available on sharpcvslib.
False
cvsfullpath file The full path to the cvs binary used. The cvs tasks will attempt to "guess" the location of your cvs binary based on your path. If the task is unable to resolve the location, or resolves it incorrectly this can be used to manually specify the path. False
cvsroot string

The cvs root variable has the following components:

[protocol]:[username]@[servername]:[server path]
  • protocol: ext, pserver, ssh (sharpcvslib); if you are not using sharpcvslib consult your cvs documentation.
  • username: [username]
  • servername: cvs.sourceforge.net
  • server path: /cvsroot/nant

False
cvsrsh file The executable to use for ssh communication. False
destination directory Destination directory for the local sandbox. If destination is not specified then the current directory is used. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
passfile file The full path to the cached password file. If not specified then the environment variables are used to try and locate the file. False
password string Deprecated. The password for logging in to the repository. False
quiet bool Indicates if the output from the cvs command should be supressed. The default is false. False
readonly bool true if the sandbox files should be checked out in read only mode. The default is false. False
readwrite bool true if the sandbox files should be checked out in read/write mode. The default is true. False
reallyquiet bool Indicates if the output from the cvs command should be stopped. The default is false. False
timeout int The maximum amount of time the application is allowed to execute, expressed in milliseconds. Defaults to no time-out. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
usesharpcvslib bool

true if the SharpCvsLib binaries that come bundled with NAnt should be used to perform the cvs commands, false otherwise.

You may also specify an override value for all cvs tasks instead of specifying a value for each. To do this set the property sourcecontrol.usesharpcvslib to false.

If you choose not to use SharpCvsLib to checkout from cvs you will need to include a cvs.exe binary in your path.
False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Framework-configurable parameters

Attribute Type Description Required
managed ManagedExecution Specifies whether the external program should be treated as a managed application, possibly forcing it to be executed under the currently targeted version of the CLR. False
useruntimeengine bool Deprecated. Specifies whether the external program is a managed application which should be executed using a runtime engine, if configured. The default is false. False

Nested Elements:

<fileset>

Used to specify the version control system (VCS) files that are going to be acted on.

</fileset>

<arg>

The command-line arguments for the external program.

Represents a command-line argument.

When passed to an external application, the argument will be quoted when appropriate. This does not apply to the line parameter, which is always passed as is.

Parameters

AttributeTypeDescriptionRequired
dirdirectory The value for a directory-based command-line argument; will be replaced with the absolute path of the directory. False
filefile The name of a file as a single command-line argument; will be replaced with the absolute filename of the file. False
ifbool Indicates if the argument should be passed to the external program. If true then the argument will be passed; otherwise, skipped. The default is true. False
linestring List of command-line arguments; will be passed to the executable as is. False
path<path> The value for a PATH-like command-line argument; you can use : or ; as path separators and NAnt will convert it to the platform's local conventions, while resolving references to environment variables. False
unlessbool Indicates if the argument should not be passed to the external program. If false then the argument will be passed; otherwise, skipped. The default is false. False
valuestring A single command-line argument; can contain space characters. False

Nested Elements:

<path>

Sets a single command-line argument and treats it like a PATH - ensures the right separator for the local platform is used.

</path>

Examples

  • A single command-line argument containing a space character.

    <arg value="-l -a" />
        
  • Two separate command-line arguments.

    <arg line="-l -a" />
        
  • A single command-line argument with the value \dir;\dir2;\dir3 on DOS-based systems and /dir:/dir2:/dir3 on Unix-like systems.

    <arg path="/dir;/dir2:\dir3" />
        

</arg>

Examples

  • Tag NAnt sources remotely.

    <cvs-tag 
        cvsroot=":pserver:anonymous@cvs.sourceforge.net:/cvsroot/nant" 
        destination="."
        tag="v0_8_4"
         />
        
  • Remove a tag from the remote repository.

    <cvs-tag 
        cvsroot=":pserver:anonymous@cvs.sourceforge.net:/cvsroot/nant" 
        destination="."
        tag="v0_8_4"
        remove="true"
        fail-if-modified="true"
         />
        

Requirements

Assembly: NAnt.SourceControlTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/unzip.html0000644000175000017500000001112311757307423017705 0ustar jtaylorjtaylor <unzip> Task

<unzip>

[This is preliminary documentation and subject to change.]

Extracts files from a zip archive.

Uses #ziplib (SharpZipLib), an open source Zip/GZip library written entirely in C#.

Parameters

Attribute Type Description Required
zipfile file The archive file to expand. True
encoding Encoding The character encoding that has been used for filenames inside the zip file. The default is the system's OEM code page. False
todir directory The directory where the expanded files should be stored. The default is the project base directory. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
overwrite bool Overwrite files, even if they are newer than the corresponding entries in the archive. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Examples

  • Extracts all the file from the zip, preserving the directory structure.

    <unzip zipfile="backup.zip"/>
        

Requirements

Assembly: NAnt.CompressionTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/untar.html0000644000175000017500000001100411757307423017667 0ustar jtaylorjtaylor <untar> Task

<untar>

[This is preliminary documentation and subject to change.]

Extracts files from a tar archive.

Uses #ziplib (SharpZipLib), an open source Zip/GZip library written entirely in C#.

Parameters

Attribute Type Description Required
src file The archive file to expand. True
compression TarCompressionMethod The compression method. The default is None. False
dest directory The directory where to store the expanded file(s). The default is the project base directory. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
overwrite bool Overwrite files, even if they are newer than the corresponding entries in the archive. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Examples

  • Extracts all files from a gzipped tar, preserving the directory structure.

    <untar src="nant-bin.tar.gz" dest="bin" compression="gzip" />
        

Requirements

Assembly: NAnt.CompressionTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/delete.html0000644000175000017500000001261611757307433020013 0ustar jtaylorjtaylor <delete> Task

<delete>

[This is preliminary documentation and subject to change.]

Deletes a file, fileset or directory.

Deletes either a single file, all files in a specified directory and its sub-directories, or a set of files specified by one or more filesets.

If the file or dir attribute is set then the fileset contents will be ignored. To delete the files in the fileset ommit the file and dir attributes in the <delete> element.

If the specified file or directory does not exist, no error is reported.

Note: Read-only files cannot be deleted. Use the <attrib> task first to remove the read-only attribute.

Parameters

Attribute Type Description Required
dir directory The directory to delete. False
file file The file to delete. False
includeemptydirs bool Remove any empty directories included in the <fileset>. The default is true. False
verbose bool Controls whether to show the name of each deleted file or directory. The default is false. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False

Nested Elements:

<fileset>

All the files in the file set will be deleted.

</fileset>

Examples

  • Delete a single file.

    <delete file="myfile.txt" />
        
  • Delete a directory and the contents within. If the directory does not exist, no error is reported.

    <delete dir="${build.dir}" />
        
  • Delete a set of files.

    <delete>
        <fileset>
            <include name="${basename}-??.exe" />
            <include name="${basename}-??.pdb" />
        </fileset>
    </delete>
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/rc.html0000644000175000017500000002656111757307556017167 0ustar jtaylorjtaylor <rc> Task

<rc>

[This is preliminary documentation and subject to change.]

Compiles resources using rc.exe, Microsoft's Win32 resource compiler.

Parameters

Attribute Type Description Required
rcfile file The resource file to compile. True
langid int Default language ID. False
options string Options to pass to the compiler. False
output file Output file. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
timeout int The maximum amount of time the application is allowed to execute, expressed in milliseconds. Defaults to no time-out. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Framework-configurable parameters

Attribute Type Description Required
exename string The name of the executable that should be used to launch the external program. False
managed ManagedExecution Specifies whether the external program should be treated as a managed application, possibly forcing it to be executed under the currently targeted version of the CLR. False
useruntimeengine bool Deprecated. Specifies whether the external program is a managed application which should be executed using a runtime engine, if configured. The default is false. False

Nested Elements:

<includedirs>

The list of directories in which to search for include files.

</includedirs>

<defines>

Macro definitions to pass to rc.exe. Each entry will generate a /d
<define>

Represents an option.

Parameters

AttributeTypeDescriptionRequired
namestring Name of the option. True
ifbool Indicates if the option should be passed to the task. If true then the option will be passed; otherwise, skipped. The default is true. False
unlessbool Indicates if the option should not be passed to the task. If false then the option will be passed; otherwise, skipped. The default is false. False
valuestring Value of the option. The default is a null reference (Nothing in Visual Basic). False
</define>

</defines>

<arg>

The command-line arguments for the external program.

Represents a command-line argument.

When passed to an external application, the argument will be quoted when appropriate. This does not apply to the line parameter, which is always passed as is.

Parameters

AttributeTypeDescriptionRequired
dirdirectory The value for a directory-based command-line argument; will be replaced with the absolute path of the directory. False
filefile The name of a file as a single command-line argument; will be replaced with the absolute filename of the file. False
ifbool Indicates if the argument should be passed to the external program. If true then the argument will be passed; otherwise, skipped. The default is true. False
linestring List of command-line arguments; will be passed to the executable as is. False
path<path> The value for a PATH-like command-line argument; you can use : or ; as path separators and NAnt will convert it to the platform's local conventions, while resolving references to environment variables. False
unlessbool Indicates if the argument should not be passed to the external program. If false then the argument will be passed; otherwise, skipped. The default is false. False
valuestring A single command-line argument; can contain space characters. False

Nested Elements:

<path>

Sets a single command-line argument and treats it like a PATH - ensures the right separator for the local platform is used.

</path>

Examples

  • A single command-line argument containing a space character.

    <arg value="-l -a" />
        
  • Two separate command-line arguments.

    <arg line="-l -a" />
        
  • A single command-line argument with the value \dir;\dir2;\dir3 on DOS-based systems and /dir:/dir2:/dir3 on Unix-like systems.

    <arg path="/dir;/dir2:\dir3" />
        

</arg>

Examples

  • Compile text.rc to text.res using the default options.

    <rc rcfile="text.rc" output="text.res" />
        
  • Compile text.rc, passing an additional option.

    <rc rcfile="text.rc" options="/r"/>
        

Requirements

Assembly: NAnt.VisualCppTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/mail.html0000644000175000017500000002264411757307446017501 0ustar jtaylorjtaylor <mail> Task

<mail>

[This is preliminary documentation and subject to change.]

Sends an SMTP message.

Text and text files to include in the message body may be specified as well as binary attachments.

Parameters

Attribute Type Description Required
from string Email address of sender. True
bcclist string Semicolon-separated list of BCC: recipient email addresses. False
cclist string Semicolon-separated list of CC: recipient email addresses. False
format MailFormat Deprecated. Format of the message. The default is Text. False
isbodyhtml bool Indicates whether or not the body of the email is in html format. The default value is false. False
mailhost string Host name of mail server. The default is localhost. False
mailport int The port number used to connect to the mail server. The default is 25. False
message string Text to send in body of email message. False
password string The password to use when connecting to the smtp host. False
replyto string Reply to email address. False
ssl bool Indicates whether or not ssl should be used to connect to the smtp host. False
subject string Text to send in subject line of email message. False
tolist string Semicolon-separated list of recipient email addresses. False
user string The username to use when connecting to the smtp host. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Nested Elements:

<files>

Files that are transmitted as part of the body of the email message.

</files>

<attachments>

Attachments that are transmitted with the message.

</attachments>

Examples

  • Sends an email from nant@sourceforge.net to three recipients with a subject about the attachments. The body of the message will be the combined contents of all .txt files in the base directory. All zip files in the base directory will be included as attachments. The message will be sent using the smtpserver.anywhere.com SMTP server.

    <mail 
        from="nant@sourceforge.net" 
        tolist="recipient1@sourceforge.net" 
        cclist="recipient2@sourceforge.net" 
        bcclist="recipient3@sourceforge.net" 
        subject="Msg 7: With attachments" 
        mailhost="smtpserver.anywhere.com">
        <files>
            <include name="*.txt" />
        </files>   
        <attachments>
            <include name="*.zip" />
        </attachments>
    </mail>
        
  • Sends an email from a gmail account to multiple recipients. This example illustrates how to add a recipient's name to an email address.

    <mail
        from="+xxxx+@gmail.com"
        tolist="(Rep A) recipient1@sourceforge.net;(Rep B) recipient2@sourceforge.net"
        subject="Sample Email"
        mailhost="smtp.gmail.com"
        mailport="465"
        ssl="true"
        user="+xxxx+@gmail.com"
        password="p@ssw0rd!"
        message="Email from NAnt" />
        

    Email addresses in any of the lists (to, cc, bcc, from) can be in one of the five listed formats below.

    • Full Name <address@abcxyz.com>
    • <address@abcxyz.com> Full Name
    • (Full Name) address@abcxyz.com
    • address@abcxyz.com (Full Name)
    • address@abcxyz.com

    Remember to use &gt; and &lt; XML entities for the angle brackets.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/uptodate.html0000644000175000017500000001033311757307456020375 0ustar jtaylorjtaylor <uptodate> Task

<uptodate>

[This is preliminary documentation and subject to change.]

Check modification dates on groups of files.

If all targetfiles are same or newer than all sourcefiles, the specified property is set to true, otherwise it is set to false.

Parameters

AttributeTypeDescriptionRequired
propertystring Property that will be set to true or false depending on the result of the date check. True
failonerrorbool Determines if task failure stops the build, or is just reported. The default is true. False
ifbool If true then the task will be executed; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbosebool Determines whether the task should report detailed build log messages. The default is false. False

Nested Elements:

<sourcefiles>

The <fileset> that contains list of source files.

</sourcefiles>

<targetfiles>

The <fileset> that contains list of target files.

</targetfiles>

Examples

  • Check file dates. If myfile.dll is same or newer than myfile.cs, then set myfile.dll.uptodate property to either true or false.

    <uptodate property="myfile.dll.uptodate">
        <sourcefiles>
            <include name="myfile.cs" />
        </sourcefiles>
        <targetfiles>
            <include name="myfile.dll" />
        </targetfiles>
    </uptodate>
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/tar.html0000644000175000017500000001245311757307422017334 0ustar jtaylorjtaylor <tar> Task

<tar>

[This is preliminary documentation and subject to change.]

Creates a tar file from the specified filesets.

Uses #ziplib (SharpZipLib), an open source Tar/Zip/GZip library written entirely in C#.

Parameters

Attribute Type Description Required
destfile file The tar file to create. True
compression TarCompressionMethod The compression method. The default is None. False
flatten bool Ignore directory structure of source directory, compress all files into a single directory. The default value is false. False
includeemptydirs bool Include empty directories in the generated tar file. The default is false. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Nested Elements:

<fileset>

The set of files to be included in the archive.

</fileset>

Examples

  • Tar all files in ${build.dir} and ${doc.dir} into a file called "backup.tar.gz", and apply gzip compression to it.

    <tar destfile="backup.tar.gz" compression="GZip">
        <fileset basedir="${bin.dir}" prefix="bin">
            <include name="**/*" />
        </fileset>
        <fileset basedir="${doc.dir}" prefix="doc">
            <include name="**/*" />
        </fileset>
    </tar>
        

Requirements

Assembly: NAnt.CompressionTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/cl.html0000644000175000017500000004024311757307550017144 0ustar jtaylorjtaylor <cl> Task

<cl>

[This is preliminary documentation and subject to change.]

Compiles C/C++ programs using cl.exe, Microsoft's C/C++ compiler.

This task is intended for version 13.00.9466 of cl.exe.

Parameters

Attribute Type Description Required
outputdir directory Directory where all output files are placed. True
characterset CharacterSet Tells the compiler to use the specified character set. False
managedextensions bool Specifies whether Managed Extensions for C++ should be enabled. The default is false. False
objectfile string A name to override the default object file name; can be either a file or directory name. The default is the output directory. False
options string Options to pass to the compiler. False
pchfile string Specifies the path and/or name of the generated precompiled header file - given either relative to outputdir or as an absolute path. False
pchmode PrecompiledHeaderMode The mode in which the specified pchfile (if any) is used. The default is Use. False
pchthroughfile string The path of the boundary file when generating/using the specified pchfile. If a precompiled header file is not specified then this attribute is ignored. False
pdbfile string A name for the compiler-generated PDB file; can be either a file or directory name. The default is the output directory. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
timeout int The maximum amount of time the application is allowed to execute, expressed in milliseconds. Defaults to no time-out. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Framework-configurable parameters

Attribute Type Description Required
exename string The name of the executable that should be used to launch the external program. False
managed ManagedExecution Specifies whether the external program should be treated as a managed application, possibly forcing it to be executed under the currently targeted version of the CLR. False
useruntimeengine bool Deprecated. Specifies whether the external program is a managed application which should be executed using a runtime engine, if configured. The default is false. False

Nested Elements:

<sources>

The list of files to compile.

</sources>

<includedirs>

The list of directories in which to search for include files.

</includedirs>

<metadataincludedirs>

Directories that the compiler will search to resolve file references passed to the #using directive.

</metadataincludedirs>

<forcedusingfiles>

Specifies metadata files to reference in this compilation as an alternative to passing a file name to #using in source code.

</forcedusingfiles>

<defines>

Macro definitions to pass to cl.exe. Each entry will generate a /D
<define>

Represents an option.

Parameters

AttributeTypeDescriptionRequired
namestring Name of the option. True
ifbool Indicates if the option should be passed to the task. If true then the option will be passed; otherwise, skipped. The default is true. False
unlessbool Indicates if the option should not be passed to the task. If false then the option will be passed; otherwise, skipped. The default is false. False
valuestring Value of the option. The default is a null reference (Nothing in Visual Basic). False
</define>

</defines>

<undefines>

Macro undefines (/U) to pass to cl.exe.
<undefine>

Represents an option.

Parameters

AttributeTypeDescriptionRequired
namestring Name of the option. True
ifbool Indicates if the option should be passed to the task. If true then the option will be passed; otherwise, skipped. The default is true. False
unlessbool Indicates if the option should not be passed to the task. If false then the option will be passed; otherwise, skipped. The default is false. False
valuestring Value of the option. The default is a null reference (Nothing in Visual Basic). False
</undefine>

</undefines>

<arg>

The command-line arguments for the external program.

Represents a command-line argument.

When passed to an external application, the argument will be quoted when appropriate. This does not apply to the line parameter, which is always passed as is.

Parameters

AttributeTypeDescriptionRequired
dirdirectory The value for a directory-based command-line argument; will be replaced with the absolute path of the directory. False
filefile The name of a file as a single command-line argument; will be replaced with the absolute filename of the file. False
ifbool Indicates if the argument should be passed to the external program. If true then the argument will be passed; otherwise, skipped. The default is true. False
linestring List of command-line arguments; will be passed to the executable as is. False
path<path> The value for a PATH-like command-line argument; you can use : or ; as path separators and NAnt will convert it to the platform's local conventions, while resolving references to environment variables. False
unlessbool Indicates if the argument should not be passed to the external program. If false then the argument will be passed; otherwise, skipped. The default is false. False
valuestring A single command-line argument; can contain space characters. False

Nested Elements:

<path>

Sets a single command-line argument and treats it like a PATH - ensures the right separator for the local platform is used.

</path>

Examples

  • A single command-line argument containing a space character.

    <arg value="-l -a" />
        
  • Two separate command-line arguments.

    <arg line="-l -a" />
        
  • A single command-line argument with the value \dir;\dir2;\dir3 on DOS-based systems and /dir:/dir2:/dir3 on Unix-like systems.

    <arg path="/dir;/dir2:\dir3" />
        

</arg>

Examples

  • Compiles helloworld.cpp for the Common Language Runtime.

    <cl outputdir="build" options="/clr">
        <sources>
            <include name="helloworld.cpp" />
        </sources>
    </cl>
        

Requirements

Assembly: NAnt.VisualCppTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/cvs.html0000644000175000017500000003423011757307537017345 0ustar jtaylorjtaylor <cvs> Task

<cvs>

[This is preliminary documentation and subject to change.]

Executes the cvs command specified by the command attribute.

Parameters

Attribute Type Description Required
command string The cvs command to execute. True
commandline string Command-line arguments for the program. The command line arguments are used to specify any cvs command options that are not available as attributes. These are appended after the command itself and are additive to whatever attributes are currently specified. False
compressionlevel int Compression level to use for all net traffic. This should be a value from 1-9.



NOTE: This is not available on sharpcvslib.
False
cvsfullpath file The full path to the cvs binary used. The cvs tasks will attempt to "guess" the location of your cvs binary based on your path. If the task is unable to resolve the location, or resolves it incorrectly this can be used to manually specify the path. False
cvsroot string

The cvs root variable has the following components:

[protocol]:[username]@[servername]:[server path]
  • protocol: ext, pserver, ssh (sharpcvslib); if you are not using sharpcvslib consult your cvs documentation.
  • username: [username]
  • servername: cvs.sourceforge.net
  • server path: /cvsroot/nant

False
cvsrsh file The executable to use for ssh communication. False
destination directory Destination directory for the local sandbox. If destination is not specified then the current directory is used. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
module string The module to perform an operation on. False
passfile file The full path to the cached password file. If not specified then the environment variables are used to try and locate the file. False
password string Deprecated. The password for logging in to the repository. False
quiet bool Indicates if the output from the cvs command should be supressed. The default is false. False
readonly bool true if the sandbox files should be checked out in read only mode. The default is false. False
readwrite bool true if the sandbox files should be checked out in read/write mode. The default is true. False
reallyquiet bool Indicates if the output from the cvs command should be stopped. The default is false. False
timeout int The maximum amount of time the application is allowed to execute, expressed in milliseconds. Defaults to no time-out. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
usesharpcvslib bool

true if the SharpCvsLib binaries that come bundled with NAnt should be used to perform the cvs commands, false otherwise.

You may also specify an override value for all cvs tasks instead of specifying a value for each. To do this set the property sourcecontrol.usesharpcvslib to false.

If you choose not to use SharpCvsLib to checkout from cvs you will need to include a cvs.exe binary in your path.
False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Framework-configurable parameters

Attribute Type Description Required
managed ManagedExecution Specifies whether the external program should be treated as a managed application, possibly forcing it to be executed under the currently targeted version of the CLR. False
useruntimeengine bool Deprecated. Specifies whether the external program is a managed application which should be executed using a runtime engine, if configured. The default is false. False

Nested Elements:

<fileset>

Used to specify the version control system (VCS) files that are going to be acted on.

</fileset>

<arg>

The command-line arguments for the external program.

Represents a command-line argument.

When passed to an external application, the argument will be quoted when appropriate. This does not apply to the line parameter, which is always passed as is.

Parameters

AttributeTypeDescriptionRequired
dirdirectory The value for a directory-based command-line argument; will be replaced with the absolute path of the directory. False
filefile The name of a file as a single command-line argument; will be replaced with the absolute filename of the file. False
ifbool Indicates if the argument should be passed to the external program. If true then the argument will be passed; otherwise, skipped. The default is true. False
linestring List of command-line arguments; will be passed to the executable as is. False
path<path> The value for a PATH-like command-line argument; you can use : or ; as path separators and NAnt will convert it to the platform's local conventions, while resolving references to environment variables. False
unlessbool Indicates if the argument should not be passed to the external program. If false then the argument will be passed; otherwise, skipped. The default is false. False
valuestring A single command-line argument; can contain space characters. False

Nested Elements:

<path>

Sets a single command-line argument and treats it like a PATH - ensures the right separator for the local platform is used.

</path>

Examples

  • A single command-line argument containing a space character.

    <arg value="-l -a" />
        
  • Two separate command-line arguments.

    <arg line="-l -a" />
        
  • A single command-line argument with the value \dir;\dir2;\dir3 on DOS-based systems and /dir:/dir2:/dir3 on Unix-like systems.

    <arg path="/dir;/dir2:\dir3" />
        

</arg>

Examples

  • Checkout NAnt.

    <cvs command="checkout" 
         destination="c:\src\nant\" 
         cvsroot=":pserver:anonymous@cvs.sourceforge.net:/cvsroot/nant" 
         module="nant" />
        

Requirements

Assembly: NAnt.SourceControlTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/setenv.html0000644000175000017500000002362011757307452020053 0ustar jtaylorjtaylor <setenv> Task

<setenv>

[This is preliminary documentation and subject to change.]

Sets an environment variable or a whole collection of them. Use an empty value attribute to clear a variable.

Note: Variables will be set for the current NAnt process and all child processes that NAnt spawns (compilers, shell tools, etc). If the intention is to only set a variable for a single child process, then using the <exec> task and its nested environment element might be a better option.

Note: Expansion of inline environment variables is performed using the syntax of the current platform. So on Windows platforms using the string %PATH% in the value attribute will result in the value of the PATH variable being expanded in place before the variable is set.

Parameters

Attribute Type Description Required
dir directory The value for a directory-based environment variable. NAnt will convert it to an absolute path. False
file file The value for a file-based environment variable. NAnt will convert it to an absolute filename. False
name string The name of a single Environment variable to set False
path <path> The value for a PATH like environment variable. You can use : or ; as path separators and NAnt will convert it to the platform's local conventions. False
value string The literal value for the environment variable. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Nested Elements:

<variable>

Represents an environment variable.

Parameters

Attribute Type Description Required
name string The name of the environment variable. True
dir directory The value for a directory-based environment variable. NAnt will convert it to an absolute path. False
file file The value for a file-based environment variable. NAnt will convert it to an absolute filename. False
if bool Indicates if the environment variable should be passed to the external program. If true then the environment variable will be passed; otherwise, skipped. The default is true. False
path <path> The value for a PATH like environment variable. You can use : or ; as path separators and NAnt will convert it to the platform's local conventions. False
unless bool Indicates if the environment variable should not be passed to the external program. If false then the environment variable will be passed; otherwise, skipped. The default is false. False
value string The literal value for the environment variable. False

Nested Elements:

<path>

Sets a single environment variable and treats it like a PATH - ensures the right separator for the local platform is used.

</path>

</variable>

Examples

  • Set the MONO_PATH environment variable on a *nix platform.

      <setenv name=="MONO_PATH" value="/home/jimbob/dev/foo:%MONO_PATH%"/>
      
  • Set a collection of environment variables. Note the nested variable used to set var3.

      <setenv>
              <variable name="var1" value="value2" />
              <variable name="var2" value="value2" />
              <variable name="var3" value="value3:%var2%" />
      </setenv>
      
  • Set environment variables using nested path elements.

      <path id="build.path">
             <pathelement dir="c:/windows" />
             <pathelement dir="c:/cygwin/usr/local/bin" />
         </path>
      <setenv>         
              <variable name="build_path" >
                     <path refid="build.path" />
              </variable>
              <variable name="path2">
                 <path>
                     <pathelement dir="c:/windows" />
                     <pathelement dir="c:/cygwin/usr/local/bin" />
                 </path>
              </variable>
      </setenv>    
      

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/move.html0000644000175000017500000002210111757307447017512 0ustar jtaylorjtaylor <move> Task

<move>

[This is preliminary documentation and subject to change.]

Moves a file, a directory, or set of files to a new file or directory.

Files are only moved if the source file is newer than the destination file, or if the destination file does not exist. However, you can explicitly overwrite files with the overwrite attribute.

Entire directory structures can be moved to a new location. For this to happen, the following criteria must be met:

  • Everything in the fileset is included
  • The directory structure is not flattened
  • Empty directories are included
  • Destination directory does not exist

If any of these items are not met, then the files within the source directory will be moved over instead of the entire directory structure.

A <fileset> can be used to select files or directories to move. To use a <fileset>, the todir attribute must be set.

Encoding

Unless an encoding is specified, the encoding associated with the system's current ANSI code page is used.

An UTF-8, little-endian Unicode, and big-endian Unicode encoded text file is automatically recognized, if the file starts with the appropriate byte order marks.

Note: If you employ filters in your move operation, you should limit the move to text files. Binary files will be corrupted by the move operation.

Parameters

Attribute Type Description Required
file file The file to move. False
flatten bool Ignore directory structure of source directory, move all files into a single directory, specified by the todir attribute. The default is false. False
todir directory The directory to move to. False
tofile file The file to move to. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
includeemptydirs bool Copy any empty directories included in the <fileset>. The default is true. False
inputencoding Encoding The encoding to use when reading files. The default is the system's current ANSI code page. False
outputencoding Encoding The encoding to use when writing the files. The default is the encoding of the input file. False
overwrite bool Overwrite existing files even if the destination files are newer. The default is false. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Nested Elements:

<fileset>

Used to select the files to move. To use a <fileset>, the todir attribute must be set.

</fileset>

<filterchain>

Chain of filters used to alter the file's content as it is moved.

</filterchain>

Examples

  • Move a single file while changing its encoding from "latin1" to "utf-8".

    <move
        file="myfile.txt"
        tofile="mycopy.txt"
        inputencoding="latin1"
        outputencoding="utf-8" />
        
  • Move a set of files.

    <move todir="${build.dir}">
        <fileset basedir="bin">
            <include name="*.dll" />
        </fileset>
    </move>
        
  • Move a set of files to a directory, replacing @TITLE@ with "Foo Bar" in all files.

    <move todir="../backup/dir">
        <fileset basedir="src_dir">
            <include name="**/*" />
        </fileset>
        <filterchain>
            <replacetokens>
                <token key="TITLE" value="Foo Bar" />
            </replacetokens>
        </filterchain>
    </move>
        
  • Move an entire directory and its contents.

    <move todir="target/dir">
      <fileset basedir="source/dir"/>
    </move>
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/mc.html0000644000175000017500000002313411757307554017151 0ustar jtaylorjtaylor <mc> Task

<mc>

[This is preliminary documentation and subject to change.]

Compiles messages using mc.exe, Microsoft's Win32 message compiler.

Parameters

Attribute Type Description Required
mcfile file Input filename. True
headerpath directory Path to store header file. The default is the project base directory. False
options string Options to pass to the compiler. False
rcpath directory Path to store RC file. The default is the project base directory. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
timeout int The maximum amount of time the application is allowed to execute, expressed in milliseconds. Defaults to no time-out. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Framework-configurable parameters

Attribute Type Description Required
exename string The name of the executable that should be used to launch the external program. False
managed ManagedExecution Specifies whether the external program should be treated as a managed application, possibly forcing it to be executed under the currently targeted version of the CLR. False
useruntimeengine bool Deprecated. Specifies whether the external program is a managed application which should be executed using a runtime engine, if configured. The default is false. False

Nested Elements:

<arg>

The command-line arguments for the external program.

Represents a command-line argument.

When passed to an external application, the argument will be quoted when appropriate. This does not apply to the line parameter, which is always passed as is.

Parameters

AttributeTypeDescriptionRequired
dirdirectory The value for a directory-based command-line argument; will be replaced with the absolute path of the directory. False
filefile The name of a file as a single command-line argument; will be replaced with the absolute filename of the file. False
ifbool Indicates if the argument should be passed to the external program. If true then the argument will be passed; otherwise, skipped. The default is true. False
linestring List of command-line arguments; will be passed to the executable as is. False
path<path> The value for a PATH-like command-line argument; you can use : or ; as path separators and NAnt will convert it to the platform's local conventions, while resolving references to environment variables. False
unlessbool Indicates if the argument should not be passed to the external program. If false then the argument will be passed; otherwise, skipped. The default is false. False
valuestring A single command-line argument; can contain space characters. False

Nested Elements:

<path>

Sets a single command-line argument and treats it like a PATH - ensures the right separator for the local platform is used.

</path>

Examples

  • A single command-line argument containing a space character.

    <arg value="-l -a" />
        
  • Two separate command-line arguments.

    <arg line="-l -a" />
        
  • A single command-line argument with the value \dir;\dir2;\dir3 on DOS-based systems and /dir:/dir2:/dir3 on Unix-like systems.

    <arg path="/dir;/dir2:\dir3" />
        

</arg>

Examples

  • Compile text.mc using the default options.

    <mc mcfile="text.mc"/>
        

    Compile text.mc, passing a path to store the header, the rc file and some additonal options.

    <mc mcfile="text.mc" headerpath=".\build" rcpath=".\build" options="-v -c -u"/>
        

Requirements

Assembly: NAnt.VisualCppTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/cvs-checkout.html0000644000175000017500000004060111757307535021145 0ustar jtaylorjtaylor <cvs-checkout> Task

<cvs-checkout>

[This is preliminary documentation and subject to change.]

Checks out a CVS module to the required directory.

Parameters

Attribute Type Description Required
date datetime Specify the revision date to checkout. The date specified is validated and then passed to the cvs binary in a standard format recognized by cvs. False
overridedir string Specify a directory name to replace the module name. Valid names include any valid filename, excluding path information. False
override-directory string Specify a directory name to replace the module name. Valid names include any valid filename, excluding path information. False
revision string Specify the revision to checkout. This corresponds to the "sticky-tag" of the file. False
sticky-tag string Sticky tag or revision to checkout. False
commandline string Command-line arguments for the program. The command line arguments are used to specify any cvs command options that are not available as attributes. These are appended after the command itself and are additive to whatever attributes are currently specified. False
compressionlevel int Compression level to use for all net traffic. This should be a value from 1-9.



NOTE: This is not available on sharpcvslib.
False
cvsfullpath file The full path to the cvs binary used. The cvs tasks will attempt to "guess" the location of your cvs binary based on your path. If the task is unable to resolve the location, or resolves it incorrectly this can be used to manually specify the path. False
cvsroot string

The cvs root variable has the following components:

[protocol]:[username]@[servername]:[server path]
  • protocol: ext, pserver, ssh (sharpcvslib); if you are not using sharpcvslib consult your cvs documentation.
  • username: [username]
  • servername: cvs.sourceforge.net
  • server path: /cvsroot/nant

False
cvsrsh file The executable to use for ssh communication. False
destination directory Destination directory for the local sandbox. If destination is not specified then the current directory is used. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
module string The module to perform an operation on. False
passfile file The full path to the cached password file. If not specified then the environment variables are used to try and locate the file. False
password string Deprecated. The password for logging in to the repository. False
quiet bool Indicates if the output from the cvs command should be supressed. The default is false. False
readonly bool true if the sandbox files should be checked out in read only mode. The default is false. False
readwrite bool true if the sandbox files should be checked out in read/write mode. The default is true. False
reallyquiet bool Indicates if the output from the cvs command should be stopped. The default is false. False
timeout int The maximum amount of time the application is allowed to execute, expressed in milliseconds. Defaults to no time-out. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
usesharpcvslib bool

true if the SharpCvsLib binaries that come bundled with NAnt should be used to perform the cvs commands, false otherwise.

You may also specify an override value for all cvs tasks instead of specifying a value for each. To do this set the property sourcecontrol.usesharpcvslib to false.

If you choose not to use SharpCvsLib to checkout from cvs you will need to include a cvs.exe binary in your path.
False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Framework-configurable parameters

Attribute Type Description Required
managed ManagedExecution Specifies whether the external program should be treated as a managed application, possibly forcing it to be executed under the currently targeted version of the CLR. False
useruntimeengine bool Deprecated. Specifies whether the external program is a managed application which should be executed using a runtime engine, if configured. The default is false. False

Nested Elements:

<fileset>

Used to specify the version control system (VCS) files that are going to be acted on.

</fileset>

<arg>

The command-line arguments for the external program.

Represents a command-line argument.

When passed to an external application, the argument will be quoted when appropriate. This does not apply to the line parameter, which is always passed as is.

Parameters

AttributeTypeDescriptionRequired
dirdirectory The value for a directory-based command-line argument; will be replaced with the absolute path of the directory. False
filefile The name of a file as a single command-line argument; will be replaced with the absolute filename of the file. False
ifbool Indicates if the argument should be passed to the external program. If true then the argument will be passed; otherwise, skipped. The default is true. False
linestring List of command-line arguments; will be passed to the executable as is. False
path<path> The value for a PATH-like command-line argument; you can use : or ; as path separators and NAnt will convert it to the platform's local conventions, while resolving references to environment variables. False
unlessbool Indicates if the argument should not be passed to the external program. If false then the argument will be passed; otherwise, skipped. The default is false. False
valuestring A single command-line argument; can contain space characters. False

Nested Elements:

<path>

Sets a single command-line argument and treats it like a PATH - ensures the right separator for the local platform is used.

</path>

Examples

  • A single command-line argument containing a space character.

    <arg value="-l -a" />
        
  • Two separate command-line arguments.

    <arg line="-l -a" />
        
  • A single command-line argument with the value \dir;\dir2;\dir3 on DOS-based systems and /dir:/dir2:/dir3 on Unix-like systems.

    <arg path="/dir;/dir2:\dir3" />
        

</arg>

Examples

  • Checkout NAnt.

    <cvs-checkout 
        destination="c:\src\nant\" 
        cvsroot=":pserver:anonymous@cvs.sourceforge.net:/cvsroot/nant" 
        module="nant" />
        
  • Checkout NAnt revision named 0_85 to the folder c:\src\nant\v0.85.

    <cvs-checkout 
        destination="c:\src\nant" 
        cvsroot=":pserver:anonymous@cvs.sourceforge.net:/cvsroot/nant" 
        module="nant"
        revision="0_85"
        overridedir="v0.85" />
        

    So the nant module tagged with revision 0_85 will be checked out in the folder v0.85 under the working/ destination directory.

    This could be used to work on different branches of a repository at the same time.

  • Checkout NAnt with specified revision date to the folder c:\src\nant\2003_08_16.

    <cvs-checkout 
        destination="c:\src\nant\" 
        cvsroot=":pserver:anonymous@cvs.sourceforge.net:/cvsroot/nant" 
        module="nant"
        date="2003/08/16"
        overridedir="2003_08_16" />
        

Requirements

Assembly: NAnt.SourceControlTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/exec.html0000644000175000017500000004271111757307440017472 0ustar jtaylorjtaylor <exec> Task

<exec>

[This is preliminary documentation and subject to change.]

Executes a system command.

Use of nested arg element(s) is advised over the commandline parameter, as it supports automatic quoting and can resolve relative to absolute paths.

Parameters

Attribute Type Description Required
program string The program to execute without command arguments. True
append bool Gets or sets a value indicating whether output should be appended to the output file. The default is false. False
basedir directory The directory the program is in. False
commandline string The command-line arguments for the program. These will be passed as is to the external program. When quoting is necessary, these must be explictly set as part of the value. Consider using nested arg elements instead. False
managed ManagedExecution Specifies whether the external program is a managed application which should be executed using a runtime engine, if configured. The default is false. False
output file The file to which the standard output will be redirected. False
pidproperty string The name of a property in which the unique identifier of the spawned application should be stored. Only of interest if spawn is true. False
resultproperty string

The name of a property in which the exit code of the program should be stored. Only of interest if failonerror is false.

If the exit code of the program is "-1000" then the program could not be started, or did not exit (in time).

False
spawn bool Gets or sets a value indicating whether the application should be spawned. If you spawn an application, its output will not be logged by NAnt. The default is false. False
useruntimeengine bool Deprecated. Specifies whether the external program should be executed using a runtime engine, if configured. The default is false. False
workingdir directory The directory in which the command will be executed. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
timeout int The maximum amount of time the application is allowed to execute, expressed in milliseconds. Defaults to no time-out. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Framework-configurable parameters

Attribute Type Description Required
exename string The name of the executable that should be used to launch the external program. False

Nested Elements:

<environment>

Environment variables to pass to the program.

A set of environment variables.

Nested Elements:

<option>

Deprecated. Environment variable to pass to a program.

Represents an option.

Parameters

AttributeTypeDescriptionRequired
namestring Name of the option. True
ifbool Indicates if the option should be passed to the task. If true then the option will be passed; otherwise, skipped. The default is true. False
unlessbool Indicates if the option should not be passed to the task. If false then the option will be passed; otherwise, skipped. The default is false. False
valuestring Value of the option. The default is a null reference (Nothing in Visual Basic). False

</option>

<variable>

Environment variable to pass to a program.

Represents an environment variable.

Parameters

AttributeTypeDescriptionRequired
namestring The name of the environment variable. True
dirdirectory The value for a directory-based environment variable. NAnt will convert it to an absolute path. False
filefile The value for a file-based environment variable. NAnt will convert it to an absolute filename. False
ifbool Indicates if the environment variable should be passed to the external program. If true then the environment variable will be passed; otherwise, skipped. The default is true. False
path<path> The value for a PATH like environment variable. You can use : or ; as path separators and NAnt will convert it to the platform's local conventions. False
unlessbool Indicates if the environment variable should not be passed to the external program. If false then the environment variable will be passed; otherwise, skipped. The default is false. False
valuestring The literal value for the environment variable. False

Nested Elements:

<path>

Sets a single environment variable and treats it like a PATH - ensures the right separator for the local platform is used.

</path>

</variable>

</environment>

<arg>

The command-line arguments for the external program.

Represents a command-line argument.

When passed to an external application, the argument will be quoted when appropriate. This does not apply to the line parameter, which is always passed as is.

Parameters

AttributeTypeDescriptionRequired
dirdirectory The value for a directory-based command-line argument; will be replaced with the absolute path of the directory. False
filefile The name of a file as a single command-line argument; will be replaced with the absolute filename of the file. False
ifbool Indicates if the argument should be passed to the external program. If true then the argument will be passed; otherwise, skipped. The default is true. False
linestring List of command-line arguments; will be passed to the executable as is. False
path<path> The value for a PATH-like command-line argument; you can use : or ; as path separators and NAnt will convert it to the platform's local conventions, while resolving references to environment variables. False
unlessbool Indicates if the argument should not be passed to the external program. If false then the argument will be passed; otherwise, skipped. The default is false. False
valuestring A single command-line argument; can contain space characters. False

Nested Elements:

<path>

Sets a single command-line argument and treats it like a PATH - ensures the right separator for the local platform is used.

</path>

Examples

  • A single command-line argument containing a space character.

    <arg value="-l -a" />
        
  • Two separate command-line arguments.

    <arg line="-l -a" />
        
  • A single command-line argument with the value \dir;\dir2;\dir3 on DOS-based systems and /dir:/dir2:/dir3 on Unix-like systems.

    <arg path="/dir;/dir2:\dir3" />
        

</arg>

Examples

  • Ping "nant.sourceforge.net".

    <exec program="ping">
        <arg value="nant.sourceforge.net" />
    </exec>
        
  • Execute a java application using IKVM.NET that requires the Apache FOP jars, and a set of custom jars.

          <path id="fop-classpath">
              <pathelement file="${fop.dist.dir}/build/fop.jar" />
              <pathelement file="${fop.dist.dir}/lib/xercesImpl-2.2.1.jar" />
              <pathelement file="${fop.dist.dir}/lib/avalon-framework-cvs-20020806.jar" />
              <pathelement file="${fop.dist.dir}/lib/batik.jar" />
          </path>
          <exec program="ikvm.exe" useruntimeengine="true">
              <arg value="-cp" />
              <arg>
                  <path>
                      <pathelement dir="conf" />
                      <path refid="fop-classpath" />
                      <pathelement file="lib/mylib.jar" />
                      <pathelement file="lib/otherlib.zip" />
                  </path>
              </arg>
              <arg value="org.me.MyProg" />
          </exec>
      

    Assuming the base directory of the build file is "c:\ikvm-test" and the value of the "fop.dist.dir" property is "c:\fop", then the value of the -cp argument that is passed toikvm.exe is "c:\ikvm-test\conf;c:\fop\build\fop.jar;conf;c:\fop\lib\xercesImpl-2.2.1.jar;c:\fop\lib\avalon-framework-cvs-20020806.jar;c:\fop\lib\batik.jar;c:\ikvm-test\lib\mylib.jar;c:\ikvm-test\lib\otherlib.zip" on a DOS-based system.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/lib.html0000644000175000017500000003022711757307552017317 0ustar jtaylorjtaylor <lib> Task

<lib>

[This is preliminary documentation and subject to change.]

Run lib.exe, Microsoft's Library Manager.

Parameters

Attribute Type Description Required
output file The output file. True
moduledefinition file The module definition file. False
options string Options to pass to the compiler. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
timeout int The maximum amount of time the application is allowed to execute, expressed in milliseconds. Defaults to no time-out. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Framework-configurable parameters

Attribute Type Description Required
exename string The name of the executable that should be used to launch the external program. False
managed ManagedExecution Specifies whether the external program should be treated as a managed application, possibly forcing it to be executed under the currently targeted version of the CLR. False
useruntimeengine bool Deprecated. Specifies whether the external program is a managed application which should be executed using a runtime engine, if configured. The default is false. False

Nested Elements:

<sources>

The list of files to combine into the output file.

</sources>

<symbols>

Symbols to add to the symbol table.
<symbol>

Represents a symbol.

Parameters

AttributeTypeDescriptionRequired
namestring The name of the symbol. True
ifbool If true then the element will be processed; otherwise, skipped. The default is true. False
unlessbool If true then the element will be skipped; otherwise, processed. The default is false. False
</symbol>

</symbols>

<ignorelibraries>

Names of default libraries to ignore.
<library>

Represents a library.

Parameters

AttributeTypeDescriptionRequired
namestring The name of the library. True
ifbool If true then the element will be processed; otherwise, skipped. The default is true. False
unlessbool If true then the element will be skipped; otherwise, processed. The default is false. False
</library>

</ignorelibraries>

<libdirs>

The list of additional library directories to search.

</libdirs>

<arg>

The command-line arguments for the external program.

Represents a command-line argument.

When passed to an external application, the argument will be quoted when appropriate. This does not apply to the line parameter, which is always passed as is.

Parameters

AttributeTypeDescriptionRequired
dirdirectory The value for a directory-based command-line argument; will be replaced with the absolute path of the directory. False
filefile The name of a file as a single command-line argument; will be replaced with the absolute filename of the file. False
ifbool Indicates if the argument should be passed to the external program. If true then the argument will be passed; otherwise, skipped. The default is true. False
linestring List of command-line arguments; will be passed to the executable as is. False
path<path> The value for a PATH-like command-line argument; you can use : or ; as path separators and NAnt will convert it to the platform's local conventions, while resolving references to environment variables. False
unlessbool Indicates if the argument should not be passed to the external program. If false then the argument will be passed; otherwise, skipped. The default is false. False
valuestring A single command-line argument; can contain space characters. False

Nested Elements:

<path>

Sets a single command-line argument and treats it like a PATH - ensures the right separator for the local platform is used.

</path>

Examples

  • A single command-line argument containing a space character.

    <arg value="-l -a" />
        
  • Two separate command-line arguments.

    <arg line="-l -a" />
        
  • A single command-line argument with the value \dir;\dir2;\dir3 on DOS-based systems and /dir:/dir2:/dir3 on Unix-like systems.

    <arg path="/dir;/dir2:\dir3" />
        

</arg>

Examples

  • Create a library.

    <lib output="library.lib">
        <sources>
            <include name="library.obj" />
        </sources>
    </lib>
        

Requirements

Assembly: NAnt.VisualCppTasks (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/foreach.html0000644000175000017500000002140411757307445020156 0ustar jtaylorjtaylor <foreach> Task

<foreach>

[This is preliminary documentation and subject to change.]

Loops over a set of items.

Can loop over files in directory, lines in a file, etc.

The property value is stored before the loop is done, and restored when the loop is finished.

The property is returned to its normal value once it is used. Read-only parameters cannot be overridden in this loop.

Parameters

Attribute Type Description Required
item LoopItem The type of iteration that should be done. True
property string The NAnt property name(s) that should be used for the current iterated item. True
delim string The deliminator char. False
in string The source of the iteration. False
trim LoopTrim The type of whitespace trimming that should be done. The default is None. False
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Nested Elements:

<in>

Stuff to operate in. Just like the in attribute, but supports more complicated things like a <fileset> and such.

Note: Please remove the in attribute if you are using this element.

Nested Elements:

<items>

</items>

</in>

<do>

Tasks to execute for each matching item.

Executes embedded tasks in the order in which they are defined.

Parameters

AttributeTypeDescriptionRequired
failonerrorbool Determines if task failure stops the build, or is just reported. The default is true. False
ifbool If true then the task will be executed; otherwise, skipped. The default is true. False
unlessbool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbosebool Determines whether the task should report detailed build log messages. The default is false. False

</do>

Examples

  • Loops over the files in c:\.

    <foreach item="File" in="c:\" property="filename">
        <echo message="${filename}" />
    </foreach>
        
  • Loops over all files in the project directory.

    <foreach item="File" property="filename">
        <in>
            <items>
                <include name="**" />
            </items>
        </in>
        <do>
            <echo message="${filename}" />
        </do>
    </foreach>
        
  • Loops over the folders in c:\.

    <foreach item="Folder" in="c:\" property="foldername">
        <echo message="${foldername}" />
    </foreach>
        
  • Loops over all folders in the project directory.

    <foreach item="Folder" property="foldername">
        <in>
            <items>
                <include name="**" />
            </items>
        </in>
        <do>
            <echo message="${foldername}" />
        </do>
    </foreach>
        
  • Loops over a list.

    <foreach item="String" in="1 2,3" delim=" ," property="count">
        <echo message="${count}" />
    </foreach>
        
  • Loops over lines in the file properties.csv, where each line is of the format name,value.

    <foreach item="Line" in="properties.csv" delim="," property="x,y">
        <echo message="Read pair ${x}=${y}" />
    </foreach>
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/tasks/trycatch.html0000644000175000017500000002201411757307455020367 0ustar jtaylorjtaylor <trycatch> Task

<trycatch>

[This is preliminary documentation and subject to change.]

Executes a set of tasks, and optionally catches a build exception to allow recovery or rollback steps to be taken, or to define some steps to be taken regardless if the tasks succeed or fail, or both.

The tasks defined in the <try> block will be executed in turn, as they normally would in a target.

If a <catch> block is defined, the tasks in that block will be executed in turn only if one of the tasks in the <try> block fails. This failure will then be suppressed by the <catch> block.

The message associated with the failure can also be caught in a property for use within the <catch> block. The original contents of the property will be restored upon exiting the <catch> block.

If a <finally> block is defined, the tasks in that block will be executed after the tasks in both the <try> and <catch> blocks have been executed, regardless of whether any task fails in either block.

Parameters

Attribute Type Description Required
failonerror bool Determines if task failure stops the build, or is just reported. The default is true. False
if bool If true then the task will be executed; otherwise, skipped. The default is true. False
unless bool Opposite of if. If false then the task will be executed; otherwise, skipped. The default is false. False
verbose bool Determines whether the task should report detailed build log messages. The default is false. False

Nested Elements:

<try>

The tasks in this block will be executed as a normal part of the build script.

Executes embedded tasks/elements in the order in which they are defined.

</try>

<catch>

The tasks in this block will be executed if any task in the try block fails.

Parameters

AttributeTypeDescriptionRequired
propertystring Defines the name of the property to save the message describing the failure that has been caught. False

</catch>

<finally>

The tasks in this block will always be executed, regardless of what happens in the try and catch blocks.

Executes embedded tasks/elements in the order in which they are defined.

</finally>

Examples

  • <trycatch>
        <try>
            <echo message="In try" />
            <fail message="Failing!" />
        </try>
        <catch>
            <echo message="In catch" />
        </catch>
        <finally>
            <echo message="Finally done" />
        </finally>
    </trycatch>
        

    The output of this example will be:

    In try
    In catch
    Finally done
      

    The failure in the <try> block will not cause the build to fail.

  • <trycatch>
        <try>
            <echo message="In try" />
            <fail message="Just because..." />
        </try>
        <catch property="failure">
            <echo message="Caught failure: ${failure}" />
            <fail message="Bad catch" />
        </catch>
        <finally>
            <echo message="Finally done" />
        </finally>
    </trycatch>
        

    The output of this example will be:

    In try
    Caught failure: Just because...
    Finally done
    Build failed: Bad catch
      

    Like the above, the failure in the <try> block does not cause the build to fail. The failure in the <catch> block does, however. Note that the <finally> block is executed even though the <catch> block failed.

  • <trycatch>
        <try>
            <echo message="In try" />
            <fail message="yet again" />
        </try>
        <catch property="failure">
            <echo message="Caught failure ${failure}" />
            <fail message="Bad catch" />
        </catch>
        <finally>
            <echo message="Finally done ${failure}" />
        </finally>
    </trycatch>
        

    The output of this example will be:

    In try
    Caught failure yet again
    Build failed: Property 'failure' has not been set.
      

    The <echo> task in the <finally> block failed because the "failure" property was not defined after exiting the <catch> block. Note that the failure in the <finally> block has eclipsed the failure in the <catch> block.

  • <trycatch>
        <try>
            <property name="temp.file" value="${path::get-temp-file-name()}" />
            <do-stuff to="${temp.file}" />
            <fail message="Oops..." />
        </try>
        <finally>
            <echo message="Cleaning up..." />
            <if test="${property::exists('temp.file')}">
                <delete file="${temp.file}" />
            </if>
        </finally>
    </trycatch>
        

    A more concrete example, that will always clean up the generated temporary file after it has been created.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/style.css0000644000175000017500000000662111757302272016403 0ustar jtaylorjtaylorbody { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 90%; background: white; color: black; } h1, h2, h3, h4, h5, h6 { font-family: Verdana, Arial, Helvetica, Geneva, SunSans-Regular, sans-serif; } h1.LinkHeader, h2.LinkHeader, h3.LinkHeader { margin-bottom: -18px; } h4 { margin-bottom: 0.5em; } hr { color: gray; background-color: inherit; } input { font-family: Verdana, Arial, Helvetica, Geneva, SunSans-Regular, sans-serif; } a:link { color: #0000cc; background-color: inherit; } a:visited { color: purple; background-color: inherit; } a:active { color: #cc0000; background-color: inherit; } a:hover { color: #cc0000; background-color: inherit; } a.heading:link { color: black; background-color: inherit; text-decoration: none; } a.heading:visited { color: black; background-color: inherit; text-decoration: none; } a.heading:active { color: black; background-color: inherit; text-decoration: none; } a.heading:hover { color: #0000cc; background-color: inherit; } .NavBar { color: black; background-color: #dfff80; border-color: #999966; border-style: none none solid none; border-width: 2px; } .NavBar-Cell { font-family: Verdana, Arial, Helvetica, Geneva, SunSans-Regular, sans-serif; font-size: 79%; } .SideBar { font-size: 80%; font-family: Verdana, Arial, Helvetica, Geneva, SunSans-Regular, sans-serif; padding: 8px; } div.table { margin-left: 40px; font-family: Verdana, Arial, Helvetica, Geneva, SunSans-Regular, sans-serif; font-size: 80%; } div.nested-element { margin-left: 40px; position: relative; } div.nested-element table { font-size: 100%; border-collapse: collapse; width: 710px; } .table table { font-size: 100%; border-collapse: collapse; width: 93%; } .table th { background-color: #eeeeee; color: #000000; font-weight: bolder; padding: 5px; border: 1px solid #999999; text-align: left; } .table td { border: 1px solid #999999; padding: 5px; } .table td.section { border: 1px solid #999999; background-color: #f0f0e0; padding: 5px; font-weight: bold; } .N { color: #99cc00; background-color: inherit; } .Ant { color: #ff9900; background-color: inherit; } pre { margin-top: .5em; margin-bottom: .5em; } code { font-family: Monospace, Courier New, Courier; background-color: inherit; color: #0000AA; font-size: 100%; } pre.code { font-family: Monospace, Courier New, Courier; background-color: inherit; color: #0000AA; font-size: 100%; } pre.syntax { background-color: #cccccc; padding: 4px 8px; cursor: text; margin-top: 1em; margin-bottom: 1em; color: #000000; border-width: 1px; border-style: solid; border-color: #999999; } span.code { font-family: Monospace, Courier New, Courier; background-color: inherit; color: #0000AA; font-size: 100%; } span.expression { font-family: Monospace, Courier New, Courier; background-color: inherit; color: #0000AA; font-weight: bold; font-size: 100%; } tr.required { } td.required { font-weight: bolder; } .missing { color: red; } span.parameter { color: #606080; } p.topicstatus { display: block; color: red; } ul.examples { list-style-type: lower-roman; } nant-0.92-rc1/doc/help/functions/0000755000175000017500000000000011757310030016523 5ustar jtaylorjtaylornant-0.92-rc1/doc/help/functions/string.trim-start(System.String).html0000644000175000017500000000415111757307610025632 0ustar jtaylorjtaylor string::trim-start Function

string::trim-start

[This is preliminary documentation and subject to change.]

Returns the given string trimmed of leading whitespace.

Usage

string string::trim-start(s)

Parameters

Name Type Description
s string input string

Return Value

The string s with any leading whites pace characters removed.

Examples

  • string::trim-start('  test  ') ==> 'test  '
  • string::trim-start('\t\tfoo  \r\n') ==> 'foo  \r\n'

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/environment.get-user-name().html0000644000175000017500000000367711757307573024605 0ustar jtaylorjtaylor environment::get-user-name Function

environment::get-user-name

[This is preliminary documentation and subject to change.]

Gets the user name of the person who started the current thread.

Usage

string environment::get-user-name()

Return Value

The name of the person logged on to the system who started the current thread.

Examples

  • Modify the home directory of the current user on unix-based systems.

    <exec program="usermod">
        <arg value="-d" />
        <arg value="/home/temp" />
        <arg value="${environment::get-user-name()}" />
    </exec>
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/datetime.to-string(System.DateTime).html0000644000175000017500000000470311757307571026177 0ustar jtaylorjtaylor datetime::to-string Function

datetime::to-string

[This is preliminary documentation and subject to change.]

Converts the specified DateTime to its equivalent string representation.

Usage

string datetime::to-string(value)

Parameters

Name Type Description
value datetime A DateTime to convert.

Return Value

A string representation of value formatted using the general format specifier ("G").

Remarks

value is formatted with the DateTimeFormatInfo for the invariant culture.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/version.get-minor(System.Version).html0000644000175000017500000000453611757307615025777 0ustar jtaylorjtaylor version::get-minor Function

version::get-minor

[This is preliminary documentation and subject to change.]

Gets the value of the minor component of a given version.

Usage

int version::get-minor(version)

Parameters

Name Type Description
version Version A version.

Return Value

The minor version number.

Requirements

Assembly: NAnt.Core (0.92.4526.0)

See Also

assemblyname::get-version() | environment::get-version() | operating-system::get-version() nant-0.92-rc1/doc/help/functions/environment.get-variable(System.String).html0000644000175000017500000000425611757307573027142 0ustar jtaylorjtaylor environment::get-variable Function

environment::get-variable

[This is preliminary documentation and subject to change.]

Returns the value of the specified environment variable.

Usage

string environment::get-variable(name)

Parameters

Name Type Description
name string The environment variable of which the value should be returned.

Return Value

The value of the specified environment variable.

Exceptions

The function will fail in any of the following circumstances:
  • Environment variable name does not exist.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/int.parse(System.String).html0000644000175000017500000000477011757307577024145 0ustar jtaylorjtaylor int::parse Function

int::parse

[This is preliminary documentation and subject to change.]

Converts the specified string representation of a number to its 32-bit signed integer equivalent.

Usage

int int::parse(s)

Parameters

Name Type Description
s string A string containing a number to convert.

Return Value

A 32-bit signed integer equivalent to the number contained in s.

Exceptions

The function will fail in any of the following circumstances:
  • s is not of the correct format.
  • s represents a number less than MinValue or greater than MaxValue.

Remarks

The NumberFormatInfo for the invariant culture is used to supply formatting information about s.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/assembly.load-from-file(System.String).html0000644000175000017500000000532011757307565026642 0ustar jtaylorjtaylor assembly::load-from-file Function

assembly::load-from-file

[This is preliminary documentation and subject to change.]

Loads an assembly given its file name or path.

Usage

Assembly assembly::load-from-file(assemblyFile)

Parameters

Name Type Description
assemblyFile string The name or path of the file that contains the manifest of the assembly.

Return Value

The loaded assembly.

Exceptions

The function will fail in any of the following circumstances:
  • assemblyFile is an empty String.
  • assemblyFile is not found, or the module you are trying to load does not specify a filename extension.
  • assemblyFile is not a valid assembly.
  • An assembly or module was loaded twice with two different evidences, or the assembly name is longer than MAX_PATH characters.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/project.get-buildfile-uri().html0000644000175000017500000000371111757307601024524 0ustar jtaylorjtaylor project::get-buildfile-uri Function

project::get-buildfile-uri

[This is preliminary documentation and subject to change.]

Gets the Uri form of the build file.

Usage

string project::get-buildfile-uri()

Return Value

The Uri form of the build file, or an empty String if the project is not file backed.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/double.to-string(System.Double).html0000644000175000017500000000465711757307573025405 0ustar jtaylorjtaylor double::to-string Function

double::to-string

[This is preliminary documentation and subject to change.]

Converts the specified Double to its equivalent string representation.

Usage

string double::to-string(value)

Parameters

Name Type Description
value double A Double to convert.

Return Value

The string representation of value formatted using the general format specifier ("G").

Remarks

value is formatted with the NumberFormatInfo for the invariant culture.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/pkg-config.exists(System.String).html0000644000175000017500000000415011757307606025565 0ustar jtaylorjtaylor pkg-config::exists Function

pkg-config::exists

[This is preliminary documentation and subject to change.]

Determines whether the given package exists.

Usage

bool pkg-config::exists(package)

Parameters

Name Type Description
package string The package to check.

Return Value

true if the package exists; otherwise, false.

Exceptions

The function will fail in any of the following circumstances:
  • pkg-config could not be started.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/assemblyname.get-name(System.Reflection.AssemblyName).html0000644000175000017500000000517011757307566031612 0ustar jtaylorjtaylor assemblyname::get-name Function

assemblyname::get-name

[This is preliminary documentation and subject to change.]

Gets the simple, unencrypted name of the assembly.

Usage

string assemblyname::get-name(assemblyName)

Parameters

Name Type Description
assemblyName AssemblyName The AssemblyName of the assembly.

Return Value

The simple, unencrypted name of the assembly.

Examples

  • Output the simple name of the nunit.framework assembly to the build log.

    <echo message="${assemblyname::get-name(assemblyname::get-assembly-name('nunit.framework.dll'))}" />
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)

See Also

assembly::get-name() nant-0.92-rc1/doc/help/functions/math.floor(System.Double).html0000644000175000017500000000367611757307600024246 0ustar jtaylorjtaylor math::floor Function

math::floor

[This is preliminary documentation and subject to change.]

Returns the largest whole number less than or equal to the specified number.

Usage

double math::floor(value)

Parameters

Name Type Description
value double value to be , can be anything convertible to a double

Return Value

The largest whole number less than or equal to the specified number.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/project.get-default-target().html0000644000175000017500000000353611757307601024705 0ustar jtaylorjtaylor project::get-default-target Function

project::get-default-target

[This is preliminary documentation and subject to change.]

Gets the name of the target that will be executed when no other build targets are specified.

Usage

string project::get-default-target()

Return Value

The name of the target that will be executed when no other build targets are specified, or an empty String if no default target is defined for the project.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/pkg-config.get-compile-flags(System.String).html0000644000175000017500000000443411757307606027552 0ustar jtaylorjtaylor pkg-config::get-compile-flags Function

pkg-config::get-compile-flags

[This is preliminary documentation and subject to change.]

Gets the compile flags required to compile the package, including all its dependencies.

Usage

string pkg-config::get-compile-flags(package)

Parameters

Name Type Description
package string The package for which the compile flags should be retrieved.

Return Value

The pre-processor and compile flags required to compile the package.

Exceptions

The function will fail in any of the following circumstances:
  • pkg-config could not be started.
  • package does not exist.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/convert.to-int(System.Int32).html0000644000175000017500000000373211757307567024560 0ustar jtaylorjtaylor convert::to-int Function

convert::to-int

[This is preliminary documentation and subject to change.]

(Deprecated)

Converts the argument to an integer.

Usage

int convert::to-int(value)

Parameters

Name Type Description
value int value to be converted

Return Value

value converted to integer. The function fails with an exception when the conversion is not possible.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/timespan.from-hours(System.Double).html0000644000175000017500000000437111757307614026113 0ustar jtaylorjtaylor timespan::from-hours Function

timespan::from-hours

[This is preliminary documentation and subject to change.]

Returns a TimeSpan that represents a specified number of hours, where the specification is accurate to the nearest millisecond.

Usage

timespan timespan::from-hours(value)

Parameters

Name Type Description
value double A number of hours, accurate to the nearest millisecond.

Return Value

A TimeSpan that represents value.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/datetime.get-day(System.DateTime).html0000644000175000017500000000363111757307570025601 0ustar jtaylorjtaylor datetime::get-day Function

datetime::get-day

[This is preliminary documentation and subject to change.]

Gets the day of the month represented by the specified date.

Usage

int datetime::get-day(date)

Parameters

Name Type Description
date datetime The date of which to get the day of the month.

Return Value

The day value, between 1 and 31.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/framework.get-version(System.String).html0000644000175000017500000000476011757307576026476 0ustar jtaylorjtaylor framework::get-version Function

framework::get-version

[This is preliminary documentation and subject to change.]

Gets the version of the specified framework.

Usage

Version framework::get-version(framework)

Parameters

Name Type Description
framework string The framework of which the version should be returned.

Return Value

The version of the specified framework.

Exceptions

The function will fail in any of the following circumstances:
  • framework is not a valid framework identifier.

Requirements

Assembly: NAnt.Core (0.92.4526.0)

See Also

framework::get-runtime-framework() | framework::get-target-framework() nant-0.92-rc1/doc/help/functions/string.pad-left(System.String,System.Int32,System.String).html0000644000175000017500000000672111757307610032132 0ustar jtaylorjtaylor string::pad-left Function

string::pad-left

[This is preliminary documentation and subject to change.]

Returns the given string left-padded to the given length.

Usage

string string::pad-left(s, totalWidth, paddingChar)

Parameters

Name Type Description
s string The String that needs to be left-padded.
totalWidth int The number of characters in the resulting string, equal to the number of original characters plus any additional padding characters.
paddingChar string A Unicode padding character.

Return Value

If the length of s is at least totalWidth, then a new String identical to s is returned. Otherwise, s will be padded on the left with as many paddingChar characters as needed to create a length of totalWidth.

Exceptions

The function will fail in any of the following circumstances:
  • totalWidth is less than zero.

Remarks

Note that only the first character of paddingChar will be used when padding the result.

Examples

  • string::pad-left('test', 10, ' ') ==> '      test'
  • string::pad-left('test', 10, 'test') ==> 'tttttttest'
  • string::pad-left('test', 3, ' ') ==> 'test'
  • string::pad-left('test', -4, ' ') ==> ERROR

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/timespan.get-total-hours(System.TimeSpan).html0000644000175000017500000000454711757307611027360 0ustar jtaylorjtaylor timespan::get-total-hours Function

timespan::get-total-hours

[This is preliminary documentation and subject to change.]

Returns the total number of hours represented by the specified TimeSpan, expressed in whole and fractional hours.

Usage

double timespan::get-total-hours(value)

Parameters

Name Type Description
value timespan A TimeSpan.

Return Value

The total number of hours represented by the given TimeSpan.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/target.has-executed(System.String).html0000644000175000017500000000422011757307602026061 0ustar jtaylorjtaylor target::has-executed Function

target::has-executed

[This is preliminary documentation and subject to change.]

Checks whether the specified target has already been executed.

Usage

bool target::has-executed(name)

Parameters

Name Type Description
name string The target to test.

Return Value

true if the specified target has already been executed; otherwise, false.

Exceptions

The function will fail in any of the following circumstances:
  • Target name does not exist.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/assembly.load(System.String).html0000644000175000017500000000544411757307565024773 0ustar jtaylorjtaylor assembly::load Function

assembly::load

[This is preliminary documentation and subject to change.]

Loads an assembly given the long form of its name.

Usage

Assembly assembly::load(assemblyString)

Parameters

Name Type Description
assemblyString string The long form of the assembly name.

Return Value

The loaded assembly.

Exceptions

The function will fail in any of the following circumstances:
  • assemblyString is a a null reference (Nothing in Visual Basic).
  • assemblyString is not found.

Examples

  • Determine the location of the Microsoft Access 11 Primary Interop Assembly by loading it using its fully qualified name, and copy it to the build directory.

    <property name="access.pia.path" value="${assembly::get-location(assembly::load('Microsoft.Office.Interop.Access, Version=11.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c'))}" />
    <copy file="${access.pia.path}" todir="${build.dir}" />
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/int.to-string(System.Int32).html0000644000175000017500000000474611757307600024400 0ustar jtaylorjtaylor int::to-string Function

int::to-string

[This is preliminary documentation and subject to change.]

Converts the specified Int32 to its equivalent string representation.

Usage

string int::to-string(value)

Parameters

Name Type Description
value int A Int32 to convert.

Return Value

The string representation of value, consisting of a negative sign if the value is negative, and a sequence of digits ranging from 0 to 9 with no leading zeroes.

Remarks

value is formatted with the NumberFormatInfo for the invariant culture.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/datetime.is-leap-year(System.Int32).html0000644000175000017500000000367211757307571025750 0ustar jtaylorjtaylor datetime::is-leap-year Function

datetime::is-leap-year

[This is preliminary documentation and subject to change.]

Returns an indication whether the specified year is a leap year.

Usage

bool datetime::is-leap-year(year)

Parameters

Name Type Description
year int A 4-digit year.

Return Value

true if year is a leap year; otherwise, false.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/file.up-to-date(System.String,System.String).html0000644000175000017500000000516611757307574027662 0ustar jtaylorjtaylor file::up-to-date Function

file::up-to-date

[This is preliminary documentation and subject to change.]

Determines whether targetFile is more or equal up-to-date than srcFile.

Usage

bool file::up-to-date(srcFile, targetFile)

Parameters

Name Type Description
srcFile string The file to check against the target file.
targetFile string The file for which we want to determine the status.

Return Value

true if targetFile is more or equal up-to-date than srcFile; otherwise, false.

Exceptions

The function will fail in any of the following circumstances:
  • srcFile or targetFile is a zero-length string, contains only white space, or contains one or more invalid characters.
  • The specified path, file name, or both of either srcFile or targetFile exceed the system-defined maximum length.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/pkg-config.is-exact-version(System.String,System.String).html0000644000175000017500000000461111757307606032176 0ustar jtaylorjtaylor pkg-config::is-exact-version Function

pkg-config::is-exact-version

[This is preliminary documentation and subject to change.]

Determines whether the given package is exactly version version.

Usage

bool pkg-config::is-exact-version(package, version)

Parameters

Name Type Description
package string The package to check.
version string The version the package should have.

Return Value

true if the given package is exactly version version; otherwise, false.

Exceptions

The function will fail in any of the following circumstances:
  • pkg-config could not be started.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/index.html0000644000175000017500000015660211757307417020551 0ustar jtaylorjtaylor Function Reference

Function Reference

[This is preliminary documentation and subject to change.]

Assembly Functions
Conversion Functions
Date/Time Functions
Directory Functions
DNS Functions
Environment Functions
File Functions
Math Functions
NAnt Functions
Operating System Functions
Path Functions
String Functions
Unix/Cygwin Functions
Version Functions

Assembly Functions

Name Summary
assembly::get-full-name Gets the full name of the assembly, also known as the display name.
assembly::get-location Gets the physical location, in codebase format, of the loaded file that contains the manifest.
assembly::get-name Gets an AssemblyName for the specified assembly.
assembly::load Loads an assembly given the long form of its name.
assembly::load-from-file Loads an assembly given its file name or path.
assemblyname::get-assembly-name Gets the AssemblyName for a given file.
assemblyname::get-codebase Gets the location of the assembly as a URL.
assemblyname::get-escaped-codebase Gets the URI, including escape characters, that represents the codebase.
assemblyname::get-full-name Gets the full name of the assembly, also known as the display name.
assemblyname::get-name Gets the simple, unencrypted name of the assembly.
assemblyname::get-version Gets the version of the assembly.

Conversion Functions

Name Summary
bool::parse Converts the specified string representation of a logical value to its Boolean equivalent.
bool::to-string Converts the specified Boolean to its equivalent string representation.
convert::to-boolean Converts the argument to a boolean
convert::to-datetime Converts the argument to a datetime.
convert::to-double Converts the argument to double
convert::to-int Converts the argument to an integer.
convert::to-string Converts the argument to a string.
datetime::format-to-string Converts the specified DateTime to its equivalent string representation.
datetime::parse Converts the specified string representation of a date and time to its DateTime equivalent.
datetime::to-string Converts the specified DateTime to its equivalent string representation.
double::parse Converts the specified string representation of a number to its double-precision floating point number equivalent.
double::to-string Converts the specified Double to its equivalent string representation.
int::parse Converts the specified string representation of a number to its 32-bit signed integer equivalent.
int::to-string Converts the specified Int32 to its equivalent string representation.
long::parse Converts the specified string representation of a number to its 64-bit signed integer equivalent.
long::to-string Converts the specified Int64 to its equivalent string representation.
timespan::parse Constructs a TimeSpan from a time indicated by a specified string.
timespan::to-string Converts the specified TimeSpan to its equivalent string representation.
version::parse Converts the specified string representation of a version to its Version equivalent.
version::to-string Converts the specified Version to its equivalent string representation.

Date/Time Functions

Name Summary
datetime::get-day Gets the day of the month represented by the specified date.
datetime::get-day-of-week Gets the day of the week represented by the specified date.
datetime::get-day-of-year Gets the day of the year represented by the specified date.
datetime::get-days-in-month Returns the number of days in the specified month of the specified year.
datetime::get-hour Gets the hour component of the specified date.
datetime::get-millisecond Gets the milliseconds component of the specified date.
datetime::get-minute Gets the minute component of the specified date.
datetime::get-month Gets the month component of the specified date.
datetime::get-second Gets the seconds component of the specified date.
datetime::get-ticks Gets the number of ticks that represent the specified date.
datetime::get-year Gets the year component of the specified date.
datetime::is-leap-year Returns an indication whether the specified year is a leap year.
datetime::now Gets a DateTime that is the current local date and time on this computer.
timespan::from-days Returns a TimeSpan that represents a specified number of days, where the specification is accurate to the nearest millisecond.
timespan::from-hours Returns a TimeSpan that represents a specified number of hours, where the specification is accurate to the nearest millisecond.
timespan::from-milliseconds Returns a TimeSpan that represents a specified number of milliseconds.
timespan::from-minutes Returns a TimeSpan that represents a specified number of minutes, where the specification is accurate to the nearest millisecond.
timespan::from-seconds Returns a TimeSpan that represents a specified number of seconds, where the specification is accurate to the nearest millisecond.
timespan::from-ticks Returns a TimeSpan that represents a specified time, where the specification is in units of ticks.
timespan::get-days Returns the number of whole days represented by the specified TimeSpan.
timespan::get-hours Returns the number of whole hours represented by the specified TimeSpan.
timespan::get-milliseconds Returns the number of whole milliseconds represented by the specified TimeSpan.
timespan::get-minutes Returns the number of whole minutes represented by the specified TimeSpan.
timespan::get-seconds Returns the number of whole seconds represented by the specified TimeSpan.
timespan::get-ticks Returns the number of ticks contained in the specified TimeSpan.
timespan::get-total-days Returns the total number of days represented by the specified TimeSpan, expressed in whole and fractional days.
timespan::get-total-hours Returns the total number of hours represented by the specified TimeSpan, expressed in whole and fractional hours.
timespan::get-total-milliseconds Returns the total number of milliseconds represented by the specified TimeSpan, expressed in whole and fractional milliseconds.
timespan::get-total-minutes Returns the total number of minutes represented by the specified TimeSpan, expressed in whole and fractional minutes.
timespan::get-total-seconds Returns the total number of seconds represented by the specified TimeSpan, expressed in whole and fractional seconds.

Directory Functions

Name Summary
directory::exists Determines whether the given path refers to an existing directory on disk.
directory::get-creation-time Returns the creation date and time of the specified directory.
directory::get-current-directory Gets the current working directory.
directory::get-directory-root Returns the volume information, root information, or both for the specified path.
directory::get-last-access-time Returns the date and time the specified directory was last accessed.
directory::get-last-write-time Returns the date and time the specified directory was last written to.
directory::get-parent-directory Retrieves the parent directory of the specified path.

DNS Functions

Name Summary
dns::get-host-name Gets the host name of the local computer.

Environment Functions

Name Summary
environment::get-folder-path Gets the path to the system special folder identified by the specified enumeration.
environment::get-machine-name Gets the NetBIOS name of this local computer.
environment::get-operating-system Gets an OperatingSystem object that represents the current operating system.
environment::get-user-name Gets the user name of the person who started the current thread.
environment::get-variable Returns the value of the specified environment variable.
environment::get-version Gets a Version object that describes the major, minor, build, and revision numbers of the Common Language Runtime.
environment::newline Gets the newline string defined for this environment.
environment::variable-exists Gets a value indicating whether the specified environment variable exists.

File Functions

Name Summary
file::exists Determines whether the specified file exists.
file::get-creation-time Returns the creation date and time of the specified file.
file::get-last-access-time Returns the date and time the specified file was last accessed.
file::get-last-write-time Returns the date and time the specified file was last written to.
file::get-length Gets the length of the file.
file::is-assembly Checks if a given file is an assembly.
file::up-to-date Determines whether targetFile is more or equal up-to-date than srcFile.

Math Functions

Name Summary
math::abs Returns the absolute value of the specified number
math::ceiling Returns the smallest whole number greater than or equal to the specified number
math::floor Returns the largest whole number less than or equal to the specified number.
math::round Rounds the value to the nearest whole number

NAnt Functions

Name Summary
framework::exists Checks whether the specified framework exists, and is valid.
framework::get-assembly-directory Gets the assembly directory of the specified framework.
framework::get-clr-version Gets the Common Language Runtime version of the current target framework.
framework::get-clr-version Gets the Common Language Runtime version of the specified framework.
framework::get-description Gets the description of the current target framework.
framework::get-description Gets the description of the specified framework.
framework::get-family Gets the family of the specified framework.
framework::get-framework-directory Gets the framework directory of the specified framework.
framework::get-frameworks Gets a comma-separated list of frameworks filtered by the specified FrameworkTypes.
framework::get-runtime-engine Gets the runtime engine of the specified framework.
framework::get-runtime-framework Gets the identifier of the runtime framework.
framework::get-sdk-directory Gets the SDK directory of the specified framework.
framework::get-target-framework Gets the identifier of the current target framework.
framework::get-tool-path Gets the absolute path of the specified tool for the current target framework.
framework::get-version Gets the version of the current target framework.
framework::get-version Gets the version of the specified framework.
framework::sdk-exists Checks whether the SDK for the specified framework is installed.
nant::get-assembly Gets the NAnt assembly.
nant::get-base-directory Gets the base directory of the appdomain in which NAnt is running.
platform::get-name Gets the name of the platform on which NAnt is running.
platform::is-unix Checks whether NAnt is running on Unix.
platform::is-win32 Checks whether NAnt is running on Windows (and not just 32-bit Windows as the name may lead you to believe).
platform::is-windows Checks whether NAnt is running on Windows.
project::get-base-directory Gets the base directory of the current project.
project::get-buildfile-path Gets the local path to the build file.
project::get-buildfile-uri Gets the Uri form of the build file.
project::get-default-target Gets the name of the target that will be executed when no other build targets are specified.
project::get-name Gets the name of the current project.
property::exists Checks whether the specified property exists.
property::get-value Gets the value of the specified property.
property::is-dynamic Checks whether the specified property is a dynamic property.
property::is-readonly Checks whether the specified property is read-only.
target::exists Checks whether the specified target exists.
target::get-current-target Gets the name of the target being executed.
target::has-executed Checks whether the specified target has already been executed.
task::exists Checks whether the specified task exists.
task::get-assembly Returns the Assembly from which the specified task was loaded.

Operating System Functions

Name Summary
operating-system::get-platform Gets a PlatformID value that identifies the operating system platform.
operating-system::get-version Gets a Version object that identifies this operating system.
operating-system::to-string Converts the value of the specified operating system to its equivalent String representation.

Path Functions

Name Summary
path::change-extension Changes the extension of the path string.
path::combine Combines two paths.
path::get-directory-name Returns the directory information for the specified path string.
path::get-extension Returns the extension for the specified path string.
path::get-file-name Returns the filename for the specified path string.
path::get-file-name-without-extension Returns the filename without extension for the specified path string.
path::get-full-path Returns the fully qualified path.
path::get-path-root Gets the root directory of the specified path.
path::get-temp-file-name Returns a uniquely named zero-byte temporary file on disk and returns the full path to that file.
path::get-temp-path Gets the path to the temporary directory.
path::has-extension Determines whether a path string includes an extension.
path::is-path-rooted Determines whether a path string is absolute.

String Functions

Name Summary
string::contains Tests whether the specified string contains the given search string.
string::ends-with Tests whether the specified string ends with the specified suffix string.
string::get-length Returns the length of the specified string.
string::index-of Returns the position of the first occurrence in the specified string of the given search string.
string::last-index-of Returns the position of the last occurrence in the specified string of the given search string.
string::pad-left Returns the given string left-padded to the given length.
string::pad-right Returns the given string right-padded to the given length.
string::replace Returns a string corresponding to the replacement of a given string with another in the specified string.
string::starts-with Tests whether the specified string starts with the specified prefix string.
string::substring Returns a substring of the specified string.
string::to-lower Returns the specified string converted to lowercase.
string::to-upper Returns the specified string converted to uppercase.
string::trim Returns the given string trimmed of whitespace.
string::trim-end Returns the given string trimmed of trailing whitespace.
string::trim-start Returns the given string trimmed of leading whitespace.

Unix/Cygwin Functions

Name Summary
cygpath::get-dos-path Gets the DOS (short) form of the specified path.
cygpath::get-unix-path Gets the Unix form of the specified path.
cygpath::get-windows-path Gets the Windows form of the specified path.
pkg-config::exists Determines whether the given package exists.
pkg-config::get-compile-flags Gets the compile flags required to compile the package, including all its dependencies.
pkg-config::get-link-flags Gets the link flags required to compile the package, including all its dependencies.
pkg-config::get-mod-version Determines the version of the given package.
pkg-config::get-variable Gets the value of a variable for the specified package.
pkg-config::is-atleast-version Determines whether the given package is at least version version.
pkg-config::is-between-version Determines whether the given package is between two versions.
pkg-config::is-exact-version Determines whether the given package is exactly version version.
pkg-config::is-max-version Determines whether the given package is at no newer than version version.

Version Functions

Name Summary
fileversioninfo::get-company-name Gets the name of the company that produced the file.
fileversioninfo::get-file-version Gets the file version of a file.
fileversioninfo::get-product-name Gets the name of the product the file is distributed with.
fileversioninfo::get-product-version Gets the product version of a file.
fileversioninfo::get-version-info Returns a FileVersionInfo representing the version information associated with the specified file.
version::get-build Gets the value of the build component of a given version.
version::get-major Gets the value of the major component of a given version.
version::get-minor Gets the value of the minor component of a given version.
version::get-revision Gets the value of the revision component of a given version.
nant-0.92-rc1/doc/help/functions/string.trim-end(System.String).html0000644000175000017500000000413311757307610025243 0ustar jtaylorjtaylor string::trim-end Function

string::trim-end

[This is preliminary documentation and subject to change.]

Returns the given string trimmed of trailing whitespace.

Usage

string string::trim-end(s)

Parameters

Name Type Description
s string input string

Return Value

The string s with any trailing white space characters removed.

Examples

  • string::trim-end('  test  ') ==> '  test'
  • string::trim-end('\t\tfoo  \r\n') ==> '\t\tfoo'

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/file.get-length(System.String).html0000644000175000017500000000404511757307574025206 0ustar jtaylorjtaylor file::get-length Function

file::get-length

[This is preliminary documentation and subject to change.]

Gets the length of the file.

Usage

long file::get-length(file)

Parameters

Name Type Description
file string filename

Return Value

Length in bytes, of the file named file.

Exceptions

The function will fail in any of the following circumstances:
  • The file specified cannot be found.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/framework.exists(System.String).html0000644000175000017500000000366711757307575025557 0ustar jtaylorjtaylor framework::exists Function

framework::exists

[This is preliminary documentation and subject to change.]

Checks whether the specified framework exists, and is valid.

Usage

bool framework::exists(framework)

Parameters

Name Type Description
framework string The framework to test.

Return Value

true if the specified framework exists ; otherwise, false.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/nant.get-assembly().html0000644000175000017500000000317511757307601023105 0ustar jtaylorjtaylor nant::get-assembly Function

nant::get-assembly

[This is preliminary documentation and subject to change.]

Gets the NAnt assembly.

Usage

Assembly nant::get-assembly()

Return Value

The NAnt assembly.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/framework.get-assembly-directory(System.String).html0000644000175000017500000000470311757307576030627 0ustar jtaylorjtaylor framework::get-assembly-directory Function

framework::get-assembly-directory

[This is preliminary documentation and subject to change.]

Gets the assembly directory of the specified framework.

Usage

string framework::get-assembly-directory(framework)

Parameters

Name Type Description
framework string The framework of which the assembly directory should be returned.

Return Value

The assembly directory of the specified framework.

Exceptions

The function will fail in any of the following circumstances:
  • framework is not a valid framework identifier.

Requirements

Assembly: NAnt.Core (0.92.4526.0)

See Also

framework::get-runtime-framework() | framework::get-target-framework() nant-0.92-rc1/doc/help/functions/timespan.get-total-days(System.TimeSpan).html0000644000175000017500000000453711757307611027157 0ustar jtaylorjtaylor timespan::get-total-days Function

timespan::get-total-days

[This is preliminary documentation and subject to change.]

Returns the total number of days represented by the specified TimeSpan, expressed in whole and fractional days.

Usage

double timespan::get-total-days(value)

Parameters

Name Type Description
value timespan A TimeSpan.

Return Value

The total number of days represented by the given TimeSpan.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/directory.get-directory-root(System.String).html0000644000175000017500000000462211757307572027776 0ustar jtaylorjtaylor directory::get-directory-root Function

directory::get-directory-root

[This is preliminary documentation and subject to change.]

Returns the volume information, root information, or both for the specified path.

Usage

string directory::get-directory-root(path)

Parameters

Name Type Description
path string The path for which to retrieve the parent directory.

Return Value

A string containing the volume information, root information, or both for the specified path.

Exceptions

The function will fail in any of the following circumstances:
  • path is a zero-length string, contains only white space, or contains one or more invalid characters.
  • The specified path, file name, or both exceed the system-defined maximum length.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/fileversioninfo.get-version-info(System.String).html0000644000175000017500000000525311757307575030630 0ustar jtaylorjtaylor fileversioninfo::get-version-info Function

fileversioninfo::get-version-info

[This is preliminary documentation and subject to change.]

Returns a FileVersionInfo representing the version information associated with the specified file.

Usage

FileVersionInfo fileversioninfo::get-version-info(fileName)

Parameters

Name Type Description
fileName string The file to retrieve the version information for.

Return Value

A FileVersionInfo containing information about the file.

Exceptions

The function will fail in any of the following circumstances:
  • The file specified cannot be found.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/platform.is-unix().html0000644000175000017500000000304511757307602022766 0ustar jtaylorjtaylor platform::is-unix Function

platform::is-unix

[This is preliminary documentation and subject to change.]

Checks whether NAnt is running on Unix.

Usage

bool platform::is-unix()

Return Value

true if NAnt is running on Unix; otherwise, false.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/operating-system.get-version(System.OperatingSystem).html0000644000175000017500000000526011757307603031665 0ustar jtaylorjtaylor operating-system::get-version Function

operating-system::get-version

[This is preliminary documentation and subject to change.]

Gets a Version object that identifies this operating system.

Usage

Version operating-system::get-version(operatingSystem)

Parameters

Name Type Description
operatingSystem OperatingSystem The operating system.

Return Value

A Version object that describes the major version, minor version, build, and revision of the operating system.

Requirements

Assembly: NAnt.Core (0.92.4526.0)

See Also

environment::get-operating-system() nant-0.92-rc1/doc/help/functions/datetime.get-month(System.DateTime).html0000644000175000017500000000362111757307570026150 0ustar jtaylorjtaylor datetime::get-month Function

datetime::get-month

[This is preliminary documentation and subject to change.]

Gets the month component of the specified date.

Usage

int datetime::get-month(date)

Parameters

Name Type Description
date datetime The date of which to get the month component.

Return Value

The month, between 1 and 12.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootnant-0.92-rc1/doc/help/functions/fileversioninfo.get-file-version(System.Diagnostics.FileVersionInfo).htmlnant-0.92-rc1/doc/help/functions/fileversioninfo.get-file-version(System.Diagnostics.FileVersionInfo0000644000175000017500000000466311757307575033645 0ustar jtaylorjtaylor fileversioninfo::get-file-version Function

fileversioninfo::get-file-version

[This is preliminary documentation and subject to change.]

Gets the file version of a file.

Usage

Version fileversioninfo::get-file-version(fileVersionInfo)

Parameters

Name Type Description
fileVersionInfo FileVersionInfo A FileVersionInfo instance containing version information about a file.

Return Value

The file version of a file.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/timespan.to-string(System.TimeSpan).html0000644000175000017500000000434311757307615026246 0ustar jtaylorjtaylor timespan::to-string Function

timespan::to-string

[This is preliminary documentation and subject to change.]

Converts the specified TimeSpan to its equivalent string representation.

Usage

string timespan::to-string(value)

Parameters

Name Type Description
value timespan A TimeSpan to convert.

Return Value

The string representation of value. The format of the return value is of the form: [-][d.]hh:mm:ss[.ff].

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/long.parse(System.String).html0000644000175000017500000000477511757307600024302 0ustar jtaylorjtaylor long::parse Function

long::parse

[This is preliminary documentation and subject to change.]

Converts the specified string representation of a number to its 64-bit signed integer equivalent.

Usage

long long::parse(s)

Parameters

Name Type Description
s string A string containing a number to convert.

Return Value

A 64-bit signed integer equivalent to the number contained in s.

Exceptions

The function will fail in any of the following circumstances:
  • s is not of the correct format.
  • s represents a number less than MinValue or greater than MaxValue.

Remarks

The NumberFormatInfo for the invariant culture is used to supply formatting information about s.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/assemblyname.get-version(System.Reflection.AssemblyName).html0000644000175000017500000000551411757307566032361 0ustar jtaylorjtaylor assemblyname::get-version Function

assemblyname::get-version

[This is preliminary documentation and subject to change.]

Gets the version of the assembly.

Usage

Version assemblyname::get-version(assemblyName)

Parameters

Name Type Description
assemblyName AssemblyName The AssemblyName of the assembly.

Return Value

The version of the assembly.

Examples

  • Output the major version of the nunit.framework assembly to the build log.

    <echo message="${version::get-major-version(assemblyname::get-version(assemblyname::get-assembly-name('nunit.framework.dll')))}" />
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)

See Also

assembly::get-name() | Version Functions nant-0.92-rc1/doc/help/functions/string.pad-right(System.String,System.Int32,System.String).html0000644000175000017500000000673511757307610032322 0ustar jtaylorjtaylor string::pad-right Function

string::pad-right

[This is preliminary documentation and subject to change.]

Returns the given string right-padded to the given length.

Usage

string string::pad-right(s, totalWidth, paddingChar)

Parameters

Name Type Description
s string The String that needs to be right-padded.
totalWidth int The number of characters in the resulting string, equal to the number of original characters plus any additional padding characters.
paddingChar string A Unicode padding character.

Return Value

If the length of s is at least totalWidth, then a new String identical to s is returned. Otherwise, s will be padded on the right with as many paddingChar characters as needed to create a length of totalWidth.

Exceptions

The function will fail in any of the following circumstances:
  • totalWidth is less than zero.

Remarks

Note that only the first character of paddingChar will be used when padding the result.

Examples

  • string::pad-right('test', 10, ' ') ==> 'test      '
  • string::pad-right('test', 10, 'abcd') ==> 'testaaaaaa'
  • string::pad-right('test', 3, ' ') ==> 'test'
  • string::pad-right('test', -3, ' ') ==> ERROR

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/directory.get-parent-directory(System.String).html0000644000175000017500000000610711757307572030304 0ustar jtaylorjtaylor directory::get-parent-directory Function

directory::get-parent-directory

[This is preliminary documentation and subject to change.]

Retrieves the parent directory of the specified path.

Usage

string directory::get-parent-directory(path)

Parameters

Name Type Description
path string The path for which to retrieve the parent directory.

Return Value

The parent directory, or an empty String if path is the root directory, including the root of a UNC server or share name.

Exceptions

The function will fail in any of the following circumstances:
  • The directory specified by path is read-only.
  • path is a zero-length string, contains only white space, or contains one or more invalid characters.
  • The specified path, file name, or both exceed the system-defined maximum length.
  • The specified path was not found.

Examples

  • Copy "readme.txt" from the current working directory to its parent directory.

    <property name="current.dir" value="${directory::get-current-directory()}" />
    <property name="current.dir.parent" value="${directory::get-parent-directory(current.dir)}" />
    <copy file="${path::combine(current.dir, 'readme.txt')} todir="${current.dir.parent}" />
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/path.is-path-rooted(System.String).html0000644000175000017500000000420711757307605026017 0ustar jtaylorjtaylor path::is-path-rooted Function

path::is-path-rooted

[This is preliminary documentation and subject to change.]

Determines whether a path string is absolute.

Usage

bool path::is-path-rooted(path)

Parameters

Name Type Description
path string The path to test.

Return Value

true if path contains an absolute path; otherwise, false.

Exceptions

The function will fail in any of the following circumstances:
  • path contains one or more invalid characters.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/project.get-base-directory().html0000644000175000017500000000310611757307601024702 0ustar jtaylorjtaylor project::get-base-directory Function

project::get-base-directory

[This is preliminary documentation and subject to change.]

Gets the base directory of the current project.

Usage

string project::get-base-directory()

Return Value

The base directory of the current project.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/framework.get-runtime-framework().html0000644000175000017500000000313111757307576026004 0ustar jtaylorjtaylor framework::get-runtime-framework Function

framework::get-runtime-framework

[This is preliminary documentation and subject to change.]

Gets the identifier of the runtime framework.

Usage

string framework::get-runtime-framework()

Return Value

The identifier of the runtime framework.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/framework.get-sdk-directory(System.String).html0000644000175000017500000000514011757307577027566 0ustar jtaylorjtaylor framework::get-sdk-directory Function

framework::get-sdk-directory

[This is preliminary documentation and subject to change.]

Gets the SDK directory of the specified framework.

Usage

string framework::get-sdk-directory(framework)

Parameters

Name Type Description
framework string The framework of which the SDK directory should be returned.

Return Value

The SDK directory of the specified framework, or an empty String if the SDK of the specified framework is not installed.

Exceptions

The function will fail in any of the following circumstances:
  • framework is not a valid framework identifier.

Requirements

Assembly: NAnt.Core (0.92.4526.0)

See Also

framework::get-runtime-framework() | framework::get-target-framework() nant-0.92-rc1/doc/help/functions/assemblyname.get-full-name(System.Reflection.AssemblyName).html0000644000175000017500000000526511757307566032557 0ustar jtaylorjtaylor assemblyname::get-full-name Function

assemblyname::get-full-name

[This is preliminary documentation and subject to change.]

Gets the full name of the assembly, also known as the display name.

Usage

string assemblyname::get-full-name(assemblyName)

Parameters

Name Type Description
assemblyName AssemblyName The AssemblyName of the assembly.

Return Value

The full name of the assembly, also known as the display name.

Examples

  • Output the full name of the nunit.framework assembly to the build log.

    <echo message="${assemblyname::get-full-name(assemblyname::get-assembly-name('nunit.framework.dll'))}" />
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)

See Also

assembly::get-name() nant-0.92-rc1/doc/help/functions/assembly.get-location(System.Reflection.Assembly).html0000644000175000017500000000417511757307565031043 0ustar jtaylorjtaylor assembly::get-location Function

assembly::get-location

[This is preliminary documentation and subject to change.]

Gets the physical location, in codebase format, of the loaded file that contains the manifest.

Usage

string assembly::get-location(assembly)

Parameters

Name Type Description
assembly Assembly The assembly to get the location for.

Return Value

The location of the specified assembly.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/version.get-revision(System.Version).html0000644000175000017500000000462611757307616026512 0ustar jtaylorjtaylor version::get-revision Function

version::get-revision

[This is preliminary documentation and subject to change.]

Gets the value of the revision component of a given version.

Usage

int version::get-revision(version)

Parameters

Name Type Description
version Version A version.

Return Value

The revision number, or -1 if the revision number is undefined.

Requirements

Assembly: NAnt.Core (0.92.4526.0)

See Also

assemblyname::get-version() | environment::get-version() | operating-system::get-version() nant-0.92-rc1/doc/help/functions/directory.get-creation-time(System.String).html0000644000175000017500000000462611757307572027555 0ustar jtaylorjtaylor directory::get-creation-time Function

directory::get-creation-time

[This is preliminary documentation and subject to change.]

Returns the creation date and time of the specified directory.

Usage

datetime directory::get-creation-time(path)

Parameters

Name Type Description
path string The directory for which to obtain creation date and time information.

Return Value

The creation date and time of the specified directory.

Exceptions

The function will fail in any of the following circumstances:
  • The specified directory does not exist.
  • path is a zero-length string, contains only white space, or contains one or more invalid characters.
  • The specified path, file name, or both exceed the system-defined maximum length.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/directory.get-last-access-time(System.String).html0000644000175000017500000000475111757307572030152 0ustar jtaylorjtaylor directory::get-last-access-time Function

directory::get-last-access-time

[This is preliminary documentation and subject to change.]

Returns the date and time the specified directory was last accessed.

Usage

datetime directory::get-last-access-time(path)

Parameters

Name Type Description
path string The directory for which to obtain access date and time information.

Return Value

The date and time the specified directory was last accessed.

Exceptions

The function will fail in any of the following circumstances:
  • The specified directory does not exist.
  • path is a zero-length string, contains only white space, or contains one or more invalid characters.
  • The specified path, file name, or both exceed the system-defined maximum length.
  • The path parameter is in an invalid format.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/file.exists(System.String).html0000644000175000017500000000415511757307574024471 0ustar jtaylorjtaylor file::exists Function

file::exists

[This is preliminary documentation and subject to change.]

Determines whether the specified file exists.

Usage

bool file::exists(file)

Parameters

Name Type Description
file string The file to check.

Return Value

true if file refers to an existing file; otherwise, false.

Examples

  • Execute a set of tasks, if file "output.xml" does not exist.

    <if test="${not file::exists('output.xml')}">
        ...
    </if>
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/datetime.parse(System.String).html0000644000175000017500000000530111757307571025130 0ustar jtaylorjtaylor datetime::parse Function

datetime::parse

[This is preliminary documentation and subject to change.]

Converts the specified string representation of a date and time to its DateTime equivalent.

Usage

datetime datetime::parse(s)

Parameters

Name Type Description
s string A string containing a date and time to convert.

Return Value

A DateTime equivalent to the date and time contained in s.

Exceptions

The function will fail in any of the following circumstances:
  • s does not contain a valid string representation of a date and time.

Remarks

The DateTimeFormatInfo for the invariant culture is used to supply formatting information about s.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/path.get-file-name(System.String).html0000644000175000017500000000507511757307604025575 0ustar jtaylorjtaylor path::get-file-name Function

path::get-file-name

[This is preliminary documentation and subject to change.]

Returns the filename for the specified path string.

Usage

string path::get-file-name(path)

Parameters

Name Type Description
path string The path string from which to obtain the file name and extension.

Return Value

A String consisting of the characters after the last directory character in path.

If the last character of path is a directory or volume separator character, an empty String is returned.

Exceptions

The function will fail in any of the following circumstances:
  • path contains one or more invalid characters.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/pkg-config.is-max-version(System.String,System.String).html0000644000175000017500000000463111757307606031661 0ustar jtaylorjtaylor pkg-config::is-max-version Function

pkg-config::is-max-version

[This is preliminary documentation and subject to change.]

Determines whether the given package is at no newer than version version.

Usage

bool pkg-config::is-max-version(package, version)

Parameters

Name Type Description
package string The package to check.
version string The version the package should maximum have.

Return Value

true if the given package is at no newer than version version; otherwise, false.

Exceptions

The function will fail in any of the following circumstances:
  • pkg-config could not be started.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/version.get-build(System.Version).html0000644000175000017500000000457611757307615025756 0ustar jtaylorjtaylor version::get-build Function

version::get-build

[This is preliminary documentation and subject to change.]

Gets the value of the build component of a given version.

Usage

int version::get-build(version)

Parameters

Name Type Description
version Version A version.

Return Value

The build number, or -1 if the build number is undefined.

Requirements

Assembly: NAnt.Core (0.92.4526.0)

See Also

assemblyname::get-version() | environment::get-version() | operating-system::get-version() nant-0.92-rc1/doc/help/functions/framework.sdk-exists(System.String).html0000644000175000017500000000426511757307576026332 0ustar jtaylorjtaylor framework::sdk-exists Function

framework::sdk-exists

[This is preliminary documentation and subject to change.]

Checks whether the SDK for the specified framework is installed.

Usage

bool framework::sdk-exists(framework)

Parameters

Name Type Description
framework string The framework to test.

Return Value

true if the SDK for specified framework is installed; otherwise, false.

Requirements

Assembly: NAnt.Core (0.92.4526.0)

See Also

framework::get-runtime-framework() | framework::get-target-framework() nant-0.92-rc1/doc/help/functions/long.to-string(System.Int64).html0000644000175000017500000000475311757307600024550 0ustar jtaylorjtaylor long::to-string Function

long::to-string

[This is preliminary documentation and subject to change.]

Converts the specified Int64 to its equivalent string representation.

Usage

string long::to-string(value)

Parameters

Name Type Description
value long A Int64 to convert.

Return Value

The string representation of value, consisting of a negative sign if the value is negative, and a sequence of digits ranging from 0 to 9 with no leading zeroes.

Remarks

value is formatted with the NumberFormatInfo for the invariant culture.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootnant-0.92-rc1/doc/help/functions/assemblyname.get-escaped-codebase(System.Reflection.AssemblyName).htmlnant-0.92-rc1/doc/help/functions/assemblyname.get-escaped-codebase(System.Reflection.AssemblyName).h0000644000175000017500000000470311757307566033325 0ustar jtaylorjtaylor assemblyname::get-escaped-codebase Function

assemblyname::get-escaped-codebase

[This is preliminary documentation and subject to change.]

Gets the URI, including escape characters, that represents the codebase.

Usage

string assemblyname::get-escaped-codebase(assemblyName)

Parameters

Name Type Description
assemblyName AssemblyName The AssemblyName of the assembly.

Return Value

The URI, including escape characters, that represents the codebase.

Requirements

Assembly: NAnt.Core (0.92.4526.0)

See Also

assembly::get-name() nant-0.92-rc1/doc/help/functions/string.contains(System.String,System.String).html0000644000175000017500000000513211757307607030076 0ustar jtaylorjtaylor string::contains Function

string::contains

[This is preliminary documentation and subject to change.]

Tests whether the specified string contains the given search string.

Usage

bool string::contains(source, value)

Parameters

Name Type Description
source string The string to search.
value string The string to locate within source.

Return Value

true if value is found in source; otherwise, false.

Remarks

This function performs a case-sensitive word search using the invariant culture.

Examples

  • string::contains('testing string', 'test') ==> true
  • string::contains('testing string', '') ==> true
  • string::contains('testing string', 'Test') ==> false
  • string::contains('testing string', 'foo') ==> false

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/double.parse(System.String).html0000644000175000017500000000507711757307572024621 0ustar jtaylorjtaylor double::parse Function

double::parse

[This is preliminary documentation and subject to change.]

Converts the specified string representation of a number to its double-precision floating point number equivalent.

Usage

double double::parse(s)

Parameters

Name Type Description
s string A string containing a number to convert.

Return Value

A double-precision floating point number equivalent to the numeric value or symbol specified in s.

Exceptions

The function will fail in any of the following circumstances:
  • s is not a number in a valid format.
  • s represents a number less than MinValue or greater than MaxValue.

Remarks

The NumberFormatInfo for the invariant culture is used to supply formatting information about s.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/datetime.get-minute(System.DateTime).html0000644000175000017500000000363111757307570026325 0ustar jtaylorjtaylor datetime::get-minute Function

datetime::get-minute

[This is preliminary documentation and subject to change.]

Gets the minute component of the specified date.

Usage

int datetime::get-minute(date)

Parameters

Name Type Description
date datetime The date of which to get the minute component.

Return Value

The minute, between 0 and 59.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/convert.to-datetime(System.DateTime).html0000644000175000017500000000377611757307567026367 0ustar jtaylorjtaylor convert::to-datetime Function

convert::to-datetime

[This is preliminary documentation and subject to change.]

(Deprecated)

Converts the argument to a datetime.

Usage

datetime convert::to-datetime(value)

Parameters

Name Type Description
value datetime value to be converted

Return Value

value converted to datetime. The function fails with an exception when the conversion is not possible.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/string.last-index-of(System.String,System.String).html0000644000175000017500000000550411757307610030727 0ustar jtaylorjtaylor string::last-index-of Function

string::last-index-of

[This is preliminary documentation and subject to change.]

Returns the position of the last occurrence in the specified string of the given search string.

Usage

int string::last-index-of(source, value)

Parameters

Name Type Description
source string The string to search.
value string The string to locate within source.

Return Value

The highest-index position of value in source if it is found, or -1 if source does not contain value.

If value is an empty string, the return value is the last index position in source.

Remarks

This function performs a case-sensitive word search using the invariant culture.

Examples

  • string::last-index-of('testing string', 'test') ==> 0
  • string::last-index-of('testing string', '') ==> 13
  • string::last-index-of('testing string', 'Test') ==> -1
  • string::last-index-of('testing string', 'ing') ==> 11

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/bool.to-string(System.Boolean).html0000644000175000017500000000425611757307567025231 0ustar jtaylorjtaylor bool::to-string Function

bool::to-string

[This is preliminary documentation and subject to change.]

Converts the specified Boolean to its equivalent string representation.

Usage

string bool::to-string(value)

Parameters

Name Type Description
value bool A Boolean to convert.

Return Value

"True" if value is true, or "False" if value is false.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/bool.parse(System.String).html0000644000175000017500000000445711757307567024307 0ustar jtaylorjtaylor bool::parse Function

bool::parse

[This is preliminary documentation and subject to change.]

Converts the specified string representation of a logical value to its Boolean equivalent.

Usage

bool bool::parse(s)

Parameters

Name Type Description
s string A string containing the value to convert.

Return Value

true if s is equivalent to "True"; otherwise, false.

Exceptions

The function will fail in any of the following circumstances:
  • s is not equivalent to TrueString or FalseString.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/timespan.get-seconds(System.TimeSpan).html0000644000175000017500000000445411757307613026534 0ustar jtaylorjtaylor timespan::get-seconds Function

timespan::get-seconds

[This is preliminary documentation and subject to change.]

Returns the number of whole seconds represented by the specified TimeSpan.

Usage

int timespan::get-seconds(value)

Parameters

Name Type Description
value timespan A TimeSpan.

Return Value

The number of whole seconds represented by the given TimeSpan.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/environment.newline().html0000644000175000017500000000343111757307574023562 0ustar jtaylorjtaylor environment::newline Function

environment::newline

[This is preliminary documentation and subject to change.]

Gets the newline string defined for this environment.

Usage

string environment::newline()

Return Value

A string containing CRLF for non-Unix platforms, or LF for Unix platforms.

Examples

  • Output two lines in a log file.

    <echo file="build.log" message="First line${environment::newline()}Second line" />
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootnant-0.92-rc1/doc/help/functions/fileversioninfo.get-company-name(System.Diagnostics.FileVersionInfo).htmlnant-0.92-rc1/doc/help/functions/fileversioninfo.get-company-name(System.Diagnostics.FileVersionInfo0000644000175000017500000000452711757307575033626 0ustar jtaylorjtaylor fileversioninfo::get-company-name Function

fileversioninfo::get-company-name

[This is preliminary documentation and subject to change.]

Gets the name of the company that produced the file.

Usage

string fileversioninfo::get-company-name(fileVersionInfo)

Parameters

Name Type Description
fileVersionInfo FileVersionInfo A FileVersionInfo instance containing version information about a file.

Return Value

The name of the company that produced the file.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/path.change-extension(System.String,System.String).html0000644000175000017500000000645111757307604031147 0ustar jtaylorjtaylor path::change-extension Function

path::change-extension

[This is preliminary documentation and subject to change.]

Changes the extension of the path string.

Usage

string path::change-extension(path, extension)

Parameters

Name Type Description
path string The path information to modify. The path cannot contain any of the characters defined in InvalidPathCharsInvalidPathChars.
extension string The new extension (with a leading period). Specify a null reference to remove an existing extension from path.

Return Value

A string containing the modified path information.

On Windows-based desktop platforms, if path is an empty String, the path information is returned unmodified. If path has no extension, the returned path String contains extension appended to the end of path.

Exceptions

The function will fail in any of the following circumstances:
  • path contains one or more invalid characters.

Remarks

For more information see the Path documentation.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/project.get-buildfile-path().html0000644000175000017500000000334411757307601024663 0ustar jtaylorjtaylor project::get-buildfile-path Function

project::get-buildfile-path

[This is preliminary documentation and subject to change.]

Gets the local path to the build file.

Usage

string project::get-buildfile-path()

Return Value

The local path of the build file, or an empty String if the project is not file backed.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/path.get-path-root(System.String).html0000644000175000017500000000474311757307605025657 0ustar jtaylorjtaylor path::get-path-root Function

path::get-path-root

[This is preliminary documentation and subject to change.]

Gets the root directory of the specified path.

Usage

string path::get-path-root(path)

Parameters

Name Type Description
path string The path from which to obtain root directory information.

Return Value

A String containing the root directory of path, such as "C:\", or an empty String if path does not contain root directory information.

Exceptions

The function will fail in any of the following circumstances:
  • path contains invalid characters, or is empty.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/framework.get-description().html0000644000175000017500000000327711757307576024664 0ustar jtaylorjtaylor framework::get-description Function

framework::get-description

[This is preliminary documentation and subject to change.]

Gets the description of the current target framework.

Usage

string framework::get-description()

Return Value

The description of the current target framework.

Requirements

Assembly: NAnt.Core (0.92.4526.0)

See Also

framework::get-target-framework() nant-0.92-rc1/doc/help/functions/string.to-lower(System.String).html0000644000175000017500000000440211757307607025301 0ustar jtaylorjtaylor string::to-lower Function

string::to-lower

[This is preliminary documentation and subject to change.]

Returns the specified string converted to lowercase.

Usage

string string::to-lower(s)

Parameters

Name Type Description
s string input string

Return Value

The string s in lowercase.

Remarks

The casing rules of the invariant culture are used to convert the s to lowercase.

Examples

  • string::to-lower('testing string') ==> 'testing string'
  • string::to-lower('Testing String') ==> 'testing string'
  • string::to-lower('Test 123') ==> 'test 123'

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/platform.is-win32().html0000644000175000017500000000324011757307602022742 0ustar jtaylorjtaylor platform::is-win32 Function

platform::is-win32

[This is preliminary documentation and subject to change.]

(Deprecated)

Checks whether NAnt is running on Windows (and not just 32-bit Windows as the name may lead you to believe).

Usage

bool platform::is-win32()

Return Value

true if NAnt is running on Windows; otherwise, false.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/timespan.get-minutes(System.TimeSpan).html0000644000175000017500000000445411757307613026562 0ustar jtaylorjtaylor timespan::get-minutes Function

timespan::get-minutes

[This is preliminary documentation and subject to change.]

Returns the number of whole minutes represented by the specified TimeSpan.

Usage

int timespan::get-minutes(value)

Parameters

Name Type Description
value timespan A TimeSpan.

Return Value

The number of whole minutes represented by the given TimeSpan.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/math.ceiling(System.Double).html0000644000175000017500000000363711757307600024534 0ustar jtaylorjtaylor math::ceiling Function

math::ceiling

[This is preliminary documentation and subject to change.]

Returns the smallest whole number greater than or equal to the specified number

Usage

double math::ceiling(value)

Parameters

Name Type Description
value double value

Return Value

The smallest whole number greater than or equal to the specified number.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/pkg-config.is-atleast-version(System.String,System.String).html0000644000175000017500000000463611757307606032536 0ustar jtaylorjtaylor pkg-config::is-atleast-version Function

pkg-config::is-atleast-version

[This is preliminary documentation and subject to change.]

Determines whether the given package is at least version version.

Usage

bool pkg-config::is-atleast-version(package, version)

Parameters

Name Type Description
package string The package to check.
version string The version the package should at least have.

Return Value

true if the given package is at least version version; otherwise, false.

Exceptions

The function will fail in any of the following circumstances:
  • pkg-config could not be started.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/datetime.get-ticks(System.DateTime).html0000644000175000017500000000371511757307570026144 0ustar jtaylorjtaylor datetime::get-ticks Function

datetime::get-ticks

[This is preliminary documentation and subject to change.]

Gets the number of ticks that represent the specified date.

Usage

long datetime::get-ticks(date)

Parameters

Name Type Description
date datetime The date of which to get the number of ticks.

Return Value

The number of ticks that represent the date and time of the specified date.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/cygpath.get-dos-path(System.String).html0000644000175000017500000000424111757307616026157 0ustar jtaylorjtaylor cygpath::get-dos-path Function

cygpath::get-dos-path

[This is preliminary documentation and subject to change.]

Gets the DOS (short) form of the specified path.

Usage

string cygpath::get-dos-path(path)

Parameters

Name Type Description
path string The path to convert.

Return Value

The DOS (short) form of the specified path.

Exceptions

The function will fail in any of the following circumstances:
  • cygpath could not be started.
  • path could not be converted to a short form.

Requirements

Assembly: NAnt.Win32Tasks (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/timespan.get-days(System.TimeSpan).html0000644000175000017500000000530611757307612026032 0ustar jtaylorjtaylor timespan::get-days Function

timespan::get-days

[This is preliminary documentation and subject to change.]

Returns the number of whole days represented by the specified TimeSpan.

Usage

int timespan::get-days(value)

Parameters

Name Type Description
value timespan A TimeSpan.

Return Value

The number of whole days represented by the given TimeSpan.

Examples

  • Remove all files that have not been modified in the last 7 days from directory "binaries".

    <foreach item="File" in="binaries" property="filename">
        <if test="${timespan::get-days(datetime::now() - file::get-last-write-time(filename)) >= 7}">
            <delete file="${filename}" />
        </if>
    </foreach>
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/datetime.get-hour(System.DateTime).html0000644000175000017500000000361111757307570025777 0ustar jtaylorjtaylor datetime::get-hour Function

datetime::get-hour

[This is preliminary documentation and subject to change.]

Gets the hour component of the specified date.

Usage

int datetime::get-hour(date)

Parameters

Name Type Description
date datetime The date of which to get the hour component.

Return Value

The hour, between 0 and 23.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/datetime.format-to-string(System.DateTime,System.String).html0000644000175000017500000000515711757307572032220 0ustar jtaylorjtaylor datetime::format-to-string Function

datetime::format-to-string

[This is preliminary documentation and subject to change.]

Converts the specified DateTime to its equivalent string representation.

Usage

string datetime::format-to-string(value, format)

Parameters

Name Type Description
value datetime A DateTime to convert.
format string A format string.

Return Value

A string representation of value formatted using the specified format

Remarks

value is formatted with the DateTimeFormatInfo for the invariant culture.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/pkg-config.get-variable(System.String,System.String).html0000644000175000017500000000457311757307605031346 0ustar jtaylorjtaylor pkg-config::get-variable Function

pkg-config::get-variable

[This is preliminary documentation and subject to change.]

Gets the value of a variable for the specified package.

Usage

string pkg-config::get-variable(package, name)

Parameters

Name Type Description
package string The package for which the variable should be retrieved.
name string The name of the variable.

Return Value

The value of variable name for the specified package.

Exceptions

The function will fail in any of the following circumstances:
  • pkg-config could not be started.
  • package does not exist.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/string.ends-with(System.String,System.String).html0000644000175000017500000000521611757307607030165 0ustar jtaylorjtaylor string::ends-with Function

string::ends-with

[This is preliminary documentation and subject to change.]

Tests whether the specified string ends with the specified suffix string.

Usage

bool string::ends-with(s1, s2)

Parameters

Name Type Description
s1 string test string
s2 string suffix string

Return Value

true when s2 is a suffix for the string s1. Meaning, the characters at the end of s1 are identical to s2; otherwise, false.

Remarks

This function performs a case-sensitive word search using the invariant culture.

Examples

  • string::ends-with('testing string', 'string') ==> true
  • string::ends-with('testing string', '') ==> true
  • string::ends-with('testing string', 'bring') ==> false
  • string::ends-with('string', 'testing string') ==> false

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/framework.get-tool-path(System.String).html0000644000175000017500000000542011757307577026713 0ustar jtaylorjtaylor framework::get-tool-path Function

framework::get-tool-path

[This is preliminary documentation and subject to change.]

Gets the absolute path of the specified tool for the current target framework.

Usage

string framework::get-tool-path(tool)

Parameters

Name Type Description
tool string The file name of the tool to search for.

Return Value

The absolute path to tool if found in one of the configured tool paths; otherwise, an error is reported.

Exceptions

The function will fail in any of the following circumstances:
  • tool could not be found in the configured tool paths.

Remarks

The configured tool paths are scanned in the order in which they are defined in the framework configuration.

The file name of the tool to search should include the extension.

Examples

  • Use gacutil to install an assembly in the GAC.

    <exec program="${framework::get-tool-path('gacutil.exe')}" managed="strict">
        <arg value="/i" />
        <arg file="Cegeka.HealthFramework.dll" />
    </exec>
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/property.is-readonly(System.String).html0000644000175000017500000000444411757307602026336 0ustar jtaylorjtaylor property::is-readonly Function

property::is-readonly

[This is preliminary documentation and subject to change.]

Checks whether the specified property is read-only.

Usage

bool property::is-readonly(name)

Parameters

Name Type Description
name string The property to test.

Return Value

true if the specified property is read-only; otherwise, false.

Exceptions

The function will fail in any of the following circumstances:
  • Property name has not been set.

Examples

  • Check whether the "debug" property is read-only.

    property::is-readonly('debug')

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/environment.get-folder-path(System.Environment.SpecialFolder).html0000644000175000017500000000555011757307573033331 0ustar jtaylorjtaylor environment::get-folder-path Function

environment::get-folder-path

[This is preliminary documentation and subject to change.]

Gets the path to the system special folder identified by the specified enumeration.

Usage

string environment::get-folder-path(folder)

Parameters

Name Type Description
folder SpecialFolder An enumerated constant that identifies a system special folder.

Return Value

The path to the specified system special folder, if that folder physically exists on your computer; otherwise, the empty string ("").

Exceptions

The function will fail in any of the following circumstances:

Examples

  • Copy "out.log" from the project base directory to the program files directory.

    <copy file="out.log" todir="${environment::get-folder-path('ProgramFiles')}" />
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/environment.get-operating-system().html0000644000175000017500000000503411757307573026210 0ustar jtaylorjtaylor environment::get-operating-system Function

environment::get-operating-system

[This is preliminary documentation and subject to change.]

Gets an OperatingSystem object that represents the current operating system.

Usage

OperatingSystem environment::get-operating-system()

Return Value

An OperatingSystem object that contains the current platform identifier and version number.

Examples

  • Output string representation of the current operating system.

    <echo message="OS=${operating-system::to-string(environment::get-operating-system())}" />
        

    If the operating system is Windows 2000, the output is:

    Microsoft Windows NT 5.0.2195.0
      

Requirements

Assembly: NAnt.Core (0.92.4526.0)

See Also

Operating System Functions nant-0.92-rc1/doc/help/functions/file.get-last-access-time(System.String).html0000644000175000017500000000470111757307574027062 0ustar jtaylorjtaylor file::get-last-access-time Function

file::get-last-access-time

[This is preliminary documentation and subject to change.]

Returns the date and time the specified file was last accessed.

Usage

datetime file::get-last-access-time(path)

Parameters

Name Type Description
path string The file for which to obtain access date and time information.

Return Value

The date and time the specified file was last accessed.

Exceptions

The function will fail in any of the following circumstances:
  • The specified file does not exist.
  • path is a zero-length string, contains only white space, or contains one or more invalid characters.
  • The specified path, file name, or both exceed the system-defined maximum length.
  • The path parameter is in an invalid format.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/path.get-full-path(System.String).html0000644000175000017500000000455511757307603025635 0ustar jtaylorjtaylor path::get-full-path Function

path::get-full-path

[This is preliminary documentation and subject to change.]

Returns the fully qualified path.

Usage

string path::get-full-path(path)

Parameters

Name Type Description
path string The file or directory for which to obtain absolute path information.

Return Value

A string containing the fully qualified location of path, such as "C:\MyFile.txt".

Exceptions

The function will fail in any of the following circumstances:
  • path is a zero-length string, contains only white space, or contains one or more invalid characters.
  • path contains a colon (":").
  • The specified path, file name, or both exceed the system-defined maximum length.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/path.get-temp-path().html0000644000175000017500000000325511757307605023164 0ustar jtaylorjtaylor path::get-temp-path Function

path::get-temp-path

[This is preliminary documentation and subject to change.]

Gets the path to the temporary directory.

Usage

string path::get-temp-path()

Return Value

A String containing the path information of a temporary directory.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/framework.get-target-framework().html0000644000175000017500000000314211757307576025611 0ustar jtaylorjtaylor framework::get-target-framework Function

framework::get-target-framework

[This is preliminary documentation and subject to change.]

Gets the identifier of the current target framework.

Usage

string framework::get-target-framework()

Return Value

The identifier of the current target framework.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootnant-0.92-rc1/doc/help/functions/fileversioninfo.get-product-version(System.Diagnostics.FileVersionInfo).htmlnant-0.92-rc1/doc/help/functions/fileversioninfo.get-product-version(System.Diagnostics.FileVersionI0000644000175000017500000000471011757307575033674 0ustar jtaylorjtaylor fileversioninfo::get-product-version Function

fileversioninfo::get-product-version

[This is preliminary documentation and subject to change.]

Gets the product version of a file.

Usage

Version fileversioninfo::get-product-version(fileVersionInfo)

Parameters

Name Type Description
fileVersionInfo FileVersionInfo A FileVersionInfo instance containing version information about a file.

Return Value

The product version of a file.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/datetime.get-day-of-week(System.DateTime).html0000644000175000017500000000376411757307570027143 0ustar jtaylorjtaylor datetime::get-day-of-week Function

datetime::get-day-of-week

[This is preliminary documentation and subject to change.]

Gets the day of the week represented by the specified date.

Usage

int datetime::get-day-of-week(date)

Parameters

Name Type Description
date datetime The date of which to get the day of the week.

Return Value

The day of the week, ranging from zero, indicating Sunday, to six, indicating Saturday.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/timespan.from-minutes(System.Double).html0000644000175000017500000000440711757307614026437 0ustar jtaylorjtaylor timespan::from-minutes Function

timespan::from-minutes

[This is preliminary documentation and subject to change.]

Returns a TimeSpan that represents a specified number of minutes, where the specification is accurate to the nearest millisecond.

Usage

timespan timespan::from-minutes(value)

Parameters

Name Type Description
value double A number of minutes, accurate to the nearest millisecond.

Return Value

A TimeSpan that represents value.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/string.starts-with(System.String,System.String).html0000644000175000017500000000525411757307607030556 0ustar jtaylorjtaylor string::starts-with Function

string::starts-with

[This is preliminary documentation and subject to change.]

Tests whether the specified string starts with the specified prefix string.

Usage

bool string::starts-with(s1, s2)

Parameters

Name Type Description
s1 string test string
s2 string prefix string

Return Value

true when s2 is a prefix for the string s1. Meaning, the characters at the beginning of s1 are identical to s2; otherwise, false.

Remarks

This function performs a case-sensitive word search using the invariant culture.

Examples

  • string::starts-with('testing string', 'test') ==> true
  • string::starts-with('testing string', 'testing') ==> true
  • string::starts-with('testing string', 'string') ==> false
  • string::starts-with('test', 'testing string') ==> false

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/timespan.get-milliseconds(System.TimeSpan).html0000644000175000017500000000451711757307613027563 0ustar jtaylorjtaylor timespan::get-milliseconds Function

timespan::get-milliseconds

[This is preliminary documentation and subject to change.]

Returns the number of whole milliseconds represented by the specified TimeSpan.

Usage

int timespan::get-milliseconds(value)

Parameters

Name Type Description
value timespan A TimeSpan.

Return Value

The number of whole milliseconds represented by the given TimeSpan.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/cygpath.get-windows-path(System.String).html0000644000175000017500000000425711757307616027073 0ustar jtaylorjtaylor cygpath::get-windows-path Function

cygpath::get-windows-path

[This is preliminary documentation and subject to change.]

Gets the Windows form of the specified path.

Usage

string cygpath::get-windows-path(path)

Parameters

Name Type Description
path string The path to convert.

Return Value

The Windows form of the specified path.

Exceptions

The function will fail in any of the following circumstances:
  • cygpath could not be started.
  • path could not be converted to a Windows form.

Requirements

Assembly: NAnt.Win32Tasks (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/environment.get-machine-name().html0000644000175000017500000000342711757307573025224 0ustar jtaylorjtaylor environment::get-machine-name Function

environment::get-machine-name

[This is preliminary documentation and subject to change.]

Gets the NetBIOS name of this local computer.

Usage

string environment::get-machine-name()

Return Value

The NetBIOS name of this local computer.

Exceptions

The function will fail in any of the following circumstances:
  • The name of this computer cannot be obtained.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/assemblyname.get-codebase(System.Reflection.AssemblyName).html0000644000175000017500000000454211757307566032441 0ustar jtaylorjtaylor assemblyname::get-codebase Function

assemblyname::get-codebase

[This is preliminary documentation and subject to change.]

Gets the location of the assembly as a URL.

Usage

string assemblyname::get-codebase(assemblyName)

Parameters

Name Type Description
assemblyName AssemblyName The AssemblyName of the assembly.

Return Value

The location of the assembly as a URL.

Requirements

Assembly: NAnt.Core (0.92.4526.0)

See Also

assembly::get-name() nant-0.92-rc1/doc/help/functions/operating-system.get-platform(System.OperatingSystem).html0000644000175000017500000000524111757307603032023 0ustar jtaylorjtaylor operating-system::get-platform Function

operating-system::get-platform

[This is preliminary documentation and subject to change.]

Gets a PlatformID value that identifies the operating system platform.

Usage

PlatformID operating-system::get-platform(operatingSystem)

Parameters

Name Type Description
operatingSystem OperatingSystem The operating system.

Return Value

PlatformID value that identifies the operating system platform.

Requirements

Assembly: NAnt.Core (0.92.4526.0)

See Also

environment::get-operating-system() nant-0.92-rc1/doc/help/functions/assembly.get-full-name(System.Reflection.Assembly).html0000644000175000017500000000417611757307565031114 0ustar jtaylorjtaylor assembly::get-full-name Function

assembly::get-full-name

[This is preliminary documentation and subject to change.]

Gets the full name of the assembly, also known as the display name.

Usage

string assembly::get-full-name(assembly)

Parameters

Name Type Description
assembly Assembly The assembly to get the full name for.

Return Value

The full name of the assembly, also known as the display name.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/version.get-major(System.Version).html0000644000175000017500000000453611757307615025763 0ustar jtaylorjtaylor version::get-major Function

version::get-major

[This is preliminary documentation and subject to change.]

Gets the value of the major component of a given version.

Usage

int version::get-major(version)

Parameters

Name Type Description
version Version A version.

Return Value

The major version number.

Requirements

Assembly: NAnt.Core (0.92.4526.0)

See Also

assemblyname::get-version() | environment::get-version() | operating-system::get-version() nant-0.92-rc1/doc/help/functions/assemblyname.get-assembly-name(System.String).html0000644000175000017500000000644311757307567030231 0ustar jtaylorjtaylor assemblyname::get-assembly-name Function

assemblyname::get-assembly-name

[This is preliminary documentation and subject to change.]

Gets the AssemblyName for a given file.

Usage

AssemblyName assemblyname::get-assembly-name(assemblyFile)

Parameters

Name Type Description
assemblyFile string The assembly file for which to get the AssemblyName.

Return Value

An AssemblyName object representing the given file.

Exceptions

The function will fail in any of the following circumstances:
  • assemblyFile is an empty String.
  • assemblyFile does not exist.
  • assemblyFile is not a valid assembly.

Remarks

The assembly is not added to this domain.

Examples

  • Output the full name of the nunit.framework assembly to the build log.

    <echo message="${assemblyname::get-full-name(assemblyname::get-assembly-name('nunit.framework.dll'))}" />
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/datetime.get-millisecond(System.DateTime).html0000644000175000017500000000370411757307570027327 0ustar jtaylorjtaylor datetime::get-millisecond Function

datetime::get-millisecond

[This is preliminary documentation and subject to change.]

Gets the milliseconds component of the specified date.

Usage

int datetime::get-millisecond(date)

Parameters

Name Type Description
date datetime The date of which to get the milliseconds component.

Return Value

The millisecond, between 0 and 999.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/timespan.get-total-seconds(System.TimeSpan).html0000644000175000017500000000456711757307611027660 0ustar jtaylorjtaylor timespan::get-total-seconds Function

timespan::get-total-seconds

[This is preliminary documentation and subject to change.]

Returns the total number of seconds represented by the specified TimeSpan, expressed in whole and fractional seconds.

Usage

double timespan::get-total-seconds(value)

Parameters

Name Type Description
value timespan A TimeSpan.

Return Value

The total number of seconds represented by the given TimeSpan.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/target.exists(System.String).html0000644000175000017500000000414711757307601025030 0ustar jtaylorjtaylor target::exists Function

target::exists

[This is preliminary documentation and subject to change.]

Checks whether the specified target exists.

Usage

bool target::exists(name)

Parameters

Name Type Description
name string The target to test.

Return Value

true if the specified target exists; otherwise, false.

Examples

  • Execute target "clean", if it exists.

    <if test="${target::exists('clean')}">
        <call target="clean" />
    </if>
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/version.to-string(System.Version).html0000644000175000017500000000550311757307616026020 0ustar jtaylorjtaylor version::to-string Function

version::to-string

[This is preliminary documentation and subject to change.]

Converts the specified Version to its equivalent string representation.

Usage

string version::to-string(value)

Parameters

Name Type Description
value Version A Version to convert.

Return Value

The string representation of the values of the major, minor, build, and revision components of the specified Version.

Requirements

Assembly: NAnt.Core (0.92.4526.0)

See Also

assemblyname::get-version() | environment::get-version() | operating-system::get-version() nant-0.92-rc1/doc/help/functions/convert.to-boolean(System.Boolean).html0000644000175000017500000000404111757307567026057 0ustar jtaylorjtaylor convert::to-boolean Function

convert::to-boolean

[This is preliminary documentation and subject to change.]

(Deprecated)

Converts the argument to a boolean

Usage

bool convert::to-boolean(value)

Parameters

Name Type Description
value bool The string value to be converted to boolean. Must be 'true' or 'false'.

Return Value

value converted to boolean. The function fails with an exception when the conversion is not possible.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/framework.get-clr-version().html0000644000175000017500000000355211757307576024600 0ustar jtaylorjtaylor framework::get-clr-version Function

framework::get-clr-version

[This is preliminary documentation and subject to change.]

Gets the Common Language Runtime version of the current target framework.

Usage

Version framework::get-clr-version()

Return Value

The Common Language Runtime version of the current target framework.

Requirements

Assembly: NAnt.Core (0.92.4526.0)

See Also

framework::get-target-framework() nant-0.92-rc1/doc/help/functions/datetime.get-year(System.DateTime).html0000644000175000017500000000361311757307570025764 0ustar jtaylorjtaylor datetime::get-year Function

datetime::get-year

[This is preliminary documentation and subject to change.]

Gets the year component of the specified date.

Usage

int datetime::get-year(date)

Parameters

Name Type Description
date datetime The date of which to get the year component.

Return Value

The year, between 1 and 9999.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/property.exists(System.String).html0000644000175000017500000000435711757307602025432 0ustar jtaylorjtaylor property::exists Function

property::exists

[This is preliminary documentation and subject to change.]

Checks whether the specified property exists.

Usage

bool property::exists(name)

Parameters

Name Type Description
name string The property to test.

Return Value

true if the specified property exists; otherwise, false.

Examples

  • Execute a set of tasks if the "build.debug" property exists.

    <if test="${property::exists('build.debug')}">
        <echo message="Starting debug build" />
        <call target="init-debug" />
        <call target="build" />
    </if>
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/datetime.get-days-in-month(System.Int32,System.Int32).html0000644000175000017500000000452111757307571031075 0ustar jtaylorjtaylor datetime::get-days-in-month Function

datetime::get-days-in-month

[This is preliminary documentation and subject to change.]

Returns the number of days in the specified month of the specified year.

Usage

int datetime::get-days-in-month(year, month)

Parameters

Name Type Description
year int The year.
month int The month (a number ranging from 1 to 12).

Return Value

The number of days in month for the specified year.

Exceptions

The function will fail in any of the following circumstances:
  • month is less than 1 or greater than 12.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/environment.get-version().html0000644000175000017500000000406411757307574024366 0ustar jtaylorjtaylor environment::get-version Function

environment::get-version

[This is preliminary documentation and subject to change.]

Gets a Version object that describes the major, minor, build, and revision numbers of the Common Language Runtime.

Usage

Version environment::get-version()

Return Value

A Version object.

Examples

  • Output the major version of the CLR.

    <echo message="Major version=${version::get-major(environment::get-version())}" />
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/timespan.from-milliseconds(System.Double).html0000644000175000017500000000430511757307614027435 0ustar jtaylorjtaylor timespan::from-milliseconds Function

timespan::from-milliseconds

[This is preliminary documentation and subject to change.]

Returns a TimeSpan that represents a specified number of milliseconds.

Usage

timespan timespan::from-milliseconds(value)

Parameters

Name Type Description
value double A number of milliseconds.

Return Value

A TimeSpan that represents value.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/framework.get-runtime-engine(System.String).html0000644000175000017500000000517611757307577027742 0ustar jtaylorjtaylor framework::get-runtime-engine Function

framework::get-runtime-engine

[This is preliminary documentation and subject to change.]

Gets the runtime engine of the specified framework.

Usage

string framework::get-runtime-engine(framework)

Parameters

Name Type Description
framework string The framework of which the runtime engine should be returned.

Return Value

The full path to the runtime engine of the specified framework, or an empty String if no runtime engine is defined for the specified framework.

Exceptions

The function will fail in any of the following circumstances:
  • framework is not a valid framework identifier.

Requirements

Assembly: NAnt.Core (0.92.4526.0)

See Also

framework::get-runtime-framework() | framework::get-target-framework() nant-0.92-rc1/doc/help/functions/cygpath.get-unix-path(System.String).html0000644000175000017500000000422711757307616026361 0ustar jtaylorjtaylor cygpath::get-unix-path Function

cygpath::get-unix-path

[This is preliminary documentation and subject to change.]

Gets the Unix form of the specified path.

Usage

string cygpath::get-unix-path(path)

Parameters

Name Type Description
path string The path to convert.

Return Value

The Unix form of the specified path.

Exceptions

The function will fail in any of the following circumstances:
  • cygpath could not be started.
  • path could not be converted to a Unix form.

Requirements

Assembly: NAnt.Win32Tasks (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/property.get-value(System.String).html0000644000175000017500000000365411757307564026012 0ustar jtaylorjtaylor property::get-value Function

property::get-value

[This is preliminary documentation and subject to change.]

Gets the value of the specified property.

Usage

string property::get-value(propertyName)

Parameters

Name Type Description
propertyName string The name of the property to get the value of.

Return Value

The value of the specified property.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/target.get-current-target().html0000644000175000017500000000361111757307601024555 0ustar jtaylorjtaylor target::get-current-target Function

target::get-current-target

[This is preliminary documentation and subject to change.]

Gets the name of the target being executed.

Usage

string target::get-current-target()

Return Value

A String that contains the name of the target being executed.

Exceptions

The function will fail in any of the following circumstances:
  • No target is being executed.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/assembly.get-name(System.Reflection.Assembly).html0000644000175000017500000000531211757307565030145 0ustar jtaylorjtaylor assembly::get-name Function

assembly::get-name

[This is preliminary documentation and subject to change.]

Gets an AssemblyName for the specified assembly.

Usage

AssemblyName assembly::get-name(assembly)

Parameters

Name Type Description
assembly Assembly The assembly to get an AssemblyName for.

Return Value

An AssemblyName for the specified assembly.

Requirements

Assembly: NAnt.Core (0.92.4526.0)

See Also

Assembly Functions nant-0.92-rc1/doc/help/functions/string.index-of(System.String,System.String).html0000644000175000017500000000541011757307607027770 0ustar jtaylorjtaylor string::index-of Function

string::index-of

[This is preliminary documentation and subject to change.]

Returns the position of the first occurrence in the specified string of the given search string.

Usage

int string::index-of(source, value)

Parameters

Name Type Description
source string The string to search.
value string The string to locate within source.

Return Value

The lowest-index position of value in source if it is found, or -1 if source does not contain value.

If value is an empty string, the return value will always be 0.

Remarks

This function performs a case-sensitive word search using the invariant culture.

Examples

  • string::index-of('testing string', 'test') ==> 0
  • string::index-of('testing string', '') ==> 0
  • string::index-of('testing string', 'Test') ==> -1
  • string::index-of('testing string', 'ing') ==> 4

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/path.get-temp-file-name().html0000644000175000017500000000335611757307605024067 0ustar jtaylorjtaylor path::get-temp-file-name Function

path::get-temp-file-name

[This is preliminary documentation and subject to change.]

Returns a uniquely named zero-byte temporary file on disk and returns the full path to that file.

Usage

string path::get-temp-file-name()

Return Value

A String containing the name of the temporary file.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/file.is-assembly(System.String).html0000644000175000017500000000520611757307574025400 0ustar jtaylorjtaylor file::is-assembly Function

file::is-assembly

[This is preliminary documentation and subject to change.]

Checks if a given file is an assembly.

Usage

bool file::is-assembly(assemblyFile)

Parameters

Name Type Description
assemblyFile string The name or path of the file to be checked.

Return Value

True if the file is a valid assembly, false if it's not or if the assembly seems corrupted (invalid headers or metadata).

Exceptions

The function will fail in any of the following circumstances:
  • assemblyFile is a null String.
  • assemblyFile is an empty String.
  • assemblyFile is not found, or the file you are trying to check does not specify a filename extension.
  • The caller does not have path discovery permission.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/convert.to-double(System.Double).html0000644000175000017500000000375611757307567025561 0ustar jtaylorjtaylor convert::to-double Function

convert::to-double

[This is preliminary documentation and subject to change.]

(Deprecated)

Converts the argument to double

Usage

double convert::to-double(value)

Parameters

Name Type Description
value double The value to be converted.

Return Value

value converted to double. The function fails with an exception when the conversion is not possible.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/pkg-config.get-mod-version(System.String).html0000644000175000017500000000425211757307606027270 0ustar jtaylorjtaylor pkg-config::get-mod-version Function

pkg-config::get-mod-version

[This is preliminary documentation and subject to change.]

Determines the version of the given package.

Usage

string pkg-config::get-mod-version(package)

Parameters

Name Type Description
package string The package to get the version of.

Return Value

The version of the given package.

Exceptions

The function will fail in any of the following circumstances:
  • pkg-config could not be started.
  • package does not exist.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/platform.get-name().html0000644000175000017500000000305111757307602023064 0ustar jtaylorjtaylor platform::get-name Function

platform::get-name

[This is preliminary documentation and subject to change.]

Gets the name of the platform on which NAnt is running.

Usage

string platform::get-name()

Return Value

The name of the platform on which NAnt is running.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/datetime.now().html0000644000175000017500000000343711757307570022156 0ustar jtaylorjtaylor datetime::now Function

datetime::now

[This is preliminary documentation and subject to change.]

Gets a DateTime that is the current local date and time on this computer.

Usage

datetime datetime::now()

Return Value

A DateTime whose value is the current date and time.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/framework.get-frameworks(NAnt.Core.FrameworkTypes).html0000644000175000017500000000563611757307577031154 0ustar jtaylorjtaylor framework::get-frameworks Function

framework::get-frameworks

[This is preliminary documentation and subject to change.]

Gets a comma-separated list of frameworks filtered by the specified FrameworkTypes.

Usage

string framework::get-frameworks(types)

Parameters

Name Type Description
types FrameworkTypes A bitwise combination of FrameworkTypes values that filter the frameworks to retrieve.

Return Value

A comma-separated list of frameworks filtered by the specified FrameworkTypes, sorted on name.

Examples

  • Define a build-all target that executes the build target once for each installed framework targeting compact devices.

    <target name="build-all">
        <foreach item="String" in="${framework::get-frameworks('installed compact')}" delim="," property="framework">
            <property name="nant.settings.currentframework" value="${framework}" />
            <call target="build" />
        </foreach>
    </target>
    
    <target name="build">
        ...
    </target>
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/directory.get-current-directory().html0000644000175000017500000000333711757307572026025 0ustar jtaylorjtaylor directory::get-current-directory Function

directory::get-current-directory

[This is preliminary documentation and subject to change.]

Gets the current working directory.

Usage

string directory::get-current-directory()

Return Value

A String containing the path of the current working directory.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/directory.get-last-write-time(System.String).html0000644000175000017500000000465411757307572030045 0ustar jtaylorjtaylor directory::get-last-write-time Function

directory::get-last-write-time

[This is preliminary documentation and subject to change.]

Returns the date and time the specified directory was last written to.

Usage

datetime directory::get-last-write-time(path)

Parameters

Name Type Description
path string The directory for which to obtain write date and time information.

Return Value

The date and time the specified directory was last written to.

Exceptions

The function will fail in any of the following circumstances:
  • The specified directory does not exist.
  • path is a zero-length string, contains only white space, or contains one or more invalid characters.
  • The specified path, file name, or both exceed the system-defined maximum length.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/platform.is-windows().html0000644000175000017500000000307211757307602023475 0ustar jtaylorjtaylor platform::is-windows Function

platform::is-windows

[This is preliminary documentation and subject to change.]

Checks whether NAnt is running on Windows.

Usage

bool platform::is-windows()

Return Value

true if NAnt is running on Windows; otherwise, false.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/timespan.from-seconds(System.Double).html0000644000175000017500000000440711757307614026411 0ustar jtaylorjtaylor timespan::from-seconds Function

timespan::from-seconds

[This is preliminary documentation and subject to change.]

Returns a TimeSpan that represents a specified number of seconds, where the specification is accurate to the nearest millisecond.

Usage

timespan timespan::from-seconds(value)

Parameters

Name Type Description
value double A number of seconds, accurate to the nearest millisecond.

Return Value

A TimeSpan that represents value.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/string.get-length(System.String).html0000644000175000017500000000400711757307606025567 0ustar jtaylorjtaylor string::get-length Function

string::get-length

[This is preliminary documentation and subject to change.]

Returns the length of the specified string.

Usage

int string::get-length(s)

Parameters

Name Type Description
s string input string

Return Value

The string's length.

Examples

  • string::get-length('foo') ==> 3
  • string::get-length('') ==> 0

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/pkg-config.get-link-flags(System.String).html0000644000175000017500000000436211757307605027056 0ustar jtaylorjtaylor pkg-config::get-link-flags Function

pkg-config::get-link-flags

[This is preliminary documentation and subject to change.]

Gets the link flags required to compile the package, including all its dependencies.

Usage

string pkg-config::get-link-flags(package)

Parameters

Name Type Description
package string The package for which the link flags should be retrieved.

Return Value

The link flags required to compile the package.

Exceptions

The function will fail in any of the following circumstances:
  • pkg-config could not be started.
  • package does not exist.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/path.get-extension(System.String).html0000644000175000017500000000474611757307604025760 0ustar jtaylorjtaylor path::get-extension Function

path::get-extension

[This is preliminary documentation and subject to change.]

Returns the extension for the specified path string.

Usage

string path::get-extension(path)

Parameters

Name Type Description
path string The path string from which to get the extension.

Return Value

A String containing the extension of the specified path (including the "."), or an empty String if path does not have extension information.

Exceptions

The function will fail in any of the following circumstances:
  • path contains one or more invalid characters.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/path.has-extension(System.String).html0000644000175000017500000000442211757307605025744 0ustar jtaylorjtaylor path::has-extension Function

path::has-extension

[This is preliminary documentation and subject to change.]

Determines whether a path string includes an extension.

Usage

bool path::has-extension(path)

Parameters

Name Type Description
path string The path to search for an extension.

Return Value

true. if the characters that follow the last directory separator or volume separator in the path include a period (.) followed by one or more characters; otherwise, false.

Exceptions

The function will fail in any of the following circumstances:
  • path contains one or more invalid characters.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/path.get-file-name-without-extension(System.String).html0000644000175000017500000000512711757307605031307 0ustar jtaylorjtaylor path::get-file-name-without-extension Function

path::get-file-name-without-extension

[This is preliminary documentation and subject to change.]

Returns the filename without extension for the specified path string.

Usage

string path::get-file-name-without-extension(path)

Parameters

Name Type Description
path string The path of the file.

Return Value

A String containing the String returned by path::get-file-name(), minus the last period (.) and all characters following it.

Exceptions

The function will fail in any of the following circumstances:
  • path contains one or more invalid characters.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/project.get-name().html0000644000175000017500000000327111757307601022711 0ustar jtaylorjtaylor project::get-name Function

project::get-name

[This is preliminary documentation and subject to change.]

Gets the name of the current project.

Usage

string project::get-name()

Return Value

The name of the current project, or an empty String if no name is specified in the build file.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/framework.get-clr-version(System.String).html0000644000175000017500000000511311757307576027245 0ustar jtaylorjtaylor framework::get-clr-version Function

framework::get-clr-version

[This is preliminary documentation and subject to change.]

Gets the Common Language Runtime version of the specified framework.

Usage

Version framework::get-clr-version(framework)

Parameters

Name Type Description
framework string The framework of which the Common Language Runtime version should be returned.

Return Value

The Common Language Runtime version of the specified framework.

Exceptions

The function will fail in any of the following circumstances:
  • framework is not a valid framework identifier.

Requirements

Assembly: NAnt.Core (0.92.4526.0)

See Also

framework::get-runtime-framework() | framework::get-target-framework() nant-0.92-rc1/doc/help/functions/timespan.parse(System.String).html0000644000175000017500000000461511757307615025162 0ustar jtaylorjtaylor timespan::parse Function

timespan::parse

[This is preliminary documentation and subject to change.]

Constructs a TimeSpan from a time indicated by a specified string.

Usage

timespan timespan::parse(s)

Parameters

Name Type Description
s string A string.

Return Value

A TimeSpan that corresponds to s.

Exceptions

The function will fail in any of the following circumstances:
  • s has an invalid format.
  • At least one of the hours, minutes, or seconds components is outside its valid range.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/string.trim(System.String).html0000644000175000017500000000407411757307610024503 0ustar jtaylorjtaylor string::trim Function

string::trim

[This is preliminary documentation and subject to change.]

Returns the given string trimmed of whitespace.

Usage

string string::trim(s)

Parameters

Name Type Description
s string input string

Return Value

The string s with any leading or trailing white space characters removed.

Examples

  • string::trim('  test  ') ==> 'test'
  • string::trim('\t\tfoo  \r\n') ==> 'foo'

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/timespan.get-total-minutes(System.TimeSpan).html0000644000175000017500000000456711757307611027706 0ustar jtaylorjtaylor timespan::get-total-minutes Function

timespan::get-total-minutes

[This is preliminary documentation and subject to change.]

Returns the total number of minutes represented by the specified TimeSpan, expressed in whole and fractional minutes.

Usage

double timespan::get-total-minutes(value)

Parameters

Name Type Description
value timespan A TimeSpan.

Return Value

The total number of minutes represented by the given TimeSpan.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/timespan.get-hours(System.TimeSpan).html0000644000175000017500000000443611757307612026235 0ustar jtaylorjtaylor timespan::get-hours Function

timespan::get-hours

[This is preliminary documentation and subject to change.]

Returns the number of whole hours represented by the specified TimeSpan.

Usage

int timespan::get-hours(value)

Parameters

Name Type Description
value timespan A TimeSpan.

Return Value

The number of whole hours represented by the given TimeSpan.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/framework.get-family(System.String).html0000644000175000017500000000454411757307576026272 0ustar jtaylorjtaylor framework::get-family Function

framework::get-family

[This is preliminary documentation and subject to change.]

Gets the family of the specified framework.

Usage

string framework::get-family(framework)

Parameters

Name Type Description
framework string The framework of which the family should be returned.

Return Value

The family of the specified framework.

Exceptions

The function will fail in any of the following circumstances:
  • framework is not a valid framework identifier.

Requirements

Assembly: NAnt.Core (0.92.4526.0)

See Also

framework::get-runtime-framework() | framework::get-target-framework() nant-0.92-rc1/doc/help/functions/math.abs(System.Double).html0000644000175000017500000000364511757307600023666 0ustar jtaylorjtaylor math::abs Function

math::abs

[This is preliminary documentation and subject to change.]

Returns the absolute value of the specified number

Usage

double math::abs(value)

Parameters

Name Type Description
value double value to take the absolute value from

Return Value

value when value is greater than or equal to zero; otherwise, -value.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/timespan.get-ticks(System.TimeSpan).html0000644000175000017500000000441711757307613026212 0ustar jtaylorjtaylor timespan::get-ticks Function

timespan::get-ticks

[This is preliminary documentation and subject to change.]

Returns the number of ticks contained in the specified TimeSpan.

Usage

long timespan::get-ticks(value)

Parameters

Name Type Description
value timespan A TimeSpan.

Return Value

The number of ticks contained in the given TimeSpan.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/convert.to-string(System.String).html0000644000175000017500000000413711757307567025643 0ustar jtaylorjtaylor convert::to-string Function

convert::to-string

[This is preliminary documentation and subject to change.]

(Deprecated)

Converts the argument to a string.

Usage

string convert::to-string(value)

Parameters

Name Type Description
value string The value to be converted.

Return Value

value converted to string. The function fails with an exception when the conversion is not possible.

Remarks

Named method ConvertToString as a static ToString method would break CLS compliance.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/string.substring(System.String,System.Int32,System.Int32).html0000644000175000017500000000655111757307606032115 0ustar jtaylorjtaylor string::substring Function

string::substring

[This is preliminary documentation and subject to change.]

Returns a substring of the specified string.

Usage

string string::substring(str, startIndex, length)

Parameters

Name Type Description
str string input string
startIndex int position of the start of the substring
length int the length of the substring

Return Value

If the length is greater than zero, the function returns a substring starting at character position startIndex with a length of length characters.

If the length is equal to zero, the function returns an empty string.

Exceptions

The function will fail in any of the following circumstances:
  • startIndex or length is less than zero.
  • startIndex is greater than the length of str.
  • startIndex plus length indicates a position not within str.

Examples

  • string::substring('testing string', 0, 4) ==> 'test'
  • string::substring('testing string', 8, 3) ==> 'str'
  • string::substring('testing string', 8, 0) ==> ''
  • string::substring('testing string', -1, 5) ==> ERROR
  • string::substring('testing string', 8, -1) ==> ERROR
  • string::substring('testing string', 5, 17) ==> ERROR

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/file.get-last-write-time(System.String).html0000644000175000017500000000460411757307574026755 0ustar jtaylorjtaylor file::get-last-write-time Function

file::get-last-write-time

[This is preliminary documentation and subject to change.]

Returns the date and time the specified file was last written to.

Usage

datetime file::get-last-write-time(path)

Parameters

Name Type Description
path string The file for which to obtain write date and time information.

Return Value

The date and time the specified file was last written to.

Exceptions

The function will fail in any of the following circumstances:
  • The specified file does not exist.
  • path is a zero-length string, contains only white space, or contains one or more invalid characters.
  • The specified path, file name, or both exceed the system-defined maximum length.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/task.get-assembly(System.String).html0000644000175000017500000000523711757307602025563 0ustar jtaylorjtaylor task::get-assembly Function

task::get-assembly

[This is preliminary documentation and subject to change.]

Returns the Assembly from which the specified task was loaded.

Usage

Assembly task::get-assembly(name)

Parameters

Name Type Description
name string The name of the task to get the Assembly of.

Return Value

The Assembly from which the specified task was loaded.

Exceptions

The function will fail in any of the following circumstances:
  • Task name is not available.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/path.combine(System.String,System.String).html0000644000175000017500000000455511757307603027326 0ustar jtaylorjtaylor path::combine Function

path::combine

[This is preliminary documentation and subject to change.]

Combines two paths.

Usage

string path::combine(path1, path2)

Parameters

Name Type Description
path1 string first path
path2 string second path

Return Value

A string containing the combined paths. If one of the specified paths is a zero-length string, this method returns the other path. If path2 contains an absolute path, this method returns path2.

Exceptions

The function will fail in any of the following circumstances:
  • path1 or path2 contain one or more invalid characters.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootnant-0.92-rc1/doc/help/functions/pkg-config.is-between-version(System.String,System.String,System.String).htmlnant-0.92-rc1/doc/help/functions/pkg-config.is-between-version(System.String,System.String,System.St0000644000175000017500000000515411757307606033360 0ustar jtaylorjtaylor pkg-config::is-between-version Function

pkg-config::is-between-version

[This is preliminary documentation and subject to change.]

Determines whether the given package is between two versions.

Usage

bool pkg-config::is-between-version(package, minVersion, maxVersion)

Parameters

Name Type Description
package string The package to check.
minVersion string The version the package should at least have.
maxVersion string The version the package should maximum have.

Return Value

true if the given package is between minVersion and maxVersion; otherwise, false.

Exceptions

The function will fail in any of the following circumstances:
  • pkg-config could not be started.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/timespan.from-ticks(System.Int64).html0000644000175000017500000000431311757307615025557 0ustar jtaylorjtaylor timespan::from-ticks Function

timespan::from-ticks

[This is preliminary documentation and subject to change.]

Returns a TimeSpan that represents a specified time, where the specification is in units of ticks.

Usage

timespan timespan::from-ticks(value)

Parameters

Name Type Description
value long A number of ticks that represent a time.

Return Value

A TimeSpan that represents value.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/property.is-dynamic(System.String).html0000644000175000017500000000447311757307602026147 0ustar jtaylorjtaylor property::is-dynamic Function

property::is-dynamic

[This is preliminary documentation and subject to change.]

Checks whether the specified property is a dynamic property.

Usage

bool property::is-dynamic(name)

Parameters

Name Type Description
name string The property to test.

Return Value

true if the specified property is a dynamic property; otherwise, false.

Exceptions

The function will fail in any of the following circumstances:
  • Property name has not been set.

Examples

  • Check whether the "debug" property is a dynamic property.

    property::is-dynamic('debug')

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/directory.exists(System.String).html0000644000175000017500000000420011757307572025543 0ustar jtaylorjtaylor directory::exists Function

directory::exists

[This is preliminary documentation and subject to change.]

Determines whether the given path refers to an existing directory on disk.

Usage

bool directory::exists(path)

Parameters

Name Type Description
path string The path to test.

Return Value

true if path refers to an existing directory; otherwise, false.

Examples

  • Remove directory "test", if it exists.

    <delete dir="test" if="${directory::exists('test')}" />
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/framework.get-description(System.String).html0000644000175000017500000000461411757307576027332 0ustar jtaylorjtaylor framework::get-description Function

framework::get-description

[This is preliminary documentation and subject to change.]

Gets the description of the specified framework.

Usage

string framework::get-description(framework)

Parameters

Name Type Description
framework string The framework of which the description should be returned.

Return Value

The description of the specified framework.

Exceptions

The function will fail in any of the following circumstances:
  • framework is not a valid framework identifier.

Requirements

Assembly: NAnt.Core (0.92.4526.0)

See Also

framework::get-runtime-framework() | framework::get-target-framework() nant-0.92-rc1/doc/help/functions/datetime.get-day-of-year(System.DateTime).html0000644000175000017500000000370411757307570027142 0ustar jtaylorjtaylor datetime::get-day-of-year Function

datetime::get-day-of-year

[This is preliminary documentation and subject to change.]

Gets the day of the year represented by the specified date.

Usage

int datetime::get-day-of-year(date)

Parameters

Name Type Description
date datetime The date of which to get the day of the year.

Return Value

The day of the year, between 1 and 366.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/version.parse(System.String).html0000644000175000017500000000562011757307616025025 0ustar jtaylorjtaylor version::parse Function

version::parse

[This is preliminary documentation and subject to change.]

Converts the specified string representation of a version to its Version equivalent.

Usage

Version version::parse(version)

Parameters

Name Type Description
version string A string containing the major, minor, build, and revision numbers, where each number is delimited with a period character ('.').

Return Value

A Version instance representing the specified String.

Exceptions

The function will fail in any of the following circumstances:
  • version has fewer than two components or more than four components.
  • A major, minor, build, or revision component is less than zero.
  • At least one component of version does not parse to a decimal integer.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/path.get-directory-name(System.String).html0000644000175000017500000000503611757307604026657 0ustar jtaylorjtaylor path::get-directory-name Function

path::get-directory-name

[This is preliminary documentation and subject to change.]

Returns the directory information for the specified path string.

Usage

string path::get-directory-name(path)

Parameters

Name Type Description
path string The path of a file or directory.

Return Value

A String containing directory information for path, or an empty String if path denotes a root directory, or does not contain directory information.

Exceptions

The function will fail in any of the following circumstances:
  • path contains invalid characters, is empty, or contains only white spaces.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/timespan.from-days(System.Double).html0000644000175000017500000000436211757307614025713 0ustar jtaylorjtaylor timespan::from-days Function

timespan::from-days

[This is preliminary documentation and subject to change.]

Returns a TimeSpan that represents a specified number of days, where the specification is accurate to the nearest millisecond.

Usage

timespan timespan::from-days(value)

Parameters

Name Type Description
value double A number of days, accurate to the nearest millisecond.

Return Value

A TimeSpan that represents value.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/dns.get-host-name().html0000644000175000017500000000341111757307572023005 0ustar jtaylorjtaylor dns::get-host-name Function

dns::get-host-name

[This is preliminary documentation and subject to change.]

Gets the host name of the local computer.

Usage

string dns::get-host-name()

Return Value

A string that contains the DNS host name of the local computer.

Exceptions

The function will fail in any of the following circumstances:
  • An error is encountered when resolving the local host name.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/string.replace(System.String,System.String,System.String).html0000644000175000017500000000667111757307607032432 0ustar jtaylorjtaylor string::replace Function

string::replace

[This is preliminary documentation and subject to change.]

Returns a string corresponding to the replacement of a given string with another in the specified string.

Usage

string string::replace(str, oldValue, newValue)

Parameters

Name Type Description
str string input string
oldValue string A String to be replaced.
newValue string A String to replace all occurrences of oldValue.

Return Value

A String equivalent to str but with all instances of oldValue replaced with newValue.

Exceptions

The function will fail in any of the following circumstances:
  • oldValue is an empty string.

Remarks

This function performs a word (case-sensitive and culture-sensitive) search to find oldValue.

Examples

  • string::replace('testing string', 'test', 'winn') ==> 'winning string'
  • string::replace('testing string', 'foo', 'winn') ==> 'testing string'
  • string::replace('testing string', 'ing', '') ==> 'test str'
  • string::replace('banana', 'ana', 'ana') ==> 'banana'

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/string.to-upper(System.String).html0000644000175000017500000000440211757307607025304 0ustar jtaylorjtaylor string::to-upper Function

string::to-upper

[This is preliminary documentation and subject to change.]

Returns the specified string converted to uppercase.

Usage

string string::to-upper(s)

Parameters

Name Type Description
s string input string

Return Value

The string s in uppercase.

Remarks

The casing rules of the invariant culture are used to convert the s to uppercase.

Examples

  • string::to-upper('testing string') ==> 'TESTING STRING'
  • string::to-upper('Testing String') ==> 'TESTING STRING'
  • string::to-upper('Test 123') ==> 'TEST 123'

Requirements

Assembly: NAnt.Core (0.92.4526.0)
././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootnant-0.92-rc1/doc/help/functions/fileversioninfo.get-product-name(System.Diagnostics.FileVersionInfo).htmlnant-0.92-rc1/doc/help/functions/fileversioninfo.get-product-name(System.Diagnostics.FileVersionInfo0000644000175000017500000000454311757307575033636 0ustar jtaylorjtaylor fileversioninfo::get-product-name Function

fileversioninfo::get-product-name

[This is preliminary documentation and subject to change.]

Gets the name of the product the file is distributed with.

Usage

string fileversioninfo::get-product-name(fileVersionInfo)

Parameters

Name Type Description
fileVersionInfo FileVersionInfo A FileVersionInfo instance containing version information about a file.

Return Value

The name of the product the file is distributed with.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/task.exists(System.String).html0000644000175000017500000000357311757307602024507 0ustar jtaylorjtaylor task::exists Function

task::exists

[This is preliminary documentation and subject to change.]

Checks whether the specified task exists.

Usage

bool task::exists(name)

Parameters

Name Type Description
name string The task to test.

Return Value

true if the specified task exists; otherwise, false.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/nant.get-base-directory().html0000644000175000017500000000314011757307601024172 0ustar jtaylorjtaylor nant::get-base-directory Function

nant::get-base-directory

[This is preliminary documentation and subject to change.]

Gets the base directory of the appdomain in which NAnt is running.

Usage

string nant::get-base-directory()

Return Value

The base directory of the appdomain in which NAnt is running.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/environment.variable-exists(System.String).html0000644000175000017500000000441111757307573027673 0ustar jtaylorjtaylor environment::variable-exists Function

environment::variable-exists

[This is preliminary documentation and subject to change.]

Gets a value indicating whether the specified environment variable exists.

Usage

bool environment::variable-exists(name)

Parameters

Name Type Description
name string The environment variable that should be checked.

Return Value

true if the environment variable exists; otherwise, false.

Examples

  • Execute a set of tasks only if the "BUILD_DEBUG" environment variable is set.

    <if test="${environment::variable-exists('BUILD_DEBUG')}">
        ...
    </if>
        

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/operating-system.to-string(System.OperatingSystem).html0000644000175000017500000000557111757307603031356 0ustar jtaylorjtaylor operating-system::to-string Function

operating-system::to-string

[This is preliminary documentation and subject to change.]

Converts the value of the specified operating system to its equivalent String representation.

Usage

string operating-system::to-string(operatingSystem)

Parameters

Name Type Description
operatingSystem OperatingSystem The operating system.

Return Value

The String representation of operatingSystem.

Examples

  • Output string representation of the current operating system.

    <echo message="OS=${operating-system::to-string(environment::get-operating-system())}" />
        

    If the operating system is Windows 2000, the output is:

    Microsoft Windows NT 5.0.2195.0
      

Requirements

Assembly: NAnt.Core (0.92.4526.0)

See Also

environment::get-operating-system() nant-0.92-rc1/doc/help/functions/file.get-creation-time(System.String).html0000644000175000017500000000465111757307574026470 0ustar jtaylorjtaylor file::get-creation-time Function

file::get-creation-time

[This is preliminary documentation and subject to change.]

Returns the creation date and time of the specified file.

Usage

datetime file::get-creation-time(path)

Parameters

Name Type Description
path string The file for which to obtain creation date and time information.

Return Value

The creation date and time of the specified file.

Exceptions

The function will fail in any of the following circumstances:
  • The specified file does not exist.
  • path is a zero-length string, contains only white space, or contains one or more invalid characters.
  • The specified path, file name, or both exceed the system-defined maximum length.
  • The path parameter is in an invalid format.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/framework.get-version().html0000644000175000017500000000344711757307576024025 0ustar jtaylorjtaylor framework::get-version Function

framework::get-version

[This is preliminary documentation and subject to change.]

Gets the version of the current target framework.

Usage

Version framework::get-version()

Return Value

The version of the current target framework.

Requirements

Assembly: NAnt.Core (0.92.4526.0)

See Also

framework::get-target-framework() nant-0.92-rc1/doc/help/functions/math.round(System.Double).html0000644000175000017500000000356111757307600024245 0ustar jtaylorjtaylor math::round Function

math::round

[This is preliminary documentation and subject to change.]

Rounds the value to the nearest whole number

Usage

double math::round(value)

Parameters

Name Type Description
value double Number to be rounded, can be anything convertible to a double.

Return Value

Rounded value.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/datetime.get-second(System.DateTime).html0000644000175000017500000000363411757307570026302 0ustar jtaylorjtaylor datetime::get-second Function

datetime::get-second

[This is preliminary documentation and subject to change.]

Gets the seconds component of the specified date.

Usage

int datetime::get-second(date)

Parameters

Name Type Description
date datetime The date of which to get the seconds component.

Return Value

The seconds, between 0 and 59.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/timespan.get-total-milliseconds(System.TimeSpan).html0000644000175000017500000000463711757307612030706 0ustar jtaylorjtaylor timespan::get-total-milliseconds Function

timespan::get-total-milliseconds

[This is preliminary documentation and subject to change.]

Returns the total number of milliseconds represented by the specified TimeSpan, expressed in whole and fractional milliseconds.

Usage

double timespan::get-total-milliseconds(value)

Parameters

Name Type Description
value timespan A TimeSpan.

Return Value

The total number of milliseconds represented by the given TimeSpan.

Requirements

Assembly: NAnt.Core (0.92.4526.0)
nant-0.92-rc1/doc/help/functions/framework.get-framework-directory(System.String).html0000644000175000017500000000471311757307576031006 0ustar jtaylorjtaylor framework::get-framework-directory Function

framework::get-framework-directory

[This is preliminary documentation and subject to change.]

Gets the framework directory of the specified framework.

Usage

string framework::get-framework-directory(framework)

Parameters

Name Type Description
framework string The framework of which the framework directory should be returned.

Return Value

The framework directory of the specified framework.

Exceptions

The function will fail in any of the following circumstances:
  • framework is not a valid framework identifier.

Requirements

Assembly: NAnt.Core (0.92.4526.0)

See Also

framework::get-runtime-framework() | framework::get-target-framework() nant-0.92-rc1/Makefile.nmake0000644000175000017500000000603711757302272015567 0ustar jtaylorjtaylor#NAnt nmake makefile for building on windows CSC=csc RESGEN=resgen TARGET=net-2.0 !ifdef MONO DEFINE = MONO FRAMEWORK_DIR = mono !else DEFINE = NET FRAMEWORK_DIR = net !endif !if "$(TARGET)" == "net-2.0" || "$(TARGET)" == "mono-2.0" DEFINE = $(DEFINE),NET_1_0,NET_1_1,NET_2_0,ONLY_2_0 !else if "$(TARGET)" == "net-3.5" || "$(TARGET)" == "mono-3.5" DEFINE = $(DEFINE),NET_1_0,NET_1_1,NET_2_0,NET_3_5,ONLY_3_5 !else if "$(TARGET)" == "net-4.0" || "$(TARGET)" == "mono-4.0" DEFINE = $(DEFINE),NET_1_0,NET_1_1,NET_2_0,NET_3_5,NET_4_0,ONLY_4_0 !else !error Specified target "$(TARGET)" is not valid !endif !ifdef DEBUG NANT_DEBUG = -debug+ !endif TARGET_FRAMEWORK = -t:$(TARGET) NANT = $(MONO) bootstrap\NAnt.exe $(NANT_DEBUG) all: bootstrap build-nant build-nant: bootstrap $(NANT) $(TARGET_FRAMEWORK) -f:NAnt.build build clean: if exist bootstrap rmdir /S /Q bootstrap if exist build rmdir /S /Q build install: bootstrap $(NANT) $(TARGET_FRAMEWORK) -f:NAnt.build install -D:prefix="$(prefix)" -D:destdir="$(DESTDIR)" -D:doc.prefix="$(docdir)" run-test: bootstrap $(NANT) $(TARGET_FRAMEWORK) -f:NAnt.build test bootstrap: setup bootstrap\NAnt.exe bootstrap\NAnt.Core.dll bootstrap\NAnt.DotNetTasks.dll bootstrap\NAnt.CompressionTasks.dll bootstrap\NAnt.Win32Tasks.dll setup: if not exist bootstrap md bootstrap if not exist bootstrap\lib md bootstrap\lib xcopy lib bootstrap\lib /S /Y /Q copy lib\common\neutral\log4net.dll bootstrap copy src\NAnt.Console\App.config bootstrap\NAnt.exe.config bootstrap\NAnt.exe: $(CSC) $(DEBUG) -target:exe -define:$(DEFINE) -out:bootstrap\NAnt.exe -r:bootstrap\log4net.dll \ -r:System.Configuration.dll -recurse:src\NAnt.Console\*.cs src\CommonAssemblyInfo.cs bootstrap\NAnt.Core.dll: $(RESGEN) src\NAnt.Core\Resources\Strings.resx bootstrap\NAnt.Core.Resources.Strings.resources $(CSC) $(DEBUG) -target:library -warn:0 -define:$(DEFINE) -out:bootstrap\NAnt.Core.dll -r:bootstrap\log4net.dll \ -r:System.Web.dll -resource:bootstrap\NAnt.Core.Resources.Strings.resources \ -recurse:src\NAnt.Core\*.cs src\CommonAssemblyInfo.cs bootstrap\NAnt.DotNetTasks.dll: $(RESGEN) src\NAnt.DotNet\Resources\Strings.resx bootstrap\NAnt.DotNet.Resources.Strings.resources $(CSC) $(DEBUG) -target:library -warn:0 -define:$(DEFINE) -out:bootstrap\NAnt.DotNetTasks.dll \ -r:bootstrap\NAnt.Core.dll -r:bootstrap/lib/common/neutral/NDoc.Core.dll \ -resource:bootstrap\NAnt.DotNet.Resources.Strings.resources -recurse:src\NAnt.DotNet\*.cs \ src\CommonAssemblyInfo.cs bootstrap\NAnt.CompressionTasks.dll: $(CSC) $(DEBUG) -target:library -warn:0 -define:$(DEFINE) -out:bootstrap\NAnt.CompressionTasks.dll \ -r:bootstrap\NAnt.Core.dll -r:bootstrap\lib\common\neutral\ICSharpCode.SharpZipLib.dll \ -recurse:src\NAnt.Compression\*.cs src\CommonAssemblyInfo.cs bootstrap\NAnt.Win32Tasks.dll: $(CSC) $(DEBUG) -target:library -warn:0 -define:$(DEFINE) -out:bootstrap\NAnt.Win32Tasks.dll \ -r:bootstrap\NAnt.Core.dll -r:bootstrap\NAnt.DotNetTasks.dll -r:System.ServiceProcess.dll \ -recurse:src\NAnt.Win32\*.cs \ src\CommonAssemblyInfo.cs nant-0.92-rc1/Makefile0000644000175000017500000001005711757302272014472 0ustar jtaylorjtaylor# NAnt make makefile for *nix MONO=mono MCS=gmcs RESGEN=resgen TARGET=mono-2.0 # Contains a list of acceptable targets used to build NAnt VALID_TARGETS := mono-2.0 mono-3.5 mono-4.0 net-2.0 net-3.5 net-4.0 ifndef DIRSEP ifeq ($(OS),Windows_NT) DIRSEP = \\ else DIRSEP = / endif endif ifndef PLATFORM_REFERENCES ifeq ($(OS),Windows_NT) PLATFORM_REFERENCES = \ bootstrap/NAnt.Win32Tasks.dll endif endif ifeq ($(MONO),mono) FRAMEWORK_DIR = mono DEFINE = MONO else FRAMEWORK_DIR = net DEFINE = NET endif # Validates TARGET var. If the value of TARGET exists # in VALID_TARGETS array, SELECTED_TARGET will contain # the value of TARGET; otherwise SELECTED_TARGET var # will be empty SELECTED_TARGET := $(filter $(TARGET),$(VALID_TARGETS)) # If TARGET var is valid, load the DEFINE var # based on value of TARGET ifneq ($(SELECTED_TARGET),) # Loads (net,mono)-2.0 DEFINE vars ifeq ($(findstring 2.0,$(SELECTED_TARGET)),2.0) DEFINE := $(DEFINE),NET_1_0,NET_1_1,NET_2_0,ONLY_2_0 endif # Loads (net,mono)-3.5 DEFINE vars ifeq ($(findstring 3.5,$(SELECTED_TARGET)),3.5) DEFINE := $(DEFINE),NET_1_0,NET_1_1,NET_2_0,NET_3_5,ONLY_3_5 endif # Loads (net,mono)-4.0 DEFINE vars ifeq ($(findstring 4.0,$(SELECTED_TARGET)),4.0) DEFINE := $(DEFINE),NET_1_0,NET_1_1,NET_2_0,NET_3_5,NET_4_0,ONLY_4_0 endif # If TARGET var is invalid, throw an error else $(error Specified target "$(TARGET)" is not valid) endif # Make sure that -debug+ is specified in NAnt command if DEBUG is defined ifdef DEBUG NANT_DEBUG := -debug+ endif # Assign remaining vars TARGET_FRAMEWORK = -t:$(TARGET) NANT = $(MONO) bootstrap/NAnt.exe $(NANT_DEBUG) all: bootstrap build-nant build-nant: $(NANT) $(TARGET_FRAMEWORK) -f:NAnt.build build clean: rm -fR build bootstrap install: bootstrap $(NANT) $(TARGET_FRAMEWORK) -f:NAnt.build install -D:prefix="$(prefix)" -D:destdir="$(DESTDIR)" -D:doc.prefix="$(docdir)" run-test: bootstrap $(NANT) $(TARGET_FRAMEWORK) -f:NAnt.build test bootstrap/NAnt.exe: $(MCS) $(DEBUG) -target:exe -define:$(DEFINE) -out:bootstrap${DIRSEP}NAnt.exe -r:bootstrap${DIRSEP}log4net.dll \ -r:System.Configuration.dll -recurse:src${DIRSEP}NAnt.Console${DIRSEP}*.cs src${DIRSEP}CommonAssemblyInfo.cs bootstrap: setup bootstrap/NAnt.exe bootstrap/NAnt.Core.dll bootstrap/NAnt.DotNetTasks.dll bootstrap/NAnt.CompressionTasks.dll ${PLATFORM_REFERENCES} setup: mkdir -p bootstrap cp -R lib/ bootstrap/lib # Mono loads log4net before privatebinpath is set-up, so we need this in the same directory # as NAnt.exe cp lib/common/neutral/log4net.dll bootstrap cp src/NAnt.Console/App.config bootstrap/NAnt.exe.config bootstrap/NAnt.Core.dll: $(RESGEN) src/NAnt.Core/Resources/Strings.resx bootstrap/NAnt.Core.Resources.Strings.resources $(MCS) $(DEBUG) -target:library -warn:0 -define:$(DEFINE) -out:bootstrap/NAnt.Core.dll -debug \ -resource:bootstrap/NAnt.Core.Resources.Strings.resources -r:lib${DIRSEP}common${DIRSEP}neutral${DIRSEP}log4net.dll \ -r:System.Web.dll -recurse:src${DIRSEP}NAnt.Core${DIRSEP}*.cs src${DIRSEP}CommonAssemblyInfo.cs bootstrap/NAnt.DotNetTasks.dll: $(RESGEN) src/NAnt.DotNet/Resources/Strings.resx bootstrap/NAnt.DotNet.Resources.Strings.resources $(MCS) $(DEBUG) -target:library -warn:0 -define:$(DEFINE) -out:bootstrap/NAnt.DotNetTasks.dll \ -r:./bootstrap/NAnt.Core.dll -r:bootstrap/lib/common/neutral/NDoc.Core.dll \ -recurse:src${DIRSEP}NAnt.DotNet${DIRSEP}*.cs -resource:bootstrap/NAnt.DotNet.Resources.Strings.resources \ src${DIRSEP}CommonAssemblyInfo.cs bootstrap/NAnt.CompressionTasks.dll: $(MCS) $(DEBUG) -target:library -warn:0 -define:$(DEFINE) -out:bootstrap/NAnt.CompressionTasks.dll \ -r:./bootstrap/NAnt.Core.dll -r:bootstrap/lib/common/neutral/ICSharpCode.SharpZipLib.dll \ -recurse:src${DIRSEP}NAnt.Compression${DIRSEP}*.cs src${DIRSEP}CommonAssemblyInfo.cs bootstrap/NAnt.Win32Tasks.dll: $(MCS) $(DEBUG) -target:library -warn:0 -define:$(DEFINE) -out:bootstrap/NAnt.Win32Tasks.dll \ -r:./bootstrap/NAnt.Core.dll -r:./bootstrap/NAnt.DotNetTasks.dll -r:System.ServiceProcess.dll \ -recurse:src${DIRSEP}NAnt.Win32${DIRSEP}*.cs src${DIRSEP}CommonAssemblyInfo.cs nant-0.92-rc1/tests/0000755000175000017500000000000011757310031014161 5ustar jtaylorjtaylornant-0.92-rc1/tests/NAnt.Core/0000755000175000017500000000000011757310031015710 5ustar jtaylorjtaylornant-0.92-rc1/tests/NAnt.Core/ExpressionEvaluatorTest.cs0000644000175000017500000010110711757302275023134 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Jaroslaw Kowalski (jkowalski@users.sourceforge.net) using System; using System.Collections; using System.Collections.Specialized; using System.IO; using System.Globalization; using NAnt.Core; using NAnt.Core.Attributes; using Tests.NAnt.Core.Util; using NUnit.Framework; namespace Tests.NAnt.Core { [TestFixture] public class ExpressionEvaluatorTest : BuildTestBase { #region Private Instance Fields private string _format = @" {1} {2} "; private string _buildFileName; private Project _project; #endregion Private Instance Fields #region Override implementation of BuildTestBase [SetUp] protected override void SetUp() { base.SetUp(); _buildFileName = Path.Combine(TempDirName, "test.build"); TempFile.CreateWithContents(FormatBuildFile("", ""), _buildFileName); _project = new Project(_buildFileName, Level.Info, 0); _project.Properties["prop1"] = "asdf"; } #endregion Override implementation of BuildTestBase #region Public Instance Methods [Test] public void TestRelationOperators() { // string & string AssertExpression("'a' == 'a'", true); AssertExpression("'a' == 'b'", false); AssertExpression("'a' != 'b'", true); AssertExpression("'a' != 'a'", false); AssertExpression("'a' > 'b'", false); AssertExpression("'a' > 'a'", false); AssertExpression("'b' > 'a'", true); AssertExpression("'a' >= 'b'", false); AssertExpression("'a' >= 'a'", true); AssertExpression("'b' >= 'a'", true); AssertExpression("'a' < 'b'", true); AssertExpression("'a' < 'a'", false); AssertExpression("'b' < 'a'", false); AssertExpression("'a' <= 'b'", true); AssertExpression("'a' <= 'a'", true); AssertExpression("'b' <= 'a'", false); // bool & bool AssertExpression("false == false", true); AssertExpression("false == true", false); AssertExpression("false != true", true); AssertExpression("false != false", false); AssertExpression("false > true", false); AssertExpression("false > false", false); AssertExpression("true > false", true); AssertExpression("false >= true", false); AssertExpression("false >= false", true); AssertExpression("true >= false", true); AssertExpression("false < true", true); AssertExpression("false < false", false); AssertExpression("true < false", false); AssertExpression("false <= true", true); AssertExpression("false <= false", true); AssertExpression("true <= false", false); // int & int AssertExpression("1 == 1", true); AssertExpression("1 == 2", false); AssertExpression("1 != 2", true); AssertExpression("1 != 1", false); AssertExpression("1 > 2", false); AssertExpression("1 > 1", false); AssertExpression("2 > 1", true); AssertExpression("1 >= 2", false); AssertExpression("1 >= 1", true); AssertExpression("2 >= 1", true); AssertExpression("1 < 2", true); AssertExpression("1 < 1", false); AssertExpression("2 < 1", false); AssertExpression("1 <= 2", true); AssertExpression("1 <= 1", true); AssertExpression("2 <= 1", false); // int & long AssertExpression("1 == long::parse('1')", true); AssertExpression("1 == long::parse('66666666666666')", false); AssertExpression("1 != long::parse('66666666666666')", true); AssertExpression("1 != long::parse('1')", false); AssertExpression("1 > long::parse('2')", false); AssertExpression("1 > long::parse('1')", false); AssertExpression("2 > long::parse('1')", true); AssertExpression("1 >= long::parse('66666666666666')", false); AssertExpression("1 >= long::parse('1')", true); AssertExpression("2 >= long::parse('1')", true); AssertExpression("1 < long::parse('66666666666666')", true); AssertExpression("1 < long::parse('1')", false); AssertExpression("2 < long::parse('1')", false); AssertExpression("1 <= long::parse('66666666666666')", true); AssertExpression("1 <= long::parse('1')", true); AssertExpression("2 <= long::parse('1')", false); // int & double AssertExpression("1 == 1.0", true); AssertExpression("1 == 1.5", false); AssertExpression("1 != 1.5", true); AssertExpression("1 != 1.0", false); AssertExpression("1 > 1.5", false); AssertExpression("2 > 1.5", true); AssertExpression("1 > 0.0", true); AssertExpression("1 >= 1.5", false); AssertExpression("1 >= 1.0", true); AssertExpression("2 >= 1.5", true); AssertExpression("1 < 1.5", true); AssertExpression("1 < 1.0", false); AssertExpression("2 < 1", false); AssertExpression("1 <= 1.5", true); AssertExpression("1 <= 1.0", true); AssertExpression("2 <= 1.5", false); // long & long AssertExpression("66666666666666 == 66666666666666", true); AssertExpression("66666666666666 == 77777777777777", false); AssertExpression("66666666666666 != 77777777777777", true); AssertExpression("66666666666666 != 66666666666666", false); AssertExpression("66666666666666 > 77777777777777", false); AssertExpression("66666666666666 > 66666666666666", false); AssertExpression("77777777777777 > 66666666666666", true); AssertExpression("66666666666666 >= 77777777777777", false); AssertExpression("66666666666666 >= 66666666666666", true); AssertExpression("77777777777777 >= 66666666666666", true); AssertExpression("66666666666666 < 77777777777777", true); AssertExpression("66666666666666 < 66666666666666", false); AssertExpression("77777777777777 < 66666666666666", false); AssertExpression("66666666666666 <= 77777777777777", true); AssertExpression("66666666666666 <= 66666666666666", true); AssertExpression("77777777777777 <= 66666666666666", false); // long & int AssertExpression("long::parse('1') == 1", true); AssertExpression("long::parse('1') == 2", false); AssertExpression("long::parse('1') != 2", true); AssertExpression("long::parse('1') != 1", false); AssertExpression("long::parse('1') > 2", false); AssertExpression("long::parse('1') > 1", false); AssertExpression("long::parse('2') > 1", true); AssertExpression("long::parse('1') >= 2", false); AssertExpression("long::parse('1') >= 1", true); AssertExpression("long::parse('2') >= 1", true); AssertExpression("long::parse('1') < 2", true); AssertExpression("long::parse('1') < 1", false); AssertExpression("long::parse('2') < 1", false); AssertExpression("long::parse('1') <= 2", true); AssertExpression("long::parse('1') <= 1", true); AssertExpression("long::parse('2') <= 1", false); // long & double AssertExpression("long::parse('1') == 1.0", true); AssertExpression("long::parse('1') == 2.0", false); AssertExpression("long::parse('1') != 2.0", true); AssertExpression("long::parse('1') != 1.0", false); AssertExpression("long::parse('1') > 2.0", false); AssertExpression("long::parse('1') > 1.0", false); AssertExpression("long::parse('2') > 1.0", true); AssertExpression("long::parse('1') >= 2.0", false); AssertExpression("long::parse('1') >= 1.0", true); AssertExpression("long::parse('2') >= 1.0", true); AssertExpression("long::parse('1') < 2.0", true); AssertExpression("long::parse('1') < 1.0", false); AssertExpression("long::parse('2') < 1.0", false); AssertExpression("long::parse('1') <= 2.0", true); AssertExpression("long::parse('1') <= 1.0", true); AssertExpression("long::parse('2') <= 1.0", false); // double & double AssertExpression("1.0 == 1.0", true); AssertExpression("1.0 == 2.0", false); AssertExpression("1.0 != 2.0", true); AssertExpression("1.0 != 1.0", false); AssertExpression("1.0 > 2.0", false); AssertExpression("1.0 > 1.0", false); AssertExpression("2.0 > 1.0", true); AssertExpression("1.0 >= 2.0", false); AssertExpression("1.0 >= 1.0", true); AssertExpression("2.0 >= 1.0", true); AssertExpression("1.0 < 2.0", true); AssertExpression("1.0 < 1.0", false); AssertExpression("2.0 < 1.0", false); AssertExpression("1.0 <= 2.0", true); AssertExpression("1.0 <= 1.0", true); AssertExpression("2.0 <= 1.0", false); // double & int AssertExpression("1.0 == 1", true); AssertExpression("1.0 == 2", false); AssertExpression("1.0 != 2", true); AssertExpression("1.0 != 1", false); AssertExpression("1.0 > 2", false); AssertExpression("1.0 > 1", false); AssertExpression("2.0 > 1", true); AssertExpression("1.0 >= 2", false); AssertExpression("1.0 >= 1", true); AssertExpression("2.0 >= 1", true); AssertExpression("1.0 < 2", true); AssertExpression("1.0 < 1", false); AssertExpression("2.0 < 1", false); AssertExpression("1.0 <= 2", true); AssertExpression("1.0 <= 1", true); AssertExpression("2.0 <= 1", false); // double & long AssertExpression("1.0 == long::parse('1')", true); AssertExpression("1.0 == 66666666666666", false); AssertExpression("1.0 != 66666666666666", true); AssertExpression("1.0 != long::parse('1')", false); AssertExpression("1.0 > 66666666666666", false); AssertExpression("1.0 > long::parse('1')", false); AssertExpression("2.0 > long::parse('1')", true); AssertExpression("1.0 >= 66666666666666", false); AssertExpression("1.0 >= long::parse('1')", true); AssertExpression("2.0 >= long::parse('1')", true); AssertExpression("1.0 < 66666666666666", true); AssertExpression("1.0 < long::parse('1')", false); AssertExpression("2.0 < long::parse('1')", false); AssertExpression("1.0 <= 66666666666666", true); AssertExpression("1.0 <= long::parse('1')", true); AssertExpression("2.0 <= long::parse('1')", false); // datetime & datetime // TO-DO !!!! // timespan & timespan AssertExpression("timespan::from-days(1.0) == timespan::from-days(1.0)", true); AssertExpression("timespan::from-days(1.0) == timespan::from-days(2.0)", false); AssertExpression("timespan::from-days(1.0) != timespan::from-days(2.0)", true); AssertExpression("timespan::from-days(1.0) != timespan::from-days(1.0)", false); AssertExpression("timespan::from-days(1.0) > timespan::from-days(2.0)", false); AssertExpression("timespan::from-days(1.0) > timespan::from-days(1.0)", false); AssertExpression("timespan::from-days(2.0) > timespan::from-days(1.0)", true); AssertExpression("timespan::from-days(1.0) >= timespan::from-days(2.0)", false); AssertExpression("timespan::from-days(1.0) >= timespan::from-days(1.0)", true); AssertExpression("timespan::from-days(2.0) >= timespan::from-days(1.0)", true); AssertExpression("timespan::from-days(1.0) < timespan::from-days(2.0)", true); AssertExpression("timespan::from-days(1.0) < timespan::from-days(1.0)", false); AssertExpression("timespan::from-days(2.0) < timespan::from-days(1.0)", false); AssertExpression("timespan::from-days(1.0) <= timespan::from-days(2.0)", true); AssertExpression("timespan::from-days(1.0) <= timespan::from-days(1.0)", true); AssertExpression("timespan::from-days(2.0) <= timespan::from-days(1.0)", false); // version & version AssertExpression("version::parse('1.0') == version::parse('1.0')", true); AssertExpression("version::parse('1.0') == version::parse('1.0.0')", false); AssertExpression("version::parse('1.0') == version::parse('1.0.0.1')", false); AssertExpression("version::parse('1.0') == version::parse('2.0')", false); AssertExpression("version::parse('1.0') != version::parse('1.0')", false); AssertExpression("version::parse('1.0') != version::parse('1.0.0')", true); AssertExpression("version::parse('1.0') != version::parse('1.0.0.1')", true); AssertExpression("version::parse('1.0') != version::parse('2.0')", true); AssertExpression("version::parse('1.0') > version::parse('1.0')", false); AssertExpression("version::parse('1.0') > version::parse('1.0.0')", false); AssertExpression("version::parse('1.0') > version::parse('1.0.0.1')", false); AssertExpression("version::parse('1.0') > version::parse('2.0')", false); AssertExpression("version::parse('1.0.0') > version::parse('1.0')", true); AssertExpression("version::parse('1.0.1') > version::parse('1.0')", true); AssertExpression("version::parse('2.0') > version::parse('1.0')", true); AssertExpression("version::parse('1.0') >= version::parse('1.0')", true); AssertExpression("version::parse('1.0') >= version::parse('1.0.0')", false); AssertExpression("version::parse('1.0') >= version::parse('1.0.0.1')", false); AssertExpression("version::parse('1.0') >= version::parse('2.0')", false); AssertExpression("version::parse('1.0.1') >= version::parse('1.0')", true); AssertExpression("version::parse('1.0') < version::parse('1.0')", false); AssertExpression("version::parse('1.0') < version::parse('1.0.0')", true); AssertExpression("version::parse('1.0') < version::parse('1.0.0.1')", true); AssertExpression("version::parse('1.0') < version::parse('2.0')", true); AssertExpression("version::parse('1.0.1') < version::parse('1.0')", false); AssertExpression("version::parse('2.0') < version::parse('1.0')", false); AssertExpression("version::parse('1.0') <= version::parse('1.0')", true); AssertExpression("version::parse('1.0') <= version::parse('1.0.0')", true); AssertExpression("version::parse('1.0') <= version::parse('1.0.0.1')", true); AssertExpression("version::parse('1.0') <= version::parse('2.0')", true); AssertExpression("version::parse('1.0.1') <= version::parse('1.0')", false); AssertExpression("version::parse('2.0') <= version::parse('1.0')", false); } [Test] public void TestCoreOperations() { AssertExpression("1 + 2", 3); AssertExpression("1 + 2 + 3", 6); AssertExpression("1 + 2 * 3", 7); AssertExpression("2 * 1 * 3", 6); AssertExpression("1 / 2 + 3", 3); AssertExpression("5.0 / (2 + 8)", 0.5); AssertExpression("((((1))))", 1); AssertExpression("((((1 + 2))))", 3); AssertExpression("((((1 + 2)+(2 + 1))))", 6); AssertExpression("((((1 + 2)/(2 + 1))))", 1); AssertExpression("-1", -1); AssertExpression("--1", 1); AssertExpression("10 % 3", 1); AssertExpression("10 % 3 % 5", 1); AssertExpression("-1 == 1 - 2", true); AssertExpression("--1.0 == 1.0", true); AssertExpression("1 != 1", false); AssertExpression("1 == 2", false); AssertExpression("10.0 - 1.0 >= 8.9", true); AssertExpression("10.0 + 1 <= 11.1", true); AssertExpression("1 * 1.0 == 1.0", true); AssertFailure("1.aaaa"); // fractional part expected AssertFailure("(1 1)"); AssertFailure("aaaa::1"); AssertFailure("aaaa::bbbb 1"); } [Test] public void TestCoreOperationFailures() { AssertFailure("1 + aaaa"); AssertFailure("1 + "); AssertFailure("*3"); AssertFailure("2 */ 1 * 3"); AssertFailure("1 // 2 + 3"); AssertFailure("double::tostring(5)/(2 + 8)"); AssertFailure("double::to-string(1 / 2 + 3"); AssertFailure("-'aaa'"); AssertFailure("true + true"); AssertFailure("true - true"); AssertFailure("true * true"); AssertFailure("true / true"); AssertFailure("true % true"); AssertFailure("((((1)))"); AssertFailure("((1 + 2))))"); AssertFailure("((((1 + 2) + (2 + 1)))"); AssertFailure("5 / 0"); AssertFailure("5 % 0"); } [Test] public void TestRelationalOperators() { AssertExpression("'a' + 'b' == 'ab'", true); AssertExpression("true", true); AssertExpression("false", false); } [Test] public void TestLogicalOperators() { AssertExpression("true or false or false", true); AssertExpression("false or false or false", false); AssertExpression("false or true", true); AssertExpression("true and false", false); AssertExpression("true and true and false", false); AssertExpression("true and true and true", true); AssertExpression("false and true and true", false); AssertExpression("not true", false); AssertExpression("not false", true); AssertExpression("not (1==1)", false); AssertExpression("true or not (1 == 1)", true); AssertExpression("true or not (--1 == 1)", true); } [Test] public void TestConversionFunctions() { // string to bool AssertExpression("bool::parse('True')", true); AssertExpression("bool::parse('true')", true); AssertExpression("bool::parse('False')", false); AssertExpression("bool::parse('false')", false); AssertFailure("bool::parse('aaafalse')"); // bool to string AssertExpression("bool::to-string(false)", bool.FalseString); AssertExpression("bool::to-string(true)", bool.TrueString); AssertFailure("bool::to-string('aaafalse')"); AssertFailure("bool::to-string(1)"); // string to int AssertExpression("int::parse('123' + '45')", 12345); AssertFailure("int::parse('12345.66666')"); // int to string AssertExpression("int::to-string(12345)", "12345"); // string to long AssertExpression("long::parse('6667778888' + '666777')", 6667778888666777); // long to string AssertExpression("long::to-string(6667778888666777)", "6667778888666777"); // string to double AssertExpression("double::parse('5') / (2 + 8)", 0.5); AssertExpression("double::parse('1') / 2 + 3", 3.5); AssertFailure("double::parse('aaaaaaaaa')"); // double to string AssertExpression("double::to-string(5.56)", "5.56"); AssertExpression("double::to-string(5.0)", "5"); AssertFailure("double::to-string(5#0)"); // string to datetime AssertExpression("datetime::parse('12/31/1999 01:23:34')", new DateTime(1999,12,31,1,23,34)); AssertFailure("datetime::parse('B')"); // coercion AssertExpression("coercion::get-name(coercion::create-bar())", "default bar"); AssertExpression("coercion::get-name(coercion::create-bar('a'))", "a"); AssertExpression("coercion::get-name(coercion::create-boo())", "default boo"); AssertExpression("coercion::get-name(coercion::create-boo('b'))", "b"); AssertExpression("coercion::get-name(coercion::create-zoo())", "default zoo"); AssertExpression("coercion::get-name(coercion::create-zoo('c'))", "c"); AssertFailure("coercion::get-name(coercion::create-foo())"); AssertFailure("coercion::get-name(coercion::create-foo('d'))"); } [Test] public void TestStringFunctions() { AssertExpression("string::get-length('')", 0); AssertExpression("string::get-length('') == 0", true); AssertExpression("string::get-length('') == 1", false); AssertExpression("string::get-length('test')", 4); AssertExpression("string::get-length('test') == 4", true); AssertExpression("string::get-length('test') == 5", false); AssertExpression("string::get-length(prop1)", 4); AssertExpression("string::get-length('d''Artagnan')", 10); AssertExpression("string::get-length('d''Artagnan') == 10", true); AssertExpression("string::get-length('d''Artagnan') == 11", false); AssertExpression("string::substring('abcde',1,2) == 'bc'", true); AssertExpression("string::trim(' ab ') == 'ab'", true); AssertExpression("string::trim-start(' ab ') == 'ab '", true); AssertExpression("string::trim-end(' ab ') == ' ab'", true); AssertExpression("string::pad-left('ab',5,'.') == '...ab'", true); AssertExpression("string::pad-right('ab',5,'.') == 'ab...'", true); AssertExpression("string::index-of('abc','c') == 2", true); AssertExpression("string::index-of('abc','d') == -1", true); AssertExpression("string::index-of('abc','d') == -1", true); } [Test] public void TestDateTimeFunctions() { AssertFailure("datetime::now(111)"); AssertFailure("datetime::add()"); AssertFailure("datetime::now("); } [Test] public void TestMathFunctions() { AssertExpression("math::round(0.1)", 0.0); AssertExpression("math::round(0.7)", 1.0); AssertExpression("math::floor(0.1)", 0.0); AssertExpression("math::floor(0.7)", 0.0); AssertExpression("math::ceiling(0.1)", 1.0); AssertExpression("math::ceiling(0.7)", 1.0); AssertExpression("math::abs(1)", 1.0); AssertExpression("math::abs(-1)", 1.0); } [Test] public void TestConditional() { AssertExpression("if(true,1,2)", 1); AssertExpression("if(true,'a','b')", "a"); AssertExpression("if(false,'a','b')", "b"); AssertFailure("if(1,2,3)"); AssertFailure("if(true 2,3)"); AssertFailure("if(true,2,3 3"); AssertFailure("if(true,2 2,3)"); AssertFailure("if [ true, 1, 0 ]"); } [Test] public void TestFileFunctions() { AssertExpression("file::exists('c:\\i_am_not_there.txt')", false); AssertFailure("file::get-last-write-time('c:/no-such-file.txt')"); } [Test] public void TestDirectoryFunctions() { AssertExpression("directory::exists('c:\\i_am_not_there')", false); AssertExpression("directory::exists('" + Directory.GetCurrentDirectory() + "')", true); } [Test] public void TestNAntFunctions() { AssertExpression("property::get-value('prop1')", "asdf"); AssertExpression("property::exists('prop1')", true); AssertExpression("property::exists('prop1a')", false); //AssertExpression("target::exists('i_am_not_there')", false); //AssertExpression("target::exists('test')", true); } [Test] public void TestStandaloneEvaluator() { ExpressionEvaluator eval = new ExpressionEvaluator(_project, _project.Properties, new Hashtable(), new Stack()); Assert.AreEqual(eval.Evaluate("1 + 2 * 3"), 7); eval.CheckSyntax("1 + 2 * 3"); } [Test] [ExpectedException(typeof(ExpressionParseException))] public void TestStandaloneEvaluatorFailure() { ExpressionEvaluator eval = new ExpressionEvaluator(_project, _project.Properties, new Hashtable(), new Stack()); eval.Evaluate("1 + 2 * datetime::now("); } [Test] [ExpectedException(typeof(ExpressionParseException))] public void TestStandaloneEvaluatorFailure2() { ExpressionEvaluator eval = new ExpressionEvaluator(_project, _project.Properties, new Hashtable(), new Stack()); eval.Evaluate("1 1"); } [Test] [ExpectedException(typeof(ExpressionParseException))] public void TestStandaloneEvaluatorSyntaxCheckFailure() { ExpressionEvaluator eval = new ExpressionEvaluator(_project, _project.Properties, new Hashtable(), new Stack()); eval.CheckSyntax("1 + 2 * 3 1"); } #endregion Public Instance Methods #region Private Instance Methods private void AssertExpression(string expression, object expectedReturnValue) { string value = _project.ExpandProperties("${" + expression + "}", Location.UnknownLocation); string expectedStringValue = Convert.ToString(expectedReturnValue, CultureInfo.InvariantCulture); _project.Log(Level.Debug, "expression: " + expression); _project.Log(Level.Debug, "value: " + value + ", expected: " + expectedStringValue); Assert.AreEqual(expectedStringValue, value, expression); } private void AssertFailure(string expression) { try { string value = _project.ExpandProperties("${" + expression + "}", Location.UnknownLocation); // we shouldn't get here Assert.Fail("Expected BuildException while evaluating ${" + expression + "}, nothing was thrown. The returned value was " + value); } catch (BuildException ex) { _project.Log(Level.Debug, "Got expected failure on ${" + expression + "}: " + ((ex.InnerException != null) ? ex.InnerException.Message : "")); // ok - this one should have been thrown } catch (Exception ex) { // some other exception has been thrown - fail Assert.Fail("Expected BuildException while evaluating ${" + expression + "}, but " + ex.GetType().FullName + " was thrown."); } } private string FormatBuildFile(string globalTasks, string targetTasks) { return string.Format(CultureInfo.InvariantCulture, _format, TempDirName, globalTasks, targetTasks); } #endregion Private Instance Methods } [FunctionSet("coercion", "Test Function Extensibility")] public class CoercionFunctions : FunctionSetBase { public CoercionFunctions(Project project, PropertyDictionary propDict ) : base(project, propDict) { } [Function("create-foo")] public static Foo CreateFoo() { return new Foo(); } [Function("create-foo")] public static Foo CreateFoo(string name) { return new Foo(name); } [Function("create-bar")] public static Bar CreateBar() { return new Bar(); } [Function("create-bar")] public static Bar CreateBar(string name) { return new Bar(name); } [Function("create-zoo")] public static Zoo CreateZoo() { return new Zoo(); } [Function("create-zoo")] public static Zoo CreateZoo(string name) { return new Zoo(name); } [Function("create-boo")] public static Bar CreateBoo() { return new Boo(); } [Function("create-boo")] public static Boo CreateBoo(string name) { return new Boo(name); } [Function("get-name")] public static string GetName(Bar bar) { return bar.Name; } } public class Foo { private readonly string name; public Foo() : this("default foo") { } public Foo(String name) { this.name = name; } public string Name { get { return name; } } } public class Bar : Foo { public Bar() : this("default bar") { } public Bar(String name) : base(name) { } } public class Zoo : Bar { public Zoo() : this("default zoo") { } public Zoo(String name) : base(name) { } } public class Boo : Bar, IConvertible { public Boo() : this("default boo") { } public Boo(String name) : base(name) { } #region IConvertible Members [CLSCompliant(false)] public ulong ToUInt64(IFormatProvider provider) { return 0; } [CLSCompliant(false)] public sbyte ToSByte(IFormatProvider provider) { return 0; } public double ToDouble(IFormatProvider provider) { return 0; } public DateTime ToDateTime(IFormatProvider provider) { return new DateTime (); } public float ToSingle(IFormatProvider provider) { return 0; } public bool ToBoolean(IFormatProvider provider) { return false; } public int ToInt32(IFormatProvider provider) { return 0; } [CLSCompliant(false)] public ushort ToUInt16(IFormatProvider provider) { return 0; } public short ToInt16(IFormatProvider provider) { return 0; } public string ToString(IFormatProvider provider) { return null; } public byte ToByte(IFormatProvider provider) { return 0; } public char ToChar(IFormatProvider provider) { return '\0'; } public long ToInt64(IFormatProvider provider) { return 0; } public System.TypeCode GetTypeCode() { return new System.TypeCode (); } public decimal ToDecimal(IFormatProvider provider) { return 0; } public object ToType(Type conversionType, IFormatProvider provider) { if (conversionType == typeof(Foo)) return new Foo(Name + " => foo"); if (conversionType == typeof(Bar)) return new Bar(Name + " => bar"); throw new InvalidCastException(); } [CLSCompliant(false)] public uint ToUInt32(IFormatProvider provider) { return 0; } #endregion } } nant-0.92-rc1/tests/NAnt.Core/ExceptionTest.cs0000644000175000017500000003440111757302275021052 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Eric Gunnerson // Gerry Shaw (gerry_shaw@yahoo.com) using System; using System.IO; using System.Reflection; using System.Collections; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Globalization; using NUnit.Framework; using NAnt.Core; namespace Tests.NAnt.Core { /// /// General purpose test that checks to see that all exceptions implement /// required methods. /// /// /// This class was inspired / stolen from the article "The Well-Tempered Exception", /// by Eric Gunnerson, Microsoft. /// /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncscol/html/csharp08162001.asp /// /// The test verifies: /// 1) The exception name ends in "Exception"... /// 2) The exception implements the 3 standard constructors: /// class(); /// class(string message); /// class(string message, Exception inner); /// 3) The exception implements the deserialization constructor: /// class(SerializationInfo info, StreamingContext context); /// 4) The exception has no public fields /// 5) If the exception has private fields, that it implements GetObjectData() /// (there's no guarantee it does it *correctly*) /// 6) If the exception has private fields, it overrides the Message property. /// 7) The exception is marked as serializable. /// [TestFixture] public class ExceptionTest { #region Public Instance Methods [Test] public void Test_AllExceptions() { // For each assembly we want to check instantiate an object from // that assembly and use the type to get the assembly. // NAnt.Core.dll ProcessAssembly(Assembly.GetAssembly(typeof(Project))); // Check the test exceptions to make sure test is valid - see bottom // of this file. ProcessAssembly(Assembly.GetAssembly(this.GetType())); } public void ProcessAssembly(Assembly a) { foreach (Type t in a.GetTypes()) { if (IsException(t)) { CheckException(a, t); } } } #endregion Public Instance Methods #region Private Instance Methods private bool IsException(Type type) { Type baseType = null; while ((baseType = type.BaseType) != null) { if (baseType == typeof(System.Exception)) { return true; } type = baseType; } return false; } private void CheckPublicConstructor(Type t, string description, params Type[] parameters) { // locate constructor ConstructorInfo ci = t.GetConstructor(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, parameters, null); // fail if constructor does not exist Assert.IsNotNull(ci, t.Name + description + " is a required constructor."); // fail if constructor is private Assert.IsFalse(ci.IsPrivate, t.Name + description + " is private, must be public."); // fail if constructor is protected Assert.IsFalse(ci.IsFamily, t.Name + description + " is internal, must be public."); // fail if constructor is internal Assert.IsFalse(ci.IsAssembly, t.Name + description + " is internal, must be public."); // fail if constructor is protected internal Assert.IsFalse(ci.IsFamilyOrAssembly, t.Name + description + " is protected internal, must be public."); // sanity check to make sure the constructor is public Assert.IsTrue(ci.IsPublic, t.Name + description + " is not public, must be public."); } private void CheckProtectedConstructor(Type t, string description, params Type[] parameters) { // locate constructor ConstructorInfo ci = t.GetConstructor(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, parameters, null); // fail if constructor does not exist Assert.IsNotNull(ci, t.Name + description + " is a required constructor."); // fail if constructor is public Assert.IsFalse(ci.IsPublic, t.Name + description + " is public, must be protected."); // fail if constructor is private Assert.IsFalse(ci.IsPrivate, t.Name + description + " is private, must be public or protected."); // fail if constructor is internal Assert.IsFalse(ci.IsAssembly, t.Name + description + " is internal, must be protected."); // fail if constructor is protected internal Assert.IsFalse(ci.IsFamilyOrAssembly, t.Name + description + " is protected internal, must be protected."); // sanity check to make sure the constructor is protected Assert.IsTrue(ci.IsFamily, t.Name + description + " is not protected, must be protected."); } private void CheckPrivateConstructor(Type t, string description, params Type[] parameters) { // locate constructor ConstructorInfo ci = t.GetConstructor(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, parameters, null); // fail if constructor does not exist Assert.IsNotNull(ci, t.Name + description + " is a required constructor."); // fail if constructor is public Assert.IsFalse(ci.IsPublic, t.Name + description + " is public, must be private."); // fail if constructor is protected Assert.IsFalse(ci.IsFamily, t.Name + description + " is protected, must be private."); // fail if constructor is internal Assert.IsFalse(ci.IsAssembly, t.Name + description + " is internal, must be private."); // fail if constructor is protected internal Assert.IsFalse(ci.IsFamilyOrAssembly, t.Name + description + " is protected internal, must be private."); // sainty check to make sure the constructor is private Assert.IsTrue(ci.IsPrivate, t.Name + description + " is not private, must be private."); } private void CheckException(Assembly assembly, Type t) { // check to see that the exception is correctly named, with "Exception" at the end t.Name.EndsWith("Exception"); Assert.IsTrue(t.Name.EndsWith("Exception"), t.Name + " class name must end with Exception."); // Does the exception have the 3 standard constructors? // Default constructor CheckPublicConstructor(t, "()"); // Constructor with a single string parameter CheckPublicConstructor(t, "(string message)", typeof(System.String)); // Constructor with a string and an inner exception CheckPublicConstructor(t, "(string message, Exception inner)", typeof(System.String), typeof(System.Exception)); // check to see if the serialization constructor is present // if exception is sealed, constructor should be private // if exception is not sealed, constructor should be protected if (t.IsSealed) { // check to see if the private serialization constructor is present... CheckPrivateConstructor(t, "(SerializationInfo info, StreamingContext context)", typeof(System.Runtime.Serialization.SerializationInfo), typeof(System.Runtime.Serialization.StreamingContext)); } else { // check to see if the protected serialization constructor is present... CheckProtectedConstructor(t, "(SerializationInfo info, StreamingContext context)", typeof(System.Runtime.Serialization.SerializationInfo), typeof(System.Runtime.Serialization.StreamingContext)); } // check to see if the type is market as serializable Assert.IsTrue(t.IsSerializable, t.Name + " is not serializable, missing [Serializable]?"); // check to see if there are any public fields. These should be properties instead... FieldInfo[] publicFields = t.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance); if (publicFields.Length != 0) { foreach (FieldInfo fieldInfo in publicFields) { Assert.Fail(t.Name + "." + fieldInfo.Name + " is a public field, should be exposed through property instead."); } } // If this exception has any fields, check to make sure it has a // version of GetObjectData. If not, it does't serialize those fields. FieldInfo[] fields = t.GetFields(BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); if (fields.Length != 0) { if (t.GetMethod("GetObjectData", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance) == null) { Assert.Fail(t.Name + " does not implement GetObjectData but has private fields."); } // Make sure Message is overridden if there are private fields. // drieseng : commented out this test, as it does not always // make sense. Not all private fields should somehow be exposed // as part of the message of the exception. //Assert.IsTrue(t.GetProperty("Message", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance) != null, t.Name + " does not override the Message property."); } } #endregion Private Instance Methods } /// Do nothing exception to verify that the exception tester is working correctly. [Serializable] public class SimpleTestException : ApplicationException { #region Public Instance Constructors public SimpleTestException() { } public SimpleTestException(string message) : base(message) { } public SimpleTestException(string message, Exception inner) : base(message, inner) { } #endregion Public Instance Constructors #region Protected Instance Constructors // deserialization constructor protected SimpleTestException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endregion Protected Instance Constructors } /// /// Exception to verify that the exception tester is working correctly. /// [Serializable] public class TestException : ApplicationException, ISerializable { #region Private Instance Fields private int _value; #endregion Private Instance Fields #region Public Instance Constructors public TestException() { } public TestException(string message) : base(message) { } public TestException(string message, Exception inner) : base(message, inner) { } // constructors that take the added value public TestException(string message, int value) : base(message) { _value = value; } #endregion Public Instance Constructors #region Protected Instance Constructors // deserialization constructor protected TestException(SerializationInfo info, StreamingContext context) : base(info, context) { _value = info.GetInt32("Value"); } #endregion Protected Instance Constructors #region Public Instance Properties public int Value { get { return _value; } } #endregion Public Instance Properties #region Override implementation of ApplicationException // Called by the frameworks during serialization // to fetch the data from an object. public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("Value", _value); } // overridden Message property. This will give the // proper textual representation of the exception, // with the added field value. public override string Message { get { // NOTE: should be localized... string s = String.Format(CultureInfo.InvariantCulture, "Value: {0}", _value); return base.Message + Environment.NewLine + s; } } #endregion Override implementation of ApplicationException } /// /// Exception to verify that the exception tester is working on sealed exception. /// [Serializable] public sealed class SealedTestException : TestException { #region Public Instance Constructors public SealedTestException() { } public SealedTestException(string message) : base(message) { } public SealedTestException(string message, Exception inner) : base(message, inner) { } // constructors that take the added value public SealedTestException(string message, int value) : base(message, value) { } #endregion Public Instance Constructors #region Private Instance Constructors // deserialization constructor private SealedTestException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endregion Private Instance Constructors } } nant-0.92-rc1/tests/NAnt.Core/Framework.config0000644000175000017500000041545311757302275021063 0ustar jtaylorjtaylor true true sn lc false false true true sn lc true true true true true true true true true true true true true true true true true true true true true true sn lc true true true true true true true true true true true true true true true true true true true true true true true sn lc true true true true true true true true true true true true true true true true true true true true true true true sn lc true The .NET Framework 1.1 SDK is not installed. true true true cfresgen sn lc The .NET Framework 2.0 SDK is not installed. true true true true true true true true true true true true true true true true true true true true sn lc true true true true true true true true true true true true true true true true true true true true true true true true true true sn lc true true ${csc.tool} true true true ${csc.supportsdocgeneration} true true true true mjs true ${mbas.tool} true ${resgen.tool} true sn true false true true gmcs true true true ${csc.supportsdocgeneration} true true true true mjs strict vbnc true ${resgen.tool} true ${resgen.supportsexternalfilereferences} sn true false true true gmcs true linq true true true true true true true mjs strict vbnc true true true sn true false true true dmcs true linq true true true true true true true mjs strict vbnc true true true sn true false true smcs true true true true true true true true true true sn false true true sn false true true Unable to locate 'mono' module using pkg-config. Download the Mono development packages from http://www.mono-project.com/downloads/. Unable to locate 'mono' module using pkg-config. Download the Mono development packages from http://www.mono-project.com/downloads/. true ${path::combine(prefix, 'lib/mono/1.0/mcs.exe')} true true true ${csc.supportsdocgeneration} true true true true mjs true ${path::combine(prefix, 'lib/mono/1.0/mbas.exe')} true ${resgen.tool} true sn true false true Unable to locate 'mono' module using pkg-config. Download the Mono development packages from http://www.mono-project.com/downloads/. true gmcs true true true ${csc.supportsdocgeneration} true true true true mjs strict vbnc true ${resgen.tool} true ${resgen.supportsexternalfilereferences} sn true false true Unable to locate 'mono' module using pkg-config. Download the Mono development packages from http://www.mono-project.com/downloads/. true gmcs true linq true true true true true true true mjs strict vbnc true true true sn true false true Unable to locate 'mono' module using pkg-config. Download the Mono development packages from http://www.mono-project.com/downloads/. true dmcs true linq true true true true true true true mjs strict vbnc true true true sn true false true Unable to locate 'mono' module using pkg-config. Download the Mono development packages from http://www.mono-project.com/downloads/. smcs true true true true true true true true true true sn false nant-0.92-rc1/tests/NAnt.Core/Attributes/0000755000175000017500000000000011757310030020035 5ustar jtaylorjtaylornant-0.92-rc1/tests/NAnt.Core/Attributes/DateTimeValidatorAttributeTest.cs0000644000175000017500000000451111757302275026467 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Clayton Harbour (claytonharbour@sporadicism.com) using System; using System.IO; using System.Text; using System.Xml; using System.Globalization; using NUnit.Framework; using NAnt.Core; using NAnt.Core.Attributes; using Tests.NAnt.Core.Util; namespace Tests.NAnt.Core.Attributes { [TestFixture] public class DateTimeValidatorAttributeTest : BuildTestBase { /// /// Test that valid dates do not throw an exception. /// [Test] public void Test_ValidDates() { Assert.IsTrue(IsValid("August 2, 1975")); Assert.IsTrue(IsValid("2004/01/01")); Assert.IsTrue(IsValid("1901/01/01")); Assert.IsTrue(IsValid("May 1, 2004")); Assert.IsTrue(IsValid("January 15, 2999")); } /// /// Test that invalid dates throw an exception. /// [Test] public void Test_InvalidDates() { Assert.IsFalse(IsValid("August is an awesome month.")); Assert.IsFalse(IsValid("August 2nd is cool.")); Assert.IsFalse(IsValid("1234567890")); Assert.IsFalse(IsValid("More invalid dates.")); Assert.IsFalse(IsValid("@!#$%$^^")); } private bool IsValid (object date) { try { DateTimeValidatorAttribute validator = new DateTimeValidatorAttribute(); validator.Validate(date); return true; } catch (ValidationException) { return false; } } } } nant-0.92-rc1/tests/NAnt.Core/Attributes/StringValidatorAttributeTest.cs0000644000175000017500000000607011757302275026243 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Clayton Harbour (claytonharbour@sporadicism.com) using System; using System.IO; using System.Text; using System.Xml; using System.Globalization; using NUnit.Framework; using NAnt.Core; using NAnt.Core.Attributes; using Tests.NAnt.Core.Util; namespace Tests.NAnt.Core.Attributes { [TestFixture] public class StringValidatorAttributeTest : BuildTestBase { /// /// Test that valid values do not throw an exception. /// [Test] public void Test_ValidStrings() { Assert.IsTrue(IsValid("August 2, 1975")); Assert.IsTrue(IsValid("blah")); Assert.IsTrue(IsValid("n", false)); Assert.IsTrue(IsValid("http://nant.sourceforge.net", @"(?\w+):\/\/(?[\w.]+\/?)\S*")); Assert.IsTrue(IsValid("", true, @"^[A-Za-z0-9][A-Za-z0-9._\-]*$")); // validate name of file Assert.IsTrue(IsValid("name_of_file", @"^[A-Za-z0-9][A-Za-z0-9._\-]*$")); } /// /// Test that invalid dates throw an exception. /// [Test] public void Test_InvalidStrings() { Assert.IsFalse(IsValid("the/path/to/a/file", @"^[A-Za-z0-9][A-Za-z0-9._\-]*$")); Assert.IsFalse(IsValid("", false)); Assert.IsFalse(IsValid("blah blah", @"(?\w+):\/\/(?[\w.]+\/?)\S*")); } private bool IsValid (object value) { return this.IsValid(value, true); } private bool IsValid (object value, bool allowEmpty) { return this.IsValid(value, allowEmpty, null); } private bool IsValid (object value, string expression) { return this.IsValid(value, true, expression); } private bool IsValid (object value, bool allowEmpty, string expression) { try { StringValidatorAttribute validator = new StringValidatorAttribute(); validator.AllowEmpty = allowEmpty; validator.Expression = expression; validator.Validate(value); return true; } catch (ValidationException) { return false; } } } } nant-0.92-rc1/tests/NAnt.Core/ElementTest.cs0000644000175000017500000002473011757302275020511 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Tomas Restrepo (tomasr@mvps.org) using System; using System.Collections; using System.ComponentModel; using System.IO; using System.Reflection; using System.Text; using System.Xml; using NUnit.Framework; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Types; namespace Tests.NAnt.Core { /// /// A simple task with a null element to test failures. /// [TaskName("elementTest1")] class ElementTest1Task : Task { #region Private Instance Fields private OutputType _outputType = OutputType.None; private Uri _uri; #endregion Private Instance Fields #region Internal Static Fields internal const string UriPropertyName = "elementTest1.uri"; #endregion Internal Static Fields #region Public Instance Properties [BuildElement("fileset")] public FileSet FileSet { get { return null; } // we'll test for null later! } [TaskAttribute("type")] public OutputType Type { get { return _outputType; } set { _outputType = value; } } [TaskAttribute("uri")] public Uri Uri { get { return _uri; } set { _uri = value; } } #endregion Public Instance Properties #region Override implementation of Task protected override void ExecuteTask() { Log(Level.Info, "OutputType is \"{0}\".", Type.ToString()); if (Uri != null) { Properties.Add(ElementTest1Task.UriPropertyName, Uri.ToString()); } } #endregion Override implementation of Task [TypeConverter(typeof(OutputTypeConverter))] public enum OutputType { None = 0, Exe = 1, Dll = 2 } public class OutputTypeConverter : EnumConverter { public OutputTypeConverter() : base(typeof(OutputType)) { } public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { if (value is string) { if (string.Compare((string) value, "executable", true, culture) == 0) { return OutputType.Exe; } } return base.ConvertFrom (context, culture, value); } } } /* /// /// A simple task with a null element to test failures. /// [TaskName("elementTest2")] class ElementTest2Task : Task { #region Private Instance Fields private ArrayList _children = new ArrayList(); #endregion Private Instance Fields #region Public Instance Properties [BuildElementCollection("children", "child", ElementType=typeof(object))] public ArrayList Children { get { return _children; } set { _children = value; } } #endregion Public Instance Properties #region Override implementation of Task protected override void ExecuteTask() { } #endregion Override implementation of Task } */ [TestFixture] public class ElementTest : BuildTestBase { #region Public Instance Methods /// /// Test that a read-only property with an element doesn't /// return null when the getter is invoked /// [Test] public void Test_Null_Element_Prop_Value() { const string build = @" "; try { string result = RunBuild(build); Assert.Fail("Null property value allowed." + Environment.NewLine + result); } catch (TestBuildException e) { if (!(e.InnerException is BuildException)) { Assert.Fail("Unexpected exception thrown." + Environment.NewLine + e.ToString()); } } } [Test] public void Test_Enum_Default() { const string build = @" "; string result = RunBuild(build); Assert.IsTrue(result.IndexOf("OutputType is \"None\".") != -1); } [Test] public void Test_Enum_TypeConverter() { const string build = @" "; string result = RunBuild(build); Assert.IsTrue(result.IndexOf("OutputType is \"Exe\".") != -1); } [ExpectedException(typeof(TestBuildException))] public void Test_Enum_InvalidValue() { const string build = @" "; RunBuild(build); } [Test] public void Test_Uri_Default() { const string build = @" "; Project project = CreateFilebasedProject(build); ExecuteProject(project); // uri property should not be registered Assert.IsFalse(project.Properties.Contains(ElementTest1Task.UriPropertyName)); } [Test] public void Test_Uri_RelativeFilePath() { const string build = @" "; Project project = CreateFilebasedProject(build); ExecuteProject(project); Uri expectedUri = new Uri(project.GetFullPath("dir/test.txt")); // uri property should be registered Assert.IsTrue(project.Properties.Contains(ElementTest1Task.UriPropertyName)); // path should have been resolved to absolute path (in project dir) Assert.AreEqual(expectedUri.ToString(), project.Properties[ ElementTest1Task.UriPropertyName]); } [Test] public void Test_Uri_FileScheme() { const string build = @" "; Project project = CreateFilebasedProject(build); ExecuteProject(project); // uri property should be registered Assert.IsTrue(project.Properties.Contains(ElementTest1Task.UriPropertyName)); // ensure resulting property matches expected URI Assert.AreEqual(new Uri("file:///test/file.txt"), new Uri(project.Properties[ElementTest1Task.UriPropertyName])); } [Test] public void Test_Uri_HttpScheme() { const string build = @" "; Project project = CreateFilebasedProject(build); ExecuteProject(project); // uri property should be registered Assert.IsTrue(project.Properties.Contains(ElementTest1Task.UriPropertyName)); // ensure resulting property matches expected URI Assert.AreEqual("http://nant.sourceforge.net/", project.Properties[ ElementTest1Task.UriPropertyName]); } [Test] [ExpectedException(typeof(TestBuildException))] public void Test_Uri_InvalidUri() { const string build = @" "; RunBuild(build); } [Test] [Ignore ("Re-enable this test once we modified the task to generate a schema for a specified set of assemblies.")] [ExpectedException(typeof(TestBuildException))] public void Test_Non_StronglyTyped_Element_Collection() { const string build = @" "; RunBuild(build); } #endregion Public Instance Methods } } nant-0.92-rc1/tests/NAnt.Core/FrameworkInfoTest.cs0000644000175000017500000002170111757302275021664 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2007 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.IO; using System.Reflection; using System.Runtime.Serialization.Formatters.Binary; using System.Xml; using NUnit.Framework; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Types; namespace Tests.NAnt.Core { [TestFixture] public class FrameworkInfoTest : BuildTestBase { [Test] public void Serialization_Valid() { Project p = CreateEmptyProject(); FrameworkInfoDictionary frameworks = p.Frameworks; BinaryFormatter bf = new BinaryFormatter(); foreach (FrameworkInfo framework in frameworks) { if (!framework.IsValid) continue; MemoryStream ms = new MemoryStream(); bf.Serialize(ms, framework); ms.Position = 0; FrameworkInfo df = (FrameworkInfo) bf.Deserialize(ms); Assert.IsNotNull(framework.ClrVersion, "#1"); Assert.AreEqual(framework.ClrVersion, df.ClrVersion, "#2"); Assert.IsNotNull(framework.Description, "#3"); Assert.AreEqual(framework.Description, df.Description, "#4"); Assert.IsNotNull(framework.Family, "#5"); Assert.AreEqual(framework.Family, df.Family, "#6"); Assert.IsNotNull(framework.FrameworkAssemblyDirectory, "#7"); Assert.IsNotNull(df.FrameworkAssemblyDirectory, "#8"); Assert.AreEqual(framework.FrameworkAssemblyDirectory.FullName, df.FrameworkAssemblyDirectory.FullName, "#9"); Assert.IsNotNull(framework.FrameworkDirectory, "#10"); Assert.IsNotNull(df.FrameworkDirectory, "#11"); Assert.AreEqual(framework.FrameworkDirectory.FullName, df.FrameworkDirectory.FullName, "#12"); Assert.IsNotNull(framework.Name, "#13"); Assert.AreEqual(framework.Name, df.Name, "#14"); Assert.IsNotNull(framework.Project, "#15"); Assert.IsNotNull(df.Project, "#16"); if (framework.SdkDirectory != null) { Assert.IsNotNull(df.SdkDirectory, "#18"); Assert.AreEqual(framework.SdkDirectory.FullName, df.SdkDirectory.FullName, "#19"); } else { Assert.IsNull(df.SdkDirectory, "#18"); } Assert.IsNotNull(framework.TaskAssemblies, "#20"); Assert.IsNotNull(df.TaskAssemblies, "#21"); Assert.IsNotNull(framework.TaskAssemblies.BaseDirectory, "#22"); Assert.IsNotNull(df.TaskAssemblies.BaseDirectory, "#23"); Assert.AreEqual(framework.TaskAssemblies.BaseDirectory.FullName, df.TaskAssemblies.BaseDirectory.FullName, "#24"); Assert.AreEqual(framework.TaskAssemblies.FileNames.Count, df.TaskAssemblies.FileNames.Count, "#25"); Assert.IsNotNull(framework.Version, "#26"); Assert.AreEqual(framework.Version, df.Version, "#27"); } } [Test] public void Serialization_Invalid() { Project p = CreateEmptyProject(); FrameworkInfoDictionary frameworks = p.Frameworks; BinaryFormatter bf = new BinaryFormatter(); foreach (FrameworkInfo framework in frameworks) { if (framework.IsValid) continue; MemoryStream ms = new MemoryStream(); bf.Serialize(ms, framework); ms.Position = 0; FrameworkInfo df = (FrameworkInfo) bf.Deserialize(ms); Assert.IsNotNull(framework.Description, "#A1"); Assert.AreEqual(framework.Description, df.Description, "#A2"); Assert.IsNotNull(framework.Family, "#A3"); Assert.AreEqual(framework.Family, df.Family, "#A4"); Assert.IsNotNull(framework.Name, "#A5"); Assert.AreEqual(framework.Name, df.Name, "#A6"); Assert.IsNotNull(framework.ClrVersion, "#A7"); Assert.AreEqual(framework.ClrVersion, df.ClrVersion, "#A8"); Assert.IsNotNull(framework.Version, "#A7"); Assert.AreEqual(framework.Version, df.Version, "#A8"); Assert.IsTrue (Enum.IsDefined(typeof(ClrType), framework.ClrType), "#A9"); Assert.AreEqual(framework.ClrType, df.ClrType, "#A10"); Assert.IsNotNull(framework.VisualStudioVersion, "#A11"); try { object x = df.FrameworkAssemblyDirectory; Assert.Fail ("#C1:" + x); } catch (ArgumentException ex) { // The current framework is not valid Assert.AreEqual(typeof(ArgumentException), ex.GetType(), "#C2"); Assert.IsNull(ex.InnerException, "#C3"); Assert.IsNotNull(ex.Message, "#C4"); Assert.IsNull(ex.ParamName, "#C5"); } try { object x = df.FrameworkDirectory; Assert.Fail ("#D1:" + x); } catch (ArgumentException ex) { // The current framework is not valid Assert.AreEqual(typeof(ArgumentException), ex.GetType(), "#D2"); Assert.IsNull(ex.InnerException, "#D3"); Assert.IsNotNull(ex.Message, "#D4"); Assert.IsNull(ex.ParamName, "#D5"); } try { object x = df.Project; Assert.Fail ("#E1:" + x); } catch (ArgumentException ex) { // The current framework is not valid Assert.AreEqual(typeof(ArgumentException), ex.GetType(), "#E2"); Assert.IsNull(ex.InnerException, "#E3"); Assert.IsNotNull(ex.Message, "#E4"); Assert.IsNull(ex.ParamName, "#E5"); } try { object x = df.SdkDirectory; Assert.Fail ("#F1" + x); } catch (ArgumentException ex) { // The current framework is not valid Assert.AreEqual(typeof(ArgumentException), ex.GetType(), "#F2"); Assert.IsNull(ex.InnerException, "#F3"); Assert.IsNotNull(ex.Message, "#F4"); Assert.IsNull(ex.ParamName, "#F5"); } try { object x = df.TaskAssemblies; Assert.Fail ("#G1" + x); } catch (ArgumentException ex) { // The current framework is not valid Assert.AreEqual(typeof(ArgumentException), ex.GetType(), "#G2"); Assert.IsNull(ex.InnerException, "#G3"); Assert.IsNotNull(ex.Message, "#G4"); Assert.IsNull(ex.ParamName, "#G5"); } } } [Test] public void Invalid_SDK() { const string xml = @" ${gacutil.tool} "; XmlDocument configDoc = new XmlDocument (); using (Stream cs = Assembly.GetExecutingAssembly().GetManifestResourceStream("NAnt.Core.Tests.Framework.config")) { configDoc.Load (cs); } Project project = CreateFilebasedProject(xml, Level.Info, configDoc.DocumentElement); FrameworkInfo tf = project.Frameworks ["testnet-1.0"]; if (!tf.IsValid) { Assert.Ignore(tf.Description + "is not available."); } Assert.IsNull(tf.SdkDirectory, "#1"); ExecuteProject(project); } } } nant-0.92-rc1/tests/NAnt.Core/Types/0000755000175000017500000000000011757310031017014 5ustar jtaylorjtaylornant-0.92-rc1/tests/NAnt.Core/Types/FileSetTest.cs0000644000175000017500000003436311757302275021562 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Gerry Shaw (gerry_shaw@yahoo.com) using System; using System.IO; using System.Xml; using NUnit.Framework; using NAnt.Core; using NAnt.Core.Types; using Tests.NAnt.Core.Util; namespace Tests.NAnt.Core { [TestFixture] public class FileSetTest : BuildTestBase { FileSet _fileSet; [SetUp] protected override void SetUp() { base.SetUp(); // create the file set _fileSet = new FileSet(); _fileSet.BaseDirectory = TempDirectory; // create some test files to match against TempFile.CreateWithContents( @"world.peace world.war reefer.maddness", Path.Combine(TempDirName, "include.list") ); TempFile.Create(Path.Combine(TempDirName, "world.peace")); TempFile.Create(Path.Combine(TempDirName, "world.war")); TempFile.Create(Path.Combine(TempDirName, "reefer.maddness")); TempFile.Create(Path.Combine(TempDirName, "reefer.saddness")); string sub1Path = Path.Combine(TempDirName, "sub1"); Directory.CreateDirectory(sub1Path); TempFile.Create(Path.Combine(sub1Path, "sub.one")); string sub2Path = Path.Combine(TempDirName, "sub2"); Directory.CreateDirectory(sub2Path); } [Test] public void CaseSensitive () { FileSet fileSet = new FileSet (); Assert.AreEqual (PlatformHelper.IsUnix, fileSet.CaseSensitive, "#1"); fileSet.CaseSensitive = true; Assert.IsTrue (fileSet.CaseSensitive, "#2"); fileSet.CaseSensitive = false; Assert.IsFalse (fileSet.CaseSensitive, "#3"); } [Test] public void Test_AsIs() { _fileSet.AsIs.Add("foo"); _fileSet.AsIs.Add("bar"); AssertMatch("foo", false); AssertMatch("bar", false); Assert.AreEqual(2, _fileSet.FileNames.Count); } [Test] public void Test_IncludesAndAsIs() { _fileSet.Includes.Add("foo"); _fileSet.AsIs.Add("foo"); _fileSet.AsIs.Add("bar"); AssertMatch("foo", false); AssertMatch("bar", false); Assert.AreEqual(2, _fileSet.FileNames.Count); } [Test] public void Test_Includes_All() { _fileSet.Includes.Add("**/*"); AssertMatch("sub1" + Path.DirectorySeparatorChar + "sub.one"); AssertMatch("world.peace"); AssertMatch("world.war"); AssertMatch("reefer.maddness"); AssertMatch("reefer.saddness"); // Expect 6 - not including directory Assert.AreEqual(6, _fileSet.FileNames.Count); // Two directories, including one empty one Assert.AreEqual(2, _fileSet.DirectoryNames.Count); } [Test] public void Test_Includes_All_Excludes_Some() { _fileSet.Includes.Add("**/*"); _fileSet.Excludes.Add("**/*reefer*"); AssertMatch("sub1" + Path.DirectorySeparatorChar + "sub.one"); AssertMatch("world.peace"); AssertMatch("world.war"); // Expect 4 - not including directory Assert.AreEqual(4, _fileSet.FileNames.Count); // Two directories, including one empty one Assert.AreEqual(2, _fileSet.DirectoryNames.Count); } [Test] public void Test_Includes_Wildcards1() { _fileSet.Includes.Add("world.*"); AssertMatch("world.peace"); AssertMatch("world.war"); Assert.AreEqual(2, _fileSet.FileNames.Count); } [Test] public void Test_Includes_Wildcards2() { _fileSet.Includes.Add("*.?addness"); AssertMatch("reefer.maddness"); AssertMatch("reefer.saddness"); Assert.AreEqual(2, _fileSet.FileNames.Count); } [Test] public void Test_Includes_Sub1() { _fileSet.Includes.Add("sub?/sub*"); AssertMatch("sub1" + Path.DirectorySeparatorChar + "sub.one"); Assert.AreEqual(1, _fileSet.FileNames.Count); } [Test] public void Test_Includes_Sub2() { _fileSet.Includes.Add("sub2/**/*"); Assert.AreEqual(0, _fileSet.FileNames.Count); } [Test] public void Test_Includes_List() { FileSet.IncludesFile elem = new FileSet.IncludesFile(); XmlDocument doc = new XmlDocument(); doc.LoadXml( "" ); elem.Project = CreateFilebasedProject("" ); elem.Initialize(doc.DocumentElement); _fileSet.IncludesFiles = new FileSet.IncludesFile[] { elem }; Assert.AreEqual(3, _fileSet.FileNames.Count); } [Test] public void Test_Includes_File() { FileSet.IncludesFile elem = new FileSet.IncludesFile(); XmlDocument doc = new XmlDocument(); doc.LoadXml( "" ); elem.Project = CreateFilebasedProject("" ); elem.Initialize(doc.DocumentElement); _fileSet.IncludesFiles = new FileSet.IncludesFile[] { elem }; Assert.AreEqual(3, _fileSet.FileNames.Count); } [Test] public void Test_NewestFile() { string file1 = this.CreateTempFile("testfile1.txt", "hellow"); string file2 = this.CreateTempFile("testfile2.txt", "hellow"); string file3 = this.CreateTempFile("testfile3.txt", "hellow"); string file4 = this.CreateTempFile("testfile4.txt", "hellow"); //file1 was created first, but we will set the time in the future. FileInfo f1 = new FileInfo(file1); f1.LastWriteTime = DateTime.Now.AddDays(2); FileSet fs = new FileSet(); fs.Includes.Add(file1); fs.Includes.Add(file2); fs.Includes.Add(file3); fs.Includes.Add(file4); FileInfo newestfile = fs.MostRecentLastWriteTimeFile; Assert.IsTrue(f1.FullName == newestfile.FullName, "Most Recent File should be '{0}', but was '{1}'", f1.Name, newestfile.Name); } [Test] [ExpectedException(typeof(TestBuildException))] public void Test_IncludesFile_NotExists() { const string buildXML = @" "; RunBuild(buildXML); } [Test] public void Test_IncludesFile_NotExists_Conditional() { const string buildXML = @" "; RunBuild(buildXML); } [Test] [ExpectedException(typeof(TestBuildException))] public void Test_ExcludesFile_NotExists() { const string buildXML = @" "; RunBuild(buildXML); } [Test] public void Test_ExcludesFile_NotExists_Conditional() { const string buildXML = @" "; RunBuild(buildXML); } [Test] public void Matching_CaseInsensitive () { _fileSet.CaseSensitive = false; _fileSet.Includes.Add ("WoRLD.*"); _fileSet.Includes.Add ("Sub*/*.OnE"); Assert.AreEqual(3, _fileSet.FileNames.Count, "#1"); _fileSet.Excludes.Add ("WoRLD.peacE"); _fileSet.Scan (); Assert.AreEqual(2, _fileSet.FileNames.Count, "#2"); _fileSet.Excludes.Add ("SuB*/**"); _fileSet.Scan (); Assert.AreEqual(1, _fileSet.FileNames.Count, "#3"); } [Test] public void Matching_CaseSensitive () { _fileSet.CaseSensitive = true; _fileSet.Includes.Add ("WoRLD.*"); _fileSet.Includes.Add ("Sub*/*.OnE"); Assert.AreEqual(0, _fileSet.FileNames.Count, "#1"); _fileSet.Includes.Add ("world.*"); _fileSet.Includes.Add ("sub1/*.one"); _fileSet.Scan (); Assert.AreEqual(3, _fileSet.FileNames.Count, "#2"); _fileSet.Excludes.Add ("WoRLD.peacE"); _fileSet.Scan (); Assert.AreEqual(3, _fileSet.FileNames.Count, "#3"); _fileSet.Excludes.Add ("SuB*/**"); _fileSet.Scan (); Assert.AreEqual(3, _fileSet.FileNames.Count, "#4"); } [Test] public void Matching_Unix () { if (!PlatformHelper.IsUnix) { return; } _fileSet.Includes.Add ("WoRLD.*"); _fileSet.Includes.Add ("Sub1/*.OnE"); Assert.AreEqual(0, _fileSet.FileNames.Count, "#1"); _fileSet.Includes.Clear (); _fileSet.Includes.Add ("world.*"); _fileSet.Includes.Add ("sub1/*.one"); _fileSet.Scan (); Assert.AreEqual(3, _fileSet.FileNames.Count, "#2"); _fileSet.Excludes.Add ("WoRLD.peacE"); _fileSet.Scan (); Assert.AreEqual(3, _fileSet.FileNames.Count, "#3"); _fileSet.Excludes.Add ("SuB1/**"); _fileSet.Scan (); Assert.AreEqual(3, _fileSet.FileNames.Count, "#4"); TempFile.Create(Path.Combine(TempDirName, "world.peacE")); _fileSet.Includes.Clear (); _fileSet.Includes.Add ("world.*"); _fileSet.Excludes.Clear (); _fileSet.Scan (); Assert.AreEqual (3, _fileSet.FileNames.Count, "#5"); _fileSet.Includes.Clear (); _fileSet.Includes.Add ("su*/**"); _fileSet.Scan (); Assert.AreEqual (1, _fileSet.FileNames.Count, "#6"); string sub1Path = Path.Combine(TempDirName, "suB1"); Directory.CreateDirectory(sub1Path); TempFile.Create(Path.Combine(sub1Path, "sub.one")); _fileSet.Scan (); Assert.AreEqual (2, _fileSet.FileNames.Count, "#7"); _fileSet.CaseSensitive = false; _fileSet.Includes.Clear (); _fileSet.Includes.Add ("SuB1/*.one"); _fileSet.Excludes.Clear (); Assert.AreEqual(0, _fileSet.FileNames.Count, "#8"); } [Test] public void Matching_Windows () { if (PlatformHelper.IsUnix) { return; } _fileSet.Includes.Add ("WoRLD.*"); _fileSet.Includes.Add ("Sub1/*.OnE"); Assert.AreEqual(3, _fileSet.FileNames.Count, "#1"); _fileSet.Includes.Clear (); _fileSet.Includes.Add ("world.*"); _fileSet.Includes.Add ("sub1/*.one"); _fileSet.Scan (); Assert.AreEqual(3, _fileSet.FileNames.Count, "#2"); _fileSet.Excludes.Add ("WoRLD.peacE"); _fileSet.Scan (); Assert.AreEqual(2, _fileSet.FileNames.Count, "#3"); _fileSet.Excludes.Add ("SuB1/**"); _fileSet.Scan (); Assert.AreEqual(1, _fileSet.FileNames.Count, "#4"); _fileSet.CaseSensitive = true; _fileSet.Includes.Clear (); _fileSet.Includes.Add ("SuB1/*.one"); _fileSet.Excludes.Clear (); Assert.AreEqual(1, _fileSet.FileNames.Count, "#5"); } [Test] public void Bug1776101 () { if (PlatformHelper.IsUnix) { Assert.Ignore ("Only valid on non-Unix platform"); } const string buildXML = @" #1 "; RunBuild(buildXML); } void AssertMatch(string fileName) { AssertMatch(fileName, true); } void AssertMatch(string fileName, bool prefixBaseDir) { if (prefixBaseDir && !Path.IsPathRooted(fileName)) { fileName = Path.Combine(_fileSet.BaseDirectory.FullName, fileName); } Assert.IsTrue(_fileSet.FileNames.IndexOf(fileName) != -1, fileName + " should have been in file set."); } } } nant-0.92-rc1/tests/NAnt.Core/Resources/0000755000175000017500000000000011757310030017661 5ustar jtaylorjtaylornant-0.92-rc1/tests/NAnt.Core/Resources/Build.Files/0000775000175000017500000000000011760131347021771 5ustar jtaylorjtaylornant-0.92-rc1/tests/NAnt.Core/Resources/Build.Files/Invalid/0000755000175000017500000000000011757310030023347 5ustar jtaylorjtaylornant-0.92-rc1/tests/NAnt.Core/Resources/Build.Files/Invalid/mixedroot.xml0000644000175000017500000000017411757302275026121 0ustar jtaylorjtaylor I am text, is that okay? nant-0.92-rc1/tests/NAnt.Core/Resources/Build.Files/Invalid/If-NoCondition.xml0000644000175000017500000000011511757302275026661 0ustar jtaylorjtaylor nant-0.92-rc1/tests/NAnt.Core/Resources/Build.Files/Invalid/MismatchedNS.xml0000644000175000017500000000033111757302275026421 0ustar jtaylorjtaylor nant-0.92-rc1/tests/NAnt.Core/Resources/Build.Files/Invalid/BadRoot.xml0000644000175000017500000000007111757302275025435 0ustar jtaylorjtaylor nant-0.92-rc1/tests/NAnt.Core/Resources/Build.Files/Valid/0000755000175000017500000000000011757310030023020 5ustar jtaylorjtaylornant-0.92-rc1/tests/NAnt.Core/Resources/Build.Files/Valid/DocType.xml0000644000175000017500000000175511757302275025135 0ustar jtaylorjtaylor ]> nant-0.92-rc1/tests/NAnt.Core/Resources/Build.Files/Valid/Namespaces2.xml0000644000175000017500000000016211757302275025716 0ustar jtaylorjtaylor nant-0.92-rc1/tests/NAnt.Core/Resources/Build.Files/Valid/Comments.xml0000644000175000017500000000024011757302275025337 0ustar jtaylorjtaylor nant-0.92-rc1/tests/NAnt.Core/Resources/Build.Files/Valid/CommentsWithNS.xml0000644000175000017500000000034411757302275026441 0ustar jtaylorjtaylor nant-0.92-rc1/tests/NAnt.Core/Resources/Build.Files/Valid/NamespacePrefix2.xml0000644000175000017500000000017511757302275026715 0ustar jtaylorjtaylor message nant-0.92-rc1/tests/NAnt.Core/Resources/Build.Files/Valid/NamespacePrefix1.xml0000644000175000017500000000015311757302275026710 0ustar jtaylorjtaylor message nant-0.92-rc1/tests/NAnt.Core/Resources/Build.Files/Valid/Namespaces.xml0000644000175000017500000000034711757302275025641 0ustar jtaylorjtaylor nant-0.92-rc1/tests/NAnt.Core/Resources/readme.txt0000644000175000017500000000026711757302275021700 0ustar jtaylorjtaylorAll the files in these subdirs will be loaded and tested. Each file in Valid is expected to pass the test with success, while the Invalid files are expected to fail with an error.nant-0.92-rc1/tests/NAnt.Core/TargetTest.cs0000644000175000017500000002420611757302275020344 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Globalization; using NUnit.Framework; using NAnt.Core; namespace Tests.NAnt.Core { [TestFixture] public class TargetTest : BuildTestBase { #region Private Static Fields private const string BuildFragment = @" "; private const string BuildFragment1 = @" "; private const string BuildFragment2 = @" "; #endregion Private Static Fields #region Public Instance Methods [Test] public void Test_Normal() { // create new listener that allows us to track build events TestBuildListener listener = new TestBuildListener(); // run the build string result = RunBuild(FormatBuildFile("Target1", "false", "true", string.Empty), listener); Assert.AreEqual(1, listener.GetTargetExecutionCount("Target1"), "Target1 should have executed once." + Environment.NewLine + result); Assert.AreEqual(0, listener.GetTargetExecutionCount("Target2"), "Target2 should not have executed." + Environment.NewLine + result); Assert.AreEqual(0, listener.GetTargetExecutionCount("Target3"), "Target3 should not have executed." + Environment.NewLine + result); } [Test] public void Test_If() { // create new listener that allows us to track build events TestBuildListener listener = new TestBuildListener(); // run the build string result = RunBuild(FormatBuildFile("Target1", "true", "true", string.Empty), listener); Assert.AreEqual(1, listener.GetTargetExecutionCount("Target1"), "Target1 should have executed once." + Environment.NewLine + result); Assert.AreEqual(1, listener.GetTargetExecutionCount("Target2"), "Target2 should have executed once." + Environment.NewLine + result); Assert.AreEqual(0, listener.GetTargetExecutionCount("Target3"), "Target3 should not have executed." + Environment.NewLine + result); } [Test] public void Test_Unless() { // create new listener that allows us to track build events TestBuildListener listener = new TestBuildListener(); // run the build string result = RunBuild(FormatBuildFile("Target1", "false", "false", string.Empty), listener); Assert.AreEqual(1, listener.GetTargetExecutionCount("Target1"), "Target1 should have executed once." + Environment.NewLine + result); Assert.AreEqual(0, listener.GetTargetExecutionCount("Target2"), "Target2 should not have executed." + Environment.NewLine + result); Assert.AreEqual(1, listener.GetTargetExecutionCount("Target3"), "Target3 should have executed once." + Environment.NewLine + result); } [Test] public void Test_Depends() { // create new listener that allows us to track build events TestBuildListener listener = new TestBuildListener(); // run the build string result = RunBuild(FormatBuildFile("Target1", "true", "false", "Target2"), listener); Assert.AreEqual(1, listener.GetTargetExecutionCount("Target1"), "Target1 should have executed once." + Environment.NewLine + result); Assert.AreEqual(1, listener.GetTargetExecutionCount("Target2"), "Target2 should have executed once." + Environment.NewLine + result); Assert.AreEqual(1, listener.GetTargetExecutionCount("Target3"), "Target3 should have executed once." + Environment.NewLine + result); } [Test] public void Test_Depends2() { // create new listener that allows us to track build events TestBuildListener listener = new TestBuildListener(); // run the build string result = RunBuild(FormatBuildFile("Target1", "true", "false", string.Empty), listener); Assert.AreEqual(1, listener.GetTargetExecutionCount("Target1"), "Target1 should have executed once." + Environment.NewLine + result); Assert.AreEqual(1, listener.GetTargetExecutionCount("Target2"), "Target2 should have executed once." + Environment.NewLine + result); Assert.AreEqual(1, listener.GetTargetExecutionCount("Target3"), "Target3 should have executed once." + Environment.NewLine + result); } /// /// Ensures dependencies of a target are executed before the condition /// is checked. Meaning, dependencies are executed even if the target /// itself should not be executed (because of condition that is not met). /// [Test] public void Test_Depends3() { // create new listener that allows us to track build events TestBuildListener listener = new TestBuildListener(); // run the build string result = RunBuild(FormatBuildFile("Target3", "true", "true", "Target2"), listener); Assert.AreEqual(0, listener.GetTargetExecutionCount("Target1"), "Target1 should not have executed." + Environment.NewLine + result); Assert.AreEqual(1, listener.GetTargetExecutionCount("Target2"), "Target2 should have executed once." + Environment.NewLine + result); Assert.AreEqual(0, listener.GetTargetExecutionCount("Target3"), "Target3 should not have executed." + Environment.NewLine + result); } [Test] public void Test_Wild() { // create new listener that allows us to track build events TestBuildListener listener = new TestBuildListener(); Project project = CreateFilebasedProject(BuildFragment1); //use Project.AttachBuildListeners to attach. IBuildListener[] listners = {listener}; project.AttachBuildListeners(new BuildListenerCollection(listners)); //add targets like they are added from the command line. project.BuildTargets.Add("WildTarget"); string result = ExecuteProject(project); Assert.AreEqual(1, listener.GetTargetExecutionCount("WildTarget"), "WildTarget should have executed once." + Environment.NewLine + result); Assert.AreEqual(0, listener.GetTargetExecutionCount("Target"), "Target should not have executed." + Environment.NewLine + result); } [Test] public void Test_CommandLineTargets() { // create new listener that allows us to track build events TestBuildListener listener = new TestBuildListener(); Project project = CreateFilebasedProject(BuildFragment2); //use Project.AttachBuildListeners to attach. IBuildListener[] listners = {listener}; project.AttachBuildListeners(new BuildListenerCollection(listners)); //add targets like they are added from the command line. project.BuildTargets.Add("Release"); project.BuildTargets.Add("Build"); string result = ExecuteProject(project); Assert.AreEqual(1, listener.GetTargetExecutionCount("Init"), "'Init' target should have executed once." + Environment.NewLine + result); Assert.AreEqual(1, listener.GetTargetExecutionCount("Release"), "'Release' target should have executed once." + Environment.NewLine + result); Assert.AreEqual(1, listener.GetTargetExecutionCount("Build"), "'Build' target should have executed once." + Environment.NewLine + result); } [Test] [ExpectedException(typeof(TestBuildException))] public void Test_CircularDependency() { // run the build with Target1 dependent on Target3 and vice versa RunBuild(FormatBuildFile("Target1", "true", "false", "Target1")); } [Test] [ExpectedException(typeof(TestBuildException))] public void Test_UnknowDependentTarget() { // run the build with an unknown dependent target RunBuild(FormatBuildFile("Target1", "true", "false", "Unknown")); } [Test] [ExpectedException(typeof(TestBuildException))] public void Test_UnknowDefaultTarget() { // run the build with an unknown default target RunBuild(FormatBuildFile("Unknown", "true", "false", string.Empty)); } #endregion Public Instance Methods #region Private Instance Methods private string FormatBuildFile(string defaultTarget, string a, string b, string target3Depends) { return string.Format(CultureInfo.InvariantCulture, BuildFragment, defaultTarget, a, b, target3Depends); } #endregion Private Instance Methods } } nant-0.92-rc1/tests/NAnt.Core/ExpressionTokenizerTest.cs0000644000175000017500000000471011757302275023146 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Jaroslaw Kowalski (jkowalski@users.sourceforge.net) using System; using NAnt.Core; using NUnit.Framework; namespace Tests.NAnt.Core { [TestFixture] public class ExpressionTokenizerTest { [Test] public void Keyword() { string [] identifiers = new string[] { "a.d", "a-d", "a.d", "a\\d", "a_d", "_ad", "ad5" }; for (int i = 0; i < identifiers.Length; i++) { string identifier = identifiers[i]; ExpressionTokenizer et = new ExpressionTokenizer(); et.InitTokenizer(identifier); Assert.AreEqual (identifier, et.TokenText, "#A1"); Assert.AreEqual (ExpressionTokenizer.TokenType.Keyword, et.CurrentToken, "#A2:" + identifier); et.GetNextToken(); Assert.AreEqual (identifier, et.TokenText, "#B1"); Assert.AreEqual (ExpressionTokenizer.TokenType.EOF, et.CurrentToken, "#B2:" + identifier); } } [Test] public void Keyword_ShouldNotEndWithDash() { ExpressionTokenizer et = new ExpressionTokenizer(); try { et.InitTokenizer("abc-"); Assert.Fail(); } catch (ExpressionParseException) { } } [Test] public void Keyword_ShouldNotEndWithDot() { ExpressionTokenizer et = new ExpressionTokenizer(); try { et.InitTokenizer("abc."); Assert.Fail(); } catch (ExpressionParseException) { } } } } nant-0.92-rc1/tests/NAnt.Core/Util/0000755000175000017500000000000011757310031016625 5ustar jtaylorjtaylornant-0.92-rc1/tests/NAnt.Core/Util/ConsoleWriter.cs0000644000175000017500000000355511757302275021776 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2007 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.IO; using System.Text; namespace Tests.NAnt.Core.Util { /// /// Specialized that uses the encoding the /// console uses to write output. /// public class ConsoleWriter : StreamWriter { /// /// Initializes a new instance of the /// that uses a as underlying stream and /// the encoding that the console uses to write output. /// public ConsoleWriter() : base (new MemoryStream (), ConsoleEncoding) { } public override string ToString() { Flush (); BaseStream.Position = 0; StreamReader sr = new StreamReader (BaseStream, Encoding); return sr.ReadToEnd (); } static Encoding ConsoleEncoding { get { #if NET_2_0 return System.Console.OutputEncoding; #else return Encoding.Default; #endif } } } } nant-0.92-rc1/tests/NAnt.Core/Util/TempDir.cs0000644000175000017500000000756111757302275020544 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Scott Hernandez (ScottHernandez@hotmail.com) using System; using System.IO; using NUnit.Framework; namespace Tests.NAnt.Core.Util { public sealed class TempDir { /// Creates a temporary directory for a unit test. /// /// If the directory already exists it will first be deleted and a new empty directory will be created. /// The complete path to the created directory. public static string Create(string name) { string path = Path.Combine(Path.GetTempPath(), name); if(Path.IsPathRooted(name)) path = name; // delete any existing directory from previously failed test Delete(path); // create the new empty directory Directory.CreateDirectory(path); if (!Directory.Exists(path)) { throw new AssertionException("TempDir: " + path + " does not exists."); } return path; } /// Delete the directory at the given path and everything in it. public static void Delete(string path) { bool bError = false; try { if (Directory.Exists(path)) { // ensure directorty is writable File.SetAttributes(path, FileAttributes.Normal); // ensure all files and subdirectories are writable SetAllFileAttributesToNormal(path); string[] directoryNames = Directory.GetDirectories(path); foreach (string directoryName in directoryNames) { Delete(directoryName); } string[] fileNames = Directory.GetFiles(path); foreach (string fileName in fileNames) { File.Delete(fileName); } Directory.Delete(path, true); } } catch(Exception ex) { bError = true; throw new AssertionException("Unable to cleanup '" + path + "'. " + ex.Message, ex); } finally { if (!bError && Directory.Exists(path)) { throw new AssertionException("TempDir: "+ path + " still exists."); } } } /// /// Recurse over all files in the directory setting each file's attributes /// to . /// private static void SetAllFileAttributesToNormal(string path) { string[] fileNames = Directory.GetFiles(path); foreach (string fileName in fileNames) { File.SetAttributes(fileName, FileAttributes.Normal); } string[] directoryNames = Directory.GetDirectories(path); foreach (string directoryName in directoryNames) { File.SetAttributes(directoryName, FileAttributes.Normal); SetAllFileAttributesToNormal(directoryName); } } } } nant-0.92-rc1/tests/NAnt.Core/Util/TempDirTest.cs0000644000175000017500000000252511757302275021377 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Gerry Shaw (gerry_shaw@yahoo.com) using System; using System.IO; using NUnit.Framework; namespace Tests.NAnt.Core.Util { [TestFixture] public class TempDirTest { [Test] public void Test_CreateAndDestroy() { string path = TempDir.Create("foobar"); Assert.IsTrue(Directory.Exists(path), path + " does not exists."); Assert.IsTrue(path.EndsWith("foobar"), path + " does not end with 'foobar'."); TempDir.Delete(path); Assert.IsFalse(Directory.Exists(path), path + " exists."); } } } nant-0.92-rc1/tests/NAnt.Core/Util/StopWatchStackTest.cs0000644000175000017500000000515011757302275022732 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2005 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Owen Rogers (exortech@gmail.com) using System; using NUnit.Framework; using NAnt.Core.Util; namespace Tests.NAnt.Core.Util { [TestFixture] public class StopWatchStackTest { private StopWatchStack stack; private MockDateTimeProvider mockDateTimeProvider; private DateTime startTime; [SetUp] protected void CreateStopWatchStackAndSetUpMocks() { startTime = new DateTime(2004, 12, 1, 12, 0, 0); mockDateTimeProvider = new MockDateTimeProvider(); stack = new StopWatchStack(mockDateTimeProvider); } [Test] public void ShouldPushAndPopSingleStopWatch() { mockDateTimeProvider.SetExpectedNow(startTime); // start stop watch mockDateTimeProvider.SetExpectedNow(startTime.AddMilliseconds(2)); // stop stop watch stack.PushStart(); TimeSpan elapsed = stack.PopStop(); Assert.IsNotNull(elapsed); Assert.AreEqual(2, elapsed.Milliseconds, "two milliseconds should have elapsed"); } [Test] public void ShouldPushAndPopMultipleStopWatches() { mockDateTimeProvider.SetExpectedNow(startTime); // start first stop watch mockDateTimeProvider.SetExpectedNow(startTime.AddMilliseconds(2)); // start second stop watch mockDateTimeProvider.SetExpectedNow(startTime.AddMilliseconds(4)); // stop second stop watch mockDateTimeProvider.SetExpectedNow(startTime.AddMilliseconds(4)); // stop first stop watch stack.PushStart(); stack.PushStart(); Assert.AreEqual(2, stack.PopStop().Milliseconds, "two milliseconds should have elapsed for the second stopwatch"); Assert.AreEqual(4, stack.PopStop().Milliseconds, "four milliseconds should have elapsed for the first stopwatch"); } } }nant-0.92-rc1/tests/NAnt.Core/Util/MockDateTimeProvider.cs0000644000175000017500000000235311757302275023213 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2005 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Owen Rogers (exortech@gmail.com) using System; using System.Collections; using NAnt.Core.Util; namespace Tests.NAnt.Core.Util { internal class MockDateTimeProvider : DateTimeProvider { private Queue _expectations = new Queue(); public override DateTime Now { get { return (DateTime) _expectations.Dequeue(); } } public void SetExpectedNow(DateTime value) { _expectations.Enqueue(value); } } } nant-0.92-rc1/tests/NAnt.Core/Util/TempFileTest.cs0000644000175000017500000000450411757302275021537 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Gerry Shaw (gerry_shaw@yahoo.com) using System; using System.Globalization; using System.IO; using NUnit.Framework; namespace Tests.NAnt.Core.Util { [TestFixture] public class TempFileTest { [Test] public void Test_Create() { string fileName = TempFile.Create(); Assert.IsTrue(File.Exists(fileName), fileName + " does not exists."); try { TimeSpan diff = DateTime.Now - File.GetCreationTime(fileName); Assert.IsTrue(diff.TotalSeconds < 10.0, "Creation time should be less than 10 seconds ago."); } finally { File.Delete(fileName); Assert.IsFalse(File.Exists(fileName), fileName + " exists."); } } [Test] public void Test_Create_NullArgument() { try { TempFile.Create(null); Assert.Fail("Exception not thrown."); } catch { } } [Test] public void Test_Create_WithContents() { string expected = string.Format(CultureInfo.InvariantCulture, "Line 1{0}Line Two{0}{0}Line Three", Environment.NewLine); string fileName = TempFile.CreateWithContents(expected); try { string actual = TempFile.Read(fileName); Assert.AreEqual(expected, actual); } finally { // delete the temp file File.Delete(fileName); Assert.IsFalse(File.Exists(fileName), fileName + " exists."); } } } } nant-0.92-rc1/tests/NAnt.Core/Util/ConsoleCapture.cs0000644000175000017500000000703011757302275022115 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) using System; using System.IO; using System.Text; namespace Tests.NAnt.Core.Util { /// /// Captures console output to a string. /// /// /// Used to capture the output so that it can be tested. /// /// /// /// using (ConsoleCapture c = new ConsoleCapture()) { /// Console.WriteLine("Hello World"); /// string result = c.Close(); /// Console.WriteLine("cached results: '{0}'", result); /// } /// /// public sealed class ConsoleCapture : IDisposable { #region Public Instance Constructors /// /// Initializes a new instance of the /// class. /// public ConsoleCapture() { _oldWriter = System.Console.Out; _oldErrorWriter = System.Console.Error; _writer = new ConsoleWriter(); System.Console.SetOut(_writer); System.Console.SetError(_writer); } #endregion Public Instance Constructors #region Finalizer ~ConsoleCapture() { Dispose(); } #endregion Finalizer #region Implementation of IDisposable public void Dispose() { if (!_disposed) { Close (); _writer.Close (); } _disposed = true; GC.SuppressFinalize(this); } #endregion Implementation of IDisposable #region Override implementation of Object /// /// Returns the contents of the capture buffer. Can be called after /// is called. /// public override string ToString() { return _writer.ToString(); } #endregion Override implementation of Object #region Public Instance Methods /// /// Restores console output and returns the contents of the captured /// buffer. /// public string Close() { if (_disposed) { throw new ObjectDisposedException("ConsoleCapture", "Capture has already been closed/disposed."); } _writer.Flush(); System.Console.SetOut(_oldWriter); System.Console.SetError(_oldErrorWriter); return ToString(); } #endregion Public Instance Methods #region Private Instance Fields private bool _disposed; private ConsoleWriter _writer; private TextWriter _oldWriter; private TextWriter _oldErrorWriter; #endregion Private Instance Fields } } nant-0.92-rc1/tests/NAnt.Core/Util/FileUtilsTest.cs0000644000175000017500000002071411757302275021733 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2005 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.IO; using System.Text; using NUnit.Framework; using NAnt.Core; using NAnt.Core.Util; namespace Tests.NAnt.Core.Util { [TestFixture] public class FileUtilsTest { [Test] [ExpectedException(typeof(ArgumentNullException))] public void Test_GetFullPath_Null() { FileUtils.GetFullPath(null); } [Test] [ExpectedException(typeof(ArgumentException))] public void Test_GetFullPath_Empty() { FileUtils.GetFullPath(string.Empty); } [Test] [ExpectedException(typeof(ArgumentException))] public void Test_GetFullPath_Whitespace() { FileUtils.GetFullPath(" "); } [Test] public void Test_GetFullPath() { if (!PlatformHelper.IsWin32) { return; } Assert.IsTrue(FileUtils.GetFullPath("Z:").StartsWith(@"Z:\"), "#1"); Assert.AreEqual(@"c:\abc\def", FileUtils.GetFullPath (@"c:\abc\def"), "#2"); Assert.IsTrue(FileUtils.GetFullPath(@"\").EndsWith(@"\"), "#3"); Assert.IsTrue(FileUtils.GetFullPath("/").EndsWith (@"\"), "#4"); Assert.IsTrue(FileUtils.GetFullPath("readme.txt").EndsWith(@"\readme.txt"), "#5"); Assert.IsTrue(FileUtils.GetFullPath("c").EndsWith(@"\c"), "#5"); Assert.IsTrue(FileUtils.GetFullPath(@"abc\def").EndsWith(@"abc\def"), "#6"); Assert.IsTrue(FileUtils.GetFullPath(@"\abc\def").EndsWith(@"\abc\def"), "#7"); Assert.AreEqual(@"\\abc\def", FileUtils.GetFullPath (@"\\abc\def"), "#8"); Assert.AreEqual(Directory.GetCurrentDirectory() + @"\abc\def", FileUtils.GetFullPath(@"abc//def"), "#9"); Assert.AreEqual(Directory.GetCurrentDirectory().Substring(0,2) + @"\abc\def", FileUtils.GetFullPath("/abc/def"), "#10"); Assert.AreEqual(@"\\abc\def", FileUtils.GetFullPath("//abc/def"), "#11"); StringBuilder sb = new StringBuilder(); while (sb.Length < 260) { sb.Append(@"test\..\"); } sb.Append("what.txt"); Assert.AreEqual(Path.Combine(Directory.GetCurrentDirectory(), "what.txt"), FileUtils.GetFullPath(sb.ToString()), "#12"); // clear buffer sb.Length = 0; string[] currentDirParts = Directory.GetCurrentDirectory().Split(Path.DirectorySeparatorChar); for (int i = 0; i < (currentDirParts.Length - 1); i++) { sb.Append(@"..\"); } sb.Append(@"test\what.txt"); Assert.AreEqual(Path.Combine(currentDirParts[0] + Path.DirectorySeparatorChar, @"test\what.txt"), FileUtils.GetFullPath(sb.ToString()), "#13"); // filter out single dot parts Assert.AreEqual(Directory.GetCurrentDirectory() + @"\abc\def", FileUtils.GetFullPath(@"abc/./def"), "#14"); Assert.AreEqual(Directory.GetCurrentDirectory() + @"\abc\def", FileUtils.GetFullPath(@"abc\.\def"), "#15"); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void Test_CombinePaths_Path1_Null() { FileUtils.CombinePaths((string) null, "whatever"); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void Test_CombinePaths_Path2_Null() { FileUtils.CombinePaths("whatever", (string) null); } [Test] public void Test_CombinePaths() { if (!PlatformHelper.IsWin32) { return; } Assert.AreEqual(@"c:\test\whatever\test.txt", FileUtils.CombinePaths(@"c:\test", @"whatever\test.txt"), "#1"); Assert.AreEqual(@"c:\test\whatever\test.txt", FileUtils.CombinePaths(@"c:\test", "whatever/test.txt"), "#2"); Assert.AreEqual(@"c:\test\whatever\test.txt", FileUtils.CombinePaths(@"c:\test\whatever", @"..\whatever\test.txt"), "#3"); Assert.AreEqual(@"c:\test\whatever\test.txt", FileUtils.CombinePaths(@"c:\test\whatever", "../whatever/test.txt"), "#4"); Assert.AreEqual(@"\\test\c$\whatever.txt", FileUtils.CombinePaths(@"\\test\c$", @"test\..\whatever.txt"), "#5"); Assert.AreEqual(@"\\test\c$\whatever.txt", FileUtils.CombinePaths(@"\\test\c$", "test/../whatever.txt"), "#6"); Assert.AreEqual(@"c:\test\whatever\obj", FileUtils.CombinePaths(@"c:\test", @"whatever\obj"), "#7"); Assert.AreEqual(@"c:\test\whatever\obj", FileUtils.CombinePaths(@"c:\test", @"whatever/obj"), "#8"); // retain trailing separator character Assert.AreEqual(@"c:\test\whatever\obj\", FileUtils.CombinePaths(@"c:\test", @"whatever\obj\"), "#7"); Assert.AreEqual(@"c:\test\whatever\obj\", FileUtils.CombinePaths(@"c:\test", @"whatever\obj/"), "#8"); // ignore duplicate directory separators Assert.AreEqual(@"c:\test\whatever\obj\", FileUtils.CombinePaths(@"c:\test", @"whatever\obj\/"), "#8"); Assert.AreEqual(@"c:\test\whatever\obj", FileUtils.CombinePaths(@"c:\test", @"whatever\/obj"), "#8"); Assert.AreEqual(@"c:\test\whatever\obj\", FileUtils.CombinePaths(@"c:\test", @"whatever\\obj\\"), "#9"); Assert.AreEqual(@"c:\test\whatever\obj\", FileUtils.CombinePaths(@"c:\test", @"whatever\\\obj\\\"), "#9"); Assert.AreEqual(@"c:\test\whatever\obj\", FileUtils.CombinePaths(@"c:\test", @"whatever//obj//"), "#10"); Assert.AreEqual(@"c:\test\whatever\obj\", FileUtils.CombinePaths(@"c:\test", @"whatever///obj///"), "#10"); // if second path is rooted, it should be returned as is Assert.AreEqual(@"c:\whatever\..\test", FileUtils.CombinePaths(@"c:\test", @"c:\whatever\..\test"), "#11"); Assert.AreEqual(@"c:\whatever\..\test\\", FileUtils.CombinePaths(@"c:\test", @"c:\whatever\..\test\\"), "#12"); Assert.AreEqual(@"\\server\c$\test.txt", FileUtils.CombinePaths(@"c:\test", @"\\server\c$\test.txt"), "#13"); // skip single dot parts Assert.AreEqual(@"c:\test\whatever\test.txt", FileUtils.CombinePaths(@"c:\test", @"whatever\.\test.txt"), "#14"); Assert.AreEqual(@"c:\test\whatever\test.txt", FileUtils.CombinePaths(@"c:\test", @"whatever/./test.txt"), "#15"); // trailing path seperators Assert.AreEqual(@"c:\test\whatever\test.txt", FileUtils.CombinePaths(@"c:\test\whatever\", @"..\whatever\test.txt"), "#16"); Assert.AreEqual(@"c:\whatever\test.txt", FileUtils.CombinePaths(@"c:\", @"whatever\test.txt"), "#17"); Assert.AreEqual(@"c:\..\whatever\test.txt", FileUtils.CombinePaths(@"c:\", @"..\whatever\test.txt"), "#18"); // handle zero-length paths and paths containing only directoy separator char Assert.AreEqual(@"..\whatever\test.txt", FileUtils.CombinePaths(@"", @"..\whatever\test.txt"), "#19"); Assert.AreEqual(@"\..\whatever\test.txt", FileUtils.CombinePaths(@"", @"\..\whatever\test.txt"), "#20"); Assert.AreEqual(@"c:\test\whatever", FileUtils.CombinePaths(@"c:\test\whatever", @""), "#21"); Assert.AreEqual(@"\", FileUtils.CombinePaths(@"c:\test\whatever", @"\"), "#22"); Assert.AreEqual(@"\..\whatever\test.txt", FileUtils.CombinePaths(@"\", @"..\whatever\test.txt"), "#23"); Assert.AreEqual(@"\..\whatever\test.txt", FileUtils.CombinePaths(@"\", @"\..\whatever\test.txt"), "#24"); Assert.AreEqual(@"c:\whatever\test.txt", FileUtils.CombinePaths(@"c:\test", @"..\whatever\test.txt"), "#25"); Assert.AreEqual(@"c:\whatever\test.txt", FileUtils.CombinePaths(@"c:\test\", "../whatever/test.txt"), "#26"); } } } nant-0.92-rc1/tests/NAnt.Core/Util/TempFile.cs0000644000175000017500000000460111757302275020675 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) using System; using System.IO; using NUnit.Framework; namespace Tests.NAnt.Core.Util { public sealed class TempFile { /// Creates a small temp file returns the file name. public static string Create() { return Create(Path.GetTempFileName()); } public static string Create(string fileName) { string contents = "You can delete this file." + Environment.NewLine; return CreateWithContents(contents, fileName); } public static string CreateWithContents(string contents) { return CreateWithContents(contents, Path.GetTempFileName()); } public static string CreateWithContents(string contents, string fileName) { // ensure the directory exists Directory.CreateDirectory(Path.GetDirectoryName(fileName)); // write the text into the temp file. using (FileStream f = new FileStream(fileName, FileMode.Create)) { StreamWriter s = new StreamWriter(f); s.Write(contents); s.Close(); f.Close(); } if (!File.Exists(fileName)) { throw new AssertionException("TempFile: " + fileName + " wasn't created."); } return fileName; } public static string Read(string fileName) { string contents; using (StreamReader s = File.OpenText(fileName)) { contents = s.ReadToEnd(); s.Close(); } return contents; } } } nant-0.92-rc1/tests/NAnt.Core/Util/XmlLoggerTest.cs0000644000175000017500000003223311757302275021732 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // William E. Caputo (wecaputo@thoughtworks.com | logosity@yahoo.com) // Owen Rogers (orogers@thoughtworks.com | exortech@gmail.com) using System; using System.Globalization; using System.IO; using System.Xml; using NUnit.Framework; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Util; namespace Tests.NAnt.Core.Util { [TestFixture] public class XmlLoggerTest { private XmlLogger _log; private string _tempDir; private string _format = @" {1} {2} "; [SetUp] protected void SetUp() { _log = CreateXmlLogger(); _tempDir = TempDir.Create("NAnt.Tests.XmlLoggerTest"); } [TearDown] protected void TearDown() { TempDir.Delete(_tempDir); } [Test] public void StripFormatting() { string baseMessage = "this is a typical message."; string formattedMessage = "[foo] " + baseMessage; Assert.AreEqual(baseMessage, _log.StripFormatting(formattedMessage), "#1"); formattedMessage = "\t[foo] " + baseMessage; Assert.AreEqual(baseMessage, _log.StripFormatting(formattedMessage), "#2"); formattedMessage = "\t\0[foo] " + baseMessage; Assert.AreEqual(baseMessage, _log.StripFormatting(formattedMessage), "#3"); formattedMessage = "\t\0[foo] \0" + baseMessage + '\0'; Assert.AreEqual(baseMessage, _log.StripFormatting(formattedMessage), "#4"); formattedMessage = "\t\t[foo] " + baseMessage; Assert.AreEqual(baseMessage, _log.StripFormatting(formattedMessage), "#5"); string timestamp = "Thursday, August 01, 2002 12:52:54 AM"; formattedMessage = String.Format(CultureInfo.InvariantCulture, "\t\t\t[tstamp] {0}", timestamp); Assert.AreEqual(timestamp, _log.StripFormatting(formattedMessage), "#6"); } [Test] public void StripFormattingMultiline() { string baseMessage = "this is a typical message." + Environment.NewLine + "Multiline message that is."; string formattedMessage = "[foo] " + baseMessage; Assert.AreEqual(baseMessage, _log.StripFormatting(formattedMessage)); } [Test] public void IsJustWhiteSpace() { string message = ""; Assert.IsTrue(_log.IsJustWhiteSpace(message), "check failed for: {0}", message); message = " "; Assert.IsTrue(_log.IsJustWhiteSpace(message), "check failed for: {0}", message); message = "\0"; Assert.IsTrue(_log.IsJustWhiteSpace(message), "check failed for: {0}", message); message = " "; Assert.IsTrue(_log.IsJustWhiteSpace(message), "check failed for: {0}", message); message = "\t\t\t\t"; Assert.IsTrue(_log.IsJustWhiteSpace(message), "check failed for: {0}", message); message = "hello"; Assert.IsFalse(_log.IsJustWhiteSpace(message), "check should not have failed for: {0}", message); message = "hello "; Assert.IsFalse(_log.IsJustWhiteSpace(message), "check should not have failed for: {0}", message); message = " hello"; Assert.IsFalse(_log.IsJustWhiteSpace(message), "check should not have failed for: {0}", message); message = "\t\t\thello"; Assert.IsFalse(_log.IsJustWhiteSpace(message), "check should not have failed for: {0}", message); } [Test] public void WriteLine() { string baseMessage = "this is a typical message."; string formattedMessage = "[foo] " + baseMessage; BuildEventArgs args = CreateBuildEventArgs(formattedMessage, Level.Info); _log.MessageLogged(this, args); string expected = string.Format(CultureInfo.InvariantCulture, "", baseMessage); Assert.AreEqual(expected, _log.ToString()); } [Test] public void Write() { string baseMessage = "this is a typical message."; string formattedMessage = "[foo] " + baseMessage; BuildEventArgs args = CreateBuildEventArgs(formattedMessage, Level.Info); _log.MessageLogged(this, args); string expected = string.Format(CultureInfo.InvariantCulture, "", baseMessage); Assert.AreEqual(expected, _log.ToString()); string unformattedMessage = "message:"; _log = CreateXmlLogger(); args.Message = unformattedMessage; _log.MessageLogged(this, args); expected = string.Format(CultureInfo.InvariantCulture, "", unformattedMessage); Assert.AreEqual(expected, _log.ToString()); unformattedMessage = "message with no tag in front."; _log = CreateXmlLogger(); args.Message = unformattedMessage; _log.MessageLogged(this, args); expected = string.Format(CultureInfo.InvariantCulture, "", unformattedMessage); Assert.AreEqual(expected, _log.ToString()); unformattedMessage = "BUILD SUCCESSFUL"; _log = CreateXmlLogger(); args.Message = unformattedMessage; _log.MessageLogged(this, args); expected = string.Format(CultureInfo.InvariantCulture, "", unformattedMessage); Assert.AreEqual(expected, _log.ToString()); } [Test] public void WriteStrangeCharacters() { string baseMessage = "this message has !@!)$)(&^%^%$$##@@}{[]\"';:<<>/+=-_. in it."; string formattedMessage = "[foo] " + baseMessage; BuildEventArgs args = CreateBuildEventArgs(formattedMessage, Level.Info); _log.MessageLogged(this, args); string expected = string.Format(CultureInfo.InvariantCulture, "", baseMessage); Assert.AreEqual(expected, _log.ToString()); } [Test] public void WriteEmbeddedMathFormulas() { string baseMessage = "this message has: x < 20 = y in it."; string formattedMessage = "[foo] " + baseMessage; BuildEventArgs args = CreateBuildEventArgs(formattedMessage, Level.Info); _log.MessageLogged(this, args); string expected = string.Format(CultureInfo.InvariantCulture, "", baseMessage); Assert.AreEqual(expected, _log.ToString()); } [Test] public void WriteTextWithEmbeddedCDATATag() { string message = @"some stuff with and more "; string expected = @" more stuff and more cdata]]>"; BuildEventArgs args = CreateBuildEventArgs(message, Level.Info); _log.MessageLogged(this, args); Assert.AreEqual(expected, _log.ToString()); } [Test] public void WriteXmlWithDeclaration() { string message = @""; string expected = @""; BuildEventArgs args = CreateBuildEventArgs(message, Level.Info); _log.MessageLogged(this, args); Assert.AreEqual(expected, _log.ToString()); } [Test] public void WriteXmlWithLeadingWhitespace() { string message = @" "; string expected = @""; BuildEventArgs args = CreateBuildEventArgs(message, Level.Info); _log.MessageLogged(this, args); Assert.AreEqual(expected, _log.ToString()); } [Test] public void WriteEmbeddedXml() { string baseMessage = ""; string expected = string.Format(CultureInfo.InvariantCulture, "{0}", baseMessage); BuildEventArgs args = CreateBuildEventArgs(baseMessage, Level.Info); _log.MessageLogged(this, args); Assert.AreEqual(expected, _log.ToString()); } [Test] public void WriteEmbeddedMalformedXml() { string baseMessage = "malformed"; string expected = string.Format(CultureInfo.InvariantCulture, "", baseMessage); BuildEventArgs args = CreateBuildEventArgs(baseMessage, Level.Info); _log.MessageLogged(this, args); Assert.AreEqual(expected, _log.ToString()); } [Test] public void BuildStartedAndBuildFinished() { string expected = "123"; _log = CreateXmlLogger(CreateDateTimeProvider(123)); BuildEventArgs args = new BuildEventArgs(CreateProject()); _log.BuildStarted(this, args); _log.BuildFinished(this, args); Assert.AreEqual(expected, _log.ToString()); } [Test] public void TargetStartedAndTargetFinished() { string expected = @"123"; _log = CreateXmlLogger(CreateDateTimeProvider(123)); BuildEventArgs args = CreateBuildEventArgsWithTarget("foo"); _log.TargetStarted(this, args); _log.TargetFinished(this, args); Assert.AreEqual(expected, _log.ToString()); } [Test] public void TaskStartedAndTaskFinished() { string expected = @"321"; _log = CreateXmlLogger(CreateDateTimeProvider(321)); BuildEventArgs args = new BuildEventArgs(new TestTask()); _log.TaskStarted(this, args); _log.TaskFinished(this, args); Assert.AreEqual(expected, _log.ToString()); } private MockDateTimeProvider CreateDateTimeProvider(int duration) { MockDateTimeProvider mockDateTimeProvider = new MockDateTimeProvider(); mockDateTimeProvider.SetExpectedNow(new DateTime(2004, 12, 1, 1, 0, 0)); mockDateTimeProvider.SetExpectedNow(new DateTime(2004, 12, 1, 1, 0, 0, duration)); return mockDateTimeProvider; } private XmlLogger CreateXmlLogger() { return CreateXmlLogger(new DateTimeProvider()); } private XmlLogger CreateXmlLogger(DateTimeProvider dtProvider) { XmlLogger logger = new XmlLogger(new StopWatchStack(dtProvider)); logger.OutputWriter = new StringWriter(); return logger; } private BuildEventArgs CreateBuildEventArgsWithTarget(string targetName) { Target target = new Target(); target.Name = targetName; return new BuildEventArgs(target); } private string FormatBuildFile(string globalTasks, string targetTasks, string projectName) { return String.Format(CultureInfo.InvariantCulture, _format, _tempDir, globalTasks, targetTasks, projectName); } private BuildEventArgs CreateBuildEventArgs(string formattedMessage, Level level) { BuildEventArgs args = new BuildEventArgs(new Target()); args.Message = formattedMessage; args.MessageLevel = level; return args; } private Project CreateProject() { XmlDocument doc = new XmlDocument(); doc.LoadXml(FormatBuildFile("", "", "testproject")); return new Project(doc, Level.Info, 0); } [TaskName("testtask")] private class TestTask : Task { protected override void ExecuteTask() {} } } }nant-0.92-rc1/tests/NAnt.Core/Functions/0000755000175000017500000000000011757310030017657 5ustar jtaylorjtaylornant-0.92-rc1/tests/NAnt.Core/Functions/FileFunctionsTest.cs0000644000175000017500000000656111757302275023642 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2006 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System.IO; using NUnit.Framework; using NAnt.Core; namespace Tests.NAnt.Core.Functions { [TestFixture] public class FileFunctionsTest : BuildTestBase { #region Public Instance Methods [Test] public void IsAssembly_OK() { string buildFragment = "" + " " + " #1" + " " + ""; RunBuild(buildFragment); } [Test] public void IsAssembly_InvalidAssembly() { string buildFragment = "" + " test" + " " + " #1" + " " + ""; RunBuild(buildFragment); } [Test] public void IsAssembly_NoAssembly() { string buildFragment1 = "" + " test" + " " + " #1" + " " + ""; RunBuild(buildFragment1); string buildFragment2 = "" + " " + " #1" + " " + ""; RunBuild(buildFragment2); } [Test] public void IsAssembly_AssemblyDoesNotExist() { string buildFragment = "" + " " + " #1" + " " + ""; try { RunBuild(buildFragment); Assert.Fail ("#1"); } catch (TestBuildException ex) { Assert.IsNotNull (ex.InnerException, "#2"); Assert.AreEqual (typeof (BuildException), ex.InnerException.GetType(), "#3"); Assert.IsNotNull (ex.InnerException.InnerException, "#4"); Assert.AreEqual (typeof (FileNotFoundException), ex.InnerException.InnerException.GetType(), "#5"); } } #endregion Public Instance Methods } } nant-0.92-rc1/tests/NAnt.Core/Functions/TargetFunctionsTest.cs0000644000175000017500000000560411757302275024206 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Eric Gunnerson // Gerry Shaw (gerry_shaw@yahoo.com) using System; using System.IO; using System.Reflection; using System.Collections; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Globalization; using NUnit.Framework; using NAnt.Core; namespace Tests.NAnt.Core.Functions { [TestFixture] public class TargetFunctionsTest : BuildTestBase { #region Public Instance Methods [Test] public void Test_CurrentTarget() { string buildFragment = @" "; Project project = CreateFilebasedProject(buildFragment); ExecuteProject(project); // check whether all expected properties exist Assert.IsTrue(project.Properties.Contains("A.1"), "Property \"A.1\" does not exist."); Assert.IsTrue(project.Properties.Contains("A.2"), "Property \"A.2\" does not exist."); Assert.IsTrue(project.Properties.Contains("B"), "Property \"B\" does not exist."); Assert.IsTrue(project.Properties.Contains("C"), "Property \"C\" does not exist."); // check values Assert.AreEqual("A", project.Properties["A.1"], "A.1"); Assert.AreEqual("A", project.Properties["A.2"], "A.2"); Assert.AreEqual("B", project.Properties["B"], "B"); Assert.AreEqual("C", project.Properties["C"], "C"); } #endregion Public Instance Methods } } nant-0.92-rc1/tests/NAnt.Core/Functions/EnvironmentFunctionsTest.cs0000644000175000017500000000355611757302275025270 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Globalization; using NUnit.Framework; using NAnt.Core; namespace Tests.NAnt.Core.Functions { [TestFixture] public class EnvironmentFunctionsTest : BuildTestBase { private Project _project; [SetUp] protected override void SetUp() { base.SetUp(); _project = CreateEmptyProject (); } [Test] public void NewLine() { AssertExpression("environment::newline()", Environment.NewLine); } private void AssertExpression(string expression, object expectedReturnValue) { string value = _project.ExpandProperties("${" + expression + "}", Location.UnknownLocation); string expectedStringValue = Convert.ToString(expectedReturnValue, CultureInfo.InvariantCulture); _project.Log(Level.Debug, "expression: " + expression); _project.Log(Level.Debug, "value: " + value + ", expected: " + expectedStringValue); Assert.AreEqual(expectedStringValue, value, expression); } } } nant-0.92-rc1/tests/NAnt.Core/BuildFilesInResourcesTest.cs0000644000175000017500000000636211757302275023325 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2003 Scott Hernandez // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Scott Hernandez (ScottHernandez@hotmail.com) using System; using System.IO; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Xml; using NUnit.Framework; using NAnt.Core; using Tests.NAnt.Core.Util; namespace Tests.NAnt.Core { [TestFixture] public class BuildFilesInResourcesTest { #region Public Instance Methods [SetUp] public void SetUp() { _tempFolder = Path.Combine (Path.GetTempPath (), "Tests.NAnt.Core.BuildFilesInResourcesTest"); if (!Directory.Exists (_tempFolder)) Directory.CreateDirectory (_tempFolder); } [TearDown] public void TearDown() { if (Directory.Exists (_tempFolder)) Directory.Delete (_tempFolder, true); } [Test] public void Test_FilesInResources() { string buildFile = Path.Combine (_tempFolder, "default.build"); foreach (string resName in Assembly.GetExecutingAssembly().GetManifestResourceNames()) { if (!resName.StartsWith("XML_.Build.Files")) { continue; } using (FileStream fs = File.Open (buildFile, FileMode.Create, FileAccess.ReadWrite, FileShare.Read)) { byte[] buffer = new byte[8192]; Stream rs = Assembly.GetExecutingAssembly().GetManifestResourceStream(resName); while (true) { int bytesRead = rs.Read(buffer, 0, buffer.Length); if (bytesRead == 0) { break; } fs.Write(buffer, 0, bytesRead); } } bool expectSuccess = (resName.IndexOf(".Valid.") > 0); try { XmlDocument doc = new XmlDocument(); doc.Load(buildFile); Project p = new Project(doc, Level.Info, 0); string output = BuildTestBase.ExecuteProject(p); Assert.IsTrue (expectSuccess, "#1: " + resName + " " + output); } catch (Exception ex) { Assert.IsFalse (expectSuccess, "#2: " +resName + " " + ex.ToString()); } } } #endregion Public Instance Methods #region Private Instance Fields private string _tempFolder; #endregion Private Instance Fields } } nant-0.92-rc1/tests/NAnt.Core/Tasks/0000755000175000017500000000000011757310030016774 5ustar jtaylorjtaylornant-0.92-rc1/tests/NAnt.Core/Tasks/EchoTest.cs0000644000175000017500000007332711757302275021071 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2002 Scott Hernandez (ScottHernandez@hotmail.com) // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Scott Hernandez (ScottHernandez@hotmail.com) // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.IO; using System.Text; using NUnit.Framework; using NAnt.Core; using NAnt.Core.Tasks; namespace Tests.NAnt.Core.Tasks { /// /// Tests the Echo task. /// [TestFixture] public class EchoTest : BuildTestBase { [SetUp] protected override void SetUp() { base.SetUp(); } [Test] public void EncodingTest () { EchoTask echo = new EchoTask(); Assert.AreEqual (65001, echo.Encoding.CodePage, "#1"); Assert.AreEqual (new byte [0], echo.Encoding.GetPreamble (), "#2"); echo.Encoding = Encoding.ASCII; Assert.AreEqual (Encoding.ASCII, echo.Encoding, "#3"); echo.Encoding = null; Assert.AreEqual (65001, echo.Encoding.CodePage, "#4"); Assert.AreEqual (new byte [0], echo.Encoding.GetPreamble (), "#5"); } [Test] public void Test_EchoDefaultProjectInfo() { string _xml = @" "; string result = RunBuild(_xml); Assert.IsTrue(result.IndexOf("Go Away!") != -1, "Echo message missing:" + result); } [Test] public void Test_EchoDefaultProjectInfoMacro() { string _xml = @" "; string result = RunBuild(_xml); Assert.IsTrue(result.IndexOf("Go Away!") != -1, "Macro should have expanded:" + result); } [Test] public void Test_EchoDebugProjectInfo() { string _xml = @" "; string result = RunBuild(_xml, Level.Info); Assert.IsTrue(result.IndexOf("Go Away!") == -1, "Debug echo should not be output when Project level is Info."); } [Test] public void Test_EchoWarningProjectInfo() { string _xml = @" Go Away! "; string result = RunBuild(_xml, Level.Info); Assert.IsTrue(result.IndexOf("Go Away!") != -1, "Warning echo should be output when Project level is Info."); } [Test] public void Test_EchoWarningProjectInfoMacro() { string _xml = @" ${prop} Away! "; string result = RunBuild(_xml, Level.Info); Assert.IsTrue(result.IndexOf("Go Away!") != -1, "Macro should have expanded:" + result); } [Test] public void Test_EchoWarningProjectError() { string _xml = @" Go Away! "; string result = RunBuild(_xml, Level.Error); Assert.IsTrue(result.IndexOf("Go Away!") == -1, "Warning echo should not be output when Project level is Error."); } [Test] [ExpectedException(typeof(TestBuildException))] public void Test_EchoInvalidLevel() { string _xml = @" "; RunBuild(_xml, Level.Error); } [Test] public void Test_EchoMessageAndInlineContent() { string xml1 = @" Go Away! "; try { RunBuild(xml1, Level.Info); Assert.Fail ("#1"); } catch (TestBuildException) { } string xml2 = @" Go Away! "; try { RunBuild(xml2, Level.Info); Assert.Fail ("#2"); } catch (TestBuildException) { } string xml3 = @" a "; try { RunBuild(xml3, Level.Info); Assert.Fail ("#3"); } catch (TestBuildException) { } } [Test] [ExpectedException(typeof(TestBuildException))] public void Encoding_Invalid() { string _xml = @" Go Away! "; RunBuild(_xml, Level.Info); } [Test] public void NewFile() { string msg = "\u0041\u2262\u0391\u002E!"; string logfile = Path.Combine (TempDirName, "log"); TestBuildListener listener; string result; string _xml1 = @" "; listener = new TestBuildListener(); result = RunBuild (_xml1, listener); Assert.IsTrue(result.IndexOf(msg) == -1, "#A1"); Assert.IsFalse(listener.HasMessageBeenLogged (msg, true), "#A2"); Assert.IsTrue (File.Exists(logfile), "#A3"); using (StreamReader sr = new StreamReader (logfile, Encoding.UTF8)) { string content = sr.ReadToEnd (); Assert.AreEqual (msg, content, "#A4"); } File.Delete (logfile); string _xml2 = @" " + msg + @" "; listener = new TestBuildListener(); result = RunBuild (_xml2, listener); Assert.IsTrue(result.IndexOf(msg) == -1, "#B1"); Assert.IsFalse(listener.HasMessageBeenLogged (msg, true), "#B2"); Assert.IsTrue (File.Exists(logfile), "#B3"); using (StreamReader sr = new StreamReader (logfile, Encoding.UTF8)) { string content = sr.ReadToEnd (); Assert.AreEqual (msg, content, "#B4"); } } [Test] public void ExistingFile_Append_Default() { string msg = "\u0041\u2262\u0391\u002E!"; string logfile = Path.Combine (TempDirName, "log"); TestBuildListener listener; string result; string _xml1 = @" "; using (StreamWriter sw = new StreamWriter (logfile, false, Encoding.Unicode)) { sw.Write ("ok"); } listener = new TestBuildListener(); result = RunBuild (_xml1, listener); Assert.IsTrue(result.IndexOf(msg) == -1, "#A1"); Assert.IsFalse(listener.HasMessageBeenLogged (msg, true), "#A2"); Assert.IsTrue (File.Exists(logfile), "#A3"); using (FileStream fs = File.OpenRead (logfile)) { Assert.AreEqual (12, fs.Length, "#A4"); using (StreamReader sr = new StreamReader (fs, Encoding.Unicode)) { string content = sr.ReadToEnd (); Assert.AreEqual (msg, content, "#A5"); } } File.Delete (logfile); string _xml2 = @" " + msg + @" "; using (StreamWriter sw = new StreamWriter (logfile, false, Encoding.Unicode)) { sw.Write ("ok"); } listener = new TestBuildListener(); result = RunBuild (_xml2, listener); Assert.IsTrue(result.IndexOf(msg) == -1, "#B1"); Assert.IsFalse(listener.HasMessageBeenLogged (msg, true), "#B2"); Assert.IsTrue (File.Exists(logfile), "#B3"); using (FileStream fs = File.OpenRead (logfile)) { Assert.AreEqual (12, fs.Length, "#B4"); using (StreamReader sr = new StreamReader (fs, Encoding.Unicode)) { string content = sr.ReadToEnd (); Assert.AreEqual (msg, content, "#B5"); } } } [Test] public void ExistingFile_Append_False() { string msg = "\u0041\u2262\u0391\u002E!"; string logfile = Path.Combine (TempDirName, "log"); TestBuildListener listener; string result; string _xml1 = @" "; using (StreamWriter sw = new StreamWriter (logfile, false, Encoding.UTF8)) { sw.Write ("ok"); } listener = new TestBuildListener(); result = RunBuild (_xml1, listener); Assert.IsTrue(result.IndexOf(msg) == -1, "#A1"); Assert.IsFalse(listener.HasMessageBeenLogged (msg, true), "#A2"); Assert.IsTrue (File.Exists(logfile), "#A3"); using (FileStream fs = File.OpenRead (logfile)) { Assert.AreEqual (11, fs.Length, "#A4"); using (StreamReader sr = new StreamReader (fs, Encoding.UTF8)) { string content = sr.ReadToEnd (); Assert.AreEqual (msg, content, "#A5"); } } File.Delete (logfile); string _xml2 = @" " + msg + @" "; using (StreamWriter sw = new StreamWriter (logfile, false, Encoding.UTF8)) { sw.Write ("ok"); } listener = new TestBuildListener(); result = RunBuild (_xml2, listener); Assert.IsTrue(result.IndexOf(msg) == -1, "#B1"); Assert.IsFalse(listener.HasMessageBeenLogged (msg, true), "#B2"); Assert.IsTrue (File.Exists(logfile), "#B3"); using (FileStream fs = File.OpenRead (logfile)) { Assert.AreEqual (11, fs.Length, "#B4"); using (StreamReader sr = new StreamReader (fs, Encoding.UTF8)) { string content = sr.ReadToEnd (); Assert.AreEqual (msg, content, "#B5"); } } } [Test] public void ExistingFile_Append_True() { string msg = "\u0041\u2262\u0391\u002E!"; string logfile = Path.Combine (TempDirName, "log"); TestBuildListener listener; string result; string _xml1 = @" "; using (StreamWriter sw = new StreamWriter (logfile, false, Encoding.UTF8)) { sw.Write ("ok"); } listener = new TestBuildListener(); result = RunBuild (_xml1, listener); Assert.IsTrue(result.IndexOf(msg) == -1, "#A1"); Assert.IsFalse(listener.HasMessageBeenLogged (msg, true), "#A2"); Assert.IsTrue (File.Exists(logfile), "#A3"); using (FileStream fs = File.OpenRead (logfile)) { Assert.AreEqual (13, fs.Length, "#A4"); using (StreamReader sr = new StreamReader (fs, Encoding.UTF8)) { string content = sr.ReadToEnd (); Assert.AreEqual ("ok" + msg, content, "#A5"); } } File.Delete (logfile); string _xml2 = @" " + msg + @" "; using (StreamWriter sw = new StreamWriter (logfile, false, Encoding.UTF8)) { sw.Write ("ok"); } listener = new TestBuildListener(); result = RunBuild (_xml2, listener); Assert.IsTrue(result.IndexOf(msg) == -1, "#B1"); Assert.IsFalse(listener.HasMessageBeenLogged (msg, true), "#B2"); Assert.IsTrue (File.Exists(logfile), "#B3"); using (FileStream fs = File.OpenRead (logfile)) { Assert.AreEqual (13, fs.Length, "#B4"); using (StreamReader sr = new StreamReader (fs, Encoding.UTF8)) { string content = sr.ReadToEnd (); Assert.AreEqual ("ok" + msg, content, "#B5"); } } } [Test] public void File_Message_Empty() { string logfile = Path.Combine (TempDirName, "log"); TestBuildListener listener; string _xml1 = @" "; listener = new TestBuildListener(); RunBuild (_xml1, listener); Assert.IsTrue (File.Exists(logfile), "#A1"); Assert.IsFalse(listener.HasMessageBeenLogged (" ", true), "#A2"); using (StreamReader sr = new StreamReader (logfile, Encoding.UTF8)) { string content = sr.ReadToEnd (); Assert.AreEqual (string.Empty, content, "#A3"); } File.Delete (logfile); string _xml2 = @" "; listener = new TestBuildListener(); RunBuild (_xml2, listener); Assert.IsTrue (File.Exists(logfile), "#B1"); Assert.IsFalse(listener.HasMessageBeenLogged (" ", true), "#B2"); using (StreamReader sr = new StreamReader (logfile, Encoding.UTF8)) { string content = sr.ReadToEnd (); Assert.AreEqual (string.Empty, content, "#B3"); } File.Delete (logfile); string msg = "\u0041\u2262\n\u0391\u002E!"; string _xml3 = @" " + msg + @" "; listener = new TestBuildListener(); RunBuild (_xml3, listener); Assert.IsTrue (File.Exists(logfile), "#C1"); Assert.IsFalse(listener.HasMessageBeenLogged (msg, true), "#C2"); using (StreamReader sr = new StreamReader (logfile, Encoding.UTF8)) { string content = sr.ReadToEnd (); Assert.AreEqual (msg, content, "#C3"); } } [Test] public void File_Level_Ignored() { string msg = "\u0041\u2262\u0391\u002E!"; string logfile = Path.Combine (TempDirName, "log"); TestBuildListener listener; string result; string _xml1 = @" "; listener = new TestBuildListener(); result = RunBuild (_xml1, Level.Error, listener); Assert.IsTrue(result.IndexOf(msg) == -1, "#A1"); Assert.IsFalse(listener.HasMessageBeenLogged (msg, true), "#A2"); Assert.IsTrue (File.Exists(logfile), "#A3"); using (FileStream fs = File.OpenRead (logfile)) { Assert.AreEqual (11, fs.Length, "#A4"); using (StreamReader sr = new StreamReader (fs, Encoding.UTF8)) { string content = sr.ReadToEnd (); Assert.AreEqual (msg, content, "#A5"); } } File.Delete (logfile); string _xml2 = @" " + msg + @" "; listener = new TestBuildListener(); result = RunBuild (_xml2, Level.Error, listener); Assert.IsTrue(result.IndexOf(msg) == -1, "#B1"); Assert.IsFalse(listener.HasMessageBeenLogged (msg, true), "#B2"); Assert.IsTrue (File.Exists(logfile), "#B3"); using (FileStream fs = File.OpenRead (logfile)) { Assert.AreEqual (11, fs.Length, "#B4"); using (StreamReader sr = new StreamReader (fs, Encoding.UTF8)) { string content = sr.ReadToEnd (); Assert.AreEqual (msg, content, "#B5"); } } } [Test] public void File_Directory_DoesNotExist() { string dir = Path.Combine (TempDirName, "tmp"); string logfile = Path.Combine (dir, "log"); TestBuildListener listener; string _xml = @" "; listener = new TestBuildListener(); RunBuild (_xml, listener); Assert.IsTrue (File.Exists(logfile), "#1"); Assert.IsFalse(listener.HasMessageBeenLogged ("sometest", true), "#2"); using (StreamReader sr = new StreamReader (logfile, Encoding.Default)) { string content = sr.ReadToEnd (); Assert.AreEqual ("sometest", content, "#3"); } } [Test] public void File_Multiline() { string msg; string logfile = Path.Combine (TempDirName, "log"); TestBuildListener listener; string result; msg = " \u0041\u2262" + Environment.NewLine + "\u0391\u002E! "; string _xml1 = @" "; using (StreamWriter sw = new StreamWriter (logfile, false, Encoding.UTF8)) { sw.Write ("ok"); } listener = new TestBuildListener(); result = RunBuild (_xml1, listener); Assert.IsTrue(result.IndexOf(msg) == -1, "#A1"); Assert.IsFalse(listener.HasMessageBeenLogged (msg, true), "#A2"); Assert.IsTrue (File.Exists(logfile), "#A3"); using (FileStream fs = File.OpenRead (logfile)) { using (StreamReader sr = new StreamReader (fs, Encoding.UTF8)) { string content = sr.ReadToEnd (); Assert.AreEqual ("ok" + msg, content, "#A4"); } } msg = string.Format ("{0}\u0041\u2262{0}\u0391\u002E!{0}", Environment.NewLine); string _xml2 = @" " + msg + @" "; using (StreamWriter sw = new StreamWriter (logfile, false, Encoding.UTF8)) { sw.Write ("ok" + Environment.NewLine); } listener = new TestBuildListener(); result = RunBuild (_xml2, listener); Assert.IsTrue(result.IndexOf(msg) == -1, "#B1"); Assert.IsFalse(listener.HasMessageBeenLogged (msg, true), "#B2"); Assert.IsTrue (File.Exists(logfile), "#B3"); using (FileStream fs = File.OpenRead (logfile)) { using (StreamReader sr = new StreamReader (fs, Encoding.UTF8)) { string content = sr.ReadToEnd (); Assert.AreEqual ("ok" + Environment.NewLine + msg, content, "#B4"); } } } [Test] public void File_Message_Missing() { string logfile = Path.Combine (TempDirName, "log"); TestBuildListener listener; string xml = @" "; listener = new TestBuildListener(); RunBuild (xml, listener); Assert.IsTrue(listener.HasMessageBeenLogged (string.Empty, true), "#1"); Assert.IsTrue (File.Exists(logfile), "#2"); using (FileStream fs = File.OpenRead (logfile)) { using (StreamReader sr = new StreamReader (fs, Encoding.UTF8)) { string content = sr.ReadToEnd (); Assert.AreEqual (string.Empty, content, "#3"); } } } [Test] public void File_Message_Whitespace() { string msg; string logfile = Path.Combine (TempDirName, "log"); TestBuildListener listener; string result; msg = " \t \n "; string xml1 = @" "; listener = new TestBuildListener(); result = RunBuild (xml1, listener); Assert.IsTrue(result.IndexOf(msg) == -1, "#A1"); Assert.IsFalse(listener.HasMessageBeenLogged (msg, true), "#A2"); Assert.IsTrue (File.Exists(logfile), "#A3"); using (FileStream fs = File.OpenRead (logfile)) { using (StreamReader sr = new StreamReader (fs, Encoding.UTF8)) { string content = sr.ReadToEnd (); Assert.AreEqual (string.Empty, content, "#A4"); } } string xml2 = @" " + msg + @" "; listener = new TestBuildListener(); result = RunBuild (xml2, listener); Assert.IsTrue(result.IndexOf(msg) == -1, "#B1"); Assert.IsFalse(listener.HasMessageBeenLogged (msg, true), "#B2"); Assert.IsTrue (File.Exists(logfile), "#B3"); using (FileStream fs = File.OpenRead (logfile)) { using (StreamReader sr = new StreamReader (fs, Encoding.UTF8)) { string content = sr.ReadToEnd (); Assert.AreEqual (string.Empty, content, "#B4"); } } string xml3 = @" " + Environment.NewLine + @" "; listener = new TestBuildListener(); result = RunBuild (xml3, listener); Assert.IsTrue(result.IndexOf(msg) == -1, "#C1"); Assert.IsFalse(listener.HasMessageBeenLogged (msg, true), "#C2"); Assert.IsTrue (File.Exists(logfile), "#C3"); using (FileStream fs = File.OpenRead (logfile)) { using (StreamReader sr = new StreamReader (fs, Encoding.UTF8)) { string content = sr.ReadToEnd (); Assert.AreEqual (string.Empty, content, "#C4"); } } string xml4 = @" " + msg + @" "; listener = new TestBuildListener(); result = RunBuild (xml4, listener); Assert.IsTrue(result.IndexOf(msg) == -1, "#D1"); Assert.IsFalse(listener.HasMessageBeenLogged (msg, true), "#D2"); Assert.IsTrue (File.Exists(logfile), "#D3"); using (FileStream fs = File.OpenRead (logfile)) { using (StreamReader sr = new StreamReader (fs, Encoding.UTF8)) { string content = sr.ReadToEnd (); Assert.AreEqual (string.Empty, content, "#D4"); } } msg = " \t X \n "; string xml5 = @" " + Environment.NewLine + @" "; listener = new TestBuildListener(); result = RunBuild (xml5, listener); Assert.IsTrue(result.IndexOf(msg) == -1, "#E1"); Assert.IsFalse(listener.HasMessageBeenLogged (msg, true), "#E2"); Assert.IsTrue (File.Exists(logfile), "#E3"); using (FileStream fs = File.OpenRead (logfile)) { using (StreamReader sr = new StreamReader (fs, Encoding.UTF8)) { string content = sr.ReadToEnd (); Assert.AreEqual (msg, content, "#E4"); } } string xml6 = @" " + msg + @" "; listener = new TestBuildListener(); result = RunBuild (xml6, listener); Assert.IsTrue(result.IndexOf(msg) == -1, "#F1"); Assert.IsFalse(listener.HasMessageBeenLogged (msg, true), "#F2"); Assert.IsTrue (File.Exists(logfile), "#F3"); using (FileStream fs = File.OpenRead (logfile)) { using (StreamReader sr = new StreamReader (fs, Encoding.UTF8)) { string content = sr.ReadToEnd (); Assert.AreEqual (msg, content, "#F4"); } } } [Test] public void Log_Message_Missing() { string xml = @" "; TestBuildListener listener = new TestBuildListener(); RunBuild (xml, listener); Assert.IsTrue(listener.HasMessageBeenLogged (string.Empty, true), "#1"); } [Test] public void Log_Message_Whitespace() { string msg; TestBuildListener listener; string result; msg = " \t \n "; string xml1 = @" "; listener = new TestBuildListener(); result = RunBuild (xml1, listener); Assert.IsTrue(result.IndexOf(msg) == -1, "#A1"); Assert.IsFalse(listener.HasMessageBeenLogged (msg, true), "#A2"); Assert.IsTrue(listener.HasMessageBeenLogged (string.Empty, true), "#A3"); string xml2 = @" " + msg + @" "; listener = new TestBuildListener(); result = RunBuild (xml2, listener); Assert.IsTrue(result.IndexOf(msg) == -1, "#B1"); Assert.IsFalse(listener.HasMessageBeenLogged (msg, true), "#B2"); Assert.IsTrue(listener.HasMessageBeenLogged (string.Empty, true), "#B3"); string xml3 = @" " + Environment.NewLine + @" "; listener = new TestBuildListener(); result = RunBuild (xml3, listener); Assert.IsTrue(result.IndexOf(msg) == -1, "#C1"); Assert.IsFalse(listener.HasMessageBeenLogged (msg, true), "#C2"); Assert.IsTrue(listener.HasMessageBeenLogged (string.Empty, true), "#C3"); string xml4 = @" " + msg + @" "; listener = new TestBuildListener(); result = RunBuild (xml4, listener); Assert.IsTrue(result.IndexOf(msg) == -1, "#D1"); Assert.IsFalse(listener.HasMessageBeenLogged (msg, true), "#D2"); Assert.IsTrue(listener.HasMessageBeenLogged (string.Empty, true), "#D3"); msg = " \t X \n "; string xml5 = @" " + Environment.NewLine + @" "; listener = new TestBuildListener(); result = RunBuild (xml5, listener); Assert.IsTrue(listener.HasMessageBeenLogged (msg, true), "#E"); string xml6 = @" " + msg + @" "; listener = new TestBuildListener(); result = RunBuild (xml6, listener); Assert.IsTrue(listener.HasMessageBeenLogged (msg, true), "#F"); } } } nant-0.92-rc1/tests/NAnt.Core/Tasks/AttribTaskTest.cs0000644000175000017500000001727311757302275022261 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Gerry Shaw (gerry_shaw@yahoo.com) using System; using System.IO; using System.Text; using System.Xml; using System.Globalization; using NUnit.Framework; using NAnt.Core; using Tests.NAnt.Core.Util; namespace Tests.NAnt.Core.Tasks { [TestFixture] public class AttribTaskTest : BuildTestBase { const string _format = @" {2} "; string _tempFileName; FileAttributes _normalFileAttributes; [SetUp] protected override void SetUp() { base.SetUp(); _tempFileName = Path.Combine(TempDirName, "myfile.txt"); TempFile.Create(_tempFileName); File.SetAttributes(_tempFileName, FileAttributes.Normal); // Handle case when temp folder is compressed _normalFileAttributes = File.GetAttributes(_tempFileName) & (FileAttributes.Normal | FileAttributes.Compressed); } [Test] public void Test_Normal() { File.SetAttributes(_tempFileName, FileAttributes.Archive | FileAttributes.Hidden | FileAttributes.ReadOnly | FileAttributes.System); if (!PlatformHelper.IsUnix) { Assert.IsTrue((File.GetAttributes(_tempFileName) & FileAttributes.Archive) != 0, "#1"); Assert.IsTrue((File.GetAttributes(_tempFileName) & FileAttributes.Hidden) != 0, "#2"); Assert.IsTrue((File.GetAttributes(_tempFileName) & FileAttributes.System) != 0, "#3"); } Assert.IsTrue((File.GetAttributes(_tempFileName) & FileAttributes.ReadOnly) != 0, "#4"); RunBuild(FormatBuildFile("normal='true'")); if (!PlatformHelper.IsUnix) { Assert.IsTrue((File.GetAttributes(_tempFileName) & FileAttributes.Archive) == 0, "#5"); Assert.IsTrue((File.GetAttributes(_tempFileName) & _normalFileAttributes) != 0, "#6"); Assert.IsTrue((File.GetAttributes(_tempFileName) & FileAttributes.Hidden) == 0, "#7"); Assert.IsTrue((File.GetAttributes(_tempFileName) & FileAttributes.System) == 0, "#8"); } Assert.IsTrue((File.GetAttributes(_tempFileName) & FileAttributes.ReadOnly) == 0, "#9"); } /// /// Ensure that an invalid path causes a /// to be thrown. /// [Test] public void Test_InvalidFilePath() { // this test not valid on unix's where every character bar the / is valid for filenames. if (!PlatformHelper.IsUnix) { try { // execute build with invalid file path RunBuild(string.Format(CultureInfo.InvariantCulture, _format, "ab|c", "", "")); // have the test fail Assert.Fail("Build should have failed."); } catch (TestBuildException ex) { // assert that a BuildException was the cause of the TestBuildException Assert.IsTrue((ex.InnerException != null && ex.InnerException.GetType() == typeof(BuildException))); } } } [Test] public void Test_Archive() { if (! PlatformHelper.IsUnix ) { Assert.IsTrue((File.GetAttributes(_tempFileName) & FileAttributes.Archive) == 0, _tempFileName + " should not have Archive file attribute."); RunBuild(FormatBuildFile("archive='true'")); Assert.IsTrue((File.GetAttributes(_tempFileName) & FileAttributes.Archive) != 0, _tempFileName + " should have Archive file attribute."); } } [Test] public void Test_Hidden() { if (! PlatformHelper.IsUnix ) { Assert.IsTrue((File.GetAttributes(_tempFileName) & FileAttributes.Hidden) == 0, _tempFileName + " should not have Hidden file attribute."); RunBuild(FormatBuildFile("hidden='true'")); Assert.IsTrue((File.GetAttributes(_tempFileName) & FileAttributes.Hidden) != 0, _tempFileName + " should have Hidden file attribute."); } } [Test] public void Test_ReadOnly() { Assert.IsTrue((File.GetAttributes(_tempFileName) & FileAttributes.ReadOnly) == 0, _tempFileName + " should not have ReadOnly file attribute."); RunBuild(FormatBuildFile("readonly='true'")); Assert.IsTrue((File.GetAttributes(_tempFileName) & FileAttributes.ReadOnly) != 0, _tempFileName + " should have ReadOnly file attribute."); } [Test] public void Test_System() { if (! PlatformHelper.IsUnix ) { Assert.IsTrue((File.GetAttributes(_tempFileName) & FileAttributes.System) == 0, _tempFileName + " should not have System file attribute."); RunBuild(FormatBuildFile("system='true'")); Assert.IsTrue((File.GetAttributes(_tempFileName) & FileAttributes.System) != 0, _tempFileName + " should have System file attribute."); } } [Test] public void Test_Multiple() { for (int i = 0; i < 10; i++) { string fileName = Path.Combine(TempDirName, "myfile" + i + ".txt"); TempFile.Create(fileName); } // pick any of the just created files for testing string testFileName = Path.Combine(TempDirName, "myfile8.txt"); Assert.IsTrue((File.GetAttributes(testFileName) & FileAttributes.ReadOnly) == 0, testFileName + " should not have ReadOnly file attribute."); string result = RunBuild(FormatBuildFile("verbose='true' readonly='true'", "")); Assert.IsTrue((File.GetAttributes(testFileName) & FileAttributes.ReadOnly) != 0, testFileName + " should have ReadOnly file attribute."); // check for valid output Assert.IsTrue(result.IndexOf("myfile8.txt") != 0, "Build output should include names of all files changed." + Environment.NewLine + result); Assert.IsTrue(result.IndexOf("11 files") != 0, "Build output should include count of all files changed." + Environment.NewLine + result); Assert.IsTrue(result.IndexOf("ReadOnly") != 0, "Build output should include file attributes set." + Environment.NewLine + result); Assert.IsTrue(result.IndexOf("myfile.txt") != 0, "Build output should name specified in file attribute." + Environment.NewLine + result); } private string FormatBuildFile(string attributes) { return FormatBuildFile(attributes, ""); } private string FormatBuildFile(string attributes, string nestedElements) { return string.Format(CultureInfo.InvariantCulture, _format, _tempFileName, attributes, nestedElements); } } } nant-0.92-rc1/tests/NAnt.Core/Tasks/AvailableTest.cs0000644000175000017500000001627611757302275022073 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System.Globalization; using System.IO; using NUnit.Framework; using NAnt.Core; using NAnt.Core.Tasks; namespace Tests.NAnt.Core.Tasks { /// /// Tests available Task. /// [TestFixture] public class AvailableTest : BuildTestBase { #region Override implementation of BuildTestBase [SetUp] protected override void SetUp() { base.SetUp(); _tempFile = CreateTempFile("a.b"); _tempDir = CreateTempDir("foo"); // create a temporary file _notExistingTempFile = CreateTempFile("b.c"); // delete it to make sure it definitely not exists if (_notExistingTempFile != null && File.Exists(_notExistingTempFile)) { File.Delete(_notExistingTempFile); } // create a temporary directory _notExistingTempDir = CreateTempDir("test"); // delete it to make sure it definitely does not exist if (_notExistingTempDir != null && Directory.Exists(_notExistingTempDir)) { Directory.Delete(_notExistingTempDir); } } #endregion Override implementation of BuildTestBase #region Public Instance Methods [Test] public void Test_ExistingFile() { string xml= @" "; string result = RunBuild(string.Format(CultureInfo.InvariantCulture, xml, AvailableTask.ResourceType.File.ToString(CultureInfo.InvariantCulture), _tempFile, "${file.exists}")); Assert.IsTrue(result.ToLower().IndexOf("file.exists=true") != -1, "File resource should have existed:" + result); } [Test] public void Test_NotExistingFile() { string xml= @" "; string result = RunBuild(string.Format(CultureInfo.InvariantCulture, xml, AvailableTask.ResourceType.File.ToString(CultureInfo.InvariantCulture), _notExistingTempFile, "${file.exists}")); Assert.IsTrue(result.ToLower().IndexOf("file.exists=false") != -1, "File resource not should have existed:" + result); } [Test] [ExpectedException(typeof(TestBuildException))] public void Test_InvalidFile() { string xml= @" "; // unix accepts most characters ( except / ) so this test won't fail there. // mono even on windows acts like unix here. if (!(PlatformHelper.IsMono)) { RunBuild(string.Format(CultureInfo.InvariantCulture, xml, AvailableTask.ResourceType.File.ToString(CultureInfo.InvariantCulture), "###-?", "${file.exists}")); } else { // throw the exception to keep the test happy throw new TestBuildException(); } } [Test] public void Test_ExistingDirectory() { string xml= @" "; string result = RunBuild(string.Format(CultureInfo.InvariantCulture, xml, AvailableTask.ResourceType.Directory.ToString(CultureInfo.InvariantCulture), _tempDir, "${dir.exists}")); Assert.IsTrue(result.ToLower().IndexOf("dir.exists=true") != -1, "Directory resource should have existed:" + result); } [Test] public void Test_NotExistingDirectory() { string xml= @" "; string result = RunBuild(string.Format(CultureInfo.InvariantCulture, xml, AvailableTask.ResourceType.Directory.ToString(CultureInfo.InvariantCulture), _notExistingTempDir, "${dir.exists}")); Assert.IsTrue(result.ToLower().IndexOf("dir.exists=false") != -1, "Directory resource not should have existed:" + result); } [Test] [ExpectedException(typeof(TestBuildException))] public void Test_InvalidDirectory() { string xml= @" "; // unix accepts most characters ( except / ) so this test won't fail there. if (! PlatformHelper.IsUnix ) { RunBuild(string.Format(CultureInfo.InvariantCulture, xml, AvailableTask.ResourceType.Directory.ToString(CultureInfo.InvariantCulture), "|", "${dir.exists}")); } else { throw new TestBuildException(); } } [Test] [ExpectedException(typeof(TestBuildException))] public void Test_InvalidResourceType() { string xml= @" "; RunBuild(string.Format(CultureInfo.InvariantCulture, xml, "InvalidResourceType", @"\\#(){/}.dddd", "${file.exists}")); } #endregion Public Instance Methods #region Private Instance Fields private string _tempFile; private string _tempDir; private string _notExistingTempFile; private string _notExistingTempDir; #endregion Private Instance Fields } } nant-0.92-rc1/tests/NAnt.Core/Tasks/DeleteTest.cs0000644000175000017500000012371411757302275021411 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2002 Scott Hernandez (ScottHernandez@hotmail.com) // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Scott Hernandez (ScottHernandez@hotmail.com) using System; using System.IO; using System.Reflection; using System.Text; using System.Xml; using System.Globalization; using NUnit.Framework; namespace Tests.NAnt.Core.Tasks { /// /// Tests the deletion of the following: /// /// /// file /// folder /// folder with a file (recursive) /// /// /// /// This test should also test for failures, like permission errors, and filesets [TestFixture] public class DeleteTest : BuildTestBase { const string _xmlProjectTemplate = @" "; string tempFile1, tempFile2, tempFile3, tempFile4, tempFile5, tempFile6, tempFile7, tempFile8, tempFile9, tempFile10; string tempDir1, tempDir2, tempDir3, tempDir4, tempDir5, tempDir6, tempDir7, tempDir8; /// /// Creates a structure like so: /// a.b\ /// a.bb /// a.bc /// foo\* /// x.x /// goo\* /// x\ /// y.y /// ha.he /// ha.he2* /// ha.he3* /// a.boo /// boo /// a.c\ /// a.d\ /// boo\ /// a.e\ /// a.ee /// [SetUp] protected override void SetUp() { base.SetUp(); tempDir1 = CreateTempDir("a.b"); tempDir2 = CreateTempDir(Path.Combine(tempDir1, "foo")); tempDir3 = CreateTempDir(Path.Combine(tempDir1, "goo")); tempDir4 = CreateTempDir(Path.Combine(tempDir1, Path.Combine(tempDir3, "x"))); tempDir5 = CreateTempDir("a.c"); tempDir6 = CreateTempDir("a.d"); tempDir7 = CreateTempDir(Path.Combine(tempDir6, "boo")); tempDir8 = CreateTempDir("a.e"); tempFile1 = CreateTempFile(Path.Combine(tempDir1, "a.bb")); tempFile2 = CreateTempFile(Path.Combine(tempDir1, "a.bc")); tempFile3 = CreateTempFile(Path.Combine(tempDir2, "x.x")); tempFile4 = CreateTempFile(Path.Combine(tempDir4, "y.y")); tempFile5 = CreateTempFile(Path.Combine(tempDir3, "ha.he")); tempFile6 = CreateTempFile(Path.Combine(tempDir3, "ha.he2")); tempFile7 = CreateTempFile(Path.Combine(tempDir3, "ha.he3")); tempFile8 = CreateTempFile(Path.Combine(tempDir8, "a.ee")); tempFile9 = CreateTempFile(Path.Combine(tempDir3, "a.boo")); tempFile10 = CreateTempFile(Path.Combine(tempDir3, "boo")); /* File.SetAttributes(tempDir2, FileAttributes.ReadOnly); File.SetAttributes(tempDir3, FileAttributes.ReadOnly); */ File.SetAttributes(Path.Combine(tempDir3, "ha.he3"), FileAttributes.ReadOnly); File.SetAttributes(Path.Combine(tempDir3, "ha.he2"), FileAttributes.ReadOnly); } [Test] public void Test_Delete() { Assert.IsTrue(File.Exists(tempFile1), "File should have been created:" + tempFile1); Assert.IsTrue(File.Exists(tempFile2), "File should have been created:" + tempFile2); Assert.IsTrue(File.Exists(tempFile3), "File should have been created:" + tempFile3); Assert.IsTrue(File.Exists(tempFile4), "File should have been created:" + tempFile4); Assert.IsTrue(File.Exists(tempFile5), "File should have been created:" + tempFile5); Assert.IsTrue(File.Exists(tempFile6), "File should have been created:" + tempFile6); Assert.IsTrue(File.Exists(tempFile7), "File should have been created:" + tempFile7); Assert.IsTrue(Directory.Exists(tempDir1), "Dir should have been created:" + tempDir1); Assert.IsTrue(Directory.Exists(tempDir2), "Dir should have been created:" + tempDir2); Assert.IsTrue(Directory.Exists(tempDir3), "Dir should have been created:" + tempDir3); Assert.IsTrue(Directory.Exists(tempDir4), "Dir should have been created:" + tempDir4); RunBuild(String.Format(CultureInfo.InvariantCulture, _xmlProjectTemplate, "file", tempFile6 )); Assert.IsTrue(File.Exists(tempFile1), "File should not have been deleted:" + tempFile1); Assert.IsTrue(File.Exists(tempFile2), "File should not have been deleted:" + tempFile2); Assert.IsTrue(File.Exists(tempFile3), "File should not have been deleted:" + tempFile3); Assert.IsTrue(File.Exists(tempFile4), "File should not have been deleted:" + tempFile4); Assert.IsTrue(File.Exists(tempFile5), "File should not have been deleted:" + tempFile5); Assert.IsFalse(File.Exists(tempFile6), "File should have been deleted:" + tempFile6); Assert.IsTrue(File.Exists(tempFile7), "File should not have been deleted:" + tempFile7); Assert.IsTrue(Directory.Exists(tempDir1), "Dir should not have been deleted:" + tempDir1); Assert.IsTrue(Directory.Exists(tempDir2), "Dir should not have been deleted:" + tempDir2); Assert.IsTrue(Directory.Exists(tempDir3), "Dir should not have been deleted:" + tempDir3); Assert.IsTrue(Directory.Exists(tempDir4), "Dir should not have been deleted:" + tempDir4); RunBuild(String.Format(CultureInfo.InvariantCulture, _xmlProjectTemplate, "dir", tempDir2)); Assert.IsTrue(File.Exists(tempFile1), "File should not have been deleted:" + tempFile1); Assert.IsTrue(File.Exists(tempFile2), "File should not have been deleted:" + tempFile2); Assert.IsFalse(File.Exists(tempFile3), "File should have been deleted:" + tempFile3); Assert.IsTrue(File.Exists(tempFile4), "File should not have been deleted:" + tempFile4); Assert.IsTrue(File.Exists(tempFile5), "File should not have been deleted:" + tempFile5); Assert.IsFalse(File.Exists(tempFile6), "File should have been deleted:" + tempFile6); Assert.IsTrue(File.Exists(tempFile7), "File should not have been deleted:" + tempFile7); Assert.IsTrue(Directory.Exists(tempDir1), "Dir should not have been deleted:" + tempDir1); Assert.IsFalse(Directory.Exists(tempDir2), "Dir should have been deleted:" + tempDir2); Assert.IsTrue(Directory.Exists(tempDir3), "Dir should not have been deleted:" + tempDir3); Assert.IsTrue(Directory.Exists(tempDir4), "Dir should not have been deleted:" + tempDir4); RunBuild(String.Format(CultureInfo.InvariantCulture, _xmlProjectTemplate, "file", tempFile1 )); Assert.IsFalse(File.Exists(tempFile1), "File should have been deleted:" + tempFile1); Assert.IsTrue(File.Exists(tempFile2), "File should not have been deleted:" + tempFile2); Assert.IsFalse(File.Exists(tempFile3), "File should have been deleted:" + tempFile3); Assert.IsTrue(File.Exists(tempFile4), "File should not have been deleted:" + tempFile4); Assert.IsTrue(File.Exists(tempFile5), "File should not have been deleted:" + tempFile5); Assert.IsFalse(File.Exists(tempFile6), "File should have been deleted:" + tempFile6); Assert.IsTrue(File.Exists(tempFile7), "File should not have been deleted:" + tempFile7); Assert.IsTrue(Directory.Exists(tempDir1), "Dir should not have been deleted:" + tempDir1); Assert.IsFalse(Directory.Exists(tempDir2), "Dir should have been deleted:" + tempDir2); Assert.IsTrue(Directory.Exists(tempDir3), "Dir should not have been deleted:" + tempDir3); Assert.IsTrue(Directory.Exists(tempDir4), "Dir should not have been deleted:" + tempDir4); } /// /// Checks whether an include pattern (without wildcards) that matches /// a directory containing both files an directories, will NOT cause /// that directory to be removed. /// [Test] public void Test_DeleteFileSet2() { string xmlProjectTemplateFileSet = @" "; RunBuild(string.Format(CultureInfo.InvariantCulture, xmlProjectTemplateFileSet, TempDirName, "a.b")); Assert.IsTrue(File.Exists(tempFile1), "File should not have been deleted:" + tempFile1); Assert.IsTrue(File.Exists(tempFile2), "File should not have been deleted:" + tempFile2); Assert.IsTrue(File.Exists(tempFile3), "File should not have been deleted:" + tempFile3); Assert.IsTrue(File.Exists(tempFile4), "File should not have been deleted:" + tempFile4); Assert.IsTrue(File.Exists(tempFile5), "File should not have been deleted:" + tempFile5); Assert.IsTrue(File.Exists(tempFile6), "File should not have been deleted:" + tempFile6); Assert.IsTrue(File.Exists(tempFile7), "File should not have been deleted:" + tempFile7); Assert.IsTrue(File.Exists(tempFile8), "File should not have been deleted:" + tempFile8); Assert.IsTrue(Directory.Exists(tempDir1), "Dir should not have been deleted:" + tempDir1); Assert.IsTrue(Directory.Exists(tempDir2), "Dir should not have been deleted:" + tempDir2); Assert.IsTrue(Directory.Exists(tempDir3), "Dir should not have been deleted:" + tempDir3); Assert.IsTrue(Directory.Exists(tempDir4), "Dir should not have been deleted:" + tempDir4); Assert.IsTrue(Directory.Exists(tempDir5), "Dir should not have been deleted:" + tempDir5); Assert.IsTrue(Directory.Exists(tempDir6), "Dir should not have been deleted:" + tempDir6); Assert.IsTrue(Directory.Exists(tempDir7), "Dir should not have been deleted:" + tempDir7); Assert.IsTrue(Directory.Exists(tempDir8), "Dir should not have been deleted:" + tempDir8); } /// /// Checks whether an include pattern (without wildcards) that matches /// a directory containing subdirectories, will NOT cause that directory /// to be removed. /// [Test] public void Test_DeleteFileSet3() { string xmlProjectTemplateFileSet = @" "; RunBuild(string.Format(CultureInfo.InvariantCulture, xmlProjectTemplateFileSet, TempDirName, "a.d")); Assert.IsTrue(File.Exists(tempFile1), "File should not have been deleted:" + tempFile1); Assert.IsTrue(File.Exists(tempFile2), "File should not have been deleted:" + tempFile2); Assert.IsTrue(File.Exists(tempFile3), "File should not have been deleted:" + tempFile3); Assert.IsTrue(File.Exists(tempFile4), "File should not have been deleted:" + tempFile4); Assert.IsTrue(File.Exists(tempFile5), "File should not have been deleted:" + tempFile5); Assert.IsTrue(File.Exists(tempFile6), "File should not have been deleted:" + tempFile6); Assert.IsTrue(File.Exists(tempFile7), "File should not have been deleted:" + tempFile7); Assert.IsTrue(File.Exists(tempFile8), "File should not have been deleted:" + tempFile8); Assert.IsTrue(Directory.Exists(tempDir1), "Dir should not have been deleted:" + tempDir1); Assert.IsTrue(Directory.Exists(tempDir2), "Dir should not have been deleted:" + tempDir2); Assert.IsTrue(Directory.Exists(tempDir3), "Dir should not have been deleted:" + tempDir3); Assert.IsTrue(Directory.Exists(tempDir4), "Dir should not have been deleted:" + tempDir4); Assert.IsTrue(Directory.Exists(tempDir5), "Dir should not have been deleted:" + tempDir5); Assert.IsTrue(Directory.Exists(tempDir6), "Dir should not have been deleted:" + tempDir6); Assert.IsTrue(Directory.Exists(tempDir7), "Dir should not have been deleted:" + tempDir7); Assert.IsTrue(Directory.Exists(tempDir8), "Dir should not have been deleted:" + tempDir8); } /// /// Checks whether an include pattern (without wildcards) that matches /// a directory containing files, will NOT cause that directory to be /// removed. /// [Test] public void Test_DeleteFileSet4() { string xmlProjectTemplateFileSet = @" "; /// Checks whether an include pattern (without wildcards) that matches /// a directory containing files, will NOT cause that directory to be /// removed. RunBuild(string.Format(CultureInfo.InvariantCulture, xmlProjectTemplateFileSet, TempDirName, "a.e")); Assert.IsTrue(File.Exists(tempFile1), "File should not have been deleted:" + tempFile1); Assert.IsTrue(File.Exists(tempFile2), "File should not have been deleted:" + tempFile2); Assert.IsTrue(File.Exists(tempFile3), "File should not have been deleted:" + tempFile3); Assert.IsTrue(File.Exists(tempFile4), "File should not have been deleted:" + tempFile4); Assert.IsTrue(File.Exists(tempFile5), "File should not have been deleted:" + tempFile5); Assert.IsTrue(File.Exists(tempFile6), "File should not have been deleted:" + tempFile6); Assert.IsTrue(File.Exists(tempFile7), "File should not have been deleted:" + tempFile7); Assert.IsTrue(File.Exists(tempFile8), "File should not have been deleted:" + tempFile8); Assert.IsTrue(Directory.Exists(tempDir1), "Dir should not have been deleted:" + tempDir1); Assert.IsTrue(Directory.Exists(tempDir2), "Dir should not have been deleted:" + tempDir2); Assert.IsTrue(Directory.Exists(tempDir3), "Dir should not have been deleted:" + tempDir3); Assert.IsTrue(Directory.Exists(tempDir4), "Dir should not have been deleted:" + tempDir4); Assert.IsTrue(Directory.Exists(tempDir5), "Dir should not have been deleted:" + tempDir5); Assert.IsTrue(Directory.Exists(tempDir6), "Dir should not have been deleted:" + tempDir6); Assert.IsTrue(Directory.Exists(tempDir7), "Dir should not have been deleted:" + tempDir7); Assert.IsTrue(Directory.Exists(tempDir8), "Dir should not have been deleted:" + tempDir8); /// Checks whether removing the last file from a directory, with a /// pattern that does not match the directory itself, will not CAUSE /// that directory to be removed. RunBuild(string.Format(CultureInfo.InvariantCulture, xmlProjectTemplateFileSet, TempDirName, "a.e/a.ee")); Assert.IsTrue(File.Exists(tempFile1), "File should not have been deleted:" + tempFile1); Assert.IsTrue(File.Exists(tempFile2), "File should not have been deleted:" + tempFile2); Assert.IsTrue(File.Exists(tempFile3), "File should not have been deleted:" + tempFile3); Assert.IsTrue(File.Exists(tempFile4), "File should not have been deleted:" + tempFile4); Assert.IsTrue(File.Exists(tempFile5), "File should not have been deleted:" + tempFile5); Assert.IsTrue(File.Exists(tempFile6), "File should not have been deleted:" + tempFile6); Assert.IsTrue(File.Exists(tempFile7), "File should not have been deleted:" + tempFile7); Assert.IsFalse(File.Exists(tempFile8), "File should have been deleted:" + tempFile8); Assert.IsTrue(Directory.Exists(tempDir1), "Dir should not have been deleted:" + tempDir1); Assert.IsTrue(Directory.Exists(tempDir2), "Dir should not have been deleted:" + tempDir2); Assert.IsTrue(Directory.Exists(tempDir3), "Dir should not have been deleted:" + tempDir3); Assert.IsTrue(Directory.Exists(tempDir4), "Dir should not have been deleted:" + tempDir4); Assert.IsTrue(Directory.Exists(tempDir5), "Dir should not have been deleted:" + tempDir5); Assert.IsTrue(Directory.Exists(tempDir6), "Dir should not have been deleted:" + tempDir6); Assert.IsTrue(Directory.Exists(tempDir7), "Dir should not have been deleted:" + tempDir7); Assert.IsTrue(Directory.Exists(tempDir8), "Dir should not have been deleted:" + tempDir8); /// Checks whether an include pattern that matches all files in an /// empty directory, will NOT cause that directory to be removed. RunBuild(string.Format(CultureInfo.InvariantCulture, xmlProjectTemplateFileSet, TempDirName, "a.e/**/*")); Assert.IsTrue(File.Exists(tempFile1), "File should not have been deleted:" + tempFile1); Assert.IsTrue(File.Exists(tempFile2), "File should not have been deleted:" + tempFile2); Assert.IsTrue(File.Exists(tempFile3), "File should not have been deleted:" + tempFile3); Assert.IsTrue(File.Exists(tempFile4), "File should not have been deleted:" + tempFile4); Assert.IsTrue(File.Exists(tempFile5), "File should not have been deleted:" + tempFile5); Assert.IsTrue(File.Exists(tempFile6), "File should not have been deleted:" + tempFile6); Assert.IsTrue(File.Exists(tempFile7), "File should not have been deleted:" + tempFile7); Assert.IsFalse(File.Exists(tempFile8), "File should have been deleted in previous step:" + tempFile8); Assert.IsTrue(Directory.Exists(tempDir1), "Dir should not have been deleted:" + tempDir1); Assert.IsTrue(Directory.Exists(tempDir2), "Dir should not have been deleted:" + tempDir2); Assert.IsTrue(Directory.Exists(tempDir3), "Dir should not have been deleted:" + tempDir3); Assert.IsTrue(Directory.Exists(tempDir4), "Dir should not have been deleted:" + tempDir4); Assert.IsTrue(Directory.Exists(tempDir5), "Dir should not have been deleted:" + tempDir5); Assert.IsTrue(Directory.Exists(tempDir6), "Dir should not have been deleted:" + tempDir6); Assert.IsTrue(Directory.Exists(tempDir7), "Dir should not have been deleted:" + tempDir7); Assert.IsTrue(Directory.Exists(tempDir8), "Dir should not have been deleted:" + tempDir8); /// Checks whether an include pattern that matches all files in a /// empty directory and the directory itself, will cause that /// directory to be removed. RunBuild(string.Format(CultureInfo.InvariantCulture, xmlProjectTemplateFileSet, TempDirName, "a.e/**")); Assert.IsTrue(File.Exists(tempFile1), "File should not have been deleted:" + tempFile1); Assert.IsTrue(File.Exists(tempFile2), "File should not have been deleted:" + tempFile2); Assert.IsTrue(File.Exists(tempFile3), "File should not have been deleted:" + tempFile3); Assert.IsTrue(File.Exists(tempFile4), "File should not have been deleted:" + tempFile4); Assert.IsTrue(File.Exists(tempFile5), "File should not have been deleted:" + tempFile5); Assert.IsTrue(File.Exists(tempFile6), "File should not have been deleted:" + tempFile6); Assert.IsTrue(File.Exists(tempFile7), "File should not have been deleted:" + tempFile7); Assert.IsFalse(File.Exists(tempFile8), "File should have been deleted in previous step:" + tempFile8); Assert.IsTrue(Directory.Exists(tempDir1), "Dir should not have been deleted:" + tempDir1); Assert.IsTrue(Directory.Exists(tempDir2), "Dir should not have been deleted:" + tempDir2); Assert.IsTrue(Directory.Exists(tempDir3), "Dir should not have been deleted:" + tempDir3); Assert.IsTrue(Directory.Exists(tempDir4), "Dir should not have been deleted:" + tempDir4); Assert.IsTrue(Directory.Exists(tempDir5), "Dir should not have been deleted:" + tempDir5); Assert.IsTrue(Directory.Exists(tempDir6), "Dir should not have been deleted:" + tempDir6); Assert.IsTrue(Directory.Exists(tempDir7), "Dir should not have been deleted:" + tempDir7); Assert.IsFalse(Directory.Exists(tempDir8), "Dir should have been deleted:" + tempDir8); } /// /// Checks whether an include pattern that matches all files in a /// non-empty directory (and its subdirectories) and that directory /// itself, will cause that directory to be removed. /// [Test] public void Test_DeleteFileSet5() { string xmlProjectTemplateFileSet = @" "; RunBuild(string.Format(CultureInfo.InvariantCulture, xmlProjectTemplateFileSet, TempDirName, "a.e/**")); Assert.IsTrue(File.Exists(tempFile1), "File should not have been deleted:" + tempFile1); Assert.IsTrue(File.Exists(tempFile2), "File should not have been deleted:" + tempFile2); Assert.IsTrue(File.Exists(tempFile3), "File should not have been deleted:" + tempFile3); Assert.IsTrue(File.Exists(tempFile4), "File should not have been deleted:" + tempFile4); Assert.IsTrue(File.Exists(tempFile5), "File should not have been deleted:" + tempFile5); Assert.IsTrue(File.Exists(tempFile6), "File should not have been deleted:" + tempFile6); Assert.IsTrue(File.Exists(tempFile7), "File should not have been deleted:" + tempFile7); Assert.IsFalse(File.Exists(tempFile8), "File should have been deleted:" + tempFile8); Assert.IsTrue(Directory.Exists(tempDir1), "Dir should not have been deleted:" + tempDir1); Assert.IsTrue(Directory.Exists(tempDir2), "Dir should not have been deleted:" + tempDir2); Assert.IsTrue(Directory.Exists(tempDir3), "Dir should not have been deleted:" + tempDir3); Assert.IsTrue(Directory.Exists(tempDir4), "Dir should not have been deleted:" + tempDir4); Assert.IsTrue(Directory.Exists(tempDir5), "Dir should not have been deleted:" + tempDir5); Assert.IsTrue(Directory.Exists(tempDir6), "Dir should not have been deleted:" + tempDir6); Assert.IsTrue(Directory.Exists(tempDir7), "Dir should not have been deleted:" + tempDir7); Assert.IsFalse(Directory.Exists(tempDir8), "Dir should have been deleted:" + tempDir8); } /// /// Checks whether an include pattern that matches all files in the base /// directory (and its subdirectories), will NOT cause that directory /// to be removed. /// [Test] public void Test_DeleteFileSet6() { string xmlProjectTemplateFileSet = @" "; RunBuild(string.Format(CultureInfo.InvariantCulture, xmlProjectTemplateFileSet, tempDir1, "**/*")); Assert.IsFalse(File.Exists(tempFile1), "File should have been deleted:" + tempFile1); Assert.IsFalse(File.Exists(tempFile2), "File should have been deleted:" + tempFile2); Assert.IsFalse(File.Exists(tempFile3), "File should have been deleted:" + tempFile3); Assert.IsFalse(File.Exists(tempFile4), "File should have been deleted:" + tempFile4); Assert.IsFalse(File.Exists(tempFile5), "File should have been deleted:" + tempFile5); Assert.IsFalse(File.Exists(tempFile6), "File should have been deleted:" + tempFile6); Assert.IsFalse(File.Exists(tempFile7), "File should have been deleted:" + tempFile7); Assert.IsTrue(File.Exists(tempFile8), "File should not have been deleted:" + tempFile8); Assert.IsTrue(Directory.Exists(tempDir1), "Dir should not have been deleted:" + tempDir1); Assert.IsFalse(Directory.Exists(tempDir2), "Dir should have been deleted:" + tempDir2); Assert.IsFalse(Directory.Exists(tempDir3), "Dir should have been deleted:" + tempDir3); Assert.IsFalse(Directory.Exists(tempDir4), "Dir should have been deleted:" + tempDir4); Assert.IsTrue(Directory.Exists(tempDir5), "Dir should not have been deleted:" + tempDir5); Assert.IsTrue(Directory.Exists(tempDir6), "Dir should not have been deleted:" + tempDir6); Assert.IsTrue(Directory.Exists(tempDir7), "Dir should not have been deleted:" + tempDir7); Assert.IsTrue(Directory.Exists(tempDir8), "Dir should not have been deleted:" + tempDir8); } [Test] public void Test_DeleteFileSet7() { string xmlProjectTemplateFileSet = @" "; // pattern should match both directories and files named "boo" RunBuild(string.Format(CultureInfo.InvariantCulture, xmlProjectTemplateFileSet, TempDirName, "**/boo")); Assert.IsTrue(File.Exists(tempFile1), "File should not have been deleted:" + tempFile1); Assert.IsTrue(File.Exists(tempFile2), "File should not have been deleted:" + tempFile2); Assert.IsTrue(File.Exists(tempFile3), "File should not have been deleted:" + tempFile3); Assert.IsTrue(File.Exists(tempFile4), "File should not have been deleted:" + tempFile4); Assert.IsTrue(File.Exists(tempFile5), "File should not have been deleted:" + tempFile5); Assert.IsTrue(File.Exists(tempFile6), "File should not have been deleted:" + tempFile6); Assert.IsTrue(File.Exists(tempFile7), "File should not have been deleted:" + tempFile7); Assert.IsTrue(File.Exists(tempFile8), "File should not have been deleted:" + tempFile8); Assert.IsTrue(File.Exists(tempFile9), "File should not have been deleted:" + tempFile9); Assert.IsFalse(File.Exists(tempFile10), "File should have been deleted:" + tempFile10); Assert.IsTrue(Directory.Exists(tempDir1), "Dir should not have been deleted:" + tempDir1); Assert.IsTrue(Directory.Exists(tempDir2), "Dir should not have been deleted:" + tempDir2); Assert.IsTrue(Directory.Exists(tempDir3), "Dir should not have been deleted:" + tempDir3); Assert.IsTrue(Directory.Exists(tempDir4), "Dir should not have been deleted:" + tempDir4); Assert.IsTrue(Directory.Exists(tempDir5), "Dir should not have been deleted:" + tempDir5); Assert.IsTrue(Directory.Exists(tempDir6), "Dir should not have been deleted:" + tempDir6); Assert.IsFalse(Directory.Exists(tempDir7), "Dir should have been deleted:" + tempDir7); Assert.IsTrue(Directory.Exists(tempDir8), "Dir should not have been deleted:" + tempDir8); } [Test] public void Test_ExcludePattern1() { string xmlProjectTemplateFileSet = @" "; RunBuild(string.Format(CultureInfo.InvariantCulture, xmlProjectTemplateFileSet, tempDir1)); Assert.IsTrue(File.Exists(tempFile1), "File should have been deleted:" + tempFile1); Assert.IsTrue(File.Exists(tempFile2), "File should have been deleted:" + tempFile2); Assert.IsTrue(File.Exists(tempFile3), "File should have been deleted:" + tempFile3); Assert.IsFalse(File.Exists(tempFile4), "File should have been deleted:" + tempFile4); Assert.IsFalse(File.Exists(tempFile5), "File should have been deleted:" + tempFile5); Assert.IsFalse(File.Exists(tempFile6), "File should have been deleted:" + tempFile6); Assert.IsTrue(File.Exists(tempFile7), "File should not have been deleted:" + tempFile7); Assert.IsTrue(File.Exists(tempFile8), "File should not have been deleted:" + tempFile8); Assert.IsTrue(Directory.Exists(tempDir1), "Dir should not have been deleted:" + tempDir1); Assert.IsTrue(Directory.Exists(tempDir2), "Dir should not have been deleted:" + tempDir2); Assert.IsTrue(Directory.Exists(tempDir3), "Dir should not have been deleted:" + tempDir3); Assert.IsFalse(Directory.Exists(tempDir4), "Dir should have been deleted:" + tempDir4); Assert.IsTrue(Directory.Exists(tempDir5), "Dir should not have been deleted:" + tempDir5); Assert.IsTrue(Directory.Exists(tempDir6), "Dir should not have been deleted:" + tempDir6); Assert.IsTrue(Directory.Exists(tempDir7), "Dir should not have been deleted:" + tempDir7); Assert.IsTrue(Directory.Exists(tempDir8), "Dir should not have been deleted:" + tempDir8); } [Test] public void Test_ExcludePattern1_NoIncludeEmptyDirs() { string xmlProjectTemplateFileSet = @" "; RunBuild(string.Format(CultureInfo.InvariantCulture, xmlProjectTemplateFileSet, tempDir1)); Assert.IsTrue(File.Exists(tempFile1), "File should have been deleted:" + tempFile1); Assert.IsTrue(File.Exists(tempFile2), "File should have been deleted:" + tempFile2); Assert.IsTrue(File.Exists(tempFile3), "File should have been deleted:" + tempFile3); Assert.IsFalse(File.Exists(tempFile4), "File should have been deleted:" + tempFile4); Assert.IsFalse(File.Exists(tempFile5), "File should have been deleted:" + tempFile5); Assert.IsFalse(File.Exists(tempFile6), "File should have been deleted:" + tempFile6); Assert.IsTrue(File.Exists(tempFile7), "File should not have been deleted:" + tempFile7); Assert.IsTrue(File.Exists(tempFile8), "File should not have been deleted:" + tempFile8); Assert.IsTrue(Directory.Exists(tempDir1), "Dir should not have been deleted:" + tempDir1); Assert.IsTrue(Directory.Exists(tempDir2), "Dir should not have been deleted:" + tempDir2); Assert.IsTrue(Directory.Exists(tempDir3), "Dir should not have been deleted:" + tempDir3); Assert.IsTrue(Directory.Exists(tempDir4), "Dir should not have been deleted:" + tempDir4); Assert.IsTrue(Directory.Exists(tempDir5), "Dir should not have been deleted:" + tempDir5); Assert.IsTrue(Directory.Exists(tempDir6), "Dir should not have been deleted:" + tempDir6); Assert.IsTrue(Directory.Exists(tempDir7), "Dir should not have been deleted:" + tempDir7); Assert.IsTrue(Directory.Exists(tempDir8), "Dir should not have been deleted:" + tempDir8); } [Test] public void Test_ExcludePattern2() { string xmlProjectTemplateFileSet = @" "; RunBuild(string.Format(CultureInfo.InvariantCulture, xmlProjectTemplateFileSet, TempDirName)); Assert.IsFalse(File.Exists(tempFile1), "File should have been deleted:" + tempFile1); Assert.IsFalse(File.Exists(tempFile2), "File should have been deleted:" + tempFile2); Assert.IsFalse(File.Exists(tempFile3), "File should have been deleted:" + tempFile3); Assert.IsFalse(File.Exists(tempFile4), "File should have been deleted:" + tempFile4); Assert.IsFalse(File.Exists(tempFile5), "File should have been deleted:" + tempFile5); Assert.IsFalse(File.Exists(tempFile6), "File should have been deleted:" + tempFile6); Assert.IsFalse(File.Exists(tempFile7), "File should have been deleted:" + tempFile7); Assert.IsTrue(File.Exists(tempFile8), "File should not have been deleted:" + tempFile8); Assert.IsFalse(Directory.Exists(tempDir1), "Dir should have been deleted:" + tempDir1); Assert.IsFalse(Directory.Exists(tempDir2), "Dir should have been deleted:" + tempDir2); Assert.IsFalse(Directory.Exists(tempDir3), "Dir should have been deleted:" + tempDir3); Assert.IsFalse(Directory.Exists(tempDir4), "Dir should have been deleted:" + tempDir4); Assert.IsFalse(Directory.Exists(tempDir5), "Dir should have been deleted:" + tempDir5); Assert.IsFalse(Directory.Exists(tempDir6), "Dir should have been deleted:" + tempDir6); Assert.IsFalse(Directory.Exists(tempDir7), "Dir should have been deleted:" + tempDir7); Assert.IsTrue(Directory.Exists(tempDir8), "Dir should not have been deleted:" + tempDir8); } [Test] public void Test_ExcludePattern2_NoIncludeEmptyDirs() { string xmlProjectTemplateFileSet = @" "; RunBuild(string.Format(CultureInfo.InvariantCulture, xmlProjectTemplateFileSet, TempDirName)); Assert.IsFalse(File.Exists(tempFile1), "File should have been deleted:" + tempFile1); Assert.IsFalse(File.Exists(tempFile2), "File should have been deleted:" + tempFile2); Assert.IsFalse(File.Exists(tempFile3), "File should have been deleted:" + tempFile3); Assert.IsFalse(File.Exists(tempFile4), "File should have been deleted:" + tempFile4); Assert.IsFalse(File.Exists(tempFile5), "File should have been deleted:" + tempFile5); Assert.IsFalse(File.Exists(tempFile6), "File should have been deleted:" + tempFile6); Assert.IsFalse(File.Exists(tempFile7), "File should have been deleted:" + tempFile7); Assert.IsTrue(File.Exists(tempFile8), "File should not have been deleted:" + tempFile8); Assert.IsTrue(Directory.Exists(tempDir1), "Dir should not have been deleted:" + tempDir1); Assert.IsTrue(Directory.Exists(tempDir2), "Dir should not have been deleted:" + tempDir2); Assert.IsTrue(Directory.Exists(tempDir3), "Dir should not have been deleted:" + tempDir3); Assert.IsTrue(Directory.Exists(tempDir4), "Dir should not have been deleted:" + tempDir4); Assert.IsTrue(Directory.Exists(tempDir5), "Dir should not have been deleted:" + tempDir5); Assert.IsTrue(Directory.Exists(tempDir6), "Dir should not have been deleted:" + tempDir6); Assert.IsTrue(Directory.Exists(tempDir7), "Dir should not have been deleted:" + tempDir7); Assert.IsTrue(Directory.Exists(tempDir8), "Dir should not have been deleted:" + tempDir8); } [Test] public void Test_ExcludePattern3() { string xmlProjectTemplateFileSet = @" "; RunBuild(string.Format(CultureInfo.InvariantCulture, xmlProjectTemplateFileSet, TempDirName)); Assert.IsFalse(File.Exists(tempFile1), "File should have been deleted:" + tempFile1); Assert.IsFalse(File.Exists(tempFile2), "File should have been deleted:" + tempFile2); Assert.IsFalse(File.Exists(tempFile3), "File should have been deleted:" + tempFile3); Assert.IsFalse(File.Exists(tempFile4), "File should have been deleted:" + tempFile4); Assert.IsFalse(File.Exists(tempFile5), "File should have been deleted:" + tempFile5); Assert.IsFalse(File.Exists(tempFile6), "File should have been deleted:" + tempFile6); Assert.IsFalse(File.Exists(tempFile7), "File should have been deleted:" + tempFile7); Assert.IsFalse(File.Exists(tempFile8), "File should have been deleted:" + tempFile8); Assert.IsFalse(Directory.Exists(tempDir1), "Dir should have been deleted:" + tempDir1); Assert.IsFalse(Directory.Exists(tempDir2), "Dir should have been deleted:" + tempDir2); Assert.IsFalse(Directory.Exists(tempDir3), "Dir should have been deleted:" + tempDir3); Assert.IsFalse(Directory.Exists(tempDir4), "Dir should have been deleted:" + tempDir4); Assert.IsFalse(Directory.Exists(tempDir5), "Dir should have been deleted:" + tempDir5); Assert.IsFalse(Directory.Exists(tempDir6), "Dir should have been deleted:" + tempDir6); Assert.IsFalse(Directory.Exists(tempDir7), "Dir should have been deleted:" + tempDir7); Assert.IsFalse(Directory.Exists(tempDir8), "Dir should have been deleted:" + tempDir8); } [Test] public void Test_ExcludePattern3_NoIncludeEmptyDirs() { string xmlProjectTemplateFileSet = @" "; RunBuild(string.Format(CultureInfo.InvariantCulture, xmlProjectTemplateFileSet, TempDirName)); Assert.IsFalse(File.Exists(tempFile1), "File should have been deleted:" + tempFile1); Assert.IsFalse(File.Exists(tempFile2), "File should have been deleted:" + tempFile2); Assert.IsFalse(File.Exists(tempFile3), "File should have been deleted:" + tempFile3); Assert.IsFalse(File.Exists(tempFile4), "File should have been deleted:" + tempFile4); Assert.IsFalse(File.Exists(tempFile5), "File should have been deleted:" + tempFile5); Assert.IsFalse(File.Exists(tempFile6), "File should have been deleted:" + tempFile6); Assert.IsFalse(File.Exists(tempFile7), "File should have been deleted:" + tempFile7); Assert.IsFalse(File.Exists(tempFile8), "File should have been deleted:" + tempFile8); Assert.IsTrue(Directory.Exists(tempDir1), "Dir should not have been deleted:" + tempDir1); Assert.IsTrue(Directory.Exists(tempDir2), "Dir should not have been deleted:" + tempDir2); Assert.IsTrue(Directory.Exists(tempDir3), "Dir should not have been deleted:" + tempDir3); Assert.IsTrue(Directory.Exists(tempDir4), "Dir should not have been deleted:" + tempDir4); Assert.IsTrue(Directory.Exists(tempDir5), "Dir should not have been deleted:" + tempDir5); Assert.IsTrue(Directory.Exists(tempDir6), "Dir should not have been deleted:" + tempDir6); Assert.IsTrue(Directory.Exists(tempDir7), "Dir should not have been deleted:" + tempDir7); Assert.IsTrue(Directory.Exists(tempDir8), "Dir should not have been deleted:" + tempDir8); } [Test] public void Test_NonExistingFile() { string xmlProject = @" "; RunBuild(xmlProject); } [Test] public void Test_NonExistingDirectory() { string xmlProject = @" "; RunBuild(xmlProject); } } } nant-0.92-rc1/tests/NAnt.Core/Tasks/LoadTasksTest.cs0000644000175000017500000000742311757302275022072 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2002 Ian MacLean (Ian_maclean@another.com) // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Ian MacLean (Ian_maclean@another.com) using System; using System.IO; using System.Reflection; using System.Text; using System.Xml; using System.Globalization; using NUnit.Framework; using NAnt.Core; namespace Tests.NAnt.Core.Tasks { /// /// Load Tasks Test. /// [TestFixture] public class LoadTasksTest : BuildTestBase { [SetUp] protected override void SetUp() { base.SetUp(); } [Test] public void Test_AssemblyNotExists() { const string _xml = @" "; try { RunBuild(_xml); Assert.Fail("Invalid assembly path did not generate an exception"); } catch (TestBuildException be) { if( be.InnerException.Message.IndexOf("'does not exist") != -1) { Assert.Fail("Wrong type of exception; does not contain words 'does not exist'! " + Environment.NewLine + be.ToString()); } } catch { Assert.Fail("Incorrect exception type !"); } } [Test] public void Test_IncorrectArgs() { const string _xml = @" "; try { RunBuild(_xml); Assert.Fail("Invalid attribute combination did not generate an exception"); } catch (TestBuildException e) { if (!(e.InnerException is BuildException)) Assert.Fail("Incorrect exception type !"); } catch { Assert.Fail("Incorrect exception type !"); } } /// /// Check whether the filename of the assembly that caused the failure /// is part of the build failure message. /// public void Test_AssemblyLoadFailure() { string tempFile = CreateTempFile("test.dll"); const string _xml = @" "; try { RunBuild(string.Format(CultureInfo.InvariantCulture, _xml, tempFile)); Assert.Fail("LoadTasks should have failed"); } catch (TestBuildException e) { if (!(e.InnerException is BuildException)) { Assert.Fail("Incorrect exception type !"); } else { BuildException buildError = (BuildException) e.InnerException; Assert.IsTrue(buildError.Message.IndexOf("test.dll") != -1, "Assembly causing failure is not part of message."); } } } } }nant-0.92-rc1/tests/NAnt.Core/Tasks/CopyTest.cs0000644000175000017500000006732711757302275021130 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2002-2003 Scott Hernandez (ScottHernandez@hotmail.com) // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Scott Hernandez (ScottHernandez@hotmail.com) using System; using System.IO; using System.Reflection; using System.Text; using System.Xml; using System.Globalization; using NUnit.Framework; using NAnt.Core; namespace Tests.NAnt.Core.Tasks { /// /// Tests the deletion of the following: /// /// /// file /// folder /// folder with a file (recursive) /// /// /// /// This test should also test for failures, like permission errors, and filesets [TestFixture] public class CopyTest : BuildTestBase { const string _xmlProjectTemplate = @" "; const string _xmlProjectTemplate2 = @" "; const string _xmlProjectTemplate3 = @" "; const string _xmlProjectTemplate4 = @" "; string tempFile1, tempFile2, tempFile3, tempFile4, tempFile5, tempFile6, tempFile7; string tempDir1, tempDir2, tempDir3, tempDir4, tempDir5; /// /// Creates a structure like so: /// a.b\ /// a.bb /// a.bc /// foo\* /// x.x /// goo\* /// x\ /// y.y /// ha.he /// ha.he2* /// ha.he3* /// empty\ -- note: empty directory /// [SetUp] protected override void SetUp() { base.SetUp(); tempDir1 = CreateTempDir("a.b"); tempDir2 = CreateTempDir(Path.Combine(tempDir1, "foo")); tempDir3 = CreateTempDir(Path.Combine(tempDir1, "goo")); tempDir4 = CreateTempDir(Path.Combine(tempDir1, Path.Combine(tempDir3, "x"))); tempDir5 = CreateTempDir(Path.Combine(tempDir1, "empty")); tempFile1 = CreateTempFile(Path.Combine(tempDir1, "a.bb")); tempFile2 = CreateTempFile(Path.Combine(tempDir1, "a.bc")); tempFile3 = CreateTempFile(Path.Combine(tempDir2, "x.x")); tempFile4 = CreateTempFile(Path.Combine(tempDir4, "y.y")); tempFile5 = CreateTempFile(Path.Combine(tempDir3, "ha.he")); tempFile6 = CreateTempFile(Path.Combine(tempDir3, "ha.he2")); tempFile7 = CreateTempFile(Path.Combine(tempDir3, "ha.he3")); File.SetAttributes(tempDir2, FileAttributes.ReadOnly); File.SetAttributes(tempDir3, FileAttributes.ReadOnly); File.SetAttributes(Path.Combine(tempDir3, "ha.he3"), FileAttributes.ReadOnly); File.SetAttributes(Path.Combine(tempDir3, "ha.he2"), FileAttributes.ReadOnly); } private string GetPath(string rootPath, params string[] fileParts) { string path = rootPath; foreach (string filePart in fileParts) { path = Path.Combine(path, Path.GetFileName(filePart)); } return path; } /// /// Copy only the directory given. /// [Test] public void Test_Copy_Only_Directory() { string dest = CreateTempDir("a.99"); RunBuild(string.Format(CultureInfo.InvariantCulture, _xmlProjectTemplate, dest, tempDir1, string.Empty)); Assert.IsFalse(File.Exists(GetPath(dest,tempDir1,tempFile1)), "File should not have been created:" + tempFile1); Assert.IsFalse(File.Exists(GetPath(dest,tempDir1,tempFile2)), "File should not have been created:" + tempFile2); Assert.IsFalse(File.Exists(GetPath(dest,tempDir1,tempDir2,tempFile3)), "File should not have been created:" + tempFile3); Assert.IsFalse(File.Exists(GetPath(dest,tempDir1,tempDir3,tempDir4,tempFile4)), "File should not have been created:" + tempFile4); Assert.IsFalse(File.Exists(GetPath(dest,tempDir1,tempDir3,tempFile5)), "File should not have been created:" + tempFile5); Assert.IsFalse(File.Exists(GetPath(dest,tempDir1,tempDir3,tempFile6)), "File should not have been created:" + tempFile6); Assert.IsFalse(File.Exists(GetPath(dest,tempDir1,tempDir3,tempFile7)), "File should not have been created:" + tempFile7); Assert.IsTrue(Directory.Exists(GetPath(dest,tempDir1)), "Dir should have been created:" + tempDir1); Assert.IsFalse(Directory.Exists(GetPath(dest,tempDir1,tempDir2)), "Dir should not have been created:" + tempDir2); Assert.IsFalse(Directory.Exists(GetPath(dest,tempDir1,tempDir3)), "Dir should not have been created:" + tempDir3); Assert.IsFalse(Directory.Exists(GetPath(dest,tempDir1,tempDir3,tempDir4)), "Dir should not have been created:" + tempDir4); Assert.IsFalse(Directory.Exists(GetPath(dest,tempDir1,tempDir5)), "Dir should not have been created:" + tempDir5); } /// /// Ensure that an invalid path for destination directory causes a /// to be thrown. /// [Test] public void Test_Copy_InvalidDestinationDirectory() { if (!PlatformHelper.IsUnix) { try { RunBuild(string.Format(CultureInfo.InvariantCulture, _xmlProjectTemplate, "|", tempDir1, string.Empty)); // have the test fail Assert.Fail("Build should have failed."); } catch (TestBuildException ex) { // assert that a BuildException was the cause of the TestBuildException Assert.IsTrue((ex.InnerException != null && ex.InnerException.GetType() == typeof(BuildException))); } } } /// /// Copy everything from under tempDir1 to a new temp directory and /// ensure it exists. /// [Test] public void Test_Copy_Structure() { string dest = CreateTempDir("a.xx"); RunBuild(string.Format(CultureInfo.InvariantCulture, _xmlProjectTemplate, dest, tempDir1 + "\\**\\*", string.Empty)); Assert.IsTrue(File.Exists(GetPath(dest,tempDir1,tempFile1)), "File should have been created:" + tempFile1); Assert.IsTrue(File.Exists(GetPath(dest,tempDir1,tempFile2)), "File should have been created:" + tempFile2); Assert.IsTrue(File.Exists(GetPath(dest,tempDir1,tempDir2,tempFile3)), "File should have been created:" + tempFile3); Assert.IsTrue(File.Exists(GetPath(dest,tempDir1,tempDir3,tempDir4,tempFile4)), "File should have been created:" + tempFile4); Assert.IsTrue(File.Exists(GetPath(dest,tempDir1,tempDir3,tempFile5)), "File should have been created:" + tempFile5); Assert.IsTrue(File.Exists(GetPath(dest,tempDir1,tempDir3,tempFile6)), "File should have been created:" + tempFile6); Assert.IsTrue(File.Exists(GetPath(dest,tempDir1,tempDir3,tempFile7)), "File should have been created:" + tempFile7); Assert.IsTrue(Directory.Exists(GetPath(dest,tempDir1)), "Dir should have been created:" + tempDir1); Assert.IsTrue(Directory.Exists(GetPath(dest,tempDir1,tempDir2)), "Dir should have been created:" + tempDir2); Assert.IsTrue(Directory.Exists(GetPath(dest,tempDir1,tempDir3)), "Dir should have been created:" + tempDir3); Assert.IsTrue(Directory.Exists(GetPath(dest,tempDir1,tempDir3,tempDir4)), "Dir should have been created:" + tempDir4); Assert.IsTrue(Directory.Exists(GetPath(dest,tempDir1,tempDir5)), "Dir should have been created:" + tempDir5); } /// /// Simple directory copy test. /// [Test] public void Test_copy_Dir_Structure() { string dest = Path.Combine(TempDirName, "a.c"); RunBuild(String.Format(_xmlProjectTemplate4, dest, tempDir1)); Assert.IsTrue(Directory.Exists(dest), String.Format("Directory was not copied: {0}", tempDir1)); } /// /// Copy everything from under tempDir1 to a new temp directory and /// ensure it exists. /// [Test] public void Test_Copy_Structure_IncludeEmptyDirs() { string dest = CreateTempDir("a.xx"); RunBuild(string.Format(CultureInfo.InvariantCulture, _xmlProjectTemplate, dest, tempDir1 + "\\**\\*", " includeemptydirs='true' ")); Assert.IsTrue(File.Exists(GetPath(dest,tempDir1,tempFile1)), "File should have been created:" + tempFile1); Assert.IsTrue(File.Exists(GetPath(dest,tempDir1,tempFile2)), "File should have been created:" + tempFile2); Assert.IsTrue(File.Exists(GetPath(dest,tempDir1,tempDir2,tempFile3)), "File should have been created:" + tempFile3); Assert.IsTrue(File.Exists(GetPath(dest,tempDir1,tempDir3,tempDir4,tempFile4)), "File should have been created:" + tempFile4); Assert.IsTrue(File.Exists(GetPath(dest,tempDir1,tempDir3,tempFile5)), "File should have been created:" + tempFile5); Assert.IsTrue(File.Exists(GetPath(dest,tempDir1,tempDir3,tempFile6)), "File should have been created:" + tempFile6); Assert.IsTrue(File.Exists(GetPath(dest,tempDir1,tempDir3,tempFile7)), "File should have been created:" + tempFile7); Assert.IsTrue(Directory.Exists(GetPath(dest,tempDir1)), "Dir should have been created:" + tempDir1); Assert.IsTrue(Directory.Exists(GetPath(dest,tempDir1,tempDir2)), "Dir should have been created:" + tempDir2); Assert.IsTrue(Directory.Exists(GetPath(dest,tempDir1,tempDir3)), "Dir should have been created:" + tempDir3); Assert.IsTrue(Directory.Exists(GetPath(dest,tempDir1,tempDir3,tempDir4)), "Dir should have been created:" + tempDir4); Assert.IsTrue(Directory.Exists(GetPath(dest,tempDir1,tempDir5)), "Dir should have been created:" + tempDir5); } /// /// Copy everything from under tempDir1 to a new temp directory and /// ensure it exists. Do NOT copy empty dirs. /// [Test] public void Test_Copy_Structure_ExcludeEmptyDirs() { string dest = CreateTempDir("a.xx"); RunBuild(string.Format(CultureInfo.InvariantCulture, _xmlProjectTemplate, dest, tempDir1 + "\\**\\*", " includeemptydirs='false' ")); Assert.IsTrue(File.Exists(GetPath(dest,tempDir1,tempFile1)), "File should have been created:" + tempFile1); Assert.IsTrue(File.Exists(GetPath(dest,tempDir1,tempFile2)), "File should have been created:" + tempFile2); Assert.IsTrue(File.Exists(GetPath(dest,tempDir1,tempDir2,tempFile3)), "File should have been created:" + tempFile3); Assert.IsTrue(File.Exists(GetPath(dest,tempDir1,tempDir3,tempDir4,tempFile4)), "File should have been created:" + tempFile4); Assert.IsTrue(File.Exists(GetPath(dest,tempDir1,tempDir3,tempFile5)), "File should have been created:" + tempFile5); Assert.IsTrue(File.Exists(GetPath(dest,tempDir1,tempDir3,tempFile6)), "File should have been created:" + tempFile6); Assert.IsTrue(File.Exists(GetPath(dest,tempDir1,tempDir3,tempFile7)), "File should have been created:" + tempFile7); Assert.IsTrue(Directory.Exists(GetPath(dest,tempDir1)), "Dir should have been created:" + tempDir1); Assert.IsTrue(Directory.Exists(GetPath(dest,tempDir1,tempDir2)), "Dir should have been created:" + tempDir2); Assert.IsTrue(Directory.Exists(GetPath(dest,tempDir1,tempDir3)), "Dir should have been created:" + tempDir3); Assert.IsTrue(Directory.Exists(GetPath(dest,tempDir1,tempDir3,tempDir4)), "Dir should have been created:" + tempDir4); Assert.IsFalse(Directory.Exists(GetPath(dest, tempDir1, tempDir5)), "Dir should not have been created:" + tempDir5); } [Test] public void Test_Copy_Structure_Overwrite() { string dest = CreateTempDir("a.c"); RunBuild(string.Format(CultureInfo.InvariantCulture, _xmlProjectTemplate, dest, tempDir1 + "/**/*", string.Empty)); Assert.IsTrue(File.Exists(GetPath(dest,tempDir1,tempFile1)), "File should have been created:" + tempFile1); Assert.IsTrue(File.Exists(GetPath(dest,tempDir1,tempFile2)), "File should have been created:" + tempFile2); Assert.IsTrue(File.Exists(GetPath(dest,tempDir1,tempDir2,tempFile3)), "File should have been created:" + tempFile3); Assert.IsTrue(File.Exists(GetPath(dest,tempDir1,tempDir3,tempDir4,tempFile4)), "File should have been created:" + tempFile4); Assert.IsTrue(File.Exists(GetPath(dest,tempDir1,tempDir3,tempFile5)), "File should have been created:" + tempFile5); Assert.IsTrue(File.Exists(GetPath(dest,tempDir1,tempDir3,tempFile6)), "File should have been created:" + tempFile6); Assert.IsTrue(File.Exists(GetPath(dest,tempDir1,tempDir3,tempFile7)), "File should have been created:" + tempFile7); Assert.IsTrue(Directory.Exists(GetPath(dest,tempDir1)), "Dir should have been created:" + tempDir1); Assert.IsTrue(Directory.Exists(GetPath(dest,tempDir1,tempDir2)), "Dir should have been created:" + tempDir2); Assert.IsTrue(Directory.Exists(GetPath(dest,tempDir1,tempDir3)), "Dir should have been created:" + tempDir3); Assert.IsTrue(Directory.Exists(GetPath(dest,tempDir1,tempDir3,tempDir4)), "Dir should have been created:" + tempDir4); Assert.IsTrue(Directory.Exists(GetPath(dest,tempDir1,tempDir5)), "Dir should have been created:" + tempDir5); // delete some files and directories File.Delete(GetPath(dest,tempDir1,tempDir3,tempDir4,tempFile4)); File.Delete(GetPath(dest,tempDir1,tempDir2,tempFile3)); Directory.Delete(GetPath(dest,tempDir1,tempDir5)); // ensure file is outdated File.SetLastWriteTime(GetPath(dest,tempDir1,tempDir3,tempFile5), new DateTime(2000, 1,1)); // set some read-only attributes File.SetAttributes(GetPath(dest,tempDir1,tempDir3,tempFile5), FileAttributes.ReadOnly); // run it again to overwrite RunBuild(String.Format(CultureInfo.InvariantCulture, _xmlProjectTemplate, dest, tempDir1 + "/**/*", string.Empty)); Assert.IsTrue(File.Exists(GetPath(dest,tempDir1,tempFile1)), "File should have been created:" + tempFile1); Assert.IsTrue(File.Exists(GetPath(dest,tempDir1,tempFile2)), "File should have been created:" + tempFile2); Assert.IsTrue(File.Exists(GetPath(dest,tempDir1,tempDir2,tempFile3)), "File should have been created:" + tempFile3); Assert.IsTrue(File.Exists(GetPath(dest,tempDir1,tempDir3,tempDir4,tempFile4)), "File should have been created:" + tempFile4); Assert.IsTrue(File.Exists(GetPath(dest,tempDir1,tempDir3,tempFile5)), "File should have been created:" + tempFile5); Assert.IsTrue(File.Exists(GetPath(dest,tempDir1,tempDir3,tempFile6)), "File should have been created:" + tempFile6); Assert.IsTrue(File.Exists(GetPath(dest,tempDir1,tempDir3,tempFile7)), "File should have been created:" + tempFile7); Assert.IsTrue(Directory.Exists(GetPath(dest,tempDir1)), "Dir should have been created:" + tempDir1); Assert.IsTrue(Directory.Exists(GetPath(dest,tempDir1,tempDir2)), "Dir should have been created:" + tempDir2); Assert.IsTrue(Directory.Exists(GetPath(dest,tempDir1,tempDir3)), "Dir should have been created:" + tempDir3); Assert.IsTrue(Directory.Exists(GetPath(dest,tempDir1,tempDir3,tempDir4)), "Dir should have been created:" + tempDir4); Assert.IsTrue(Directory.Exists(GetPath(dest,tempDir1,tempDir5)), "Dir should have been created:" + tempDir5); // check whether readonly file was overwritten (no longer readonly) Assert.IsTrue((File.GetAttributes(GetPath(dest,tempDir1,tempDir3,tempFile5)) & FileAttributes.ReadOnly) != FileAttributes.ReadOnly); } /// /// Ensure that nested files are in fact flattened, nested directories /// are not created and up-to-date checking compares the flattened files. /// [Test] public void Test_Copy_Files_Flatten() { string dest = CreateTempDir("a.f"); RunBuild(string.Format(CultureInfo.InvariantCulture, _xmlProjectTemplate, dest, tempDir1 + "/**/*", "flatten=\"true\"")); Assert.IsTrue(File.Exists(GetPath(dest, tempFile1)), "File should have been created:" + tempFile1); Assert.IsTrue(File.Exists(GetPath(dest, tempFile2)), "File should have been created:" + tempFile2); Assert.IsTrue(File.Exists(GetPath(dest, tempFile3)), "File should have been created:" + tempFile3); Assert.IsTrue(File.Exists(GetPath(dest, tempFile4)), "File should have been created:" + tempFile4); Assert.IsTrue(File.Exists(GetPath(dest, tempFile5)), "File should have been created:" + tempFile5); Assert.IsTrue(File.Exists(GetPath(dest, tempFile6)), "File should have been created:" + tempFile6); Assert.IsTrue(File.Exists(GetPath(dest, tempFile7)), "File should have been created:" + tempFile7); Assert.IsFalse(Directory.Exists(GetPath(dest, tempDir1)), "Dir should not have been created:" + tempDir1); // make a file read-only File.SetAttributes(GetPath(dest, tempFile1), FileAttributes.ReadOnly); // run build again RunBuild(String.Format(CultureInfo.InvariantCulture, _xmlProjectTemplate, dest, tempDir1 + "/**/*", "flatten=\"true\"")); // if up-to-date check works, build should not have failed and // read-only file should still be read-only Assert.IsTrue((File.GetAttributes(GetPath(dest, tempFile1)) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly); } /// /// When multiple source files match the same destination file, then /// only the last updated file should actually be copied. /// [Test] public void Test_Copy_Files_Flatten_UpToDate() { const string buildXml = @" dest dir1 dir2 dir3 File content was '${file.content}'. "; RunBuild(buildXml, Level.Debug); } /// /// Ensure that an invalid path for source file causes a /// to be thrown. /// [Test] public void Test_Copy_Files_InvalidSourceFilePath() { File.Delete(tempFile2); if (! PlatformHelper.IsUnix ) { try { RunBuild(string.Format(CultureInfo.InvariantCulture, _xmlProjectTemplate3, "|", tempFile2)); // have the test fail Assert.Fail("Build should have failed."); } catch (TestBuildException ex) { // assert that a BuildException was the cause of the TestBuildException Assert.IsTrue((ex.InnerException != null && ex.InnerException.GetType() == typeof(BuildException))); } } } /// /// Ensure that an invalid path for destination file causes a /// to be thrown. /// [Test] public void Test_Copy_Files_InvalidDestinationFilePath() { if (! PlatformHelper.IsUnix ) { try { RunBuild(string.Format(CultureInfo.InvariantCulture, _xmlProjectTemplate3, tempFile1, "|")); // have the test fail Assert.Fail("Build should have failed."); } catch (TestBuildException ex) { // assert that a BuildException was the cause of the TestBuildException Assert.IsTrue((ex.InnerException != null && ex.InnerException.GetType() == typeof(BuildException))); } } } [Test] public void Test_Copy_Files_No_Overwrite() { File.Delete(tempFile2); RunBuild(string.Format(CultureInfo.InvariantCulture, _xmlProjectTemplate3, tempFile1, tempFile2)); Assert.IsTrue(File.Exists(tempFile2), "File should have been created:" + tempFile2); } [Test] public void Test_Copy_Files_Overwrite() { RunBuild(String.Format(CultureInfo.InvariantCulture, _xmlProjectTemplate3, tempFile1, tempFile2)); Assert.IsTrue(File.Exists(tempFile2), "File should have been created:" + tempFile2); } [Test] public void Test_Copy_Files_Overwrite_Readonly() { File.SetAttributes(tempFile2, FileAttributes.ReadOnly); RunBuild(string.Format(CultureInfo.InvariantCulture, _xmlProjectTemplate3, tempFile1, tempFile2)); Assert.IsTrue(File.Exists(tempFile2), "File should have been created:" + tempFile2); } /// /// /// This test suggested by drieseng@users.sourceforge.net. Tests copying subdirectories only. /// /// /// Empty directories should be copied when includeemptydirs /// is not specified (default is ). /// /// [Test] public void Test_Copy_Structure_Directories() { RunBuild(string.Format(CultureInfo.InvariantCulture, _xmlProjectTemplate2, tempDir1, string.Empty)); Assert.IsTrue(Directory.Exists(GetPath(tempDir1, "destination")), "Dir should have been created:" + GetPath(tempDir1, "destination")); Assert.IsTrue(Directory.Exists(GetPath(tempDir1, "source", "test")), "Dir should have been created:" + GetPath(tempDir1, "source", "test")); Assert.IsTrue(Directory.Exists(GetPath(tempDir1, "destination", "source", "test")), "Dir should have been created:" + GetPath(tempDir1, "destination", "source","test")); } /// /// /// This test suggested by drieseng@users.sourceforge.net. Tests copying subdirectories only. /// /// /// Empty directories should not be copied when includeemptydirs /// is . /// /// [Test] public void Test_Copy_Structure_Directories_ExcludeEmptyDirs() { RunBuild(string.Format(CultureInfo.InvariantCulture, _xmlProjectTemplate2, tempDir1, " includeemptydirs='false' ")); Assert.IsTrue(Directory.Exists(GetPath(tempDir1, "destination")), "Dir should have been created:" + GetPath(tempDir1, "destination")); Assert.IsTrue(Directory.Exists(GetPath(tempDir1, "source", "test")), "Dir should have been created:" + GetPath(tempDir1, "source", "test")); Assert.IsFalse(Directory.Exists(GetPath(tempDir1, "destination", "source", "test")), "Dir should not have been created:" + GetPath(tempDir1, "destination", "source","test")); } /// /// The todir and tofile attribute of the <copy> /// task should not be combined. /// [Test] [ExpectedException(typeof(TestBuildException))] public void Test_ToFile_ToDir() { const string xmlProjectTemplate = @" "; RunBuild(xmlProjectTemplate); } /// /// The tofile attribute of the <copy> task cannot /// be combined with a <fileset> element. /// [Test] [ExpectedException(typeof(TestBuildException))] public void Test_ToFile_FileSet() { const string xmlProjectTemplate = @" "; RunBuild(xmlProjectTemplate); } /// /// The file attribute of the <copy> task cannot /// be combined with a <fileset> element. /// [Test] [ExpectedException(typeof(TestBuildException))] public void Test_File_FileSet() { const string xmlProjectTemplate = @" "; RunBuild(xmlProjectTemplate); } } } nant-0.92-rc1/tests/NAnt.Core/Tasks/MailTaskTest.cs0000644000175000017500000017376011757302275021722 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Jay Turpin (recipient2@sourceforge.net) // Gerry Shaw (gerry_shaw@yahoo.com) // Ryan Boggs (rmboggs@users.sourceforge.net) using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using NUnit.Framework; using NAnt.Core; using NAnt.Core.Tasks; using NAnt.Core.Types; using netDumbster.smtp; namespace Tests.NAnt.Core.Tasks { [TestFixture] public class MailTaskTest : BuildTestBase { #region Private Static Fields /// /// The fake Smtp server to use for testing. This ensures that /// the sample emails generated by these tests do not leave the /// testing machine. /// private static SimpleSmtpServer _smtpServer; /// /// The From email address to use for all testing. /// private const string _fromEmail = "nant@sourceforge.net"; /// /// The default mail host to use for testing. /// private const string _mailHost = "localhost"; /// /// String format to use when creating email subject text. /// private const string _subjectText = "Message from {0} method"; /// /// Valid email address to use for single email scenario testing. /// private const string _singleEmail = "jake@example.com"; /// /// Valid (name) Email address pair to use for single email scenario testing. /// private const string _singleParenthesisNameEmail = "(Jake Example) jake@example.com"; /// /// Valid name <Email address> pair to use for single email /// scenario testing. /// private const string _singleAngleBracketNameEmail = "Jake Example "; /// /// Valid Email address (name) pair to use for single email scenario testing. /// private const string _singleParenthesisEmailName = "jake@example.com (Jake Example)"; /// /// Valid <Email address> name pair to use for single email /// scenario testing. /// private const string _singleAngleBracketEmailName = " Jake Example"; /// /// Invalid email address to use for single email scenario testing. /// /// /// There is no @ symbol in the email address. /// private const string _badEmail = "jake.example.com"; /// /// Invalid (name) Email address pair to use for single email scenario testing. /// /// /// The email address is surrounded by brackets. /// private const string _badParenthesisNameEmail = "(Jake Example) [jake@example.com]"; /// /// Invalid name <Email address> pair to use for single email /// scenario testing. /// /// /// There is no @ symbol in the email address. /// private const string _badAngleBracketNameEmail = "Jake Example "; /// /// Invalid Email address (name) pair to use for single email scenario testing. /// /// /// The email address is surrounded by parenthesis as well. /// private const string _badParenthesisEmailName = "(jake@example.com) (Jake Example)"; /// /// Invalid <Email address> name pair to use for single email /// scenario testing. /// /// /// The email address contains angle brackets. /// private const string _badAngleBracketEmailName = "<> Jake Example"; #endregion Private Static Fields #region Private Instance Fields /// /// Holds the version of NAnt to print in the email messages. /// /// /// A nice to have option just in case these tests are converted to /// another way (ie: actual working internal smtp server). It would be /// nice to see which version of NAnt created the test emails. /// private Version _nantVersion; /// /// The system temp path to store test message files. /// private string _tempPath; /// /// Random number generator used to pick a random port for the /// fake smtp server to listen on. /// private Random _portRand = new Random(); /// /// Contains the Port number for the fake smtp server to listen on. /// int _port; /// /// Contains the complete paths of the files used during testing. /// List _files; // Email address array fields. // These should be used for multiple email tests (ie: multi To list, etc). /// /// Two format valid email addresses. /// string[] _twoEmails = new string[] { "jack@example.org", "jane@example.com" }; /// /// Muliple format valid email addresses. /// string[] _multiEmails = new string[] { "jack@example.org", "jane@example.com", "carrie@example.net", "barbara@test.org", "brad@invalid.com", "jon@test.com" }; /// /// Two format valid (name) email addresses. /// string[] _twoParenthesisNameEmails = new string[] { "(Michael Test) michael@test.org", "(Michele Test) michele@test.net" }; /// /// Mulitple format valid (name) email addresses. /// string[] _multiParenthesisNameEmails = new string[] { "(Michael Test) michael@test.org", "(Michele Test) michele@test.net", "(Kathy Test) kathy@test.org", "(Janet Invalid) janet@invalid.net", "(Shannon Localhost) shannon@localhost.com", "(Margaret Localhost) margaret@localhost.net" }; /// /// Two format valid name <email addresses>. /// string[] _twoAngleBracketsNameEmails = new string[] { "Frank Invalid ", "Bill Localhost " }; /// /// Multiple format valid name <email addresses>. /// string[] _multiAngleBracketsNameEmails = new string[] { "Frank Invalid ", "Bill Localhost ", "Morgan Example ", "Kathy Test ", "Janet Invalid ", "Shannon Localhost " }; /// /// Two format valid email addresses (name). /// string[] _twoParenthesisEmailNames = new string[] { "michael@test.org (Michael Test)", "michele@test.net (Michele Test)" }; /// /// Multiple format valid email addresses (name). /// string[] _multiParenthesisEmailNames = new string[] { "michael@test.org (Michael Test)", "michele@test.net (Michele Test)", "kathy@test.org (Kathy Test)", "janet@invalid.net (Janet Invalid)", "shannon@localhost.com (Shannon Localhost)", "margaret@localhost.net (Margaret Localhost)" }; /// /// Two format valid <email addresses> name. /// string[] _twoAngleBracketsEmailNames = new string[] { " Frank Invalid", " Bill Localhost" }; /// /// Multiple format valid <email addresses> name. /// string[] _multiAngleBracketsEmailNames = new string[] { " Frank Invalid", " Bill Localhost", " Morgan Example", " Kathy Test", " Janet Invalid", " Shannon Localhost" }; #endregion Private Instance Fields #region SetUp/TearDown Methods [TestFixtureSetUp] public void Init() { // Assign the fake smtp port _port = _portRand.Next(50000, 60000); // Starts up the fake smtp server. _smtpServer = SimpleSmtpServer.Start(_port); // Gets the current executing version of NAnt to use for some // of the test emails. _nantVersion = Assembly.GetExecutingAssembly().GetName().Version; // Setup the temp directory _tempPath = Path.Combine(Path.GetTempPath(), "NAntEmailTesting"); if (!Directory.Exists(_tempPath)) { Directory.CreateDirectory(_tempPath); } // Create temp files containing messages to load for testing. The // resulting paths are stored in a List var for location // purposes. _files = new List(3); _files.Add(CreateEmailMessageTempFile("NAntMailFile1.txt")); _files.Add(CreateEmailMessageTempFile("NAntMailFile2.txt")); _files.Add(CreateEmailMessageTempFile("NAntMailFile3.txt")); } [TestFixtureTearDown] public void Shutdown() { // Shuts down the fake smtp server. _smtpServer.Stop(); // Try to remove the temp directory and files from the system. // If the directory delete fails, print the exception message to // the console without interrupting the remaining tests. try { Directory.Delete(_tempPath, true); } catch (Exception ex) { Console.WriteLine("Could not cleanup temp dir: {0}", _tempPath); Console.WriteLine("Encountered error:"); Console.WriteLine(ex.Message); } } protected override void SetUp() { base.SetUp(); // Clears out any existing emails in the fake smtp server // before running the next test. _smtpServer.ClearReceivedEmail(); } #endregion SetUp/TearDown Methods #region Simple Email Test Methods /// /// Test a simple email scenario with 1 email address. /// [Test] public void SimpleEmailTest() { string methodName = "SimpleEmailTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.ToList = _singleEmail; mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); Assert.AreEqual(1, _smtpServer.ReceivedEmailCount); } /// /// Test a simple email scenario with 1 email address formatted as /// (Full Name) address@abcxyz.com in the To address field. /// [Test] public void SimpleNameEmailWithParenthesisTest() { string methodName = "SimpleNameEmailWithParenthesisTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.ToList = _singleParenthesisNameEmail; mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); Assert.AreEqual(1, _smtpServer.ReceivedEmailCount); } /// /// Test a simple email scenario with 1 email address formatted as /// address@abcxyz.com (Full Name) in the To address field. /// [Test] public void SimpleEmailNameWithParenthesisTest() { string methodName = "SimpleEmailNameWithParenthesisTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.ToList = _singleParenthesisEmailName; mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); Assert.AreEqual(1, _smtpServer.ReceivedEmailCount); } /// /// Test a simple email scenario with 1 email address formatted as /// Full Name <address@abcxyz.com> in the To address field. /// [Test] public void SimpleNameEmailWithAngleBracketsTest() { string methodName = "SimpleNameEmailWithAngleBracketsTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.ToList = _singleAngleBracketNameEmail; mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); Assert.AreEqual(1, _smtpServer.ReceivedEmailCount); } /// /// Test a simple email scenario with 1 email address formatted as /// <address@abcxyz.com> Full Name in the To address field. /// [Test] public void SimpleEmailNameWithAngleBracketsTest() { string methodName = "SimpleEmailNameWithAngleBracketsTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.ToList = _singleAngleBracketEmailName; mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); Assert.AreEqual(1, _smtpServer.ReceivedEmailCount); } #endregion Simple Email Test Methods #region Mulitple To Email Test Methods /// /// Test a simple email scenario with 2 email addresses in the /// To Address field. /// [Test] public void TwoToEmailAddressesTest() { string methodName = "TwoToEmailAddressesTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.ToList = CreateEmailListString(_twoEmails); mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); Assert.AreEqual(1, _smtpServer.ReceivedEmailCount); Assert.AreEqual(2, _smtpServer.ReceivedEmail[0].ToAddresses.Length); } /// /// Test a simple email scenario with 6 email addresses in the /// To Address field. /// [Test] public void ManyToEmailAddressesTest() { string methodName = "ManyToEmailAddressesTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.ToList = CreateEmailListString(_multiEmails); mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); Assert.AreEqual(1, _smtpServer.ReceivedEmailCount); Assert.AreEqual(6, _smtpServer.ReceivedEmail[0].ToAddresses.Length); } /// /// Test a simple email scenario with 2 email addresses formatted as /// (Full Name) address@abcxyz.com in the To address field. /// [Test] public void TwoToNamesAndEmailAddressesInParenthesisTest() { string methodName = "TwoToNamesAndEmailAddressesInParenthesisTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.ToList = CreateEmailListString(_twoParenthesisNameEmails); mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); Assert.AreEqual(1, _smtpServer.ReceivedEmailCount); Assert.AreEqual(2, _smtpServer.ReceivedEmail[0].ToAddresses.Length); } /// /// Test a simple email scenario with 6 email addresses formatted as /// (Full Name) address@abcxyz.com in the To address field. /// [Test] public void ManyToNamesAndEmailAddressesInParenthesisTest() { string methodName = "ManyToNamesAndEmailAddressesInParenthesisTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.ToList = CreateEmailListString(_multiParenthesisNameEmails); mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); Assert.AreEqual(1, _smtpServer.ReceivedEmailCount); Assert.AreEqual(6, _smtpServer.ReceivedEmail[0].ToAddresses.Length); } /// /// Test a simple email scenario with 2 email addresses formatted as /// Full Name <address@abcxyz.com> in the To address field. /// [Test] public void TwoToNamesAndEmailAddressesInAngleBracketsTest() { string methodName = "TwoToNamesAndEmailAddressesInAngleBracketsTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.ToList = CreateEmailListString(_twoAngleBracketsNameEmails); mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); Assert.AreEqual(1, _smtpServer.ReceivedEmailCount); Assert.AreEqual(2, _smtpServer.ReceivedEmail[0].ToAddresses.Length); } /// /// Test a simple email scenario with 6 email addresses formatted as /// Full Name <address@abcxyz.com> in the To address field. /// [Test] public void ManyToNamesAndEmailAddressesInAngleBracketsTest() { string methodName = "ManyToNamesAndEmailAddressesInAngleBracketsTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.ToList = CreateEmailListString(_multiAngleBracketsNameEmails); mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); Assert.AreEqual(1, _smtpServer.ReceivedEmailCount); Assert.AreEqual(6, _smtpServer.ReceivedEmail[0].ToAddresses.Length); } /// /// Test a simple email scenario with 2 email addresses formatted as /// address@abcxyz.com (Full Name) in the To address field. [Test] public void TwoToEmailAddressesAndNamesInParenthesisTest() { string methodName = "TwoToEmailAddressesAndNamesInParenthesisTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.ToList = CreateEmailListString(_twoParenthesisEmailNames); mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); Assert.AreEqual(1, _smtpServer.ReceivedEmailCount); Assert.AreEqual(2, _smtpServer.ReceivedEmail[0].ToAddresses.Length); } /// /// Test a simple email scenario with 6 email addresses formatted as /// address@abcxyz.com (Full Name) in the To address field. [Test] public void ManyToEmailAddressesAndNamesInParenthesisTest() { string methodName = "ManyToEmailAddressesAndNamesInParenthesisTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.ToList = CreateEmailListString(_multiParenthesisEmailNames); mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); Assert.AreEqual(1, _smtpServer.ReceivedEmailCount); Assert.AreEqual(6, _smtpServer.ReceivedEmail[0].ToAddresses.Length); } /// /// Test a simple email scenario with 2 email addresses formatted as /// <address@abcxyz.com> Full Name in the To address field. /// [Test] public void TwoToEmailAddressesAndNamesInAngleBracketsTest() { string methodName = "TwoToEmailAddressesAndNamesInAngleBracketsTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.ToList = CreateEmailListString(_twoAngleBracketsEmailNames); mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); Assert.AreEqual(1, _smtpServer.ReceivedEmailCount); Assert.AreEqual(2, _smtpServer.ReceivedEmail[0].ToAddresses.Length); } /// /// Test a simple email scenario with 6 email addresses formatted as /// <address@abcxyz.com> Full Name in the To address field. /// [Test] public void ManyToEmailAddressesAndNamesInAngleBracketsTest() { string methodName = "ManyToEmailAddressesAndNamesInAngleBracketsTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.ToList = CreateEmailListString(_multiAngleBracketsEmailNames); mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); Assert.AreEqual(1, _smtpServer.ReceivedEmailCount); Assert.AreEqual(6, _smtpServer.ReceivedEmail[0].ToAddresses.Length); } #endregion Mulitple To Email Test Methods #region Mulitple CC Email Test Methods /// /// Test a simple email scenario with 2 email addresses in the /// CC Address field. /// [Test] public void TwoCcEmailAddressesTest() { string methodName = "TwoCcEmailAddressesTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.CcList = CreateEmailListString(_twoEmails); mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); Assert.AreEqual(1, _smtpServer.ReceivedEmailCount); if (_smtpServer.ReceivedEmail[0].Headers.ContainsKey("Cc")) { string[] ccEmails = GetCcAddressesFromSentMail(); Assert.AreEqual(2, ccEmails.Length); } else { Assert.Fail("Test email did not contain addresses in the CC line"); } } /// /// Test a simple email scenario with 6 email addresses in the /// CC Address field. /// [Test] public void ManyCcEmailAddressesTest() { string methodName = "ManyCcEmailAddressesTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.CcList = CreateEmailListString(_multiEmails); mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); Assert.AreEqual(1, _smtpServer.ReceivedEmailCount); if (_smtpServer.ReceivedEmail[0].Headers.ContainsKey("Cc")) { string[] ccEmails = GetCcAddressesFromSentMail(); Assert.AreEqual(6, ccEmails.Length); } else { Assert.Fail("Test email did not contain addresses in the CC line"); } } /// /// Test a simple email scenario with 2 email addresses formatted as /// (Full Name) address@abcxyz.com in the CC address field. /// [Test] public void TwoCcNamesAndEmailAddressesInParenthesisTest() { string methodName = "TwoCcNamesAndEmailAddressesInParenthesisTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.CcList = CreateEmailListString(_twoParenthesisNameEmails); mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); Assert.AreEqual(1, _smtpServer.ReceivedEmailCount); if (_smtpServer.ReceivedEmail[0].Headers.ContainsKey("Cc")) { string[] ccEmails = GetCcAddressesFromSentMail(); Assert.AreEqual(2, ccEmails.Length); } else { Assert.Fail("Test email did not contain addresses in the CC line"); } } /// /// Test a simple email scenario with 6 email addresses formatted as /// (Full Name) address@abcxyz.com in the CC address field. /// [Test] public void ManyCcNamesAndEmailAddressesInParenthesisTest() { string methodName = "ManyCcNamesAndEmailAddressesInParenthesisTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.CcList = CreateEmailListString(_multiParenthesisNameEmails); mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); Assert.AreEqual(1, _smtpServer.ReceivedEmailCount); if (_smtpServer.ReceivedEmail[0].Headers.ContainsKey("Cc")) { string[] ccEmails = GetCcAddressesFromSentMail(); Assert.AreEqual(6, ccEmails.Length); } else { Assert.Fail("Test email did not contain addresses in the CC line"); } } /// /// Test a simple email scenario with 2 email addresses formatted as /// Full Name <address@abcxyz.com> in the CC address field. /// [Test] public void TwoCcNamesAndEmailAddressesInAngleBracketsTest() { string methodName = "TwoCcNamesAndEmailAddressesInAngleBracketsTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.CcList = CreateEmailListString(_twoAngleBracketsNameEmails); mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); Assert.AreEqual(1, _smtpServer.ReceivedEmailCount); if (_smtpServer.ReceivedEmail[0].Headers.ContainsKey("Cc")) { string[] ccEmails = GetCcAddressesFromSentMail(); Assert.AreEqual(2, ccEmails.Length); } else { Assert.Fail("Test email did not contain addresses in the CC line"); } } /// /// Test a simple email scenario with 6 email addresses formatted as /// Full Name <address@abcxyz.com> in the CC address field. /// [Test] public void ManyCcNamesAndEmailAddressesInAngleBracketsTest() { string methodName = "ManyCcNamesAndEmailAddressesInAngleBracketsTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.CcList = CreateEmailListString(_multiAngleBracketsNameEmails); mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); Assert.AreEqual(1, _smtpServer.ReceivedEmailCount); if (_smtpServer.ReceivedEmail[0].Headers.ContainsKey("Cc")) { string[] ccEmails = GetCcAddressesFromSentMail(); Assert.AreEqual(6, ccEmails.Length); } else { Assert.Fail("Test email did not contain addresses in the CC line"); } } /// /// Test a simple email scenario with 2 email addresses formatted as /// address@abcxyz.com (Full Name) in the CC address field. /// [Test] public void TwoCcEmailAddressesAndNamesInParenthesisTest() { string methodName = "TwoCcEmailAddressesAndNamesInParenthesisTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.CcList = CreateEmailListString(_twoParenthesisEmailNames); mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); Assert.AreEqual(1, _smtpServer.ReceivedEmailCount); if (_smtpServer.ReceivedEmail[0].Headers.ContainsKey("Cc")) { string[] ccEmails = GetCcAddressesFromSentMail(); Assert.AreEqual(2, ccEmails.Length); } else { Assert.Fail("Test email did not contain addresses in the CC line"); } } /// /// Test a simple email scenario with 6 email addresses formatted as /// address@abcxyz.com (Full Name) in the CC address field. /// [Test] public void ManyCcEmailAddressesAndNamesInParenthesisTest() { string methodName = "ManyCcEmailAddressesAndNamesInParenthesisTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.CcList = CreateEmailListString(_multiParenthesisEmailNames); mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); Assert.AreEqual(1, _smtpServer.ReceivedEmailCount); if (_smtpServer.ReceivedEmail[0].Headers.ContainsKey("Cc")) { string[] ccEmails = GetCcAddressesFromSentMail(); Assert.AreEqual(6, ccEmails.Length); } else { Assert.Fail("Test email did not contain addresses in the CC line"); } } /// /// Test a simple email scenario with 2 email addresses formatted as /// <address@abcxyz.com> Full Name in the CC address field. /// [Test] public void TwoCcEmailAddressesAndNamesInAngleBracketsTest() { string methodName = "TwoCcEmailAddressesAndNamesInAngleBracketsTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.CcList = CreateEmailListString(_twoAngleBracketsEmailNames); mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); Assert.AreEqual(1, _smtpServer.ReceivedEmailCount); if (_smtpServer.ReceivedEmail[0].Headers.ContainsKey("Cc")) { string[] ccEmails = GetCcAddressesFromSentMail(); Assert.AreEqual(2, ccEmails.Length); } else { Assert.Fail("Test email did not contain addresses in the CC line"); } } /// /// Test a simple email scenario with 6 email addresses formatted as /// <address@abcxyz.com> Full Name in the CC address field. /// [Test] public void ManyCcEmailAddressesAndNamesInAngleBracketsTest() { string methodName = "ManyCcEmailAddressesAndNamesInAngleBracketsTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.CcList = CreateEmailListString(_multiAngleBracketsEmailNames); mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); Assert.AreEqual(1, _smtpServer.ReceivedEmailCount); if (_smtpServer.ReceivedEmail[0].Headers.ContainsKey("Cc")) { string[] ccEmails = GetCcAddressesFromSentMail(); Assert.AreEqual(6, ccEmails.Length); } else { Assert.Fail("Test email did not contain addresses in the CC line"); } } #endregion Mulitple CC Email Test Methods #region Mulitple BCC Email Test Methods /// /// Test a simple email scenario with 2 email addresses in the /// BCC Address field. /// [Test] public void TwoBccEmailAddressesTest() { string methodName = "TwoBccEmailAddressesTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.BccList = CreateEmailListString(_twoEmails); mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); Assert.AreEqual(1, _smtpServer.ReceivedEmailCount); Assert.AreEqual(2, _smtpServer.ReceivedEmail[0].ToAddresses.Length); } /// /// Test a simple email scenario with 6 email addresses in the /// BCC Address field. /// [Test] public void ManyBccEmailAddressesTest() { string methodName = "ManyBccEmailAddressesTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.BccList = CreateEmailListString(_multiEmails); mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); Assert.AreEqual(1, _smtpServer.ReceivedEmailCount); Assert.AreEqual(6, _smtpServer.ReceivedEmail[0].ToAddresses.Length); } /// /// Test a simple email scenario with 2 email addresses formatted as /// (Full Name) address@abcxyz.com in the BCC address field. /// [Test] public void TwoBccNamesAndEmailAddressesInParenthesisTest() { string methodName = "TwoBccNamesAndEmailAddressesInParenthesisTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.BccList = CreateEmailListString(_twoParenthesisNameEmails); mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); Assert.AreEqual(1, _smtpServer.ReceivedEmailCount); Assert.AreEqual(2, _smtpServer.ReceivedEmail[0].ToAddresses.Length); } /// /// Test a simple email scenario with 6 email addresses formatted as /// (Full Name) address@abcxyz.com in the BCC address field. /// [Test] public void ManyBccNamesAndEmailAddressesInParenthesisTest() { string methodName = "ManyBccNamesAndEmailAddressesInParenthesisTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.BccList = CreateEmailListString(_multiParenthesisNameEmails); mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); Assert.AreEqual(1, _smtpServer.ReceivedEmailCount); Assert.AreEqual(6, _smtpServer.ReceivedEmail[0].ToAddresses.Length); } /// /// Test a simple email scenario with 2 email addresses formatted as /// Full Name <address@abcxyz.com> in the BCC address field. /// [Test] public void TwoBccNamesAndEmailAddressesInAngleBracketsTest() { string methodName = "TwoBccNamesAndEmailAddressesInAngleBracketsTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.BccList = CreateEmailListString(_twoAngleBracketsNameEmails); mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); Assert.AreEqual(1, _smtpServer.ReceivedEmailCount); Assert.AreEqual(2, _smtpServer.ReceivedEmail[0].ToAddresses.Length); } /// /// Test a simple email scenario with 6 email addresses formatted as /// Full Name <address@abcxyz.com> in the BCC address field. /// [Test] public void ManyBccNamesAndEmailAddressesInAngleBracketsTest() { string methodName = "ManyBccNamesAndEmailAddressesInAngleBracketsTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.BccList = CreateEmailListString(_multiAngleBracketsNameEmails); mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); Assert.AreEqual(1, _smtpServer.ReceivedEmailCount); Assert.AreEqual(6, _smtpServer.ReceivedEmail[0].ToAddresses.Length); } /// /// Test a simple email scenario with 2 email addresses formatted as /// address@abcxyz.com (Full Name) in the BCC address field. /// [Test] public void TwoBccEmailAddressesAndNamesInParenthesisTest() { string methodName = "TwoBccEmailAddressesAndNamesInParenthesisTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.BccList = CreateEmailListString(_twoParenthesisEmailNames); mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); Assert.AreEqual(1, _smtpServer.ReceivedEmailCount); Assert.AreEqual(2, _smtpServer.ReceivedEmail[0].ToAddresses.Length); } /// /// Test a simple email scenario with 6 email addresses formatted as /// address@abcxyz.com (Full Name) in the BCC address field. /// [Test] public void ManyBccEmailAddressesAndNamesInParenthesisTest() { string methodName = "ManyBccEmailAddressesAndNamesInParenthesisTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.BccList = CreateEmailListString(_multiParenthesisEmailNames); mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); Assert.AreEqual(1, _smtpServer.ReceivedEmailCount); Assert.AreEqual(6, _smtpServer.ReceivedEmail[0].ToAddresses.Length); } /// /// Test a simple email scenario with 2 email addresses formatted as /// <address@abcxyz.com> Full Name in the BCC address field. /// [Test] public void TwoBccEmailAddressesAndNamesInAngleBracketsTest() { string methodName = "TwoBccEmailAddressesAndNamesInAngleBracketsTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.BccList = CreateEmailListString(_twoAngleBracketsEmailNames); mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); Assert.AreEqual(1, _smtpServer.ReceivedEmailCount); Assert.AreEqual(2, _smtpServer.ReceivedEmail[0].ToAddresses.Length); } /// /// Test a simple email scenario with 6 email addresses formatted as /// <address@abcxyz.com> Full Name in the BCC address field. /// [Test] public void ManyBccEmailAddressesAndNamesInAngleBracketsTest() { string methodName = "ManyBccEmailAddressesAndNamesInAngleBracketsTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.BccList = CreateEmailListString(_multiAngleBracketsEmailNames); mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); Assert.AreEqual(1, _smtpServer.ReceivedEmailCount); Assert.AreEqual(6, _smtpServer.ReceivedEmail[0].ToAddresses.Length); } #endregion Mulitple BCC Email Test Methods #region Misc Email Test Methods /// /// Tests sending an email with the To, CC, and BCC address fields /// filled in at once. /// [Test] public void AllRecipientListsTest() { string methodName = "AllRecipientListsTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.ToList = CreateEmailListString(_twoEmails); mailTask.CcList = CreateEmailListString(_twoParenthesisEmailNames); mailTask.BccList = CreateEmailListString(_twoAngleBracketsNameEmails); mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); Assert.AreEqual(1, _smtpServer.ReceivedEmailCount); Assert.AreEqual(6, _smtpServer.ReceivedEmail[0].ToAddresses.Length); Assert.AreEqual(2, GetCcAddressesFromSentMail().Length); } /// /// Tests sending an email with multiple email address in the /// To address field in different formats. /// [Test] public void MixedEmailFormatTest() { string methodName = "MixedEmailFormatTest()"; string[] toEmails = new string[] { CreateEmailListString(_twoEmails), CreateEmailListString(_twoAngleBracketsNameEmails), CreateEmailListString(_twoParenthesisEmailNames), CreateEmailListString(_twoAngleBracketsEmailNames), CreateEmailListString(_twoParenthesisNameEmails) }; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.ToList = CreateEmailListString(toEmails); mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); Assert.AreEqual(1, _smtpServer.ReceivedEmailCount); Assert.AreEqual(10, _smtpServer.ReceivedEmail[0].ToAddresses.Length); } #endregion Misc Email Test Methods #region Email With External Files Test Methods /// /// Tests sending an email where the body of the email was filled in /// using external files. /// [Test] public void EmailMessageFromFileTest() { string methodName = "EmailMessageFromFileTest()"; FileSet fileSet = new FileSet(); fileSet.FileNames.AddRange(_files.ToArray()); MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.ToList = CreateEmailListString(_twoEmails); mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Files = fileSet; mailTask.Execute(); Assert.AreEqual(1, _smtpServer.ReceivedEmailCount); } /// /// Tests sending an email where the body of the email was filled in /// using external files and specified in the Message property. /// [Test] public void AppendedEmailMessageFromFileTest() { string methodName = "AppendedEmailMessageFromFileTest()"; FileSet fileSet = new FileSet(); fileSet.FileNames.AddRange(_files.ToArray()); MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.ToList = CreateEmailListString(_twoEmails); mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Files = fileSet; mailTask.Execute(); Assert.AreEqual(1, _smtpServer.ReceivedEmailCount); } /// /// Tests sending an email with attachments. /// [Test] public void EmailAttachmentTest() { string methodName = "EmailAttachmentTest()"; FileSet fileSet = new FileSet(); fileSet.FileNames.AddRange(_files.ToArray()); MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.ToList = CreateEmailListString(_twoEmails); mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Attachments = fileSet; mailTask.Execute(); Assert.AreEqual(1, _smtpServer.ReceivedEmailCount); } #endregion Email With External Files Test Methods #region Exception Test Methods /// /// Tests sending an email with a badly formatted email address. /// [Test] [ExpectedException(typeof(BuildException))] public void BadEmailTest() { string methodName = "BadEmailTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.ToList = _badEmail; mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); } /// /// Tests sending an email with a badly formatted email address /// as Full Name <address@abcxyz.com>. /// [Test] [ExpectedException(typeof(BuildException))] public void BadAngleBracketNameEmailTest() { string methodName = "BadAngleBracketNameEmailTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.ToList = _badAngleBracketNameEmail; mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); } /// /// Tests sending an email with a badly formatted email address /// as <address@abcxyz.com> Full Name. /// [Test] [ExpectedException(typeof(BuildException))] public void BadAngleBracketEmailNameTest() { string methodName = "BadAngleBracketEmailNameTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.ToList = _badAngleBracketEmailName; mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); } /// /// Tests sending an email with a badly formatted email address /// as (Full Name) address@abcxyz.com. /// [Test] [ExpectedException(typeof(BuildException))] public void BadParenthesisNameEmailTest() { string methodName = "BadParenthesisNameEmailTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.ToList = _badParenthesisNameEmail; mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); } /// /// Tests sending an email with a badly formatted email address /// as address@abcxyz.com (Full Name). /// [Test] [ExpectedException(typeof(BuildException))] public void BadParenthesisEmailNameTest() { string methodName = "BadParenthesisEmailNameTest()"; MailTask mailTask = new MailTask(); mailTask.Project = CreateEmptyProject(); mailTask.Mailhost = _mailHost; mailTask.Port = _port; mailTask.From = _fromEmail; mailTask.ToList = _badParenthesisEmailName; mailTask.Subject = String.Format(_subjectText, methodName); mailTask.Message = CreateSampleEmailMessage(methodName); mailTask.Execute(); } #endregion Exception Test Methods #region Private Instance Methods /// /// Creates a simple message to use for all /// email tests that do not retrieve message text from external files. /// /// /// The idea here is rather than simply printing 'Sample message text' /// in the test email, useful information can easily be put in all test /// emails just in case tests fail. Any additional information that could /// prove useful when investigating failed test cases should be added to /// this method. /// /// /// The name of the test method that created the sample email message. /// /// /// The sample email message. /// private string CreateSampleEmailMessage(string methodName) { StringBuilder msg = new StringBuilder(); msg.AppendFormat(CultureInfo.InvariantCulture, "This test email was generated by the test method: {0}", methodName) .AppendLine(); msg.AppendLine(); msg.AppendFormat(CultureInfo.InvariantCulture, "This test was conducted on {0} using NAnt version: {1}.", DateTime.Now, _nantVersion) .AppendLine(); return msg.ToString(); } /// /// Creates the email message temp file. /// /// /// Name of the file to save the message to with the complete path omitted. /// /// /// The complete path and file name of the temp file that the method /// created. /// private string CreateEmailMessageTempFile(string fileName) { // Setup the complete path/filename to write to. string targetFile = Path.Combine(_tempPath, fileName); // Create the message StringBuilder msg = new StringBuilder(); msg.AppendFormat(CultureInfo.InvariantCulture, "This text came from a temporary file named: {0}", fileName) .AppendLine(); msg.AppendLine(); msg.AppendLine( "It is ok to delete this file after NAnt's test suite finishes its run."); msg.AppendLine(); msg.AppendFormat(CultureInfo.InvariantCulture, "This file was conducted on {0} using NAnt version: {1}.", DateTime.Now, _nantVersion) .AppendLine(); // Write the above message to the file using (StreamWriter writer = File.CreateText(targetFile)) { writer.Write(msg.ToString()); writer.Flush(); writer.Close(); } return targetFile; } /// /// Creates a new email list from an array /// of email addresses. /// /// /// A array of email addresses to join together. /// /// /// A new list of email addresses separated by a semicolon. /// private string CreateEmailListString(string[] emails) { return String.Join(";", emails); } /// /// Retrieves the CC addresses from the first email that was /// received by the fake smtp server. /// /// /// A array of email addresses that /// were in the CC line of the first email received by the fake /// smtp server. If the email did not contain email addresses in /// the CC line, an empty array is /// returned. /// private string[] GetCcAddressesFromSentMail() { if (_smtpServer.ReceivedEmailCount > 0) { if (_smtpServer.ReceivedEmail[0].Headers.ContainsKey("Cc")) { string ccEmails = _smtpServer.ReceivedEmail[0].Headers["Cc"].ToString(); return ccEmails.Split(',',';'); } return new string[0]; } // This should not be reached... throw new ArgumentNullException("Test smtp server has not yet received emails"); } #endregion Private Instance Methods } } nant-0.92-rc1/tests/NAnt.Core/Tasks/SetEnvTaskTest.cs0000644000175000017500000001700511757302275022231 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2002 Scott Hernandez (ScottHernandez@hotmail.com) // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian MacLean (imaclean@gmail.com) using System; using System.IO; using NAnt.Core; using NUnit.Framework; namespace Tests.NAnt.Core.Tasks { /// /// Tests the Echo task. /// [TestFixture] public class SetEnvTaskTest : BuildTestBase { [SetUp] protected override void SetUp() { base.SetUp(); } [Test] public void SetSingleEnv() { string _xml1 = @" "; RunBuild(_xml1); Assert.AreEqual ("ValueA", Environment.GetEnvironmentVariable("FooA"), "#A1"); Assert.AreEqual ("ValueB", Environment.GetEnvironmentVariable("FooB"), "#A2"); Assert.AreEqual ("ValueC", Environment.GetEnvironmentVariable("FooC"), "#A3"); string _xml2 = @" "; RunBuild(_xml2); Assert.IsNull (Environment.GetEnvironmentVariable("FooA"), "#B1"); Assert.IsNull (Environment.GetEnvironmentVariable("FooB"), "#B2"); Assert.AreEqual (" ", Environment.GetEnvironmentVariable("FooC"), "#B3"); Assert.IsNull (Environment.GetEnvironmentVariable("FooD"), "#B4"); Assert.IsNull (Environment.GetEnvironmentVariable("FooE"), "#B5"); Assert.AreEqual (" ", Environment.GetEnvironmentVariable("FooF"), "#B6"); } [Test] public void Test_SetMultipleEnvVars() { string _xml = @" "; RunBuild(_xml); Assert.AreEqual ("value1", Environment.GetEnvironmentVariable("var1"), "#1"); Assert.AreEqual ("value2", Environment.GetEnvironmentVariable("var2"), "#2"); Assert.IsNull (Environment.GetEnvironmentVariable("var3"), "#3"); Assert.IsNull (Environment.GetEnvironmentVariable("var4"), "#4"); Assert.IsNull (Environment.GetEnvironmentVariable("var5"), "#5"); Assert.IsNull (Environment.GetEnvironmentVariable("var6"), "#6"); Assert.AreEqual (" ", Environment.GetEnvironmentVariable("var7"), "#7"); Assert.IsNull (Environment.GetEnvironmentVariable("var8"), "#8"); Assert.AreEqual ("value9", Environment.GetEnvironmentVariable("var9"), "#9"); } [Test] public void Test_ExpandEnvStrings() { string _xml1 = @" "; string _xml2 = @" "; RunBuild(_xml1); Assert.IsNull (Environment.GetEnvironmentVariable ("var1"), "#A1"); Assert.AreEqual ("value2", Environment.GetEnvironmentVariable("var2"), "#A2"); Assert.AreEqual("value3:value2:%var1%", Environment.GetEnvironmentVariable("var3"), "#A3"); RunBuild (_xml2); Assert.IsNull (Environment.GetEnvironmentVariable ("var4"), "#B1"); Assert.AreEqual ("value5", Environment.GetEnvironmentVariable ("var5"), "#B2"); Assert.AreEqual ("value6:value5:%var4%", Environment.GetEnvironmentVariable ("var6"), "#B3"); } [Test] public void Test_UsePathAttribute() { string _xml = @" "; RunBuild(_xml); Assert.IsTrue( Environment.GetEnvironmentVariable("test_path") != null, "Environment variable test_path should have been set" ); Assert.IsTrue( Environment.GetEnvironmentVariable("test_path") == "/home/foo", "Environment variable test_path should have been set to '/home/foo'" ); } [Test] public void Test_NestedPathElement() { string expectedPath = string.Format(@"{0}{1}dir1{2}{0}{1}dir2", TempDirectory.FullName, Path.DirectorySeparatorChar, Path.PathSeparator); string _xml = @" "; RunBuild(_xml); Assert.IsTrue( Environment.GetEnvironmentVariable("test_path2") != null, "Environment variable test_path2 should have been set" ); Assert.IsTrue( Environment.GetEnvironmentVariable("test_path2") == expectedPath, "Environment variable test_path2 should have been set to '{0}' actual value is {1}", expectedPath, Environment.GetEnvironmentVariable("test_path2") ); } } } nant-0.92-rc1/tests/NAnt.Core/Tasks/ExecTaskTest.cs0000644000175000017500000000627311757302275021716 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Gerry Shaw (gerry_shaw@yahoo.com) using System; using System.IO; using System.Text; using System.Xml; using System.Globalization; using NUnit.Framework; using NAnt.Core; using Tests.NAnt.Core.Util; namespace Tests.NAnt.Core.Tasks { [TestFixture] public class ExecTaskTest : BuildTestBase { const string _format = @" {1} "; /// Test option. [Test] public void Test_ArgOption() { string result = ""; if (PlatformHelper.IsWin32) { result = RunBuild(FormatBuildFile("program='cmd.exe'", "")); } else { result = RunBuild(FormatBuildFile("program='echo'", "")); } Assert.IsTrue(result.IndexOf("Hello, World!") != -1, "Could not find expected text from external program, element is not working correctly."); } /// Regression test for bug #461732 - ExternalProgramBase.ExecuteTask() hanging /// /// http://sourceforge.net/tracker/index.php?func=detail&aid=461732&group_id=31650&atid=402868 /// [Test] public void Test_ReadLargeAmountFromStdout() { // create a text file with A LOT of data string line = "01234567890123456789012345678901234567890123456789012345678901234567890123456789" + Environment.NewLine; StringBuilder contents = new StringBuilder("You can delete this file" + Environment.NewLine); for (int i = 0; i < 250; i++) { contents.Append(line); } string tempFileName = Path.Combine(TempDirName, "bigfile.txt"); TempFile.Create(tempFileName); if (PlatformHelper.IsWin32) { RunBuild(FormatBuildFile("program='cmd.exe' commandline='/c type "" + tempFileName + ""'", "")); } else { RunBuild(FormatBuildFile("program='cat' commandline=' "" + tempFileName + ""'", "")); } // if we get here then we passed, ie, no hang = bug fixed } private string FormatBuildFile(string attributes, string nestedElements) { return String.Format(CultureInfo.InvariantCulture, _format, attributes, nestedElements); } } } nant-0.92-rc1/tests/NAnt.Core/Tasks/ExternalProgramBaseTest.cs0000644000175000017500000001017411757302275024107 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2007 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Gert Driesen (drieseng@users.sourceforge.net) using System; using NUnit.Framework; using NAnt.Core.Tasks; using NAnt.Core.Types; namespace Tests.NAnt.Core.Tasks { [TestFixture] public class ExternalProgramBaseTest { [Test] public void UseRuntimeEngine () { ExternalProgramBase prog; prog = new MockExternalProgram (); Assert.IsFalse (prog.UseRuntimeEngine, "#A1"); Assert.AreEqual (ManagedExecution.Default, prog.Managed, "#A2"); prog.UseRuntimeEngine = true; Assert.IsTrue (prog.UseRuntimeEngine, "#A3"); Assert.AreEqual (ManagedExecution.Auto, prog.Managed, "#A4"); prog.UseRuntimeEngine = false; Assert.IsFalse (prog.UseRuntimeEngine, "#A5"); Assert.AreEqual (ManagedExecution.Default, prog.Managed, "#A6"); prog = new ManagedExternalProgram (); Assert.IsTrue (prog.UseRuntimeEngine, "#B1"); Assert.AreEqual (ManagedExecution.Auto, prog.Managed, "#B2"); prog.UseRuntimeEngine = false; Assert.IsFalse (prog.UseRuntimeEngine, "#B3"); Assert.AreEqual (ManagedExecution.Default, prog.Managed, "#B4"); } [Test] public void Managed () { ExternalProgramBase prog; prog = new MockExternalProgram (); Assert.AreEqual (ManagedExecution.Default, prog.Managed, "#A1"); prog.Managed = ManagedExecution.Auto; Assert.AreEqual (ManagedExecution.Auto, prog.Managed, "#A2"); Assert.IsTrue (prog.UseRuntimeEngine, "#A3"); prog.Managed = ManagedExecution.Default; Assert.AreEqual (ManagedExecution.Default, prog.Managed, "#A4"); Assert.IsFalse (prog.UseRuntimeEngine, "#A5"); prog.Managed = ManagedExecution.Strict; Assert.AreEqual (ManagedExecution.Strict, prog.Managed, "#A6"); Assert.IsTrue (prog.UseRuntimeEngine, "#A7"); prog.UseRuntimeEngine = true; Assert.AreEqual (ManagedExecution.Strict, prog.Managed, "#A8"); Assert.IsTrue (prog.UseRuntimeEngine, "#A9"); prog = new ManagedExternalProgram (); Assert.AreEqual (ManagedExecution.Auto, prog.Managed, "#B1"); prog.Managed = ManagedExecution.Strict; Assert.AreEqual (ManagedExecution.Strict, prog.Managed, "#B2"); Assert.IsTrue (prog.UseRuntimeEngine, "#B3"); prog.Managed = ManagedExecution.Default; Assert.AreEqual (ManagedExecution.Default, prog.Managed, "#B4"); Assert.IsFalse (prog.UseRuntimeEngine, "#B5"); prog.UseRuntimeEngine = true; Assert.AreEqual (ManagedExecution.Auto, prog.Managed, "#B6"); Assert.IsTrue (prog.UseRuntimeEngine, "#B7"); } } class MockExternalProgram : ExternalProgramBase { public override string ProgramArguments { get { return "boo.exe"; } } } class ManagedExternalProgram : ExternalProgramBase { private bool _useRuntimeEngine = true; [Obsolete] public override bool UseRuntimeEngine { get { return _useRuntimeEngine; } set { _useRuntimeEngine = value; } } public override string ProgramArguments { get { return "boo.exe"; } } } } nant-0.92-rc1/tests/NAnt.Core/Tasks/MkDirTest.cs0000644000175000017500000000323511757302275021210 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2002 Scott Hernandez (ScottHernandez@hotmail.com) // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Scott Hernandez (ScottHernandez@hotmail.com) using System; using System.IO; using System.Reflection; using System.Text; using System.Xml; using System.Globalization; using NUnit.Framework; namespace Tests.NAnt.Core.Tasks { /// /// Tests mkdir Tasks. Creates a temp directory and deletes it. /// [TestFixture] public class MkDirTest : BuildTestBase { [Test] public void Test_CreateDirectory() { string _xml= @" "; string tempDir = Path.Combine(TempDirName, "goo"); string result = RunBuild(String.Format(CultureInfo.InvariantCulture, _xml, tempDir)); Assert.IsTrue(Directory.Exists(tempDir), "Dir should have been created:" + result); } } } nant-0.92-rc1/tests/NAnt.Core/Tasks/SleepTaskTest.cs0000644000175000017500000000377211757302275022103 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Bernard Vander Beken using System; using NUnit.Framework; namespace Tests.NAnt.Core.Tasks { [TestFixture] public class SleepTaskTest : BuildTestBase { const string _format = @" "; [Test] public void Test_Normal() { string result = RunBuild(String.Format(_format, " milliseconds='20'")); Assert.IsTrue(result.IndexOf("[sleep]") != -1, "Task should have executed." + Environment.NewLine + result); } [Test] public void Test_NoDurationSpecified() { string result = RunBuild(String.Format(_format, "")); Assert.IsTrue(result.IndexOf("[sleep]") != -1, "Task should have executed." + Environment.NewLine + result); } [Test] [ExpectedException(typeof(TestBuildException))] public void Test_NegativeDurationFails() { RunBuild(String.Format(_format, " milliseconds='-1'")); } [Test] [ExpectedException(typeof(TestBuildException))] public void Test_NegativePartialDurationFails() { RunBuild(String.Format(_format, " seconds='1' milliseconds='-1'")); } } } nant-0.92-rc1/tests/NAnt.Core/Tasks/NAntTaskTest.cs0000644000175000017500000001326511757302275021671 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Gerry Shaw (gerry_shaw@yahoo.com) // Scott Hernandez (ScottHernandez@hotmail.com) using System; using System.IO; using System.Reflection; using System.Text; using System.Xml; using System.Globalization; using NUnit.Framework; using Tests.NAnt.Core.Util; namespace Tests.NAnt.Core.Tasks { [TestFixture] public class NAntTaskTest : BuildTestBase { const string _format = @" "; const string _externalBuildFile = @" "; string _externalBuildFileName; [SetUp] protected override void SetUp() { base.SetUp(); _externalBuildFileName = Path.Combine(TempDirName, "external.build"); TempFile.CreateWithContents(_externalBuildFile, _externalBuildFileName); } [Test] public void Test_Simple() { string result = RunBuild(FormatBuildFile("")); Assert.IsTrue(result.IndexOf("External build file executed") != -1, "External build should have executed." + Environment.NewLine + result); Assert.IsTrue(result.IndexOf("External target executed") == -1, "External target should not have executed." + Environment.NewLine + result); } [Test] public void Test_SingleTarget() { string result = RunBuild(FormatBuildFile("target='test'")); Assert.IsTrue(result.IndexOf("External build file executed") != -1, "External build should have executed." + Environment.NewLine + result); Assert.IsTrue(result.IndexOf("External target executed") != -1, "External target should have executed." + Environment.NewLine + result); } [Test] public void Test_MultipleTargets() { string result = RunBuild(FormatBuildFile("target='test t2 t3'")); Assert.IsTrue(result.IndexOf("External build file executed") != -1, "External build should have executed." + Environment.NewLine + result); Assert.IsTrue(result.IndexOf("External target executed") != -1, "External target should have executed." + Environment.NewLine + result); Assert.IsTrue(result.IndexOf("Second target executed") != -1, "Second target should have executed." + Environment.NewLine + result); Assert.IsTrue(result.IndexOf("Third target executed") != -1, "Third target should have executed." + Environment.NewLine + result); } [Test] public void Test_PropertyInherit() { string _xml = @" "; string result = null; //check inheritance. result = RunBuild(String.Format(CultureInfo.InvariantCulture, _xml, _externalBuildFileName, "inheritall='true'","${test}")); Assert.IsTrue(result.IndexOf("testprop=1st") != -1, "Property should be inherited into nant project." + Environment.NewLine + result); Assert.IsTrue(result.IndexOf("testprop=2nd") != -1, "Property should be inherited, and updatable." + Environment.NewLine + result); Assert.IsTrue(result.IndexOf("after=1st") != -1, "Property should not be changed by inherited nant project." + Environment.NewLine + result); //check to make sure inheritance isn't working. result = RunBuild(String.Format(CultureInfo.InvariantCulture, _xml, _externalBuildFileName, "inheritall='false'","${test}")); Assert.IsTrue(result.IndexOf("testprop=1st") == -1, "Property should not be inherited into nant project." + Environment.NewLine + result); Assert.IsTrue(result.IndexOf("testprop=2nd") != -1, "Property is definable." + Environment.NewLine + result); Assert.IsTrue(result.IndexOf("after=1st") != -1, "Property defined in called project should not affect the caller." + Environment.NewLine + result); } private string FormatBuildFile(string attributes) { return String.Format(CultureInfo.InvariantCulture, _format, _externalBuildFileName, attributes); } } } nant-0.92-rc1/tests/NAnt.Core/Tasks/FailTest.cs0000644000175000017500000000732711757302275021063 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2002-2003 Scott Hernandez // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Scott Hernandez (ScottHernandez@hotmail.com) using System; using System.Xml; using NUnit.Framework; namespace Tests.NAnt.Core.Tasks { /// /// Tests the Fail task. /// [TestFixture] public class FailTest : BuildTestBase { [Test] public void Test_FailMessage() { string _xml = @" "; try { string result = RunBuild(_xml); Assert.Fail("Project should have failed:" + result); } catch (TestBuildException be) { Assert.IsTrue(be.InnerException.ToString().IndexOf("Death Sucks!") != -1, "Project did not fail from Test!"); } } [Test] public void Test_FailMessageMacro() { string _xml = @" "; try { string result = RunBuild(_xml); Assert.Fail("Project should have failed:" + result); } catch (TestBuildException be) { Assert.IsTrue(be.InnerException.ToString().IndexOf("Death Sucks!") != -1, "Macro should have expanded!"); } } [Test] public void Test_FailContent() { string _xml = @" Death Sucks! "; try { string result = RunBuild(_xml); Assert.Fail("Project should have failed:" + result); } catch (TestBuildException be) { Assert.IsTrue(be.InnerException.ToString().IndexOf("Death Sucks!") != -1, "Project did not fail from Test!"); } } [Test] public void Test_FailContentMacro() { string _xml = @" ${prop} Sucks! "; try { string result = RunBuild(_xml); Assert.Fail("Project should have failed:" + result); } catch (TestBuildException be) { Assert.IsTrue(be.InnerException.ToString().IndexOf("Death Sucks!") != -1, "Macro should have expanded!"); } } [Test] [ExpectedException(typeof(TestBuildException))] public void Test_FailMessageAndInlineContent() { string _xml = @" Death Sucks! "; RunBuild(_xml); } } } nant-0.92-rc1/tests/NAnt.Core/Tasks/GetTaskTest.cs0000644000175000017500000002466011757302275021551 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Jay Turpin (JayTurpin@Hotmail.Com) using System; using System.IO; using System.Net; using NUnit.Framework; using NAnt.Core.Tasks; using NAnt.Core.Types; namespace Tests.NAnt.Core.Tasks { [TestFixture] [Category("InetAccess")] public class GetTaskTest : BuildTestBase { string _proxy = null; /// /// Fetch a page from a FTP site. /// /// /// /// [Test] public void Test_GetFtpFile() { GetTask getTask = new GetTask(); getTask.Project = CreateEmptyProject(); getTask.HttpProxy = _proxy; string source = "ftp://ftp.info-zip.org/pub/infozip/zlib/zlib.html"; string destination = Path.GetTempFileName() + ".html"; if (File.Exists(destination)) { File.Delete(destination); } Assert.IsFalse(File.Exists(destination), destination + " exists, but shouldn't."); getTask.Source = source; getTask.DestinationFile = new FileInfo(destination); getTask.UseTimeStamp = false; getTask.IgnoreErrors = true; getTask.Verbose = true;; try { getTask.Execute(); } catch { // error is expected until FTP support is added } // after FTP support is added, do the assert //Assertion.Assert(destination + " should exist, but doesn't.", File.Exists(destination)); } /// /// Fetch a small binary file from a web site. /// File will have same timestamp as on remote server. /// /// /// /// [Test] public void Test_GetLittleFile() { string source = "http://nant.sourceforge.net/arrow.gif"; string destination = Path.GetTempFileName() + ".gif"; { GetTask getTask = new GetTask(); getTask.Project = CreateEmptyProject(); getTask.HttpProxy = _proxy; if (File.Exists(destination)) { File.Delete(destination); } Assert.IsFalse(File.Exists(destination), destination + " exists, but shouldn't"); getTask.Source = source; getTask.DestinationFile = new FileInfo(destination); getTask.UseTimeStamp = true; getTask.IgnoreErrors = true; getTask.Verbose = true;; getTask.Execute(); Assert.IsTrue(File.Exists(destination), destination + " doesn't exist, but should"); } // check for file exists using TimeStampEqual { GetTask getTask = new GetTask(); getTask.Project = CreateEmptyProject(); getTask.HttpProxy = _proxy; Assert.IsTrue(File.Exists(destination), destination + " does not exist, but should"); DateTime fileDateTime = File.GetLastWriteTime(destination); getTask.Source = source; getTask.DestinationFile = new FileInfo(destination); getTask.UseTimeStamp = true; getTask.IgnoreErrors = true; getTask.Verbose = true;; getTask.Execute(); Assert.IsTrue(fileDateTime.Equals(File.GetLastWriteTime(destination)), destination + " lastModified times are different"); } // Test_FileExists_UseTimeStamp { GetTask getTask = new GetTask(); getTask.Project = CreateEmptyProject(); getTask.HttpProxy = _proxy; Assert.IsTrue(File.Exists(destination), destination + " doesn't exist"); File.SetLastWriteTime(destination, DateTime.Parse("01/01/2000 00:00")); DateTime fileDateTime = File.GetLastWriteTime(destination); getTask.Source = source; getTask.DestinationFile = new FileInfo(destination); getTask.UseTimeStamp = true; getTask.IgnoreErrors = true; getTask.Verbose = true;; getTask.Execute(); Assert.IsFalse(fileDateTime.Equals(File.GetLastWriteTime(destination)), destination + " was not fetched"); } // cleanup if (File.Exists(destination)) { File.Delete(destination); } } /// /// Fetch a large binary file from a web site. /// /// /// /// [Test] public void Test_GetBigFile() { GetTask getTask = new GetTask(); getTask.Project = CreateEmptyProject(); string source = "http://www.tolvanen.com/eraser/eraser52.zip"; string destination = Path.GetTempFileName() + ".zip"; if (File.Exists(destination)) { File.Delete(destination); } Assert.IsTrue(!File.Exists(destination), destination + " exists, but shouldn't"); getTask.Source = source; getTask.DestinationFile = new FileInfo(destination); getTask.UseTimeStamp = true; getTask.Verbose = true; getTask.Execute(); Assert.IsTrue(File.Exists(destination), destination + " doesn't exist."); // cleanup if (File.Exists(destination)) { File.Delete(destination); } Assert.IsTrue(!File.Exists(destination), destination + " exists, but shouldn't."); } /// /// Fetch a HTML page from a web site. /// /// /// /// [Test] public void Test_GetHtmlFile() { GetTask getTask = new GetTask(); getTask.Project = CreateEmptyProject(); getTask.HttpProxy = _proxy; string source = "http://nant.sourceforge.net/index.html"; string destination = Path.GetTempFileName() + ".gif"; if (File.Exists(destination)) { File.Delete(destination); } Assert.IsFalse(File.Exists(destination), destination + " exists, but shouldn't."); getTask.Source = source; getTask.DestinationFile = new FileInfo(destination); getTask.UseTimeStamp = false; getTask.IgnoreErrors = true; getTask.Verbose = true;; getTask.Execute(); Assert.IsTrue(File.Exists(destination), destination + " should exist, but doesn't."); // cleanup if (File.Exists(destination)) { File.Delete(destination); } Assert.IsFalse(File.Exists(destination), destination + " exists, but shouldn't."); } /// /// Test Object Accessors /// [Test] public void Test_Accessors() { GetTask getTask = new GetTask(); getTask.Project = CreateEmptyProject(); string proxy = _proxy; getTask.HttpProxy = proxy; Assert.IsTrue(getTask.HttpProxy == proxy, "Proxy accessor bug"); string source = "http://nant.sourceforge.net/arrow.gif"; getTask.Source = source; Assert.IsTrue(getTask.Source == source, "Source accessor bug"); string destination = Path.GetTempFileName(); getTask.DestinationFile = new FileInfo(destination); bool ignoreErrors = true; getTask.IgnoreErrors = ignoreErrors; Assert.IsTrue(getTask.IgnoreErrors == ignoreErrors, "ignoreErrors=true accessor bug"); ignoreErrors = false; getTask.IgnoreErrors = ignoreErrors; Assert.IsTrue(getTask.IgnoreErrors == ignoreErrors, "ignoreErrors=false accessor bug"); bool useTimeStamp = true; getTask.UseTimeStamp = useTimeStamp; Assert.IsTrue(getTask.UseTimeStamp == useTimeStamp, "useTimeStamp=true accessor bug"); useTimeStamp = false; getTask.UseTimeStamp = useTimeStamp; Assert.IsTrue(getTask.UseTimeStamp == useTimeStamp, "useTimeStamp=false accessor bug"); bool verbose = true; getTask.Verbose = verbose; Assert.IsTrue(getTask.Verbose == verbose, "Verbose=true accessor bug"); verbose = false; getTask.Verbose = verbose; Assert.IsTrue(getTask.Verbose == verbose, "Verbose=false accessor bug"); } } } nant-0.92-rc1/tests/NAnt.Core/Tasks/TStampTaskTest.cs0000644000175000017500000000712211757302275022234 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Gerry Shaw (gerry_shaw@yahoo.com) using System; using System.IO; using System.Text; using System.Xml; using System.Globalization; using NUnit.Framework; namespace Tests.NAnt.Core.Tasks { [TestFixture] public class TStampTaskTest : BuildTestBase { const string _format = @" {1} "; [Test] public void Test_Normal() { string result = RunBuild(String.Format(CultureInfo.InvariantCulture, _format, "", "")); Assert.IsTrue(result.IndexOf("[tstamp]") != -1, "Task should have executed." + Environment.NewLine + result); } [Test] public void Test_Custom() { string result = RunBuild(String.Format(CultureInfo.InvariantCulture, _format, " verbose='true' property='build.date' pattern='yyyy-MM-DDTHH:mm:ss zzz'", "")); Assert.IsTrue(result.IndexOf("[tstamp]") != -1, "Task should have executed." + Environment.NewLine + result); Assert.IsTrue(result.IndexOf("build.date") != -1, "build.date property should have been set." + Environment.NewLine + result); } [Test] public void Test_NoVerbose() { string result = RunBuild(String.Format(CultureInfo.InvariantCulture, _format, "property='build.date' pattern='yyyy-MM-DDTHH:mm:ss zzz'", "")); Assert.IsTrue(result.IndexOf("[tstamp]") != -1, "Task should have executed." + Environment.NewLine + result); Assert.IsTrue(result.IndexOf("build.date") == -1, "build.date property should not have been printed to log." + Environment.NewLine + result); } [Test] public void Test_Formatter() { string result = RunBuild(String.Format(CultureInfo.InvariantCulture, _format, "verbose='true'", "")); Assert.IsTrue(result.IndexOf("[tstamp]") != -1, "Task should have executed." + Environment.NewLine + result); } } } /* TODO: [tstamp] Monday, March 4, 2002 11:31pm [tstamp] Monday, March 4, 2002 11:31pm [tstamp] build.date = 20020305 [tstamp] Monday, March 4, 2002 11:31pm [tstamp] TODAY = 5 Mar 2002 [tstamp] DSTAMP = 20020305 [tstamp] TSTAMP = 2331 */nant-0.92-rc1/tests/NAnt.Core/Tasks/LoopTest.cs0000644000175000017500000001516211757302275021115 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2002 Scott Hernandez (ScottHernandez@hotmail.com) // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Scott Hernandez (ScottHernandez@hotmail.com) using System; using System.IO; using System.Reflection; using System.Text; using System.Xml; using NUnit.Framework; namespace Tests.NAnt.Core.Tasks { [TestFixture] public class LoopTest : BuildTestBase { [Test] public void Test_Loop_String_Default_Delim() { string _xml = @" "; string result = RunBuild(_xml); Assert.IsTrue(result.IndexOf("Count:1") != -1); Assert.IsTrue(result.IndexOf("Count:2") != -1); Assert.IsTrue(result.IndexOf("Count:3") != -1); Assert.IsTrue(result.IndexOf("Count:4") != -1); Assert.IsTrue(result.IndexOf("Count:5") != -1); } [Test] public void Test_Loop_Files() { string _xml = @" "; string result = RunBuild(_xml); Assert.IsTrue(result.IndexOf("test.build") != -1); } [Test] public void Test_Loop_Files_From_FileSet() { string _xml = @" "; string result = RunBuild(_xml); Assert.IsTrue(result.IndexOf("test.build") != -1); } [Test] public void Test_Loop_Folders() { string _xml = @" "; string result = RunBuild(_xml); Assert.IsTrue(result.IndexOf("foo") != -1); Assert.IsTrue(result.IndexOf("bar") != -1); } [Test] public void Test_Loop_Folders_From_FileSet() { string _xml = @" "; string result = RunBuild(_xml); Assert.IsTrue(result.IndexOf("foo") != -1); Assert.IsTrue(result.IndexOf("bar") != -1); } [Test] public void Test_Loop_Lines() { string strTempFile = CreateTempFile("looptest.loop_lines_test.txt"); using ( StreamWriter sw = new StreamWriter( strTempFile ) ) { sw.WriteLine( "x,y" ); sw.WriteLine( "x2,y2 " ); sw.WriteLine( "x3 ,y3" ); sw.WriteLine( "x4, y4" ); sw.Close(); string _xml = String.Format( @" ", strTempFile ); string result = RunBuild(_xml); Assert.IsTrue(result.IndexOf("|x=y|") != -1); Assert.IsTrue(result.IndexOf("|x2=y2|") != -1); Assert.IsTrue(result.IndexOf("|x3=y3|") != -1); Assert.IsTrue(result.IndexOf("|x4=y4|") != -1); } } [Test] public void Test_Loop_Lines_No_Delim() { string strTempFile = CreateTempFile("looptest.loop_lines_test.txt"); using ( StreamWriter sw = new StreamWriter( strTempFile ) ) { sw.WriteLine( "x,y " ); sw.WriteLine( "x2,y2 " ); sw.WriteLine( " x3 ,y3 " ); sw.WriteLine( " x4, y4 " ); sw.Close(); string _xml = String.Format( @" ", strTempFile ); string result = RunBuild(_xml); Assert.IsTrue(result.IndexOf("|x,y |") != -1); Assert.IsTrue(result.IndexOf("|x2,y2 |") != -1); Assert.IsTrue(result.IndexOf("|x3 ,y3 |") != -1); Assert.IsTrue(result.IndexOf("|x4, y4 |") != -1); } } } }nant-0.92-rc1/tests/NAnt.Core/Tasks/XmlPokeTest.cs0000644000175000017500000003175011757302275021564 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.IO; using System.Globalization; using System.Text; using System.Xml; using NUnit.Framework; using NAnt.Core; using Tests.NAnt.Core.Util; namespace Tests.NAnt.Core.Tasks { [TestFixture] public class XmlPokeTest : BuildTestBase { #region Private Instance Fields private const string _projectXml = "" + "" + "" + "" + "" + ""; private const string _projectXmlPreserveWhitespace = "" + "" + "" + "" + "" + ""; private const string _projectXmlWithNamespace = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + ""; private const string _validXml = "" + "" + "" + "" + "" + ""; private const string _validXmlWithNamespace = "" + "" + "" + "" + "" + ""; // note the extra whitespace before the nodes private const string _validXmlWithWhitespace = "" + " " + " " + " " + " " + " "; #endregion Private Instance Fields #region Public Instance Methods [Test] public void Test_PokeValidXml() { // write xml content to file string xmlFile = CreateTempFile("validxml.xml", _validXml); // set-up task attributes string xmlPokeTaskAttributes = string.Format(CultureInfo.InvariantCulture, "file=\"{0}\" xpath=\"/configuration/appSettings/add[@key ='server']/@value\"" + " value=\"productionhost.somecompany.com\"", xmlFile); // set-up task attributes string xmlPeekTaskAttributes = string.Format(CultureInfo.InvariantCulture, "file=\"{0}\" xpath=\"/configuration/appSettings/add[@key ='server']/@value\"", xmlFile); // execute build string buildLog = RunBuild(string.Format(CultureInfo.InvariantCulture, _projectXml, xmlPokeTaskAttributes, xmlPeekTaskAttributes, "${configuration.server}")); // ensure original value was not retained Assert.IsTrue(buildLog.IndexOf("configuration.server=testhost.somecompany.com!") == -1, "Value of node was not updated, orignal value is still in xml file."); // ensure new value was set Assert.IsTrue(buildLog.IndexOf("configuration.server=productionhost.somecompany.com!") != -1, "Value of node was not updated correctly, new value does not match."); } [Test] public void Test_PokeValidXmlWithNamespace() { // write xml content to file string xmlFile = CreateTempFile("validxmlnamespace.xml", _validXmlWithNamespace); // set-up task attributes string xmlPokeTaskAttributes = string.Format(CultureInfo.InvariantCulture, "file=\"{0}\" xpath=\"/x:configuration/x:appSettings/x:add[@key ='server']/@value\"" + " value=\"productionhost.somecompany.com\"", xmlFile); // set-up task attributes string xmlPeekTaskAttributes = string.Format(CultureInfo.InvariantCulture, "file=\"{0}\" xpath=\"/x:configuration/x:appSettings/x:add[@key ='server']/@value\"", xmlFile); // execute build string buildLog = RunBuild(string.Format(CultureInfo.InvariantCulture, _projectXmlWithNamespace, xmlPokeTaskAttributes, xmlPeekTaskAttributes, "${configuration.server}")); // ensure original value was not retained Assert.IsTrue(buildLog.IndexOf("configuration.server=testhost.somecompany.com!") == -1, "Value of node was not updated, orignal value is still in xml file."); // ensure new value was set Assert.IsTrue(buildLog.IndexOf("configuration.server=productionhost.somecompany.com!") != -1, "Value of node was not updated correctly, new value does not match."); } [Test] public void Test_PokeEmptyValue() { // write xml content to file string xmlFile = CreateTempFile("validxml.xml", _validXml); // set-up task attributes string xmlPokeTaskAttributes = string.Format(CultureInfo.InvariantCulture, "file=\"{0}\" xpath=\"/configuration/appSettings/add[@key ='server']/@value\"" + " value=\"\"", xmlFile); // set-up task attributes string xmlPeekTaskAttributes = string.Format(CultureInfo.InvariantCulture, "file=\"{0}\" xpath=\"/configuration/appSettings/add[@key ='server']/@value\"", xmlFile); // execute build string buildLog = RunBuild(string.Format(CultureInfo.InvariantCulture, _projectXml, xmlPokeTaskAttributes, xmlPeekTaskAttributes, "${configuration.server}")); // ensure original value was not retained Assert.IsTrue(buildLog.IndexOf("configuration.server=testhost.somecompany.com!") == -1, "Value of node was not updated, orignal value is still in xml file."); // ensure new value was set Assert.IsTrue(buildLog.IndexOf("configuration.server=!") != -1, "Value of node was not updated correctly, new value does not match."); } /// /// Ensures no is thrown when no nodes /// match the XPath expression. /// [Test] public void Test_PokeValidXmlNoMatches() { // write xml content to file string xmlFile = CreateTempFile("validxml.xml", _validXml); // set-up task attributes string xmlPokeTaskAttributes = string.Format(CultureInfo.InvariantCulture, "file=\"{0}\" xpath=\"/configuration/appSettings/add[@key ='anythingisok']/@value\"" + " value=\"productionhost.somecompany.com\"", xmlFile); // set-up task attributes string xmlPeekTaskAttributes = string.Format(CultureInfo.InvariantCulture, "file=\"{0}\" xpath=\"/configuration/appSettings/add[@key ='server']/@value\"", xmlFile); try { // execute build RunBuild(string.Format(CultureInfo.InvariantCulture, _projectXml, xmlPokeTaskAttributes, xmlPeekTaskAttributes, "${configuration.server}")); } catch (TestBuildException ex) { // assert that a BuildException was the cause of the TestBuildException Assert.IsTrue((ex.InnerException != null && ex.InnerException.GetType() == typeof(BuildException))); } } [Test] public void Test_PokeEmptyFile() { // create empty file string xmlFile = CreateTempFile("empty.xml"); // set-up task attributes string xmlPokeTaskAttributes = string.Format(CultureInfo.InvariantCulture, "file=\"{0}\" xpath=\"/configuration/appSettings/add[@key ='anythingisok']/@value\"" + " value=\"productionhost.somecompany.com\"", xmlFile); // set-up task attributes string xmlPeekTaskAttributes = string.Format(CultureInfo.InvariantCulture, "file=\"{0}\" xpath=\"/configuration/appSettings/add[@key ='server']/@value\"", xmlFile); try { // execute build RunBuild(string.Format(CultureInfo.InvariantCulture, _projectXml, xmlPokeTaskAttributes, xmlPeekTaskAttributes, "${configuration.server}")); // have the test fail Assert.Fail("Build should have failed."); } catch (TestBuildException ex) { // assert that a BuildException was the cause of the TestBuildException Assert.IsTrue((ex.InnerException != null && ex.InnerException.GetType() == typeof(BuildException))); // assert that an XmlException was the cause of the BuildException Assert.IsTrue((ex.InnerException.InnerException != null && ex.InnerException.InnerException.GetType() == typeof(XmlException))); } } [Test] public void Test_PokePreserveWhitespaceTrue() { AssertPokePreserveWhitespace(true); } [Test] public void Test_PokePreserveWhitespaceFalse() { AssertPokePreserveWhitespace(false); } #endregion Public Instance Methods #region Private Instance Methods private void AssertPokePreserveWhitespace(bool preserveWhitespace) { // write xml content to file string xmlFile = CreateTempFile("validxmlwithwhitespace.xml", _validXmlWithWhitespace); string originalXmlFile = ReadFile(xmlFile); // set-up task attributes string xmlPokeTaskAttributes = string.Format(CultureInfo.InvariantCulture, "file=\"{0}\" xpath=\"/configuration/appSettings/add[@key ='server']/@value\"" + " value=\"testhost.somecompany.com\"", xmlFile); // don't change anything // set-up task attributes string xmlPeekTaskAttributes = string.Format(CultureInfo.InvariantCulture, "file=\"{0}\" xpath=\"/configuration/appSettings/add[@key ='server']/@value\"", xmlFile); // execute build, preserving whitespace RunBuild(string.Format(CultureInfo.InvariantCulture, _projectXmlPreserveWhitespace, xmlPokeTaskAttributes, preserveWhitespace, xmlPeekTaskAttributes, "${configuration.server}")); string currentXmlFile = ReadFile(xmlFile); if (preserveWhitespace) { Assert.AreEqual(originalXmlFile, currentXmlFile); } else { Assert.AreNotEqual(originalXmlFile, currentXmlFile); } } private static string ReadFile(string path) { string contents; using (StreamReader sr = new StreamReader(path, Encoding.UTF8, true)) { contents = sr.ReadToEnd(); } return contents; } #endregion Private Instance Methods } } nant-0.92-rc1/tests/NAnt.Core/Tasks/MoveTest.cs0000644000175000017500000006546011757302275021120 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2002 Scott Hernandez (ScottHernandez@hotmail.com) // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Scott Hernandez (ScottHernandez@hotmail.com) using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; using System.Xml; using System.Globalization; using NUnit.Framework; using NAnt.Core; using NAnt.Core.Tasks; using Tests.NAnt.Core.Util; namespace Tests.NAnt.Core.Tasks { /// /// Tests . /// [TestFixture] public class MoveTest : BuildTestBase { #region Private Instance Fields private string _tempDirDest; private string _tempFileSrc; private string _tempDirSourceOne; private string _tempDirSourceTwo; private string _tempDirSourceThree; private string _tempDirSourceFour; private string _tempFileSourceOne; private string _tempFileSourceTwo; private string _tempFileSourceThree; private string _tempFileSourceFour; private string _tempDirTargetOne; private string _tempDirTargetTwo; private string _tempDirTargetThree; private string _tempDirTargetFour; private string _tempFileTargetOne; private string _tempFileTargetTwo; private string _tempFileTargetThree; private string _tempFileTargetFour; #endregion Private Instance Fields #region Private Static Fields private const string _xmlProjectTemplate = @" "; private const string _xmlProjectTemplate2 = @" "; private const string _xmlProjectTemplate3 = @" "; private const string _xmlProjectTemplate4 = @" "; private const string _xmlProjectTemplate5 = @" "; #endregion Private Static Fields [SetUp] protected override void SetUp() { base.SetUp(); _tempDirDest = CreateTempDir("foob"); _tempFileSrc = CreateTempFile("foo.xml", "SRC"); // The following vars are needed for directory moving tests. _tempDirSourceOne = CreateTempDir("dirA"); _tempDirSourceTwo = CreateTempDir(Path.Combine("dirA", "subDir")); _tempDirSourceThree = CreateTempDir("dirE"); _tempDirSourceFour = CreateTempDir(Path.Combine(_tempDirSourceThree, "CVS")); _tempFileSourceOne = CreateTempFile(Path.Combine(_tempDirSourceOne, "file.one")); _tempFileSourceTwo = CreateTempFile(Path.Combine(_tempDirSourceTwo, "file2.two")); _tempFileSourceThree = CreateTempFile(Path.Combine(_tempDirSourceThree, "file3.three")); _tempFileSourceFour = CreateTempFile(Path.Combine(_tempDirSourceFour, "file4.four")); _tempDirTargetOne = Path.Combine(TempDirName, "dirB"); _tempDirTargetTwo = Path.Combine(_tempDirTargetOne, "subDir"); _tempDirTargetThree = Path.Combine(_tempDirTargetOne, "dirX"); _tempDirTargetFour = Path.Combine(_tempDirTargetThree, "CVS"); _tempFileTargetOne = Path.Combine(_tempDirTargetOne, "file.one"); _tempFileTargetTwo = Path.Combine(_tempDirTargetTwo, "file2.two"); _tempFileTargetThree = Path.Combine(_tempDirTargetThree, "file3.three"); _tempFileTargetFour = Path.Combine(_tempDirTargetFour, "file4.four"); } /// /// Tests moving a directory using a fileset element. /// [Test] public void FilesetDirectoryMoveTest() { RunBuild(string.Format(_xmlProjectTemplate2, _tempDirTargetOne, _tempDirSourceOne)); Assert.IsTrue(Directory.Exists(_tempDirTargetOne), string.Format("'{0}' directory does not exist", _tempDirTargetOne)); Assert.IsTrue(File.Exists(_tempFileTargetOne), string.Format("'{0}' file does not exist", _tempFileTargetOne)); Assert.IsTrue(Directory.Exists(_tempDirTargetTwo), string.Format("'{0}' directory does not exist", _tempDirTargetTwo)); Assert.IsTrue(File.Exists(_tempFileTargetTwo), string.Format("'{0}' file does not exist", _tempFileTargetTwo)); Assert.IsFalse(Directory.Exists(_tempDirSourceOne), string.Format("'{0}' directory still exists", _tempDirSourceOne)); Assert.IsFalse(File.Exists(_tempFileSourceOne), string.Format("'{0}' file still exists", _tempFileSourceOne)); Assert.IsFalse(Directory.Exists(_tempDirSourceTwo), string.Format("'{0}' directory still exists", _tempDirSourceTwo)); Assert.IsFalse(File.Exists(_tempFileSourceTwo), string.Format("'{0}' file still exists", _tempFileSourceTwo)); } /// /// Tests moving the contents of a directory using a fileset element. /// [Test] public void FilesetIncludeDirectoryMoveTest() { RunBuild(string.Format(_xmlProjectTemplate3, _tempDirTargetOne, _tempDirSourceOne, "**/*")); Assert.IsTrue(Directory.Exists(_tempDirTargetOne), string.Format("'{0}' directory does not exist", _tempDirTargetOne)); Assert.IsTrue(File.Exists(_tempFileTargetOne), string.Format("'{0}' file does not exist", _tempFileTargetOne)); Assert.IsTrue(Directory.Exists(_tempDirTargetTwo), string.Format("'{0}' directory does not exist", _tempDirTargetTwo)); Assert.IsTrue(File.Exists(_tempFileTargetTwo), string.Format("'{0}' file does not exist", _tempFileTargetTwo)); Assert.IsFalse(Directory.Exists(_tempDirSourceOne), string.Format("'{0}' directory still exists", _tempDirSourceOne)); Assert.IsFalse(File.Exists(_tempFileSourceOne), string.Format("'{0}' file still exists", _tempFileSourceOne)); Assert.IsFalse(Directory.Exists(_tempDirSourceTwo), string.Format("'{0}' directory still exists", _tempDirSourceTwo)); Assert.IsFalse(File.Exists(_tempFileSourceTwo), string.Format("'{0}' file still exists", _tempFileSourceTwo)); } /// /// A simple file move test. /// [Test] public void SimpleFileMoveTest() { RunBuild(String.Format(_xmlProjectTemplate, _tempFileSourceOne, _tempFileTargetOne, "true")); Assert.IsFalse(File.Exists(_tempFileSourceOne), string.Format("'{0}' file still exists", _tempFileSourceOne)); Assert.IsTrue(File.Exists(_tempFileTargetOne), string.Format("'{0}' file does not exist", _tempFileTargetOne)); } /// /// Tests moving select contents of a directory using a fileset element. /// [Test] public void SelectFileMoveTest() { RunBuild(string.Format(_xmlProjectTemplate3, _tempDirTargetOne, _tempDirSourceOne, "**/file.*")); Assert.IsTrue(Directory.Exists(_tempDirSourceOne), string.Format("'{0}' source directory does not exist", _tempDirSourceOne)); Assert.IsTrue(Directory.Exists(_tempDirTargetOne), string.Format("'{0}' target directory does not exist", _tempDirTargetOne)); Assert.IsFalse(File.Exists(_tempFileSourceOne), string.Format("'{0}' source file still exists", _tempFileSourceOne)); Assert.IsTrue(File.Exists(_tempFileTargetOne), string.Format("'{0}' target file does not exist", _tempFileTargetOne)); Assert.IsTrue(File.Exists(_tempFileSourceTwo), string.Format("'{0}' source file does not exists", _tempFileSourceTwo)); Assert.IsFalse(File.Exists(_tempFileTargetTwo), string.Format("'{0}' target file does exist", _tempFileTargetTwo)); } /// /// Simple file to dir move test. /// [Test] public void SimpleFileToDirMoveTest() { RunBuild(String.Format(_xmlProjectTemplate4, _tempFileSourceOne, _tempDirTargetOne)); Assert.IsFalse(File.Exists(_tempFileSourceOne), string.Format("'{0}' file still exists", _tempFileSourceOne)); Assert.IsTrue(File.Exists(_tempFileTargetOne), string.Format("'{0}' file does not exist", _tempFileTargetOne)); } /// /// Tests to ensure that files of a subdirectory are moved without actually /// moving the subdirectory itself. /// /// /// This should happen when the fileset base directory has other files/directories /// besides the subdirectory being moved. /// [Test] public void MoveSubdirectoryOnlyTest() { string targetDir = CreateTempDir("dirAtarget"); string targetSubDir = Path.Combine(targetDir, "subDir"); string targetSubDirFile = Path.Combine(targetSubDir, "file2.two"); RunBuild(String.Format(_xmlProjectTemplate3, targetDir, _tempDirSourceOne, "subDir/**")); Assert.IsTrue(Directory.Exists(targetSubDir), string.Format("'{0}' target sub directory does not exist", targetSubDir)); Assert.IsTrue(File.Exists(targetSubDirFile), string.Format("'{0}' target sub directory file does not exist", targetSubDirFile)); Assert.IsTrue(Directory.Exists(_tempDirSourceTwo), string.Format("'{0}' source sub directory does exist", _tempDirSourceTwo)); Assert.IsFalse(File.Exists(_tempFileSourceTwo), string.Format("'{0}' source sub directory file does exist", _tempFileSourceTwo)); } /// /// Renames a directory with the same name but different casing. /// [Test] public void RenameDirectoryToSameNameDifferenceCasingTest() { string sameNameSubDir = "Dira"; string sameNameTarget = Path.Combine(TempDirName, sameNameSubDir); RunBuild(String.Format(_xmlProjectTemplate2, sameNameTarget, _tempDirSourceOne)); // This should be true regardless of underlying OS NAnt is running on. Assert.IsTrue(Directory.Exists(sameNameTarget), string.Format("'{0}' directory does not exist", sameNameTarget)); if (PlatformHelper.IsWindows) { // Because Windows is case-insensitive, need to make sure that // the directory name's casing matches what is on the filesystem // after the move. DirectoryInfo parent = new DirectoryInfo(TempDirName); DirectoryInfo[] subDirs = parent.GetDirectories(); bool foundCasing = false; foreach (DirectoryInfo subDir in subDirs) { if (sameNameSubDir.Equals(subDir.Name, StringComparison.InvariantCulture)) { foundCasing = true; break; } } if (!foundCasing) { Assert.Fail("Directory '{0}' may exist but not in the expected casing: '{1}'", _tempDirSourceOne, sameNameTarget); } } else { Assert.IsFalse(Directory.Exists(_tempDirSourceOne), string.Format("'{0}' directory still exists", _tempDirSourceOne)); } } /// /// Tests empty directory moves when includeemptydir property is false. /// [Test] public void DoNotIncludeEmptyDirMoveTest() { string emptySourceDirOne = CreateTempDir(Path.Combine(_tempDirSourceOne, "EmptyOne")); string emptySourceDirTwo = CreateTempDir(Path.Combine(_tempDirSourceOne, "EmptyTwo")); string emptyTargetDirOne = Path.Combine(_tempDirTargetOne, "EmptyOne"); string emptyTargetDirTwo = Path.Combine(_tempDirTargetOne, "EmptyTwo"); RunBuild(String.Format(_xmlProjectTemplate5, _tempDirTargetOne, _tempDirSourceOne)); Assert.IsTrue(Directory.Exists(_tempDirTargetOne), string.Format("'{0}' target directory does not exist", _tempDirTargetOne)); Assert.IsTrue(Directory.Exists(_tempDirSourceOne), string.Format("'{0}' source directory does not exist", _tempDirSourceOne)); Assert.IsTrue(Directory.Exists(emptySourceDirOne), string.Format("'{0}' empty directory does not exist", emptySourceDirOne)); Assert.IsTrue(Directory.Exists(emptySourceDirTwo), string.Format("'{0}' empty directory does not exist", emptySourceDirTwo)); Assert.IsFalse(Directory.Exists(emptyTargetDirOne), string.Format("'{0}' empty directory does exist", emptyTargetDirOne)); Assert.IsFalse(Directory.Exists(emptyTargetDirTwo), string.Format("'{0}' empty directory does exist", emptyTargetDirTwo)); } /// /// Checks to see if the move task will move /// [Test] public void FilesetExcludeDirectoryMoveTest() { RunBuild(String.Format(_xmlProjectTemplate3, _tempDirTargetThree, _tempDirSourceThree, "**/*")); Assert.IsTrue(Directory.Exists(_tempDirTargetThree), string.Format("'{0}' target directory does not exist", _tempDirTargetThree)); Assert.IsTrue(Directory.Exists(_tempDirSourceThree), string.Format("'{0}' source directory does not exist", _tempDirSourceThree)); Assert.IsTrue(File.Exists(_tempFileTargetThree), string.Format("'{0}' target file does not exist", _tempFileTargetThree)); Assert.IsTrue(File.Exists(_tempFileSourceFour), string.Format("'{0}' source file does not exist", _tempFileSourceFour)); Assert.IsFalse(Directory.Exists(_tempDirTargetFour), string.Format("'{0}' target directory does exist", _tempDirTargetFour)); Assert.IsFalse(File.Exists(_tempFileTargetFour), string.Format("'{0}' target file does exist", _tempFileTargetFour)); Assert.IsFalse(File.Exists(_tempFileSourceThree), string.Format("'{0}' source file does exist", _tempFileSourceThree)); } [Test] public void NoOverwrite_Destination_DoesNotExist() { string tempFileDest = Path.Combine(_tempDirDest, "foo.xml"); string result = RunBuild(string.Format(CultureInfo.InvariantCulture, _xmlProjectTemplate, _tempFileSrc, tempFileDest, "false")); Assert.IsFalse(File.Exists(_tempFileSrc), "#1:" + result); Assert.IsTrue(File.Exists(Path.Combine(_tempDirDest, "foo.xml")), "#2:" + result); using (StreamReader sr = new StreamReader (tempFileDest, Encoding.UTF8, true)) { Assert.AreEqual ("SRC", sr.ReadToEnd (), "#3"); } } [Test] public void NoOverwrite_Destination_Newer() { string tempFileDest = CreateTempFile(Path.Combine(_tempDirDest, "foo.xml"), "DEST"); // ensure destination file is more recent than source file File.SetLastWriteTime(tempFileDest, DateTime.Now.AddDays(1)); string result = RunBuild(string.Format(CultureInfo.InvariantCulture, _xmlProjectTemplate, _tempFileSrc, tempFileDest, "false")); Assert.IsTrue(File.Exists(_tempFileSrc), "#1:" + result); Assert.IsTrue(File.Exists(Path.Combine(_tempDirDest, "foo.xml")), "#2:" + result); using (StreamReader sr = new StreamReader (_tempFileSrc, Encoding.UTF8, true)) { Assert.AreEqual ("SRC", sr.ReadToEnd (), "#3:" + result); } using (StreamReader sr = new StreamReader (tempFileDest, Encoding.UTF8, true)) { Assert.AreEqual ("DEST", sr.ReadToEnd (), "#4:" + result); } } [Test] public void NoOverwrite_Destination_Older() { string tempFileDest = CreateTempFile(Path.Combine(_tempDirDest, "foo.xml"), "DEST"); // ensure source file is more recent than destination file File.SetLastWriteTime(_tempFileSrc, DateTime.Now.AddDays(1)); string result = RunBuild(string.Format(CultureInfo.InvariantCulture, _xmlProjectTemplate, _tempFileSrc, tempFileDest, "false")); Assert.IsFalse(File.Exists(_tempFileSrc), "#1:" + result); Assert.IsTrue(File.Exists(Path.Combine(_tempDirDest, "foo.xml")), "#2:" + result); using (StreamReader sr = new StreamReader (tempFileDest, Encoding.UTF8, true)) { Assert.AreEqual ("SRC", sr.ReadToEnd (), "#3"); } } [Test] public void NoOverwrite_Destination_Same() { string result = RunBuild(string.Format(CultureInfo.InvariantCulture, _xmlProjectTemplate, _tempFileSrc, _tempFileSrc, "false")); Assert.IsTrue(File.Exists(_tempFileSrc), "#1:" + result); using (StreamReader sr = new StreamReader (_tempFileSrc, Encoding.UTF8, true)) { Assert.AreEqual ("SRC", sr.ReadToEnd (), "#2"); } } [Test] public void NoOverwrite_Destination_UpToDate() { string tempFileDest = CreateTempFile(Path.Combine(_tempDirDest, "foo.xml"), "DEST"); // ensure destination file has same write time than source file File.SetLastWriteTime(tempFileDest, File.GetLastWriteTime (_tempFileSrc)); string result = RunBuild(string.Format(CultureInfo.InvariantCulture, _xmlProjectTemplate, _tempFileSrc, tempFileDest, "false")); Assert.IsTrue (File.Exists (_tempFileSrc), "#1:" + result); Assert.IsTrue (File.Exists (tempFileDest), "#2:" + result); using (StreamReader sr = new StreamReader (_tempFileSrc, Encoding.UTF8, true)) { Assert.AreEqual ("SRC", sr.ReadToEnd (), "#3"); } using (StreamReader sr = new StreamReader (tempFileDest, Encoding.UTF8, true)) { Assert.AreEqual ("DEST", sr.ReadToEnd (), "#4"); } } [Test] public void NoOverwrite_Source_DoesNotExist() { string tempFileDest = CreateTempFile(Path.Combine(_tempDirDest, "foo.xml"), "DEST"); File.Delete (_tempFileSrc); try { string result = RunBuild(string.Format(CultureInfo.InvariantCulture, _xmlProjectTemplate, _tempFileSrc, tempFileDest, "false")); Assert.Fail (result); } catch (TestBuildException) { // just catch the exception } Assert.IsFalse (File.Exists (_tempFileSrc), "#1"); Assert.IsTrue (File.Exists (tempFileDest), "#2"); using (StreamReader sr = new StreamReader (tempFileDest, Encoding.UTF8, true)) { Assert.AreEqual ("DEST", sr.ReadToEnd (), "#3"); } } [Test] public void Overwrite_Destination_DoesNotExist() { string tempFileDest = Path.Combine(_tempDirDest, "foo.xml"); string result = RunBuild(string.Format(CultureInfo.InvariantCulture, _xmlProjectTemplate, _tempFileSrc, tempFileDest, "true")); Assert.IsFalse (File.Exists (_tempFileSrc), "#1:" + result); Assert.IsTrue (File.Exists (tempFileDest), "#2:" + result); using (StreamReader sr = new StreamReader (tempFileDest, Encoding.UTF8, true)) { Assert.AreEqual ("SRC", sr.ReadToEnd (), "#3"); } } [Test] public void Overwrite_Destination_Newer() { string tempFileDest = CreateTempFile(Path.Combine(_tempDirDest, "foo.xml"), "DEST"); // ensure destination file is more recent than source file File.SetLastWriteTime(tempFileDest, DateTime.Now.AddDays(1)); string result = RunBuild(string.Format(CultureInfo.InvariantCulture, _xmlProjectTemplate, _tempFileSrc, tempFileDest, "true")); Assert.IsFalse (File.Exists (_tempFileSrc), "#1:" + result); Assert.IsTrue (File.Exists (tempFileDest), "#2:" + result); using (StreamReader sr = new StreamReader (tempFileDest, Encoding.UTF8, true)) { Assert.AreEqual ("SRC", sr.ReadToEnd (), "#3"); } } [Test] public void Overwrite_Destination_Older() { string tempFileDest = CreateTempFile(Path.Combine(_tempDirDest, "foo.xml")); // ensure source file is more recent than destination file File.SetLastWriteTime(_tempFileSrc, DateTime.Now.AddDays(1)); string result = RunBuild(string.Format(CultureInfo.InvariantCulture, _xmlProjectTemplate, _tempFileSrc, tempFileDest, "true")); Assert.IsFalse (File.Exists (_tempFileSrc), "#1:" + result); Assert.IsTrue (File.Exists (tempFileDest), "#2:" + result); using (StreamReader sr = new StreamReader (tempFileDest, Encoding.UTF8, true)) { Assert.AreEqual ("SRC", sr.ReadToEnd (), "#3"); } } [Test] public void Overwrite_Destination_Same() { string result = RunBuild(string.Format(CultureInfo.InvariantCulture, _xmlProjectTemplate, _tempFileSrc, _tempFileSrc, "true")); Assert.IsTrue(File.Exists(_tempFileSrc), "#1:" + result); using (StreamReader sr = new StreamReader (_tempFileSrc, Encoding.UTF8, true)) { Assert.AreEqual ("SRC", sr.ReadToEnd (), "#2"); } } [Test] public void Overwrite_Destination_UpToDate() { string tempFileDest = CreateTempFile(Path.Combine(_tempDirDest, "foo.xml"), "DEST"); // ensure destination file has same write time than source file File.SetLastWriteTime(tempFileDest, File.GetLastWriteTime (_tempFileSrc)); string result = RunBuild(string.Format(CultureInfo.InvariantCulture, _xmlProjectTemplate, _tempFileSrc, tempFileDest, "true")); Assert.IsFalse (File.Exists (_tempFileSrc), "#1:" + result); Assert.IsTrue (File.Exists (tempFileDest), "#2:" + result); using (StreamReader sr = new StreamReader (tempFileDest, Encoding.UTF8, true)) { Assert.AreEqual ("SRC", sr.ReadToEnd (), "#4"); } } [Test] public void Overwrite_Source_DoesNotExist() { string tempFileDest = CreateTempFile(Path.Combine(_tempDirDest, "foo.xml"), "DEST"); File.Delete (_tempFileSrc); try { string result = RunBuild(string.Format(CultureInfo.InvariantCulture, _xmlProjectTemplate, _tempFileSrc, tempFileDest, "true")); Assert.Fail (result); } catch (TestBuildException) { // just catch the exception } Assert.IsFalse (File.Exists (_tempFileSrc), "#1"); Assert.IsTrue (File.Exists (tempFileDest), "#2"); using (StreamReader sr = new StreamReader (tempFileDest, Encoding.UTF8, true)) { Assert.AreEqual ("DEST", sr.ReadToEnd (), "#3"); } } /// /// When multiple source files match the same destination file, then /// only the last updated file should actually be moved. /// [Test] public void Test_Move_Files_Flatten() { const string buildXml = @" #1 #2 #3 #4 #5 #6 #7 "; RunBuild(buildXml); } } } nant-0.92-rc1/tests/NAnt.Core/Tasks/TryCatchTaskTest.cs0000644000175000017500000001535111757302275022550 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2005 Gert Driesen // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Troy Laurin (fiontan@westnet.com.au) using System; using NUnit.Framework; namespace Tests.NAnt.Core.Tasks { /// /// Tests the TryCatch task. /// [TestFixture] public class TryCatchTaskTest : BuildTestBase { [SetUp] protected override void SetUp() { base.SetUp(); } [Test] public void Test_CatchExceptionWithoutMessage() { string _xml = @" "; string result = RunBuild(_xml); Assert.IsTrue(result.IndexOf("Catch!") != -1, "Exception should have been caught"); } [Test] public void Test_CatchExceptionWithMessage() { string _xml = @" "; string result = RunBuild(_xml); Assert.IsTrue(result.IndexOf("Catch: Exception text") != -1, "Exception message should have been caught and displayed"); } [Test] public void Test_CatchWithoutFail() { string _xml = @" "; string result = RunBuild(_xml); Assert.IsTrue(result.IndexOf("No exception") != -1, "Try block should have run"); Assert.IsTrue(result.IndexOf("Catch!") == -1, "Catch block shouldn't have run"); } [Test] public void Test_CatchExceptionAndFinally() { string _xml = @" "; string result = RunBuild(_xml); Assert.IsTrue(result.IndexOf("Catch!") != -1, "Exception should have been caught"); Assert.IsTrue(result.IndexOf("Finally!") != -1, "Finally block should have run"); } [Test] public void Test_CatchWithoutFailAndFinally() { string _xml = @" "; string result = RunBuild(_xml); Assert.IsTrue(result.IndexOf("No exception") != -1, "Try block should have run"); Assert.IsTrue(result.IndexOf("Catch!") == -1, "Catch block shouldn't have run"); Assert.IsTrue(result.IndexOf("Finally!") != -1, "Finally block should have run"); } [Test] public void Test_PropertyScopePreset() { string _xml = @" "; string result = RunBuild(_xml); Assert.IsTrue(result.IndexOf("Catch: Exception text") != -1, "Exception message should have been caught and displayed"); Assert.IsTrue(result.IndexOf("Finally: Original") != -1, "Exception property should be reset outside the catch block"); } [Test] [ExpectedException(typeof(TestBuildException))] public void Test_MessagePropertyScopeEmpty() { string _xml = @" "; RunBuild(_xml); } } } nant-0.92-rc1/tests/NAnt.Core/Tasks/TouchTaskTest.cs0000644000175000017500000002073211757302275022110 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Jay Turpin (jayturpin@hotmail.com) // Gerry Shaw (gerry_shaw@yahoo.com) using System; using System.Collections.Specialized; using System.IO; using System.Globalization; using NUnit.Framework; using NAnt.Core.Tasks; using Tests.NAnt.Core.Util; namespace Tests.NAnt.Core.Tasks { [TestFixture] public class TouchTaskTest : BuildTestBase { const string _format = @" {1} "; private static long TICKS_PER_MILLISECOND = TimeSpan.FromMilliseconds(1).Ticks; StringCollection _fileList = new StringCollection(); /// Create the text fixture. [SetUp] protected override void SetUp() { base.SetUp(); // add 3 directories Directory.CreateDirectory(Path.Combine(TempDirName, "dir1")); Directory.CreateDirectory(Path.Combine(TempDirName, "dir2")); Directory.CreateDirectory(Path.Combine(TempDirName, "dir3")); // add file names _fileList.Add(Path.Combine(TempDirName, "file1.txt")); _fileList.Add(Path.Combine(TempDirName, "file2.txt")); _fileList.Add(Path.Combine(TempDirName, Path.Combine("dir1" ,"file3.tab"))); _fileList.Add(Path.Combine(TempDirName, Path.Combine("dir1" ,"file4.txt"))); _fileList.Add(Path.Combine(TempDirName, Path.Combine("dir2" ,"file5.tab"))); _fileList.Add(Path.Combine(TempDirName, Path.Combine("dir2" ,"file6.txt"))); // add some text to each file, just for fun ;) for (int i = 0; i < _fileList.Count; i++) { TempFile.Create(_fileList[i]); } } [Test] public void Test_File_DateTime() { DateTime newTouchDate = DateTime.Parse("01/01/1980"); string fileName = _fileList[0]; RunBuild(FormatBuildFile("file='" + fileName + "' datetime='" + newTouchDate.ToString(CultureInfo.InvariantCulture) + "'")); FileInfo file = new FileInfo(fileName); DateTime lastTouchDate = file.LastWriteTime; Assert.IsTrue(newTouchDate.Equals(lastTouchDate), "File not touched"); // Make sure another file is NOT touched fileName = _fileList[1]; file = new FileInfo(fileName); lastTouchDate = file.LastWriteTime; Assert.IsFalse(newTouchDate.Equals(lastTouchDate), "Wrong file was touched"); } [Test] public void Test_File_Millis() { // string fileName = _fileList[0]; long milliSeconds = ((DateTime.Parse("01/01/1980").Ticks - DateTime.Parse("01/01/1970").Ticks) / TICKS_PER_MILLISECOND); DateTime newTouchDate = DateTime.Parse("01/01/1970").Add(TimeSpan.FromMilliseconds(milliSeconds)); RunBuild(FormatBuildFile("file='" + fileName + "' millis='" + milliSeconds.ToString() + "'")); FileInfo file = new FileInfo(fileName); DateTime lastTouchDate = file.LastWriteTime; Assert.IsTrue(newTouchDate.Equals(lastTouchDate), "Wrong touch date"); // Make sure another file is NOT touched fileName = _fileList[1]; file = new FileInfo(fileName); lastTouchDate = file.LastWriteTime; Assert.IsFalse(newTouchDate.Equals(lastTouchDate), "Wrong file touched"); } [Test] public void Test_File_Default() { // avoid test failure on fast machines and linux System.Threading.Thread.Sleep(1000); string fileName = _fileList[0]; DateTime newTouchDate = DateTime.Now; // avoid test failure on fast machines and linux System.Threading.Thread.Sleep(1000); RunBuild(FormatBuildFile("file='" + fileName + "'")); FileInfo file = new FileInfo(fileName); DateTime lastTouchDate = file.LastWriteTime; // Can only ensure that Now() is greater or equal to the file date Assert.IsTrue(lastTouchDate.CompareTo(newTouchDate) >= 0, "Touch date incorrect"); // Make sure another file is NOT touched fileName = _fileList[1]; file = new FileInfo(fileName); lastTouchDate = file.LastWriteTime; Assert.IsFalse(newTouchDate.Equals(lastTouchDate), "Wrong file touched"); } [Test] public void Test_Same_File_Twice() { // // // Old code used to lock the file - shouldn't now, allowing us to mess with it between runs string fileName = _fileList[0]; // Get rid of the file first File.Delete(fileName); RunBuild(FormatBuildFile("file='" + fileName + "'")); Assert.IsTrue(File.Exists(fileName), "File doesn't exist!"); File.Delete(fileName); RunBuild(FormatBuildFile("file='" + fileName + "'")); Assert.IsTrue(File.Exists(fileName), "File doesn't exist!"); File.Delete(fileName); } [Test] public void Test_FileSet_DateTime() { // // // DateTime newTouchDate = DateTime.Parse("01/01/1980"); RunBuild(FormatBuildFile("datetime='" + newTouchDate.ToString(CultureInfo.InvariantCulture) + "'","")); for (int i = 0; i < _fileList.Count; i++) { FileInfo file = new FileInfo(_fileList[i]); DateTime lastTouchDate = file.LastWriteTime; Assert.IsTrue(newTouchDate.Equals(lastTouchDate), "Touch: fileset, datetime, " + _fileList[i]); } } [Test] public void Test_FileSet_Millis() { // // // long milliSeconds = ((DateTime.Parse("01/01/1980").Ticks - DateTime.Parse("01/01/1970").Ticks) / TICKS_PER_MILLISECOND); DateTime newTouchDate = DateTime.Parse("01/01/1970").Add(TimeSpan.FromMilliseconds(milliSeconds)); RunBuild(FormatBuildFile("millis='" + milliSeconds.ToString(CultureInfo.InvariantCulture) + "'","")); for (int i = 0; i < _fileList.Count; i++) { FileInfo file = new FileInfo(_fileList[i]); DateTime lastTouchDate = file.LastWriteTime; Assert.IsTrue(newTouchDate.Equals(lastTouchDate), "Touch: fileset, millis, " + _fileList[i]); } } [Test] public void Test_FileSet_Default() { DateTime newTouchDate = DateTime.Now; // avoid test failure on linux System.Threading.Thread.Sleep(1000); RunBuild(FormatBuildFile("","")); for (int i = 0; i < _fileList.Count; i++) { FileInfo file = new FileInfo(_fileList[i]); DateTime lastTouchDate = file.LastWriteTime; Assert.IsTrue(lastTouchDate.CompareTo(newTouchDate) >= 0, "Touch: fileset ONLY, " + _fileList[i]); } } private string FormatBuildFile(string options) { return FormatBuildFile(options, ""); } private string FormatBuildFile(string options, string nestedElements) { return String.Format(CultureInfo.InvariantCulture, _format, options, nestedElements); } } } nant-0.92-rc1/tests/NAnt.Core/Tasks/PropertyTest.cs0000644000175000017500000002454611757302275022036 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2002 Scott Hernandez (ScottHernandez@hotmail.com) // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Scott Hernandez (ScottHernandez@hotmail.com) using System; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using System.Threading; using System.Xml; using NUnit.Framework; using NAnt.Core; namespace Tests.NAnt.Core.Tasks { [TestFixture] public class PropertyTest : BuildTestBase { private CultureInfo _originalCulture; private CultureInfo _originalUICulture; protected override void SetUp() { base.SetUp(); _originalCulture = Thread.CurrentThread.CurrentCulture; _originalUICulture = Thread.CurrentThread.CurrentUICulture; Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US"); } [TearDown] protected override void TearDown() { base.TearDown(); Thread.CurrentThread.CurrentCulture = _originalCulture; Thread.CurrentThread.CurrentUICulture = _originalUICulture; } [Test] public void Test_PropCreate() { string _xml = @" "; string result = RunBuild(_xml); Assert.IsTrue(result.IndexOf("I Love you") != -1, "Property value not set." + Environment.NewLine + result); } [Test] public void Test_PropReset() { string _xml = @" "; string result = RunBuild(_xml); Assert.IsTrue(result.IndexOf("I Love me") != -1, "Property value not re-set." + Environment.NewLine + result); } /// /// Overwriting a read-only property should result in build error. /// [Ignore("For now, we only output a warning message when read-only properties are overwritten.")] [Test] [ExpectedException(typeof(TestBuildException))] public void Test_ROSet() { string _xml = @" "; RunBuild(_xml); } [Test] public void Test_NoOverwriteProperty() { string _xml = @" "; string result = RunBuild(_xml); Assert.IsTrue(result.IndexOf("I Love me") == -1, "Property value should not have been overwritten." + Environment.NewLine + result); } [Test] public void Test_OverwriteProperty() { string _xml = @" "; string result = RunBuild(_xml); Assert.IsTrue(result.IndexOf("I Love me") != -1, "Property value should have been overwritten." + Environment.NewLine + result); } /// /// Overwriting a read-only property should result in build error. /// [Ignore("For now, we only output a warning message when read-only properties are overwritten.")] [Test] [ExpectedException(typeof(TestBuildException))] public void Test_OverwriteReadOnlyProperty() { string _xml = @" "; RunBuild(_xml); } [Test] public void Test_DynamicProperty() { string _xml = @" "; string result = RunBuild(_xml); Assert.IsTrue(result.IndexOf("I Love you") != -1, "Value of dynamic property should have reflected change in referenced property." + Environment.NewLine + result); } [Test] [ExpectedException(typeof(TestBuildException))] public void Test_DynamicPropertyNotExisting() { string _xml = @" "; RunBuild(_xml); } [Test] [ExpectedException(typeof(TestBuildException))] public void Test_DynamicPropertyCircularReference() { string _xml = @" "; RunBuild(_xml); } [Test] public void Test_ChangeStaticPropertyToDynamic() { string _xml = @" "; string result = RunBuild(_xml); Assert.IsTrue(result.IndexOf("I Love you") != -1, "Static property should be upgraded to dynamic property." + Environment.NewLine + result); } [Test] public void Test_ReadOnlyDynamicProperty() { string _xml = @" "; string result = RunBuild(_xml); Assert.IsTrue(result.IndexOf("I Love you") != -1, "Value of read-only dynamic property should have reflected change in referenced property." + Environment.NewLine + result); } [Test] public void CurrentFramework_NonExisting () { string _xml = @" "; try { RunBuild(_xml); Assert.Fail ("#1"); } catch (TestBuildException ex) { Assert.IsNotNull(ex.InnerException, "#2"); string expectedError = "Target framework could not be changed. " + "\"doesnotexist\" is not a valid framework identifier."; BuildException inner = ex.InnerException as BuildException; Assert.IsNotNull(inner, "#3"); Assert.IsNull(inner.InnerException, "#4"); Assert.IsNotNull(inner.RawMessage, "#5"); Assert.IsTrue(inner.RawMessage.StartsWith(expectedError), "#6:" + inner.RawMessage); } } [Test] public void CurrentFramework_Invalid () { FrameworkInfo invalid = null; Project p = CreateEmptyProject(); foreach (FrameworkInfo framework in p.Frameworks) { if (!framework.IsValid) { invalid = framework; break; } } if (invalid == null) { Assert.Ignore("Test requires at least one invalid framework."); } string _xml = @" "; try { RunBuild(string.Format(_xml, invalid.Name)); Assert.Fail ("#1"); } catch (TestBuildException ex) { Assert.IsNotNull(ex.InnerException, "#2"); // either initialization of the framework failed, or validation // failed BuildException inner = ex.InnerException as BuildException; Assert.IsNotNull(inner, "#3"); Assert.IsNotNull(inner.InnerException, "#4"); Assert.IsNotNull(inner.RawMessage, "#5"); } } } } nant-0.92-rc1/tests/NAnt.Core/Tasks/RegexTaskTest.cs0000644000175000017500000000521711757302275022101 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2003 Scott Hernandez (ScottHernandez_at_hotmail.com) // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Michael Aird (mike@airdian.com) using System; using NUnit.Framework; namespace Tests.NAnt.Core.Tasks { [TestFixture] public class RegexTest : BuildTestBase { [Test] public void Test_RegexMatch() { string _xml = @" "; string result = RunBuild(_xml); Assert.AreNotEqual(-1, result.IndexOf("sentence"), String.Concat("Regex did not match properly.\n", result)); } [Test] public void Test_RegexMatchMultiple() { string _xml = @" "; string result = RunBuild(_xml); Assert.AreNotEqual(-1, result.IndexOf(@"path=d:\Temp\SomeDir\SomeDir\"), String.Concat("Regex did not set first property correcty.\n", result)); Assert.AreNotEqual(-1, result.IndexOf(@"file=bla.xml"), String.Concat("Regex did not set second property correcty.\n", result)); } [Test] [ExpectedException(typeof(TestBuildException))] public void Test_RegexNoMatch() { string _xml = @" "; RunBuild(_xml); } } } nant-0.92-rc1/tests/NAnt.Core/Tasks/IfTest.cs0000644000175000017500000001671011757302275020542 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2002-2003 Scott Hernandez (ScottHernandez@hotmail.com) // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Scott Hernandez (ScottHernandez@hotmail.com) using System; using System.IO; using System.Reflection; using System.Text; using System.Xml; using System.Globalization; using NUnit.Framework; namespace Tests.NAnt.Core.Tasks { [TestFixture] public class IfTest : BuildTestBase { string _newFile = null; string _oldFile = null; protected override void SetUp() { base.SetUp(); _newFile = this.CreateTempFile("new.txt","I'm younger"); _oldFile = this.CreateTempFile("old.txt","I'm older"); File.SetLastWriteTime(_oldFile, DateTime.Now.AddHours(-1)); } [Test] public void Test_IF_NewerFile() { string _xml = @" "; string result = RunBuild(string.Format(CultureInfo.InvariantCulture, _xml, _oldFile, _newFile)); Assert.IsTrue(result.IndexOf("is same/newer than") != -1, result); } [Test] public void Test_IFNot_NewerFile() { string _xml = @" "; string result = RunBuild(String.Format(CultureInfo.InvariantCulture, _xml, _oldFile, _newFile)); Assert.IsTrue(result.IndexOf("is not same/newer than") == -1, result); } [Test] public void Test_IF_NewerFiles() { string _xml = @" "; string result = RunBuild(String.Format(CultureInfo.InvariantCulture, _xml, _newFile, _oldFile)); Assert.IsTrue(result.IndexOf("is same/newer than") != -1, result); } [Test] public void Test_IFNot_NewerFilesUptodateFiles() { string _xml = @" "; string result = RunBuild(String.Format(CultureInfo.InvariantCulture, _xml, _newFile, _oldFile)); Assert.IsTrue(result.IndexOf("is not same/newer than") == -1, result); } [Test] public void Test_IFNot_NewerFilesUptodateFilesWithWildcard() { string _xml = @" "; string result = RunBuild(String.Format(CultureInfo.InvariantCulture, _xml, (new FileInfo(_newFile)).Directory.FullName + "\\*", _oldFile)); Assert.IsTrue(result.IndexOf("is not same/newer than") == -1, result); } [Test] public void Test_IF_PropExists_Positive() { string _xml = @" "; string result = RunBuild(_xml); Assert.IsTrue(result.IndexOf("line=hi") != -1, result); } [Test] public void Test_IF_PropExists_Negative() { string _xml = @" "; string result = RunBuild(_xml); Assert.IsTrue(result.IndexOf("line=") == -1, result); } [Test] public void Test_IF_PropTrue_Positive() { string _xml = @" "; string result = RunBuild(_xml); Assert.IsTrue(result.IndexOf("Hello") != -1, result); } [Test] public void Test_IF_PropTrue_Negative() { string _xml = @" "; string result = RunBuild(_xml); Assert.IsTrue(result.IndexOf("Hello") == -1, result); } [Test] public void Test_IF_Target_Positive() { string _xml = @" "; string result = RunBuild(_xml); Assert.IsTrue(result.IndexOf("called") != -1, result); } [Test] public void Test_IF_Target_Negative() { string _xml = @" "; string result = RunBuild(_xml); Assert.IsTrue(result.IndexOf("failed") == -1, result); } } }nant-0.92-rc1/tests/NAnt.Core/Tasks/StyleTaskTest.cs0000644000175000017500000005001311757302275022121 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Michael Aird (mike@airdian.com) using System; using System.IO; using System.Reflection; using System.Text; using System.Xml; using System.Globalization; using NAnt.Core; using NUnit.Framework; using Tests.NAnt.Core.Util; namespace Tests.NAnt.Core.Tasks { [TestFixture] public class StyleTaskTest : BuildTestBase { #region Private Instance Fields private string _projectXml = @" "; string outputFN = Path.Combine(TempDirName, _xmlSrcFileName + "." + _outputFileExtension); RunBuild(String.Format(CultureInfo.InvariantCulture, _xml, _xslSrcFileNameFull, _xmlSrcFileNameFull, outputFN)); Assert.IsTrue(File.Exists(outputFN) && (new FileInfo(outputFN)).Length > 0, "Output file not created."); } [Test] public void Test_Extension() { string _xml = @" "; RunBuild(String.Format(CultureInfo.InvariantCulture, _xml, _xslSrcFileNameFull, _outputFileExtension,_xmlSrcFileNameFull, _xmlSrcFile2NameFull )); string outputFN = Path.Combine(TempDirName, _xmlSrcFileName + "." + _outputFileExtension); Assert.IsTrue(File.Exists(outputFN) && (new FileInfo(outputFN)).Length > 0, "Output file not created."); } [Test] [ExpectedException(typeof(TestBuildException))] public void Test_NoSrcfiles() { string _xml = @" "; RunBuild(String.Format(CultureInfo.InvariantCulture, _xml, _xslSrcFileNameFull, _xmlSrcFileNameFull, Path.Combine(TempDirName, _xmlSrcFileName + "." + _outputFileExtension))); } [Test] [ExpectedException(typeof(TestBuildException))] public void Test_XslFileMissing() { string _xml = @" nant-0.92-rc1/examples/StyleTask/SimpleExtensionObject/SimpleExtension.cs0000644000175000017500000000036311757302272026524 0ustar jtaylorjtaylorusing System; //Calculates the circumference of a circle given the radius. public class Calculate { private double circ = 0; public double Circumference(double radius){ circ = Math.PI*2*radius; return circ; } }nant-0.92-rc1/examples/HelloWindowsForms/0000755000175000017500000000000011757310030020261 5ustar jtaylorjtaylornant-0.92-rc1/examples/HelloWindowsForms/HelloWindowsForms.vbproj0000644000175000017500000000756611757302272025161 0ustar jtaylorjtaylor nant-0.92-rc1/examples/HelloWindowsForms/MainForm.resx0000644000175000017500000001243611757302272022713 0ustar jtaylorjtaylor text/microsoft-resx 1.3 System.Resources.ResXResourceReader, System.Windows.Forms, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Assembly MainForm nant-0.92-rc1/examples/HelloWindowsForms/MainForm.vb0000644000175000017500000000376511757302272022346 0ustar jtaylorjtaylorPublic Class MainForm Inherits System.Windows.Forms.Form #Region " Windows Form Designer generated code " Public Sub New() MyBase.New() 'This call is required by the Windows Form Designer. InitializeComponent() 'Add any initialization after the InitializeComponent() call End Sub 'Form overrides dispose to clean up the component list. Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) If disposing Then If Not (components Is Nothing) Then components.Dispose() End If End If MyBase.Dispose(disposing) End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. Friend WithEvents myLabel As System.Windows.Forms.Label Private Sub InitializeComponent() Me.myLabel = New System.Windows.Forms.Label() Me.SuspendLayout() ' 'myLabel ' Me.myLabel.Dock = System.Windows.Forms.DockStyle.Fill Me.myLabel.Font = New System.Drawing.Font("Tahoma", 24.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.myLabel.Name = "myLabel" Me.myLabel.Size = New System.Drawing.Size(304, 118) Me.myLabel.TabIndex = 0 Me.myLabel.Text = "Hello Windows Forms" Me.myLabel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter ' 'MainForm ' Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13) Me.ClientSize = New System.Drawing.Size(304, 118) Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.myLabel}) Me.Name = "MainForm" Me.Text = "Hello Windows Forms" Me.ResumeLayout(False) End Sub #End Region End Class nant-0.92-rc1/examples/HelloWindowsForms/HelloWindowsForms.build0000644000175000017500000000427211757302272024745 0ustar jtaylorjtaylor nant-0.92-rc1/examples/Simple/0000755000175000017500000000000011757310030016065 5ustar jtaylorjtaylornant-0.92-rc1/examples/Simple/Simple.cs0000644000175000017500000000015211757302272017654 0ustar jtaylorjtaylorpublic class Simple { static void Main() { System.Console.WriteLine("Hello, World!"); } } nant-0.92-rc1/examples/Simple/Simple.build0000644000175000017500000000134111757302272020347 0ustar jtaylorjtaylor nant-0.92-rc1/examples/ScriptTask/0000755000175000017500000000000011757310030016723 5ustar jtaylorjtaylornant-0.92-rc1/examples/ScriptTask/script-sample.build0000644000175000017500000000172611757302272022546 0ustar jtaylorjtaylor nant-0.92-rc1/examples/Solution/0000775000175000017500000000000011760131347016460 5ustar jtaylorjtaylornant-0.92-rc1/examples/Solution/vjs/0000755000175000017500000000000011757310030017252 5ustar jtaylorjtaylornant-0.92-rc1/examples/Solution/vjs/WinForms/0000755000175000017500000000000011757310030021016 5ustar jtaylorjtaylornant-0.92-rc1/examples/Solution/vjs/WinForms/Form1.resx0000644000175000017500000000323311757302272022717 0ustar jtaylorjtaylor text/microsoft-resx 1.0.0.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 nant-0.92-rc1/examples/Solution/vjs/WinForms/WinForms.sln0000644000175000017500000000156111757302272023314 0ustar jtaylorjtaylorMicrosoft Visual Studio Solution File, Format Version 8.00 Project("{E6FDF86B-F3D1-11D4-8576-0002A516ECE8}") = "WinForms", "WinForms.vjsproj", "{84A7C512-CE63-4884-B9FB-DF863EEC3800}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Global GlobalSection(SolutionConfiguration) = preSolution Debug = Debug Release = Release EndGlobalSection GlobalSection(ProjectConfiguration) = postSolution {84A7C512-CE63-4884-B9FB-DF863EEC3800}.Debug.ActiveCfg = Debug|.NET {84A7C512-CE63-4884-B9FB-DF863EEC3800}.Debug.Build.0 = Debug|.NET {84A7C512-CE63-4884-B9FB-DF863EEC3800}.Release.ActiveCfg = Release|.NET {84A7C512-CE63-4884-B9FB-DF863EEC3800}.Release.Build.0 = Release|.NET EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution EndGlobalSection GlobalSection(ExtensibilityAddIns) = postSolution EndGlobalSection EndGlobal nant-0.92-rc1/examples/Solution/vjs/WinForms/WinForms.vjsproj0000644000175000017500000000770011757302272024216 0ustar jtaylorjtaylor nant-0.92-rc1/examples/Solution/vjs/WinForms/AssemblyInfo.jsl0000644000175000017500000000447311757302272024144 0ustar jtaylorjtaylorimport System.Reflection.*; import System.Runtime.CompilerServices.*; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // /** @assembly AssemblyTitle("") */ /** @assembly AssemblyDescription("") */ /** @assembly AssemblyConfiguration("") */ /** @assembly AssemblyCompany("") */ /** @assembly AssemblyProduct("") */ /** @assembly AssemblyCopyright("") */ /** @assembly AssemblyTrademark("") */ /** @assembly AssemblyCulture("") */ // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build // Numbers by using the '*' as shown below: /** @assembly AssemblyVersion("1.0.*") */ // // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project directory. For example, if your KeyFile is // located in the project directory itself, you would specify the // AssemblyKeyFile attribute as @assembly AssemblyKeyFile("mykey.snk") // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // /** @assembly AssemblyDelaySign(false) */ /** @assembly AssemblyKeyFile("") */ /** @assembly AssemblyKeyName("") */ nant-0.92-rc1/examples/Solution/vjs/WinForms/Form1.jsl0000644000175000017500000000241311757302272022525 0ustar jtaylorjtaylorpackage WinForms; import System.Drawing.*; import System.Collections.*; import System.ComponentModel.*; import System.Windows.Forms.*; import System.Data.*; /** * Summary description for Form1. */ public class Form1 extends System.Windows.Forms.Form { /** * Required designer variable. */ private System.ComponentModel.Container components = null; public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /** * Clean up any resources being used. */ protected void Dispose(boolean disposing) { if (disposing) { if (components != null) { components.Dispose(); } } super.Dispose(disposing); } #region Windows Form Designer generated code /** * Required method for Designer support - do not modify * the contents of this method with the code editor. */ private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.set_Size(new System.Drawing.Size(300,300)); this.set_Text("Form1"); } #endregion /** * The main entry point for the application. */ /** @attribute System.STAThread() */ public static void main(String[] args) { Application.Run(new Form1()); } } nant-0.92-rc1/examples/Solution/vjs/WinForms/vjs.build0000644000175000017500000000173511757302272022660 0ustar jtaylorjtaylor Output file doesn't exist in ${expected.output} nant-0.92-rc1/examples/Solution/vjs/default.build0000644000175000017500000000052011757302272021725 0ustar jtaylorjtaylor nant-0.92-rc1/examples/Solution/vb/0000755000175000017500000000000011757310030017057 5ustar jtaylorjtaylornant-0.92-rc1/examples/Solution/vb/WinForms/0000755000175000017500000000000011757310030020623 5ustar jtaylorjtaylornant-0.92-rc1/examples/Solution/vb/WinForms/Form1.resx0000644000175000017500000000323311757302272022524 0ustar jtaylorjtaylor text/microsoft-resx 1.0.0.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 nant-0.92-rc1/examples/Solution/vb/WinForms/WinForms.sln0000644000175000017500000000156011757302272023120 0ustar jtaylorjtaylorMicrosoft Visual Studio Solution File, Format Version 8.00 Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "WinForms", "WinForms.vbproj", "{B01CBC5B-0F63-4623-8B41-806E063D4F0C}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Global GlobalSection(SolutionConfiguration) = preSolution Debug = Debug Release = Release EndGlobalSection GlobalSection(ProjectConfiguration) = postSolution {B01CBC5B-0F63-4623-8B41-806E063D4F0C}.Debug.ActiveCfg = Debug|.NET {B01CBC5B-0F63-4623-8B41-806E063D4F0C}.Debug.Build.0 = Debug|.NET {B01CBC5B-0F63-4623-8B41-806E063D4F0C}.Release.ActiveCfg = Release|.NET {B01CBC5B-0F63-4623-8B41-806E063D4F0C}.Release.Build.0 = Release|.NET EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution EndGlobalSection GlobalSection(ExtensibilityAddIns) = postSolution EndGlobalSection EndGlobal nant-0.92-rc1/examples/Solution/vb/WinForms/vb.build0000644000175000017500000000175711757302272022276 0ustar jtaylorjtaylor Output file doesn't exist in ${expected.output} nant-0.92-rc1/examples/Solution/vb/WinForms/AssemblyInfo.vb0000644000175000017500000000176411757302272023570 0ustar jtaylorjtaylorImports System Imports System.Reflection Imports System.Runtime.InteropServices ' General Information about an assembly is controlled through the following ' set of attributes. Change these attribute values to modify the information ' associated with an assembly. ' Review the values of the assembly attributes 'The following GUID is for the ID of the typelib if this project is exposed to COM ' Version information for an assembly consists of the following four values: ' ' Major Version ' Minor Version ' Build Number ' Revision ' ' You can specify all the values or you can default the Build and Revision Numbers ' by using the '*' as shown below: nant-0.92-rc1/examples/Solution/vb/WinForms/WinForms.vbproj0000644000175000017500000001001111757302272023615 0ustar jtaylorjtaylor nant-0.92-rc1/examples/Solution/vb/WinForms/Form1.vb0000644000175000017500000000216211757302272022152 0ustar jtaylorjtaylorPublic Class Form1 Inherits System.Windows.Forms.Form #Region " Windows Form Designer generated code " Public Sub New() MyBase.New() 'This call is required by the Windows Form Designer. InitializeComponent() 'Add any initialization after the InitializeComponent() call End Sub 'Form overrides dispose to clean up the component list. Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) If disposing Then If Not (components Is Nothing) Then components.Dispose() End If End If MyBase.Dispose(disposing) End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. Private Sub InitializeComponent() components = New System.ComponentModel.Container() Me.Text = "Form1" End Sub #End Region End Class nant-0.92-rc1/examples/Solution/vb/default.build0000644000175000017500000000052011757302272021532 0ustar jtaylorjtaylor nant-0.92-rc1/examples/Solution/cpp/0000755000175000017500000000000011757310030017232 5ustar jtaylorjtaylornant-0.92-rc1/examples/Solution/cpp/WinForms/0000755000175000017500000000000011757310030020776 5ustar jtaylorjtaylornant-0.92-rc1/examples/Solution/cpp/WinForms/resource.h0000644000175000017500000000013011757302272023001 0ustar jtaylorjtaylor//{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by app.rc nant-0.92-rc1/examples/Solution/cpp/WinForms/WinForms.sln0000644000175000017500000000156411757302272023277 0ustar jtaylorjtaylorMicrosoft Visual Studio Solution File, Format Version 8.00 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "WinForms", "WinForms.vcproj", "{11211AF9-DD1D-4151-844A-A2430B67DE3D}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Global GlobalSection(SolutionConfiguration) = preSolution Debug = Debug Release = Release EndGlobalSection GlobalSection(ProjectConfiguration) = postSolution {11211AF9-DD1D-4151-844A-A2430B67DE3D}.Debug.ActiveCfg = Debug|Win32 {11211AF9-DD1D-4151-844A-A2430B67DE3D}.Debug.Build.0 = Debug|Win32 {11211AF9-DD1D-4151-844A-A2430B67DE3D}.Release.ActiveCfg = Release|Win32 {11211AF9-DD1D-4151-844A-A2430B67DE3D}.Release.Build.0 = Release|Win32 EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution EndGlobalSection GlobalSection(ExtensibilityAddIns) = postSolution EndGlobalSection EndGlobal nant-0.92-rc1/examples/Solution/cpp/WinForms/AssemblyInfo.cpp0000644000175000017500000000434011757302272024107 0ustar jtaylorjtaylor#include "stdafx.h" using namespace System::Reflection; using namespace System::Runtime::CompilerServices; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly:AssemblyTitleAttribute("")]; [assembly:AssemblyDescriptionAttribute("")]; [assembly:AssemblyConfigurationAttribute("")]; [assembly:AssemblyCompanyAttribute("")]; [assembly:AssemblyProductAttribute("")]; [assembly:AssemblyCopyrightAttribute("")]; [assembly:AssemblyTrademarkAttribute("")]; [assembly:AssemblyCultureAttribute("")]; // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the value or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly:AssemblyVersionAttribute("1.0.*")]; // // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project directory. // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly:AssemblyDelaySignAttribute(false)]; [assembly:AssemblyKeyFileAttribute("")]; [assembly:AssemblyKeyNameAttribute("")]; nant-0.92-rc1/examples/Solution/cpp/WinForms/cpp.build0000644000175000017500000000173511757302272022620 0ustar jtaylorjtaylor Output file doesn't exist in ${expected.output} nant-0.92-rc1/examples/Solution/cpp/WinForms/WinForms.vcproj0000644000175000017500000001124411757302272024002 0ustar jtaylorjtaylor nant-0.92-rc1/examples/Solution/cpp/WinForms/stdafx.h0000644000175000017500000000064611757302272022457 0ustar jtaylorjtaylor// stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently #pragma once #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers // C RunTime Header Files #include #include #include #include // TODO: reference additional headers your program requires here nant-0.92-rc1/examples/Solution/cpp/WinForms/app.rc0000644000175000017500000000215311757302272022116 0ustar jtaylorjtaylor// Microsoft Visual C++ generated resource script. // #include "resource.h" #define APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// #undef APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // English (U.S.) resources ///////////////////////////////////////////////////////////////////////////// // // Icon // // Icon placed first or with lowest ID value becomes application icon LANGUAGE 9, 1 #pragma code_page(1252) 1 ICON "app.ico" #ifdef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // TEXTINCLUDE // 1 TEXTINCLUDE BEGIN "resource.h\0" "\0" END #endif // APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// #ifndef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 3 resource. // ///////////////////////////////////////////////////////////////////////////// #endif // not APSTUDIO_INVOKED nant-0.92-rc1/examples/Solution/cpp/WinForms/Form1.h0000644000175000017500000000262711757302272022153 0ustar jtaylorjtaylor#pragma once namespace WinForms { using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; /// /// Summary for Form1 /// /// WARNING: If you change the name of this class, you will need to change the /// 'Resource File Name' property for the managed resource compiler tool /// associated with all .resx files this class depends on. Otherwise, /// the designers will not be able to interact properly with localized /// resources associated with this form. /// public __gc class Form1 : public System::Windows::Forms::Form { public: Form1(void) { InitializeComponent(); } protected: void Dispose(Boolean disposing) { if (disposing && components) { components->Dispose(); } __super::Dispose(disposing); } private: /// /// Required designer variable. /// System::ComponentModel::Container * components; /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// void InitializeComponent(void) { this->components = new System::ComponentModel::Container(); this->Size = System::Drawing::Size(300,300); this->Text = S"Form1"; } }; } nant-0.92-rc1/examples/Solution/cpp/WinForms/app.ico0000644000175000017500000000206611757302272022267 0ustar jtaylorjtaylor &(( @wwwwwwwwwwwwwwpDDDDDDDDDDDDDDppppppppppppppppppppDDDDDDDDDDDDDDpLLLLLLLLLNItpDDDDDDDDDDDDD@( wwwwwwwDDDDDDDGOGOGOGOGOGOGOGOGHGLGDDDDDDnant-0.92-rc1/examples/Solution/cpp/WinForms/stdafx.cpp0000644000175000017500000000031111757302272022777 0ustar jtaylorjtaylor// stdafx.cpp : source file that includes just the standard includes // winforms.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" nant-0.92-rc1/examples/Solution/cpp/WinForms/ReadMe.txt0000644000175000017500000000241311757302272022705 0ustar jtaylorjtaylor======================================================================== APPLICATION : winforms Project Overview ======================================================================== AppWizard has created this winforms Application for you. This file contains a summary of what you will find in each of the files that make up your winforms application. winforms.vcproj This is the main project file for VC++ projects generated using an Application Wizard. It contains information about the version of Visual C++ that generated the file, and information about the platforms, configurations, and project features selected with the Application Wizard. Form1.cpp This is the main application source file. Contains the code to display the form. Form1.h Contains the implementation of your form class and InitializeComponent() function. AssemblyInfo.cpp Contains custom attributes for modifying assembly metadata. ///////////////////////////////////////////////////////////////////////////// Other standard files: StdAfx.h, StdAfx.cpp These files are used to build a precompiled header (PCH) file named Win32.pch and a precompiled types file named StdAfx.obj. ///////////////////////////////////////////////////////////////////////////// nant-0.92-rc1/examples/Solution/cpp/WinForms/Form1.cpp0000644000175000017500000000063011757302272022476 0ustar jtaylorjtaylor#include "stdafx.h" #include "Form1.h" #include using namespace WinForms; int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { System::Threading::Thread::CurrentThread->ApartmentState = System::Threading::ApartmentState::STA; Application::Run(new Form1()); return 0; } nant-0.92-rc1/examples/Solution/cpp/WinForms/Form1.resX0000644000175000017500000000323311757302272022637 0ustar jtaylorjtaylor text/microsoft-resx 1.0.0.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 nant-0.92-rc1/examples/Solution/cpp/default.build0000644000175000017500000000052011757302272021705 0ustar jtaylorjtaylor nant-0.92-rc1/examples/Solution/cs/0000755000175000017500000000000011757310030017055 5ustar jtaylorjtaylornant-0.92-rc1/examples/Solution/cs/WinForms/0000755000175000017500000000000011757310030020621 5ustar jtaylorjtaylornant-0.92-rc1/examples/Solution/cs/WinForms/Form1.resx0000644000175000017500000000323311757302272022522 0ustar jtaylorjtaylor text/microsoft-resx 1.0.0.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 nant-0.92-rc1/examples/Solution/cs/WinForms/WinForms.sln0000644000175000017500000000156011757302272023116 0ustar jtaylorjtaylorMicrosoft Visual Studio Solution File, Format Version 8.00 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WinForms", "WinForms.csproj", "{C0E751EE-4590-447A-B236-FF7E71A484DF}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Global GlobalSection(SolutionConfiguration) = preSolution Debug = Debug Release = Release EndGlobalSection GlobalSection(ProjectConfiguration) = postSolution {C0E751EE-4590-447A-B236-FF7E71A484DF}.Debug.ActiveCfg = Debug|.NET {C0E751EE-4590-447A-B236-FF7E71A484DF}.Debug.Build.0 = Debug|.NET {C0E751EE-4590-447A-B236-FF7E71A484DF}.Release.ActiveCfg = Release|.NET {C0E751EE-4590-447A-B236-FF7E71A484DF}.Release.Build.0 = Release|.NET EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution EndGlobalSection GlobalSection(ExtensibilityAddIns) = postSolution EndGlobalSection EndGlobal nant-0.92-rc1/examples/Solution/cs/WinForms/App.ico0000644000175000017500000000206611757302272022052 0ustar jtaylorjtaylor &(( @wwwwwwwwwwwwwwpDDDDDDDDDDDDDDppppppppppppppppppppDDDDDDDDDDDDDDpLLLLLLLLLNItpDDDDDDDDDDDDD@( wwwwwwwDDDDDDDGOGOGOGOGOGOGOGOGHGLGDDDDDDnant-0.92-rc1/examples/Solution/cs/WinForms/AssemblyInfo.cs0000644000175000017500000000450011757302272023553 0ustar jtaylorjtaylorusing System.Reflection; using System.Runtime.CompilerServices; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")] nant-0.92-rc1/examples/Solution/cs/WinForms/Form1.cs0000644000175000017500000000260511757302272022150 0ustar jtaylorjtaylorusing System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; namespace WinForms { /// /// Summary description for Form1. /// public class Form1 : System.Windows.Forms.Form { /// /// Required designer variable. /// private System.ComponentModel.Container components = null; public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// /// Clean up any resources being used. /// protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.Size = new System.Drawing.Size(300,300); this.Text = "Form1"; } #endregion /// /// The main entry point for the application. /// [STAThread] static void Main() { Application.Run(new Form1()); } } } nant-0.92-rc1/examples/Solution/cs/WinForms/cs.build0000644000175000017500000000175711757302272022272 0ustar jtaylorjtaylor Output file doesn't exist in ${expected.output} nant-0.92-rc1/examples/Solution/cs/WinForms/WinForms.csproj0000644000175000017500000001073511757302272023626 0ustar jtaylorjtaylor nant-0.92-rc1/examples/Solution/cs/default.build0000644000175000017500000000052011757302272021530 0ustar jtaylorjtaylor nant-0.92-rc1/examples/HelloWorld/0000755000175000017500000000000011757310030016707 5ustar jtaylorjtaylornant-0.92-rc1/examples/HelloWorld/HelloWorld.vb0000644000175000017500000000022611757302272021324 0ustar jtaylorjtaylorImports System Public Class MainApp Shared Sub Main() Console.WriteLine("Hello World using VB.NET") Return End Sub End Class nant-0.92-rc1/examples/HelloWorld/HelloWorld.cs0000644000175000017500000000016611757302272021325 0ustar jtaylorjtaylorpublic class ProjectName { static void Main() { System.Console.WriteLine("Hello World using C#"); } } nant-0.92-rc1/examples/HelloWorld/HelloWorld.js0000644000175000017500000000004711757302272021332 0ustar jtaylorjtaylorprint("Hello World using JScript.NET");nant-0.92-rc1/examples/HelloWorld/default.build0000644000175000017500000000236211757302272021370 0ustar jtaylorjtaylor nant-0.92-rc1/COPYING.txt0000644000175000017500000004313111757302272014702 0ustar jtaylorjtaylor GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. nant-0.92-rc1/lib/0000775000175000017500000000000011760131347013574 5ustar jtaylorjtaylornant-0.92-rc1/lib/common/0000775000175000017500000000000011760131347015064 5ustar jtaylorjtaylornant-0.92-rc1/lib/common/neutral/0000755000175000017500000000000011760131373016533 5ustar jtaylorjtaylornant-0.92-rc1/lib/common/2.0/0000755000175000017500000000000011760131373015360 5ustar jtaylorjtaylornant-0.92-rc1/lib/common/2.0/nunit-console.exe.config0000644000175000017500000000202411757302272022126 0ustar jtaylorjtaylor nant-0.92-rc1/NAnt.build0000644000175000017500000013163611757306735014732 0ustar jtaylorjtaylor #!/bin/sh${environment::newline()} exec ${path::combine(install.prefix, 'bin')}/mono ${path::combine(install.nant, 'bin')}/NAnt.exe "$@" nant-0.92-rc1/etc/0000755000175000017500000000000011757310027013577 5ustar jtaylorjtaylornant-0.92-rc1/etc/nant.pc.in0000644000175000017500000000035411757302272015475 0ustar jtaylorjtaylorprefix=${pcfiledir}/../.. extensiondir=${prefix}/share/NAnt/bin/extensions libdir=${prefix}/share/NAnt/bin/lib Name: NAnt Description: A build tool for .NET and Mono Version: @VERSION@ Libs: -r:"${prefix}/share/NAnt/bin/NAnt.Core.dll" nant-0.92-rc1/README.txt0000644000175000017500000001166211757302272014533 0ustar jtaylorjtaylorNAnt What is it? ----------- NAnt is a .NET based build tool. In theory it is kind of like make without make's wrinkles. In practice it's a lot like Ant. If you are not familiar with Jakarta Ant you can get more information at the Ant project web site (http://ant.apache.org/). Why NAnt? --------- Because Ant was too Java specific. Because Ant needed the Java runtime. NAnt only needs the .NET or Mono runtime. The Latest Version ------------------ Details of the latest version can be found on the NAnt project web site http://nant.sourceforge.net/ Files ----- README.txt - This file. Makefile - Makefile for compilation with GNU Make. Makefile.nmake - Makefile for compilation with Microsoft NMake. Compilation and Installation ---------------------------- a. Overview ----------- The compilation process uses NAnt to build NAnt. The approach is to first compile a copy of NAnt (using make/nmake) for bootstrapping purpose. Next, the bootstrapped version of NAnt is used in conjunction with NAnt build file (NAnt.build) to build the full version. b. Prerequisites ---------------- To build NAnt, you will need the following components: Windows ------- * A version of the Microsoft .NET Framework Available from http://msdn.microsoft.com/netframework/ You will need the .NET Framework SDK as well as the runtime components if you intend to compile programs. Note: NAnt currently supports versions 1.0, 1.1, 2.0, 3.5, and 4.0 of the Microsoft .NET Framework. or * Mono for Windows (version 2.0 or higher) Available from http://www.mono-project.com/downloads/ Linux/Unix ---------- * GNU toolchain - including GNU make * pkg-config Available from: http://www.freedesktop.org/Software/pkgconfig * A working Mono installation and development libraries (version 2.0 or higher) Available from: http://www.mono-project.com/downloads/ b. Building the Software ------------------------ Build NAnt using Microsoft .NET: GNU Make -------- make install MONO= MCS=csc prefix= [DESTDIR=] [TARGET=] eg. make install MONO= MCS=csc prefix="c:\Program Files" TARGET=net-2.0 NMake ----- nmake -f Makefile.nmake install prefix= [DESTDIR=] [TARGET=] eg. nmake -f Makefile.nmake install prefix="c:\Program Files" TARGET=net-4.0 Building NAnt using Mono: GNU Make -------- make install prefix= [DESTDIR=] [TARGET=] eg. make install prefix="c:\Program Files" TARGET=mono-4.0 NMake ----- nmake -f Makefile.nmake install MONO=mono CSC=mcs prefix= [DESTDIR=] [TARGET=] eg. nmake -f Makefile.nmake install MONO=mono CSC=mcs prefix=/usr/local/ Note: These instructions only apply to the source distribution of NAnt, as the binary distribution contains pre-built assemblies. Documentation ------------- Documentation is available in HTML format, in the doc/ directory. License ------- Copyright (C) 2001-2012 Gerry Shaw This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA As a special exception, the copyright holders of this software give you permission to link the assemblies with independent modules to produce new assemblies, regardless of the license terms of these independent modules, and to copy and distribute the resulting assemblies under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on these assemblies. If you modify this software, you may extend this exception to your version of the software, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. A copy of the GNU General Public License is available in the COPYING.txt file included with all NAnt distributions. For more licensing information refer to the GNU General Public License on the GNU Project web site. http://www.gnu.org/copyleft/gpl.html nant-0.92-rc1/src/0000755000175000017500000000000011757310030013605 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.Core/0000755000175000017500000000000011757310030015334 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.Core/Task.cs0000644000175000017500000005046411757302273016610 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Mike Krueger (mike@icsharpcode.net) // Ian MacLean (imaclean@gmail.com) // William E. Caputo (wecaputo@thoughtworks.com | logosity@yahoo.com) // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.ComponentModel; using System.Globalization; using System.Reflection; using System.Xml; using NAnt.Core.Attributes; using NAnt.Core.Util; namespace NAnt.Core { /// /// Provides the abstract base class for tasks. /// /// /// A task is a piece of code that can be executed. /// [Serializable()] public abstract class Task : Element { #region Private Static Fields private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion Private Static Fields #region Private Instance Fields private bool _failOnError = true; private bool _verbose; private bool _ifDefined = true; private bool _unlessDefined; private Level _threshold = Level.Debug; #endregion Private Instance Fields #region Public Instance Properties /// /// Determines if task failure stops the build, or is just reported. /// The default is . /// [TaskAttribute("failonerror")] [BooleanValidator()] public bool FailOnError { get { return _failOnError; } set { _failOnError = value; } } /// /// Determines whether the task should report detailed build log messages. /// The default is . /// [TaskAttribute("verbose")] [BooleanValidator()] public virtual bool Verbose { get { return (_verbose || Project.Verbose); } set { _verbose = value; } } /// /// If then the task will be executed; otherwise, /// skipped. The default is . /// [TaskAttribute("if")] [BooleanValidator()] public bool IfDefined { get { return _ifDefined; } set { _ifDefined = value; } } /// /// Opposite of . If /// then the task will be executed; otherwise, skipped. The default is /// . /// [TaskAttribute("unless")] [BooleanValidator()] public bool UnlessDefined { get { return _unlessDefined; } set { _unlessDefined = value; } } /// /// The name of the task. /// public override string Name { get { string name = null; TaskNameAttribute taskName = (TaskNameAttribute) Attribute.GetCustomAttribute(GetType(), typeof(TaskNameAttribute)); if (taskName != null) { name = taskName.Name; } return name; } } /// /// The prefix used when sending messages to the log. /// [Obsolete("Will be removed soon", false)] public string LogPrefix { get { string prefix = "[" + Name + "] "; return prefix.PadLeft(Project.IndentationSize); } } /// /// Gets or sets the log threshold for this . By /// default the threshold of a task is , /// causing no messages to be filtered in the task itself. /// /// /// The log threshold level for this . /// /// /// When the threshold of a is higher than the /// threshold of the , then all messages will /// still be delivered to the build listeners. /// public Level Threshold { get { return _threshold; } set { _threshold = value; } } #endregion Public Instance Properties #region Internal Instance Properties /// /// Returns the TaskBuilder used to construct an instance of this /// . /// internal TaskBuilder TaskBuilder { get { return TypeFactory.TaskBuilders [Name]; } } #endregion Internal Instance Properties #region Public Instance Methods /// /// Executes the task unless it is skipped. /// public void Execute() { logger.Debug(string.Format( CultureInfo.InvariantCulture, ResourceUtils.GetString("String_TaskExecute"), Name)); if (IfDefined && !UnlessDefined) { try { Project.OnTaskStarted(this, new BuildEventArgs(this)); ExecuteTask(); } catch (Exception ex) { logger.Error(string.Format( CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1077"), Name), ex); if (FailOnError) { throw; } else { if (this.Verbose) { // output exception (with stacktrace) to build log Log(Level.Error, ex.ToString()); } else { string msg = ex.Message; // get first nested exception Exception nestedException = ex.InnerException; // set initial indentation level for the nested exceptions int exceptionIndentationLevel = 0; // output message of nested exceptions while (nestedException != null && !String.IsNullOrEmpty(nestedException.Message)) { // indent exception message with 4 extra spaces // (for each nesting level) exceptionIndentationLevel += 4; // start new line for each exception level msg = (msg != null) ? msg + Environment.NewLine : string.Empty; // output exception message msg += new string(' ', exceptionIndentationLevel) + nestedException.Message; // move on to next inner exception nestedException = nestedException.InnerException; } // output message of exception(s) to build log Log(Level.Error, msg); } } } finally { Project.OnTaskFinished(this, new BuildEventArgs(this)); } } } /// /// Logs a message with the given priority. /// /// The message priority at which the specified message is to be logged. /// The message to be logged. /// /// /// The actual logging is delegated to the project. /// /// /// If the attribute is set on the task and a /// message is logged with level , the /// priority of the message will be increased to /// when the threshold of the build log is . /// /// /// This will allow individual tasks to run in verbose mode while /// the build log itself is still configured with threshold /// . /// /// /// The threshold of the project is not taken into account to determine /// whether a message should be passed to the logging infrastructure, /// as build listeners might be interested in receiving all messages. /// /// public override void Log(Level messageLevel, string message) { if (!IsLogEnabledFor(messageLevel)) { return; } if (_verbose && messageLevel == Level.Verbose && Project.Threshold == Level.Info) { Project.Log(this, Level.Info, message); } else { Project.Log(this, messageLevel, message); } } /// /// Logs a formatted message with the given priority. /// /// The message priority at which the specified message is to be logged. /// The message to log, containing zero or more format items. /// An array containing zero or more objects to format. /// /// /// The actual logging is delegated to the project. /// /// /// If the attribute is set on the task and a /// message is logged with level , the /// priority of the message will be increased to . /// when the threshold of the build log is . /// /// /// This will allow individual tasks to run in verbose mode while /// the build log itself is still configured with threshold /// . /// /// public override void Log(Level messageLevel, string message, params object[] args) { string logMessage = string.Format(CultureInfo.InvariantCulture, message, args); Log(messageLevel, logMessage); } /// /// Determines whether build output is enabled for the given /// . /// /// The to check. /// /// if messages with the given /// should be passed on to the logging infrastructure; otherwise, /// . /// /// /// The threshold of the project is not taken into account to determine /// whether a message should be passed to the logging infrastructure, /// as build listeners might be interested in receiving all messages. /// public bool IsLogEnabledFor(Level messageLevel) { if (_verbose && messageLevel == Level.Verbose) { return Level.Info >= Threshold; } return (messageLevel >= Threshold); } /// /// Initializes the configuration of the task using configuration /// settings retrieved from the NAnt configuration file. /// /// /// TO-DO : Remove this temporary hack when a permanent solution is /// available for loading the default values from the configuration /// file if a build element is constructed from code. /// public void InitializeTaskConfiguration() { PropertyInfo[] properties = GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo propertyInfo in properties) { XmlNode attributeNode = null; string attributeValue = null; FrameworkConfigurableAttribute frameworkAttribute = (FrameworkConfigurableAttribute) Attribute.GetCustomAttribute(propertyInfo, typeof(FrameworkConfigurableAttribute)); if (frameworkAttribute != null) { // locate XML configuration node for current attribute attributeNode = GetAttributeConfigurationNode( Project.TargetFramework, frameworkAttribute.Name); if (attributeNode != null) { // get the configured value attributeValue = attributeNode.InnerText; if (frameworkAttribute.ExpandProperties && Project.TargetFramework != null) { try { // expand attribute properites attributeValue = Project.TargetFramework.Project.Properties.ExpandProperties( attributeValue, Location); } catch (Exception ex) { // throw BuildException if required if (frameworkAttribute.Required) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1075"), frameworkAttribute.Name, Name), Location, ex); } // set value to null attributeValue = null; } } } else { // check if its required if (frameworkAttribute.Required) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "'{0}' is a required framework configuration setting for the '{1}'" + " build element that should be set in the NAnt configuration file.", frameworkAttribute.Name, Name), Location); } } if (attributeValue != null) { if (propertyInfo.CanWrite) { Type propertyType = propertyInfo.PropertyType; //validate attribute value with custom ValidatorAttribute(ors) object[] validateAttributes = (ValidatorAttribute[]) Attribute.GetCustomAttributes(propertyInfo, typeof(ValidatorAttribute)); try { foreach (ValidatorAttribute validator in validateAttributes) { logger.Info(string.Format( CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1074"), attributeValue, Name, validator.GetType().Name)); validator.Validate(attributeValue); } } catch (ValidationException ve) { logger.Error("Validation Exception", ve); throw new ValidationException("Validation failed on" + propertyInfo.DeclaringType.FullName, Location, ve); } // holds the attribute value converted to the property type object propertyValue = null; // If the object is an enum if (propertyType.IsEnum) { try { TypeConverter tc = TypeDescriptor.GetConverter(propertyType); if (!(tc.GetType() == typeof(EnumConverter))) { propertyValue = tc.ConvertFrom(attributeValue); } else { propertyValue = Enum.Parse(propertyType, attributeValue); } } catch (Exception) { // catch type conversion exceptions here string message = "Invalid configuration value \"" + attributeValue + "\". Valid values for this attribute are: "; foreach (object value in Enum.GetValues(propertyType)) { message += value.ToString() + ", "; } // strip last , message = message.Substring(0, message.Length - 2); throw new BuildException(message, Location); } } else { propertyValue = Convert.ChangeType(attributeValue, propertyInfo.PropertyType, CultureInfo.InvariantCulture); } //set property value propertyInfo.SetValue(this, propertyValue, BindingFlags.Public | BindingFlags.Instance, null, null, CultureInfo.InvariantCulture); } } } } } #endregion Public Instance Methods #region Protected Instance Methods /// Initializes the task. protected override void Initialize() { // Just defer for now so that everything just works InitializeTask(XmlNode); } /// Initializes the task. [Obsolete("Deprecated. Use Initialize() instead")] protected virtual void InitializeTask(XmlNode taskNode) { } /// Executes the task. protected abstract void ExecuteTask(); /// /// Locates the XML node for the specified attribute in either the /// configuration section of the extension assembly or the.project. /// /// The name of attribute for which the XML configuration node should be located. /// The framework to use to obtain framework specific information, or if no framework specific information should be used. /// /// The XML configuration node for the specified attribute, or /// if no corresponding XML node could be /// located. /// /// /// If there's a valid current framework, the configuration section for /// that framework will first be searched. If no corresponding /// configuration node can be located in that section, the framework-neutral /// section of the project configuration node will be searched. /// protected override XmlNode GetAttributeConfigurationNode(FrameworkInfo framework, string attributeName) { XmlNode extensionConfig = TaskBuilder.ExtensionAssembly.ConfigurationSection; if (extensionConfig != null) { return base.GetAttributeConfigurationNode(extensionConfig, framework, attributeName); } return base.GetAttributeConfigurationNode(framework, attributeName); } #endregion Protected Instance Methods } }nant-0.92-rc1/src/NAnt.Core/Element.cs0000644000175000017500000024006611757302273017276 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian MacLean (ian@maclean.ms) // Scott Hernandez (ScottHernandez@hotmail.com) // Gert Driesen (drieseng@users.sourceforge.net) // Giuseppe Greco (giuseppe.greco@agamura.com) using System; using System.Collections; using System.Collections.Specialized; using System.ComponentModel; using System.Configuration; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using System.Xml; using NAnt.Core.Attributes; using NAnt.Core.Configuration; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.Core { /// /// Models a NAnt XML element in the build file. /// /// /// /// Automatically validates attributes in the element based on attributes /// applied to members in derived classes. /// /// [Serializable()] public abstract class Element { #region Private Instance Fields private Location _location = Location.UnknownLocation; private Project _project; [NonSerialized()] private XmlNode _xmlNode; private object _parent; [NonSerialized()] private XmlNamespaceManager _nsMgr; #endregion Private Instance Fields #region Private Static Fields private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion Private Static Fields #region Protected Instance Constructors /// /// Initializes a new instance of the class. /// protected Element() { } /// /// Initializes a new instance of the class /// from the specified element. /// /// The element that should be used to create a new instance of the class. protected Element(Element e) : this() { _location = e._location; _project = e._project; _xmlNode = e._xmlNode; _nsMgr = e._nsMgr; } #endregion Protected Instance Constructors #region Public Instance Properties /// /// Gets or sets the parent of the element. /// /// /// The parent of the element. /// /// /// This will be the parent , , or /// depending on where the element is defined. /// public object Parent { get { return _parent; } set { _parent = value; } } /// /// Gets the name of the XML element used to initialize this element. /// /// /// The name of the XML element used to initialize this element. /// public virtual string Name { get { return Element.GetElementNameFromType(GetType()); } } /// /// Gets or sets the to which this element belongs. /// /// /// The to which this element belongs. /// public virtual Project Project { get { return _project; } set { _project = value; } } /// /// Gets the properties local to this and the /// . /// /// /// The properties local to this and the . /// public virtual PropertyDictionary Properties { get { return Project.Properties; } } /// /// Gets or sets the . /// /// /// The . /// /// /// The defines the current namespace /// scope and provides methods for looking up namespace information. /// public XmlNamespaceManager NamespaceManager { get { return _nsMgr; } set { _nsMgr = value; } } #endregion Public Instance Properties #region Protected Instance Properties /// /// Gets or sets the XML node of the element. /// /// /// The XML node of the element. /// protected virtual XmlNode XmlNode { get { return _xmlNode; } set { _xmlNode = value; } } /// /// Gets or sets the location in the build file where the element is /// defined. /// /// /// The location in the build file where the element is defined. /// protected virtual Location Location { get { return _location; } set { _location = value; } } /// /// Gets a value indicating whether the element is performing additional /// processing using the that was used to /// initialize the element. /// /// /// . /// /// /// /// Elements that need to perform additional processing of the /// that was used to initialize the element, should /// override this property and return . /// /// /// When , no build errors will be reported for /// unknown nested build elements. /// /// protected virtual bool CustomXmlProcessing { get { return false; } } #endregion Protected Instance Properties #region Public Instance Methods /// /// Performs default initialization. /// /// /// Derived classes that wish to add custom initialization should override /// the method. /// public void Initialize(XmlNode elementNode) { Initialize(elementNode, Project.Properties, Project.TargetFramework); } /// /// Retrieves the location in the build file where the element is /// defined. /// /// The element's build file location public Location GetLocation() { return Location; } /// /// Logs a message with the given priority. /// /// The message priority at which the specified message is to be logged. /// The message to be logged. /// /// The actual logging is delegated to the project. /// public virtual void Log(Level messageLevel, string message) { if (Project != null) { Project.Log(messageLevel, message); } } /// /// Logs a message with the given priority. /// /// The message priority at which the specified message is to be logged. /// The message to log, containing zero or more format items. /// An array containing zero or more objects to format. /// /// The actual logging is delegated to the project. /// public virtual void Log(Level messageLevel, string message, params object[] args) { if (Project != null) { Project.Log(messageLevel, message, args); } } #endregion Public Instance Methods #region Protected Instance Methods /// /// Derived classes should override to this method to provide extra /// initialization and validation not covered by the base class. /// /// The XML node of the element to use for initialization. [Obsolete("Deprecated. Use Initialize() instead")] protected virtual void InitializeElement(XmlNode elementNode) { } /// /// Derived classes should override to this method to provide extra /// initialization and validation not covered by the base class. /// /// /// Access to the that was used to initialize /// this is available through . /// protected virtual void Initialize() { } /// /// Copies all instance data of the to a given /// . /// protected void CopyTo(Element clone) { clone._location = _location; clone._nsMgr = _nsMgr; clone._parent = _parent; clone._project = _project; if (_xmlNode != null) { clone._xmlNode = _xmlNode.Clone(); } } #endregion Protected Instance Methods #region Internal Instance Methods /// /// Performs initialization using the given set of properties. /// internal void Initialize(XmlNode elementNode, PropertyDictionary properties, FrameworkInfo framework) { if (Project == null) { throw new InvalidOperationException("Element has invalid Project property."); } // save position in buildfile for reporting useful error messages. try { _location = Project.LocationMap.GetLocation(elementNode); } catch (ArgumentException ex) { logger.Warn("Location of Element node could be located.", ex); } InitializeXml(elementNode, properties, framework); // allow inherited classes a chance to do some custom initialization InitializeElement(elementNode); Initialize(); } #endregion Internal Instance Methods #region Protected Instance Methods /// /// Initializes all build attributes and child elements. /// protected virtual void InitializeXml(XmlNode elementNode, PropertyDictionary properties, FrameworkInfo framework) { _xmlNode = elementNode; AttributeConfigurator configurator = new AttributeConfigurator( this, elementNode, properties, framework); configurator.Initialize(); } /// /// Locates the XML node for the specified attribute in the project /// configuration node. /// /// The name of attribute for which the XML configuration node should be located. /// The framework to use to obtain framework specific information, or if no framework specific information should be used. /// /// The XML configuration node for the specified attribute, or /// if no corresponding XML node could be /// located. /// /// /// If there's a valid current framework, the configuration section for /// that framework will first be searched. If no corresponding /// configuration node can be located in that section, the framework-neutral /// section of the project configuration node will be searched. /// protected virtual XmlNode GetAttributeConfigurationNode(FrameworkInfo framework, string attributeName) { return GetAttributeConfigurationNode(Project.ConfigurationNode, framework, attributeName); } #endregion Protected Instance Methods #region Protected Instance Instance Methods protected XmlNode GetAttributeConfigurationNode(XmlNode configSection, FrameworkInfo framework, string attributeName) { XmlNode attributeNode = null; string xpath = ""; int level = 0; #region Construct XPath expression for locating configuration node Element parentElement = this as Element; while (parentElement != null) { if (parentElement is Task) { xpath += " and parent::task[@name=\"" + parentElement.Name + "\""; level++; break; } // For now do not support framework configurable attributes // on nested types. /* } else if (!(parentElement is Target)) { if (parentElement.XmlNode != null) { // perform lookup using name of the node xpath += " and parent::element[@name=\"" + parentElement.XmlNode.Name + "\""; } else { // perform lookup using name of the element xpath += " and parent::element[@name=\"" + parentElement.Name + "\""; } level++; } */ parentElement = parentElement.Parent as Element; } xpath = "descendant::attribute[@name=\"" + attributeName + "\"" + xpath; for (int counter = 0; counter < level; counter++) { xpath += "]"; } xpath += "]"; #endregion Construct XPath expression for locating configuration node #region Retrieve framework-specific configuration node if (framework != null) { // locate framework node for current framework XmlNode frameworkNode = configSection.SelectSingleNode("frameworks/platform[@name=\"" + Project.PlatformName + "\"]/framework[@name=\"" + framework.Name + "\"]", NamespaceManager); if (frameworkNode != null) { // locate framework-specific configuration node attributeNode = frameworkNode.SelectSingleNode(xpath, NamespaceManager); } } #endregion Retrieve framework-specific configuration node #region Retrieve framework-neutral configuration node if (attributeNode == null) { // locate framework-neutral node XmlNode frameworkNeutralNode = configSection.SelectSingleNode( "frameworks/tasks", NamespaceManager); if (frameworkNeutralNode != null) { // locate framework-neutral configuration node attributeNode = frameworkNeutralNode.SelectSingleNode(xpath, NamespaceManager); } } #endregion Retrieve framework-neutral configuration node return attributeNode; } #endregion Protected Instance Instance Methods #region Public Static Methods public static Element InitializeBuildElement(Element parent, XmlNode childNode, Element buildElement, Type elementType) { // if subtype of DataTypeBase DataTypeBase dataType = buildElement as DataTypeBase; if (dataType != null && dataType.CanBeReferenced && childNode.Attributes["refid"] != null ) { dataType.RefID = childNode.Attributes["refid"].Value; if (!String.IsNullOrEmpty(dataType.ID)) { // throw exception because of id and ref throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1183")), parent.Project.LocationMap.GetLocation(childNode)); } if (parent.Project.DataTypeReferences.Contains(dataType.RefID)) { dataType = parent.Project.DataTypeReferences[dataType.RefID]; // clear any instance specific state dataType.Reset(); } else { // reference not found exception throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1184"), dataType.Name, dataType.RefID), parent.Project.LocationMap.GetLocation(childNode)); } if (!elementType.IsAssignableFrom(dataType.GetType())) { // see if we have a valid copy constructor ConstructorInfo constructor = elementType.GetConstructor(new Type[] {dataType.GetType()}); if (constructor != null) { dataType = (DataTypeBase) constructor.Invoke(new object[] {dataType}); } else { ElementNameAttribute dataTypeAttr = (ElementNameAttribute) Attribute.GetCustomAttribute(dataType.GetType(), typeof(ElementNameAttribute)); ElementNameAttribute elementTypeAttr = (ElementNameAttribute) Attribute.GetCustomAttribute(elementType, typeof(ElementNameAttribute)); // throw error wrong type definition throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1185"), dataTypeAttr.Name, elementTypeAttr.Name), parent.Project.LocationMap.GetLocation(childNode)); } } // re-initialize the object with current context dataType.Project = parent.Project; dataType.Parent = parent; dataType.NamespaceManager = parent.NamespaceManager; dataType.Location = parent.Project.LocationMap.GetLocation(childNode); // return initialized data type return dataType; } else { // initialize the object with context buildElement.Project = parent.Project; buildElement.Parent = parent; buildElement.NamespaceManager = parent.NamespaceManager; // initialize element from XML buildElement.Initialize(childNode); // return initialize build element return buildElement; } } #endregion Public Static Methods #region Private Static Methods /// /// Returns the of the /// assigned to the specified /// . /// /// The of which the assigned should be retrieved. /// /// The assigned to the specified /// or a null reference is no /// is assigned to the . /// private static string GetElementNameFromType(Type type) { if (type == null) { throw new ArgumentNullException("type"); } ElementNameAttribute elementNameAttribute = (ElementNameAttribute) Attribute.GetCustomAttribute(type, typeof(ElementNameAttribute), false); if (elementNameAttribute != null) { return elementNameAttribute.Name; } return null; } #endregion Private Static Methods /// /// Configures an using meta-data provided by /// assigned attributes. /// public class AttributeConfigurator { #region Public Instance Constructors /// /// Initializes a new instance of the /// class for the given . /// /// The for which an should be created. /// The to initialize the with. /// The to use for property expansion. /// The framework that the should target. /// /// is . /// -or- /// is . /// -or- /// is . /// public AttributeConfigurator(Element element, XmlNode elementNode, PropertyDictionary properties, FrameworkInfo targetFramework) { if (element == null) { throw new ArgumentNullException("element"); } if (elementNode == null) { throw new ArgumentNullException("elementNode"); } if (properties == null) { throw new ArgumentNullException("properties"); } _element = element; _elementXml = elementNode; _properties = properties; _targetFramework = targetFramework; // collect a list of attributes, we will check to see if we use them all. _unprocessedAttributes = new StringCollection(); foreach (XmlAttribute attribute in elementNode.Attributes) { // skip non-nant namespace attributes if (attribute.NamespaceURI.Length > 0 && !attribute.NamespaceURI.Equals(NamespaceManager.LookupNamespace("nant")) ) { continue; } _unprocessedAttributes.Add(attribute.Name); } // create collection of node names _unprocessedChildNodes = new StringCollection(); foreach (XmlNode childNode in elementNode) { // skip non-nant namespace elements and special elements like comments, pis, text, etc. if (!(childNode.NodeType == XmlNodeType.Element) || !childNode.NamespaceURI.Equals(NamespaceManager.LookupNamespace("nant"))) { continue; } // skip existing names as we only need unique names. if (_unprocessedChildNodes.Contains(childNode.Name)) { continue; } _unprocessedChildNodes.Add(childNode.Name); } } #endregion Public Instance Constructors #region Public Instance Properties public Element Element { get { return _element; } } public Location Location { get { return Element.Location; } } public string Name { get { return Element.Name; } } public Project Project { get { return Element.Project; } } public XmlNode ElementXml { get { return _elementXml; } } public PropertyDictionary Properties { get { return _properties; } } public FrameworkInfo TargetFramework { get { return _targetFramework; } } public StringCollection UnprocessedAttributes { get { return _unprocessedAttributes; } } public StringCollection UnprocessedChildNodes { get { return _unprocessedChildNodes; } } /// /// Gets the . /// /// /// The . /// /// /// The defines the current namespace /// scope and provides methods for looking up namespace information. /// public XmlNamespaceManager NamespaceManager { get { return Element.NamespaceManager; } } #endregion Public Instance Properties #region Public Instance Methods public void Initialize() { Type currentType = Element.GetType(); PropertyInfo[] propertyInfoArray = currentType.GetProperties( BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic); // loop through all the properties in the derived class. foreach (PropertyInfo propertyInfo in propertyInfoArray) { MethodInfo getter = null; MethodInfo setter = null; setter = propertyInfo.GetSetMethod(true); if (setter != null && !(setter.IsPublic || setter.IsFamily)) { setter = null; } getter = propertyInfo.GetGetMethod(true); if (getter != null && !(getter.IsPublic || getter.IsFamily)) { getter = null; } // skip properties that are not public or protected if (getter == null && setter == null) continue; if (InitializeAttribute(propertyInfo)) { continue; } if (InitializeBuildElementCollection(propertyInfo)) { continue; } if (InitializeChildElement(propertyInfo, getter, setter)) { continue; } } // also support child elements that are backed by methods // we need this in order to support ordered child elements InitializeOrderedChildElements(); // skip checking for anything in target if(!(currentType.Equals(typeof(Target)) || currentType.IsSubclassOf(typeof(Target)))) { // check if there are unused attributes if (UnprocessedAttributes.Count > 0) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1027"), UnprocessedAttributes[0], ElementXml.Name), Location); } if (!Element.CustomXmlProcessing) { // check if there are unused nested build elements if (UnprocessedChildNodes.Count > 0) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1032"), ElementXml.Name, UnprocessedChildNodes[0]), Location); } } } } protected virtual bool InitializeAttribute(PropertyInfo propertyInfo) { XmlNode attributeNode = null; string attributeValue = null; XmlNode frameworkAttributeNode = null; #region Initialize property using framework configuration FrameworkConfigurableAttribute frameworkAttribute = (FrameworkConfigurableAttribute) Attribute.GetCustomAttribute(propertyInfo, typeof(FrameworkConfigurableAttribute), false); if (frameworkAttribute != null) { // locate XML configuration node for current attribute frameworkAttributeNode = Element.GetAttributeConfigurationNode( TargetFramework, frameworkAttribute.Name); if (frameworkAttributeNode != null) { // get the configured value attributeValue = frameworkAttributeNode.InnerText; if (frameworkAttribute.ExpandProperties && TargetFramework != null) { try { // expand attribute properties attributeValue = TargetFramework.Project.Properties.ExpandProperties( attributeValue, Location); } catch (BuildException ex) { // throw BuildException if required if (frameworkAttribute.Required) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1015"), frameworkAttribute.Name, ElementXml.Name), Location, ex); } // set value to null attributeValue = null; } } } else { // check if the attribute is required if (frameworkAttribute.Required) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1015"), frameworkAttribute.Name, ElementXml.Name), Location); } } } #endregion Initialize property using framework configuration #region Initialize property with an assigned BuildAttribute // process all BuildAttribute attributes BuildAttributeAttribute buildAttribute = (BuildAttributeAttribute) Attribute.GetCustomAttribute(propertyInfo, typeof(BuildAttributeAttribute), false); if (buildAttribute != null) { logger.Debug(string.Format( CultureInfo.InvariantCulture, ResourceUtils.GetString("String_FoundAttribute"), buildAttribute.Name, propertyInfo.DeclaringType.FullName)); if (ElementXml != null) { // locate attribute in build file attributeNode = ElementXml.Attributes[buildAttribute.Name]; } if (attributeNode != null) { // remove processed attribute name UnprocessedAttributes.Remove(attributeNode.Name); // if we don't process the xml then skip on if (!buildAttribute.ProcessXml) { logger.Debug(string.Format( CultureInfo.InvariantCulture, ResourceUtils.GetString("String_SkippingAttribute"), buildAttribute.Name, propertyInfo.DeclaringType.FullName)); // consider this property done return true; } // get the configured value attributeValue = attributeNode.Value; if (buildAttribute.ExpandProperties) { // expand attribute properites attributeValue = Properties.ExpandProperties(attributeValue, Location); } // check if property is deprecated ObsoleteAttribute obsoleteAttribute = (ObsoleteAttribute) Attribute.GetCustomAttribute(propertyInfo, typeof(ObsoleteAttribute)); // emit warning or error if attribute is deprecated if (obsoleteAttribute != null) { string obsoleteMessage = string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1014"), buildAttribute.Name, ElementXml.Name, obsoleteAttribute.Message); if (obsoleteAttribute.IsError) { throw new BuildException(obsoleteMessage, Location); } else { Element.Log(Level.Warning, Location.ToString() + " " + obsoleteMessage); } } } else { // check if attribute is required if (buildAttribute.Required) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1033"), buildAttribute.Name, ElementXml.Name), Location); } } } #endregion Initialize property with an assigned BuildAttribute if (attributeValue != null) { // if attribute was not encountered in the build file, but // still has a value, then it was configured in the framework // section of the NAnt configuration file if (attributeNode == null) { attributeNode = frameworkAttributeNode; } logger.Debug(string.Format( CultureInfo.InvariantCulture, ResourceUtils.GetString("String_SettingValue"), propertyInfo.Name, attributeValue, propertyInfo.DeclaringType.Name)); if (propertyInfo.CanWrite) { // get the type of the property Type propertyType = propertyInfo.PropertyType; // validate attribute value with custom ValidatorAttribute(ors) object[] validateAttributes = (ValidatorAttribute[]) Attribute.GetCustomAttributes(propertyInfo, typeof(ValidatorAttribute)); try { foreach (ValidatorAttribute validator in validateAttributes) { logger.Info(string.Format( CultureInfo.InvariantCulture, ResourceUtils.GetString("String_ValidatingElement"), validator.GetType().Name, ElementXml.Name, attributeNode.Name)); validator.Validate(attributeValue); } } catch (ValidationException ve) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1022"), attributeValue, attributeNode.Name, ElementXml.Name), Location, ve); } // create an attribute setter for the type of the property IAttributeSetter attributeSetter = CreateAttributeSetter(propertyType); // set the property value attributeSetter.Set(attributeNode, Element, propertyInfo, attributeValue); // if a value is assigned to the property, we consider // it done return true; } } // if a BuildAttribute was assigned to the property, then // there's no need to try to initialize this property as a // collection or nested element return (buildAttribute != null); } protected virtual bool InitializeBuildElementCollection(PropertyInfo propertyInfo) { BuildElementArrayAttribute buildElementArrayAttribute = null; BuildElementCollectionAttribute buildElementCollectionAttribute = null; // do build element arrays (assuming they are of a certain collection type.) buildElementArrayAttribute = (BuildElementArrayAttribute) Attribute.GetCustomAttribute(propertyInfo, typeof(BuildElementArrayAttribute), false); buildElementCollectionAttribute = (BuildElementCollectionAttribute) Attribute.GetCustomAttribute(propertyInfo, typeof(BuildElementCollectionAttribute), false); if (buildElementArrayAttribute == null && buildElementCollectionAttribute == null) { // continue trying to initialize property return false; } if (!propertyInfo.PropertyType.IsArray && !(typeof(ICollection).IsAssignableFrom(propertyInfo.PropertyType))) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1031"), buildElementArrayAttribute.Name, Name), Location); } Type elementType = null; // determine type of child elements if (buildElementArrayAttribute != null) { elementType = buildElementArrayAttribute.ElementType; } else { elementType = buildElementCollectionAttribute.ElementType; } if (propertyInfo.PropertyType.IsArray) { if (!propertyInfo.CanWrite) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1016"), buildElementArrayAttribute.Name, Name), Location); } if (elementType == null) { elementType = propertyInfo.PropertyType.GetElementType(); } } else { if (!propertyInfo.CanRead) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1019"), buildElementArrayAttribute.Name, Name), Location); } if (elementType == null) { // locate Add method with 1 parameter, type of that parameter is parameter type foreach (MethodInfo method in propertyInfo.PropertyType.GetMethods(BindingFlags.Public | BindingFlags.Instance)) { if (method.Name == "Add" && method.GetParameters().Length == 1) { ParameterInfo parameter = method.GetParameters()[0]; elementType = parameter.ParameterType; break; } } } } // make sure the element is strongly typed if (elementType == null || !typeof(Element).IsAssignableFrom(elementType)) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1140"), propertyInfo.PropertyType.FullName, propertyInfo.Name), Location); } XmlNodeList collectionNodes = null; if (buildElementCollectionAttribute != null) { collectionNodes = ElementXml.SelectNodes("nant:" + buildElementCollectionAttribute.Name, NamespaceManager); if (collectionNodes.Count == 0 && buildElementCollectionAttribute.Required) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1021"), buildElementCollectionAttribute.Name, ElementXml.Name), Location); } if (collectionNodes.Count == 1) { // check if property is deprecated ObsoleteAttribute obsoleteAttribute = (ObsoleteAttribute) Attribute.GetCustomAttribute(propertyInfo, typeof(ObsoleteAttribute)); // emit warning or error if attribute is deprecated if (obsoleteAttribute != null) { string obsoleteMessage = string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1034"), buildElementCollectionAttribute.Name, ElementXml.Name, obsoleteAttribute.Message); if (obsoleteAttribute.IsError) { throw new BuildException(obsoleteMessage, Location); } else { Element.Log(Level.Warning, Location.ToString() + " " + obsoleteMessage); } } // remove element from list of remaining items UnprocessedChildNodes.Remove(collectionNodes[0].Name); string elementName = buildElementCollectionAttribute.ChildElementName; if (elementName == null) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1026"), elementType.FullName, buildElementCollectionAttribute.Name, Name), Location); } // get actual collection of element nodes collectionNodes = collectionNodes[0].SelectNodes("nant:" + elementName, NamespaceManager); // check if its required if (collectionNodes.Count == 0 && buildElementCollectionAttribute.Required) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1021"), elementName, buildElementCollectionAttribute.Name), Location); } } else if (collectionNodes.Count > 1) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1030"), buildElementCollectionAttribute.Name, Name), Location); } } else { collectionNodes = ElementXml.SelectNodes("nant:" + buildElementArrayAttribute.Name, NamespaceManager); if (collectionNodes.Count > 0) { // check if property is deprecated ObsoleteAttribute obsoleteAttribute = (ObsoleteAttribute) Attribute.GetCustomAttribute(propertyInfo, typeof(ObsoleteAttribute)); // emit warning or error if attribute is deprecated if (obsoleteAttribute != null) { string obsoleteMessage = string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1034"), buildElementArrayAttribute.Name, ElementXml.Name, obsoleteAttribute.Message); if (obsoleteAttribute.IsError) { throw new BuildException(obsoleteMessage, Location); } else { Element.Log(Level.Warning, Location.ToString() + " " + obsoleteMessage); } } // remove element from list of remaining items UnprocessedChildNodes.Remove(collectionNodes[0].Name); } else if (buildElementArrayAttribute.Required) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1035"), buildElementArrayAttribute.Name, ElementXml.Name), Location); } } if (buildElementArrayAttribute != null) { if (!buildElementArrayAttribute.ProcessXml) { return true; } } else if (!buildElementCollectionAttribute.ProcessXml) { return true; } // create new array of the required size - even if size is 0 Array list = Array.CreateInstance(elementType, collectionNodes.Count); int arrayIndex = 0; foreach (XmlNode childNode in collectionNodes) { // skip non-nant namespace elements and special elements like comments, pis, text, etc. if (!(childNode.NodeType == XmlNodeType.Element) || !childNode.NamespaceURI.Equals(NamespaceManager.LookupNamespace("nant"))) { continue; } // create and initialize child element (from XML or data type reference) Element childElement = InitializeBuildElement(childNode, elementType); // check if element should actually be added ConditionalElement conditional = childElement as ConditionalElement; if (conditional != null && !conditional.Enabled) { continue; } // set element in array list.SetValue(childElement, arrayIndex); // move to next index position in array arrayIndex++; } if (propertyInfo.PropertyType.IsArray) { try { if (arrayIndex != list.Length) { // create a new array with a size that exactly matches // the number of initialized elements Array final = Array.CreateInstance(elementType, arrayIndex); // copy initialized entries to new array Array.Copy(list, 0, final, 0, arrayIndex); // set the member array to our newly created array propertyInfo.SetValue(Element, final, null); } else { // set the member array to our newly created array propertyInfo.SetValue(Element, list, null); } } catch (TargetInvocationException ex) { if (ex.InnerException is BuildException) { throw ex.InnerException; } throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1012"), elementType.FullName, propertyInfo.PropertyType.FullName, propertyInfo.Name, Name), Location, ex); } } else { MethodInfo addMethod = null; // get array of public instance methods MethodInfo[] addMethods = propertyInfo.PropertyType.GetMethods(BindingFlags.Public | BindingFlags.Instance); // search for a method called 'Add' which accepts a parameter // to which the element type is assignable foreach (MethodInfo method in addMethods) { if (method.Name == "Add" && method.GetParameters().Length == 1) { ParameterInfo parameter = method.GetParameters()[0]; if (parameter.ParameterType.IsAssignableFrom(elementType)) { addMethod = method; break; } } } if (addMethod == null) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1020"), elementType.FullName, propertyInfo.PropertyType.FullName, propertyInfo.Name, Name), Location); } // if value of property is null, create new instance of collection object collection = propertyInfo.GetValue(Element, BindingFlags.Default, null, null, CultureInfo.InvariantCulture); if (collection == null) { if (!propertyInfo.CanWrite) { if (buildElementArrayAttribute != null) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1093"), buildElementArrayAttribute.Name, Name), Location); } else { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1029"), buildElementCollectionAttribute.Name, Name), Location); } } object instance = Activator.CreateInstance( propertyInfo.PropertyType, BindingFlags.Public | BindingFlags.Instance, null, null, CultureInfo.InvariantCulture); propertyInfo.SetValue(Element, instance, BindingFlags.Default, null, null, CultureInfo.InvariantCulture); } // add each element of the array to collection instance for (int i = 0; i < arrayIndex; i++) { object child = list.GetValue(i); addMethod.Invoke(collection, BindingFlags.Default, null, new object[] {child}, CultureInfo.InvariantCulture); } } return true; } protected virtual bool InitializeChildElement(PropertyInfo propertyInfo, MethodInfo getter, MethodInfo setter) { // now do nested BuildElements BuildElementAttribute buildElementAttribute = (BuildElementAttribute) Attribute.GetCustomAttribute(propertyInfo, typeof(BuildElementAttribute), false); if (buildElementAttribute == null) { return false; } // will hold the XML node XmlNode nestedElementNode; // when element is initialized from application configuration file, // there's no DocumentElement if (ElementXml.OwnerDocument.DocumentElement == null) { nestedElementNode = ElementXml[buildElementAttribute.Name]; } else { nestedElementNode = ElementXml[buildElementAttribute.Name, ElementXml.OwnerDocument.DocumentElement.NamespaceURI]; } // check if its required if (nestedElementNode == null && buildElementAttribute.Required) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1013"), buildElementAttribute.Name, ElementXml.Name), Location); } if (nestedElementNode != null) { //remove item from list. Used to account for each child xmlelement. UnprocessedChildNodes.Remove(nestedElementNode.Name); if (!buildElementAttribute.ProcessXml) { return true; } // create the child build element; not needed directly. It will be assigned to the local property. CreateChildBuildElement(propertyInfo, getter, setter, nestedElementNode, Properties, TargetFramework); // output warning to build log when multiple nested elements // were specified in the build file, as NAnt will only process // the first element it encounters if (ElementXml.SelectNodes("nant:" + buildElementAttribute.Name, NamespaceManager).Count > 1) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1186"), ElementXml.Name, buildElementAttribute.Name), Location); } } return true; } protected virtual void InitializeOrderedChildElements() { // first, we'll fill a hashtable with public methods that take // a single argument and to which a BuildElementAttribute is // assigned Hashtable childElementMethods = new Hashtable(); // will hold list of required methods, in order to check missing // required elements Hashtable requiredMethods = new Hashtable(); MethodInfo[] methods = Element.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance); foreach (MethodInfo method in methods) { ParameterInfo[] parameters = method.GetParameters(); // we're only interested in methods with one argument, meaning // the element if (parameters.Length != 1) { continue; } // ignore methods that do not have a BuildElementAttribute // assigned to it object[] buildElementAttributes = method.GetCustomAttributes( typeof(BuildElementAttribute), true); if (buildElementAttributes.Length == 0) { continue; } BuildElementAttribute buildElementAttribute = (BuildElementAttribute) buildElementAttributes[0]; childElementMethods.Add(buildElementAttribute.Name, method); if (buildElementAttribute.Required) { requiredMethods.Add(buildElementAttribute.Name, method); } } // keep track of nodes that were processed as ordered build // elements StringCollection processedNodes = new StringCollection(); foreach (XmlNode childNode in ElementXml.ChildNodes) { string elementName = childNode.Name; // skip childnodes that have already been processed // (by other means) if (!UnprocessedChildNodes.Contains(elementName)) { continue; } // skip child nodes for which no init method exists MethodInfo method = (MethodInfo) childElementMethods[elementName]; if (method == null) { continue; } // mark node as processed (as an ordered build element) if (!processedNodes.Contains(elementName)) { processedNodes.Add(elementName); } // ensure method is marked processed if (requiredMethods.ContainsKey(elementName)) { requiredMethods.Remove(elementName); } // obtain buildelementattribute to check whether xml // should be processed BuildElementAttribute buildElementAttribute = (BuildElementAttribute) Attribute.GetCustomAttribute(method, typeof(BuildElementAttribute), false); if (!buildElementAttribute.ProcessXml) { continue; } // methods should have an argument of a type that derives // from Element Type childElementType = method.GetParameters()[0].ParameterType; // create and initialize the element (from XML or datatype reference) Element element = InitializeBuildElement(childNode, childElementType); try { // invoke method, passing in the initialized element method.Invoke(Element, BindingFlags.InvokeMethod, null, new object[] {element}, CultureInfo.InvariantCulture); } catch (TargetInvocationException ex) { if (ex.InnerException != null) { throw ex.InnerException; } throw; } } // permanently mark nodes as processed foreach (string node in processedNodes) { UnprocessedChildNodes.Remove(node); } // finally check if there are methods that are required, and for // which no element was specified in the build file if (requiredMethods.Count > 0) { foreach (DictionaryEntry entry in requiredMethods) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1021"), (string) entry.Key, ElementXml.Name), Location); } } } protected virtual Element InitializeBuildElement(XmlNode childNode, Type elementType) { if (!typeof(Element).IsAssignableFrom(elementType)) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1187"), childNode.Name, elementType.FullName), Location); } // create a child element Element childElement = (Element) Activator.CreateInstance( elementType, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, null, CultureInfo.InvariantCulture); // initialize the element return Element.InitializeBuildElement(Element, childNode, childElement, elementType); } #endregion Public Instance Methods #region Private Instance Methods /// /// Creates a child using property set/get methods. /// /// The instance that represents the property of the current class. /// A representing the get accessor for the property. /// A representing the set accessor for the property. /// The used to initialize the new instance. /// The collection of property values to use for macro expansion. /// The from which to obtain framework-specific information. /// The child. private Element CreateChildBuildElement(PropertyInfo propInf, MethodInfo getter, MethodInfo setter, XmlNode xml, PropertyDictionary properties, FrameworkInfo framework) { Element childElement = null; Type elementType = null; // if there is a getter, then get the current instance of the object, and use that if (getter != null) { try { childElement = (Element) propInf.GetValue(Element, null); } catch (InvalidCastException) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1188"), propInf.Name, Element.GetType().FullName, propInf.PropertyType.FullName, typeof(Element).FullName), Location); } if (childElement == null) { if (setter == null) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1189"), propInf.Name, Element.GetType().FullName), Location); } else { // fake the getter as null so we process the rest like there is no getter getter = null; logger.Info(string.Format(CultureInfo.InvariantCulture,"{0}_get() returned null; will go the route of set method to populate.", propInf.Name)); } } else { elementType = childElement.GetType(); } } // create a new instance of the object if there is no get method // or the get object returned null if (getter == null) { elementType = setter.GetParameters()[0].ParameterType; if (elementType.IsAbstract) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("String_AbstractType"), elementType.Name, propInf.Name, Name)); } childElement = (Element) Activator.CreateInstance(elementType, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, null , CultureInfo.InvariantCulture); } // initialize the child element childElement = Element.InitializeBuildElement(Element, xml, childElement, elementType); // check if we're dealing with a reference to a data type DataTypeBase dataType = childElement as DataTypeBase; if (dataType != null && xml.Attributes["refid"] != null) { // references to data type should be always be set if (setter == null) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1190"), propInf.Name, this.GetType().FullName), Location); } // re-set the getter (for force the setter to be used) getter = null; } // call the set method if we created the object if (setter != null && getter == null) { setter.Invoke(Element, new object[] {childElement}); } // return the new/used object return childElement; } /// /// Creates an for the given /// . /// /// The for which an should be created. /// /// An for the given . /// private IAttributeSetter CreateAttributeSetter(Type attributeType) { if (AttributeSetters.ContainsKey(attributeType)) { return (IAttributeSetter) AttributeSetters[attributeType]; } IAttributeSetter attributeSetter = null; if (attributeType.IsEnum) { attributeSetter = new EnumAttributeSetter(); } else if (attributeType == typeof(Encoding)) { attributeSetter = new EncodingAttributeSetter(); } else if (attributeType == typeof(FileInfo)) { attributeSetter = new FileAttributeSetter(); } else if (attributeType == typeof(DirectoryInfo)) { attributeSetter = new DirectoryAttributeSetter(); } else if (attributeType == typeof(PathSet)) { attributeSetter = new PathSetAttributeSetter(); } else if (attributeType == typeof(Uri)) { attributeSetter = new UriAttributeSetter(); } else { attributeSetter = new ConvertableAttributeSetter(); } if (attributeSetter != null) { AttributeSetters.Add(attributeType, attributeSetter); } return attributeSetter; } #endregion Private Instance Methods #region Private Instance Fields /// /// Holds the that should be initialized. /// private readonly Element _element; /// /// Holds the that should be used to initialize /// the . /// private readonly XmlNode _elementXml; /// /// Holds the dictionary that should be used for property /// expansion. /// private readonly PropertyDictionary _properties; /// /// Holds the framework that should be targeted by the /// that we're configuring, or /// if there's no current target /// framework. /// private readonly FrameworkInfo _targetFramework; /// /// Holds the names of the attributes that still need to be /// processed. /// private readonly StringCollection _unprocessedAttributes; /// /// Holds the names of the child nodes that still need to be /// processed. /// private readonly StringCollection _unprocessedChildNodes; #endregion Private Instance Fields #region Private Static Fields /// /// Holds the logger for the current class. /// private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); /// /// Holds the cache of instances. /// private static Hashtable AttributeSetters = new Hashtable(); #endregion Private Static Fields private class EnumAttributeSetter : IAttributeSetter { public void Set(XmlNode attributeNode, Element parent, PropertyInfo property, string value) { try { object propertyValue; // check for more specific type converter TypeConverter tc = TypeDescriptor.GetConverter(property.PropertyType); if (!(tc.GetType() == typeof(EnumConverter))) { propertyValue = tc.ConvertFrom(value); } else { propertyValue = Enum.Parse(property.PropertyType, value); } property.SetValue(parent, propertyValue, BindingFlags.Public | BindingFlags.Instance, null, null, CultureInfo.InvariantCulture); } catch (FormatException) { throw CreateBuildException(attributeNode, parent, property, value); } catch (ArgumentException) { throw CreateBuildException(attributeNode, parent, property, value); } } private BuildException CreateBuildException(XmlNode attributeNode, Element parent, PropertyInfo property, string value) { StringBuilder sb = new StringBuilder(); foreach (object field in Enum.GetValues(property.PropertyType)) { if (sb.Length > 0) { sb.Append(", "); } sb.Append(field.ToString()); } string message = string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1023"), value, attributeNode.Name, parent.Name, sb.ToString()); return new BuildException(message, parent.Location); } } private class EncodingAttributeSetter : IAttributeSetter { public void Set(XmlNode attributeNode, Element parent, PropertyInfo property, string value) { string encodingName = StringUtils.ConvertEmptyToNull(value); if (encodingName == null) { return; } Encoding encoding = null; try { encoding = System.Text.Encoding.GetEncoding( encodingName); } catch (ArgumentException) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1191"), encodingName), parent.Location); } catch (NotSupportedException) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1192"), encodingName), parent.Location); } try { property.SetValue(parent, encoding, BindingFlags.Public | BindingFlags.Instance, null, null, CultureInfo.InvariantCulture); } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1022"), value, attributeNode.Name, parent.Name), parent.Location, ex); } } } private class FileAttributeSetter : IAttributeSetter { public void Set(XmlNode attributeNode, Element parent, PropertyInfo property, string value) { string path = StringUtils.ConvertEmptyToNull(value); if (path != null) { object propertyValue; try { propertyValue = new FileInfo(parent.Project.GetFullPath(value)); } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1022"), value, attributeNode.Name, parent.Name), parent.Location, ex); } try { property.SetValue(parent, propertyValue, BindingFlags.Public | BindingFlags.Instance, null, null, CultureInfo.InvariantCulture); } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1022"), value, attributeNode.Name, parent.Name), parent.Location, ex); } } else { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1193"), attributeNode.Name, parent.Name), parent.Location); } } } private class DirectoryAttributeSetter : IAttributeSetter { public void Set(XmlNode attributeNode, Element parent, PropertyInfo property, string value) { string path = StringUtils.ConvertEmptyToNull(value); if (path != null) { try { object propertyValue = new DirectoryInfo( parent.Project.GetFullPath(value)); property.SetValue(parent, propertyValue, BindingFlags.Public | BindingFlags.Instance, null, null, CultureInfo.InvariantCulture); } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1022"), value, attributeNode.Name, parent.Name), parent.Location, ex); } } else { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1193"), attributeNode.Name, parent.Name), parent.Location); } } } private class PathSetAttributeSetter : IAttributeSetter { public void Set(XmlNode attributeNode, Element parent, PropertyInfo property, string value) { try { PathSet propertyValue = new PathSet(parent.Project, value); property.SetValue(parent, propertyValue, BindingFlags.Public | BindingFlags.Instance, null, null, CultureInfo.InvariantCulture); } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1022"), value, attributeNode.Name, parent.Name), parent.Location, ex); } } } private class UriAttributeSetter : IAttributeSetter { public void Set(XmlNode attributeNode, Element parent, PropertyInfo property, string value) { string uri = StringUtils.ConvertEmptyToNull(value); if (uri != null) { Uri propertyValue; // if uri does not contain a scheme, we'll consider it // to be a normal path and as such we need to resolve // it to an absolute path (relative to project base // directory if (value.IndexOf(Uri.SchemeDelimiter) == -1) { uri = parent.Project.GetFullPath(value); } try { propertyValue = new Uri(uri); } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1022"), value, attributeNode.Name, parent.Name), parent.Location, ex); } try { property.SetValue(parent, propertyValue, BindingFlags.Public | BindingFlags.Instance, null, null, CultureInfo.InvariantCulture); } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1022"), value, attributeNode.Name, parent.Name), parent.Location, ex); } } else { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1193"), attributeNode.Name, parent.Name), parent.Location); } } } private class ConvertableAttributeSetter : IAttributeSetter { public void Set(XmlNode attributeNode, Element parent, PropertyInfo property, string value) { try { object propertyValue = Convert.ChangeType(value, property.PropertyType, CultureInfo.InvariantCulture); property.SetValue(parent, propertyValue, BindingFlags.Public | BindingFlags.Instance, null, null, CultureInfo.InvariantCulture); } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1022"), value, attributeNode.Name, parent.Name), parent.Location, ex); } } } /// /// Internal interface used for setting element attributes. /// private interface IAttributeSetter { void Set(XmlNode attributeNode, Element parent, PropertyInfo property, string value); } } } } nant-0.92-rc1/src/NAnt.Core/CommandLineOptions.cs0000644000175000017500000003230511757302272021441 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections.Specialized; using System.IO; using NAnt.Core.Util; namespace NAnt.Core { /// /// Represents the set of command-line options supported by NAnt. /// public class CommandLineOptions { #region Public Instance Properties /// /// Gets or sets the target framework to use (overrides /// NAnt.exe.config settings) /// /// /// The framework that should be used. /// /// /// For a list of possible frameworks, see NAnt.exe.config, possible /// values include "net-1.0", "net-1.1", etc. /// [CommandLineArgument(CommandLineArgumentTypes.AtMostOnce, Name="targetframework", ShortName="t", Description="Specifies the framework to target")] public string TargetFramework { get { return _targetFramework; } set { _targetFramework = value; } } /// /// Gets or sets the target framework to use (overrides /// NAnt.exe.config settings) /// /// /// The framework that should be used. /// /// /// For a list of possible frameworks, see NAnt.exe.config, possible /// values include "net-1.0", "net-1.1", etc. /// [CommandLineArgument(CommandLineArgumentTypes.AtMostOnce, Name="defaultframework", ShortName="k", Description="Specifies the framework to target")] [Obsolete("Use the -[t]argetframework option instead.", false)] public string DefaultFramework { get { return _targetFramework; } set { _targetFramework = value; } } /// /// Gets or sets the buildfile that should be executed. /// /// /// The buildfile that should be executed. /// /// /// Can be both a file or an URI. /// [CommandLineArgument(CommandLineArgumentTypes.AtMostOnce, Name="buildfile", ShortName="f", Description="Use given buildfile")] public string BuildFile { get { return _buildFile; } set { _buildFile = value; } } /// /// Pauses before program ends. /// /// /// for pausing on program end; /// otherwise, . The default is . /// [CommandLineArgument(CommandLineArgumentTypes.AtMostOnce, Name = "pause", Description = "Pauses before program ends")] public bool Pause { get { return _pause; } set { _pause = value; } } /// /// Gets or sets a value indicating whether more information should be /// displayed during the build process. /// /// /// if more information should be displayed; /// otherwise, . The default is . /// [CommandLineArgument(CommandLineArgumentTypes.AtMostOnce, Name = "verbose", ShortName="v", Description = "Displays more information during build process")] public bool Verbose { get { return _verbose; } set { _verbose = value; } } /// /// Gets or sets a value indicating whether debug information should be /// displayed during the build process. /// /// /// if debug information should be displayed; /// otherwise, . The default is . /// [CommandLineArgument(CommandLineArgumentTypes.AtMostOnce, Name = "debug", Description = "Displays debug information during build process")] public bool Debug { get { return _debug; } set { _debug = value; } } /// /// Gets or sets a value indicating whether only error and debug debug messages should be /// displayed during the build process. /// /// /// if only error or warning messages should be /// displayed; otherwise, . The default is /// . /// [CommandLineArgument(CommandLineArgumentTypes.AtMostOnce, Name = "quiet", ShortName="q", Description = "Displays only error or warning messages during build process")] public bool Quiet { get { return _quiet; } set { _quiet = value; } } /// /// Gets or sets a value indicating whether to produce emacs (and other /// editor) friendly output. /// /// /// if output is to be unadorned so that emacs /// and other editors can parse files names, etc. The default is /// . /// [CommandLineArgument(CommandLineArgumentTypes.AtMostOnce, Name = "emacs", ShortName="e", Description = "Produce logging information without adornments")] public bool EmacsMode { get { return _emacsMode; } set { _emacsMode = value; } } /// /// Gets a value indicating whether parent directories should be searched /// for a buildfile. /// /// /// if parent directories should be searched for /// a build file; otherwise, . The default is /// . /// [CommandLineArgument(CommandLineArgumentTypes.AtMostOnce, Name = "find", Description = "Search parent directories for build file")] public bool FindInParent { get { return _findInParent; } set { _findInParent = value; } } /// /// Gets or sets the indentation level of the build output. /// /// /// The indentation level of the build output. The default is 0. /// [CommandLineArgument(CommandLineArgumentTypes.AtMostOnce, Name = "indent", Description = "Indentation level of build output")] public int IndentationLevel { get { return _indentationLevel; } set { _indentationLevel = value; } } /// /// Gets or sets the list of properties that should be set. /// /// /// The list of properties that should be set. /// [CommandLineArgument(CommandLineArgumentTypes.MultipleUnique, Name = "D", Description = "Use value for given property")] public NameValueCollection Properties { get { return _properties; } } /// /// Gets or sets the of logger to add to the list /// of listeners. /// /// /// The of logger to add to the list of /// listeners. /// /// /// The should derive from . /// [CommandLineArgument(CommandLineArgumentTypes.AtMostOnce, Name="logger", Description="Use given type as logger")] public string LoggerType { get { return _loggerType; } set { _loggerType = value; } } /// /// Gets or sets the name of the file to log output to. /// /// /// The name of the file to log output to. /// [CommandLineArgument(CommandLineArgumentTypes.AtMostOnce, Name="logfile", ShortName="l", Description="Use value as name of log output file")] public FileInfo LogFile { get { return _logFile; } set { _logFile = value; } } /// /// Gets a collection containing fully qualified type names of classes /// implementating that should be added /// to the project as listeners. /// /// /// A collection of fully qualified type names that should be added as /// listeners to the . /// [CommandLineArgument(CommandLineArgumentTypes.MultipleUnique, Name="listener", Description="Add an instance of class as a project listener")] public StringCollection Listeners { get { return _listeners; } } /// /// Gets a collection of assemblies to load extensions from. /// /// /// A collection of assemblies to load extensions from. /// [CommandLineArgument(CommandLineArgumentTypes.MultipleUnique, Name="extension", ShortName="ext", Description="Load NAnt extensions from the specified assembly")] public StringCollection ExtensionAssemblies { get { return _extensionAssemblies; } } /// /// Gets or sets a value indicating whether help /// should be printed. /// /// /// if help should be /// printed; otherwise, . The default is /// . /// [CommandLineArgument(CommandLineArgumentTypes.AtMostOnce, Name = "projecthelp", Description = "Prints project help information")] public bool ShowProjectHelp { get { return _showProjectHelp; } set { _showProjectHelp = value; } } /// /// Gets or sets a value indicating whether the logo banner should be /// printed. /// /// /// if the logo banner should be printed; otherwise, /// . The default is . /// [CommandLineArgument(CommandLineArgumentTypes.AtMostOnce, Name = "nologo", Description = "Suppresses display of the logo banner")] public bool NoLogo { get { return _noLogo; } set { _noLogo = value; } } /// /// Gets or sets a value indicating whether the NAnt help should be /// printed. /// /// /// if NAnt help should be printed; otherwise, /// . The default is . /// [CommandLineArgument(CommandLineArgumentTypes.Exclusive, Name = "help", ShortName = "h", Description = "Prints this message")] public bool ShowHelp { get { return _showHelp; } set { _showHelp = value; } } /// /// Gets a collection containing the targets that should be executed. /// /// /// A collection that contains the targets that should be executed. /// [DefaultCommandLineArgument(CommandLineArgumentTypes.MultipleUnique, Name="target")] public StringCollection Targets { get { return _targets; } } #endregion Public Instance Properties #region Private Instance Fields private string _targetFramework; private string _buildFile; private bool _noLogo; private bool _showHelp; private bool _quiet; private bool _verbose; private bool _debug; private bool _emacsMode; private int _indentationLevel = 0; private bool _findInParent; private NameValueCollection _properties = new NameValueCollection(); private string _loggerType; private FileInfo _logFile; private StringCollection _listeners = new StringCollection(); private StringCollection _extensionAssemblies = new StringCollection(); private StringCollection _targets = new StringCollection(); private bool _showProjectHelp; private bool _pause; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.Core/TaskBuilder.cs0000644000175000017500000001132211757302273020105 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Gerry Shaw (gerry_shaw@yahoo.com) // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Globalization; using System.IO; using System.Reflection; using System.Security.Permissions; using NAnt.Core.Attributes; using NAnt.Core.Extensibility; namespace NAnt.Core { public class TaskBuilder : ExtensionBuilder { #region Public Instance Constructors /// /// Creates a new instance of the class /// for the specified class in the specified /// . /// /// /// An for the specified /// is cached for future use. /// /// The containing the . /// The class representing the . public TaskBuilder (Assembly assembly, string className) : this (ExtensionAssembly.Create (assembly), className) { } #endregion Public Instance Constructors #region Internal Instance Constructors /// /// Creates a new instance of the class /// for the specified class in the specified /// . /// /// The containing the . /// The class representing the . internal TaskBuilder(ExtensionAssembly extensionAssembly, string className) : base (extensionAssembly) { _className = className; } #endregion Internal Instance Constructors #region Public Instance Properties /// /// Gets the name of the class that can be created /// using this . /// /// /// The name of the class that can be created using /// this . /// public string ClassName { get { return _className; } } /// /// Gets the name of the task which the /// can create. /// /// /// The name of the task which the can /// create. /// public string TaskName { get { if (_taskName == null) { TaskNameAttribute taskNameAttribute = (TaskNameAttribute) Attribute.GetCustomAttribute(Assembly.GetType(ClassName), typeof(TaskNameAttribute)); _taskName = taskNameAttribute.Name; } return _taskName; } } #endregion Public Instance Properties #region Public Instance Methods [ReflectionPermission(SecurityAction.Demand, Flags=ReflectionPermissionFlag.NoFlags)] public Task CreateTask() { Task task = (Task) Assembly.CreateInstance( ClassName, true, BindingFlags.Public | BindingFlags.Instance, null, null, CultureInfo.InvariantCulture, null); IPluginConsumer pluginConsumer = task as IPluginConsumer; if (pluginConsumer != null) { TypeFactory.PluginScanner.RegisterPlugins(pluginConsumer); } return task; } #endregion Public Instance Methods #region Private Instance Fields private readonly string _className; private string _taskName; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.Core/Project.cs0000644000175000017500000022122211757302273017304 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Ian MacLean (imaclean@gmail.com) // Scott Hernandez (ScottHernandez@hotmail.com) // William E. Caputo (wecaputo@thoughtworks.com | logosity@yahoo.com) using System; using System.Collections; using System.Collections.Specialized; using System.ComponentModel; using System.Configuration; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using System.Xml; using Microsoft.Win32; using NAnt.Core.Tasks; using NAnt.Core.Util; namespace NAnt.Core { /// /// Central representation of a NAnt project. /// /// /// /// The method will initialize the project with the build /// file specified in the constructor and execute the default target. /// /// /// /// /// /// /// /// If no target is given, the default target will be executed if specified /// in the project. /// /// /// /// /// [Serializable()] public class Project { #region Private Static Fields /// /// Holds the logger for this class. /// private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // XML element and attribute names that are not defined in metadata private const string RootXml = "project"; private const string ProjectNameAttribute = "name"; private const string ProjectDefaultAttribte = "default"; private const string ProjectBaseDirAttribute = "basedir"; private const string TargetXml = "target"; private const string WildTarget = "*"; /// /// Constant for the "visiting" state, used when traversing a DFS of /// target dependencies. /// private const string Visiting = "VISITING"; /// /// Constant for the "visited" state, used when traversing a DFS of /// target dependencies. /// private const string Visited = "VISITED"; #endregion Private Static Fields #region Internal Static Fields // named properties internal const string NAntPlatform = "nant.platform"; internal const string NAntPlatformName = NAntPlatform + ".name"; internal const string NAntPropertyFileName = "nant.filename"; internal const string NAntPropertyVersion = "nant.version"; internal const string NAntPropertyLocation = "nant.location"; internal const string NAntPropertyProjectName = "nant.project.name"; internal const string NAntPropertyProjectBuildFile = "nant.project.buildfile"; internal const string NAntPropertyProjectBaseDir = "nant.project.basedir"; internal const string NAntPropertyProjectDefault = "nant.project.default"; internal const string NAntPropertyOnSuccess = "nant.onsuccess"; internal const string NAntPropertyOnFailure = "nant.onfailure"; #endregion Internal Static Fields #region Public Instance Events public event BuildEventHandler BuildStarted; public event BuildEventHandler BuildFinished; public event BuildEventHandler TargetStarted; public event BuildEventHandler TargetFinished; public event BuildEventHandler TaskStarted; public event BuildEventHandler TaskFinished; public event BuildEventHandler MessageLogged; #endregion Public Instance Events #region Private Instance Fields private string _baseDirectory; private string _projectName = ""; private string _defaultTargetName; private int _indentationSize = 4; private int _indentationLevel = 0; private BuildListenerCollection _buildListeners = new BuildListenerCollection(); private StringCollection _buildTargets = new StringCollection(); private TargetCollection _targets = new TargetCollection(); private LocationMap _locationMap = new LocationMap(); private PropertyDictionary _properties; private PropertyDictionary _frameworkNeutralProperties; private Target _currentTarget; // info about frameworks private FrameworkInfoDictionary _frameworks = new FrameworkInfoDictionary(); private FrameworkInfo _runtimeFramework; private FrameworkInfo _targetFramework; [NonSerialized()] private XmlNode _configurationNode; [NonSerialized()] private XmlDocument _doc; // set in ctorHelper [NonSerialized()] private XmlNamespaceManager _nsMgr = new XmlNamespaceManager(new NameTable()); //used to map "nant" to default namespace. [NonSerialized()] private DataTypeBaseDictionary _dataTypeReferences = new DataTypeBaseDictionary(); /// /// Holds the default threshold for build loggers. /// private Level _threshold = Level.Info; #endregion Private Instance Fields #region Public Instance Constructors /// /// Initializes a new class with the given /// document, message threshold and indentation level. /// /// Any valid build format will do. /// The message threshold. /// The project indentation level. public Project(XmlDocument doc, Level threshold, int indentLevel) { // use NAnt settings from application configuration file for loading // internal configuration settings _configurationNode = GetConfigurationNode(); // initialize project CtorHelper(doc, threshold, indentLevel, Optimizations.None); } /// /// Initializes a new class with the given /// document, message threshold and indentation level, and using /// the specified to load internal configuration /// settings. /// /// Any valid build format will do. /// The message threshold. /// The project indentation level. /// The NAnt should use to initialize configuration settings. /// /// This constructor is useful for developers using NAnt as a class /// library. /// public Project(XmlDocument doc, Level threshold, int indentLevel, XmlNode configurationNode) { // set configuration node to use for loading internal configuration // settings _configurationNode = configurationNode; // initialize project CtorHelper(doc, threshold, indentLevel, Optimizations.None); } /// /// Initializes a new class with the given /// source, message threshold and indentation level. /// /// /// The full path to the build file. /// This can be of any form that accepts. /// /// The message threshold. /// The project indentation level. /// /// If the source is a uri of form 'file:///path' then use the path part. /// public Project(string uriOrFilePath, Level threshold, int indentLevel) { // use NAnt settings from application configuration file for loading // internal configuration settings _configurationNode = GetConfigurationNode(); // initialize project CtorHelper(LoadBuildFile(uriOrFilePath), threshold, indentLevel, Optimizations.None); } /// /// Initializes a new class with the given /// source, message threshold and indentation level, and using /// the specified to load internal configuration /// settings. /// /// /// The full path to the build file. /// This can be of any form that accepts. /// /// The message threshold. /// The project indentation level. /// The NAnt should use to initialize configuration settings. /// is . /// /// If the source is a uri of form 'file:///path' then use the path part. /// public Project(string uriOrFilePath, Level threshold, int indentLevel, XmlNode configurationNode) { // set configuration node to use for loading internal configuration // settings _configurationNode = configurationNode; // initialize project CtorHelper(LoadBuildFile(uriOrFilePath), threshold, indentLevel, Optimizations.None); } #endregion Public Instance Constructors #region Internal Instance Constructors /// /// Initializes a as subproject of the specified /// . /// /// /// The full path to the build file. /// This can be of any form that accepts. /// /// The parent . /// /// Optimized for framework initialization projects, by skipping automatic /// discovery of extension assemblies and framework configuration. /// internal Project(string uriOrFilePath, Project parent) { // set configuration node to use for loading internal configuration // settings _configurationNode = parent.ConfigurationNode; // initialize project CtorHelper(LoadBuildFile(uriOrFilePath), parent.Threshold, parent.IndentationLevel + 1, Optimizations.SkipFrameworkConfiguration); // add listeners of current project to new project AttachBuildListeners(parent.BuildListeners); // inherit discovered frameworks from current project foreach (FrameworkInfo framework in parent.Frameworks) { Frameworks.Add(framework.Name, framework); } // have the new project inherit the runtime framework from the // current project RuntimeFramework = parent.RuntimeFramework; // have the new project inherit the current framework from the // current project TargetFramework = parent.TargetFramework; } /// /// Initializes a with /// set to , and /// set to 0. /// /// An containing the build script. /// /// Optimized for framework initialization projects, by skipping automatic /// discovery of extension assemblies and framework configuration. /// internal Project(XmlDocument doc) { // initialize project CtorHelper(doc, Level.None, 0, Optimizations.SkipAutomaticDiscovery | Optimizations.SkipFrameworkConfiguration); } #endregion Internal Instance Constructors #region Public Instance Properties /// /// Gets or sets the indendation level of the build output. /// /// /// The indentation level of the build output. /// /// /// To change the , the /// and methods should be used. /// public int IndentationLevel { get { return _indentationLevel; } } /// /// Gets or sets the indentation size of the build output. /// /// /// The indendation size of the build output. /// public int IndentationSize { get { return _indentationSize; } } /// /// Gets or sets the default threshold level for build loggers. /// /// /// The default threshold level for build loggers. /// public Level Threshold { get { return _threshold; } set { _threshold = value; } } /// /// Gets the name of the . /// /// /// The name of the or an empty /// if no name is specified. /// public string ProjectName { get { return _projectName; } } /// /// Gets or sets the base directory used for relative references. /// /// /// The base directory used for relative references. /// /// The directory is not rooted. /// /// /// The gets and sets the built-in property /// named "nant.project.basedir". /// /// public string BaseDirectory { get { if (_baseDirectory == null) { return null; } if (!Path.IsPathRooted(_baseDirectory)) { throw new BuildException(string.Format(CultureInfo.InstalledUICulture, "Invalid base directory '{0}'. The project base directory" + "must be rooted.", _baseDirectory), Location.UnknownLocation); } return _baseDirectory; } set { if (!Path.IsPathRooted(value)) { throw new BuildException(string.Format(CultureInfo.InstalledUICulture, "Invalid base directory '{0}'. The project base directory" + "must be rooted.", value), Location.UnknownLocation); } Properties[NAntPropertyProjectBaseDir] = _baseDirectory = value; } } /// /// Gets the . /// /// /// The . /// /// /// The defines the current namespace /// scope and provides methods for looking up namespace information. /// public XmlNamespaceManager NamespaceManager { get { return _nsMgr; } } /// /// Gets the form of the current project definition. /// /// /// The form of the current project definition. /// public Uri BuildFileUri { get { //TODO: Need to remove this. if (Document == null || String.IsNullOrEmpty(Document.BaseURI)) { return null; //new Uri("http://localhost"); } else { // manually escape '#' in URI (why doesn't .NET do this?) to allow // projects in paths containing a '#' character string escapedUri = Document.BaseURI.Replace("#", Uri.HexEscape('#')); // return escaped URI return new Uri(escapedUri); } } } /// /// Gets a collection of available .NET frameworks. /// /// /// A collection of available .NET frameworks. /// public FrameworkInfoDictionary Frameworks { get { return _frameworks; } } /// /// Gets the list of supported frameworks filtered by the specified /// parameter. /// /// A bitwise combination of values that filter the frameworks to retrieve. /// /// An array of type that contains the /// frameworks specified by the parameter, /// sorted on name. /// internal FrameworkInfo[] GetFrameworks (FrameworkTypes types) { ArrayList matches = new ArrayList(Frameworks.Count); foreach (FrameworkInfo framework in Frameworks.Values) { if ((types & FrameworkTypes.InstallStateMask) != 0) { if ((types & FrameworkTypes.Installed) == 0 && framework.IsValid) continue; if ((types & FrameworkTypes.NotInstalled) == 0 && !framework.IsValid) continue; } if ((types & FrameworkTypes.DeviceMask) != 0) { switch (framework.ClrType) { case ClrType.Compact: if ((types & FrameworkTypes.Compact) == 0) continue; break; case ClrType.Desktop: if ((types & FrameworkTypes.Desktop) == 0) continue; break; case ClrType.Browser: if ((types & FrameworkTypes.Browser) == 0) continue; break; default: throw new NotSupportedException(string.Format( CultureInfo.InvariantCulture, "CLR type '{0}'" + " is not supported.", framework.ClrType)); } } if ((types & FrameworkTypes.VendorMask) != 0) { switch (framework.Vendor) { case VendorType.Mono: if ((types & FrameworkTypes.Mono) == 0) continue; break; case VendorType.Microsoft: if ((types & FrameworkTypes.MS) == 0) continue; break; } } matches.Add(framework); } matches.Sort(FrameworkInfo.NameComparer); FrameworkInfo[] frameworks = new FrameworkInfo[matches.Count]; matches.CopyTo(frameworks); return frameworks; } /// /// Gets the framework in which NAnt is currently running. /// /// /// The framework in which NAnt is currently running. /// public FrameworkInfo RuntimeFramework { get { return _runtimeFramework; } set { _runtimeFramework = value; } } /// /// Gets or sets the framework to use for compilation. /// /// /// The framework to use for compilation. /// /// The value specified is . /// The specified framework is not installed, or not configured correctly. /// /// We will use compiler tools and system assemblies for this framework /// in framework-related tasks. /// public FrameworkInfo TargetFramework { get { return _targetFramework; } set { if (value == null) { throw new ArgumentNullException("value"); } value.Validate (); _targetFramework = value; UpdateTargetFrameworkProperties(); } } /// /// Gets the name of the platform on which NAnt is currently running. /// /// /// The name of the platform on which NAnt is currently running. /// /// /// /// Possible values are: /// /// /// /// win32 /// /// /// unix /// /// /// /// NAnt does not support the current platform. public string PlatformName { get { if (PlatformHelper.IsWin32) { return "win32"; } else if (PlatformHelper.IsUnix) { return "unix"; } else { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1060"), Environment.OSVersion.Platform.ToString(CultureInfo.InvariantCulture), (int) Environment.OSVersion.Platform)); } } } /// /// Gets the current target. /// /// /// The current target, or if no target is /// executing. /// public Target CurrentTarget { get { return _currentTarget; } } /// /// Gets the path to the build file. /// /// /// The path to the build file, or if the build /// document is not file backed. /// public string BuildFileLocalName { get { if (BuildFileUri != null && BuildFileUri.IsFile) { return BuildFileUri.LocalPath; } else { return null; } } } /// /// Gets the active definition. /// /// /// The active definition. /// public XmlDocument Document { get { return _doc; } } /// /// Gets the NAnt should use to initialize /// configuration settings. /// /// /// The NAnt should use to initialize /// configuration settings. /// public XmlNode ConfigurationNode { get { return _configurationNode; } } /// /// Gets the name of the target that will be executed when no other /// build targets are specified. /// /// /// The name of the target that will be executed when no other /// build targets are specified, or if no /// default target is specified in the build file. /// public string DefaultTargetName { get { return _defaultTargetName; } } /// /// Gets a value indicating whether tasks should output more build log /// messages. /// /// /// if tasks should output more build log message; /// otherwise, . /// public bool Verbose { get { return Level.Verbose >= Threshold; } } /// /// The list of targets to build. /// /// /// Targets are built in the order they appear in the collection. If /// the collection is empty the default target will be built. /// public StringCollection BuildTargets { get { return _buildTargets; } } /// /// Gets the properties defined in this project. /// /// The properties defined in this project. /// /// /// This is the collection of properties that are defined by the system /// and property task statements. /// /// /// These properties can be used in expansion. /// /// public PropertyDictionary Properties { get { return _properties; } } /// /// Gets the framework-neutral properties defined in the NAnt /// configuration file. /// /// /// The framework-neutral properties defined in the NAnt configuration /// file. /// /// /// /// This is the collection of read-only properties that are defined in /// the NAnt configuration file. /// /// /// These properties can only be used for expansion in framework-specific /// and framework-neutral configuration settings. These properties are /// not available for expansion in the build file. /// /// public PropertyDictionary FrameworkNeutralProperties { get { return _frameworkNeutralProperties; } } /// /// Gets the instances defined in this project. /// /// /// The instances defined in this project. /// /// /// /// This is the collection of instances that /// are defined by (eg fileset) declarations. /// /// public DataTypeBaseDictionary DataTypeReferences { get { return _dataTypeReferences; } } /// /// Gets the targets defined in this project. /// /// /// The targets defined in this project. /// public TargetCollection Targets { get { return _targets; } } /// /// Gets the build listeners for this project. /// /// /// The build listeners for this project. /// public BuildListenerCollection BuildListeners { get { return _buildListeners; } } #endregion Public Instance Properties #region Internal Instance Properties internal LocationMap LocationMap { get { return _locationMap; } } #endregion Internal Instance Properties #region Public Instance Methods /// /// Returns the of the given node in an XML /// file loaded by NAnt. /// /// /// /// The must be from an /// that has been loaded by NAnt. /// /// /// NAnt also does not process any of the following node types: /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// As a result, no location information is available for these nodes. /// /// /// The to get the for. /// /// of the given node in an XML file loaded by NAnt, or /// if the node was not loaded from /// an XML file. /// /// /// is from an XML file that was not loaded by NAnt. /// -or /// was not processed by NAnt (eg. an XML declaration). /// public Location GetLocation(XmlNode node) { return LocationMap.GetLocation(node); } /// /// Dispatches a event to the build listeners /// for this . /// /// The source of the event. /// A that contains the event data. public void OnBuildStarted(object sender, BuildEventArgs e) { if (BuildStarted != null) { BuildStarted(sender, e); } } /// /// Dispatches a event to the build listeners /// for this . /// /// The source of the event. /// A that contains the event data. public void OnBuildFinished(object sender, BuildEventArgs e) { if (BuildFinished != null) { BuildFinished(sender, e); } } /// /// Dispatches a event to the build listeners /// for this . /// /// The source of the event. /// A that contains the event data. public void OnTargetStarted(object sender, BuildEventArgs e) { if (TargetStarted != null) { TargetStarted(sender, e); } } /// /// Dispatches a event to the build listeners /// for this . /// /// The source of the event. /// A that contains the event data. public void OnTargetFinished(object sender, BuildEventArgs e) { if (TargetFinished != null) { TargetFinished(sender, e); } } /// /// Dispatches a event to the build listeners /// for this . /// /// The source of the event. /// A that contains the event data. public void OnTaskStarted(object sender, BuildEventArgs e) { if (TaskStarted != null) { TaskStarted(sender, e); } } /// /// Dispatches the event to the build listeners /// for this . /// /// The source of the event. /// A that contains the event data. public void OnTaskFinished(object sender, BuildEventArgs e) { if (TaskFinished != null) { TaskFinished(sender, e); } } /// /// Dispatches a event to the build listeners /// for this . /// /// A that contains the event data. public void OnMessageLogged(BuildEventArgs e) { if (MessageLogged != null) { MessageLogged(this, e); } } /// /// Writes a level message to the build log with /// the given . /// /// The to log at. /// The message to log. public void Log(Level messageLevel, string message) { BuildEventArgs eventArgs = new BuildEventArgs(this); eventArgs.Message = message; eventArgs.MessageLevel = messageLevel; OnMessageLogged(eventArgs); } /// /// Writes a level formatted message to the build /// log with the given . /// /// The to log at. /// The message to log, containing zero or more format items. /// An array containing zero or more objects to format. public void Log(Level messageLevel, string message, params object[] args) { BuildEventArgs eventArgs = new BuildEventArgs(this); eventArgs.Message = string.Format(CultureInfo.InvariantCulture, message, args); eventArgs.MessageLevel = messageLevel; OnMessageLogged(eventArgs); } /// /// Writes a task level message to the build log /// with the given . /// /// The from which the message originated. /// The to log at. /// The message to log. public void Log(Task task, Level messageLevel, string message) { BuildEventArgs eventArgs = new BuildEventArgs(task); eventArgs.Message = message; eventArgs.MessageLevel = messageLevel; OnMessageLogged(eventArgs); } /// /// Writes a level message to the build log with /// the given . /// /// The from which the message orignated. /// The level to log at. /// The message to log. public void Log(Target target, Level messageLevel, string message) { BuildEventArgs eventArgs = new BuildEventArgs(target); eventArgs.Message = message; eventArgs.MessageLevel = messageLevel; OnMessageLogged(eventArgs); } /// /// Executes the default target. /// /// /// No top level error handling is done. Any /// will be passed onto the caller. /// public virtual void Execute() { if (BuildTargets.Count == 0 && !String.IsNullOrEmpty(DefaultTargetName)) { BuildTargets.Add(DefaultTargetName); } //log the targets specified, or the default target if specified. StringBuilder sb = new StringBuilder(); if (BuildTargets != null) { foreach(string target in BuildTargets) { sb.Append(target); sb.Append(" "); } } if(sb.Length > 0) { Log(Level.Info, "Target(s) specified: " + sb.ToString()); Log(Level.Info, string.Empty); } else { Log(Level.Info, string.Empty); } // initialize the list of Targets, and execute any global tasks. InitializeProjectDocument(Document); if (BuildTargets.Count == 0) { //It is okay if there are no targets defined in a build file. //It just means we have all global tasks. -- skot //throw new BuildException("No Target Specified"); } else { foreach (string targetName in BuildTargets) { //do not force dependencies of build targets. Execute(targetName, false); } } } /// /// Executes a specific target, and its dependencies. /// /// The name of the target to execute. /// /// Global tasks are not executed. /// public void Execute(string targetName) { Execute(targetName, true); } /// /// Executes a specific target. /// /// The name of the target to execute. /// Whether dependencies should be forced to execute /// /// Global tasks are not executed. /// public void Execute(string targetName, bool forceDependencies) { // sort the dependency tree, and run everything from the // beginning until we hit our targetName. // // sorting checks if all the targets (and dependencies) // exist, and if there is any cycle in the dependency // graph. TargetCollection sortedTargets = TopologicalTargetSort(targetName, Targets); int currentIndex = 0; Target currentTarget; // store calling target Target callingTarget = _currentTarget; do { // determine target that should be executed currentTarget = (Target) sortedTargets[currentIndex++]; // store target that will be executed _currentTarget = currentTarget; // only execute targets that have not been executed already, if // we are not forcing. if (forceDependencies || !currentTarget.Executed || currentTarget.Name == targetName) { currentTarget.Execute(); } } while (currentTarget.Name != targetName); // restore calling target, as a task might have caused the // current target to be executed and when finished executing this // target, the target that contained the task should be // considered the current target again _currentTarget = callingTarget; } /// /// Executes the default target and wraps in error handling and time /// stamping. /// /// /// if the build was successful; otherwise, /// . /// public bool Run() { Exception error = null; try { OnBuildStarted(this, new BuildEventArgs(this)); // output build file that we're running Log(Level.Info, "Buildfile: {0}", BuildFileUri); // output current target framework in build log Log(Level.Info, "Target framework: {0}", TargetFramework != null ? TargetFramework.Description : "None"); // write verbose project information after Initialize to make // sure properties are correctly initialized Log(Level.Verbose, "Base Directory: {0}.", BaseDirectory); // execute the project Execute(); // signal build success return true; } catch (BuildException e) { // store exception in error variable in order to include it // in the BuildFinished event. error = e; // log exception details to log4net logger.Error("Build failed.", e); // signal build failure return false; } catch (Exception e) { // store exception in error variable in order to include it // in the BuildFinished event. error = e; // log exception details to log4net logger.Fatal("Build failed.", e); // signal build failure return false; } finally { string endTarget; if (error == null) { endTarget = Properties[NAntPropertyOnSuccess]; } else { endTarget = Properties[NAntPropertyOnFailure]; } if (!String.IsNullOrEmpty(endTarget)) { // executing the target identified by the 'nant.onsuccess' // or 'nant.onfailure' properties should not affect the // build outcome CallTask callTask = new CallTask(); callTask.Parent = this; callTask.Project = this; callTask.NamespaceManager = NamespaceManager; callTask.Verbose = Verbose; callTask.FailOnError = false; callTask.TargetName = endTarget; callTask.Execute(); } // fire BuildFinished event with details of build outcome BuildEventArgs buildFinishedArgs = new BuildEventArgs(this); buildFinishedArgs.Exception = error; OnBuildFinished(this, buildFinishedArgs); } } public DataTypeBase CreateDataTypeBase(XmlNode elementNode) { DataTypeBase type = TypeFactory.CreateDataType(elementNode, this); type.Project = this; type.Parent = this; type.NamespaceManager = NamespaceManager; type.Initialize(elementNode); return type; } /// /// Creates a new from the given . /// /// The definition. /// The new instance. public Task CreateTask(XmlNode taskNode) { return CreateTask(taskNode, null); } /// /// Creates a new from the given /// within a . /// /// The definition. /// The owner . /// The new instance. public Task CreateTask(XmlNode taskNode, Target target) { Task task = TypeFactory.CreateTask(taskNode, this); task.Project = this; task.Parent = target; task.NamespaceManager = NamespaceManager; task.Initialize(taskNode); return task; } /// /// Expands a from known properties. /// /// The with replacement tokens. /// The location in the build file. Used to throw more accurate exceptions. /// The expanded and replaced . public string ExpandProperties(string input, Location location) { return Properties.ExpandProperties(input, location); } /// /// Combines the specified path with the of /// the to form a full path to file or directory. /// /// The relative or absolute path. /// /// A rooted path, or the of the /// if the parameter is a null reference. /// public string GetFullPath(string path) { if (String.IsNullOrEmpty(path)) { return BaseDirectory; } // check whether path is a file URI try { Uri uri = new Uri(path); if (uri.IsFile) { path = uri.LocalPath; } else { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1061"), path, uri.Scheme), Location.UnknownLocation); } } catch { // ignore exception and treat path as normal path } if (!Path.IsPathRooted(path)) { path = Path.GetFullPath(Path.Combine(BaseDirectory, path)); } return path; } /// /// Creates the default and attaches it to /// the . /// public void CreateDefaultLogger() { IBuildLogger buildLogger = new DefaultLogger(); // hook up to build events BuildStarted += new BuildEventHandler(buildLogger.BuildStarted); BuildFinished += new BuildEventHandler(buildLogger.BuildFinished); TargetStarted += new BuildEventHandler(buildLogger.TargetStarted); TargetFinished += new BuildEventHandler(buildLogger.TargetFinished); TaskStarted += new BuildEventHandler(buildLogger.TaskStarted); TaskFinished += new BuildEventHandler(buildLogger.TaskFinished); MessageLogged += new BuildEventHandler(buildLogger.MessageLogged); // set threshold of logger equal to threshold of the project buildLogger.Threshold = Threshold; // add default logger to list of build listeners BuildListeners.Add(buildLogger); } /// /// Increases the of the . /// public void Indent() { _indentationLevel++; } /// /// Decreases the of the . /// public void Unindent() { _indentationLevel--; } /// /// Detaches the currently attached instances /// from the . /// public void DetachBuildListeners() { foreach (IBuildListener listener in BuildListeners) { BuildStarted -= new BuildEventHandler(listener.BuildStarted); BuildFinished -= new BuildEventHandler(listener.BuildFinished); TargetStarted -= new BuildEventHandler(listener.TargetStarted); TargetFinished -= new BuildEventHandler(listener.TargetFinished); TaskStarted -= new BuildEventHandler(listener.TaskStarted); TaskFinished -= new BuildEventHandler(listener.TaskFinished); MessageLogged -= new BuildEventHandler(listener.MessageLogged); if (typeof(IBuildLogger).IsAssignableFrom(listener.GetType())) { ((IBuildLogger)listener).Flush(); } } BuildListeners.Clear(); } /// /// Attaches the specified build listeners to the . /// /// The instances to attach to the . /// /// The currently attached instances will /// be detached before the new instances /// are attached. /// public void AttachBuildListeners(BuildListenerCollection listeners) { // detach currently attached build listeners DetachBuildListeners(); foreach (IBuildListener listener in listeners) { // hook up listener to project build events BuildStarted += new BuildEventHandler(listener.BuildStarted); BuildFinished += new BuildEventHandler(listener.BuildFinished); TargetStarted += new BuildEventHandler(listener.TargetStarted); TargetFinished += new BuildEventHandler(listener.TargetFinished); TaskStarted += new BuildEventHandler(listener.TaskStarted); TaskFinished += new BuildEventHandler(listener.TaskFinished); MessageLogged += new BuildEventHandler(listener.MessageLogged); // add listener to project listener list BuildListeners.Add(listener); } } #endregion Public Instance Methods #region Protected Instance Methods /// /// Inits stuff: /// TypeFactory: Calls Initialize and AddProject /// Log.IndentSize set to 12 /// Project properties are initialized ("nant.* stuff set") /// /// NAnt Props: /// nant.filename /// nant.version /// nant.location /// nant.project.name /// nant.project.buildfile (if doc has baseuri) /// nant.project.basedir /// nant.project.default = defaultTarget /// /// /// An representing the project definition. /// The project message threshold. /// The project indentation level. /// Optimization flags. /// is . private void CtorHelper(XmlDocument doc, Level threshold, int indentLevel, Optimizations optimization) { if (doc == null) { throw new ArgumentNullException("doc"); } string newBaseDir = null; _properties = new PropertyDictionary(this); _frameworkNeutralProperties = new PropertyDictionary(this); // set the project definition _doc = doc; // set the indentation size of the build output _indentationSize = 12; // set the indentation level of the build output _indentationLevel = indentLevel; // set the project message threshold Threshold = threshold; // add default logger CreateDefaultLogger(); // configure platform properties ConfigurePlatformProperties(); // fill the namespace manager up, so we can make qualified xpath // expressions if (String.IsNullOrEmpty(doc.DocumentElement.NamespaceURI)) { string defURI; XmlAttribute nantNS = doc.DocumentElement.Attributes["xmlns", "nant"]; if (nantNS == null) { defURI = @"http://none"; } else { defURI = nantNS.Value; } XmlAttribute attr = doc.CreateAttribute("xmlns"); attr.Value = defURI; doc.DocumentElement.Attributes.Append(attr); } NamespaceManager.AddNamespace("nant", doc.DocumentElement.NamespaceURI); // check to make sure that the root element in named correctly if (!doc.DocumentElement.LocalName.Equals(RootXml)) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1059"), doc.BaseURI, RootXml)); } // get project attributes if (doc.DocumentElement.HasAttribute(ProjectNameAttribute)) { _projectName = doc.DocumentElement.GetAttribute(ProjectNameAttribute); } if (doc.DocumentElement.HasAttribute(ProjectBaseDirAttribute)) { newBaseDir = doc.DocumentElement.GetAttribute(ProjectBaseDirAttribute); } if (doc.DocumentElement.HasAttribute(ProjectDefaultAttribte)) { _defaultTargetName = doc.DocumentElement.GetAttribute(ProjectDefaultAttribte); } // give the project a meaningful base directory if (String.IsNullOrEmpty(newBaseDir)) { if (!String.IsNullOrEmpty(BuildFileLocalName)) { newBaseDir = Path.GetDirectoryName(BuildFileLocalName); } else { newBaseDir = Environment.CurrentDirectory; } } else { // if basedir attribute is set to a relative path, then resolve // it relative to the build file path if (!String.IsNullOrEmpty(BuildFileLocalName) && !Path.IsPathRooted(newBaseDir)) { newBaseDir = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(BuildFileLocalName), newBaseDir)); } } newBaseDir = Path.GetFullPath(newBaseDir); // base directory must be rooted. BaseDirectory = newBaseDir; // load project-level extensions assemblies bool scan = ((optimization & Optimizations.SkipAutomaticDiscovery) == 0); TypeFactory.AddProject(this, scan); if ((optimization & Optimizations.SkipFrameworkConfiguration) == 0) { // load settings out of settings file ProjectSettingsLoader psl = new ProjectSettingsLoader(this); psl.ProcessSettings(); } // set here and in nant:Main Assembly ass = Assembly.GetExecutingAssembly(); // TO-DO: remove these built-in properties after NAnt 0.87 (?) // as these have been deprecated since NAnt 0.85 Properties.AddReadOnly(NAntPropertyFileName, ass.CodeBase); Properties.AddReadOnly(NAntPropertyVersion, ass.GetName().Version.ToString()); Properties.AddReadOnly(NAntPropertyLocation, AppDomain.CurrentDomain.BaseDirectory); Properties.AddReadOnly(NAntPropertyProjectName, ProjectName); if (BuildFileUri != null) { Properties.AddReadOnly(NAntPropertyProjectBuildFile, BuildFileUri.ToString()); } Properties.AddReadOnly(NAntPropertyProjectDefault, StringUtils.ConvertNullToEmpty(DefaultTargetName)); } #endregion Protected Instance Methods #region Internal Instance Methods /// /// This method is only meant to be used by the /// class and . /// internal void InitializeProjectDocument(XmlDocument doc) { // load line and column number information into position map LocationMap.Add(doc); // initialize targets first foreach (XmlNode childNode in doc.DocumentElement.ChildNodes) { // skip non-nant namespace elements and special elements like // comments, pis, text, etc. if (childNode.LocalName.Equals(TargetXml) && childNode.NamespaceURI.Equals(NamespaceManager.LookupNamespace("nant"))) { Target target = new Target(); target.Project = this; target.Parent = this; target.NamespaceManager = NamespaceManager; target.Initialize(childNode); Targets.Add(target); } } // initialize datatypes and execute global tasks foreach (XmlNode childNode in doc.DocumentElement.ChildNodes) { // skip targets that were handled above, skip non-nant namespace // elements and special elements like comments, pis, text, etc. if (!(childNode.NodeType == XmlNodeType.Element) || !childNode.NamespaceURI.Equals(NamespaceManager.LookupNamespace("nant")) || childNode.LocalName.Equals(TargetXml)) { continue; } if (TypeFactory.TaskBuilders.Contains(childNode.Name)) { // create task instance Task task = CreateTask(childNode); task.Parent = this; // execute task task.Execute(); } else if (TypeFactory.DataTypeBuilders.Contains(childNode.Name)) { // we are an datatype declaration DataTypeBase dataType = CreateDataTypeBase(childNode); Log(Level.Debug, "Adding a {0} reference with id '{1}'.", childNode.Name, dataType.ID); if (! DataTypeReferences.Contains(dataType.ID)) { DataTypeReferences.Add(dataType.ID, dataType); } else { DataTypeReferences[dataType.ID] = dataType; // overwrite with the new reference. } } else { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1071"), childNode.Name), LocationMap.GetLocation(childNode)); } } } #endregion Internal Instance Methods #region Private Instance Methods /// /// Creates a new based on the project /// definition. /// /// /// The full path to the build file. /// This can be of any form that accepts. /// /// /// An based on the specified project /// definition. /// private XmlDocument LoadBuildFile(string uriOrFilePath) { string path = uriOrFilePath; //if the source is not a valid uri, pass it thru. //if the source is a file uri, pass the localpath of it thru. try { Uri testURI = new Uri(uriOrFilePath); if (testURI.IsFile) { path = testURI.LocalPath; } } catch (Exception ex) { logger.Debug("Error creating URI in project constructor. Moving on... ", ex); } finally { if (path == null) { path = uriOrFilePath; } } XmlDocument doc = new XmlDocument(); try { doc.Load(path); } catch (XmlException ex) { Location location = new Location(path, ex.LineNumber, ex.LinePosition); throw new BuildException("Error loading buildfile.", location, ex); } catch (Exception ex) { Location location = new Location(path); throw new BuildException("Error loading buildfile.", location, ex); } return doc; } /// /// Configures the platform properties for the current platform. /// /// NAnt does not support the current platform. private void ConfigurePlatformProperties() { Properties.AddReadOnly(NAntPlatformName, PlatformName); switch (PlatformName) { case "win32": Properties.AddReadOnly(NAntPlatform + ".unix", "false"); Properties.AddReadOnly(NAntPlatform + "." + PlatformName, "true"); break; case "unix": Properties.AddReadOnly(NAntPlatform + "." + PlatformName, "true"); Properties.AddReadOnly(NAntPlatform + ".win32", "false"); break; default: throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1060"), Environment.OSVersion.Platform.ToString(CultureInfo.InvariantCulture), (int) Environment.OSVersion.Platform)); } } /// /// Updates dependent properties when the /// is set. /// private void UpdateTargetFrameworkProperties() { Properties["nant.settings.currentframework"] = TargetFramework.Name; Properties["nant.settings.currentframework.version"] = TargetFramework.Version.ToString(); Properties["nant.settings.currentframework.description"] = TargetFramework.Description; Properties["nant.settings.currentframework.frameworkdirectory"] = TargetFramework.FrameworkDirectory.FullName; if (TargetFramework.SdkDirectory != null) { Properties["nant.settings.currentframework.sdkdirectory"] = TargetFramework.SdkDirectory.FullName; } else { Properties["nant.settings.currentframework.sdkdirectory"] = ""; } Properties["nant.settings.currentframework.frameworkassemblydirectory"] = TargetFramework.FrameworkAssemblyDirectory.FullName; Properties["nant.settings.currentframework.runtimeengine"] = TargetFramework.RuntimeEngine; } private XmlNode GetConfigurationNode() { XmlNode configurationNode = ConfigurationSettings.GetConfig("nant") as XmlNode; if (configurationNode == null) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "The NAnt configuration settings in file '{0}' could" + " not be loaded. Please ensure this file is available" + " and contains a 'nant' settings node.", AppDomain.CurrentDomain.SetupInformation.ConfigurationFile)); } return configurationNode; } #endregion Private Instance Methods /// /// Topologically sorts a set of targets. /// /// The name of the root target. The sort is created in such a way that the sequence of targets up to the root target is the minimum possible such sequence. Must not be . /// A collection of instances. /// /// A collection of instances in sorted order. /// /// There is a cyclic dependecy among the targets, or a named target does not exist. public TargetCollection TopologicalTargetSort(string root, TargetCollection targets) { TargetCollection executeTargets = new TargetCollection(); Hashtable state = new Hashtable(); Stack visiting = new Stack(); // We first run a DFS based sort using the root as the starting node. // This creates the minimum sequence of Targets to the root node. // We then do a sort on any remaining unVISITED targets. // This is unnecessary for doing our build, but it catches // circular dependencies or missing Targets on the entire // dependency tree, not just on the Targets that depend on the // build Target. TopologicalTargetSort(root, targets, state, visiting, executeTargets); Log(Level.Debug, "Build sequence for target `" + root + "' is " + executeTargets); foreach (Target target in targets) { string st = (string) state[target.Name]; if (st == null) { TopologicalTargetSort(target.Name, targets, state, visiting, executeTargets); } else if (st == Project.Visiting) { throw new Exception("Unexpected node in visiting state: " + target.Name); } } Log(Level.Debug, "Complete build sequence is " + executeTargets); return executeTargets; } /// /// /// Performs a single step in a recursive depth-first-search traversal /// of the target dependency tree. /// /// /// The current target is first set to the "visiting" state, and pushed /// onto the "visiting" stack. /// /// /// An exception is then thrown if any child of the current node is in /// the visiting state, as that implies a circular dependency. The /// exception contains details of the cycle, using elements of the /// "visiting" stack. /// /// /// If any child has not already been "visited", this method is called /// recursively on it. /// /// /// The current target is then added to the ordered list of targets. /// Note that this is performed after the children have been visited in /// order to get the correct order. The current target is set to the /// "visited" state. /// /// /// By the time this method returns, the ordered list contains the /// sequence of targets up to and including the current target. /// /// /// The current target to inspect. Must not be . /// A collection of instances. /// A mapping from targets to states The states in question are "VISITING" and "VISITED". Must not be . /// A stack of targets which are currently being visited. Must not be . /// The list to add target names to. This will end up containing the complete list of depenencies in dependency order. Must not be . /// /// A non-existent target is specified /// -or- /// A circular dependency is detected. /// private void TopologicalTargetSort(string root, TargetCollection targets, Hashtable state, Stack visiting, TargetCollection executeTargets) { state[root] = Project.Visiting; visiting.Push(root); Target target = (Target) targets.Find(root); if (target == null) { // check if there's a wildcard target defined target = (Target) targets.Find(WildTarget); if (target != null) { // if a wildcard target exists, then treat the wildcard // target as the requested target target = target.Clone(); target.Name = root; } else { StringBuilder sb = new StringBuilder("Target '"); sb.Append(root); sb.Append("' does not exist in this project."); visiting.Pop(); if (visiting.Count > 0) { string parent = (string) visiting.Peek(); sb.Append(" "); sb.Append("It is used from target '"); sb.Append(parent); sb.Append("'."); } throw new BuildException(sb.ToString()); } } foreach (string dependency in target.Dependencies) { string m = (string) state[dependency]; if (m == null) { // Not been visited TopologicalTargetSort(dependency, targets, state, visiting, executeTargets); } else if (m == Project.Visiting) { // Currently visiting this node, so have a cycle throw CreateCircularException(dependency, visiting); } } string p = (string) visiting.Pop(); if (root != p) { throw new Exception("Unexpected internal error: expected to pop " + root + " but got " + p); } state[root] = Project.Visited; executeTargets.Add(target); } /// /// Builds an appropriate exception detailing a specified circular /// dependency. /// /// The dependency to stop at. Must not be . /// A stack of dependencies. Must not be . /// /// A detailing the specified circular /// dependency. /// private static BuildException CreateCircularException(string end, Stack stack) { StringBuilder sb = new StringBuilder("Circular dependency: "); sb.Append(end); string c; do { c = (string) stack.Pop(); sb.Append(" <- "); sb.Append(c); } while (!c.Equals(end)); return new BuildException(sb.ToString()); } } /// /// Allow the project construction to be optimized. /// /// /// Use this with care! /// internal enum Optimizations { /// /// Do not perform any optimizations. /// None = 0, /// /// The project base directory must not be automatically scanned /// for extension assemblies. /// SkipAutomaticDiscovery = 1, /// /// Do not scan the project configuration for frameworks, and /// do not configure the runtime and target framework. /// SkipFrameworkConfiguration = 2, } } nant-0.92-rc1/src/NAnt.Core/TypeFactory.cs0000644000175000017500000007614511757302273020163 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Scott Hernandez (ScottHernandez@hotmail.com) using System; using System.Collections; using System.Globalization; using System.IO; using System.Reflection; using System.Security.Permissions; using System.Xml; using NAnt.Core.Attributes; using NAnt.Core.Extensibility; using NAnt.Core.Filters; using NAnt.Core.Tasks; using NAnt.Core.Util; namespace NAnt.Core { /// /// Comprises all of the loaded, and available, tasks. /// Use these static methods to register, initialize and create a task. /// public sealed class TypeFactory { #region Private Static Fields private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static TaskBuilderCollection _taskBuilders = new TaskBuilderCollection(); private static DataTypeBaseBuilderCollection _dataTypeBuilders = new DataTypeBaseBuilderCollection(); private static FilterBuilderCollection _filterBuilders = new FilterBuilderCollection(); private static Hashtable _methodInfoCollection = new Hashtable(); private static PluginScanner _pluginScanner = new PluginScanner(); #endregion Private Static Fields #region Internal Static Properties /// /// Gets the list of loaded instances. /// /// /// List of loaded instances. /// public static TaskBuilderCollection TaskBuilders { get { return _taskBuilders; } } /// /// Gets the list of loaded instances. /// /// /// List of loaded instances. /// public static DataTypeBaseBuilderCollection DataTypeBuilders { get { return _dataTypeBuilders; } } /// /// Gets the list of loaded instances. /// /// /// List of loaded instances. /// public static FilterBuilderCollection FilterBuilders { get { return _filterBuilders; } } internal static PluginScanner PluginScanner { get { return _pluginScanner; } } #endregion Internal Static Properties #region Public Static Methods /// /// Scans the given assembly for tasks, types, functions and filters. /// /// The assembly to scan for tasks, types, functions and filters. /// The which will be used to output messages to the build log. [ReflectionPermission(SecurityAction.Demand, Flags=ReflectionPermissionFlag.NoFlags)] public static bool ScanAssembly(string assemblyFile, Task task) { Assembly assembly = Assembly.LoadFrom(assemblyFile); return ScanAssembly(assembly, task); } /// /// Scans the given assembly for tasks, types, functions and filters. /// /// The assembly to scan for tasks, types, functions and filters. /// The which will be used to output messages to the build log. /// /// if contains at /// least one "extension"; otherwise, . /// [ReflectionPermission(SecurityAction.Demand, Flags=ReflectionPermissionFlag.NoFlags)] public static bool ScanAssembly(Assembly assembly, Task task) { task.Log(Level.Verbose, "Scanning assembly \"{0}\" for extensions.", assembly.GetName().Name); foreach (Type type in assembly.GetExportedTypes()) { foreach (MethodInfo methodInfo in type.GetMethods()) { if (methodInfo.IsStatic) { task.Log(Level.Verbose, "Found method {0}.", methodInfo.Name); } } } bool isExtensionAssembly = false; ExtensionAssembly extensionAssembly = new ExtensionAssembly ( assembly); Type[] types; try { types = assembly.GetTypes(); } catch(ReflectionTypeLoadException ex) { if(ex.LoaderExceptions != null && ex.LoaderExceptions.Length > 0) { throw ex.LoaderExceptions[0]; } throw; } foreach (Type type in types) { // // each extension type is exclusive, meaning a given type // cannot be both a task and data type // // so it doesn't make sense to scan a type for, for example, // data types if the type has already been positively // identified as a task // bool extensionFound = ScanTypeForTasks(extensionAssembly, type, task); if (!extensionFound) { extensionFound = ScanTypeForDataTypes(extensionAssembly, type, task); } if (!extensionFound) { extensionFound = ScanTypeForFunctions(type, task); } if (!extensionFound) { extensionFound = ScanTypeForFilters(extensionAssembly, type, task); } if (!extensionFound) { extensionFound = _pluginScanner.ScanTypeForPlugins( extensionAssembly, type, task); } // if extension is found in type, then mark assembly as // extension assembly isExtensionAssembly = isExtensionAssembly || extensionFound; } // if no extension could be found at all, then we might be dealing // with an extension assembly that was built using an older version // of NAnt(.Core) if (!isExtensionAssembly) { AssemblyName coreAssemblyName = Assembly.GetExecutingAssembly(). GetName(false); foreach (AssemblyName assemblyName in assembly.GetReferencedAssemblies()) { if (assemblyName.Name == coreAssemblyName.Name) { // the given assembly references NAnt.Core, so check whether // it doesn't reference an older version of NAnt.Core if (assemblyName.Version != coreAssemblyName.Version) { task.Log(Level.Warning, "Assembly \"{0}\" is built" + " using version {1} of NAnt. If any problems" + " arise, then try using a version that is built" + " for NAnt version {2}.", assembly.GetName().Name, assemblyName.Version, coreAssemblyName.Version); } } } } return isExtensionAssembly; } /// /// Scans the path for any task assemblies and adds them. /// /// The directory to scan in. /// The which will be used to output messages to the build log. /// indicating whether scanning of the directory should halt on first error. [ReflectionPermission(SecurityAction.Demand, Flags=ReflectionPermissionFlag.NoFlags)] public static void ScanDir(string path, Task task, bool failOnError) { // don't do anything if we don't have a valid directory path if (String.IsNullOrEmpty(path)) { return; } task.Log(Level.Info, "Scanning directory \"{0}\" for extension" + " assemblies.", path); // scan all dll's for tasks, types and functions DirectoryScanner scanner = new DirectoryScanner(); scanner.BaseDirectory = new DirectoryInfo(path); scanner.Includes.Add("*.dll"); foreach (string assemblyFile in scanner.FileNames) { try { TypeFactory.ScanAssembly(assemblyFile, task); } catch (Exception ex) { string msg = string.Format(CultureInfo.InvariantCulture, "Failure scanning \"{0}\" for extensions", assemblyFile); if (failOnError) { throw new BuildException(msg + ".", Location.UnknownLocation, ex); } task.Log(Level.Error, msg + ": " + assemblyFile, ex.Message); } } } /// /// Adds any task assemblies in the project base directory /// and its tasks subdirectory. /// /// The project to work from. internal static void AddProject(Project project) { AddProject(project, true); } /// /// Registers the project with , and optionally /// scan the for extension assemblies. /// /// The project to work from. /// Specified whether to scan the for extension assemblies. internal static void AddProject(Project project, bool scan) { if (!scan || String.IsNullOrEmpty(project.BaseDirectory)) return; LoadTasksTask loadTasks = new LoadTasksTask(); loadTasks.Project = project; loadTasks.NamespaceManager = project.NamespaceManager; loadTasks.Parent = project; loadTasks.FailOnError = false; loadTasks.Threshold = (project.Threshold == Level.Debug) ? Level.Debug : Level.Warning; string tasksDir = Path.Combine(project.BaseDirectory, "extensions"); string commonTasksDir = Path.Combine(tasksDir, "common"); // scan framework-neutral and version-neutral assemblies ScanDir(Path.Combine(commonTasksDir, "neutral"), loadTasks, false); // skip further processing if runtime framework has not yet // been set if (project.RuntimeFramework == null) { return; } // scan framework-neutral but version-specific assemblies ScanDir(Path.Combine(commonTasksDir, project.RuntimeFramework. ClrVersion.ToString (2)), loadTasks, false); string frameworkTasksDir = Path.Combine(tasksDir, project.RuntimeFramework.Family); // scan framework-specific but version-neutral assemblies ScanDir(Path.Combine(frameworkTasksDir, "neutral"), loadTasks, false); // scan framework-specific and version-specific assemblies ScanDir(Path.Combine(frameworkTasksDir, project.RuntimeFramework .Version.ToString()), loadTasks, false); } /// /// Looks up a function by name and argument count. /// /// The name of the function to lookup, including namespace prefix. /// The argument of the function to lookup. /// The in which the function is invoked. /// /// A representing the function, or /// if a function with the given name and /// arguments does not exist. /// internal static MethodInfo LookupFunction(string functionName, FunctionArgument[] args, Project project) { object function = _methodInfoCollection[functionName]; if (function == null) throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1052"), functionName)); MethodInfo mi = function as MethodInfo; if (mi != null) { if (mi.GetParameters ().Length == args.Length) { CheckDeprecation(functionName, mi, project); return mi; } } else { ArrayList matches = (ArrayList) function; for (int i = 0; i < matches.Count; i++) { mi = (MethodInfo) matches [i]; if (mi.GetParameters ().Length == args.Length) { CheckDeprecation(functionName, mi, project); return mi; } } } throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1044"), functionName, args.Length)); } private static void CheckDeprecation(string functionName, MethodInfo function, Project project) { // check whether the function is deprecated ObsoleteAttribute obsoleteAttribute = (ObsoleteAttribute) Attribute.GetCustomAttribute(function, typeof(ObsoleteAttribute), true); // if function itself is not deprecated, check if its declaring // type is deprecated if (obsoleteAttribute == null) { obsoleteAttribute = (ObsoleteAttribute) Attribute.GetCustomAttribute(function.DeclaringType, typeof(ObsoleteAttribute), true); } if (obsoleteAttribute != null) { string obsoleteMessage = string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1087"), functionName, obsoleteAttribute.Message); if (obsoleteAttribute.IsError) { throw new BuildException(obsoleteMessage, Location.UnknownLocation); } else { project.Log(Level.Warning, "{0}", obsoleteMessage); } } } /// /// Creates a new instance for the given XML and /// . /// /// The XML to initialize the task with. /// The that the belongs to. /// /// The new instance. /// public static Task CreateTask(XmlNode taskNode, Project proj) { if (taskNode == null) { throw new ArgumentNullException("taskNode"); } if (proj == null) { throw new ArgumentNullException("proj"); } string taskName = taskNode.Name; TaskBuilder builder = TaskBuilders[taskName]; if (builder == null) { Location location = proj.LocationMap.GetLocation(taskNode); throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1083"), taskName), location); } Task task = builder.CreateTask(); task.Project = proj; task.NamespaceManager = proj.NamespaceManager; // check whether the task (or its base class) is deprecated ObsoleteAttribute obsoleteAttribute = (ObsoleteAttribute) Attribute.GetCustomAttribute(task.GetType(), typeof(ObsoleteAttribute), true); if (obsoleteAttribute != null) { Location location = proj.LocationMap.GetLocation(taskNode); string obsoleteMessage = string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1086"), taskName, obsoleteAttribute.Message); if (obsoleteAttribute.IsError) { throw new BuildException(obsoleteMessage, location); } else { proj.Log(Level.Warning, "{0} {1}", location, obsoleteMessage); } } return task; } public static Filter CreateFilter(XmlNode elementNode, Element parent) { if (elementNode == null) { throw new ArgumentNullException("elementNode"); } if (parent == null) { throw new ArgumentNullException("parent"); } string filterName = elementNode.Name; FilterBuilder builder = FilterBuilders[filterName]; if (builder == null) { Location location = parent.Project.LocationMap.GetLocation(elementNode); throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1082"), filterName), location); } Filter filter = (Filter) builder.CreateFilter(); filter.Parent = parent; filter.Project = parent.Project; filter.NamespaceManager = parent.Project.NamespaceManager; filter.Initialize(elementNode); // check whether the type (or its base class) is deprecated ObsoleteAttribute obsoleteAttribute = (ObsoleteAttribute) Attribute.GetCustomAttribute(filter.GetType(), typeof(ObsoleteAttribute), true); if (obsoleteAttribute != null) { Location location = parent.Project.LocationMap.GetLocation(elementNode); string obsoleteMessage = string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1079"), filterName, obsoleteAttribute.Message); if (obsoleteAttribute.IsError) { throw new BuildException(obsoleteMessage, location); } else { parent.Project.Log(Level.Warning, "{0} {1}", location, obsoleteMessage); } } return filter; } public static DataTypeBase CreateDataType(XmlNode elementNode, Project proj) { if (elementNode == null) { throw new ArgumentNullException("elementNode"); } if (proj == null) { throw new ArgumentNullException("proj"); } string dataTypeName = elementNode.Name; DataTypeBaseBuilder builder = DataTypeBuilders[dataTypeName]; if (builder == null) { Location location = proj.LocationMap.GetLocation(elementNode); throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1081"), dataTypeName), location); } DataTypeBase element = (DataTypeBase) builder.CreateDataTypeBase(); element.Project = proj; element.NamespaceManager = proj.NamespaceManager; // check whether the type (or its base class) is deprecated ObsoleteAttribute obsoleteAttribute = (ObsoleteAttribute) Attribute.GetCustomAttribute(element.GetType(), typeof(ObsoleteAttribute), true); if (obsoleteAttribute != null) { Location location = proj.LocationMap.GetLocation(elementNode); string obsoleteMessage = string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1085"), dataTypeName, obsoleteAttribute.Message); if (obsoleteAttribute.IsError) { throw new BuildException(obsoleteMessage, location); } else { proj.Log(Level.Warning, "{0} {1}", location, obsoleteMessage); } } return element; } #endregion Public Static Methods #region Private Static Methods /// /// Scans a given for tasks. /// /// The containing the to scan. /// The to scan. /// The which will be used to output messages to the build log. /// /// if represents a /// ; otherwise, . /// private static bool ScanTypeForTasks(ExtensionAssembly extensionAssembly, Type type, Task task) { try { TaskNameAttribute taskNameAttribute = (TaskNameAttribute) Attribute.GetCustomAttribute(type, typeof(TaskNameAttribute)); if (type.IsSubclassOf(typeof(Task)) && !type.IsAbstract && taskNameAttribute != null) { task.Log(Level.Debug, string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("String_CreatingTaskBuilder"), type.Name)); TaskBuilder tb = new TaskBuilder(extensionAssembly, type.FullName); if (TaskBuilders[tb.TaskName] == null) { task.Log(Level.Debug, string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("String_AddingTask"), tb.TaskName, GetAssemblyLocation(tb.Assembly), tb.ClassName)); TaskBuilders.Add(tb); } // specified type represents a task return true; } else { // specified type does not represent valid task return false; } } catch { task.Log(Level.Error, "Failure scanning \"{0}\" for tasks.", type.AssemblyQualifiedName); throw; } } /// /// Scans a given for data type. /// /// The containing the to scan. /// The to scan. /// The which will be used to output messages to the build log. /// /// if represents a /// data type; otherwise, . /// private static bool ScanTypeForDataTypes(ExtensionAssembly extensionAssembly, Type type, Task task) { try { ElementNameAttribute elementNameAttribute = (ElementNameAttribute) Attribute.GetCustomAttribute(type, typeof(ElementNameAttribute)); if (type.IsSubclassOf(typeof(DataTypeBase)) && !type.IsAbstract && elementNameAttribute != null) { logger.Info(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("String_CreatingDataTypeBaseBuilder"), type.Name)); DataTypeBaseBuilder dtb = new DataTypeBaseBuilder(extensionAssembly, type.FullName); if (DataTypeBuilders[dtb.DataTypeName] == null) { logger.Debug(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("String_AddingDataType"), dtb.DataTypeName, GetAssemblyLocation(dtb.Assembly), dtb.ClassName)); DataTypeBuilders.Add(dtb); } // specified type represents a data type return true; } else { // specified type does not represent valid data type return false; } } catch { task.Log(Level.Error, "Failure scanning \"{0}\" for data types.", type.AssemblyQualifiedName); throw; } } /// /// Scans a given for functions. /// /// The to scan. /// The which will be used to output messages to the build log. /// /// if represents a /// valid set of funtions; otherwise, . /// private static bool ScanTypeForFunctions(Type type, Task task) { try { FunctionSetAttribute functionSetAttribute = (FunctionSetAttribute) Attribute.GetCustomAttribute(type, typeof(FunctionSetAttribute)); if (functionSetAttribute == null) { // specified type does not represent a valid functionset return false; } bool acceptType = (type == typeof(ExpressionEvaluator)); if (type.IsSubclassOf(typeof(FunctionSetBase)) && !type.IsAbstract) { acceptType = true; } if (acceptType) { string prefix = functionSetAttribute.Prefix; if (prefix != null && prefix != String.Empty) { prefix += "::"; } else { task.Log(Level.Warning, "Ignoring functions in type \"{0}\":" + " no prefix was set.", type.AssemblyQualifiedName); // specified type does not represent a valid functionset return false; } // // add public static/instance methods // foreach (MethodInfo info in type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)) { FunctionAttribute functionAttribute = (FunctionAttribute) Attribute.GetCustomAttribute(info, typeof(FunctionAttribute)); if (functionAttribute != null) RegisterFunction(prefix + functionAttribute.Name, info); } // specified type represents a valid functionset return true; } else { // specified type does not represent a valid functionset return false; } } catch { task.Log(Level.Error, "Failure scanning \"{0}\" for functions.", type.AssemblyQualifiedName); throw; } } private static void RegisterFunction(string key, MethodInfo info) { object functions = _methodInfoCollection [key]; if (functions == null) { _methodInfoCollection.Add(key, info); } else { MethodInfo mi = functions as MethodInfo; if (mi == null) { ArrayList overloads = (ArrayList) functions; overloads.Add (info); } else { ArrayList overloads = new ArrayList (3); overloads.Add (mi); overloads.Add (info); _methodInfoCollection [key] = overloads; } } } /// /// Scans a given for filters. /// /// The containing the to scan. /// The to scan. /// The which will be used to output messages to the build log. /// /// if represents a /// ; otherwise, . /// private static bool ScanTypeForFilters(ExtensionAssembly extensionAssembly, Type type, Task task) { try { ElementNameAttribute elementNameAttribute = (ElementNameAttribute) Attribute.GetCustomAttribute(type, typeof(ElementNameAttribute)); if (type.IsSubclassOf(typeof(Filter)) && !type.IsAbstract && elementNameAttribute != null) { task.Log(Level.Debug, "Creating FilterBuilder for \"{0}\".", type.Name); FilterBuilder builder = new FilterBuilder(extensionAssembly, type.FullName); if (FilterBuilders[builder.FilterName] == null) { FilterBuilders.Add(builder); task.Log(Level.Debug, "Adding filter \"{0}\" from {1}:{2}.", builder.FilterName, GetAssemblyLocation(builder.Assembly), builder.ClassName); } // specified type represents a filter return true; } // specified type does not represent a valid filter return false; } catch { task.Log(Level.Error, "Failure scanning \"{0}\" for filters.", type.AssemblyQualifiedName); throw; } } private static string GetAssemblyLocation(Assembly assembly) { try { return assembly.Location; } catch (NotSupportedException) { // Location is not supported in dynamic assemblies, so instead // return name return assembly.GetName().Name; } } #endregion Private Static Methods } } nant-0.92-rc1/src/NAnt.Core/DataTypeBaseBuilder.cs0000644000175000017500000001116411757302272021514 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Ian MacLean (imaclean@gmail.com) using System; using System.Globalization; using System.Reflection; using System.Security.Permissions; using NAnt.Core.Attributes; using NAnt.Core.Extensibility; namespace NAnt.Core { public class DataTypeBaseBuilder : ExtensionBuilder { #region Public Instance Constructors /// /// Creates a new instance of the class /// for the specified class in the specified /// . /// /// /// An for the specified /// is cached for future use. /// /// The containing the . /// The class representing the . public DataTypeBaseBuilder (Assembly assembly, string className) : this (ExtensionAssembly.Create (assembly), className) { } #endregion Public Instance Constructors #region Internal Instance Constructors /// /// Creates a new instance of the /// class for the specified class in the /// specified. /// /// The containing the . /// The class representing the . internal DataTypeBaseBuilder(ExtensionAssembly extensionAssembly, string className) : base (extensionAssembly) { _className = className; } #endregion Internal Instance Constructors #region Public Instance Properties /// /// Gets the name of the class that can be /// created using this . /// /// /// The name of the class that can be created /// using this . /// public string ClassName { get { return _className; } } /// /// Gets the name of the data type which the /// can create. /// /// /// The name of the data type which the /// can create. /// public string DataTypeName { get { if (_dataTypeName == null) { ElementNameAttribute ElementNameAttribute = (ElementNameAttribute) Attribute.GetCustomAttribute(Assembly.GetType(ClassName), typeof(ElementNameAttribute)); _dataTypeName = ElementNameAttribute.Name; } return _dataTypeName; } } #endregion Public Instance Properties #region Public Instance Methods [ReflectionPermission(SecurityAction.Demand, Flags=ReflectionPermissionFlag.NoFlags)] public DataTypeBase CreateDataTypeBase() { return (DataTypeBase) Assembly.CreateInstance( ClassName, true, BindingFlags.Public | BindingFlags.Instance, null, null, CultureInfo.InvariantCulture, null); } #endregion Public Instance Methods #region Private Instance Fields private readonly string _className; private string _dataTypeName; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.Core/DataTypeBase.cs0000644000175000017500000001175011757302272020206 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian MacLean (imaclean@gmail.com) using System; using System.Globalization; using System.Xml; using NAnt.Core.Attributes; using NAnt.Core.Util; namespace NAnt.Core { /// /// Provides the abstract base class for types. /// [Serializable()] public abstract class DataTypeBase : Element { #region Private Instance Fields private string _id; private string _refID; #endregion Private Instance Fields #region Public Instance Properties /// /// The ID used to be referenced later. /// [TaskAttribute("id" )] public string ID { get { return _id; } set { _id = StringUtils.ConvertEmptyToNull(value); } } /// /// The ID to use as the reference. /// [TaskAttribute("refid")] public string RefID { get { return _refID; } set { _refID = StringUtils.ConvertEmptyToNull(value); } } /// /// Gets a value indicating whether a reference to the type can be /// defined. /// /// /// Only types with an assigned /// to it, can be referenced. /// public bool CanBeReferenced { get { return Name != null; } } #endregion Public Instance Properties #region Override implementation of Element /// /// Gets the name of the datatype. /// /// /// The name of the datatype. /// public override string Name { get { string name = null; ElementNameAttribute elementName = (ElementNameAttribute) Attribute.GetCustomAttribute(GetType(), typeof(ElementNameAttribute)); if (elementName != null) { name = elementName.Name; } return name; } } protected override void Initialize() { if (Parent == null) { // output warning message Log(Level.Warning, "Parent property should be set on types" + " deriving from DataTypeBase to determine whether" + " the type is declared on a valid level."); // skip further tests return; } if (Parent.GetType() == typeof(Project) || Parent.GetType() == typeof(Target)) { if (String.IsNullOrEmpty(ID)) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1010"), Name), Location); } if (!String.IsNullOrEmpty(RefID)) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1009"), Name), Location); } } else { if (!String.IsNullOrEmpty(ID)) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1008") + " can only be declared at Project or Target level.", Name), Location); } } } #endregion Override implementation of Element #region Public Instance Methods /// /// Should be overridden by derived classes. clones the referenced types /// data into the current instance. /// public virtual void Reset( ) { } #endregion Public Instance Methods #region Protected Instance Methods /// /// Copies all instance data of the to a given /// . /// protected void CopyTo(DataTypeBase clone) { base.CopyTo(clone); clone._id = _id; clone._refID = _refID; } #endregion Protected Instance Methods } }nant-0.92-rc1/src/NAnt.Core/Attributes/0000755000175000017500000000000011757310030017462 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.Core/Attributes/FunctionAttribute.cs0000644000175000017500000000536711757302272023506 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Jaroslaw Kowalski (jkowalski@users.sourceforge.net) using System; namespace NAnt.Core.Attributes { /// /// Indicates that the method should be exposed as a function in NAnt build /// files. /// /// /// Attach this attribute to a method of a class that derives from /// to have NAnt be able to recognize it. /// [AttributeUsage(AttributeTargets.Method, Inherited=false, AllowMultiple=false)] public sealed class FunctionAttribute : Attribute { #region Public Instance Constructors /// /// Initializes a new instance of the /// class with the specified name. /// /// The name of the function. /// is . /// is a zero-length . public FunctionAttribute(string name) { if (name == null) { throw new ArgumentNullException("name"); } if (name.Trim().Length == 0) { throw new ArgumentOutOfRangeException("name", name, "A zero-length string is not an allowed value."); } _name = name; } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets the name of the function. /// /// /// The name of the function. /// public string Name { get { return _name; } set { _name = value; } } #endregion Public Instance Properties #region Private Instance Fields private string _name; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.Core/Attributes/BooleanValidatorAttribute.cs0000644000175000017500000000451611757302272025141 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) using System; using System.Globalization; using NAnt.Core.Util; namespace NAnt.Core.Attributes { /// /// Used to indicate that a property should be able to be converted into a /// . /// [AttributeUsage(AttributeTargets.Property, Inherited=true)] public sealed class BooleanValidatorAttribute : ValidatorAttribute { #region Public Instance Constructors /// /// Initializes a new instance of the /// class. /// public BooleanValidatorAttribute() { } #endregion Public Instance Constructors #region Override implementation of ValidatorAttribute /// /// Checks if the specified value can be converted to a . /// /// The value to be checked. /// cannot be converted to a . public override void Validate(object value) { try { Convert.ToBoolean(value, CultureInfo.InvariantCulture); } catch (Exception ex) { throw new ValidationException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1088"), value.ToString()), ex); } } #endregion Override implementation of ValidatorAttribute } }nant-0.92-rc1/src/NAnt.Core/Attributes/DateTimeValidatorAttribute.cs0000644000175000017500000000455511757302272025261 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Clayton Harbour (claytonharbour@sporadicism.com) using System; using System.Globalization; using NAnt.Core.Util; namespace NAnt.Core.Attributes { /// /// Used to indicate that a property should be able to be converted into a /// . /// [AttributeUsage(AttributeTargets.Property, Inherited=true)] public sealed class DateTimeValidatorAttribute : ValidatorAttribute { #region Public Instance Constructors /// /// Initializes a new instance of the /// class. /// public DateTimeValidatorAttribute() { } #endregion Public Instance Constructors #region Override implementation of ValidatorAttribute /// /// Checks if the specified value can be converted to a . /// /// The value to be checked. /// cannot be converted to a . public override void Validate(object value) { try { Convert.ToDateTime(value, CultureInfo.InvariantCulture); } catch (Exception ex) { throw new ValidationException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1089"), value.ToString()), ex); } } #endregion Override implementation of ValidatorAttribute } }nant-0.92-rc1/src/NAnt.Core/Attributes/ProgramLocationAttribute.cs0000644000175000017500000000622711757302272025015 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian MacLean ( ian@maclean.ms ) using System; using NAnt.Core.Tasks; namespace NAnt.Core.Attributes { /// /// Defines possible locations in which a task executable can be located. /// public enum LocationType { /// /// Locates the task executable in the current Framework directory. /// FrameworkDir, /// /// Locates the task executable in the current Framework SDK directory. /// FrameworkSdkDir } /// /// Indicates the location that a task executable can be located in. /// /// /// /// When applied to a task deriving from , /// the program to execute will first be searched for in the designated /// location. /// /// /// If the program does not exist in that location, and the file name is /// not an absolute path then the list of tool paths of the current /// target framework will be searched (in the order in which they are /// defined in the NAnt configuration file). /// /// [AttributeUsage(AttributeTargets.Class, Inherited=false, AllowMultiple=false)] public class ProgramLocationAttribute : Attribute { #region Protected Instance Constructors /// /// Initializes a new instance of the /// with the specified location. /// /// The of the attribute. public ProgramLocationAttribute(LocationType type) { LocationType = type; } #endregion Protected Instance Constructors #region Public Instance Properties /// /// Gets or sets the of the task. /// /// /// The location type of the task to which the attribute is assigned. /// public LocationType LocationType { get { return _locationType; } set { _locationType = value; } } #endregion Public Instance Properties #region Private Instance Fields private LocationType _locationType; #endregion Private Instance Fields } }nant-0.92-rc1/src/NAnt.Core/Attributes/FunctionSetAttribute.cs0000644000175000017500000001001711757302272024146 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Jaroslaw Kowalski (jkowalski@users.sourceforge.net) using System; namespace NAnt.Core.Attributes { /// /// Indicates that class should be treated as a set of functions. /// /// /// Attach this attribute to a class that derives from /// to have NAnt be able to recognize it as containing custom functions. /// [AttributeUsage(AttributeTargets.Class, Inherited=false, AllowMultiple=false)] public sealed class FunctionSetAttribute : Attribute { #region Public Instance Constructors /// /// Initializes a new instance of the /// class with the specified name. /// /// The prefix used to distinguish the functions. /// The category of the functions. /// /// is . /// -or- /// is . /// /// /// is a zero-length . /// -or- /// is a zero-length . /// public FunctionSetAttribute(string prefix, string category) { if (prefix == null) { throw new ArgumentNullException("prefix"); } if (category == null) { throw new ArgumentNullException("category"); } if (prefix.Trim().Length == 0) { throw new ArgumentOutOfRangeException("prefix", prefix, "A zero-length string is not an allowed value."); } if (category.Trim().Length == 0) { throw new ArgumentOutOfRangeException("category", category, "A zero-length string is not an allowed value."); } _prefix = prefix; _category = category; } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets the category of the function set. /// /// /// The name of the category of the function set. /// /// /// This will be displayed in the user docs. /// public string Category { get { return _category; } set { _category = value; } } /// /// Gets or sets the prefix of all functions in this function set. /// /// /// The prefix of the functions in this function set. /// public string Prefix { get { return _prefix; } set { _prefix = value; } } #endregion Public Instance Properties #region Private Instance Fields private string _prefix; private string _category; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.Core/Attributes/Int32ValidatorAttribute.cs0000644000175000017500000001203511757302272024454 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) using System; using System.Reflection; using System.Globalization; using NAnt.Core.Util; namespace NAnt.Core.Attributes { /// /// Indicates that property should be able to be converted into a /// within the given range. /// [AttributeUsage(AttributeTargets.Property, Inherited=true)] public sealed class Int32ValidatorAttribute : ValidatorAttribute { #region Public Instance Constructors /// /// Initializes a new instance of the /// class. /// public Int32ValidatorAttribute() { } /// /// Initializes a new instance of the /// class with the specied minimum and maximum values. /// /// The minimum value. /// The maximum value. public Int32ValidatorAttribute(int minValue, int maxValue) { MinValue = minValue; MaxValue = maxValue; } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets the minimum value. /// /// /// The minimum value. The default is . /// public int MinValue { get { return _minValue; } set { _minValue = value; } } /// /// Gets or sets the maximum value. /// /// /// The maximum value. The default is . /// public int MaxValue { get { return _maxValue; } set { _maxValue = value; } } /// /// The base of the number to validate, which must be 2, 8, 10, or 16. /// /// /// The base of the number to validate. /// /// /// The default is 10. /// public int Base { get { return _base; } set { _base = value; } } #endregion Public Instance Properties #region Override implementation of ValidatorAttribute /// /// Checks whether the specified value can be converted to an /// and whether the value lies within the range defined by the /// and properties. /// /// The value to be checked. /// /// /// cannot be converted to an . /// /// -or- /// /// is not in the range defined by /// and . /// /// public override void Validate(object value) { Int32 intValue; try { if (value is String) { intValue = Convert.ToInt32((string) value, Base); } else { intValue = Convert.ToInt32(value, CultureInfo.InvariantCulture); } } catch (Exception ex) { throw new ValidationException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1091"), value.ToString()), ex); } if (intValue < MinValue || intValue > MaxValue) { throw new ValidationException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1090"), value.ToString(), MinValue, MaxValue)); } } #endregion Override implementation of ValidatorAttribute #region Private Instance Fields private int _minValue = Int32.MinValue; private int _maxValue = Int32.MaxValue; private int _base = 10; #endregion Private Instance Fields } }nant-0.92-rc1/src/NAnt.Core/Attributes/ValidatorAttribute.cs0000644000175000017500000000267011757302272023640 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) using System; namespace NAnt.Core.Attributes { /// /// Base class for all validator attributes. /// [AttributeUsage(AttributeTargets.Property, Inherited=true)] public abstract class ValidatorAttribute : Attribute { #region Public Instance Methods /// /// Validates the specified value. /// /// The value to be validated. /// The validation fails. public abstract void Validate(object value); #endregion Public Instance Methods } }nant-0.92-rc1/src/NAnt.Core/Attributes/BuildElementAttribute.cs0000644000175000017500000001007211757302272024257 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian MacLean ( ian@maclean.ms ) // Scott Hernandez (ScottHernandez_at_HOtMail_dot_dot_dot_com?) using System; namespace NAnt.Core.Attributes { /// /// Indicates that the property should be treated as an XML element and /// further processing should be done. /// /// /// /// The XML format is like this: /// /// /// /// /// /// /// ]]> /// /// /// [AttributeUsage(AttributeTargets.Property | AttributeTargets.Method, Inherited=true)] public class BuildElementAttribute : Attribute { #region Protected Instance Constructors /// /// Initializes a new instance of the with the /// specified name. /// /// The name of the attribute. /// is . /// is a zero-length . public BuildElementAttribute(string name) { Name = name; } #endregion Protected Instance Constructors #region Public Instance Properties /// /// Gets or sets the name of the attribute. /// /// /// The name of the attribute. /// public string Name { get { return _name; } set { if (value == null) { throw new ArgumentNullException("name"); } // XML element names cannot have whitespace at the beginning, // or end. _name = value.Trim(); if (_name.Length == 0) { throw new ArgumentOutOfRangeException("name", value, "A zero-length string is not an allowed value."); } } } /// /// Gets or sets a value indicating whether the attribute is required. /// /// /// if the attribute is required; otherwise, /// . The default is . /// public bool Required { get { return _required; } set { _required = value; } } /// /// Used to specify how this element will be handled as the XML is parsed /// and given to the element. /// /// /// if XML should be processed; otherwise /// . The default is . /// public bool ProcessXml { get { return _processXml; } set { _processXml = value; } } #endregion Public Instance Properties #region Private Instance Fields private string _name; private bool _required; private bool _processXml = true; #endregion Private Instance Fields } }nant-0.92-rc1/src/NAnt.Core/Attributes/BuildElementCollectionAttribute.cs0000644000175000017500000000711511757302272026277 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) // Scott Hernandez (ScottHernandez_at_HOtMail_dot_dot_dot_com?) using System; namespace NAnt.Core.Attributes { /// /// Indicates that the property should be treated as a container for a /// collection of build elements. /// /// /// /// Should only be applied to properties exposing strongly typed arrays or /// strongly typed collections. /// /// /// The XML format is like this: /// /// /// /// /// /// /// /// /// /// ]]> /// /// /// [AttributeUsage(AttributeTargets.Property, Inherited=true)] public sealed class BuildElementCollectionAttribute : BuildElementArrayAttribute{ #region Public Instance Constructors /// /// Initializes a new instance of the with the /// specified name and child element name. /// /// The name of the collection. /// The name of the child elements in the collection /// is . /// is a zero-length . public BuildElementCollectionAttribute(string collectionName, string childName) : base(collectionName) { if (childName == null) { throw new ArgumentNullException("childName"); } _elementName = childName.Trim(); if (_elementName.Length == 0) { throw new ArgumentOutOfRangeException("childName", childName, "A zero-length string is not an allowed value."); } } #endregion Public Instance Constructors #region Public Instance Constructors /// /// The name of the child element within the collection. /// /// /// The name to check for in the XML of the elements in the collection. /// /// /// This can be used for validation and schema generation. /// public string ChildElementName { get { return _elementName; } } #endregion Public Instance Constructors #region Private Instance Fields private string _elementName; #endregion Private Instance Fields } }nant-0.92-rc1/src/NAnt.Core/Attributes/BuildAttributeAttribute.cs0000644000175000017500000001265411757302272024641 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) using System; namespace NAnt.Core.Attributes { /// /// Indicates that property should be treated as a XML attribute for the /// task. /// /// /// Examples of how to specify task attributes /// /// #region Public Instance Properties /// /// [BuildAttribute("out", Required=true)] /// public string Output { /// get { return _out; } /// set { _out = value; } /// } /// /// [BuildAttribute("optimize")] /// [BooleanValidator()] /// public bool Optimize { /// get { return _optimize; } /// set { _optimize = value; } /// } /// /// [BuildAttribute("warnlevel")] /// [Int32Validator(0,4)] // limit values to 0-4 /// public int WarnLevel { /// get { return _warnLevel; } /// set { _warnLevel = value; } /// } /// /// [BuildElement("sources")] /// public FileSet Sources { /// get { return _sources; } /// set { _sources = value; } /// } /// /// #endregion Public Instance Properties /// /// #region Private Instance Fields /// /// private string _out = null; /// private bool _optimize = false; /// private int _warnLevel = 4; /// private FileSet _sources = new FileSet(); /// /// #endregion Private Instance Fields /// /// [AttributeUsage(AttributeTargets.Property, Inherited=true)] public abstract class BuildAttributeAttribute : Attribute { #region Protected Instance Constructors /// /// Initializes a new instance of the with the /// specified name. /// /// The name of the attribute. /// is . /// is a zero-length . protected BuildAttributeAttribute(string name) { Name = name; } #endregion Protected Instance Constructors #region Public Instance Properties /// /// Gets or sets the name of the XML attribute. /// /// /// The name of the XML attribute. /// public string Name { get { return _name; } set { if (value == null) { throw new ArgumentNullException("name"); } // XML attribute names cannot have whitespace at the beginning, // or end. _name = value.Trim(); if (_name.Length == 0) { throw new ArgumentOutOfRangeException("name", value, "A zero-length string is not an allowed value."); } } } /// /// Gets or sets a value indicating whether the attribute is required. /// /// /// if the attribute is required; otherwise, /// . The default is . /// public bool Required { get { return _required; } set { _required = value; } } /// /// Gets or sets a value indicating whether property references should /// be expanded. /// /// /// if properties should be expanded; otherwise /// . The default is . /// public bool ExpandProperties { get { return _expandProperties; } set { _expandProperties = value; } } /// /// Used to specify how this attribute will be handled as the XML is /// parsed and given to the element. /// /// /// if XML should be processed; otherwise /// . The default is . /// public bool ProcessXml { get { return _processXml; } set { _processXml = value; } } #endregion Public Instance Properties #region Private Instance Fields private string _name; private bool _required; private bool _expandProperties = true; private bool _processXml = true; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.Core/Attributes/StringValidatorAttribute.cs0000644000175000017500000001175111757302272025027 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Globalization; using System.Text.RegularExpressions; using NAnt.Core.Util; namespace NAnt.Core.Attributes { /// /// Used to indicate whether a property should allow /// an empty string value or not. /// [AttributeUsage(AttributeTargets.Property, Inherited=true)] public sealed class StringValidatorAttribute : ValidatorAttribute { #region Public Instance Constructors /// /// Initializes a new instance of the /// class. /// public StringValidatorAttribute() { } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets a value indicating whether an empty string or /// should be a considered a valid value. /// /// /// if an empty string or /// should be considered a valid value; otherwise, . /// The default is . /// public bool AllowEmpty { get { return _allowEmpty; } set { _allowEmpty = value; } } /// /// Gets or sets a regular expression. The string will be validated to /// determine if it matches the expression. /// /// /// /// public string Expression { get { return _expression; } set { _expression = value; } } /// /// An optional error message that can be used to better describe the /// regular expression error. /// public string ExpressionErrorMessage { get { return this._expressionErrorMessage; } set { this._expressionErrorMessage = value; } } #endregion Public Instance Properties #region Override implementation of ValidatorAttribute /// /// Checks if the specified value adheres to the rules defined by the /// properties of the . /// /// The value to be checked. /// is an empty string value and is set to . public override void Validate(object value) { string valueString; try { valueString = Convert.ToString(value, CultureInfo.InvariantCulture); } catch (Exception ex) { throw new ValidationException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1092"), value.ToString()), ex); } if (String.IsNullOrEmpty(valueString)) { if (!AllowEmpty) { throw new ValidationException("An empty value is not allowed."); } // if we allow empty value, then there's no need to validate // value against expression return; } if (!String.IsNullOrEmpty(Expression)) { if (!Regex.IsMatch(Convert.ToString(value), Expression)) { string msg = string.Format("String {0} does not match expression {1}.", value, Expression); if (null != this.ExpressionErrorMessage && string.Empty != this.ExpressionErrorMessage) { msg = this.ExpressionErrorMessage; } throw new ValidationException(msg); } } } #endregion Override implementation of ValidatorAttribute #region Private Instance Fields private bool _allowEmpty = true; private string _expression; private string _expressionErrorMessage; #endregion Private Instance Fields } }nant-0.92-rc1/src/NAnt.Core/Attributes/TaskNameAttribute.cs0000644000175000017500000000400711757302272023412 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Scott Hernandez (ScottHernandez_at_HOtMail_dot_dot_dot_com?) using System; namespace NAnt.Core.Attributes { /// /// Indicates that class should be treated as a task. /// /// /// Attach this attribute to a subclass of Task to have NAnt be able /// to recognize it. The name should be short but must not confict /// with any other task already in use. /// [AttributeUsage(AttributeTargets.Class, Inherited=false, AllowMultiple=false)] public sealed class TaskNameAttribute : ElementNameAttribute { #region Public Instance Constructors /// /// Initializes a new instance of the /// with the specified name. /// /// The name of the task. /// is . /// is a zero-length . public TaskNameAttribute(string name) : base(name) { } #endregion Public Instance Constructors } } nant-0.92-rc1/src/NAnt.Core/Attributes/TaskAttributeAttribute.cs0000644000175000017500000000542711757302272024504 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) using System; namespace NAnt.Core.Attributes { /// /// Indicates that property should be treated as a XML attribute for the /// task. /// /// /// Examples of how to specify task attributes /// /// // task XmlType default is string /// [TaskAttribute("out", Required=true)] /// string _out = null; // assign default value here /// /// [TaskAttribute("optimize")] /// [BooleanValidator()] /// // during ExecuteTask you can safely use Convert.ToBoolean(_optimize) /// string _optimize = Boolean.FalseString; /// /// [TaskAttribute("warnlevel")] /// [Int32Validator(0,4)] // limit values to 0-4 /// // during ExecuteTask you can safely use Convert.ToInt32(_optimize) /// string _warnlevel = "0"; /// /// [BuildElement("sources")] /// FileSet _sources = new FileSet(); /// /// NOTE: Attribute values must be of type of string if you want /// to be able to have macros. The field stores the exact value during /// Initialize. Just before ExecuteTask is called NAnt will expand /// all the macros with the current values. /// [AttributeUsage(AttributeTargets.Property, Inherited=true)] public sealed class TaskAttributeAttribute : BuildAttributeAttribute { #region Public Instance Constructors /// /// Initializes a new instance of the /// with the specified attribute name. /// /// The name of the task attribute. /// is a . /// is a zero-length . public TaskAttributeAttribute(string name) : base(name){ } #endregion Public Instance Constructors } } nant-0.92-rc1/src/NAnt.Core/Attributes/FrameworkConfigurableAttribute.cs0000644000175000017500000001052411757302272026166 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; namespace NAnt.Core.Attributes { /// /// Indicates that the value of the property to which the attribute is /// assigned, can be configured on the framework-level in the NAnt application /// configuration file. /// /// /// /// The following example shows a property of which the value can be /// configured for a specific framework in the NAnt configuration file. /// /// /// [FrameworkConfigurable("exename", Required=true)] /// public virtual string ExeName { /// get { return _exeName; } /// set { _exeName = value; } /// } /// /// [AttributeUsage(AttributeTargets.Property, Inherited=true)] public sealed class FrameworkConfigurableAttribute : Attribute { #region Public Instance Constructors /// /// Initializes a new instance of the /// with the specified attribute name. /// /// The name of the framework configuration attribute. /// is a . /// is a zero-length . public FrameworkConfigurableAttribute(string name) { Name = name; } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets the name of the framework configuration attribute. /// /// The name of the framework configuration attribute. public string Name { get { return _name; } set { if (value == null) { throw new ArgumentNullException("name"); } // attribute names cannot have whitespace at the beginning, // or end. _name = value.Trim(); if (_name.Length == 0) { throw new ArgumentOutOfRangeException("name", value, "A zero-length string is not an allowed value."); } } } /// /// Gets or sets a value indicating whether the configuration attribute /// is required. /// /// /// if the configuration attribute is required; /// otherwise, . The default is . /// public bool Required { get { return _required; } set { _required = value; } } #endregion Public Instance Properties /// /// Gets or sets a value indicating whether property references should /// be expanded. /// /// /// if properties should be expanded; otherwise /// . The default is . /// public bool ExpandProperties { get { return _expandProperties; } set { _expandProperties = value; } } #region Private Instance Fields private string _name; private bool _required; private bool _expandProperties = true; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.Core/Attributes/BuildElementArrayAttribute.cs0000644000175000017500000000656511757302272025272 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian MacLean ( ian@maclean.ms ) // Scott Hernandez (ScottHernandez_at_HOtMail_dot_dot_dot_com?) using System; namespace NAnt.Core.Attributes { /// /// Indicates that property should be treated as a XML arrayList /// /// /// /// Should only be applied to properties exposing strongly typed arrays or /// strongly typed collections. /// /// /// The XML format is like this: /// /// /// /// /// /// /// /// ]]> /// /// /// [AttributeUsage(AttributeTargets.Property, Inherited=true)] public class BuildElementArrayAttribute : BuildElementAttribute { #region Public Instance Constructors /// /// Initializes a new instance of the /// with the specified name. /// /// The name of the attribute. /// is . /// is a zero-length . public BuildElementArrayAttribute(string name) : base(name) { } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets the type of objects that this container holds. /// /// /// The type of the elements that this container holds. /// /// /// /// This can be used for validation and schema generation. /// /// /// If not specified, the type of the elements will be determined using /// reflection. /// /// /// is . public Type ElementType { get { return _elementType; } set { if (value == null) { throw new ArgumentNullException("ElementType"); } _elementType = value; } } #endregion Public Instance Properties #region Private Instance Fields private Type _elementType; #endregion Private Instance Fields } }nant-0.92-rc1/src/NAnt.Core/Attributes/FileSetAttribute.cs0000644000175000017500000000367611757302272023255 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2005 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Ian MacLean ( ian@maclean.ms ) // Scott Hernandez (ScottHernandez_at_HOtMail_dot_dot_dot_com?) using System; namespace NAnt.Core.Attributes { /// /// Indicates that a property should be treated as a XML file set for the /// task. /// [AttributeUsage(AttributeTargets.Property, Inherited=true)] [Obsolete("Please use a BuildElement attribute instead. This class will be removed soon.", true)] public sealed class FileSetAttribute : BuildElementAttribute { #region Public Instance Constructors /// /// Initializes a new instance of the with the /// specified name. /// /// The name of the attribute. /// is . /// is a zero-length . public FileSetAttribute(string name) : base(name) { } #endregion Public Instance Constructors } }nant-0.92-rc1/src/NAnt.Core/Attributes/ElementNameAttribute.cs0000644000175000017500000000562211757302272024105 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian MacLean (imaclean@gmail.com) using System; using System.Reflection; namespace NAnt.Core.Attributes { /// /// Indicates that class should be treated as a NAnt element. /// /// /// Attach this attribute to a subclass of Element to have NAnt be able /// to recognize it. The name should be short but must not confict /// with any other element already in use. /// [AttributeUsage(AttributeTargets.Class, Inherited=false, AllowMultiple=false)] public class ElementNameAttribute : Attribute { #region Public Instance Constructors /// /// Initializes a new instance of the /// with the specified name. /// /// The name of the element. /// is . /// is a zero-length . public ElementNameAttribute(string name) { Name = name; } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets the name of the element. /// /// /// The name of the element. /// public string Name { get { return _name; } set { if (value == null) { throw new ArgumentNullException("name"); } // Element names cannot have whitespace at the beginning, // or end. _name = value.Trim(); if (_name.Length == 0) { throw new ArgumentOutOfRangeException("name", value, "A zero-length string is not an allowed value."); } } } #endregion Public Instance Properties #region Private Instance Fields private string _name; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.Core/AssemblyInfo.cs0000644000175000017500000000233211757302272020267 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Scott Hernandez (ScottHernandez@hotmail.com) // Gert Driesen (drieseng@users.sourceforge.net) using System.Reflection; // This will not compile with Visual Studio. If you want to build a signed // executable use the NAnt build file. To build under Visual Studio just // exclude this file from the build. [assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile(@"..\NAnt.key")] [assembly: AssemblyKeyName("")]nant-0.92-rc1/src/NAnt.Core/PropertyDictionary.cs0000644000175000017500000006175011757302273021560 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Tomas Restrepo (tomasr@mvps.org) // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.Text; using System.Text.RegularExpressions; using NAnt.Core.Util; namespace NAnt.Core { [Serializable()] public class PropertyDictionary : DictionaryBase { #region Public Instance Constructors /// /// Initializes a new instance of the /// class holding properties for the given /// instance. /// /// The project for which the dictionary will hold properties. public PropertyDictionary(Project project){ _project = project; } #endregion Public Instance Constructors #region Public Instance Properties /// /// Indexer property. /// public virtual string this[string name] { get { string value = (string) Dictionary[(object) name]; // check whether (built-in) property is deprecated CheckDeprecation(name); if (IsDynamicProperty(name)) { return ExpandProperties(value, Location.UnknownLocation); } else { return value; } } set { Dictionary[name] = value; } } /// /// Gets the project for which the dictionary holds properties. /// /// /// The project for which the dictionary holds properties. /// public Project Project { get { return _project; } } #endregion Public Instance Properties #region Override implementation of DictionaryBase protected override void OnClear() { _readOnlyProperties.Clear(); _dynamicProperties.Clear(); } protected override void OnSet(object key, object oldValue, object newValue) { // at this point we're sure the key is valid, as it has already // been verified by OnValidate string propertyName = (string) key; // do not allow value of read-only property to be overwritten if (IsReadOnlyProperty(propertyName)) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1068"), propertyName), Location.UnknownLocation); } base.OnSet(key, oldValue, newValue); } /// /// Performs additional custom processes before inserting a new element /// into the instance. /// /// The key of the element to insert. /// The value of the element to insert. protected override void OnInsert(object key, object value) { // at this point we're sure the key is valid, as it has already // been verified by OnValidate string propertyName = (string) key; // ensure property doesn't already exist if (Contains(propertyName)) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1065"), propertyName), Location.UnknownLocation); } } /// /// Performs additional custom processes before removing an element /// from the instance. /// /// The key of the element to remove. /// The value of the element to remove. protected override void OnRemove(object key, object value) { string propertyName = key as string; if (propertyName != null && _readOnlyProperties.Contains (propertyName)) { _readOnlyProperties.Remove (propertyName); } } /// /// Performs additional custom processes when validating the element /// with the specified key and value. /// /// The key of the element to validate. /// The value of the element to validate. protected override void OnValidate(object key, object value) { string propertyName = key as string; if (propertyName == null) { throw new ArgumentException("Property name must be a string.", "key"); } ValidatePropertyName(propertyName, Location.UnknownLocation); ValidatePropertyValue(value, Location.UnknownLocation); base.OnValidate(key, value); } #endregion Override implementation of DictionaryBase #region Public Instance Methods /// /// Adds a property that cannot be changed. /// /// The name of the property. /// The value to assign to the property. /// /// Properties added with this method can never be changed. Note that /// they are removed if the method is called. /// public virtual void AddReadOnly(string name, string value) { if (!IsReadOnlyProperty(name)) { Dictionary.Add(name, value); _readOnlyProperties.Add(name); } } /// /// Marks a property as a property of which the value is expanded at /// execution time. /// /// The name of the property to mark as dynamic. public virtual void MarkDynamic(string name) { if (!IsDynamicProperty(name)) { // check if the property actually exists if (!Contains(name)) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1067"))) ; } _dynamicProperties.Add(name); } } /// /// Adds a property to the collection. /// /// The name of the property. /// The value to assign to the property. public virtual void Add(string name, string value) { Dictionary.Add(name, value); } /// /// Determines whether the specified property is listed as read-only. /// /// The name of the property to check. /// /// if the property is listed as read-only; /// otherwise, . /// public virtual bool IsReadOnlyProperty(string name) { return _readOnlyProperties.Contains(name); } /// /// Determines whether the specified property is listed as dynamic. /// /// The name of the property to check. /// /// if the property is listed as dynamic; /// otherwise, . /// public virtual bool IsDynamicProperty(string name) { return _dynamicProperties.Contains(name); } /// /// Inherits properties from an existing property dictionary Instance. /// /// Property list to inherit. /// The list of properties to exclude during inheritance. public virtual void Inherit(PropertyDictionary source, StringCollection excludes) { foreach (DictionaryEntry entry in source.Dictionary) { string propertyName = (string) entry.Key; if (excludes != null && excludes.Contains(propertyName)) { continue; } // do not overwrite an existing read-only property if (IsReadOnlyProperty(propertyName)) { continue; } // add property to dictionary ValidatePropertyName(propertyName, Location.UnknownLocation); Dictionary[propertyName] = entry.Value; // if property is readonly, add to collection of readonly properties if (source.IsReadOnlyProperty(propertyName)) { _readOnlyProperties.Add(propertyName); } // if property is dynamic, add to collection of dynamic properties // if it was not already in that collection if (source.IsDynamicProperty(propertyName) && !IsDynamicProperty(propertyName)) { _dynamicProperties.Add(propertyName); } } } /// /// Expands a from known properties. /// /// The replacement tokens. /// The to pass through for any exceptions. /// The expanded and replaced string. public string ExpandProperties(string input, Location location) { Hashtable state = new Hashtable(); Stack visiting = new Stack(); return ExpandProperties(input, location, state, visiting); } /// /// Determines whether a property already exists. /// /// The name of the property to check. /// /// if the specified property already exists; /// otherwise, . /// public bool Contains(string name) { return Dictionary.Contains(name); } /// /// Removes the property with the specified name. /// /// The name of the property to remove. public void Remove(string name) { Dictionary.Remove(name); } #endregion Public Instance Methods #region Internal Instance Methods internal string GetPropertyValue(string propertyName) { // check whether (built-in) property is deprecated CheckDeprecation(propertyName); return (string) Dictionary[propertyName]; } /// /// Expands a from known properties. /// /// The replacement tokens. /// The to pass through for any exceptions. /// A mapping from properties to states. The states in question are "VISITING" and "VISITED". Must not be . /// A stack of properties which are currently being visited. Must not be . /// The expanded and replaced string. internal string ExpandProperties(string input, Location location, Hashtable state, Stack visiting) { return EvaluateEmbeddedExpressions(input, location, state, visiting); } #endregion Internal Instance Methods #region Private Instance Methods /// /// Evaluates the given expression string and returns the result /// /// /// /// /// /// private string EvaluateEmbeddedExpressions(string input, Location location, Hashtable state, Stack visiting) { if (input == null) { return null; } if (input.IndexOf('$') < 0) { return input; } try { StringBuilder output = new StringBuilder(input.Length); ExpressionTokenizer tokenizer = new ExpressionTokenizer(); ExpressionEvaluator eval = new ExpressionEvaluator(Project, this, state, visiting); tokenizer.IgnoreWhitespace = false; tokenizer.SingleCharacterMode = true; tokenizer.InitTokenizer(input); while (tokenizer.CurrentToken != ExpressionTokenizer.TokenType.EOF) { if (tokenizer.CurrentToken == ExpressionTokenizer.TokenType.Dollar) { tokenizer.GetNextToken(); if (tokenizer.CurrentToken == ExpressionTokenizer.TokenType.LeftCurlyBrace) { tokenizer.IgnoreWhitespace = true; tokenizer.SingleCharacterMode = false; tokenizer.GetNextToken(); string val = Convert.ToString(eval.Evaluate(tokenizer), CultureInfo.InvariantCulture); output.Append(val); tokenizer.IgnoreWhitespace = false; if (tokenizer.CurrentToken != ExpressionTokenizer.TokenType.RightCurlyBrace) { throw new ExpressionParseException("'}' expected", tokenizer.CurrentPosition.CharIndex); } tokenizer.SingleCharacterMode = true; tokenizer.GetNextToken(); } else { output.Append('$'); if (tokenizer.CurrentToken != ExpressionTokenizer.TokenType.EOF) { output.Append(tokenizer.TokenText); tokenizer.GetNextToken(); } } } else { output.Append(tokenizer.TokenText); tokenizer.GetNextToken(); } } return output.ToString(); } catch (ExpressionParseException ex) { StringBuilder errorMessage = new StringBuilder(); string reformattedInput = input; // replace CR, LF and TAB with a space reformattedInput = reformattedInput.Replace('\n', ' '); reformattedInput = reformattedInput.Replace('\r', ' '); reformattedInput = reformattedInput.Replace('\t', ' '); errorMessage.Append(ex.Message); errorMessage.Append(Environment.NewLine); string label = "Expression: "; errorMessage.Append(label); errorMessage.Append(reformattedInput); int p0 = ex.StartPos; int p1 = ex.EndPos; if (p0 != -1 || p1 != -1) { errorMessage.Append(Environment.NewLine); if (p1 == -1) p1 = p0 + 1; for (int i = 0; i < p0 + label.Length; ++i) errorMessage.Append(' '); for (int i = p0; i < p1; ++i) errorMessage.Append('^'); } throw new BuildException(errorMessage.ToString(), location, ex.InnerException); } } /// /// Checks whether the specified property is deprecated. /// /// The property to check. private void CheckDeprecation(string name) { switch (name) { case Project.NAntPropertyFileName: Project.Log(Level.Warning, "Built-in property '{0}' is deprecated." + " Use assembly::get-location(nant::get-assembly()) expression instead.", name); break; case Project.NAntPropertyVersion: Project.Log(Level.Warning, "Built-in property '{0}' is deprecated." + " Use the assemblyname::get-version(assembly::get-name(nant::get-assembly))" + " expression instead.", name); break; case Project.NAntPropertyLocation: Project.Log(Level.Warning, "Built-in property '{0}' is deprecated." + " Use the nant::get-base-directory() function instead.", name); break; case Project.NAntPropertyProjectBaseDir: Project.Log(Level.Warning, "Built-in property '{0}' is deprecated." + " Use the project::get-base-directory() function instead.", name); break; case Project.NAntPropertyProjectName: Project.Log(Level.Warning, "Built-in property '{0}' is deprecated." + " Use the project::get-name() function instead.", name); break; case Project.NAntPropertyProjectBuildFile: Project.Log(Level.Warning, "Built-in property '{0}' is deprecated." + " Use the project::get-buildfile-uri() function" + " instead.", name); break; case Project.NAntPropertyProjectDefault: Project.Log(Level.Warning, "Built-in property '{0}' is deprecated." + " Use the project::get-default-target() function" + " instead.", name); break; case Project.NAntPlatformName: Project.Log(Level.Warning, "Built-in property '{0}' is deprecated." + " Use the platform::get-name() function instead.", name); break; case Project.NAntPlatform + ".win32": Project.Log(Level.Warning, "Built-in property '{0}' is deprecated." + " Use the platform::is-win32() function instead.", name); break; case Project.NAntPlatform + ".unix": Project.Log(Level.Warning, "Built-in property '{0}' is deprecated." + " Use the platform::is-unix() function instead.", name); break; case "nant.settings.currentframework.description": Project.Log(Level.Warning, "Built-in property '{0}' is deprecated." + " Use the framework::get-description(framework::get-target-framework())" + " function instead.", name); break; case "nant.settings.currentframework.frameworkdirectory": Project.Log(Level.Warning, "Built-in property '{0}' is deprecated." + " Use the framework::get-framework-directory(framework::get-target-framework())" + " function instead.", name); break; case "nant.settings.currentframework.sdkdirectory": Project.Log(Level.Warning, "Built-in property '{0}' is deprecated." + " Use the framework::get-sdk-directory(framework::get-target-framework())" + " function instead.", name); break; case "nant.settings.currentframework.frameworkassemblydirectory": Project.Log(Level.Warning, "Built-in property '{0}' is deprecated." + " Use the framework::get-assembly-directory(framework::get-target-framework())" + " function instead.", name); break; case "nant.settings.currentframework.runtimeengine": Project.Log(Level.Warning, "Built-in property '{0}' is deprecated." + " Use the framework::get-runtime-engine(framework::get-target-framework())" + " function instead.", name); break; default: break; } } #endregion Private Instance Methods #region Private Static Methods private static void ValidatePropertyName(string propertyName, Location location) { const string propertyNamePattern = "^[_A-Za-z0-9][_A-Za-z0-9\\-.]*$"; // validate property name // if (!Regex.IsMatch(propertyName, propertyNamePattern)) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1064"), propertyName), location); } if (propertyName.EndsWith("-") || propertyName.EndsWith(".")) { // this additional rule helps simplify the regex pattern throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1064"), propertyName), location); } } private static void ValidatePropertyValue(object value, Location location) { if (value != null) { if (!(value is string)) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1066"), value.GetType()), "value"); } } else { // TODO: verify this // throw new ArgumentException("Property value '" + propertyName + "' must not be null", "value"); return; } } #endregion Private Static Methods #region Internal Static Methods /// /// Builds an appropriate exception detailing a specified circular /// reference. /// /// The property reference to stop at. Must not be . /// A stack of property references. Must not be . /// /// A detailing the specified circular /// dependency. /// internal static BuildException CreateCircularException(string end, Stack stack) { StringBuilder sb = new StringBuilder("Circular property reference: "); sb.Append(end); string c; do { c = (string) stack.Pop(); sb.Append(" <- "); sb.Append(c); } while (!c.Equals(end)); return new BuildException(sb.ToString()); } #endregion Internal Static Methods #region Private Instance Fields /// /// Maintains a list of the property names that are readonly. /// private StringCollection _readOnlyProperties = new StringCollection(); /// /// Maintains a list of the property names of which the value is expanded /// on usage, not at initalization. /// private StringCollection _dynamicProperties = new StringCollection(); /// /// The project for which the dictionary holds properties. /// private readonly Project _project; #endregion Private Instance Fields #region Internal Static Fields /// /// Constant for the "visiting" state, used when traversing a DFS of /// property references. /// internal const string Visiting = "VISITING"; /// /// Constant for the "visited" state, used when travesing a DFS of /// property references. /// internal const string Visited = "VISITED"; #endregion Internal Static Fields } } nant-0.92-rc1/src/NAnt.Core/DirectoryScanner.cs0000644000175000017500000012156511757302272021164 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Kevin Dente (kevindente@yahoo.com) // This is useful for debugging where filesets are scanned from - scanning is one // of the most intensive activities for NAnt //#define DEBUG_REGEXES /* Examples: "**\*.class" matches all .class files/dirs in a directory tree. "test\a??.java" matches all files/dirs which start with an 'a', then two more characters and then ".java", in a directory called test. "**" matches everything in a directory tree. "**\test\**\XYZ*" matches all files/dirs that start with "XYZ" and where there is a parent directory called test (e.g. "abc\test\def\ghi\XYZ123"). Example of usage: DirectoryScanner scanner = DirectoryScanner(); scanner.Includes.Add("**\\*.class"); scanner.Exlucdes.Add("modules\\*\\**"); scanner.BaseDirectory = "test"; scanner.Scan(); foreach (string filename in GetIncludedFiles()) { Console.WriteLine(filename); } */ using System; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Text; using System.Text.RegularExpressions; using NAnt.Core.Util; namespace NAnt.Core { /// /// Used for searching filesystem based on given include/exclude rules. /// /// /// Simple client code for testing the class. /// /// while (true) { /// DirectoryScanner scanner = new DirectoryScanner(); /// /// Console.Write("Scan Basedirectory : "); /// string s = Console.ReadLine(); /// if (s.Length == 0) break; /// scanner.BaseDirectory = s; /// /// while(true) { /// Console.Write("Include pattern : "); /// s = Console.ReadLine(); /// if (s.Length == 0) break; /// scanner.Includes.Add(s); /// } /// /// while(true) { /// Console.Write("Exclude pattern : "); /// s = Console.ReadLine(); /// if (s.Length == 0) break; /// scanner.Excludes.Add(s); /// } /// /// foreach (string name in scanner.FileNames) /// Console.WriteLine("file:" + name); /// foreach (string name in scanner.DirectoryNames) /// Console.WriteLine("dir :" + name); /// /// Console.WriteLine(""); /// } /// /// [Serializable()] public class DirectoryScanner : ICloneable { #region Private Instance Fields // set to current directory in Scan if user doesn't specify something first. // keeping it null, lets the user detect if it's been set or not. private DirectoryInfo _baseDirectory; // holds the nant patterns (absolute or relative paths) private StringCollectionWithGoodToString _includes = new StringCollectionWithGoodToString(); private StringCollectionWithGoodToString _excludes = new StringCollectionWithGoodToString(); // holds the nant patterns converted to regular expression patterns (absolute canonized paths) private ArrayList _includePatterns; private ArrayList _excludePatterns; // holds the nant patterns converted to non-regex names (absolute canonized paths) private StringCollectionWithGoodToString _includeNames; private StringCollectionWithGoodToString _excludeNames; // holds the result from a scan private StringCollectionWithGoodToString _fileNames; private DirScannerStringCollection _directoryNames; // directories that should be scanned and directories scanned so far private DirScannerStringCollection _searchDirectories; private DirScannerStringCollection _scannedDirectories; private ArrayList _searchDirIsRecursive; private bool _caseSensitive; // Indicates whether or not every file scanned was included private bool _isEverythingIncluded = true; #endregion Private Instance Fields #region Private Static Fields private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static Hashtable cachedCaseSensitiveRegexes = new Hashtable(); private static Hashtable cachedCaseInsensitiveRegexes = new Hashtable(); #endregion Private Static Fields #region Public Instance Constructor /// /// Initializes a new instance of the . /// /// /// On unix, patterns are matching case-sensitively; otherwise, they /// are matched case-insensitively. /// public DirectoryScanner () : this (PlatformHelper.IsUnix) { } /// /// Initializes a new instance of the /// specifying whether patterns are to be match case-sensitively. /// /// Specifies whether patterns are to be matched case-sensititely. public DirectoryScanner (bool caseSensitive) { _caseSensitive = caseSensitive; } #endregion Public Instance Constructor #region Implementation of ICloneable /// /// Creates a shallow copy of the . /// /// /// A shallow copy of the . /// public object Clone() { DirectoryScanner clone = new DirectoryScanner(); if (_baseDirectory != null) { clone._baseDirectory = new DirectoryInfo(_baseDirectory.FullName); } if (_directoryNames != null) { clone._directoryNames = (DirScannerStringCollection) _directoryNames.Clone(); } if (_excludePatterns != null) { clone._excludePatterns = (ArrayList) _excludePatterns.Clone(); } if (_excludeNames != null) { clone._excludeNames = (StringCollectionWithGoodToString) _excludeNames.Clone(); } clone._excludes = (StringCollectionWithGoodToString) _excludes.Clone(); if (_fileNames != null) { clone._fileNames = (StringCollectionWithGoodToString) _fileNames.Clone(); } if (_includePatterns != null) { clone._includePatterns = (ArrayList) _includePatterns.Clone(); } if (_includeNames != null) { clone._includeNames = (StringCollectionWithGoodToString) _includeNames.Clone(); } clone._includes = (StringCollectionWithGoodToString) _includes.Clone(); if (_scannedDirectories != null) { clone._scannedDirectories = (DirScannerStringCollection) _scannedDirectories.Clone(); } if (_searchDirectories != null) { clone._searchDirectories = (DirScannerStringCollection) _searchDirectories.Clone(); } if (_searchDirIsRecursive != null) { clone._searchDirIsRecursive = (ArrayList) _searchDirIsRecursive.Clone(); } clone._caseSensitive = _caseSensitive; return clone; } #endregion Implementation of ICloneable #region Public Instance Properties /// /// Gets or set a value indicating whether or not to use case-sensitive /// pattern matching. /// public bool CaseSensitive { get { return _caseSensitive; } set { if (value != _caseSensitive) { _caseSensitive = value; Reset (); } } } /// /// Gets the collection of include patterns. /// public StringCollection Includes { get { return _includes; } } /// /// Gets the collection of exclude patterns. /// public StringCollection Excludes { get { return _excludes; } } /// /// The base directory to scan. The default is the /// current directory. /// public DirectoryInfo BaseDirectory { get { if (_baseDirectory == null) { _baseDirectory = new DirectoryInfo(CleanPath( Environment.CurrentDirectory).ToString()); } return _baseDirectory; } set { if (value != null) { // convert both slashes and backslashes to directory separator // char value = new DirectoryInfo(CleanPath( value.FullName).ToString()); } if (value != _baseDirectory) { _baseDirectory = value; Reset (); } } } /// /// Gets the list of files that match the given patterns. /// public StringCollection FileNames { get { if (_fileNames == null) { Scan(); } return _fileNames; } } /// /// Gets the list of directories that match the given patterns. /// public StringCollection DirectoryNames { get { if (_directoryNames == null) { Scan(); } return _directoryNames; } } /// /// Gets the list of directories that were scanned for files. /// public StringCollection ScannedDirectories { get { if (_scannedDirectories == null) { Scan(); } return _scannedDirectories; } } /// /// Indicates whether or not the directory scanner included everything /// that it scanned. /// public bool IsEverythingIncluded { get { return _isEverythingIncluded; } } #endregion Public Instance Properties #region Public Instance Methods /// /// Uses and search criteria (relative to /// or absolute), to search for filesystem objects. /// public void Scan() { _includePatterns = new ArrayList(); _includeNames = new StringCollectionWithGoodToString (); _excludePatterns = new ArrayList(); _excludeNames = new StringCollectionWithGoodToString (); _fileNames = new StringCollectionWithGoodToString (); _directoryNames = new DirScannerStringCollection(CaseSensitive); _searchDirectories = new DirScannerStringCollection(CaseSensitive); _searchDirIsRecursive = new ArrayList(); _scannedDirectories = new DirScannerStringCollection(CaseSensitive); #if DEBUG_REGEXES Console.WriteLine("*********************************************************************"); Console.WriteLine("DirectoryScanner.Scan()"); Console.WriteLine("*********************************************************************"); Console.WriteLine(new System.Diagnostics.StackTrace().ToString()); Console.WriteLine("Base Directory: " + BaseDirectory.FullName); Console.WriteLine("Includes:"); foreach (string strPattern in _includes) Console.WriteLine(strPattern); Console.WriteLine("Excludes:"); foreach (string strPattern in _excludes) Console.WriteLine(strPattern); Console.WriteLine("--- Starting Scan ---"); #endif // convert given NAnt patterns to regex patterns with absolute paths // side effect: searchDirectories will be populated ConvertPatterns(_includes, _includePatterns, _includeNames, true); ConvertPatterns(_excludes, _excludePatterns, _excludeNames, false); for (int index = 0; index < _searchDirectories.Count; index++) { ScanDirectory(_searchDirectories[index], (bool) _searchDirIsRecursive[index]); } #if DEBUG_REGEXES Console.WriteLine("*********************************************************************"); #endif } #endregion Public Instance Methods #region Private Instance Methods private void Reset () { _isEverythingIncluded = true; _includePatterns = null; _includeNames = null; _excludePatterns = null; _excludeNames = null; _fileNames = null; _directoryNames = null; _searchDirectories = null; _searchDirIsRecursive = null; _scannedDirectories = null; } /// /// Parses specified NAnt search patterns for search directories and /// corresponding regex patterns. /// /// In. NAnt patterns. Absolute or relative paths. /// Out. Regex patterns. Absolute canonical paths. /// Out. Non-regex files. Absolute canonical paths. /// In. Whether to allow a pattern to add search directories. private void ConvertPatterns(StringCollection nantPatterns, ArrayList regexPatterns, StringCollection nonRegexFiles, bool addSearchDirectories) { string searchDirectory; string regexPattern; bool isRecursive; bool isRegex; foreach (string nantPattern in nantPatterns) { ParseSearchDirectoryAndPattern(addSearchDirectories, nantPattern, out searchDirectory, out isRecursive, out isRegex, out regexPattern); if (isRegex) { RegexEntry entry = new RegexEntry(); entry.IsRecursive = isRecursive; entry.BaseDirectory = searchDirectory; entry.Pattern = regexPattern; if (regexPattern.EndsWith(@"**/*") || regexPattern.EndsWith(@"**\*")) logger.Warn( "**/* pattern may not produce desired results" ); regexPatterns.Add(entry); } else { string exactName = Path.Combine(searchDirectory, regexPattern); if (!nonRegexFiles.Contains(exactName)) { nonRegexFiles.Add(exactName); } } if (!addSearchDirectories) { continue; } int index = _searchDirectories.IndexOf(searchDirectory); // if the directory was found before, but wasn't recursive // and is now, mark it as so if (index > -1) { if (!(bool)_searchDirIsRecursive[index] && isRecursive) { _searchDirIsRecursive[index] = isRecursive; } } else { // if the directory has not been added, add it _searchDirectories.Add(searchDirectory); _searchDirIsRecursive.Add(isRecursive); } } } /// /// Given a NAnt search pattern returns a search directory and an regex /// search pattern. /// /// Whether this pattern is an include or exclude pattern /// NAnt searh pattern (relative to the Basedirectory OR absolute, relative paths refering to parent directories ( ../ ) also supported) /// Out. Absolute canonical path to the directory to be searched /// Out. Whether the pattern is potentially recursive or not /// Out. Whether this is a regex pattern or not /// Out. Regex search pattern (absolute canonical path) private void ParseSearchDirectoryAndPattern(bool isInclude, string originalNAntPattern, out string searchDirectory, out bool recursive, out bool isRegex, out string regexPattern) { string s = originalNAntPattern; s = s.Replace('\\', Path.DirectorySeparatorChar); s = s.Replace('/', Path.DirectorySeparatorChar); // Get indices of pieces used for recursive check only int indexOfFirstDirectoryWildcard = s.IndexOf("**"); int indexOfLastOriginalDirectorySeparator = s.LastIndexOf(Path.DirectorySeparatorChar); // search for the first wildcard character (if any) and exclude the rest of the string beginnning from the character char[] wildcards = {'?', '*'}; int indexOfFirstWildcard = s.IndexOfAny(wildcards); if (indexOfFirstWildcard != -1) { // if found any wildcard characters s = s.Substring(0, indexOfFirstWildcard); } // find the last DirectorySeparatorChar (if any) and exclude the rest of the string int indexOfLastDirectorySeparator = s.LastIndexOf(Path.DirectorySeparatorChar); // The pattern is potentially recursive if and only if more than one base directory could be matched. // ie: // ** // **/*.txt // foo*/xxx // x/y/z?/www // This condition is true if and only if: // - The first wildcard is before the last directory separator, or // - The pattern contains a directory wildcard ("**") recursive = (indexOfFirstWildcard != -1 && (indexOfFirstWildcard < indexOfLastOriginalDirectorySeparator )) || indexOfFirstDirectoryWildcard != -1; // substring preceding the separator represents our search directory // and the part following it represents nant search pattern relative // to it if (indexOfLastDirectorySeparator != -1) { s = originalNAntPattern.Substring(0, indexOfLastDirectorySeparator); if (s.Length == 2 && s[1] == Path.VolumeSeparatorChar) { s += Path.DirectorySeparatorChar; } } else { s = string.Empty; } // we only prepend BaseDirectory when s represents a relative path. if (Path.IsPathRooted(s)) { searchDirectory = new DirectoryInfo(s).FullName; } else { // we also (correctly) get to this branch of code when s.Length == 0 searchDirectory = new DirectoryInfo(Path.Combine( BaseDirectory.FullName, s)).FullName; } // remove trailing directory separator character, fixes bug #1195736 // // do not remove trailing directory separator if search directory is // root of drive (eg. d:\) if (searchDirectory.EndsWith(Path.DirectorySeparatorChar.ToString()) && (searchDirectory.Length != 3 || searchDirectory[1] != Path.VolumeSeparatorChar)) { searchDirectory = searchDirectory.Substring(0, searchDirectory.Length - 1); } // check if the pattern matches shorthand for full recursive // match // for example: mypackage/ is shorthand for mypackage/** bool shorthand = indexOfLastOriginalDirectorySeparator != -1 && indexOfLastOriginalDirectorySeparator == (originalNAntPattern.Length - 1); // if it's not a wildcard, just return if (indexOfFirstWildcard == -1 && !shorthand) { regexPattern = CleanPath(BaseDirectory.FullName, originalNAntPattern); isRegex = false; #if DEBUG_REGEXES Console.WriteLine( "Convert name: {0} -> {1}", originalNAntPattern, regexPattern ); #endif return; } string modifiedNAntPattern = originalNAntPattern.Substring(indexOfLastDirectorySeparator + 1); if (shorthand) { modifiedNAntPattern += "**"; recursive = true; } //if the fs in case-insensitive, make all the regex directories lowercase. regexPattern = ToRegexPattern(modifiedNAntPattern); #if DEBUG_REGEXES Console.WriteLine( "Convert pattern: {0} -> [{1}]{2}", originalNAntPattern, searchDirectory, regexPattern ); #endif isRegex = true; } /// /// Searches a directory recursively for files and directories matching /// the search criteria. /// /// Directory in which to search (absolute canonical path) /// Whether to scan recursively or not private void ScanDirectory(string path, bool recursive) { // scan each directory only once if (_scannedDirectories.Contains(path)) { return; } // add directory to list of scanned directories _scannedDirectories.Add(path); // if the path doesn't exist, return. if (!Directory.Exists(path)) { return; } // get info for the current directory DirectoryInfo currentDirectoryInfo = new DirectoryInfo(path); CompareOptions compareOptions = CompareOptions.None; CompareInfo compare = CultureInfo.InvariantCulture.CompareInfo; if (!CaseSensitive) compareOptions |= CompareOptions.IgnoreCase; ArrayList includedPatterns = new ArrayList(); ArrayList excludedPatterns = new ArrayList(); // Only include the valid patterns for this path foreach (RegexEntry entry in _includePatterns) { string baseDirectory = entry.BaseDirectory; // check if the directory being searched is equal to the // base directory of the RegexEntry if (compare.Compare(path, baseDirectory, compareOptions) == 0) { includedPatterns.Add(entry); } else { // check if the directory being searched is subdirectory of // base directory of RegexEntry if (!entry.IsRecursive) { continue; } // make sure basedirectory ends with directory separator if (!baseDirectory.EndsWith(Path.DirectorySeparatorChar.ToString())) { baseDirectory += Path.DirectorySeparatorChar; } // check if path is subdirectory of base directory if (compare.IsPrefix(path, baseDirectory, compareOptions)) { includedPatterns.Add(entry); } } } foreach (RegexEntry entry in _excludePatterns) { string baseDirectory = entry.BaseDirectory; if (entry.BaseDirectory.Length == 0 || compare.Compare(path, baseDirectory, compareOptions) == 0) { excludedPatterns.Add(entry); } else { // check if the directory being searched is subdirectory of // basedirectory of RegexEntry if (!entry.IsRecursive) { continue; } // make sure basedirectory ends with directory separator if (!baseDirectory.EndsWith(Path.DirectorySeparatorChar.ToString())) { baseDirectory += Path.DirectorySeparatorChar; } // check if path is subdirectory of base directory if (compare.IsPrefix(path, baseDirectory, compareOptions)) { excludedPatterns.Add(entry); } } } foreach (DirectoryInfo directoryInfo in currentDirectoryInfo.GetDirectories()) { if (recursive) { // scan subfolders if we are running recursively ScanDirectory(directoryInfo.FullName, true); } else { // otherwise just test to see if the subdirectories are included if (IsPathIncluded(directoryInfo.FullName, includedPatterns, excludedPatterns)) { _directoryNames.Add(directoryInfo.FullName); } } } // scan files foreach (FileInfo fileInfo in currentDirectoryInfo.GetFiles()) { string filename = Path.Combine(path, fileInfo.Name); if (IsPathIncluded(filename, includedPatterns, excludedPatterns)) { _fileNames.Add(Path.Combine(path, fileInfo.Name)); } } // check current path last so that delete task will correctly // delete empty directories. This may *seem* like a special case // but it is more like formalizing something in a way that makes // writing the delete task easier :) if (IsPathIncluded(path, includedPatterns, excludedPatterns)) { _directoryNames.Add(path); } } private bool TestRegex(string path, RegexEntry entry) { Hashtable regexCache = CaseSensitive ? cachedCaseSensitiveRegexes : cachedCaseInsensitiveRegexes; Regex r = (Regex)regexCache[entry.Pattern]; if (r == null) { RegexOptions regexOptions = RegexOptions.Compiled; if (!CaseSensitive) regexOptions |= RegexOptions.IgnoreCase; regexCache[entry.Pattern] = r = new Regex(entry.Pattern, regexOptions); } // Check to see if the empty string matches the pattern if (path.Length == entry.BaseDirectory.Length) { #if DEBUG_REGEXES Console.WriteLine("{0} (empty string) [basedir={1}]", entry.Pattern, entry.BaseDirectory); #endif return r.IsMatch(String.Empty); } bool endsWithSlash = entry.BaseDirectory.EndsWith(Path.DirectorySeparatorChar.ToString()); #if DEBUG_REGEXES Console.WriteLine("{0} ({1}) [basedir={2}]", entry.Pattern, path.Substring(entry.BaseDirectory.Length + ((endsWithSlash) ? 0 : 1)), entry.BaseDirectory); #endif if (endsWithSlash) { return r.IsMatch(path.Substring(entry.BaseDirectory.Length)); } else { return r.IsMatch(path.Substring(entry.BaseDirectory.Length + 1)); } } private bool IsPathIncluded(string path, ArrayList includedPatterns, ArrayList excludedPatterns) { bool included = false; CompareOptions compareOptions = CompareOptions.None; CompareInfo compare = CultureInfo.InvariantCulture.CompareInfo; if (!CaseSensitive) compareOptions |= CompareOptions.IgnoreCase; #if DEBUG_REGEXES Console.WriteLine("Test: {0}", path); #endif // check path against include names foreach (string name in _includeNames) { #if DEBUG_REGEXES Console.WriteLine("Test include name: '{0}'", name); #endif if (compare.Compare(name, path, compareOptions) == 0) { included = true; #if DEBUG_REGEXES Console.WriteLine("Included by name: {0}", name); #endif break; } } // check path against include regexes if (!included) { foreach (RegexEntry entry in includedPatterns) { #if DEBUG_REGEXES Console.Write("Test include pattern: "); #endif if (TestRegex(path, entry)) { included = true; #if DEBUG_REGEXES Console.WriteLine("Included by pattern: {0}", entry.Pattern); #endif break; } } } // check path against exclude names if (included) { foreach (string name in _excludeNames) { #if DEBUG_REGEXES Console.WriteLine("Test exclude name: '{0}'", name); #endif if (compare.Compare(name, path, compareOptions) == 0) { included = false; #if DEBUG_REGEXES Console.WriteLine("Excluded by name: {0}", name); #endif break; } } } // check path against exclude regexes if (included) { foreach (RegexEntry entry in excludedPatterns) { #if DEBUG_REGEXES Console.Write("Test exclude pattern: "); #endif if (TestRegex(path, entry)) { included = false; #if DEBUG_REGEXES Console.WriteLine("Excluded by pattern: {0}", entry.Pattern); #endif break; } } } #if DEBUG_REGEXES Console.WriteLine("Result: {0}", included); #endif // If the current file was not included and the isEverythingIncluded // indicator is true; set the isEverythingIncluded indicator to false. // Note: File.Exists(path) is used to make sure the current path is // a file and not a directory. if (!included && _isEverythingIncluded && File.Exists(path)) { _isEverythingIncluded = false; } return included; } #endregion Private Instance Methods #region Private Static Methods private static StringBuilder CleanPath(string nantPath) { StringBuilder pathBuilder = new StringBuilder(nantPath); // NAnt patterns can use either / \ as a directory separator. // We must replace both of these characters with Path.DirectorySeparatorChar pathBuilder.Replace('/', Path.DirectorySeparatorChar); pathBuilder.Replace('\\', Path.DirectorySeparatorChar); return pathBuilder; } private static string CleanPath(string baseDirectory, string nantPath) { return new DirectoryInfo(Path.Combine(baseDirectory, CleanPath(nantPath).ToString())).FullName; } /// /// Converts search pattern to a regular expression pattern. /// /// Search pattern relative to the search directory. /// Regular expresssion private static string ToRegexPattern(string nantPattern) { StringBuilder pattern = CleanPath(nantPattern); // The '\' character is a special character in regular expressions // and must be escaped before doing anything else. pattern.Replace(@"\", @"\\"); // Escape the rest of the regular expression special characters. // NOTE: Characters other than . $ ^ { [ ( | ) * + ? \ match themselves. // TODO: Decide if ] and } are missing from this list, the above // list of characters was taking from the .NET SDK docs. pattern.Replace(".", @"\."); pattern.Replace("$", @"\$"); pattern.Replace("^", @"\^"); pattern.Replace("{", @"\{"); pattern.Replace("[", @"\["); pattern.Replace("(", @"\("); pattern.Replace(")", @"\)"); pattern.Replace("+", @"\+"); // Special case directory seperator string under Windows. string seperator = Path.DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture); if (seperator == @"\") seperator = @"\\"; // Convert NAnt pattern characters to regular expression patterns. // Start with ? - it's used below pattern.Replace("?", "[^" + seperator + "]?"); // SPECIAL CASE: any *'s directory between slashes or at the end of the // path are replaced with a 1..n pattern instead of 0..n: (?<=\\)\*(?=($|\\)) // This ensures that C:\*foo* matches C:\foo and C:\* won't match C:. pattern = new StringBuilder(Regex.Replace(pattern.ToString(), "(?<=" + seperator + ")\\*(?=($|" + seperator + "))", "[^" + seperator + "]+")); // SPECIAL CASE: to match subdirectory OR current directory, If // we do this then we can write something like 'src/**/*.cs' // to match all the files ending in .cs in the src directory OR // subdirectories of src. pattern.Replace(seperator + "**" + seperator, seperator + "(.|?" + seperator + ")?" ); pattern.Replace("**" + seperator, ".|(?<=^|" + seperator + ")" ); pattern.Replace(seperator + "**", "(?=$|" + seperator + ").|" ); // .| is a place holder for .* to prevent it from being replaced in next line pattern.Replace("**", ".|"); pattern.Replace("*", "[^" + seperator + "]*"); pattern.Replace(".|", ".*"); // replace place holder string // Help speed up the search if (pattern.Length > 0) { pattern.Insert(0, '^'); // start of line pattern.Append('$'); // end of line } string patternText = pattern.ToString(); if (patternText.StartsWith("^.*")) patternText = patternText.Substring(3); if (patternText.EndsWith(".*$")) patternText = patternText.Substring(0, pattern.Length - 3); return patternText; } #endregion Private Static Methods [Serializable()] private class RegexEntry { public bool IsRecursive; public string BaseDirectory; public string Pattern; } } [Serializable()] internal class StringCollectionWithGoodToString : StringCollection, ICloneable { #region Implementation of ICloneable /// /// Creates a shallow copy of the . /// /// /// A shallow copy of the . /// public virtual object Clone() { string[] strings = new string[Count]; CopyTo(strings, 0); StringCollectionWithGoodToString clone = new StringCollectionWithGoodToString(); clone.AddRange(strings); return clone; } #endregion Implementation of ICloneable #region Override implemenation of Object /// /// Creates a string representing a list of the strings in the collection. /// /// /// A string that represents the contents. /// public override string ToString() { StringBuilder sb = new StringBuilder(base.ToString()); sb.Append(":" + Environment.NewLine); foreach (string s in this) { sb.Append(s); sb.Append(Environment.NewLine); } return sb.ToString(); } #endregion Override implemenation of Object } [Serializable()] internal class DirScannerStringCollection : StringCollectionWithGoodToString { #region Public Instance Constructors /// /// Initialize a new instance of the /// class specifying whether or not string comparison should be /// case-sensitive. /// /// Specifies whether or not string comparison should be case-sensitive. public DirScannerStringCollection (bool caseSensitive) { _caseSensitive = caseSensitive; } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets a value indicating whether string comparison is case-sensitive. /// /// /// A value indicating whether string comparison is case-sensitive. /// public bool CaseSensitive { get { return _caseSensitive; } } #endregion Public Instance Properties #region Override implementation of ICloneable /// /// Creates a shallow copy of the . /// /// /// A shallow copy of the . /// public override object Clone() { string[] strings = new string[Count]; CopyTo(strings, 0); DirScannerStringCollection clone = new DirScannerStringCollection(CaseSensitive); clone.AddRange(strings); return clone; } #endregion Override implementation of ICloneable #region Override implementation of StringCollection /// /// Determines whether the specified string is in the /// . /// /// The string to locate in the . The value can be . /// /// if value is found in the ; otherwise, . /// /// /// String comparisons within the /// are only case-sensitive if is /// /// public new virtual bool Contains(string value) { return (IndexOf(value) > -1); } /// /// Searches for the specified string and returns the zero-based index /// of the first occurrence within the . /// /// The string to locate. The value can be . /// /// The zero-based index of the first occurrence of /// in the , if found; otherwise, -1. /// /// /// String comparisons within the /// are only case-sensitive if is /// . /// public new virtual int IndexOf(string value) { if (value == null || CaseSensitive) { return base.IndexOf(value); } else { foreach (string s in this) { if (string.Compare(s, value, true, CultureInfo.InvariantCulture) == 0) { return base.IndexOf(s); } } return -1; } } #endregion Override implementation of StringCollection #region Private Instance Fields private readonly bool _caseSensitive; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.Core/FrameworkInfo.cs0000644000175000017500000010057211757302273020453 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2002-2003 Scott Hernandez // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian MacLean (imaclean@gmail.com) using System; using System.Collections; using System.Globalization; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Xml; using NAnt.Core.Configuration; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.Core { /// /// Encalsulates information about installed frameworks incuding version /// information and directory locations for finding tools. /// [Serializable()] public class FrameworkInfo : ISerializable { #region Private Instance Fields private readonly XmlNode _frameworkNode; private readonly XmlNamespaceManager _nsMgr; private readonly string _name; private readonly string _family; private readonly string _description; private Version _version; private Version _clrVersion; private ClrType _clrType; private VendorType _vendor; private DirectoryInfo _frameworkDirectory; private DirectoryInfo _sdkDirectory; private DirectoryInfo _frameworkAssemblyDirectory; private Runtime _runtime; private Project _project; private FileSet _taskAssemblies; private FileSet[] _referenceAssemblies; private string[] _toolPaths; private InitStatus _status = InitStatus.Uninitialized; #endregion Private Instance Fields #region Internal Instance Constructors internal FrameworkInfo(XmlNode frameworkNode, XmlNamespaceManager nsMgr) { if (frameworkNode == null) { throw new ArgumentNullException("frameworkNode"); } if (nsMgr == null) { throw new ArgumentNullException("nsMgr"); } _frameworkNode = frameworkNode; _nsMgr = nsMgr; _name = GetXmlAttributeValue(frameworkNode, "name"); if (_name == null) { throw new ArgumentException("The \"name\" attribute does not " + "exist, or has no value."); } _family = GetXmlAttributeValue(frameworkNode, "family"); if (_family == null) { throw new ArgumentException("The \"family\" attribute does " + "not exist, or has no value."); } _description = GetXmlAttributeValue(_frameworkNode, "description"); if (_description == null) { throw new ArgumentException("The \"description\" attribute " + "does not exist, or has no value."); } string vendor = GetXmlAttributeValue(_frameworkNode, "vendor"); if (vendor == null) { throw new ArgumentException("The \"vendor\" attribute does " + "not exist, or has no value."); } try { _vendor = (VendorType) Enum.Parse(typeof (VendorType), vendor, true); } catch (Exception ex) { throw new ArgumentException("The value of the \"vendor\" " + "attribute is not valid.", ex); } } #endregion Internal Instance Constructors #region Protected Instance Constructors protected FrameworkInfo(SerializationInfo info, StreamingContext context) { _name = info.GetString("Name"); _family = info.GetString("Family"); _description = info.GetString("Description"); _status = (InitStatus) info.GetValue("Status", typeof(InitStatus)); _clrType = (ClrType) info.GetValue("ClrType", typeof(ClrType)); _version = (Version) info.GetValue("Version", typeof(Version)); _clrVersion = (Version) info.GetValue("ClrVersion", typeof(Version)); _vendor = (VendorType) info.GetValue("Vendor", typeof(VendorType)); if (_status != InitStatus.Valid) { return; } _frameworkDirectory = (DirectoryInfo) info.GetValue("FrameworkDirectory", typeof(DirectoryInfo)); _sdkDirectory = (DirectoryInfo) info.GetValue("SdkDirectory", typeof(DirectoryInfo)); _frameworkAssemblyDirectory = (DirectoryInfo) info.GetValue("FrameworkAssemblyDirectory", typeof(DirectoryInfo)); _runtime = (Runtime) info.GetValue("Runtime", typeof(Runtime)); _project = (Project) info.GetValue("Project", typeof(Project)); _taskAssemblies = (FileSet) info.GetValue("TaskAssemblies", typeof(FileSet)); _referenceAssemblies = (FileSet[]) info.GetValue("ReferenceAssemblies", typeof(FileSet[])); _toolPaths = (string[]) info.GetValue("ToolPaths", typeof(string[])); } #endregion Protected Instance Constructors #region Private Instance Constructors void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("Name", Name); info.AddValue("Family", Family); info.AddValue("Description", Description); info.AddValue("ClrType", ClrType); info.AddValue("Version", Version); info.AddValue("ClrVersion", ClrVersion); info.AddValue("Status", _status); info.AddValue("Vendor", Vendor); if (IsValid) { info.AddValue("FrameworkDirectory", FrameworkDirectory); info.AddValue("SdkDirectory", SdkDirectory); info.AddValue("FrameworkAssemblyDirectory", FrameworkAssemblyDirectory); info.AddValue("Runtime", Runtime); info.AddValue("Project", Project); info.AddValue("TaskAssemblies", TaskAssemblies); info.AddValue("ReferenceAssemblies", ReferenceAssemblies); info.AddValue("ToolPaths", ToolPaths); } } #endregion Private Instance Constructors #region Public Instance Properties /// /// Gets the name of the framework. /// /// /// The name of the framework. /// public string Name { get { return _name; } } /// /// Gets the family of the framework. /// /// /// The family of the framework. /// public string Family { get { return _family; } } /// /// Gets the description of the framework. /// /// /// The description of the framework. /// public string Description { get { return _description; } } /// /// Gets the vendor of the framework. /// /// /// The vendor of the framework. /// internal VendorType Vendor { get { return _vendor; } } /// /// Gets the version of the framework. /// /// /// The version of the framework. /// /// The framework is not valid. /// /// When is not configured, the framework is not /// considered valid. /// public Version Version { get { if (_version == null) { if (_frameworkNode == null) { throw new ArgumentException("The current framework " + "is not valid."); } string version = GetXmlAttributeValue(_frameworkNode, "version"); if (version != null) { _version = new Version(version); } } return _version; } } /// /// Gets the Common Language Runtime version of the framework. /// /// /// The Common Language Runtime version of the framework. /// /// The framework is not valid. /// /// When is , the /// framework is not considered valid. /// public Version ClrVersion { get { if (_clrVersion == null) { if (_frameworkNode == null) { throw new ArgumentException("The current framework " + "is not valid."); } string clrVersion = GetXmlAttributeValue(_frameworkNode, "clrversion"); if (clrVersion != null) { _clrVersion = new Version(clrVersion); } } return _clrVersion; } } /// /// Gets the CLR type of the framework. /// /// /// The CLR type of the framework. /// /// The framework is not valid. public ClrType ClrType { get { if (_clrType == 0) { if (_frameworkNode == null) { throw new ArgumentException("The current framework " + "is not valid."); } string clrType = GetXmlAttributeValue(_frameworkNode, "clrtype"); if (clrType != null) { try { _clrType = (ClrType) Enum.Parse(typeof (ClrType), clrType, true); } catch (Exception ex) { throw new ArgumentException("The value of the \"clrtype\" " + "attribute is not valid.", ex); } } } return _clrType; } } /// /// Gets the Visual Studio version that corresponds with this /// framework. /// /// /// The Visual Studio version that corresponds with this framework. /// /// The framework is not valid. /// There is no version of Visual Studio that corresponds with this framework. public Version VisualStudioVersion { get { if (ClrVersion == null) { throw new ArgumentException("The current framework " + "is not valid."); } switch (ClrVersion.ToString(2)) { case "1.0": return new Version(7, 0); case "1.1": return new Version(7, 1); case "2.0": return new Version(8, 0); case "4.0": return new Version(10, 0); default: throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1055"), Description), Location.UnknownLocation); } } } /// /// Gets the base directory of the framework tools for the framework. /// /// /// The base directory of the framework tools for the framework. /// /// The framework is not valid. public DirectoryInfo FrameworkDirectory { get { // ensure we're not dealing with an invalid framework AssertNotInvalid(); if (_frameworkDirectory == null) { string frameworkDir = Project.ExpandProperties( GetXmlAttributeValue(_frameworkNode, "frameworkdirectory"), Location.UnknownLocation); if (frameworkDir != null) { // ensure the framework directory exists if (Directory.Exists(frameworkDir)) { _frameworkDirectory = new DirectoryInfo(frameworkDir); } else { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Framework directory '{0}' does not exist.", frameworkDir)); } } } return _frameworkDirectory; } } /// /// Gets the runtime information for this framework. /// /// /// The runtime information for the framework or /// if no runtime information is configured for the framework. /// /// The framework is not valid. internal Runtime Runtime { get { Init(); return _runtime; } } /// /// Gets the directory where the system assemblies for the framework /// are located. /// /// /// The directory where the system assemblies for the framework are /// located. /// /// The framework is not valid. public DirectoryInfo FrameworkAssemblyDirectory { get { // ensure we're not dealing with an invalid framework AssertNotInvalid(); if (_frameworkAssemblyDirectory == null) { string frameworkAssemblyDir = Project.ExpandProperties( GetXmlAttributeValue(_frameworkNode, "frameworkassemblydirectory"), Location.UnknownLocation); if (frameworkAssemblyDir != null) { // ensure the framework assembly directory exists if (Directory.Exists(frameworkAssemblyDir)) { // only consider framework assembly directory valid if an assembly // named "System.dll" exists in that directory if (!File.Exists(Path.Combine(frameworkAssemblyDir, "System.dll"))) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1054"), frameworkAssemblyDir)); } _frameworkAssemblyDirectory = new DirectoryInfo(frameworkAssemblyDir); } else { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Framework assembly directory '{0}' does not exist.", frameworkAssemblyDir)); } } } return _frameworkAssemblyDirectory; } } /// /// Gets the directory containing the SDK tools for the framework. /// /// /// The directory containing the SDK tools for the framework or a null /// reference if the configured sdk directory does not exist, or is not /// valid. /// /// The framework is not valid. public DirectoryInfo SdkDirectory { get { Init(); // ensure we're not dealing with an invalid framework AssertNotInvalid(); return _sdkDirectory; } } /// /// Gets the used to initialize this framework. /// /// /// The used to initialize this framework. /// /// The framework is not valid. public Project Project { get { Init(); // ensure we're not dealing with an invalid framework AssertNotInvalid(); return _project; } } /// /// Gets the set of assemblies and directories that should scanned for /// NAnt tasks, types or functions. /// /// /// The set of assemblies and directories that should be scanned for /// NAnt tasks, types or functions. /// /// The framework is not valid. public FileSet TaskAssemblies { get { // ensure we're not dealing with an invalid framework AssertNotInvalid(); if (_taskAssemblies == null) { // process framework task assemblies _taskAssemblies = new FileSet(); _taskAssemblies.Project = Project; _taskAssemblies.NamespaceManager = NamespaceManager; _taskAssemblies.Parent = Project; // avoid warnings by setting the parent of the fileset _taskAssemblies.ID = "internal-task-assemblies"; // avoid warnings by assigning an id XmlNode taskAssembliesNode = _frameworkNode.SelectSingleNode( "nant:task-assemblies", NamespaceManager); if (taskAssembliesNode != null) { _taskAssemblies.Initialize(taskAssembliesNode, Project.Properties, this); } } return _taskAssemblies; } } /// /// Returns a value indicating whether the current framework is valid. /// /// /// if the framework is installed and correctly /// configured; otherwise, . /// public bool IsValid { get { try { Validate (); return true; } catch { return false; } } } #endregion Public Instance Properties #region Internal Instance Properties /// /// Gets the reference assemblies for the current framework. /// /// /// The reference assemblies for the current framework. /// /// The framework is not valid. internal FileSet[] ReferenceAssemblies { get { // ensure we're not dealing with an invalid framework AssertNotInvalid(); if (_referenceAssemblies == null) { // reference assemblies XmlNodeList referenceAssemblies = _frameworkNode.SelectNodes( "nant:reference-assemblies", NamespaceManager); _referenceAssemblies = new FileSet [referenceAssemblies.Count]; for (int i = 0; i < referenceAssemblies.Count; i++) { XmlNode node = referenceAssemblies [i]; FileSet fileset = new FileSet(); fileset.Project = Project; fileset.NamespaceManager = NamespaceManager; fileset.Parent = Project; fileset.ID = "reference-assemblies-" + i.ToString (CultureInfo.InvariantCulture); fileset.Initialize(node, Project.Properties, this); _referenceAssemblies [i] = fileset; } } return _referenceAssemblies; } } /// /// Gets the tool paths for the current framework. /// /// /// The tool paths for the current framework. /// /// The framework is not valid. internal string[] ToolPaths { get { // ensure we're not dealing with an invalid framework AssertNotInvalid(); if (_toolPaths == null) { XmlNode node = _frameworkNode.SelectSingleNode( "nant:tool-paths", NamespaceManager); if (node != null) { DirList dirs = new DirList(); dirs.Project = Project; dirs.NamespaceManager = NamespaceManager; dirs.Parent = Project; dirs.Initialize(node, Project.Properties, this); _toolPaths = dirs.GetDirectories(); } else { _toolPaths = new string[0]; } } return _toolPaths; } } internal string RuntimeEngine { get { if (Runtime == null) { return string.Empty; } ManagedExecutionMode mode = Runtime.Modes.GetExecutionMode (ManagedExecution.Auto); if (mode != null) { RuntimeEngine engine = mode.Engine; if (engine.Program != null) { return engine.Program.FullName; } } return string.Empty; } } #endregion Internal Instance Properties #region Private Instance Properties /// /// Gets the . /// /// /// The . /// /// /// The defines the current namespace /// scope and provides methods for looking up namespace information. /// private XmlNamespaceManager NamespaceManager { get { return _nsMgr; } } #endregion Private Instance Properties #region Internal Static Properties internal static IComparer NameComparer { get { return new FrameworkNameComparer (); } } #endregion Internal Static Properties #region Public Instance Methods /// /// Resolves the specified assembly to a full path by matching it /// against the reference assemblies. /// /// The file name of the assembly to resolve (without path information). /// /// An absolute path to the assembly, or if the /// assembly could not be found or no reference assemblies are configured /// for the current framework. /// /// /// Whether the file name is matched case-sensitively depends on the /// operating system. /// public string ResolveAssembly (string fileName) { string resolvedAssembly = null; foreach (FileSet fileset in ReferenceAssemblies) { resolvedAssembly = fileset.Find (fileName); if (resolvedAssembly != null) { break; } } return resolvedAssembly; } #endregion Public Instance Methods #region Internal Instance Methods internal void Validate() { if (_status == InitStatus.Valid) { return; } Init(); // reset status to avoid status check in properties from getting // triggered _status = InitStatus.Initialized; try { // verify if framework directory is configured, and indirectly // check if it exists if (FrameworkDirectory == null) { throw new ArgumentException("The \"frameworkdirectory\" " + "attribute does not exist, or has no value."); } // verify if framework assembly directory is configured, and // indirectly check if it exists if (FrameworkAssemblyDirectory == null) { throw new ArgumentException("The \"frameworkassemblydirectory\" " + "attribute does not exist, or has no value."); } // verify if version is configured if (Version == null) { throw new ArgumentException("The \"version\" attribute " + "does not exist, or has no value."); } // verify if clrversion is configured if (ClrVersion == null) { throw new ArgumentException("The \"clrversion\" attribute " + "does not exist, or has no value."); } // mark framework valid _status = InitStatus.Valid; } catch (Exception ex) { _status = InitStatus.Invalid; throw new BuildException(string.Format(CultureInfo.InvariantCulture, "{0} ({1}) is not installed, or not correctly configured.", Description, Name), Location.UnknownLocation, ex); } } /// /// Searches the list of tool paths of the current framework for the /// given file, and returns the absolute path if found. /// /// The file name of the tool to search for. /// /// The absolute path to if found in one of the /// configured tool paths; otherwise, . /// /// is . /// /// /// The configured tool paths are scanned in the order in which they /// are defined in the framework configuration. /// /// /// The file name of the tool to search should include the extension. /// /// internal string GetToolPath (string tool) { if (tool == null) throw new ArgumentNullException ("tool"); return FileUtils.ResolveFile(ToolPaths, tool, false); } #endregion Internal Instance Methods #region Private Instance Methods private void Init() { if (_status != InitStatus.Uninitialized) { return; } // the framework node is not available when working with a // deserialized FrameworkInfo, and as such it's no use // attempting to initialize it when the status is invalid // since it will not get us the actual reason anyway AssertNotInvalid(); try { PerformInit(); } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Failed to initialize the '{0}' ({1}) target framework.", Description, Name), Location.UnknownLocation, ex); } } private void PerformInit() { // get framework-specific project node XmlNode projectNode = _frameworkNode.SelectSingleNode("nant:project", NamespaceManager); if (projectNode == null) throw new ArgumentException("No node is defined."); // create XmlDocument from project node XmlDocument projectDoc = new XmlDocument(); projectDoc.LoadXml(projectNode.OuterXml); // create and execute project Project frameworkProject = new Project(projectDoc); frameworkProject.BaseDirectory = AppDomain.CurrentDomain.BaseDirectory; frameworkProject.Execute(); XmlNode runtimeNode = _frameworkNode.SelectSingleNode ("runtime", NamespaceManager); if (runtimeNode != null) { _runtime = new Runtime (); _runtime.Parent = _runtime.Project = frameworkProject; _runtime.NamespaceManager = NamespaceManager; _runtime.Initialize(runtimeNode, frameworkProject.Properties, this); } string sdkDir = GetXmlAttributeValue(_frameworkNode, "sdkdirectory"); try { sdkDir = frameworkProject.ExpandProperties(sdkDir, Location.UnknownLocation); } catch (BuildException) { // do nothing with this exception as a framework is still // considered valid if the sdk directory is not available // or not configured correctly } // the sdk directory does not actually have to exist for a // framework to be considered valid if (sdkDir != null && Directory.Exists(sdkDir)) _sdkDirectory = new DirectoryInfo(sdkDir); _project = frameworkProject; _status = InitStatus.Initialized; } private void AssertNotInvalid() { if (_status == InitStatus.Invalid || (_status == InitStatus.Uninitialized && _frameworkNode == null)) { throw new ArgumentException("The current framework " + "is not valid."); } } #endregion Private Instance Methods #region Private Static Methods /// /// Gets the value of the specified attribute from the specified node. /// /// The node of which the attribute value should be retrieved. /// The attribute of which the value should be returned. /// /// The value of the attribute with the specified name or /// if the attribute does not exist or has no value. /// private static string GetXmlAttributeValue(XmlNode xmlNode, string attributeName) { string attributeValue = null; if (xmlNode != null) { XmlAttribute xmlAttribute = (XmlAttribute)xmlNode.Attributes.GetNamedItem(attributeName); if (xmlAttribute != null) { attributeValue = StringUtils.ConvertEmptyToNull(xmlAttribute.Value); } } return attributeValue; } #endregion Private Static Methods private enum InitStatus { Uninitialized, Initialized, Invalid, Valid } private class FrameworkNameComparer : IComparer { public int Compare(object x, object y) { FrameworkInfo fix = x as FrameworkInfo; FrameworkInfo fiy = y as FrameworkInfo; return string.Compare(fix.Name, fiy.Name,false, CultureInfo.InvariantCulture); } } } public enum ClrType { Desktop = 1, Compact = 2, Browser = 3 } public enum VendorType { Microsoft = 1, Mono = 2 } } nant-0.92-rc1/src/NAnt.Core/Types/0000755000175000017500000000000011757310030016440 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.Core/Types/XsltParameterCollection.cs0000644000175000017500000002442711757302273023621 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; namespace NAnt.Core.Types { /// /// Contains a collection of elements. /// [Serializable()] public class XsltParameterCollection : CollectionBase { #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public XsltParameterCollection() { } /// /// Initializes a new instance of the class /// with the specified instance. /// public XsltParameterCollection(XsltParameterCollection value) { AddRange(value); } /// /// Initializes a new instance of the class /// with the specified array of instances. /// public XsltParameterCollection(XsltParameter[] value) { AddRange(value); } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets the element at the specified index. /// /// The zero-based index of the element to get or set. [System.Runtime.CompilerServices.IndexerName("Item")] public XsltParameter this[int index] { get { return (XsltParameter) base.List[index]; } set { base.List[index] = value; } } /// /// Gets the with the specified name. /// /// The name of the to get. [System.Runtime.CompilerServices.IndexerName("Item")] public XsltParameter this[string value] { get { if (value != null) { // Try to locate instance using Value foreach (XsltParameter parameter in base.List) { if (parameter.Name == value) { return parameter; } } } return null; } } #endregion Public Instance Properties #region Public Instance Methods /// /// Adds a to the end of the collection. /// /// The to be added to the end of the collection. /// The position into which the new element was inserted. public int Add(XsltParameter item) { return base.List.Add(item); } /// /// Adds the elements of a array to the end of the collection. /// /// The array of elements to be added to the end of the collection. public void AddRange(XsltParameter[] items) { for (int i = 0; (i < items.Length); i = (i + 1)) { Add(items[i]); } } /// /// Adds the elements of a to the end of the collection. /// /// The to be added to the end of the collection. public void AddRange(XsltParameterCollection items) { for (int i = 0; (i < items.Count); i = (i + 1)) { Add(items[i]); } } /// /// Determines whether a is in the collection. /// /// The to locate in the collection. /// /// if is found in the /// collection; otherwise, . /// public bool Contains(XsltParameter item) { return base.List.Contains(item); } /// /// Determines whether a with the specified /// value is in the collection. /// /// The argument value to locate in the collection. /// /// if a with /// value is found in the collection; otherwise, /// . /// public bool Contains(string value) { return this[value] != null; } /// /// Copies the entire collection to a compatible one-dimensional array, starting at the specified index of the target array. /// /// The one-dimensional array that is the destination of the elements copied from the collection. The array must have zero-based indexing. /// The zero-based index in at which copying begins. public void CopyTo(XsltParameter[] array, int index) { base.List.CopyTo(array, index); } /// /// Retrieves the index of a specified object in the collection. /// /// The object for which the index is returned. /// /// The index of the specified . If the is not currently a member of the collection, it returns -1. /// public int IndexOf(XsltParameter item) { return base.List.IndexOf(item); } /// /// Inserts a into the collection at the specified index. /// /// The zero-based index at which should be inserted. /// The to insert. public void Insert(int index, XsltParameter item) { base.List.Insert(index, item); } /// /// Returns an enumerator that can iterate through the collection. /// /// /// A for the entire collection. /// public new XsltParameterEnumerator GetEnumerator() { return new XsltParameterEnumerator(this); } /// /// Removes a member from the collection. /// /// The to remove from the collection. public void Remove(XsltParameter item) { base.List.Remove(item); } #endregion Public Instance Methods } /// /// Enumerates the elements of a . /// public class XsltParameterEnumerator : IEnumerator { #region Internal Instance Constructors /// /// Initializes a new instance of the class /// with the specified . /// /// The collection that should be enumerated. internal XsltParameterEnumerator(XsltParameterCollection arguments) { IEnumerable temp = (IEnumerable) (arguments); _baseEnumerator = temp.GetEnumerator(); } #endregion Internal Instance Constructors #region Implementation of IEnumerator /// /// Gets the current element in the collection. /// /// /// The current element in the collection. /// public XsltParameter Current { get { return (XsltParameter) _baseEnumerator.Current; } } object IEnumerator.Current { get { return _baseEnumerator.Current; } } /// /// Advances the enumerator to the next element of the collection. /// /// /// if the enumerator was successfully advanced /// to the next element; if the enumerator has /// passed the end of the collection. /// public bool MoveNext() { return _baseEnumerator.MoveNext(); } bool IEnumerator.MoveNext() { return _baseEnumerator.MoveNext(); } /// /// Sets the enumerator to its initial position, which is before the /// first element in the collection. /// public void Reset() { _baseEnumerator.Reset(); } void IEnumerator.Reset() { _baseEnumerator.Reset(); } #endregion Implementation of IEnumerator #region Private Instance Fields private IEnumerator _baseEnumerator; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.Core/Types/Option.cs0000644000175000017500000000620511757302273020254 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Tomas Restrepo (tomasr@mvps.org) // Gert Driesen (drieseng@users.sourceforge.net) using NAnt.Core.Attributes; namespace NAnt.Core.Types { /// /// Represents an option. /// [ElementName("option")] public class Option : Element { #region Private Instance Fields private string _name; private string _value; private bool _ifDefined = true; private bool _unlessDefined; #endregion Private Instance Fields /// /// name, value constructor /// /// /// public Option(string name, string value) { _name = name; _value = value; } /// /// Default constructor /// public Option() {} #region Public Instance Properties /// /// Name of the option. /// [TaskAttribute("name", Required=true)] [StringValidator(AllowEmpty=false)] public string OptionName { get { return _name; } set { _name = value; } } /// /// Value of the option. The default is . /// [TaskAttribute("value")] public string Value { get { return _value; } set { _value = value; } } /// /// Indicates if the option should be passed to the task. /// If then the option will be passed; /// otherwise, skipped. The default is . /// [TaskAttribute("if")] [BooleanValidator()] public bool IfDefined { get { return _ifDefined; } set { _ifDefined = value; } } /// /// Indicates if the option should not be passed to the task. /// If then the option will be passed; /// otherwise, skipped. The default is . /// [TaskAttribute("unless")] [BooleanValidator()] public bool UnlessDefined { get { return _unlessDefined; } set { _unlessDefined = value; } } #endregion Public Instance Properties } } nant-0.92-rc1/src/NAnt.Core/Types/ManagedExecution.cs0000644000175000017500000000735311757302273022231 0ustar jtaylorjtaylorusing System; using System.ComponentModel; using System.Globalization; namespace NAnt.Core.Types { /// /// Specifies the execution mode for managed applications. /// /// /// /// For backward compatibility, the following string values can also be /// used in build files: /// /// /// /// Value /// Corresponding field /// /// /// "true" /// /// /// /// "false" /// /// /// /// /// Even if set to , the operating system can still /// run the program as a managed application. /// /// On Linux this can be done through binfmt_misc, while on /// Windows installing the .NET Framework redistributable caused managed /// applications to run on the MS CLR by default. /// /// [TypeConverter(typeof(ManagedExecutionConverter))] public enum ManagedExecution { /// /// Do not threat the program as a managed application. /// Default, /// /// Leave it up to the CLR to determine which specific version of /// the CLR will be used to run the application. /// Auto, /// /// Forces an application to run against the currently targeted /// version of a given CLR. /// Strict } /// /// Specialized that also supports /// case-insensitive conversion of "true" to /// and "false" to /// . /// public class ManagedExecutionConverter : EnumConverter { /// /// Initializes a new instance of the /// class. /// public ManagedExecutionConverter() : base(typeof(ManagedExecution)) { } /// /// Converts the given object to the type of this converter, using the /// specified context and culture information. /// /// An that provides a format context. /// A object. If a is passed, the current culture is assumed. /// The to convert. /// /// An that represents the converted value. /// public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value is string) { string stringValue = (string) value; if (string.Compare(stringValue, Boolean.TrueString, true, culture) == 0) { return ManagedExecution.Auto; } if (string.Compare(stringValue, Boolean.FalseString, true, culture) == 0) { return ManagedExecution.Default; } return Enum.Parse(typeof(ManagedExecution), stringValue, true); } // default to EnumConverter behavior return base.ConvertFrom(context, culture, value); } } } nant-0.92-rc1/src/NAnt.Core/Types/Credential.cs0000644000175000017500000001100711757302273021052 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; using System.Net; using NAnt.Core.Attributes; using NAnt.Core.Util; namespace NAnt.Core.Types { /// /// Provides credentials for password-based authentication schemes. /// [ElementName("credential")] public class Credential : DataTypeBase { #region Private Instance Fields private string _domain; private string _password; private string _userName; private bool _ifDefined = true; private bool _unlessDefined; #endregion Private Instance Fields #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public Credential() { } #endregion Public Instance Constructors #region Public Instance Properties /// /// The domain or computer name that verifies the credentials. /// [TaskAttribute("domain", Required=false)] public string Domain { get { return _domain; } set { _domain = StringUtils.ConvertEmptyToNull(value); } } /// /// The password for the user name associated with the credentials. /// [TaskAttribute("password", Required=false)] public string Password { get { return _password; } set { _password = StringUtils.ConvertEmptyToNull(value); } } /// /// The user name associated with the credentials. /// [TaskAttribute("username", Required=false)] public string UserName { get { return _userName; } set { _userName = StringUtils.ConvertEmptyToNull(value); } } /// /// Indicates if the credentials should be used to provide authentication /// information to the external resource. If then /// the credentials will be passed; otherwise, not. The default is /// . /// [TaskAttribute("if")] [BooleanValidator()] public bool IfDefined { get { return _ifDefined; } set { _ifDefined = value; } } /// /// Indicates if the credentials should not be used to provide authentication /// information to the external resource. If then the /// credentials will be passed; otherwise, not. The default is /// . /// [TaskAttribute("unless")] [BooleanValidator()] public bool UnlessDefined { get { return _unlessDefined; } set { _unlessDefined = value; } } #endregion Public Instance Properties #region Public Instance Methods /// /// Returns a instance representing /// the current . /// /// /// A instance representing the current /// , or if the /// credentials should not be used to provide authentication information /// to the external resource. /// public ICredentials GetCredential() { ICredentials credentials = null; if (IfDefined && !UnlessDefined) { credentials = new NetworkCredential(UserName, Password, Domain); } return credentials; } #endregion Public Instance Methods } } nant-0.92-rc1/src/NAnt.Core/Types/FileSet.cs0000644000175000017500000012101311757302273020332 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Ian MacLean (ian@maclean.ms) using System; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Text; using System.Xml; using NAnt.Core.Attributes; using NAnt.Core.Util; namespace NAnt.Core.Types { /// /// Filesets are groups of files. These files can be found in a directory /// tree starting in a base directory and are matched by patterns taken /// from a number of patterns. Filesets can appear inside tasks that support /// this feature or at the project level, i.e., as children of <project>. /// /// ///

Patterns

/// /// As described earlier, patterns are used for the inclusion and exclusion. /// These patterns look very much like the patterns used in DOS and UNIX: /// /// /// /// /// '*' matches zero or more characters /// For example: /// /// *.cs matches .cs, x.cs and FooBar.cs, /// but not FooBar.xml (does not end with .cs). /// /// /// /// /// /// '?' matches one character /// For example: /// /// ?.cs matches x.cs, A.cs, but not /// .cs or xyz.cs (both don't have one character /// before .cs). /// /// /// /// /// /// Combinations of *'s and ?'s are allowed. /// /// /// Matching is done per-directory. This means that first the first directory /// in the pattern is matched against the first directory in the path to match. /// Then the second directory is matched, and so on. For example, when we have /// the pattern /?abc/*/*.cs and the path /xabc/foobar/test.cs, /// the first ?abc is matched with xabc, then * is matched /// with foobar, and finally *.cs is matched with test.cs. /// They all match, so the path matches the pattern. /// /// /// To make things a bit more flexible, we added one extra feature, which makes /// it possible to match multiple directory levels. This can be used to match a /// complete directory tree, or a file anywhere in the directory tree. To do this, /// ** must be used as the name of a directory. When ** is used as /// the name of a directory in the pattern, it matches zero or more directories. /// For example: /test/** matches all files/directories under /test/, /// such as /test/x.cs, or /test/foo/bar/xyz.html, but not /xyz.xml. /// /// /// There is one "shorthand" - if a pattern ends with / or \, then /// ** is appended. For example, mypackage/test/ is interpreted as /// if it were mypackage/test/**. /// ///

Case-Sensitivity

/// /// By default, pattern matching is case-sensitive on Unix and case-insensitive /// on other platforms. The parameter can be used /// to override this. /// ///

Default Excludes

/// /// There are a set of definitions that are excluded by default from all /// tasks that use filesets. They are: /// /// /// **/.svn /// **/.svn/** /// **/_svn /// **/_svn/** /// **/.git /// **/.git/** /// **/.git* (eg. .gitignore) /// **/.hg /// **/.hg/** /// **/.hg* (eg. .hgignore) /// **/SCCS /// **/SCCS/** /// **/vssver.scc /// **/vssver2.scc /// **/_vti_cnf/** /// **/*~ /// **/#*# /// **/.#* /// **/%*% /// **/CVS /// **/CVS/** /// **/.cvsignore /// /// /// If you do not want these default excludes applied, you may disable them /// by setting to . /// ///
/// /// /// /// Pattern /// Match /// /// /// **/CVS/* /// /// /// Matches all files in CVS directories that can be /// located anywhere in the directory tree. /// /// Matches: /// /// /// CVS/Repository /// /// /// org/apache/CVS/Entries /// /// /// org/apache/jakarta/tools/ant/CVS/Entries /// /// /// But not: /// /// /// org/apache/CVS/foo/bar/Entries (foo/bar/ part does not match) /// /// /// /// /// /// org/apache/jakarta/** /// /// /// Matches all files in the org/apache/jakarta directory /// tree. /// /// Matches: /// /// /// org/apache/jakarta/tools/ant/docs/index.html /// /// /// org/apache/jakarta/test.xml /// /// /// But not: /// /// /// org/apache/xyz.java (jakarta/ part is missing) /// /// /// /// /// /// org/apache/**/CVS/* /// /// /// Matches all files in CVS directories that are located /// anywhere in the directory tree under org/apache. /// /// Matches: /// /// /// org/apache/CVS/Entries /// /// /// org/apache/jakarta/tools/ant/CVS/Entries /// /// /// But not: /// /// /// org/apache/CVS/foo/bar/Entries (foo/bar/ part does not match) /// /// /// /// /// /// **/test/** /// /// /// Matches all files that have a test element in their /// path, including test as a filename. /// /// /// /// /// /// [Serializable()] [ElementName("fileset")] public class FileSet : DataTypeBase { #region Private Instance Fields private bool _hasScanned; private bool _defaultExcludes = true; private bool _failOnEmpty; private DirectoryInfo _baseDirectory; private DirectoryScanner _scanner = new DirectoryScanner(); private StringCollection _asis = new StringCollection(); private PathScanner _pathFiles = new PathScanner(); #endregion Private Instance Fields #region Private Static Fields private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion Private Static Fields #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public FileSet() { } /// /// copy constructor /// /// public FileSet(FileSet fs) { fs.CopyTo((FileSet)this); } #endregion Public Instance Constructors #region Public Instance Properties /// /// Indicates whether include and exclude patterns must be treated in a /// case-sensitive way. The default is on Unix; /// otherwise, . /// [TaskAttribute("casesensitive")] public bool CaseSensitive { get { return _scanner.CaseSensitive; } set { _scanner.CaseSensitive = value; } } /// /// When set to , causes the fileset element to /// throw a when no files match the /// includes and excludes criteria. The default is . /// [TaskAttribute("failonempty")] [BooleanValidator()] public bool FailOnEmpty { get { return _failOnEmpty; } set { _failOnEmpty = value; } } /// /// Indicates whether default excludes should be used or not. /// The default is . /// [TaskAttribute("defaultexcludes")] [BooleanValidator()] public bool DefaultExcludes { get { return _defaultExcludes; } set { _defaultExcludes = value; } } /// /// The base of the directory of this fileset. The default is the project /// base directory. /// [TaskAttribute("basedir")] public virtual DirectoryInfo BaseDirectory { get { if (_baseDirectory == null) { if (Parent != null && typeof(FileSet).IsAssignableFrom(Parent.GetType())) { return ((FileSet) Parent).BaseDirectory; } else if (Project != null) { return new DirectoryInfo(Project.BaseDirectory); } } return _baseDirectory; } set { _baseDirectory = value; } } /// /// Gets the collection of include patterns. /// public StringCollection Includes { get { return _scanner.Includes; } } /// /// Gets the collection of exclude patterns. /// public StringCollection Excludes { get { return _scanner.Excludes; } } /// /// Gets the collection of files that will be added to the /// without pattern matching or checking if the /// file exists. /// public StringCollection AsIs { get { return _asis; } } public PathScanner PathFiles { get { return _pathFiles; } } /// /// Gets the collection of file names that match the fileset. /// /// /// A collection that contains the file names that match the /// . /// public StringCollection FileNames { get { if (!_hasScanned) { Scan(); } return _scanner.FileNames; } } /// /// Gets the collection of directory names that match the fileset. /// /// /// A collection that contains the directory names that match the /// . /// public StringCollection DirectoryNames { get { if (!_hasScanned) { Scan(); } return _scanner.DirectoryNames; } } /// /// Gets the collection of directory names that were scanned for files. /// /// /// A collection that contains the directory names that were scanned for /// files. /// public StringCollection ScannedDirectories { get { if (!_hasScanned) { Scan(); } return _scanner.ScannedDirectories; } } /// /// The items to include in the fileset. /// [BuildElementArray("includes")] [Obsolete("Use element instead.", false)] public Include[] SetIncludes { set { IncludeElements = value; } } /// /// The items to include in the fileset. /// [BuildElementArray("include")] public Include[] IncludeElements { set { foreach (Include include in value) { if (include.IfDefined && !include.UnlessDefined) { if (include.AsIs) { logger.Debug(string.Format(CultureInfo.InvariantCulture, "Including AsIs=", include.Pattern)); AsIs.Add(include.Pattern); } else if (include.FromPath) { logger.Debug(string.Format(CultureInfo.InvariantCulture, "Including FromPath=", include.Pattern)); PathFiles.Add(include.Pattern); } else { logger.Debug(string.Format(CultureInfo.InvariantCulture, "Including pattern", include.Pattern)); Includes.Add(include.Pattern); } } } } } /// /// The items to exclude from the fileset. /// [BuildElementArray("excludes")] [Obsolete("Use element instead.", false)] public Exclude[] SetExcludes { set { ExcludeElements = value; } } /// /// The items to exclude from the fileset. /// [BuildElementArray("exclude")] public Exclude[] ExcludeElements { set { foreach (Exclude exclude in value) { if (exclude.IfDefined && !exclude.UnlessDefined) { logger.Debug(string.Format(CultureInfo.InvariantCulture, "Excluding pattern", exclude.Pattern)); Excludes.Add(exclude.Pattern); } } } } /// /// The files from which a list of patterns or files to include should /// be obtained. /// [BuildElementArray("includesList")] [Obsolete("Use instead.", false)] public IncludesFile[] SetIncludesList { set { IncludesFiles = value; } } /// /// The files from which a list of patterns or files to include should /// be obtained. /// [BuildElementArray("includesfile")] public IncludesFile[] IncludesFiles { set { foreach (IncludesFile includesFile in value) { if (includesFile.IfDefined && !includesFile.UnlessDefined) { if (includesFile.AsIs) { foreach (string pattern in includesFile.Patterns) { logger.Debug(string.Format(CultureInfo.InvariantCulture, "Including AsIs=", pattern)); AsIs.Add(pattern); } } else if (includesFile.FromPath) { foreach (string pattern in includesFile.Patterns) { logger.Debug(string.Format(CultureInfo.InvariantCulture, "Including FromPath=", pattern)); PathFiles.Add(pattern); } } else { foreach (string pattern in includesFile.Patterns) { logger.Debug(string.Format(CultureInfo.InvariantCulture, "Including Pattern=", pattern)); Includes.Add(pattern); } } } } } } /// /// The files from which a list of patterns or files to exclude should /// be obtained. /// [BuildElementArray("excludesfile")] public ExcludesFile[] ExcludesFiles { set { foreach (ExcludesFile excludesFile in value) { if (excludesFile.IfDefined && !excludesFile.UnlessDefined) { foreach (string pattern in excludesFile.Patterns) { logger.Debug(string.Format(CultureInfo.InvariantCulture, "Excluding=", pattern)); Excludes.Add(pattern); } } } } } /// /// Determines the most recently modified file in the fileset (by LastWriteTime of the ). /// /// /// The of the file that has the newest (closest to present) last write time. /// public FileInfo MostRecentLastWriteTimeFile { get{ FileInfo newestFile = null; foreach (string fileName in FileNames) { FileInfo fileInfo = new FileInfo(fileName); if(newestFile == null && fileInfo.Exists) { newestFile = fileInfo; } if (!fileInfo.Exists) { logger.Info(string.Format(CultureInfo.InvariantCulture, "File '{0}' does not exist (and is not newer than {1})", fileName, newestFile)); continue; } if (newestFile != null && fileInfo.LastWriteTime > newestFile.LastWriteTime) { logger.Info(string.Format(CultureInfo.InvariantCulture, "'{0}' was newer than {1}", fileName, newestFile)); newestFile = fileInfo; } } return newestFile; } } #endregion Public Instance Properties #region Implementation of ICloneable /// /// Creates a shallow copy of the . /// /// /// A shallow copy of the . /// public virtual object Clone() { FileSet clone = new FileSet(); CopyTo(clone); return clone; } #endregion Implementation of ICloneable #region Override implementation of Element protected override void Initialize() { base.Initialize(); if (DefaultExcludes) { // add default exclude patterns Excludes.Add("**/.svn"); Excludes.Add("**/.svn/**"); Excludes.Add("**/_svn"); Excludes.Add("**/_svn/**"); Excludes.Add("**/.git"); Excludes.Add("**/.git/**"); Excludes.Add("**/.git*"); // eg .gitignore Excludes.Add("**/.hg"); Excludes.Add("**/.hg/**"); Excludes.Add("**/.hg*"); // eg .hgignore Excludes.Add("**/SCCS"); Excludes.Add("**/SCCS/**"); Excludes.Add("**/vssver.scc"); Excludes.Add("**/vssver2.scc"); Excludes.Add("**/_vti_cnf/**"); Excludes.Add("**/*~"); Excludes.Add("**/#*#"); Excludes.Add("**/.#*"); Excludes.Add("**/%*%"); Excludes.Add("**/CVS"); Excludes.Add("**/CVS/**"); Excludes.Add("**/.cvsignore"); } } #endregion Override implementation of Element #region Override implementation of DataTypeBase public override void Reset() { // ensure that scanning will happen again for each use _hasScanned = false; } #endregion Override implementation of DataTypeBase #region Override implementation of Object public override string ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if (!_hasScanned){ sb.AppendFormat("Base path: {0}", BaseDirectory); sb.AppendLine(); sb.AppendLine("AsIs:"); sb.AppendLine(AsIs.ToString()); sb.AppendLine("Files:"); sb.AppendLine(_scanner.ToString()); sb.AppendLine("PathFiles:"); sb.AppendLine(_pathFiles.ToString()); } else { sb.AppendFormat("IsEverythingIncluded: {0}", IsEverythingIncluded); sb.AppendLine(); sb.AppendLine("Files:"); foreach (string file in this.FileNames) { sb.Append(file); sb.Append(Environment.NewLine); } sb.Append("Dirs:"); sb.Append(Environment.NewLine); foreach (string dir in this.DirectoryNames) { sb.Append(dir); sb.Append(Environment.NewLine); } } return sb.ToString(); } #endregion Override implementation of Object #region Public Instance Methods /// /// Adds a nested set of patterns, or references a standalone patternset. /// [BuildElement("patternset")] public void AddPatternSet (PatternSet patternSet) { Includes.AddRange(patternSet.GetIncludePatterns()); Excludes.AddRange(patternSet.GetExcludePatterns()); } public virtual void Scan() { try { _scanner.BaseDirectory = BaseDirectory; _scanner.Scan(); // add all the as-is patterns to the scanned files. foreach (string name in AsIs) { if (Directory.Exists(name)) { _scanner.DirectoryNames.Add(name); } else { _scanner.FileNames.Add(name); } } // add all the path-searched patterns to the scanned files. foreach (string name in PathFiles.Scan()) { _scanner.FileNames.Add(name); } _hasScanned = true; } catch (Exception ex) { throw new BuildException("Error creating FileSet.", Location, ex); } if (FailOnEmpty && _scanner.FileNames.Count == 0) { throw new ValidationException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1164"), _scanner.BaseDirectory, _scanner.Includes.ToString()), Location); } } #endregion Public Instance Methods #region Protected Instance Methods /// /// Copies all instance data of the to a given /// . /// protected void CopyTo(FileSet clone) { base.CopyTo(clone); clone._asis = StringUtils.Clone(_asis); if (_baseDirectory != null) { clone._baseDirectory = new DirectoryInfo(_baseDirectory.FullName); } clone._defaultExcludes = _defaultExcludes; clone._failOnEmpty = _failOnEmpty; clone._hasScanned = _hasScanned; clone._pathFiles = _pathFiles.Clone(); clone._scanner = (DirectoryScanner) _scanner.Clone(); } #endregion Protected Instance Methods #region Internal Instance Methods internal string Find (string fileName) { CompareOptions compareOptions = CompareOptions.None; CompareInfo compare = CultureInfo.InvariantCulture.CompareInfo; if (!CaseSensitive) compareOptions |= CompareOptions.IgnoreCase; foreach (string file in FileNames) { if (compare.Compare (Path.GetFileName (file), fileName, compareOptions) == 0) { return file; } } return null; } #endregion Internal Instance Methods #region Protected Internal Instance Properties /// /// Indicates whether or not every file and directory is included in /// the fileset list. /// protected internal bool IsEverythingIncluded { get { if (!_hasScanned) { Scan(); } return _scanner.IsEverythingIncluded; } } #endregion Protected Internal Instance Properties #region Public Static Methods /// /// Determines if a file has a more recent last write time than the /// given time, or no longer exists. /// /// A file to check the last write time against. /// The datetime to compare against. /// /// The name of the file that has a last write time greater than /// or that no longer exists; /// otherwise, . /// public static string FindMoreRecentLastWriteTime(string fileName, DateTime targetLastWriteTime) { StringCollection fileNames = new StringCollection(); fileNames.Add(fileName); return FileSet.FindMoreRecentLastWriteTime(fileNames, targetLastWriteTime); } /// /// Determines if one of the given files has a more recent last write /// time than the given time. If one of the given files no longer exists, /// the target will be considered out-of-date. /// /// A collection of filenames to check the last write time against. /// The datetime to compare against. /// /// The name of the first file that has a last write time greater than /// ; otherwise, null. /// public static string FindMoreRecentLastWriteTime(StringCollection fileNames, DateTime targetLastWriteTime) { foreach (string fileName in fileNames) { // only check fully file names that have a full path if (Path.IsPathRooted(fileName)) { FileInfo fileInfo = new FileInfo(fileName); if (!fileInfo.Exists) { logger.Info(string.Format(CultureInfo.InvariantCulture, "File '{0}' no longer exist (so the target might need to be updated)", fileName, targetLastWriteTime)); return fileName; } if (fileInfo.LastWriteTime > targetLastWriteTime) { logger.Info(string.Format(CultureInfo.InvariantCulture, "'{0}' was newer than {1}", fileName, targetLastWriteTime)); return fileName; } } } return null; } #endregion Public Static Methods // These classes provide a way of getting the Element task to initialize // the values from the build file. public class Exclude : Element { #region Private Instance Fields private string _pattern; private bool _ifDefined = true; private bool _unlessDefined; #endregion Private Instance Fields #region Public Instance Properties /// /// The pattern or file name to exclude. /// [TaskAttribute("name", Required=true)] [StringValidator(AllowEmpty=false)] public virtual string Pattern { get { return _pattern; } set { _pattern = value; } } /// /// If then the pattern will be excluded; /// otherwise, skipped. The default is . /// [TaskAttribute("if")] [BooleanValidator()] public virtual bool IfDefined { get { return _ifDefined; } set { _ifDefined = value; } } /// /// Opposite of . If /// then the pattern will be excluded; otherwise, skipped. The default /// is . /// [TaskAttribute("unless")] [BooleanValidator()] public virtual bool UnlessDefined { get { return _unlessDefined; } set { _unlessDefined = value; } } #endregion Public Instance Properties } public class Include : Exclude { #region Private Instance Fields private bool _asIs; private bool _fromPath; #endregion Private Instance Fields #region Public Instance Properties /// /// If then the file name will be added to /// the without pattern matching or checking /// if the file exists. The default is . /// [TaskAttribute("asis")] [BooleanValidator()] public bool AsIs { get { return _asIs; } set { _asIs = value; } } /// /// If then the file will be searched for /// on the path. The default is . /// [TaskAttribute("frompath")] [BooleanValidator()] public bool FromPath { get { return _fromPath; } set { _fromPath = value; } } #endregion Public Instance Properties #region Override implementation of Exclude /// /// The pattern or file name to include. /// [TaskAttribute("name", Required=true)] [StringValidator(AllowEmpty=false)] public override string Pattern { get { return base.Pattern; } set { base.Pattern = value; } } /// /// If then the pattern will be included; /// otherwise, skipped. The default is . /// [TaskAttribute("if")] [BooleanValidator()] public override bool IfDefined { get { return base.IfDefined; } set { base.IfDefined = value; } } /// /// Opposite of . If /// then the pattern will be included; otherwise, skipped. The default /// is . /// [TaskAttribute("unless")] [BooleanValidator()] public override bool UnlessDefined { get { return base.UnlessDefined; } set { base.UnlessDefined = value; } } #endregion Override implementation of Exclude } public class ExcludesFile : Element { #region Private Instance Fields private bool _ifDefined = true; private bool _unlessDefined; private FileInfo _patternFile; #endregion Private Instance Fields #region Public Instance Properties /// /// Gets the list of patterns in . /// public StringCollection Patterns { get { StringCollection patterns = new StringCollection(); if (PatternFile == null) { return patterns; } try { using (StreamReader sr = new StreamReader(PatternFile.FullName, Encoding.Default, true)) { string line = sr.ReadLine (); while (line != null) { // remove leading and trailing whitespace line = line.Trim (); // only consider non-empty lines that are not comments if (line.Length != 0 && line [0] != '#') { // add line as pattern patterns.Add(line); } // read next line line = sr.ReadLine (); } } return patterns; } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "'{0}' list could not be opened.", PatternFile.FullName), Location, ex); } } } /// /// If then the patterns will be excluded; /// otherwise, skipped. The default is . /// [TaskAttribute("if")] [BooleanValidator()] public virtual bool IfDefined { get { return _ifDefined; } set { _ifDefined = value; } } /// /// Opposite of . If /// then the patterns will be excluded; otherwise, skipped. The default /// is . /// [TaskAttribute("unless")] [BooleanValidator()] public virtual bool UnlessDefined { get { return _unlessDefined; } set { _unlessDefined = value; } } /// /// The name of a file; each line of this file is taken to be a /// pattern. /// [TaskAttribute("name", Required=true)] [StringValidator(AllowEmpty=false)] public FileInfo PatternFile { get { return _patternFile; } set { _patternFile = value; } } #endregion Public Instance Properties } public class IncludesFile : ExcludesFile { #region Private Instance Fields private bool _asIs; private bool _fromPath; #endregion Private Instance Fields #region Public Instance Properties /// /// If then the patterns in the include file /// will be added to the without pattern /// matching or checking if the file exists. The default is /// . /// [TaskAttribute("asis")] [BooleanValidator()] public bool AsIs { get { return _asIs; } set { _asIs = value; } } /// /// If then the patterns in the include file /// will be searched for on the path. The default is . /// [TaskAttribute("frompath")] [BooleanValidator()] public bool FromPath { get { return _fromPath; } set { _fromPath = value; } } #endregion Public Instance Properties #region Override implementation of ExcludesFile /// /// If then the patterns will be included; /// otherwise, skipped. The default is . /// [TaskAttribute("if")] [BooleanValidator()] public override bool IfDefined { get { return base.IfDefined; } set { base.IfDefined = value; } } /// /// Opposite of . If /// then the patterns will be included; otherwise, skipped. The default /// is . /// [TaskAttribute("unless")] [BooleanValidator()] public override bool UnlessDefined { get { return base.UnlessDefined; } set { base.UnlessDefined = value; } } #endregion Override implementation of ExcludesFile } } } nant-0.92-rc1/src/NAnt.Core/Types/XmlNamespace.cs0000644000175000017500000000571311757302273021364 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Martin Aliger // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Martin Aliger (martin_aliger@gordic.cz) // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Xml; using NAnt.Core; using NAnt.Core.Attributes; namespace NAnt.Core.Types { /// /// Represents an XML namespace. /// [ElementName("namespace")] public class XmlNamespace : Element { #region Private Instance Fields private string _prefix; private string _uri; private bool _ifDefined = true; private bool _unlessDefined; #endregion Private Instance Fields #region Public Instance Properties /// /// The prefix to associate with the namespace. /// [TaskAttribute("prefix", Required=true)] [StringValidator(AllowEmpty=true)] public string Prefix { get { return _prefix; } set { _prefix = value; } } /// /// The associated XML namespace URI. /// [TaskAttribute("uri", Required=true)] [StringValidator(AllowEmpty=true)] public string Uri { get { return _uri; } set { _uri = value; } } /// /// Indicates if the namespace should be added to the . /// If then the namespace will be added; /// otherwise, skipped. The default is . /// [TaskAttribute("if")] [BooleanValidator()] public bool IfDefined { get { return _ifDefined; } set { _ifDefined = value; } } /// /// Indicates if the namespace should not be added to the . /// list. If then the parameter will be /// added; otherwise, skipped. The default is . /// [TaskAttribute("unless")] [BooleanValidator()] public bool UnlessDefined { get { return _unlessDefined; } set { _unlessDefined = value; } } #endregion Public Instance Properties } } nant-0.92-rc1/src/NAnt.Core/Types/XmlNamespaceCollection.cs0000644000175000017500000002435711757302273023405 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; namespace NAnt.Core.Types { /// /// Contains a collection of elements. /// [Serializable()] public class XmlNamespaceCollection : CollectionBase { #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public XmlNamespaceCollection() { } /// /// Initializes a new instance of the class /// with the specified instance. /// public XmlNamespaceCollection(XmlNamespaceCollection value) { AddRange(value); } /// /// Initializes a new instance of the class /// with the specified array of instances. /// public XmlNamespaceCollection(XmlNamespace[] value) { AddRange(value); } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets the element at the specified index. /// /// The zero-based index of the element to get or set. [System.Runtime.CompilerServices.IndexerName("Item")] public XmlNamespace this[int index] { get { return (XmlNamespace) base.List[index]; } set { base.List[index] = value; } } /// /// Gets the with the specified prefix. /// /// The prefix of the to get. [System.Runtime.CompilerServices.IndexerName("Item")] public XmlNamespace this[string value] { get { if (value != null) { // Try to locate instance using Value foreach (XmlNamespace xmlNamespace in base.List) { if (xmlNamespace.Prefix == value) { return xmlNamespace; } } } return null; } } #endregion Public Instance Properties #region Public Instance Methods /// /// Adds a to the end of the collection. /// /// The to be added to the end of the collection. /// The position into which the new element was inserted. public int Add(XmlNamespace item) { return base.List.Add(item); } /// /// Adds the elements of a array to the end of the collection. /// /// The array of elements to be added to the end of the collection. public void AddRange(XmlNamespace[] items) { for (int i = 0; (i < items.Length); i = (i + 1)) { Add(items[i]); } } /// /// Adds the elements of a to the end of the collection. /// /// The to be added to the end of the collection. public void AddRange(XmlNamespaceCollection items) { for (int i = 0; (i < items.Count); i = (i + 1)) { Add(items[i]); } } /// /// Determines whether a is in the collection. /// /// The to locate in the collection. /// /// if is found in the /// collection; otherwise, . /// public bool Contains(XmlNamespace item) { return base.List.Contains(item); } /// /// Determines whether a with the specified /// value is in the collection. /// /// The argument value to locate in the collection. /// /// if a with /// value is found in the collection; otherwise, /// . /// public bool Contains(string value) { return this[value] != null; } /// /// Copies the entire collection to a compatible one-dimensional array, starting at the specified index of the target array. /// /// The one-dimensional array that is the destination of the elements copied from the collection. The array must have zero-based indexing. /// The zero-based index in at which copying begins. public void CopyTo(XmlNamespace[] array, int index) { base.List.CopyTo(array, index); } /// /// Retrieves the index of a specified object in the collection. /// /// The object for which the index is returned. /// /// The index of the specified . If the is not currently a member of the collection, it returns -1. /// public int IndexOf(XmlNamespace item) { return base.List.IndexOf(item); } /// /// Inserts a into the collection at the specified index. /// /// The zero-based index at which should be inserted. /// The to insert. public void Insert(int index, XmlNamespace item) { base.List.Insert(index, item); } /// /// Returns an enumerator that can iterate through the collection. /// /// /// A for the entire collection. /// public new XmlNamespaceEnumerator GetEnumerator() { return new XmlNamespaceEnumerator(this); } /// /// Removes a member from the collection. /// /// The to remove from the collection. public void Remove(XmlNamespace item) { base.List.Remove(item); } #endregion Public Instance Methods } /// /// Enumerates the elements of a . /// public class XmlNamespaceEnumerator : IEnumerator { #region Internal Instance Constructors /// /// Initializes a new instance of the class /// with the specified . /// /// The collection that should be enumerated. internal XmlNamespaceEnumerator(XmlNamespaceCollection arguments) { IEnumerable temp = (IEnumerable) (arguments); _baseEnumerator = temp.GetEnumerator(); } #endregion Internal Instance Constructors #region Implementation of IEnumerator /// /// Gets the current element in the collection. /// /// /// The current element in the collection. /// public XmlNamespace Current { get { return (XmlNamespace) _baseEnumerator.Current; } } object IEnumerator.Current { get { return _baseEnumerator.Current; } } /// /// Advances the enumerator to the next element of the collection. /// /// /// if the enumerator was successfully advanced /// to the next element; if the enumerator has /// passed the end of the collection. /// public bool MoveNext() { return _baseEnumerator.MoveNext(); } bool IEnumerator.MoveNext() { return _baseEnumerator.MoveNext(); } /// /// Sets the enumerator to its initial position, which is before the /// first element in the collection. /// public void Reset() { _baseEnumerator.Reset(); } void IEnumerator.Reset() { _baseEnumerator.Reset(); } #endregion Implementation of IEnumerator #region Private Instance Fields private IEnumerator _baseEnumerator; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.Core/Types/OptionCollection.cs0000644000175000017500000002370411757302273022273 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; namespace NAnt.Core.Types { /// /// Contains a collection of elements. /// [Serializable()] public class OptionCollection : CollectionBase { #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public OptionCollection() { } /// /// Initializes a new instance of the class /// with the specified instance. /// public OptionCollection(OptionCollection value) { AddRange(value); } /// /// Initializes a new instance of the class /// with the specified array of instances. /// public OptionCollection(Option[] value) { AddRange(value); } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets the element at the specified index. /// /// The zero-based index of the element to get or set. [System.Runtime.CompilerServices.IndexerName("Item")] public Option this[int index] { get {return ((Option)(base.List[index]));} set {base.List[index] = value;} } /// /// Gets the with the specified name. /// /// The name of the option that should be located in the collection. [System.Runtime.CompilerServices.IndexerName("Item")] public Option this[string name] { get { if (name != null) { // Try to locate instance using OptionName foreach (Option Option in base.List) { if (name.Equals(Option.OptionName)) { return Option; } } } return null; } } #endregion Public Instance Properties #region Public Instance Methods /// /// Adds a to the end of the collection. /// /// The to be added to the end of the collection. /// The position into which the new element was inserted. public int Add(Option item) { return base.List.Add(item); } /// /// Adds the elements of a array to the end of the collection. /// /// The array of elements to be added to the end of the collection. public void AddRange(Option[] items) { for (int i = 0; (i < items.Length); i = (i + 1)) { Add(items[i]); } } /// /// Adds the elements of a to the end of the collection. /// /// The to be added to the end of the collection. public void AddRange(OptionCollection items) { for (int i = 0; (i < items.Count); i = (i + 1)) { Add(items[i]); } } /// /// Determines whether a is in the collection. /// /// The to locate in the collection. /// /// if is found in the /// collection; otherwise, . /// public bool Contains(Option item) { return base.List.Contains(item); } /// /// Determines whether a for the specified /// task is in the collection. /// /// The name of task for which the should be located in the collection. /// /// if a for the specified /// task is found in the collection; otherwise, . /// public bool Contains(string taskName) { return this[taskName] != null; } /// /// Copies the entire collection to a compatible one-dimensional array, starting at the specified index of the target array. /// /// The one-dimensional array that is the destination of the elements copied from the collection. The array must have zero-based indexing. /// The zero-based index in at which copying begins. public void CopyTo(Option[] array, int index) { base.List.CopyTo(array, index); } /// /// Retrieves the index of a specified object in the collection. /// /// The object for which the index is returned. /// /// The index of the specified . If the is not currently a member of the collection, it returns -1. /// public int IndexOf(Option item) { return base.List.IndexOf(item); } /// /// Inserts a into the collection at the specified index. /// /// The zero-based index at which should be inserted. /// The to insert. public void Insert(int index, Option item) { base.List.Insert(index, item); } /// /// Returns an enumerator that can iterate through the collection. /// /// /// A for the entire collection. /// public new OptionEnumerator GetEnumerator() { return new OptionEnumerator(this); } /// /// Removes a member from the collection. /// /// The to remove from the collection. public void Remove(Option item) { base.List.Remove(item); } #endregion Public Instance Methods } /// /// Enumerates the elements of a . /// public class OptionEnumerator : IEnumerator { #region Internal Instance Constructors /// /// Initializes a new instance of the class /// with the specified . /// /// The collection that should be enumerated. internal OptionEnumerator(OptionCollection arguments) { IEnumerable temp = (IEnumerable) (arguments); _baseEnumerator = temp.GetEnumerator(); } #endregion Internal Instance Constructors #region Implementation of IEnumerator /// /// Gets the current element in the collection. /// /// /// The current element in the collection. /// public Option Current { get { return (Option) _baseEnumerator.Current; } } object IEnumerator.Current { get { return _baseEnumerator.Current; } } /// /// Advances the enumerator to the next element of the collection. /// /// /// if the enumerator was successfully advanced /// to the next element; if the enumerator has /// passed the end of the collection. /// public bool MoveNext() { return _baseEnumerator.MoveNext(); } bool IEnumerator.MoveNext() { return _baseEnumerator.MoveNext(); } /// /// Sets the enumerator to its initial position, which is before the /// first element in the collection. /// public void Reset() { _baseEnumerator.Reset(); } void IEnumerator.Reset() { _baseEnumerator.Reset(); } #endregion Implementation of IEnumerator #region Private Instance Fields private IEnumerator _baseEnumerator; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.Core/Types/PatternSet.cs0000644000175000017500000003263011757302273021076 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2007 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; using System.Globalization; using System.IO; using System.Text; using System.Xml; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Util; namespace NAnt.Core.Types { /// /// A set of patterns, mostly used to include or exclude certain files. /// /// /// /// The individual patterns support if and unless attributes /// to specify that the element should only be used if or unless a given /// condition is met. /// /// /// The and /// elements load patterns from a file. When the file is a relative path, /// it will be resolved relative to the project base directory in which /// the patternset is defined. Each line of this file is taken to be a /// pattern. /// /// /// The number sign (#) as the first non-blank character in a line denotes /// that all text following it is a comment: /// /// /// /// /// /// Patterns can be grouped to sets, and later be referenced by their /// . /// /// /// When used as a standalone element (global type), any properties that /// are referenced will be resolved when the definition is processed, not /// when it actually used. Passing a reference to a nested build file /// will not cause the properties to be re-evaluated. /// /// /// To improve reuse of globally defined patternsets, avoid referencing /// any properties altogether. /// /// /// /// /// Define a set of patterns that matches all .cs files that do not contain /// the text Test in their name. /// /// /// /// /// /// /// ]]> /// /// /// /// /// Define two sets. One holding C# sources, and one holding VB sources. /// Both sets only include test sources when the test property is /// set. A third set combines both C# and VB sources. /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// ]]> /// /// /// /// /// Define a set from patterns in a file. /// /// /// /// /// /// /// ]]> /// /// /// /// /// Defines a patternset with patterns that are loaded from an external /// file, and shows the behavior when that patternset is passed as a /// reference to a nested build script. /// /// /// External file "c:\foo\build\service.lst" holding patterns /// of source files to include for the Foo.Service assembly: /// /// /// /// /// Main build script located in "c:\foo\default.build": /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// ///
]]> /// /// Nested build script located in "c:\foo\services\default.build" /// which uses the patternset to feed sources files to the C# compiler: /// /// /// /// /// /// /// /// /// /// /// ]]> /// /// At the time when the patternset is used in the "service" /// build script, the following source files in "c:\foo\services\src" /// match the defined patterns: /// /// /// /// /// You should have observed that: /// /// /// /// /// although the patternset is used from the "service" /// build script, the path to the external file is resolved relative /// to the base directory of the "main" build script in /// which the patternset is defined. /// /// /// /// /// the "TraceListener.cs" file is included, even though /// the "build.debug" property was changed to false /// after the patternset was defined (but before it was passed to /// the nested build, and used). /// /// /// /// /// [ElementName("patternset")] public class PatternSet : DataTypeBase { #region Public Instance Constructor /// /// Initializes a new instance of the class. /// public PatternSet() { _include = new PatternCollection(); _exclude = new PatternCollection(); _includesFile = new PatternCollection(); _excludesFile = new PatternCollection(); } #endregion Public Instance Constructor #region Public Instance Properties /// /// Defines a single pattern for files to include. /// [BuildElementArrayAttribute("include")] public PatternCollection Include { get { return _include; } } /// /// Loads multiple patterns of files to include from a given file, set /// using the parameter. /// [BuildElementArrayAttribute("includesfile")] public PatternCollection IncludesFile { get { return _includesFile; } } /// /// Defines a single pattern for files to exclude. /// [BuildElementArrayAttribute("exclude")] public PatternCollection Exclude { get { return _exclude; } } /// /// Loads multiple patterns of files to exclude from a given file, set /// using the parameter. /// [BuildElementArrayAttribute("excludesfile")] public PatternCollection ExcludesFile { get { return _excludesFile; } } #endregion Public Instance Properties #region Public Instance Methods /// /// Adds a nested set of patterns, or references other standalone /// patternset. /// /// The to add. [BuildElement("patternset")] public void Append(PatternSet patternSet) { string[] includePatterns = patternSet.GetIncludePatterns(); foreach (string includePattern in includePatterns) { _include.Add(new Pattern(Project, includePattern)); } string[] excludePatterns = patternSet.GetExcludePatterns(); foreach (string excludePattern in excludePatterns) { _exclude.Add(new Pattern(Project, excludePattern)); } } public string[] GetIncludePatterns () { ArrayList includes = new ArrayList (Include.Count); foreach (Pattern include in Include) { if (!include.Enabled) { continue; } includes.Add(include.PatternName); } foreach (Pattern includesfile in IncludesFile) { if (!includesfile.Enabled) { continue; } string absoluteFile = Project.GetFullPath(includesfile.PatternName); if (!File.Exists (absoluteFile)) { throw new BuildException ("Includesfile '" + absoluteFile + "' not found.", Location); } ReadPatterns(absoluteFile, includes); } return (string[]) includes.ToArray(typeof(string)); } public string[] GetExcludePatterns () { ArrayList excludes = new ArrayList (Exclude.Count); foreach (Pattern exclude in Exclude) { if (!exclude.Enabled) { continue; } excludes.Add(exclude.PatternName); } foreach (Pattern excludesfile in ExcludesFile) { if (!excludesfile.Enabled) { continue; } string absoluteFile = Project.GetFullPath(excludesfile.PatternName); if (!File.Exists (absoluteFile)) { throw new BuildException ("Excludesfile '" + absoluteFile + "' not found.", Location); } ReadPatterns(absoluteFile, excludes); } return (string[]) excludes.ToArray(typeof(string)); } #endregion Public Instance Methods #region Private Instance Methods private void ReadPatterns(string fileName, ArrayList patterns) { using (StreamReader sr = new StreamReader(fileName, Encoding.Default, true)) { string line = sr.ReadLine (); while (line != null) { // remove leading and trailing whitespace line = line.Trim (); // only consider non-empty lines that are not comments if (line.Length != 0 && line [0] != '#') { // add line as pattern patterns.Add(line); } // read next line line = sr.ReadLine (); } } } #endregion Private Instance Methods #region Private Instance Fields private readonly PatternCollection _include; private readonly PatternCollection _exclude; private readonly PatternCollection _includesFile; private readonly PatternCollection _excludesFile; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.Core/Types/XsltParameter.cs0000644000175000017500000000763211757302273021604 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; using NAnt.Core.Attributes; using NAnt.Core.Util; namespace NAnt.Core.Types { /// /// Represents an XSLT parameter. /// [ElementName("xsltparameter")] public class XsltParameter : Element { #region Private Instance Fields private string _name = string.Empty; private string _namespaceUri = string.Empty; private string _value = string.Empty; private bool _ifDefined = true; private bool _unlessDefined; #endregion Private Instance Fields #region Public Instance Constructors /// /// Initializes a new instance of the /// class. /// public XsltParameter() { } #endregion Public Instance Constructors #region Public Instance Properties /// /// The name of the XSLT parameter. /// /// /// The name of the XSLT parameter, or if /// not set. /// [TaskAttribute("name", Required=true)] [StringValidator(AllowEmpty=false)] public string ParameterName { get { return _name; } set { _name = value; } } /// /// The namespace URI to associate with the parameter. /// /// /// The namespace URI to associate with the parameter, or /// if not set. /// [TaskAttribute("namespaceuri")] public string NamespaceUri { get { return _namespaceUri; } set { _namespaceUri = value; } } /// /// The value of the XSLT parameter. /// /// /// The value of the XSLT parameter, or if /// not set. /// [TaskAttribute("value", Required=true)] public string Value { get { return _value; } set { _value = value; } } /// /// Indicates if the parameter should be added to the XSLT argument list. /// If then the parameter will be added; /// otherwise, skipped. The default is . /// [TaskAttribute("if")] [BooleanValidator()] public bool IfDefined { get { return _ifDefined; } set { _ifDefined = value; } } /// /// Indicates if the parameter should not be added to the XSLT argument /// list. If then the parameter will be /// added; otherwise, skipped. The default is . /// [TaskAttribute("unless")] [BooleanValidator()] public bool UnlessDefined { get { return _unlessDefined; } set { _unlessDefined = value; } } #endregion Public Instance Properties } } nant-0.92-rc1/src/NAnt.Core/Types/Token.cs0000644000175000017500000000526311757302273020067 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // using System; using NAnt.Core.Attributes; namespace NAnt.Core.Types { /// /// ReplaceTokens filter token. /// [ElementName("token")] public class Token : Element { #region Private Instance Fields private string _key; private string _value; private bool _ifDefined = true; private bool _unlessDefined; #endregion Private Instance Fields #region Public Instance Properties /// /// Token to be replaced. /// [TaskAttribute("key", Required=true)] [StringValidator(AllowEmpty=false)] public string Key { get { return _key; } set { _key = value; } } /// /// New value of token. /// [TaskAttribute("value", Required=true)] public string Value { get { return _value; } set { _value = value; } } /// /// Indicates if the token should be used to replace values. /// If then the token will be used; /// otherwise, not. The default is . /// [TaskAttribute("if", Required=false)] [BooleanValidator()] public bool IfDefined { get { return _ifDefined; } set { _ifDefined = value; } } /// /// Indicates if the token should not be used to replace values. /// If then the token will be used; /// otherwise, not. The default is . /// [TaskAttribute("unless", Required=false)] [BooleanValidator()] public bool UnlessDefined { get { return _unlessDefined; } set { _unlessDefined = value; } } #endregion Public Instance Properties } } nant-0.92-rc1/src/NAnt.Core/Types/PathElement.cs0000644000175000017500000001171411757302273021213 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Xml; using NAnt.Core.Attributes; namespace NAnt.Core.Types { /// /// Represents a nested path element. /// [Serializable()] [ElementName("pathelement")] public class PathElement : Element { #region Private Instance Fields private FileInfo _file; private DirectoryInfo _directory; private PathSet _path; private bool _ifDefined = true; private bool _unlessDefined; #endregion Private Instance Fields #region Public Instance Properties /// /// The name of a file to add to the path. Will be replaced with /// the absolute path of the file. /// [TaskAttribute("file")] public FileInfo File { get { return _file; } set { _file = value; } } /// /// The name of a directory to add to the path. Will be replaced with /// the absolute path of the directory. /// [TaskAttribute("dir")] public DirectoryInfo Directory { get { return _directory; } set { _directory = value; } } /// /// A string that will be treated as a path-like string. You can use /// : or ; as path separators and NAnt will convert it /// to the platform's local conventions, while resolving references /// to environment variables. /// [TaskAttribute("path")] public PathSet Path { get { return _path; } set { _path = value; } } /// /// If then the entry will be added to the /// path; otherwise, skipped. The default is . /// [TaskAttribute("if")] public bool IfDefined { get { return _ifDefined; } set { _ifDefined = value; } } /// /// Opposite of . If /// then the entry will be added to the path; otherwise, skipped. /// The default is . /// [TaskAttribute("unless")] public bool UnlessDefined { get { return _unlessDefined; } set { _unlessDefined = value; } } /// /// Gets the parts of a path represented by this element. /// /// /// A containing the parts of a path /// represented by this element. /// public StringCollection Parts { get { if (File != null) { StringCollection parts = new StringCollection(); parts.Add(File.FullName); return parts; } else if (Directory != null) { StringCollection parts = new StringCollection(); parts.Add(Directory.FullName); return parts; } else if (Path != null) { return Path.GetElements(); } return new StringCollection(); } } #endregion Public Instance Properties #region Override implementation of Element protected override void Initialize() { if (File == null && Directory == null && Path == null) { throw new BuildException(string.Format(CultureInfo.InstalledUICulture, "At least \"file\", \"directory\" or \"path\" must be" + " specified."), Location); } if (File == null && Directory == null && Path == null) { throw new BuildException(string.Format(CultureInfo.InstalledUICulture, "\"file\", \"directory\" and \"path\" cannot be specified" + " together."), Location); } } #endregion Override implementation of Element } }nant-0.92-rc1/src/NAnt.Core/Types/XsltExtensionObjectCollection.cs0000644000175000017500000002575311757302273025007 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) // Tim Noll (tim.noll@gmail.com) using System; using System.Collections; namespace NAnt.Core.Types { /// /// Contains a collection of elements. /// [Serializable()] public class XsltExtensionObjectCollection : CollectionBase { #region Public Instance Constructors /// /// Initializes a new instance of the /// class. /// public XsltExtensionObjectCollection() { } /// /// Initializes a new instance of the /// class with the /// specified instance. /// public XsltExtensionObjectCollection(XsltExtensionObjectCollection value) { AddRange(value); } /// /// Initializes a new instance of the /// class with the /// specified array of instances. /// public XsltExtensionObjectCollection(XsltExtensionObject[] value) { AddRange(value); } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets the element at the specified index. /// /// The zero-based index of the element to get /// or set. [System.Runtime.CompilerServices.IndexerName("Item")] public XsltExtensionObject this[int index] { get { return (XsltExtensionObject) base.List[index]; } set { base.List[index] = value; } } /// /// Gets the with the specified name. /// /// The name of the /// to get. [System.Runtime.CompilerServices.IndexerName("Item")] public XsltExtensionObject this[string value] { get { if (value != null) { // Try to locate instance using Value foreach (XsltExtensionObject extensionObject in base.List) { if (extensionObject.Name == value) { return extensionObject; } } } return null; } } #endregion Public Instance Properties #region Public Instance Methods /// /// Adds a to the end of the collection. /// /// The to be added /// to the end of the collection. /// The position into which the new element was inserted. public int Add(XsltExtensionObject item) { return base.List.Add(item); } /// /// Adds the elements of a array to the /// end of the collection. /// /// The array of /// elements to be added to the end of the collection. public void AddRange(XsltExtensionObject[] items) { for (int i = 0; (i < items.Length); i = (i + 1)) { Add(items[i]); } } /// /// Adds the elements of a /// to the end of the collection. /// /// The /// to be added to the end of the collection. public void AddRange(XsltExtensionObjectCollection items) { for (int i = 0; (i < items.Count); i = (i + 1)) { Add(items[i]); } } /// /// Determines whether a is in the /// collection. /// /// The to locate /// in the collection. /// /// if is found in the /// collection; otherwise, . /// public bool Contains(XsltExtensionObject item) { return base.List.Contains(item); } /// /// Determines whether a with the /// specified value is in the collection. /// /// The argument value to locate in the /// collection. /// /// if a /// with value is found in the collection; /// otherwise, . /// public bool Contains(string value) { return this[value] != null; } /// /// Copies the entire collection to a compatible one-dimensional array, /// starting at the specified index of the target array. /// /// The one-dimensional array that is the /// destination of the elements copied from the collection. The array /// must have zero-based indexing. /// The zero-based index in /// at which copying begins. public void CopyTo(XsltExtensionObject[] array, int index) { base.List.CopyTo(array, index); } /// /// Retrieves the index of a specified /// object in the collection. /// /// The object for /// which the index is returned. /// /// The index of the specified . If the /// is not currently a member of the /// collection, it returns -1. /// public int IndexOf(XsltExtensionObject item) { return base.List.IndexOf(item); } /// /// Inserts a into the collection at /// the specified index. /// /// The zero-based index at which /// should be inserted. /// The to /// insert. public void Insert(int index, XsltExtensionObject item) { base.List.Insert(index, item); } /// /// Returns an enumerator that can iterate through the collection. /// /// /// A for the entire /// collection. /// public new XsltExtensionObjectEnumerator GetEnumerator() { return new XsltExtensionObjectEnumerator(this); } /// /// Removes a member from the collection. /// /// The to remove /// from the collection. public void Remove(XsltExtensionObject item) { base.List.Remove(item); } #endregion Public Instance Methods } /// /// Enumerates the elements of a /// . /// public class XsltExtensionObjectEnumerator : IEnumerator { #region Internal Instance Constructors /// /// Initializes a new instance of the /// class /// with the specified . /// /// The collection that should be /// enumerated. internal XsltExtensionObjectEnumerator(XsltExtensionObjectCollection arguments) { IEnumerable temp = (IEnumerable) (arguments); _baseEnumerator = temp.GetEnumerator(); } #endregion Internal Instance Constructors #region Implementation of IEnumerator /// /// Gets the current element in the collection. /// /// /// The current element in the collection. /// public XsltExtensionObject Current { get { return (XsltExtensionObject) _baseEnumerator.Current; } } object IEnumerator.Current { get { return _baseEnumerator.Current; } } /// /// Advances the enumerator to the next element of the collection. /// /// /// if the enumerator was successfully advanced /// to the next element; if the enumerator has /// passed the end of the collection. /// public bool MoveNext() { return _baseEnumerator.MoveNext(); } bool IEnumerator.MoveNext() { return _baseEnumerator.MoveNext(); } /// /// Sets the enumerator to its initial position, which is before the /// first element in the collection. /// public void Reset() { _baseEnumerator.Reset(); } void IEnumerator.Reset() { _baseEnumerator.Reset(); } #endregion Implementation of IEnumerator #region Private Instance Fields private IEnumerator _baseEnumerator; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.Core/Types/PathSet.cs0000644000175000017500000002102511757302273020351 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; using System.Collections.Specialized; using System.IO; using System.Text; using NAnt.Core.Attributes; using NAnt.Core.Util; namespace NAnt.Core.Types { /// /// /// Paths are groups of files and/or directories that need to be passed as a single /// unit. The order in which parts of the path are specified in the build file is /// retained, and duplicate parts are automatically suppressed. /// /// /// /// /// Define a global <path> that can be referenced by other /// tasks or types. /// /// /// /// /// /// /// ]]> /// /// [Serializable()] [ElementName("path")] public class PathSet : DataTypeBase { #region Private Instance Fields private ArrayList _elements = new ArrayList(); private StringCollection _translatedElements = new StringCollection(); #endregion Private Instance Fields #region Private Static Fields private static readonly bool _dosBasedFileSystem = (Path.PathSeparator == ';'); #endregion Private Static Fields #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public PathSet() { } /// /// Invoked by for build /// attributes with an underlying type. /// /// The to be used to resolve relative paths. /// The string representing a path. public PathSet(Project project, string path) { base.Project = project; _translatedElements = PathSet.TranslatePath(project, path); } #endregion Public Instance Constructors #region Override implementation of Object /// /// Returns a textual representation of the path, which can be used as /// PATH environment variable definition. /// /// /// A textual representation of the path. /// public override string ToString() { StringCollection parts = GetElements(); // empty path return empty string if (parts.Count == 0) { return ""; } // path containing one or more elements StringBuilder result = new StringBuilder(parts[0], parts.Count); for (int i = 1; i < parts.Count; i++) { result.Append(Path.PathSeparator); result.Append(parts[i]); } return result.ToString(); } #endregion Override implementation of Object #region Public Instance Methods /// /// Defines a set of path elements to add to the current path. /// /// The to add. [BuildElement("path")] public void AddPath(PathSet path) { _elements.Add(path); } /// /// Defines a path element to add to the current path. /// /// The to add. [BuildElement("pathelement")] public void AddPathElement(PathElement pathElement) { _elements.Add(pathElement); } /// /// Returns all path elements defined by this path object. /// /// /// A list of path elements. /// public StringCollection GetElements() { StringCollection result = StringUtils.Clone(_translatedElements); foreach (object path in _elements) { if (path is PathSet) { foreach (string part in ((PathSet) path).GetElements()) { if (!result.Contains(part)) { result.Add(part); } } } else if (path is PathElement) { PathElement pathElement = (PathElement) path; if (!pathElement.IfDefined || pathElement.UnlessDefined) { continue; } foreach (string part in ((PathElement) path).Parts) { if (!result.Contains(part)) { result.Add(part); } } } } return result; } #endregion Public Instance Methods #region Public Static Methods /// /// Splits a PATH (with ; or : as separators) into its parts, while /// resolving references to environment variables. /// /// The to be used to resolve relative paths. /// The path to translate. /// /// A PATH split up its parts, with references to environment variables /// resolved and duplicate entries removed. /// public static StringCollection TranslatePath(Project project, string source) { StringCollection result = new StringCollection(); if (source == null) { return result; } string[] parts = source.Split(':',';'); for (int i = 0; i < parts.Length; i++) { string part = parts[i]; // on a DOS filesystem, the ':' character might be part of a // drive spec and in that case we need to combine the current // and the next part if (part.Length == 1 && Char.IsLetter(part[0]) && _dosBasedFileSystem && (parts.Length > i + 1)) { string nextPart = parts[i + 1].Trim(); if (nextPart.StartsWith("\\") || nextPart.StartsWith("/")) { part += ":" + nextPart; // skip the next part as we've also processed it i++; } } // expand env variables in part string expandedPart = Environment.ExpandEnvironmentVariables(part); // check if part is a reference to an environment variable // that could not be expanded (does not exist) if (expandedPart.StartsWith("%") && expandedPart.EndsWith("%")) { continue; } // resolve each part in the expanded environment variable to a // full path foreach (string path in expandedPart.Split(Path.PathSeparator)) { try { string absolutePath = project.GetFullPath(path); if (!result.Contains(absolutePath)) { result.Add(absolutePath); } } catch (Exception ex) { project.Log(Level.Verbose, "Dropping path element '{0}'" + " as it could not be resolved to a full path. {1}", path, ex.Message); } } } return result; } #endregion Public Static Methods } }nant-0.92-rc1/src/NAnt.Core/Types/EnvironmentVariableCollection.cs0000644000175000017500000002517611757302273025002 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; namespace NAnt.Core.Types { /// /// Contains a collection of elements. /// [Serializable()] public class EnvironmentVariableCollection : CollectionBase { #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public EnvironmentVariableCollection() { } /// /// Initializes a new instance of the class /// with the specified instance. /// public EnvironmentVariableCollection(EnvironmentVariableCollection value) { AddRange(value); } /// /// Initializes a new instance of the class /// with the specified array of instances. /// public EnvironmentVariableCollection(EnvironmentVariable[] value) { AddRange(value); } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets the element at the specified index. /// /// The zero-based index of the element to get or set. [System.Runtime.CompilerServices.IndexerName("Item")] public EnvironmentVariable this[int index] { get {return ((EnvironmentVariable)(base.List[index]));} set {base.List[index] = value;} } /// /// Gets the with the specified name. /// /// The name of the to get. [System.Runtime.CompilerServices.IndexerName("Item")] public EnvironmentVariable this[string name] { get { if (name != null) { // try to locate instance by name foreach (EnvironmentVariable environmentVariable in base.List) { if (environmentVariable.VariableName == name) { return environmentVariable; } } } return null; } } #endregion Public Instance Properties #region Public Instance Methods /// /// Adds a to the end of the collection. /// /// The to be added to the end of the collection. /// The position into which the new element was inserted. public int Add(EnvironmentVariable item) { return base.List.Add(item); } /// /// Adds the elements of a array to the end of the collection. /// /// The array of elements to be added to the end of the collection. public void AddRange(EnvironmentVariable[] items) { for (int i = 0; (i < items.Length); i = (i + 1)) { Add(items[i]); } } /// /// Adds the elements of a to the end of the collection. /// /// The to be added to the end of the collection. public void AddRange(EnvironmentVariableCollection items) { for (int i = 0; (i < items.Count); i = (i + 1)) { Add(items[i]); } } /// /// Determines whether a is in the collection. /// /// The to locate in the collection. /// /// if is found in the /// collection; otherwise, . /// public bool Contains(EnvironmentVariable item) { return base.List.Contains(item); } /// /// Determines whether a with the specified /// value is in the collection. /// /// The argument value to locate in the collection. /// /// if a with value /// is found in the collection; otherwise, /// . /// public bool Contains(string value) { return this[value] != null; } /// /// Copies the entire collection to a compatible one-dimensional array, starting at the specified index of the target array. /// /// The one-dimensional array that is the destination of the elements copied from the collection. The array must have zero-based indexing. /// The zero-based index in at which copying begins. public void CopyTo(EnvironmentVariable[] array, int index) { base.List.CopyTo(array, index); } /// /// Retrieves the index of a specified object in the collection. /// /// The object for which the index is returned. /// /// The index of the specified . If the is not currently a member of the collection, it returns -1. /// public int IndexOf(EnvironmentVariable item) { return base.List.IndexOf(item); } /// /// Inserts a into the collection at the specified index. /// /// The zero-based index at which should be inserted. /// The to insert. public void Insert(int index, EnvironmentVariable item) { base.List.Insert(index, item); } /// /// Returns an enumerator that can iterate through the collection. /// /// /// A for the entire collection. /// public new EnvironmentVariableEnumerator GetEnumerator() { return new EnvironmentVariableEnumerator(this); } /// /// Removes a member from the collection. /// /// The to remove from the collection. public void Remove(EnvironmentVariable item) { base.List.Remove(item); } #endregion Public Instance Methods } /// /// Enumerates the elements of a . /// public class EnvironmentVariableEnumerator : IEnumerator { #region Internal Instance Constructors /// /// Initializes a new instance of the class /// with the specified . /// /// The collection that should be enumerated. internal EnvironmentVariableEnumerator(EnvironmentVariableCollection arguments) { IEnumerable temp = (IEnumerable) (arguments); _baseEnumerator = temp.GetEnumerator(); } #endregion Internal Instance Constructors #region Implementation of IEnumerator /// /// Gets the current element in the collection. /// /// /// The current element in the collection. /// public EnvironmentVariable Current { get { return (EnvironmentVariable) _baseEnumerator.Current; } } object IEnumerator.Current { get { return _baseEnumerator.Current; } } /// /// Advances the enumerator to the next element of the collection. /// /// /// if the enumerator was successfully advanced /// to the next element; if the enumerator has /// passed the end of the collection. /// public bool MoveNext() { return _baseEnumerator.MoveNext(); } bool IEnumerator.MoveNext() { return _baseEnumerator.MoveNext(); } /// /// Sets the enumerator to its initial position, which is before the /// first element in the collection. /// public void Reset() { _baseEnumerator.Reset(); } void IEnumerator.Reset() { _baseEnumerator.Reset(); } #endregion Implementation of IEnumerator #region Private Instance Fields private IEnumerator _baseEnumerator; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.Core/Types/DirSet.cs0000644000175000017500000000361111757302273020174 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using NAnt.Core.Attributes; namespace NAnt.Core.Types { /// /// A specialized used for specifying a set of /// directories. /// /// /// Hint for supporting tasks that the included directories instead of /// files should be used. /// [ElementName("dirset")] public class DirSet : FileSet, ICloneable { #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public DirSet() : base() { } /// /// Copy constructor for . Required in order to /// assign references of type where /// is used. /// /// A instance to create a from. public DirSet(FileSet fs) : base(fs) { } #endregion Public Instance Constructors } }nant-0.92-rc1/src/NAnt.Core/Types/ArgumentCollection.cs0000644000175000017500000002533311757302273022605 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; using System.Text; namespace NAnt.Core.Types { /// /// Contains a collection of elements. /// [Serializable()] public class ArgumentCollection : CollectionBase { #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public ArgumentCollection() { } /// /// Initializes a new instance of the class /// with the specified instance. /// public ArgumentCollection(ArgumentCollection value) { AddRange(value); } /// /// Initializes a new instance of the class /// with the specified array of instances. /// public ArgumentCollection(Argument[] value) { AddRange(value); } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets the element at the specified index. /// /// The zero-based index of the element to get or set. [System.Runtime.CompilerServices.IndexerName("Item")] public Argument this[int index] { get {return ((Argument)(base.List[index]));} set {base.List[index] = value;} } /// /// Gets the with the specified value. /// /// The value of the to get. [System.Runtime.CompilerServices.IndexerName("Item")] public Argument this[string value] { get { if (value != null) { // try to locate instance using value foreach (Argument argument in base.List) { if (argument.StringValue == value) { return argument; } } } return null; } } #endregion Public Instance Properties #region Override implementation of Object public override string ToString() { StringBuilder sb = new StringBuilder(); ToString (sb); return sb.ToString (); } #endregion Override implementation of Object #region Public Instance Methods /// /// Adds a to the end of the collection. /// /// The to be added to the end of the collection. /// The position into which the new element was inserted. public int Add(Argument item) { return base.List.Add(item); } /// /// Adds the elements of a array to the end of the collection. /// /// The array of elements to be added to the end of the collection. public void AddRange(Argument[] items) { for (int i = 0; (i < items.Length); i = (i + 1)) { Add(items[i]); } } /// /// Adds the elements of a to the end of the collection. /// /// The to be added to the end of the collection. public void AddRange(ArgumentCollection items) { for (int i = 0; (i < items.Count); i = (i + 1)) { Add(items[i]); } } /// /// Determines whether a is in the collection. /// /// The to locate in the collection. /// /// if is found in the /// collection; otherwise, . /// public bool Contains(Argument item) { return base.List.Contains(item); } /// /// Determines whether a with the specified /// value is in the collection. /// /// The argument value to locate in the collection. /// /// if a with value /// is found in the collection; otherwise, /// . /// public bool Contains(string value) { return this[value] != null; } /// /// Copies the entire collection to a compatible one-dimensional array, starting at the specified index of the target array. /// /// The one-dimensional array that is the destination of the elements copied from the collection. The array must have zero-based indexing. /// The zero-based index in at which copying begins. public void CopyTo(Argument[] array, int index) { base.List.CopyTo(array, index); } /// /// Retrieves the index of a specified object in the collection. /// /// The object for which the index is returned. /// /// The index of the specified . If the is not currently a member of the collection, it returns -1. /// public int IndexOf(Argument item) { return base.List.IndexOf(item); } /// /// Inserts a into the collection at the specified index. /// /// The zero-based index at which should be inserted. /// The to insert. public void Insert(int index, Argument item) { base.List.Insert(index, item); } /// /// Returns an enumerator that can iterate through the collection. /// /// /// A for the entire collection. /// public new ArgumentEnumerator GetEnumerator() { return new ArgumentEnumerator(this); } /// /// Removes a member from the collection. /// /// The to remove from the collection. public void Remove(Argument item) { base.List.Remove(item); } #endregion Public Instance Methods #region Internal Instance Methods internal void ToString(StringBuilder sb) { foreach (Argument arg in this) { if (arg.IfDefined && !arg.UnlessDefined) { if (sb.Length > 0) { sb.Append(' '); } sb.Append(arg.ToString()); } } } #endregion Internal Instance Methods } /// /// Enumerates the elements of a . /// public class ArgumentEnumerator : IEnumerator { #region Internal Instance Constructors /// /// Initializes a new instance of the class /// with the specified . /// /// The collection that should be enumerated. internal ArgumentEnumerator(ArgumentCollection arguments) { IEnumerable temp = (IEnumerable) (arguments); _baseEnumerator = temp.GetEnumerator(); } #endregion Internal Instance Constructors #region Implementation of IEnumerator /// /// Gets the current element in the collection. /// /// /// The current element in the collection. /// public Argument Current { get { return (Argument) _baseEnumerator.Current; } } object IEnumerator.Current { get { return _baseEnumerator.Current; } } /// /// Advances the enumerator to the next element of the collection. /// /// /// if the enumerator was successfully advanced /// to the next element; if the enumerator has /// passed the end of the collection. /// public bool MoveNext() { return _baseEnumerator.MoveNext(); } bool IEnumerator.MoveNext() { return _baseEnumerator.MoveNext(); } /// /// Sets the enumerator to its initial position, which is before the /// first element in the collection. /// public void Reset() { _baseEnumerator.Reset(); } void IEnumerator.Reset() { _baseEnumerator.Reset(); } #endregion Implementation of IEnumerator #region Private Instance Fields private IEnumerator _baseEnumerator; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.Core/Types/Proxy.cs0000644000175000017500000001205311757302273020123 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; using System.Net; using NAnt.Core.Attributes; using NAnt.Core.Util; namespace NAnt.Core.Types { /// /// Contains HTTP proxy settings used to process requests to Internet /// resources. /// [ElementName("proxy")] public class Proxy : DataTypeBase { #region Private Instance Fields private string _host; private int _port; private bool _bypassOnLocal; private Credential _credentials; private bool _ifDefined = true; private bool _unlessDefined; #endregion Private Instance Fields #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public Proxy() { } #endregion Public Instance Constructors #region Public Instance Properties /// /// The name of the proxy host. /// [TaskAttribute("host", Required=true)] [StringValidator(AllowEmpty=false)] public string Host { get { return _host; } set { _host = StringUtils.ConvertEmptyToNull(value); } } /// /// The port number on to use. /// [TaskAttribute("port", Required=true)] [Int32Validator()] public int Port { get { return _port; } set { _port = value; } } /// /// Specifies whether to bypass the proxy server for local addresses. /// The default is . /// [TaskAttribute("bypassonlocal", Required=false)] [BooleanValidator()] public bool BypassOnLocal { get { return _bypassOnLocal; } set { _bypassOnLocal = value; } } /// /// The credentials to submit to the proxy server for authentication. /// [BuildElement("credentials", Required=false)] public Credential Credentials { get { return _credentials; } set { _credentials = value; } } /// /// Indicates if the proxy should be used to connect to the external /// resource. If then the proxy will be used; /// otherwise, not. The default is . /// [TaskAttribute("if", Required=false)] [BooleanValidator()] public bool IfDefined { get { return _ifDefined; } set { _ifDefined = value; } } /// /// Indicates if the proxy should not be used to connect to the external /// resource. If then the proxy will be used; /// otherwise, not. The default is . /// [TaskAttribute("unless", Required=false)] [BooleanValidator()] public bool UnlessDefined { get { return _unlessDefined; } set { _unlessDefined = value; } } #endregion Public Instance Properties #region Public Instance Methods /// /// Gets a instance representing the current /// . /// /// /// A instance representing the current /// , or /// if this proxy should not be used to connect to the external resource. /// public IWebProxy GetWebProxy() { if (IfDefined && !UnlessDefined) { WebProxy proxy = new WebProxy(Host, Port); proxy.BypassProxyOnLocal = BypassOnLocal; // set authentication information if (Credentials != null) { proxy.Credentials = Credentials.GetCredential(); } return proxy; } else { // the global HTTP proxy return GlobalProxySelection.Select; } } #endregion Public Instance Methods } } nant-0.92-rc1/src/NAnt.Core/Types/RawXml.cs0000644000175000017500000000365711757302273020226 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Xml; namespace NAnt.Core.Types { /// /// Represents an element of which the XML is processed by its parent task /// or type. /// public class RawXml : Element { #region Public Instance Properties /// /// Gets the XML that this element represents. /// public XmlNode Xml { get { return base.XmlNode; } } #endregion Public Instance Properties #region Override implementation of Element /// /// Gets a value indicating whether the element is performing additional /// processing using the that was use to /// initialize the element. /// /// /// , as the XML that represents this build /// element is processed by the containing task or type. /// protected override bool CustomXmlProcessing { get { return true; } } #endregion Override implementation of Element } } nant-0.92-rc1/src/NAnt.Core/Types/EnvironmentVariable.cs0000644000175000017500000001602111757302273022753 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.IO; using NAnt.Core.Attributes; using NAnt.Core.Util; namespace NAnt.Core.Types { /// /// Represents an environment variable. /// [Serializable()] [ElementName("env")] public class EnvironmentVariable : Element { #region Private Instance Fields private string _name; private string _value; private string _literalValue; private FileInfo _file; private DirectoryInfo _directory; private PathSet _path; private bool _ifDefined = true; private bool _unlessDefined; #endregion Private Instance Fields /// /// Initializes a instance with the /// specified name and value. /// /// The name of the environment variable. /// The value of the environment variable. public EnvironmentVariable(string name, string value) { _name = name; _value = value; } /// /// Initializes a instance. /// public EnvironmentVariable() { } #region Public Instance Properties /// /// The name of the environment variable. /// [TaskAttribute("name", Required=true)] [StringValidator(AllowEmpty=false)] public string VariableName { get { return _name; } set { _name = value; } } /// /// The literal value for the environment variable. /// [TaskAttribute("value")] public string LiteralValue { get { return _literalValue; } set { _value = value; _literalValue = value; } } /// /// The value for a file-based environment variable. NAnt will convert /// it to an absolute filename. /// [TaskAttribute("file")] public FileInfo File { get { return _file; } set { _value = value.ToString(); _file = value; } } /// /// The value for a directory-based environment variable. NAnt will /// convert it to an absolute path. /// [TaskAttribute("dir")] public DirectoryInfo Directory { get { return _directory; } set { _value = value.ToString(); _directory = value; } } /// /// The value for a PATH like environment variable. You can use /// : or ; as path separators and NAnt will convert it to /// the platform's local conventions. /// [TaskAttribute("path")] public PathSet Path { get { return _path; } set { _value = value.ToString(); _path = value; } } /// /// Sets a single environment variable and treats it like a PATH - /// ensures the right separator for the local platform is used. /// [BuildElement("path")] public PathSet PathSet { get { return _path; } set { // check if path hasn't already been set using "path" attribute if (_path != null) { throw new BuildException("Either set the path using the \"path\"" + " attribute or the element. You cannot set both.", Location); } _value = value.ToString(); _path = value; } } /// /// Gets the value of the environment variable. /// public string Value { get { return _value; } } /// /// Indicates if the environment variable should be passed to the /// external program. If then the environment /// variable will be passed; otherwise, skipped. The default is /// . /// [TaskAttribute("if")] [BooleanValidator()] public bool IfDefined { get { return _ifDefined; } set { _ifDefined = value; } } /// /// Indicates if the environment variable should not be passed to the /// external program. If then the environment /// variable will be passed; otherwise, skipped. The default is /// . /// [TaskAttribute("unless")] [BooleanValidator()] public bool UnlessDefined { get { return _unlessDefined; } set { _unlessDefined = value; } } #endregion Public Instance Properties } /// /// A set of environment variables. /// [Serializable] [ElementName("environment")] public class EnvironmentSet : Element { #region Private Instance Fields private OptionCollection _options = new OptionCollection(); private EnvironmentVariableCollection _environmentVariables = new EnvironmentVariableCollection(); #endregion Private Instance Fields #region Public Instance Properties /// /// Environment variable to pass to a program. /// [BuildElementArray("option")] [Obsolete("Use element instead.")] public OptionCollection Options { get { return _options; } set { _options = value; } } /// /// Environment variable to pass to a program. /// [BuildElementArray("variable")] public EnvironmentVariableCollection EnvironmentVariables { get { return _environmentVariables; } set { _environmentVariables = value; } } #endregion Public Instance Properties } } nant-0.92-rc1/src/NAnt.Core/Types/Pattern.cs0000644000175000017500000000574611757302273020432 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2007 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using NAnt.Core; using NAnt.Core.Attributes; namespace NAnt.Core.Types { public class Pattern : Element { #region Private Instance Fields private string _patternName; private bool _ifDefined = true; private bool _unlessDefined; #endregion Private Instance Fields #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public Pattern() { } #endregion Public Instance Constructors #region Internal Instance Constructors internal Pattern(Project project, string patternName) { PatternName = patternName; Project = project; } #endregion Internal Instance Constructors #region Public Instance Properties /// /// The name pattern to include/exclude. /// [TaskAttribute("name", Required=true)] [StringValidator(AllowEmpty=false)] public virtual string PatternName { get { return _patternName; } set { _patternName = value; } } /// /// If then the pattern will be used; /// otherwise, skipped. The default is . /// [TaskAttribute("if", Required=false)] [BooleanValidator()] public bool IfDefined { get { return _ifDefined; } set { _ifDefined = value; } } /// /// If then the pattern will be used; /// otherwise, skipped. The default is . /// [TaskAttribute("unless", Required=false)] [BooleanValidator()] public bool UnlessDefined { get { return _unlessDefined; } set { _unlessDefined = value; } } #endregion Public Instance Properties #region Internal Instance Properties internal bool Enabled { get { return IfDefined && !UnlessDefined; } } #endregion Internal Instance Properties } } nant-0.92-rc1/src/NAnt.Core/Types/Argument.cs0000644000175000017500000002372511757302273020574 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; using System.Collections.Specialized; using System.IO; using System.Text; using NAnt.Core.Attributes; namespace NAnt.Core.Types { /// /// Represents a command-line argument. /// /// /// /// When passed to an external application, the argument will be quoted /// when appropriate. This does not apply to the /// parameter, which is always passed as is. /// /// /// /// /// A single command-line argument containing a space character. /// /// /// /// ]]> /// /// /// /// /// Two separate command-line arguments. /// /// /// /// ]]> /// /// /// /// /// A single command-line argument with the value \dir;\dir2;\dir3 /// on DOS-based systems and /dir:/dir2:/dir3 on Unix-like systems. /// /// /// /// ]]> /// /// [Serializable] [ElementName("arg")] public class Argument : Element { #region Private Instance Fields private FileInfo _file; private DirectoryInfo _directory; private PathSet _path; private string _value; private string _line; private bool _ifDefined = true; private bool _unlessDefined; #endregion Private Instance Fields #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public Argument() { } /// /// Initializes a new instance of the class /// with the specified command-line argument. /// public Argument(string value) { _value = value; } /// /// Initializes a new instance of the class /// with the given file. /// public Argument(FileInfo value) { _file = value; } /// /// Initializes a new instance of the class /// with the given path. /// public Argument(PathSet value) { _path = value; } #endregion Public Instance Constructors #region Override implementation of Object /// /// Returns the argument as a . /// /// /// The argument as a . /// /// /// File and individual path elements will be quoted if necessary. /// public override string ToString() { if (File != null) { return QuoteArgument(File.FullName); } else if (Directory != null) { return QuoteArgument(Directory.FullName); } else if (Path != null) { return QuoteArgument(Path.ToString()); } else if (Value != null) { return QuoteArgument(Value); } else if (Line != null) { return Line; } else { return string.Empty; } } #endregion Override implementation of Object #region Public Instance Properties /// /// A single command-line argument; can contain space characters. /// [TaskAttribute("value")] public string Value { get { return _value; } set { _value = value; } } /// /// The name of a file as a single command-line argument; will be /// replaced with the absolute filename of the file. /// [TaskAttribute("file")] public FileInfo File { get { return _file; } set { _file = value; } } /// /// The value for a directory-based command-line argument; will be /// replaced with the absolute path of the directory. /// [TaskAttribute("dir")] public DirectoryInfo Directory { get { return _directory; } set { _directory = value; } } /// /// The value for a PATH-like command-line argument; you can use /// : or ; as path separators and NAnt will convert it /// to the platform's local conventions, while resolving references to /// environment variables. /// /// /// Individual parts will be replaced with the absolute path, resolved /// relative to the project base directory. /// [TaskAttribute("path")] public PathSet Path { get { return _path; } set { // check if path hasn't already been set using element if (_path != null) { throw new BuildException("Either set the path using the \"path\"" + " attribute or the element. You cannot set both.", Location); } _path = value; } } /// /// Sets a single command-line argument and treats it like a PATH - ensures /// the right separator for the local platform is used. /// [BuildElement("path")] public PathSet PathSet { get { return _path; } set { // check if path hasn't already been set using "path" attribute if (_path != null) { throw new BuildException("Either set the path using the \"path\"" + " attribute or the element. You cannot set both.", Location); } _path = value; } } /// /// List of command-line arguments; will be passed to the executable /// as is. /// [TaskAttribute("line")] public string Line { get { return _line; } set { _line = value; } } /// /// Indicates if the argument should be passed to the external program. /// If then the argument will be passed; /// otherwise, skipped. The default is . /// [TaskAttribute("if")] [BooleanValidator()] public bool IfDefined { get { return _ifDefined; } set { _ifDefined = value; } } /// /// Indicates if the argument should not be passed to the external /// program. If then the argument will be /// passed; otherwise, skipped. The default is . /// [TaskAttribute("unless")] [BooleanValidator()] public bool UnlessDefined { get { return _unlessDefined; } set { _unlessDefined = value; } } #endregion Public Instance Properties #region Internal Instance Properties /// /// Gets string value corresponding with the argument. /// internal string StringValue { get { if (File != null) { return File.FullName; } else if (Directory != null) { return Directory.FullName; } else if (Path != null) { return Path.ToString(); } else if (Line != null) { return Line; } else { return Value; } } } #endregion Internal Instance Properties #region Private Static Methods /// /// Quotes a command line argument if it contains a single quote or a /// space. /// /// The command line argument. /// /// A quoted command line argument if /// contains a single quote or a space; otherwise, /// . /// private static string QuoteArgument(string argument) { if (argument.IndexOf("\"") > -1) { // argument is already quoted return argument; } else if (argument.IndexOf("'") > -1 || argument.IndexOf(" ") > -1) { // argument contains space and is not quoted, so quote it return '\"' + argument + '\"'; } else { return argument; } } #endregion Private Static Methods } } nant-0.92-rc1/src/NAnt.Core/Types/Formatter.cs0000644000175000017500000000544011757302273020747 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using NAnt.Core.Attributes; namespace NAnt.Core.Types { [ElementName("formatter")] public class Formatter : Element { #region Private Instance Fields private string _property; private string _pattern; private bool _ifDefined = true; private bool _unlessDefined; #endregion Private Instance Fields #region Public Instance Properties /// /// The name of the NAnt property to set. /// [TaskAttribute("property", Required=true)] [StringValidator(AllowEmpty=false)] public string Property { get { return _property; } set { _property= value; } } /// /// The string pattern to use to format the property. /// [TaskAttribute("pattern", Required=true)] [StringValidator(AllowEmpty=false)] public string Pattern { get { return _pattern; } set { _pattern= value; } } /// /// Indicates if the formatter should be used to format the timestamp. /// If then the formatter will be used; /// otherwise, skipped. The default is . /// [TaskAttribute("if")] [BooleanValidator()] public bool IfDefined { get { return _ifDefined; } set { _ifDefined = value; } } /// /// Indicates if the formatter should be not used to format the /// timestamp. If then the formatter will be /// used; otherwise, skipped. The default is . /// [TaskAttribute("unless")] [BooleanValidator()] public bool UnlessDefined { get { return _unlessDefined; } set { _unlessDefined = value; } } #endregion Public Instance Properties } } nant-0.92-rc1/src/NAnt.Core/Types/FormatterCollection.cs0000644000175000017500000002145411757302273022766 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; namespace NAnt.Core.Types { /// /// Contains a collection of elements. /// [Serializable()] public class FormatterCollection : CollectionBase { #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public FormatterCollection() { } /// /// Initializes a new instance of the class /// with the specified instance. /// public FormatterCollection(FormatterCollection value) { AddRange(value); } /// /// Initializes a new instance of the class /// with the specified array of instances. /// public FormatterCollection(Formatter[] value) { AddRange(value); } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets the element at the specified index. /// /// The zero-based index of the element to get or set. [System.Runtime.CompilerServices.IndexerName("Item")] public Formatter this[int index] { get {return ((Formatter)(base.List[index]));} set {base.List[index] = value;} } #endregion Public Instance Properties #region Public Instance Methods /// /// Adds a to the end of the collection. /// /// The to be added to the end of the collection. /// The position into which the new element was inserted. public int Add(Formatter item) { return base.List.Add(item); } /// /// Adds the elements of a array to the end of the collection. /// /// The array of elements to be added to the end of the collection. public void AddRange(Formatter[] items) { for (int i = 0; (i < items.Length); i = (i + 1)) { Add(items[i]); } } /// /// Adds the elements of a to the end of the collection. /// /// The to be added to the end of the collection. public void AddRange(FormatterCollection items) { for (int i = 0; (i < items.Count); i = (i + 1)) { Add(items[i]); } } /// /// Determines whether a is in the collection. /// /// The to locate in the collection. /// /// if is found in the /// collection; otherwise, . /// public bool Contains(Formatter item) { return base.List.Contains(item); } /// /// Copies the entire collection to a compatible one-dimensional array, starting at the specified index of the target array. /// /// The one-dimensional array that is the destination of the elements copied from the collection. The array must have zero-based indexing. /// The zero-based index in at which copying begins. public void CopyTo(Formatter[] array, int index) { base.List.CopyTo(array, index); } /// /// Retrieves the index of a specified object in the collection. /// /// The object for which the index is returned. /// /// The index of the specified . If the is not currently a member of the collection, it returns -1. /// public int IndexOf(Formatter item) { return base.List.IndexOf(item); } /// /// Inserts a into the collection at the specified index. /// /// The zero-based index at which should be inserted. /// The to insert. public void Insert(int index, Formatter item) { base.List.Insert(index, item); } /// /// Returns an enumerator that can iterate through the collection. /// /// /// A for the entire collection. /// public new FormatterEnumerator GetEnumerator() { return new FormatterEnumerator(this); } /// /// Removes a member from the collection. /// /// The to remove from the collection. public void Remove(Formatter item) { base.List.Remove(item); } #endregion Public Instance Methods } /// /// Enumerates the elements of a . /// public class FormatterEnumerator : IEnumerator { #region Internal Instance Constructors /// /// Initializes a new instance of the class /// with the specified . /// /// The collection that should be enumerated. internal FormatterEnumerator(FormatterCollection arguments) { IEnumerable temp = (IEnumerable) (arguments); _baseEnumerator = temp.GetEnumerator(); } #endregion Internal Instance Constructors #region Implementation of IEnumerator /// /// Gets the current element in the collection. /// /// /// The current element in the collection. /// public Formatter Current { get { return (Formatter) _baseEnumerator.Current; } } object IEnumerator.Current { get { return _baseEnumerator.Current; } } /// /// Advances the enumerator to the next element of the collection. /// /// /// if the enumerator was successfully advanced /// to the next element; if the enumerator has /// passed the end of the collection. /// public bool MoveNext() { return _baseEnumerator.MoveNext(); } bool IEnumerator.MoveNext() { return _baseEnumerator.MoveNext(); } /// /// Sets the enumerator to its initial position, which is before the /// first element in the collection. /// public void Reset() { _baseEnumerator.Reset(); } void IEnumerator.Reset() { _baseEnumerator.Reset(); } #endregion Implementation of IEnumerator #region Private Instance Fields private IEnumerator _baseEnumerator; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.Core/Types/XsltExtensionObject.cs0000644000175000017500000001252511757302273022764 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) // Tim Noll (tim.noll@gmail.com) using System; using System.Collections; using System.Globalization; using System.IO; using System.Reflection; using NAnt.Core.Attributes; using NAnt.Core.Util; namespace NAnt.Core.Types { /// /// Represents an XSLT extension object. The object should have a default /// parameterless constructor and the return value should be one of the /// four basic XPath data types of number, string, Boolean or node set. /// [ElementName("xsltextensionobject")] public class XsltExtensionObject : Element { #region Private Instance Fields private string _namespaceUri = string.Empty; private string _typeName; private FileInfo _assemblyPath; private bool _ifDefined = true; private bool _unlessDefined; #endregion Private Instance Fields #region Public Instance Constructors /// /// Initializes a new instance of the /// class. /// public XsltExtensionObject() { } #endregion Public Instance Constructors #region Public Instance Properties /// /// The namespace URI to associate with the extension object. /// /// /// The namespace URI to associate with the extension object, or /// if not set. /// [TaskAttribute("namespaceuri")] public string NamespaceUri { get { return _namespaceUri; } set { _namespaceUri = value; } } /// /// The full type name of the XSLT extension object. /// [TaskAttribute("typename", Required=true)] [StringValidator(AllowEmpty=false)] public string TypeName { get { return _typeName; } set { _typeName = value; } } /// /// The assembly which contains the XSLT extension object. /// [TaskAttribute("assembly", Required=true)] [StringValidator(AllowEmpty=false)] public FileInfo AssemblyPath { get { return _assemblyPath; } set { _assemblyPath = value; } } /// /// Indicates if the extension object should be added to the XSLT argument /// list. If then the extension object will be /// added; otherwise, skipped. The default is . /// [TaskAttribute("if")] [BooleanValidator()] public bool IfDefined { get { return _ifDefined; } set { _ifDefined = value; } } /// /// Indicates if the extension object should not be added to the XSLT argument /// list. If then the extension object will be /// added; otherwise, skipped. The default is . /// [TaskAttribute("unless")] [BooleanValidator()] public bool UnlessDefined { get { return _unlessDefined; } set { _unlessDefined = value; } } #endregion Public Instance Properties #region Public Instance Methods public object CreateInstance() { // test whether extension assembly exists if (!AssemblyPath.Exists) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1166"), AssemblyPath.FullName), Location); } // load extension object from assembly object extensionInstance = null; try { Assembly extensionAssembly = Assembly.LoadFrom(AssemblyPath.FullName); extensionInstance = extensionAssembly.CreateInstance(TypeName); if ( extensionInstance == null){ throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1168"), TypeName, AssemblyPath.FullName), Location ); } } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1167"), TypeName, AssemblyPath.FullName), Location, ex); } return extensionInstance; } #endregion } } nant-0.92-rc1/src/NAnt.Core/Types/PatternCollection.cs0000644000175000017500000002774611757302273022452 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; namespace NAnt.Core.Types { /// /// Contains a collection of elements. /// [Serializable()] public class PatternCollection : IList { #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public PatternCollection() { _list = new ArrayList (); } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets the element at the specified index. /// /// The zero-based index of the element to get or set. public Pattern this[int index] { get { return (Pattern) List[index] ;} set { List[index] = value; } } #endregion Public Instance Properties #region Private Instance Properties private ArrayList List { get { return _list; } } #endregion Private Instance Properties #region Implementation of ICollection public int Count { get { return List.Count; } } void ICollection.CopyTo (Array array, int index) { List.CopyTo(array, index); } bool ICollection.IsSynchronized { get { return List.IsSynchronized; } } object ICollection.SyncRoot { get { return List.SyncRoot; } } #endregion Implementation of ICollection #region Implementation of IEnumerable IEnumerator IEnumerable.GetEnumerator() { return List.GetEnumerator(); } #endregion Implementation of IEnumerable #region Implementation of IList object IList.this [int index] { get { return this [index]; } set { if (value == null) { throw new ArgumentNullException("value"); } if (!(value is Pattern)) { throw new ArgumentException ("Specified value is not an instance" + " of " + typeof (Pattern).FullName + "."); } this [index] = (Pattern) value; } } bool IList.IsFixedSize { get { return false; } } bool IList.IsReadOnly { get { return false; } } int IList.Add (object value) { if (value == null) { throw new ArgumentNullException ("value"); } if (!(value is Pattern)) { throw new ArgumentException ("Specified value is not an instance" + " of " + typeof (Pattern).FullName + "."); } return Add ((Pattern) value); } bool IList.Contains (object value) { if (value == null) { throw new ArgumentNullException("value"); } if (!(value is Pattern)) { throw new ArgumentException ("Specified value is not an instance" + " of " + typeof (Pattern).FullName + "."); } return Contains ((Pattern) value); } /// /// Removes all items from the . /// public void Clear () { List.Clear (); } int IList.IndexOf(object value) { if (value == null) { throw new ArgumentNullException("value"); } if (!(value is Pattern)) { throw new ArgumentException ("Specified value is not an instance" + " of " + typeof (Pattern).FullName + "."); } return IndexOf ((Pattern) value); } void IList.Insert(int index, object value) { if (value == null) { throw new ArgumentNullException("value"); } if (!(value is Pattern)) { throw new ArgumentException ("Specified value is not an instance" + " of " + typeof (Pattern).FullName + "."); } Insert(index, (Pattern) value); } void IList.Remove(object value) { if (value == null) { throw new ArgumentNullException("value"); } if (!(value is Pattern)) { throw new ArgumentException ("Specified value is not an instance" + " of " + typeof (Pattern).FullName + "."); } Remove((Pattern) value); } void IList.RemoveAt (int index) { List.RemoveAt(index); } #endregion Implementation of IList #region Public Instance Methods /// /// Adds a to the end of the collection. /// /// The to be added to the end of the collection. /// The position into which the new element was inserted. public int Add(Pattern item) { return List.Add(item); } /// /// Adds the elements of a array to the end of the collection. /// /// The array of elements to be added to the end of the collection. public void AddRange(Pattern[] items) { for (int i = 0; (i < items.Length); i = (i + 1)) { Add(items[i]); } } /// /// Adds the elements of a to the end of the collection. /// /// The to be added to the end of the collection. public void AddRange(PatternCollection items) { for (int i = 0; (i < items.Count); i = (i + 1)) { Add(items[i]); } } /// /// Determines whether a is in the collection. /// /// The to locate in the collection. /// /// if is found in the /// collection; otherwise, . /// public bool Contains(Pattern item) { return List.Contains(item); } /// /// Copies the entire collection to a compatible one-dimensional array, /// starting at the specified index of the target array. /// /// The one-dimensional array that is the destination of the elements copied from the collection. The array must have zero-based indexing. /// The zero-based index in at which copying begins. public void CopyTo(Pattern[] array, int index) { List.CopyTo(array, index); } /// /// Retrieves the index of a specified object in the collection. /// /// The object for which the index is returned. /// /// The index of the specified . If the is not currently a member of the collection, it returns -1. /// public int IndexOf(Pattern item) { return List.IndexOf(item); } /// /// Inserts a into the collection at the specified index. /// /// The zero-based index at which should be inserted. /// The to insert. public void Insert(int index, Pattern item) { List.Insert(index, item); } /// /// Returns an enumerator that can iterate through the collection. /// /// /// A for the entire collection. /// public PatternEnumerator GetEnumerator() { return new PatternEnumerator(this); } /// /// Removes a member from the collection. /// /// The to remove from the collection. public void Remove(Pattern item) { List.Remove(item); } #endregion Public Instance Methods #region Private Instance Fields private readonly ArrayList _list; #endregion Private Instance Fields } /// /// Enumerates the elements of a . /// public class PatternEnumerator : IEnumerator { #region Internal Instance Constructors /// /// Initializes a new instance of the class /// with the specified . /// /// The collection that should be enumerated. internal PatternEnumerator(PatternCollection arguments) { IEnumerable temp = (IEnumerable) (arguments); _baseEnumerator = temp.GetEnumerator(); } #endregion Internal Instance Constructors #region Implementation of IEnumerator /// /// Gets the current element in the collection. /// /// /// The current element in the collection. /// public Pattern Current { get { return (Pattern) _baseEnumerator.Current; } } /// /// Gets the current element in the collection. /// /// /// The current element in the collection. /// object IEnumerator.Current { get { return _baseEnumerator.Current; } } /// /// Advances the enumerator to the next element of the collection. /// /// /// if the enumerator was successfully advanced /// to the next element; if the enumerator has /// passed the end of the collection. /// public bool MoveNext() { return _baseEnumerator.MoveNext(); } /// /// Sets the enumerator to its initial position, which is before the /// first element in the collection. /// public void Reset() { _baseEnumerator.Reset(); } #endregion Implementation of IEnumerator #region Private Instance Fields private IEnumerator _baseEnumerator; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.Core/ExpressionParseException.cs0000644000175000017500000000502411757302273022707 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Jaroslaw Kowalski (jkowalski@users.sourceforge.net) using System; using System.IO; using System.Text; using System.Runtime.Serialization; namespace NAnt.Core { [Serializable] public class ExpressionParseException : Exception { private int _startPos = -1; private int _endPos = -1; public int StartPos { get { return _startPos; } } public int EndPos { get { return _endPos; } } public ExpressionParseException() : base () {} public ExpressionParseException(string message) : base(message, null) {} public ExpressionParseException(string message, Exception inner) : base(message, inner) {} protected ExpressionParseException(SerializationInfo info, StreamingContext context) : base(info, context) { _startPos = (int)info.GetValue("startPos", typeof(int)); _endPos = (int)info.GetValue("endPos", typeof(int)); } public ExpressionParseException(string message, int pos) : base(message, null) { _startPos = pos; _endPos = -1; } public ExpressionParseException(string message, int startPos, int endPos) : base(message, null) { _startPos = startPos; _endPos = endPos; } public ExpressionParseException(string message, int startPos, int endPos, Exception inner) : base(message, inner) { _startPos = startPos; _endPos = endPos; } public override void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("startPos", _startPos); info.AddValue("endPos", _endPos); base.GetObjectData(info, context); } } } nant-0.92-rc1/src/NAnt.Core/Resources/0000755000175000017500000000000011757310030017306 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.Core/Resources/ProjectHelp.xslt0000644000175000017500000000715211757302273022460 0ustar jtaylorjtaylor Default Target: Main Targets: Sub Targets: nant-0.92-rc1/src/NAnt.Core/Resources/Strings.resx0000644000175000017500000010557111757302273021665 0ustar jtaylorjtaylor text/microsoft-resx 1.0 System.Resources.ResXResourceReader System.Resources.ResXResourceWriter More than one '{0}' file found in '{1}' and no default.build exists. Error creating listener of type '{0}'. Error creating logger of type '{0}'. Could not find a '{0}' file in '{1}' Error creating output log file '{0}'. Could not load type {0}. Could not find a '{0}' file in directory tree. 'id' is an invalid attribute for a <{0}> tag. Datatypes 'refid' attribute is invalid for a <{0}> datatype declaration. 'id' is a required attribute for a <{0}> datatype declaration. Child element type {0} is not assignable to the type of the underlying array ({1} for property {2} for <{3} ... />. '{0}' is a required element of <{1} ... />. Attribute '{0}' for <{1} ... /> is deprecated. {2} '{0}' is a required framework configuration setting for <{1} ... />. BuildElementArrayAttribute cannot be applied to read-only array-based properties. '{0}' element for <{1} .../>. BuildElementArrayAttribute cannot be applied to read-only property with uninitialized collection-based value '{0}' element for <{1} ... />. BuildElementArrayAttribute cannot be applied to write-only collection-based properties. '{0}' element for >{1} .../<. Child element type {0} cannot be added to collection {1} for underlying property {2} for <{3} ... />. There must be a least one '{0}' element for <{1} .../>. '{0}' is not a valid value for attribute '{1}' of <{2} ... />. '{0}' is not a valid value for attribute '{1}' of <{2} ... />. Valid values are: {3}. BuildElementArrayAttribute and BuildElementCollectionAttribute should have an element type assigned that derives from Element for <{0} .../>. No name was assigned to the base element '{0}' for collection element {1} for <{2} .../>. Unexpected attribute "{0}" on element <{1}>. BuildElementCollectionAttribute cannot be applied to read-only property with uninitialized collection-based value '{0}' element for <{1} ... />. Use BuildElementArrayAttributes to have array like elements! There must be at most one '{0}' element for <{1} ... />. BuildElementArrayAttribute and BuildElementCollection attributes must be applied to array or collection-based types '{0}' element for <{1} .../>. <{0}> does not support the nested build element "{1}". '{0}' is a required attribute of <{1} ... />. Element <{0}... /> for <{1}... /> is deprecated. {2} Element Required! There must be a least one '{0}' element for <{1} ... />. Datatype references cannot contain an id attribute. {0} reference '{1}' not defined. Attempting to use a <{0}> reference where a <{1}> is required. <{0} ... /> does not support multiple '{1}' child elements. <{0} ... /> could not be initialized as its backed by type '{1}' which does not derive from Element. Property '{0}' for class '{1}' is backed by '{2}' which does not derive from '{3}'. Property {0} cannot return null (if there is no set method) for class {1}. DataType child element '{0}' in class '{1}' must define a set method. '{0}' is not a valid encoding. '{0}' encoding is not supported on the current platform. An empty string is not a valid value for attribute '{0}' of <{1} ... />. Operator '*' cannot be applied to arguments of type '{0}' and '{1}'. Operator '>' cannot be applied to arguments of type '{0}' and '{1}'. Operator '==' cannot be applied to arguments of type '{0}' and '{1}'. Operator '/' cannot be applied to arguments of type '{0}' and '{1}'. Unary minus not supported for arguments of type '{0}'. Operator '+' cannot be applied to arguments of type '{0}' and '{1}'. Operator '!=' cannot be applied to arguments of type '{0}' and '{1}'. Attempt to divide by zero. No overload for '{0}' takes '{1}' arguments. Cannot convert {0} to '{1}' (value was null). Operator '%' cannot be applied to arguments of type '{0}' and '{1}'. Operator '-' cannot be applied to arguments of type '{0}' and '{1}'. Operator '<=' cannot be applied to arguments of type '{0}' and '{1}'. Operator '>=' cannot be applied to arguments of type '{0}' and '{1}'. Operator '<' cannot be applied to arguments of type '{0}' and '{1}'. Unknown function '{0}'. Property '{0}' has not been set. Identifier cannot end with a dash or a dot: {0} The 'System.dll' assembly does not exist in framework assembly directory '{0}'. There is no version of Visual Studio .NET that corresponds with {0}. Root element in '{0}' must be named '{1}'. NAnt currently does not support this platform ({0}, ID = {1}). Invalid path '{0}'. The '{1}' scheme is not supported for paths. The NAnt configuration file does not contain a framework definition for the current runtime framework (family '{0}' clrversion '{1}'). The current runtime framework '{0}' is not correctly configured in the NAnt configuration file. Property name '{0}' is invalid. Property '{0}' already exists. Property value must be a string, was '{0}'. Property '{0}' does not exist. Read-only property "{0}" cannot be overwritten. Cannot resolve expanded value '{0}' of 'unless' attribute to a Boolean value. Cannot resolve expanded value '{0}' of 'if' attribute to a Boolean value. Invalid element <{0}>. Unknown task or datatype. Duplicate target named '{0}'! Configuration value {0} for task {1} was not considered valid by {2}. '{0}' is a required framework configuration setting for the '{1}' build element that should be set in the NAnt configuration file. {0} Generated Exception '{0}' is a required framework configuration setting for the '{1}' build element that should be set in the NAnt configuration file. Filter <{0}> is deprecated. {1} Unknown element <{0}>. Unknown filter <{0}>. Unknown task <{0}>. Type <{0}> is deprecated. {1} Task <{0}> is deprecated. {1} Function {0} is deprecated. {1} Cannot resolve '{0}' to boolean value. Cannot resolve '{0}' to DateTime value. Cannot resolve '{0}' to integer between '{1}' and '{2}'. Cannot resolve '{0}' to integer value. Cannot resolve '{0}' to a string value. BuildElementArrayAttribute cannot be applied to read-only property with uninitialized collection-based value '{0}' element for <{1} ... />. Child element type {0} cannot be added to collection {1} for underlying property {2} for <{3} ... />. Environment variable "{0}" does not exist. "{0}" is not a valid framework identifier. Target "{0}" does not exist. Property '{0}' has not been set. Task '{0}' is not available. Package "{0}" does not exist. Cannot set attributes for directory '{0}'. Cannot set attributes for file '{0}'. Unable to determine whether directory '{0}' is available. Unable to determine whether file '{0}' is available. The 'tofile' and 'todir' attribute cannot both be set. 'flatten' attribute requires that 'todir' has been set. The 'file' attribute and the <fileset> element Either the 'tofile' or 'todir' attribute should be set. The 'todir' should be set when using the <fileset> element Failed to create directory '{0}'. Cannot copy '{0}' to '{1}'. Could not find file '{0}' to copy. Cannot delete directory '{0}'. Cannot delete file '{0}'. Failed to write message to file '{0}'. '{0}' is not a valid value for attribute 'program' of <{1} ... />. External Program {0} did not finish within {1} milliseconds. External Program Failed: {0} (return code was {1}) The '{0}' task cannot be executed, as it relies on an active framework. '{0}' failed to start. The SDK for the '{0}' framework is not available or not configured. The framework directory for the '{0}' framework is not available or not configured. Unable to download '{0}' to '{1}'. PropertyTrue test failed for '{0}'. Build file '{0}' does not exist. Could not include build file '{0}'. The content of file '{0}' could not be loaded. Failure scanning "{0}" for extensions. Path "{0}" does not exist. Can't scan for extensions. Assembly "{0}" does not exist. Can't scan for extensions. Source file '{0}' does not exist. Source directory '{0}' does not exist. File '{0}' NOT added to message body. {1} File '{0}' NOT attached to message. {1} Directory '{0}' could not be created. Failed to move {0} to {1}. BuildElementArrayAttribute and BuildElementCollectionAttribute should have an element type assigned that derives from Element for {0}.{1}. The 'buildfile' attribute and the <buildfiles> element cannot be combined. Target framework could not be changed. "{0}" is not a valid framework identifier. {1} No match found for expression '{0}' in '{1}'. Invalid value "{0}" for "pattern" attribute. Failed setting environment variable "{0}" to "{1}". No source files indicated; use "in" or "infiles". The "out" attribute is not allowed when "infiles" is used. Stylesheet '{0}' does not exist. Unable to find source XML file '{0}'. Could not perform XSLT transformation of '{0}' using stylesheet '{1}'. Cannot touch file '{0}'. Could not peek at XML file '{0}'. XML file '{0}' does not exist. Failed to select node with XPath expression '{0}'. No matching nodes found for XPath expression '{0}'. Nodeindex '{0}' is out of range. Failed to load the XML document '{0}'. Could not poke at XML file '{0}'. Failed to select nodes with XPath expression '{0}'. Failed to save the XML document to '{0}'. The fileset specified is empty after scanning '{0}' for: {1} '{0}' list could not be opened. Assembly "{0}" does not exist. Can't create extension object. Can't create extension object "{0}" from "{1}". Failed to create extension object "{0}" from "{1}" Assembly.CreateInstance() returned null. Collection-based command-line argument '-{0}' has no strongly-typed Add method. Invalid value '{0}' for command-line argument '-{1}'. Command-line argument '-{0}' is collection-based, Duplicate value '{0}' for command-line argument '-{1}'. The signature of the Add method for the collection-based command-line argument '-{0}' is not supported. Duplicate property named '{0}' for command-line argument '{1}'. Duplicate command-line argument '-{0}'. Commandline argument '-{0}' is obsolete. {1} The default targetframework '{0}' is not valid. Defaulting to the runtime framework ({1}). Recursive includes are not allowed. Task not allowed in targets. Must be at project level. Validating <{1} {2}='...'> with {0} Abstract type: {0} for {2}.{1} Found {0} <attribute> for {1} Skipping {0} <attribute> for {1} Setting value: {2}.{0} = {1} Total time: {0} seconds. BUILD SUCCEEDED - {0} non-fatal error(s), {1} warning(s) BUILD FAILED - {0} non-fatal error(s), {1} warning(s) Adding Target '{0}' Task.Execute() for '{0}' Adding data type '{0}' from {1}:{2} Creating DataTypeBaseBuilder for {0} Adding task '{0}' from {1}:{2} Creating TaskBuilder for {0} Cannot read past end of stream. End of output has been reached. Peek currently is not supported. One or more tokens and replacement values should be specified. A base filter must be used. Starting '{1} ({2})' in '{0}' Duplicate include of file '{0}'. Including file {0}. NAnt schema generated at {0} Valid values are: {0}. {0} {1} (Build {2}; {3}; {4}) nant-0.92-rc1/src/NAnt.Core/FunctionSetBase.cs0000644000175000017500000000343311757302273020734 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian MacLean (imaclean@gmail.com) using System; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Types; namespace NAnt.Core { public abstract class FunctionSetBase { #region Protected Instance Constructors protected FunctionSetBase(Project project, PropertyDictionary properties) { _project = project; } #endregion Protected Instance Constructors #region Public Instance Properties /// /// Gets or sets the that this functionset will /// reference. /// /// /// The that this functionset will reference. /// public virtual Project Project { get { return _project; } set { _project = value; } } #endregion Public Instance Properties #region Private Instance Fields private Project _project; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.Core/Util/0000755000175000017500000000000011757310030016251 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.Core/Util/DateTimeProvider.cs0000644000175000017500000000174411757302273022027 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2005 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Owen Rogers (exortech@gmail.com) using System; namespace NAnt.Core.Util { public class DateTimeProvider { public virtual DateTime Now { get { return DateTime.Now; } } } }nant-0.92-rc1/src/NAnt.Core/Util/CommandLineParser.cs0000644000175000017500000005307611757302273022170 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Collections; using System.Collections.Specialized; using System.Text; namespace NAnt.Core.Util { /// /// Commandline parser. /// public class CommandLineParser { #region Public Instance Constructors /// /// Initializes a new instance of the class /// using possible arguments deducted from the specific . /// /// The from which the possible command-line arguments should be retrieved. /// A value indicating whether or not a response file is able to be used. /// is a null reference. public CommandLineParser(Type argumentSpecification, bool supportsResponseFile ) { if (argumentSpecification == null) { throw new ArgumentNullException("argumentSpecification"); } _argumentCollection = new CommandLineArgumentCollection(); foreach (PropertyInfo propertyInfo in argumentSpecification.GetProperties(BindingFlags.Instance | BindingFlags.Public)) { if (propertyInfo.CanWrite || typeof(ICollection).IsAssignableFrom(propertyInfo.PropertyType)) { CommandLineArgumentAttribute attribute = GetCommandLineAttribute(propertyInfo); if (attribute is DefaultCommandLineArgumentAttribute) { Debug.Assert(_defaultArgument == null); _defaultArgument = new CommandLineArgument(attribute, propertyInfo); } else if (attribute != null) { _argumentCollection.Add(new CommandLineArgument(attribute, propertyInfo)); } } } _argumentSpecification = argumentSpecification; _supportsResponseFile = supportsResponseFile; } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets a logo banner using version and copyright attributes defined on the /// or the /// . /// /// /// A logo banner. /// public virtual string LogoBanner { get { string productName; string informationalVersion; Version assemblyVersion; string configurationInformation = null; string copyrightInformation = null; string companyInformation = null; DateTime releaseDate; Assembly assembly = Assembly.GetEntryAssembly(); if (assembly == null) { assembly = Assembly.GetCallingAssembly(); } // get product name object[] productAttributes = assembly.GetCustomAttributes(typeof(AssemblyProductAttribute), false); if (productAttributes.Length > 0) { AssemblyProductAttribute productAttribute = (AssemblyProductAttribute) productAttributes[0]; productName = productAttribute.Product; } else { productName = assembly.GetName().Name; } // get informational version object[] informationalVersionAttributes = assembly.GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false); if (informationalVersionAttributes.Length > 0) { AssemblyInformationalVersionAttribute informationalVersionAttribute = (AssemblyInformationalVersionAttribute) informationalVersionAttributes[0]; informationalVersion = informationalVersionAttribute.InformationalVersion; } else { FileVersionInfo info = FileVersionInfo.GetVersionInfo(assembly.Location); informationalVersion = info.FileMajorPart + "." + info.FileMinorPart + "." + info.FileBuildPart + "." + info.FilePrivatePart; } // get assembly version assemblyVersion = assembly.GetName().Version; // determine release date using build number of assembly // version (specified as number of days passed since 1/1/2000) releaseDate = new DateTime(2000, 1, 1).AddDays(assemblyVersion.Build); // get configuration information object[] configurationAttributes = assembly.GetCustomAttributes(typeof(AssemblyConfigurationAttribute), false); if (configurationAttributes.Length > 0) { AssemblyConfigurationAttribute configurationAttribute = (AssemblyConfigurationAttribute) configurationAttributes[0]; configurationInformation = configurationAttribute.Configuration; } // get copyright information object[] copyrightAttributes = assembly.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false); if (copyrightAttributes.Length > 0) { AssemblyCopyrightAttribute copyrightAttribute = (AssemblyCopyrightAttribute) copyrightAttributes[0]; copyrightInformation = copyrightAttribute.Copyright; } // get company information object[] companyAttributes = assembly.GetCustomAttributes(typeof(AssemblyCompanyAttribute), false); if (companyAttributes.Length > 0) { AssemblyCompanyAttribute companyAttribute = (AssemblyCompanyAttribute) companyAttributes[0]; companyInformation = companyAttribute.Company; } StringBuilder logoBanner = new StringBuilder(); logoBanner.AppendFormat(CultureInfo.InvariantCulture, ResourceUtils.GetString("String_BuildBanner"), productName, informationalVersion, assemblyVersion.ToString(4), configurationInformation, releaseDate.ToShortDateString()); // output copyright information if (!String.IsNullOrEmpty(copyrightInformation)) { logoBanner.Append(Environment.NewLine); logoBanner.Append(copyrightInformation); } // output company information if (!String.IsNullOrEmpty(companyInformation)) { logoBanner.Append(Environment.NewLine); logoBanner.Append(companyInformation); } return logoBanner.ToString(); } } /// /// Gets the usage instructions. /// /// The usage instructions. public virtual string Usage { get { StringBuilder helpText = new StringBuilder(); Assembly assembly = Assembly.GetEntryAssembly(); if (assembly == null) { assembly = Assembly.GetCallingAssembly(); } // Add usage instructions to helptext if (helpText.Length > 0) { helpText.Append(Environment.NewLine); } helpText.Append("Usage : " + assembly.GetName().Name + " [options]"); if (_defaultArgument != null) { helpText.Append(" <" + _defaultArgument.LongName + ">"); if (_defaultArgument.AllowMultiple) { helpText.Append(" <" + _defaultArgument.LongName + ">"); helpText.Append(" ..."); } } helpText.Append(Environment.NewLine); // Add options to helptext helpText.Append("Options : "); helpText.Append(Environment.NewLine); helpText.Append(Environment.NewLine); foreach (CommandLineArgument argument in _argumentCollection) { string valType = ""; if (argument.ValueType == typeof(string)) { valType = ":"; } else if (argument.ValueType == typeof(bool)) { valType = "[+|-]"; } else if (argument.ValueType == typeof(FileInfo)) { valType = ":"; } else if (argument.ValueType == typeof(int)) { valType = ":"; } else if (argument.IsNameValueCollection) { valType = ":="; } else { valType = ":" + argument.ValueType.FullName; } string optionName = argument.LongName; if (argument.ShortName != null) { if (argument.LongName.StartsWith(argument.ShortName)) { optionName = optionName.Insert(argument.ShortName.Length, "[") + "]"; } helpText.AppendFormat(CultureInfo.InvariantCulture, " -{0,-30}{1}", optionName + valType, argument.Description); if (!optionName.StartsWith(argument.ShortName)) { helpText.AppendFormat(CultureInfo.InvariantCulture, " (Short format: /{0})", argument.ShortName); } } else { helpText.AppendFormat(CultureInfo.InvariantCulture, " -{0,-30}{1}", optionName + valType, argument.Description); } helpText.Append(Environment.NewLine); } if (_supportsResponseFile) { helpText.AppendFormat(CultureInfo.InvariantCulture, " {0,-31}{1}", "@", "Insert command-line settings from a text file."); helpText.Append(Environment.NewLine); } return helpText.ToString(); } } /// /// Gets a value indicating whether no arguments were specified on the /// command line. /// public bool NoArgs { get { foreach(CommandLineArgument argument in _argumentCollection) { if (argument.SeenValue) { return true; } } if (_defaultArgument != null) { return _defaultArgument.SeenValue; } return false; } } #endregion Public Instance Properties #region Public Instance Methods /// /// Parses an argument list. /// /// The arguments to parse. /// The destination object on which properties will be set corresponding to the specified arguments. /// is a null reference. /// The of does not match the argument specification that was used to initialize the parser. public void Parse(string[] args, object destination) { if (destination == null) { throw new ArgumentNullException("destination"); } if (!_argumentSpecification.IsAssignableFrom(destination.GetType())) { throw new ArgumentException("Type of destination does not match type of argument specification."); } ParseArgumentList(args); // check for missing required arguments foreach (CommandLineArgument arg in _argumentCollection) { arg.Finish(destination); } if (_defaultArgument != null) { _defaultArgument.Finish(destination); } } #endregion Public Instance Methods #region Private Instance Methods /// /// Splits a string and removes any empty strings from the /// result. Same functionality as the /// public string[] Split(char[] separator, StringSplitOptions options) /// method in .Net 2.0. Replace with that call when 2.0 is standard. /// /// /// /// the array of strings string[] ParseArguments(string sourceString, char[] delimiters) { bool inQuotedArgument = false; StringBuilder arg = new StringBuilder (); StringCollection arguments = new StringCollection(); foreach (char c in sourceString) { if (c == '"') { inQuotedArgument = !inQuotedArgument; continue; } if (!inQuotedArgument && IsDelimiter(c, delimiters)) { if (arg.Length > 0) { arguments.Add (arg.ToString ()); arg.Length = 0; } } else { arg.Append (c); } } if (arg.Length > 0) { arguments.Add (arg.ToString ()); } string[] result = new string[arguments.Count]; arguments.CopyTo(result, 0); return result; } private static bool IsDelimiter(char c, char[] delimiters) { foreach (char delimiter in delimiters) { if (c == delimiter) { return true; } } return false; } /// /// Read a response file and parse the arguments as usual. /// /// The response file to load arguments private void ProcessResponseFile(string file) { char[] whitespaceChars = new char[] {' ', '\t'}; StringCollection argsCol = new StringCollection(); using (StreamReader sr = new StreamReader(file, Encoding.Default, true)) { String line; // Read and concat lines from the file until the end of // the file is reached. while ((line = sr.ReadLine()) != null) { line = line.Trim(whitespaceChars); if (!line.StartsWith("#")) { argsCol.AddRange(ParseArguments(line, whitespaceChars)); } } string[] args = new string[argsCol.Count]; argsCol.CopyTo(args, 0); //parse as a regular argument list. ParseArgumentList(args); } } /// /// Parse the argument list using the /// /// private void ParseArgumentList(string[] args) { if (args == null) { return; } foreach (string argument in args) { if (argument.Length == 0) { continue; } switch (argument[0]) { case '-': case '/': int endIndex = argument.IndexOfAny(new char[] {':', '+', '-'}, 1); string option = argument.Substring(1, endIndex == -1 ? argument.Length - 1 : endIndex - 1); string optionArgument; if (option.Length + 1 == argument.Length) { optionArgument = null; } else if (argument.Length > 1 + option.Length && argument[1 + option.Length] == ':') { optionArgument = argument.Substring(option.Length + 2); } else { optionArgument = argument.Substring(option.Length + 1); } CommandLineArgument arg = _argumentCollection[option]; if (arg == null) { throw new CommandLineArgumentException(string.Format(CultureInfo.InvariantCulture, "Unknown argument '{0}'", argument)); } else { // check if argument is obsolete Attribute[] attribs = (Attribute[]) arg.Property.GetCustomAttributes( typeof(ObsoleteAttribute), false); if (attribs.Length > 0) { ObsoleteAttribute obsoleteAttrib = (ObsoleteAttribute) attribs[0]; string message = string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1177"), option, obsoleteAttrib.Message); if (obsoleteAttrib.IsError) { throw new CommandLineArgumentException(message); } else { Console.WriteLine(string.Empty); Console.WriteLine("Warning: " + message); Console.WriteLine(string.Empty); } } if (arg.IsExclusive && args.Length > 1) { throw new CommandLineArgumentException(string.Format(CultureInfo.InvariantCulture, "Commandline argument '-{0}' cannot be combined with other arguments.", arg.LongName)); } else { arg.SetValue(optionArgument); } } break; case '@': if (_supportsResponseFile) { string responseFile = argument.Substring(1, argument.Length - 1); if (!File.Exists(responseFile)) { throw new CommandLineArgumentException(string.Format(CultureInfo.InvariantCulture, "Unable to open response file '{0}'.", responseFile)); } // load file and parse it. ProcessResponseFile(responseFile); break; } continue; default: if (_defaultArgument != null) { _defaultArgument.SetValue(argument); } else { throw new CommandLineArgumentException(string.Format(CultureInfo.InvariantCulture, "Unknown argument '{0}'", argument)); } break; } } } #endregion Private Instance Methods #region Private Static Methods /// /// Returns the that's applied /// on the specified property. /// /// The property of which applied should be returned. /// /// The that's applied to the /// , or a null reference if none was applied. /// private static CommandLineArgumentAttribute GetCommandLineAttribute(PropertyInfo propertyInfo) { object[] attributes = propertyInfo.GetCustomAttributes(typeof(CommandLineArgumentAttribute), false); if (attributes.Length == 1) return (CommandLineArgumentAttribute) attributes[0]; Debug.Assert(attributes.Length == 0); return null; } #endregion Private Static Methods #region Private Instance Fields private CommandLineArgumentCollection _argumentCollection; private CommandLineArgument _defaultArgument; private Type _argumentSpecification; private bool _supportsResponseFile; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.Core/Util/StringUtils.cs0000644000175000017500000001532211757302273021104 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections.Specialized; namespace NAnt.Core.Util { /// /// Groups a set of useful manipulation and validation /// methods. /// public sealed class StringUtils { #region Private Instance Constructors /// /// Initializes a new instance of the class. /// /// /// Prevents instantiation of the class. /// private StringUtils() { } #endregion Private Instance Constructors #region Public Static Methods /// /// Determines whether the last character of the given /// matches the specified character. /// /// The string. /// The character. /// /// if the last character of /// matches ; otherwise, . /// /// is . [Obsolete ("StringUtils.EndsWith method is depreciated. Use string.EndsWith(string) instead.")] public static bool EndsWith(string value, char c) { if (value == null) throw new ArgumentNullException("value"); int stringLength = value.Length; if ((stringLength != 0) && (value[stringLength - 1] == c)) { return true; } return false; } /// /// Indicates whether or not the specified is /// or an string. /// /// The value to check. /// /// if is /// or an empty string (""); otherwise, . /// [Obsolete ("StringUtils.IsNullOrEmpty method is depreciated. Use System.String.IsNullOrEmpty(string) instead.")] public static bool IsNullOrEmpty(string value) { return (value == null || value.Length == 0); } /// /// Converts an empty string ("") to . /// /// The value to convert. /// /// if is an empty /// string ("") or ; otherwise, . /// public static string ConvertEmptyToNull(string value) { if (!String.IsNullOrEmpty(value)) return value; return null; } /// /// Converts to an empty string. /// /// The value to convert. /// /// An empty string if is ; /// otherwise, . /// public static string ConvertNullToEmpty(string value) { if (value == null) return string.Empty; return value; } /// /// Concatenates a specified separator between each /// element of a specified , yielding a /// single concatenated string. /// /// A . /// A . /// /// A consisting of the elements of /// interspersed with the separator string. /// /// /// /// For example if is ", " and the elements /// of are "apple", "orange", "grape", and "pear", /// returns "apple, orange, /// grape, pear". /// /// /// If is , an empty /// string () is used instead. /// /// public static string Join(string separator, StringCollection value) { if (value == null) throw new ArgumentNullException("value"); if (separator == null) separator = string.Empty; // create with size equal to number of elements in collection string[] elements = new string[value.Count]; // copy elements in collection to array value.CopyTo(elements, 0); // concatenate specified separator between each elements return string.Join(separator, elements); } /// /// Creates a shallow copy of the specified . /// /// The that should be copied. /// /// A shallow copy of the specified . /// public static StringCollection Clone(StringCollection stringCollection) { string[] strings = new string[stringCollection.Count]; stringCollection.CopyTo(strings, 0); StringCollection clone = new StringCollection(); clone.AddRange(strings); return clone; } #endregion Public Static Methods } } nant-0.92-rc1/src/NAnt.Core/Util/CommandLineArgumentException.cs0000644000175000017500000000577311757302273024376 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Runtime.Serialization; namespace NAnt.Core.Util { /// /// The exception that is thrown when one of the command-line arguments provided /// is not valid. /// [Serializable()] public sealed class CommandLineArgumentException : ArgumentException { #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public CommandLineArgumentException() : base() { } /// /// Initializes a new instance of the class /// with a descriptive message. /// /// A descriptive message to include with the exception. public CommandLineArgumentException(string message) : base(message) { } /// /// Initializes a new instance of the class /// with a descriptive message and an inner exception. /// /// A descriptive message to include with the exception. /// A nested exception that is the cause of the current exception. public CommandLineArgumentException(string message, Exception innerException) : base(message, innerException) { } #endregion Public Instance Constructors #region Private Instance Constructors /// /// Initializes a new instance of the class /// with serialized data. /// /// The that holds the serialized object data about the exception being thrown. /// The that contains contextual information about the source or destination. private CommandLineArgumentException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endregion Private Instance Constructors } } nant-0.92-rc1/src/NAnt.Core/Util/FileUtils.cs0000644000175000017500000007154211757302273020523 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using NAnt.Core.Filters; using NAnt.Core.Types; namespace NAnt.Core.Util { /// /// Provides modified version for Copy and Move from the File class that /// allow for filter chain processing. /// public static class FileUtils { #region Private Static Fields /// /// Constant buffer size for copy/move functions. /// /// Default value is 8k private const int _bufferSize = 8192; #endregion Private Static Fields #region Public Static Methods /// /// Copies a file filtering its content through the filter chain. /// /// /// The file to copy /// /// /// The file to copy to /// /// /// Chain of filters to apply when copying, or is no /// filters should be applied. /// /// /// The encoding used to read the soure file. /// /// /// The encoding used to write the destination file. /// public static void CopyFile( string sourceFileName, string destFileName, FilterChain filterChain, Encoding inputEncoding, Encoding outputEncoding) { // If the source file does not exist, throw an exception. if (!File.Exists(sourceFileName)) { throw new BuildException( String.Format("Cannot copy file: Source File {0} does not exist", sourceFileName)); } // determine if filters are available bool filtersAvailable = !FilterChain.IsNullOrEmpty(filterChain); // if no filters have been defined, and no input or output encoding // is set, we can just use the File.Copy method if (!filtersAvailable && inputEncoding == null && outputEncoding == null) { File.Copy(sourceFileName, destFileName, true); } else { // determine actual input encoding to use. if no explicit input // encoding is specified, we'll use the system's current ANSI // code page Encoding actualInputEncoding = (inputEncoding != null) ? inputEncoding : Encoding.Default; // get base filter built on the file's reader. // Use the value of _bufferSize as the buffer size. using (StreamReader sourceFileReader = new StreamReader(sourceFileName, actualInputEncoding, true, _bufferSize)) { Encoding actualOutputEncoding = outputEncoding; if (actualOutputEncoding == null) { // if no explicit output encoding is specified, we'll // just use the encoding of the input file as determined // by the runtime // // Note : the input encoding as specified on the filterchain // might not match the current encoding of the streamreader // // eg. when specifing an ANSI encoding, the runtime might // still detect the file is using UTF-8 encoding, because // we use BOM detection actualOutputEncoding = sourceFileReader.CurrentEncoding; } // writer for destination file using (StreamWriter destFileWriter = new StreamWriter(destFileName, false, actualOutputEncoding, _bufferSize)) { if (filtersAvailable) { Filter baseFilter = filterChain.GetBaseFilter(new PhysicalTextReader(sourceFileReader)); bool atEnd = false; int character; while (!atEnd) { character = baseFilter.Read(); if (character > -1) { destFileWriter.Write((char)character); } else { atEnd = true; } } } else { char[] buffer = new char[_bufferSize]; while (true) { int charsRead = sourceFileReader.Read(buffer, 0, buffer.Length); if (charsRead == 0) { break; } destFileWriter.Write(buffer, 0, charsRead); } } } } } } /// /// Moves a file filtering its content through the filter chain. /// /// /// The file to move. /// /// /// The file to move move to. /// /// /// Chain of filters to apply when moving, or is no /// filters should be applied. /// /// /// The encoding used to read the soure file. /// /// /// The encoding used to write the destination file. /// public static void MoveFile( string sourceFileName, string destFileName, FilterChain filterChain, Encoding inputEncoding, Encoding outputEncoding) { // If the source file does not exist, throw an exception. if (!File.Exists(sourceFileName)) { throw new BuildException( String.Format("Cannot move file: Source File {0} does not exist", sourceFileName)); } // if no filters have been defined, and no input or output encoding // is set, we can just use the File.Move method if (FilterChain.IsNullOrEmpty(filterChain) && inputEncoding == null && outputEncoding == null) { File.Move(sourceFileName, destFileName); } else { CopyFile(sourceFileName, destFileName, filterChain, inputEncoding, outputEncoding); File.Delete(sourceFileName); } } /// /// Copies a directory while filtering its file content through the filter chain. /// /// /// Source directory to copy from. /// /// /// Destination directory to copy to. /// /// /// Chain of filters to apply when copying, or is no /// filters should be applied. /// /// /// The encoding used to read the soure file. /// /// /// The encoding used to write the destination file. /// internal static void CopyDirectory( string sourceDirectory, string destDirectory, FilterChain filterChain, Encoding inputEncoding, Encoding outputEncoding) { // If the source directory does not exist, throw an exception. if (!Directory.Exists(sourceDirectory)) { throw new BuildException( String.Format("Cannot copy directory: Source Directory {0} does not exist", sourceDirectory) ); } // Create the destination directory if it does not exist. if (!Directory.Exists(destDirectory)) { Directory.CreateDirectory(destDirectory); } // Copy all of the files to the destination directory using // the CopyFile static method. foreach (string file in Directory.GetFiles(sourceDirectory)) { string targetFile = CombinePaths(destDirectory, Path.GetFileName(file)); CopyFile(file, targetFile, filterChain, inputEncoding, outputEncoding); } // Copy all of the subdirectory information by calling this method again. foreach (string dir in Directory.GetDirectories(sourceDirectory)) { string targetDir = CombinePaths(destDirectory, Path.GetFileName(dir)); CopyDirectory(dir, targetDir, filterChain, inputEncoding, outputEncoding); } } /// /// Moves a directory while filtering its file content through the filter chain. /// /// /// Source directory to move from. /// /// /// Destination directory to move to. /// /// /// Chain of filters to apply when copying, or is no /// filters should be applied. /// /// /// The encoding used to read the soure file. /// /// /// The encoding used to write the destination file. /// internal static void MoveDirectory( string sourceDirectory, string destDirectory, FilterChain filterChain, Encoding inputEncoding, Encoding outputEncoding) { // If the source directory does not exist, throw an exception. if (!Directory.Exists(sourceDirectory)) { throw new BuildException( String.Format("Cannot move directory: Source Directory {0} does not exist", sourceDirectory)); } // if no filters have been defined, and no input or output encoding // is set, proceed with a straight directory move. if (FilterChain.IsNullOrEmpty(filterChain) && inputEncoding == null && outputEncoding == null) { // If the source & target paths are completely the same, including // case, throw an exception. if (sourceDirectory.Equals(destDirectory, StringComparison.InvariantCulture)) { throw new BuildException("Source and Target paths are identical"); } try { // wants to rename a directory with the same name but different casing // (ie: C:\nant to C:\NAnt), then the move needs to be staged. if (PlatformHelper.IsWindows) { // If the directory names are the same but different casing, stage // the move by moving the source directory to a temp location // before moving it to the destination. if (sourceDirectory.Equals(destDirectory, StringComparison.InvariantCultureIgnoreCase)) { // Since the directory is being renamed with different // casing, the temp directory should be in the same // location as the destination directory to avoid // possible different volume errors. string rootPath = Directory.GetParent(destDirectory).FullName; string stagePath = Path.Combine(rootPath, Path.GetRandomFileName()); try { // Move the source dir to the stage path // before moving everything to the destination // path. Directory.Move(sourceDirectory, stagePath); Directory.Move(stagePath, destDirectory); } catch { // If an error occurred during the staged directory // move, check to see if the stage path exists. If // the source directory successfully moved to the // stage path, move the stage path back to the // source path and rethrow the exception. if (Directory.Exists(stagePath)) { if (!Directory.Exists(sourceDirectory)) { Directory.Move(stagePath, sourceDirectory); } } throw; } } // If the directory source and destination names are // different, use Directory.Move. else { Directory.Move(sourceDirectory, destDirectory); } } // Non-Windows systems, such as Linux/Unix, filenames and directories // are case-sensitive. So as long as the directory names are not // identical, with the check above, the Directory.Move method // can be used. else { Directory.Move(sourceDirectory, destDirectory); } } // Catch and rethrow any IO exceptions that may arise during // the directory move. catch (IOException ioEx) { // If the error occurred because the destination directory // exists, throw a build exception to tell the user that the // destination directory already exists. if (Directory.Exists(destDirectory)) { throw new BuildException( string.Format(CultureInfo.InvariantCulture, "Failed to move directory {0}." + "Directory '{1}' already exists.", sourceDirectory, destDirectory)); } // Any other IOExceptions should be displayed to the user // via build exception. else { throw new BuildException( String.Format("Unhandled IOException when trying to move directory '{0}' to '{1}'", sourceDirectory, destDirectory), ioEx); } } } else { // Otherwise, use the copy directory method and directory.delete // method to move the directory over. CopyDirectory(sourceDirectory, destDirectory, filterChain, inputEncoding, outputEncoding); Directory.Delete(sourceDirectory, true); } } /// /// Generates a new temporary directory name based on the system's /// temporary path. /// /// /// The temp directory name. /// internal static string GetTempDirectoryName() { return CombinePaths(Path.GetTempPath(), Path.GetRandomFileName()); } /// /// Reads a file filtering its content through the filter chain. /// /// The file to read. /// Chain of filters to apply when reading, or is no filters should be applied. /// The encoding used to read the file. /// /// If is , /// then the system's ANSI code page will be used to read the file. /// public static string ReadFile(string fileName, FilterChain filterChain, Encoding inputEncoding) { string content = null; // determine character encoding to use Encoding encoding = (inputEncoding != null) ? inputEncoding : Encoding.Default; // read file using (StreamReader sr = new StreamReader(fileName, encoding, true)) { if (filterChain == null || filterChain.Filters.Count == 0) { content = sr.ReadToEnd(); } else { Filter baseFilter = filterChain.GetBaseFilter( new PhysicalTextReader(sr)); StringWriter sw = new StringWriter(); while (true) { int character = baseFilter.Read(); if (character == -1) break; sw.Write((char) character); } content = sw.ToString(); } } return content; } /// /// Returns a uniquely named empty temporary directory on disk. /// /// /// A representing the temporary directory. /// public static DirectoryInfo GetTempDirectory() { // create a uniquely named zero-byte file string tempFile = Path.GetTempFileName(); // remove the temporary file File.Delete(tempFile); // create a directory named after the unique temporary file Directory.CreateDirectory(tempFile); // return the return new DirectoryInfo(tempFile); } /// /// Combines two path strings. /// /// The first path. /// The second path. /// /// A string containing the combined paths. If one of the specified /// paths is a zero-length string, this method returns the other path. /// If contains an absolute path, this method /// returns . /// /// /// On *nix, processing is delegated to . /// /// On Windows, this method normalized the paths to avoid running into /// the 260 character limit of a path and converts forward slashes in /// both and to /// the platform's directory separator character. /// /// public static string CombinePaths(string path1, string path2) { if (PlatformHelper.IsUnix) { return Path.Combine(path1, path2); } if (path1 == null) { throw new ArgumentNullException("path1"); } if (path2 == null) { throw new ArgumentNullException("path2"); } if (Path.IsPathRooted(path2)) { return path2; } char separatorChar = Path.DirectorySeparatorChar; char[] splitChars = new char[] {'/', separatorChar}; // Now we split the Path by the Path Separator String[] path2Parts = path2.Split(splitChars); ArrayList arList = new ArrayList(); // for each Item in the path that differs from ".." we just add it // to the ArrayList, but skip empty parts for (int iCount = 0; iCount < path2Parts.Length; iCount++) { string currentPart = path2Parts[iCount]; // skip empty parts or single dot parts if (currentPart.Length == 0 || currentPart == ".") { continue; } // if we get a ".." Try to remove the last item added (as if // going up in the Directory Structure) if (currentPart == "..") { if (arList.Count > 0 && ((string) arList[arList.Count - 1] != "..")) { arList.RemoveAt(arList.Count -1); } else { arList.Add(currentPart); } } else { arList.Add(currentPart); } } bool trailingSeparator = (path1.Length > 0 && path1.IndexOfAny(splitChars, path1.Length - 1) != -1); // if the first path ends in directory seperator character, then // we need to omit that trailing seperator when we split the path string[] path1Parts; if (trailingSeparator) { path1Parts = path1.Substring(0, path1.Length - 1).Split(splitChars); } else { path1Parts = path1.Split(splitChars); } int counter = path1Parts.Length; // if the second path starts with parts to move up the directory tree, // then remove corresponding parts in the first path // // eg. path1 = d:\whatever\you\want\to\do // path2 = ../../test // // -> // // path1 = d:\whatever\you\want // path2 = test ArrayList arList2 = (ArrayList) arList.Clone(); for (int i = 0; i < arList2.Count; i++) { // never discard first part of path1 if ((string) arList2[i] != ".." || counter < 2) { break; } // skip part of current directory counter--; arList.RemoveAt(0); } string separatorString = separatorChar.ToString(CultureInfo.InvariantCulture); // if path1 only has one remaining part, and the original path had // a trailing separator character or the remaining path had multiple // parts (which were discarded by a relative path in path2), then // add separator to remaining part if (counter == 1 && (trailingSeparator || path1Parts.Length > 1)) { path1Parts[0] += separatorString; } string combinedPath = Path.Combine(string.Join(separatorString, path1Parts, 0, counter), string.Join(separatorString, (String[]) arList.ToArray(typeof(String)))); // if path2 ends in directory separator character, then make sure // combined path has trailing directory separator character if (path2.EndsWith("/") || path2.EndsWith(separatorString)) { combinedPath += Path.DirectorySeparatorChar; } return combinedPath; } /// /// Returns Absolute Path (Fix for 260 Char Limit of Path.GetFullPath(...)) /// /// The file or directory for which to obtain absolute path information. /// Path Resolved /// path is a zero-length string, contains only white space or contains one or more invalid characters as defined by . /// is . public static string GetFullPath(string path) { if (path == null) { throw new ArgumentNullException("path"); } if (PlatformHelper.IsUnix || Path.IsPathRooted(path)) { return Path.GetFullPath(path); } if (path.Length == 0 || path.Trim().Length == 0 || path.IndexOfAny(Path.InvalidPathChars) != -1) { throw new ArgumentException("The path is not of a legal form."); } string combinedPath = FileUtils.CombinePaths( Directory.GetCurrentDirectory(), path); return Path.GetFullPath(combinedPath); } /// /// Returns the home directory of the current user. /// /// /// The home directory of the current user. /// public static string GetHomeDirectory() { if (PlatformHelper.IsUnix) { return Environment.GetEnvironmentVariable("HOME"); } else { return Environment.GetEnvironmentVariable("USERPROFILE"); } } /// /// Scans a list of directories for the specified filename. /// /// The list of directories to search. /// The name of the file to look for. /// Specifies whether the directory should be searched recursively. /// /// The directories are scanned in the order in which they are defined. /// /// /// The absolute path to the specified file, or null if the file was /// not found. /// public static string ResolveFile(string[] directories, string fileName, bool recursive) { if (directories == null) throw new ArgumentNullException("directories"); if (fileName == null) throw new ArgumentNullException("fileName"); string resolvedFile = null; foreach (string directory in directories) { if (!Directory.Exists(directory)) continue; resolvedFile = ScanDirectory (directory, fileName, recursive); if (resolvedFile != null) break; } return resolvedFile; } #endregion Public Static Methods #region Private Static Methods private static string ScanDirectory(string directory, string fileName, bool recursive) { string absolutePath = Path.Combine(directory, fileName); if (File.Exists(absolutePath)) return absolutePath; if (!recursive) return null; string[] subDirs = Directory.GetDirectories(directory); foreach (string subDir in subDirs) { absolutePath = ScanDirectory (Path.Combine (directory, subDir), fileName, recursive); if (absolutePath != null) return absolutePath; } return null; } #endregion Private Static Methods } } nant-0.92-rc1/src/NAnt.Core/Util/AssemblyResolver.cs0000644000175000017500000001706611757302273022125 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; using System.Collections.Specialized; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.Remoting.Lifetime; using NAnt.Core; namespace NAnt.Core.Util { /// /// Resolves assemblies by caching assemblies that were loaded. /// [Serializable()] public sealed class AssemblyResolver { #region Public Instance Constructors /// /// Initializes an instanse of the /// class. /// public AssemblyResolver() { _assemblyCache = new Hashtable(); } /// /// Initializes an instanse of the /// class in the context of the given . /// public AssemblyResolver(Task task) : this() { _task = task; } #endregion Public Instance Constructors #region Public Instance Methods /// /// Installs the assembly resolver by hooking up to the /// event. /// public void Attach() { AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(AssemblyResolve); AppDomain.CurrentDomain.AssemblyLoad += new AssemblyLoadEventHandler(AssemblyLoad); } /// /// Uninstalls the assembly resolver. /// public void Detach() { AppDomain.CurrentDomain.AssemblyResolve -= new ResolveEventHandler(this.AssemblyResolve); AppDomain.CurrentDomain.AssemblyLoad -= new AssemblyLoadEventHandler(AssemblyLoad); this._assemblyCache.Clear(); } #endregion Public Instance Methods #region Private Instance Methods /// /// Resolves an assembly not found by the system using the assembly /// cache. /// /// The source of the event. /// A that contains the event data. /// /// The loaded assembly, or if not found. /// private Assembly AssemblyResolve(object sender, ResolveEventArgs args) { bool isFullName = args.Name.IndexOf("Version=") != -1; // first try to find an already loaded assembly Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in assemblies) { if (isFullName) { if (assembly.FullName == args.Name) { // output debug message Log(Level.Debug, "Resolved assembly '{0}' from" + " loaded assemblies using full name.", args.Name); // return assembly from AppDomain return assembly; } } else if (assembly.GetName(false).Name == args.Name) { // output debug message Log(Level.Debug, "Resolved assembly '{0}' from" + " loaded assemblies using name.", args.Name); // return assembly from AppDomain return assembly; } } // find assembly in cache if (isFullName) { if (_assemblyCache.Contains(args.Name)) { // output debug message Log(Level.Debug, "Resolved assembly '{0}' from" + " cache using full name.", args.Name); // return assembly from cache return (Assembly) _assemblyCache[args.Name]; } } else { foreach (Assembly assembly in _assemblyCache.Values) { if (assembly.GetName(false).Name == args.Name) { // output debug message Log(Level.Debug, "Resolved assembly '{0}'" + " from cache using name.", args.Name); // return assembly from cache return assembly; } } } // output debug message Log(Level.Debug, "Assembly '{0}' could not be located.", args.Name); return null; } /// /// Occurs when an assembly is loaded. The loaded assembly is added /// to the assembly cache. /// /// The source of the event. /// An that contains the event data. private void AssemblyLoad(object sender, AssemblyLoadEventArgs args) { // store assembly in cache _assemblyCache[args.LoadedAssembly.FullName] = args.LoadedAssembly; // output debug message Log(Level.Debug, "Added assembly '{0}' to assembly cache.", args.LoadedAssembly.FullName); } /// /// Logs a message with the given priority. /// /// The message priority at which the specified message is to be logged. /// The message to log, containing zero or more format items. /// An array containing zero or more objects to format. /// /// The actual logging is delegated to the in which /// the is executing /// private void Log(Level messageLevel, string message, params object[] args) { if (_task != null) { _task.Log(messageLevel, message, args); } } #endregion Private Instance Methods #region Private Instance Fields /// /// Holds the loaded assemblies. /// private Hashtable _assemblyCache; /// /// Holds the in which the /// is executing. /// /// /// The in which the /// is executing or if the /// is not executing in the context of a . /// private Task _task; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.Core/Util/CommandLineArgument.cs0000644000175000017500000006444311757302273022516 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; using System.Collections.Specialized; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Security.Permissions; using System.Text.RegularExpressions; namespace NAnt.Core.Util { /// /// Represents a valid command-line argument. /// public class CommandLineArgument { #region Public Instance Constructors public CommandLineArgument(CommandLineArgumentAttribute attribute, PropertyInfo propertyInfo) { _attribute = attribute; _propertyInfo = propertyInfo; _seenValue = false; _elementType = GetElementType(propertyInfo); _argumentType = GetArgumentType(attribute, propertyInfo); if (IsCollection || IsArray) { _collectionValues = new ArrayList(); } else if (IsNameValueCollection) { _valuePairs = new NameValueCollection(); } Debug.Assert(LongName != null && LongName.Length > 0); Debug.Assert((!IsCollection && !IsArray && !IsNameValueCollection) || AllowMultiple, "Collection and array arguments must have allow multiple"); Debug.Assert(!Unique || (IsCollection || IsArray || IsNameValueCollection), "Unique only applicable to collection arguments"); } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets the property that backs the argument. /// /// /// The property that backs the arguments. /// public PropertyInfo Property { get { return _propertyInfo; } } /// /// Gets the underlying of the argument. /// /// /// The underlying of the argument. /// /// /// If the of the argument is a collection type, /// this property will returns the underlying type of that collection. /// public Type ValueType { get { return IsCollection || IsArray ? _elementType : Type; } } /// /// Gets the long name of the argument. /// /// The long name of the argument. public string LongName { get { if (_attribute != null && _attribute.Name != null) { return _attribute.Name; } else { return _propertyInfo.Name; } } } /// /// Gets the short name of the argument. /// /// The short name of the argument. public string ShortName { get { if (_attribute != null) { return _attribute.ShortName; } else { return null; } } } /// /// Gets the description of the argument. /// /// The description of the argument. public string Description { get { if (_attribute != null) { return _attribute.Description; } else { return null; } } } /// /// Gets a value indicating whether the argument is required. /// /// /// if the argument is required; otherwise, /// . /// public bool IsRequired { get { return 0 != (_argumentType & CommandLineArgumentTypes.Required); } } /// /// Gets a value indicating whether a mathing command-line argument /// was already found. /// /// /// if a matching command-line argument was /// already found; otherwise, . /// public bool SeenValue { get { return _seenValue; } } /// /// Gets a value indicating whether the argument can be specified multiple /// times. /// /// /// if the argument may be specified multiple /// times; otherwise, . /// public bool AllowMultiple { get { return (IsCollection || IsArray || IsNameValueCollection) && (0 != (_argumentType & CommandLineArgumentTypes.Multiple)); } } /// /// Gets a value indicating whether the argument can only be specified once /// with a certain value. /// /// /// if the argument should always have a unique /// value; otherwise, . /// public bool Unique { get { return 0 != (_argumentType & CommandLineArgumentTypes.Unique); } } /// /// Gets the of the property to which the argument /// is applied. /// /// /// The of the property to which the argument is /// applied. /// public Type Type { get { return _propertyInfo.PropertyType; } } /// /// Gets a value indicating whether the argument is collection-based. /// /// /// if the argument is backed by a /// that can be assigned to and is not backed /// by a that can be assigned to /// ; otherwise, . /// public bool IsCollection { get { return IsCollectionType(Type); } } /// /// Gets a value indicating whether the argument is a set of name/value /// pairs. /// /// /// if the argument is backed by a /// that can be assigned to ; otherwise, /// . /// public bool IsNameValueCollection { get { return IsNameValueCollectionType(Type); } } /// /// Gets a value indicating whether the argument is array-based. /// /// /// if the argument is backed by an array; /// otherwise, . /// public bool IsArray { get { return IsArrayType(Type); } } /// /// Gets a value indicating whether the argument is the default argument. /// /// /// if the argument is the default argument; /// otherwise, . /// public bool IsDefault { get { return (_attribute != null && _attribute is DefaultCommandLineArgumentAttribute); } } /// /// Gets a value indicating whether the argument cannot be combined with /// other arguments. /// /// /// if the argument cannot be combined with other /// arguments; otherwise, . /// public bool IsExclusive { get { return 0 != (_argumentType & CommandLineArgumentTypes.Exclusive); } } #endregion Public Instance Properties #region Public Instance Methods /// /// Sets the value of the argument on the specified object. /// /// The object on which the value of the argument should be set. /// The argument is required and no value was specified. /// /// /// The matching property is collection-based, but is not initialized /// and cannot be written to. /// /// -or- /// /// The matching property is collection-based, but has no strongly-typed /// Add method. /// /// -or- /// /// The matching property is collection-based, but the signature of the /// Add method is not supported. /// /// [ReflectionPermission(SecurityAction.Demand, Flags=ReflectionPermissionFlag.NoFlags)] public void Finish(object destination) { if (IsRequired && !SeenValue) { throw new CommandLineArgumentException(string.Format(CultureInfo.InvariantCulture, "Missing required argument '-{0}'.", LongName)); } if (IsArray) { _propertyInfo.SetValue(destination, _collectionValues.ToArray(_elementType), BindingFlags.Default, null, null, CultureInfo.InvariantCulture); } else if (IsCollection) { // If value of property is null, create new instance of collection if (_propertyInfo.GetValue(destination, BindingFlags.Default, null, null, CultureInfo.InvariantCulture) == null) { if (!_propertyInfo.CanWrite) { throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1171") + " but is not initialized and does not allow the" + "collection to be initialized.", LongName)); } object instance = Activator.CreateInstance(_propertyInfo.PropertyType, BindingFlags.Public | BindingFlags.Instance, null, null, CultureInfo.InvariantCulture); _propertyInfo.SetValue(destination, instance, BindingFlags.Default, null, null, CultureInfo.InvariantCulture); } object value = _propertyInfo.GetValue(destination, BindingFlags.Default, null, null, CultureInfo.InvariantCulture); MethodInfo addMethod = null; // Locate Add method with 1 parameter foreach (MethodInfo method in value.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance)) { if (method.Name == "Add" && method.GetParameters().Length == 1) { ParameterInfo parameter = method.GetParameters()[0]; if (parameter.ParameterType != typeof(object)) { addMethod = method; break; } } } if (addMethod == null) { throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1169"), LongName)); } else { try { foreach (object item in _collectionValues) { addMethod.Invoke(value, BindingFlags.Default, null, new object[] {item}, CultureInfo.InvariantCulture); } } catch (Exception ex) { throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1173"), LongName), ex); } } } else if (IsNameValueCollection) { // If value of property is null, create new instance of collection if (_propertyInfo.GetValue(destination, BindingFlags.Default, null, null, CultureInfo.InvariantCulture) == null) { if (!_propertyInfo.CanWrite) { throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1171") + " but is not initialized and does not allow the" + "collection to be initialized.", LongName)); } object instance = Activator.CreateInstance(_propertyInfo.PropertyType, BindingFlags.Public | BindingFlags.Instance, null, null, CultureInfo.InvariantCulture); _propertyInfo.SetValue(destination, instance, BindingFlags.Default, null, null, CultureInfo.InvariantCulture); } object value = _propertyInfo.GetValue(destination, BindingFlags.Default, null, null, CultureInfo.InvariantCulture); MethodInfo addMethod = null; // Locate Add method with 2 string parameters foreach (MethodInfo method in value.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance)) { if (method.Name == "Add" && method.GetParameters().Length == 2) { if (method.GetParameters()[0].ParameterType == typeof(string) && method.GetParameters()[1].ParameterType == typeof(string)) { addMethod = method; break; } } } if (addMethod == null) { throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1169"), LongName)); } else { try { foreach (string key in _valuePairs) { addMethod.Invoke(value, BindingFlags.Default, null, new object[] {key, _valuePairs.Get(key)}, CultureInfo.InvariantCulture); } } catch (Exception ex) { throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1173"), LongName), ex); } } } else { // this fails on mono if the _argumentValue is null if (_argumentValue != null) { _propertyInfo.SetValue(destination, _argumentValue, BindingFlags.Default, null, null, CultureInfo.InvariantCulture); } } } /// /// Assigns the specified value to the argument. /// /// The value that should be assigned to the argument. /// /// Duplicate argument. /// -or- /// Invalid value. /// public void SetValue(string value) { if (SeenValue && !AllowMultiple) { throw new CommandLineArgumentException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1175"), LongName)); } _seenValue = true; object newValue = ParseValue(ValueType, value); if (IsCollection || IsArray) { if (Unique && _collectionValues.Contains(newValue)) { throw new CommandLineArgumentException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1172"), value, LongName)); } else { _collectionValues.Add(newValue); } } else if (IsNameValueCollection) { // name/value pair is added to collection in ParseValue } else { _argumentValue = newValue; } } #endregion Public Instance Methods #region Private Instance Methods private object ParseValue(Type type, string stringData) { // null is only valid for bool variables // empty string is never valid if ((stringData != null || type == typeof(bool)) && (stringData == null || stringData.Length > 0)) { try { if (type == typeof(string)) { return stringData; } else if (type == typeof(bool)) { if (stringData == null || stringData == "+") { return true; } else if (stringData == "-") { return false; } } else if (IsNameValueCollectionType(type)) { Match match = Regex.Match(stringData, @"(\w+[^=]*)=(\w*.*)"); if (match.Success) { string name = match.Groups[1].Value; string value = match.Groups[2].Value; if (Unique && _valuePairs.Get(name) != null) { // we always assume we're dealing with properties // here to make the message more clear throw new CommandLineArgumentException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1174"), name, LongName)); } _valuePairs.Add(name, value); return _valuePairs; } else { throw new CommandLineArgumentException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1170"), stringData, LongName), new ArgumentException( "Expected name/value pair (=).")); } } else { if (type.IsEnum) { try { return Enum.Parse(type, stringData, true); } catch(ArgumentException ex) { string message = "Invalid value {0} for command-line argument '-{1}'. Valid values are: "; foreach (object value in Enum.GetValues(type)) { message += value.ToString() + ", "; } // strip last , message = message.Substring(0, message.Length - 2) + "."; throw new CommandLineArgumentException(string.Format(CultureInfo.InvariantCulture, message, stringData, LongName), ex); } } else { // Make a guess that the there's a public static Parse method on the type of the property // that will take an argument of type string to convert the string to the type // required by the property. System.Reflection.MethodInfo parseMethod = type.GetMethod( "Parse", BindingFlags.Public | BindingFlags.Static, null, CallingConventions.Standard, new Type[] {typeof(string)}, null); if (parseMethod != null) { // Call the Parse method return parseMethod.Invoke(null, BindingFlags.Default, null, new object[] {stringData}, CultureInfo.InvariantCulture); } else if (type.IsClass) { // Search for a constructor that takes a string argument ConstructorInfo stringArgumentConstructor = type.GetConstructor(new Type[] {typeof(string)}); if (stringArgumentConstructor != null) { return stringArgumentConstructor.Invoke( BindingFlags.Default, null, new object[] {stringData}, CultureInfo.InvariantCulture); } } } } } catch (CommandLineArgumentException) { throw; } catch (Exception ex) { throw new CommandLineArgumentException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1170"), stringData, LongName), ex); } } throw new CommandLineArgumentException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1170"), stringData, LongName)); } #endregion Private Instance Methods #region Private Static Methods private static CommandLineArgumentTypes GetArgumentType(CommandLineArgumentAttribute attribute, PropertyInfo propertyInfo) { if (attribute != null) { return attribute.Type; } else if (IsCollectionType(propertyInfo.PropertyType)) { return CommandLineArgumentTypes.MultipleUnique; } else { return CommandLineArgumentTypes.AtMostOnce; } } private static Type GetElementType(PropertyInfo propertyInfo) { Type elementType = null; if (propertyInfo.PropertyType.IsArray) { elementType = propertyInfo.PropertyType.GetElementType(); if (elementType == typeof(object)) { throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, "Property {0} is not a strong-typed array.", propertyInfo.Name)); } } else if (typeof(ICollection).IsAssignableFrom(propertyInfo.PropertyType)) { // Locate Add method with 1 parameter foreach (MethodInfo method in propertyInfo.PropertyType.GetMethods(BindingFlags.Public | BindingFlags.Instance)) { if (method.Name == "Add" && method.GetParameters().Length == 1) { ParameterInfo parameter = method.GetParameters()[0]; if (parameter.ParameterType == typeof(object)) { throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, "Property {0} is not a strong-typed collection.", propertyInfo.Name)); } else { elementType = parameter.ParameterType; break; } } } if (elementType == null) { throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, "Invalid commandline argument type for property {0}.", propertyInfo.Name)); } } return elementType; } /// /// Indicates whether the specified is a /// . /// /// /// if can be assigned /// to ; otherwise, . /// private static bool IsNameValueCollectionType(Type type) { return typeof(NameValueCollection).IsAssignableFrom(type); } /// /// Indicates whether the specified is collection-based. /// /// /// if can be assigned /// to and is not backed by a /// that can be assigned to ; /// otherwise, . /// private static bool IsCollectionType(Type type) { return typeof(ICollection).IsAssignableFrom(type) && !IsNameValueCollectionType(type); } /// /// Indicates whether the specified is an array. /// /// /// if is an array; /// otherwise, . /// private static bool IsArrayType(Type type) { return type.IsArray; } #endregion Private Static Methods #region Private Instance Fields private Type _elementType; private bool _seenValue; private CommandLineArgumentTypes _argumentType; private PropertyInfo _propertyInfo; private CommandLineArgumentAttribute _attribute; private object _argumentValue; private ArrayList _collectionValues; private NameValueCollection _valuePairs; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.Core/Util/StopWatchStack.cs0000644000175000017500000000334311757302273021517 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2005 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Owen Rogers (exortech@gmail.com) using System; using System.Collections; namespace NAnt.Core.Util { public class StopWatchStack { private readonly DateTimeProvider _dtProvider; private readonly Stack _stack = new Stack(); public StopWatchStack(DateTimeProvider dtProvider) { _dtProvider = dtProvider; } public void PushStart() { _stack.Push(new StopWatch(_dtProvider)); } public TimeSpan PopStop() { return ((StopWatch) _stack.Pop()).Elapsed(); } private class StopWatch { private readonly DateTimeProvider _dtProvider; private readonly DateTime _start; public StopWatch(DateTimeProvider dtProvider) { _dtProvider = dtProvider; _start = dtProvider.Now; } public TimeSpan Elapsed() { return _dtProvider.Now - _start; } } } }nant-0.92-rc1/src/NAnt.Core/Util/CommandLineArgumentTypes.cs0000644000175000017500000000442511757302273023535 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; namespace NAnt.Core.Util { /// /// Used to control parsing of command-line arguments. /// [Flags] public enum CommandLineArgumentTypes { /// /// Indicates that this field is required. An error will be displayed /// if it is not present when parsing arguments. /// Required = 0x01, /// /// Only valid in conjunction with Multiple. /// Duplicate values will result in an error. /// Unique = 0x02, /// /// Inidicates that the argument may be specified more than once. /// Only valid if the argument is a collection /// Multiple = 0x04, /// /// Inidicates that if this argument is specified, no other arguments may be specified. /// Exclusive = 0x08, /// /// The default type for non-collection arguments. /// The argument is not required, but an error will be reported if it is specified more than once. /// AtMostOnce = 0x00, /// /// The default type for collection arguments. /// The argument is permitted to occur multiple times, but duplicate /// values will cause an error to be reported. /// MultipleUnique = Multiple | Unique, } } nant-0.92-rc1/src/NAnt.Core/Util/ResourceUtils.cs0000644000175000017500000002266311757302273021433 0ustar jtaylorjtaylor// ResourceUtils.cs // // Giuseppe Greco // Copyright (C) 2005 Agamura, Inc. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Giuseppe Greco (giuseppe.greco@agamura.com) // Ian MacLean (imaclean@gmail.com) using System.Reflection; using System.Resources; using System.Globalization; using System.Collections; using System.Runtime.CompilerServices; namespace NAnt.Core.Util { /// /// Provides resource support to NAnt assemblies. This class cannot /// be inherited from. /// public sealed class ResourceUtils { #region Private Static Fields private static ResourceManager _sharedResourceManager; private static readonly Hashtable _resourceManagerDictionary = new Hashtable(); #endregion Private Static Fields #region Private Instance Constructors /// /// Prevents the class from being /// instantiated explicitly. /// private ResourceUtils() {} #endregion Private Instance Constructors #region Public Static Methods /// /// Registers the assembly to be used as the fallback if resources /// aren't found in the local satellite assembly. /// /// /// A that represents the /// assembly to register. /// /// /// The following example shows how to register a shared satellite /// assembly. /// /// /// /// public static void RegisterSharedAssembly(Assembly assembly) { _sharedResourceManager = new ResourceManager(assembly.GetName().Name, assembly); } /// /// Returns the value of the specified string resource. /// /// /// A that contains the name of the /// resource to get. /// /// /// A that contains the value of the /// resource localized for the current culture. /// /// /// The returned resource is localized for the cultural settings of the /// current . /// /// The GetString method is thread-safe. /// /// /// /// The following example demonstrates the GetString method using /// the cultural settings of the current . /// /// /// /// [MethodImpl(MethodImplOptions.NoInlining)] public static string GetString(string name) { Assembly assembly = Assembly.GetCallingAssembly(); return GetString(name, null, assembly); } /// /// Returns the value of the specified string resource localized for /// the specified culture. /// /// /// /// /// A that contains the value of the /// resource localized for the specified culture. /// /// /// /// The GetString method is thread-safe. /// /// /// /// The following example demonstrates the GetString method using /// a specific culture. /// /// /// /// [MethodImpl(MethodImplOptions.NoInlining)] public static string GetString(string name, CultureInfo culture ) { Assembly assembly = Assembly.GetCallingAssembly(); return GetString(name, culture, assembly); } /// /// Returns the value of the specified string resource localized for /// the specified culture for the specified assembly. /// /// /// A that contains the name of the /// resource to get. /// /// /// A that represents /// the culture for which the resource is localized. /// /// /// A /// /// /// A that contains the value of the /// resource localized for the specified culture. /// /// /// /// The GetString method is thread-safe. /// /// /// /// The following example demonstrates the GetString method using /// specific culture and assembly. /// /// /// /// public static string GetString(string name, CultureInfo culture, Assembly assembly) { string assemblyName = assembly.GetName().Name; if (!_resourceManagerDictionary.Contains(assemblyName)) { RegisterAssembly(assembly); } // retrieve resource manager for assembly ResourceManager resourceManager = (ResourceManager) _resourceManagerDictionary[assemblyName]; // try to get the required string from the given assembly string localizedString = resourceManager.GetString(name, culture); // if the given assembly does not contain the required string, then // try to get it from the shared satellite assembly, if registered if (localizedString == null && _sharedResourceManager != null) { return _sharedResourceManager.GetString(name, culture); } return localizedString; } #endregion Public Static Methods #region Private Static Methods /// /// Registers the specified assembly. /// /// /// A that represents the /// assembly to register. /// private static void RegisterAssembly(Assembly assembly) { lock (_resourceManagerDictionary) { string assemblyName = assembly.GetName().Name; _resourceManagerDictionary.Add(assemblyName, new ResourceManager(GetResourceName(assemblyName), assembly)); } } /// /// Determines the manifest resource name of the resource holding the /// localized strings. /// /// The name of the assembly. /// /// The manifest resource name of the resource holding the localized /// strings for the specified assembly. /// /// /// The manifest resource name of the resource holding the localized /// strings should match the name of the assembly, minus Tasks /// suffix. /// private static string GetResourceName(string assemblyName) { string resourceName = null; if (assemblyName.EndsWith("Tasks")) { // hack to determine the manifest resource name as our // assembly names have a Tasks suffix, while our // root namespace in VS.NET does not resourceName = assemblyName.Substring(0, assemblyName.Length - 5); } else { resourceName = assemblyName; } return resourceName + ".Resources.Strings"; } #endregion Private Static Methods } } nant-0.92-rc1/src/NAnt.Core/Util/GacCache.cs0000644000175000017500000002356011757302273020236 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Matt Mastracci // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Remoting.Lifetime; using System.Security; using System.Security.Permissions; using System.Security.Policy; using NAnt.Core; namespace NAnt.Core.Util { /// /// Helper class for determining whether assemblies are located in the /// Global Assembly Cache. /// public sealed class GacCache : IDisposable { #region Public Instance Constructors /// /// Initializes a new instance of the class in /// the context of the given . /// public GacCache(Project project) { _project = project; _gacQueryCache = CollectionsUtil.CreateCaseInsensitiveHashtable(); RecreateDomain(); } #endregion Public Instance Constructors #region Public Instance Destructors ~GacCache() { Dispose(false); } #endregion Public Instance Destructors #region Public Instance Properties /// /// Gets the context of the . /// /// /// The context of the . /// public Project Project { get { return _project; } } #endregion Public Instance Properties #region Private Instance Properties private AppDomain Domain { get { return _domain; } } private GacResolver Resolver { get { if (_resolver == null) { _resolver = ((GacResolver) Domain.CreateInstanceFrom( Assembly.GetExecutingAssembly().Location, typeof(GacResolver).FullName).Unwrap()); } return _resolver; } } #endregion Private Instance Properties #region Implementation of IDisposable public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if (!_disposed) { AppDomain.Unload(_domain); _disposed = true; } } #endregion Implementation of IDisposable #region Public Instance Methods public void RecreateDomain() { // don't recreate this domain unless it has actually loaded an assembly if (!_hasLoadedAssembly && _domain != null) return; if (_domain != null) AppDomain.Unload(_domain); _resolver = null; PermissionSet domainPermSet = new PermissionSet(PermissionState.Unrestricted); _domain = AppDomain.CreateDomain("GacCacheDomain", AppDomain.CurrentDomain.Evidence, AppDomain.CurrentDomain.SetupInformation, domainPermSet); _hasLoadedAssembly = false; } /// /// Determines whether an assembly is installed in the Global /// Assembly Cache given its file name or path. /// /// The name or path of the file that contains the manifest of the assembly. /// /// if is /// installed in the Global Assembly Cache; otherwise, /// . /// /// /// /// To determine whether the specified assembly is installed in the /// Global Assembly Cache, the assembly is loaded into a separate /// . /// /// /// If the family of the current runtime framework does not match the /// family of the current target framework, this method will return /// for all assemblies as there's no way to /// determine whether a given assembly is in the Global Assembly Cache /// for another framework family than the family of the current runtime /// framework. /// /// public bool IsAssemblyInGac(string assemblyFile) { if (Project.RuntimeFramework.Family != Project.TargetFramework.Family) { return false; } string assemblyFilePath = Path.GetFullPath(assemblyFile); if (_gacQueryCache.Contains(assemblyFilePath)) { return (bool) _gacQueryCache[assemblyFilePath]; } _hasLoadedAssembly = true; _gacQueryCache[assemblyFilePath] = Resolver.IsAssemblyInGac(assemblyFilePath); return (bool) _gacQueryCache[assemblyFilePath]; } #endregion Public Instance Methods #region Private Instance Fields /// /// Holds the in which assemblies will be loaded /// to determine whether they are in the Global Assembly Cache. /// private AppDomain _domain; /// /// Holds the context of the . /// private Project _project; /// /// Holds a list of assembly files for which already has been determined /// whether they are located in the Global Assembly Cache. /// /// /// /// The key of the is the full path to the /// assembly file and the value is a indicating /// whether the assembly is located in the Global Assembly Cache. /// /// private Hashtable _gacQueryCache; private bool _hasLoadedAssembly; private GacResolver _resolver; /// /// Holds a value indicating whether the object has been disposed. /// private bool _disposed; #endregion Private Instance Fields private class GacResolver : MarshalByRefObject { #region Override implementation of MarshalByRefObject /// /// Obtains a lifetime service object to control the lifetime policy for /// this instance. /// /// /// An object of type used to control the lifetime /// policy for this instance. This is the current lifetime service object /// for this instance if one exists; otherwise, a new lifetime service /// object initialized with a lease that will never time out. /// public override Object InitializeLifetimeService() { ILease lease = (ILease) base.InitializeLifetimeService(); if (lease.CurrentState == LeaseState.Initial) { lease.InitialLeaseTime = TimeSpan.Zero; } return lease; } #endregion Override implementation of MarshalByRefObject #region Public Instance Methods /// /// Determines whether an assembly is installed in the Global /// Assembly Cache given its file name or path. /// /// The name or path of the file that contains the manifest of the assembly. /// /// if is /// installed in the Global Assembly Cache; otherwise, /// . /// public bool IsAssemblyInGac(string assemblyFile) { try { AssemblyName assemblyName = AssemblyName.GetAssemblyName(assemblyFile); // the assembly can't be in the GAC if it has no public key if (assemblyName.GetPublicKeyToken() == null) { return false; } // load assembly Assembly assembly = Assembly.Load(assemblyName); // tests whether the specified assembly is loaded in the // global assembly cache if (PlatformHelper.IsMono) { // TODO: remove mono specific code when FromGlobalAccessCache // is implemented return assembly.GlobalAssemblyCache; } else { return RuntimeEnvironment.FromGlobalAccessCache(assembly); } } catch { return false; } } #endregion Public Instance Methods } } }nant-0.92-rc1/src/NAnt.Core/Util/CommandLineArgumentCollection.cs0000644000175000017500000002456511757302273024533 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; namespace NAnt.Core.Util { /// /// Contains a strongly typed collection of objects. /// [Serializable] public class CommandLineArgumentCollection : CollectionBase { #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public CommandLineArgumentCollection() { } /// /// Initializes a new instance of the class /// with the specified instance. /// public CommandLineArgumentCollection(CommandLineArgumentCollection value) { AddRange(value); } /// /// Initializes a new instance of the class /// with the specified array of instances. /// public CommandLineArgumentCollection(CommandLineArgument[] value) { AddRange(value); } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets the element at the specified index. /// /// The zero-based index of the element to get or set. [System.Runtime.CompilerServices.IndexerName("Item")] public CommandLineArgument this[int index] { get {return ((CommandLineArgument)(base.List[index]));} set {base.List[index] = value;} } /// /// Gets the with the specified name. /// /// The name of the to get. [System.Runtime.CompilerServices.IndexerName("Item")] public CommandLineArgument this[string name] { get { if (name != null) { // Try to locate instance using LongName foreach (CommandLineArgument CommandLineArgument in base.List) { if (name.Equals(CommandLineArgument.LongName)) { return CommandLineArgument; } } // Try to locate instance using ShortName foreach (CommandLineArgument CommandLineArgument in base.List) { if (name.Equals(CommandLineArgument.ShortName)) { return CommandLineArgument; } } } return null; } } #endregion Public Instance Properties #region Public Instance Methods /// /// Adds a to the end of the collection. /// /// The to be added to the end of the collection. /// The position into which the new element was inserted. public int Add(CommandLineArgument item) { return base.List.Add(item); } /// /// Adds the elements of a array to the end of the collection. /// /// The array of elements to be added to the end of the collection. public void AddRange(CommandLineArgument[] items) { for (int i = 0; (i < items.Length); i = (i + 1)) { Add(items[i]); } } /// /// Adds the elements of a to the end of the collection. /// /// The to be added to the end of the collection. public void AddRange(CommandLineArgumentCollection items) { for (int i = 0; (i < items.Count); i = (i + 1)) { Add(items[i]); } } /// /// Determines whether a is in the collection. /// /// The to locate in the collection. /// /// if is found in the /// collection; otherwise, . /// public bool Contains(CommandLineArgument item) { return base.List.Contains(item); } /// /// Copies the entire collection to a compatible one-dimensional array, starting at the specified index of the target array. /// /// The one-dimensional array that is the destination of the elements copied from the collection. The array must have zero-based indexing. /// The zero-based index in at which copying begins. public void CopyTo(CommandLineArgument[] array, int index) { base.List.CopyTo(array, index); } /// /// Retrieves the index of a specified object in the collection. /// /// The object for which the index is returned. /// /// The index of the specified . If the is not currently a member of the collection, it returns -1. /// public int IndexOf(CommandLineArgument item) { return base.List.IndexOf(item); } /// /// Inserts a into the collection at the specified index. /// /// The zero-based index at which should be inserted. /// The to insert. public void Insert(int index, CommandLineArgument item) { base.List.Insert(index, item); } /// /// Returns an enumerator that can iterate through the collection. /// /// /// A for the entire collection. /// public new CommandLineArgumentEnumerator GetEnumerator() { return new CommandLineArgumentEnumerator(this); } /// /// Removes a member from the collection. /// /// The to remove from the collection. public void Remove(CommandLineArgument item) { base.List.Remove(item); } #endregion Public Instance Methods } /// /// Enumerates the elements of a . /// public class CommandLineArgumentEnumerator : IEnumerator { #region Internal Instance Constructors /// /// Initializes a new instance of the class /// with the specified . /// /// The collection that should be enumerated. internal CommandLineArgumentEnumerator(CommandLineArgumentCollection arguments) { IEnumerable temp = (IEnumerable) (arguments); _baseEnumerator = temp.GetEnumerator(); } #endregion Internal Instance Constructors #region Implementation of IEnumerator /// /// Gets the current element in the collection. /// /// /// The current element in the collection. /// public CommandLineArgument Current { get { return (CommandLineArgument) _baseEnumerator.Current; } } object IEnumerator.Current { get { return _baseEnumerator.Current; } } /// /// Advances the enumerator to the next element of the collection. /// /// /// if the enumerator was successfully advanced /// to the next element; if the enumerator has /// passed the end of the collection. /// public bool MoveNext() { return _baseEnumerator.MoveNext(); } bool IEnumerator.MoveNext() { return _baseEnumerator.MoveNext(); } /// /// Sets the enumerator to its initial position, which is before the /// first element in the collection. /// public void Reset() { _baseEnumerator.Reset(); } void IEnumerator.Reset() { _baseEnumerator.Reset(); } #endregion Implementation of IEnumerator #region Private Instance Fields private IEnumerator _baseEnumerator; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.Core/Util/DefaultCommandLineArgumentAttribute.cs0000644000175000017500000000320611757302273025675 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; namespace NAnt.Core.Util { /// /// Marks a command-line option as being the default option. When the name of /// a command-line argument is not specified, this option will be assumed. /// [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public sealed class DefaultCommandLineArgumentAttribute : CommandLineArgumentAttribute { /// /// Initializes a new instance of the class /// with the specified argument type. /// /// Specifies the checking to be done on the argument. public DefaultCommandLineArgumentAttribute(CommandLineArgumentTypes argumentType) : base(argumentType) { } } } nant-0.92-rc1/src/NAnt.Core/Util/ReflectionUtils.cs0000644000175000017500000001072611757302273021733 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections.Specialized; using System.Globalization; using System.Reflection; namespace NAnt.Core.Util { /// /// Provides a set of helper methods related to reflection. /// public sealed class ReflectionUtils { #region Private Instance Constructors /// /// Initializes a new instance of the class. /// /// /// Uses a private access modifier to prevent instantiation of this class. /// private ReflectionUtils() { } #endregion Private Instance Constructors #region Public Static Methods /// /// Loads the type specified in the type string with assembly qualified name. /// /// The assembly qualified name of the type to load. /// Flag set to to throw an exception if the type cannot be loaded. /// /// is and /// an error is encountered while loading the , or /// is not an assembly qualified name. /// /// /// If the cannot be instantiated from the assembly /// qualified type name, then we'll try to instantiate the type using its /// simple type name from an already loaded assembly with an assembly /// name mathing the assembly in the assembly qualified type name. /// /// /// The type loaded or if it could not be loaded. /// public static Type GetTypeFromString(string typeName, bool throwOnError) { Type type = Type.GetType(typeName, throwOnError); if (type == null) { // if the type name specifies the assembly name, try to instantiate // type from currently loaded assemblies if (typeName.IndexOf(',') != -1) { int startAssembly = typeName.IndexOf(','); int startVersion = typeName.IndexOf(',', startAssembly + 1); // get type from assembly qualified type name string simpleTypeName = typeName.Substring( 0, startAssembly); string assemblyName = null; if (startVersion != -1) { assemblyName = typeName.Substring(startAssembly + 1, startVersion - startAssembly - 1).Trim(); } else { assemblyName = typeName.Substring(startAssembly + 1).Trim(); } // try to instantiate type from currently loaded assemblies type = Type.GetType(simpleTypeName + ", " + assemblyName, false); } else { // iterate over currently loaded assemblies and try to // instantiate type from one of them Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in assemblies) { type = assembly.GetType(typeName, false); if (type != null) { break; } } } } return type; } #endregion Public Static Methods } } nant-0.92-rc1/src/NAnt.Core/Util/CommandLineArgumentAttribute.cs0000644000175000017500000000603511757302273024373 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; namespace NAnt.Core.Util { /// /// Allows control of command line parsing. /// [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public class CommandLineArgumentAttribute : Attribute { #region Public Instance Constructors /// /// Initializes a new instance of the class /// with the specified argument type. /// /// Specifies the checking to be done on the argument. public CommandLineArgumentAttribute(CommandLineArgumentTypes argumentType) { _argumentType = argumentType; } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets the checking to be done on the argument. /// /// The checking that should be done on the argument. public CommandLineArgumentTypes Type { get { return _argumentType; } } /// /// Gets or sets the long name of the argument. /// /// The long name of the argument. public string Name { get { return _name; } set { _name = value; } } /// /// Gets or sets the short name of the argument. /// /// The short name of the argument. public string ShortName { get { return _shortName; } set { _shortName = value; } } /// /// Gets or sets the description of the argument. /// /// The description of the argument. public string Description { get { return _description; } set { _description = value; } } #endregion Public Instance Properties #region Private Instance Fields private CommandLineArgumentTypes _argumentType; private string _name; private string _shortName; private string _description; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.Core/Functions/0000755000175000017500000000000011757310030017304 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.Core/Functions/AssemblyFunctions.cs0000644000175000017500000001273511757302273023325 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian Maclean (imaclean@gmail.com) // Jaroslaw Kowalski (jkowalski@users.sourceforge.net) using System; using System.IO; using System.Collections; using System.Reflection; using System.Globalization; using NAnt.Core; using NAnt.Core.Types; using NAnt.Core.Attributes; namespace NAnt.Core.Functions { /// /// Functions to return information for a given assembly. /// [FunctionSet("assembly", "Assembly")] public class AssemblyFunctions : FunctionSetBase { #region Public Instance Constructors public AssemblyFunctions(Project project, PropertyDictionary properties) : base(project, properties) {} #endregion Public Instance Constructors #region Public Instance Methods /// /// Loads an assembly given its file name or path. /// /// The name or path of the file that contains the manifest of the assembly. /// /// The loaded assembly. /// /// is an empty . /// is not found, or the module you are trying to load does not specify a filename extension. /// is not a valid assembly. /// An assembly or module was loaded twice with two different evidences, or the assembly name is longer than MAX_PATH characters. [Function("load-from-file")] public Assembly LoadFromFile(string assemblyFile) { return Assembly.LoadFrom(Project.GetFullPath(assemblyFile)); } /// /// Loads an assembly given the long form of its name. /// /// The long form of the assembly name. /// /// The loaded assembly. /// /// is a . /// is not found. /// /// /// Determine the location of the Microsoft Access 11 Primary Interop /// Assembly by loading it using its fully qualified name, and copy it /// to the build directory. /// /// /// /// /// ]]> /// /// [Function("load")] public Assembly Load(string assemblyString) { return Assembly.Load(assemblyString); } #endregion Public Instance Methods #region Public Static Methods /// /// Gets the full name of the assembly, also known as the display name. /// /// The assembly to get the full name for. /// /// The full name of the assembly, also known as the display name. /// [Function("get-full-name")] public static string GetFullName(Assembly assembly) { return assembly.FullName; } /// /// Gets an for the specified assembly. /// /// The assembly to get an for. /// /// An for the specified assembly. /// /// [Function("get-name")] public static AssemblyName GetName(Assembly assembly) { return assembly.GetName(false); } /// /// Gets the physical location, in codebase format, of the loaded file /// that contains the manifest. /// /// The assembly to get the location for. /// /// The location of the specified assembly. /// [Function("get-location")] public static string GetLocation(Assembly assembly) { return assembly.Location; } #endregion Public Static Methods } } nant-0.92-rc1/src/NAnt.Core/Functions/DateTimeFunctions.cs0000644000175000017500000002414711757302273023242 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian Maclean (imaclean@gmail.com) // Jaroslaw Kowalski (jkowalski@users.sourceforge.net) using System; using System.Collections; using System.Globalization; using System.IO; using System.Reflection; using NAnt.Core; using NAnt.Core.Types; using NAnt.Core.Attributes; namespace NAnt.Core.Functions { [FunctionSet("datetime", "Date/Time")] public class DateTimeFunctions : FunctionSetBase { #region Public Instance Constructors public DateTimeFunctions(Project project, PropertyDictionary properties) : base(project, properties) { } #endregion Public Instance Constructors #region Public Static Methods /// /// Gets a that is the current local date and /// time on this computer. /// /// /// A whose value is the current date and time. /// [Function("now")] public static DateTime Now() { return DateTime.Now; } /// /// Gets the year component of the specified date. /// /// The date of which to get the year component. /// /// The year, between 1 and 9999. /// [Function("get-year")] public static int GetYear(DateTime date) { return date.Year; } /// /// Gets the month component of the specified date. /// /// The date of which to get the month component. /// /// The month, between 1 and 12. /// [Function("get-month")] public static int GetMonth(DateTime date) { return date.Month; } /// /// Gets the day of the month represented by the specified date. /// /// The date of which to get the day of the month. /// /// The day value, between 1 and 31. /// [Function("get-day")] public static int GetDay(DateTime date) { return date.Day; } /// /// Gets the hour component of the specified date. /// /// The date of which to get the hour component. /// /// The hour, between 0 and 23. /// [Function("get-hour")] public static int GetHour(DateTime date) { return date.Hour; } /// /// Gets the minute component of the specified date. /// /// The date of which to get the minute component. /// /// The minute, between 0 and 59. /// [Function("get-minute")] public static int GetMinute(DateTime date) { return date.Minute; } /// /// Gets the seconds component of the specified date. /// /// The date of which to get the seconds component. /// /// The seconds, between 0 and 59. /// [Function("get-second")] public static int GetSecond(DateTime date) { return date.Second; } /// /// Gets the milliseconds component of the specified date. /// /// The date of which to get the milliseconds component. /// /// The millisecond, between 0 and 999. /// [Function("get-millisecond")] public static int GetMillisecond(DateTime date) { return date.Millisecond; } /// /// Gets the number of ticks that represent the specified date. /// /// The date of which to get the number of ticks. /// /// The number of ticks that represent the date and time of the /// specified date. /// [Function("get-ticks")] public static long GetTicks(DateTime date) { return date.Ticks; } /// /// Gets the day of the week represented by the specified date. /// /// The date of which to get the day of the week. /// /// The day of the week, ranging from zero, indicating Sunday, to six, /// indicating Saturday. /// [Function("get-day-of-week")] public static int GetDayOfWeek(DateTime date) { return (int) date.DayOfWeek; } /// /// Gets the day of the year represented by the specified date. /// /// The date of which to get the day of the year. /// /// The day of the year, between 1 and 366. /// [Function("get-day-of-year")] public static int GetDayOfYear(DateTime date) { return (int) date.DayOfYear; } /// /// Returns the number of days in the specified month of the specified /// year. /// /// The year. /// The month (a number ranging from 1 to 12). /// /// The number of days in for the specified /// . /// /// is less than 1 or greater than 12. [Function("get-days-in-month")] public static int GetDaysInMonth(int year, int month) { return DateTime.DaysInMonth(year, month); } /// /// Returns an indication whether the specified year is a leap year. /// /// A 4-digit year. /// /// if is a leap year; /// otherwise, . /// [Function("is-leap-year")] public static bool IsLeapYear(int year) { return DateTime.IsLeapYear(year); } #endregion Public Static Methods } [FunctionSet("datetime", "Conversion")] public class DateTimeConversionFunctions : FunctionSetBase { #region Public Instance Constructors public DateTimeConversionFunctions(Project project, PropertyDictionary properties) : base(project, properties) { } #endregion Public Instance Constructors #region Public Static Methods /// /// Converts the specified string representation of a date and time to /// its equivalent. /// /// A string containing a date and time to convert. /// /// A equivalent to the date and time contained /// in . /// /// does not contain a valid string representation of a date and time. /// /// The for the invariant culture is /// used to supply formatting information about . /// [Function("parse")] public static DateTime Parse(string s) { return DateTime.Parse(s, CultureInfo.InvariantCulture); } /// /// Converts the specified to its equivalent /// string representation. /// /// A to convert. /// /// A string representation of formatted using /// the general format specifier ("G"). /// /// /// is formatted with the /// for the invariant culture. /// [Function("to-string")] public static string ToString(DateTime value) { return value.ToString(CultureInfo.InvariantCulture); } /// /// Converts the specified to its equivalent /// string representation. /// /// A to convert. /// A format string. /// /// A string representation of formatted /// using the specified format /// /// /// is formatted with the /// for the invariant culture. /// [Function("format-to-string")] public static string ToString(DateTime value, string format) { return value.ToString(format, CultureInfo.InvariantCulture); } #endregion Public Static Methods } } nant-0.92-rc1/src/NAnt.Core/Functions/StringFunctions.cs0000644000175000017500000005113611757302273023012 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian Maclean (imaclean@gmail.com) // Jaroslaw Kowalski (jkowalski@users.sourceforge.net) using System; using System.IO; using System.Collections; using System.Reflection; using System.Globalization; using NAnt.Core; using NAnt.Core.Types; using NAnt.Core.Attributes; namespace NAnt.Core.Functions { [FunctionSet("string", "String")] public class StringFunctions : FunctionSetBase { #region Public Instance Constructors public StringFunctions(Project project, PropertyDictionary propDict) : base(project, propDict) { } #endregion Public Instance Constructors #region Public Static Methods /// /// Returns the length of the specified string. /// /// input string /// /// The string's length. /// /// /// string::get-length('foo') ==> 3 /// /// /// string::get-length('') ==> 0 /// [Function("get-length")] public static int GetLength(string s) { return s.Length; } /// /// Returns a substring of the specified string. /// /// input string /// position of the start of the substring /// the length of the substring /// /// /// If the is greater than zero, the /// function returns a substring starting at character position /// with a length of /// characters. /// /// /// If the is equal to zero, the function /// returns an empty string. /// /// /// or is less than zero. /// is greater than the length of . /// plus indicates a position not within . /// /// string::substring('testing string', 0, 4) ==> 'test' /// /// /// string::substring('testing string', 8, 3) ==> 'str' /// /// /// string::substring('testing string', 8, 0) ==> '' /// /// /// string::substring('testing string', -1, 5) ==> ERROR /// /// /// string::substring('testing string', 8, -1) ==> ERROR /// /// /// string::substring('testing string', 5, 17) ==> ERROR /// [Function("substring")] public static string Substring(string str, int startIndex, int length) { return str.Substring(startIndex, length); } /// /// Tests whether the specified string starts with the specified prefix /// string. /// /// test string /// prefix string /// /// when is a prefix for /// the string . Meaning, the characters at the /// beginning of are identical to /// ; otherwise, . /// /// /// This function performs a case-sensitive word search using the /// invariant culture. /// /// /// string::starts-with('testing string', 'test') ==> true /// /// /// string::starts-with('testing string', 'testing') ==> true /// /// /// string::starts-with('testing string', 'string') ==> false /// /// /// string::starts-with('test', 'testing string') ==> false /// [Function("starts-with")] public static bool StartsWith(string s1, string s2) { return CultureInfo.InvariantCulture.CompareInfo.IsPrefix(s1, s2); } /// /// Tests whether the specified string ends with the specified suffix /// string. /// /// test string /// suffix string /// /// when is a suffix for /// the string . Meaning, the characters at the /// end of are identical to /// ; otherwise, . /// /// /// This function performs a case-sensitive word search using the /// invariant culture. /// /// /// string::ends-with('testing string', 'string') ==> true /// /// /// string::ends-with('testing string', '') ==> true /// /// /// string::ends-with('testing string', 'bring') ==> false /// /// /// string::ends-with('string', 'testing string') ==> false /// [Function("ends-with")] public static bool EndsWith(string s1, string s2) { return CultureInfo.InvariantCulture.CompareInfo.IsSuffix(s1, s2); } /// /// Returns the specified string converted to lowercase. /// /// input string /// /// The string in lowercase. /// /// /// The casing rules of the invariant culture are used to convert the /// to lowercase. /// /// /// string::to-lower('testing string') ==> 'testing string' /// /// /// string::to-lower('Testing String') ==> 'testing string' /// /// /// string::to-lower('Test 123') ==> 'test 123' /// [Function("to-lower")] public static string ToLower(string s) { return s.ToLower(CultureInfo.InvariantCulture); } /// /// Returns the specified string converted to uppercase. /// /// input string /// /// The string in uppercase. /// /// /// The casing rules of the invariant culture are used to convert the /// to uppercase. /// /// /// string::to-upper('testing string') ==> 'TESTING STRING' /// /// /// string::to-upper('Testing String') ==> 'TESTING STRING' /// /// /// string::to-upper('Test 123') ==> 'TEST 123' /// [Function("to-upper")] public static string ToUpper(string s) { return s.ToUpper(CultureInfo.InvariantCulture); } /// /// Returns a string corresponding to the replacement of a given string /// with another in the specified string. /// /// input string /// A to be replaced. /// A to replace all occurrences of . /// /// A equivalent to but /// with all instances of replaced with /// . /// /// is an empty string. /// /// This function performs a word (case-sensitive and culture-sensitive) /// search to find . /// /// /// string::replace('testing string', 'test', 'winn') ==> 'winning string' /// /// /// string::replace('testing string', 'foo', 'winn') ==> 'testing string' /// /// /// string::replace('testing string', 'ing', '') ==> 'test str' /// /// /// string::replace('banana', 'ana', 'ana') ==> 'banana' /// [Function("replace")] public static string Replace(string str, string oldValue, string newValue) { return str.Replace(oldValue, newValue); } /// /// Tests whether the specified string contains the given search string. /// /// The string to search. /// The string to locate within . /// /// if is found in /// ; otherwise, . /// /// /// This function performs a case-sensitive word search using the /// invariant culture. /// /// /// string::contains('testing string', 'test') ==> true /// /// /// string::contains('testing string', '') ==> true /// /// /// string::contains('testing string', 'Test') ==> false /// /// /// string::contains('testing string', 'foo') ==> false /// [Function("contains")] public static bool Contains(string source, string value) { return CultureInfo.InvariantCulture.CompareInfo.IndexOf(source, value, CompareOptions.None) >= 0; } /// /// Returns the position of the first occurrence in the specified string /// of the given search string. /// /// The string to search. /// The string to locate within . /// /// /// The lowest-index position of in /// if it is found, or -1 if /// does not contain . /// /// /// If is an empty string, the return value /// will always be 0. /// /// /// /// This function performs a case-sensitive word search using the /// invariant culture. /// /// /// string::index-of('testing string', 'test') ==> 0 /// /// /// string::index-of('testing string', '') ==> 0 /// /// /// string::index-of('testing string', 'Test') ==> -1 /// /// /// string::index-of('testing string', 'ing') ==> 4 /// [Function("index-of")] public static int IndexOf(string source, string value) { return CultureInfo.InvariantCulture.CompareInfo.IndexOf(source, value, CompareOptions.None); } /// /// Returns the position of the last occurrence in the specified string /// of the given search string. /// /// The string to search. /// The string to locate within . /// /// /// The highest-index position of in /// if it is found, or -1 if /// does not contain . /// /// /// If is an empty string, the return value /// is the last index position in . /// /// /// /// This function performs a case-sensitive word search using the /// invariant culture. /// /// /// string::last-index-of('testing string', 'test') ==> 0 /// /// /// string::last-index-of('testing string', '') ==> 13 /// /// /// string::last-index-of('testing string', 'Test') ==> -1 /// /// /// string::last-index-of('testing string', 'ing') ==> 11 /// [Function("last-index-of")] public static int LastIndexOf(string source, string value) { return CultureInfo.InvariantCulture.CompareInfo.LastIndexOf(source, value, CompareOptions.None); } /// /// Returns the given string left-padded to the given length. /// /// The that needs to be left-padded. /// The number of characters in the resulting string, equal to the number of original characters plus any additional padding characters. /// A Unicode padding character. /// /// If the length of is at least /// , then a new identical /// to is returned. Otherwise, /// will be padded on the left with as many /// characters as needed to create a length of . /// /// is less than zero. /// /// Note that only the first character of /// will be used when padding the result. /// /// /// string::pad-left('test', 10, ' ') ==> ' test' /// /// /// string::pad-left('test', 10, 'test') ==> 'tttttttest' /// /// /// string::pad-left('test', 3, ' ') ==> 'test' /// /// /// string::pad-left('test', -4, ' ') ==> ERROR /// [Function("pad-left")] public static string PadLeft(string s, int totalWidth, string paddingChar) { return s.PadLeft(totalWidth, paddingChar[0]); } /// /// Returns the given string right-padded to the given length. /// /// The that needs to be right-padded. /// The number of characters in the resulting string, equal to the number of original characters plus any additional padding characters. /// A Unicode padding character. /// /// If the length of is at least /// , then a new identical /// to is returned. Otherwise, /// will be padded on the right with as many /// characters as needed to create a length of . /// /// is less than zero. /// /// Note that only the first character of /// will be used when padding the result. /// /// /// string::pad-right('test', 10, ' ') ==> 'test ' /// /// /// string::pad-right('test', 10, 'abcd') ==> 'testaaaaaa' /// /// /// string::pad-right('test', 3, ' ') ==> 'test' /// /// /// string::pad-right('test', -3, ' ') ==> ERROR /// [Function("pad-right")] public static string PadRight(string s, int totalWidth, string paddingChar) { return s.PadRight(totalWidth, paddingChar[0]); } /// /// Returns the given string trimmed of whitespace. /// /// input string /// /// The string with any leading or trailing /// white space characters removed. /// /// /// string::trim(' test ') ==> 'test' /// /// /// string::trim('\t\tfoo \r\n') ==> 'foo' /// [Function("trim")] public static string Trim(string s) { return s.Trim(); } /// /// Returns the given string trimmed of leading whitespace. /// /// input string /// /// The string with any leading /// whites pace characters removed. /// /// /// string::trim-start(' test ') ==> 'test ' /// /// /// string::trim-start('\t\tfoo \r\n') ==> 'foo \r\n' /// [Function("trim-start")] public static string TrimStart(string s) { return s.TrimStart(); } /// /// Returns the given string trimmed of trailing whitespace. /// /// input string /// /// The string with any trailing /// white space characters removed. /// /// /// string::trim-end(' test ') ==> ' test' /// /// /// string::trim-end('\t\tfoo \r\n') ==> '\t\tfoo' /// [Function("trim-end")] public static string TrimEnd(string s) { return s.TrimEnd(); } #endregion Public Static Methods } } nant-0.92-rc1/src/NAnt.Core/Functions/VersionFunctions.cs0000644000175000017500000001400311757302273023161 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Reflection; using NAnt.Core; using NAnt.Core.Attributes; namespace NAnt.Core.Functions { [FunctionSet("version", "Version")] public class VersionFunctions : FunctionSetBase { #region Public Instance Constructors public VersionFunctions(Project project, PropertyDictionary properties) : base(project, properties) { } #endregion Public Instance Constructors #region Public Static Methods /// /// Gets the value of the major component of a given version. /// /// A version. /// /// The major version number. /// /// /// /// [Function("get-major")] public static int GetMajor(Version version) { return version.Major; } /// /// Gets the value of the minor component of a given version. /// /// A version. /// /// The minor version number. /// /// /// /// [Function("get-minor")] public static int GetMinor(Version version) { return version.Minor; } /// /// Gets the value of the build component of a given version. /// /// A version. /// /// The build number, or -1 if the build number is undefined. /// /// /// /// [Function("get-build")] public static int GetBuild(Version version) { return version.Build; } /// /// Gets the value of the revision component of a given version. /// /// A version. /// /// The revision number, or -1 if the revision number is undefined. /// /// /// /// [Function("get-revision")] public static int GetRevision(Version version) { return version.Revision; } #endregion Public Static Methods } [FunctionSet("version", "Conversion")] public class VersionConversionFunctions : FunctionSetBase { #region Public Instance Constructors public VersionConversionFunctions(Project project, PropertyDictionary properties) : base(project, properties) { } #endregion Public Instance Constructors #region Public Static Methods /// /// Converts the specified string representation of a version to /// its equivalent. /// /// A string containing the major, minor, build, and revision numbers, where each number is delimited with a period character ('.'). /// /// A instance representing the specified /// . /// /// has fewer than two components or more than four components. /// A major, minor, build, or revision component is less than zero. /// At least one component of does not parse to a decimal integer. [Function("parse")] public static Version Parse(string version) { return new Version(version); } /// /// Converts the specified to its equivalent /// string representation. /// /// A to convert. /// /// The string representation of the values of the major, minor, build, /// and revision components of the specified . /// /// /// /// [Function("to-string")] public static string ToString(Version value) { return value.ToString(); } #endregion Public Static Methods } } nant-0.92-rc1/src/NAnt.Core/Functions/Int32Functions.cs0000644000175000017500000000627411757302273022446 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Globalization; using NAnt.Core; using NAnt.Core.Types; using NAnt.Core.Attributes; namespace NAnt.Core.Functions { [FunctionSet("int", "Conversion")] public class Int32ConversionFunctions : FunctionSetBase { #region Public Instance Constructors public Int32ConversionFunctions(Project project, PropertyDictionary properties) : base(project, properties) { } #endregion Public Instance Constructors #region Public Static Methods /// /// Converts the specified string representation of a number to its /// 32-bit signed integer equivalent. /// /// A string containing a number to convert. /// /// A 32-bit signed integer equivalent to the number contained in /// . /// /// is not of the correct format. /// represents a number less than or greater than . /// /// The for the invariant culture is /// used to supply formatting information about . /// [Function("parse")] public static int Parse(string s) { return int.Parse(s, CultureInfo.InvariantCulture); } /// /// Converts the specified to its equivalent string /// representation. /// /// A to convert. /// /// The string representation of , consisting /// of a negative sign if the value is negative, and a sequence of /// digits ranging from 0 to 9 with no leading zeroes. /// /// /// is formatted with the /// for the invariant culture. /// [Function("to-string")] public static string ToString(int value) { return value.ToString(CultureInfo.InvariantCulture); } #endregion Public Static Methods } } nant-0.92-rc1/src/NAnt.Core/Functions/MathFunctions.cs0000644000175000017500000000640211757302273022431 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian Maclean (imaclean@gmail.com) // Jaroslaw Kowalski (jkowalski@users.sourceforge.net) using System; using System.Collections; using System.Globalization; using System.IO; using System.Reflection; using NAnt.Core; using NAnt.Core.Types; using NAnt.Core.Attributes; namespace NAnt.Core.Functions { [FunctionSet("math", "Math")] public class MathFunctions : FunctionSetBase { #region Public Instance Constructors public MathFunctions(Project project, PropertyDictionary properties) : base(project, properties) { } #endregion Public Instance Constructors #region Public Static Methods /// /// Rounds the value to the nearest whole number /// /// Number to be rounded, can be anything convertible to a double. /// /// Rounded value. /// [Function("round")] public static double Round(double value) { return Math.Round(value); } /// /// Returns the largest whole number less than or equal to the specified /// number. /// /// value to be , can be anything convertible to a double /// /// The largest whole number less than or equal to the specified number. /// [Function("floor")] public static double Floor(double value) { return Math.Floor(value); } /// /// Returns the smallest whole number greater than or equal to the specified number /// /// value /// /// The smallest whole number greater than or equal to the specified number. /// [Function("ceiling")] public static double Ceiling(double value) { return Math.Ceiling(value); } /// /// Returns the absolute value of the specified number /// /// value to take the absolute value from /// /// when is greater /// than or equal to zero; otherwise, -. /// [Function("abs")] public static double Abs(double value) { return Math.Abs(value); } #endregion Public Static Methods } } nant-0.92-rc1/src/NAnt.Core/Functions/FileVersionInfoFunctions.cs0000644000175000017500000001125011757302273024576 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Diagnostics; using System.IO; using System.Reflection; using NAnt.Core; using NAnt.Core.Types; using NAnt.Core.Attributes; namespace NAnt.Core.Functions { /// /// Functions that provide version information for a physical file on disk. /// [FunctionSet("fileversioninfo", "Version")] public class FileVersionInfoFunctions : FunctionSetBase { #region Public Instance Constructors public FileVersionInfoFunctions(Project project, PropertyDictionary properties) : base(project, properties) {} #endregion Public Instance Constructors #region Public Instance Methods /// /// Returns a representing the version /// information associated with the specified file. /// /// The file to retrieve the version information for. /// /// A containing information about the file. /// /// The file specified cannot be found. [Function("get-version-info")] public FileVersionInfo GetVersionInfo(string fileName) { return FileVersionInfo.GetVersionInfo( Project.GetFullPath(fileName)); } #endregion Public Instance Methods #region Public Static Methods /// /// Gets the name of the company that produced the file. /// /// A instance containing version information about a file. /// /// The name of the company that produced the file. /// [Function("get-company-name")] public static string GetCompanyName(FileVersionInfo fileVersionInfo) { return fileVersionInfo.CompanyName; } /// /// Gets the file version of a file. /// /// A instance containing version information about a file. /// /// The file version of a file. /// /// [Function("get-file-version")] public static Version GetFileVersion(FileVersionInfo fileVersionInfo) { return new Version(fileVersionInfo.FileMajorPart, fileVersionInfo.FileMinorPart, fileVersionInfo.FileBuildPart, fileVersionInfo.FilePrivatePart); } /// /// Gets the name of the product the file is distributed with. /// /// A instance containing version information about a file. /// /// The name of the product the file is distributed with. /// [Function("get-product-name")] public static string GetProductName(FileVersionInfo fileVersionInfo) { return fileVersionInfo.ProductName; } /// /// Gets the product version of a file. /// /// A instance containing version information about a file. /// /// The product version of a file. /// /// [Function("get-product-version")] public static Version GetProductVersion(FileVersionInfo fileVersionInfo) { return new Version(fileVersionInfo.ProductMajorPart, fileVersionInfo.ProductMinorPart, fileVersionInfo.ProductBuildPart, fileVersionInfo.ProductPrivatePart); } #endregion Public Static Methods } } nant-0.92-rc1/src/NAnt.Core/Functions/EnvironmentFunctions.cs0000644000175000017500000002032711757302273024046 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian Maclean (imaclean@gmail.com) // Jaroslaw Kowalski (jkowalski@users.sourceforge.net) using System; using System.IO; using System.Collections; using System.Reflection; using System.Globalization; using NAnt.Core; using NAnt.Core.Types; using NAnt.Core.Attributes; using NAnt.Core.Util; namespace NAnt.Core.Functions { /// /// Provide information about the current environment and platform. /// [FunctionSet("environment", "Environment")] public class EnvironmentFunctions : FunctionSetBase { #region Public Instance Constructors public EnvironmentFunctions(Project project, PropertyDictionary properties) : base(project, properties) { } #endregion Public Instance Constructors #region Public Instance Methods /// /// Gets the path to the system special folder identified by the /// specified enumeration. /// /// An enumerated constant that identifies a system special folder. /// /// The path to the specified system special folder, if that folder /// physically exists on your computer; otherwise, the empty string (""). /// /// is not a member of . /// /// /// Copy "out.log" from the project base directory to the /// program files directory. /// /// /// /// ]]> /// /// [Function("get-folder-path")] public static string GetFolderPath(Environment.SpecialFolder folder) { return Environment.GetFolderPath(folder); } /// /// Gets the NetBIOS name of this local computer. /// /// /// The NetBIOS name of this local computer. /// /// The name of this computer cannot be obtained. [Function("get-machine-name")] public static string GetMachineName() { return Environment.MachineName; } /// /// Gets an object that represents the /// current operating system. /// /// /// An object that contains the current /// platform identifier and version number. /// /// /// /// Output string representation of the current operating system. /// /// /// /// ]]> /// /// If the operating system is Windows 2000, the output is: /// /// Microsoft Windows NT 5.0.2195.0 /// /// /// [Function("get-operating-system")] public static OperatingSystem GetOperatingSystem() { return Environment.OSVersion; } /// /// Gets the user name of the person who started the current thread. /// /// /// The name of the person logged on to the system who started the /// current thread. /// /// /// /// Modify the home directory of the current user on unix-based systems. /// /// /// /// /// /// /// /// ]]> /// /// [Function("get-user-name")] public static string GetUserName() { return Environment.UserName; } /// /// Returns the value of the specified environment variable. /// /// The environment variable of which the value should be returned. /// /// The value of the specified environment variable. /// /// Environment variable does not exist. [Function("get-variable")] public static string GetVariable(string name) { if (!VariableExists(name)) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1095"), name)); } return Environment.GetEnvironmentVariable(name); } /// /// Gets a value indicating whether the specified environment variable /// exists. /// /// The environment variable that should be checked. /// /// if the environment variable exists; otherwise, /// . /// /// /// /// Execute a set of tasks only if the "BUILD_DEBUG" environment /// variable is set. /// /// /// /// ... /// /// ]]> /// /// [Function("variable-exists")] public static bool VariableExists(string name) { return (Environment.GetEnvironmentVariable(name) != null); } /// /// Gets a object that describes the major, /// minor, build, and revision numbers of the Common Language Runtime. /// /// /// A Version object. /// /// /// Output the major version of the CLR. /// /// /// ]]> /// /// [Function("get-version")] public static Version GetVersion() { return Environment.Version; } /// /// Gets the newline string defined for this environment. /// /// /// A string containing CRLF for non-Unix platforms, or LF for Unix /// platforms. /// /// /// Output two lines in a log file. /// /// /// ]]> /// /// [Function("newline")] public static string NewLine() { return Environment.NewLine; } #endregion Public Instance Methods } } nant-0.92-rc1/src/NAnt.Core/Functions/FileFunctions.cs0000644000175000017500000002514611757302273022425 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian Maclean (imaclean@gmail.com) // Jaroslaw Kowalski (jkowalski@users.sourceforge.net) using System; using System.Collections; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Security; using NAnt.Core; using NAnt.Core.Types; using NAnt.Core.Attributes; namespace NAnt.Core.Functions { /// /// Groups a set of functions for dealing with files. /// [FunctionSet("file", "File")] public class FileFunctions : FunctionSetBase { #region Public Instance Constructors public FileFunctions(Project project, PropertyDictionary properties) : base(project, properties) { } #endregion Public Instance Constructors #region Public Instance Methods /// /// Returns the creation date and time of the specified file. /// /// The file for which to obtain creation date and time information. /// /// The creation date and time of the specified file. /// /// The specified file does not exist. /// is a zero-length string, contains only white space, or contains one or more invalid characters. /// The specified path, file name, or both exceed the system-defined maximum length. /// The parameter is in an invalid format. [Function("get-creation-time")] public DateTime GetCreationTime(string path) { string fullPath = Project.GetFullPath(path); // File.GetCreationTime no longer throws an IOException on // .NET 2.0 if the path does not exist, so we take care of this // ourselves to ensure the behaviour of this function remains // consistent across different CLR versions if (!File.Exists(fullPath)) { throw new IOException(string.Format(CultureInfo.InvariantCulture, "Could not find a part of the path \"{0}\".", fullPath)); } return File.GetCreationTime(fullPath); } /// /// Returns the date and time the specified file was last written to. /// /// The file for which to obtain write date and time information. /// /// The date and time the specified file was last written to. /// /// The specified file does not exist. /// is a zero-length string, contains only white space, or contains one or more invalid characters. /// The specified path, file name, or both exceed the system-defined maximum length. [Function("get-last-write-time")] public DateTime GetLastWriteTime(string path) { string fullPath = Project.GetFullPath(path); // File.GetLastWriteTime no longer throws an IOException on // .NET 2.0 if the path does not exist, so we take care of this // ourselves to ensure the behaviour of this function remains // consistent across different CLR versions if (!File.Exists(fullPath)) { throw new IOException(string.Format(CultureInfo.InvariantCulture, "Could not find a part of the path \"{0}\".", fullPath)); } return File.GetLastWriteTime(fullPath); } /// /// Returns the date and time the specified file was last accessed. /// /// The file for which to obtain access date and time information. /// /// The date and time the specified file was last accessed. /// /// The specified file does not exist. /// is a zero-length string, contains only white space, or contains one or more invalid characters. /// The specified path, file name, or both exceed the system-defined maximum length. /// The parameter is in an invalid format. [Function("get-last-access-time")] public DateTime GetLastAccessTime(string path) { string fullPath = Project.GetFullPath(path); // File.GetLastAccessTime no longer throws an IOException on // .NET 2.0 if the path does not exist, so we take care of this // ourselves to ensure the behaviour of this function remains // consistent across different CLR versions if (!File.Exists(fullPath)) { throw new IOException(string.Format(CultureInfo.InvariantCulture, "Could not find a part of the path \"{0}\".", fullPath)); } return File.GetLastAccessTime(fullPath); } /// /// Determines whether the specified file exists. /// /// The file to check. /// /// if refers to an /// existing file; otherwise, . /// /// /// Execute a set of tasks, if file "output.xml" does not exist. /// /// /// ... /// /// ]]> /// /// [Function("exists")] public bool Exists(string file) { return File.Exists(Project.GetFullPath(file)); } /// /// Determines whether is more or equal /// up-to-date than . /// /// The file to check against the target file. /// The file for which we want to determine the status. /// /// if is more /// or equal up-to-date than ; otherwise, /// . /// /// or is a zero-length string, contains only white space, or contains one or more invalid characters. /// The specified path, file name, or both of either or exceed the system-defined maximum length. [Function("up-to-date")] public bool UpToDate(string srcFile, string targetFile) { string srcPath = Project.GetFullPath(srcFile); string targetPath = Project.GetFullPath(targetFile); if (!File.Exists(targetPath)) { // if targetFile does not exist, we consider it out-of-date return false; } // get lastwritetime of targetFile DateTime targetLastWriteTime = File.GetLastWriteTime(targetPath); // determine whether lastwritetime of srcFile is more recent // than lastwritetime or targetFile string newerFile = FileSet.FindMoreRecentLastWriteTime( srcPath, targetLastWriteTime); // return true if srcFile is not newer than target file return newerFile == null; } /// /// Gets the length of the file. /// /// filename /// /// Length in bytes, of the file named . /// /// The file specified cannot be found. [Function("get-length")] public long GetLength(string file) { FileInfo fi = new FileInfo(Project.GetFullPath(file)); return fi.Length; } /// /// Checks if a given file is an assembly. /// /// The name or path of the file to be checked. /// True if the file is a valid assembly, false if it's not or if the assembly seems corrupted (invalid headers or metadata). /// is a null . /// is an empty . /// is not found, or the file you are trying to check does not specify a filename extension. /// The caller does not have path discovery permission. [Function("is-assembly")] public bool IsAssembly(string assemblyFile) { try { AssemblyName.GetAssemblyName(Project.GetFullPath(assemblyFile)); //no exception occurred, this is an assembly return true; } catch (FileLoadException) { return false; } catch (BadImageFormatException) { return false; } } #endregion Public Instance Methods } } nant-0.92-rc1/src/NAnt.Core/Functions/AssemblyNameFunctions.cs0000644000175000017500000001536711757302273024132 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.IO; using System.Reflection; using NAnt.Core; using NAnt.Core.Attributes; namespace NAnt.Core.Functions { /// /// Functions that return information about an assembly's identity. /// [FunctionSet("assemblyname", "Assembly")] public class AssemblyNameFunctions : FunctionSetBase { #region Public Instance Constructors public AssemblyNameFunctions(Project project, PropertyDictionary properties) : base(project, properties) {} #endregion Public Instance Constructors #region Public Static Methods /// /// Gets the location of the assembly as a URL. /// /// The of the assembly. /// /// The location of the assembly as a URL. /// /// [Function("get-codebase")] public static string GetCodeBase(AssemblyName assemblyName) { return assemblyName.CodeBase; } /// /// Gets the URI, including escape characters, that represents the codebase. /// /// The of the assembly. /// /// The URI, including escape characters, that represents the codebase. /// /// [Function("get-escaped-codebase")] public static string GetEscapedCodeBase(AssemblyName assemblyName) { return assemblyName.EscapedCodeBase; } /// /// Gets the full name of the assembly, also known as the display name. /// /// The of the assembly. /// /// The full name of the assembly, also known as the display name. /// /// /// /// Output the full name of the nunit.framework assembly to the /// build log. /// /// /// /// ]]> /// /// /// [Function("get-full-name")] public static string GetFullName(AssemblyName assemblyName) { return assemblyName.FullName; } /// /// Gets the simple, unencrypted name of the assembly. /// /// The of the assembly. /// /// The simple, unencrypted name of the assembly. /// /// /// /// Output the simple name of the nunit.framework assembly to /// the build log. /// /// /// /// ]]> /// /// /// [Function("get-name")] public static string GetName(AssemblyName assemblyName) { return assemblyName.Name; } /// /// Gets the version of the assembly. /// /// The of the assembly. /// /// The version of the assembly. /// /// /// /// Output the major version of the nunit.framework assembly /// to the build log. /// /// /// /// ]]> /// /// /// /// [Function("get-version")] public static Version GetVersion(AssemblyName assemblyName) { return assemblyName.Version; } /// /// Gets the for a given file. /// /// The assembly file for which to get the . /// /// An object representing the given file. /// /// is an empty . /// does not exist. /// is not a valid assembly. /// /// The assembly is not added to this domain. /// /// /// /// Output the full name of the nunit.framework assembly to the /// build log. /// /// /// /// ]]> /// /// [Function("get-assembly-name")] public AssemblyName GetAssemblyName(string assemblyFile) { return AssemblyName.GetAssemblyName(Project.GetFullPath(assemblyFile)); } #endregion Public Static Methods } } nant-0.92-rc1/src/NAnt.Core/Functions/OperatingSystemFunctions.cs0000644000175000017500000000760511757302273024703 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.IO; using System.Reflection; using NAnt.Core; using NAnt.Core.Types; using NAnt.Core.Attributes; namespace NAnt.Core.Functions { /// /// Functions that return information about an operating system. /// [FunctionSet("operating-system", "Operating System")] public class OperatingSystemFunctions : FunctionSetBase { #region Public Instance Constructors public OperatingSystemFunctions(Project project, PropertyDictionary properties) : base(project, properties) {} #endregion Public Instance Constructors #region Public Static Methods /// /// Gets a value that identifies the operating /// system platform. /// /// The operating system. /// /// value that identifies the operating system /// platform. /// /// [Function("get-platform")] public static PlatformID GetPlatform(OperatingSystem operatingSystem) { return operatingSystem.Platform; } /// /// Gets a object that identifies this operating /// system. /// /// The operating system. /// /// A object that describes the major version, /// minor version, build, and revision of the operating system. /// /// [Function("get-version")] public static Version GetVersion(OperatingSystem operatingSystem) { return operatingSystem.Version; } /// /// Converts the value of the specified operating system to its equivalent /// representation. /// /// The operating system. /// /// The representation of /// . /// /// /// /// Output string representation of the current operating system. /// /// /// /// ]]> /// /// If the operating system is Windows 2000, the output is: /// /// Microsoft Windows NT 5.0.2195.0 /// /// /// [Function("to-string")] public static string ToString(OperatingSystem operatingSystem) { return operatingSystem.ToString(); } #endregion Public Static Methods } } nant-0.92-rc1/src/NAnt.Core/Functions/ConversionFunctions.cs0000644000175000017500000001070011757302273023661 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian Maclean (imaclean@gmail.com) // Jaroslaw Kowalski (jkowalski@users.sourceforge.net) using System; using System.IO; using System.Collections; using System.Reflection; using System.Globalization; using NAnt.Core; using NAnt.Core.Types; using NAnt.Core.Attributes; namespace NAnt.Core.Functions { [FunctionSet("convert", "Conversion")] public class ConversionFunctions : FunctionSetBase { #region Public Instance Constructors public ConversionFunctions(Project project, PropertyDictionary propDict ) : base(project, propDict) {} #endregion Public Instance Constructors #region Public Static Methods /// /// Converts the argument to an integer. /// /// value to be converted /// converted to integer. The function fails with an exception when the conversion is not possible. [Function("to-int")] [Obsolete("Use type-specific conversion functions instead.", false)] public static int ToInt(int value) { return value; // conversion is done at the invocation level } /// /// Converts the argument to double /// /// The value to be converted. /// converted to double. The function fails with an exception when the conversion is not possible. [Function("to-double")] [Obsolete("Use type-specific conversion functions instead.", false)] public static double ToDouble(double value) { return value; // conversion is done at the invocation level } /// /// Converts the argument to a string. /// /// The value to be converted. /// /// converted to string. The function fails /// with an exception when the conversion is not possible. /// /// /// Named method ConvertToString as a static ToString method would break /// CLS compliance. /// [Function("to-string")] [Obsolete("Use type-specific conversion functions instead.", false)] public static string ConvertToString(string value) { return value; // conversion is done at the invocation level } /// /// Converts the argument to a datetime. /// /// value to be converted /// converted to datetime. The function fails with an exception when the conversion is not possible. [Function("to-datetime")] [Obsolete("Use type-specific conversion functions instead.", false)] public static DateTime ToDateTime(DateTime value) { return value; // conversion is done at the invocation level } /// /// Converts the argument to a boolean /// /// The string value to be converted to boolean. Must be 'true' or 'false'. /// /// converted to boolean. The function fails /// with an exception when the conversion is not possible. /// [Function("to-boolean")] [Obsolete("Use type-specific conversion functions instead.", false)] public static bool ToBoolean(bool value) { return value; // conversion is done at the invocation level } #endregion Public Static Methods } } nant-0.92-rc1/src/NAnt.Core/Functions/DnsFunctions.cs0000644000175000017500000000361311757302273022265 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2007 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Net; using System.Net.Sockets; using NAnt.Core; using NAnt.Core.Types; using NAnt.Core.Attributes; namespace NAnt.Core.Functions { /// /// Functions for requesting information from DNS. /// [FunctionSet("dns", "DNS")] public class DnsFunctions : FunctionSetBase { #region Public Instance Constructors public DnsFunctions(Project project, PropertyDictionary properties) : base(project, properties) {} #endregion Public Instance Constructors #region Public Instance Methods /// /// Gets the host name of the local computer. /// /// /// A string that contains the DNS host name of the local computer. /// /// An error is encountered when resolving the local host name. [Function("get-host-name")] public static string GetHostName() { return Dns.GetHostName(); } #endregion Public Static Methods } } nant-0.92-rc1/src/NAnt.Core/Functions/DirectoryFunctions.cs0000644000175000017500000002445711757302273023516 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian Maclean (imaclean@gmail.com) // Jaroslaw Kowalski (jkowalski@users.sourceforge.net) using System; using System.IO; using System.Collections; using System.Reflection; using System.Globalization; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.Core.Functions { /// /// Groups a set of functions for dealing with directories. /// [FunctionSet("directory", "Directory")] public class DirectoryFunctions : FunctionSetBase { #region Public Instance Constructors public DirectoryFunctions(Project project, PropertyDictionary properties) : base(project, properties) { } #endregion Public Instance Constructors #region Public Instance Methods /// /// Returns the creation date and time of the specified directory. /// /// The directory for which to obtain creation date and time information. /// /// The creation date and time of the specified directory. /// /// The specified directory does not exist. /// is a zero-length string, contains only white space, or contains one or more invalid characters. /// The specified path, file name, or both exceed the system-defined maximum length. [Function("get-creation-time")] public DateTime GetCreationTime(string path) { string fullPath = Project.GetFullPath(path); // Directory.GetCreationTime no longer throws an IOException on // .NET 2.0 if the path does not exist, so we take care of this // ourselves to ensure the behaviour of this function remains // consistent across different CLR versions if (!Directory.Exists(fullPath)) { throw new IOException(string.Format(CultureInfo.InvariantCulture, "Could not find a part of the path \"{0}\".", fullPath)); } return Directory.GetCreationTime(fullPath); } /// /// Returns the date and time the specified directory was last written to. /// /// The directory for which to obtain write date and time information. /// /// The date and time the specified directory was last written to. /// /// The specified directory does not exist. /// is a zero-length string, contains only white space, or contains one or more invalid characters. /// The specified path, file name, or both exceed the system-defined maximum length. [Function("get-last-write-time")] public DateTime GetLastWriteTime(string path) { string fullPath = Project.GetFullPath(path); // Directory.GetLastWriteTime no longer throws an IOException on // .NET 2.0 if the path does not exist, so we take care of this // ourselves to ensure the behaviour of this function remains // consistent across different CLR versions if (!Directory.Exists(fullPath)) { throw new IOException(string.Format(CultureInfo.InvariantCulture, "Could not find a part of the path \"{0}\".", fullPath)); } return Directory.GetLastWriteTime(fullPath); } /// /// Returns the date and time the specified directory was last accessed. /// /// The directory for which to obtain access date and time information. /// /// The date and time the specified directory was last accessed. /// /// The specified directory does not exist. /// is a zero-length string, contains only white space, or contains one or more invalid characters. /// The specified path, file name, or both exceed the system-defined maximum length. /// The parameter is in an invalid format. [Function("get-last-access-time")] public DateTime GetLastAccessTime(string path) { string fullPath = Project.GetFullPath(path); // Directory.GetLastAccessTime no longer throws an IOException on // .NET 2.0 if the path does not exist, so we take care of this // ourselves to ensure the behaviour of this function remains // consistent across different CLR versions if (!Directory.Exists(fullPath)) { throw new IOException(string.Format(CultureInfo.InvariantCulture, "Could not find a part of the path \"{0}\".", fullPath)); } return Directory.GetLastAccessTime(fullPath); } /// /// Gets the current working directory. /// /// /// A containing the path of the current working /// directory. /// [Function("get-current-directory")] public static string GetCurrentDirectory() { return Directory.GetCurrentDirectory(); } /// /// Retrieves the parent directory of the specified path. /// /// The path for which to retrieve the parent directory. /// /// The parent directory, or an empty if /// is the root directory, including the root /// of a UNC server or share name. /// /// The directory specified by is read-only. /// is a zero-length string, contains only white space, or contains one or more invalid characters. /// The specified path, file name, or both exceed the system-defined maximum length. /// The specified path was not found. /// /// /// Copy "readme.txt" from the current working directory to /// its parent directory. /// /// /// /// /// /// ]]> /// /// [Function("get-parent-directory")] public string GetParentDirectory(string path) { // do not use Directory.GetParent() as that will not return the // parent if the directory ends with the directory separator DirectoryInfo directory = new DirectoryInfo(Project.GetFullPath(path)); DirectoryInfo parentDirectory = directory.Parent; return parentDirectory != null ? parentDirectory.FullName : string.Empty; } /// /// Returns the volume information, root information, or both for the /// specified path. /// /// The path for which to retrieve the parent directory. /// /// A string containing the volume information, root information, or /// both for the specified path. /// /// is a zero-length string, contains only white space, or contains one or more invalid characters. /// The specified path, file name, or both exceed the system-defined maximum length. [Function("get-directory-root")] public string GetDirectoryRoot(string path) { string directoryRoot = Directory.GetDirectoryRoot( Project.GetFullPath(path)); return StringUtils.ConvertNullToEmpty(directoryRoot); } /// /// Determines whether the given path refers to an existing directory /// on disk. /// /// The path to test. /// /// if refers to an /// existing directory; otherwise, . /// /// /// Remove directory "test", if it exists. /// /// /// ]]> /// /// [Function("exists")] public bool Exists(string path) { return Directory.Exists(Project.GetFullPath(path)); } #endregion Public Instance Methods } } nant-0.92-rc1/src/NAnt.Core/Functions/PkgConfigFunctions.cs0000644000175000017500000003165411757302273023416 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian Maclean (imaclean@gmail.com) // Jaroslaw Kowalski (jkowalski@users.sourceforge.net) // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.ComponentModel; using System.IO; using System.Collections; using System.Reflection; using System.Globalization; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Tasks; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.Core.Functions { [FunctionSet("pkg-config", "Unix/Cygwin")] public class PkgConfigFunctions : FunctionSetBase { #region Public Instance Constructors public PkgConfigFunctions(Project project, PropertyDictionary properties) : base(project, properties) { } #endregion Public Instance Constructors #region Public Instance Methods /// /// Gets the value of a variable for the specified package. /// /// The package for which the variable should be retrieved. /// The name of the variable. /// /// The value of variable for the specified /// package. /// /// pkg-config could not be started. /// does not exist. [Function("get-variable")] public string GetVariable(string package, string name) { if (!Exists(package)) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1100"), package)); } return RunPkgConfigString(new Argument[] { new Argument("--variable=\"" + name + "\""), new Argument(package) }); } /// /// Gets the link flags required to compile the package, including all /// its dependencies. /// /// The package for which the link flags should be retrieved. /// /// The link flags required to compile the package. /// /// pkg-config could not be started. /// does not exist. [Function("get-link-flags")] public string GetLinkFlags(string package) { if (!Exists(package)) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1100"), package)); } return RunPkgConfigString(new Argument[] { new Argument("--libs"), new Argument(package) }); } /// /// Gets the compile flags required to compile the package, including all /// its dependencies. /// /// The package for which the compile flags should be retrieved. /// /// The pre-processor and compile flags required to compile the package. /// /// pkg-config could not be started. /// does not exist. [Function("get-compile-flags")] public string GetCompileFlags(string package) { if (!Exists(package)) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1100"), package)); } return RunPkgConfigString(new Argument[] { new Argument("--cflags"), new Argument(package) }); } /// /// Determines the version of the given package. /// /// The package to get the version of. /// /// The version of the given package. /// /// pkg-config could not be started. /// does not exist. [Function("get-mod-version")] public string GetModVersion(string package) { if (!Exists(package)) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1100"), package)); } return RunPkgConfigString( new Argument[]{ new Argument("--modversion"), new Argument(package) }); } /// /// Determines whether the given package is at least version /// . /// /// The package to check. /// The version the package should at least have. /// /// if the given package is at least version /// ; otherwise, . /// /// pkg-config could not be started. [Function("is-atleast-version")] public bool IsAtLeastVersion(string package, string version) { return RunPkgConfigBool( new Argument[]{ new Argument("--atleast-version=\"" + version + "\""), new Argument(package) }); } /// /// Determines whether the given package is exactly version /// . /// /// The package to check. /// The version the package should have. /// /// if the given package is exactly version /// ; otherwise, . /// /// pkg-config could not be started. [Function("is-exact-version")] public bool IsExactVersion(string package, string version) { return RunPkgConfigBool( new Argument[]{ new Argument("--exact-version=\"" + version + "\""), new Argument(package)}); } /// /// Determines whether the given package is at no newer than version /// . /// /// The package to check. /// The version the package should maximum have. /// /// if the given package is at no newer than /// version ; otherwise, . /// /// pkg-config could not be started. [Function("is-max-version")] public bool IsMaxVersion(string package, string version) { return RunPkgConfigBool( new Argument[]{ new Argument("--max-version=\"" + version + "\""), new Argument(package) }); } /// /// Determines whether the given package is between two versions. /// /// The package to check. /// The version the package should at least have. /// The version the package should maximum have. /// /// if the given package is between /// and ; otherwise, . /// /// pkg-config could not be started. [Function("is-between-version")] public bool IsBetweenVersion(string package, string minVersion, string maxVersion) { return RunPkgConfigBool( new Argument[]{ new Argument("--atleast-version=\"" + minVersion + "\""), new Argument("--max-version=\"" + maxVersion + "\""), new Argument(package) } ); } /// /// Determines whether the given package exists. /// /// The package to check. /// /// if the package exists; otherwise, /// . /// /// pkg-config could not be started. [Function("exists")] public bool Exists(string package) { return RunPkgConfigBool( new Argument[]{ new Argument("--exists"), new Argument(package)} ); } #endregion Public Instance Methods #region Private Instance Methods /// /// Runs pkg-config with the specified arguments and returns a /// based on the exit code. /// /// The arguments to pass to pkg-config. /// /// if pkg-config exited with exit code 0; /// otherwise, /// private bool RunPkgConfigBool(Argument[] args) { MemoryStream ms = new MemoryStream(); ExecTask execTask = GetTask(ms); execTask.Arguments.AddRange(args); try { execTask.Execute(); return true; } catch (Exception) { if (execTask.ExitCode == ExternalProgramBase.UnknownExitCode) { // process could not be started or did not exit in time throw; } return false; } } /// /// Runs pkg-config with the specified arguments and returns the result /// as a . /// /// The arguments to pass to pkg-config. /// /// The result of running pkg-config with the specified arguments. /// private string RunPkgConfigString(Argument[] args) { MemoryStream ms = new MemoryStream(); ExecTask execTask = GetTask(ms); execTask.Arguments.AddRange(args); try { execTask.Execute(); ms.Position = 0; StreamReader sr = new StreamReader(ms); string output = sr.ReadLine(); sr.Close(); return output; } catch (Exception ex) { ms.Position = 0; StreamReader sr = new StreamReader(ms); string output = sr.ReadToEnd(); sr.Close(); if (output.Length != 0) { throw new BuildException(output, ex); } else { throw; } } } /// /// Factory method to return a new instance of ExecTask /// /// /// private ExecTask GetTask(Stream stream) { ExecTask execTask = new ExecTask(); execTask.Parent = Project; execTask.Project = Project; execTask.FileName = "pkg-config"; execTask.Threshold = Level.None; execTask.ErrorWriter = execTask.OutputWriter = new StreamWriter(stream); return execTask; } #endregion Private Instance Methods } } nant-0.92-rc1/src/NAnt.Core/Functions/NAntFunctions.cs0000644000175000017500000005110611757302273022401 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian Maclean (imaclean@gmail.com) // Jaroslaw Kowalski (jkowalski@users.sourceforge.net) // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; using System.ComponentModel; using System.Globalization; using System.IO; using System.Reflection; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Configuration; using NAnt.Core.Types; using NAnt.Core.Util; // // This file defines functions for the NAnt category. // // Please note that property::get-value() is defined in ExpressionEvaluator // class because it needs the intimate knowledge of the expressione evaluation stack. // Other functions should be defined here. // namespace NAnt.Core.Functions { [FunctionSet("nant", "NAnt")] public class NAntFunctions : FunctionSetBase { #region Public Instance Constructors public NAntFunctions(Project project, PropertyDictionary properties) : base(project, properties) { } #endregion Public Instance Constructors #region Public Instance Methods /// /// Gets the base directory of the appdomain in which NAnt is running. /// /// /// The base directory of the appdomain in which NAnt is running. /// [Function("get-base-directory")] public string GetBaseDirectory() { return AppDomain.CurrentDomain.BaseDirectory; } /// /// Gets the NAnt assembly. /// /// /// The NAnt assembly. /// [Function("get-assembly")] public Assembly GetAssembly() { Assembly assembly = Assembly.GetEntryAssembly(); // check if NAnt was launched as a console application if (assembly.GetName().Name != "NAnt") { // NAnt is being used as a class library, so return the // NAnt.Core assembly assembly = Assembly.GetExecutingAssembly(); } return assembly; } /// /// Searches the probing paths of the current target framework for the /// specified file. /// /// The name of the file to search for. /// /// The absolute path to if found in one of the /// configured probing; otherwise, an error is reported. /// /// could not be found in the configured probing paths. /// /// /// The (relative) probing paths are resolved relative to the base /// directory of the appdomain in which NAnt is running. /// /// /// The configured probing paths are scanned recursively in the order /// in which they are defined in the framework configuration. /// /// /// The file name to search should include the extension. /// /// /// /// /// Compile an assembly referencing the nunit.framework assembly /// for the current target framework that is shipped as part of the /// NAnt distribution. /// /// /// /// /// /// /// /// /// /// /// /// ]]> /// /// [Function("scan-probing-paths")] [EditorBrowsable(EditorBrowsableState.Never)] public string ScanProbingPaths(string fileName) { string libPath = null; FrameworkInfo fi = Project.TargetFramework; if (fi.Runtime != null) { string[] probingPaths = fi.Runtime.ProbingPaths.GetDirectories(); libPath = FileUtils.ResolveFile(probingPaths, fileName, true); } if (libPath == null) { throw new FileNotFoundException (string.Format (CultureInfo.InvariantCulture, "\"{0}\" could not be found in any of the configured " + "probing paths.", fileName)); } return libPath; } /// /// Searches the probing paths of the current target framework for the /// specified file. /// /// The directory to use a base directory for the probing paths. /// The name of the file to search for. /// /// The absolute path to if found in one of the /// configured probing; otherwise, an error is reported. /// /// could not be found in the configured probing paths. /// /// /// The (relative) probing paths are resolved relative to the specified /// base directory. /// /// /// The configured probing paths are scanned recursively in the order /// in which they are defined in the framework configuration. /// /// /// The file name to search should include the extension. /// /// /// /// /// Compile an assembly referencing the nunit.framework assembly /// for the current target framework that is shipped as part of the /// NAnt distribution. /// /// /// /// /// /// /// /// /// /// /// /// ]]> /// /// [Function("scan-probing-paths")] [EditorBrowsable(EditorBrowsableState.Never)] public string ScanProbingPaths(string baseDirectory, string fileName) { string libPath = null; FrameworkInfo fi = Project.TargetFramework; if (fi.Runtime != null) { string[] probingPaths = fi.Runtime.ProbingPaths.GetDirectories(baseDirectory); libPath = FileUtils.ResolveFile(probingPaths, fileName, true); } if (libPath == null) { throw new FileNotFoundException (string.Format (CultureInfo.InvariantCulture, "\"{0}\" could not be found in any of the configured " + "probing paths.", fileName)); } return libPath; } #endregion Public Instance Methods } [FunctionSet("project", "NAnt")] public class ProjectFunctions : FunctionSetBase { #region Public Instance Constructors public ProjectFunctions(Project project, PropertyDictionary properties) : base(project, properties) { } #endregion Public Instance Constructors #region Public Instance Methods /// /// Gets the name of the current project. /// /// /// The name of the current project, or an empty /// if no name is specified in the build file. /// [Function("get-name")] public string GetName() { return StringUtils.ConvertNullToEmpty(Project.ProjectName); } /// /// Gets the form of the build file. /// /// /// The form of the build file, or /// an empty if the project is not file backed. /// [Function("get-buildfile-uri")] public string GetBuildFileUri() { if (Project.BuildFileUri != null) { return Project.BuildFileUri.ToString(); } return string.Empty; } /// /// Gets the local path to the build file. /// /// /// The local path of the build file, or an empty /// if the project is not file backed. /// [Function("get-buildfile-path")] public string GetBuildFilePath() { return StringUtils.ConvertNullToEmpty(Project.BuildFileLocalName); } /// /// Gets the name of the target that will be executed when no other /// build targets are specified. /// /// /// The name of the target that will be executed when no other build /// targets are specified, or an empty if no /// default target is defined for the project. /// [Function("get-default-target")] public string GetDefaultTarget() { return StringUtils.ConvertNullToEmpty(Project.DefaultTargetName); } /// /// Gets the base directory of the current project. /// /// /// The base directory of the current project. /// [Function("get-base-directory")] public string GetBaseDirectory() { return Project.BaseDirectory; } #endregion Public Instance Methods } [FunctionSet("target", "NAnt")] public class TargetFunctions : FunctionSetBase { #region Public Instance Constructors public TargetFunctions(Project project, PropertyDictionary properties) : base(project, properties) { } #endregion Public Instance Constructors #region Public Instance Methods /// /// Checks whether the specified target exists. /// /// The target to test. /// /// if the specified target exists; otherwise, /// . /// /// /// /// Execute target "clean", if it exists. /// /// /// /// /// /// ]]> /// /// [Function("exists")] public bool Exists(string name) { return (Project.Targets.Find(name) != null); } /// /// Gets the name of the target being executed. /// /// /// A that contains the name of the target /// being executed. /// /// No target is being executed. [Function("get-current-target")] public string GetCurrentTarget() { Target target = Project.CurrentTarget; if (target == null) { throw new InvalidOperationException("No target is being executed."); } return target.Name; } /// /// Checks whether the specified target has already been executed. /// /// The target to test. /// /// if the specified target has already been /// executed; otherwise, . /// /// Target does not exist. [Function("has-executed")] public bool HasExecuted(string name) { Target target = Project.Targets.Find(name); if (target == null) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1097"), name)); } return target.Executed; } #endregion Public Instance Methods } [FunctionSet("task", "NAnt")] public class TaskFunctions : FunctionSetBase { #region Public Instance Constructors public TaskFunctions(Project project, PropertyDictionary properties) : base(project, properties) { } #endregion Public Instance Constructors #region Public Instance Methods /// /// Checks whether the specified task exists. /// /// The task to test. /// /// if the specified task exists; otherwise, /// . /// [Function("exists")] public bool Exists(string name) { return TypeFactory.TaskBuilders.Contains(name); } /// /// Returns the from which the specified task /// was loaded. /// /// The name of the task to get the of. /// /// The from which the specified task was loaded. /// /// Task is not available. [Function("get-assembly")] public Assembly GetAssembly(string name) { TaskBuilder task = TypeFactory.TaskBuilders[name]; if (task == null) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1099"), name)); } return task.Assembly; } #endregion Public Instance Methods } [FunctionSet("property", "NAnt")] public class PropertyFunctions : FunctionSetBase { #region Public Instance Constructors public PropertyFunctions(Project project, PropertyDictionary properties) : base(project, properties) { } #endregion Public Instance Constructors #region Public Instance Methods /// /// Checks whether the specified property exists. /// /// The property to test. /// /// if the specified property exists; otherwise, /// . /// /// /// /// Execute a set of tasks if the "build.debug" property /// exists. /// /// /// /// /// /// /// /// ]]> /// /// [Function("exists")] public bool Exists(string name) { return Project.Properties.Contains(name); } /// /// Checks whether the specified property is read-only. /// /// The property to test. /// /// if the specified property is read-only; /// otherwise, . /// /// /// Check whether the "debug" property is read-only. /// property::is-readonly('debug') /// /// Property has not been set. [Function("is-readonly")] public bool IsReadOnly(string name) { if (!Project.Properties.Contains(name)) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1053"), name)); } return Project.Properties.IsReadOnlyProperty(name); } /// /// Checks whether the specified property is a dynamic property. /// /// The property to test. /// /// if the specified property is a dynamic /// property; otherwise, . /// /// Property has not been set. /// /// /// Check whether the "debug" property is a dynamic property. /// /// property::is-dynamic('debug') /// [Function("is-dynamic")] public bool IsDynamic(string name) { if (!Project.Properties.Contains(name)) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1053"), name)); } return Project.Properties.IsDynamicProperty(name); } #endregion Public Instance Methods } [FunctionSet("platform", "NAnt")] public class PlatformFunctions : FunctionSetBase { #region Public Instance Constructors public PlatformFunctions(Project project, PropertyDictionary properties) : base(project, properties) { } #endregion Public Instance Constructors #region Public Instance Methods /// /// Gets the name of the platform on which NAnt is running. /// /// /// The name of the platform on which NAnt is running. /// [Function("get-name")] public string GetName() { return Project.PlatformName; } #endregion Public Instance Methods #region Public Static Methods /// /// Checks whether NAnt is running on Windows (and not just 32-bit Windows /// as the name may lead you to believe). /// /// /// if NAnt is running on Windows; /// otherwise, . /// [Function("is-win32")] [Obsolete("Use the is-windows function instead.")] public static bool IsWin32() { return PlatformHelper.IsWindows; } /// /// Checks whether NAnt is running on Windows. /// /// /// if NAnt is running on Windows; /// otherwise, . /// [Function("is-windows")] public static bool IsWindows() { return PlatformHelper.IsWindows; } /// /// Checks whether NAnt is running on Unix. /// /// /// if NAnt is running on Unix; /// otherwise, . /// [Function("is-unix")] public static bool IsUnix() { return PlatformHelper.IsUnix; } #endregion Public Static Methods } } nant-0.92-rc1/src/NAnt.Core/Functions/DoubleFunctions.cs0000644000175000017500000000621611757302273022755 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Globalization; using NAnt.Core.Attributes; namespace NAnt.Core.Functions { [FunctionSet("double", "Conversion")] public class DoubleConversionFunctions : FunctionSetBase { #region Public Instance Constructors public DoubleConversionFunctions(Project project, PropertyDictionary properties) : base(project, properties) { } #endregion Public Instance Constructors #region Public Static Methods /// /// Converts the specified string representation of a number to its /// double-precision floating point number equivalent. /// /// A string containing a number to convert. /// /// A double-precision floating point number equivalent to the numeric /// value or symbol specified in . /// /// is not a number in a valid format. /// represents a number less than or greater than . /// /// The for the invariant culture is /// used to supply formatting information about . /// [Function("parse")] public static double Parse(string s) { return double.Parse(s, CultureInfo.InvariantCulture); } /// /// Converts the specified to its equivalent /// string representation. /// /// A to convert. /// /// The string representation of formatted /// using the general format specifier ("G"). /// /// /// is formatted with the /// for the invariant culture. /// [Function("to-string")] public static string ToString(double value) { return value.ToString(CultureInfo.InvariantCulture); } #endregion Public Static Methods } } nant-0.92-rc1/src/NAnt.Core/Functions/Int64Functions.cs0000644000175000017500000000630411757302273022445 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Globalization; using NAnt.Core; using NAnt.Core.Types; using NAnt.Core.Attributes; namespace NAnt.Core.Functions { [FunctionSet("long", "Conversion")] public class Int64ConversionFunctions : FunctionSetBase { #region Public Instance Constructors public Int64ConversionFunctions(Project project, PropertyDictionary properties) : base(project, properties) { } #endregion Public Instance Constructors #region Public Static Methods /// /// Converts the specified string representation of a number to its /// 64-bit signed integer equivalent. /// /// A string containing a number to convert. /// /// A 64-bit signed integer equivalent to the number contained in /// . /// /// is not of the correct format. /// represents a number less than or greater than . /// /// The for the invariant culture is /// used to supply formatting information about . /// [Function("parse")] public static long Parse(string s) { return long.Parse(s, CultureInfo.InvariantCulture); } /// /// Converts the specified to its equivalent string /// representation. /// /// A to convert. /// /// The string representation of , consisting /// of a negative sign if the value is negative, and a sequence of /// digits ranging from 0 to 9 with no leading zeroes. /// /// /// is formatted with the /// for the invariant culture. /// [Function("to-string")] public static string ToString(long value) { return value.ToString(CultureInfo.InvariantCulture); } #endregion Public Static Methods } } nant-0.92-rc1/src/NAnt.Core/Functions/PathFunctions.cs0000644000175000017500000002573011757302273022441 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian Maclean (imaclean@gmail.com) // Jaroslaw Kowalski (jkowalski@users.sourceforge.net) using System; using System.IO; using System.Collections; using System.Reflection; using System.Globalization; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.Core.Functions { [FunctionSet("path", "Path")] public class PathFunctions : FunctionSetBase { #region Public Instance Constructors public PathFunctions(Project project, PropertyDictionary properties) : base(project, properties) { } #endregion Public Instance Constructors #region Public Instance Methods /// /// Returns the fully qualified path. /// /// The file or directory for which to obtain absolute path information. /// /// A string containing the fully qualified location of , /// such as "C:\MyFile.txt". /// /// is a zero-length string, contains only white space, or contains one or more invalid characters. /// contains a colon (":"). /// The specified path, file name, or both exceed the system-defined maximum length. [Function("get-full-path")] public string GetFullPath(string path) { return Project.GetFullPath(path); } #endregion Public Instance Methods #region Public Static Methods /// /// Combines two paths. /// /// first path /// second path /// /// A string containing the combined paths. If one of the specified paths /// is a zero-length string, this method returns the other path. If /// contains an absolute path, this method /// returns . /// /// or contain one or more invalid characters. [Function("combine")] public static string Combine(string path1, string path2) { return Path.Combine(path1, path2); } /// /// Changes the extension of the path string. /// /// The path information to modify. The path cannot contain any of the characters /// defined in InvalidPathChars. /// The new extension (with a leading period). Specify a null reference /// to remove an existing extension from . /// /// /// A string containing the modified path information. /// /// /// On Windows-based desktop platforms, if is /// an empty , the path information is returned /// unmodified. If has no extension, the returned /// path contains /// appended to the end of . /// /// /// /// For more information see the documentation. /// /// contains one or more invalid characters. [Function("change-extension")] public static string ChangeExtension(string path, string extension) { return Path.ChangeExtension(path, extension); } /// /// Returns the directory information for the specified path string. /// /// The path of a file or directory. /// /// A containing directory information for /// , or an empty if /// denotes a root directory, or does not /// contain directory information. /// /// contains invalid characters, is empty, or contains only white spaces. [Function("get-directory-name")] public static string GetDirectoryName(string path) { string dirName = Path.GetDirectoryName(path); return StringUtils.ConvertNullToEmpty(dirName); } /// /// Returns the extension for the specified path string. /// /// The path string from which to get the extension. /// /// A containing the extension of the specified /// (including the "."), or an empty /// if does not have /// extension information. /// /// contains one or more invalid characters. [Function("get-extension")] public static string GetExtension(string path) { return Path.GetExtension(path); } /// /// Returns the filename for the specified path string. /// /// The path string from which to obtain the file name and extension. /// /// /// A consisting of the characters after the last /// directory character in path. /// /// /// If the last character of is a directory or /// volume separator character, an empty is returned. /// /// /// contains one or more invalid characters. [Function("get-file-name")] public static string GetFileName(string path) { return Path.GetFileName(path); } /// /// Returns the filename without extension for the specified path string. /// /// The path of the file. /// /// A containing the returned /// by , minus the last period (.) and all /// characters following it. /// /// contains one or more invalid characters. [Function("get-file-name-without-extension")] public static string GetFileNameWithoutExtension(string path) { return Path.GetFileNameWithoutExtension(path); } /// /// Gets the root directory of the specified path. /// /// The path from which to obtain root directory information. /// /// A containing the root directory of /// , such as "C:\", or an empty /// if does not contain root directory information. /// /// contains invalid characters, or is empty. [Function("get-path-root")] public static string GetPathRoot(string path) { string pathRoot = Path.GetPathRoot(path); return StringUtils.ConvertNullToEmpty(pathRoot); } /// /// Returns a uniquely named zero-byte temporary file on disk and returns the full path to that file. /// /// /// A containing the name of the temporary file. /// [Function("get-temp-file-name")] public static string GetTempFileName() { return Path.GetTempFileName(); } /// /// Gets the path to the temporary directory. /// /// /// A containing the path information of a /// temporary directory. /// [Function("get-temp-path")] public static string GetTempPath() { return Path.GetTempPath(); } /// /// Determines whether a path string includes an extension. /// /// The path to search for an extension. /// /// . if the characters that follow the last /// directory separator or volume separator in the /// include a period (.) followed by one or more characters; /// otherwise, . /// /// contains one or more invalid characters. [Function("has-extension")] public static bool HasExtension(string path) { return Path.HasExtension(path); } /// /// Determines whether a path string is absolute. /// /// The path to test. /// /// if path contains an absolute ; /// otherwise, . /// /// contains one or more invalid characters. [Function("is-path-rooted")] public static bool IsPathRooted(string path) { return Path.IsPathRooted(path); } #endregion Public Static Methods } } nant-0.92-rc1/src/NAnt.Core/Functions/TimeSpanFunctions.cs0000644000175000017500000003117511757302273023265 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; using System.Globalization; using System.IO; using System.Reflection; using NAnt.Core; using NAnt.Core.Types; using NAnt.Core.Attributes; namespace NAnt.Core.Functions { [FunctionSet("timespan", "Date/Time")] public class TimeSpanFunctions : FunctionSetBase { #region Public Instance Constructors public TimeSpanFunctions(Project project, PropertyDictionary properties) : base(project, properties) { } #endregion Public Instance Constructors #region Public Static Methods /// /// Returns the total number of days represented by the specified /// , expressed in whole and fractional days. /// /// A . /// /// The total number of days represented by the given . /// [Function("get-total-days")] public static double GetTotalDays(TimeSpan value) { return value.TotalDays; } /// /// Returns the total number of hours represented by the specified /// , expressed in whole and fractional hours. /// /// A . /// /// The total number of hours represented by the given . /// [Function("get-total-hours")] public static double GetTotalHours(TimeSpan value) { return value.TotalHours; } /// /// Returns the total number of minutes represented by the specified /// , expressed in whole and fractional minutes. /// /// A . /// /// The total number of minutes represented by the given . /// [Function("get-total-minutes")] public static double GetTotalMinutes(TimeSpan value) { return value.TotalMinutes; } /// /// Returns the total number of seconds represented by the specified /// , expressed in whole and fractional seconds. /// /// A . /// /// The total number of seconds represented by the given . /// [Function("get-total-seconds")] public static double GetTotalSeconds(TimeSpan value) { return value.TotalSeconds; } /// /// Returns the total number of milliseconds represented by the specified /// , expressed in whole and fractional milliseconds. /// /// A . /// /// The total number of milliseconds represented by the given /// . /// [Function("get-total-milliseconds")] public static double GetTotalMilliseconds(TimeSpan value) { return value.TotalMilliseconds; } /// /// Returns the number of whole days represented by the specified /// . /// /// A . /// /// The number of whole days represented by the given /// . /// /// /// /// Remove all files that have not been modified in the last 7 days from directory "binaries". /// /// /// /// /// /// /// ]]> /// /// [Function("get-days")] public static int GetDays(TimeSpan value) { return value.Days; } /// /// Returns the number of whole hours represented by the specified /// . /// /// A . /// /// The number of whole hours represented by the given /// . /// [Function("get-hours")] public static int GetHours(TimeSpan value) { return value.Hours; } /// /// Returns the number of whole minutes represented by the specified /// . /// /// A . /// /// The number of whole minutes represented by the given /// . /// [Function("get-minutes")] public static int GetMinutes(TimeSpan value) { return value.Minutes; } /// /// Returns the number of whole seconds represented by the specified /// . /// /// A . /// /// The number of whole seconds represented by the given /// . /// [Function("get-seconds")] public static int GetSeconds(TimeSpan value) { return value.Seconds; } /// /// Returns the number of whole milliseconds represented by the specified /// . /// /// A . /// /// The number of whole milliseconds represented by the given /// . /// [Function("get-milliseconds")] public static int GetMilliseconds(TimeSpan value) { return value.Milliseconds; } /// /// Returns the number of ticks contained in the specified /// . /// /// A . /// /// The number of ticks contained in the given . /// [Function("get-ticks")] public static long GetTicks(TimeSpan value) { return value.Ticks; } /// /// Returns a that represents a specified number /// of days, where the specification is accurate to the nearest millisecond. /// /// A number of days, accurate to the nearest millisecond. /// /// A that represents . /// [Function("from-days")] public static TimeSpan FromDays(double value) { return TimeSpan.FromDays(value); } /// /// Returns a that represents a specified number /// of hours, where the specification is accurate to the nearest /// millisecond. /// /// A number of hours, accurate to the nearest millisecond. /// /// A that represents . /// [Function("from-hours")] public static TimeSpan FromHours(double value) { return TimeSpan.FromHours(value); } /// /// Returns a that represents a specified number /// of minutes, where the specification is accurate to the nearest /// millisecond. /// /// A number of minutes, accurate to the nearest millisecond. /// /// A that represents . /// [Function("from-minutes")] public static TimeSpan FromMinutes(double value) { return TimeSpan.FromMinutes(value); } /// /// Returns a that represents a specified number /// of seconds, where the specification is accurate to the nearest /// millisecond. /// /// A number of seconds, accurate to the nearest millisecond. /// /// A that represents . /// [Function("from-seconds")] public static TimeSpan FromSeconds(double value) { return TimeSpan.FromSeconds(value); } /// /// Returns a that represents a specified number /// of milliseconds. /// /// A number of milliseconds. /// /// A that represents . /// [Function("from-milliseconds")] public static TimeSpan FromMilliseconds(double value) { return TimeSpan.FromMilliseconds(value); } /// /// Returns a that represents a specified time, /// where the specification is in units of ticks. /// /// A number of ticks that represent a time. /// /// A that represents . /// [Function("from-ticks")] public static TimeSpan FromTicks(long value) { return TimeSpan.FromTicks(value); } #endregion Public Static Methods } [FunctionSet("timespan", "Conversion")] public class TimeSpanConversionFunctions : FunctionSetBase { #region Public Instance Constructors public TimeSpanConversionFunctions(Project project, PropertyDictionary properties) : base(project, properties) { } #endregion Public Instance Constructors #region Public Static Methods /// /// Constructs a from a time indicated by a /// specified string. /// /// A string. /// /// A that corresponds to . /// /// has an invalid format. /// At least one of the hours, minutes, or seconds components is outside its valid range. [Function("parse")] public static TimeSpan Parse(string s) { return TimeSpan.Parse(s); } /// /// Converts the specified to its equivalent /// string representation. /// /// A to convert. /// /// The string representation of . The format /// of the return value is of the form: [-][d.]hh:mm:ss[.ff]. /// [Function("to-string")] public static string ToString(TimeSpan value) { return value.ToString(); } #endregion Public Static Methods } } nant-0.92-rc1/src/NAnt.Core/Functions/FrameworkFunctions.cs0000644000175000017500000004136411757302273023503 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian Maclean (imaclean@gmail.com) // Jaroslaw Kowalski (jkowalski@users.sourceforge.net) // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Globalization; using System.IO; using System.Text; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Util; namespace NAnt.Core.Functions { [FunctionSet("framework", "NAnt")] public class FrameworkFunctions : FunctionSetBase { #region Public Instance Constructors public FrameworkFunctions(Project project, PropertyDictionary properties) : base(project, properties) { } #endregion Public Instance Constructors #region Public Instance Methods /// /// Checks whether the specified framework exists, and is valid. /// /// The framework to test. /// /// if the specified framework exists ; otherwise, /// . /// [Function("exists")] public bool Exists(string framework) { FrameworkInfo fi = Project.Frameworks [framework]; return (fi != null && fi.IsValid); } /// /// Checks whether the SDK for the specified framework is installed. /// /// The framework to test. /// /// if the SDK for specified framework is installed; /// otherwise, . /// /// /// [Function("sdk-exists")] public bool SdkExists(string framework) { // obtain framework and ensure it's valid FrameworkInfo fi = GetFramework(framework); return (fi.SdkDirectory != null); } /// /// Gets the identifier of the current target framework. /// /// /// The identifier of the current target framework. /// [Function("get-target-framework")] public string GetTargetFramework() { return Project.TargetFramework.Name; } /// /// Gets the identifier of the runtime framework. /// /// /// The identifier of the runtime framework. /// [Function("get-runtime-framework")] public string GetRuntimeFramework() { return Project.RuntimeFramework.Name; } /// /// Gets the family of the specified framework. /// /// The framework of which the family should be returned. /// /// The family of the specified framework. /// /// is not a valid framework identifier. /// /// [Function("get-family")] public string GetFamily(string framework) { // obtain framework and ensure it's valid FrameworkInfo fi = GetFramework(framework); // return the family of the specified framework return fi.Family; } /// /// Gets the version of the current target framework. /// /// /// The version of the current target framework. /// /// [Function("get-version")] public Version GetVersion() { return Project.TargetFramework.Version; } /// /// Gets the version of the specified framework. /// /// The framework of which the version should be returned. /// /// The version of the specified framework. /// /// is not a valid framework identifier. /// /// [Function("get-version")] public Version GetVersion(string framework) { // obtain framework and ensure it's valid FrameworkInfo fi = GetFramework(framework); // return the version of the specified framework return fi.Version; } /// /// Gets the description of the current target framework. /// /// /// The description of the current target framework. /// /// [Function("get-description")] public string GetDescription() { return Project.TargetFramework.Description; } /// /// Gets the description of the specified framework. /// /// The framework of which the description should be returned. /// /// The description of the specified framework. /// /// is not a valid framework identifier. /// /// [Function("get-description")] public string GetDescription(string framework) { // obtain framework and ensure it's valid FrameworkInfo fi = GetFramework(framework); // return the description of the specified framework return fi.Description; } /// /// Gets the Common Language Runtime version of the current target /// framework. /// /// /// The Common Language Runtime version of the current target framework. /// /// [Function("get-clr-version")] public Version GetClrVersion() { return Project.TargetFramework.ClrVersion; } /// /// Gets the Common Language Runtime version of the specified framework. /// /// The framework of which the Common Language Runtime version should be returned. /// /// The Common Language Runtime version of the specified framework. /// /// is not a valid framework identifier. /// /// [Function("get-clr-version")] public Version GetClrVersion(string framework) { // obtain framework and ensure it's valid FrameworkInfo fi = GetFramework(framework); // return the family of the specified framework return fi.ClrVersion; } /// /// Gets the framework directory of the specified framework. /// /// The framework of which the framework directory should be returned. /// /// The framework directory of the specified framework. /// /// is not a valid framework identifier. /// /// [Function("get-framework-directory")] public string GetFrameworkDirectory(string framework) { // obtain framework and ensure it's valid FrameworkInfo fi = GetFramework(framework); // return full path to the framework directory of the specified framework return fi.FrameworkDirectory.FullName; } /// /// Gets the assembly directory of the specified framework. /// /// The framework of which the assembly directory should be returned. /// /// The assembly directory of the specified framework. /// /// is not a valid framework identifier. /// /// [Function("get-assembly-directory")] public string GetAssemblyDirectory(string framework) { // obtain framework and ensure it's valid FrameworkInfo fi = GetFramework(framework); // return full path to the assembly directory of the specified framework return fi.FrameworkAssemblyDirectory.FullName; } /// /// Gets the SDK directory of the specified framework. /// /// The framework of which the SDK directory should be returned. /// /// The SDK directory of the specified framework, or an empty /// if the SDK of the specified framework is not /// installed. /// /// is not a valid framework identifier. /// /// [Function("get-sdk-directory")] public string GetSdkDirectory(string framework) { // obtain framework and ensure it's valid FrameworkInfo fi = GetFramework(framework); // get the SDK directory of the specified framework DirectoryInfo sdkDirectory = fi.SdkDirectory; // return directory or empty string if SDK is not installed return (sdkDirectory != null) ? sdkDirectory.FullName : string.Empty; } /// /// Gets the absolute path of the specified tool for the current /// target framework. /// /// The file name of the tool to search for. /// /// The absolute path to if found in one of the /// configured tool paths; otherwise, an error is reported. /// /// could not be found in the configured tool paths. /// /// /// The configured tool paths are scanned in the order in which they /// are defined in the framework configuration. /// /// /// The file name of the tool to search should include the extension. /// /// /// /// Use gacutil to install an assembly in the GAC. /// /// /// /// /// /// ]]> /// /// [Function("get-tool-path")] public string GetToolPath(string tool) { string toolPath = Project.TargetFramework.GetToolPath (tool); if (toolPath == null) { throw new FileNotFoundException (string.Format (CultureInfo.InvariantCulture, "\"{0}\" could not be found in any of the configured " + "tool paths.", tool)); } return toolPath; } /// /// Gets the runtime engine of the specified framework. /// /// The framework of which the runtime engine should be returned. /// /// The full path to the runtime engine of the specified framework, or /// an empty if no runtime engine is defined /// for the specified framework. /// /// is not a valid framework identifier. /// /// [Function("get-runtime-engine")] public string GetRuntimeEngine(string framework) { // obtain framework and ensure it's valid FrameworkInfo fi = GetFramework(framework); return fi.RuntimeEngine; } /// /// Gets a comma-separated list of frameworks filtered by the specified /// . /// /// A bitwise combination of values that filter the frameworks to retrieve. /// /// A comma-separated list of frameworks filtered by the specified /// , sorted on name. /// /// /// /// Define a build-all target that executes the build /// target once for each installed framework targeting compact /// devices. /// /// /// /// /// /// /// /// /// /// /// ... /// /// ]]> /// /// [Function("get-frameworks")] public string GetFrameworks(FrameworkTypes types) { FrameworkInfo[] frameworks = Project.GetFrameworks(types); if (frameworks.Length == 0) return string.Empty; StringBuilder sb = new StringBuilder(); for (int i = 0; i < frameworks.Length; i++) { if (i > 0) sb.Append (","); sb.Append (frameworks [i].Name); } return sb.ToString(); } #endregion Public Instance Methods #region Private Instance Methods /// /// Checks whether the specified framework is valid. /// /// The framework to check. /// is not a valid framework identifier. private FrameworkInfo GetFramework(string framework) { if (framework == Project.TargetFramework.Name) { return Project.TargetFramework; } FrameworkInfo fi = Project.Frameworks [framework]; if (fi == null) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1096"), framework)); } else { // ensure framework is valid fi.Validate(); return fi; } } #endregion Private Instance Methods } } nant-0.92-rc1/src/NAnt.Core/Functions/BooleanFunctions.cs0000644000175000017500000000522211757302273023116 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Globalization; using NAnt.Core; using NAnt.Core.Types; using NAnt.Core.Attributes; namespace NAnt.Core.Functions { [FunctionSet("bool", "Conversion")] public class BooleanConversionFunctions : FunctionSetBase { #region Public Instance Constructors public BooleanConversionFunctions(Project project, PropertyDictionary properties) : base(project, properties) { } #endregion Public Instance Constructors #region Public Static Methods /// /// Converts the specified string representation of a logical value to /// its equivalent. /// /// A string containing the value to convert. /// /// if is equivalent to /// "True"; otherwise, . /// /// is not equivalent to or . [Function("parse")] public static bool Parse(string s) { return bool.Parse(s); } /// /// Converts the specified to its equivalent string /// representation. /// /// A to convert. /// /// "True" if is , or /// "False" if is . /// [Function("to-string")] public static string ToString(bool value) { return value.ToString(CultureInfo.InvariantCulture); } #endregion Public Static Methods } } nant-0.92-rc1/src/NAnt.Core/Target.cs0000644000175000017500000002403111757302273017123 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Gerry Shaw (gerry_shaw@yahoo.com) // Ian MacLean (imaclean@gmail.com) // Scott Hernandez (ScottHernandez@hotmail.com) // William E. Caputo (wecaputo@thoughtworks.com | logosity@yahoo.com) using System; using System.Collections.Specialized; using System.Globalization; using System.Xml; using NAnt.Core.Attributes; using NAnt.Core.Util; namespace NAnt.Core { [Serializable()] public sealed class Target : Element, ICloneable { #region Private Instance Fields private string _name; private string _description; private string _ifCondition; private string _unlessCondition; private StringCollection _dependencies = new StringCollection(); private bool _executed; #endregion Private Instance Fields #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public Target() { } #endregion Public Instance Constructors #region Public Instance Properties /// /// This indicates whether the target has already executed. /// public bool Executed { get { return _executed; } } /// /// The name of the target. /// /// /// /// Hides to have /// return the name of target, not the name of XML element - which /// would always be target. /// /// /// Note: Properties are not allowed in the name. /// /// [TaskAttribute("name", Required=true, ExpandProperties=false)] [StringValidator(AllowEmpty=false)] public new string Name { get { return _name; } set { _name = value; } } /// /// If then the target will be executed; /// otherwise, skipped. The default is . /// [TaskAttribute("if", ExpandProperties=false)] public string IfCondition { get { return _ifCondition; } set { _ifCondition = StringUtils.ConvertEmptyToNull(value); } } /// /// Gets a value indicating whether the target should be executed. /// /// /// if the target should be executed; otherwise, /// . /// public bool IfDefined { get { // expand properties in condition string expandedCondition = Project.Properties.ExpandProperties(IfCondition, Location); // if a condition is supplied, it should evaluate to a bool if (!String.IsNullOrEmpty(expandedCondition)) { try { return Convert.ToBoolean(expandedCondition, CultureInfo.InvariantCulture); } catch (FormatException) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1070"), expandedCondition), Location); } } // no condition is supplied return true; } } /// /// Opposite of . If /// then the target will be executed; otherwise, skipped. The default /// is . /// [TaskAttribute("unless", ExpandProperties=false)] public string UnlessCondition { get { return _unlessCondition; } set { _unlessCondition = StringUtils.ConvertEmptyToNull(value); } } /// /// Gets a value indicating whether the target should NOT be executed. /// /// /// if the target should NOT be executed; /// otherwise, . /// public bool UnlessDefined { get { // expand properties in condition string expandedCondition = Project.Properties.ExpandProperties(UnlessCondition, Location); // if a condition is supplied, it should evaluate to a bool if (!String.IsNullOrEmpty(expandedCondition)) { try { return Convert.ToBoolean(expandedCondition, CultureInfo.InvariantCulture); } catch (FormatException) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1069"), expandedCondition), Location); } } // no condition is supplied return false; } } /// /// The description of the target. /// [TaskAttribute("description")] public string Description { set { _description = value;} get { return _description; } } /// /// Space separated list of targets that this target depends on. /// [TaskAttribute("depends")] public string DependsListString { set { foreach (string str in value.Split(new char[] {' ', ','})) { string dependency = str.Trim(); if (dependency.Length > 0) { Dependencies.Add(dependency); } } } } /// /// A collection of target names that must be executed before this /// target. /// public StringCollection Dependencies { get { return _dependencies; } } #endregion Public Instance Properties #region Implementation of ICloneable /// /// Creates a shallow copy of the . /// /// /// A shallow copy of the . /// object ICloneable.Clone() { return Clone(); } #endregion #region Public Instance Methods /// /// Creates a shallow copy of the . /// /// /// A shallow copy of the . /// public Target Clone() { Target clone = new Target(); base.CopyTo(clone); clone._dependencies = _dependencies; clone._description = _description; clone._executed = _executed; clone._ifCondition = _ifCondition; clone._name = _name; clone._unlessCondition = _unlessCondition; return clone; } /// /// Executes dependent targets first, then the target. /// public void Execute() { if (IfDefined && !UnlessDefined) { try { Project.OnTargetStarted(this, new BuildEventArgs(this)); // select all the task nodes and execute them foreach (XmlNode childNode in XmlNode) { if (!(childNode.NodeType == XmlNodeType.Element)|| !childNode.NamespaceURI.Equals(NamespaceManager.LookupNamespace("nant"))) { continue; } if (TypeFactory.TaskBuilders.Contains(childNode.Name)) { Task task = Project.CreateTask(childNode, this); if (task != null) { task.Execute(); } } else if (TypeFactory.DataTypeBuilders.Contains(childNode.Name)) { DataTypeBase dataType = Project.CreateDataTypeBase(childNode); Project.Log(Level.Verbose, "Adding a {0} reference with id '{1}'.", childNode.Name, dataType.ID); if (!Project.DataTypeReferences.Contains(dataType.ID)) { Project.DataTypeReferences.Add(dataType.ID, dataType); } else { Project.DataTypeReferences[dataType.ID] = dataType; // overwrite with the new reference. } } else { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1071"), childNode.Name), Project.LocationMap.GetLocation(childNode)); } } } finally { _executed = true; Project.OnTargetFinished(this, new BuildEventArgs(this)); } } } #endregion Public Instance Methods } } nant-0.92-rc1/src/NAnt.Core/ExpressionTokenizer.cs0000644000175000017500000002502211757302273021730 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Jaroslaw Kowalski (jkowalski@users.sourceforge.net) using System; using System.Globalization; using System.IO; using System.Text; using NAnt.Core.Util; namespace NAnt.Core { /// /// Splits an input string into a sequence of tokens used during parsing. /// public class ExpressionTokenizer { public struct Position { private int _charIndex; public Position(int charIndex) { _charIndex = charIndex; } public int CharIndex { get { return _charIndex; } } } /// /// Available tokens /// public enum TokenType { BOF, EOF, Number, String, Keyword, EQ, NE, LT, GT, LE, GE, Plus, Minus, Mul, Div, Mod, LeftParen, RightParen, LeftCurlyBrace, RightCurlyBrace, Not, Punctuation, Whitespace, Dollar, Comma, Dot, DoubleColon, } #region Public Instance Constructors public ExpressionTokenizer() { } #endregion Public Instance Constructors #region Static Constructor static ExpressionTokenizer() { for (int i = 0; i < 128; ++i) charIndexToTokenType[i] = TokenType.Punctuation; foreach (CharToTokenType cht in charToTokenType) charIndexToTokenType[(int) cht.ch] = cht.tokenType; } #endregion Static Constructor #region Public Instance Properties public bool IgnoreWhitespace { get { return _ignoreWhiteSpace; } set { _ignoreWhiteSpace = value; } } public bool SingleCharacterMode { get { return _singleCharacterMode; } set { _singleCharacterMode = value; } } public TokenType CurrentToken { get { return _tokenType; } } public string TokenText { get { return _tokenText; } } public Position CurrentPosition { get { return _tokenStartPosition; } } #endregion Public Instance Properties #region Public Instance Methods public void InitTokenizer(string s) { _text = s; _position = 0; _tokenType = TokenType.BOF; GetNextToken(); } public void GetNextToken() { if (_tokenType == TokenType.EOF) throw new ExpressionParseException(ResourceUtils.GetString("String_CannotReadPastStream"), -1, -1); if (IgnoreWhitespace) SkipWhitespace(); _tokenStartPosition = new Position(_position); int peek = PeekChar(); if (peek == -1) { _tokenType = TokenType.EOF; return; } char ch = (char) peek; if (!SingleCharacterMode) { if (!IgnoreWhitespace && Char.IsWhiteSpace(ch)) { StringBuilder sb = new StringBuilder(); while ((peek = PeekChar()) != -1) { if (!Char.IsWhiteSpace((char) peek)) break; sb.Append((char) peek); ReadChar(); } _tokenType = TokenType.Whitespace; _tokenText = sb.ToString(); return; } if (Char.IsDigit(ch)) { _tokenType = TokenType.Number; string s = string.Empty; s += ch; ReadChar(); while ((peek = PeekChar()) != -1) { ch = (char) peek; if (Char.IsDigit(ch)) { s += (char) ReadChar(); } else { break; } } _tokenText = s; return; } if (ch == '\'') { _tokenType = TokenType.String; string s = ""; ReadChar(); while ((peek = ReadChar()) != -1) { ch = (char) peek; if (ch == '\'') { if (PeekChar() == (int)'\'') { ReadChar(); } else break; } s += ch; } _tokenText = s; return; } if (ch == '_' || Char.IsLetter(ch)) { _tokenType = TokenType.Keyword; StringBuilder sb = new StringBuilder(); sb.Append((char) ch); ReadChar(); while ((peek = PeekChar()) != -1) { char c = (char) peek; if (c == '_' || c == '-' || c == '.' || c == '\\' || Char.IsLetterOrDigit(c)) { ReadChar(); sb.Append(c); } else { break; } } _tokenText = sb.ToString(); if (_tokenText.EndsWith("-") || _tokenText.EndsWith(".")) throw new ExpressionParseException(String.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1182"), _tokenText), CurrentPosition.CharIndex); return; } ReadChar(); peek = PeekChar(); if (ch == ':' && peek == (int) ':') { _tokenType = TokenType.DoubleColon; _tokenText = "::"; ReadChar(); return; } if (ch == '!' && peek == (int) '=') { _tokenType = TokenType.NE; _tokenText = "!="; ReadChar(); return; } if (ch == '=' && peek == (int) '=') { _tokenType = TokenType.EQ; _tokenText = "=="; ReadChar(); return; } if (ch == '<' && peek == (int) '=') { _tokenType = TokenType.LE; _tokenText = "<="; ReadChar(); return; } if (ch == '>' && peek == (int) '=') { _tokenType = TokenType.GE; _tokenText = ">="; ReadChar(); return; } } else { ReadChar(); } _tokenText = new String(ch, 1); if (ch >= 32 && ch < 128) { _tokenType = charIndexToTokenType[ch]; } else { _tokenType = TokenType.Punctuation; } } public bool IsKeyword(string k) { return (_tokenType == TokenType.Keyword) && (_tokenText == k); } #endregion Public Instance Methods #region Private Instance Methods private int ReadChar() { if (_position < _text.Length) return _text[_position++]; return -1; } private int PeekChar() { if (_position < _text.Length) return _text[_position]; return -1; } private void SkipWhitespace() { int ch; while ((ch = PeekChar()) != -1) { if (!Char.IsWhiteSpace((char) ch)) break; ReadChar(); } } #endregion Private Instance Methods #region Private Instance Fields private string _text; private int _position; private Position _tokenStartPosition; private TokenType _tokenType; private string _tokenText; private bool _ignoreWhiteSpace = true; private bool _singleCharacterMode; #endregion Private Instance Fields #region Private Static Fields private static CharToTokenType[] charToTokenType = { new CharToTokenType('+', TokenType.Plus), new CharToTokenType('-', TokenType.Minus), new CharToTokenType('*', TokenType.Mul), new CharToTokenType('/', TokenType.Div), new CharToTokenType('%', TokenType.Mod), new CharToTokenType('<', TokenType.LT), new CharToTokenType('>', TokenType.GT), new CharToTokenType('(', TokenType.LeftParen), new CharToTokenType(')', TokenType.RightParen), new CharToTokenType('{', TokenType.LeftCurlyBrace), new CharToTokenType('}', TokenType.RightCurlyBrace), new CharToTokenType('!', TokenType.Not), new CharToTokenType('$', TokenType.Dollar), new CharToTokenType(',', TokenType.Comma), new CharToTokenType('.', TokenType.Dot), }; private static TokenType[] charIndexToTokenType = new TokenType[128]; #endregion Private Static Fields private struct CharToTokenType { public readonly char ch; public readonly TokenType tokenType; public CharToTokenType(char ch, TokenType tokenType) { this.ch = ch; this.tokenType = tokenType; } } } } nant-0.92-rc1/src/NAnt.Core/Tasks/0000755000175000017500000000000011757310030016421 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.Core/Tasks/TryCatchTask.cs0000644000175000017500000002534011757302273021332 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2005 Gert Driesen // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Troy Laurin (fiontan@westnet.com.au) using System; using NAnt.Core; using NAnt.Core.Tasks; using NAnt.Core.Attributes; using NAnt.Core.Util; namespace NAnt.Core.Tasks { /// /// Executes a set of tasks, and optionally catches a build exception to /// allow recovery or rollback steps to be taken, or to define some steps /// to be taken regardless if the tasks succeed or fail, or both. /// /// /// /// The tasks defined in the <> block /// will be executed in turn, as they normally would in a target. /// /// /// If a <> block is defined, the /// tasks in that block will be executed in turn only if one of the tasks /// in the <> block fails. This /// failure will then be suppressed by the <> /// block. /// /// /// The message associated with the failure can also be caught in a /// property for use within the <> /// block. The original contents of the property will be restored upon /// exiting the <> block. /// /// /// If a <> block is defined, the /// tasks in that block will be executed after the tasks in both the /// <> and <> /// blocks have been executed, regardless of whether any task fails in /// either block. /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// ]]> /// /// /// The output of this example will be: /// /// /// In try /// In catch /// Finally done /// /// /// The failure in the <> block will /// not cause the build to fail. /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// ]]> /// /// /// The output of this example will be: /// /// /// In try /// Caught failure: Just because... /// Finally done /// Build failed: Bad catch /// /// /// Like the above, the failure in the <> /// block does not cause the build to fail. The failure in the /// <> block does, however. /// Note that the <> block is /// executed even though the <> /// block failed. /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// ]]> /// /// /// The output of this example will be: /// /// /// In try /// Caught failure yet again /// Build failed: Property 'failure' has not been set. /// /// /// The in the <> /// block failed because the "failure" property was not defined /// after exiting the <> block. /// Note that the failure in the <> /// block has eclipsed the failure in the <> /// block. /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// ]]> /// /// /// A more concrete example, that will always clean up the generated /// temporary file after it has been created. /// /// [TaskName("trycatch")] public class TryCatchTask : Task { #region Private Instance Fields private ElementContainer _tryBlock; private CatchElement _catchBlock; private ElementContainer _finallyBlock; #endregion Private Instance Fields #region Public Instance Properties /// /// The tasks in this block will be executed as a normal part of /// the build script. /// [BuildElement("try", Required=true)] public ElementContainer TryBlock { get { return _tryBlock; } set { _tryBlock = value; } } /// /// The tasks in this block will be executed if any task in the try /// block fails. /// [BuildElement("catch", Required=false)] public CatchElement CatchBlock { get { return _catchBlock; } set { _catchBlock = value; } } /// /// The tasks in this block will always be executed, regardless of /// what happens in the try and catch blocks. /// /// /// Note that any failure in any of the tasks in this block will /// prevent any subsequent tasks from executing. /// [BuildElement("finally", Required=false)] public ElementContainer FinallyBlock { get { return _finallyBlock; } set { _finallyBlock = value; } } #endregion Public Instance Properties #region Override implementation of Task protected override void ExecuteTask() { try { if (TryBlock != null) { TryBlock.Execute(); } } catch (BuildException be) { if (CatchBlock != null) { CatchBlock.Catch(be); } else { throw; } } finally { if (FinallyBlock != null) { FinallyBlock.Execute(); } } } #endregion Override implementation of Task public class CatchElement : ElementContainer { #region Private Instance Fields private string _property; #endregion Private Instance Fields #region Public Instance Properties /// /// Defines the name of the property to save the message describing /// the failure that has been caught. /// /// /// /// The failure message is only available in the context of the catch /// block. If you wish to preserve the message, you will need to save /// it into another property. /// /// /// Readonly properties cannot be overridden by this mechanism. /// /// [TaskAttribute("property", Required=false)] [StringValidator(AllowEmpty=false)] public string Property { get { return _property; } set { _property = StringUtils.ConvertEmptyToNull(value); } } #endregion Public Instance Properties #region Public Instance Methods public void Catch(BuildException be) { bool propertyExists = false; string originalPropertyValue = null; if (Property != null) { propertyExists = Project.Properties.Contains(Property); originalPropertyValue = Project.Properties[Property]; Project.Properties[Property] = be.RawMessage; } try { Execute(); } finally { if (Property != null) { if (!propertyExists) { // if the property did not exist, then remove it again Project.Properties.Remove(Property); } else { // restore original value Project.Properties[Property] = originalPropertyValue; } } } } #endregion Public Instance Methods } } } nant-0.92-rc1/src/NAnt.Core/Tasks/TouchTask.cs0000644000175000017500000001525711757302273020701 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Jay Turpin (jayturpin@hotmail.com) // Gerry Shaw (gerry_shaw@yahoo.com) using System; using System.IO; using System.Globalization; using NAnt.Core.Attributes; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.Core.Tasks { /// /// Touches a file or set of files -- corresponds to the Unix touch command. /// /// /// /// If the file specified does not exist, the task will create it. /// /// /// /// Touch the Main.cs file. The current time is used. /// /// /// ]]> /// /// /// /// /// Touch all executable files in the project base directory and its /// subdirectories. /// /// /// /// /// /// /// ///
/// ]]> /// /// [TaskName("touch")] public class TouchTask : Task { #region Private Instance Fields private FileInfo _file; private long _millis; private DateTime _datetime; private FileSet _fileset = new FileSet(); #endregion Private Instance Fields #region Public Instance Properties /// /// The file to touch. /// [TaskAttribute("file")] public FileInfo File { get { return _file; } set { _file = value; } } /// /// Specifies the new modification time of the file(s) in milliseconds /// since midnight Jan 1 1970. /// [TaskAttribute("millis")] public long Millis { get { return _millis; } set { _millis = value; } } /// /// Specifies the new modification time of the file in the format /// MM/DD/YYYY HH:MM:SS. /// [TaskAttribute("datetime")] [DateTimeValidator()] public DateTime Datetime { get { return _datetime; } set { _datetime = value; } } /// /// Used to select files that should be touched. /// [BuildElement("fileset")] public FileSet TouchFileSet { get { return _fileset; } set { _fileset = value; } } #endregion Public Instance Properties #region Override implementation of Task /// /// Ensures the supplied attributes are valid. /// protected override void Initialize() { // limit task to either millis or a date string if (Millis != 0 && Datetime != DateTime.MinValue) { throw new BuildException("Cannot specify 'millis' and 'datetime'" + " in the same task.", Location); } // limit task to touching either a file or fileset if (File != null && TouchFileSet.Includes.Count != 0) { throw new BuildException("Cannot specify both 'file' attribute" + " and use in the same task.", Location); } } protected override void ExecuteTask() { DateTime touchDateTime = DateTime.Now; // ensure base directory is set, even if fileset was not initialized // from XML if (TouchFileSet.BaseDirectory == null) { TouchFileSet.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } if (Millis != 0) { touchDateTime = GetDateTime(Millis); } else if (Datetime != DateTime.MinValue) { touchDateTime = Datetime; } // try to touch specified file if (File != null) { // touch file TouchFile(File.FullName, touchDateTime); } else { // touch files in fileset // only use the file set if file attribute has NOT been set foreach (string path in TouchFileSet.FileNames) { TouchFile(path, touchDateTime); } } } #endregion Override implementation of Task #region Private Instance Methods private void TouchFile(string path, DateTime touchDateTime) { try { if (System.IO.File.Exists(path)) { Log(Level.Verbose, "Touching file '{0}' with '{1}'.", path, touchDateTime.ToString(CultureInfo.InvariantCulture)); } else { Log(Level.Verbose, "Creating file '{0}' with '{1}'.", path, touchDateTime.ToString(CultureInfo.InvariantCulture)); // create the file (and ensure stream is closed) using (FileStream fs = System.IO.File.Create(path)) { } } System.IO.File.SetLastWriteTime(path, touchDateTime); } catch (Exception ex) { string msg = string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1152"), path); if (FailOnError) { throw new BuildException(msg, Location, ex); } // swallow any errors and move on Log(Level.Verbose, msg + " " + ex.Message); } } private DateTime GetDateTime(long milliSeconds) { DateTime touchDateTime = DateTime.Parse("01/01/1970 00:00:00", CultureInfo.InvariantCulture); return touchDateTime.Add(TimeSpan.FromMilliseconds(milliSeconds)); } #endregion Private Instance Methods } } nant-0.92-rc1/src/NAnt.Core/Tasks/LoadTasks.cs0000644000175000017500000001476311757302273020662 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Ian MacLean (imaclean@gmail.com) using System; using System.Globalization; using System.IO; using System.Reflection; using System.Security.Permissions; using System.Text; using System.Xml; using NAnt.Core.Attributes; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.Core.Tasks { /// /// Loads tasks form a given assembly or all assemblies in a given directory /// or . /// /// /// /// Load tasks from a single assembly. /// /// /// /// ]]> /// /// /// /// /// Scan a single directory for task assemblies. /// /// /// /// ]]> /// /// /// /// /// Use a containing both a directory and an /// assembly. /// /// /// /// /// /// /// /// /// ]]> /// /// [TaskName("loadtasks")] public class LoadTasksTask : Task { #region Private Instance Fields private FileInfo _assembly; private DirectoryInfo _path; private FileSet _fileset = new FileSet(); #endregion Private Instance Fields #region Public Instance Properties /// /// An assembly to load tasks from. /// [TaskAttribute("assembly")] public FileInfo AssemblyPath { get { return _assembly; } set { _assembly = value; } } /// /// A directory to scan for task assemblies. /// [TaskAttribute("path")] public DirectoryInfo Path { get { return _path; } set { _path = value; } } /// /// Used to select which directories or individual assemblies to scan. /// [BuildElement("fileset")] public FileSet TaskFileSet { get { return _fileset; } set { _fileset = value; } } #endregion Public Instance Properties #region Override implemenation of Task /// /// Executes the Load Tasks task. /// /// Specified assembly or path does not exist. [ReflectionPermission(SecurityAction.Demand, Flags=ReflectionPermissionFlag.NoFlags)] protected override void ExecuteTask() { // ensure base directory is set, even if fileset was not initialized // from XML if (TaskFileSet.BaseDirectory == null) { TaskFileSet.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } if (AssemblyPath != null) { // single file case if (!AssemblyPath.Exists) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1132"), AssemblyPath.FullName), Location); } TaskFileSet.FileNames.Add(AssemblyPath.FullName); } else if (Path != null) { if (!Path.Exists) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1131"), Path), Location); } TaskFileSet.DirectoryNames.Add(Path.FullName); } // process the fileset foreach (string assemblyPath in TaskFileSet.FileNames) { try { TypeFactory.ScanAssembly(assemblyPath, this); } catch (Exception ex) { string message = string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1130"), assemblyPath); if (FailOnError) { throw new BuildException(message, Location, ex); } else { Log(Level.Error, message + " " + ex.Message); } } } // process the path foreach (string scanPath in TaskFileSet.DirectoryNames) { try { TypeFactory.ScanDir(scanPath, this, FailOnError); } catch (BuildException) { throw; } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1130"), scanPath), Location, ex); } } } /// /// Validates the attributes. /// /// Both and are set. protected override void Initialize() { //verify that our params are correct if (AssemblyPath != null && Path != null) { throw new BuildException("Both asssembly and path attributes are set." + " Use one or the other.", Location); } } #endregion Override implemenation of Task } } nant-0.92-rc1/src/NAnt.Core/Tasks/IncludeTask.cs0000644000175000017500000002613311757302273021175 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian MacLean (ian@maclean.ms) // Gerry Shaw (gerry_shaw@yahoo.com) // Scott Hernandez (ScottHernandez@_yeah_not_really_@hotmail.com) using System; using System.Collections; using System.Globalization; using System.IO; using System.Xml; using NAnt.Core.Attributes; using NAnt.Core.Util; namespace NAnt.Core.Tasks { /// /// Includes an external build file. /// /// /// /// This task is used to break your build file into smaller chunks. You /// can load a partial build file and have it included into the build file. /// /// /// Any global (project level) tasks in the included build file are executed /// when this task is executed. Tasks in target elements are only executed /// if that target is executed. /// /// /// The project element attributes are ignored. /// /// /// This task can only be in the global (project level) section of the /// build file. /// /// /// This task can only include files from the file system. /// /// /// /// /// Include a task that fetches the project version from the /// GetProjectVersion.include build file. /// /// /// /// ]]> /// /// [TaskName("include")] public class IncludeTask : Task { #region Private Instance Fields private string _buildFileName; #endregion Private Instance Fields #region Private Static Fields /// /// Used to check for recursived includes. /// private static Stack _includedFileNames = new Stack(); private static string _currentBasedir = ""; private static int _nestinglevel = 0; #endregion Private Static Fields #region Public Instance Properties /// /// Build file to include. /// [TaskAttribute("buildfile", Required=true)] [StringValidator(AllowEmpty=false)] public string BuildFileName { get { return _buildFileName; } set { _buildFileName = value; } } #endregion Public Instance Properties #region Override implementation of Task /// /// Verifies parameters. /// protected override void Initialize() { // Task can only be included as a global task. // This might not be a firm requirement but you could get some real // funky errors if you start including targets wily-nily. if (Parent != null && !(Parent is Project)) { throw new BuildException(ResourceUtils.GetString("NA1180"), Location); } if (String.IsNullOrEmpty(_currentBasedir) || _nestinglevel == 0) { _currentBasedir = Project.BaseDirectory; } string buildFileName = null; try { // check if build file is valid file name buildFileName = Path.GetFullPath(Path.Combine(_currentBasedir, BuildFileName)); } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1128"), BuildFileName), Location, ex); } // check for recursive includes foreach (string currentFileName in _includedFileNames) { if (currentFileName == buildFileName) { throw new BuildException(ResourceUtils.GetString("NA1179"), Location); } } } protected override void ExecuteTask() { string includedFileName = Path.GetFullPath(Path.Combine(_currentBasedir, BuildFileName)); // check if build file exists if (!File.Exists(includedFileName)) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1127"), includedFileName), Location); } // check if file has already been mapped, if it has not yet been mapped, // add the include file to the map. This addresses Bug#: 3016497 if (Project.LocationMap.FileIsMapped(includedFileName)) { Log(Level.Verbose, ResourceUtils.GetString("String_DuplicateInclude"), includedFileName); return; } else { XmlDocument mapDoc = new XmlDocument(); mapDoc.Load(includedFileName); Project.LocationMap.Add(mapDoc); mapDoc = null; } // push ourselves onto the stack (prevents recursive includes) _includedFileNames.Push(includedFileName); // increment the nesting level _nestinglevel ++; Log(Level.Verbose, "Including file {0}.", includedFileName); // store original base directory string oldBaseDir = _currentBasedir; // set basedir to be used by the nested calls (if any) _currentBasedir = Path.GetDirectoryName(includedFileName); try { // This section addresses SF Bug#:2824210.. // // Description of issue: // The root cause to this bug is mismatching NamespaceURIs between the main // build file and the include file. There is no place where the include // build file's Namespace is added to the main build files namespace collection. // So if the NamespaceURI of the include file doesn't match the main build file, // then the Project class would not import any of the include file contents. // // Resolution: // The key is to have the Namespaces match between project and include files. // Rather than remove the Namespace checks in the Project class, I decided to // copy the project's namespace into the include file prior to importing into the // main file. Unfortunately, it is not an easy task. // Create two XmlDocument variables. One to sanitize the include file (doc) // and one to pass to the project class (loadDoc). XmlDocument doc = new XmlDocument(); XmlDocument loadDoc = new XmlDocument(); // Gets the namespace from the main project. string projectNamespaceURI = Project.Document.DocumentElement.NamespaceURI; // String variable to hold the main build file's namespace. string projectURI = ""; // Rather than loading the xml file directly into the XmlDocument, it is loaded // into an XmlTextReader so any NamespaceURI may be stripped out before proceeding // further. XmlTextReader includeXmlReader = new XmlTextReader(includedFileName); // Turn the namespaces off includeXmlReader.Namespaces = false; // Load the contents of the XmlTextReader into the doc XmlDocument doc.Load(includeXmlReader); // Strip the namespace attribute. doc.DocumentElement.Attributes.RemoveNamedItem("xmlns"); // Kill the XmlTextReader ((IDisposable)includeXmlReader).Dispose(); includeXmlReader = null; // Assigns the main build file's namespace to the // local string variable if it is not blank. if (!String.IsNullOrEmpty(projectNamespaceURI)) { projectURI = projectNamespaceURI; } // If the projectURI is not empty at this point, add // the Namespace attribute to the doc XmlDocument. if (!String.IsNullOrEmpty(projectURI)) { XmlAttribute projAttr = doc.CreateAttribute("xmlns"); projAttr.Value = projectURI; doc.DocumentElement.Attributes.Append(projAttr); } // Set up a stringwriter and XmlTextWriter variable to pass the // contents of the doc XmlDocument variable to. using (StringWriter includeFileSW = new StringWriter()) { XmlTextWriter includeFileXW = new XmlTextWriter(includeFileSW); // Loads the contents from doc to the XmlTextWriter. doc.WriteTo(includeFileXW); // Then the contents of the XmlTextWriter to the loadDoc XmlDocument // var. This will ensure that the main build file's Namespace // is loaded into the include file before it's passed to the Project // class. loadDoc.LoadXml(includeFileSW.ToString()); // Kill the XmlTextWriter ((IDisposable)includeFileXW).Dispose(); includeFileXW = null; } // Pass the loadDoc XmlDocument to the project. Project.InitializeProjectDocument(loadDoc); } catch (BuildException) { // rethrow exception throw; } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1128"), includedFileName), Location, ex); } finally { // pop off the stack _includedFileNames.Pop(); // decrease the nesting level _nestinglevel--; // restore original base directory _currentBasedir = oldBaseDir; } } #endregion Override implementation of Task } } nant-0.92-rc1/src/NAnt.Core/Tasks/MkDirTask.cs0000644000175000017500000000545311757302273020622 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Ian MacLean (imaclean@gmail.com) using System; using System.Globalization; using System.IO; using NAnt.Core.Attributes; using NAnt.Core.Util; namespace NAnt.Core.Tasks { /// /// Creates a directory and any non-existent parent directory if necessary. /// /// /// Create the directory build. /// /// /// ]]> /// /// /// /// Create the directory tree one/two/three. /// /// /// ]]> /// /// [TaskName("mkdir")] public class MkDirTask : Task { #region Private Instance Fields private DirectoryInfo _dir; #endregion Private Instance Fields #region Public Instance Properties /// /// The directory to create. /// [TaskAttribute("dir", Required=true)] public DirectoryInfo Dir { get { return _dir; } set { _dir = value; } } #endregion Public Instance Properties #region Override implementation of Task /// /// Creates the directory specified by the property. /// /// The directory could not be created. protected override void ExecuteTask() { try { if (!Dir.Exists) { Log(Level.Info, "Creating directory '{0}'.", Dir.FullName); Dir.Create(); } } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1137"), Dir.FullName), Location, ex); } } #endregion Override implementation of Task } } nant-0.92-rc1/src/NAnt.Core/Tasks/StyleTask.cs0000644000175000017500000004210411757302273020706 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Serge (serge@wildwestsoftware.com) // Gerry Shaw (gerry_shaw@yahoo.com) // Scott Hernandez (ScottHernandez@hotmail.com) // Tim Noll (tim.noll@gmail.com) // Giuseppe Greco (giuseppe.greco@agamura.com) using System; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Net; using System.Xml; using System.Xml.Xsl; using System.Xml.XPath; using NAnt.Core.Attributes; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.Core.Tasks { /// /// Processes a document via XSLT. /// /// /// Create a report in HTML. /// /// /// ]]> /// /// /// /// Create a report in HTML, with a param. /// /// /// /// /// /// /// ]]> /// /// /// /// Create a report in HTML, with a expanded param. /// /// /// /// /// /// /// ]]> /// /// /// /// Create some code based on a directory of templates. /// /// /// /// /// /// /// /// /// /// ]]> /// /// [TaskName("style")] public class StyleTask : Task { #region Private Instance Fields private DirectoryInfo _destDir; private string _extension = "html"; private Uri _xsltFile; private FileInfo _srcFile; private FileInfo _outputFile; private FileSet _inFiles = new FileSet(); private XsltParameterCollection _xsltParameters = new XsltParameterCollection(); private XsltExtensionObjectCollection _xsltExtensions = new XsltExtensionObjectCollection(); private Proxy _proxy; #endregion Private Instance Fields #region Public Instance Properties /// /// Directory in which to store the results. The default is the project /// base directory. /// [TaskAttribute("destdir", Required=false)] public DirectoryInfo DestDir { get { if (_destDir == null) { return new DirectoryInfo(Project.BaseDirectory); } return _destDir; } set { _destDir = value; } } /// /// Desired file extension to be used for the targets. The default is /// html. /// [TaskAttribute("extension", Required=false)] public string Extension { get { return _extension; } set { _extension = value; } } /// /// URI or path that points to the stylesheet to use. If given as path, it can /// be relative to the project's basedir or absolute. /// [TaskAttribute("style", Required=true)] public Uri XsltFile { get { return _xsltFile; } set { _xsltFile = value; } } /// /// Specifies a single XML document to be styled. Should be used with /// the attribute. /// [TaskAttribute("in", Required=false)] public FileInfo SrcFile { get { return _srcFile; } set { _srcFile = value; } } /// /// Specifies the output name for the styled result from the /// attribute. /// [TaskAttribute("out", Required=false)] public FileInfo OutputFile { get { return _outputFile; } set { _outputFile = value; } } /// /// Specifies a group of input files to which to apply the stylesheet. /// [BuildElement("infiles")] public FileSet InFiles { get { return _inFiles; } set { _inFiles = value; } } /// /// XSLT parameters to be passed to the XSLT transformation. /// [BuildElementCollection("parameters", "parameter")] public XsltParameterCollection Parameters { get { return _xsltParameters; } } /// /// XSLT extension objects to be passed to the XSLT transformation. /// [BuildElementCollection("extensionobjects", "extensionobject")] public XsltExtensionObjectCollection ExtensionObjects { get { return _xsltExtensions; } } /// /// The network proxy to use to access the Internet resource. /// [BuildElement("proxy")] public Proxy Proxy { get { return _proxy; } set { _proxy = value; } } #endregion Public Instance Properties #region Override implementation of Task protected override void ExecuteTask() { // ensure base directory is set, even if fileset was not initialized // from XML if (InFiles.BaseDirectory == null) { InFiles.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } StringCollection srcFiles = null; if (SrcFile != null) { srcFiles = new StringCollection(); srcFiles.Add(SrcFile.FullName); } else if (InFiles.FileNames.Count > 0) { if (OutputFile != null) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1148")), Location); } srcFiles = InFiles.FileNames; } if (srcFiles == null || srcFiles.Count == 0) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1147")), Location); } if (XsltFile.IsFile) { FileInfo fileInfo = new FileInfo(XsltFile.LocalPath); if (!fileInfo.Exists) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1149"), fileInfo.FullName), Location); } } else { HttpWebRequest request = (HttpWebRequest) WebRequest.Create(XsltFile); if (Proxy != null) { request.Proxy = Proxy.GetWebProxy(); } HttpWebResponse response = (HttpWebResponse) request.GetResponse(); if (response.StatusCode != HttpStatusCode.OK) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1149"), XsltFile), Location); } } foreach (string srcFile in srcFiles) { string destFile = null; if (OutputFile != null) { destFile = OutputFile.FullName; } if (String.IsNullOrEmpty(destFile)) { // TODO: use System.IO.Path (gs) // append extension if necessary string ext = Extension.IndexOf(".") > -1 ? Extension : "." + Extension; int extPos = srcFile.LastIndexOf('.'); if (extPos == -1) { destFile = srcFile + ext; } else { destFile = srcFile.Substring(0, extPos) + ext; } destFile = Path.GetFileName(destFile); } FileInfo srcInfo = new FileInfo(srcFile); FileInfo destInfo = new FileInfo(Path.GetFullPath(Path.Combine( DestDir.FullName, destFile))); if (!srcInfo.Exists) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1150"), srcInfo.FullName), Location); } bool destOutdated = !destInfo.Exists || srcInfo.LastWriteTime > destInfo.LastWriteTime; if (!destOutdated && XsltFile.IsFile) { FileInfo fileInfo = new FileInfo(XsltFile.LocalPath); destOutdated |= fileInfo.LastWriteTime > destInfo.LastWriteTime; } if (destOutdated) { XmlReader xmlReader = null; XmlReader xslReader = null; TextWriter writer = null; try { // store current directory string originalCurrentDirectory = Directory.GetCurrentDirectory(); // initialize XPath document holding input XML XPathDocument xml = null; try { // change current directory to directory containing // XSLT file, to allow includes to be resolved // correctly Directory.SetCurrentDirectory(srcInfo.DirectoryName); // load the xml that needs to be transformed Log(Level.Verbose, "Loading XML file '{0}'.", srcInfo.FullName); xmlReader = CreateXmlReader(new Uri(srcInfo.FullName)); xml = new XPathDocument(xmlReader); } finally { // restore original current directory Directory.SetCurrentDirectory(originalCurrentDirectory); } // initialize xslt parameters XsltArgumentList xsltArgs = new XsltArgumentList(); // set the xslt parameters foreach (XsltParameter parameter in Parameters) { if (IfDefined && !UnlessDefined) { xsltArgs.AddParam(parameter.ParameterName, parameter.NamespaceUri, parameter.Value); } } // create extension objects foreach (XsltExtensionObject extensionObject in ExtensionObjects) { if (extensionObject.IfDefined && !extensionObject.UnlessDefined) { object extensionInstance = extensionObject.CreateInstance(); xsltArgs.AddExtensionObject(extensionObject.NamespaceUri, extensionInstance); } } try { if (XsltFile.IsFile) { // change current directory to directory containing // XSLT file, to allow includes to be resolved // correctly FileInfo fileInfo = new FileInfo(XsltFile.LocalPath); Directory.SetCurrentDirectory(fileInfo.DirectoryName); } // load the stylesheet Log(Level.Verbose, "Loading stylesheet '{0}'.", XsltFile); xslReader = CreateXmlReader(XsltFile); // create writer for the destination xml writer = CreateWriter(destInfo.FullName); // do the actual transformation Log(Level.Info, "Processing '{0}' to '{1}'.", srcInfo.FullName, destInfo.FullName); XslCompiledTransform xslt = new XslCompiledTransform(); string xslEngineName = xslt.GetType().Name; Log(Level.Verbose, "Using {0} to load '{1}'.", xslEngineName, XsltFile); xslt.Load(xslReader, new XsltSettings(true, true), new XmlUrlResolver() ); Log(Level.Verbose, "Using {0} to process '{1}' to '{2}'.", xslEngineName, srcInfo.FullName, destInfo.FullName); xslt.Transform(xml, xsltArgs, writer); } finally { // restore original current directory Directory.SetCurrentDirectory(originalCurrentDirectory); } } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1151"), srcInfo.FullName, XsltFile), Location, ex); } finally { // ensure file handles are closed if (xmlReader != null) { xmlReader.Close(); } if (xslReader != null) { xslReader.Close(); } if (writer != null) { writer.Close(); } } } } } #endregion Override implementation of Task #region Protected Instance Methods protected virtual XmlReader CreateXmlReader(Uri uri) { Stream stream = null; XmlUrlResolver resolver = null; if (uri.IsFile) { stream = new FileStream(uri.LocalPath, FileMode.Open, FileAccess.Read); } else { resolver = new XmlUrlResolver(); HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(uri); if (Proxy != null) { request.Proxy = Proxy.GetWebProxy(); resolver.Credentials = Proxy.Credentials.GetCredential(); } else { resolver.Credentials = CredentialCache.DefaultCredentials; } stream = request.GetResponse().GetResponseStream(); } XmlTextReader xmlReader = new XmlTextReader(uri.ToString(), stream); xmlReader.XmlResolver = resolver; return new XmlValidatingReader(xmlReader); } protected virtual TextWriter CreateWriter(string filepath) { string targetDir = Path.GetDirectoryName(Path.GetFullPath(filepath)); if (!String.IsNullOrEmpty(targetDir) && !Directory.Exists(targetDir)) { Directory.CreateDirectory(targetDir); } return new StreamWriter(filepath); } #endregion Protected Instance Methods } } nant-0.92-rc1/src/NAnt.Core/Tasks/RegexTask.cs0000644000175000017500000001441611757302273020665 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Arjen Poutsma (poutsma@yahoo.com) // Sascha Andres (sa@programmers-world.com) // John Cole (john.cole@uai.com) using System; using System.Collections; using System.Globalization; using System.Text.RegularExpressions; using NAnt.Core.Attributes; using NAnt.Core.Util; namespace NAnt.Core.Tasks { /// /// Sets project properties based on the evaluatuion of a regular expression. /// /// /// /// The attribute must contain one or more /// /// named grouping constructs, which represents the names of the /// properties to be set. These named grouping constructs can be enclosed /// by angle brackets (?<name>) or single quotes (?'name'). /// /// /// In the build file, use the XML element to specify <, /// and to specify >. /// /// /// The named grouping construct must not contain any punctuation and it /// cannot begin with a number. /// /// /// /// /// Find the last word in the given string and stores it in the property /// lastword. /// /// /// /// /// ]]> /// /// /// /// /// Split the full filename and extension of a filename. /// /// /// /// ]]> /// /// /// /// /// Split the path and the filename. (This checks for / or \ /// as the path separator). /// /// /// /// ]]> /// /// /// Results in path=d:\Temp\SomeDir\SomeDir\ and file=bla.xml. /// /// [TaskName("regex")] public class RegexTask : Task { #region Private Instance Fields private string _pattern; private string _input; private RegexOptions _options = RegexOptions.None; #endregion Private Instance Fields #region Public Instance Properties /// /// Represents the regular expression to be evalued. /// /// /// The regular expression to be evalued. /// /// /// The pattern must contain one or more named constructs, which may /// not contain any punctuation and cannot begin with a number. /// [TaskAttribute("pattern", Required=true)] [StringValidator(AllowEmpty=false)] public string Pattern { get { return _pattern;} set { _pattern = value; } } /// /// A comma separated list of options to pass to the regex engine. The /// default is . /// [TaskAttribute("options", Required=false)] [StringValidator(AllowEmpty=true)] public RegexOptions Options { get { return _options;} set { _options = value; } } /// /// Represents the input for the regular expression. /// /// /// The input for the regular expression. /// [TaskAttribute("input", Required=true)] [StringValidator(AllowEmpty=true)] public string Input { get { return _input;} set { _input = value; } } #endregion Public Instance Properties #region Override implementation of Task /// /// Executes the task. /// protected override void ExecuteTask() { Regex regex = null; try { regex = new Regex(Pattern, Options); } catch (ArgumentException ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1145"), Pattern), Location, ex); } Match match = regex.Match(Input); if (match == Match.Empty) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1144"), Pattern, Input), Location); } // we start the iteration at 1, since the collection of groups // always starts with a group which matches the entire input and // is named '0', this group is of no interest to us for (int i = 1; i < match.Groups.Count; i++) { string groupName = regex.GroupNameFromNumber(i); Log(Level.Verbose, "Setting property '{0}' to '{1}'.", groupName, match.Groups[groupName].Value); Properties[groupName] = match.Groups[groupName].Value; } } #endregion Override implementation of Task } } nant-0.92-rc1/src/NAnt.Core/Tasks/GetTask.cs0000644000175000017500000004354711757302273020341 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Jay Turpin (jayturpin@hotmail.com) // Gerry Shaw (gerry_shaw@yahoo.com) using System; using System.Globalization; using System.IO; using System.Net; using System.Security.Cryptography.X509Certificates; using NAnt.Core.Attributes; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.Core.Tasks { /// /// Gets a particular file from a URL source. /// /// /// /// Options include verbose reporting and timestamp based fetches. /// /// /// Currently, only HTTP and UNC protocols are supported. FTP support may /// be added when more pluggable protocols are added to the System.Net /// assembly. /// /// /// The option enables you to control downloads /// so that the remote file is only fetched if newer than the local copy. /// If there is no local copy, the download always takes place. When a file /// is downloaded, the timestamp of the downloaded file is set to the remote /// timestamp. /// /// /// This timestamp facility only works on downloads using the HTTP protocol. /// /// /// /// /// Gets the index page of the NAnt home page, and stores it in the file /// help/index.html relative to the project base directory. /// /// /// /// ]]> /// /// /// /// /// Gets the index page of a secured web site using the given credentials, /// while connecting using the specified password-protected proxy server. /// /// /// /// /// /// /// /// /// ]]> /// /// [TaskName("get")] public class GetTask : Task { #region Private Instance Fields private string _src; private FileInfo _destFile; private string _httpProxy; private Proxy _proxy; private int _timeout = 100000; private bool _useTimeStamp; private Credential _credentials; private FileSet _certificates = new FileSet(); #endregion Private Instance Fields #region Public Instance Properties /// /// The URL from which to retrieve a file. /// [TaskAttribute("src", Required=true)] [StringValidator(AllowEmpty=false)] public string Source { get { return _src; } set { _src = StringUtils.ConvertEmptyToNull(value); } } /// /// The file where to store the retrieved file. /// [TaskAttribute("dest", Required=true)] public FileInfo DestinationFile { get { return _destFile; } set { _destFile = value; } } /// /// If inside a firewall, proxy server/port information /// Format: {proxy server name}:{port number} /// Example: proxy.mycompany.com:8080 /// [TaskAttribute("httpproxy")] [Obsolete("Use the child element instead.", false)] public string HttpProxy { get { return _httpProxy; } set { _httpProxy = value; } } /// /// The network proxy to use to access the Internet resource. /// [BuildElement("proxy")] public Proxy Proxy { get { return _proxy; } set { _proxy = value; } } /// /// The network credentials used for authenticating the request with /// the Internet resource. /// [BuildElement("credentials")] public Credential Credentials { get { return _credentials; } set { _credentials = value; } } /// /// Log errors but don't treat as fatal. The default is . /// [TaskAttribute("ignoreerrors")] [Obsolete("Use the 'failonerror' attribute instead.")] [BooleanValidator()] public bool IgnoreErrors { get { return FailOnError; } set { FailOnError = value; } } /// /// Conditionally download a file based on the timestamp of the local /// copy. HTTP only. The default is . /// [TaskAttribute("usetimestamp")] [BooleanValidator()] public bool UseTimeStamp { get { return _useTimeStamp; } set { _useTimeStamp = value; } } /// /// The length of time, in milliseconds, until the request times out. /// The default is 100000 milliseconds. /// [TaskAttribute("timeout")] [Int32Validator()] public int Timeout { get { return _timeout; } set { _timeout = value; } } /// /// The security certificates to associate with the request. /// [BuildElement("certificates")] public FileSet Certificates { get { return _certificates; } set { _certificates = value; } } #endregion Public Instance Properties #region Override implementation of Task /// /// Initializes task and ensures the supplied attributes are valid. /// protected override void Initialize() { if (DestinationFile.Exists && (FileAttributes.ReadOnly == (File.GetAttributes(DestinationFile.FullName) & FileAttributes.ReadOnly))) { throw new BuildException(string.Format("Destination file '{0}' is read-only.", DestinationFile.FullName), Location); } if (Proxy != null && HttpProxy != null) { throw new BuildException("The child element and the 'httpproxy' attribute are mutually exclusive.", Location); } } /// /// This is where the work is done /// protected override void ExecuteTask() { try { //set the timestamp to the file date. DateTime fileTimeStamp = new DateTime(); if (UseTimeStamp && DestinationFile.Exists) { fileTimeStamp = DestinationFile.LastWriteTime; Log(Level.Verbose, "Local file time stamp is {0}.", fileTimeStamp.ToString(CultureInfo.InvariantCulture)); } //set up the URL connection WebRequest webRequest = GetWebRequest(Source, fileTimeStamp); WebResponse webResponse = webRequest.GetResponse(); Stream responseStream = null; // Get stream // try three times, then error out int tryCount = 1; while (true) { try { responseStream = webResponse.GetResponseStream(); break; } catch (IOException ex) { if (tryCount > 3) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1125"), Source, DestinationFile.FullName), Location); } else { Log(Level.Warning, "Unable to open connection to '{0}' (try {1} of 3): " + ex.Message, Source, tryCount); } } // increment try count tryCount++; } // open file for writing BinaryWriter destWriter = new BinaryWriter(new FileStream( DestinationFile.FullName, FileMode.Create)); Log(Level.Info, "Retrieving '{0}' to '{1}'.", Source, DestinationFile.FullName); // Read in stream from URL and write data in chunks // to the dest file. int bufferSize = 100 * 1024; byte[] buffer = new byte[bufferSize]; int totalReadCount = 0; int totalBytesReadFromStream = 0; int totalBytesReadSinceLastDot = 0; do { totalReadCount = responseStream.Read(buffer, 0, bufferSize); if (totalReadCount != 0) { // zero means EOF // write buffer into file destWriter.Write(buffer, 0, totalReadCount); // increment byte counters totalBytesReadFromStream += totalReadCount; totalBytesReadSinceLastDot += totalReadCount; // display progress if (Verbose && totalBytesReadSinceLastDot > bufferSize) { if (totalBytesReadSinceLastDot == totalBytesReadFromStream) { // TO-DO !!!! //Log.Write(LogPrefix); } // TO-DO !!! //Log.Write("."); totalBytesReadSinceLastDot = 0; } } } while (totalReadCount != 0); if (totalBytesReadFromStream > bufferSize) { Log(Level.Verbose, ""); } Log(Level.Verbose, "Number of bytes read: {0}.", totalBytesReadFromStream.ToString(CultureInfo.InvariantCulture)); // clean up response streams destWriter.Close(); responseStream.Close(); // refresh file info DestinationFile.Refresh(); // check to see if we actually have a file... if(!DestinationFile.Exists) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1125"), Source, DestinationFile.FullName), Location); } // if (and only if) the use file time option is set, then the // saved file now has its timestamp set to that of the downloaded file if (UseTimeStamp) { // HTTP only if (webRequest is HttpWebRequest) { HttpWebResponse httpResponse = (HttpWebResponse) webResponse; // get timestamp of remote file DateTime remoteTimestamp = httpResponse.LastModified; Log(Level.Verbose, "'{0}' last modified on {1}.", Source, remoteTimestamp.ToString(CultureInfo.InvariantCulture)); // update timestamp of local file to match that of the // remote file TouchFile(DestinationFile, remoteTimestamp); } } } catch (BuildException) { // re-throw the exception throw; } catch (WebException ex) { // If status is WebExceptionStatus.ProtocolError, // there has been a protocol error and a WebResponse // should exist. Display the protocol error. if (ex.Status == WebExceptionStatus.ProtocolError) { // test for a 304 result (HTTP only) // Get HttpWebResponse so we can check the HTTP status code HttpWebResponse httpResponse = (HttpWebResponse) ex.Response; if (httpResponse.StatusCode == HttpStatusCode.NotModified) { //not modified so no file download. just return instead //and trace out something so the user doesn't think that the //download happened when it didn't Log(Level.Verbose, "'{0}' not downloaded. Not modified since {1}.", Source, DestinationFile.LastWriteTime.ToString(CultureInfo.InvariantCulture)); return; } else { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1125"), Source, DestinationFile.FullName), Location, ex); } } else { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1125"), Source, DestinationFile.FullName), Location, ex); } } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1125"), Source, DestinationFile.FullName), Location, ex); } } #endregion Override implementation of Task #region Protected Instance Methods /// /// Sets the timestamp of a given file to a specified time. /// protected void TouchFile(FileInfo file, DateTime touchDateTime) { try { if (file.Exists) { Log(Level.Verbose, "Touching file {0} with {1}.", file.FullName, touchDateTime.ToString(CultureInfo.InvariantCulture)); file.LastWriteTime = touchDateTime; } else { throw new FileNotFoundException(); } } catch (Exception e) { // swallow any errors and move on Log(Level.Verbose, "Error: {0}.", e.ToString()); } } #endregion Protected Instance Methods #region Private Instance Methods private WebRequest GetWebRequest(string url, DateTime fileLastModified) { WebRequest webRequest = null; Uri uri = new Uri(url); // conditionally determine type of connection // if HTTP, cast to an HttpWebRequest so that IfModifiedSince can be set if (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps) { HttpWebRequest httpRequest = (HttpWebRequest) WebRequest.Create(uri); //modify the headers if (!fileLastModified.Equals(new DateTime())) { // IfModifiedSince is an HTTP request header field for // conditionally downloading only resource modified after // the specific time. If the resource has not been modified // since the specific time, then a 304 response will be // returned. // By default all System.Net writes out the property in // GMT/UTC format. For good measure, 1 second is added to // make sure the the resource is newer. DateTime utcTime = fileLastModified.ToUniversalTime().AddSeconds(1); httpRequest.IfModifiedSince = utcTime; //REVISIT: at this point even non HTTP connections may support the if-modified-since //behaviour -we just check the date of the content and skip the write if it is not //newer. Some protocols (FTP) dont include dates, of course. } // associate security certificates foreach (string certificate in Certificates.FileNames) { httpRequest.ClientCertificates.Add( X509Certificate.CreateFromCertFile(certificate)); } webRequest = httpRequest; } else { webRequest = WebRequest.Create(uri); } // set the number of milliseconds that the request will wait // for a response webRequest.Timeout = Timeout; // configure proxy settings if (Proxy != null) { webRequest.Proxy = Proxy.GetWebProxy(); } else if (HttpProxy != null) { webRequest.Proxy = new WebProxy(HttpProxy); } // set authentication information if (Credentials != null) { webRequest.Credentials = Credentials.GetCredential(); } return webRequest; } #endregion Private Instance Methods } } nant-0.92-rc1/src/NAnt.Core/Tasks/IfTask.cs0000644000175000017500000003455611757302273020160 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2002-2003 Scott Hernandez // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Scott Hernandez (ScottHernandez@hotmail.com) // Jaroslaw Kowalski (jkowalski@users.sourceforge.net) using System; using System.Globalization; using System.IO; using NAnt.Core.Attributes; using NAnt.Core.Functions; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.Core.Tasks { /// /// Checks the conditional attributes and executes the children if /// . /// /// /// /// If no conditions are checked, all child tasks are executed. /// /// /// If more than one attribute is used, they are &&'d. The first /// to fail stops the check. /// /// /// The order of condition evaluation is, , /// , , /// . /// /// /// instead of using the deprecated attributes, we advise you to use the /// following functions in combination with the /// attribute: /// /// /// /// Function /// Description /// /// /// /// Checks whether the specified property exists. /// /// /// /// Checks whether the specified target exists. /// /// /// /// /// Tests the value of a property using expressions. /// /// /// Build release configuration /// /// ]]> /// /// /// /// Tests the the output of a function. /// /// /// /// /// ]]> /// /// /// /// (Deprecated) Check that a target exists. /// /// /// /// /// /// ]]> /// /// /// /// (Deprecated) Check existence of a property. /// /// /// /// /// ]]> /// /// /// /// (Deprecated) Check that a property value is true. /// /// /// /// /// ]]> /// /// /// /// /// (Deprecated) Check that a property exists and is /// (uses multiple conditions). /// /// /// /// /// /// ]]> /// /// which is the same as /// /// /// /// /// /// /// ]]> /// /// /// /// /// (Deprecated) Check file dates. If myfile.dll is uptodate, /// then do stuff. /// /// /// /// /// /// ]]> /// /// or /// /// /// /// /// /// /// /// ]]> /// /// or /// /// /// /// /// /// /// /// /// /// /// ]]> /// /// [TaskName("if")] public class IfTask : TaskContainer { #region Private Instance Fields private string _propNameTrue; private string _propNameExists; private string _targetName; private string _test; private FileSet _compareFiles; private FileSet _uptodateFiles; #endregion Private Instance Fields #region Public Instance Properties /// /// The file to compare if uptodate. /// [TaskAttribute("uptodatefile")] [System.Obsolete("Use instead.", false)] public string UpToDateFile { set { if (_uptodateFiles == null) { _uptodateFiles = new FileSet(); _uptodateFiles.Parent = this; _uptodateFiles.Project = Project; _uptodateFiles.NamespaceManager = NamespaceManager; } _uptodateFiles.Includes.Add(value); } } /// /// The file to check against for the uptodate file. /// [TaskAttribute("comparefile")] [System.Obsolete("Use instead.", false)] public string CompareFile { set { if (_compareFiles == null) { _compareFiles = new FileSet(); _compareFiles.Parent = this; _compareFiles.Project = Project; _compareFiles.NamespaceManager = NamespaceManager; } _compareFiles.Includes.Add(value); } } /// /// The that contains the comparison files for /// the (s) check. /// [BuildElement("comparefiles")] [System.Obsolete("Use task instead.", false)] public FileSet CompareFiles { get { return _compareFiles; } set { _compareFiles = value; } } /// /// The that contains the uptodate files for /// the (s) check. /// [BuildElement("uptodatefiles")] [System.Obsolete("Use task instead.", false)] public FileSet UpToDateFiles { get { return _uptodateFiles; } set { _uptodateFiles = value; } } /// /// Used to test whether a property is true. /// [TaskAttribute("propertytrue")] [System.Obsolete("Use instead.", false)] public string PropertyNameTrue { get { return _propNameTrue; } set { _propNameTrue = StringUtils.ConvertEmptyToNull(value); } } /// /// Used to test whether a property exists. /// [TaskAttribute("propertyexists")] [System.Obsolete("Use instead.", false)] public string PropertyNameExists { get { return _propNameExists;} set { _propNameExists = StringUtils.ConvertEmptyToNull(value); } } /// /// Used to test whether a target exists. /// [TaskAttribute("targetexists")] [System.Obsolete("Use instead.", false)] public string TargetNameExists { get { return _targetName; } set { _targetName = StringUtils.ConvertEmptyToNull(value); } } /// /// Used to test arbitrary boolean expression. /// [TaskAttribute("test")] [BooleanValidator()] public string Test { get { return _test; } set { _test = StringUtils.ConvertEmptyToNull(value); } } #endregion Public Instance Properties #region Protected Instance Properties protected virtual bool ConditionsTrue { get { bool ret = true; if (Test != null) { if (!Convert.ToBoolean(Test, CultureInfo.InvariantCulture)) { return false; } } // check if target exists if (TargetNameExists != null) { ret = ret && (Project.Targets.Find(TargetNameExists) != null); if (!ret) { return false; } } // check if property exists if (PropertyNameExists != null) { ret = ret && Properties.Contains(PropertyNameExists); if (!ret) { return false; } } // check if value of property is boolean true if (PropertyNameTrue != null) { try { ret = ret && bool.Parse(Properties[PropertyNameTrue]); if (!ret) { return false; } } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1126"), PropertyNameTrue), Location, ex); } } // check if file is up-to-date if (UpToDateFiles != null) { FileInfo primaryFile = UpToDateFiles.MostRecentLastWriteTimeFile; if (primaryFile == null || !primaryFile.Exists) { ret = false; Log(Level.Verbose, "Uptodatefile(s) do(es) not exist."); } else { string newerFile = FileSet.FindMoreRecentLastWriteTime(_compareFiles.FileNames, primaryFile.LastWriteTime); bool needsAnUpdate = (newerFile != null); if (needsAnUpdate) { Log(Level.Verbose, "{0} is newer than {1}.", newerFile, primaryFile.Name); } ret = ret && !needsAnUpdate; } if (!ret) { return false; } } return ret; } } #endregion Protected Instance Properties #region Override implementation of TaskContainer protected override void ExecuteTask() { if (ConditionsTrue) { base.ExecuteTask(); } } #endregion Override implementation of TaskContainer #region Override implementation of Task protected override void Initialize() { base.Initialize(); //check that we have something to do. if ((UpToDateFiles == null || CompareFiles == null) && Test == null && PropertyNameExists == null && PropertyNameTrue == null && TargetNameExists == null) { throw new BuildException("At least one if condition" + " must be set (test, propertytrue, targetexists, etc...):", Location); } } #endregion Override implementation of Task } /// /// The opposite of the if task. /// /// /// Check that a property does not exist. /// /// /// /// /// ]]> /// /// Check that a property value is not true. /// /// /// /// /// ]]> /// /// /// /// Check that a target does not exist. /// /// /// /// /// ]]> /// /// [TaskName("ifnot")] [Obsolete("Use the task instead.", false)] public class IfNotTask : IfTask { #region Override implementation of IfTask protected override bool ConditionsTrue { get { return !base.ConditionsTrue; } } #endregion Override implementation of IfTask } } nant-0.92-rc1/src/NAnt.Core/Tasks/DescriptionTask.cs0000644000175000017500000000265411757302273022077 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Gerry Shaw (gerry_shaw@yahoo.com) using System; using NAnt.Core.Attributes; namespace NAnt.Core.Tasks { /// /// An empty task that allows a build file to contain a description. /// /// /// Set a description. /// /// This is a description. /// ]]> /// /// [TaskName("description")] public class DescriptionTask : Task { #region Override implementation of Task protected override void ExecuteTask() { } #endregion Override implementation of Task } } nant-0.92-rc1/src/NAnt.Core/Tasks/UpToDateTask.cs0000644000175000017500000001042011757302273021267 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2002-2003 Scott Hernandez // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Scott Hernandez (ScottHernandez@hotmail.com) // Jaroslaw Kowalski (jkowalski@users.sourceforge.net) using System; using System.Globalization; using System.IO; using NAnt.Core.Attributes; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.Core.Tasks { /// /// Check modification dates on groups of files. /// /// /// If all are same or newer than all , the specified property is set to , otherwise it /// is set to . /// /// /// /// Check file dates. If myfile.dll is same or newer than myfile.cs, then set myfile.dll.uptodate property /// to either or . /// /// /// /// /// /// /// /// /// /// /// ]]> /// /// [TaskName("uptodate")] public class UpToDateTask : Task { #region Private Instance Fields private string _propertyName; private FileSet _sourceFiles; private FileSet _targetFiles; #endregion Private Instance Fields #region Public Instance Properties /// /// Property that will be set to or depending on the /// result of the date check. /// [TaskAttribute("property", Required=true)] [StringValidator(AllowEmpty=false)] public string PropertyName { get { return _propertyName; } set { _propertyName = StringUtils.ConvertEmptyToNull(value); } } /// /// The that contains list of source files. /// [BuildElement("sourcefiles")] public FileSet SourceFiles { get { return _sourceFiles; } set { _sourceFiles = value; } } /// /// The that contains list of target files. /// [BuildElement("targetfiles")] public FileSet TargetFiles { get { return _targetFiles; } set { _targetFiles = value; } } #endregion Public Instance Properties #region Override implementation of Task protected override void ExecuteTask() { bool value = true; FileInfo primaryFile = _targetFiles.MostRecentLastWriteTimeFile; if (primaryFile == null || !primaryFile.Exists) { value = false; Log(Level.Verbose, "Destination file(s) do(es) not exist."); } else { string newerFile = FileSet.FindMoreRecentLastWriteTime(_sourceFiles.FileNames, primaryFile.LastWriteTime); bool needsAnUpdate = (newerFile != null); if (needsAnUpdate) { value = false; Log(Level.Verbose, "{0} is newer than {1}.", newerFile, primaryFile.Name); } } Project.Properties[PropertyName] = Convert.ToString(value, CultureInfo.InvariantCulture); } #endregion Override implementation of Task } } nant-0.92-rc1/src/NAnt.Core/Tasks/CopyTask.cs0000644000175000017500000015456311757302273020535 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Ian MacLean (imaclean@gmail.com) // Ryan Boggs (rmboggs@users.sourceforge.net) using System; using System.Collections; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Text; using NAnt.Core.Attributes; using NAnt.Core.Types; using NAnt.Core.Util; using NAnt.Core.Filters; namespace NAnt.Core.Tasks { /// /// Copies a file, a directory, or set of files to a new file or directory. /// /// /// /// Files are only copied if the source file is newer than the destination /// file, or if the destination file does not exist. However, you can /// explicitly overwrite files with the attribute. /// /// /// Entire directory structures can be copied to a new location. For this /// to happen, the following criteria must be met: /// /// /// /// /// Everything in the fileset is included /// /// /// /// /// The directory structure is not flattened /// /// /// /// /// Empty directories are included /// /// /// /// /// Destination directory does not exist /// /// /// /// /// If any of these items are not met, then the files within the source /// directory will be copied over instead of the entire directory structure. /// /// /// When a is used to select files or directories to /// copy, the attribute must be set. Files that are /// located under the base directory of the will /// be copied to a directory under the destination directory matching the /// path relative to the base directory of the , /// unless the attribute is set to /// . /// /// /// Files that are not located under the the base directory of the /// will be copied directly under to the destination /// directory, regardless of the value of the /// attribute. /// ///

Encoding

/// /// Unless an encoding is specified, the encoding associated with the /// system's current ANSI code page is used. /// /// /// An UTF-8, little-endian Unicode, and big-endian Unicode encoded text /// file is automatically recognized, if the file starts with the /// appropriate byte order marks. /// /// /// If you employ filters in your copy operation, you should limit the copy /// to text files. Binary files will be corrupted by the copy operation. /// ///
/// /// /// Copy a single file while changing its encoding from "latin1" to /// "utf-8". /// /// /// /// ]]> /// /// /// /// Copy a set of files to a new directory. /// /// /// /// /// /// /// ]]> /// /// /// /// /// Copy a set of files to a directory, replacing @TITLE@ with /// "Foo Bar" in all files. /// /// /// /// /// /// /// /// /// /// /// /// /// ]]> /// /// /// /// /// Copy an entire directory and its contents. /// /// /// /// /// /// ]]> /// /// [TaskName("copy")] public class CopyTask : Task { #region Private Instance Fields private FileInfo _sourceFile; private FileInfo _toFile; private DirectoryInfo _toDirectory; private bool _overwrite; private bool _flatten; private FileSet _fileset = new FileSet(); private FileOperationMap _operationMap; private bool _includeEmptyDirs = true; private FilterChain _filters; private Encoding _inputEncoding; private Encoding _outputEncoding; #endregion Private Instance Fields #region Public Instance Constructors /// /// Initialize new instance of the . /// public CopyTask() { if (PlatformHelper.IsUnix) { _operationMap = new FileOperationMap(); } else { _operationMap = new FileOperationMap(StringComparer.InvariantCultureIgnoreCase); } } #endregion Public Instance Constructors #region Public Instance Properties /// /// The file to copy. /// [TaskAttribute("file")] public virtual FileInfo SourceFile { get { return _sourceFile; } set { _sourceFile = value; } } /// /// The file to copy to. /// [TaskAttribute("tofile")] public virtual FileInfo ToFile { get { return _toFile; } set { _toFile = value; } } /// /// The directory to copy to. /// [TaskAttribute("todir")] public virtual DirectoryInfo ToDirectory { get { return _toDirectory; } set { _toDirectory = value; } } /// /// Overwrite existing files even if the destination files are newer. /// The default is . /// [TaskAttribute("overwrite")] [BooleanValidator()] public bool Overwrite { get { return _overwrite; } set { _overwrite = value; } } /// /// Ignore directory structure of source directory, copy all files into /// a single directory, specified by the /// attribute. The default is . /// [TaskAttribute("flatten")] [BooleanValidator()] public virtual bool Flatten { get { return _flatten; } set { _flatten = value; } } /// /// Copy any empty directories included in the . /// The default is . /// [TaskAttribute("includeemptydirs")] [BooleanValidator()] public bool IncludeEmptyDirs { get { return _includeEmptyDirs; } set { _includeEmptyDirs = value; } } /// /// Used to select the files to copy. To use a , /// the attribute must be set. /// [BuildElement("fileset")] public virtual FileSet CopyFileSet { get { return _fileset; } set { _fileset = value; } } /// /// Chain of filters used to alter the file's content as it is copied. /// [BuildElement("filterchain")] public virtual FilterChain Filters { get { return _filters; } set { _filters = value; } } /// /// The encoding to use when reading files. The default is the system's /// current ANSI code page. /// [TaskAttribute("inputencoding")] public Encoding InputEncoding { get { return _inputEncoding; } set { _inputEncoding = value; } } /// /// The encoding to use when writing the files. The default is /// the encoding of the input file. /// [TaskAttribute("outputencoding")] public Encoding OutputEncoding { get { return _outputEncoding; } set { _outputEncoding = value; } } #endregion Public Instance Properties #region Protected Instance Properties /// /// The set of files to perform a file operation on. /// /// /// /// FileCopyMap should now be considered a readonly hashtable. Any changes to /// this property will not be taken into account during the file operation /// task. To interact with the file operation, use the /// property. /// /// /// The key of the is the absolute path of /// the destination file and the value is a /// holding the path and last write time of the most recently updated /// source file that is selected to be copied or moved to the /// destination file. /// /// /// On Windows, the is case-insensitive. /// /// [ObsoleteAttribute("FileCopyMap is now considered a readonly hashtable. To interact with file operation, use the OperationMap property")] protected Hashtable FileCopyMap { get { return _operationMap.ConvertToHashtable(); } } /// /// Gets the operation map containing all the files/directories to /// perform file operations on. /// /// /// /// The type of class for this object inherits from KeyedCollection /// and is structured so that the key of this collection contains the /// full path of the target file/location while the value contains /// the object /// with the operation details. /// /// /// On Windows, the /// is case-insensitive. /// /// protected FileOperationMap OperationMap { get { return _operationMap; } } #endregion Protected Instance Properties #region Override implementation of Task /// /// Checks whether the task is initialized with valid attributes. /// protected override void Initialize() { if (Flatten && ToDirectory == null) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "'flatten' attribute requires that 'todir' has been set."), Location); } if (ToDirectory == null && CopyFileSet != null && CopyFileSet.Includes.Count > 0) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "The 'todir' should be set when using the element" + " to specify the list of files to be copied."), Location); } if (SourceFile != null && CopyFileSet != null && CopyFileSet.Includes.Count > 0) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "The 'file' attribute and the element" + " cannot be combined."), Location); } if (ToFile == null && ToDirectory == null) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Either the 'tofile' or 'todir' attribute should be set."), Location); } if (ToFile != null && ToDirectory != null) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "The 'tofile' and 'todir' attribute cannot both be set."), Location); } } /// /// Executes the Copy task. /// /// A file that has to be copied does not exist or could not be copied. protected override void ExecuteTask() { // ensure base directory is set, even if fileset was not initialized // from XML if (CopyFileSet.BaseDirectory == null) { CopyFileSet.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } // Clear previous copied files _operationMap.Clear(); // copy a single file object. if (SourceFile != null) { // Setup the necessary local vars FileOperation operation; FileSystemInfo srcInfo; FileSystemInfo dstInfo; // If the full path in the SourceFile is an actual file, // assign the SourceFile object as is to srcInfo. if (SourceFile.Exists) { srcInfo = SourceFile; } // If the full path in the SoureFile is a directory, // assign the SourceFile object as a DirectoryInfo object to srcInfo. else if (Directory.Exists(SourceFile.FullName)) { srcInfo = new DirectoryInfo(SourceFile.FullName); } // Otherwise, throw an error. else { throw CreateSourceFileNotFoundException(SourceFile.FullName); } // If the ToFile object is not null, assign it to dstInfo; // otherwise, assign the ToDirectory object to dstInfo. if (ToFile != null) { dstInfo = ToFile; } else { dstInfo = ToDirectory; } // Initialize the operation var with the srcInfo and dstInfo // objects that were assigned above. operation = new FileOperation(srcInfo, dstInfo); // If the user specified "Overwrite" or the target file/path // is considered outdated, ensure that the target file/path is // normalized before adding to the operation map. if (Overwrite || operation.Outdated) { operation.NormalizeTargetAttributes(); _operationMap.Add(operation); } } // This copy/moves the entire directory. In order for this to occur, the // following criteria needs to be met: // * Everything in the fileset is included // * The directory structure is not flattened // * Empty directories are included // * and either // * the destination directory does not exist // * or the destination directory is the same as source directory but // with different casing (ie: C:\nant to C:\NAnt) else if (CopyFileSet.IsEverythingIncluded && !Flatten && IncludeEmptyDirs && FileOperation.TargetDirectoryDoesNotExist(CopyFileSet.BaseDirectory, ToDirectory)) { OperationMap.Add(new FileOperation(CopyFileSet.BaseDirectory, ToDirectory)); } // Otherwise, copy/move the individual files. else { // If no includes were specified, add all files and subdirectories // from the fileset's base directory to the fileset. if (CopyFileSet.Includes.Count == 0) { CopyFileSet.Includes.Add("**/*"); // Make sure to rescan the fileset after adding "**/*" CopyFileSet.Scan(); } // copy file set contents. // get the complete path of the base directory of the fileset, // ie, c:\work\nant\src DirectoryInfo srcBaseInfo = CopyFileSet.BaseDirectory; // if source file not specified use fileset foreach (string pathname in CopyFileSet.FileNames) { FileInfo srcInfo = new FileInfo(pathname); if (srcInfo.Exists) { // will holds the full path to the destination file string dstFilePath; if (Flatten) { dstFilePath = Path.Combine(ToDirectory.FullName, srcInfo.Name); } else { // Gets the relative path and file info from the full // source filepath // pathname = C:\f2\f3\file1, srcBaseInfo=C:\f2, then // dstRelFilePath=f3\file1 string dstRelFilePath = ""; if (srcInfo.FullName.IndexOf(srcBaseInfo.FullName, 0) != -1) { dstRelFilePath = srcInfo.FullName.Substring( srcBaseInfo.FullName.Length); } else { dstRelFilePath = srcInfo.Name; } if (dstRelFilePath[0] == Path.DirectorySeparatorChar) { dstRelFilePath = dstRelFilePath.Substring(1); } // The full filepath to copy to. dstFilePath = Path.Combine(ToDirectory.FullName, dstRelFilePath); } // Setup both the destination info and file operation vars. FileInfo dstInfo = new FileInfo(dstFilePath); FileOperation operation = new FileOperation(srcInfo, dstInfo); // If the user specified "Overwrite" or the target file/path // is considered outdated, proceed to add to operation map. if (Overwrite || operation.Outdated) { // if multiple source files are selected to be copied // to the same destination file, then only the last // updated source should actually be copied if (_operationMap.ContainsKey(dstInfo.FullName)) { _operationMap[dstInfo.FullName].UpdateSource(srcInfo); } else { // ensure that the target file/path is normalized // before adding to the operation map. operation.NormalizeTargetAttributes(); _operationMap.Add(operation); } } } else { throw CreateSourceFileNotFoundException(srcInfo.FullName); } } if (IncludeEmptyDirs && !Flatten) { // create any specified directories that weren't created during the copy (ie: empty directories) foreach (string pathname in CopyFileSet.DirectoryNames) { DirectoryInfo srcInfo = new DirectoryInfo(pathname); // skip directory if not relative to base dir of fileset if (srcInfo.FullName.IndexOf(srcBaseInfo.FullName) == -1) { continue; } string dstRelPath = srcInfo.FullName.Substring(srcBaseInfo.FullName.Length); if (dstRelPath.Length > 0 && dstRelPath[0] == Path.DirectorySeparatorChar) { dstRelPath = dstRelPath.Substring(1); } // The full filepath to copy to. string destinationDirectory = Path.Combine(ToDirectory.FullName, dstRelPath); if (!Directory.Exists(destinationDirectory)) { try { Directory.CreateDirectory(destinationDirectory); } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Failed to create directory '{0}'.", destinationDirectory), Location, ex); } Log(Level.Verbose, "Created directory '{0}'.", destinationDirectory); } } } } // do all the actual copy operations now DoFileOperations(); } #endregion Override implementation of Task #region Protected Instance Methods /// /// Actually does the file copies. /// protected virtual void DoFileOperations() { // If the operation map is empty, exit (return) the method. if (OperationMap.Count <= 0) { return; } // Get the number of file and directory copies to display to // the user. int fileMovements = OperationMap.CountFileOperations(); int dirMovements = OperationMap.CountDirectoryOperations(); // Output the number of file copies if (fileMovements > 0) { if (ToFile != null) { Log(Level.Info, "Copying {0} file{1} to '{2}'.", fileMovements, (fileMovements != 1) ? "s" : "", ToFile); } else { Log(Level.Info, "Copying {0} file{1} to '{2}'.", fileMovements, (fileMovements != 1) ? "s" : "", ToDirectory); } } // Output the number of directory copies if (dirMovements > 0) { if (ToFile != null) { Log(Level.Info, "Copying {0} {1} to '{2}'.", dirMovements, (dirMovements != 1) ? "directories" : "directory", ToFile); } else { Log(Level.Info, "Copying {0} {1} to '{2}'.", dirMovements, (dirMovements != 1) ? "directories" : "directory", ToDirectory); } } // loop thru our file list for (int i = 0; i < OperationMap.Count; i++) { // Setup a temporary var to hold the current file operation // details. FileOperation currentOperation = OperationMap[i]; if (currentOperation.SourceEqualsTarget()) { Log(Level.Verbose, "Skipping self-copy of '{0}'.", currentOperation.Source); continue; } try { Log(Level.Verbose, "Copying {0}.", currentOperation.ToString()); switch (currentOperation.OperationType) { case OperationType.FileToFile: // create directory if not present string destinationDirectory = Path.GetDirectoryName(currentOperation.Target); if (!Directory.Exists(destinationDirectory)) { Directory.CreateDirectory(destinationDirectory); Log(Level.Verbose, "Created directory '{0}'.", destinationDirectory); } // Ensure the target file is removed before // attempting to copy. if (File.Exists(currentOperation.Target)) { File.Delete(currentOperation.Target); } // copy the file with filters FileUtils.CopyFile(currentOperation.Source, currentOperation.Target, Filters, InputEncoding, OutputEncoding); break; case OperationType.FileToDirectory: // Setup a local var that combines the directory // of the target path with the source file name. string targetFile = Path.Combine(currentOperation.Target, Path.GetFileName(currentOperation.Source)); // create directory if not present if (!Directory.Exists(currentOperation.Target)) { Directory.CreateDirectory(currentOperation.Target); Log(Level.Verbose, "Created directory '{0}'.", currentOperation.Target); } // Ensure the target file is removed before // attempting to copy. if (File.Exists(targetFile)) { File.Delete(targetFile); } // copy the file with filters FileUtils.CopyFile(currentOperation.Source, targetFile, Filters, InputEncoding, OutputEncoding); break; case OperationType.DirectoryToDirectory: // Throw a build exception if the target directory // already exists. if (Directory.Exists(currentOperation.Target)) { throw new BuildException( string.Format(CultureInfo.InvariantCulture, "Failed to copy {0}. Directory '{1}' already exists.", currentOperation.ToString(), currentOperation.Target)); } // Copy over the entire directory with filters FileUtils.CopyDirectory(currentOperation.Source, currentOperation.Target, Filters, InputEncoding, OutputEncoding); break; default: throw new BuildException("Unrecognized copy operation. " + "The copy task can only copy a file to file, " + "file to directory, or directory to directory."); } } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Cannot copy {0}.", currentOperation.ToString()), Location, ex); } } } protected virtual BuildException CreateSourceFileNotFoundException (string sourceFile) { return new BuildException(string.Format(CultureInfo.InvariantCulture, "Could not find file '{0}' to copy.", sourceFile), Location); } #endregion Protected Instance Methods /// /// Holds the absolute paths and last write time of a given file. /// protected class FileDateInfo { #region Public Instance Constructors /// /// Initializes a new instance of the /// class /// for the specified . /// /// /// A object containing /// the full path and last write time of the file the object represents. /// public FileDateInfo(FileSystemInfo file) : this(file.FullName, file.LastWriteTime) {} /// /// Initializes a new instance of the /// class for the specified file and last write time. /// /// The absolute path of the file. /// The last write time of the file. public FileDateInfo(string path, DateTime lastWriteTime) { _path = path; _lastWriteTime = lastWriteTime; } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets the absolute path of the current file. /// /// /// The absolute path of the current file. /// public string Path { get { return _path; } } /// /// Gets the time when the current file was last written to. /// /// /// The time when the current file was last written to. /// public DateTime LastWriteTime { get { return _lastWriteTime; } } #endregion Public Instance Properties #region Private Instance Fields private DateTime _lastWriteTime; private string _path; #endregion Private Instance Fields } /// /// Provides methods and properties to properly manage file operations for /// NAnt file system based tasks (such as CopyTask and MoveTask). /// protected class FileOperation { #region Private Instance Fields private FileSystemInfo _source; private FileSystemInfo _target; private StringComparer _comparer; #endregion Private Instance Fields #region Public Constructors /// /// Initializes a new instance of the /// class with the /// source and target locations specified. /// /// /// A object representing the file/location /// where the file operation will start. /// /// /// A object representing the file/location /// where the file operation will end. /// public FileOperation(FileSystemInfo source, FileSystemInfo target) { if (source == null) { throw new ArgumentNullException("source"); } if (target == null) { throw new ArgumentNullException("target"); } if (IsFileSystemType(source) && IsFileSystemType(target)) { throw new BuildException("Cannot transfer directory to file"); } _source = source; _target = target; } #endregion Public Constructors #region Public Instance Properties /// /// Gets or sets the string comparer to use when comparing /// the source path to the target path. /// public StringComparer Comparer { get { return _comparer; } set { _comparer = value; } } /// /// Gets the full path of /// . /// public string Source { get { return _source.FullName; } } /// /// Gets the details of the source path. /// public FileSystemInfo SourceInfo { get { return _source; } } /// /// Gets the type of /// . /// public Type SourceType { get { return _source.GetType(); } } /// /// Gets the type of the file operation an instance of /// represents. /// public OperationType OperationType { get { if (IsFileSystemType(SourceInfo) && IsFileSystemType(TargetInfo)) { return OperationType.FileToFile; } if (IsFileSystemType(SourceInfo) && IsFileSystemType(TargetInfo)) { return OperationType.FileToDirectory; } return OperationType.DirectoryToDirectory; } } /// /// Gets a value indicating whether /// is /// outdated. /// /// /// true if /// is /// outdated (or simply a directory); otherwise, false. /// public bool Outdated { get { return IsFileSystemType(_target) || (IsFileSystemType(_target) && TargetIsOutdated(_source, _target)); } } /// /// Gets the full path of /// . /// public string Target { get { return _target.FullName; } } /// /// Gets the details of the target path. /// public FileSystemInfo TargetInfo { get { return _target; } } /// /// Gets the type of /// . /// public Type TargetType { get { return _target.GetType(); } } #endregion Public Instance Properties #region Public Instance Methods /// /// Normalizes the attributes of /// . /// public void NormalizeTargetAttributes() { if (IsFileSystemType(_target) && _target.Exists && _target.Attributes != FileAttributes.Normal) { File.SetAttributes(_target.FullName, FileAttributes.Normal); } } /// /// Checks to see whether or not the full path of /// /// matches the full path of /// . /// /// /// is /// used to check path equality. /// /// /// true if both paths match; otherwise false. /// public bool SourceEqualsTarget() { return _comparer.Compare(_source.FullName, _target.FullName) == 0; } /// /// Checks to see whether or not the full path of /// /// is identical to the full path of /// . /// /// /// The difference between this method and SourceEqualsTarget is /// that the casing of the path is never ignored regardless of /// operating system. /// /// /// true if both paths are identical; otherwise false. /// public bool SourceIsIdenticalToTarget() { return _source.FullName.Equals(_target.FullName, StringComparison.InvariantCulture); } /// /// Updates the source of a given instance based on the /// . /// /// If the LastWriteTime property of the /// is greater than the LastWriteTime property of /// , then /// is /// replaced with . /// /// /// /// The new to replace /// the current /// object. /// public void UpdateSource(FileSystemInfo newSource) { if (_source.LastWriteTime < newSource.LastWriteTime) { _source = newSource; } } /// /// Returns a that represents the current /// . /// /// /// A that represents the current /// . /// public override string ToString() { return String.Format("'{0}' to '{1}'", Source, Target); } #endregion Public Instance Methods #region Public Static Methods /// /// Checks to see if a given /// target is considered outdated. /// /// /// A used for comparison purposes /// against . /// /// /// The to check. /// /// /// true if the target file is considered out of date; otherwise /// false /// public static bool TargetIsOutdated(FileSystemInfo source, FileSystemInfo target) { return (!target.Exists) || (source.LastWriteTime > target.LastWriteTime); } /// /// Checks to see if the target directory does not exist or that /// it does match the source directory name but not string casing. /// /// /// Source directory to check against . /// /// /// The target directory to validate. /// /// /// true if the target directory does not exist or matches the source /// directory name but not casing; otherwise false /// public static bool TargetDirectoryDoesNotExist(DirectoryInfo source, DirectoryInfo target) { // If the target doesn't exist, return true. if (!target.Exists) { return true; } // Otherwise, check to see if the source and target paths are the same when ignoring case. // Return the result of the path comparison. return source.FullName.Equals(target.FullName, StringComparison.InvariantCultureIgnoreCase); } #endregion Public Static Methods #region Private Instance Methods /// /// Checks to see whether is a file type or /// a directory type. /// /// /// The FileSystemInfo type used to compare with. /// /// /// The object to check. /// /// /// true if is the same type as /// ; otherwise, false. /// private bool IsFileSystemType(FileSystemInfo item) where TFileSystemInfo : FileSystemInfo { return item.GetType() == typeof(TFileSystemInfo); } #endregion Private Instance Methods } /// /// A collection class used to track all of the /// objects for /// a given file operation task (such as the CopyTask or MoveTask). /// protected class FileOperationMap : KeyedCollection { #region Private Instance Fields /// /// The StringComparer used when comparing file paths. /// private StringComparer _stringComparer; #endregion Private Instance Fields #region Public Constructors /// /// Initializes a new instance of the /// /// class that uses the default string comparer. /// public FileOperationMap() : base(StringComparer.InvariantCulture) { _stringComparer = StringComparer.InvariantCulture; } /// /// Initializes a new instance of the /// /// class that uses the specified string comparer. /// /// /// The string comparer to use when comparing keys in the /// . /// public FileOperationMap(StringComparer comparer) : base(comparer) { _stringComparer = comparer; } #endregion Public Constructors #region Public Instance Methods /// /// Determines whether the /// contains the /// specified key. /// /// /// The key to locate in the /// . /// /// /// true if the /// contains an element with the specified key; otherwise, false. /// public bool ContainsKey(string key) { if (Dictionary != null) { return Dictionary.ContainsKey(key); } return false; } /// /// Counts the number of directory operations in a collection. /// /// /// The number of directory operations performed by this collection. /// public int CountDirectoryOperations() { int result = 0; for (int i = 0; i < this.Count; i++) { if (this[i].SourceType == typeof(DirectoryInfo)) { result++; } } return result; } /// /// Counts the number of file operations in a collection. /// /// /// The number of file operations performed by this collection. /// public int CountFileOperations() { int result = 0; for (int i = 0; i < this.Count; i++) { if (this[i].SourceType == typeof(FileInfo)) { result++; } } return result; } /// /// Converts the current instance of /// to /// the old style FileCopyMap hashtable. /// /// /// The contents of /// in a /// new hashtable. /// public Hashtable ConvertToHashtable() { // Setup var to return Hashtable result; // Initialize return var with the proper case sensitivity // based on underlying OS. if (PlatformHelper.IsUnix) { result = new Hashtable(); } else { result = CollectionsUtil.CreateCaseInsensitiveHashtable(); } // Loop through this collection and load the return hashtable var. for (int i = 0; i < this.Count; i++) { FileOperation temp = this[i]; string sourceFileName; string targetFileName; // For a FileToFile operation, load the file names in the return // hashtable var as is. if (temp.OperationType == CopyTask.OperationType.FileToFile) { result.Add(temp.Target, new FileDateInfo(temp.SourceInfo)); } // For a FileToDirectory operation, use the source file name as // the target file name and load accordingly. else if (temp.OperationType == CopyTask.OperationType.FileToDirectory) { sourceFileName = Path.GetFileName(temp.Source); targetFileName = Path.Combine(temp.Target, sourceFileName); result.Add(targetFileName, new FileDateInfo(temp.SourceInfo)); } // For other operations (ie: DirectoryToDirectory), scan the // source directory for all files and load them into the // return hashtable var. else { // Retrieve all files from the current path and any subdirectories. DirectoryScanner dirScan = new DirectoryScanner(); dirScan.BaseDirectory = temp.SourceInfo as DirectoryInfo; dirScan.Includes.Add("**/*"); dirScan.Scan(); StringCollection sourceFiles = dirScan.FileNames; for (int s = 0; s < sourceFiles.Count; s++) { string source = sourceFiles[s]; sourceFileName = Path.GetFileName(source); targetFileName = Path.Combine(temp.Target, sourceFileName); result.Add(targetFileName, new FileDateInfo(sourceFileName, File.GetLastWriteTime(sourceFileName))); } } } return result; } #endregion Public Instance Methods #region Protected Instance Methods /// /// Extracts the key from the specified /// element. /// /// /// The from which to /// extract the key. /// /// /// The key for the specified /// . /// protected override string GetKeyForItem(FileOperation item) { return item.Target; } /// /// Inserts an element into the /// at the /// specified index. /// /// /// The zero-based index at which item should be inserted. /// /// /// The to insert. /// protected override void InsertItem(int index, FileOperation item) { // Assigns the string comparer to the item before calling // the base method. item.Comparer = _stringComparer; base.InsertItem(index, item); } /// /// Replaces the item at the specified index with the specified item. /// /// /// The zero-based index of the item to be replaced. /// /// /// The new item. /// protected override void SetItem(int index, FileOperation item) { // Assigns the string comparer to the item before calling // the base method. item.Comparer = _stringComparer; base.SetItem(index, item); } #endregion Protected Instance Methods } /// /// Used to identify the type of operation a given /// represent. /// protected enum OperationType { /// /// Indicates that the operation is from file to file. /// FileToFile = 0, /// /// Indicates that the operation is from file to directory. /// FileToDirectory = 1, /// /// Indicates that the operation is from directory to directory. /// DirectoryToDirectory = 2 } } } nant-0.92-rc1/src/NAnt.Core/Tasks/SleepTask.cs0000644000175000017500000001034511757302273020660 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian MacLean (ian@maclean.ms) using System; using System.Globalization; using System.Xml; using System.Threading; using NAnt.Core.Attributes; namespace NAnt.Core.Tasks { /// /// A task for sleeping a specified period of time, useful when a build or deployment process /// requires an interval between tasks. /// /// /// Sleep 1 hour, 2 minutes, 3 seconds and 4 milliseconds. /// /// /// ]]> /// /// /// /// Sleep 123 milliseconds. /// /// /// ]]> /// /// [TaskName("sleep")] public class SleepTask : Task { #region Private Instance Fields private int _hours = 0; private int _minutes = 0; private int _seconds = 0; private int _milliseconds = 0; #endregion Private Instance Fields #region Public Instance Properties /// /// Hours to add to the sleep time. /// [TaskAttribute("hours")] [Int32Validator(0, Int32.MaxValue)] public int Hours { get { return _hours; } set { _hours = value; } } /// /// Minutes to add to the sleep time. /// [TaskAttribute("minutes")] [Int32Validator(0, Int32.MaxValue)] public int Minutes { get { return _minutes; } set {_minutes = value; } } /// /// Seconds to add to the sleep time. /// [TaskAttribute("seconds")] [Int32Validator(0, Int32.MaxValue)] public int Seconds { get { return _seconds; } set { _seconds = value; } } /// /// Milliseconds to add to the sleep time. /// [TaskAttribute("milliseconds")] [Int32Validator(0, Int32.MaxValue)] public int Milliseconds { get { return _milliseconds; } set { _milliseconds = value; } } #endregion Public Instance Properties #region Override implementation of Task /// /// Verify parameters. /// protected override void Initialize() { if (GetSleepTime() < 0) { throw new BuildException("Negative sleep periods are not supported.", Location); } } protected override void ExecuteTask() { int sleepTime = GetSleepTime(); Log(Level.Info, "Sleeping for {0} milliseconds.", sleepTime); DoSleep(sleepTime); } #endregion Override implementation of Task #region Private Instance Methods /// /// Return time to sleep. /// private int GetSleepTime() { return ((((int) Hours * 60) + Minutes) * 60 + Seconds) * 1000 + Milliseconds; } /// /// Sleeps for the specified number of milliseconds. /// /// Number of milliseconds to sleep. private void DoSleep(int millis ) { Thread.Sleep(millis); } #endregion Private Instance Methods } } nant-0.92-rc1/src/NAnt.Core/Tasks/SetEnvTask.cs0000644000175000017500000002075511757302273021022 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian MacLean (imaclean@gmail.com) // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.ComponentModel; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Xml; using NAnt.Core.Attributes; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.Core.Tasks { /// /// Sets an environment variable or a whole collection of them. Use an empty /// attribute to clear a variable. /// /// /// /// Variables will be set for the current NAnt process and all child /// processes that NAnt spawns (compilers, shell tools, etc). If the /// intention is to only set a variable for a single child process, then /// using the and its nested /// element might be a better option. /// /// /// Expansion of inline environment variables is performed using the syntax /// of the current platform. So on Windows platforms using the string %PATH% /// in the attribute will result in the value of /// the PATH variable being expanded in place before the variable is set. /// /// /// /// Set the MONO_PATH environment variable on a *nix platform. /// /// /// ]]> /// /// /// /// Set a collection of environment variables. Note the nested variable used to set var3. /// /// /// /// /// /// /// ]]> /// /// /// /// Set environment variables using nested path elements. /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// ]]> /// /// [TaskName("setenv")] public class SetEnvTask : Task { #region Private Instance Fields private string _name; private string _value; private string _literalValue; private FileInfo _file; private DirectoryInfo _directory; private PathSet _path; private EnvironmentVariableCollection _environmentVariables = new EnvironmentVariableCollection(); #endregion Private Instance Fields #region Private Static Fields #endregion Private Static Fields #region Public Instance Properties /// /// The name of a single Environment variable to set /// [TaskAttribute("name")] public string EnvName { get { return _name; } set { _name = StringUtils.ConvertEmptyToNull(value); } } /// /// The literal value for the environment variable. /// [TaskAttribute("value")] public string LiteralValue { get { return _literalValue; } set { _value = value; _literalValue = value; } } /// /// The value for a file-based environment variable. NAnt will convert /// it to an absolute filename. /// [TaskAttribute("file")] public FileInfo File { get { return _file; } set { _value = value.ToString(); _file = value; } } /// /// The value for a directory-based environment variable. NAnt will /// convert it to an absolute path. /// [TaskAttribute("dir")] public DirectoryInfo Directory { get { return _directory; } set { _value = value.ToString(); _directory = value; } } /// /// The value for a PATH like environment variable. You can use /// : or ; as path separators and NAnt will convert it to /// the platform's local conventions. /// [TaskAttribute("path")] public PathSet Path { get { return _path; } set { _value = value.ToString(); _path = value; } } [BuildElementArray("variable", ElementType=typeof(EnvironmentVariable))] public EnvironmentVariableCollection EnvironmentVariables { get { return _environmentVariables; } set { _environmentVariables = value; } } #endregion Public Instance Properties #region Override implementation of Task /// /// Checks whether the task is initialized with valid attributes. /// protected override void Initialize() { if (EnvName == null && EnvironmentVariables.Count == 0) { throw new BuildException("Either the \"name\" attribute or at" + " least one nested element is required.", Location); } } /// /// Set the environment variables /// protected override void ExecuteTask() { if (EnvName != null) { // add single environment variable EnvironmentVariables.Add(new EnvironmentVariable(EnvName, _value)); } foreach (EnvironmentVariable env in EnvironmentVariables) { if (env.IfDefined && !env.UnlessDefined) { SetSingleEnvironmentVariable(env.VariableName, env.Value); } } } #endregion Override implementation of Task #region Private Instance Methods /// /// Do the actual work here. /// /// The name of the environment variable. /// The value of the environment variable. private void SetSingleEnvironmentVariable(string name, string value) { Log(Level.Verbose, "Setting environment variable \"{0}\" to \"{1}\".", name, value); // expand any env vars in value string expandedValue = null; if (value != null) { expandedValue = Environment.ExpandEnvironmentVariables(value); } try { Environment.SetEnvironmentVariable (name, expandedValue); } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Error setting environment variable \"{0}\" to \"{1}\".", name, value), Location, ex); } } #endregion Private Instance Methods } } nant-0.92-rc1/src/NAnt.Core/Tasks/EchoTask.cs0000644000175000017500000002172511757302273020472 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Gerry Shaw (gerry_shaw@yahoo.com) // Brian Deacon (bdeacon@vidya.com) using System; using System.IO; using System.Globalization; using System.Text; using System.Xml; using NAnt.Core.Attributes; using NAnt.Core.Util; namespace NAnt.Core.Tasks { /// /// Writes a message to the build log or a specified file. /// /// /// /// The message can be specified using the attribute /// or as inline content. If neither is included - or the message contains /// only whitespace - then an empty message will be emitted in the output. /// /// /// Macros in the message will be expanded. /// /// /// When writing to a file, the attribute is /// ignored. /// /// /// Since NAnt 0.86, a newline will no longer be implictly added when /// writing a message to a file. /// /// /// /// /// Writes a message with level to the build log. /// /// /// /// ]]> /// /// /// /// /// Writes a two-line message to the build log using inline content. /// /// /// First line /// Second line /// ]]> /// /// /// /// /// Writes a two-line message to the build log using the attribute. /// /// /// /// ]]> /// /// /// /// /// Writes a message with expanded macro to the build log. /// /// /// /// ]]> /// /// /// /// /// Functionally equivalent to the previous example. /// /// /// Base build directory = ${nant.project.basedir} /// ]]> /// /// /// /// /// Writes the previous message to a file in the project directory, /// overwriting the file if it exists. /// /// /// Base build directory = ${nant.project.basedir} /// ]]> /// /// [TaskName("echo")] public class EchoTask : Task { #region Private Instance Fields private string _message; private string _contents; private FileInfo _file; private bool _append; private Level _messageLevel = Level.Info; private Encoding _encoding; #endregion Private Instance Fields #region Public Instance Properties /// /// The encoding to use when writing message to a file. The default is /// UTF-8 encoding without a Byte Order Mark (BOM). /// [TaskAttribute("encoding")] public Encoding Encoding { get { if (_encoding == null) return new UTF8Encoding (); return _encoding; } set { _encoding = value; } } /// /// The message to output. /// [TaskAttribute("message")] public string Message { get { return _message; } set { if (value != null && value.Trim ().Length > 0) { if (Contents != null) { throw new ValidationException("Inline content and the message attribute are mutually exclusive in the task.", Location); } else { _message = value; } } else { _message = null; } } } /// /// Gets or sets the inline content that should be output. /// /// /// The inline content that should be output. /// public string Contents { get { return _contents; } set { if (value != null && value.Trim ().Length > 0) { if (Message != null) { throw new ValidationException("Inline content and the message attribute are mutually exclusive in the task.", Location); } else { _contents = value; } } else { _contents = null; } } } /// /// The file to write the message to. /// [TaskAttribute("file")] public FileInfo File { get { return _file; } set { _file = value; } } /// /// Determines whether the should append to the /// file, or overwrite it. By default, the file will be overwritten. /// /// /// if output should be appended to the file; /// otherwise, . The default is /// . /// [TaskAttribute("append")] public bool Append { get { return _append; } set { _append = value; } } /// /// The logging level with which the message should be output. The default /// is . /// [TaskAttribute("level")] public Level MessageLevel { get { return _messageLevel; } set { if (!Enum.IsDefined(typeof(Level), value)) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "An invalid level {0} was specified.", value)); } else { this._messageLevel = value; } } } #endregion Public Instance Properties #region Override implementation of Task /// /// Outputs the message to the build log or the specified file. /// protected override void ExecuteTask() { if (File != null) { // output to file try { // ensure the output directory exists if (!File.Directory.Exists) { File.Directory.Create(); File.Directory.Refresh(); } // write the message to the file using (StreamWriter writer = new StreamWriter(File.FullName, Append, Encoding)) { if (!String.IsNullOrEmpty(Message)) { writer.Write(Message); } else if (!String.IsNullOrEmpty(Contents)) { writer.Write(Contents); } } } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1116"), File.FullName), Location, ex); } } else { // output to build log if (Message != null) { Log(MessageLevel, Message); } else if (Contents != null) { Log(MessageLevel, Contents); } else { Log(MessageLevel, string.Empty); } } } protected override void Initialize() { if (XmlNode.ChildNodes.Count == 0) return; Contents = Project.ExpandProperties(XmlNode.InnerText, Location); } #endregion Override implementation of Task } } nant-0.92-rc1/src/NAnt.Core/Tasks/DeleteTask.cs0000644000175000017500000002672011757302273021016 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) using System; using System.IO; using System.Globalization; using NAnt.Core.Attributes; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.Core.Tasks { /// /// Deletes a file, fileset or directory. /// /// /// /// Deletes either a single file, all files in a specified directory and /// its sub-directories, or a set of files specified by one or more filesets. /// /// /// If the or attribute is /// set then the fileset contents will be ignored. To delete the files /// in the fileset ommit the and /// attributes in the <delete> element. /// /// /// If the specified file or directory does not exist, no error is /// reported. /// /// /// Read-only files cannot be deleted. Use the /// first to remove the read-only attribute. /// /// /// /// Delete a single file. /// /// /// ]]> /// /// /// /// /// Delete a directory and the contents within. If the directory does not /// exist, no error is reported. /// /// /// /// ]]> /// /// /// /// /// Delete a set of files. /// /// /// /// /// /// /// /// /// ]]> /// /// [TaskName("delete")] public class DeleteTask : Task { #region Private Instance Fields private FileInfo _file; private DirectoryInfo _dir; private FileSet _fileset = new FileSet(); private bool _includeEmptyDirs = true; #endregion Private Instance Fields #region Public Instance Properties /// /// The file to delete. /// [TaskAttribute("file")] public FileInfo File { get { return _file; } set { _file = value; } } /// /// The directory to delete. /// [TaskAttribute("dir")] public DirectoryInfo Directory { get { return _dir; } set { _dir = value; } } /// /// Remove any empty directories included in the . /// The default is . /// [TaskAttribute("includeemptydirs")] [BooleanValidator()] public bool IncludeEmptyDirs { get { return _includeEmptyDirs; } set { _includeEmptyDirs = value; } } /// /// All the files in the file set will be deleted. /// [BuildElement("fileset")] public FileSet DeleteFileSet { get { return _fileset; } set { _fileset = value; } } #endregion Public Instance Properties #region Override implementation of Task /// /// Controls whether to show the name of each deleted file or directory. /// The default is . /// [TaskAttribute("verbose")] [BooleanValidator()] public override bool Verbose { get { return base.Verbose; } set { base.Verbose = value; } } /// /// Ensures the supplied attributes are valid. /// protected override void Initialize() { // limit task to deleting either a file, directory if (File != null && Directory != null) { throw new BuildException("Cannot specify both 'file' and 'dir'" + " attribute in the same task.", Location); } // limit task to deleting either a file/directory or fileset if ((File != null || Directory != null) && DeleteFileSet.Includes.Count != 0) { throw new BuildException("Cannot specify both 'file' or 'dir'" + " attribute and use in the same task.", Location); } } protected override void ExecuteTask() { // ensure base directory is set, even if fileset was not initialized // from XML if (DeleteFileSet.BaseDirectory == null) { DeleteFileSet.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } if (File != null) { // delete a single file // delete the file in verbose mode DeleteFile(File.FullName, true); } else if (Directory != null) { // delete the directory // explicitly check if directory exist here (while the same // check is performed in RecursiveDeleteDirectory), to avoid // output of Info message below if (!Directory.Exists) { return; } // log message here if we're not in verbose mode, otherwise the // RecursiveDeleteDirectory method will output verbose message // for each directory that is removed if (!Verbose) { Log(Level.Info, "Deleting directory '{0}'.", Directory.FullName); } RecursiveDeleteDirectory(Directory.FullName); } else { // delete files or directories in fileset if (DeleteFileSet.FileNames.Count > 0) { Log(Level.Info, "Deleting {0} files.", DeleteFileSet.FileNames.Count); foreach (string path in DeleteFileSet.FileNames) { DeleteFile(path, Verbose); } } if (DeleteFileSet.DirectoryNames.Count > 0 && IncludeEmptyDirs) { int dirCount = 0; foreach (string path in DeleteFileSet.DirectoryNames) { string[] entries = System.IO.Directory.GetFileSystemEntries(path); if (entries == null || entries.Length == 0) { try { DeleteDirectory(path); dirCount++; } catch (Exception ex) { string msg = string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1113"), path); if (FailOnError) { throw new BuildException(msg, Location, ex); } Log(Level.Warning, msg + " " + ex.Message); } } } if (dirCount > 0) { Log(Level.Info, "Deleted {0} directories.", dirCount); } } } } #endregion Override implementation of Task #region Private Instance Methods private void RecursiveDeleteDirectory(string path) { try { // skip the directory if it doesn't exist if (!System.IO.Directory.Exists(path)) { return; } // first, recursively delete all directories in the directory string[] dirs = System.IO.Directory.GetDirectories(path); foreach (string dir in dirs) { RecursiveDeleteDirectory(dir); } // next, delete all files in the directory string[] files = System.IO.Directory.GetFiles(path); foreach (string file in files) { try { System.IO.File.SetAttributes(file, FileAttributes.Normal); Log(Level.Verbose, "Deleting file '{0}'.", file); System.IO.File.Delete(file); } catch (Exception ex) { string msg = string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1114"), file); if (FailOnError) { throw new BuildException(msg, Location, ex); } Log(Level.Verbose, msg + " " + ex.Message); } } DeleteDirectory(path); } catch (BuildException ex) { throw ex; } catch (Exception ex) { string msg = string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1113"), path); if (FailOnError) { throw new BuildException(msg, Location, ex); } Log(Level.Warning, msg + " " + ex.Message); } } private void DeleteFile(string path, bool verbose) { try { FileInfo deleteInfo = new FileInfo(path); if (!deleteInfo.Exists) { return; } if (verbose) { Log(Level.Info, "Deleting file {0}.", path); } if (deleteInfo.Attributes != FileAttributes.Normal) { System.IO.File.SetAttributes(deleteInfo.FullName, FileAttributes.Normal); } System.IO.File.Delete(path); } catch (Exception ex) { string msg = string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1114"), path); if (FailOnError) { throw new BuildException(msg, Location, ex); } Log(Level.Warning, msg + " " + ex.Message); } } private void DeleteDirectory(string path) { // ensure path is not read-only System.IO.File.SetAttributes(path, FileAttributes.Normal); // write output to build log Log(Level.Verbose, "Deleting directory '{0}'.", path); // finally, delete the directory System.IO.Directory.Delete(path); } #endregion Private Instance Methods } } nant-0.92-rc1/src/NAnt.Core/Tasks/LoopTask.cs0000644000175000017500000004130711757302273020523 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2002-2003 Scott Hernandez // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Scott Hernandez (ScottHernandez@hotmail.com) using System; using System.Globalization; using System.IO; using NAnt.Core.Attributes; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.Core.Tasks { /// /// Loops over a set of items. /// /// /// /// Can loop over files in directory, lines in a file, etc. /// /// /// The property value is stored before the loop is done, and restored /// when the loop is finished. /// /// /// The property is returned to its normal value once it is used. Read-only /// parameters cannot be overridden in this loop. /// /// /// /// Loops over the files in c:\. /// /// /// /// /// ]]> /// /// /// /// Loops over all files in the project directory. /// /// /// /// /// /// /// /// /// /// /// /// ]]> /// /// /// /// Loops over the folders in c:\. /// /// /// /// /// ]]> /// /// /// /// Loops over all folders in the project directory. /// /// /// /// /// /// /// /// /// /// /// /// ]]> /// /// /// /// Loops over a list. /// /// /// /// /// ]]> /// /// /// /// /// Loops over lines in the file properties.csv, where each line /// is of the format name,value. /// /// /// /// /// /// ]]> /// /// [TaskName("foreach")] public class LoopTask : TaskContainer { public enum LoopItem { File = 1, Folder = 2, String = 3, Line = 4 } public enum LoopTrim { /// /// Do not remove any white space characters. /// None = 0, /// /// Remove all white space characters from the end of the current /// item. /// End = 1, /// /// Remove all white space characters from the beginning of the /// current item. /// Start = 2, /// /// Remove all white space characters from the beginning and end of /// the current item. /// Both = 3 } #region Private Instance Fields private string _prop; private string[] _props; private LoopItem _loopItem; private LoopTrim _loopTrim = LoopTrim.None; private string _inAttribute; private string _delim; private InElement _inElement; private TaskContainer _doStuff; #endregion Private Instance Fields #region Public Instance Properties /// /// The NAnt property name(s) that should be used for the current /// iterated item. /// /// /// If specifying multiple properties, separate them with a comma. /// [TaskAttribute("property", Required=true)] [StringValidator(AllowEmpty=false)] public string Property { get { return _prop; } set { _prop = value; _props = _prop.Split(','); foreach (string prop in _props) { if (Properties.IsReadOnlyProperty(prop)) { throw new BuildException("Property is readonly! :" + prop, Location); } } } } /// /// The type of iteration that should be done. /// [TaskAttribute("item", Required=true)] public LoopItem ItemType { get { return _loopItem; } set { _loopItem = value; } } /// /// The type of whitespace trimming that should be done. The default /// is . /// [TaskAttribute("trim")] public LoopTrim TrimType { get { return _loopTrim;} set { _loopTrim = value; } } /// /// The source of the iteration. /// [TaskAttribute("in", Required=false)] public string Source { get { return _inAttribute;} set { _inAttribute = StringUtils.ConvertEmptyToNull(value); } } /// /// The deliminator char. /// [TaskAttribute("delim")] public string Delimiter { get { return _delim; } set { if (value == null || value.Length == 0) { _delim = null; } else { _delim = value; } } } /// /// Stuff to operate in. Just like the /// attribute, but supports more complicated things like a /// and such. /// /// Please remove the attribute if you /// are using this element. /// /// [BuildElement("in")] public InElement InElement { get { return _inElement; } set { _inElement = value; } } /// /// Tasks to execute for each matching item. /// [BuildElement("do")] public TaskContainer StuffToDo { get { return _doStuff; } set { _doStuff = value; } } #endregion Public Instance Properties #region Override implementation of TaskContainer protected override void ExecuteTask() { string[] oldPropVals = new string[_props.Length]; // Save all of the old property values for (int nIndex = 0; nIndex < oldPropVals.Length; nIndex++) { oldPropVals[nIndex] = Properties[_props[nIndex]]; } try { switch (ItemType) { case LoopItem.File: if (String.IsNullOrEmpty(Source) && InElement == null) { throw new BuildException("Invalid foreach", Location, new ArgumentException("Nothing to work with...!", "in")); } if (!String.IsNullOrEmpty(Source)) { // resolve to full path Source = Project.GetFullPath(Source); // ensure directory exists if (!Directory.Exists(Source)) { throw new BuildException(string.Format( CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1134"), Source), Location); } if (_props.Length != 1) { throw new BuildException(@"Only one property is valid for item=""File""", Location); } DirectoryInfo dirInfo = new DirectoryInfo(Source); FileInfo[] files = dirInfo.GetFiles(); foreach (FileInfo file in files) { DoWork(file.FullName); } } else { if (StuffToDo == null) { throw new BuildException("Must use with .", Location); } foreach (string file in InElement.Items.FileNames) { DoWork(file); } } break; case LoopItem.Folder: if (String.IsNullOrEmpty(Source) && InElement == null) { throw new BuildException("Invalid foreach", Location, new ArgumentException("Nothing to work with...!", "in")); } if (_props.Length != 1) { throw new BuildException(@"Only one property is valid for item=""Folder""", Location); } if (!String.IsNullOrEmpty(Source)) { // resolve to full path Source = Project.GetFullPath(Source); // ensure directory exists if (!Directory.Exists(Source)) { throw new BuildException(string.Format( CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1134"), Source), Location); } DirectoryInfo dirInfo = new DirectoryInfo(Source); DirectoryInfo[] dirs = dirInfo.GetDirectories(); foreach (DirectoryInfo dir in dirs) { DoWork(dir.FullName); } } else { if (StuffToDo == null) { throw new BuildException("Must use with .", Location); } foreach (string dir in InElement.Items.DirectoryNames) { DoWork(dir); } } break; case LoopItem.Line: if (String.IsNullOrEmpty(Source) && InElement == null) { throw new BuildException("Invalid foreach", Location, new ArgumentException("Nothing to work with...!", "in")); } if (_props.Length > 1 && Delimiter == null) { throw new BuildException("Delimiter(s) must be specified if multiple properties are specified", Location); } if (!String.IsNullOrEmpty(Source)) { // resolve to full path Source = Project.GetFullPath(Source); // ensure file exists if (!File.Exists(Source)) { throw new BuildException(string.Format( CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1133"), Source), Location); } DoWorkOnFileLines(Source); } else { if (StuffToDo == null) { throw new BuildException("Must use with .", Location); } foreach (string file in InElement.Items.FileNames) { DoWorkOnFileLines(file); } } break; case LoopItem.String: if (String.IsNullOrEmpty(Source)) { return; } if (_props.Length > 1) { throw new BuildException(@"Only one property may be specified for item=""String""", Location); } if (Delimiter == null) { throw new BuildException(@"Delimiter must be specified for item=""String""", Location); } string[] items = Source.Split(Delimiter.ToCharArray()); foreach (string s in items) { DoWork(s); } break; } } finally { // Restore all of the old property values for (int nIndex = 0; nIndex < oldPropVals.Length; nIndex++) { Properties[_props[nIndex]] = oldPropVals[nIndex]; } } } protected override void ExecuteChildTasks() { if (StuffToDo == null) { base.ExecuteChildTasks(); } else { StuffToDo.Execute(); } } #endregion Override implementation of TaskContainer #region Protected Instance Methods protected virtual void DoWork(params string[] propVals) { for (int nIndex = 0; nIndex < propVals.Length; nIndex++) { string propValue = propVals[nIndex]; if (nIndex >= _props.Length) { throw new BuildException("Too many items on line", Location); } switch (TrimType) { case LoopTrim.Both: propValue = propValue.Trim(); break; case LoopTrim.Start: propValue = propValue.TrimStart(); break; case LoopTrim.End: propValue = propValue.TrimEnd(); break; } Properties[_props[nIndex]] = propValue; } base.ExecuteTask(); } #endregion Protected Instance Methods #region Private Instance Methods private void DoWorkOnFileLines(string filename) { using (StreamReader sr = File.OpenText(filename)) { while (true) { string line = sr.ReadLine(); if (line == null) { break; } if (Delimiter == null) { DoWork(line); } else { DoWork(line.Split(Delimiter.ToCharArray())); } } } } #endregion Private Instance Methods } public class InElement : Element { #region Private Instance Fields private FileSet _items; #endregion Private Instance Fields #region Public Instance Properties [BuildElement("items")] public FileSet Items { get { return _items;} set { _items = value; } } #endregion Public Instance Properties } } nant-0.92-rc1/src/NAnt.Core/Tasks/SysInfo.cs0000644000175000017500000002266411757302273020366 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) using System; using System.Collections; using System.Diagnostics; using System.Globalization; using System.IO; using NAnt.Core.Attributes; using NAnt.Core.Functions; namespace NAnt.Core.Tasks { /// /// Sets properties with system information. /// /// /// Sets a number of properties with information about the system environment. The intent of this task is for nightly build logs to have a record of system information so that the build was performed on. /// /// /// Property /// Value /// /// /// <>.clr.version /// Common Language Runtime version number. /// /// /// <>.env.* /// Environment variables (e.g., <>.env.PATH). /// /// /// <>.os.platform /// Operating system platform ID. /// /// /// <>.os.version /// Operating system version. /// /// /// <>.os /// Operating system version string. /// /// /// <>.os.folder.applicationdata /// The directory that serves as a common repository for application-specific data for the current roaming user. /// /// /// <>.os.folder.commonapplicationdata /// The directory that serves as a common repository for application-specific data that is used by all users. /// /// /// <>.os.folder.commonprogramfiles /// The directory for components that are shared across applications. /// /// /// <>.os.folder.desktopdirectory /// The directory used to physically store file objects on the desktop. Do not confuse this directory with the desktop folder itself, which is a virtual folder. /// /// /// <>.os.folder.programfiles /// The Program Files directory. /// /// /// <>.os.folder.system /// The System directory. /// /// /// <>.os.folder.temp /// The temporary directory. /// /// /// /// When the name of an environment variable is not a valid property name, /// the task will fail. In that case, set to /// to allow that environment variable to be /// skipped. /// /// /// we advise you to use the following functions instead: /// /// /// /// Function /// Description /// /// /// /// Gets a object that identifies this operating system. /// /// /// /// Gets the path to a system special folder. /// /// /// /// Returns the value of a environment variable. /// /// /// /// Gets the path to the temporary directory. /// /// /// /// Gets the Common Language Runtime version. /// /// /// /// /// Register the properties with the default property prefix. /// /// /// ]]> /// /// /// /// Register the properties without a prefix. /// /// /// ]]> /// /// /// /// Register properties and display a summary. /// /// /// ]]> /// /// [TaskName("sysinfo")] public class SysInfoTask : Task { #region Private Instance Fields private string _prefix = "sys."; #endregion Private Instance Fields #region Public Instance Properties /// /// The string to prefix the property names with. The default is "sys.". /// [TaskAttribute("prefix", Required=false)] public string Prefix { get { return _prefix; } set { _prefix = value; } } #endregion Public Instance Properties #region Override implementation of Task protected override void ExecuteTask() { Log(Level.Info, "Setting system information properties under " + Prefix + "*"); // set properties Properties[Prefix + "clr.version"] = Environment.Version.ToString(); Properties[Prefix + "os.platform"] = Environment.OSVersion.Platform.ToString(CultureInfo.InvariantCulture); Properties[Prefix + "os.version"] = Environment.OSVersion.Version.ToString(); Properties[Prefix + "os.folder.applicationdata"] = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); Properties[Prefix + "os.folder.commonapplicationData"] = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); Properties[Prefix + "os.folder.commonprogramFiles"] = Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles); Properties[Prefix + "os.folder.desktopdirectory"] = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); Properties[Prefix + "os.folder.programfiles"] = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); Properties[Prefix + "os.folder.system"] = Environment.GetFolderPath(Environment.SpecialFolder.System); Properties[Prefix + "os.folder.temp"] = Path.GetTempPath(); Properties[Prefix + "os"] = Environment.OSVersion.ToString(); // set environment variables IDictionary variables = Environment.GetEnvironmentVariables(); foreach (string name in variables.Keys) { try { Properties[Prefix + "env." + name] = (string) variables[name]; } catch (Exception ex) { if (!FailOnError) { Log(Level.Warning, "Property could not be created for" + " environment variable '{0}' : {1}", name, ex.Message); } else { throw; } } } // display the properties if (Verbose) { foreach (DictionaryEntry entry in Properties) { string name = (string) entry.Key; if (name.StartsWith(Prefix)) { Log(Level.Info, name + " = " + entry.Value.ToString()); } } } } #endregion Override implementation of Task } } nant-0.92-rc1/src/NAnt.Core/Tasks/ChooseTask.cs0000644000175000017500000001737611757302273021043 0ustar jtaylorjtaylor// // NAntContrib // Copyright (C) 2001-2005 Gerry Shaw // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Globalization; using System.Xml; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Util; namespace NAnt.Core.Tasks { /// /// /// Executes an alternate set of task or type definition depending on /// conditions that are individually set on each group. /// /// /// /// /// The selects one among a number of possible /// alternatives. It consists of a sequence of <when> elements /// followed by an optional <otherwise> element. /// /// /// Each <when> element has a single attribute, test, which /// specifies an expression. The content of the <when> and /// <otherwise> elements is a set of nested tasks. /// /// /// The content of the first, and only the first, <when> /// element whose test is is executed. If no /// <when> element is , the /// content of the <otherwise> element is executed. /// If no <when> element is , and no /// <otherwise> element is present, nothing is done. /// /// /// /// /// Execute alternate set of tasks depending on the configuration being /// built. /// /// /// /// /// /// ... /// /// /// /// ... /// /// /// Build configuration '${build.config}' is not supported! /// /// /// ]]> /// /// /// /// /// Define a sources patternset holding an alternate set of patterns /// depending on the configuration being built. /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// Build configuration '${build.config}' is not supported! /// /// /// ]]> /// /// [TaskName("choose")] public class ChooseTask : Task { #region Private Instance Fields private List _elementContainers = new List(); #endregion Private Instance Fields #region Private Instance Properties /// /// Gets a value indicating whether a fallback element is defined. /// /// /// if a fallback element is defined; otherwise, /// . /// private bool IsFallbackDefined { get { foreach (ElementContainer container in _elementContainers) { // only allow one fallback container, so check if a otherwise // container was already added if (!(container is When)) { return true; } } return false; } } #endregion Private Instance Properties #region Override implementation of Task protected override void ExecuteTask() { foreach (ElementContainer container in _elementContainers) { When when = container as When; // execute the nested tasks of the first matching when element if (when != null) { if (when.Test) { when.Execute(); break; } } else { container.Execute(); } } } #endregion Override implementation of Task #region Public Instance Methods /// /// One or more alternative sets of tasks to execute. /// /// The set of tasks to add. [BuildElement("when", Required=true)] public void AddCondition(When when) { if (IsFallbackDefined) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "The element must be defined as the last nested" + " element in the <{0} ... /> task.", Name), Location); } _elementContainers.Add(when); } /// /// The set of tasks to execute if none of the /// elements are . /// [BuildElement("otherwise")] public void AddFallback(ElementContainer fallback) { if (IsFallbackDefined) { throw new BuildException("The element may only" + " be defined once.", Location); } _elementContainers.Add(fallback); } #endregion Public Instance Methods /// /// Groups a set of tasks to execute when a condition is met. /// public class When : ElementContainer { #region Private Instance Fields private bool _test = true; #endregion Private Instance Fields #region Public Instance Properties /// /// Used to test arbitrary boolean expression. /// [TaskAttribute("test", Required=true)] [BooleanValidator()] public bool Test { get { return _test; } set { _test = value; } } #endregion Public Instance Properties #region Override implementation of NestedTaskContainer public override void Execute() { if (!Test) { return; } base.Execute(); } #endregion Override implementation of NestedTaskContainer } } } nant-0.92-rc1/src/NAnt.Core/Tasks/NAntTask.cs0000644000175000017500000002331611757302273020452 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Scott Hernandez (ScottHernandez@hotmail.com) using System; using System.IO; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.Xml; using NAnt.Core.Attributes; using NAnt.Core.Util; using NAnt.Core.Types; namespace NAnt.Core.Tasks { /// /// Runs NAnt on a supplied build file, or a set of build files. /// /// /// /// By default, all the properties of the current project will be available /// in the new project. Alternatively, you can set /// to to not copy any properties to the new /// project. /// /// /// You can also set properties in the new project from the old project by /// using nested property tags. These properties are always passed to the /// new project regardless of the setting of . /// This allows you to parameterize your subprojects. /// /// /// References to data types can also be passed to the new project, but by /// default they are not. If you set the to /// , all references will be copied. /// /// /// /// /// Build a project located in a different directory if the debug /// property is not . /// /// /// /// ]]> /// /// /// /// /// Build a project while adding a set of properties to that project. /// /// /// /// /// /// /// /// /// /// ]]> /// /// /// /// /// Build all projects named default.build located anywhere under /// the project base directory. /// /// /// /// /// /// /// /// /// /// ]]> /// /// [TaskName("nant")] public class NAntTask : Task { #region Private Instance Fields private FileInfo _buildFile; private FileSet _buildFiles = new FileSet(); private string _target; private bool _inheritAll = true; private bool _inheritRefs; private ArrayList _overrideProperties = new ArrayList(); #endregion Private Instance Fields #region Public Instance Properties /// /// The build file to build. /// [TaskAttribute("buildfile")] public FileInfo BuildFile { get { return _buildFile; } set { _buildFile = value; } } /// /// The target to execute. To specify more than one target seperate /// targets with a space. Targets are executed in order if possible. /// The default is to use target specified in the project's default /// attribute. /// [TaskAttribute("target")] public string DefaultTarget { get { return _target; } set { _target = StringUtils.ConvertEmptyToNull(value); } } /// /// Used to specify a set of build files to process. /// [BuildElement("buildfiles")] public virtual FileSet BuildFiles { get { return _buildFiles; } set { _buildFiles = value; } } /// /// Specifies whether current property values should be inherited by /// the executed project. The default is . /// [TaskAttribute("inheritall")] [BooleanValidator()] public bool InheritAll { get { return _inheritAll; } set { _inheritAll = value; } } /// /// Specifies whether all references will be copied to the new project. /// The default is . /// [TaskAttribute("inheritrefs")] [BooleanValidator()] public bool InheritRefs { get { return _inheritRefs; } set { _inheritRefs = value; } } /// /// Specifies a collection of properties that should be created in the /// executed project. Note, existing properties with identical names /// that are not read-only will be overwritten. /// [BuildElementCollection("properties", "property", ElementType=typeof(PropertyTask))] public ArrayList OverrideProperties { get { return _overrideProperties; } } #endregion Public Instance Properties #region Override implementation of Task /// /// Validates the element. /// protected override void Initialize() { if (BuildFile != null && BuildFiles != null && BuildFiles.Includes.Count > 0) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1141")), Location); } } protected override void ExecuteTask() { // run the build file specified in an attribute if (BuildFile != null) { RunBuild(BuildFile); } else { if (BuildFiles.FileNames.Count == 0) { Log(Level.Warning, "No matching build files found to run."); return; } // run all build files specified in the fileset foreach (string buildFile in BuildFiles.FileNames) { RunBuild(new FileInfo(buildFile)); } } } private void RunBuild(FileInfo buildFile) { Log(Level.Info, "{0} {1}", buildFile.FullName, DefaultTarget); // create new project with same threshold as current project and // increased indentation level, and initialize it using the same // configuration node Project project = new Project(buildFile.FullName, Project); // have the new project inherit properties from the current project if (InheritAll) { StringCollection excludes = new StringCollection(); excludes.Add(Project.NAntPropertyFileName); excludes.Add(Project.NAntPropertyLocation); excludes.Add(Project.NAntPropertyOnSuccess); excludes.Add(Project.NAntPropertyOnFailure); excludes.Add(Project.NAntPropertyProjectBaseDir); excludes.Add(Project.NAntPropertyProjectBuildFile); excludes.Add(Project.NAntPropertyProjectDefault); excludes.Add(Project.NAntPropertyProjectName); excludes.Add(Project.NAntPropertyVersion); project.Properties.Inherit(Properties, excludes); } // add/overwrite properties foreach (PropertyTask property in OverrideProperties) { // expand properties in context of current project for non-dynamic // properties if (!property.Dynamic) { property.Value = Project.ExpandProperties(property.Value, Location); } property.Project = project; property.Execute(); } if (InheritRefs) { // pass datatypes thru to the child project project.DataTypeReferences.Inherit(Project.DataTypeReferences); } // handle multiple targets if (DefaultTarget != null) { foreach (string t in DefaultTarget.Split(' ')) { string target = t.Trim(); if (target.Length > 0) { project.BuildTargets.Add(target); } } } // run the given build if (!project.Run()) { throw new BuildException("Nested build failed. Refer to build log for exact reason."); } } #endregion Override implementation of Task } } nant-0.92-rc1/src/NAnt.Core/Tasks/ExternalProgramBase.cs0000644000175000017500000006461211757302273022700 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Scott Hernandez (ScottHernandez@hotmail.com) // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; using System.Collections.Specialized; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; using System.Threading; using System.Xml; using NAnt.Core.Attributes; using NAnt.Core.Configuration; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.Core.Tasks { /// /// Provides the abstract base class for tasks that execute external applications. /// /// /// /// When a is applied to the /// deriving class and does not return an /// absolute path, then the program to execute will first be searched for /// in the location specified by . /// /// /// If the program does not exist in that location, then the list of tool /// paths of the current target framework will be scanned in the order in /// which they are defined in the NAnt configuration file. /// /// [Serializable()] public abstract class ExternalProgramBase : Task { #region Private Instance Fields private StreamReader _stdError; private StreamReader _stdOut; private ArgumentCollection _arguments = new ArgumentCollection(); private ManagedExecution _managed = ManagedExecution.Default; private string _exeName; private int _timeout = Int32.MaxValue; private TextWriter _outputWriter; private TextWriter _errorWriter; private int _exitCode = UnknownExitCode; private bool _spawn; private int _processId = 0; private bool _useRuntimeEngine; #endregion Private Instance Fields #region Public Static Fields /// /// Defines the exit code that will be returned by /// if the process could not be started, or did not exit (in time). /// public const int UnknownExitCode = -1000; #endregion Public Static Fields #region Private Static Fields private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); /// /// Will be used to ensure thread-safe operations. /// private static object _lockObject = new object(); #endregion Private Static Fields #region Public Instance Properties /// /// The name of the executable that should be used to launch the /// external program. /// /// /// The name of the executable that should be used to launch the external /// program, or if no name is specified. /// /// /// If available, the configured value in the NAnt configuration /// file will be used if no name is specified. /// [FrameworkConfigurable("exename")] public virtual string ExeName { get { return (_exeName != null) ? _exeName : Name; } set { _exeName = value; } } /// /// Gets the filename of the external program to start. /// /// /// The filename of the external program. /// /// /// Override in derived classes to explicitly set the location of the /// external tool. /// public virtual string ProgramFileName { get { return DetermineFilePath(); } } /// /// Gets the command-line arguments for the external program. /// /// /// The command-line arguments for the external program. /// public abstract string ProgramArguments { get; } /// /// Gets the file to which the standard output should be redirected. /// /// /// The file to which the standard output should be redirected, or /// if the standard output should not be /// redirected. /// /// /// The default implementation will never allow the standard output /// to be redirected to a file. Deriving classes should override this /// property to change this behaviour. /// public virtual FileInfo Output { get { return null; } set {} //so that it can be overriden. } /// /// Gets a value indicating whether output will be appended to the /// . /// /// /// if output should be appended to the ; /// otherwise, . /// public virtual bool OutputAppend { get { return false; } set {} //so that it can be overriden. } /// /// Gets the working directory for the application. /// /// /// The working directory for the application. /// public virtual DirectoryInfo BaseDirectory { get { return new DirectoryInfo(Project.BaseDirectory); } set {} // so that it can be overriden. } /// /// The maximum amount of time the application is allowed to execute, /// expressed in milliseconds. Defaults to no time-out. /// [TaskAttribute("timeout")] [Int32Validator()] public int TimeOut { get { return _timeout; } set { _timeout = value; } } /// /// The command-line arguments for the external program. /// [BuildElementArray("arg")] public virtual ArgumentCollection Arguments { get { return _arguments; } } /// /// Specifies whether the external program is a managed application /// which should be executed using a runtime engine, if configured. /// The default is . /// /// /// if the external program should be executed /// using a runtime engine; otherwise, . /// /// /// /// The value of is only used from /// , and then only if its value is set to /// . In which case /// returns /// if is . /// /// /// In all other cases, the value of /// is ignored. /// /// [FrameworkConfigurable("useruntimeengine")] [Obsolete("Use the managed attribute and Managed property instead.", false)] public virtual bool UseRuntimeEngine { get { return _useRuntimeEngine; } set { _useRuntimeEngine = value; } } /// /// Specifies whether the external program should be treated as a managed /// application, possibly forcing it to be executed under the currently /// targeted version of the CLR. /// /// /// A indicating how the program should /// be treated. /// /// /// /// If is set to , /// which is the default value, and is /// then /// is returned. /// /// /// When the changing to , /// then is set to ; /// otherwise, it is changed to . /// /// [FrameworkConfigurable("managed")] public virtual ManagedExecution Managed { get { // deal with cases where UseRuntimeEngine is overridden to // return true by default if (UseRuntimeEngine && _managed == ManagedExecution.Default) { return ManagedExecution.Auto; } return _managed; } set { _managed = value; UseRuntimeEngine = (value != ManagedExecution.Default); } } /// /// Gets or sets the to which standard output /// messages of the external program will be written. /// /// /// The to which standard output messages of /// the external program will be written. /// /// /// By default, standard output messages wil be written to the build log /// with level . /// public virtual TextWriter OutputWriter { get { if (_outputWriter == null) { _outputWriter = new LogWriter(this, Level.Info, CultureInfo.InvariantCulture); } return _outputWriter; } set { _outputWriter = value; } } /// /// Gets or sets the to which error output /// of the external program will be written. /// /// /// The to which error output of the external /// program will be written. /// /// /// By default, error output wil be written to the build log with level /// . /// public virtual TextWriter ErrorWriter { get { if (_errorWriter == null) { _errorWriter = new LogWriter(this, Level.Warning, CultureInfo.InvariantCulture); } return _errorWriter; } set { _errorWriter = value; } } /// /// Gets the value that the process specified when it terminated. /// /// /// The code that the associated process specified when it terminated, /// or -1000 if the process could not be started or did not /// exit (in time). /// public int ExitCode { get { return _exitCode; } } /// /// Gets the unique identifier for the spawned application. /// protected int ProcessId { get { if (!Spawn) { throw new InvalidOperationException ("The unique identifier" + " only applies to spawned applications."); } if (_processId == 0) { throw new InvalidOperationException ("The application was not started."); } return _processId; } } /// /// Gets or sets a value indicating whether the application should be /// spawned. If you spawn an application, its output will not be logged /// by NAnt. The default is . /// public virtual bool Spawn { get { return _spawn; } set { _spawn = value; } } #endregion Public Instance Properties #region Override implementation of Task /// /// Starts the external process and captures its output. /// /// /// The external process did not finish within the configured timeout. /// -or- /// The exit code of the external process indicates a failure. /// protected override void ExecuteTask() { Thread outputThread = null; Thread errorThread = null; try { // Start the external process Process process = StartProcess(); if (Spawn) { _processId = process.Id; return; } outputThread = new Thread(new ThreadStart(StreamReaderThread_Output)); errorThread = new Thread(new ThreadStart(StreamReaderThread_Error)); _stdOut = process.StandardOutput; _stdError = process.StandardError; outputThread.Start(); errorThread.Start(); // Wait for the process to terminate process.WaitForExit(TimeOut); // Wait for the threads to terminate outputThread.Join(2000); errorThread.Join(2000); if (!process.HasExited) { try { process.Kill(); } catch { // ignore possible exceptions that are thrown when the // process is terminated } throw new BuildException( String.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1118"), ProgramFileName, TimeOut), Location); } _exitCode = process.ExitCode; if (process.ExitCode != 0) { throw new BuildException( String.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1119"), ProgramFileName, process.ExitCode), Location); } } catch (BuildException e) { if (FailOnError) { throw; } else { logger.Error("Execution Error", e); Log(Level.Error, e.Message); } } catch (Exception e) { logger.Error("Execution Error", e); throw new BuildException( string.Format(CultureInfo.InvariantCulture, "{0}: {1} had errors. Please see log4net log.", GetType().ToString(), ProgramFileName), Location, e); } finally { // ensure outputThread is always aborted if (outputThread != null && outputThread.IsAlive) { outputThread.Abort(); } // ensure errorThread is always aborted if (errorThread != null && errorThread.IsAlive) { errorThread.Abort(); } } } #endregion Override implementation of Task #region Public Instance Methods /// /// Gets the command-line arguments, separated by spaces. /// public string CommandLine { get { // append any nested arguments to the command line StringBuilder arguments = new StringBuilder(ProgramArguments); Arguments.ToString(arguments); return arguments.ToString(); } } #endregion Public Instance Methods #region Protected Instance Methods /// /// Updates the of the specified /// . /// /// The of which the should be updated. protected virtual void PrepareProcess(Process process){ ManagedExecutionMode executionMode = ManagedExecutionMode; // create process (redirect standard output to temp buffer) if (executionMode != null && executionMode.Engine != null) { process.StartInfo.FileName = executionMode.Engine.Program.FullName; StringBuilder arguments = new StringBuilder(); executionMode.Engine.Arguments.ToString (arguments); if (arguments.Length >= 0) { arguments.Append (' '); } arguments.AppendFormat("\"{0}\" {1}", ProgramFileName, CommandLine); process.StartInfo.Arguments = arguments.ToString(); } else { process.StartInfo.FileName = ProgramFileName; process.StartInfo.Arguments = CommandLine; } if (!Spawn) { process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; } // required to allow redirects and allow environment variables to // be set process.StartInfo.UseShellExecute = false; // do not start process in new window unless we're spawning (if not, // the console output of spawned application is not displayed on MS) process.StartInfo.CreateNoWindow = !Spawn; process.StartInfo.WorkingDirectory = BaseDirectory.FullName; // set framework-specific environment variables if executing the // external process using the runtime engine of the currently // active framework if (executionMode != null) { foreach (EnvironmentVariable environmentVariable in executionMode.Environment.EnvironmentVariables) { if (environmentVariable.IfDefined && !environmentVariable.UnlessDefined) { if (environmentVariable.Value == null) { process.StartInfo.EnvironmentVariables[environmentVariable.VariableName] = ""; } else { process.StartInfo.EnvironmentVariables[environmentVariable.VariableName] = environmentVariable.Value; } } } } } /// /// Starts the process and handles errors. /// /// The that was started. protected virtual Process StartProcess() { Process p = new Process(); PrepareProcess(p); try { string msg = string.Format( CultureInfo.InvariantCulture, ResourceUtils.GetString("String_Starting_Program"), p.StartInfo.WorkingDirectory, p.StartInfo.FileName, p.StartInfo.Arguments); logger.Info(msg); Log(Level.Verbose, msg); p.Start(); return p; } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1121"), p.StartInfo.FileName), Location, ex); } } #endregion Protected Instance Methods #region Private Instance Methods /// /// Reads from the stream until the external program is ended. /// private void StreamReaderThread_Output() { StreamReader reader = _stdOut; bool doAppend = OutputAppend; while (true) { string logContents = reader.ReadLine(); if (logContents == null) { break; } // ensure only one thread writes to the log at any time lock (_lockObject) { if (Output != null) { StreamWriter writer = new StreamWriter(Output.FullName, doAppend); writer.WriteLine(logContents); doAppend = true; writer.Close(); } else { OutputWriter.WriteLine(logContents); } } } lock (_lockObject) { OutputWriter.Flush(); } } /// /// Reads from the stream until the external program is ended. /// private void StreamReaderThread_Error() { StreamReader reader = _stdError; bool doAppend = OutputAppend; while (true) { string logContents = reader.ReadLine(); if (logContents == null) { break; } // ensure only one thread writes to the log at any time lock (_lockObject) { ErrorWriter.WriteLine(logContents); if (Output != null) { StreamWriter writer = new StreamWriter(Output.FullName, doAppend); writer.WriteLine(logContents); doAppend = true; writer.Close(); } } } lock (_lockObject) { ErrorWriter.Flush(); } } /// /// Determines the path of the external program that should be executed. /// /// /// A fully qualifies pathname including the program name. /// /// The task is not available or not configured for the current framework. private string DetermineFilePath() { string fullPath = ""; // if the Exename is already specified as a full path then just use that. if (ExeName != null && Path.IsPathRooted(ExeName)) { return ExeName; } // get the ProgramLocation attribute ProgramLocationAttribute programLocationAttribute = (ProgramLocationAttribute) Attribute.GetCustomAttribute(this.GetType(), typeof(ProgramLocationAttribute)); if (programLocationAttribute != null) { // ensure we have a valid framework set. if ((programLocationAttribute.LocationType == LocationType.FrameworkDir || programLocationAttribute.LocationType == LocationType.FrameworkSdkDir) && (Project.TargetFramework == null)) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1120") + Environment.NewLine, Name)); } switch (programLocationAttribute.LocationType) { case LocationType.FrameworkDir: if (Project.TargetFramework.FrameworkDirectory != null) { string frameworkDir = Project.TargetFramework.FrameworkDirectory.FullName; fullPath = Path.Combine(frameworkDir, ExeName + ".exe"); } else { throw new BuildException( string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1124"), Project.TargetFramework.Name)); } break; case LocationType.FrameworkSdkDir: if (Project.TargetFramework.SdkDirectory != null) { string sdkDirectory = Project.TargetFramework.SdkDirectory.FullName; fullPath = Path.Combine(sdkDirectory, ExeName + ".exe"); } else { throw new BuildException( string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1122"), Project.TargetFramework.Name)); } break; } if (!File.Exists (fullPath)) { string toolPath = Project.TargetFramework.GetToolPath ( ExeName + ".exe"); if (toolPath != null) { fullPath = toolPath; } } } else { // rely on it being on the path. fullPath = ExeName; } return fullPath; } private ManagedExecutionMode ManagedExecutionMode { get { if (Project.TargetFramework == null || Managed == ManagedExecution.Default) { return null; } Runtime runtime = Project.TargetFramework.Runtime; if (runtime != null) { return runtime.Modes.GetExecutionMode (Managed); } return null; } } #endregion Private Instance Methods } } nant-0.92-rc1/src/NAnt.Core/Tasks/MoveTask.cs0000644000175000017500000003075511757302273020525 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Ian MacLean (imaclean@gmail.com) // Ryan Boggs (rmboggs@users.sourceforge.net) using System; using System.Globalization; using System.IO; using NAnt.Core.Attributes; using NAnt.Core.Types; using NAnt.Core.Util; using NAnt.Core.Filters; namespace NAnt.Core.Tasks { /// /// Moves a file, a directory, or set of files to a new file or directory. /// /// /// /// Files are only moved if the source file is newer than the destination /// file, or if the destination file does not exist. However, you can /// explicitly overwrite files with the /// attribute. /// /// /// Entire directory structures can be moved to a new location. For this /// to happen, the following criteria must be met: /// /// /// /// /// Everything in the fileset is included /// /// /// /// /// The directory structure is not flattened /// /// /// /// /// Empty directories are included /// /// /// /// /// Destination directory does not exist /// /// /// /// /// If any of these items are not met, then the files within the source /// directory will be moved over instead of the entire directory structure. /// /// /// A can be used to select files or directories to move. /// To use a , the /// attribute must be set. /// ///

Encoding

/// /// Unless an encoding is specified, the encoding associated with the /// system's current ANSI code page is used. /// /// /// An UTF-8, little-endian Unicode, and big-endian Unicode encoded text /// file is automatically recognized, if the file starts with the /// appropriate byte order marks. /// /// /// If you employ filters in your move operation, you should limit the /// move to text files. Binary files will be corrupted by the move /// operation. /// ///
/// /// /// Move a single file while changing its encoding from "latin1" to /// "utf-8". /// /// /// /// ]]> /// /// /// /// Move a set of files. /// /// /// /// /// /// /// ]]> /// /// /// /// /// Move a set of files to a directory, replacing @TITLE@ with /// "Foo Bar" in all files. /// /// /// /// /// /// /// /// /// /// /// /// /// ]]> /// /// /// /// /// Move an entire directory and its contents. /// /// /// /// /// /// ]]> /// /// [TaskName("move")] public class MoveTask : CopyTask { #region Override implementation of CopyTask /// /// The file to move. /// [TaskAttribute("file")] public override FileInfo SourceFile { get { return base.SourceFile; } set { base.SourceFile = value; } } /// /// The file to move to. /// [TaskAttribute("tofile")] public override FileInfo ToFile { get { return base.ToFile; } set { base.ToFile = value; } } /// /// The directory to move to. /// [TaskAttribute("todir")] public override DirectoryInfo ToDirectory { get { return base.ToDirectory; } set { base.ToDirectory = value; } } /// /// Used to select the files to move. To use a , /// the attribute must be set. /// [BuildElement("fileset")] public override FileSet CopyFileSet { get { return base.CopyFileSet; } set { base.CopyFileSet = value; } } /// /// Ignore directory structure of source directory, move all files into /// a single directory, specified by the /// attribute. The default is . /// [TaskAttribute("flatten")] [BooleanValidator()] public override bool Flatten { get { return base.Flatten; } set { base.Flatten = value; } } /// /// Chain of filters used to alter the file's content as it is moved. /// [BuildElement("filterchain")] public override FilterChain Filters { get { return base.Filters; } set { base.Filters = value; } } /// /// Actually does the file moves. /// protected override void DoFileOperations() { // If the operation map is empty, exit (return) the method. if (OperationMap.Count <= 0) { return; } // loop thru our file list for (int i = 0; i < OperationMap.Count; i++) { // Setup a temporary var to hold the current file operation // details. FileOperation currentOperation = OperationMap[i]; if (currentOperation.SourceIsIdenticalToTarget()) { Log(Level.Warning, String.Format("Skipping self-move of {0}.", currentOperation.Source)); continue; } try { Log(Level.Verbose, "Moving {0}.", currentOperation.ToString()); string destinationDirectory = null; switch (currentOperation.OperationType) { case OperationType.FileToFile: // Setup the dest directory var destinationDirectory = Path.GetDirectoryName(currentOperation.Target); // create directory if not present if (!Directory.Exists(destinationDirectory)) { Directory.CreateDirectory(destinationDirectory); Log(Level.Verbose, "Created directory '{0}'.", destinationDirectory); } // Ensure the target file is removed before // attempting to move. if (File.Exists(currentOperation.Target)) { File.Delete(currentOperation.Target); } // move the file with filters FileUtils.MoveFile(currentOperation.Source, currentOperation.Target, Filters, InputEncoding, OutputEncoding); break; case OperationType.FileToDirectory: // Setup the dest directory var destinationDirectory = currentOperation.Target; // Setup a local var that combines the directory // of the target path with the source file name. string targetFile = Path.Combine(destinationDirectory, Path.GetFileName(currentOperation.Source)); // create directory if not present if (!Directory.Exists(destinationDirectory)) { Directory.CreateDirectory(destinationDirectory); Log(Level.Verbose, "Created directory '{0}'.", destinationDirectory); } // Ensure the target file is removed before // attempting to move. if (File.Exists(targetFile)) { File.Delete(targetFile); } // move the file with filters FileUtils.MoveFile(currentOperation.Source, targetFile, Filters, InputEncoding, OutputEncoding); break; case OperationType.DirectoryToDirectory: // Move over the entire directory with filters FileUtils.MoveDirectory(currentOperation.Source, currentOperation.Target, Filters, InputEncoding, OutputEncoding); break; default: throw new BuildException("Unrecognized move operation. " + "The move task can only move a file to file, " + "file to directory, or directory to directory."); } } catch (IOException ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Failed to move {0}.", currentOperation.ToString()), Location, ex); } } int fileMovements = OperationMap.CountFileOperations(); int dirMovements = OperationMap.CountDirectoryOperations(); if (fileMovements > 0) { Log(Level.Info, "{0} file{1} moved.", fileMovements, fileMovements != 1 ? "s" : ""); } if (dirMovements > 0) { Log(Level.Info, "{0} {1} moved.", dirMovements, dirMovements != 1 ? "directories" : "directory"); } } protected override BuildException CreateSourceFileNotFoundException (string sourceFile) { return new BuildException(string.Format(CultureInfo.InvariantCulture, "Could not find file '{0}' to move.", sourceFile), Location); } #endregion Override implementation of CopyTask } } nant-0.92-rc1/src/NAnt.Core/Tasks/AttribTask.cs0000644000175000017500000002464611757302273021046 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Chris Jenkin (oneinchhard@hotmail.com) // Gerry Shaw (gerry_shaw@yahoo.com) using System; using System.Collections.Specialized; using System.Globalization; using System.IO; using NAnt.Core.Attributes; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.Core.Tasks { /// /// Changes the file attributes of a file or set of files and directories. /// /// /// /// does not have the concept of turning /// attributes off. Instead you specify all the attributes that you want /// turned on and the rest are turned off by default. /// /// /// Refer to the enumeration in the .NET SDK /// for more information about file attributes. /// /// /// /// /// Set the read-only file attribute for the specified file in /// the project directory. /// /// /// /// ]]> /// /// /// /// /// Set the normal file attribute for the specified file. /// /// /// /// ]]> /// /// /// /// /// Set the normal file attribute for all executable files in /// the current project directory and sub-directories. /// /// /// /// /// /// /// /// /// ]]> /// /// [TaskName("attrib")] public class AttribTask : Task { #region Private Instance Fields private FileInfo _file; private FileSet _fileset = new FileSet(); private bool _archiveAttrib; private bool _hiddenAttrib; private bool _normalAttrib; private bool _readOnlyAttrib; private bool _systemAttrib; #endregion Private Instance Fields #region Public Instance Properties /// /// The name of the file which will have its attributes set. This is /// provided as an alternate to using the task's fileset. /// [TaskAttribute("file")] public FileInfo File { get { return _file; } set { _file = value; } } /// /// All the matching files and directories in this fileset will have /// their attributes set. /// [BuildElement("fileset")] public FileSet AttribFileSet { get { return _fileset; } set {_fileset = value; } } /// /// Set the archive attribute. The default is . /// [TaskAttribute("archive")] [BooleanValidator()] public bool ArchiveAttrib { get { return _archiveAttrib; } set { _archiveAttrib = value; } } /// /// Set the hidden attribute. The default is . /// [TaskAttribute("hidden")] [BooleanValidator()] public bool HiddenAttrib { get { return _hiddenAttrib; } set { _hiddenAttrib = value; } } /// /// Set the normal file attributes. This attribute is only valid if used /// alone. The default is . /// [TaskAttribute("normal")] [BooleanValidator()] public bool NormalAttrib { get { return _normalAttrib; } set { _normalAttrib = value; } } /// /// Set the read-only attribute. The default is . /// [TaskAttribute("readonly")] [BooleanValidator()] public bool ReadOnlyAttrib { get { return _readOnlyAttrib; } set { _readOnlyAttrib = value; } } /// /// Set the system attribute. The default is . /// [TaskAttribute("system")] [BooleanValidator()] public bool SystemAttrib { get { return _systemAttrib; } set { _systemAttrib = value; } } #endregion Public Instance Properties #region Override implementation of Task protected override void ExecuteTask() { // ensure base directory is set, even if fileset was not initialized // from XML if (AttribFileSet.BaseDirectory == null) { AttribFileSet.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } // add the shortcut filename to the file set if (File != null) { AttribFileSet.Includes.Add(File.FullName); } if (AttribFileSet.FileNames.Count > 0) { // determine attributes to set on files FileAttributes fileAttributes = GetFileAttributes(); // display build log message Log(Level.Info, "Setting file attributes for {0} files to {1}.", AttribFileSet.FileNames.Count, fileAttributes.ToString(CultureInfo.InvariantCulture)); // perform operation on files foreach (string path in AttribFileSet.FileNames) { SetFileAttributes(path, fileAttributes); } } if (AttribFileSet.DirectoryNames.Count > 0) { // determine attributes to set on directories FileAttributes directoryAttributes = GetDirectoryAttributes(); // display build log message Log(Level.Info, "Setting attributes for {0} directories to {1}.", AttribFileSet.DirectoryNames.Count, directoryAttributes.ToString(CultureInfo.InvariantCulture)); // perform operation on directories foreach (string path in AttribFileSet.DirectoryNames) { SetDirectoryAttributes(path, directoryAttributes); } } if (AttribFileSet.FileNames.Count == 0 && AttribFileSet.DirectoryNames.Count == 0) { Log(Level.Verbose, "No matching files or directories found."); } } #endregion Override implementation of Task #region Private Instance Methods private FileAttributes GetFileAttributes() { FileAttributes fileAttributes = 0; if (NormalAttrib) { fileAttributes = FileAttributes.Normal; } else { if (ArchiveAttrib) { fileAttributes |= FileAttributes.Archive; } if (HiddenAttrib) { fileAttributes |= FileAttributes.Hidden; } if (ReadOnlyAttrib) { fileAttributes |= FileAttributes.ReadOnly; } if (SystemAttrib) { fileAttributes |= FileAttributes.System; } } if (!Enum.IsDefined(typeof(FileAttributes), fileAttributes)) { fileAttributes = FileAttributes.Normal; } return fileAttributes; } private void SetFileAttributes(string path, FileAttributes fileAttributes) { try { Log(Level.Verbose, path); System.IO.File.SetAttributes(path, fileAttributes); } catch (Exception ex) { string msg = string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1102"), path); if (FailOnError) { throw new BuildException(msg, Location, ex); } else { Log(Level.Verbose, msg + " " + ex.Message); } } } private FileAttributes GetDirectoryAttributes() { FileAttributes directoryAttributes = FileAttributes.Directory; if (!NormalAttrib) { if (ArchiveAttrib) { directoryAttributes |= FileAttributes.Archive; } if (HiddenAttrib) { directoryAttributes |= FileAttributes.Hidden; } if (ReadOnlyAttrib) { directoryAttributes |= FileAttributes.ReadOnly; } if (SystemAttrib) { directoryAttributes |= FileAttributes.System; } } return directoryAttributes; } private void SetDirectoryAttributes(string path, FileAttributes fileAttributes) { try { if (System.IO.Directory.Exists(path)) { Log(Level.Verbose, path); System.IO.File.SetAttributes(path, fileAttributes); } else { throw new DirectoryNotFoundException(); } } catch (Exception ex) { string msg = string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1101"), path); if (FailOnError) { throw new BuildException(msg, Location, ex); } else { Log(Level.Verbose, msg + " " + ex.Message); } } } #endregion Private Instance Methods } } nant-0.92-rc1/src/NAnt.Core/Tasks/ExecTask.cs0000644000175000017500000003474211757302273020503 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) using System; using System.Globalization; using System.IO; using System.Xml; using NAnt.Core.Attributes; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.Core.Tasks { /// /// Executes a system command. /// /// /// /// Use of nested element(s) /// is advised over the parameter, as /// it supports automatic quoting and can resolve relative to absolute /// paths. /// /// /// /// Ping "nant.sourceforge.net". /// /// /// /// /// ]]> /// /// /// /// /// Execute a java application using IKVM.NET that requires the /// Apache FOP jars, and a set of custom jars. /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// ]]> /// /// /// Assuming the base directory of the build file is "c:\ikvm-test" and /// the value of the "fop.dist.dir" property is "c:\fop", then the value /// of the -cp argument that is passed toikvm.exe is /// "c:\ikvm-test\conf;c:\fop\build\fop.jar;conf;c:\fop\lib\xercesImpl-2.2.1.jar;c:\fop\lib\avalon-framework-cvs-20020806.jar;c:\fop\lib\batik.jar;c:\ikvm-test\lib\mylib.jar;c:\ikvm-test\lib\otherlib.zip" /// on a DOS-based system. /// /// [TaskName("exec")] public class ExecTask : ExternalProgramBase { #region Private Instance Fields private string _program; private string _commandline; private DirectoryInfo _baseDirectory; private DirectoryInfo _workingDirectory; private FileInfo _output; private bool _outputAppend; private EnvironmentSet _environmentSet = new EnvironmentSet(); private string _resultProperty; private string _processIdProperty; #endregion Private Instance Fields #region Public Instance Properties /// /// The program to execute without command arguments. /// /// /// The path will not be evaluated to a full path using the project /// base directory. /// [TaskAttribute("program", Required=true)] [StringValidator(AllowEmpty=false)] public string FileName { get { return _program; } set { _program = StringUtils.ConvertEmptyToNull(value); } } /// /// The command-line arguments for the program. These will be /// passed as is to the external program. When quoting is necessary, /// these must be explictly set as part of the value. Consider using /// nested elements instead. /// [TaskAttribute("commandline")] public string CommandLineArguments { get { return _commandline; } set { _commandline = StringUtils.ConvertEmptyToNull(value); } } /// /// Environment variables to pass to the program. /// [BuildElement("environment")] public EnvironmentSet EnvironmentSet { get { return _environmentSet; } } /// /// The directory in which the command will be executed. /// /// /// The directory in which the command will be executed. The default /// is the project's base directory. /// /// /// /// The working directory will be evaluated relative to the project's /// base directory if it is relative. /// /// [TaskAttribute("workingdir")] public DirectoryInfo WorkingDirectory { get { if (_workingDirectory == null) { return base.BaseDirectory; } return _workingDirectory; } set { _workingDirectory = value; } } /// /// /// The name of a property in which the exit code of the program should /// be stored. Only of interest if is /// . /// /// /// If the exit code of the program is "-1000" then the program could /// not be started, or did not exit (in time). /// /// [TaskAttribute("resultproperty")] [StringValidator(AllowEmpty=false)] public string ResultProperty { get { return _resultProperty; } set { _resultProperty = value; } } #endregion Public Instance Properties #region Override implementation of ExternalProgramBase /// /// Specifies whether the external program should be executed using a /// runtime engine, if configured. The default is . /// /// /// if the external program should be executed /// using a runtime engine; otherwise, . /// [TaskAttribute("useruntimeengine")] [Obsolete("Use the managed attribute and Managed property instead.", false)] public override bool UseRuntimeEngine { get { return base.UseRuntimeEngine ; } set { base.UseRuntimeEngine = value; } } /// /// Specifies whether the external program is a managed application /// which should be executed using a runtime engine, if configured. /// The default is . /// /// /// if the external program should be executed /// using a runtime engine; otherwise, . /// [TaskAttribute("managed")] public override ManagedExecution Managed { get { return base.Managed; } set { base.Managed = value; } } /// /// Gets the filename of the external program to start. /// /// /// The filename of the external program. /// public override string ProgramFileName { get { if (Path.IsPathRooted(FileName)) { return FileName; } else if (_baseDirectory == null) { // resolve program to full path relative to project directory string fullPath = Project.GetFullPath(FileName); // check if the program exists in that location if (File.Exists(fullPath)) { // return full path to program (which we know exists) return fullPath; } return FileName; } else { return Path.GetFullPath(Path.Combine(BaseDirectory.FullName, FileName)); } } } /// /// Performs additional checks after the task has been initialized. /// /// does not hold a valid file name. protected override void Initialize() { base.Initialize(); try { // just check if program file to execute is a valid file name if (Path.IsPathRooted(FileName)) { // do nothing } } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1117"), FileName, Name), Location, ex); } } /// /// Gets the command-line arguments for the external program. /// /// /// The command-line arguments for the external program. /// public override string ProgramArguments { get { return _commandline; } } /// /// The directory the program is in. /// /// /// /// The directory the program is in. The default is the project's base /// directory. /// /// /// The basedir will be evaluated relative to the project's base /// directory if it is relative. /// /// [TaskAttribute("basedir")] public override DirectoryInfo BaseDirectory { get { if (_baseDirectory == null) { return base.BaseDirectory; } return _baseDirectory; } set { _baseDirectory = value; } } /// /// The file to which the standard output will be redirected. /// /// /// By default, the standard output is redirected to the console. /// [TaskAttribute("output")] public override FileInfo Output { get { return _output; } set { _output = value; } } /// /// Gets or sets a value indicating whether output should be appended /// to the output file. The default is . /// /// /// if output should be appended to the ; /// otherwise, . /// [TaskAttribute("append")] public override bool OutputAppend { get { return _outputAppend; } set { _outputAppend = value; } } /// /// Gets or sets a value indicating whether the application should be /// spawned. If you spawn an application, its output will not be logged /// by NAnt. The default is . /// [TaskAttribute("spawn")] public override bool Spawn { get { return base.Spawn; } set { base.Spawn = value; } } /// /// The name of a property in which the unique identifier of the spawned /// application should be stored. Only of interest if /// is . /// [TaskAttribute("pidproperty")] [StringValidator(AllowEmpty=false)] public string ProcessIdProperty { get { return _processIdProperty; } set { _processIdProperty = value; } } /// /// Executes the external program. /// protected override void ExecuteTask() { base.ExecuteTask(); if (ResultProperty != null) { Properties[ResultProperty] = base.ExitCode.ToString( CultureInfo.InvariantCulture); } if (Spawn && ProcessIdProperty != null) { Properties[ProcessIdProperty] = base.ProcessId.ToString( CultureInfo.InvariantCulture); } } protected override void PrepareProcess(System.Diagnostics.Process process) { base.PrepareProcess(process); // set working directory specified by user process.StartInfo.WorkingDirectory = WorkingDirectory.FullName; // set environment variables foreach (Option option in EnvironmentSet.Options) { if (option.IfDefined && !option.UnlessDefined) { if (option.Value == null) { process.StartInfo.EnvironmentVariables[option.OptionName] = ""; } else { process.StartInfo.EnvironmentVariables[option.OptionName] = option.Value; } } } foreach (EnvironmentVariable variable in EnvironmentSet.EnvironmentVariables) { if (variable.IfDefined && !variable.UnlessDefined) { if (variable.Value == null) { process.StartInfo.EnvironmentVariables[variable.VariableName] = ""; } else { process.StartInfo.EnvironmentVariables[variable.VariableName] = variable.Value; } } } } #endregion Override implementation of ExternalProgramBase } } nant-0.92-rc1/src/NAnt.Core/Tasks/XmlPokeTask.cs0000644000175000017500000003013711757302273021170 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian McLean (ianm@activestate.com) // Mitch Denny (mitch.denny@monash.net) using System; using System.Globalization; using System.IO; using System.Xml; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.Core.Tasks { /// /// Replaces text in an XML file at the location specified by an XPath /// expression. /// /// /// /// The location specified by the XPath expression must exist, it will /// not create the parent elements for you. However, provided you have /// a root element you could use a series of the tasks to build the /// XML file up if necessary. /// /// /// /// /// Change the server setting in the configuration from testhost.somecompany.com /// to productionhost.somecompany.com. /// /// XML file: /// /// /// /// /// /// /// /// ]]> /// /// Build fragment: /// /// /// ]]> /// /// /// /// /// Modify the noNamespaceSchemaLocation in an XML file. /// /// XML file: /// /// /// /// /// ]]> /// /// Build fragment: /// /// /// /// /// ///
/// ]]> /// /// [TaskName("xmlpoke")] public class XmlPokeTask : Task { #region Private Instance Fields private FileInfo _xmlFile; private string _value; private string _xPathExpression; private bool _preserveWhitespace; private XmlNamespaceCollection _namespaces = new XmlNamespaceCollection(); #endregion Private Instance Fields #region Public Instance Properties /// /// The name of the file that contains the XML document that is going /// to be poked. /// [TaskAttribute("file", Required=true)] public FileInfo XmlFile { get { return _xmlFile; } set { _xmlFile = value; } } /// /// The XPath expression used to select which nodes are to be modified. /// [TaskAttribute("xpath", Required=true)] [StringValidator(AllowEmpty=false)] public string XPath { get { return _xPathExpression; } set { _xPathExpression = value; } } /// /// The value that replaces the contents of the selected nodes. /// [TaskAttribute("value", Required=true)] [StringValidator(AllowEmpty=true)] public string Value { get { return _value; } set { _value = value; } } /// /// Namespace definitions to resolve prefixes in the XPath expression. /// [BuildElementCollection("namespaces", "namespace")] public XmlNamespaceCollection Namespaces { get { return _namespaces; } set { _namespaces = value; } } /// /// If then the whitespace in the resulting /// document will be preserved; otherwise the whitespace will be removed. /// The default is . /// [TaskAttribute("preserveWhitespace", Required = false)] [StringValidator(AllowEmpty = false)] public bool PreserveWhitespace { get { return _preserveWhitespace; } set { _preserveWhitespace = value; } } #endregion Public Instance Properties #region Override implementation of Task /// /// Executes the XML poke task. /// protected override void ExecuteTask() { // ensure the specified xml file exists if (!XmlFile.Exists) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1154"), XmlFile.FullName), Location); } try { XmlDocument document = LoadDocument(XmlFile.FullName, PreserveWhitespace); XmlNamespaceManager nsMgr = new XmlNamespaceManager(document.NameTable); foreach (XmlNamespace xmlNamespace in Namespaces) { if (xmlNamespace.IfDefined && !xmlNamespace.UnlessDefined) { nsMgr.AddNamespace(xmlNamespace.Prefix, xmlNamespace.Uri); } } XmlNodeList nodes = SelectNodes(XPath, document, nsMgr); // don't bother trying to update any nodes or save the // file if no nodes were found in the first place. if (nodes.Count > 0) { UpdateNodes(nodes, Value); SaveDocument(document, XmlFile.FullName); } } catch (BuildException ex) { throw ex; } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1159"), XmlFile.FullName), Location, ex); } } #endregion Override implementation of Task #region Private Instance Methods /// /// Loads an XML document from a file on disk. /// /// /// The file name of the file to load the XML document from. /// /// /// Value for XmlDocument.PreserveWhitespace that is set before the xml is loaded. /// /// /// An containing /// the document object model representing the file. /// private XmlDocument LoadDocument(string fileName, bool preserveWhitespace) { XmlDocument document = null; try { Log(Level.Verbose, "Attempting to load XML document" + " in file '{0}'.", fileName); document = new XmlDocument(); document.PreserveWhitespace = preserveWhitespace; document.Load(fileName); Log(Level.Verbose, "XML document in file '{0}' loaded" + " successfully.", fileName); return document; } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1158"), fileName), Location, ex); } } /// /// Given an XML document and an expression, returns a list of nodes /// which match the expression criteria. /// /// /// The XPath expression used to select the nodes. /// /// /// The XML document that is searched. /// /// /// An to use for resolving namespaces /// for prefixes in the XPath expression. /// /// /// An containing references to the nodes /// that matched the XPath expression. /// private XmlNodeList SelectNodes(string xpath, XmlDocument document, XmlNamespaceManager nsMgr) { XmlNodeList nodes = null; try { Log(Level.Verbose, "Selecting nodes with XPath" + " expression '{0}'.", xpath); nodes = document.SelectNodes(xpath, nsMgr); } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1161"), xpath), Location, ex); } // throw exception if no nodes found for XPath (handled gracefully if failonerror=false) if (nodes == null || nodes.Count == 0) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1156"), xpath), Location); } // report back how many we found. Log(Level.Info, "Found '{0}' nodes matching" + " XPath expression '{1}'.", nodes.Count, xpath); return nodes; } /// /// Given a node list, replaces the XML within those nodes. /// /// /// The list of nodes to replace the contents of. /// /// /// The text to replace the contents with. /// private void UpdateNodes(XmlNodeList nodes, string value) { Log(Level.Verbose, "Updating nodes with value '{0}'.", value); int index = 0; foreach (XmlNode node in nodes) { Log(Level.Verbose, "Updating node '{0}'.", index); node.InnerXml = value; index ++; } Log( Level.Verbose, "Updated all nodes successfully.", value); } /// /// Saves the XML document to a file. /// /// The XML document to be saved. /// The file name to save the XML document under. private void SaveDocument(XmlDocument document, string fileName) { try { Log(Level.Verbose, "Attempting to save XML document" + " to '{0}'.", fileName); document.Save(fileName); Log(Level.Verbose, "XML document successfully saved" + " to '{0}'.", fileName); } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1162"), fileName), Location, ex); } } #endregion Private Instance Methods } }nant-0.92-rc1/src/NAnt.Core/Tasks/XmlPeekTask.cs0000644000175000017500000002500511757302273021154 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian McLean (ianm@activestate.com) // Mitch Denny (mitch.denny@monash.net) // Charles Chan (cchan_qa@users.sourceforge.net) using System; using System.Globalization; using System.IO; using System.Xml; using System.Xml.XPath; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.Core.Tasks { /// /// Extracts text from an XML file at the location specified by an XPath /// expression. /// /// /// /// If the XPath expression specifies multiple nodes the node index is used /// to determine which of the nodes' text is returned. /// /// /// /// /// The example provided assumes that the following XML file (App.config) /// exists in the current build directory. /// /// /// /// /// /// /// /// /// ]]> /// /// /// /// /// The example will read the server value from the above /// configuration file. /// /// /// /// /// /// ///
/// ]]> /// /// [TaskName("xmlpeek")] public class XmlPeekTask : Task { #region Private Instance Fields private FileInfo _xmlFile; private int _nodeIndex = 0; private string _property; private string _xPath; private XmlNamespaceCollection _namespaces = new XmlNamespaceCollection(); #endregion Private Instance Fields #region Public Instance Properties /// /// The name of the file that contains the XML document /// that is going to be peeked at. /// [TaskAttribute("file", Required=true)] public FileInfo XmlFile { get { return _xmlFile; } set { _xmlFile = value; } } /// /// The index of the node that gets its text returned when the query /// returns multiple nodes. /// [TaskAttribute("nodeindex", Required=false)] [Int32Validator(0, Int32.MaxValue)] public int NodeIndex { get { return _nodeIndex; } set { _nodeIndex = value; } } /// /// The property that receives the text representation of the XML inside /// the node returned from the XPath expression. /// [TaskAttribute("property", Required=true)] [StringValidator(AllowEmpty=false)] public string Property { get { return _property; } set { _property = value; } } /// /// The XPath expression used to select which node to read. /// [TaskAttribute("xpath", Required=true)] [StringValidator(AllowEmpty=false)] public string XPath { get { return _xPath; } set { _xPath = value; } } /// /// Namespace definitions to resolve prefixes in the XPath expression. /// [BuildElementCollection("namespaces", "namespace")] public XmlNamespaceCollection Namespaces { get { return _namespaces; } set { _namespaces = value; } } #endregion Public Instance Properties #region Override implementation of Task /// /// Executes the XML peek task. /// protected override void ExecuteTask() { Log(Level.Verbose, "Peeking at '{0}' with XPath expression '{1}'.", XmlFile.FullName, XPath); // ensure the specified xml file exists if (!XmlFile.Exists) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1154"), XmlFile.FullName), Location); } try { XmlDocument document = LoadDocument(XmlFile.FullName); Properties[Property] = GetNodeContents(XPath, document, NodeIndex); } catch (BuildException ex) { throw ex; // Just re-throw the build exceptions. } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1153"), XmlFile.FullName), Location, ex); } } #endregion Override implementation of Task #region private Instance Methods /// /// Loads an XML document from a file on disk. /// /// The file name of the file to load the XML document from. /// /// A document containing /// the document object representing the file. /// private XmlDocument LoadDocument(string fileName) { XmlDocument document = null; try { document = new XmlDocument(); document.Load(fileName); return document; } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1158"), fileName), Location, ex); } } /// /// Gets the contents of the node specified by the XPath expression. /// /// The XPath expression used to determine which nodes to choose from. /// The XML document to select the nodes from. /// The node index in the case where multiple nodes satisfy the expression. /// /// The contents of the node specified by the XPath expression. /// private string GetNodeContents(string xpath, XmlDocument document, int nodeIndex ) { string contents = null; Object result = null; int numNodes = 0; try { XmlNamespaceManager nsMgr = new XmlNamespaceManager(document.NameTable); foreach (XmlNamespace xmlNamespace in Namespaces) { if (xmlNamespace.IfDefined && !xmlNamespace.UnlessDefined) { nsMgr.AddNamespace(xmlNamespace.Prefix, xmlNamespace.Uri); } } XPathNavigator nav = document.CreateNavigator(); XPathExpression expr = nav.Compile(xpath); expr.SetContext(nsMgr); result = nav.Evaluate(expr); } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1155"), xpath), Location, ex); } if (result == null) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1156"), xpath), Location); } // When using XPathNavigator.Evaluate(), // the result of the expression can be one of Boolean, number, // string, or node set). This maps to Boolean, Double, String, // or XPathNodeIterator objects respectively. // So therefore if the result is not null, then there is at least // 1 node that matches. numNodes = 1; // If the result is a node set, then there could be multiple nodes. XPathNodeIterator xpathNodesIterator = result as XPathNodeIterator; if (xpathNodesIterator != null) { numNodes = xpathNodesIterator.Count; } Log(Level.Verbose, "Found '{0}' node{1} with the XPath expression '{2}'.", numNodes, numNodes > 1 ? "s" : "", xpath); if (xpathNodesIterator != null) { if (nodeIndex >= numNodes){ throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1157"), nodeIndex), Location); } while (xpathNodesIterator.MoveNext()) { // CurrentPosition is 1-based. if (xpathNodesIterator.CurrentPosition == (nodeIndex + 1)) { // Get the entire node of the current xpathNodesIterator and return innerxml. XmlNode currentNode = ((IHasXmlNode)xpathNodesIterator.Current).GetNode(); contents = currentNode.InnerXml; } } } else { if (result is IFormattable) { IFormattable formattable = (IFormattable) result; contents = formattable.ToString(null, CultureInfo.InvariantCulture); } else { contents = result.ToString(); } } return contents; } #endregion private Instance Methods } } nant-0.92-rc1/src/NAnt.Core/Tasks/AvailableTask.cs0000644000175000017500000002677311757302273021504 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.IO; using System.Globalization; using NAnt.Core.Attributes; using NAnt.Core.Functions; using NAnt.Core.Util; namespace NAnt.Core.Tasks { /// /// Checks if a resource is available at runtime. /// /// /// /// The specified property is set to if the /// requested resource is available at runtime, and /// if the resource is not available. /// /// /// we advise you to use the following functions instead: /// /// /// /// Function /// Description /// /// /// /// Determines whether the specified file exists. /// /// /// /// Determines whether the given path refers to an existing directory on disk. /// /// /// /// Checks whether the specified framework exists.. /// /// /// /// Checks whether the SDK for the specified framework is installed. /// /// /// /// /// /// Sets the myfile.present property to if the /// file is available on the filesystem and if the /// file is not available. /// /// /// /// ]]> /// /// /// /// /// Sets the build.dir.present property to /// if the directory is available on the filesystem and /// if the directory is not available. /// /// /// /// ]]> /// /// /// /// /// Sets the mono-0.21.framework.present property to /// if the Mono 0.21 framework is available on the current system and /// if the framework is not available. /// /// /// /// ]]> /// /// /// /// /// Sets the net-1.1.frameworksdk.present property to /// if the .NET 1.1 Framework SDK is available on the current system and /// if the SDK is not available. /// /// /// /// ]]> /// /// [TaskName("available")] [Obsolete("Use functions instead.", false)] public class AvailableTask : Task { /// /// Defines the possible resource checks. /// public enum ResourceType : int { /// /// Determines whether a given file exists. /// File = 1, /// /// Determines whether a given directory exists. /// Directory = 2, /// /// Determines whether a given framework is available. /// Framework = 3, /// /// Determines whether a given SDK is available. /// FrameworkSDK = 4 } #region Public Instance Properties /// /// The resource which must be available. /// [TaskAttribute("resource", Required=true)] [StringValidator(AllowEmpty=false)] public string Resource { get { return _resource; } set { _resource = StringUtils.ConvertEmptyToNull(value); } } /// /// The type of resource which must be present. /// [TaskAttribute("type", Required=true)] public ResourceType Type { get { return _resourceType; } set { if (!Enum.IsDefined(typeof(ResourceType), value)) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "An invalid type {0} was specified.", value)); } else { this._resourceType = value; } } } /// /// The property that must be set if the resource is available. /// [TaskAttribute("property", Required=true)] [StringValidator(AllowEmpty=false)] public string PropertyName { get { return _propertyName; } set { _propertyName = StringUtils.ConvertEmptyToNull(value); } } #endregion Public Instance Properties #region Override implementation of Task /// /// Executes the task. /// /// /// /// Sets the property identified by to /// when the resource exists and to /// when the resource doesn't exist. /// /// /// The availability of the resource could not be evaluated. protected override void ExecuteTask() { Project.Properties[PropertyName] = Evaluate().ToString(CultureInfo.InvariantCulture); } #endregion Override implementation of Task #region Protected Instance Methods /// /// Evaluates the availability of a resource. /// /// /// if the resource is available; otherwise, /// . /// /// The availability of the resource could not be evaluated. protected virtual bool Evaluate() { bool resourceAvailable = false; switch(Type) { case ResourceType.File: resourceAvailable = CheckFile(); break; case ResourceType.Directory: resourceAvailable = CheckDirectory(); break; case ResourceType.Framework: resourceAvailable = CheckFramework(); break; case ResourceType.FrameworkSDK: resourceAvailable = CheckFrameworkSDK(); break; default: throw new BuildException(string.Format(CultureInfo.InvariantCulture, "No resource check is implemented for {0}", Type)); } if (!resourceAvailable) { Log(Level.Verbose, "Unable to find {0} {1}.", Type, Resource); } return resourceAvailable; } #endregion Protected Instance Methods #region Private Instance Methods /// /// Checks if the file specified in the property is /// available on the filesystem. /// /// /// when the file exists; otherwise, . /// private bool CheckFile() { try { FileInfo fileInfo = new FileInfo(Project.GetFullPath(Resource)); return fileInfo.Exists; } catch (ArgumentException ex) { throw new BuildException(string.Format( CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1104"), Resource), Location, ex); } } /// /// Checks if the directory specified in the /// property is available on the filesystem. /// /// /// when the directory exists; otherwise, . /// private bool CheckDirectory() { try { DirectoryInfo dirInfo = new DirectoryInfo(Project.GetFullPath(Resource)); return dirInfo.Exists; } catch (ArgumentException ex) { throw new BuildException(string.Format( CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1103"), Resource), Location, ex); } } /// /// Checks if the framework specified in the /// property is available on the current system. /// /// /// when the framework is available; otherwise, /// . /// private bool CheckFramework() { return Project.Frameworks.Contains(Resource); } /// /// Checks if the SDK for the framework specified in the /// property is available on the current system. /// /// /// when the SDK for the specified framework is /// available; otherwise, . /// private bool CheckFrameworkSDK() { FrameworkInfo framework = Project.Frameworks[Resource]; if (framework != null) { return framework.SdkDirectory != null; } else { return false; } } #endregion Private Instance Methods #region Private Instance Fields private ResourceType _resourceType; private string _resource; private string _propertyName; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.Core/Tasks/NAntSchemaTask.cs0000644000175000017500000006624311757302273021601 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Scott Hernandez // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Scott Hernandez (ScottHernandez@hotmail.com) // Jaroslaw Kowalski (jkowalski@users.sourceforge.net) using System; using System.Collections; using System.Collections.Specialized; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Security.Permissions; using System.Xml; using System.Xml.Schema; using NAnt.Core.Attributes; using NAnt.Core.Util; namespace NAnt.Core.Tasks { /// /// Creates an XSD File for all available tasks. /// /// /// /// This can be used in conjuntion with the command-line option to do XSD /// Schema validation on the build file. /// /// /// /// Creates a NAnt.xsd file in the current project directory. /// /// /// ]]> /// /// [TaskName("nantschema")] public class NAntSchemaTask : Task { #region Private Instance Fields private FileInfo _outputFile; private string _forType; private string _targetNamespace = "http://tempuri.org/nant-donotuse.xsd"; #endregion Private Instance Fields #region Private Static Fields private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Contains names of tasks that should have the "mixed" attribute for the complex types. private static readonly string[] mixedTaskNames = new string[] { "NAnt.Core.Tasks.DescriptionTask" }; #endregion Private Static Fields #region Public Instance Properties /// /// The name of the output file to which the XSD should be written. /// [TaskAttribute("output", Required=true)] public virtual FileInfo OutputFile { get { return _outputFile; } set { _outputFile = value; } } /// /// The target namespace for the output. Defaults to "http://tempuri.org/nant-donotuse.xsd" /// [TaskAttribute("target-ns", Required=false)] public virtual string TargetNamespace { get { return _targetNamespace; } set { _targetNamespace = StringUtils.ConvertEmptyToNull(value); } } /// /// The for which an XSD should be created. If not /// specified, an XSD will be created for all available tasks. /// [TaskAttribute("class", Required=false)] public virtual string ForType { get { return _forType; } set { _forType = StringUtils.ConvertEmptyToNull(value); } } #endregion Public Instance Properties #region Override implementation of Task [ReflectionPermission(SecurityAction.Demand, Flags=ReflectionPermissionFlag.NoFlags)] protected override void ExecuteTask() { ArrayList taskTypes; ArrayList dataTypes; if (ForType == null) { taskTypes = new ArrayList(TypeFactory.TaskBuilders.Count); dataTypes = new ArrayList(TypeFactory.DataTypeBuilders.Count); foreach (TaskBuilder tb in TypeFactory.TaskBuilders) { taskTypes.Add(tb.Assembly.GetType(tb.ClassName, true, true)); } foreach (DataTypeBaseBuilder db in TypeFactory.DataTypeBuilders) { dataTypes.Add(db.Assembly.GetType(db.ClassName, true, true)); } } else { taskTypes = new ArrayList(1); taskTypes.Add(Type.GetType(ForType, true, true)); dataTypes = new ArrayList(); } MemoryStream ms = new MemoryStream(); WriteSchema(ms, (Type[]) taskTypes.ToArray(typeof(Type)), (Type[]) dataTypes.ToArray(typeof(Type)), TargetNamespace); // reset position of memorystream ms.Position = 0; // let's validate whether we emitted a valid XML Schema try { XmlSchema schema = XmlSchema.Read(ms, null); schema.Compile(null); } catch (XmlSchemaException ex) { throw new BuildException ("The generated XML schema is not valid.", Location, ex); } // reset position of memorystream ms.Position = 0; FileIOPermission FilePermission = new FileIOPermission(FileIOPermissionAccess.AllAccess, OutputFile.FullName); FilePermission.Assert(); using (FileStream file = File.Open(OutputFile.FullName, FileMode.Create, FileAccess.Write, FileShare.Read)) { byte[] buffer = new byte[4096]; int bytesRead = ms.Read(buffer, 0, buffer.Length); while (bytesRead != 0) { file.Write(buffer, 0, bytesRead); bytesRead = ms.Read(buffer, 0, buffer.Length); } file.Flush(); file.Close(); } Log(Level.Info, "Wrote schema to '{0}'.", OutputFile.FullName); } #endregion Override implementation of Task #region Public Static Methods /// /// Creates a NAnt Schema for given types /// /// The output stream to save the schema to. If , writing is ignored, no exception generated. /// The list of tasks to generate XML Schema for. /// The list of datatypes to generate XML Schema for. /// The target namespace to output. /// The new NAnt Schema. public static XmlSchema WriteSchema(System.IO.Stream stream, Type[] tasks, Type[] dataTypes, string targetNS) { NAntSchemaGenerator gen = new NAntSchemaGenerator(tasks, dataTypes, targetNS); if (!gen.Schema.IsCompiled) { gen.Compile(); } if (stream != null) { gen.Schema.Write(stream); } return gen.Schema; } #endregion Public Static Methods #region Protected Static Methods protected static string GenerateIDFromType(Type type) { return type.ToString().Replace("+", "-").Replace("[", "_").Replace("]", "_"); } /// /// Creates a new instance. /// /// The name of the attribute. /// Value indicating whether the attribute should be required. /// The new instance. protected static XmlSchemaAttribute CreateXsdAttribute(string name, bool required) { XmlSchemaAttribute newAttr = new XmlSchemaAttribute(); newAttr.Name= name; if (required) { newAttr.Use = XmlSchemaUse.Required; } else { newAttr.Use = XmlSchemaUse.Optional; } return newAttr; } /// /// Creates a new instance. /// /// The minimum value to allow for this choice /// The maximum value to allow, Decimal.MaxValue sets it to 'unbound' /// The new instance. protected static XmlSchemaSequence CreateXsdSequence(Decimal min, Decimal max) { XmlSchemaSequence newSeq = new XmlSchemaSequence(); newSeq.MinOccurs = min; if (max != Decimal.MaxValue) { newSeq.MaxOccurs = max; } else { newSeq.MaxOccursString = "unbounded"; } return newSeq; } protected static XmlNode[] TextToNodeArray(string text) { XmlDocument doc = new XmlDocument(); return new XmlNode[1] {doc.CreateTextNode(text)}; } #endregion Protected Static Methods private class NAntSchemaGenerator { #region Private Instance Fields private IDictionary _nantComplexTypes; private XmlSchemaComplexType _targetCT; private XmlSchema _nantSchema = new XmlSchema(); #endregion Private Instance Fields #region Public Instance Constructors /// /// Creates a new instance of the /// class. /// /// Tasks for which a schema should be generated. /// Data Types for which a schema should be generated. /// The namespace to use. /// http://tempuri.org/nant.xsd /// public NAntSchemaGenerator(Type[] tasks, Type[] dataTypes, string targetNS) { //setup namespace stuff if (targetNS != null) { _nantSchema.TargetNamespace = targetNS; _nantSchema.Namespaces.Add("nant", _nantSchema.TargetNamespace); } // add XSD namespace so that all xsd elements are prefix'd _nantSchema.Namespaces.Add("xs", XmlSchema.Namespace); _nantSchema.ElementFormDefault = XmlSchemaForm.Qualified; // initialize stuff _nantComplexTypes = new HybridDictionary(tasks.Length + dataTypes.Length); XmlSchemaAnnotation schemaAnnotation = new XmlSchemaAnnotation(); XmlSchemaDocumentation schemaDocumentation = new XmlSchemaDocumentation(); string doc = String.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("String_SchemaGenerated"), DateTime.Now); schemaDocumentation.Markup = TextToNodeArray(doc); schemaAnnotation.Items.Add(schemaDocumentation); _nantSchema.Items.Add(schemaAnnotation); // create temp list of taskcontainer Complex Types ArrayList taskContainerComplexTypes = new ArrayList(4); XmlSchemaComplexType containerCT = FindOrCreateComplexType(typeof(TaskContainer)); if (containerCT.Particle == null) { // just create empty sequence to which elements will // be added later containerCT.Particle = CreateXsdSequence(0, Decimal.MaxValue); } taskContainerComplexTypes.Add(containerCT); // create temp list of task Complex Types ArrayList dataTypeComplexTypes = new ArrayList(dataTypes.Length); foreach (Type t in dataTypes) { dataTypeComplexTypes.Add(FindOrCreateComplexType(t)); } foreach (Type t in tasks) { XmlSchemaComplexType taskCT = FindOrCreateComplexType(t); // allow any tasks... if (t.IsSubclassOf(typeof(TaskContainer))) { taskContainerComplexTypes.Add(taskCT); } } Compile(); // update the taskcontainerCTs to allow any other task and the // list of tasks generated foreach(XmlSchemaComplexType ct in taskContainerComplexTypes) { XmlSchemaSequence seq = ct.Particle as XmlSchemaSequence; if (seq != null) { seq.Items.Add(CreateTaskListComplexType(tasks).Particle); } else { logger.Error("Unable to fixup complextype with children. Particle is not XmlSchemaSequence"); } } Compile(); // create target ComplexType _targetCT = CreateTaskListComplexType(tasks, dataTypes, false); _targetCT.Name = "Target"; // This is a response to Bug#: 3058913. If not considered neccessary, remove line below. _targetCT.IsMixed = true; // name attribute _targetCT.Attributes.Add(CreateXsdAttribute("name", true)); // depends attribute _targetCT.Attributes.Add(CreateXsdAttribute("depends", false)); // description attribute _targetCT.Attributes.Add(CreateXsdAttribute("description", false)); // if attribute _targetCT.Attributes.Add(CreateXsdAttribute("if", false)); // unless attribute _targetCT.Attributes.Add(CreateXsdAttribute("unless", false)); _nantSchema.Items.Add(_targetCT); Compile(); // Generate project Element and ComplexType XmlSchemaElement projectElement = new XmlSchemaElement(); projectElement.Name = "project"; XmlSchemaComplexType projectCT = CreateTaskListComplexType(tasks, dataTypes, true); projectElement.SchemaType = projectCT; //name attribute projectCT.Attributes.Add(CreateXsdAttribute("name", true)); //default attribute projectCT.Attributes.Add(CreateXsdAttribute("default", false)); //basedir attribute projectCT.Attributes.Add(CreateXsdAttribute("basedir", false)); _nantSchema.Items.Add(projectElement); Compile(); } #endregion Public Instance Constructors #region Public Instance Properties public XmlSchema Schema { get { if (!_nantSchema.IsCompiled) { Compile(); } return _nantSchema; } } #endregion Public Instance Properties #region Public Instance Methods public void Compile() { _nantSchema.Compile(new ValidationEventHandler(ValidationEH)); } #endregion Public Instance Methods #region Protected Instance Methods protected XmlSchemaComplexType CreateTaskListComplexType(Type[] tasks) { return CreateTaskListComplexType(tasks, new Type[0], false); } protected XmlSchemaComplexType CreateTaskListComplexType(Type[] tasks, Type[] dataTypes, bool includeProjectLevelItems) { XmlSchemaComplexType tasklistCT = new XmlSchemaComplexType(); XmlSchemaChoice choice = new XmlSchemaChoice(); choice.MinOccurs = 0; choice.MaxOccursString = "unbounded"; tasklistCT.Particle = choice; foreach (Type t in tasks) { XmlSchemaElement taskElement = new XmlSchemaElement(); string typeId = GenerateIDFromType(t); XmlSchemaComplexType taskCT = FindComplexTypeByID(typeId); taskElement.Name = GetTaskName(t); taskElement.SchemaTypeName = taskCT.QualifiedName; choice.Items.Add(taskElement); } foreach (Type t in dataTypes) { XmlSchemaElement dataTypeElement = new XmlSchemaElement(); string typeId = GenerateIDFromType(t); XmlSchemaComplexType dataTypeCT = FindComplexTypeByID(typeId); dataTypeElement.Name = GetDataTypeName(t); dataTypeElement.SchemaTypeName = dataTypeCT.QualifiedName; choice.Items.Add(dataTypeElement); } if (includeProjectLevelItems) { XmlSchemaElement targetElement = new XmlSchemaElement(); targetElement.Name = "target"; targetElement.SchemaTypeName = _targetCT.QualifiedName; choice.Items.Add(targetElement); } // allow elements from other namespaces XmlSchemaAny otherNamespaceAny = new XmlSchemaAny(); otherNamespaceAny.MinOccurs = 0; otherNamespaceAny.MaxOccurs = Decimal.MaxValue; otherNamespaceAny.Namespace = "##other"; otherNamespaceAny.ProcessContents = XmlSchemaContentProcessing.Strict; choice.Items.Add(otherNamespaceAny); return tasklistCT; } protected void ValidationEH(object sender, ValidationEventArgs args) { if (args.Severity == XmlSeverityType.Warning) { logger.Info("WARNING: "); } else if (args.Severity == XmlSeverityType.Error) { logger.Error("ERROR: "); } XmlSchemaComplexType source = args.Exception.SourceSchemaObject as XmlSchemaComplexType; logger.Info(args.ToString()); if (source != null) { logger.Info(string.Format(CultureInfo.InvariantCulture, "{0}", source.Name)); } } protected XmlSchemaComplexType FindComplexTypeByID(string id) { if (_nantComplexTypes.Contains(id)) { return (XmlSchemaComplexType)_nantComplexTypes[id]; } return null; } protected XmlSchemaComplexType FindOrCreateComplexType(Type t) { XmlSchemaComplexType ct; string typeId = GenerateIDFromType(t); ct = FindComplexTypeByID(typeId); if (ct != null) { return ct; } ct = new XmlSchemaComplexType(); ct.Name = typeId; // Force mixed attribute for tasks names in the mixedTaskNames array. Fixes Bug#: 3058913 if (Array.IndexOf(mixedTaskNames, ct.Name) != -1) { ct.IsMixed = true; } // add complex type to collection immediately to avoid stack // overflows, when we allow a type to be nested _nantComplexTypes.Add(typeId, ct); #if NOT_IMPLEMENTED // // TODO - add task/type documentation in the future // ct.Annotation = new XmlSchemaAnnotation(); XmlSchemaDocumentation doc = new XmlSchemaDocumentation(); ct.Annotation.Items.Add(doc); doc.Markup = ...; #endif XmlSchemaSequence group1 = null; XmlSchemaObjectCollection attributesCollection = ct.Attributes; foreach (MemberInfo memInfo in t.GetMembers(BindingFlags.Instance | BindingFlags.Public)) { if (memInfo.DeclaringType.Equals(typeof(object))) { continue; } //Check for any return type that is derived from Element // add Attributes TaskAttributeAttribute taskAttrAttr = (TaskAttributeAttribute) Attribute.GetCustomAttribute(memInfo, typeof(TaskAttributeAttribute), false); BuildElementAttribute buildElemAttr = (BuildElementAttribute) Attribute.GetCustomAttribute(memInfo, typeof(BuildElementAttribute), false); if (taskAttrAttr != null) { XmlSchemaAttribute newAttr = CreateXsdAttribute(taskAttrAttr.Name, taskAttrAttr.Required); attributesCollection.Add(newAttr); } else if (buildElemAttr != null) { // Create individial choice for any individual child Element Decimal min = 0; if (buildElemAttr.Required) { min = 1; } XmlSchemaElement childElement = new XmlSchemaElement(); childElement.MinOccurs = min; childElement.MaxOccurs = 1; childElement.Name = buildElemAttr.Name; //XmlSchemaGroupBase elementGroup = CreateXsdSequence(min, Decimal.MaxValue); Type childType; // We will only process child elements if they are defined for Properties or Fields, this should be enforced by the AttributeUsage on the Attribute class if (memInfo is PropertyInfo) { childType = ((PropertyInfo) memInfo).PropertyType; } else if (memInfo is FieldInfo) { childType = ((FieldInfo) memInfo).FieldType; } else if (memInfo is MethodInfo) { MethodInfo method = (MethodInfo) memInfo; if (method.GetParameters().Length == 1) { childType = method.GetParameters()[0].ParameterType; } else { throw new ApplicationException("Method should have one parameter."); } } else { throw new ApplicationException("Member Type != Field/Property/Method"); } BuildElementArrayAttribute buildElementArrayAttribute = (BuildElementArrayAttribute) Attribute.GetCustomAttribute(memInfo, typeof(BuildElementArrayAttribute), false); // determine type of child elements if (buildElementArrayAttribute != null) { if (buildElementArrayAttribute.ElementType == null) { if (childType.IsArray) { childType = childType.GetElementType(); } else { Type elementType = null; // locate Add method with 1 parameter, type of that parameter is parameter type foreach (MethodInfo method in childType.GetMethods(BindingFlags.Public | BindingFlags.Instance)) { if (method.Name == "Add" && method.GetParameters().Length == 1) { ParameterInfo parameter = method.GetParameters()[0]; elementType = parameter.ParameterType; break; } } childType = elementType; } } else { childType = buildElementArrayAttribute.ElementType; } if (childType == null || !typeof(Element).IsAssignableFrom(childType)) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1140"), memInfo.DeclaringType.FullName, memInfo.Name)); } } BuildElementCollectionAttribute buildElementCollectionAttribute = (BuildElementCollectionAttribute) Attribute.GetCustomAttribute(memInfo, typeof(BuildElementCollectionAttribute), false); if (buildElementCollectionAttribute != null) { XmlSchemaComplexType collectionType = new XmlSchemaComplexType(); XmlSchemaSequence sequence = new XmlSchemaSequence(); collectionType.Particle = sequence; sequence.MinOccurs = 0; sequence.MaxOccursString = "unbounded"; XmlSchemaElement itemType = new XmlSchemaElement(); itemType.Name = buildElementCollectionAttribute.ChildElementName; itemType.SchemaTypeName = FindOrCreateComplexType(childType).QualifiedName; sequence.Items.Add(itemType); childElement.SchemaType = collectionType; } else { childElement.SchemaTypeName = FindOrCreateComplexType(childType).QualifiedName; } // lazy init of sequence if (group1 == null) { group1 = CreateXsdSequence(0, Decimal.MaxValue); ct.Particle = group1; } group1.Items.Add(childElement); } } // allow attributes from other namespace ct.AnyAttribute = new XmlSchemaAnyAttribute(); ct.AnyAttribute.Namespace = "##other"; ct.AnyAttribute.ProcessContents = XmlSchemaContentProcessing.Skip; Schema.Items.Add(ct); Compile(); return ct; } #endregion Protected Instance Methods #region Private Instance Methods private string GetTaskName(Type t) { TaskNameAttribute[] attrs = (TaskNameAttribute[])t.GetCustomAttributes(typeof(TaskNameAttribute), false); if (attrs.Length == 1) { return attrs[0].Name; } else { return null; } } private string GetDataTypeName(Type t) { ElementNameAttribute[] attrs = (ElementNameAttribute[]) t.GetCustomAttributes(typeof(ElementNameAttribute), false); if (attrs.Length == 1) { return attrs[0].Name; } else { return null; } } #endregion Private Instance Methods } } } nant-0.92-rc1/src/NAnt.Core/Tasks/TStampTask.cs0000644000175000017500000003303011757302273021014 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Gerry Shaw (gerry_shaw@yahoo.com) // Chris Jenkin (oneinchhard@hotmail.com) using System; using System.Globalization; using NAnt.Core.Attributes; using NAnt.Core.Types; namespace NAnt.Core.Tasks { /// /// Sets properties with the current date and time. /// /// /// /// By default the displays the current date /// and time and sets the following properties: /// /// /// tstamp.date to yyyyMMdd /// tstamp.time to HHmm /// tstamp.now using the default DateTime.ToString() method /// /// /// To set an additional property with a custom date/time use the /// and attributes. /// To set a number of additional properties with the exact same date and /// time use the nested element (see example). /// /// /// The date and time string displayed by the /// uses the computer's default long date and time string format. You /// might consider setting these to the /// ISO 8601 standard /// for date and time notation. /// /// /// /// Set the build.date property. /// /// /// ]]> /// /// /// /// Set a number of properties for Ant like compatibility. /// /// /// /// /// ///
/// ]]> /// /// [TaskName("tstamp")] public class TStampTask : Task { #region Private Instance Fields private string _property; private string _pattern; private FormatterCollection _formatters = new FormatterCollection(); #endregion Private Instance Fields #region Public Instance Properties /// /// The property to receive the date/time string in the given pattern. /// [TaskAttribute("property", Required=false)] public string Property { get { return _property; } set { _property = value; } } /// The date/time pattern to be used. /// /// The following table lists the standard format characters for each standard pattern. The format characters are case-sensitive; for example, 'g' and 'G' represent slightly different patterns. /// /// /// Format Character /// Description Example Format Pattern (en-US) /// /// dMM/dd/yyyy /// Ddddd, dd MMMM yyyy /// fdddd, dd MMMM yyyy HH:mm /// Fdddd, dd MMMM yyyy HH:mm:ss /// gMM/dd/yyyy HH:mm /// GMM/dd/yyyy HH:mm:ss /// m, MMMMM dd /// r, Rddd, dd MMM yyyy HH':'mm':'ss 'GMT' /// syyyy'-'MM'-'dd'T'HH':'mm':'ss /// tHH:mm /// THH:mm:ss /// uyyyy'-'MM'-'dd HH':'mm':'ss'Z' /// Udddd, dd MMMM yyyy HH:mm:ss /// y, Yyyyy MMMM /// /// The following table lists the patterns that can be combined to construct custom patterns. The patterns are case-sensitive; for example, "MM" is recognized, but "mm" is not. If the custom pattern contains white-space characters or characters enclosed in single quotation marks, the output string will also contain those characters. Characters not defined as part of a format pattern or as format characters are reproduced literally. /// /// /// Format /// Pattern Description /// /// dThe day of the month. Single-digit days will not have a leading zero. /// ddThe day of the month. Single-digit days will have a leading zero. /// dddThe abbreviated name of the day of the week. /// ddddThe full name of the day of the week. /// MThe numeric month. Single-digit months will not have a leading zero. /// MMThe numeric month. Single-digit months will have a leading zero. /// MMMThe abbreviated name of the month. /// MMMMThe full name of the month. /// yThe year without the century. If the year without the century is less than 10, the year is displayed with no leading zero. /// yyThe year without the century. If the year without the century is less than 10, the year is displayed with a leading zero. /// yyyyThe year in four digits, including the century. /// ggThe period or era. This pattern is ignored if the date to be formatted does not have an associated period or era string. /// hThe hour in a 12-hour clock. Single-digit hours will not have a leading zero. /// hhThe hour in a 12-hour clock. Single-digit hours will have a leading zero. /// HThe hour in a 24-hour clock. Single-digit hours will not have a leading zero. /// HHThe hour in a 24-hour clock. Single-digit hours will have a leading zero. /// mThe minute. Single-digit minutes will not have a leading zero. /// mmThe minute. Single-digit minutes will have a leading zero. /// sThe second. Single-digit seconds will not have a leading zero. /// ssThe second. Single-digit seconds will have a leading zero. /// fThe fraction of a second in single-digit precision. The remaining digits are truncated. /// ffThe fraction of a second in double-digit precision. The remaining digits are truncated. /// fffThe fraction of a second in three-digit precision. The remaining digits are truncated. /// ffffThe fraction of a second in four-digit precision. The remaining digits are truncated. /// fffffThe fraction of a second in five-digit precision. The remaining digits are truncated. /// ffffffThe fraction of a second in six-digit precision. The remaining digits are truncated. /// fffffffThe fraction of a second in seven-digit precision. The remaining digits are truncated. /// tThe first character in the AM/PM designator. /// ttThe AM/PM designator. /// zThe time zone offset ("+" or "-" followed by the hour only). Single-digit hours will not have a leading zero. For example, Pacific Standard Time is "-8". /// zzThe time zone offset ("+" or "-" followed by the hour only). Single-digit hours will have a leading zero. For example, Pacific Standard Time is "-08". /// zzzThe full time zone offset ("+" or "-" followed by the hour and minutes). Single-digit hours and minutes will have leading zeros. For example, Pacific Standard Time is "-08:00". /// :The default time separator. /// /The default date separator. /// \ cPattern Where c is any character. Displays the character literally. To display the backslash character, use "\\". /// /// [TaskAttribute("pattern", Required=false)] public string Pattern { get { return _pattern; } set { _pattern = value; } } [BuildElementArray("formatter")] public FormatterCollection Formatters { get { return _formatters; } } #endregion Public Instance Properties #region Override implementation of Task protected override void ExecuteTask() { // get and print current date DateTime now = DateTime.Now; Log(Level.Info, "{0} {1}.", now.ToLongDateString(), now.ToLongTimeString()); // set default properties Properties["tstamp.date"] = now.ToString("yyyyMMdd", CultureInfo.InvariantCulture); Properties["tstamp.time"] = now.ToString("HHmm", CultureInfo.InvariantCulture); Properties["tstamp.now"] = now.ToString(CultureInfo.InvariantCulture); // set custom property if (_property != null && _pattern != null) { Properties[_property] = now.ToString(_pattern, CultureInfo.InvariantCulture); Log(Level.Verbose, "{0} = {1}.", _property, Properties[_property].ToString(CultureInfo.InvariantCulture)); } // set properties set in formatters nested elements foreach (Formatter f in Formatters) { if (IfDefined && !UnlessDefined) { Properties[f.Property] = now.ToString(f.Pattern, CultureInfo.InvariantCulture); Log(Level.Verbose, "{0} = {1}.", f.Property, Properties[f.Property].ToString(CultureInfo.InvariantCulture)); } } } #endregion Override implementation of Task } } nant-0.92-rc1/src/NAnt.Core/Tasks/MailTask.cs0000644000175000017500000006573511757302273020507 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Jay Turpin (jayturpin@hotmail.com) // Gerry Shaw (gerry_shaw@yahoo.com) // Gert Driesen (drieseng@users.sourceforge.net) // Ryan Boggs (rmboggs@users.sourceforge.net) using System; using System.Globalization; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Net; using System.Net.Mail; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.Core.Tasks { /// /// Sends an SMTP message. /// /// /// /// Text and text files to include in the message body may be specified as /// well as binary attachments. /// /// /// /// /// Sends an email from nant@sourceforge.net to three recipients /// with a subject about the attachments. The body of the message will be /// the combined contents of all .txt files in the base directory. /// All zip files in the base directory will be included as attachments. /// The message will be sent using the smtpserver.anywhere.com SMTP /// server. /// /// /// /// /// /// /// /// /// /// /// ]]> /// /// /// /// /// Sends an email from a gmail account to multiple recipients. This example /// illustrates how to add a recipient's name to an email address. /// /// /// /// ]]> /// /// /// Email addresses in any of the lists (to, cc, bcc, from) can be in one of /// the five listed formats below. /// /// /// /// Full Name <address@abcxyz.com> /// /// /// <address@abcxyz.com> Full Name /// /// /// (Full Name) address@abcxyz.com /// /// /// address@abcxyz.com (Full Name) /// /// /// address@abcxyz.com /// /// /// /// Remember to use &gt; and &lt; XML entities for the angle brackets. /// /// [TaskName("mail")] public class MailTask : Task { #region Private Instance Fields private string _from; private string _replyTo; private string _toList; private string _ccList; private string _bccList; private string _mailHost = "localhost"; private string _subject = ""; private string _message = ""; private string _userName = ""; private string _passWord = ""; private bool _isBodyHtml = false; private bool _enableSsl = false; private int _portNumber = 25; private FileSet _files = new FileSet(); private FileSet _attachments = new FileSet(); #endregion Private Instance Fields #region Public Instance Properties /// /// Email address of sender. /// [TaskAttribute("from", Required=true)] [StringValidator(AllowEmpty=false)] public string From { get { return _from; } set { _from = StringUtils.ConvertEmptyToNull(value); } } /// /// Semicolon-separated list of recipient email addresses. /// [TaskAttribute("tolist")] public string ToList { get { return _toList; } set { _toList = value; } } /// /// Reply to email address. /// [TaskAttribute("replyto")] public string ReplyTo { get { return _replyTo; } set { _replyTo = value; } } /// /// Semicolon-separated list of CC: recipient email addresses. /// [TaskAttribute("cclist")] public string CcList { get { return _ccList; } set { _ccList = value; } } /// /// Semicolon-separated list of BCC: recipient email addresses. /// [TaskAttribute("bcclist")] public string BccList { get { return _bccList; } set { _bccList = value; } } /// /// Host name of mail server. The default is localhost. /// [TaskAttribute("mailhost")] public string Mailhost { get { return _mailHost; } set { _mailHost = StringUtils.ConvertEmptyToNull(value); } } /// /// The port number used to connect to the mail server. /// The default is 25. /// [TaskAttribute("mailport")] [Int32Validator] public int Port { get { return _portNumber; } set { _portNumber = value; } } /// /// Indicates whether or not ssl should be used to /// connect to the smtp host. /// [TaskAttribute("ssl")] [BooleanValidator] public bool EnableSsl { get { return _enableSsl; } set { _enableSsl = value; } } /// /// Text to send in body of email message. /// [TaskAttribute("message")] public string Message { get { return _message; } set { _message = StringUtils.ConvertEmptyToNull(value); } } /// /// Text to send in subject line of email message. /// [TaskAttribute("subject")] public string Subject { get { return _subject; } set { _subject = StringUtils.ConvertEmptyToNull(value); } } /// /// Indicates whether or not the body of the email is in /// html format. The default value is false. /// [TaskAttribute("isbodyhtml")] [BooleanValidator] public bool IsBodyHtml { get { return _isBodyHtml; } set { _isBodyHtml = value; } } /// /// The username to use when connecting to the smtp host. /// [TaskAttribute("user")] public string UserName { get { return _userName; } set { _userName = value; } } /// /// The password to use when connecting to the smtp host. /// [TaskAttribute("password")] public string Password { get { return _passWord; } set { _passWord = value; } } /// /// Format of the message. The default is . /// [TaskAttribute("format")] [Obsolete("The format attribute is deprecated. Please use isbodyhtml instead", false)] public MailFormat Format { get { if (IsBodyHtml) { return MailFormat.Html; } return MailFormat.Text; } set { if (!Enum.IsDefined(typeof(MailFormat), value)) { throw new ArgumentException(string.Format( CultureInfo.InvariantCulture, "An invalid format {0} was specified.", value)); } else { if (value.Equals(MailFormat.Html)) { IsBodyHtml = true; } else { IsBodyHtml = false; } } } } /// /// Files that are transmitted as part of the body of the email message. /// [BuildElement("files")] public FileSet Files { get { return _files; } set { _files = value; } } /// /// Attachments that are transmitted with the message. /// [BuildElement("attachments")] public FileSet Attachments { get { return _attachments; } set { _attachments = value; } } #endregion Public Instance Properties #region Override implementation of Task /// /// Initializes task and ensures the supplied attributes are valid. /// protected override void Initialize() { if (String.IsNullOrEmpty(ToList) && String.IsNullOrEmpty(CcList) && String.IsNullOrEmpty(BccList)) { throw new BuildException("There must be at least one name in" + " the \"tolist\", \"cclist\" or \"bcclist\" attributes" + " of the task.", Location); } } /// /// This is where the work is done. /// protected override void ExecuteTask() { MailMessage mailMessage = new MailMessage(); // Gather any email addresses provided by the task. MailAddressCollection toAddrs = ParseAddresses(ToList); MailAddressCollection ccAddrs = ParseAddresses(CcList); MailAddressCollection bccAddrs = ParseAddresses(BccList); // If any addresses were specified in the to, cc, and/or bcc // list, add them to the mailMessage object. foreach (MailAddress toAddr in toAddrs) { mailMessage.To.Add(toAddr); } foreach (MailAddress ccAddr in ccAddrs) { mailMessage.CC.Add(ccAddr); } foreach (MailAddress bccAddr in bccAddrs) { mailMessage.Bcc.Add(bccAddr); } // If a reply to address was specified, add it to the // mailMessage object. Starting with .NET 4.0, the // ReplyTo property was deprecated in favor of // ReplyToList. if (!String.IsNullOrEmpty(ReplyTo)) { #if NET_4_0 MailAddressCollection replyAddrs = ParseAddresses(ReplyTo); if (replyAddrs.Count > 0) { foreach (MailAddress replyAddr in replyAddrs) { mailMessage.ReplyToList.Add(replyAddr); } } #else mailMessage.ReplyTo = ConvertStringToMailAddress(ReplyTo); #endif } // Add the From and Subject lines to the mailMessage object. mailMessage.From = ConvertStringToMailAddress(this.From); mailMessage.Subject = this.Subject; // Indicate whether or not the body of the email is in html format. mailMessage.IsBodyHtml = this.IsBodyHtml; // ensure base directory is set, even if fileset was not initialized // from XML if (Files.BaseDirectory == null) { Files.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } if (Attachments.BaseDirectory == null) { Attachments.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } // begin build message body StringWriter bodyWriter = new StringWriter(CultureInfo.InvariantCulture); if (!String.IsNullOrEmpty(Message)) { bodyWriter.WriteLine(Message); bodyWriter.WriteLine(); } // append file(s) to message body foreach (string fileName in Files.FileNames) { try { string content = ReadFile(fileName); if (!String.IsNullOrEmpty(content)) { bodyWriter.Write(content); bodyWriter.WriteLine(string.Empty); } } catch (Exception ex) { Log(Level.Warning, string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1135"), fileName, ex.Message)); } } // add message body to mailMessage string bodyText = bodyWriter.ToString(); if (bodyText.Length != 0) { mailMessage.Body = bodyText; } // add attachments to message foreach (string fileName in Attachments.FileNames) { try { Attachment attachment = new Attachment(fileName); mailMessage.Attachments.Add(attachment); } catch (Exception ex) { Log(Level.Warning, string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1136"), fileName, ex.Message)); } } Log(Level.Info, "Sending mail..."); Log(Level.Verbose, "To: {0}", mailMessage.To); Log(Level.Verbose, "Cc: {0}", mailMessage.CC); Log(Level.Verbose, "Bcc: {0}", mailMessage.Bcc); Log(Level.Verbose, "Subject: {0}", mailMessage.Subject); // Initialize a new SmtpClient object to sent email through. #if NET_4_0 // Starting with .NET 4.0, SmtpClient implements IDisposable. using (SmtpClient smtp = new SmtpClient(this.Mailhost)) { #else SmtpClient smtp = new SmtpClient(this.Mailhost); #endif // send message try { // If username and password attributes are provided, // use the information as the network credentials. // Otherwise, use the default credentials (the information // used by the user to login to the machine. if (!String.IsNullOrEmpty(this.UserName) && !String.IsNullOrEmpty(this.Password)) { smtp.Credentials = new NetworkCredential(this.UserName, this.Password); } else { // Mono does not implement the UseDefaultCredentials // property in the SmtpClient class. So only set the // property when NAnt is run on .NET. Otherwise, // use an emtpy NetworkCredential object as the // SmtpClient credentials. if (PlatformHelper.IsMono) { smtp.Credentials = new NetworkCredential(); } else { smtp.UseDefaultCredentials = true; } } // Set the ssl and the port information. smtp.EnableSsl = this.EnableSsl; smtp.Port = this.Port; // Send the email. smtp.Send(mailMessage); } catch (Exception ex) { StringBuilder msg = new StringBuilder(); msg.AppendLine("Error enountered while sending mail message."); msg.AppendLine("Make sure that the following information is valid:"); msg.AppendFormat(CultureInfo.InvariantCulture, "Mailhost: {0}", this.Mailhost).AppendLine(); msg.AppendFormat(CultureInfo.InvariantCulture, "Mailport: {0}", this.Port.ToString()).AppendLine(); msg.AppendFormat(CultureInfo.InvariantCulture, "Use SSL: {0}", this.EnableSsl.ToString()).AppendLine(); if (!String.IsNullOrEmpty(this.UserName) && !String.IsNullOrEmpty(this.Password)) { msg.AppendFormat(CultureInfo.InvariantCulture, "Username: {0}", this.UserName).AppendLine(); } else { msg.AppendLine("Using default credentials"); } throw new BuildException("Error sending mail:" + Environment.NewLine + msg.ToString(), Location, ex); } #if NET_4_0 } #endif } #endregion Override implementation of Task #region Private Instance Methods /// /// Reads a text file and returns the content /// in a string. /// /// The file to read content of. /// /// The content of the specified file. /// private string ReadFile(string filename) { using (StreamReader reader = new StreamReader(File.OpenRead(filename))) { string result = reader.ReadToEnd(); reader.Close(); return result; } } /// /// Converts an email address or a series of email addresses from /// a object to a new /// object. /// /// /// A list of email addresses separated by a semicolon. /// /// /// A new object /// containing the addresses from . /// private MailAddressCollection ParseAddresses(string addresses) { // Initialize the MailAddressCollection object that will be // returned by this method. MailAddressCollection results = new MailAddressCollection(); // Make sure the addresses string is not null before attempting // to parse. if (!String.IsNullOrEmpty(addresses)) { // If the addresses parameter contains a semicolon, that means // that more than one email address is present and needs to be parsed. if (addresses.Contains(";")) { string[] parsedAddresses = addresses.Split(new char[] { ';' }); foreach (string item in parsedAddresses) { results.Add(ConvertStringToMailAddress(item)); } } // Otherwise, pass the addresses param string to the new // MailAddressCollection if it is not null or empty. else { results.Add(ConvertStringToMailAddress(addresses)); } } return results; } /// /// Converts a object containing /// email address information to a /// object. /// /// /// /// Email address information passed to this method should be in /// one of five formats. /// /// /// /// Full Name <address@abcxyz.com> /// /// /// <address@abcxyz.com> Full Name /// /// /// (Full Name) address@abcxyz.com /// /// /// address@abcxyz.com (Full Name) /// /// /// address@abcxyz.com /// /// /// /// If the full name of the intended recipient (or sender) is provided, /// that information is included in the resulting /// object. /// /// /// /// The string that contains the address to parse. /// /// /// A new MailAddress object containing the information from /// . /// private MailAddress ConvertStringToMailAddress(string address) { // Convert the email address parameter from html encoded to // normal string. Makes validation easier. string plainAddress = UnescapeXmlCodes(address); // Local vars to temporarily hold names and email addresses string resultingName = null; string resultingEmail = null; // String array containing all of the regex strings used to // locate the email address in the parameter string. string[] validators = new string[] { // Format: Full Name @"^(?.+)\s<(?[^<>\(\)\s]+@[^<>\(\)\s]+\.[^<>\(\)\s]+)>$", // Format: Full Name @"^<(?[^<>\(\)\s]+@[^<>\(\)\s]+\.[^\s]+)>\s(?.+)$", // Format: (Full Name) address@abcxyz.com @"^\((?.+)\)\s(?[^<>\(\)\s]+@[^<>\(\)\s]+\.[^<>\(\)\s]+)$", // Format: address@abcxyz.com (Full Name) @"^(?[^<>\(\)\s]+@[^<>\(\)\s]+\.[^\s]+)\s\((?.+)\)$" }; // Loop through each regex string to find the one that the // email address matches. foreach (string reg in validators) { // Create the regex object and try to match // the email address with the current regex // string. Regex currentRegex = new Regex(reg); Match email = currentRegex.Match(plainAddress); // If the match is considered successful, load // the temp string vars with the found email/fullname // information to use when creating a new MailAddress // object. Then break from the loop. if (email.Success) { resultingEmail = email.Groups["email"].Value.Trim(); resultingName = email.Groups["fullname"].Value.Trim(); break; } } try { // Setup a new MailAddress to return. MailAddress result; // If both the temp name and email string vars contain values, initialize // the result MailAddress var with both values. if (!String.IsNullOrEmpty(resultingName) && !String.IsNullOrEmpty(resultingEmail)) { result = new MailAddress(resultingEmail, resultingName); } // If only the temp email string var contains a value, initialize // the result MailAddress var with just that value else if (!String.IsNullOrEmpty(resultingEmail)) { result = new MailAddress(resultingEmail); } // Otherwise, try initializing the result MailAddress var with the original // address that was passed to the method. else { result = new MailAddress(plainAddress); } // Return the result. return result; } // If the MailAddress var throws a Format exception because of a bad email address, // throw a build exception. catch (FormatException) { throw new BuildException( String.Format(CultureInfo.InvariantCulture, "{0} is not a recognized email address", plainAddress)); } // Rethrow any other exceptions. catch (Exception) { throw; } } /// /// Simple method that converts an XML escaped string back to its unescaped /// format. /// /// /// An html encoded string. /// /// /// The decoded format of the html encoded string. /// private string UnescapeXmlCodes(string value) { return value.Replace(""", "\"") .Replace("&", "&") .Replace("'", "'") .Replace("<", "<") .Replace(">", ">"); } #endregion Private Instance Methods /// /// Temporary enum replacement of /// to ease transition to newer property flags. /// public enum MailFormat { /// /// Indicates the body of the email is formatted in plain text. /// Text = 0, /// /// Indicates the body of the email is formatted in html. /// Html = 1 } } } nant-0.92-rc1/src/NAnt.Core/Tasks/FailTask.cs0000644000175000017500000001142411757302273020462 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) using System; using System.Xml; using NAnt.Core.Attributes; using NAnt.Core.Util; namespace NAnt.Core.Tasks { /// /// Exits the current build by throwing a , /// optionally printing additional information. /// /// /// /// The cause of the build failure can be specified using the /// attribute or as inline content. /// /// /// Macros in the message will be expanded. /// /// /// /// Exits the current build without giving further information. /// /// /// ]]> /// /// /// /// Exits the current build and writes a message to the build log. /// /// /// ]]> /// /// /// /// Functionally equivalent to the previous example. /// /// Something wrong here. /// ]]> /// /// [TaskName("fail")] public class FailTask : Task { #region Private Instance Fields private string _message; private string _contents; #endregion Private Instance Fields #region Public Instance Properties /// /// A message giving further information on why the build exited. /// /// /// Inline content and are mutually exclusive. /// [TaskAttribute("message")] public string Message { get { return _message; } set { if (!String.IsNullOrEmpty(value)) { if (!String.IsNullOrEmpty(Contents)) { throw new ValidationException("Inline content and the message attribute are mutually exclusive in the task.", Location); } else { _message = value; } } else { _message = null; } } } /// /// Gets or sets the inline content that should be output in the build /// log, giving further information on why the build exited. /// /// /// The inline content that should be output in the build log. /// /// /// Inline content and are mutually exclusive. /// public string Contents { get { return _contents; } set { if (!String.IsNullOrEmpty(value)) { if (!String.IsNullOrEmpty(Message)) { throw new ValidationException("Inline content and the message attribute are mutually exclusive in the task.", Location); } else { _contents = value; } } else { _contents = null; } } } #endregion Public Instance Properties #region Override implementation of Task protected override void ExecuteTask() { const string defaultMessage = "No message."; string message; if (!String.IsNullOrEmpty(Message)) { message = Message; } else if (!String.IsNullOrEmpty(Contents)) { message = Contents; } else { message = defaultMessage; } throw new BuildException(message, Location); } protected override void Initialize() { Contents = Project.ExpandProperties(XmlNode.InnerText, Location); } #endregion Override implementation of Task } } nant-0.92-rc1/src/NAnt.Core/Tasks/LoadFileTask.cs0000644000175000017500000001170011757302273021263 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System.Globalization; using System.IO; using System.Text; using NAnt.Core.Attributes; using NAnt.Core.Filters; using NAnt.Core.Util; namespace NAnt.Core.Tasks { /// /// Load a text file into a single property. /// /// /// /// Unless an encoding is specified, the encoding associated with the /// system's current ANSI code page is used. /// /// /// An UTF-8, little-endian Unicode, and big-endian Unicode encoded text /// file is automatically recognized, if the file starts with the appropriate /// byte order marks. /// /// /// /// /// Load file message.txt into property "message". /// /// /// /// ]]> /// /// /// /// /// Load a file using the "latin-1" encoding. /// /// /// /// ]]> /// /// /// /// /// Load a file, replacing all @NOW@ tokens with the current /// date/time. /// /// /// /// /// /// /// /// /// /// ]]> /// /// [TaskName("loadfile")] public class LoadFileTask : Task { #region Private Instance Fields private FileInfo _file; private Encoding _encoding; private string _property; private FilterChain _filterChain; #endregion Private Instance Fields #region Public Instance Properties /// /// The file to load. /// [TaskAttribute("file", Required=true)] public FileInfo File { get { return _file; } set { _file = value; } } /// /// The name of the property to save the content to. /// [TaskAttribute("property", Required=true)] public string Property { get { return _property; } set { _property = value; } } /// /// The encoding to use when loading the file. The default is the encoding /// associated with the system's current ANSI code page. /// [TaskAttribute("encoding")] public Encoding Encoding { get { return _encoding; } set { _encoding = value; } } /// /// The filterchain definition to use. /// [BuildElement("filterchain")] public FilterChain FilterChain { get { return _filterChain; } set { _filterChain = value; } } #endregion Public Instance Properties #region Override implementation of Task protected override void ExecuteTask() { // make sure file actually exists if (!File.Exists) { throw new BuildException(string.Format(CultureInfo.InstalledUICulture, "File '{0}' does not exist.", File.FullName), Location); } string content = null; try { content = FileUtils.ReadFile(File.FullName, FilterChain, Encoding); } catch (IOException ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1129"), File.FullName), Location, ex); } // add/update property Properties[Property] = content; } #endregion Override implementation of Task } } nant-0.92-rc1/src/NAnt.Core/Tasks/PropertyTask.cs0000644000175000017500000002232311757302273021433 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Scott Hernandez (ScottHernandez@hotmail.com) using System; using System.Collections; using System.Globalization; using NAnt.Core.Attributes; using NAnt.Core.Util; namespace NAnt.Core.Tasks { /// /// Sets a property in the current project. /// /// /// NAnt uses a number of predefined properties. /// /// /// /// Define a debug property with value . /// /// /// /// ]]> /// /// /// /// /// Use the user-defined debug property. /// /// /// /// ]]> /// /// /// /// /// Define a read-only property. This is just like passing in the param /// on the command line. /// /// /// /// ]]> /// /// /// /// /// Define a property, but do not overwrite the value if the property already exists (eg. it was specified on the command line). /// /// /// /// /// /// /// ]]> /// /// /// Executing this build file with the command line option -D:debug=false, /// would cause the value specified on the command line to remain unaltered. /// /// /// /// /// [TaskName("property")] public class PropertyTask : Task { #region Private Instance Fields private string _name; private string _value = string.Empty; private bool _readOnly; private bool _dynamic; private bool _overwrite = true; #endregion Private Instance Fields #region Public Instance Properties /// /// The name of the NAnt property to set. /// [TaskAttribute("name", Required=true)] [StringValidator(AllowEmpty=false)] public string PropertyName { get { return _name; } set { _name = value; } } /// /// The value to assign to the NAnt property. /// [TaskAttribute("value", Required=true, ExpandProperties=false)] [StringValidator(AllowEmpty=true)] public string Value { get { return _value; } set { _value = value; } } /// /// Specifies whether the property is read-only or not. /// The default is . /// [TaskAttribute("readonly", Required=false)] [BooleanValidator()] public bool ReadOnly { get { return _readOnly; } set { _readOnly = value; } } /// /// Specifies whether references to other properties should not be /// expanded when the value of the property is set, but expanded when /// the property is actually used. By default, properties will be /// expanded when set. /// [TaskAttribute("dynamic", Required=false)] [BooleanValidator()] public bool Dynamic { get { return _dynamic; } set { _dynamic = value; } } /// /// Specifies whether the value of a property should be overwritten if /// the property already exists (unless the property is read-only). /// The default is . /// [TaskAttribute("overwrite", Required=false)] [BooleanValidator()] public bool Overwrite { get { return _overwrite; } set { _overwrite = value; } } #endregion Public Instance Properties #region Override implementation of Task protected override void ExecuteTask() { string propertyValue; if (!Dynamic) { propertyValue = Project.ExpandProperties(Value, Location); } else { propertyValue = Value; } // Special check for framework setting. if (PropertyName == "nant.settings.currentframework") { FrameworkInfo newTargetFramework = Project.Frameworks[propertyValue]; // check if target framework exists if (newTargetFramework != null) { if (Project.TargetFramework != null) { if (Project.TargetFramework != newTargetFramework) { Project.TargetFramework = newTargetFramework; // only output message in build log if target // framework is actually changed Log(Level.Info, "Target framework changed to \"{0}\".", newTargetFramework.Description); } } else { Project.TargetFramework = newTargetFramework; Log(Level.Info, "Target framework set to \"{0}\".", newTargetFramework.Description); } return; } else { ArrayList validvalues = new ArrayList(); foreach (FrameworkInfo framework in Project.Frameworks) { validvalues.Add(framework.Name); } string validvaluesare = string.Empty; if (validvalues.Count > 0) { validvaluesare = string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("String_ValidValues"), string.Join(", ", (string[]) validvalues.ToArray(typeof(string)))); } throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1143"), propertyValue, validvaluesare), Location); } } if (!Project.Properties.Contains(PropertyName)) { if (ReadOnly) { Properties.AddReadOnly(PropertyName, propertyValue); } else { Properties[PropertyName] = propertyValue; } if (Dynamic) { Properties.MarkDynamic(PropertyName); } } else { if (Overwrite) { if (Project.Properties.IsReadOnlyProperty(PropertyName)) { // for now, just output a warning when attempting to // overwrite a readonly property // // we should actually be throwing a BuildException here, but // we currently don't have a good mechanism in place to allow // users to specify properties on the command line and provide // default values for these properties in the build file // // users could use either the "overwrite" property or a // "property::exists(...)" unless condition on the // task, but these do not seem to be intuitive for users Log(Level.Warning, "Read-only property \"{0}\" cannot" + " be overwritten.", PropertyName); } else { Properties[PropertyName] = propertyValue; if (Dynamic) { Properties.MarkDynamic(PropertyName); } } } else { Log(Level.Verbose, "Property \"{0}\" already exists, and \"overwrite\" is set to false.", PropertyName); } } } #endregion Override implementation of Task } } nant-0.92-rc1/src/NAnt.Core/Tasks/CallTask.cs0000644000175000017500000001721111757302273020462 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) using NAnt.Core.Attributes; using NAnt.Core.Util; namespace NAnt.Core.Tasks { /// /// Calls a NAnt target in the current project. /// /// /// /// When the is used to execute a target, both that /// target and all its dependent targets will be re-executed. /// /// /// To avoid dependent targets from being executed more than once, two /// options are available: /// /// /// /// /// Add an "unless" attribute with value "${target::has-executed('<target name>')}" /// to the dependent targets. /// /// /// /// /// Set the attribute on the /// to (recommended). /// /// /// /// /// /// /// Call the target "build". /// /// /// /// ]]> /// /// /// /// /// This shows how a project could 'compile' a debug and release build /// using a common compile target. /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// ]]> /// /// /// The parameter of the /// defaults to , /// causing the "init" target to be executed for both /// the "debug" and "release" build. /// /// /// This results in the following build log: /// /// /// build: /// /// init: /// /// [echo] initializing /// /// compile: /// /// [echo] compiling with debug = false /// /// init: /// /// [echo] initializing /// /// compile: /// /// [echo] compiling with debug = true /// /// BUILD SUCCEEDED /// /// /// If the "init" should only be executed once, set the /// attribute of the /// to . /// /// /// The build log would then look like this: /// /// /// build: /// /// init: /// /// [echo] initializing /// /// compile: /// /// [echo] compiling with debug = false /// /// compile: /// /// [echo] compiling with debug = true /// /// BUILD SUCCEEDED /// /// [TaskName("call")] public class CallTask : Task { #region Private Instance Fields private string _target; private bool _force; private bool _cascade = true; #endregion Private Instance Fields #region Public Instance Properties /// /// NAnt target to call. /// [TaskAttribute("target", Required=true)] [StringValidator(AllowEmpty=false)] public string TargetName { get { return _target; } set { _target = StringUtils.ConvertEmptyToNull(value); } } // TO-DO : remove this property after NAnt 0.8.6 or so. /// /// Force an execute even if the target has already been executed. The /// default is . /// [TaskAttribute("force")] [System.Obsolete("Use the \"cascase\" attribute to control whether dependencies should be re-executed.", false)] public bool ForceExecute { get { return _force; } set { _force = value; } } /// /// Execute the specified targets dependencies -- even if they have been /// previously executed. The default is . /// [TaskAttribute("cascade")] public bool CascadeDependencies { get { return _cascade; } set { _cascade = value; } } #endregion Public Instance Properties #region Override implementation of Task /// /// Executes the specified target. /// protected override void ExecuteTask() { Target owningTarget = Parent as Target; if (owningTarget != null) { // topologically sorted list of targets that will be executed TargetCollection targets = Project.TopologicalTargetSort(TargetName, Project.Targets); // check if owning target is part of list of targets that will // be executed again if (targets.Find(owningTarget.Name) != null) { // check if owning target is actually a dependency of the // target that should be executed if (targets.IndexOf(targets.Find(owningTarget.Name)) < targets.IndexOf(targets.Find(TargetName))) { throw new BuildException("Circular dependency: " + targets.ToString(" <- ") + " <- " + owningTarget.Name); } } } Project.Execute(TargetName, CascadeDependencies); } /// /// Makes sure the is not calling its own /// parent. /// protected override void Initialize() { Target target = Project.Targets.Find(TargetName); if (target != null) { Target owningTarget = Parent as Target; if (target == owningTarget) { throw new BuildException("Call task cannot call its own parent.", Location); } } } #endregion Override implementation of Task } } nant-0.92-rc1/src/NAnt.Core/FrameworkInfoDictionary.cs0000644000175000017500000002076711757302273022510 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2002-2003 Scott Hernandez // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian MacLean (imaclean@gmail.com) using System; using System.Collections; namespace NAnt.Core { [Serializable()] public sealed class FrameworkInfoDictionary : IDictionary, ICollection, IEnumerable, ICloneable { #region Private Instance Fields private Hashtable _innerHash; #endregion Private Instance Fields #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public FrameworkInfoDictionary() { _innerHash = new Hashtable(); } public FrameworkInfoDictionary(FrameworkInfoDictionary original) { _innerHash = new Hashtable(original.InnerHash); } public FrameworkInfoDictionary(IDictionary dictionary) { _innerHash = new Hashtable (dictionary); } /// /// Initializes a new instance of the class /// with the specified capacity. /// public FrameworkInfoDictionary(int capacity) { _innerHash = new Hashtable(capacity); } public FrameworkInfoDictionary(IDictionary dictionary, float loadFactor) { _innerHash = new Hashtable(dictionary, loadFactor); } public FrameworkInfoDictionary(IHashCodeProvider codeProvider, IComparer comparer) { _innerHash = new Hashtable(codeProvider, comparer); } public FrameworkInfoDictionary(int capacity, int loadFactor) { _innerHash = new Hashtable(capacity, loadFactor); } public FrameworkInfoDictionary(IDictionary dictionary, IHashCodeProvider codeProvider, IComparer comparer) { _innerHash = new Hashtable (dictionary, codeProvider, comparer); } public FrameworkInfoDictionary(int capacity, IHashCodeProvider codeProvider, IComparer comparer) { _innerHash = new Hashtable (capacity, codeProvider, comparer); } public FrameworkInfoDictionary(IDictionary dictionary, float loadFactor, IHashCodeProvider codeProvider, IComparer comparer) { _innerHash = new Hashtable (dictionary, loadFactor, codeProvider, comparer); } public FrameworkInfoDictionary(int capacity, float loadFactor, IHashCodeProvider codeProvider, IComparer comparer) { _innerHash = new Hashtable (capacity, loadFactor, codeProvider, comparer); } #endregion Public Instance Constructors #region Internal Instance Properties internal Hashtable InnerHash { get { return _innerHash; } set { _innerHash = value ; } } #endregion Internal Instance Properties #region Implementation of IDictionary public FrameworkInfoDictionaryEnumerator GetEnumerator() { return new FrameworkInfoDictionaryEnumerator(this); } IDictionaryEnumerator IDictionary.GetEnumerator() { return new FrameworkInfoDictionaryEnumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Remove(string key) { _innerHash.Remove(key); } void IDictionary.Remove(object key) { Remove((string) key); } public bool Contains(string key) { return _innerHash.Contains(key); } bool IDictionary.Contains(object key) { return Contains((string)key); } public void Clear() { _innerHash.Clear(); } public void Add(string key, FrameworkInfo value) { _innerHash.Add (key, value); } void IDictionary.Add(object key, object value) { Add((string) key, (FrameworkInfo) value); } public bool IsReadOnly { get { return _innerHash.IsReadOnly; } } public FrameworkInfo this[string key] { get { return (FrameworkInfo) _innerHash[key]; } set { _innerHash[key] = value; } } object IDictionary.this[object key] { get { return this[(string) key]; } set { this[(string) key] = (FrameworkInfo) value; } } public ICollection Values { get { return _innerHash.Values; } } public ICollection Keys { get { return _innerHash.Keys; } } public bool IsFixedSize { get { return _innerHash.IsFixedSize; } } #endregion Implementation of IDictionary #region Implementation of ICollection void ICollection.CopyTo(Array array, int index) { _innerHash.CopyTo(array, index); } public bool IsSynchronized { get { return _innerHash.IsSynchronized; } } public int Count { get { return _innerHash.Count; } } public object SyncRoot { get { return _innerHash.SyncRoot; } } public void CopyTo(FrameworkInfo[] array, int index) { _innerHash.CopyTo(array, index); } #endregion Implementation of ICollection #region Implementation of ICloneable public FrameworkInfoDictionary Clone() { FrameworkInfoDictionary clone = new FrameworkInfoDictionary(); clone.InnerHash = (Hashtable) _innerHash.Clone(); return clone; } object ICloneable.Clone() { return Clone(); } #endregion Implementation of ICloneable #region HashTable Methods public bool ContainsKey (string key) { return _innerHash.ContainsKey(key); } public bool ContainsValue(FrameworkInfo value) { return _innerHash.ContainsValue(value); } public static FrameworkInfoDictionary Synchronized(FrameworkInfoDictionary nonSync) { FrameworkInfoDictionary sync = new FrameworkInfoDictionary(); sync.InnerHash = Hashtable.Synchronized(nonSync.InnerHash); return sync; } #endregion HashTable Methods } public class FrameworkInfoDictionaryEnumerator : IDictionaryEnumerator { #region Private Instance Fields private IDictionaryEnumerator _innerEnumerator; #endregion Private Instance Fields #region Internal Instance Constructors internal FrameworkInfoDictionaryEnumerator(FrameworkInfoDictionary enumerable) { _innerEnumerator = enumerable.InnerHash.GetEnumerator(); } #endregion Internal Instance Constructors #region Implementation of IDictionaryEnumerator public string Key { get { return (string) _innerEnumerator.Key; } } object IDictionaryEnumerator.Key { get { return Key; } } public FrameworkInfo Value { get { return (FrameworkInfo) _innerEnumerator.Value; } } object IDictionaryEnumerator.Value { get { return Value; } } public DictionaryEntry Entry { get { return _innerEnumerator.Entry; } } #endregion Implementation of IDictionaryEnumerator #region Implementation of IEnumerator public void Reset() { _innerEnumerator.Reset(); } public bool MoveNext() { return _innerEnumerator.MoveNext(); } object IEnumerator.Current { get { return _innerEnumerator.Current; } } public FrameworkInfo Current { get { return (FrameworkInfo)((DictionaryEntry)_innerEnumerator.Current).Value; } } #endregion Implementation of IEnumerator } } nant-0.92-rc1/src/NAnt.Core/ElementContainer.cs0000644000175000017500000001175011757302273021135 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2012 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections.Specialized; using System.Globalization; using System.Xml; using NAnt.Core; using NAnt.Core.Util; namespace NAnt.Core { /// /// Executes embedded tasks/elements in the order in which they are defined. /// public class ElementContainer : Element { #region Private Instance Fields private StringCollection _subXMLElements; #endregion Private Instance Fields #region Override implementation of Element /// /// Gets a value indicating whether the element is performing additional /// processing using the that was use to /// initialize the element. /// /// /// , as a is /// responsable for creating tasks from the nested build elements. /// protected override bool CustomXmlProcessing { get { return true;} } #endregion Override implementation of Element #region Public Instance Methods public virtual void Execute() { ExecuteChildTasks(); } #endregion Public Instance Methods #region Protected Instance Methods /// /// Creates and executes the embedded (child XML nodes) elements. /// protected virtual void ExecuteChildTasks() { foreach (XmlNode childNode in XmlNode) { //we only care about xmlnodes (elements) that are of the right namespace. if (!(childNode.NodeType == XmlNodeType.Element) || !childNode.NamespaceURI.Equals(NamespaceManager.LookupNamespace("nant"))) { continue; } // ignore any private xml elements (by def. this includes any property with a BuildElementAttribute (name). if (IsPrivateXmlElement(childNode)) { continue; } if (TypeFactory.TaskBuilders.Contains(childNode.Name)) { // create task instance Task task = CreateChildTask(childNode); // for now, we should assume null tasks are because of // incomplete metadata about the XML if (task != null) { task.Parent = this; // execute task task.Execute(); } } else if (TypeFactory.DataTypeBuilders.Contains(childNode.Name)) { // we are an datatype declaration DataTypeBase dataType = CreateChildDataTypeBase(childNode); Log(Level.Debug, "Adding a {0} reference with id '{1}'.", childNode.Name, dataType.ID); if (!Project.DataTypeReferences.Contains(dataType.ID)) { Project.DataTypeReferences.Add(dataType.ID, dataType); } else { Project.DataTypeReferences[dataType.ID] = dataType; // overwrite with the new reference. } } else { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1071"), childNode.Name), Project.GetLocation(childNode)); } } } protected virtual Task CreateChildTask(XmlNode node) { return Project.CreateTask(node); } protected virtual DataTypeBase CreateChildDataTypeBase(XmlNode node) { return Project.CreateDataTypeBase(node); } protected virtual bool IsPrivateXmlElement(XmlNode node) { return (_subXMLElements != null && _subXMLElements.Contains(node.Name)); } protected virtual void AddPrivateXmlElementName(string name) { if (_subXMLElements == null) _subXMLElements = new StringCollection(); if (!_subXMLElements.Contains(name)) _subXMLElements.Add(name); } #endregion Protected Instance Methods } } nant-0.92-rc1/src/NAnt.Core/ExpressionEvaluator.cs0000644000175000017500000001212111757302273021714 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Jaroslaw Kowalski (jkowalski@users.sourceforge.net) using System; using System.IO; using System.Collections; using System.Reflection; using System.Globalization; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Extensibility; using NAnt.Core.Util; namespace NAnt.Core { [FunctionSet("property", "NAnt")] public class ExpressionEvaluator : ExpressionEvalBase { #region Private Instance Fields private PropertyDictionary _properties; private Hashtable _state; private Stack _visiting; #endregion Private Instance Fields #region Public Instance Constructors public ExpressionEvaluator(Project project, PropertyDictionary properties, Hashtable state, Stack visiting) : base(project) { _properties = properties; _state = state; _visiting = visiting; } #endregion Public Instance Constructors #region Override implementation of ExpressionEvalBase protected override object EvaluateProperty(string propertyName) { return GetPropertyValue(propertyName); } protected override object EvaluateFunction(MethodInfo methodInfo, object[] args) { try { if (methodInfo.IsStatic) { return methodInfo.Invoke(null, args); } else if (methodInfo.DeclaringType.IsAssignableFrom(typeof(ExpressionEvaluator))) { return methodInfo.Invoke(this, args); } else { // create new instance. ConstructorInfo constructor = methodInfo.DeclaringType.GetConstructor(new Type[] {typeof(Project), typeof(PropertyDictionary)}); object o = constructor.Invoke(new object[] {Project, _properties}); return methodInfo.Invoke(o, args); } } catch (TargetInvocationException ex) { if (ex.InnerException != null) { // throw actual exception throw ex.InnerException; } // re-throw exception throw; } } #endregion Override implementation of ExpressionEvalBase #region Public Instance Methods /// /// Gets the value of the specified property. /// /// The name of the property to get the value of. /// /// The value of the specified property. /// [Function("get-value")] public string GetPropertyValue(string propertyName) { if (_properties.IsDynamicProperty(propertyName)) { string currentState = (string)_state[propertyName]; // check for circular references if (currentState == PropertyDictionary.Visiting) { // Currently visiting this node, so have a cycle throw PropertyDictionary.CreateCircularException(propertyName, _visiting); } _visiting.Push(propertyName); _state[propertyName] = PropertyDictionary.Visiting; string propertyValue = _properties.GetPropertyValue(propertyName); if (propertyValue == null) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1053"), propertyName)); } Location propertyLocation = Location.UnknownLocation; // TODO - get the proper location of the property declaration propertyValue = _properties.ExpandProperties(propertyValue, propertyLocation, _state, _visiting); _visiting.Pop(); _state[propertyName] = PropertyDictionary.Visited; return propertyValue; } else { string propertyValue = _properties.GetPropertyValue(propertyName); if (propertyValue == null) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1053"), propertyName)); } return propertyValue; } } #endregion Public Instance Methods } } nant-0.92-rc1/src/NAnt.Core/Location.cs0000644000175000017500000001125111757302273017445 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian MacLean (imaclean@gmail.com) // Gerry Shaw (gerry_shaw@yahoo.com) using System; using System.Globalization; using System.IO; using System.Text; namespace NAnt.Core { /// /// Stores the file name, line number and column number to record a position /// in a text file. /// [Serializable] public class Location { #region Private Instance Fields private string _fileName; private int _lineNumber; private int _columnNumber; #endregion Private Instance Fields public static readonly Location UnknownLocation = new Location(); /// /// Creates a location consisting of a file name, line number and /// column number. /// /// /// can be a local URI resource, e.g., file:///C:/WINDOWS/setuplog.txt. /// public Location(string fileName, int lineNumber, int columnNumber) { Init(fileName, lineNumber, columnNumber); } /// /// Creates a location consisting of a file name. /// /// /// can be a local URI resource, e.g., file:///C:/WINDOWS/setuplog.txt. /// public Location(string fileName) { Init(fileName, 0, 0); } /// /// Creates an "unknown" location. /// private Location() { Init(null, 0, 0); } /// Private Init function. private void Init(string fileName, int lineNumber, int columnNumber) { if (fileName != null) { try { // first check to see if fileName is a URI Uri uri = new Uri(fileName); fileName = uri.LocalPath; } catch { try { // must be a simple filename fileName = Path.GetFullPath(fileName); } catch (ArgumentException) { // when filename is an invalid path, just leave it as // is } } } _fileName = fileName; _lineNumber = lineNumber; _columnNumber = columnNumber; } /// /// Gets a string containing the file name for the location. /// /// /// The file name includes both the file path and the extension. /// public string FileName { get { return _fileName; } } /// /// Gets the line number for the location. /// /// /// Lines start at 1. Will be zero if not specified. /// public int LineNumber { get { return _lineNumber; } } /// /// Gets the column number for the location. /// /// /// Columns start a 1. Will be zero if not specified. /// public int ColumnNumber { get { return _columnNumber; } } /// /// Returns the file name, line number and a trailing space. An error /// message can be appended easily. For unknown locations, returns /// an empty string. /// public override string ToString() { StringBuilder sb = new StringBuilder(""); if (_fileName != null) { sb.Append(_fileName); if (_lineNumber != 0) { sb.Append(String.Format(CultureInfo.InvariantCulture, "({0},{1})", _lineNumber, _columnNumber)); } sb.Append(":"); } return sb.ToString(); } } } nant-0.92-rc1/src/NAnt.Core/LocationMap.cs0000644000175000017500000002542711757302273020115 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian MacLean (imaclean@gmail.com) // Gerry Shaw (gerry_shaw@yahoo.com) using System; using System.Collections; using System.Globalization; using System.IO; using System.Text.RegularExpressions; using System.Xml; using System.Xml.XPath; using NAnt.Core.Util; namespace NAnt.Core { /// /// Maps XML nodes to the text positions from their original source. /// [Serializable()] internal class LocationMap { #region Private Instance Fields // The LocationMap uses a hash table to map filenames to resolve specific maps. private Hashtable _fileMap = new Hashtable(); #endregion Private Instance Fields #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public LocationMap() { } #endregion Public Instance Constructors #region Public Instance Methods /// /// Determines if a file has been loaded by the current project. /// /// The file to check. /// /// if the specified file has already been loaded /// by the current project; otherwise, . /// public bool FileIsMapped(string fileOrUri){ Uri uri = new Uri(fileOrUri); return _fileMap.ContainsKey(uri.AbsoluteUri); } /// /// Adds an to the map. /// /// /// An can only be added to the map once. /// public void Add(XmlDocument doc) { // check for non-backed documents if (String.IsNullOrEmpty(doc.BaseURI)) { return; } // convert URI to absolute URI Uri uri = new Uri(doc.BaseURI); string fileName = uri.AbsoluteUri; // prevent duplicate mapping if (FileIsMapped(fileName)) { // do not re-map the file a 2nd time throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "XML document '{0}' has already been mapped.", fileName)); } Hashtable map = new Hashtable(); string parentXPath = "/"; // default to root string previousXPath = ""; int previousDepth = 0; // Load text reader. XmlTextReader reader = new XmlTextReader(fileName); try { map.Add((object) "/", (object) new TextPosition(1, 1)); ArrayList indexAtDepth = new ArrayList(); // loop thru all nodes in the document while (reader.Read()) { // Ignore nodes we aren't interested in if ((reader.NodeType != XmlNodeType.Whitespace) && (reader.NodeType != XmlNodeType.EndElement) && (reader.NodeType != XmlNodeType.ProcessingInstruction) && (reader.NodeType != XmlNodeType.XmlDeclaration) && (reader.NodeType != XmlNodeType.DocumentType)) { int level = reader.Depth; string currentXPath = ""; // If we are higher than before if (reader.Depth < previousDepth) { // Clear vars for new depth string[] list = parentXPath.Split('/'); string newXPath = ""; // once appended to / will be root node for (int j = 1; j < level+1; j++) { newXPath += "/" + list[j]; } // higher than before so trim xpath\ parentXPath = newXPath; // one up from before // clear indexes for depth greater than ours indexAtDepth.RemoveRange(level+1, indexAtDepth.Count - (level+1)); } else if (reader.Depth > previousDepth) { // we are lower parentXPath = previousXPath; } // End depth setup // Setup up index array // add any needed extra items ( usually only 1 ) // would have used array but not sure what maximum depth will be beforehand for (int index = indexAtDepth.Count; index < level+1; index++) { indexAtDepth.Add(0); } // Set child index if ((int) indexAtDepth[level] == 0) { // first time thru indexAtDepth[level] = 1; } else { indexAtDepth[level] = (int) indexAtDepth[level] + 1; // lower so append to xpath } // Do actual XPath generation if (parentXPath.EndsWith("/")) { currentXPath = parentXPath; } else { currentXPath = parentXPath + "/"; // add seperator } // Set the final XPath currentXPath += "child::node()[" + indexAtDepth[level] + "]"; // Add to our hash structures map.Add((object) currentXPath, (object) new TextPosition(reader.LineNumber, reader.LinePosition)); // setup up loop vars for next iteration previousXPath = currentXPath; previousDepth = reader.Depth; } } } finally { reader.Close(); } // add map at the end to prevent adding maps that had errors _fileMap.Add(fileName, map); } /// /// Returns the in the XML file for the given node. /// /// /// The must be from an /// that has been added to the map. /// public Location GetLocation(XmlNode node) { // check for non-backed documents if (String.IsNullOrEmpty(node.BaseURI)) return Location.UnknownLocation; // return empty location because we have a fileless node. // convert URI to absolute URI Uri uri = new Uri(node.BaseURI); string fileName = uri.AbsoluteUri; if (!FileIsMapped(fileName)) { throw new ArgumentException("Xml node has not been mapped."); } // find xpath for node Hashtable map = (Hashtable) _fileMap[fileName]; string xpath = GetXPathFromNode(node); if (!map.ContainsKey(xpath)) { throw new ArgumentException("Xml node has not been mapped."); } TextPosition pos = (TextPosition) map[xpath]; Location location = new Location(fileName, pos.Line, pos.Column); return location; } #endregion Public Instance Methods #region Private Instance Methods private string GetXPathFromNode(XmlNode node) { // IM TODO review this algorithm - tidy up XPathNavigator nav = node.CreateNavigator(); string xpath = ""; int index = 0; while (nav.NodeType.ToString(CultureInfo.InvariantCulture) != "Root") { // loop thru children until we find ourselves XPathNavigator navParent = nav.Clone(); navParent.MoveToParent(); int parentIndex = 0; navParent.MoveToFirstChild(); if (navParent.IsSamePosition(nav)) { index = parentIndex; } while (navParent.MoveToNext()) { parentIndex++; if (navParent.IsSamePosition(nav)) { index = parentIndex; } } nav.MoveToParent(); // do loop condition here index++; // Convert to 1 based index string thisNode = "child::node()[" + index.ToString(CultureInfo.InvariantCulture) + "]"; if (xpath.Length == 0) { xpath = thisNode; } else { // build xpath string xpath = thisNode + "/" + xpath; } } // prepend slash to ... xpath = "/" + xpath; return xpath; } #endregion Private Instance Methods /// /// Represents a position in the build file. /// [Serializable()] private struct TextPosition { #region Public Instance Constructors /// /// Initializes a new instance of the /// with the speified line and column. /// /// The line coordinate of the position. /// The column coordinate of the position. public TextPosition(int line, int column) { Line = line; Column = column; } #endregion Public Instance Constructors #region Public Instance Fields /// /// The line coordinate of the position. /// public int Line; /// /// The column coordinate of the position. /// public int Column; #endregion Public Instance Fields } } } nant-0.92-rc1/src/NAnt.Core/FrameworkTypes.cs0000644000175000017500000000537511757302273020671 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2008 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net.be) using System; using System.ComponentModel; namespace NAnt.Core { /// /// Defines the types of frameworks. /// [Flags] public enum FrameworkTypes { /// /// Frameworks that are supported on the current platform, but are not /// installed. /// NotInstalled = 1, /// /// Frameworks that are installed on the current system. /// Installed = 2, /// /// Retrieves installation state attributes. /// [EditorBrowsable(EditorBrowsableState.Advanced)] InstallStateMask = NotInstalled | Installed, /// /// Frameworks that typically target full desktop devices. /// Desktop = 4, /// /// Frameworks that target compact devices. /// Compact = 8, /// /// Frameworks that run in a browser. /// Browser = 16, /// /// Retrieves device attributes. /// [EditorBrowsable(EditorBrowsableState.Advanced)] DeviceMask = Desktop | Compact | Browser, /// /// Frameworks released as part of the open-source Mono /// project. /// Mono = 32, /// /// Frameworks released by Microsoft. /// MS = 64, /// /// Retrieves vendor attributes. /// [EditorBrowsable(EditorBrowsableState.Advanced)] VendorMask = Mono | MS, /// /// All frameworks supported on the current platform, regarless of their /// installation state, target device or vendor. /// All = Installed | NotInstalled } } nant-0.92-rc1/src/NAnt.Core/TargetCollection.cs0000644000175000017500000000764711757302273021155 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Scott Hernandez (ScottHernandez@hotmail.com) using System; using System.Collections; using System.Globalization; using NAnt.Core.Util; namespace NAnt.Core { [Serializable()] public class TargetCollection : ArrayList { private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); public virtual int Add(Target t){ // throw an exception if an attempt is made to add a null target if (t == null) { throw new BuildException("Null Target!"); } logger.Debug(string.Format( CultureInfo.InvariantCulture, ResourceUtils.GetString("String_AddingTarget"), t.Name)); // check for existing target with same name. if (Find(t.Name) == null) { return base.Add(t); } else { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1073"), t.Name)); } } /// /// Finds a target by name. /// /// The name of the target to find. /// /// The with the specified name, or /// if no exists with /// the given name. /// public Target Find(string targetName) { foreach (Target target in this) { if (target.Name == targetName) return target; } return null; } /// /// Gets the names of the targets in the /// combined into one list separated by the given . /// /// /// A that contains a list of the names of the /// targets in the , separated by /// the specified . /// public string ToString(string separator) { string[] targetNames = new string[Count]; for (int i = 0; i < Count; i++) { targetNames[i] = ((Target) this[i]).Name; } return string.Join(separator, targetNames); } public override int Add(object value) { // call typed version above. return Add(value as Target); } #region Override implementation of Object /// /// Gets the names of the targets in the /// combined into one comma-separated list. /// /// /// A that contains a comma-separated list of the /// names of the targets in the . /// public override string ToString() { return ToString(", "); } #endregion Override implementation of Object } }nant-0.92-rc1/src/NAnt.Core/Configuration/0000755000175000017500000000000011757310030020143 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.Core/Configuration/DirectoryName.cs0000644000175000017500000000056111757302272023252 0ustar jtaylorjtaylorusing System; using NAnt.Core; using NAnt.Core.Attributes; namespace NAnt.Core.Configuration { [Serializable] internal class DirectoryName : ConditionalElement { private string _name; [TaskAttribute("name", Required=true)] public string DirName { get { return _name; } set { _name = value; } } } } nant-0.92-rc1/src/NAnt.Core/Configuration/DirList.cs0000644000175000017500000000363411757302272022063 0ustar jtaylorjtaylorusing System; using System.IO; using NAnt.Core; using NAnt.Core.Attributes; namespace NAnt.Core.Configuration { /// /// Represents an explicitly named list of directories. /// /// /// A is useful when you want to capture a list of /// directories regardless whether they currently exist. /// [Serializable] internal class DirList : Element { private DirectoryInfo _baseDirectory; private DirectoryName[] _directoryNames; /// /// The base of the directory of this dirlist. The default is the project /// base directory. /// [TaskAttribute("dir")] public DirectoryInfo Directory { get { if (_baseDirectory == null) { return new DirectoryInfo(Project.BaseDirectory); } return _baseDirectory; } set { _baseDirectory = value; } } [BuildElementArray("directory")] public DirectoryName[] DirectoryNames { get { return _directoryNames; } set { _directoryNames = value; } } public string[] GetDirectories() { string baseDir = Directory.FullName; return GetDirectories(baseDir); } internal string[] GetDirectories(string baseDir) { if (baseDir == null) throw new ArgumentNullException("baseDir"); if (_directoryNames == null) { return new string[0]; } string[] directories = new string[_directoryNames.Length]; for (int i = 0; i < _directoryNames.Length; i++) { DirectoryName dirName = _directoryNames [i]; directories [i] = Path.Combine (baseDir, dirName.DirName); } return directories; } } } nant-0.92-rc1/src/NAnt.Core/Configuration/ManagedExecutionMode.cs0000644000175000017500000000343311757302272024533 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2007 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Types; namespace NAnt.Core.Configuration { [Serializable] internal class ManagedExecutionMode : Element { private RuntimeEngine _engine; private EnvironmentSet _environmentSet = new EnvironmentSet(); [BuildElement("engine")] public RuntimeEngine Engine { get { return _engine; } set { _engine = value; } } /// /// Gets the collection of environment variables that should be passed /// to external programs that are launched. /// /// /// /// The collection of environment variables that should be passed /// to external programs that are launched. /// /// [BuildElement("environment")] public EnvironmentSet Environment { get { return _environmentSet; } } } } nant-0.92-rc1/src/NAnt.Core/Configuration/RuntimeEngine.cs0000644000175000017500000000212411757302272023253 0ustar jtaylorjtaylorusing System; using System.Globalization; using System.IO; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Types; namespace NAnt.Core.Configuration { [Serializable] internal class RuntimeEngine : Element { private FileInfo _program; private ArgumentCollection _arguments = new ArgumentCollection(); [TaskAttribute ("program", Required=true)] public FileInfo Program { get { return _program; } set { _program = value; } } /// /// The command-line arguments for the runtime engine. /// [BuildElementArray("arg")] public ArgumentCollection Arguments { get { return _arguments; } } protected override void Initialize() { base.Initialize (); if (Program != null & !Program.Exists) { throw new ArgumentException(string.Format( CultureInfo.InvariantCulture, "Runtime engine '{0}'" + " does not exist.", Program.FullName)); } } } } nant-0.92-rc1/src/NAnt.Core/Configuration/ManagedExecutionModes.cs0000644000175000017500000000221511757302272024713 0ustar jtaylorjtaylorusing System; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Types; namespace NAnt.Core.Configuration { [Serializable] internal class ManagedExecutionModes : Element { private ManagedExecutionMode _autoMode; private ManagedExecutionMode _strictMode; [BuildElement("auto")] public ManagedExecutionMode Auto { get { return _autoMode; } set { _autoMode = value; } } [BuildElement("strict")] public ManagedExecutionMode Strict { get { return _strictMode; } set { _strictMode = value; } } public ManagedExecutionMode GetExecutionMode (ManagedExecution managed) { switch (managed) { case ManagedExecution.Default: return null; case ManagedExecution.Auto: return Auto; case ManagedExecution.Strict: if (Strict != null) return Strict; return Auto; default: throw new NotImplementedException(); } } } } nant-0.92-rc1/src/NAnt.Core/Configuration/Runtime.cs0000644000175000017500000000104511757302272022126 0ustar jtaylorjtaylorusing System; using NAnt.Core; using NAnt.Core.Attributes; namespace NAnt.Core.Configuration { [Serializable] internal class Runtime : Element { private ManagedExecutionModes _modes = new ManagedExecutionModes (); private DirList _probingPaths = new DirList(); [BuildElement("probing-paths")] public DirList ProbingPaths { get { return _probingPaths; } } [BuildElement("modes")] public ManagedExecutionModes Modes { get { return _modes; } } } } nant-0.92-rc1/src/NAnt.Core/Configuration/ConditionalElement.cs0000644000175000017500000000653511757302272024271 0ustar jtaylorjtaylorusing System; using System.Reflection; using System.Xml; using NAnt.Core; using NAnt.Core.Attributes; namespace NAnt.Core.Configuration { [Serializable] internal class ConditionalElement : Element { #region Private Instance Fields private bool _ifDefined = true; private bool _unlessDefined; #endregion Private Instance Fields #region Protected Instance Constructors protected override void InitializeXml(XmlNode elementNode, PropertyDictionary properties, FrameworkInfo framework) { XmlNode = elementNode; ConditionalConfigurator configurator = new ConditionalConfigurator( this, elementNode, properties, framework); configurator.Initialize(); } #endregion Protected Instance Constructors #region Protected Instance Properties [TaskAttribute("if")] protected bool IfDefined { get { return _ifDefined; } set { _ifDefined = value; } } [TaskAttribute("unless")] protected bool UnlessDefined { get { return _unlessDefined; } set { _unlessDefined = value; } } #endregion Protected Instance Properties #region Internal Instance Properties internal bool Enabled { get { return IfDefined && !UnlessDefined; } } #endregion Internal Instance Properties #region Override implementation of Element #endregion Override implementation of Element class ConditionalConfigurator : AttributeConfigurator { public ConditionalConfigurator(ConditionalElement element, XmlNode elementNode, PropertyDictionary properties, FrameworkInfo targetFramework) : base (element, elementNode, properties, targetFramework) { Type currentType = element.GetType(); PropertyInfo ifdefined = currentType.GetProperty("IfDefined", BindingFlags.NonPublic | BindingFlags.Instance); InitializeAttribute(ifdefined); if (!element.IfDefined) { _enabled = false; } else { PropertyInfo unlessDefined = currentType.GetProperty( "UnlessDefined", BindingFlags.NonPublic | BindingFlags.Instance); InitializeAttribute(unlessDefined); _enabled = !element.UnlessDefined; } if (!_enabled) { // since we will not be processing other attributes or // child nodes, clear these collections to avoid // errors for unrecognized attributes/elements UnprocessedAttributes.Clear(); UnprocessedChildNodes.Clear(); } } protected override bool InitializeAttribute(PropertyInfo propertyInfo) { if (!_enabled) return true; return base.InitializeAttribute (propertyInfo); } protected override void InitializeOrderedChildElements() { if (!_enabled) return; base.InitializeOrderedChildElements (); } private readonly bool _enabled = true; } } } nant-0.92-rc1/src/NAnt.Core/Filters/0000755000175000017500000000000011757310030016744 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.Core/Filters/ExpandProperties.cs0000644000175000017500000001453211757302273022606 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // using System; using System.Text; using System.Xml; using NAnt.Core.Attributes; using NAnt.Core.Util; namespace NAnt.Core.Filters { /// /// Parses NAnt properties and expressions /// /// /// /// This filter parses any NAnt properties or expressions found in its input, /// inlining their values in its output. /// /// /// Note: Due to limitations on buffering, expressions longer than 2048 /// characters are not guaranteed to be expanded. /// /// Filters are intended to be used as a element of a . /// /// /// Replace all properties with their corresponding values. /// /// /// ]]> /// /// [ElementName("expandproperties")] public class ExpandProperties : Filter { #region Private Instance Fields /// /// Holds data for expression expansion between input and output. /// private StringBuilder _buffer; #endregion Private Instance Fields #region Private Static Fields // Due to limitations on buffering, expressions longer than this number of characters are not guaranteed to be expanded. const ushort MAX_RELIABLE_EXPRESSION_LENGTH = 2048; // A buffer this size ensures that any expression up to MAX_RELIABLE_EXPRESSION_LENGTH will be sent in one piece to ExpandExpression. const int BUFFER_LENGTH = MAX_RELIABLE_EXPRESSION_LENGTH * 2 - 1; #endregion Private Static Fields #region Private Instance Properties /// /// Determines whether we've passed the end of our data. /// private bool AtEnd { get { return _buffer.Length == 0; } } #endregion Private Instance Properties #region Override implementation of Filter /// /// Called after construction and after properties are set. Allows /// for filter initialization. /// public override void InitializeFilter() { _buffer = new StringBuilder(BUFFER_LENGTH); ReplenishBuffer(); } #endregion Override implementation of Filter #region Override implementation of ChainableReader /// /// Reads the next character applying the filter logic. /// /// Char as an int or -1 if at the end of the stream public override int Read() { int temp = Peek(); if (! AtEnd) { Advance(); } return temp; } /// /// Reads the next character applying the filter logic without advancing the current position in the stream. /// /// Char as an int or -1 if at the end of the stream public override int Peek() { if (AtEnd) { return -1; } else { return _buffer[0]; } } #endregion Override implementation of ChainableReader #region Private Instance Methods /// /// Moves to the next character. /// private void Advance() { if (AtEnd) { throw new IndexOutOfRangeException(ResourceUtils.GetString("String_EndOfOutput")); } _buffer.Remove(0, 1); if (_buffer.Length == (MAX_RELIABLE_EXPRESSION_LENGTH - 1)) { ReplenishBuffer(); } } /// /// Refills the buffer, running our input through /// .) /// private void ReplenishBuffer () { // Fill buffer from input. bool isMoreInput = true; int curCharInt; while ((_buffer.Length < BUFFER_LENGTH) && isMoreInput) { curCharInt = base.Read(); if (curCharInt != -1) { _buffer.Append((char) curCharInt); } else { isMoreInput = false; } } string bufferBeforeExpand = _buffer.ToString(); int lastExprStartIndex = bufferBeforeExpand.LastIndexOf("${"); int lastExprEndIndex = bufferBeforeExpand.LastIndexOf('}'); string bufferAfterExpand; // Expand properties from input into buffer for output. if (lastExprEndIndex < lastExprStartIndex) { // There's an unfinished expression - don't attempt to expand it yet. Perhaps it will all fit in the buffer next time around. bufferAfterExpand = Project.Properties.ExpandProperties(bufferBeforeExpand.Substring(0, lastExprStartIndex), Location); bufferBeforeExpand = bufferBeforeExpand.Substring(lastExprStartIndex); _buffer = new StringBuilder(bufferAfterExpand, Math.Max(BUFFER_LENGTH, bufferAfterExpand.Length + bufferBeforeExpand.Length)); _buffer.Append(bufferBeforeExpand); } else { // No partial expressions - keep it simple. bufferAfterExpand = Project.Properties.ExpandProperties(bufferBeforeExpand, Location); _buffer = new StringBuilder(bufferAfterExpand, Math.Max(BUFFER_LENGTH, bufferAfterExpand.Length)); } } #endregion Private Instance Methods } } nant-0.92-rc1/src/NAnt.Core/Filters/Support/0000755000175000017500000000000011757310030020420 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.Core/Filters/Support/Filter.cs0000644000175000017500000000451711757302273022215 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // using NAnt.Core.Attributes; namespace NAnt.Core.Filters { /// /// Allows a file's content to be modified while performing an operation. /// public abstract class Filter : ChainableReader { #region Private Instance Fields private bool _ifDefined = true; private bool _unlessDefined; #endregion Private Instance Fields #region Public Instance Properties /// /// If then the filter will be used; otherwise, /// skipped. The default is . /// [TaskAttribute("if")] [BooleanValidator()] public bool IfDefined { get { return _ifDefined; } set { _ifDefined = value; } } /// /// Opposite of . If /// then the filter will be executed; otherwise, skipped. The default /// is . /// [TaskAttribute("unless")] [BooleanValidator()] public bool UnlessDefined { get { return _unlessDefined; } set { _unlessDefined = value; } } #endregion Public Instance Properties #region Public Instance Methods /// /// Called after construction and after properties are set. Allows /// for filter initialization. /// public virtual void InitializeFilter() { } #endregion Public Instance Methods } } nant-0.92-rc1/src/NAnt.Core/Filters/Support/FilterCollection.cs0000644000175000017500000002122311757302273024222 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; namespace NAnt.Core.Filters { /// /// Contains a collection of elements. /// [Serializable()] public class FilterCollection : CollectionBase { #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public FilterCollection() { } /// /// Initializes a new instance of the class /// with the specified instance. /// public FilterCollection(FilterCollection value) { AddRange(value); } /// /// Initializes a new instance of the class /// with the specified array of instances. /// public FilterCollection(Filter[] value) { AddRange(value); } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets the element at the specified index. /// /// The zero-based index of the element to get or set. [System.Runtime.CompilerServices.IndexerName("Item")] public Filter this[int index] { get {return ((Filter)(base.List[index]));} set {base.List[index] = value;} } #endregion Public Instance Properties #region Public Instance Methods /// /// Adds a to the end of the collection. /// /// The to be added to the end of the collection. /// The position into which the new element was inserted. public int Add(Filter item) { return base.List.Add(item); } /// /// Adds the elements of a array to the end of the collection. /// /// The array of elements to be added to the end of the collection. public void AddRange(Filter[] items) { for (int i = 0; (i < items.Length); i = (i + 1)) { Add(items[i]); } } /// /// Adds the elements of a to the end of the collection. /// /// The to be added to the end of the collection. public void AddRange(FilterCollection items) { for (int i = 0; (i < items.Count); i = (i + 1)) { Add(items[i]); } } /// /// Determines whether a is in the collection. /// /// The to locate in the collection. /// /// if is found in the /// collection; otherwise, . /// public bool Contains(Filter item) { return base.List.Contains(item); } /// /// Copies the entire collection to a compatible one-dimensional array, starting at the specified index of the target array. /// /// The one-dimensional array that is the destination of the elements copied from the collection. The array must have zero-based indexing. /// The zero-based index in at which copying begins. public void CopyTo(Filter[] array, int index) { base.List.CopyTo(array, index); } /// /// Retrieves the index of a specified object in the collection. /// /// The object for which the index is returned. /// /// The index of the specified . If the is not currently a member of the collection, it returns -1. /// public int IndexOf(Filter item) { return base.List.IndexOf(item); } /// /// Inserts a into the collection at the specified index. /// /// The zero-based index at which should be inserted. /// The to insert. public void Insert(int index, Filter item) { base.List.Insert(index, item); } /// /// Returns an enumerator that can iterate through the collection. /// /// /// A for the entire collection. /// public new FilterEnumerator GetEnumerator() { return new FilterEnumerator(this); } /// /// Removes a member from the collection. /// /// The to remove from the collection. public void Remove(Filter item) { base.List.Remove(item); } #endregion Public Instance Methods } /// /// Enumerates the elements of a . /// public class FilterEnumerator : IEnumerator { #region Internal Instance Constructors /// /// Initializes a new instance of the class /// with the specified . /// /// The collection that should be enumerated. internal FilterEnumerator(FilterCollection arguments) { IEnumerable temp = (IEnumerable) (arguments); _baseEnumerator = temp.GetEnumerator(); } #endregion Internal Instance Constructors #region Implementation of IEnumerator /// /// Gets the current element in the collection. /// /// /// The current element in the collection. /// public Filter Current { get { return (Filter) _baseEnumerator.Current; } } object IEnumerator.Current { get { return _baseEnumerator.Current; } } /// /// Advances the enumerator to the next element of the collection. /// /// /// if the enumerator was successfully advanced /// to the next element; if the enumerator has /// passed the end of the collection. /// public bool MoveNext() { return _baseEnumerator.MoveNext(); } bool IEnumerator.MoveNext() { return _baseEnumerator.MoveNext(); } /// /// Sets the enumerator to its initial position, which is before the /// first element in the collection. /// public void Reset() { _baseEnumerator.Reset(); } void IEnumerator.Reset() { _baseEnumerator.Reset(); } #endregion Implementation of IEnumerator #region Private Instance Fields private IEnumerator _baseEnumerator; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.Core/Filters/Support/FilterBuilder.cs0000644000175000017500000001065611757302273023525 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Ian MacLean (imaclean@gmail.com) using System; using System.Globalization; using System.Reflection; using System.Security.Permissions; using NAnt.Core.Attributes; using NAnt.Core.Extensibility; namespace NAnt.Core.Filters { public class FilterBuilder : ExtensionBuilder { #region Public Instance Constructors /// /// Creates a new instance of the class /// for the specified class in the specified /// . /// /// /// An for the specified /// is cached for future use. /// /// The containing the . /// The class representing the . public FilterBuilder (Assembly assembly, string className) : this (ExtensionAssembly.Create (assembly), className) { } #endregion Public Instance Constructors #region Internal Instance Constructors /// /// Creates a new instance of the class /// for the specified class in the specified /// . /// /// The containing the . /// The class representing the . internal FilterBuilder(ExtensionAssembly extensionAssembly, string className) : base (extensionAssembly) { _className = className; // get Element name from attribute ElementNameAttribute ElementNameAttribute = (ElementNameAttribute) Attribute.GetCustomAttribute(Assembly.GetType(ClassName), typeof(ElementNameAttribute)); _filterName = ElementNameAttribute.Name; } #endregion Internal Instance Constructors #region Public Instance Properties /// /// Gets the name of the class that can be created /// using this . /// /// /// The name of the class that can be created using /// this . /// public string ClassName { get { return _className; } } /// /// Gets the name of the filter which the /// can create. /// /// /// The name of the task which the can /// create. /// public string FilterName { get { return _filterName; } } #endregion Public Instance Properties #region Public Instance Methods [ReflectionPermission(SecurityAction.Demand, Flags=ReflectionPermissionFlag.NoFlags)] public Filter CreateFilter() { return (Filter) Assembly.CreateInstance( ClassName, true, BindingFlags.Public | BindingFlags.Instance, null, null, CultureInfo.InvariantCulture, null); } #endregion Public Instance Methods #region Private Instance Fields private readonly string _className; private readonly string _filterName; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.Core/Filters/Support/FilterChain.cs0000644000175000017500000002733211757302273023160 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // using System; using System.Collections; using System.Globalization; using System.Reflection; using System.Text; using System.Xml; using NAnt.Core.Attributes; using NAnt.Core.Filters; using NAnt.Core.Tasks; using NAnt.Core.Util; namespace NAnt.Core.Filters { /// /// Represent a chain of NAnt filters that can be applied to a . /// /// /// /// A FilterChain represents a collection of one or more filters that can /// be appled to a such as the . /// In the case of the , the contents of the copied /// files are filtered through each filter specified in the filter chain. /// Filtering occurs in the order the filters are specified with filtered /// output of one filter feeding into another. /// /// /// :--------:--->:----------:--->:----------: ... :----------:--->:--------:
/// :.Source.:--->:.Filter 1.:--->:.Filter 2.: ... :.Filter n.:--->:.target.:
/// :--------:--->:----------:--->:----------: ... :----------:--->:--------:
///
/// /// A list of all filters that come with NAnt is available here. /// /// /// The following tasks support filtering with a FilterChain: /// /// /// /// /// /// /// /// /// ///
/// /// /// Replace all occurrences of @NOW@ with the current date/time and /// replace tabs with spaces in all copied files. /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// ]]> /// /// [Serializable] [ElementName("filterchain")] public class FilterChain : DataTypeBase { #region Private Instance Fields private Encoding _inputEncoding; private FilterCollection _filters = new FilterCollection(); #endregion Private Instance Fields #region Public Instance Properties /// /// The filters to apply. /// [BuildElementArray("filter", ElementType=typeof(Filter))] public FilterCollection Filters { get { return _filters; } } /// /// The encoding to assume when filter-copying files. The default is /// system's current ANSI code page. /// [TaskAttribute("encoding")] [Obsolete("The input encoding should now be specified on the task.", true)] public Encoding InputEncoding { get { return _inputEncoding; } set { _inputEncoding = value; } } #endregion Public Instance Properties #region Override implementation of Element /// /// Initializes all build attributes and child elements. /// /// /// needs to maintain the order in which the /// filters are specified in the build file. /// protected override void InitializeXml(XmlNode elementNode, PropertyDictionary properties, FrameworkInfo framework) { XmlNode = elementNode; FilterChainConfigurator configurator = new FilterChainConfigurator( this, elementNode, properties, framework); configurator.Initialize(); } #endregion Override implementation of Element #region Internal Instance Methods /// /// Used to to instantiate and return the chain of stream based filters. /// /// The that is the source of input to the filter chain. /// /// The is the first /// in the chain, which is based on a physical stream that feeds the chain. /// /// /// The last in the chain. /// internal Filter GetBaseFilter(PhysicalTextReader physicalTextReader) { // if there is no a PhysicalTextReader then the chain is empty if (physicalTextReader == null) { return null; } // the physicalTextReader must be the base filter (Based on a physical stream) if (!physicalTextReader.Base) { throw new BuildException(ResourceUtils.GetString("String_UseBaseFilter"), Location); } // build the chain and place the base filter at the beginning. Filter parentFilter = physicalTextReader; // iterate through the collection of filter elements and instantiate each filter. foreach (Filter filter in Filters) { if (filter.IfDefined && !filter.UnlessDefined) { filter.Chain(parentFilter); filter.InitializeFilter(); parentFilter = filter; } } return parentFilter; } #endregion Internal Instance Methods #region Internal Static Methods /// /// Determines whether a given FilterChain is null or empty. /// /// /// true if is null or empty; /// otherwise, false. /// /// /// The FilterChain to check. /// internal static bool IsNullOrEmpty(FilterChain filterChain) { if (filterChain == null) { return true; } else { return filterChain.Filters.Count <= 0; } } #endregion Internal Static Methods /// /// Configurator that initializes filters in the order in which they've /// been specified in the build file. /// public class FilterChainConfigurator : AttributeConfigurator { public FilterChainConfigurator(Element element, XmlNode elementNode, PropertyDictionary properties, FrameworkInfo targetFramework) : base(element, elementNode, properties, targetFramework) { } protected override bool InitializeBuildElementCollection(System.Reflection.PropertyInfo propertyInfo) { Type elementType = typeof(Filter); BuildElementArrayAttribute buildElementArrayAttribute = (BuildElementArrayAttribute) Attribute.GetCustomAttribute(propertyInfo, typeof(BuildElementArrayAttribute)); if (buildElementArrayAttribute == null || propertyInfo.PropertyType != typeof(FilterCollection)) { return base.InitializeBuildElementCollection(propertyInfo); } XmlNodeList collectionNodes = ElementXml.ChildNodes; // create new array of the required size - even if size is 0 ArrayList list = new ArrayList(collectionNodes.Count); foreach (XmlNode childNode in collectionNodes) { // skip non-nant namespace elements and special elements like comments, pis, text, etc. if (!(childNode.NodeType == XmlNodeType.Element) || !childNode.NamespaceURI.Equals(NamespaceManager.LookupNamespace("nant"))) { continue; } // remove element from list of remaining items UnprocessedChildNodes.Remove(childNode.Name); // initialize child element (from XML or data type reference) Filter filter = TypeFactory.CreateFilter(childNode, Element); list.Add(filter); } MethodInfo addMethod = null; // get array of public instance methods MethodInfo[] addMethods = propertyInfo.PropertyType.GetMethods(BindingFlags.Public | BindingFlags.Instance); // search for a method called 'Add' which accepts a parameter // to which the element type is assignable foreach (MethodInfo method in addMethods) { if (method.Name == "Add" && method.GetParameters().Length == 1) { ParameterInfo parameter = method.GetParameters()[0]; if (parameter.ParameterType.IsAssignableFrom(elementType)) { addMethod = method; break; } } } if (addMethod == null) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1020"), elementType.FullName, propertyInfo.PropertyType.FullName, propertyInfo.Name, Name), Location); } // if value of property is null, create new instance of collection object collection = propertyInfo.GetValue(Element, BindingFlags.Default, null, null, CultureInfo.InvariantCulture); if (collection == null) { if (!propertyInfo.CanWrite) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1093"), buildElementArrayAttribute.Name, Name), Location); } object instance = Activator.CreateInstance( propertyInfo.PropertyType, BindingFlags.Public | BindingFlags.Instance, null, null, CultureInfo.InvariantCulture); propertyInfo.SetValue(Element, instance, BindingFlags.Default, null, null, CultureInfo.InvariantCulture); } // add each element of the arraylist to collection instance foreach (object childElement in list) { addMethod.Invoke(collection, BindingFlags.Default, null, new object[] {childElement}, CultureInfo.InvariantCulture); } return true; } } } } nant-0.92-rc1/src/NAnt.Core/Filters/Support/PhysicalTextReader.cs0000644000175000017500000000245411757302273024532 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // using System; using System.IO; namespace NAnt.Core.Filters { /// /// Represents a physical . That is a reader based /// on a stream. /// /// /// Used by to represent a /// based on a in the chain. /// internal class PhysicalTextReader : Filter { public PhysicalTextReader(TextReader textReader) { base.Chain(textReader); } } } nant-0.92-rc1/src/NAnt.Core/Filters/Support/ChainableReader.cs0000644000175000017500000001206411757302273023755 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // using System; using System.IO; using NAnt.Core.Types; namespace NAnt.Core.Filters { /// /// Functions as a chainable TextReader /// /// /// Implements a abstraction over a TextReader that allows the class to represent /// either a TextReader or another ChainableReader to which it is chained. /// /// By passing a ChainableReader as a constructor paramater it is possiable to /// chain many ChainableReaders together. The last ChainableReader in the chain must /// be based on a TextReader. /// public abstract class ChainableReader : Element, IDisposable { //Delegates for supported common functionality in //encapsulated TextReader and ChainableReader private delegate int internalRead(); private delegate int internalPeek(); private delegate void internalClose(); //Point to the appropriate methods //in a TextReader or a ChainableReader. private internalRead InternalRead; private internalPeek InternalPeek; private internalClose InternalClose; private bool _baseReader; #region Public Instance Properties /// /// Gets a value indicating if the reader is backed by a stream in the /// chain. /// /// /// if the reader is backed by a stream; /// otherwise, . /// public bool Base{ get { return _baseReader; } } #endregion Public Instance Properties #region Public Instance Methods /// /// Makes it so all calls to Read and Peek are passed the ChainableReader /// passed as a parameter. /// /// ChainableReader to forward calls to public virtual void Chain(ChainableReader parentChainedReader) { if (parentChainedReader == null) { throw new ArgumentNullException("parentChainedReader", "Argument can not be null"); } //Assign delegates InternalRead = new internalRead(parentChainedReader.Read); InternalPeek = new internalPeek(parentChainedReader.Peek); InternalClose = new internalClose(parentChainedReader.Close); //This is just a reader in the chain _baseReader = false; } /// /// Makes it so all calls to Read and Peek are passed the TextReader /// passed as a parameter. /// /// TextReader to forward calls to public virtual void Chain(TextReader baseReader) { if (baseReader == null) { throw new ArgumentNullException("baseReader", "Argument can not be null"); } // Assign delegates InternalRead = new internalRead(baseReader.Read); InternalPeek = new internalPeek(baseReader.Peek); InternalClose = new internalClose(baseReader.Close); // This is the base reader _baseReader = true; } /// /// Forwards Peek calls to the TextReader or ChainableReader passed in the corresponding constructor. /// /// Character or -1 if end of stream public virtual int Peek() { return InternalPeek(); } /// /// Forwards Read calls to the TextReader or ChainableReader passed in the corresponding constructor. /// /// /// Character or -1 if end of stream. /// public virtual int Read() { return InternalRead(); } /// /// Closes the reader. /// public virtual void Close() { InternalClose(); } #endregion Public Instance Methods #region Implementation of IDisposable /// /// Calls close and supresses the finalizer for the object. /// public void Dispose() { Close(); GC.SuppressFinalize(this); } #endregion Implementation of IDisposable } } nant-0.92-rc1/src/NAnt.Core/Filters/Support/FilterBuilderCollection.cs0000644000175000017500000002465111757302273025541 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; namespace NAnt.Core.Filters { /// /// Contains a strongly typed collection of objects. /// [Serializable] public class FilterBuilderCollection : CollectionBase { #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public FilterBuilderCollection() { } /// /// Initializes a new instance of the class /// with the specified instance. /// public FilterBuilderCollection(FilterBuilderCollection value) { AddRange(value); } /// /// Initializes a new instance of the class /// with the specified array of instances. /// public FilterBuilderCollection(FilterBuilder[] value) { AddRange(value); } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets the element at the specified index. /// /// The zero-based index of the element to get or set. [System.Runtime.CompilerServices.IndexerName("Item")] public FilterBuilder this[int index] { get {return ((FilterBuilder)(base.List[index]));} set {base.List[index] = value;} } /// /// Gets the for the specified task. /// /// The name of the filter for which the should be located in the collection. [System.Runtime.CompilerServices.IndexerName("Item")] public FilterBuilder this[string filterName] { get { if (filterName != null) { // try to locate instance by name foreach (FilterBuilder filterBuilder in base.List) { if (filterName.Equals(filterBuilder.FilterName)) { return filterBuilder; } } } return null; } } #endregion Public Instance Properties #region Public Instance Methods /// /// Adds a to the end of the collection. /// /// The to be added to the end of the collection. /// The position into which the new element was inserted. public int Add(FilterBuilder item) { return base.List.Add(item); } /// /// Adds the elements of a array to the end of the collection. /// /// The array of elements to be added to the end of the collection. public void AddRange(FilterBuilder[] items) { for (int i = 0; (i < items.Length); i = (i + 1)) { Add(items[i]); } } /// /// Adds the elements of a to the end of the collection. /// /// The to be added to the end of the collection. public void AddRange(FilterBuilderCollection items) { for (int i = 0; (i < items.Count); i = (i + 1)) { Add(items[i]); } } /// /// Determines whether a is in the collection. /// /// The to locate in the collection. /// /// if is found in the /// collection; otherwise, . /// public bool Contains(FilterBuilder item) { return base.List.Contains(item); } /// /// Determines whether a for the specified /// task is in the collection. /// /// The name of task for which the should be located in the collection. /// /// if a for /// the specified task is found in the collection; otherwise, /// . /// public bool Contains(string taskName) { return this[taskName] != null; } /// /// Copies the entire collection to a compatible one-dimensional array, starting at the specified index of the target array. /// /// The one-dimensional array that is the destination of the elements copied from the collection. The array must have zero-based indexing. /// The zero-based index in at which copying begins. public void CopyTo(FilterBuilder[] array, int index) { base.List.CopyTo(array, index); } /// /// Retrieves the index of a specified object in the collection. /// /// The object for which the index is returned. /// /// The index of the specified . If the is not currently a member of the collection, it returns -1. /// public int IndexOf(FilterBuilder item) { return base.List.IndexOf(item); } /// /// Inserts a into the collection at the specified index. /// /// The zero-based index at which should be inserted. /// The to insert. public void Insert(int index, FilterBuilder item) { base.List.Insert(index, item); } /// /// Returns an enumerator that can iterate through the collection. /// /// /// A for the entire collection. /// public new FilterBuilderEnumerator GetEnumerator() { return new FilterBuilderEnumerator(this); } /// /// Removes a member from the collection. /// /// The to remove from the collection. public void Remove(FilterBuilder item) { base.List.Remove(item); } #endregion Public Instance Methods } /// /// Enumerates the elements of a . /// public class FilterBuilderEnumerator : IEnumerator { #region Internal Instance Constructors /// /// Initializes a new instance of the class /// with the specified . /// /// The collection that should be enumerated. internal FilterBuilderEnumerator(FilterBuilderCollection arguments) { IEnumerable temp = (IEnumerable) (arguments); _baseEnumerator = temp.GetEnumerator(); } #endregion Internal Instance Constructors #region Implementation of IEnumerator /// /// Gets the current element in the collection. /// /// /// The current element in the collection. /// public FilterBuilder Current { get { return (FilterBuilder) _baseEnumerator.Current; } } object IEnumerator.Current { get { return _baseEnumerator.Current; } } /// /// Advances the enumerator to the next element of the collection. /// /// /// if the enumerator was successfully advanced /// to the next element; if the enumerator has /// passed the end of the collection. /// public bool MoveNext() { return _baseEnumerator.MoveNext(); } bool IEnumerator.MoveNext() { return _baseEnumerator.MoveNext(); } /// /// Sets the enumerator to its initial position, which is before the /// first element in the collection. /// public void Reset() { _baseEnumerator.Reset(); } void IEnumerator.Reset() { _baseEnumerator.Reset(); } #endregion Implementation of IEnumerator #region Private Instance Fields private IEnumerator _baseEnumerator; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.Core/Filters/ReplaceTokens.cs0000644000175000017500000003606311757302273022054 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // using System; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Text; using System.Xml; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.Core.Filters { /// /// Replaces tokens in the original input with user-supplied values. /// /// /// /// This filter replaces all token surrounded by a beginning and ending /// token. The default beginning and ending tokens both default to '@'. The /// optional and attributes /// can be specified to change either token. By default string /// comparisons are case sensitive but this can be changed by setting the /// optional attribute to . /// /// /// Tokens are specified by using the element. It is /// possible to specify from 1 to n tokens and replacement values. Values can /// be any valid NAnt expression. /// /// /// Filters are intended to be used as a element of a . /// /// /// /// /// Replace all occurrences of the string @DATE@ with the value of property /// "TODAY". /// /// /// /// /// /// ]]> /// /// /// /// /// Replace all occurrences of the string <DATE> with the value of /// property "TODAY". /// /// /// /// /// /// ]]> /// /// [ElementName("replacetokens")] public class ReplaceTokens : Filter { /// /// Delegate for Read and Peek. Allows the same implementation /// to be used for both methods. /// delegate int AcquireCharDelegate(); #region Private Instance Fields private char _beginToken = '@'; private char _endToken = '@'; private Token[] _tokens; private StringDictionary _tokenValues = new StringDictionary(); private StringBuilder _tokenString; private int _maxTokenLength; private string _outputBuffer; private bool _endStreamAfterBuffer; private int _bufferPosition; private bool _unknownToken = true; private bool _tokenNotFound = true; private bool _ignoreCase; //Method used for Read private AcquireCharDelegate ReadChar; #endregion Private Instance Fields #region Public Instance Properties /// /// Marks the beginning of a token. The default is "@". /// [TaskAttribute("begintoken")] [StringValidator(AllowEmpty=false)] public char BeginToken { get { return _beginToken; } set { _beginToken = value; } } /// /// Marks the end of a token. The default is "@". /// [TaskAttribute("endtoken")] [StringValidator(AllowEmpty=false)] public char EndToken { get { return _endToken; } set { _endToken = value; } } /// /// Tokens and replacement values. /// [BuildElementArray("token")] public Token[] Tokens { get { return _tokens; } set { _tokens = value; } } /// /// Determines if case will be ignored. /// The default is . /// [TaskAttribute("ignorecase", Required=false)] [BooleanValidator()] public bool IgnoreCase { get { return _ignoreCase; } set { _ignoreCase = value; } } #endregion Public Instance Properties #region Override implementation of ChainableReader /// /// Construct that allows this filter to be chained to the one /// in the parameter chainedReader. /// /// Filter that the filter will be chained to public override void Chain(ChainableReader chainedReader) { base.Chain(chainedReader); ReadChar = new AcquireCharDelegate(base.Read); } /// /// Reads the next character applying the filter logic. /// /// Char as an int or -1 if at the end of the stream public override int Read() { return GetNextCharacter(ReadChar); } /// /// Reads the next character applying the filter logic without /// advancing the current position in the stream. /// /// Peek currently is not supported. /// /// /// Char as an int or -1 if at the end of the stream. /// public override int Peek() { //Need to maintain seperate state for Read and Peek for this to work throw new ApplicationException(ResourceUtils.GetString("String_PeekNotSupported")); } #endregion Override implementation of ChainableReader #region Override implementation of Element /// /// Initialize the filter by setting its parameters. /// protected override void Initialize() { foreach (Token token in Tokens) { if (token.IfDefined && !token.UnlessDefined) { _tokenValues.Add(token.Key, token.Value); // track max character length if (token.Key.Length > _maxTokenLength) { _maxTokenLength = token.Key.Length; } } } if (_tokenValues.Count == 0) { throw new BuildException(ResourceUtils.GetString("String_OneOrMoreTokens"), Location); } // create a string builder to use for a buffer while searching for // tokens _tokenString = new StringBuilder(_maxTokenLength + 1, _maxTokenLength + 1); } #endregion Override implementation of Element #region Private Instance Methods /// /// Finds a token give that we are positioned at a beginning token character. Either a /// token replacement is returned or the characters that were read looking for the token. /// /// A token was not found /// A token was found by there is no replacement /// The stream ended while looking for the token /// Either the replacement token or the characters that were read looking for the token private string FindTokenContents( out bool tokenNotFound, out bool unknownToken, out bool streamEnded) { int charactersScanned = 0; char currentChar = BeginToken; bool tokenFound = false; tokenNotFound = false; streamEnded = false; unknownToken = true; // reset token string _tokenString.Length = 0; // only peak within the limits of the largest token while ((charactersScanned <= _maxTokenLength)) { charactersScanned++; // read a character int streamChar = base.Read(); currentChar = (char) streamChar; // check for end of stream if (streamChar == -1) { //Two adjacent tokens were found tokenNotFound = true; unknownToken = true; streamEnded = true; return _tokenString.ToString(); } if (CompareCharacters(currentChar, EndToken)) { tokenFound = true; break; } else if (CompareCharacters(currentChar, BeginToken) && (!CompareCharacters(EndToken, BeginToken))) { // add end char and break, only happens if the beginning // and ending tokens are not the same tokenNotFound = true; unknownToken = true; _tokenString.Append((char) currentChar); return _tokenString.ToString(); } else { // add possiable token contents to the buffer _tokenString.Append((char) currentChar); } } // token found and length greater than 0 if (tokenFound) { string replacementValue = null; // look up token if not empty if (_tokenString.Length != 0) { // token found so look it up string contentsRead = _tokenString.ToString(); replacementValue = _tokenValues[contentsRead]; } else { // two adjacent tokens were found tokenNotFound = true; unknownToken = true; return new string(currentChar, 1); } // did we find a replacement value for the token? if (replacementValue != null) { // this was a token we can handle tokenNotFound = false; unknownToken = false; // return the replacment value to output return replacementValue; } else { // we don't know about the token // the token was not in the list so just output it but add // then ending token character back tokenNotFound = true; unknownToken = true; return _tokenString.Append(currentChar).ToString(); } } else { // read max number of characters //return string to output in future reads tokenNotFound = true; unknownToken = false; return _tokenString.ToString(); } } /// /// Returns the next character in the stream replacing the specified character. Using the /// allows for the same implementation for Read and Peek /// /// Delegate to acquire the next character. (Read/Peek) /// Char as an int or -1 if at the end of the stream private int GetNextCharacter(AcquireCharDelegate AcquireChar) { int ch; // either read the next character or if there is a buffer output // the next character if (_outputBuffer == null) { ch = base.Read(); } else { // characters left in the buffer? if (_bufferPosition < _outputBuffer.Length) { // if this is the last character of a token string that is // unknown then process the charactor again since it might // be the beginning of another token if ((_tokenNotFound == true) && (_unknownToken == true) && (_bufferPosition == _outputBuffer.Length - 1)) { // process token end char again as it could be the same // as token begin ch = _outputBuffer[_outputBuffer.Length - 1]; _bufferPosition++; } else { // pass along buffer character return _outputBuffer[_bufferPosition++]; } } else { // end of buffer // reset buffer and get next char _outputBuffer = null; _bufferPosition = 0; // read the next character or end the stream the end of the // stream was encountered while reading the buffer if (!_endStreamAfterBuffer) { ch = ReadChar(); } else { return -1; } } } // process beginning token if (CompareCharacters(ch, BeginToken)) { // look for a token after BeginToken and return either the // replacement token or the charactors that were read _outputBuffer = FindTokenContents(out _tokenNotFound, out _unknownToken, out _endStreamAfterBuffer); // a token was not found so BeginToken needs to be accounted for. if (_tokenNotFound) { _bufferPosition = 0; return BeginToken; } else { if (_outputBuffer.Length > 0) { // output first character of buffer _bufferPosition = 1; return _outputBuffer[0]; } else { // return next character return GetNextCharacter(AcquireChar); } } } else { // this was not a beginning token so just pass it through return ch; } } /// /// Compares to characters taking into account. /// /// /// /// /// private bool CompareCharacters(int char1, int char2) { //Compare chars with or without case if (IgnoreCase) { return (char.ToUpper((char)char1) == char.ToUpper((char)char2)); } else { return char1 == char2; } } #endregion Private Instance Methods } } nant-0.92-rc1/src/NAnt.Core/Filters/TabsToSpaces.cs0000644000175000017500000001113111757302273021635 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // using System; using NAnt.Core.Attributes; using NAnt.Core.Util; namespace NAnt.Core.Filters { /// /// Converts tabs to spaces. /// /// /// /// The filter replaces tabs in a text file /// with spaces. /// /// /// Filters are intended to be used as a element of a . /// /// /// /// Replace all tabs with four spaces. /// /// /// ]]> /// /// [ElementName("tabstospaces")] public class TabsToSpaces : Filter { /// /// Delegate for Read and Peek. Allows the same implementation /// to be used for both methods. /// delegate int AcquireCharDelegate(); #region Private Instance Fields private int _tabLength = 8; private int _spacesRemaining; //Method used for Read private AcquireCharDelegate ReadChar; #endregion Private Instance Fields #region Public Instance Properties /// /// The number of spaces used when converting a tab. The default is /// "8". /// [TaskAttribute("tablength")] [Int32Validator(MinValue=1, MaxValue=100)] public int TabLength { get { return _tabLength; } set { _tabLength = value; } } #endregion Public Instance Properties #region Override implementation of ChainableReader /// /// Construct that allows this filter to be chained to the one /// in the parameter chainedReader. /// /// Filter that the filter will be chained to public override void Chain(ChainableReader chainedReader) { base.Chain(chainedReader); ReadChar = new AcquireCharDelegate(base.Read); } /// /// Retrieves the next character with moving the position in the stream. /// This method is not implemented /// /// -1 if end of stream otherwise a character public override int Peek() { //Need to maintain seperate state for Read and Peek for this to work throw new ApplicationException(ResourceUtils.GetString("String_PeekNotSupported")); } /// /// Retrieves the next character in the stream. /// /// -1 if end of stream otherwise a character public override int Read() { return GetNextCharacter(ReadChar); } #endregion Override implementation of ChainableReader #region Private Instance Methods /// /// Returns the next character in the stream replacing the specified character. Using the /// allows for the same implementation for Read and Peek /// /// Delegate to acquire the next character. (Read/Peek) /// Char as an int or -1 if at the end of the stream private int GetNextCharacter(AcquireCharDelegate AcquireChar) { if (_spacesRemaining == 0) { int nextChar = AcquireChar(); if (nextChar == '\t') { _spacesRemaining = TabLength - 1; return ' '; } else { return nextChar; } } else { _spacesRemaining--; return ' '; } } #endregion Private Instance Methods } } nant-0.92-rc1/src/NAnt.Core/Filters/ReplaceString.cs0000644000175000017500000002736711757302273022066 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // using System; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Text; using System.Xml; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.Core.Filters { /// /// Replaces all occurrences of a given string in the original input with /// user-supplied replacement string. /// /// /// /// This filter replaces all occurrences of a given string in the original /// input stream with a user-supplied replacement string. By default string /// comparisons are case sensitive but this can be changed by setting the /// optional attribute to . /// /// /// To use this filter specify the string to be replaced with the /// attribute and the string to replace it with using the /// attribute. /// /// /// Filters are intended to be used as a element of a . /// /// /// /// /// Replace all occurrences of "3.14" with "PI". /// /// /// /// ]]> /// /// /// /// /// Replace all occurrences of "string", "String", etc. with "System.String". /// /// /// /// ]]> /// /// [ElementName("replacestring")] public class ReplaceString : Filter { /// /// Delegate for Read and Peek. Allows the same implementation /// to be used for both methods. /// delegate int AcquireCharDelegate(); #region Private Instance Fields private string _from; private string _to = string.Empty; private string _outputBuffer; private bool _endStreamAfterBuffer; private int _bufferPosition = 0; private bool _stringNotFound = true; private bool _ignoreCase; //Method used for Read private AcquireCharDelegate ReadChar; #endregion Private Instance Fields #region Public Instance Properties /// /// The string to be replaced. /// [TaskAttribute("from", Required=true)] [StringValidator(AllowEmpty=false)] public string From { get { return _from; } set { _from = value; } } /// /// The new value for the replaced string. /// Am empty string is permissible. /// [TaskAttribute("to", Required=false)] [StringValidator(AllowEmpty=true)] public string To { get { return _to; } set { _to = value; } } /// /// Determines if case will be ignored. /// The default is . /// [TaskAttribute("ignorecase", Required=false)] [BooleanValidator()] public bool IgnoreCase { get { return _ignoreCase; } set { _ignoreCase = value; } } #endregion Public Instance Properties #region Override implementation of ChainableReader /// /// Construct that allows this filter to be chained to the one /// in the parameter chainedReader. /// /// Filter that the filter will be chained to public override void Chain(ChainableReader chainedReader) { base.Chain(chainedReader); ReadChar = new AcquireCharDelegate(base.Read); } /// /// Reads the next character applying the filter logic. /// /// Char as an int or -1 if at the end of the stream public override int Read() { return GetNextCharacter(ReadChar); } /// /// Reads the next character applying the filter logic without /// advancing the current position in the stream. /// /// Peek currently is not supported. /// /// /// Char as an int or -1 if at the end of the stream. /// public override int Peek() { //Need to maintain seperate state for Read and Peek for this to work throw new ApplicationException(ResourceUtils.GetString("String_PeekNotSupported")); } #endregion Override implementation of ChainableReader #region Private Instance Methods /// /// /// Helper function used to search for the filter's traget string. If the string /// is found the result is true. If the string was not found false is returned and /// nonMatchingChars contains the characters that were read to determine if the /// string is present. /// /// /// /// It is assumed the stream is positioned at the character after the first character /// in the target string. /// /// /// First character in target string /// Ture if the stream ended while search for the string. /// Characters that were read while searching for the string. /// private bool FindString(int startChar, out bool streamEnded, out string nonMatchingChars) { //Init output parameters streamEnded = false; nonMatchingChars = ""; //create a new buffer StringBuilder buffer = new StringBuilder(_from.Length, _from.Length); //Add first char that initiate the FindString buffer.Append((char)startChar); //Try to read each character of the string to replace. //Store the characters in the output buffer until we know //we have found the string. int streamChar; for (int pos = 1 ; pos < _from.Length ; pos++) { //Read a character streamChar = base.Read(); //Store the character if it is not the end of the buffer character if (streamChar != -1) { buffer.Append((char)streamChar); } //Is it the correct character? if (CompareCharacters(streamChar, _from[pos]) == false) { //Check for end of stream if (streamChar == -1) { streamEnded = true; } //Put any characters that were read into the output buffer since //the string was not found. nonMatchingChars = buffer.ToString(); return false; } } //The string was found return true; } /// /// Returns the next character in the stream replacing the specified character. Using the /// allows for the same implementation for Read and Peek /// /// Delegate to acquire the next character. (Read/Peek) /// Char as an int or -1 if at the end of the stream private int GetNextCharacter(AcquireCharDelegate AcquireChar) { int ch; //Either read the next character or if there is a buffer output the next character if (_outputBuffer == null) { ch = base.Read(); } else { // characters left in the buffer? if (_bufferPosition < _outputBuffer.Length) { //If this is the last character of a buffer that was not the replacemant string //process the last charactor again since it might be the beginning of another token. if ((_stringNotFound == true) && (_bufferPosition == _outputBuffer.Length - 1)) { //Process token end char again. It could be the same as token begin. ch = _outputBuffer[_outputBuffer.Length - 1]; _bufferPosition++; } else { //Pass along buffer character return _outputBuffer[_bufferPosition++]; } } else {//End of buffer //Reset buffer and get next char _outputBuffer = null; _bufferPosition = 0; //Read the next character or end the stream the end of the stream //was encountered while reading the buffer. if (!_endStreamAfterBuffer) { ch = ReadChar(); } else { return -1; } } } // if the character matches the first character of the target string then search // for the string. if (CompareCharacters(ch, _from[0])) { // search for the target string if (FindString(ch, out _endStreamAfterBuffer, out _outputBuffer) == true) { //Target was found _stringNotFound = false; //Do nothing if _to is null; otherwise output _to if (_to==string.Empty) { _outputBuffer = null; return GetNextCharacter(AcquireChar); } else { _outputBuffer = _to; _bufferPosition = 1; } return _to[0]; } else { //Target not found _stringNotFound = true; _bufferPosition = 1; return ch; } } else { //This was not a beginning token so just pass it through return ch; } } /// /// Compares to characters taking into account the _ignoreCase flag. /// /// /// /// private bool CompareCharacters(int char1, int char2) { //Compare chars with or without case if (_ignoreCase == true) { return (char.ToUpper((char)char1) == char.ToUpper((char)char2)); } else { return char1 == char2; } } #endregion Private Instance Methods } } nant-0.92-rc1/src/NAnt.Core/BuildException.cs0000644000175000017500000001730211757302272020615 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Ian MacLean (imaclean@gmail.com) using System; using System.Globalization; using System.Runtime.Serialization; using System.Security.Permissions; using NAnt.Core.Util; namespace NAnt.Core { /// /// Thrown whenever an error occurs during the build. /// [Serializable] public class BuildException : ApplicationException { #region Private Instance Fields /// /// The location of the exception in the build document (xml file). /// private Location _location = Location.UnknownLocation; #endregion Private Instance Fields #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public BuildException() : base() { } /// /// Initializes a new instance of the class /// with a descriptive message. /// /// A descriptive message to include with the exception. public BuildException(String message) : base(message) { } /// /// Initializes a new instance of the class /// with the specified descriptive message and inner exception. /// /// A descriptive message to include with the exception. /// A nested exception that is the cause of the current exception. public BuildException(String message, Exception innerException) : base(message, innerException) { } /// /// Initializes a new instance of the class /// with a descriptive message and the location in the build file that /// caused the exception. /// /// A descriptive message to include with the exception. /// The location in the build file where the exception occured. public BuildException(String message, Location location) : base(message) { _location = location; } /// /// Initializes a new instance of the class /// with a descriptive message, the location in the build file and an /// instance of the exception that is the cause of the current exception. /// /// A descriptive message to include with the exception. /// The location in the build file where the exception occured. /// A nested exception that is the cause of the current exception. public BuildException(String message, Location location, Exception innerException) : base(message, innerException) { _location = location; } #endregion Public Instance Constructors #region Protected Instance Constructors /// /// Initializes a new instance of the class /// with serialized data. /// /// The that holds the serialized object data about the exception being thrown. /// The that contains contextual information about the source or destination. protected BuildException(SerializationInfo info, StreamingContext context) : base(info, context) { _location = info.GetValue("Location", _location.GetType()) as Location; } #endregion Protected Instance Constructors #region Public Instance Properties /// /// Gets the raw message as specified when the exception was /// constructed. /// /// /// The raw message as specified when the exception was /// constructed. /// public string RawMessage { get { return base.Message; } } /// /// Gets the location in the build file of the element from which the /// exception originated. /// /// /// The location in the build file of the element from which the /// exception originated. /// public Location Location { get { return _location; } } #endregion Public Instance Properties #region Override implementation of ISerializable /// /// Serializes this object into the provided. /// /// The to populate with data. /// The destination for this serialization. [SecurityPermission(SecurityAction.Demand, SerializationFormatter=true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("Location", _location); } #endregion Override implementation of ISerializable #region Override implementation of ApplicationException /// /// Gets a message that describes the current exception. /// /// /// The error message that explains the reason for the exception. /// /// /// Adds location information to the message, if available. /// public override string Message { get { string message = base.Message; // only include location string if not empty string locationString = string.Empty; if (_location != null) { locationString = _location.ToString(); } if (!String.IsNullOrEmpty(locationString)) { message = locationString + Environment.NewLine + message; } return message; } } #endregion Override implementation of ApplicationException #region Override implementation of Object /// /// Creates and returns a string representation of the current /// exception. /// /// /// A string representation of the current exception. /// public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "{0}:{1}{2}", Message, Environment.NewLine, base.ToString()); } #endregion Override implementation of Object } } nant-0.92-rc1/src/NAnt.Core/ProjectSettingsLoader.cs0000644000175000017500000003305211757302273022156 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Ian MacLean (imaclean@gmail.com) // Scott Hernandez (ScottHernandez@hotmail.com) // William E. Caputo (wecaputo@thoughtworks.com | logosity@yahoo.com) using System; using System.Collections; using System.Collections.Specialized; using System.Configuration; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using System.Xml; using Microsoft.Win32; using NAnt.Core.Tasks; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.Core { internal class ProjectSettingsLoader { #region Private Instance Fields private Project _project; private XmlNamespaceManager _nsMgr; #endregion Private Instance Fields #region Private Static Fields /// /// Holds a value indicating whether a scan for tasks, types and functions /// has already been performed for the current runtime framework. /// private static bool ScannedTasks; #endregion Private Static Fields #region Internal Instance Constructor /// /// Initializes a new instance of the /// class for the given . /// /// The that should be configured. internal ProjectSettingsLoader(Project project) { _project = project; // setup namespace manager _nsMgr = new XmlNamespaceManager(new NameTable()); _nsMgr.AddNamespace("nant", _nsMgr.DefaultNamespace); } #endregion Internal Instance Constructor #region Protected Instance Properties /// /// Gets the underlying instance. /// /// /// The underlying instance. /// protected Project Project { get { return _project; } } #endregion Protected Instance Properties #region Private Instance Properties /// /// Gets the . /// /// /// The . /// /// /// The defines the current namespace /// scope and provides methods for looking up namespace information. /// private XmlNamespaceManager NamespaceManager { get { return _nsMgr; } } #endregion Private Instance Properties #region Public Instance Methods /// /// Loads and processes settings from the specified /// of the configuration file. /// public void ProcessSettings() { if (Project.ConfigurationNode == null) { return; } // process platform configuration ProcessPlatform(Project.ConfigurationNode.SelectSingleNode( "nant:frameworks/nant:platform[@name='" + Project.PlatformName + "']", NamespaceManager)); // process global properties ProcessGlobalProperties(Project.ConfigurationNode.SelectNodes( "nant:properties/nant:property", NamespaceManager)); } #endregion Public Instance Methods #region Private Instance Methods private void ProcessPlatform(XmlNode platformNode) { if (platformNode == null) { throw new ArgumentNullException("platformNode"); } // process platform task assemblies if (!ScannedTasks) { FileSet platformTaskAssemblies = new FileSet(); platformTaskAssemblies.BaseDirectory = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory); platformTaskAssemblies.Project = Project; platformTaskAssemblies.NamespaceManager = NamespaceManager; platformTaskAssemblies.Parent = Project; // avoid warnings by setting the parent of the fileset platformTaskAssemblies.ID = "platform-task-assemblies"; // avoid warnings by assigning an id XmlNode taskAssembliesNode = platformNode.SelectSingleNode( "nant:task-assemblies", NamespaceManager); if (taskAssembliesNode != null) { platformTaskAssemblies.Initialize(taskAssembliesNode, Project.Properties, null); } // scan platform extensions assemblies LoadTasksTask loadTasks = new LoadTasksTask(); loadTasks.Project = Project; loadTasks.NamespaceManager = NamespaceManager; loadTasks.Parent = Project; loadTasks.TaskFileSet = platformTaskAssemblies; loadTasks.FailOnError = false; loadTasks.Threshold = (Project.Threshold == Level.Debug) ? Level.Debug : Level.Warning; loadTasks.Execute(); // scan NAnt.Core TypeFactory.ScanAssembly(Assembly.GetExecutingAssembly(), loadTasks); } // process the framework nodes of the current platform ProcessFrameworks(platformNode); // configure the runtime framework Project.RuntimeFramework = ConfigureRuntimeFramework(); // configure the default target framework Project.TargetFramework = ConfigureTargetFramework(platformNode); // process runtime framework task assemblies if (!ScannedTasks) { LoadTasksTask loadTasks = new LoadTasksTask(); loadTasks.Project = Project; loadTasks.NamespaceManager = NamespaceManager; loadTasks.Parent = Project; loadTasks.TaskFileSet = Project.RuntimeFramework.TaskAssemblies; loadTasks.FailOnError = false; loadTasks.Threshold = (Project.Threshold == Level.Debug) ? Level.Debug : Level.Warning; loadTasks.Execute(); // ensure we don't scan task assemblies for the current // runtime framework and platform again ScannedTasks = true; } } /// /// Processes the framework nodes of the given platform node. /// /// An representing the platform on which NAnt is running. private void ProcessFrameworks(XmlNode platformNode) { if (platformNode == null) { throw new ArgumentNullException("platformNode"); } // deals with xml info from the config file, not build document. foreach (XmlNode frameworkNode in platformNode.SelectNodes("nant:framework", NamespaceManager)) { // skip special elements like comments, pis, text, etc. if (!(frameworkNode.NodeType == XmlNodeType.Element)) { continue; } FrameworkInfo framework = new FrameworkInfo(frameworkNode, NamespaceManager); // add framework before it's considered valid, since we // want to inform users of possible configuration or // installation issues when they explicitly target that // framework Project.Frameworks.Add(framework.Name, framework); } } /// /// Reads the list of global properties specified in the NAnt configuration /// file. /// /// An representing global properties. private void ProcessGlobalProperties(XmlNodeList propertyNodes) { //deals with xml info from the config file, not build document. foreach (XmlNode propertyNode in propertyNodes) { //skip special elements like comments, pis, text, etc. if (!(propertyNode.NodeType == XmlNodeType.Element)) { continue; } // initialize task PropertyTask propertyTask = new PropertyTask(); propertyTask.Parent = propertyTask.Project = Project; propertyTask.NamespaceManager = NamespaceManager; propertyTask.InitializeTaskConfiguration(); // configure using xml node propertyTask.Initialize(propertyNode); // execute task propertyTask.Execute(); } } private FrameworkInfo ConfigureRuntimeFramework() { ArrayList candidates = new ArrayList(); // determine the framework family name string frameworkFamily = PlatformHelper.IsMono ? "mono" : "net"; // determine the version of the current runtime framework Version frameworkClrVersion = new Version(Environment.Version.ToString(3)); // determine which framework configuration matches the host CLR foreach (FrameworkInfo framework in Project.Frameworks) { if (framework.Family != frameworkFamily) continue; if (framework.ClrVersion != frameworkClrVersion) { continue; } candidates.Add(framework); } FrameworkInfo selected = null; for (int i = 0; i < candidates.Count; i++) { FrameworkInfo current = (FrameworkInfo) candidates[i]; try { // validate current.Validate(); selected = current; if (selected.SdkDirectory != null) { // if we found a matching framework with a valid // SDK, then skip further candidates break; } } catch { // only rethrow exception if we haven't yet found a valid // framework and we're dealing with the last candidate if (selected == null && i == (candidates.Count -1)) { throw; } } } if (selected == null) { // information about the current runtime framework should // be added to the NAnt configuration file throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1062"), frameworkFamily, frameworkClrVersion.ToString())); } return selected; } private FrameworkInfo ConfigureTargetFramework(XmlNode platformNode) { // determine default targetframework string defaultTargetFramework = GetXmlAttributeValue(platformNode, "default"); if (defaultTargetFramework == null || defaultTargetFramework == "auto") { // no need to validate the framework since this was done in // ConfigureRuntimeFramework return Project.RuntimeFramework; } FrameworkInfo framework = Project.Frameworks [defaultTargetFramework]; if (framework == null) { Project.Log(Level.Warning, ResourceUtils.GetString("NA1178"), defaultTargetFramework, Project.RuntimeFramework.Name); Project.Log(Level.Warning, ""); return null; } return framework; } #endregion Private Instance Methods #region Private Static Methods /// /// Gets the value of the specified attribute from the specified node. /// /// The node of which the attribute value should be retrieved. /// The attribute of which the value should be returned. /// /// The value of the attribute with the specified name or /// if the attribute does not exist or has no value. /// private static string GetXmlAttributeValue(XmlNode xmlNode, string attributeName) { string attributeValue = null; if (xmlNode != null) { XmlAttribute xmlAttribute = (XmlAttribute)xmlNode.Attributes.GetNamedItem(attributeName); if (xmlAttribute != null) { attributeValue = StringUtils.ConvertEmptyToNull(xmlAttribute.Value); } } return attributeValue; } #endregion Private Static Methods } } nant-0.92-rc1/src/NAnt.Core/PlatformHelper.cs0000644000175000017500000000657511757302273020636 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Jaroslaw Kowalski (jkowalski@users.sourceforge.net) using System; using System.IO; using System.Runtime.InteropServices; using System.Text; namespace NAnt.Core { [Serializable()] public class PlatformHelper { public static readonly bool IsMono; [Obsolete ("Use IsWindows instead.")] public static readonly bool IsWin32; public static readonly bool IsUnix; static PlatformHelper() { // check a class in mscorlib to determine if we're running on Mono if (Type.GetType("System.MonoType", false) != null) { // we're on Mono IsMono = true; } int p = (int) Environment.OSVersion.Platform; if ((p == 4) || (p == 6) || (p == 128)) IsUnix = true; IsWin32 = !IsUnix; } public static bool IsVolumeCaseSensitive(string path) { // GetVolumeInformation is useless, since it marks NTFS drives as // case-sensitive and provides no information for non-root // directories. // // This gave us the impression that it worked since a zero VolFlags // would be considered as case-insensitive. // // For now, we just return false on Unix and true in all other // cases. return IsUnix; } /// /// Returns a value indicating whether NAnt is running in 64-bit mode. /// /// /// if NAnt is running in 64-bit mode; otherwise, /// . /// internal static bool Is64Bit { get { return (IntPtr.Size == 8); } } /// /// Returns a value indicating whether NAnt is running in 32-bit mode. /// /// /// Note that even if the platform is 64-bit, NAnt may be running in /// 32-bit mode. /// /// /// if NAnt is running in 32-bit mode; otherwise, /// . /// internal static bool Is32Bit { get { return (IntPtr.Size == 4); } } /// /// Returns a value indicating whether NAnt is running on Windows. /// /// /// if NAnt is running on Windows; /// otherwise, . /// public static bool IsWindows { get { return !IsUnix; } } } } nant-0.92-rc1/src/NAnt.Core/PathScanner.cs0000644000175000017500000001577511757302273020122 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Brad Wilson (http://www.quality.nu/contact.aspx) using System; using System.Collections.Specialized; using System.IO; using NAnt.Core.Util; namespace NAnt.Core { /// /// Used to search for files on the PATH. /// /// /// /// The local directory is not searched (since this would already be covered /// by normal use of the includes element). /// /// /// Also, advanced pattern matching isn't supported: you need to know the /// exact name of the file. /// /// [Serializable()] public sealed class PathScanner : ICloneable { #region Private Instance Fields private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private StringCollection _unscannedNames = new StringCollection(); #endregion Private Instance Fields #region Implementation of ICloneable /// /// Creates a shallow copy of the . /// /// /// A shallow copy of the . /// object ICloneable.Clone() { return Clone(); } /// /// Creates a shallow copy of the . /// /// /// A shallow copy of the . /// public PathScanner Clone() { PathScanner clone = new PathScanner(); clone._unscannedNames = Clone(_unscannedNames); return clone; } #endregion Implementation of ICloneable #region Public Instance Methods /// /// Adds a file to the list of files to be scanned for. /// /// The filename or search pattern to add to the list. public void Add(string fileName) { _unscannedNames.Add(fileName); } public void Clear() { _unscannedNames.Clear(); } /// /// Scans all direcetories in the PATH environment variable for files. /// /// /// List of matching files found in the PATH. /// public StringCollection Scan() { return Scan("PATH"); } /// /// Scans all directories in the given environment variable for files. /// /// The environment variable of which the directories should be scanned. /// /// List of matching files found in the directory of the given /// environment variable. /// public StringCollection Scan(string name) { StringCollection scannedNames = new StringCollection(); string envValue = Environment.GetEnvironmentVariable(name); if (envValue == null) { return scannedNames; } // break apart the PATH string[] paths = envValue.Split(Path.PathSeparator); // walk the names list foreach (string unscannedName in _unscannedNames) { // check if file is rooted if (Path.IsPathRooted(unscannedName)) { if (File.Exists(unscannedName)) { scannedNames.Add(unscannedName); } else { // no need to scan paths in environment variable for // this file as it does not exist continue; } } string fileName = Path.GetFileName(unscannedName); string directoryName = Path.GetDirectoryName(unscannedName); // walk the paths, and see if the given file is on the path foreach (string path in paths) { //do not scan inaccessible directories. if (!Directory.Exists(path)) { continue; } // search pattern might include directory part (eg. foo\bar.txt) string scanPath = path; if (!String.IsNullOrEmpty(directoryName)) { scanPath = FileUtils.CombinePaths(path, directoryName); //do not scan inaccessible directories. if (!Directory.Exists(scanPath)) { continue; } } try { string[] found = Directory.GetFiles(scanPath, fileName); if (found.Length > 0) { scannedNames.Add(found[0]); break; } } catch (UnauthorizedAccessException e) { // In case of UnauthorizedAccessException, // log the issue as a warning and move on to // the next path. logger.Warn( "Access to the path \"" + scanPath + "\" is denied.", e ); continue; } } } // return an enumerator to the scanned (& found) files return scannedNames; } #endregion Public Instance Methods #region Private Static Methods /// /// Creates a shallow copy of the specified . /// /// The that should be copied. /// /// A shallow copy of the specified . /// private static StringCollection Clone(StringCollection stringCollection) { string[] strings = new string[stringCollection.Count]; stringCollection.CopyTo(strings, 0); StringCollection clone = new StringCollection(); clone.AddRange(strings); return clone; } #endregion Private Static Methods } } nant-0.92-rc1/src/NAnt.Core/DataTypeBaseDictionary.cs0000644000175000017500000002156411757302272022240 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2002-2003 Scott Hernandez // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian MacLean (imaclean@gmail.com) using System; using System.Collections; namespace NAnt.Core { public class DataTypeBaseDictionary : IDictionary, ICollection, IEnumerable, ICloneable { #region Private Instance Fields private Hashtable _innerHash; #endregion Private Instance Fields #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public DataTypeBaseDictionary() { _innerHash = new Hashtable(); } public DataTypeBaseDictionary(DataTypeBaseDictionary original) { _innerHash = new Hashtable(original.InnerHash); } public DataTypeBaseDictionary(IDictionary dictionary) { _innerHash = new Hashtable (dictionary); } /// /// Initializes a new instance of the class /// with the specified capacity. /// public DataTypeBaseDictionary(int capacity) { _innerHash = new Hashtable(capacity); } public DataTypeBaseDictionary(IDictionary dictionary, float loadFactor) { _innerHash = new Hashtable(dictionary, loadFactor); } public DataTypeBaseDictionary(IHashCodeProvider codeProvider, IComparer comparer) { _innerHash = new Hashtable(codeProvider, comparer); } public DataTypeBaseDictionary(int capacity, int loadFactor) { _innerHash = new Hashtable(capacity, loadFactor); } public DataTypeBaseDictionary(IDictionary dictionary, IHashCodeProvider codeProvider, IComparer comparer) { _innerHash = new Hashtable (dictionary, codeProvider, comparer); } public DataTypeBaseDictionary(int capacity, IHashCodeProvider codeProvider, IComparer comparer) { _innerHash = new Hashtable (capacity, codeProvider, comparer); } public DataTypeBaseDictionary(IDictionary dictionary, float loadFactor, IHashCodeProvider codeProvider, IComparer comparer) { _innerHash = new Hashtable (dictionary, loadFactor, codeProvider, comparer); } public DataTypeBaseDictionary(int capacity, float loadFactor, IHashCodeProvider codeProvider, IComparer comparer) { _innerHash = new Hashtable (capacity, loadFactor, codeProvider, comparer); } #endregion Public Instance Constructors #region Internal Instance Properties internal Hashtable InnerHash { get { return _innerHash; } set { _innerHash = value ; } } #endregion Internal Instance Properties #region Implementation of IDictionary public DataTypeBaseDictionaryEnumerator GetEnumerator() { return new DataTypeBaseDictionaryEnumerator(this); } IDictionaryEnumerator IDictionary.GetEnumerator() { return new DataTypeBaseDictionaryEnumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Remove(string key) { _innerHash.Remove(key); } void IDictionary.Remove(object key) { Remove((string) key); } public bool Contains(string key) { return _innerHash.Contains(key); } bool IDictionary.Contains(object key) { return Contains((string)key); } public void Clear() { _innerHash.Clear(); } public void Add(string key, DataTypeBase value) { _innerHash.Add (key, value); } void IDictionary.Add(object key, object value) { Add((string) key, (DataTypeBase) value); } public bool IsReadOnly { get { return _innerHash.IsReadOnly; } } public DataTypeBase this[string key] { get { return (DataTypeBase) _innerHash[key]; } set { _innerHash[key] = value; } } object IDictionary.this[object key] { get { return this[(string) key]; } set { this[(string) key] = (DataTypeBase) value; } } public ICollection Values { get { return _innerHash.Values; } } public ICollection Keys { get { return _innerHash.Keys; } } public bool IsFixedSize { get { return _innerHash.IsFixedSize; } } #endregion Implementation of IDictionary #region Implementation of ICollection void ICollection.CopyTo(Array array, int index) { _innerHash.CopyTo(array, index); } public bool IsSynchronized { get { return _innerHash.IsSynchronized; } } public int Count { get { return _innerHash.Count; } } public object SyncRoot { get { return _innerHash.SyncRoot; } } public void CopyTo(DataTypeBase[] array, int index) { _innerHash.CopyTo(array, index); } #endregion Implementation of ICollection #region Implementation of ICloneable public DataTypeBaseDictionary Clone() { DataTypeBaseDictionary clone = new DataTypeBaseDictionary(); clone.InnerHash = (Hashtable) _innerHash.Clone(); return clone; } object ICloneable.Clone() { return Clone(); } #endregion Implementation of ICloneable #region HashTable Methods public bool ContainsKey (string key) { return _innerHash.ContainsKey(key); } public bool ContainsValue(DataTypeBase value) { return _innerHash.ContainsValue(value); } public static DataTypeBaseDictionary Synchronized(DataTypeBaseDictionary nonSync) { DataTypeBaseDictionary sync = new DataTypeBaseDictionary(); sync.InnerHash = Hashtable.Synchronized(nonSync.InnerHash); return sync; } #endregion HashTable Methods /// /// Inherits Properties from an existing property /// dictionary Instance /// /// DataType list to inherit public virtual void Inherit(DataTypeBaseDictionary source) { foreach ( string key in source.Keys ){ Add( key, source[key] ); //this[key] = entry.Value; } } } public class DataTypeBaseDictionaryEnumerator : IDictionaryEnumerator { #region Private Instance Fields private IDictionaryEnumerator _innerEnumerator; #endregion Private Instance Fields #region Internal Instance Constructors internal DataTypeBaseDictionaryEnumerator(DataTypeBaseDictionary enumerable) { _innerEnumerator = enumerable.InnerHash.GetEnumerator(); } #endregion Internal Instance Constructors #region Implementation of IDictionaryEnumerator public string Key { get { return (string) _innerEnumerator.Key; } } object IDictionaryEnumerator.Key { get { return Key; } } public DataTypeBase Value { get { return (DataTypeBase) _innerEnumerator.Value; } } object IDictionaryEnumerator.Value { get { return Value; } } public DictionaryEntry Entry { get { return _innerEnumerator.Entry; } } #endregion Implementation of IDictionaryEnumerator #region Implementation of IEnumerator public void Reset() { _innerEnumerator.Reset(); } public bool MoveNext() { return _innerEnumerator.MoveNext(); } object IEnumerator.Current { get { return _innerEnumerator.Current; } } public DataTypeBase Current { get { return (DataTypeBase) _innerEnumerator.Current; } } #endregion Implementation of IEnumerator } } nant-0.92-rc1/src/NAnt.Core/Extensibility/0000755000175000017500000000000011757310030020170 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.Core/Extensibility/IPlugin.cs0000644000175000017500000000162111757302273022100 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2008 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net.be) namespace NAnt.Core.Extensibility { public interface IPlugin { } } nant-0.92-rc1/src/NAnt.Core/Extensibility/IPluginConsumer.cs0000644000175000017500000000172211757302273023616 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2008 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net.be) using System; namespace NAnt.Core.Extensibility { public interface IPluginConsumer { void ConsumePlugin(IPlugin type); } } nant-0.92-rc1/src/NAnt.Core/Extensibility/PluginConsumerAttribute.cs0000644000175000017500000000331711757302273025373 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2008 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net.be) using System; using NAnt.Core.Attributes; namespace NAnt.Core.Extensibility { [AttributeUsage(AttributeTargets.Class, Inherited=false, AllowMultiple=true)] public sealed class PluginConsumerAttribute : Attribute { private Type _type; /// /// Initializes a new instance of the /// with the specified type. /// /// The type of the to consume. /// is . public PluginConsumerAttribute(Type type) { if (type == null) { throw new ArgumentNullException("type"); } _type = type; } public Type PluginType { get { return _type; } } } } nant-0.92-rc1/src/NAnt.Core/Extensibility/ExtensionAssembly.cs0000644000175000017500000001006211757302273024204 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2008 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net.be) using System; using System.Collections; using System.IO; using System.Reflection; using System.Xml; namespace NAnt.Core.Extensibility { /// /// Represents an in which one or more extensions /// are found. /// internal class ExtensionAssembly { /// /// Initializes a new instance of the /// class for a given . /// /// /// The instance is not cached for /// future use. If this is required, use . /// /// The for which to construct an . internal ExtensionAssembly(Assembly assembly) { _assembly = assembly; } /// /// Gets the containing extensions. /// public Assembly Assembly { get { return _assembly; } } internal XmlNode ConfigurationSection { get { if (_configurationInit) return _configurationSection; try { Stream s = _assembly.GetManifestResourceStream ("NAnt.Extension.config"); if (s != null) { try { XmlDocument doc = new XmlDocument (); doc.Load (s); _configurationSection = doc.DocumentElement; } finally { s.Close (); } } return _configurationSection; } finally { _configurationInit = true; } } } /// /// Creates an for the specified /// and caches it for future use. /// /// /// If an for the same assembly is /// available in the cache, then this cached instance is returned. /// /// The for which to construct an . /// /// The for the specified . /// public static ExtensionAssembly Create (Assembly assembly) { if (assembly == null) throw new ArgumentNullException ("assembly"); string aname = assembly.FullName; ExtensionAssembly ext = _extensionAssemblies [aname] as ExtensionAssembly; if (ext == null) { ext = new ExtensionAssembly (assembly); _extensionAssemblies [aname] = assembly; } return ext; } private static Hashtable _extensionAssemblies = new Hashtable (); private readonly Assembly _assembly; private XmlNode _configurationSection; private bool _configurationInit; } } nant-0.92-rc1/src/NAnt.Core/Extensibility/ExtensionBuilder.cs0000644000175000017500000000553611757302273024025 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2008 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net.be) using System; using System.Reflection; namespace NAnt.Core.Extensibility { public abstract class ExtensionBuilder { /// /// Initializes a instance of the /// class for an extension in a given . /// /// The in which the extension is found. /// is . internal ExtensionBuilder(ExtensionAssembly extensionAssembly) { if (extensionAssembly == null) { throw new ArgumentNullException("extensionAssembly"); } _extensionAssembly = extensionAssembly; } /// /// Initializes a instance of the /// class for an extension in a given . /// /// The in which the extension is found. /// is . protected ExtensionBuilder(Assembly assembly) : this (ExtensionAssembly.Create (assembly)) { } /// /// Gets the in which the extension /// was found. /// internal ExtensionAssembly ExtensionAssembly { get { return _extensionAssembly; } } /// /// Gets the from which the extension will /// be created. /// /// /// The containing the extension. /// protected internal Assembly Assembly { get { return ExtensionAssembly.Assembly; } } private readonly ExtensionAssembly _extensionAssembly; } } nant-0.92-rc1/src/NAnt.Core/Extensibility/PluginBuilder.cs0000644000175000017500000000251711757302273023303 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2008 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net.be) using System; namespace NAnt.Core.Extensibility { internal class PluginBuilder : ExtensionBuilder { internal PluginBuilder(ExtensionAssembly extensionAssembly, Type pluginType) : base (extensionAssembly) { _pluginType = pluginType; } public Type PluginType { get { return _pluginType; } } public IPlugin CreatePlugin() { return (IPlugin) Activator.CreateInstance(PluginType); } private readonly Type _pluginType; } } nant-0.92-rc1/src/NAnt.Core/Extensibility/PluginScanner.cs0000644000175000017500000000712311757302273023304 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2008 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net.be) using System; using System.Collections; using System.Globalization; using System.Text; namespace NAnt.Core.Extensibility { /// /// Responsible for scanning types for plugins, and maintaining a cache of /// instances. /// internal class PluginScanner { private readonly ArrayList _pluginBuilders = new ArrayList(); /// /// Scans a given for plugins. /// /// The containing the to scan. /// The to scan. /// The which will be used to output messages to the build log. /// /// if represents a /// ; otherwise, . /// public bool ScanTypeForPlugins(ExtensionAssembly extensionAssembly, Type type, Task task) { if (type.IsAbstract) return false; try { bool isplugin = typeof(IPlugin).IsAssignableFrom(type); if (!isplugin) { return false; } PluginBuilder pb = new PluginBuilder(extensionAssembly, type); _pluginBuilders.Add(pb); return true; } catch { task.Log(Level.Error, "Failure scanning \"{0}\" for plugins.", type.AssemblyQualifiedName); throw; } } /// /// Registers matching plugins for the specified . /// /// The which plugins must be registered for. /// is . public void RegisterPlugins (IPluginConsumer consumer) { if (consumer == null) { throw new ArgumentNullException ("consumer"); } object[] consumes = consumer.GetType().GetCustomAttributes( typeof(PluginConsumerAttribute), false); if (consumes.Length == 0) { return; } foreach (PluginBuilder pb in _pluginBuilders) { foreach (PluginConsumerAttribute c in consumes) { if (c.PluginType.IsAssignableFrom (pb.PluginType)) { consumer.ConsumePlugin(pb.CreatePlugin()); break; } } } } } } nant-0.92-rc1/src/NAnt.Core/Extensibility/FunctionArgument.cs0000644000175000017500000000373611757302273024032 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2008 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net.be) using System; namespace NAnt.Core.Extensibility { internal class FunctionArgument { public FunctionArgument(string name, int index, object value, ExpressionTokenizer.Position beforeArgument, ExpressionTokenizer.Position afterArgument) { this._name = name; this._index = index; this._value = value; this._beforeArgument = beforeArgument; this._afterArgument = afterArgument; } public int Index { get { return _index; } } public string Name { get { return _name; } } public object Value { get { return _value; } } public ExpressionTokenizer.Position BeforeArgument { get { return _beforeArgument; } } public ExpressionTokenizer.Position AfterArgument { get { return _afterArgument; } } private readonly int _index; private readonly string _name; private readonly object _value; private readonly ExpressionTokenizer.Position _beforeArgument; private readonly ExpressionTokenizer.Position _afterArgument; } } nant-0.92-rc1/src/NAnt.Core/NAnt.Core.build0000644000175000017500000000330211757302273020114 0ustar jtaylorjtaylor nant-0.92-rc1/src/NAnt.Core/ExpressionEvalBase.cs0000644000175000017500000015706711757302273021457 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Jaroslaw Kowalski (jkowalski@users.sourceforge.net) using System; using System.IO; using System.Collections; using System.Globalization; using System.Reflection; using System.Text; using NAnt.Core.Extensibility; using NAnt.Core.Util; namespace NAnt.Core { public abstract class ExpressionEvalBase { enum EvalMode { Evaluate, ParseOnly } private EvalMode _evalMode = EvalMode.Evaluate; private ExpressionTokenizer _tokenizer; private readonly Project _project; public ExpressionEvalBase(Project project) { if (project == null) throw new ArgumentNullException("project"); _project = project; } #region Public Instance Properties public Project Project { get { return _project; } } #endregion Public Instance Properties public object Evaluate(ExpressionTokenizer tokenizer) { _evalMode = EvalMode.Evaluate; _tokenizer = tokenizer; return ParseExpression(); } public object Evaluate(string s) { _tokenizer = new ExpressionTokenizer(); _evalMode = EvalMode.Evaluate; _tokenizer.InitTokenizer(s); object val = ParseExpression(); if (_tokenizer.CurrentToken != ExpressionTokenizer.TokenType.EOF) { throw BuildParseError("Unexpected token at the end of expression", _tokenizer.CurrentPosition); } return val; } public void CheckSyntax(string s) { _tokenizer = new ExpressionTokenizer(); _evalMode = EvalMode.ParseOnly; _tokenizer.InitTokenizer(s); ParseExpression(); if (_tokenizer.CurrentToken != ExpressionTokenizer.TokenType.EOF) { throw BuildParseError("Unexpected token at the end of expression", _tokenizer.CurrentPosition); } } #region Parser bool SyntaxCheckOnly() { return _evalMode == EvalMode.ParseOnly; } private object ParseExpression() { return ParseBooleanOr(); } private object ParseBooleanOr() { ExpressionTokenizer.Position p0 = _tokenizer.CurrentPosition; object o = ParseBooleanAnd(); EvalMode oldEvalMode = _evalMode; try { while (_tokenizer.IsKeyword("or")) { bool v1 = true; if (!SyntaxCheckOnly()) { v1 = (bool)SafeConvert(typeof(bool), o, "the left hand side of the 'or' operator", p0, _tokenizer.CurrentPosition); if (v1) { // we're lazy - don't evaluate anything from now, we know that the result is 'true' _evalMode = EvalMode.ParseOnly; } } _tokenizer.GetNextToken(); ExpressionTokenizer.Position p2 = _tokenizer.CurrentPosition; object o2 = ParseBooleanAnd(); ExpressionTokenizer.Position p3 = _tokenizer.CurrentPosition; if (!SyntaxCheckOnly()) { bool v2 = (bool)SafeConvert(typeof(bool), o2, "the right hand side of the 'or' operator", p2, p3); o = v1 || v2; } } return o; } finally { _evalMode = oldEvalMode; } } private object ParseBooleanAnd() { ExpressionTokenizer.Position p0 = _tokenizer.CurrentPosition; object o = ParseRelationalExpression(); EvalMode oldEvalMode = _evalMode; try { while (_tokenizer.IsKeyword("and")) { bool v1 = true; if (!SyntaxCheckOnly()) { v1 = (bool)SafeConvert(typeof(bool), o, "the left hand side of the 'and' operator", p0, _tokenizer.CurrentPosition); if (!v1) { // we're lazy - don't evaluate anything from now, we know that the result is 'true' _evalMode = EvalMode.ParseOnly; } } _tokenizer.GetNextToken(); ExpressionTokenizer.Position p2 = _tokenizer.CurrentPosition; object o2 = ParseRelationalExpression(); ExpressionTokenizer.Position p3 = _tokenizer.CurrentPosition; if (!SyntaxCheckOnly()) { bool v2 = (bool)SafeConvert(typeof(bool), o2, "the right hand side of the 'and' operator", p2, p3); o = v1 && v2; } } return o; } finally { _evalMode = oldEvalMode; } } private object ParseRelationalExpression() { ExpressionTokenizer.Position p0 = _tokenizer.CurrentPosition; object o = ParseAddSubtract(); if (_tokenizer.CurrentToken == ExpressionTokenizer.TokenType.EQ || _tokenizer.CurrentToken == ExpressionTokenizer.TokenType.NE || _tokenizer.CurrentToken == ExpressionTokenizer.TokenType.LT || _tokenizer.CurrentToken == ExpressionTokenizer.TokenType.GT || _tokenizer.CurrentToken == ExpressionTokenizer.TokenType.LE || _tokenizer.CurrentToken == ExpressionTokenizer.TokenType.GE) { ExpressionTokenizer.TokenType op = _tokenizer.CurrentToken; _tokenizer.GetNextToken(); object o2 = ParseAddSubtract(); ExpressionTokenizer.Position p2 = _tokenizer.CurrentPosition; if (SyntaxCheckOnly()) { return null; } switch (op) { case ExpressionTokenizer.TokenType.EQ: if (o is string && o2 is string) { return o.Equals(o2); } else if (o is bool && o2 is bool) { return o.Equals(o2); } else if (o is int && o2 is int) { return o.Equals(o2); } else if (o is int && o2 is long) { return (Convert.ToInt64(o)).Equals(o2); } else if (o is int && o2 is double) { return (Convert.ToDouble(o)).Equals(o2); } else if (o is long && o2 is long) { return o.Equals(o2); } else if (o is long && o2 is int) { return (o.Equals(Convert.ToInt64(o2))); } else if (o is long && o2 is double) { return (Convert.ToDouble(o)).Equals(o2); } else if (o is double && o2 is double) { return o.Equals(o2); } else if (o is double && o2 is int) { return o.Equals(Convert.ToDouble(o2)); } else if (o is double && o2 is long) { return o.Equals(Convert.ToDouble(o2)); } else if (o is DateTime && o2 is DateTime) { return o.Equals(o2); } else if (o is TimeSpan && o2 is TimeSpan) { return o.Equals(o2); } else if (o is Version && o2 is Version) { return o.Equals(o2); } else if (o.GetType().IsEnum) { if (o2 is string) { return o.Equals(Enum.Parse(o.GetType(), (string) o2, false)); } else { return o.Equals(Enum.ToObject(o.GetType(), o2)); } } else if (o2.GetType().IsEnum) { if (o is string) { return o2.Equals(Enum.Parse(o2.GetType(), (string) o, false)); } else { return o2.Equals(Enum.ToObject(o2.GetType(), o)); } } throw BuildParseError(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1038"), GetSimpleTypeName(o.GetType()), GetSimpleTypeName(o2.GetType())), p0, p2); case ExpressionTokenizer.TokenType.NE: if (o is string && o2 is string) { return !o.Equals(o2); } else if (o is bool && o2 is bool) { return !o.Equals(o2); } else if (o is int && o2 is int) { return !o.Equals(o2); } else if (o is int && o2 is long) { return !(Convert.ToInt64(o)).Equals(o2); } else if (o is int && o2 is double) { return !(Convert.ToDouble(o)).Equals(o2); } else if (o is long && o2 is long) { return !o.Equals(o2); } else if (o is long && o2 is int) { return !(o.Equals(Convert.ToInt64(o2))); } else if (o is long && o2 is double) { return !(Convert.ToDouble(o)).Equals(o2); } else if (o is double && o2 is double) { return !o.Equals(o2); } else if (o is double && o2 is int) { return !o.Equals(Convert.ToDouble(o2)); } else if (o is double && o2 is long) { return !o.Equals(Convert.ToDouble(o2)); } else if (o is DateTime && o2 is DateTime) { return !o.Equals(o2); } else if (o is TimeSpan && o2 is TimeSpan) { return !o.Equals(o2); } else if (o is Version && o2 is Version) { return !o.Equals(o2); } else if (o.GetType().IsEnum) { if (o2 is string) { return !o.Equals(Enum.Parse(o.GetType(), (string) o2, false)); } else { return !o.Equals(Enum.ToObject(o.GetType(), o2)); } } else if (o2.GetType().IsEnum) { if (o is string) { return !o2.Equals(Enum.Parse(o2.GetType(), (string) o, false)); } else { return !o2.Equals(Enum.ToObject(o2.GetType(), o)); } } throw BuildParseError(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1042"), GetSimpleTypeName(o.GetType()), GetSimpleTypeName(o2.GetType())), p0, p2); case ExpressionTokenizer.TokenType.LT: if (o is string && o2 is string) { return string.Compare((string) o, (string) o2, false, CultureInfo.InvariantCulture) < 0; } else if (o is bool && o2 is bool) { return ((IComparable) o).CompareTo(o2) < 0; } else if (o is int && o2 is int) { return ((IComparable) o).CompareTo(o2) < 0; } else if (o is int && o2 is long) { return ((IComparable) Convert.ToInt64(o)).CompareTo(o2) < 0; } else if (o is int && o2 is double) { return ((IComparable) Convert.ToDouble(o)).CompareTo(o2) < 0; } else if (o is long && o2 is long) { return ((IComparable) o).CompareTo(o2) < 0; } else if (o is long && o2 is int) { return ((IComparable) o).CompareTo(Convert.ToInt64(o2)) < 0; } else if (o is long && o2 is double) { return ((IComparable) Convert.ToDouble(o)).CompareTo(o2) < 0; } else if (o is double && o2 is double) { return ((IComparable) o).CompareTo(o2) < 0; } else if (o is double && o2 is int) { return ((IComparable) o).CompareTo(Convert.ToDouble(o2)) < 0; } else if (o is double && o2 is long) { return ((IComparable) o).CompareTo(Convert.ToDouble(o2)) < 0; } else if (o is DateTime && o2 is DateTime) { return ((IComparable) o).CompareTo(o2) < 0; } else if (o is TimeSpan && o2 is TimeSpan) { return ((IComparable) o).CompareTo(o2) < 0; } else if (o is Version && o2 is Version) { return ((IComparable) o).CompareTo(o2) < 0; } throw BuildParseError(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1051"), GetSimpleTypeName(o.GetType()), GetSimpleTypeName(o2.GetType())), p0, p2); case ExpressionTokenizer.TokenType.GT: if (o is string && o2 is string) { return string.Compare((string) o, (string) o2, false, CultureInfo.InvariantCulture) > 0; } else if (o is bool && o2 is bool) { return ((IComparable) o).CompareTo(o2) > 0; } else if (o is int && o2 is int) { return ((IComparable) o).CompareTo(o2) > 0; } else if (o is int && o2 is long) { return ((IComparable) Convert.ToInt64(o)).CompareTo(o2) > 0; } else if (o is int && o2 is double) { return ((IComparable) Convert.ToDouble(o)).CompareTo(o2) > 0; } else if (o is long && o2 is long) { return ((IComparable) o).CompareTo(o2) > 0; } else if (o is long && o2 is int) { return ((IComparable) o).CompareTo(Convert.ToInt64(o2)) > 0; } else if (o is long && o2 is double) { return ((IComparable) Convert.ToDouble(o)).CompareTo(o2) > 0; } else if (o is double && o2 is double) { return ((IComparable) o).CompareTo(o2) > 0; } else if (o is double && o2 is int) { return ((IComparable) o).CompareTo(Convert.ToDouble(o2)) > 0; } else if (o is double && o2 is long) { return ((IComparable) o).CompareTo(Convert.ToDouble(o2)) > 0; } else if (o is DateTime && o2 is DateTime) { return ((IComparable) o).CompareTo(o2) > 0; } else if (o is TimeSpan && o2 is TimeSpan) { return ((IComparable) o).CompareTo(o2) > 0; } else if (o is Version && o2 is Version) { return ((IComparable) o).CompareTo(o2) > 0; } throw BuildParseError(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1037"), GetSimpleTypeName(o.GetType()), GetSimpleTypeName(o2.GetType())), p0, p2); case ExpressionTokenizer.TokenType.LE: if (o is string && o2 is string) { return string.Compare((string) o, (string) o2, false, CultureInfo.InvariantCulture) <= 0; } else if (o is bool && o2 is bool) { return ((IComparable) o).CompareTo(o2) <= 0; } else if (o is int && o2 is int) { return ((IComparable) o).CompareTo(o2) <= 0; } else if (o is int && o2 is long) { return ((IComparable) Convert.ToInt64(o)).CompareTo(o2) <= 0; } else if (o is int && o2 is double) { return ((IComparable) Convert.ToDouble(o)).CompareTo(o2) <= 0; } else if (o is long && o2 is long) { return ((IComparable) o).CompareTo(o2) <= 0; } else if (o is long && o2 is int) { return ((IComparable) o).CompareTo(Convert.ToInt64(o2)) <= 0; } else if (o is long && o2 is double) { return ((IComparable) Convert.ToDouble(o)).CompareTo(o2) <= 0; } else if (o is double && o2 is double) { return ((IComparable) o).CompareTo(o2) <= 0; } else if (o is double && o2 is int) { return ((IComparable) o).CompareTo(Convert.ToDouble(o2)) <= 0; } else if (o is double && o2 is long) { return ((IComparable) o).CompareTo(Convert.ToDouble(o2)) <= 0; } else if (o is DateTime && o2 is DateTime) { return ((IComparable) o).CompareTo(o2) <= 0; } else if (o is TimeSpan && o2 is TimeSpan) { return ((IComparable) o).CompareTo(o2) <= 0; } else if (o is Version && o2 is Version) { return ((IComparable) o).CompareTo(o2) <= 0; } throw BuildParseError(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1049"), GetSimpleTypeName(o.GetType()), GetSimpleTypeName(o2.GetType())), p0, p2); case ExpressionTokenizer.TokenType.GE: if (o is string && o2 is string) { return string.Compare((string) o, (string) o2, false, CultureInfo.InvariantCulture) >= 0; } else if (o is bool && o2 is bool) { return ((IComparable) o).CompareTo(o2) >= 0; } else if (o is int && o2 is int) { return ((IComparable) o).CompareTo(o2) >= 0; } else if (o is int && o2 is long) { return ((IComparable) Convert.ToInt64(o)).CompareTo(o2) >= 0; } else if (o is int && o2 is double) { return ((IComparable) Convert.ToDouble(o)).CompareTo(o2) >= 0; } else if (o is long && o2 is long) { return ((IComparable) o).CompareTo(o2) >= 0; } else if (o is long && o2 is int) { return ((IComparable) o).CompareTo(Convert.ToInt64(o2)) >= 0; } else if (o is long && o2 is double) { return ((IComparable) Convert.ToDouble(o)).CompareTo(o2) >= 0; } else if (o is double && o2 is double) { return ((IComparable) o).CompareTo(o2) >= 0; } else if (o is double && o2 is int) { return ((IComparable) o).CompareTo(Convert.ToDouble(o2)) >= 0; } else if (o is double && o2 is long) { return ((IComparable) o).CompareTo(Convert.ToDouble(o2)) >= 0; } else if (o is DateTime && o2 is DateTime) { return ((IComparable) o).CompareTo(o2) >= 0; } else if (o is TimeSpan && o2 is TimeSpan) { return ((IComparable) o).CompareTo(o2) >= 0; } else if (o is Version && o2 is Version) { return ((IComparable) o).CompareTo(o2) >= 0; } throw BuildParseError(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1050"), GetSimpleTypeName(o.GetType()), GetSimpleTypeName(o2.GetType())), p0, p2); } } return o; } private object ParseAddSubtract() { ExpressionTokenizer.Position p0 = _tokenizer.CurrentPosition; object o = ParseMulDiv(); while (true) { if (_tokenizer.CurrentToken == ExpressionTokenizer.TokenType.Plus) { _tokenizer.GetNextToken(); object o2 = ParseMulDiv(); ExpressionTokenizer.Position p3 = _tokenizer.CurrentPosition; if (!SyntaxCheckOnly()) { if (o is string && o2 is string) { o = (string) o + (string) o2; } else if (o is int && o2 is int) { o = (int) o + (int) o2; } else if (o is int && o2 is long) { o = (int) o + (long) o2; } else if (o is int && o2 is double) { o = (int) o + (double) o2; } else if (o is long && o2 is long) { o = (long) o + (long) o2; } else if (o is long && o2 is int) { o = (long) o + (int) o2; } else if (o is long && o2 is double) { o = (long) o + (double) o2; } else if (o is double && o2 is double) { o = (double) o + (double) o2; } else if (o is double && o2 is int) { o = (double) o + (int) o2; } else if (o is double && o2 is long) { o = (double) o + (long) o2; } else if (o is DateTime && o2 is TimeSpan) { o = (DateTime) o + (TimeSpan) o2; } else if (o is TimeSpan && o2 is TimeSpan) { o = (TimeSpan) o + (TimeSpan) o2; } else { throw BuildParseError(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1041"), GetSimpleTypeName(o.GetType()), GetSimpleTypeName(o2.GetType())), p0, p3); } } } else if (_tokenizer.CurrentToken == ExpressionTokenizer.TokenType.Minus) { _tokenizer.GetNextToken(); object o2 = ParseMulDiv(); ExpressionTokenizer.Position p3 = _tokenizer.CurrentPosition; if (!SyntaxCheckOnly()) { if (o is int && o2 is int) { o = (int) o - (int) o2; } else if (o is int && o2 is long) { o = (int) o - (long) o2; } else if (o is int && o2 is double) { o = (int) o - (double) o2; } else if (o is long && o2 is long) { o = (long) o - (long) o2; } else if (o is long && o2 is int) { o = (long) o - (int) o2; } else if (o is long && o2 is double) { o = (long) o - (double) o2; } else if (o is double && o2 is double) { o = (double) o - (double) o2; } else if (o is double && o2 is int) { o = (double) o - (int) o2; } else if (o is double && o2 is long) { o = (double) o - (long) o2; } else if (o is DateTime && o2 is DateTime) { o = (DateTime) o - (DateTime) o2; } else if (o is DateTime && o2 is TimeSpan) { o = (DateTime) o - (TimeSpan) o2; } else if (o is TimeSpan && o2 is TimeSpan) { o = (TimeSpan) o - (TimeSpan) o2; } else { throw BuildParseError(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1048"), GetSimpleTypeName(o.GetType()), GetSimpleTypeName(o2.GetType())), p0, p3); } } } else { break; } } return o; } private object ParseMulDiv() { ExpressionTokenizer.Position p0 = _tokenizer.CurrentPosition; object o = ParseValue(); while (true) { if (_tokenizer.CurrentToken == ExpressionTokenizer.TokenType.Mul) { _tokenizer.GetNextToken(); object o2 = ParseValue(); ExpressionTokenizer.Position p3 = _tokenizer.CurrentPosition; if (!SyntaxCheckOnly()) { if (o is int && o2 is int) { o = (int) o * (int) o2; } else if (o is int && o2 is long) { o = (int) o * (long) o2; } else if (o is int && o2 is double) { o = (int) o * (double) o2; } else if (o is long && o2 is long) { o = (long) o * (long) o2; } else if (o is long && o2 is int) { o = (long) o * (int) o2; } else if (o is long && o2 is double) { o = (long) o * (double) o2; } else if (o is double && o2 is double) { o = (double) o * (double) o2; } else if (o is double && o2 is int) { o = (double) o * (int) o2; } else if (o is double && o2 is long) { o = (double) o * (long) o2; } else { throw BuildParseError(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1036"), GetSimpleTypeName(o.GetType()), GetSimpleTypeName(o2.GetType())), p0, p3); } } } else if (_tokenizer.CurrentToken == ExpressionTokenizer.TokenType.Div) { _tokenizer.GetNextToken(); ExpressionTokenizer.Position p2 = _tokenizer.CurrentPosition; object o2 = ParseValue(); ExpressionTokenizer.Position p3 = _tokenizer.CurrentPosition; if (!SyntaxCheckOnly()) { if (o is int && o2 is int) { if ((int) o2 == 0) { throw BuildParseError(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1043")), p2, p3); } o = (int) o / (int) o2; } else if (o is int && o2 is long) { if ((long) o2 == 0) { throw BuildParseError(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1043")), p2, p3); } o = (int) o / (long) o2; } else if (o is int && o2 is double) { if ((double) o2 == 0) { throw BuildParseError(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1043")), p2, p3); } o = (int) o / (double) o2; } else if (o is long && o2 is long) { if ((long) o2 == 0) { throw BuildParseError(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1043")), p2, p3); } o = (long) o / (long) o2; } else if (o is long && o2 is int) { if ((int) o2 == 0) { throw BuildParseError(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1043")), p2, p3); } o = (long) o / (int) o2; } else if (o is long && o2 is double) { if ((double) o2 == 0) { throw BuildParseError(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1043")), p2, p3); } o = (long) o / (double) o2; } else if (o is double && o2 is double) { if ((double) o2 == 0) { throw BuildParseError(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1043")), p2, p3); } o = (double) o / (double) o2; } else if (o is double && o2 is int) { if ((int) o2 == 0) { throw BuildParseError(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1043")), p2, p3); } o = (double) o / (int) o2; } else if (o is double && o2 is long) { if ((long) o2 == 0) { throw BuildParseError(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1043")), p2, p3); } o = (double) o / (long) o2; } else { throw BuildParseError(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1039"), GetSimpleTypeName(o.GetType()), GetSimpleTypeName(o2.GetType())), p0, p3); } } } else if (_tokenizer.CurrentToken == ExpressionTokenizer.TokenType.Mod) { _tokenizer.GetNextToken(); ExpressionTokenizer.Position p2 = _tokenizer.CurrentPosition; object o2 = ParseValue(); ExpressionTokenizer.Position p3 = _tokenizer.CurrentPosition; if (!SyntaxCheckOnly()) { if (o is int && o2 is int) { if ((int) o2 == 0) { throw BuildParseError(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1043")), p2, p3); } o = (int) o % (int) o2; } else if (o is int && o2 is long) { if ((long) o2 == 0) { throw BuildParseError(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1043")), p2, p3); } o = (int) o % (long) o2; } else if (o is int && o2 is double) { if ((double) o2 == 0) { throw BuildParseError(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1043")), p2, p3); } o = (int) o % (double) o2; } else if (o is long && o2 is long) { if ((long) o2 == 0) { throw BuildParseError(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1043")), p2, p3); } o = (long) o % (long) o2; } else if (o is long && o2 is int) { if ((int) o2 == 0) { throw BuildParseError(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1043")), p2, p3); } o = (long) o % (int) o2; } else if (o is long && o2 is double) { if ((double) o2 == 0) { throw BuildParseError(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1043")), p2, p3); } o = (long) o % (double) o2; } else if (o is double && o2 is double) { if ((double) o2 == 0) { throw BuildParseError(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1043")), p2, p3); } o = (double) o % (double) o2; } else if (o is double && o2 is int) { if ((int) o2 == 0) { throw BuildParseError(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1043")), p2, p3); } o = (double) o % (int) o2; } else if (o is double && o2 is long) { if ((long) o2 == 0) { throw BuildParseError(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1043")), p2, p3); } o = (double) o % (long) o2; } else { throw BuildParseError(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1047"), GetSimpleTypeName(o.GetType()), GetSimpleTypeName(o2.GetType())), p0, p3); } } } else { break; } } return o; } private object ParseConditional() { // we're on "if" token - skip it _tokenizer.GetNextToken(); if (_tokenizer.CurrentToken != ExpressionTokenizer.TokenType.LeftParen) { throw BuildParseError("'(' expected.", _tokenizer.CurrentPosition); } _tokenizer.GetNextToken(); ExpressionTokenizer.Position p0 = _tokenizer.CurrentPosition; object val = ParseExpression(); ExpressionTokenizer.Position p1 = _tokenizer.CurrentPosition; bool cond = false; if (!SyntaxCheckOnly()) { cond = (bool) SafeConvert(typeof(bool), val, "the conditional expression", p0, p1); } // skip comma between condition value and then if (_tokenizer.CurrentToken != ExpressionTokenizer.TokenType.Comma) { throw BuildParseError("',' expected.", _tokenizer.CurrentPosition); } _tokenizer.GetNextToken(); EvalMode oldEvalMode = _evalMode; try { if (!cond) { // evaluate 'then' clause without executing functions _evalMode = EvalMode.ParseOnly; } else { _evalMode = oldEvalMode; } object thenValue = ParseExpression(); _evalMode = oldEvalMode; if (_tokenizer.CurrentToken != ExpressionTokenizer.TokenType.Comma) { throw BuildParseError("',' expected.", _tokenizer.CurrentPosition); } _tokenizer.GetNextToken(); // skip comma if (cond) { // evaluate 'else' clause without executing functions _evalMode = EvalMode.ParseOnly; } else { _evalMode = oldEvalMode; } object elseValue = ParseExpression(); _evalMode = oldEvalMode; // skip closing ')' if (_tokenizer.CurrentToken != ExpressionTokenizer.TokenType.RightParen) { throw BuildParseError("')' expected.", _tokenizer.CurrentPosition); } _tokenizer.GetNextToken(); return cond ? thenValue : elseValue; } finally { // restore evaluation mode - even on exceptions _evalMode = oldEvalMode; } } private object ParseValue() { if (_tokenizer.CurrentToken == ExpressionTokenizer.TokenType.String) { object v = _tokenizer.TokenText; _tokenizer.GetNextToken(); return v; } if (_tokenizer.CurrentToken == ExpressionTokenizer.TokenType.Number) { string number = _tokenizer.TokenText; ExpressionTokenizer.Position p0 = _tokenizer.CurrentPosition; _tokenizer.GetNextToken(); ExpressionTokenizer.Position p1 = new ExpressionTokenizer.Position( _tokenizer.CurrentPosition.CharIndex - 1); if (_tokenizer.CurrentToken == ExpressionTokenizer.TokenType.Dot) { number += "."; _tokenizer.GetNextToken(); if (_tokenizer.CurrentToken != ExpressionTokenizer.TokenType.Number) { throw BuildParseError("Fractional part expected.", _tokenizer.CurrentPosition); } number += _tokenizer.TokenText; _tokenizer.GetNextToken(); p1 = _tokenizer.CurrentPosition; try { return Double.Parse(number, CultureInfo.InvariantCulture); } catch (OverflowException) { throw BuildParseError("Value was either too large or too" + " small for type 'double'.", p0, p1); } } else { try { return Int32.Parse(number, CultureInfo.InvariantCulture); } catch (OverflowException) { try { return long.Parse(number, CultureInfo.InvariantCulture); } catch (OverflowException) { throw BuildParseError("Value was either too large or too" + " small for type 'long'.", p0, p1); } } } } if (_tokenizer.CurrentToken == ExpressionTokenizer.TokenType.Minus) { _tokenizer.GetNextToken(); // unary minus ExpressionTokenizer.Position p0 = _tokenizer.CurrentPosition; object v = ParseValue(); ExpressionTokenizer.Position p1 = _tokenizer.CurrentPosition; if (!SyntaxCheckOnly()) { if (v is int) { return -((int) v); } if (v is long) { return -((long) v); } if (v is double) { return -((double) v); } throw BuildParseError(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1040"), GetSimpleTypeName(v.GetType())), p0, p1); } return null; } if (_tokenizer.IsKeyword("not")) { _tokenizer.GetNextToken(); // unary boolean not ExpressionTokenizer.Position p0 = _tokenizer.CurrentPosition; object v = ParseValue(); ExpressionTokenizer.Position p1 = _tokenizer.CurrentPosition; if (!SyntaxCheckOnly()) { bool value = (bool)SafeConvert(typeof(bool), v, "the argument of 'not' operator", p0, p1); return !value; } return null; } if (_tokenizer.CurrentToken == ExpressionTokenizer.TokenType.LeftParen) { _tokenizer.GetNextToken(); object v = ParseExpression(); if (_tokenizer.CurrentToken != ExpressionTokenizer.TokenType.RightParen) { throw BuildParseError("')' expected.", _tokenizer.CurrentPosition); } _tokenizer.GetNextToken(); return v; } if (_tokenizer.CurrentToken == ExpressionTokenizer.TokenType.Keyword) { ExpressionTokenizer.Position p0 = _tokenizer.CurrentPosition; string functionOrPropertyName = _tokenizer.TokenText; if (functionOrPropertyName == "if") { return ParseConditional(); } if (functionOrPropertyName == "true") { _tokenizer.GetNextToken(); return true; } if (functionOrPropertyName == "false") { _tokenizer.GetNextToken(); return false; } // don't ignore whitespace - properties shouldn't be written with spaces in them _tokenizer.IgnoreWhitespace = false; _tokenizer.GetNextToken(); ArrayList args = new ArrayList(); bool isFunction = false; // gather function or property name if (_tokenizer.CurrentToken == ExpressionTokenizer.TokenType.DoubleColon) { isFunction = true; functionOrPropertyName += "::"; _tokenizer.GetNextToken(); if (_tokenizer.CurrentToken != ExpressionTokenizer.TokenType.Keyword) { throw BuildParseError("Function name expected.", p0, _tokenizer.CurrentPosition); } functionOrPropertyName += _tokenizer.TokenText; _tokenizer.GetNextToken(); } else { while (_tokenizer.CurrentToken == ExpressionTokenizer.TokenType.Dot || _tokenizer.CurrentToken == ExpressionTokenizer.TokenType.Minus || _tokenizer.CurrentToken == ExpressionTokenizer.TokenType.Keyword || _tokenizer.CurrentToken == ExpressionTokenizer.TokenType.Number) { functionOrPropertyName += _tokenizer.TokenText; _tokenizer.GetNextToken(); } } _tokenizer.IgnoreWhitespace = true; // if we've stopped on a whitespace - advance to the next token if (_tokenizer.CurrentToken == ExpressionTokenizer.TokenType.Whitespace) { _tokenizer.GetNextToken(); } MethodInfo function = null; if (isFunction) { if ( _tokenizer.CurrentToken != ExpressionTokenizer.TokenType.LeftParen) { throw BuildParseError("'(' expected.", _tokenizer.CurrentPosition); } _tokenizer.GetNextToken(); int currentArgument = 0; while (_tokenizer.CurrentToken != ExpressionTokenizer.TokenType.RightParen && _tokenizer.CurrentToken != ExpressionTokenizer.TokenType.EOF) { ExpressionTokenizer.Position beforeArgument = _tokenizer.CurrentPosition; object e = ParseExpression(); ExpressionTokenizer.Position afterArgument = _tokenizer.CurrentPosition; args.Add (new FunctionArgument(functionOrPropertyName, currentArgument, e, beforeArgument, afterArgument)); currentArgument++; if (_tokenizer.CurrentToken == ExpressionTokenizer.TokenType.RightParen) break; if (_tokenizer.CurrentToken != ExpressionTokenizer.TokenType.Comma) throw BuildParseError("',' expected.", _tokenizer.CurrentPosition); _tokenizer.GetNextToken(); } if (_tokenizer.CurrentToken != ExpressionTokenizer.TokenType.RightParen) { throw BuildParseError("')' expected.", _tokenizer.CurrentPosition); } _tokenizer.GetNextToken(); if (!SyntaxCheckOnly()) { FunctionArgument[] functionArgs = new FunctionArgument[args.Count]; args.CopyTo(0, functionArgs, 0, args.Count); // lookup function matching name and argument count try { function = TypeFactory.LookupFunction(functionOrPropertyName, functionArgs, Project); } catch (BuildException ex) { throw BuildParseError(ex.Message, p0, _tokenizer.CurrentPosition); } ParameterInfo[] formalParameters = function.GetParameters (); args.Clear (); for (int i = 0; i < functionArgs.Length; i++) { FunctionArgument arg = functionArgs[i]; ParameterInfo pi = formalParameters[i]; object convertedValue = SafeConvert(pi.ParameterType, arg.Value, string.Format(CultureInfo.InvariantCulture, "argument {1} ({0}) of {2}()", pi.Name, arg.Index, arg.Name), arg.BeforeArgument, arg.AfterArgument); args.Add(convertedValue); } } } try { if (!SyntaxCheckOnly()) { if (isFunction) { return EvaluateFunction(function, args.ToArray ()); } else { return EvaluateProperty(functionOrPropertyName); } } else { return null; // this is needed because of short-circuit evaluation } } catch (Exception e) { if (isFunction) { throw BuildParseError("Function call failed.", p0, _tokenizer.CurrentPosition, e); } else { throw BuildParseError("Property evaluation failed.", p0, _tokenizer.CurrentPosition, e); } } } return UnexpectedToken(); } protected ExpressionParseException BuildParseError(string desc, ExpressionTokenizer.Position p0) { return new ExpressionParseException(desc, p0.CharIndex); } protected ExpressionParseException BuildParseError(string desc, ExpressionTokenizer.Position p0, ExpressionTokenizer.Position p1) { return new ExpressionParseException(desc, p0.CharIndex, p1.CharIndex); } protected ExpressionParseException BuildParseError(string desc, ExpressionTokenizer.Position p0, ExpressionTokenizer.Position p1, Exception ex) { return new ExpressionParseException(desc, p0.CharIndex, p1.CharIndex, ex); } protected object SafeConvert(Type returnType, object source, string description, ExpressionTokenizer.Position p0, ExpressionTokenizer.Position p1) { try { // // TODO - Convert.ChangeType() is very liberal. It allows you to convert "true" to Double (1.0). // We shouldn't allow this. Add more cases like this here. // bool disallow = false; if (source == null) { if (returnType == typeof(string)) { return string.Empty; } throw BuildParseError(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1045"), description, GetSimpleTypeName(returnType)), p0, p1); } if (source is bool) { if (returnType != typeof(string) && returnType != typeof(bool)) { // boolean can only be converted to string or boolean disallow = true; } } if (returnType == typeof(bool)) { if (!(source is string || source is bool)) { // only string and boolean can be converted to boolean disallow = true; } } if (source is DateTime) { if (returnType != typeof(string) && returnType != typeof(DateTime)) { // DateTime can only be converted to string or DateTime disallow = true; } } if (returnType == typeof(DateTime)) { if (!(source is DateTime || source is string)) { // only string and DateTime can be converted to DateTime disallow = true; } } if (source is TimeSpan && returnType != typeof(TimeSpan)) { // implicit conversion from TimeSpan is not supported, as // TimeSpan does not implement IConvertible disallow = true; } if (returnType == typeof(TimeSpan) && !(source is TimeSpan)) { // implicit conversion to TimeSpan is not supported disallow = true; } if (returnType == typeof(string)) { if (source is DirectoryInfo) { return ((DirectoryInfo) source).FullName; } else if (source is FileInfo) { return ((FileInfo) source).FullName; } } if (returnType.IsEnum) { string sourceText = source as string; if (sourceText != null) { // support both ',' and ' ' as separator chars for flags string[] flags = sourceText.Split(' ', ','); StringBuilder sb = new StringBuilder(sourceText.Length); for (int i = 0; i < flags.Length; i++) { string flag = flags[i].Trim(); if (flag.Length == 0) continue; if (sb.Length > 0) sb.Append(','); sb.Append(flag); } return Enum.Parse(returnType, sb.ToString(), true); } else { return Enum.ToObject(returnType, source); } } if (disallow) { throw BuildParseError(string.Format(CultureInfo.InvariantCulture, "Cannot convert {0} to '{1}' (actual type was '{2}').", description, GetSimpleTypeName(returnType), GetSimpleTypeName(source.GetType())), p0, p1); } if (returnType.IsAssignableFrom(source.GetType())) return source; return Convert.ChangeType(source, returnType, CultureInfo.InvariantCulture); } catch (ExpressionParseException) { throw; } catch (Exception ex) { throw BuildParseError(string.Format(CultureInfo.InvariantCulture, "Cannot convert {0} to '{1}' (actual type was '{2}').", description, GetSimpleTypeName(returnType), GetSimpleTypeName(source.GetType())), p0, p1, ex); } } protected string GetSimpleTypeName(Type t) { if (t == typeof(int)) { return "int"; } else if (t == typeof(long)) { return "long"; } else if (t == typeof(double)) { return "double"; } else if (t == typeof(string)) { return "string"; } else if (t == typeof(bool)) { return "bool"; } else if (t == typeof(DateTime)) { return "datetime"; } else if (t == typeof(TimeSpan)) { return "timespan"; } else { return t.FullName; } } #endregion Parser #region Overridables protected abstract object EvaluateFunction(MethodInfo method, object[] args); protected abstract object EvaluateProperty(string propertyName); protected virtual object UnexpectedToken() { throw BuildParseError(string.Format(CultureInfo.InvariantCulture, "Unexpected token '{0}'.", _tokenizer.CurrentToken), _tokenizer.CurrentPosition); } #endregion Overridables } } nant-0.92-rc1/src/NAnt.Core/ConfigurationSection.cs0000644000175000017500000000265311757302272022036 0ustar jtaylorjtaylor// $Id: ConfigurationSection.cs,v 1.4 2004/04/28 07:36:11 drieseng Exp $ // NAnt - A .NET build tool // Copyright (C) 2003 Scott Hernandez // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Scott Hernandez (ScottHernandez@hotmail.com using System; using System.Text; using System.Xml; using System.Configuration; namespace NAnt.Core{ /// /// Custom configuration section handler for the element. /// public class ConfigurationSection : IConfigurationSectionHandler { /// /// This just passed things through. Return the node read from the config file. /// public Object Create(Object parent, Object configContext, XmlNode node) { return node; } } } nant-0.92-rc1/src/NAnt.Core/DataTypeBaseBuilderCollection.cs0000644000175000017500000002540111757302272023527 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian MacLean (imaclean@gmail.com) using System; using System.Collections; namespace NAnt.Core { /// /// Contains a strongly typed collection of objects. /// [Serializable] public class DataTypeBaseBuilderCollection : CollectionBase { #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public DataTypeBaseBuilderCollection() { } /// /// Initializes a new instance of the class /// with the specified instance. /// public DataTypeBaseBuilderCollection(DataTypeBaseBuilderCollection value) { AddRange(value); } /// /// Initializes a new instance of the class /// with the specified array of instances. /// public DataTypeBaseBuilderCollection(DataTypeBaseBuilder[] value) { AddRange(value); } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets the element at the specified index. /// /// The zero-based index of the element to get or set. [System.Runtime.CompilerServices.IndexerName("Item")] public DataTypeBaseBuilder this[int index] { get {return ((DataTypeBaseBuilder)(base.List[index]));} set {base.List[index] = value;} } /// /// Gets the for the specified task. /// /// The name of task for which the should be located in the collection. [System.Runtime.CompilerServices.IndexerName("Item")] public DataTypeBaseBuilder this[string dataTypeName] { get { if (dataTypeName != null) { // Try to locate instance using TaskName foreach (DataTypeBaseBuilder DataTypeBaseBuilder in base.List) { if (dataTypeName.Equals(DataTypeBaseBuilder.DataTypeName)) { return DataTypeBaseBuilder; } } } return null; } } #endregion Public Instance Properties #region Public Instance Methods /// /// Adds a to the end of the collection. /// /// The to be added to the end of the collection. /// The position into which the new element was inserted. public int Add(DataTypeBaseBuilder item) { return base.List.Add(item); } /// /// Adds the elements of a array to the end of the collection. /// /// The array of elements to be added to the end of the collection. public void AddRange(DataTypeBaseBuilder[] items) { for (int i = 0; (i < items.Length); i = (i + 1)) { Add(items[i]); } } /// /// Adds the elements of a to the end of the collection. /// /// The to be added to the end of the collection. public void AddRange(DataTypeBaseBuilderCollection items) { for (int i = 0; (i < items.Count); i = (i + 1)) { Add(items[i]); } } /// /// Determines whether a is in the collection. /// /// The to locate in the collection. /// /// if is found in the /// collection; otherwise, . /// public bool Contains(DataTypeBaseBuilder item) { return base.List.Contains(item); } /// /// Determines whether a for the specified /// task is in the collection. /// /// The name of task for which the should be located in the collection. /// /// if a for /// the specified task is found in the collection; otherwise, /// . /// public bool Contains(string taskName) { return this[taskName] != null; } /// /// Copies the entire collection to a compatible one-dimensional array, starting at the specified index of the target array. /// /// The one-dimensional array that is the destination of the elements copied from the collection. The array must have zero-based indexing. /// The zero-based index in at which copying begins. public void CopyTo(DataTypeBaseBuilder[] array, int index) { base.List.CopyTo(array, index); } /// /// Retrieves the index of a specified object in the collection. /// /// The object for which the index is returned. /// /// The index of the specified . If the is not currently a member of the collection, it returns -1. /// public int IndexOf(DataTypeBaseBuilder item) { return base.List.IndexOf(item); } /// /// Inserts a into the collection at the specified index. /// /// The zero-based index at which should be inserted. /// The to insert. public void Insert(int index, DataTypeBaseBuilder item) { base.List.Insert(index, item); } /// /// Returns an enumerator that can iterate through the collection. /// /// /// A for the entire collection. /// public new DataTypeBaseBuilderEnumerator GetEnumerator() { return new DataTypeBaseBuilderEnumerator(this); } /// /// Removes a member from the collection. /// /// The to remove from the collection. public void Remove(DataTypeBaseBuilder item) { base.List.Remove(item); } #endregion Public Instance Methods } /// /// Enumerates the elements of a . /// public class DataTypeBaseBuilderEnumerator : IEnumerator { #region Internal Instance Constructors /// /// Initializes a new instance of the class /// with the specified . /// /// The collection that should be enumerated. internal DataTypeBaseBuilderEnumerator(DataTypeBaseBuilderCollection arguments) { IEnumerable temp = (IEnumerable) (arguments); _baseEnumerator = temp.GetEnumerator(); } #endregion Internal Instance Constructors #region Implementation of IEnumerator /// /// Gets the current element in the collection. /// /// /// The current element in the collection. /// public DataTypeBaseBuilder Current { get { return (DataTypeBaseBuilder) _baseEnumerator.Current; } } object IEnumerator.Current { get { return _baseEnumerator.Current; } } /// /// Advances the enumerator to the next element of the collection. /// /// /// if the enumerator was successfully advanced /// to the next element; if the enumerator has /// passed the end of the collection. /// public bool MoveNext() { return _baseEnumerator.MoveNext(); } bool IEnumerator.MoveNext() { return _baseEnumerator.MoveNext(); } /// /// Sets the enumerator to its initial position, which is before the /// first element in the collection. /// public void Reset() { _baseEnumerator.Reset(); } void IEnumerator.Reset() { _baseEnumerator.Reset(); } #endregion Implementation of IEnumerator #region Private Instance Fields private IEnumerator _baseEnumerator; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.Core/Log.cs0000644000175000017500000015745211757302273016434 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // John R. Hicks (angryjohn69@nc.rr.com) // Gerry Shaw (gerry_shaw@yahoo.com) // William E. Caputo (wecaputo@thoughtworks.com | logosity@yahoo.com) // Gert Driesen (drieseng@users.sourceforge.net) // // Some of this class was based on code from the Mono class library. // Copyright (C) 2002 John R. Hicks // // The events described in this file are based on the comments and // structure of Ant. // Copyright (C) Copyright (c) 2000,2002 The Apache Software Foundation. // All rights reserved. using System; using System.Collections; using System.ComponentModel; using System.Globalization; using System.IO; using System.Runtime.Remoting.Lifetime; using System.Text; using System.Web.Mail; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.Core { /// /// Defines the set of levels recognised by the NAnt logging system. /// [TypeConverter(typeof(LevelConverter))] public enum Level : int { /// /// Designates fine-grained informational events that are most useful /// to debug a build process. /// Debug = 1000, /// /// Designates events that offer a more detailed view of the build /// process. /// Verbose = 2000, /// /// Designates informational events that are useful for getting a /// high-level view of the build process. /// Info = 3000, /// /// Designates potentionally harmful events. /// Warning = 4000, /// /// Designates error events. /// Error = 5000, /// /// Can be used to suppress all messages. /// /// /// No events should be logged with this . /// None = 9999 } /// /// Specialized for /// that ignores case when converting from string. /// internal class LevelConverter : EnumConverter { /// /// Initializes a new instance of the /// class. /// public LevelConverter() : base(typeof(Level)) { } /// /// Converts the given object to the type of this converter, using the /// specified context and culture information. /// /// An that provides a format context. /// A object. If a is passed, the current culture is assumed. /// The to convert. /// /// An that represents the converted value. /// public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { string stringValue = value as string; if (stringValue != null) return Enum.Parse(EnumType, stringValue, true); // default to EnumConverter behavior return base.ConvertFrom(context, culture, value); } } /// /// Class representing an event occurring during a build. /// /// /// /// An event is built by specifying either a project, a task or a target. /// /// /// A level event will only have a /// reference. /// /// /// A level event will have and /// references. /// /// /// A level event will have , /// and references. /// /// public class BuildEventArgs : EventArgs { #region Public Instance Constructors /// /// Initializes a new instance of the /// class. /// public BuildEventArgs() { } /// /// Initializes a new instance of the /// class for a level event. /// /// The that emitted the event. public BuildEventArgs(Project project) { _project = project; } /// /// Initializes a new instance of the /// class for a level event. /// /// The that emitted the event. public BuildEventArgs(Target target) { _project = target.Project; _target = target; } /// /// Initializes a new instance of the /// class for a level event. /// /// The that emitted the event. public BuildEventArgs(Task task) { _project = task.Project; _target = task.Parent as Target; _task = task; } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets the message associated with this event. /// /// /// The message associated with this event. /// public string Message { get { return _message; } set { _message = value; } } /// /// Gets or sets the priority level associated with this event. /// /// /// The priority level associated with this event. /// public Level MessageLevel { get { return _messageLevel; } set { _messageLevel = value; } } /// /// Gets or sets the associated with this event. /// /// /// The associated with this event. /// public Exception Exception { get { return _exception; } set { _exception = value; } } /// /// Gets the that fired this event. /// /// /// The that fired this event. /// public Project Project { get { return _project; } } /// /// Gets the that fired this event. /// /// /// The that fired this event, or a null reference /// if this is a level event. /// public Target Target { get { return _target; } } /// /// Gets the that fired this event. /// /// /// The that fired this event, or /// if this is a or level /// event. /// public Task Task { get { return _task; } } #endregion Public Instance Properties #region Private Instance Fields private readonly Project _project; private readonly Target _target; private readonly Task _task; private string _message; private Level _messageLevel = Level.Verbose; private Exception _exception; #endregion Private Instance Fields } /// /// Represents the method that handles the build events. /// /// The source of the event. /// A that contains the event data. public delegate void BuildEventHandler(object sender, BuildEventArgs e); /// /// Instances of classes that implement this interface can register to be /// notified when things happen during a build. /// public interface IBuildListener { /// /// Signals that a build has started. /// /// The source of the event. /// A object that contains the event data. /// /// This event is fired before any targets have started. /// void BuildStarted(object sender, BuildEventArgs e); /// /// Signals that the last target has finished. /// /// The source of the event. /// A object that contains the event data. /// /// This event will still be fired if an error occurred during the build. /// void BuildFinished(object sender, BuildEventArgs e); /// /// Signals that a target has started. /// /// The source of the event. /// A object that contains the event data. void TargetStarted(object sender, BuildEventArgs e); /// /// Signals that a target has finished. /// /// The source of the event. /// A object that contains the event data. /// /// This event will still be fired if an error occurred during the build. /// void TargetFinished(object sender, BuildEventArgs e); /// /// Signals that a task has started. /// /// The source of the event. /// A object that contains the event data. void TaskStarted(object sender, BuildEventArgs e); /// /// Signals that a task has finished. /// /// The source of the event. /// A object that contains the event data. /// /// This event will still be fired if an error occurred during the build. /// void TaskFinished(object sender, BuildEventArgs e); /// /// Signals that a message has been logged. /// /// The source of the event. /// A object that contains the event data. void MessageLogged(object sender, BuildEventArgs e); } /// /// Interface used by NAnt to log the build output. /// /// /// Depending on the supplied command-line arguments, NAnt will set the /// to or a /// with a file as backend store. /// public interface IBuildLogger : IBuildListener { /// /// Gets or sets the highest level of message this logger should respond /// to. /// /// The highest level of message this logger should respond to. /// /// Only messages with a message level higher than or equal to the given /// level should actually be written to the log. /// Level Threshold { get; set; } /// /// Gets or sets a value indicating whether to produce emacs (and other /// editor) friendly output. /// /// /// if output is to be unadorned so that emacs /// and other editors can parse files names, etc. /// bool EmacsMode { get; set; } /// /// Gets or sets the to which the logger is /// to send its output. /// TextWriter OutputWriter { get; set; } /// /// Flushes buffered build events or messages to the underlying storage. /// void Flush(); } [Serializable()] public class DefaultLogger : IBuildLogger { #region Public Instance Constructors /// /// Initializes a new instance of the /// class. /// public DefaultLogger() { } #endregion Public Instance Constructors #region Implementation of IBuildLogger /// /// Gets or sets the highest level of message this logger should respond /// to. /// /// /// The highest level of message this logger should respond to. /// /// /// Only messages with a message level higher than or equal to the given /// level should be written to the log. /// public virtual Level Threshold { get { return _threshold; } set { _threshold = value; } } /// /// Gets or sets a value indicating whether to produce emacs (and other /// editor) friendly output. /// /// /// if output is to be unadorned so that emacs /// and other editors can parse files names, etc. The default is /// . /// public virtual bool EmacsMode { get { return _emacsMode; } set { _emacsMode = value; } } /// /// Gets or sets the to which the logger is /// to send its output. /// /// /// The to which the logger sends its output. /// public virtual TextWriter OutputWriter { get { return _outputWriter; } set { _outputWriter = value; } } /// /// Flushes buffered build events or messages to the underlying storage. /// public virtual void Flush() { if (OutputWriter != null) { OutputWriter.Flush(); } } #endregion Implementation of IBuildLogger #region Implementation of IBuildListener /// /// Signals that a build has started. /// /// The source of the event. /// A object that contains the event data. /// /// This event is fired before any targets have started. /// public virtual void BuildStarted(object sender, BuildEventArgs e) { _buildReports.Push(new BuildReport(DateTime.Now)); } /// /// Signals that the last target has finished. /// /// The source of the event. /// A object that contains the event data. /// /// This event will still be fired if an error occurred during the build. /// public virtual void BuildFinished(object sender, BuildEventArgs e) { Exception error = e.Exception; int indentationLevel = 0; if (e.Project != null) { indentationLevel = e.Project.IndentationLevel * e.Project.IndentationSize; } BuildReport report = (BuildReport) _buildReports.Pop(); if (error == null) { OutputMessage(Level.Info, string.Empty, indentationLevel); if (report.Errors == 0 && report.Warnings == 0) { OutputMessage(Level.Info, "BUILD SUCCEEDED", indentationLevel); } else { OutputMessage(Level.Info, string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("String_BuildSucceeded"), report.Errors, report.Warnings), indentationLevel); } OutputMessage(Level.Info, string.Empty, indentationLevel); } else { OutputMessage(Level.Error, string.Empty, indentationLevel); if (report.Errors == 0 && report.Warnings == 0) { OutputMessage(Level.Error, "BUILD FAILED", indentationLevel); } else { OutputMessage(Level.Info, string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("String_BuildFailed"), report.Errors, report.Warnings), indentationLevel); } OutputMessage(Level.Error, string.Empty, indentationLevel); if (error is BuildException) { if (Threshold <= Level.Verbose) { OutputMessage(Level.Error, error.ToString(), indentationLevel); } else { if (error.Message != null) { OutputMessage(Level.Error, error.Message, indentationLevel); } // output nested exceptions Exception nestedException = error.InnerException; int exceptionIndentationLevel = indentationLevel; int indentShift = 4; //e.Project.IndentationSize; while (nestedException != null && !String.IsNullOrEmpty(nestedException.Message)) { exceptionIndentationLevel += indentShift; OutputMessage(Level.Error, nestedException.Message, exceptionIndentationLevel); nestedException = nestedException.InnerException; } } } else { OutputMessage(Level.Error, "INTERNAL ERROR", indentationLevel); OutputMessage(Level.Error, string.Empty, indentationLevel); OutputMessage(Level.Error, error.ToString(), indentationLevel); OutputMessage(Level.Error, string.Empty, indentationLevel); OutputMessage(Level.Error, "Please send bug report to nant-developers@lists.sourceforge.net.", indentationLevel); } OutputMessage(Level.Error, string.Empty, indentationLevel); } // output total build time TimeSpan buildTime = DateTime.Now - report.StartTime; OutputMessage(Level.Info, string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("String_TotalTime") + Environment.NewLine, Math.Round(buildTime.TotalSeconds, 1)), indentationLevel); // make sure all messages are written to the underlying storage Flush(); } /// /// Signals that a target has started. /// /// The source of the event. /// A object that contains the event data. public virtual void TargetStarted(object sender, BuildEventArgs e) { int indentationLevel = 0; if (e.Project != null) { indentationLevel = e.Project.IndentationLevel * e.Project.IndentationSize; } if (e.Target != null) { OutputMessage(Level.Info, string.Empty, indentationLevel); OutputMessage( Level.Info, string.Format(CultureInfo.InvariantCulture, "{0}:", e.Target.Name), indentationLevel); OutputMessage(Level.Info, string.Empty, indentationLevel); } } /// /// Signals that a task has finished. /// /// The source of the event. /// A object that contains the event data. /// /// This event will still be fired if an error occurred during the build. /// public virtual void TargetFinished(object sender, BuildEventArgs e) { } /// /// Signals that a task has started. /// /// The source of the event. /// A object that contains the event data. public virtual void TaskStarted(object sender, BuildEventArgs e) { } /// /// Signals that a task has finished. /// /// The source of the event. /// A object that contains the event data. /// /// This event will still be fired if an error occurred during the build. /// public virtual void TaskFinished(object sender, BuildEventArgs e) { } /// /// Signals that a message has been logged. /// /// The source of the event. /// A object that contains the event data. /// /// Only messages with a priority higher or equal to the threshold of /// the logger will actually be output in the build log. /// public virtual void MessageLogged(object sender, BuildEventArgs e) { if (_buildReports.Count > 0) { if (e.MessageLevel == Level.Error) { BuildReport report = (BuildReport) _buildReports.Peek(); report.Errors++; } else if (e.MessageLevel == Level.Warning) { BuildReport report = (BuildReport) _buildReports.Peek(); report.Warnings++; } } // output the message OutputMessage(e); } #endregion Implementation of IBuildListener #region Protected Instance Methods /// /// Empty implementation which allows derived classes to receive the /// output that is generated in this logger. /// /// The message being logged. protected virtual void Log(string message) { } #endregion Protected Instance Methods #region Private Instance Methods /// /// Outputs an indented message to the build log if its priority is /// greather than or equal to the of the /// logger. /// /// The priority of the message to output. /// The message to output. /// The number of characters that the message should be indented. private void OutputMessage(Level messageLevel, string message, int indentationLength) { OutputMessage(CreateBuildEvent(messageLevel, message), indentationLength); } /// /// Outputs an indented message to the build log if its priority is /// greather than or equal to the of the /// logger. /// /// The event to output. private void OutputMessage(BuildEventArgs e) { int indentationLength = 0; if (e.Project != null) { indentationLength = e.Project.IndentationLevel * e.Project.IndentationSize; } OutputMessage(e, indentationLength); } /// /// Outputs an indented message to the build log if its priority is /// greather than or equal to the of the /// logger. /// /// The event to output. /// The number of characters that the message should be indented. private void OutputMessage(BuildEventArgs e, int indentationLength) { if (e.MessageLevel >= Threshold) { string txt = e.Message; // beautify the message a bit txt = txt.Replace("\t", " "); // replace tabs with spaces txt = txt.Replace("\r", ""); // get rid of carriage returns // split the message by lines - the separator is "\n" since we've eliminated // \r characters string[] lines = txt.Split('\n'); string label = String.Empty; if (e.Task != null && !EmacsMode) { label = "[" + e.Task.Name + "] "; label = label.PadLeft(e.Project.IndentationSize); } if (indentationLength > 0) { label = new String(' ', indentationLength) + label; } foreach (string line in lines) { StringBuilder sb = new StringBuilder(); sb.Append(label); sb.Append(line); string indentedMessage = sb.ToString(); // output the message to the console Console.Out.WriteLine(indentedMessage); // if an OutputWriter was set, write the message to it if (OutputWriter != null) { OutputWriter.WriteLine(indentedMessage); } Log(indentedMessage); } } } #endregion Private Instance Methods #region Private Static Methods private static BuildEventArgs CreateBuildEvent(Level messageLevel, string message) { BuildEventArgs buildEvent = new BuildEventArgs(); buildEvent.MessageLevel = messageLevel; buildEvent.Message = message; return buildEvent; } #endregion Private Static Methods #region Private Instance Fields private Level _threshold = Level.Info; private TextWriter _outputWriter; private bool _emacsMode; /// /// Holds a stack of reports for all running builds. /// private readonly Stack _buildReports = new Stack(); #endregion Private Instance Fields } /// /// Used to store information about a build, to allow better reporting to /// the user. /// [Serializable()] public class BuildReport { /// /// Errors encountered so far. /// public int Errors; /// /// Warnings encountered so far. /// public int Warnings; /// /// The start time of the build process. /// public readonly DateTime StartTime; public BuildReport(DateTime startTime) { StartTime = startTime; Errors = 0; Warnings = 0; } } /// /// Buffers log messages from DefaultLogger, and sends an e-mail with the /// results. /// /// /// The following properties are used to send the mail : /// /// /// Property /// Description /// /// /// MailLogger.mailhost /// Mail server to use. [default: localhost] /// /// /// MailLogger.from /// The address of the e-mail sender. /// /// /// MailLogger.failure.notify /// Send build failure e-mails ? [default: true] /// /// /// MailLogger.success.notify /// Send build success e-mails ? [default: true] /// /// /// MailLogger.failure.to /// The address to send build failure messages to. /// /// /// MailLogger.success.to /// The address to send build success messages to. /// /// /// MailLogger.failure.subject /// The subject of build failure messages. [default: "Build Failure"] /// /// /// MailLogger.success.subject /// The subject of build success messages. [default: "Build Success"] /// /// /// MailLogger.success.attachments /// The ID of a fileset holdng set of files to attach when the build is successful. /// /// /// MailLogger.failure.attachments /// The ID of a fileset holdng set of files to attach when the build fails. /// /// /// MailLogger.body.encoding /// The encoding type of the body of the e-mail message. [default: system's ANSI code page] /// /// /// MailLogger.smtp.username /// The name of the user to login to the SMTP server. /// /// /// MailLogger.smtp.password /// The password of the specified user. /// /// /// MailLogger.smtp.enablessl /// Specifies whether to use SSL to encrypt the connection. [default: false] /// /// /// MailLogger.smtp.port /// The SMTP server port to connect to. [default: 25] /// /// /// [Serializable()] public class MailLogger : DefaultLogger { #region Public Instance Constructors /// /// Initializes a new instance of the /// class. /// public MailLogger() : base() { } #endregion Public Instance Constructors #region Override implementation of DefaultLogger /// /// Signals that a build has started. /// /// The source of the event. /// A object that contains the event data. /// /// This event is fired before any targets have started. /// public override void BuildStarted(object sender, BuildEventArgs e) { base.BuildStarted (sender, e); // add an item to the project stack _projectStack.Push(null); } /// /// Signals that the last target has finished, and send an e-mail with /// the build results. /// /// The source of the event. /// A object that contains the event data. public override void BuildFinished(object sender, BuildEventArgs e) { #if (NET_1_1) const string cdoNamespaceURI = "http://schemas.microsoft.com/cdo/configuration/"; #endif base.BuildFinished(sender, e); // remove an item from the project stack _projectStack.Pop(); // check if there are still nested projects executing if (_projectStack.Count != 0) { // do not yet send the mail, as it should only be sent when the // main project is finished return; } Encoding bodyEncoding = null; Project project = e.Project; PropertyDictionary properties = project.Properties; bool success = (e.Exception == null); string prefix = success ? "success" : "failure"; try { string propertyValue = GetPropertyValue(properties, prefix + ".notify", "true", false); bool notify = true; try { notify = Convert.ToBoolean(propertyValue, CultureInfo.InvariantCulture); } catch { notify = true; } propertyValue = GetPropertyValue(properties, "body.encoding", null, false); try { if (propertyValue != null) { bodyEncoding = Encoding.GetEncoding(propertyValue); } } catch { // ignore invalid encoding } if (!notify) { return; } // create message to send MailMessage mailMessage = new MailMessage(); mailMessage.From = GetPropertyValue(properties, "from", null, true); mailMessage.To = GetPropertyValue(properties, prefix + ".to", null, true); mailMessage.Subject = GetPropertyValue(properties, prefix + ".subject", (success) ? "Build Success" : "Build Failure", false); mailMessage.Body = _buffer.ToString(); string smtpUsername = GetPropertyValue(properties, "smtp.username", null, false); string smtpPort = GetPropertyValue(properties, "smtp.port", null, false); string smtpEnableSSL = GetPropertyValue(properties, "smtp.enablessl", null, false); #if (NET_1_1) // when either a user name or a specific port is specified, or // SSL is enabled, then send the message must be sent using the // network (instead of using the local SMTP pickup directory) if (smtpUsername != null || smtpPort != null || IsSSLEnabled(properties)) { mailMessage.Fields[cdoNamespaceURI + "sendusing"] = 2; // cdoSendUsingPort } #endif if (smtpUsername != null) { #if (NET_1_1) mailMessage.Fields[cdoNamespaceURI + "smtpauthenticate"] = 1; mailMessage.Fields[cdoNamespaceURI + "sendusername"] = smtpUsername; #else Console.Error.WriteLine("[MailLogger] MailLogger.smtp.username" + " is not supported if NAnt is built targeting .NET" + " Framework 1.0."); #endif } string smtpPassword = GetPropertyValue(properties, "smtp.password", null, false); if (smtpPassword != null) { #if (NET_1_1) mailMessage.Fields[cdoNamespaceURI + "sendpassword"] = smtpPassword; #else Console.Error.WriteLine("[MailLogger] MailLogger.smtp.password" + " is not supported if NAnt is built targeting .NET" + " Framework 1.0."); #endif } if (smtpPort != null) { #if (NET_1_1) mailMessage.Fields[cdoNamespaceURI + "smtpserverport"] = smtpPort; #else Console.Error.WriteLine("[MailLogger] MailLogger.smtp.port" + " is not supported if NAnt is built targeting .NET" + " Framework 1.0."); #endif } if (smtpEnableSSL != null) { #if (NET_1_1) mailMessage.Fields[cdoNamespaceURI + "smtpusessl"] = smtpEnableSSL; #else Console.Error.WriteLine("[MailLogger] MailLogger.smtp.enablessl" + " is not supported if NAnt is built targeting .NET" + " Framework 1.0."); #endif } // attach files in fileset to message AttachFiles(mailMessage, project, GetPropertyValue(properties, prefix + ".attachments", null, false)); // set encoding of body if (bodyEncoding != null) { mailMessage.BodyEncoding = bodyEncoding; } // send the message SmtpMail.SmtpServer = GetPropertyValue(properties, "mailhost", "localhost", false); SmtpMail.Send(mailMessage); } catch (Exception ex) { Console.Error.WriteLine("[MailLogger] E-mail could not be sent!"); Console.Error.WriteLine(ex.ToString()); } } /// /// Receives and buffers log messages. /// /// The message being logged. protected override void Log(string message) { _buffer.Append(message).Append(Environment.NewLine); } #endregion Override implementation of DefaultLogger #region Private Instance Methods /// /// Gets the value of the specified property. /// /// Properties to obtain value from. /// Suffix of property name. "MailLogger" will be prepended internally. /// Value returned if property is not present in . /// Value indicating whether the property should exist, or have a default value set. /// /// The value of the specified property; or the default value if the /// property is not present in . /// /// is , and the specified property is not present and no default value has been given. private string GetPropertyValue(PropertyDictionary properties, string name, string defaultValue, bool required) { string propertyName = "MailLogger." + name; string value = (string) properties[propertyName]; if (value == null) { value = defaultValue; } if (required && value == null) { throw new ArgumentNullException(string.Format(CultureInfo.InvariantCulture, "Missing required parameter {0}.", propertyName)); } return value; } private bool IsSSLEnabled (PropertyDictionary properties) { string enableSSL = GetPropertyValue(properties, "smtp.enablessl", null, false); if (enableSSL != null) { try { return bool.Parse (enableSSL); } catch (FormatException) { throw new ArgumentException (string.Format (CultureInfo.InvariantCulture, "Invalid value '{0}' for MailLogger.smtp.enablessl property.", enableSSL)); } } return false; } private void AttachFiles(MailMessage mail, Project project, string filesetID) { if (String.IsNullOrEmpty(filesetID)) { return; } // lookup fileset FileSet fileset = project.DataTypeReferences[filesetID] as FileSet; if (fileset == null) { Console.Error.WriteLine("[MailLogger] Fileset \"{0}\" is not" + " defined. No files have been attached.", filesetID); return; } foreach (string fileName in fileset.FileNames) { if (!File.Exists(fileName)) { Console.Error.WriteLine("[MailLogger] Attachment \"{0}\"" + " does not exist. Skipping.", filesetID); continue; } // create attachment MailAttachment attachment = new MailAttachment(fileName, MailEncoding.UUEncode); // add attachment to mail mail.Attachments.Add(attachment); } } #endregion Private Instance Methods #region Private Instance Fields /// /// Buffer in which the message is constructed prior to sending. /// private StringBuilder _buffer = new StringBuilder(); /// /// Holds the stack of currently executing projects. /// private Stack _projectStack = new Stack(); #endregion Private Instance Fields } /// /// Contains a strongly typed collection of /// objects. /// [Serializable()] public class BuildListenerCollection : CollectionBase { #region Public Instance Constructors /// /// Initializes a new instance of the /// class. /// public BuildListenerCollection() { } /// /// Initializes a new instance of the /// class with the specified instance. /// public BuildListenerCollection(BuildListenerCollection value) { AddRange(value); } /// /// Initializes a new instance of the /// class with the specified array of instances. /// public BuildListenerCollection(IBuildListener[] value) { AddRange(value); } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets the element at the specified index. /// /// The zero-based index of the element to get or set. [System.Runtime.CompilerServices.IndexerName("Item")] public IBuildListener this[int index] { get { return ((IBuildListener)(base.List[index])); } set { base.List[index] = value; } } #endregion Public Instance Properties #region Public Instance Methods /// /// Adds a to the end of the collection. /// /// The to be added to the end of the collection. /// The position into which the new element was inserted. public int Add(IBuildListener item) { return base.List.Add(item); } /// /// Adds the elements of a array to the end of the collection. /// /// The array of elements to be added to the end of the collection. public void AddRange(IBuildListener[] items) { for (int i = 0; (i < items.Length); i = (i + 1)) { Add(items[i]); } } /// /// Adds the elements of a to the end of the collection. /// /// The to be added to the end of the collection. public void AddRange(BuildListenerCollection items) { for (int i = 0; (i < items.Count); i = (i + 1)) { Add(items[i]); } } /// /// Determines whether a is in the collection. /// /// The to locate in the collection. /// /// if is found in the /// collection; otherwise, . /// public bool Contains(IBuildListener item) { return base.List.Contains(item); } /// /// Copies the entire collection to a compatible one-dimensional array, starting at the specified index of the target array. /// /// The one-dimensional array that is the destination of the elements copied from the collection. The array must have zero-based indexing. /// The zero-based index in at which copying begins. public void CopyTo(IBuildListener[] array, int index) { base.List.CopyTo(array, index); } /// /// Retrieves the index of a specified object in the collection. /// /// The object for which the index is returned. /// /// The index of the specified . If the is not currently a member of the collection, it returns -1. /// public int IndexOf(IBuildListener item) { return base.List.IndexOf(item); } /// /// Inserts a into the collection at the specified index. /// /// The zero-based index at which should be inserted. /// The to insert. public void Insert(int index, IBuildListener item) { base.List.Insert(index, item); } /// /// Returns an enumerator that can iterate through the collection. /// /// /// A for the entire collection. /// public new BuildListenerEnumerator GetEnumerator() { return new BuildListenerEnumerator(this); } /// /// Removes a member from the collection. /// /// The to remove from the collection. public void Remove(IBuildListener item) { base.List.Remove(item); } #endregion Public Instance Methods } /// /// Enumerates the elements of a . /// public class BuildListenerEnumerator : IEnumerator { #region Internal Instance Constructors /// /// Initializes a new instance of the class /// with the specified . /// /// The collection that should be enumerated. internal BuildListenerEnumerator(BuildListenerCollection arguments) { IEnumerable temp = (IEnumerable) (arguments); _baseEnumerator = temp.GetEnumerator(); } #endregion Internal Instance Constructors #region Implementation of IEnumerator /// /// Gets the current element in the collection. /// /// /// The current element in the collection. /// public IBuildListener Current { get { return (IBuildListener) _baseEnumerator.Current; } } object IEnumerator.Current { get { return _baseEnumerator.Current; } } /// /// Advances the enumerator to the next element of the collection. /// /// /// if the enumerator was successfully advanced /// to the next element; if the enumerator has /// passed the end of the collection. /// public bool MoveNext() { return _baseEnumerator.MoveNext(); } bool IEnumerator.MoveNext() { return _baseEnumerator.MoveNext(); } /// /// Sets the enumerator to its initial position, which is before the /// first element in the collection. /// public void Reset() { _baseEnumerator.Reset(); } void IEnumerator.Reset() { _baseEnumerator.Reset(); } #endregion Implementation of IEnumerator #region Private Instance Fields private IEnumerator _baseEnumerator; #endregion Private Instance Fields } /// /// Implements a for writing information to /// the NAnt logging infrastructure. /// public class LogWriter : TextWriter { #region Public Instance Constructors /// /// Initializes a new instance of the class /// for the specified with the specified output /// level and format provider. /// /// Determines the indentation level. /// The with which messages will be output to the build log. /// An object that controls formatting. public LogWriter(Task task, Level outputLevel, IFormatProvider formatProvider) : base(formatProvider) { _task = task; _outputLevel = outputLevel; } #endregion Public Instance Constructors #region Override implementation of TextWriter /// /// Gets the in which the output is written. /// /// /// The always writes output in UTF8 /// encoding. /// public override Encoding Encoding { get { return Encoding.UTF8; } } /// /// Writes a character array to the buffer. /// /// The character array to write to the text stream. public override void Write(char[] chars) { Write(new string(chars, 0, chars.Length -1)); } /// /// Writes a string to the buffer. /// /// public override void Write(string value) { _message += value; } /// /// Writes an empty string to the logging infrastructure. /// public override void WriteLine() { WriteLine(string.Empty); } /// /// Writes a string to the logging infrastructure. /// /// The string to write. If is a null reference, only the line termination characters are written. public override void WriteLine(string value) { _message += value; _task.Log(OutputLevel, _message); _message = string.Empty; } /// /// Writes out a formatted string using the same semantics as /// . /// /// The formatting string. /// The object array to write into format string. public override void WriteLine(string line, params object[] args) { _message += string.Format(CultureInfo.InvariantCulture, line, args); _task.Log(OutputLevel, _message); _message = string.Empty; } /// /// Causes any buffered data to be written to the logging infrastructure. /// public override void Flush() { if (_message.Length != 0) { _task.Log(OutputLevel, _message); _message = string.Empty; } } /// /// Closes the current writer and releases any system resources /// associated with the writer. /// public override void Close() { Flush(); base.Close(); } #endregion Override implementation of TextWriter #region Override implementation of MarshalByRefObject /// /// Obtains a lifetime service object to control the lifetime policy for /// this instance. /// /// /// An object of type used to control the lifetime /// policy for this instance. This is the current lifetime service object /// for this instance if one exists; otherwise, a new lifetime service /// object initialized with a lease that will never time out. /// public override Object InitializeLifetimeService() { ILease lease = (ILease) base.InitializeLifetimeService(); if (lease.CurrentState == LeaseState.Initial) { lease.InitialLeaseTime = TimeSpan.Zero; } return lease; } #endregion Override implementation of MarshalByRefObject #region Protected Instance Properties /// /// Gets the with which messages will be output to /// the build log. /// protected Level OutputLevel { get { return _outputLevel; } } #endregion Protected Instance Properties #region Private Instance Fields private readonly Task _task; private readonly Level _outputLevel; private string _message = string.Empty; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.Core/NAnt.Core.csproj0000644000175000017500000003176611757302273020334 0ustar jtaylorjtaylor Debug AnyCPU 2.0 {8F5F8375-4097-4952-B860-784EB9961ABE} NAnt.Core NAnt.Core Library OnSuccessfulBuild false 8.0.50727 v2.0 2.0 publish\ true Disk false Foreground 7 Days false false true 0 1.0.0.%2a false false true true full false 4 ..\..\build\Debug\ AllRules.ruleset TRACE;DEBUG ..\..\build\Debug\NAnt.Core.xml true pdbonly true ..\..\build\Release\ 4 AllRules.ruleset TRACE ..\..\build\Release\NAnt.Core.xml ..\..\lib\common\neutral\log4net.dll CommonAssemblyInfo.cs False .NET Framework 3.5 SP1 Client Profile false False .NET Framework 3.5 SP1 true False Windows Installer 3.1 true nant-0.92-rc1/src/NAnt.Core/TaskBuilderCollection.cs0000644000175000017500000002447211757302273022133 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; namespace NAnt.Core { /// /// Contains a strongly typed collection of objects. /// [Serializable] public class TaskBuilderCollection : CollectionBase { #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public TaskBuilderCollection() { } /// /// Initializes a new instance of the class /// with the specified instance. /// public TaskBuilderCollection(TaskBuilderCollection value) { AddRange(value); } /// /// Initializes a new instance of the class /// with the specified array of instances. /// public TaskBuilderCollection(TaskBuilder[] value) { AddRange(value); } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets the element at the specified index. /// /// The zero-based index of the element to get or set. [System.Runtime.CompilerServices.IndexerName("Item")] public TaskBuilder this[int index] { get {return ((TaskBuilder)(base.List[index]));} set {base.List[index] = value;} } /// /// Gets the for the specified task. /// /// The name of task for which the should be located in the collection. [System.Runtime.CompilerServices.IndexerName("Item")] public TaskBuilder this[string taskName] { get { if (taskName != null) { // Try to locate instance using TaskName foreach (TaskBuilder TaskBuilder in base.List) { if (taskName.Equals(TaskBuilder.TaskName)) { return TaskBuilder; } } } return null; } } #endregion Public Instance Properties #region Public Instance Methods /// /// Adds a to the end of the collection. /// /// The to be added to the end of the collection. /// The position into which the new element was inserted. public int Add(TaskBuilder item) { return base.List.Add(item); } /// /// Adds the elements of a array to the end of the collection. /// /// The array of elements to be added to the end of the collection. public void AddRange(TaskBuilder[] items) { for (int i = 0; (i < items.Length); i = (i + 1)) { Add(items[i]); } } /// /// Adds the elements of a to the end of the collection. /// /// The to be added to the end of the collection. public void AddRange(TaskBuilderCollection items) { for (int i = 0; (i < items.Count); i = (i + 1)) { Add(items[i]); } } /// /// Determines whether a is in the collection. /// /// The to locate in the collection. /// /// if is found in the /// collection; otherwise, . /// public bool Contains(TaskBuilder item) { return base.List.Contains(item); } /// /// Determines whether a for the specified /// task is in the collection. /// /// The name of task for which the should be located in the collection. /// /// if a for the /// specified task is found in the collection; otherwise, . /// public bool Contains(string taskName) { return this[taskName] != null; } /// /// Copies the entire collection to a compatible one-dimensional array, starting at the specified index of the target array. /// /// The one-dimensional array that is the destination of the elements copied from the collection. The array must have zero-based indexing. /// The zero-based index in at which copying begins. public void CopyTo(TaskBuilder[] array, int index) { base.List.CopyTo(array, index); } /// /// Retrieves the index of a specified object in the collection. /// /// The object for which the index is returned. /// /// The index of the specified . If the is not currently a member of the collection, it returns -1. /// public int IndexOf(TaskBuilder item) { return base.List.IndexOf(item); } /// /// Inserts a into the collection at the specified index. /// /// The zero-based index at which should be inserted. /// The to insert. public void Insert(int index, TaskBuilder item) { base.List.Insert(index, item); } /// /// Returns an enumerator that can iterate through the collection. /// /// /// A for the entire collection. /// public new TaskBuilderEnumerator GetEnumerator() { return new TaskBuilderEnumerator(this); } /// /// Removes a member from the collection. /// /// The to remove from the collection. public void Remove(TaskBuilder item) { base.List.Remove(item); } #endregion Public Instance Methods } /// /// Enumerates the elements of a . /// public class TaskBuilderEnumerator : IEnumerator { #region Internal Instance Constructors /// /// Initializes a new instance of the class /// with the specified . /// /// The collection that should be enumerated. internal TaskBuilderEnumerator(TaskBuilderCollection arguments) { IEnumerable temp = (IEnumerable) (arguments); _baseEnumerator = temp.GetEnumerator(); } #endregion Internal Instance Constructors #region Implementation of IEnumerator /// /// Gets the current element in the collection. /// /// /// The current element in the collection. /// public TaskBuilder Current { get { return (TaskBuilder) _baseEnumerator.Current; } } object IEnumerator.Current { get { return _baseEnumerator.Current; } } /// /// Advances the enumerator to the next element of the collection. /// /// /// if the enumerator was successfully advanced /// to the next element; if the enumerator has /// passed the end of the collection. /// public bool MoveNext() { return _baseEnumerator.MoveNext(); } bool IEnumerator.MoveNext() { return _baseEnumerator.MoveNext(); } /// /// Sets the enumerator to its initial position, which is before the /// first element in the collection. /// public void Reset() { _baseEnumerator.Reset(); } void IEnumerator.Reset() { _baseEnumerator.Reset(); } #endregion Implementation of IEnumerator #region Private Instance Fields private IEnumerator _baseEnumerator; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.Core/ConsoleDriver.cs0000644000175000017500000006627611757302272020473 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Gerry Shaw (gerry_shaw@yahoo.com) // Scott Hernandez (ScottHernandez@hotmail.com) // William E. Caputo (wecaputo@thoughtworks.com | logosity@yahoo.com) // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Reflection; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Xml; using System.Xml.Xsl; using NAnt.Core.Tasks; using NAnt.Core.Util; namespace NAnt.Core { /// /// Main entry point to NAnt that is called by the ConsoleStub. /// public class ConsoleDriver { #region Public Static Methods /// /// Starts NAnt. This is the Main entry point. /// /// Command Line args, or whatever you want to pass it. They will treated as Command Line args. /// /// The exit code. /// public static int Main(string[] args) { CommandLineParser commandLineParser = null; Project project = null; Level projectThreshold = Level.Info; // create assembly resolver AssemblyResolver assemblyResolver = new AssemblyResolver(); // attach assembly resolver to the current domain assemblyResolver.Attach(); CommandLineOptions cmdlineOptions = new CommandLineOptions(); try { commandLineParser = new CommandLineParser(typeof(CommandLineOptions), true); commandLineParser.Parse(args, cmdlineOptions); if (!cmdlineOptions.NoLogo) { Console.WriteLine(commandLineParser.LogoBanner); // insert empty line Console.WriteLine(); } if (cmdlineOptions.ShowHelp) { ConsoleDriver.ShowHelp(commandLineParser); return 0; } // determine the project message threshold if (cmdlineOptions.Debug) { projectThreshold = Level.Debug; } else if (cmdlineOptions.Verbose) { projectThreshold = Level.Verbose; } else if (cmdlineOptions.Quiet) { projectThreshold = Level.Warning; } if (cmdlineOptions.BuildFile != null) { if (project != null) { Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "Buildfile has already been loaded! Using new value '{0}'; discarding old project file '{1}'", cmdlineOptions.BuildFile, project.BuildFileUri)); // insert empty line Console.WriteLine(); } project = new Project(cmdlineOptions.BuildFile, projectThreshold, cmdlineOptions.IndentationLevel); } // get build file name if the project has not been created. // If a build file was not specified on the command line. if (project == null) { project = new Project(GetBuildFileName(Environment.CurrentDirectory, null, cmdlineOptions.FindInParent), projectThreshold, cmdlineOptions.IndentationLevel); } // load extension asseemblies LoadExtensionAssemblies(cmdlineOptions.ExtensionAssemblies, project); PropertyDictionary buildOptionProps = new PropertyDictionary(project); // add build logger and build listeners to project ConsoleDriver.AddBuildListeners(cmdlineOptions, project); // copy cmd line targets foreach (string target in cmdlineOptions.Targets) { project.BuildTargets.Add(target); } // build collection of valid properties that were specified on // the command line. foreach (string key in cmdlineOptions.Properties) { buildOptionProps.AddReadOnly(key, cmdlineOptions.Properties.Get(key)); } // add valid properties to the project. foreach (System.Collections.DictionaryEntry de in buildOptionProps) { project.Properties.AddReadOnly((string) de.Key, (string) de.Value); } //add these here and in the project .ctor Assembly ass = Assembly.GetExecutingAssembly(); project.Properties.AddReadOnly(Project.NAntPropertyFileName, ass.Location); project.Properties.AddReadOnly(Project.NAntPropertyVersion, ass.GetName().Version.ToString()); project.Properties.AddReadOnly(Project.NAntPropertyLocation, Path.GetDirectoryName(ass.Location)); if (cmdlineOptions.TargetFramework != null) { FrameworkInfo framework = project.Frameworks[cmdlineOptions.TargetFramework]; if (framework != null) { try { framework.Validate(); project.TargetFramework = framework; } catch (Exception ex) { // write message of exception to console WriteException(ex); // output full stacktrace when NAnt is started in debug mode if (Level.Debug >= projectThreshold) { // insert empty line Console.Error.WriteLine(); // output header Console.Error.WriteLine("Stacktrace:"); // insert empty line Console.Error.WriteLine(); // output full stacktrace Console.Error.WriteLine(ex.ToString()); } // signal error return 1; } } else { Console.Error.WriteLine("Invalid framework '{0}' specified.", cmdlineOptions.TargetFramework); // insert empty line Console.Error.WriteLine(); FrameworkInfo[] installedFrameworks = project.GetFrameworks( FrameworkTypes.Installed); if (installedFrameworks.Length == 0) { Console.Error.WriteLine("There are no supported frameworks available on your system."); } else { Console.Error.WriteLine("Possible values include:"); // insert empty line Console.Error.WriteLine(); foreach (FrameworkInfo fi in installedFrameworks) { Console.Error.WriteLine("{0} ({1})", fi.Name, fi.Description); } } // signal error return 1; } } if (cmdlineOptions.ShowProjectHelp) { Console.WriteLine(); ConsoleDriver.ShowProjectHelp(project.Document); } else { if (!project.Run()) { return 1; } } // signal success return 0; } catch (CommandLineArgumentException ex) { // Write logo banner to console if parser was created successfully if (commandLineParser != null) { Console.WriteLine(commandLineParser.LogoBanner); // insert empty line Console.Error.WriteLine(); } // write message of exception to console WriteException(ex); // output full stacktrace when NAnt is started in debug mode if (Level.Debug >= projectThreshold) { // insert empty line Console.Error.WriteLine(); // output header Console.Error.WriteLine("Stacktrace:"); // insert empty line Console.Error.WriteLine(); // output full stacktrace Console.Error.WriteLine(ex.ToString()); } // insert empty line Console.WriteLine(); // instruct users to check the usage instructions Console.WriteLine("Try 'nant -help' for more information"); // signal error return 1; } catch (ApplicationException ex) { // insert empty line Console.Error.WriteLine(); // output build result Console.Error.WriteLine("BUILD FAILED"); // insert empty line Console.Error.WriteLine(); // write message of exception to console WriteException(ex); // output full stacktrace when NAnt is started in debug mode if (Level.Debug >= projectThreshold) { // insert empty line Console.Error.WriteLine(); // output header Console.Error.WriteLine("Stacktrace:"); // insert empty line Console.Error.WriteLine(); // output full stacktrace Console.Error.WriteLine(ex.ToString()); } else { // insert empty line Console.WriteLine(string.Empty); // output help text Console.WriteLine("For more information regarding the cause of the " + "build failure, run the build again in debug mode."); } // insert empty line Console.WriteLine(); // instruct users to check the usage instructions Console.WriteLine("Try 'nant -help' for more information"); // signal error return 1; } catch (Exception ex) { // insert empty line Console.Error.WriteLine(); // all other exceptions should have been caught Console.Error.WriteLine("INTERNAL ERROR"); // insert empty line Console.Error.WriteLine(); // write message of exception to console WriteException(ex); // output full stacktrace when NAnt is started in verbose mode if (Level.Verbose >= projectThreshold) { // insert empty line Console.Error.WriteLine(); // output header Console.Error.WriteLine("Stacktrace:"); // insert empty line Console.Error.WriteLine(); // output full stacktrace Console.Error.WriteLine(ex.ToString()); } else { // insert xempty line Console.WriteLine(); // output help text Console.WriteLine("For more information regarding the cause of the " + "build failure, run the build again in verbose mode."); } // insert empty line Console.WriteLine(); // instruct users to report this problem Console.WriteLine("Please send a bug report (including the version of NAnt you're using) to nant-developers@lists.sourceforge.net"); // signal fatal error return 2; } finally { if (project != null) { project.DetachBuildListeners(); } // detach assembly resolver from the current domain assemblyResolver.Detach(); if (cmdlineOptions.Pause) Console.ReadKey(); } } /// /// Prints the projecthelp to the console. /// /// The build file to show help for. /// /// is loaded and transformed with /// ProjectHelp.xslt, which is an embedded resource. /// public static void ShowProjectHelp(XmlDocument buildDoc) { // load our transform file out of the embedded resources Stream xsltStream = Assembly.GetExecutingAssembly().GetManifestResourceStream( "NAnt.Core.Resources.ProjectHelp.xslt"); if (xsltStream == null) { throw new Exception("Missing 'ProjectHelp.xslt' Resource Stream"); } XmlTextReader reader = new XmlTextReader(xsltStream, XmlNodeType.Document,null); //first load in an XmlDocument so we can set the appropriate nant-namespace XmlDocument xsltDoc = new XmlDocument(); xsltDoc.Load(reader); xsltDoc.DocumentElement.SetAttribute("xmlns:nant",buildDoc.DocumentElement.NamespaceURI); XslTransform transform = new XslTransform(); transform.Load(xsltDoc); StringBuilder sb = new StringBuilder(); StringWriter writer = new StringWriter(sb, CultureInfo.InvariantCulture); XsltArgumentList arguments = new XsltArgumentList(); // Do transformation transform.Transform(buildDoc, arguments, writer); // Write projecthelp to console Console.WriteLine(sb.ToString()); } /// /// Gets the file name for the build file in the specified directory. /// /// The directory to look for a build file. When in doubt use Environment.CurrentDirectory for directory. /// Look for a build file with this pattern or name. If null look for a file that matches the default build pattern (*.build). /// Whether or not to search the parent directories for a build file. /// The path to the build file or null if no build file could be found. public static string GetBuildFileName(string directory, string searchPattern, bool findInParent) { string buildFileName = null; if (Path.IsPathRooted(searchPattern)) { buildFileName = searchPattern; } else { if (searchPattern == null) { searchPattern = "*.build"; } // look for a default.build DirectoryInfo directoryInfo = new DirectoryInfo(directory); FileInfo[] files = directoryInfo.GetFiles("default.build"); if (files.Length == 1) { buildFileName = files[0].FullName; return buildFileName; } // now find any file ending in .build files = directoryInfo.GetFiles(searchPattern); if (files.Length == 1) { // got a single .build buildFileName = files[0].FullName; } else if (files.Length > 1) { throw new ApplicationException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1001") + " Use -buildfile: to specify the build file to execute or " + " create a default.build file.", searchPattern, directory)); } else if (files.Length == 0 && findInParent) { // recurse up the tree DirectoryInfo parentDirectoryInfo = directoryInfo.Parent; if (findInParent && parentDirectoryInfo != null) { buildFileName = GetBuildFileName(parentDirectoryInfo.FullName, searchPattern, findInParent); } else { throw new ApplicationException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1007"), searchPattern)); } } else { throw new ApplicationException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1004"), searchPattern, directory )); } } return buildFileName; } /// /// Loads the extension assemblies in the current /// and scans them for extensions. /// /// The extension assemblies to load. /// The which will be used to output messages to the build log. private static void LoadExtensionAssemblies(StringCollection extensionAssemblies, Project project) { LoadTasksTask loadTasks = new LoadTasksTask(); loadTasks.Project = project; loadTasks.NamespaceManager = project.NamespaceManager; loadTasks.Parent = project; loadTasks.Threshold = (project.Threshold == Level.Debug) ? Level.Debug : Level.Warning; foreach (string extensionAssembly in extensionAssemblies) { loadTasks.TaskFileSet.Includes.Add(extensionAssembly); } loadTasks.Execute(); } /// /// Dynamically constructs an instance of /// the class specified. /// /// /// /// At this point, only looks in the assembly where /// is defined. /// /// /// The fully qualified name of the logger that should be instantiated. /// Type could not be loaded. /// does not implement . [ReflectionPermission(SecurityAction.Demand, Flags=ReflectionPermissionFlag.NoFlags)] public static IBuildLogger CreateLogger(string typeName) { Type loggerType = ReflectionUtils.GetTypeFromString(typeName, false); if (loggerType == null) { throw new TypeLoadException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1006"), typeName)); } object buildLogger = Activator.CreateInstance(loggerType); if (!typeof(IBuildLogger).IsAssignableFrom(buildLogger.GetType())) { throw new ArgumentException( string.Format(CultureInfo.InvariantCulture, "{0} does not implement {1}.", buildLogger.GetType().FullName, typeof(IBuildLogger).FullName)); } return (IBuildLogger) buildLogger; } /// /// Dynamically constructs an instance of /// the class specified. /// /// /// /// At this point, only looks in the assembly where /// is defined. /// /// /// The fully qualified name of the listener that should be instantiated. /// Type could not be loaded. /// does not implement . [ReflectionPermission(SecurityAction.Demand, Flags=ReflectionPermissionFlag.NoFlags)] public static IBuildListener CreateListener(string typeName) { Type listenerType = ReflectionUtils.GetTypeFromString(typeName, false); if (listenerType == null) { throw new TypeLoadException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1006"), typeName)); } object buildListener = Activator.CreateInstance(listenerType); if (!typeof(IBuildListener).IsAssignableFrom(buildListener.GetType())) { throw new ArgumentException( string.Format(CultureInfo.InvariantCulture, "{0} does not implement {1}.", buildListener.GetType().FullName, typeof(IBuildListener).FullName)); } return (IBuildListener) buildListener; } #endregion Public Static Methods #region Private Static Methods /// /// Add the listeners specified in the command line arguments, /// along with the default listener, to the specified project. /// /// The command-line options. /// The to add listeners to. private static void AddBuildListeners(CommandLineOptions cmdlineOptions, Project project) { BuildListenerCollection listeners = new BuildListenerCollection(); IBuildLogger buildLogger = null; TextWriter outputWriter = Console.Out; if (cmdlineOptions.LogFile != null) { try { outputWriter = new StreamWriter(new FileStream(cmdlineOptions.LogFile.FullName, FileMode.Create, FileAccess.Write, FileShare.Read)); } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1005"), cmdlineOptions.LogFile.FullName), Location.UnknownLocation, ex); } } if (cmdlineOptions.LoggerType != null) { try { buildLogger = ConsoleDriver.CreateLogger(cmdlineOptions.LoggerType); } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1003"), cmdlineOptions.LoggerType), Location.UnknownLocation, ex); } } // if no logger was specified on the commandline or an error occurred // while creating an instance of the specified logger, use the default // logger. if (buildLogger == null) { buildLogger = new DefaultLogger(); } // only set OutputWriter if build logger does not derive from // DefaultLogger, or if logfile was specified on command-line. // Setting the OutputWriter of the DefaultLogger to Console.Out // would cause issues with unit tests. if (!typeof(DefaultLogger).IsAssignableFrom(buildLogger.GetType()) || cmdlineOptions.LogFile != null) { buildLogger.OutputWriter = outputWriter; } // set threshold of build logger equal to threshold of project buildLogger.Threshold = project.Threshold; // set emacs mode buildLogger.EmacsMode = cmdlineOptions.EmacsMode; // add build logger to listeners collection listeners.Add(buildLogger); // add listeners to listener collection foreach (string listenerTypeName in cmdlineOptions.Listeners) { try { IBuildListener listener = ConsoleDriver.CreateListener(listenerTypeName); listeners.Add(listener); } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1002"), listenerTypeName), Location.UnknownLocation, ex); } } // attach listeners to project project.AttachBuildListeners(listeners); } /// /// Spits out generic help info to the console. /// private static void ShowHelp(CommandLineParser parser) { Console.WriteLine("NAnt comes with ABSOLUTELY NO WARRANTY."); Console.WriteLine("This is free software, and you are welcome to redistribute it under certain"); Console.WriteLine("conditions set out by the GNU General Public License. A copy of the license"); Console.WriteLine("is available in the distribution package and from the NAnt web site."); Console.WriteLine(); Console.WriteLine(parser.Usage); Console.WriteLine("A file ending in .build will be used if no buildfile is specified."); } /// /// Write the message of the specified and /// the inner exceptions to . /// /// The to write to . private static void WriteException(Exception cause) { int indentLevel = 0; while (cause != null && !String.IsNullOrEmpty(cause.Message)) { if (!String.IsNullOrEmpty(cause.Message)) { if (indentLevel > 0) { // insert empty line Console.Error.WriteLine(); } // indent exception message with extra spaces (for each // nesting level) Console.Error.WriteLine(new string(' ', indentLevel * INDENTATION_SIZE) + cause.Message); // increase indentation level indentLevel++; } // move on to next inner exception cause = cause.InnerException; } } #endregion Private Static Methods #region Private Static Fields private const int INDENTATION_SIZE = 4; #endregion Private Static Fields } } nant-0.92-rc1/src/NAnt.Core/XmlLogger.cs0000644000175000017500000004602011757302273017577 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // William E. Caputo (wecaputo@thoughtworks.com | logosity@yahoo.com) // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; using System.Globalization; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Xml; using NAnt.Core.Util; namespace NAnt.Core { /// /// Used to wrap log messages in xml <message/> elements. /// [Serializable()] public class XmlLogger : IBuildLogger, ISerializable { private readonly StopWatchStack _stopWatchStack; #region Private Instance Fields private TextWriter _outputWriter; private StringWriter _buffer = new StringWriter(); private Level _threshold = Level.Info; [NonSerialized()] private XmlTextWriter _xmlWriter; /// /// Holds the stack of currently executing projects. /// private Stack _projectStack = new Stack(); #endregion Private Instance Fields #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public XmlLogger() : this(new StopWatchStack(new DateTimeProvider())) {} public XmlLogger(StopWatchStack stopWatchStack) { _xmlWriter = new XmlTextWriter(_buffer); _stopWatchStack = stopWatchStack; } #endregion Public Instance Constructors #region Protected Instance Constructors /// /// Initializes a new instance of the class /// with serialized data. /// /// The that holds the serialized object data. /// The that contains contextual information about the source or destination. protected XmlLogger(SerializationInfo info, StreamingContext context) { _outputWriter = info.GetValue("OutputWriter", typeof (TextWriter)) as TextWriter; _buffer = info.GetValue("Buffer", typeof (StringWriter)) as StringWriter; _threshold = (Level) info.GetValue("Threshold", typeof (Level)); _xmlWriter = new XmlTextWriter(_buffer); _projectStack = (Stack) info.GetValue("ProjectStack", typeof (Stack)); } #endregion Protected Instance Constructors #region Implementation of ISerializable /// /// Populates with the data needed to serialize /// the instance. /// /// The to populate with data. /// The destination for this serialization. public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("OutputWriter", _outputWriter); info.AddValue("Buffer", _buffer); info.AddValue("Threshold", _threshold); info.AddValue("ProjectStack", _projectStack); } #endregion Implementation of ISerializable #region Override implementation of Object /// /// Returns the contents of log captured. /// public override string ToString() { return _buffer.ToString(); } #endregion Override implementation of Object #region Implementation of IBuildListener /// /// Signals that a build has started. /// /// The source of the event. /// A object that contains the event data. /// /// This event is fired before any targets have started. /// public void BuildStarted(object sender, BuildEventArgs e) { lock (_xmlWriter) { _stopWatchStack.PushStart(); _xmlWriter.WriteStartElement(Elements.BuildResults); _xmlWriter.WriteAttributeString(Attributes.Project, e.Project.ProjectName); } // add an item to the project stack _projectStack.Push(null); } /// /// Signals that the last target has finished. /// /// The source of the event. /// A object that contains the event data. /// /// This event will still be fired if an error occurred during the build. /// public void BuildFinished(object sender, BuildEventArgs e) { lock (_xmlWriter) { if (e.Exception != null) { _xmlWriter.WriteStartElement("failure"); WriteErrorNode(e.Exception); _xmlWriter.WriteEndElement(); } // output total build duration WriteDuration(); // close buildresults node _xmlWriter.WriteEndElement(); _xmlWriter.Flush(); } // remove an item from the project stack _projectStack.Pop(); // check if there are still nested projects executing if (_projectStack.Count != 0) { // do not yet persist build results, as the main project is // not finished yet return; } try { // write results to file if (OutputWriter != null) { OutputWriter.Write(_buffer.ToString()); OutputWriter.Flush(); } else { // Xmlogger is used as BuildListener string outFileName = e.Project.Properties["XmlLogger.file"]; if (outFileName == null) { outFileName = "log.xml"; } // convert to full path relative to project base directory outFileName = e.Project.GetFullPath(outFileName); // write build log to file using (StreamWriter writer = new StreamWriter(new FileStream(outFileName, FileMode.Create, FileAccess.Write, FileShare.Read), Encoding.UTF8)) { writer.Write(_buffer.ToString()); } } } catch (Exception ex) { throw new BuildException("Unable to write to log file.", ex); } } /// /// Signals that a target has started. /// /// The source of the event. /// A object that contains the event data. public void TargetStarted(object sender, BuildEventArgs e) { lock (_xmlWriter) { _stopWatchStack.PushStart(); _xmlWriter.WriteStartElement(Elements.Target); WriteNameAttribute(e.Target.Name); _xmlWriter.Flush(); } } /// /// Signals that a target has finished. /// /// The source of the event. /// A object that contains the event data. /// /// This event will still be fired if an error occurred during the build. /// public void TargetFinished(object sender, BuildEventArgs e) { lock (_xmlWriter) { // output total target duration WriteDuration(); // close target element _xmlWriter.WriteEndElement(); _xmlWriter.Flush(); } } /// /// Signals that a task has started. /// /// The source of the event. /// A object that contains the event data. public void TaskStarted(object sender, BuildEventArgs e) { lock (_xmlWriter) { _stopWatchStack.PushStart(); _xmlWriter.WriteStartElement(Elements.Task); WriteNameAttribute(e.Task.Name); _xmlWriter.Flush(); } } /// /// Signals that a task has finished. /// /// The source of the event. /// A object that contains the event data. /// /// This event will still be fired if an error occurred during the build. /// public void TaskFinished(object sender, BuildEventArgs e) { lock (_xmlWriter) { // output total target duration WriteDuration(); // close task element _xmlWriter.WriteEndElement(); _xmlWriter.Flush(); } } private void WriteDuration() { _xmlWriter.WriteElementString("duration", XmlConvert.ToString(_stopWatchStack.PopStop().TotalMilliseconds)); } /// /// Signals that a message has been logged. /// /// The source of the event. /// A object that contains the event data. /// /// Only messages with a priority higher or equal to the threshold of /// the logger will actually be output in the build log. /// public void MessageLogged(object sender, BuildEventArgs e) { if (e.MessageLevel >= Threshold) { string rawMessage = StripFormatting(e.Message.Trim()); if (IsJustWhiteSpace(rawMessage)) { return; } lock (_xmlWriter) { _xmlWriter.WriteStartElement(Elements.Message); // write message level as attribute _xmlWriter.WriteAttributeString(Attributes.MessageLevel, e.MessageLevel.ToString(CultureInfo.InvariantCulture)); if (IsValidXml(rawMessage)) { rawMessage = Regex.Replace(rawMessage, @"<\?.*\?>", string.Empty); _xmlWriter.WriteRaw(rawMessage); } else { _xmlWriter.WriteCData(StripCData(rawMessage)); } _xmlWriter.WriteEndElement(); _xmlWriter.Flush(); } } } #endregion Implementation of IBuildListener #region Implementation of IBuildLogger /// /// Gets or sets the highest level of message this logger should respond /// to. /// /// /// The highest level of message this logger should respond to. /// /// /// Only messages with a message level higher than or equal to the given /// level should be written to the log. /// public Level Threshold { get { return _threshold; } set { _threshold = value; } } /// /// Gets or sets a value indicating whether to produce emacs (and other /// editor) friendly output. /// /// /// as it has no meaning in XML format. /// public virtual bool EmacsMode { get { return false; } set {} } /// /// Gets or sets the to which the logger is /// to send its output. /// public TextWriter OutputWriter { get { return _outputWriter; } set { _outputWriter = value; } } /// /// Flushes buffered build events or messages to the underlying storage. /// public void Flush() { lock (_xmlWriter) { _xmlWriter.Flush(); } } #endregion Implementation of IBuildLogger #region Public Instance Methods public string StripFormatting(string message) { // will hold the message stripped from whitespace and null characters string strippedMessage; // looking for whitespace or null characters from front of line // followed by one or more of just about anything between [ and ] // followed by a message which we will capture. eg. ' [blah] Regex r = new Regex(@"(?ms)^[\s\0]*?\[[\s\w\d]+\](.+)"); Match m = r.Match(message); if (m.Success) { strippedMessage = m.Groups[1].Captures[0].Value; strippedMessage = strippedMessage.Replace("\0", string.Empty); strippedMessage = strippedMessage.Trim(); } else { strippedMessage = message.Replace("\0", string.Empty); } return strippedMessage; } public bool IsJustWhiteSpace(string message) { Regex r = new Regex(@"^[\s\0]*$"); return r.Match(message).Success; } #endregion Public Instance Methods #region Private Instance Methods private void WriteErrorNode(Exception exception) { // this method assumes that a synchronization // lock on _xmlWriter is already held if (exception == null) { // build success return; } else { BuildException buildException = null; if (typeof (BuildException).IsAssignableFrom(exception.GetType())) { buildException = (BuildException) exception; } if (buildException != null) { // start build error node _xmlWriter.WriteStartElement("builderror"); } else { // start build error node _xmlWriter.WriteStartElement("internalerror"); } // write exception type _xmlWriter.WriteElementString("type", exception.GetType().FullName); // write location for build exceptions if (buildException != null) { // write raw exception message if (buildException.RawMessage != null) { _xmlWriter.WriteStartElement("message"); _xmlWriter.WriteCData(StripCData(buildException.RawMessage)); _xmlWriter.WriteEndElement(); } if (buildException.Location != null) { if (!String.IsNullOrEmpty(buildException.Location.ToString())) { _xmlWriter.WriteStartElement("location"); _xmlWriter.WriteElementString("filename", buildException.Location.FileName); _xmlWriter.WriteElementString("linenumber", buildException.Location.LineNumber.ToString(CultureInfo.InvariantCulture)); _xmlWriter.WriteElementString("columnnumber", buildException.Location.ColumnNumber.ToString(CultureInfo.InvariantCulture)); _xmlWriter.WriteEndElement(); } } } else { // write exception message if (exception.Message != null) { _xmlWriter.WriteStartElement("message"); _xmlWriter.WriteCData(StripCData(exception.Message)); _xmlWriter.WriteEndElement(); } } // write stacktrace of exception to build log _xmlWriter.WriteStartElement("stacktrace"); _xmlWriter.WriteCData(exception.StackTrace); _xmlWriter.WriteEndElement(); // write information about inner exception WriteErrorNode(exception.InnerException); // close failure node _xmlWriter.WriteEndElement(); } } private bool IsValidXml(string message) { if (Regex.Match(message, @"^<.*>").Success) { XmlValidatingReader reader = null; try { // validate xml reader = new XmlValidatingReader(message, XmlNodeType.Document, null); while (reader.Read()) { } // the xml is valid return true; } catch { return false; } finally { if (reader != null) { reader.Close(); } } } return false; } private string StripCData(string message) { string strippedMessage = Regex.Replace(message, @"", string.Empty); } private void WriteNameAttribute(string name) { // this method assumes that a synchronization // lock on _xmlWriter is already held _xmlWriter.WriteAttributeString("name", name); } #endregion Private Instance Methods private class Elements { public const string BuildResults = "buildresults"; public const string Message = "message"; public const string Target = "target"; public const string Task = "task"; public const string Status = "status"; } private class Attributes { public const string Project = "project"; public const string MessageLevel = "level"; } } }nant-0.92-rc1/src/NAnt.Core/TaskContainer.cs0000644000175000017500000001461711757302273020453 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2002-2003 Scott Hernandez // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Scott Hernandez (ScottHernandez@hotmail.com) using System; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.Reflection; using System.Xml; using NAnt.Core.Attributes; using NAnt.Core.Tasks; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.Core { /// /// Executes embedded tasks in the order in which they are defined. /// public class TaskContainer : Task { #region Private Instance Fields private StringCollection _subXMLElements; #endregion Private Instance Fields #region Override implementation of Element /// /// Gets a value indicating whether the element is performing additional /// processing using the that was use to /// initialize the element. /// /// /// , as a is /// responsable for creating tasks from the nested build elements. /// protected override bool CustomXmlProcessing { get { return true;} } #endregion Override implementation of Element #region Override implementation of Task /// /// Automatically exclude build elements that are defined on the task /// from things that get executed, as they are evaluated normally during /// XML task initialization. /// protected override void Initialize() { base.Initialize(); // Exclude any BuildElements (like FileSets, etc.) from our execution elements. // These build elements will be handled during the xml init of the task container (Element xmlinit code) _subXMLElements = new StringCollection(); foreach (MemberInfo memInfo in this.GetType().GetMembers(BindingFlags.Instance | BindingFlags.Public)) { if(memInfo.DeclaringType.Equals(typeof(object))) { continue; } BuildElementAttribute buildElemAttr = (BuildElementAttribute) Attribute.GetCustomAttribute(memInfo, typeof(BuildElementAttribute), true); if (buildElemAttr != null) { _subXMLElements.Add(buildElemAttr.Name); } } } protected override void ExecuteTask() { ExecuteChildTasks(); } #endregion Override implementation of Task #region Protected Instance Methods /// /// Creates and executes the embedded (child XML nodes) elements. /// /// /// Skips any element defined by the host that has /// a defined. /// protected virtual void ExecuteChildTasks() { foreach (XmlNode childNode in XmlNode) { //we only care about xmlnodes (elements) that are of the right namespace. if (!(childNode.NodeType == XmlNodeType.Element) || !childNode.NamespaceURI.Equals(NamespaceManager.LookupNamespace("nant"))) { continue; } // ignore any private xml elements (by def. this includes any property with a BuildElementAttribute (name). if (IsPrivateXmlElement(childNode)) { continue; } if (TypeFactory.TaskBuilders.Contains(childNode.Name)) { // create task instance Task task = CreateChildTask(childNode); // for now, we should assume null tasks are because of // incomplete metadata about the XML if (task != null) { task.Parent = this; // execute task task.Execute(); } } else if (TypeFactory.DataTypeBuilders.Contains(childNode.Name)) { // we are an datatype declaration DataTypeBase dataType = CreateChildDataTypeBase(childNode); Log(Level.Debug, "Adding a {0} reference with id '{1}'.", childNode.Name, dataType.ID); if (!Project.DataTypeReferences.Contains(dataType.ID)) { Project.DataTypeReferences.Add(dataType.ID, dataType); } else { Project.DataTypeReferences[dataType.ID] = dataType; // overwrite with the new reference. } } else { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1071"), childNode.Name), Project.GetLocation(childNode)); } } } protected virtual Task CreateChildTask(XmlNode node) { return Project.CreateTask(node); } protected virtual DataTypeBase CreateChildDataTypeBase(XmlNode node) { return Project.CreateDataTypeBase(node); } protected virtual bool IsPrivateXmlElement(XmlNode node) { return (_subXMLElements != null && _subXMLElements.Contains(node.Name)); } protected virtual void AddPrivateXmlElementName(string name) { if (_subXMLElements == null) { _subXMLElements = new StringCollection(); } if (!_subXMLElements.Contains(name)) { _subXMLElements.Add(name); } } #endregion Protected Instance Methods } } nant-0.92-rc1/src/NAnt.Core/ValidationException.cs0000644000175000017500000001016711757302273021653 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2002-2003 Scott Hernandez // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Scott Hernandez (ScottHernandez@hotmail.com) using System; using System.Runtime.Serialization; using System.Security.Permissions; namespace NAnt.Core { [Serializable()] public class ValidationException : BuildException { #region Public Instance Constructors /// /// Initializes a new instance of the /// class. /// public ValidationException() : base() { } /// /// Initializes a new instance of the /// class with a descriptive message. /// /// A descriptive message to include with the exception. public ValidationException(String message) : base(message) {} /// /// Initializes a new instance of the /// class with the specified descriptive message and inner exception. /// /// A descriptive message to include with the exception. /// A nested exception that is the cause of the current exception. public ValidationException(String message, Exception innerException) : base(message, innerException) { } /// /// Initializes a new instance of the /// class with a descriptive message and the location in the build file /// that caused the exception. /// /// A descriptive message to include with the exception. /// The location in the build file where the exception occured. public ValidationException(String message, Location location) : base(message, location) { } /// /// Initializes a new instance of the /// class with a descriptive message, the location in the build file and /// an instance of the exception that is the cause of the current /// exception. /// /// A descriptive message to include with the exception. /// The location in the build file where the exception occured. /// A nested exception that is the cause of the current exception. public ValidationException(String message, Location location, Exception innerException) : base(message, location, innerException) { } #endregion Public Instance Constructors #region Protected Instance Constructors /// /// Initializes a new instance of the /// class with serialized data. /// /// The that holds the serialized object data about the exception being thrown. /// The that contains contextual information about the source or destination. protected ValidationException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endregion Protected Instance Constructors } } nant-0.92-rc1/src/NAnt.MSBuild/0000755000175000017500000000000011757310030015743 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.MSBuild/BuildEngine/0000755000175000017500000000000011757310030020130 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.MSBuild/BuildEngine/BuildItem.cs0000644000175000017500000000324211757302273022350 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2011 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Martin Aliger (martin_aliger@myrealbox.com) using System; using System.Collections; using System.Text; using System.Reflection; using System.IO; namespace NAnt.MSBuild.BuildEngine { internal class BuildItem { object _obj; Type _t; internal BuildItem(object o) { _obj = o; _t = _obj.GetType(); } public string FinalItemSpec { get { return (string)_t.GetProperty("FinalItemSpec").GetValue(_obj, null); } } public string GetMetadata(string metadataName) { return (string)_t.GetMethod("GetMetadata").Invoke(_obj, new object[] { metadataName }); } public void SetMetadata(string metadataName, string metadataValue) { _t.GetMethod("SetMetadata", new Type[] { typeof(string), typeof(string) }).Invoke(_obj, new object[] { metadataName, metadataValue }); } } } nant-0.92-rc1/src/NAnt.MSBuild/BuildEngine/Project.cs0000644000175000017500000000575611757302273022114 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2011 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Martin Aliger (martin_aliger@myrealbox.com) using System; using System.Collections; using System.Text; using System.Reflection; using System.IO; namespace NAnt.MSBuild.BuildEngine { internal class Project { object _obj; Type _t; public Project(Engine engine) { _t = engine.Assembly.GetType("Microsoft.Build.BuildEngine.Project"); _obj = Activator.CreateInstance(_t, engine.Object); } public string FullFileName { get { return (string)_t.GetProperty("FullFileName").GetValue(_obj, null); } set { _t.GetProperty("FullFileName").SetValue(_obj, value, null); } } private PropertyInfo ToolsVersionPI { get { return _t.GetProperty("ToolsVersion"); } } public string ToolsVersion { get { PropertyInfo pi = ToolsVersionPI; if (pi == null) return "2.0"; return (string)pi.GetValue(_obj, null); } set { PropertyInfo pi = ToolsVersionPI; if (pi == null) return; pi.SetValue(_obj, value, null); } } public void LoadXml(string projectXml) { _t.GetMethod("LoadXml", new Type[] { typeof(string) }).Invoke(_obj, new object[] { projectXml }); } public BuildPropertyGroup GlobalProperties { get { return new BuildPropertyGroup(_t.GetProperty("GlobalProperties").GetValue(_obj, null)); } } public string GetEvaluatedProperty(string propertyName) { return (string)_t.GetMethod("GetEvaluatedProperty").Invoke(_obj, new object[] { propertyName }); } public BuildItemGroup GetEvaluatedItemsByName(string itemName) { return new BuildItemGroup(_t.GetMethod("GetEvaluatedItemsByName").Invoke(_obj, new object[] { itemName })); } public void RemoveItemsByName(string itemName) { _t.GetMethod("RemoveItemsByName").Invoke(_obj, new object[] { itemName }); } public BuildItemGroup AddNewItemGroup() { return new BuildItemGroup(_t.GetMethod("AddNewItemGroup").Invoke(_obj, null)); } public bool Build() { return (bool) _t.GetMethod("Build", new Type[] {}).Invoke(_obj, null); } } } nant-0.92-rc1/src/NAnt.MSBuild/BuildEngine/Engine.cs0000644000175000017500000001261111757302273021677 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2011 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Martin Aliger (martin_aliger@myrealbox.com) using System; using System.Collections; using System.Text; using System.Reflection; using System.IO; namespace NAnt.MSBuild.BuildEngine { internal class Engine : MarshalByRefObject { object _obj; Type _t; Assembly _a; private Engine() { } public static Engine LoadEngine(NAnt.Core.FrameworkInfo framework) { //System.AppDomainSetup myDomainSetup = new System.AppDomainSetup(); //myDomainSetup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory; //myDomainSetup.ApplicationName = "MSBuild"; //string tempFile = Path.GetTempFileName(); //using (StreamWriter sw = File.CreateText(tempFile)) //{ // sw.WriteLine(String.Format( // "" // + "" // + "" // + "" // + "", // new Version(framework.Version.Major, framework.Version.Minor, 0, 0))); //} //myDomainSetup.ConfigurationFile = tempFile;// AppDomain.CurrentDomain.SetupInformation.ConfigurationFile; //var executionAD = AppDomain.CreateDomain(myDomainSetup.ApplicationName, // AppDomain.CurrentDomain.Evidence, myDomainSetup); //AppDomain.CurrentDomain.AssemblyLoad += new AssemblyLoadEventHandler(CurrentDomain_AssemblyLoad); //executionAD.AssemblyLoad += new AssemblyLoadEventHandler(executionAD_AssemblyLoad); //File.Delete(tempFile); //Loader l = (Loader)executionAD.CreateInstanceAndUnwrap(typeof(Loader).Assembly.FullName, typeof(Loader).FullName); Loader l = new Loader(); l.framework = framework; //executionAD.DoCallBack(new CrossAppDomainDelegate(l.DoLoad)); l.DoLoad(); return l.engine; } //[Serializable] public class Loader : MarshalByRefObject { public NAnt.Core.FrameworkInfo framework; public Engine engine; public void DoLoad() { engine = new Engine(); string pth = Path.Combine(framework.FrameworkDirectory.FullName, "Microsoft.Build.Engine.dll"); if (File.Exists(pth)) { engine._a = Assembly.LoadFile(pth); } else { //frameworks 3.0 and 3.5 do not copy its assemblies into filesystem. They reside just in assembly cache (GAC) //Microsoft.Build.Engine, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a AssemblyName an = new AssemblyName("Microsoft.Build.Engine"); an.Version = new Version(framework.Version.Major, framework.Version.Minor, 0, 0); an.CultureInfo = System.Globalization.CultureInfo.InvariantCulture; an.SetPublicKeyToken(new byte[] { 0xb0, 0x3f, 0x5f, 0x7f, 0x11, 0xd5, 0x0a, 0x3a }); engine._a = Assembly.Load(an); //load from GAC } engine._t = engine._a.GetType("Microsoft.Build.BuildEngine.Engine"); engine._obj = Activator.CreateInstance(engine._t); //2.0 if (engine._a.GetName().Version.Major == 2) { engine._t.GetProperty("BinPath").SetValue(engine._obj, framework.FrameworkDirectory.FullName, null); } } } static void executionAD_AssemblyLoad(object sender, AssemblyLoadEventArgs args) { } static void CurrentDomain_AssemblyLoad(object sender, AssemblyLoadEventArgs args) { } internal Assembly Assembly { get { return _a; } } internal object Object { get { return _obj; } } public void UnregisterAllLoggers() { _t.GetMethod("UnregisterAllLoggers").Invoke(_obj, null); } public void RegisterLogger(/*ILogger*/object logger) { _t.GetMethod("RegisterLogger").Invoke(_obj, new object[] {logger}); } } } nant-0.92-rc1/src/NAnt.MSBuild/BuildEngine/BuildPropertyGroup.cs0000644000175000017500000000257711757302273024325 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2011 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Martin Aliger (martin_aliger@myrealbox.com) using System; using System.Collections; using System.Text; using System.Reflection; using System.IO; namespace NAnt.MSBuild.BuildEngine { internal class BuildPropertyGroup { object _obj; Type _t; internal BuildPropertyGroup(object o) { _obj = o; _t = _obj.GetType(); } public void SetProperty(string propertyName, string propertyValue) { _t.GetMethod("SetProperty", new Type[] { typeof(string), typeof(string) }).Invoke(_obj, new object[] { propertyName, propertyValue }); } } } nant-0.92-rc1/src/NAnt.MSBuild/BuildEngine/BuildItemGroup.cs0000644000175000017500000000412111757302273023362 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2011 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Martin Aliger (martin_aliger@myrealbox.com) using System; using System.Collections; using System.Text; using System.Reflection; using System.IO; namespace NAnt.MSBuild.BuildEngine { internal class BuildItemGroup { #region Enumerator private class BuildItemEnumerator : IEnumerator { IEnumerator _po; internal BuildItemEnumerator(IEnumerator po) { _po = po; } public object Current { get { return new BuildItem(_po.Current); } } public bool MoveNext() { return _po.MoveNext(); } public void Reset() { _po.Reset(); } } #endregion object _obj; Type _t; internal BuildItemGroup(object o) { _obj = o; _t = _obj.GetType(); } public System.Collections.IEnumerator GetEnumerator() { return new BuildItemEnumerator((IEnumerator)_t.GetMethod("GetEnumerator").Invoke(_obj, null)); } public BuildItem AddNewItem(string itemName, string itemInclude) { return new BuildItem(_t.GetMethod("AddNewItem", new Type[] { typeof(string), typeof(string) }).Invoke(_obj, new object[] { itemName, itemInclude })); } } } nant-0.92-rc1/src/NAnt.MSBuild/NAntLogger.cs0000644000175000017500000001711211757302274020307 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2006 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Martin Aliger (martin_aliger@myrealbox.com) using System; using NAnt.Core; using NAnt.Core.Util; using System.CodeDom; using System.CodeDom.Compiler; using System.IO; using System.Reflection; namespace NAnt.MSBuild { /// /// Enum indicating the level of verbosity for the NAnt logger. /// public enum NAntLoggerVerbosity { /// Indicates no output Quiet, /// Indicates little output Minimal, /// Indicates normal output Normal, /// Indicates detailed output Detailed, /// Indicates all output Diagnostic }; //internal interface ILogger { } //internal interface IEventSource { } //internal class BuildErrorEventArgs { } //internal class BuildWarningEventArgs { } //internal class BuildMessageEventArgs { } //internal class TaskStartedEventArgs { } //internal class TaskFinishedEventArgs { } /// /// Logger classed used for MSBuild tasks in NAnt. /// public class NAntLogger { internal static NAntLogger Create(NAnt.Core.FrameworkInfo framework, Task task, NAntLoggerVerbosity verbosity, NAnt.MSBuild.BuildEngine.Engine engine) { CodeDomProvider codeDomProvider = CodeDomProvider.CreateProvider("C#"); CompilerParameters par = new CompilerParameters(); AssemblyName msbuildFrameworkName = engine.Assembly.GetName(); msbuildFrameworkName.Name = "Microsoft.Build.Framework"; Assembly msbuildFramework = Assembly.Load(msbuildFrameworkName); par.ReferencedAssemblies.Add(msbuildFramework.Location); par.ReferencedAssemblies.Add(typeof(NAnt.Core.Task).Assembly.Location); par.ReferencedAssemblies.Add(typeof(NAntLogger).Assembly.Location); par.GenerateInMemory = true; CompilerResults res = codeDomProvider.CompileAssemblyFromSource(par, _impl); if (res.Errors.HasErrors) { return null; } Type t = res.CompiledAssembly.GetType("NAntLoggerImpl"); return (NAntLogger)Activator.CreateInstance(t, task, verbosity); } private const string _impl = @" using System; using Microsoft.Build.Framework; using NAnt.Core; using NAnt.MSBuild; internal class NAntLoggerImpl : NAntLogger, ILogger { private readonly Task _task; private LoggerVerbosity _verbosity; public NAntLoggerImpl(Task task, NAntLoggerVerbosity verbosity) { _task = task; _verbosity = (LoggerVerbosity)verbosity; } /// /// Initialize is guaranteed to be called by MSBuild at the start of the build /// before any events are raised. /// public void Initialize(IEventSource eventSource) { eventSource.TaskStarted += new TaskStartedEventHandler(eventSource_TaskStarted); eventSource.TaskFinished += new TaskFinishedEventHandler(eventSource_TaskFinished); eventSource.MessageRaised += new BuildMessageEventHandler(eventSource_MessageRaised); eventSource.WarningRaised += new BuildWarningEventHandler(eventSource_WarningRaised); eventSource.ErrorRaised += new BuildErrorEventHandler(eventSource_ErrorRaised); } private string GetLocation(string file,int lineNumber, int columnNumber) { if (lineNumber != 0 || columnNumber != 0) return String.Format(""{2}({0},{1}): "", lineNumber, columnNumber,file); if (file.Length != 0) return file + "": ""; return string.Empty; } void eventSource_ErrorRaised(object sender, BuildErrorEventArgs e) { string line = String.Format(""{1}Error {0}: {2}"", e.Code, GetLocation(e.File,e.LineNumber, e.ColumnNumber), e.Message); _task.Log(Level.Error, line); } void eventSource_WarningRaised(object sender, BuildWarningEventArgs e) { string line = String.Format(""{1}Warning {0}: {2}"", e.Code, GetLocation(e.File,e.LineNumber, e.ColumnNumber), e.Message); _task.Log(Level.Warning, line); } void eventSource_MessageRaised(object sender, BuildMessageEventArgs e) { Level lev; switch (e.Importance) { case MessageImportance.High: lev = Level.Info; break; case MessageImportance.Low: lev = Level.Debug; break; default: //MessageImportance.Normal lev = Level.Verbose; break; } switch (Verbosity) { case LoggerVerbosity.Quiet: lev -= 2000; break; case LoggerVerbosity.Minimal: lev -= 1000; break; case LoggerVerbosity.Detailed: lev += 1000; break; case LoggerVerbosity.Diagnostic: lev += 2000; break; } _task.Log(lev, e.Message); } void eventSource_TaskStarted(object sender, TaskStartedEventArgs e) { Task task = new DummyTask(_task.Project, e.TaskName); _task.Project.OnTaskStarted(sender, new NAnt.Core.BuildEventArgs(task)); } void eventSource_TaskFinished(object sender, TaskFinishedEventArgs e) { Task task = new DummyTask(_task.Project, e.TaskName); _task.Project.OnTaskFinished(sender, new NAnt.Core.BuildEventArgs(task)); } public string Parameters { get { return string.Empty; } set { } } public void Shutdown() { } public LoggerVerbosity Verbosity { get { return _verbosity; } set { _verbosity = value; } } } "; /// Sample task used for testing. protected class DummyTask : Task { string _name; /// /// Sample task constructor. /// /// Project to assign task to. /// Sample name property. public DummyTask(Project p, string name) { _name = name; Project = p; } /// Gets sample name for task. public override string Name { get { return _name; } } /// Test method. protected override void ExecuteTask() { } } } } nant-0.92-rc1/src/NAnt.MSBuild/VS2008/0000755000175000017500000000000011757310030016605 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.MSBuild/VS2008/OrcasSolutionProvider.cs0000644000175000017500000000411211757302274023464 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2011 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Martin Aliger (martin_aliger@myrealbox.com) using System; using System.CodeDom.Compiler; using System.Text.RegularExpressions; using System.Xml; using NAnt.Core; using NAnt.Core.Util; using NAnt.VSNet; using NAnt.VSNet.Extensibility; using NAnt.VSNet.Tasks; namespace NAnt.VSNet { internal class OrcasSolutionProvider : ISolutionBuildProvider { #region Implementation of ISolutionBuildProvider public int IsSupported(string fileContents) { Regex reSolutionFormat = new Regex(@"^\s*Microsoft Visual Studio Solution File, Format Version\s+(?[0-9]+\.[0-9]+)", RegexOptions.Singleline); MatchCollection matches = reSolutionFormat.Matches(fileContents); if (matches.Count == 0) { return 0; } string formatVersion = matches[0].Groups["formatVersion"].Value; if (formatVersion == "10.00") { return 10; } return 0; } public SolutionBase GetInstance(string solutionContent, SolutionTask solutionTask, TempFileCollection tfc, GacCache gacCache, ReferencesResolver refResolver) { return new OrcasSolution(solutionContent, solutionTask, tfc, gacCache, refResolver); } #endregion Implementation of ISolutionBuildProvider } } nant-0.92-rc1/src/NAnt.MSBuild/VS2008/OrcasSolution.cs0000644000175000017500000000315511757302274021757 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Martin Aliger (martin_aliger@myrealbox.com) // Matthew Mastracci (matt@aclaro.com) // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Text.RegularExpressions; using NAnt.Core; using NAnt.Core.Util; using NAnt.VSNet; using NAnt.VSNet.Tasks; namespace NAnt.VSNet { /// /// Analyses Microsoft Visual Studio .NET 2008 (Orcas) solution files. /// internal class OrcasSolution : WhidbeySolution{ public OrcasSolution(string solutionContent, SolutionTask solutionTask, TempFileCollection tfc, GacCache gacCache, ReferencesResolver refResolver) : base(solutionContent, solutionTask, tfc, gacCache, refResolver) { } } } nant-0.92-rc1/src/NAnt.MSBuild/NAnt.MSBuild.csproj0000644000175000017500000001213611757302274021341 0ustar jtaylorjtaylor Debug AnyCPU 2.0 {318C04B2-D982-4243-9C6A-CA7E035E927D} NAnt.MSBuild NAnt.MSBuild Library OnSuccessfulBuild false 8.0.50727 v2.0 2.0 publish\ true Disk false Foreground 7 Days false false true 0 1.0.0.%2a false false true true full false 4 ..\..\build\Debug\ AllRules.ruleset TRACE;DEBUG ..\..\build\Debug\NAnt.MSBuild.xml true pdbonly true 4 ..\..\build\Release\ AllRules.ruleset TRACE ..\..\build\Release\NAnt.MSBuild.xml CommonAssemblyInfo.cs False .NET Framework 3.5 SP1 Client Profile false False .NET Framework 3.5 SP1 true False Windows Installer 3.1 true {8F5F8375-4097-4952-B860-784EB9961ABE} NAnt.Core {DD434690-B4DF-4BF9-91FE-F139A41E2474} NAnt.VSNet nant-0.92-rc1/src/NAnt.MSBuild/MSBuildProjectProvider.cs0000644000175000017500000000361511757302274022653 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Martin Aliger (martin_aliger@myrealbox.com) using System; using System.Configuration; using System.Xml; using System.CodeDom.Compiler; using System.IO; using NAnt.Core; using NAnt.Core.Util; using NAnt.VSNet; using NAnt.VSNet.Extensibility; using NAnt.VSNet.Tasks; namespace NAnt.MSBuild { internal class MSBuildProjectProvider : IProjectBuildProvider { #region IProjectBuildProvider Members public int IsSupported(string projectExt, XmlElement xmlDefinition) { if (MSBuildProject.IsMSBuildProject(xmlDefinition)) return 20; return 0; } public ProjectBase GetInstance(SolutionBase solution, string projectPath, XmlElement xmlDefinition, SolutionTask solutionTask, TempFileCollection tfc, GacCache gacCache, ReferencesResolver refResolver, DirectoryInfo outputDir) { return new MSBuildProject(solution, projectPath, xmlDefinition, solutionTask, tfc, gacCache, refResolver, outputDir); } public string LoadGuid(XmlElement xmlDefinition) { return MSBuildProject.LoadGuid(xmlDefinition); } #endregion } } nant-0.92-rc1/src/NAnt.MSBuild/AssemblyInfo.cs0000644000175000017500000000220511757302273020676 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System.Reflection; // This will not compile with Visual Studio. If you want to build a signed // executable use the NAnt build file. To build under Visual Studio just // exclude this file from the build. [assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile(@"..\NAnt.key")] [assembly: AssemblyKeyName("")]nant-0.92-rc1/src/NAnt.MSBuild/MSBuildReference.cs0000644000175000017500000000401411757302274021422 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Martin Aliger (martin_aliger@myrealbox.com) using System; using System.Collections.Generic; using System.Text; using System.Xml; using NAnt.Core; using NAnt.Core.Util; using NAnt.VSNet; using NAnt.VSNet.Tasks; using NAnt.VSNet.Types; namespace NAnt.MSBuild { internal class DummyXmlElement : XmlElement { internal DummyXmlElement(XmlDocument doc) : base("", "dummy", "", doc) { } } internal class MSBuildReferenceHelper { private readonly bool _isPrivate; private readonly bool _isPrivateSpecified; public MSBuildReferenceHelper(bool isPrivateSpecified, bool isPrivate) { _isPrivateSpecified = isPrivateSpecified; _isPrivate = isPrivate; } public MSBuildReferenceHelper(string priv, bool privatedefault) { _isPrivateSpecified = (priv != null && priv.Length>0); if (_isPrivateSpecified) { _isPrivate = (priv.ToLower() == "true"); } else { _isPrivate = privatedefault; } } public bool IsPrivate { get { return _isPrivate; } } public bool IsPrivateSpecified { get { return _isPrivateSpecified; } } } } nant-0.92-rc1/src/NAnt.MSBuild/VS2005/0000755000175000017500000000000011757310030016602 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.MSBuild/VS2005/WhidbeySolutionProvider.cs0000644000175000017500000000411311757302274024006 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Martin Aliger (martin_aliger@myrealbox.com) using System; using System.CodeDom.Compiler; using System.Text.RegularExpressions; using System.Xml; using NAnt.Core; using NAnt.Core.Util; using NAnt.VSNet; using NAnt.VSNet.Extensibility; using NAnt.VSNet.Tasks; namespace NAnt.VSNet { internal class WhidbeySolutionProvider : ISolutionBuildProvider { #region Implementation of ISolutionBuildProvider public int IsSupported(string fileContents) { Regex reSolutionFormat = new Regex(@"^\s*Microsoft Visual Studio Solution File, Format Version\s+(?[0-9]+\.[0-9]+)", RegexOptions.Singleline); MatchCollection matches = reSolutionFormat.Matches(fileContents); if (matches.Count == 0) { return 0; } string formatVersion = matches[0].Groups["formatVersion"].Value; if (formatVersion == "9.00") { return 10; } return 0; } public SolutionBase GetInstance(string solutionContent, SolutionTask solutionTask, TempFileCollection tfc, GacCache gacCache, ReferencesResolver refResolver) { return new WhidbeySolution(solutionContent, solutionTask, tfc, gacCache, refResolver); } #endregion Implementation of ISolutionBuildProvider } } nant-0.92-rc1/src/NAnt.MSBuild/VS2005/WhidbeySolution.cs0000644000175000017500000001411011757302274022271 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Martin Aliger (martin_aliger@myrealbox.com) // Matthew Mastracci (matt@aclaro.com) // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Text.RegularExpressions; using NAnt.Core; using NAnt.Core.Util; using NAnt.VSNet; using NAnt.VSNet.Tasks; namespace NAnt.VSNet { /// /// Analyses Microsoft Visual Studio .NET 2005 (Whidbey) solution files. /// internal class WhidbeySolution : SolutionBase { private const string SolutionFolder_GUID = "{2150E333-8FDC-42A3-9474-1A3956D46DE8}"; public WhidbeySolution(string solutionContent, SolutionTask solutionTask, TempFileCollection tfc, GacCache gacCache, ReferencesResolver refResolver) : base(solutionTask, tfc, gacCache, refResolver) { Regex reProjects = new Regex(@"Project\(\""(?\{.*?\})\"".*?\""(?.*?)\"".*?\""(?.*?)\"".*?\""(?.*?)\""(?[\s\S]*?)EndProject", RegexOptions.Multiline); MatchCollection projectMatches = reProjects.Matches(solutionContent); Hashtable explicitProjectDependencies = CollectionsUtil.CreateCaseInsensitiveHashtable(); foreach (Match projectMatch in projectMatches) { string project = projectMatch.Groups["project"].Value; string guid = projectMatch.Groups["guid"].Value; string package = projectMatch.Groups["package"].Value; // bug #1732361: skip solution folders if (package == SolutionFolder_GUID) { continue; } // translate partial project path or URL to absolute path string fullProjectPath = TranslateProjectPath(solutionTask.SolutionFile.DirectoryName, project); if (ManagedProjectBase.IsEnterpriseTemplateProject(fullProjectPath)) { RecursiveLoadTemplateProject(fullProjectPath); } else { // add project entry to collection ProjectEntries.Add(new ProjectEntry(guid, fullProjectPath)); } // set-up project dependencies Regex reDependencies = new Regex(@"^\s+(?\{[0-9a-zA-Z]{8}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{12}\})\s+=\s+(?\{[0-9a-zA-Z]{8}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{12}\})", RegexOptions.Multiline); MatchCollection dependencyMatches = reDependencies.Matches(projectMatch.Value); foreach (Match dependencyMatch in dependencyMatches) { string dependency = dependencyMatch.Groups["dep"].Value; if (!explicitProjectDependencies.ContainsKey(guid)) { explicitProjectDependencies[guid] = CollectionsUtil.CreateCaseInsensitiveHashtable(); } ((Hashtable)explicitProjectDependencies[guid])[dependency] = null; } // set-up project configuration Regex reProjectBuildConfig = new Regex(@"^\s+" + Regex.Escape(guid) + @"\.(?[^|]+)\|(?[^.]+)\.Build\.0\s*=\s*(?[^|]+)\|(?[\.\w ]+)\s*", RegexOptions.Multiline); MatchCollection projectBuildMatches = reProjectBuildConfig.Matches(solutionContent); ProjectEntry projectEntry = ProjectEntries [guid]; if (projectEntry == null) { // TODO: determine if we should report an error if a build // configuration is defined for a project that does not // exist in the solution continue; } // holds mapping between project configuration(s) and solution(s) ConfigurationMap buildConfigurations = new ConfigurationMap( projectBuildMatches.Count); for (int i = 0; i < projectBuildMatches.Count; i++) { Match projectBuildMatch = projectBuildMatches [i]; string solutionConfigName = projectBuildMatch.Groups["solutionConfiguration"].Value; string solutionPlatform = projectBuildMatch.Groups["solutionPlatform"].Value; string projectConfigName = projectBuildMatch.Groups["projectConfiguration"].Value; string projectPlatform = projectBuildMatch.Groups["projectPlatform"].Value; Configuration solutionConfig = new Configuration( solutionConfigName, solutionPlatform); Configuration projectConfig = new Configuration( projectConfigName, projectPlatform); buildConfigurations [solutionConfig] = projectConfig; } // add map to corresponding project entry projectEntry.BuildConfigurations = buildConfigurations; } LoadProjectGuids(new ArrayList(solutionTask.Projects.FileNames), false); LoadProjectGuids(new ArrayList(solutionTask.ReferenceProjects.FileNames), true); LoadProjects(gacCache, refResolver, explicitProjectDependencies); } } } nant-0.92-rc1/src/NAnt.MSBuild/MSBuildProjectReference.cs0000644000175000017500000000513211757302274022753 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2006 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Martin Aliger (martin_aliger@myrealbox.com) using System; using System.Collections.Generic; using System.Text; using System.Xml; using System.IO; using System.CodeDom.Compiler; using NAnt.Core; using NAnt.Core.Util; using NAnt.VSNet; using NAnt.VSNet.Tasks; using NAnt.VSNet.Types; namespace NAnt.MSBuild { internal class MSBuildProjectReference : ProjectReferenceBase { private readonly ProjectBase _project; private readonly MSBuildReferenceHelper _helper; public MSBuildProjectReference( ReferencesResolver referencesResolver, ProjectBase parent, ProjectBase project, bool isPrivateSpecified, bool isPrivate) :base(referencesResolver, parent) { _helper = new MSBuildReferenceHelper(isPrivateSpecified, isPrivate); _project = project; } public MSBuildProjectReference( ReferencesResolver referencesResolver, ProjectBase parent, SolutionBase solution, TempFileCollection tfc, GacCache gacCache, DirectoryInfo outputDir, string pguid, string pname, string rpath, string priv) : base(referencesResolver, parent) { _helper = new MSBuildReferenceHelper(priv, true); string projectFile = solution.GetProjectFileFromGuid(pguid); _project = LoadProject(solution, tfc, gacCache, outputDir, projectFile); } protected override bool IsPrivate { get { return _helper.IsPrivate; } } protected override bool IsPrivateSpecified { get { return _helper.IsPrivateSpecified; } } public override ProjectBase Project { get { return _project; } } public override bool IsManaged(Configuration solutionConfiguration) { return true; } } }nant-0.92-rc1/src/NAnt.MSBuild/Functions/0000755000175000017500000000000011757310030017713 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.MSBuild/Functions/MSBuildFunctions.cs0000644000175000017500000000453311757302273023451 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2006 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Martin Aliger (martin_aliger@myrealbox.com) using System; using System.IO; using System.Collections; using System.Reflection; using System.Globalization; using NAnt.Core; using NAnt.Core.Types; using NAnt.Core.Attributes; namespace NAnt.MSBuild.Functions { /// /// Functions to return information for MSBuild system. /// [FunctionSet("msbuild", "MSBuild")] public class MSBuildFunctions : FunctionSetBase { #region Public Instance Constructors /// public MSBuildFunctions(Project project, PropertyDictionary properties) : base(project, properties) {} #endregion Public Instance Constructors #region Public Instance Methods /// /// Test whether project is VS2005 project and could be built using <msbuild> /// /// The name or path of the project file (csproj, vbproj, ...). /// /// True, if it is msbuild project, False otherwise. /// [Function("is-msbuild-project")] public bool IsMsbuildProject(string project) { using(StreamReader str = new StreamReader(File.Open(project,FileMode.Open,FileAccess.Read,FileShare.ReadWrite))) { System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.Load(str); string ns = doc.NameTable.Get("http://schemas.microsoft.com/developer/msbuild/2003"); return ns != null; } } #endregion Public Static Methods } } nant-0.92-rc1/src/NAnt.MSBuild/MSBuildAssemblyReference.cs0000644000175000017500000001112511757302273023122 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2006 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Martin Aliger (martin_aliger@myrealbox.com) using System; using System.Collections.Generic; using System.Text; using System.Xml; using System.IO; using NAnt.Core; using NAnt.Core.Util; using NAnt.VSNet; using NAnt.VSNet.Tasks; using NAnt.VSNet.Types; namespace NAnt.MSBuild { internal class MSBuildAssemblyReference : AssemblyReferenceBase { private readonly string _name; private readonly MSBuildReferenceHelper _helper; private readonly string _assemblyFile; private readonly string _hintpath; public MSBuildAssemblyReference(XmlElement xe, ReferencesResolver referencesResolver, ProjectBase parent, GacCache gacCache, string name, string priv, string hintpath, string extension) : base(new DummyXmlElement(xe.OwnerDocument), referencesResolver, parent, gacCache) { if (extension == null || extension.Length == 0) { extension = ".dll"; } if (name.Contains(",")) { //fully specified reference. Hmmm - just ignore it for now. name = name.Split(',')[0]; //if (hintpath.Length == 0) //hintpath workaround // hintpath = "." + Path.DirectorySeparatorChar + name + extension; // ".dll"; } _name = name; _helper = new MSBuildReferenceHelper(priv, false); _hintpath = hintpath; _assemblyFile = ResolveAssemblyReference(); } public string HintPath { get { return _hintpath; } } protected override string ResolveAssemblyReference() { // check if assembly reference was resolved before if (_assemblyFile != null) { // if assembly file actually exists, there's no need to resolve // the assembly reference again if (File.Exists(_assemblyFile)) { return _assemblyFile; } } XmlElement referenceElement = XmlDefinition; string assemblyFileName = Name + ".dll"; // 1. The project directory // NOT SURE IF THIS IS CORRECT // 2. The ReferencePath // NOT SURE WE SHOULD DO THIS ONE // 3. The .NET Framework directory string resolvedAssemblyFile = ResolveFromFramework(assemblyFileName); if (resolvedAssemblyFile != null) { return resolvedAssemblyFile; } // 4. AssemblyFolders resolvedAssemblyFile = ResolveFromAssemblyFolders(referenceElement, assemblyFileName); if (resolvedAssemblyFile != null) { return resolvedAssemblyFile; } // ResolveFromRelativePath will return a path regardless of // whether the file actually exists // // the file might actually be created as result of building // a project resolvedAssemblyFile = ResolveFromRelativePath( HintPath); if (resolvedAssemblyFile != null) { return resolvedAssemblyFile; } // resolve from outputPath if (Parent is MSBuildProject) { resolvedAssemblyFile = ResolveFromRelativePath(Path.Combine(((MSBuildProject)Parent).OutputPath, assemblyFileName)); if (resolvedAssemblyFile != null) { return resolvedAssemblyFile; } } // assembly reference could not be resolved return null; } protected override bool IsPrivate { get { return _helper.IsPrivate; } } protected override bool IsPrivateSpecified { get { return _helper.IsPrivateSpecified; } } public override string Name { get { return _name; } } } } nant-0.92-rc1/src/NAnt.MSBuild/MSBuildProject.cs0000644000175000017500000004373311757302274021145 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2006 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Martin Aliger (martin_aliger@myrealbox.com) using System; using System.Xml; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Text; using NAnt.Core; using NAnt.Core.Util; using NAnt.VSNet; using NAnt.VSNet.Tasks; using NAnt.VSNet.Types; namespace NAnt.MSBuild { internal class MSBuildProject : ProjectBase { public static bool IsMSBuildProject(XmlElement e) { if (e.LocalName == "Project" && e.NamespaceURI.StartsWith("http://schemas.microsoft.com/developer/msbuild") ) return true; return false; } public static bool IsMSBuildProject(XmlDocument doc) { return IsMSBuildProject(doc.DocumentElement); } private static string LoadGuid(XmlElement e, XmlNamespaceManager nm) { XmlNode node = e.SelectSingleNode("//x:ProjectGuid", nm); if (node == null) return ""; return node.InnerText; } public static string LoadGuid(XmlDocument doc) { XmlNamespaceManager nm = new XmlNamespaceManager(doc.NameTable); nm.AddNamespace("x", doc.DocumentElement.NamespaceURI); return LoadGuid(doc.DocumentElement,nm); } public static string LoadGuid(XmlElement e) { XmlNamespaceManager nm = new XmlNamespaceManager(e.OwnerDocument.NameTable); nm.AddNamespace("x", e.NamespaceURI); return LoadGuid(e,nm); } private readonly string _projectPath; private readonly ArrayList _references; private readonly string _guid; private readonly DirectoryInfo _projectDirectory; private NAnt.MSBuild.BuildEngine.Project _msproj; private NAnt.MSBuild.BuildEngine.Engine _msbuild; public MSBuildProject(SolutionBase solution, string projectPath, XmlElement xmlDefinition, SolutionTask solutionTask, TempFileCollection tfc, GacCache gacCache, ReferencesResolver refResolver, DirectoryInfo outputDir) : base(xmlDefinition, solutionTask, tfc, gacCache, refResolver, outputDir) { string cfgname = solutionTask.Configuration; string platform = solutionTask.Platform; _msbuild = MSBuildEngine.CreateMSEngine(solutionTask); _msproj = new NAnt.MSBuild.BuildEngine.Project(_msbuild); _msproj.FullFileName = projectPath; _msproj.LoadXml(xmlDefinition.OuterXml); _msproj.GlobalProperties.SetProperty("Configuration", cfgname); if (platform.Length > 0) { _msproj.GlobalProperties.SetProperty("Platform", platform.Replace(" ", string.Empty)); } if (outputDir != null) { _msproj.GlobalProperties.SetProperty("OutputPath", outputDir.FullName); } bool generateDoc = false; //bool targwarnings = true; foreach (NAnt.Core.Tasks.PropertyTask property in solutionTask.CustomProperties) { string val; // expand properties in context of current project for non-dynamic properties if (!property.Dynamic) { val = solutionTask.Project.ExpandProperties(property.Value, solutionTask.GetLocation() ); } else { val = property.Value; } switch (property.PropertyName) { //if (property.PropertyName == "TargetWarnings") targwarnings = Boolean.Parse(val); case "GenerateDocumentation": generateDoc = Boolean.Parse(val); break; default: _msproj.GlobalProperties.SetProperty(property.PropertyName, val); break; } } //set tools version to the msbuild version we got loaded _msproj.ToolsVersion = SolutionTask.Project.TargetFramework.Version.ToString(); //TODO: honoring project's TargetFrameworkVersion is not working atm. System assemblies are resolved badly _msproj.GlobalProperties.SetProperty("TargetFrameworkVersion", "v" + SolutionTask.Project.TargetFramework.Version.ToString()); //evaluating _guid = _msproj.GetEvaluatedProperty("ProjectGuid"); _projectDirectory = new DirectoryInfo(_msproj.GetEvaluatedProperty("ProjectDir")); _projectPath = _msproj.GetEvaluatedProperty("ProjectPath"); //TODO: honoring project's TargetFrameworkVersion is not working atm. System assemblies are resolved badly ////check if we targeting something else and throw a warning //if (targwarnings) //{ // string verString = _msproj.GetEvaluatedProperty("TargetFrameworkVersion"); // if (verString != null) // { // if (verString.StartsWith("v")) verString = verString.Substring(1); // Version ver = new Version(verString); // if (!ver.Equals(SolutionTask.Project.TargetFramework.Version)) // { // Log(Level.Warning, "Project '{1}' targets framework {0}.", verString, Name); // } // } //} //project configuration ProjectEntry projectEntry = solution.ProjectEntries [_guid]; if (projectEntry != null && projectEntry.BuildConfigurations != null) { foreach (ConfigurationMapEntry ce in projectEntry.BuildConfigurations) { Configuration projectConfig = ce.Value; ProjectConfigurations[projectConfig] = new MSBuildConfiguration(this, _msproj, projectConfig); } } else { Configuration projectConfig = new Configuration (cfgname, platform); ProjectConfigurations[projectConfig] = new MSBuildConfiguration(this, _msproj, projectConfig); } //references _references = new ArrayList(); NAnt.MSBuild.BuildEngine.BuildItemGroup refs = _msproj.GetEvaluatedItemsByName("Reference"); foreach (NAnt.MSBuild.BuildEngine.BuildItem r in refs) { string rpath = r.FinalItemSpec; string priv = r.GetMetadata("Private"); string hintpath = r.GetMetadata("HintPath"); string ext = r.GetMetadata("ExecutableExtension"); ReferenceBase reference = new MSBuildAssemblyReference( xmlDefinition, ReferencesResolver, this, gacCache, rpath, priv, hintpath, ext); _references.Add(reference); } refs = _msproj.GetEvaluatedItemsByName("ProjectReference"); foreach (NAnt.MSBuild.BuildEngine.BuildItem r in refs) { string pguid = r.GetMetadata("Project"); string pname = r.GetMetadata("Name"); string rpath = r.FinalItemSpec; string priv = r.GetMetadata("Private"); ReferenceBase reference = new MSBuildProjectReference( ReferencesResolver, this, solution, tfc, gacCache, outputDir, pguid, pname, rpath, priv); _references.Add(reference); } if(generateDoc) { string xmlDocBuildFile = FileUtils.CombinePaths(OutputPath, this.Name + ".xml"); //// make sure the output directory for the doc file exists //if (!Directory.Exists(Path.GetDirectoryName(xmlDocBuildFile))) { // Directory.CreateDirectory(Path.GetDirectoryName(xmlDocBuildFile)); //} // add built documentation file as extra output file ExtraOutputFiles[xmlDocBuildFile] = Path.GetFileName(xmlDocBuildFile); _msproj.GlobalProperties.SetProperty("DocumentationFile", xmlDocBuildFile); } } internal string OutputPath { get { if (OutputDir != null) { return this.OutputDir.FullName; } return _msproj.GetEvaluatedProperty("OutputPath"); } } public override string Name { get { string projectPath; if (IsUrl(_projectPath)) { // construct uri for project path Uri projectUri = new Uri(_projectPath); // get last segment of the uri (which should be the // project file itself) projectPath = projectUri.LocalPath; } else { projectPath = ProjectPath; } // return file part without extension return Path.GetFileNameWithoutExtension(projectPath); } } public override ProjectType Type { get { return ProjectType.MSBuild; } } public override string ProjectPath { get { if (IsUrl(_projectPath)) { return _projectPath; } else { return FileUtils.GetFullPath(_projectPath); } } } public override System.IO.DirectoryInfo ProjectDirectory { get { return _projectDirectory; } } public override ProjectLocation ProjectLocation { get { return ProjectLocation.Local; } } public override string Guid { get { return _guid; } set { throw new InvalidOperationException("It is not allowed to change the GUID of a MSBuild project"); } } public override System.Collections.ArrayList References { get { return _references; } } public override ProjectReferenceBase CreateProjectReference(ProjectBase project, bool isPrivateSpecified, bool isPrivate) { return new MSBuildProjectReference(ReferencesResolver, this, project, isPrivateSpecified, isPrivate); } public override bool IsManaged(Configuration configuration) { return true; } /// /// Determines the version of the target msbuild file. /// /// /// /// This method identifies the msbuild version by reviewing the following tags in order: /// /// /// /// <ProductVersion> /// /// /// <TargetFrameworkVersion> /// /// /// ToolsVersion attribute /// /// /// /// /// A representing the msbuild project file. /// /// /// A enum value indicating the msbuild project /// file version. /// /// /// version string found in the tags listed above is not recognized. /// protected override ProductVersion DetermineProductVersion(System.Xml.XmlElement docElement) { XmlNamespaceManager _nsMgr = new XmlNamespaceManager(new NameTable()); _nsMgr.AddNamespace("ms", docElement.NamespaceURI); // element node XmlNode _productVerNode = docElement.SelectSingleNode("ms:PropertyGroup/ms:ProductVersion", _nsMgr); // element node XmlNode _targetNetVerNode = docElement.SelectSingleNode("ms:PropertyGroup/ms:TargetFrameworkVersion", _nsMgr); // If the element exists and it is not empty, get the // product version from it. if (_productVerNode != null && !String.IsNullOrEmpty(_productVerNode.InnerText)) { Version _ver = new Version(_productVerNode.InnerText); switch (_ver.Major) { case 8: // 8.0.50727 return ProductVersion.Whidbey; case 9: // 9.0.21022 if (_ver.Build <= 21022) { return ProductVersion.Orcas; } return ProductVersion.Rosario; } // If the element exists, get the product version from it. } else if (_targetNetVerNode != null) { string targetFrameworkVer = _targetNetVerNode.InnerText; switch (targetFrameworkVer.ToUpper().Trim()) { case "V4.0": return ProductVersion.Rosario; case "V3.5": return ProductVersion.Orcas; case "V2.0": return ProductVersion.Whidbey; } // If neither of the above mentioned tags exist, look for the "ToolsVersion" // attribute in the tag. } else { XmlAttribute toolsVersionAttribute = docElement.Attributes["ToolsVersion"]; // If the ToolsVersion attribute does not exist at this point, // assume that the project is 2.0. if (toolsVersionAttribute == null) { return ProductVersion.Whidbey; } switch (toolsVersionAttribute.Value) { case "4.0": return ProductVersion.Rosario; case "3.5": return ProductVersion.Orcas; case "2.0": return ProductVersion.Whidbey; } } // Throw a buildexception if none of the version numbers above are found. throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Unknown Project version '{0}'.", ProjectPath), Location.UnknownLocation); } protected override void VerifyProjectXml(System.Xml.XmlElement docElement) { if(!IsMSBuildProject(docElement)) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Project '{0}' is not a valid MSBUILD project.", ProjectPath), Location.UnknownLocation); } } protected override BuildResult Build(Configuration solutionConfiguration) { // explicitly set the Configuration and Platform MSBuildConfiguration projectConfig = (MSBuildConfiguration) BuildConfigurations[solutionConfiguration]; _msproj.GlobalProperties.SetProperty("Configuration", projectConfig.Name); if (!String.IsNullOrEmpty(projectConfig.PlatformName)) { _msproj.GlobalProperties.SetProperty("PlatformTarget", projectConfig.PlatformName.Replace(" ", string.Empty)); } //modify original references to contain full path to whatever we resolved _msproj.RemoveItemsByName("Reference"); _msproj.RemoveItemsByName("ProjectReference"); NAnt.MSBuild.BuildEngine.BuildItemGroup refs = _msproj.AddNewItemGroup(); foreach (ReferenceBase r in _references) { string path = r.GetPrimaryOutputFile(solutionConfiguration); if (path == null || !File.Exists(path)) { if (path == null) { Log(Level.Warning, "Reference \"{0}\" of project {1} failed to be found.", r.Name, this.Name); } else { Log(Level.Warning, "Reference \"{0}\" of project {1} failed to be found (resolved to {2})", r.Name, this.Name, path); } continue; } NAnt.MSBuild.BuildEngine.BuildItem i = refs.AddNewItem("Reference", r.Name); i.SetMetadata("HintPath", path); i.SetMetadata("CopyLocal", r.CopyLocal ? "True" : "False"); } //this should disable assembly resolution and always use hintpath (which we supply) if(_msbuild.Assembly.GetName().Version.Major >= 4) { //MSBuild 4 adds some system references automatically, so adding TargetFrameworkDirectory for those _msproj.GlobalProperties.SetProperty("AssemblySearchPaths", "{HintPathFromItem};{TargetFrameworkDirectory}"); } else { _msproj.GlobalProperties.SetProperty("AssemblySearchPaths", "{HintPathFromItem}"); } if(_msproj.Build()) { return BuildResult.Success; } return BuildResult.Failed; } private static bool IsUrl(string fileName) { if (fileName.StartsWith(Uri.UriSchemeFile) || fileName.StartsWith(Uri.UriSchemeHttp) || fileName.StartsWith(Uri.UriSchemeHttps)) { return true; } return false; } } } nant-0.92-rc1/src/NAnt.MSBuild/MSBuildConfiguration.cs0000644000175000017500000001142211757302273022333 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2006 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Martin Aliger (martin_aliger@myrealbox.com) using System; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Xml; using NAnt.Core; using NAnt.Core.Util; using NAnt.VSNet; using NAnt.VSNet.Types; namespace NAnt.MSBuild { internal class MSBuildConfiguration : ConfigurationBase { private readonly string _name; private readonly string _relativeOutputDir; private readonly DirectoryInfo _outputDir; private readonly DirectoryInfo _objdir; private readonly ManagedOutputType _outputType; private readonly string _asmname; private readonly string _platform; public MSBuildConfiguration(MSBuildProject project, NAnt.MSBuild.BuildEngine.Project msproj, Configuration projectConfig) : base(project) { _name = projectConfig.Name; _platform = projectConfig.Platform; //explicit set. EvaluatedProperties will use those. //Its caller responsibility to set it back to original values, if needed msproj.GlobalProperties.SetProperty("Configuration", _name); if (!String.IsNullOrEmpty(_platform)) { msproj.GlobalProperties.SetProperty("Platform", _platform.Replace(" ", string.Empty)); } _relativeOutputDir = msproj.GetEvaluatedProperty("OutputPath"); if (!_relativeOutputDir.EndsWith(Path.DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture))) { _relativeOutputDir = _relativeOutputDir + Path.DirectorySeparatorChar; } _outputDir = new DirectoryInfo(FileUtils.CombinePaths( project.ProjectDirectory.FullName, _relativeOutputDir)); _objdir = new DirectoryInfo(msproj.GetEvaluatedProperty("IntermediateOutputPath")); _outputType = GetType(msproj.GetEvaluatedProperty("OutputType")); _asmname = msproj.GetEvaluatedProperty("AssemblyName"); } private ManagedOutputType GetType(string p) { switch (p.ToLower(CultureInfo.InvariantCulture)) { case "library": return ManagedOutputType.Library; case "exe": return ManagedOutputType.Executable; case "winexe": return ManagedOutputType.WindowsExecutable; default: throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Output type \"{0}\" of project \"{1}\" is not supported.", p, Project.Name), Location.UnknownLocation); } } public string OutputFileName { get { return string.Concat(AssemblyName, OutputExtension); } } public string OutputExtension { get { switch (_outputType) { case ManagedOutputType.Library: return ".dll"; case ManagedOutputType.Executable: case ManagedOutputType.WindowsExecutable: default: return ".exe"; } } } public override string Name { get { return _name; } } public string AssemblyName { get { return _asmname; } } public override DirectoryInfo OutputDir { get { return _outputDir; } } public override string OutputPath { get { return FileUtils.CombinePaths(OutputDir.FullName, OutputFileName); } } public override DirectoryInfo ObjectDir { get { return _objdir; } } public override string BuildPath { get { return _objdir.FullName; } } public override string RelativeOutputDir { get { return _relativeOutputDir; } } public override string PlatformName { get { return _platform; } } } } nant-0.92-rc1/src/NAnt.MSBuild/NAnt.MSBuild.build0000644000175000017500000000545111757302274021142 0ustar jtaylorjtaylor nant-0.92-rc1/src/NAnt.MSBuild/VS2010/0000755000175000017500000000000011757310030016576 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.MSBuild/VS2010/RosarioSolution.cs0000644000175000017500000000303311757302274022312 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2011 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Martin Aliger (martin_aliger@myrealbox.com) using System; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Text.RegularExpressions; using NAnt.Core; using NAnt.Core.Util; using NAnt.VSNet; using NAnt.VSNet.Tasks; namespace NAnt.VSNet { /// /// Analyses Microsoft Visual Studio .NET 2010 (Rosario) solution files. /// internal class RosarioSolution : WhidbeySolution{ public RosarioSolution(string solutionContent, SolutionTask solutionTask, TempFileCollection tfc, GacCache gacCache, ReferencesResolver refResolver) : base(solutionContent, solutionTask, tfc, gacCache, refResolver) { } } } nant-0.92-rc1/src/NAnt.MSBuild/VS2010/RosarioSolutionProvider.cs0000644000175000017500000000411611757302274024030 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2011 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Martin Aliger (martin_aliger@myrealbox.com) using System; using System.CodeDom.Compiler; using System.Text.RegularExpressions; using System.Xml; using NAnt.Core; using NAnt.Core.Util; using NAnt.VSNet; using NAnt.VSNet.Extensibility; using NAnt.VSNet.Tasks; namespace NAnt.VSNet { internal class RosarioSolutionProvider : ISolutionBuildProvider { #region Implementation of ISolutionBuildProvider public int IsSupported(string fileContents) { Regex reSolutionFormat = new Regex(@"^\s*Microsoft Visual Studio Solution File, Format Version\s+(?[0-9]+\.[0-9]+)", RegexOptions.Singleline); MatchCollection matches = reSolutionFormat.Matches(fileContents); if (matches.Count == 0) { return 0; } string formatVersion = matches[0].Groups["formatVersion"].Value; if (formatVersion == "11.00") { return 10; } return 0; } public SolutionBase GetInstance(string solutionContent, SolutionTask solutionTask, TempFileCollection tfc, GacCache gacCache, ReferencesResolver refResolver) { return new RosarioSolution(solutionContent, solutionTask, tfc, gacCache, refResolver); } #endregion Implementation of ISolutionBuildProvider } } nant-0.92-rc1/src/NAnt.MSBuild/MSBuildEngine.cs0000644000175000017500000000564211757302273020740 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2006 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Martin Aliger (martin_aliger@myrealbox.com) using System; using System.Text; using System.Diagnostics; using NAnt.Core; using NAnt.Core.Tasks; namespace NAnt.MSBuild { internal sealed class MSBuildEngine { private static NAnt.MSBuild.BuildEngine.Engine _msbuild; public static NAnt.MSBuild.BuildEngine.Engine CreateMSEngine(NAnt.VSNet.Tasks.SolutionTask solutionTask) { if (_msbuild!=null) { return _msbuild; } try { _msbuild = NAnt.MSBuild.BuildEngine.Engine.LoadEngine(solutionTask.Project.TargetFramework); } catch (Exception e) { throw new BuildException( String.Format( "MSBuild v{0} can't be found. It is needed for building MSBuild projects. VS2005 and later is using MSBuild projects for C# and VB", solutionTask.Project.TargetFramework.Version), Location.UnknownLocation, e); } _msbuild.UnregisterAllLoggers(); NAntLoggerVerbosity _verbosity = solutionTask.Verbose ? NAntLoggerVerbosity.Normal : NAntLoggerVerbosity.Minimal; NAntLogger _logger = NAntLogger.Create(solutionTask.Project.TargetFramework, solutionTask, _verbosity, _msbuild); if (_logger != null) { _msbuild.RegisterLogger(_logger); } solutionTask.Log(Level.Verbose, "Using MSBuild version {0}.", FileVersionInfo.GetVersionInfo(_msbuild.Assembly.Location).ProductVersion); return _msbuild; } //private static TargetDotNetFrameworkVersion GetTargetDotNetFrameworkVersion (FrameworkInfo framework) { // switch (framework.ClrVersion.ToString (2)) { // case "1.1": // return TargetDotNetFrameworkVersion.Version11; // case "2.0": // return TargetDotNetFrameworkVersion.Version20; // default: // throw new BuildException ("Current target framework is not supported.", // Location.UnknownLocation); // } //} } } nant-0.92-rc1/src/NAnt.DotNet/0000755000175000017500000000000011757310030015641 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.DotNet/AssemblyInfo.cs0000644000175000017500000000233211757302273020575 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Scott Hernandez (ScottHernandez@hotmail.com) // Gert Driesen (drieseng@users.sourceforge.net) using System.Reflection; // This will not compile with Visual Studio. If you want to build a signed // executable use the NAnt build file. To build under Visual Studio just // exclude this file from the build. [assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile(@"..\NAnt.key")] [assembly: AssemblyKeyName("")]nant-0.92-rc1/src/NAnt.DotNet/Types/0000755000175000017500000000000011757310030016745 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.DotNet/Types/DebugOutput.cs0000644000175000017500000001075011757302273021560 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2005 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.ComponentModel; using System.Globalization; namespace NAnt.DotNet.Types { /// /// Specifies the type of debugging information generated by the compiler. /// /// /// /// For backward compatibility, the following string values can also be /// used in build files: /// /// /// /// Value /// Corresponding field /// /// /// "true" /// /// /// /// "false" /// /// /// /// /// When set to then the following conditional /// compilation symbols will also be defined: /// /// /// /// DEBUG /// /// /// TRACE /// /// /// [TypeConverter(typeof(DebugOutputConverter))] public enum DebugOutput { /// /// Create no debug information. /// None = 0, /// /// Enable attaching a debugger to the running program. /// Enable = 1, /// /// Enable attaching a debugger to the running program. /// Full = 2, /// /// Only display assembler when the running program is attached to the /// debugger. /// PdbOnly = 3 } /// /// Specialized that also supports /// case-insensitive conversion of "true" to /// and "false" to /// . /// public class DebugOutputConverter : EnumConverter { /// /// Initializes a new instance of the /// class. /// public DebugOutputConverter() : base(typeof(DebugOutput)) { } /// /// Converts the given object to the type of this converter, using the /// specified context and culture information. /// /// An that provides a format context. /// A object. If a is passed, the current culture is assumed. /// The to convert. /// /// An that represents the converted value. /// public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { string stringValue = value as string; if (stringValue != null) { if (string.Compare(stringValue, "true", true, culture) == 0) return DebugOutput.Enable; if (string.Compare(stringValue, "false", true, culture) == 0) return DebugOutput.None; return Enum.Parse(typeof(DebugOutput), stringValue, true); } // default to EnumConverter behavior return base.ConvertFrom(context, culture, value); } } } nant-0.92-rc1/src/NAnt.DotNet/Types/DelaySign.cs0000644000175000017500000000765411757302273021201 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2007 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.ComponentModel; using System.Globalization; namespace NAnt.DotNet.Types { /// /// Specifies whether the generated assembly is strongly named and will /// be signed later. /// /// /// /// For backward compatibility, the following string values can also be /// used in build files: /// /// /// /// Value /// Corresponding field /// /// /// "true" /// /// /// /// "false" /// /// /// /// [TypeConverter(typeof(DelaySignConverter))] public enum DelaySign { /// /// Not specified. /// NotSet = 0, /// /// Fully sign the assembly. /// No = 1, /// /// Only place the public key in the assembly, allowing the signature /// to be added later. /// Yes = 2 } /// /// Specialized that also supports /// case-insensitive conversion of "true" to /// and "false" to /// . /// public class DelaySignConverter : EnumConverter { /// /// Initializes a new instance of the /// class. /// public DelaySignConverter() : base(typeof(DelaySign)) { } /// /// Converts the given object to the type of this converter, using the /// specified context and culture information. /// /// An that provides a format context. /// A object. If a is passed, the current culture is assumed. /// The to convert. /// /// An that represents the converted value. /// public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { string stringValue = value as string; if (stringValue != null) { if (string.Compare(stringValue, "true", true, culture) == 0) return DelaySign.Yes; if (string.Compare(stringValue, "false", true, culture) == 0) return DelaySign.No; return Enum.Parse(typeof(DelaySign), stringValue, true); } // default to EnumConverter behavior return base.ConvertFrom(context, culture, value); } } } nant-0.92-rc1/src/NAnt.DotNet/Types/EmbeddedResourceCollection.cs0000644000175000017500000003002211757302273024520 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2006 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Util; namespace NAnt.DotNet.Types { /// /// Contains a collection of items. /// /// /// Do not yet expose this to build authors. /// [Serializable()] //[ElementName("embeddedresources")] public class EmbeddedResourceCollection : DataTypeCollectionBase, IList { #region Public Instance Properties /// /// Returns an enumerator that can iterate through the collection. /// /// /// A for the entire collection. /// public EmbeddedResourceEnumerator GetEnumerator() { return new EmbeddedResourceEnumerator(this); } /// /// Gets or sets the item at the specified index. /// /// The zero-based index of the item to get or set. [System.Runtime.CompilerServices.IndexerName("Item")] public EmbeddedResource this[int index] { get { RangeCheck(index); return (EmbeddedResource) List[index]; } set { this.RangeCheck(index); List[index] = value; } } /// /// Gets the with the specified manifest /// resource name. /// /// The manifest resource name of the to get. [System.Runtime.CompilerServices.IndexerName("Item")] public EmbeddedResource this[string value] { get { if (value != null) { // Try to locate instance using Value foreach (EmbeddedResource embeddedResource in base.List) { if (value.Equals(embeddedResource.ManifestResourceName)) { return embeddedResource; } } } return null; } } #endregion Public Instance Properties #region Override implementation of DataTypeCollectionBase /// /// Gets the of the items in this collection. /// /// /// The of the items in this collection. /// protected override Type ItemType { get { return typeof(EmbeddedResource); } } #endregion Override implementation of DataTypeCollectionBase #region IList Members /// /// Gets or sets the item at the specified index. /// /// The zero-based index of the item to get or set. object IList.this[int index] { get { return this[index]; } set { ValidateType(value); this[index] = (EmbeddedResource) value; } } /// /// Inserts a into the collection at the /// specified index. /// /// The zero-based index at which should be inserted. /// The to insert. void IList.Insert(int index, object value) { ValidateType(value); Insert(index, (EmbeddedResource) value); } /// /// Removes the specified from the /// collection. /// /// The to remove from the collection. void IList.Remove(object value) { ValidateType(value); Remove((EmbeddedResource) value); } /// /// Determines whether a is in the collection. /// /// The to locate in the collection. /// /// if is found in the /// collection; otherwise, . /// bool IList.Contains(object value) { ValidateType(value); return List.Contains((EmbeddedResource) value); } /// /// Gets the location of a in the collection. /// /// The object to locate. /// /// The zero-based location of the in the /// collection. /// /// /// If the is not currently a member of /// the collection, -1 is returned. /// int IList.IndexOf(object value) { ValidateType(value); return IndexOf((EmbeddedResource) value); } /// /// Adds a to the end of the collection. /// /// The to be added to the end of the collection. /// /// The position into which the new item was inserted. /// int IList.Add(object value) { ValidateType(value); return Add((EmbeddedResource) value); } #endregion #region Public Instance Methods /// /// Adds the items of a to the end of the collection. /// /// The to be added to the end of the collection. public void AddRange(EmbeddedResourceCollection items) { for (int i = 0; (i < items.Count); i = (i + 1)) { Add(items[i]); } } /// /// Adds a to the end of the collection. /// /// The to be added to the end of the collection. /// /// The position into which the new item was inserted. /// //[BuildElement("import")] public int Add(EmbeddedResource value) { return List.Add(value); } /// /// Inserts a into the collection at the /// specified index. /// /// The zero-based index at which should be inserted. /// The to insert. public void Insert(int index, EmbeddedResource value) { List.Insert(index, value); } /// /// Removes the specified from the /// collection. /// /// The to remove from the collection. public void Remove(EmbeddedResource value) { List.Remove(value); } /// /// Determines whether a is in the collection. /// /// The to locate in the collection. /// /// if is found in the /// collection; otherwise, . /// public bool Contains(EmbeddedResource value) { return List.Contains(value); } /// /// Gets the location of a in the collection. /// /// The object to locate. /// /// The zero-based location of the in the /// collection. /// /// /// If the is not currently a member of /// the collection, -1 is returned. /// public int IndexOf(EmbeddedResource value) { return List.IndexOf(value); } #endregion Public Instance Methods } /// /// Enumerates the items of a . /// public class EmbeddedResourceEnumerator : IEnumerator { #region Internal Instance Constructors /// /// Initializes a new instance of the class /// with the specified . /// /// The collection that should be enumerated. internal EmbeddedResourceEnumerator(EmbeddedResourceCollection arguments) { IEnumerable temp = (IEnumerable) (arguments); _baseEnumerator = temp.GetEnumerator(); } #endregion Internal Instance Constructors #region Implementation of IEnumerator /// /// Gets the current item in the collection. /// /// /// The current item in the collection. /// public EmbeddedResource Current { get { return (EmbeddedResource) _baseEnumerator.Current; } } /// /// Gets the current item in the collection. /// /// /// The current item in the collection. /// object IEnumerator.Current { get { return _baseEnumerator.Current; } } /// /// Advances the enumerator to the next item of the collection. /// /// /// if the enumerator was successfully advanced /// to the next item; if the enumerator has /// passed the end of the collection. /// public bool MoveNext() { return _baseEnumerator.MoveNext(); } bool IEnumerator.MoveNext() { return _baseEnumerator.MoveNext(); } /// /// Sets the enumerator to its initial position, which is before the /// first item in the collection. /// public void Reset() { _baseEnumerator.Reset(); } void IEnumerator.Reset() { _baseEnumerator.Reset(); } #endregion Implementation of IEnumerator #region Private Instance Fields private IEnumerator _baseEnumerator; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.DotNet/Types/AssemblyAttributeCollection.cs0000644000175000017500000002505311757302273024772 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; namespace NAnt.DotNet.Types { /// /// Contains a strongly typed collection of /// objects. /// [Serializable()] public class AssemblyAttributeCollection : CollectionBase { #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public AssemblyAttributeCollection() { } /// /// Initializes a new instance of the class /// with the specified instance. /// public AssemblyAttributeCollection(AssemblyAttributeCollection value) { AddRange(value); } /// /// Initializes a new instance of the class /// with the specified array of instances. /// public AssemblyAttributeCollection(AssemblyAttribute[] value) { AddRange(value); } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets the element at the specified index. /// /// The zero-based index of the element to get or set. [System.Runtime.CompilerServices.IndexerName("Item")] public AssemblyAttribute this[int index] { get {return ((AssemblyAttribute)(base.List[index]));} set {base.List[index] = value;} } /// /// Gets the with the specified value. /// /// The value of the to get. [System.Runtime.CompilerServices.IndexerName("Item")] public AssemblyAttribute this[string value] { get { if (value != null) { // Try to locate instance using Value foreach (AssemblyAttribute AssemblyAttribute in base.List) { if (value.Equals(AssemblyAttribute.Value)) { return AssemblyAttribute; } } } return null; } } #endregion Public Instance Properties #region Public Instance Methods /// /// Adds a to the end of the collection. /// /// The to be added to the end of the collection. /// The position into which the new element was inserted. public int Add(AssemblyAttribute item) { return base.List.Add(item); } /// /// Adds the elements of a array to the end of the collection. /// /// The array of elements to be added to the end of the collection. public void AddRange(AssemblyAttribute[] items) { for (int i = 0; (i < items.Length); i = (i + 1)) { Add(items[i]); } } /// /// Adds the elements of a to the end of the collection. /// /// The to be added to the end of the collection. public void AddRange(AssemblyAttributeCollection items) { for (int i = 0; (i < items.Count); i = (i + 1)) { Add(items[i]); } } /// /// Determines whether a is in the collection. /// /// The to locate in the collection. /// /// if is found in the /// collection; otherwise, . /// public bool Contains(AssemblyAttribute item) { return base.List.Contains(item); } /// /// Determines whether a with the specified /// value is in the collection. /// /// The argument value to locate in the collection. /// /// if a with /// value is found in the collection; otherwise, /// . /// public bool Contains(string value) { return this[value] != null; } /// /// Copies the entire collection to a compatible one-dimensional array, starting at the specified index of the target array. /// /// The one-dimensional array that is the destination of the elements copied from the collection. The array must have zero-based indexing. /// The zero-based index in at which copying begins. public void CopyTo(AssemblyAttribute[] array, int index) { base.List.CopyTo(array, index); } /// /// Retrieves the index of a specified object in the collection. /// /// The object for which the index is returned. /// /// The index of the specified . If the is not currently a member of the collection, it returns -1. /// public int IndexOf(AssemblyAttribute item) { return base.List.IndexOf(item); } /// /// Inserts a into the collection at the specified index. /// /// The zero-based index at which should be inserted. /// The to insert. public void Insert(int index, AssemblyAttribute item) { base.List.Insert(index, item); } /// /// Returns an enumerator that can iterate through the collection. /// /// /// A for the entire collection. /// public new AssemblyAttributeEnumerator GetEnumerator() { return new AssemblyAttributeEnumerator(this); } /// /// Removes a member from the collection. /// /// The to remove from the collection. public void Remove(AssemblyAttribute item) { base.List.Remove(item); } #endregion Public Instance Methods } /// /// Enumerates the elements of a . /// public class AssemblyAttributeEnumerator : IEnumerator { #region Internal Instance Constructors /// /// Initializes a new instance of the class /// with the specified . /// /// The collection that should be enumerated. internal AssemblyAttributeEnumerator(AssemblyAttributeCollection arguments) { IEnumerable temp = (IEnumerable) (arguments); _baseEnumerator = temp.GetEnumerator(); } #endregion Internal Instance Constructors #region Implementation of IEnumerator /// /// Gets the current element in the collection. /// /// /// The current element in the collection. /// public AssemblyAttribute Current { get { return (AssemblyAttribute) _baseEnumerator.Current; } } object IEnumerator.Current { get { return _baseEnumerator.Current; } } /// /// Advances the enumerator to the next element of the collection. /// /// /// if the enumerator was successfully advanced /// to the next element; if the enumerator has /// passed the end of the collection. /// public bool MoveNext() { return _baseEnumerator.MoveNext(); } bool IEnumerator.MoveNext() { return _baseEnumerator.MoveNext(); } /// /// Sets the enumerator to its initial position, which is before the /// first element in the collection. /// public void Reset() { _baseEnumerator.Reset(); } void IEnumerator.Reset() { _baseEnumerator.Reset(); } #endregion Implementation of IEnumerator #region Private Instance Fields private IEnumerator _baseEnumerator; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.DotNet/Types/ModuleSet.cs0000644000175000017500000000564311757302273021217 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.IO; using NAnt.Core; using NAnt.Core.Attributes; namespace NAnt.DotNet.Types { /// /// /// One or more modules to compile into an assembly. /// /// /// /// /// Define a global <moduleset> that can be referenced by /// other tasks or types. /// /// /// /// /// /// /// ]]> /// /// [Serializable()] [ElementName("moduleset")] public class ModuleSet : DataTypeBase { #region Private Instance Fields private readonly ModuleCollection _modules; private DirectoryInfo _dir; #endregion Private Instance Fields #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public ModuleSet() { _modules = new ModuleCollection(this); } #endregion Public Instance Constructors #region Public Instance Properties /// /// The base of the directory of this . /// The default is the project base directory. /// [TaskAttribute("dir")] public DirectoryInfo Dir { get { if (_dir == null) { if (Project != null) { return new DirectoryInfo(Project.BaseDirectory); } } return _dir; } set { _dir = value; } } /// /// The modules to add to this . /// [BuildElementArray("module")] public ModuleCollection Modules { get { return _modules; } } #endregion Public Instance Properties } }nant-0.92-rc1/src/NAnt.DotNet/Types/Module.cs0000644000175000017500000000624011757302273020535 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2007 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.IO; using System.Text; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Util; namespace NAnt.DotNet.Types { /// /// Represents a metadata file without assembly manifest. /// [Serializable] public class Module : Element { #region Public Instance Properties /// /// The path of the module. /// [TaskAttribute("file", Required=true)] [StringValidator(AllowEmpty=false)] public string File { get { if (ModuleSet != null && _file != null) { return Path.Combine (ModuleSet.Dir.FullName, _file); } return _file; } set { _file = value; } } /// /// File name where the module should be copied to before it is compiled /// into an assembly. /// [TaskAttribute("target", Required=false)] public string Target { get { return _target; } set { _target = StringUtils.ConvertEmptyToNull(value); } } /// /// Gets or sets the that contains the module. /// public ModuleSet ModuleSet { get { return _moduleSet; } set { _moduleSet = value; } } #endregion Public Instance Properties #region Override implementation of Object /// /// Returns a textual representation of the module, which can be used as /// argument for command-line tools. /// /// /// A textual representation of the path, file[,target]. /// public override string ToString() { if (File == null) { return null; } StringBuilder sb = new StringBuilder(); sb.Append(File); if (Target != null) { sb.Append(","); sb.Append(Target); } return sb.ToString(); } #endregion Override implementation of Object #region Private Instance Fields private string _file; private string _target; private ModuleSet _moduleSet; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.DotNet/Types/CompilerWarning.cs0000644000175000017500000000461311757302273022412 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using NAnt.Core; using NAnt.Core.Attributes; namespace NAnt.DotNet.Types { /// /// Represents a compiler warning. /// public class CompilerWarning : Element { #region Private Instance Fields private string _number; private bool _ifDefined = true; private bool _unlessDefined; #endregion Private Instance Fields #region Public Instance Properties /// /// A warning number, or comma-separated list of warnings, that you want /// the compiler to suppress or report. /// [TaskAttribute("number", Required=true)] public string Number { get { return _number; } set { _number = value; } } /// /// If then the element will be processed; /// otherwise, skipped. The default is . /// [TaskAttribute("if")] [BooleanValidator()] public bool IfDefined { get { return _ifDefined; } set { _ifDefined = value; } } /// /// If then the element will be skipped; /// otherwise, processed. The default is . /// [TaskAttribute("unless")] [BooleanValidator()] public bool UnlessDefined { get { return _unlessDefined; } set { _unlessDefined = value; } } #endregion Public Instance Properties } } nant-0.92-rc1/src/NAnt.DotNet/Types/CompilerWarningCollection.cs0000644000175000017500000002212311757302273024422 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; namespace NAnt.DotNet.Types { /// /// Contains a collection of elements. /// [Serializable()] public class CompilerWarningCollection : CollectionBase { #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public CompilerWarningCollection() { } /// /// Initializes a new instance of the class /// with the specified instance. /// public CompilerWarningCollection(CompilerWarningCollection value) { AddRange(value); } /// /// Initializes a new instance of the class /// with the specified array of instances. /// public CompilerWarningCollection(CompilerWarning[] value) { AddRange(value); } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets the element at the specified index. /// /// The zero-based index of the element to get or set. [System.Runtime.CompilerServices.IndexerName("Item")] public CompilerWarning this[int index] { get {return ((CompilerWarning)(base.List[index]));} set {base.List[index] = value;} } #endregion Public Instance Properties #region Public Instance Methods /// /// Adds a to the end of the collection. /// /// The to be added to the end of the collection. /// The position into which the new element was inserted. public int Add(CompilerWarning item) { return base.List.Add(item); } /// /// Adds the elements of a array to the end of the collection. /// /// The array of elements to be added to the end of the collection. public void AddRange(CompilerWarning[] items) { for (int i = 0; (i < items.Length); i = (i + 1)) { Add(items[i]); } } /// /// Adds the elements of a to the end of the collection. /// /// The to be added to the end of the collection. public void AddRange(CompilerWarningCollection items) { for (int i = 0; (i < items.Count); i = (i + 1)) { Add(items[i]); } } /// /// Determines whether a is in the collection. /// /// The to locate in the collection. /// /// if is found in the /// collection; otherwise, . /// public bool Contains(CompilerWarning item) { return base.List.Contains(item); } /// /// Copies the entire collection to a compatible one-dimensional array, starting at the specified index of the target array. /// /// The one-dimensional array that is the destination of the elements copied from the collection. The array must have zero-based indexing. /// The zero-based index in at which copying begins. public void CopyTo(CompilerWarning[] array, int index) { base.List.CopyTo(array, index); } /// /// Retrieves the index of a specified object in the collection. /// /// The object for which the index is returned. /// /// The index of the specified . If the is not currently a member of the collection, it returns -1. /// public int IndexOf(CompilerWarning item) { return base.List.IndexOf(item); } /// /// Inserts a into the collection at the specified index. /// /// The zero-based index at which should be inserted. /// The to insert. public void Insert(int index, CompilerWarning item) { base.List.Insert(index, item); } /// /// Returns an enumerator that can iterate through the collection. /// /// /// A for the entire collection. /// public new CompilerWarningEnumerator GetEnumerator() { return new CompilerWarningEnumerator(this); } /// /// Removes a member from the collection. /// /// The to remove from the collection. public void Remove(CompilerWarning item) { base.List.Remove(item); } #endregion Public Instance Methods } /// /// Enumerates the elements of a . /// public class CompilerWarningEnumerator : IEnumerator { #region Internal Instance Constructors /// /// Initializes a new instance of the class /// with the specified . /// /// The collection that should be enumerated. internal CompilerWarningEnumerator(CompilerWarningCollection arguments) { IEnumerable temp = (IEnumerable) (arguments); _baseEnumerator = temp.GetEnumerator(); } #endregion Internal Instance Constructors #region Implementation of IEnumerator /// /// Gets the current element in the collection. /// /// /// The current element in the collection. /// public CompilerWarning Current { get { return (CompilerWarning) _baseEnumerator.Current; } } object IEnumerator.Current { get { return _baseEnumerator.Current; } } /// /// Advances the enumerator to the next element of the collection. /// /// /// if the enumerator was successfully advanced /// to the next element; if the enumerator has /// passed the end of the collection. /// public bool MoveNext() { return _baseEnumerator.MoveNext(); } bool IEnumerator.MoveNext() { return _baseEnumerator.MoveNext(); } /// /// Sets the enumerator to its initial position, which is before the /// first element in the collection. /// public void Reset() { _baseEnumerator.Reset(); } void IEnumerator.Reset() { _baseEnumerator.Reset(); } #endregion Implementation of IEnumerator #region Private Instance Fields private IEnumerator _baseEnumerator; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.DotNet/Types/ModuleCollection.cs0000644000175000017500000004203111757302273022547 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2007 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Util; namespace NAnt.DotNet.Types { /// /// Contains a collection of items. /// /// /// Do not yet expose this to build authors. /// [Serializable()] public class ModuleCollection : IList, IEnumerable { #region Public Instance Constructor /// /// Initializes a new instance of the /// for the specified . /// /// The containing the collection. /// is . public ModuleCollection(ModuleSet moduleSet) { if (moduleSet == null) { throw new ArgumentNullException("moduleSet"); } _moduleSet = moduleSet; _list = new ArrayList(); } #endregion Public Instance Constructor #region Public Instance Properties /// /// Gets or sets the item at the specified index. /// /// The zero-based index of the item to get or set. /// The parameter is less than 0 or greater than or equal to the value of the property of the . [System.Runtime.CompilerServices.IndexerName("Item")] public Module this[int index] { get { if (index < 0 || index >= Count) { throw new ArgumentOutOfRangeException("index", index, "Invalid value."); } return (Module) List[index]; } set { if (index < 0 || index >= Count) { throw new ArgumentOutOfRangeException("index", index, "Invalid value."); } List[index] = value; } } #endregion Public Instance Properties #region Protected Instance Properties /// /// Gets the list of elements contained in the /// instance. /// /// /// An containing the elements of the /// collection. /// protected ArrayList List { get { return _list; } } #endregion Protected Instance Properties #region Implementation of IEnumerable /// /// Returns an enumerator that can iterate through the collection. /// /// /// A for the entire collection. /// IEnumerator IEnumerable.GetEnumerator() { return List.GetEnumerator(); } #endregion Implementation of IEnumerable #region Implementation of ICollection /// /// Gets a value indicating whether access to the collection is /// synchronized (thread-safe). /// /// /// . /// bool ICollection.IsSynchronized { get { return false; } } /// /// Gets the number of items in the collection. /// /// /// The number of items in the collection. /// public int Count { get { return List.Count; } } /// /// Copies the items of the collection to an , /// starting at a particular index. /// /// The one-dimensional that is the destination of the items copied from the collection. The must have zero-based indexing. /// The zero-based index in at which copying begins. public void CopyTo(Array array, int index) { List.CopyTo(array, index); } /// /// Gets an object that can be used to synchronize access to the /// collection. /// /// /// An object that can be used to synchronize access to the collection. /// object ICollection.SyncRoot { get { return this; } } #endregion Implementation of ICollection #region Implementation of IList /// /// Gets a value indicating whether the collection has a fixed size. /// /// /// . /// public bool IsFixedSize { get { return false; } } /// /// Gets a value indicating whether the collection has a fixed size. /// /// /// . /// public bool IsReadOnly { get { return false; } } /// /// Gets or sets the item at the specified index. /// /// The zero-based index of the item to get or set. /// The parameter is less than 0 or greater than or equal to the value of the property of the . object IList.this[int index] { get { return this[index]; } set { if (value == null) { throw new ArgumentNullException ("value"); } if (!(value is Module)) { throw new ArgumentException ("Value is not a Module"); } this[index] = (Module) value; } } /// /// Removes all items from the collection. /// public void Clear() { List.Clear(); } /// /// Inserts a into the collection at the /// specified index. /// /// The zero-based index at which should be inserted. /// The to insert. void IList.Insert(int index, object value) { if (value == null) { throw new ArgumentNullException ("value"); } if (!(value is Module)) { throw new ArgumentException ("Value is not a Module"); } Insert(index, (Module) value); } /// /// Removes the specified from the /// collection. /// /// The to remove from the collection. void IList.Remove(object value) { if (value == null) { throw new ArgumentNullException ("value"); } if (!(value is Module)) { throw new ArgumentException ("Value is not a Module"); } Remove((Module) value); } /// /// Removes an item at a specific index. /// /// The zero-based index of the item to remove. /// The parameter is less than 0 or greater than or equal to the value of the property of the . public void RemoveAt(int index) { if (index < 0 || index >= Count) { throw new ArgumentOutOfRangeException("index", index, "Invalid value."); } List.RemoveAt(index); } /// /// Determines whether a is in the collection. /// /// The to locate in the collection. /// /// if is found in the /// collection; otherwise, . /// bool IList.Contains(object value) { if (value == null) { throw new ArgumentNullException ("value"); } if (!(value is Module)) { throw new ArgumentException ("Value is not a Module"); } return List.Contains((Module) value); } /// /// Gets the location of a in the collection. /// /// The object to locate. /// /// The zero-based location of the in the /// collection. /// /// /// If the is not currently a member of /// the collection, -1 is returned. /// int IList.IndexOf(object value) { if (value == null) { throw new ArgumentNullException ("value"); } if (!(value is Module)) { throw new ArgumentException ("Value is not a Module"); } return IndexOf((Module) value); } /// /// Adds a to the end of the collection. /// /// The to be added to the end of the collection. /// /// The position into which the new item was inserted. /// int IList.Add(object value) { if (value == null) { throw new ArgumentNullException ("value"); } if (!(value is Module)) { throw new ArgumentException ("Value is not a Module"); } return Add((Module) value); } #endregion Implementation of IList #region Public Instance Methods /// /// Adds the items of a to the end of the collection. /// /// The to be added to the end of the collection. public void AddRange(ModuleCollection items) { for (int i = 0; (i < items.Count); i = (i + 1)) { Add(items[i]); } } /// /// Adds a to the end of the collection. /// /// The to be added to the end of the collection. /// /// The position into which the new item was inserted. /// public int Add(Module value) { if (value.ModuleSet != null) { throw new ArgumentException("Module is already linked to other ModuleSet."); } value.ModuleSet = _moduleSet; return List.Add(value); } /// /// Returns an enumerator that can iterate through the collection. /// /// /// A for the entire collection. /// public ModuleEnumerator GetEnumerator() { return new ModuleEnumerator(this); } /// /// Inserts a into the collection at the /// specified index. /// /// The zero-based index at which should be inserted. /// The to insert. public void Insert(int index, Module value) { if (value.ModuleSet != null) { throw new ArgumentException("Module is already linked to other ModuleSet."); } value.ModuleSet = _moduleSet; List.Insert(index, value); } /// /// Removes the specified from the /// collection. /// /// The to remove from the collection. public void Remove(Module value) { List.Remove(value); if (value.ModuleSet == _moduleSet) { value.ModuleSet = null; } } /// /// Determines whether a is in the collection. /// /// The to locate in the collection. /// /// if is found in the /// collection; otherwise, . /// public bool Contains(Module value) { return List.Contains(value); } /// /// Gets the location of a in the collection. /// /// The object to locate. /// /// The zero-based location of the in the /// collection. /// /// /// If the is not currently a member of /// the collection, -1 is returned. /// public int IndexOf(Module value) { return List.IndexOf(value); } #endregion Public Instance Methods #region Private Instance Fields private readonly ModuleSet _moduleSet; private readonly ArrayList _list; #endregion Private Instance Fields } /// /// Enumerates the items of a . /// public class ModuleEnumerator : IEnumerator { #region Internal Instance Constructors /// /// Initializes a new instance of the class /// with the specified . /// /// The collection that should be enumerated. internal ModuleEnumerator(ModuleCollection arguments) { IEnumerable temp = (IEnumerable) (arguments); _baseEnumerator = temp.GetEnumerator(); } #endregion Internal Instance Constructors #region Implementation of IEnumerator /// /// Gets the current item in the collection. /// /// /// The current item in the collection. /// public Module Current { get { return (Module) _baseEnumerator.Current; } } /// /// Gets the current item in the collection. /// /// /// The current item in the collection. /// object IEnumerator.Current { get { return Current; } } /// /// Advances the enumerator to the next item of the collection. /// /// /// if the enumerator was successfully advanced /// to the next item; if the enumerator has /// passed the end of the collection. /// public bool MoveNext() { return _baseEnumerator.MoveNext(); } /// /// Sets the enumerator to its initial position, which is before the /// first item in the collection. /// public void Reset() { _baseEnumerator.Reset(); } #endregion Implementation of IEnumerator #region Private Instance Fields private IEnumerator _baseEnumerator; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.DotNet/Types/ResourceFileSet.cs0000644000175000017500000002274011757302273022356 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Ian MacLean ( ian_maclean@another.com ) using System; using System.Globalization; using System.IO; using System.Text; using NAnt.Core.Attributes; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.DotNet.Types { /// /// Specialized class for managing resource files. /// [ElementName("resourcefileset")] public class ResourceFileSet : FileSet, ICloneable { #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public ResourceFileSet() : base() { } /// /// copy constructor for FileSet. Required in order to /// assign references of FileSet type where /// ResourceFileSet are used /// /// public ResourceFileSet(FileSet fs) : base(fs) { } #endregion Public Instance Constructors #region Public Instance Properties /// /// Indicates the prefix to prepend to the actual resource. /// This is usually the default namspace of the assembly. /// [TaskAttribute("prefix")] public string Prefix { get { return _prefix; } set { _prefix = StringUtils.ConvertEmptyToNull(value); } } /// /// Indicates whether prefixes should be dynamically generated by taking /// the path of the resource relative to the basedir and appending it /// to the specified prefix. The default is . /// [BooleanValidator()] [TaskAttribute("dynamicprefix")] public bool DynamicPrefix { get { return _dynamicprefix; } set { _dynamicprefix = value; } } /// /// Gets a containing all matching resx files. /// /// /// A containing all matching resx files. /// public FileSet ResxFiles { get { ResourceFileSet retFileSet = (ResourceFileSet) this.Clone(); retFileSet.Includes.Clear(); retFileSet.Excludes.Clear(); retFileSet.AsIs.Clear(); retFileSet.FailOnEmpty = false; foreach (string file in FileNames) { if (Path.GetExtension(file).ToLower(CultureInfo.InvariantCulture) == ".resx" ) { retFileSet.Includes.Add(file); } } retFileSet.Scan(); return retFileSet; } } /// /// Gets a containing all matching non-resx /// files. /// /// /// A containing all matching non-resx files. /// public FileSet NonResxFiles { get { ResourceFileSet retFileSet = (ResourceFileSet) this.Clone(); retFileSet.Includes.Clear(); retFileSet.Excludes.Clear(); retFileSet.AsIs.Clear(); retFileSet.FailOnEmpty = false; foreach (string file in FileNames) { if (Path.GetExtension(file).ToLower(CultureInfo.InvariantCulture) != ".resx" ) { retFileSet.Includes.Add(file); } } retFileSet.Scan(); return retFileSet; } } #endregion Public Instance Properties #region Implementation of ICloneable /// /// Creates a shallow copy of the . /// /// /// A shallow copy of the . /// public override object Clone() { ResourceFileSet clone = new ResourceFileSet(); base.CopyTo(clone); clone._dynamicprefix = _dynamicprefix; clone._prefix = _prefix; return clone; } #endregion Implementation of ICloneable #region Public Instance Methods /// /// Gets the manifest resource name for the specified resource file. /// /// The physical path of the resource file. /// /// The manifest resource name to be sent to the compiler. /// public string GetManifestResourceName(string resourceFile) { return GetManifestResourceName(resourceFile, resourceFile); } /// /// Gets the manifest resource name for the file using both its physical /// and logical path. /// /// The physical path of the resource file. /// The logical location of the resource file. /// /// The manifest resource name to be sent to the compiler. /// /// /// We use the relative path of the logical path, but the filename and /// and the extension of the physical path to match VS.NET /// public string GetManifestResourceName(string physicalPath, string logicalPath) { StringBuilder prefix = new StringBuilder(Prefix); if (DynamicPrefix) { string basedir = BaseDirectory.FullName; // ensure basedir ends with directory separator character if (!basedir.EndsWith(Path.DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture))) { basedir += Path.DirectorySeparatorChar; } // ensure filedir ends with directory separator character string filedir = Path.GetDirectoryName(logicalPath); if (!filedir.EndsWith(Path.DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture))) { filedir += Path.DirectorySeparatorChar; } string filePathRelativeToBaseDir = string.Empty; if (filedir != basedir && filedir.StartsWith(basedir)) { filePathRelativeToBaseDir = filedir.Substring(basedir.Length); } string relativePrefix = filePathRelativeToBaseDir.Replace(Path.DirectorySeparatorChar, '.').Replace(Path.AltDirectorySeparatorChar, '.'); if (prefix.Length > 0) { prefix.Append("."); } prefix.Append(relativePrefix); } StringBuilder manifestResourceName = new StringBuilder(); // perform the following character operations : // 1) if a part of the prefix of a manifest resource name starts with // a digit, prefix it with an underscore // eg. Namespace.16x16.1image.if -> Namespace._16x16.1image.gif // 2) characters in the prefix that are neither letter nor digit // must be replaced with underscores string[] parts = prefix.ToString().Split('.'); for (int i = 0; i < parts.Length; i++) { string currentPart = parts[i]; if (currentPart.Length == 0) { // skip empty parts continue; } for (int charIndex = 0; charIndex < currentPart.Length; charIndex++) { char currentChar = currentPart[charIndex]; if (charIndex == 0 && char.IsDigit(currentChar)) { manifestResourceName.Append('_'); manifestResourceName.Append(currentChar); } else if (!char.IsLetterOrDigit(currentChar)) { manifestResourceName.Append('_'); } else { manifestResourceName.Append(currentChar); } } manifestResourceName.Append('.'); } // add filename to manifest resource name as is, VS.NET apparently // ignore the logical filename and uses the name of the physical file manifestResourceName.Append(Path.GetFileName(physicalPath)); // return manifest resource name return manifestResourceName.ToString(); } #endregion Public Instance Methods #region Private Instance Fields private string _prefix; private bool _dynamicprefix; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.DotNet/Types/NamespaceImport.cs0000644000175000017500000001040311757302273022373 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Globalization; using System.Reflection; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Util; namespace NAnt.DotNet.Types { /// /// Represents a namespace to import. /// [Serializable()] [ElementName("import")] public class NamespaceImport : Element { #region Private Instance Fields private string _namespace; private bool _ifDefined = true; private bool _unlessDefined; #endregion Private Instance Fields #region Public Instance Constructors /// /// Initializes a new instance of the /// class. /// public NamespaceImport() { } /// /// Initializes a new instance of the /// class for the specified namespace. /// /// The namespace. /// is . public NamespaceImport(string nameSpace) { if (nameSpace == null) { throw new ArgumentNullException("nameSpace"); } this._namespace = nameSpace; } #endregion Public Instance Constructors #region Public Instance Properties /// /// The name of the namespace to import. /// /// /// The name of the namespace to import. /// [TaskAttribute("name", Required=false)] [StringValidator(AllowEmpty=false)] [Obsolete("Use \"namespace\" attribute instead.", false)] public string TempName { get { return Namespace; } set { Namespace = value; } } // TODO: we need to mark "namespace" as required after the release of // NAnt 0.85 // // We can't do this right now, as it would be a major breaking change // (build authors still use "name" right now). /// /// The name of the namespace to import. /// /// /// The name of the namespace to import. /// [TaskAttribute("namespace", Required=false)] [StringValidator(AllowEmpty=false)] public string Namespace { get { return _namespace; } set { _namespace = value.Trim(); } } /// /// Indicates if the import should be generated. /// /// /// if the import should be generated; otherwise, /// . /// [TaskAttribute("if")] [BooleanValidator()] public bool IfDefined { get { return _ifDefined; } set { _ifDefined = value; } } /// /// Indicates if the import should be not generated. /// /// /// if the import should be not generated; /// otherwise, . /// [TaskAttribute("unless")] [BooleanValidator()] public bool UnlessDefined { get { return _unlessDefined; } set { _unlessDefined = value; } } #endregion Public Instance Properties } } nant-0.92-rc1/src/NAnt.DotNet/Types/ResourceFileSetCollection.cs0000644000175000017500000002213711757302273024372 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; namespace NAnt.DotNet.Types { /// /// Contains a strongly typed collection of objects. /// [Serializable] public class ResourceFileSetCollection : CollectionBase { #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public ResourceFileSetCollection() { } /// /// Initializes a new instance of the class /// with the specified instance. /// public ResourceFileSetCollection(ResourceFileSetCollection value) { AddRange(value); } /// /// Initializes a new instance of the class /// with the specified array of instances. /// public ResourceFileSetCollection(ResourceFileSet[] value) { AddRange(value); } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets the element at the specified index. /// /// The zero-based index of the element to get or set. [System.Runtime.CompilerServices.IndexerName("Item")] public ResourceFileSet this[int index] { get {return ((ResourceFileSet)(base.List[index]));} set {base.List[index] = value;} } #endregion Public Instance Properties #region Public Instance Methods /// /// Adds a to the end of the collection. /// /// The to be added to the end of the collection. /// The position into which the new element was inserted. public int Add(ResourceFileSet item) { return base.List.Add(item); } /// /// Adds the elements of a array to the end of the collection. /// /// The array of elements to be added to the end of the collection. public void AddRange(ResourceFileSet[] items) { for (int i = 0; (i < items.Length); i = (i + 1)) { Add(items[i]); } } /// /// Adds the elements of a to the end of the collection. /// /// The to be added to the end of the collection. public void AddRange(ResourceFileSetCollection items) { for (int i = 0; (i < items.Count); i = (i + 1)) { Add(items[i]); } } /// /// Determines whether a is in the collection. /// /// The to locate in the collection. /// /// if is found in the /// collection; otherwise, . /// public bool Contains(ResourceFileSet item) { return base.List.Contains(item); } /// /// Copies the entire collection to a compatible one-dimensional array, starting at the specified index of the target array. /// /// The one-dimensional array that is the destination of the elements copied from the collection. The array must have zero-based indexing. /// The zero-based index in at which copying begins. public void CopyTo(ResourceFileSet[] array, int index) { base.List.CopyTo(array, index); } /// /// Retrieves the index of a specified object in the collection. /// /// The object for which the index is returned. /// /// The index of the specified . If the is not currently a member of the collection, it returns -1. /// public int IndexOf(ResourceFileSet item) { return base.List.IndexOf(item); } /// /// Inserts a into the collection at the specified index. /// /// The zero-based index at which should be inserted. /// The to insert. public void Insert(int index, ResourceFileSet item) { base.List.Insert(index, item); } /// /// Returns an enumerator that can iterate through the collection. /// /// /// A for the entire collection. /// public new ResourceFileSetEnumerator GetEnumerator() { return new ResourceFileSetEnumerator(this); } /// /// Removes a member from the collection. /// /// The to remove from the collection. public void Remove(ResourceFileSet item) { base.List.Remove(item); } #endregion Public Instance Methods } /// /// Enumerates the elements of a . /// public class ResourceFileSetEnumerator : IEnumerator { #region Internal Instance Constructors /// /// Initializes a new instance of the class /// with the specified . /// /// The collection that should be enumerated. internal ResourceFileSetEnumerator(ResourceFileSetCollection arguments) { IEnumerable temp = (IEnumerable) (arguments); _baseEnumerator = temp.GetEnumerator(); } #endregion Internal Instance Constructors #region Implementation of IEnumerator /// /// Gets the current element in the collection. /// /// /// The current element in the collection. /// public ResourceFileSet Current { get { return (ResourceFileSet) _baseEnumerator.Current; } } object IEnumerator.Current { get { return _baseEnumerator.Current; } } /// /// Advances the enumerator to the next element of the collection. /// /// /// if the enumerator was successfully advanced /// to the next element; if the enumerator has /// passed the end of the collection. /// public bool MoveNext() { return _baseEnumerator.MoveNext(); } bool IEnumerator.MoveNext() { return _baseEnumerator.MoveNext(); } /// /// Sets the enumerator to its initial position, which is before the /// first element in the collection. /// public void Reset() { _baseEnumerator.Reset(); } void IEnumerator.Reset() { _baseEnumerator.Reset(); } #endregion Implementation of IEnumerator #region Private Instance Fields private IEnumerator _baseEnumerator; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.DotNet/Types/NamespaceImportCollection.cs0000644000175000017500000004727511757302273024430 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; using System.Text; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Util; namespace NAnt.DotNet.Types { /// /// Base class for collections that needs to be globally referencable. /// public abstract class DataTypeCollectionBase : DataTypeBase, ICollection { #region Protected Instance Constructors /// /// Initializes a new instance of the /// class. /// protected DataTypeCollectionBase() { _list = new ArrayList(); } #endregion Protected Instance Constructors #region ICollection Members /// /// Gets a value indicating whether access to the collection is /// synchronized (thread-safe). /// /// /// . /// bool ICollection.IsSynchronized { get { return false; } } /// /// Gets the number of items in the collection. /// /// /// The number of items in the collection. /// public int Count { get { return List.Count; } } /// /// Copies the items of the collection to an , /// starting at a particular index. /// /// The one-dimensional that is the destination of the items copied from the collection. The must have zero-based indexing. /// The zero-based index in at which copying begins. public void CopyTo(Array array, int index) { List.CopyTo(array, index); } /// /// Gets an object that can be used to synchronize access to the /// collection. /// /// /// An object that can be used to synchronize access to the collection. /// object ICollection.SyncRoot { get { return this; } } #endregion #region IEnumerable Members /// /// Returns an enumerator that can iterate through a collection. /// /// /// An that can be used to iterate through /// the collection. /// IEnumerator IEnumerable.GetEnumerator() { return List.GetEnumerator(); } #endregion #region Implementation of IList /// /// Gets a value indicating whether the collection has a fixed size. /// /// /// . /// public bool IsFixedSize { get { return false; } } /// /// Gets a value indicating whether the collection has a fixed size. /// /// /// . /// public bool IsReadOnly { get { return false; } } /// /// Removes an item at a specific index. /// /// The zero-based index of the item to remove. public void RemoveAt(int index) { RangeCheck(index); List.RemoveAt(index); } /// /// Removes all items from the collection. /// public void Clear() { List.Clear(); } #endregion Implementation of IList #region Protected Instance Properties /// /// Gets the list of elements contained in the /// instance. /// /// /// An containing the elements of the /// collection. /// protected ArrayList List { get { return _list; } } /// /// Gets the of the items in this collection. /// /// /// The of the items in this collection. /// protected abstract Type ItemType { get; } #endregion Protected Instance Properties #region Private Instance Methods /// /// Used by methods that take instances as argument /// to verify whether the instance is valid for the collection class. /// /// The instance to verify. protected void ValidateType(object value) { if (value == null) { throw new ArgumentNullException("value"); } if (!this.ItemType.IsInstanceOfType(value)) { throw new ArgumentException ("Specified value is not an instance" + " of " + this.ItemType.FullName + "."); } } /// /// Checks whether the specified index is within the range of this /// collection. /// /// The index to check. protected void RangeCheck(int index) { if (index < 0 || index >= Count) { throw new ArgumentOutOfRangeException("index", index, "Index " + "must be greater than or equal to zero, and less than " + "the number of items in the collection."); } } #endregion Private Instance Methods #region Private Instance Fields private ArrayList _list; #endregion Private Instance Fields } /// /// Contains a collection of items. /// /// /// Define a reference with name "system.imports". /// /// /// /// /// /// ]]> /// /// Use the predefined set of imports to compile a VB.NET assembly. /// /// /// /// /// /// /// /// /// /// /// /// ]]> /// /// [Serializable()] [ElementName("namespaceimports")] public class NamespaceImportCollection : DataTypeCollectionBase, IList { #region Public Instance Properties /// /// Returns an enumerator that can iterate through the collection. /// /// /// A for the entire collection. /// public NamespaceImportEnumerator GetEnumerator() { return new NamespaceImportEnumerator(this); } /// /// Gets or sets the item at the specified index. /// /// The zero-based index of the item to get or set. [System.Runtime.CompilerServices.IndexerName("Item")] public NamespaceImport this[int index] { get { RangeCheck(index); return (NamespaceImport) List[index]; } set { this.RangeCheck(index); List[index] = value; } } /// /// Gets the with the specified namespace. /// /// The namespace of the to get. [System.Runtime.CompilerServices.IndexerName("Item")] public NamespaceImport this[string value] { get { if (value != null) { // Try to locate instance using Value foreach (NamespaceImport NamespaceImport in base.List) { if (value.Equals(NamespaceImport.Namespace)) { return NamespaceImport; } } } return null; } } #endregion Public Instance Properties #region Override implementation of Object /// /// Returns a comma-delimited list of namespace imports. /// /// /// A comma-delimited list of namespace imports, or an empty /// if there are no namespace imports. /// /// /// Each namespace import is quoted individually. /// public override string ToString() { StringBuilder sb = new StringBuilder(); foreach (NamespaceImport import in base.List) { if (import.IfDefined && !import.UnlessDefined) { // users might using a single NamespaceImport element to // import multiple namespaces string[] imports = import.Namespace.Split(','); foreach (string ns in imports) { // add comma delimited if its not the first import if (sb.Length > 0) { sb.Append(','); } sb.AppendFormat("\"{0}\"", ns); } } } return sb.ToString(); } #endregion Override implementation of Object #region Override implementation of DataTypeCollectionBase /// /// Gets the of the items in this collection. /// /// /// The of the items in this collection. /// protected override Type ItemType { get { return typeof(NamespaceImport); } } #endregion Override implementation of DataTypeCollectionBase #region IList Members /// /// Gets or sets the item at the specified index. /// /// The zero-based index of the item to get or set. object IList.this[int index] { get { return this[index]; } set { ValidateType(value); this[index] = (NamespaceImport) value; } } /// /// Inserts a into the collection at the /// specified index. /// /// The zero-based index at which should be inserted. /// The to insert. void IList.Insert(int index, object value) { ValidateType(value); Insert(index, (NamespaceImport) value); } /// /// Removes the specified from the /// collection. /// /// The to remove from the collection. void IList.Remove(object value) { ValidateType(value); Remove((NamespaceImport) value); } /// /// Determines whether a is in the collection. /// /// The to locate in the collection. /// /// if is found in the /// collection; otherwise, . /// bool IList.Contains(object value) { ValidateType(value); return List.Contains((NamespaceImport) value); } /// /// Gets the location of a in the collection. /// /// The object to locate. /// /// The zero-based location of the in the /// collection. /// /// /// If the is not currently a member of /// the collection, -1 is returned. /// int IList.IndexOf(object value) { ValidateType(value); return IndexOf((NamespaceImport) value); } /// /// Adds a to the end of the collection. /// /// The to be added to the end of the collection. /// /// The position into which the new item was inserted. /// int IList.Add(object value) { ValidateType(value); return Add((NamespaceImport) value); } #endregion #region Public Instance Methods /// /// Adds the items of a to the end of the collection. /// /// The to be added to the end of the collection. public void AddRange(NamespaceImportCollection items) { for (int i = 0; (i < items.Count); i = (i + 1)) { Add(items[i]); } } /// /// Adds a to the end of the collection. /// /// The to be added to the end of the collection. /// /// The position into which the new item was inserted. /// [BuildElement("import")] public int Add(NamespaceImport value) { return List.Add(value); } /// /// Inserts a into the collection at the /// specified index. /// /// The zero-based index at which should be inserted. /// The to insert. public void Insert(int index, NamespaceImport value) { List.Insert(index, value); } /// /// Removes the specified from the /// collection. /// /// The to remove from the collection. public void Remove(NamespaceImport value) { List.Remove(value); } /// /// Determines whether a is in the collection. /// /// The to locate in the collection. /// /// if is found in the /// collection; otherwise, . /// public bool Contains(NamespaceImport value) { return List.Contains(value); } /// /// Gets the location of a in the collection. /// /// The object to locate. /// /// The zero-based location of the in the /// collection. /// /// /// If the is not currently a member of /// the collection, -1 is returned. /// public int IndexOf(NamespaceImport value) { return List.IndexOf(value); } #endregion Public Instance Methods } /// /// Enumerates the items of a . /// public class NamespaceImportEnumerator : IEnumerator { #region Internal Instance Constructors /// /// Initializes a new instance of the class /// with the specified . /// /// The collection that should be enumerated. internal NamespaceImportEnumerator(NamespaceImportCollection arguments) { IEnumerable temp = (IEnumerable) (arguments); _baseEnumerator = temp.GetEnumerator(); } #endregion Internal Instance Constructors #region Implementation of IEnumerator /// /// Gets the current item in the collection. /// /// /// The current item in the collection. /// public NamespaceImport Current { get { return (NamespaceImport) _baseEnumerator.Current; } } /// /// Gets the current item in the collection. /// /// /// The current item in the collection. /// object IEnumerator.Current { get { return _baseEnumerator.Current; } } /// /// Advances the enumerator to the next item of the collection. /// /// /// if the enumerator was successfully advanced /// to the next item; if the enumerator has /// passed the end of the collection. /// public bool MoveNext() { return _baseEnumerator.MoveNext(); } bool IEnumerator.MoveNext() { return _baseEnumerator.MoveNext(); } /// /// Sets the enumerator to its initial position, which is before the /// first item in the collection. /// public void Reset() { _baseEnumerator.Reset(); } void IEnumerator.Reset() { _baseEnumerator.Reset(); } #endregion Implementation of IEnumerator #region Private Instance Fields private IEnumerator _baseEnumerator; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.DotNet/Types/AssemblyAttribute.cs0000644000175000017500000000755011757302273022760 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Globalization; using System.Reflection; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Util; namespace NAnt.DotNet.Types { /// /// Represents an assembly-level attribute. /// [ElementName("attribute")] [Serializable()] public class AssemblyAttribute : Element { #region Private Instance Fields private string _typeName; private string _value; private bool _asIs; private bool _ifDefined = true; private bool _unlessDefined; #endregion Private Instance Fields #region Public Instance Constructors /// /// Initializes a new instance of the /// class. /// public AssemblyAttribute() { } #endregion Public Instance Constructors #region Public Instance Properties /// /// Typename of the assembly-level attribute. /// [TaskAttribute("type", Required=true)] [StringValidator(AllowEmpty=false)] public string TypeName { get { return _typeName; } set { _typeName = StringUtils.ConvertEmptyToNull(value); } } /// /// Value of the attribute. /// [TaskAttribute("value")] public string Value { get { return _value; } set { _value = value; } } /// /// If then the value of the attribute will be /// set as is, without actually looking for a matching constructor or /// named properties. The default is . /// /// /// if the value of the attribute should be set /// as is; otherwise, . /// [TaskAttribute("asis")] [BooleanValidator()] public bool AsIs { get { return _asIs; } set { _asIs = value; } } /// /// Indicates if the attribute should be generated. /// /// /// if the attribute should be generated; /// otherwise, . /// [TaskAttribute("if")] [BooleanValidator()] public bool IfDefined { get { return _ifDefined; } set { _ifDefined = value; } } /// /// Indicates if the attribute should be not generated. /// /// /// if the attribute should be not generated; /// otherwise, . /// [TaskAttribute("unless")] [BooleanValidator()] public bool UnlessDefined { get { return _unlessDefined; } set { _unlessDefined = value; } } #endregion Public Instance Properties } } nant-0.92-rc1/src/NAnt.DotNet/Types/PackageCollection.cs0000644000175000017500000002133311757302273022657 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; namespace NAnt.DotNet.Types { /// /// Contains a strongly typed collection of /// objects. /// [Serializable()] public class PackageCollection : CollectionBase { #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public PackageCollection() { } /// /// Initializes a new instance of the class /// with the specified instance. /// public PackageCollection(PackageCollection value) { AddRange(value); } /// /// Initializes a new instance of the class /// with the specified array of instances. /// public PackageCollection(Package[] value) { AddRange(value); } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets the element at the specified index. /// /// The zero-based index of the element to get or set. [System.Runtime.CompilerServices.IndexerName("Item")] public Package this[int index] { get {return ((Package)(base.List[index]));} set {base.List[index] = value;} } #endregion Public Instance Properties #region Public Instance Methods /// /// Adds a to the end of the collection. /// /// The to be added to the end of the collection. /// The position into which the new element was inserted. public int Add(Package item) { return base.List.Add(item); } /// /// Adds the elements of a array to the end of the collection. /// /// The array of elements to be added to the end of the collection. public void AddRange(Package[] items) { for (int i = 0; (i < items.Length); i = (i + 1)) { Add(items[i]); } } /// /// Adds the elements of a to the end of the collection. /// /// The to be added to the end of the collection. public void AddRange(PackageCollection items) { for (int i = 0; (i < items.Count); i = (i + 1)) { Add(items[i]); } } /// /// Determines whether a is in the collection. /// /// The to locate in the collection. /// /// if is found in the /// collection; otherwise, . /// public bool Contains(Package item) { return base.List.Contains(item); } /// /// Copies the entire collection to a compatible one-dimensional array, starting at the specified index of the target array. /// /// The one-dimensional array that is the destination of the elements copied from the collection. The array must have zero-based indexing. /// The zero-based index in at which copying begins. public void CopyTo(Package[] array, int index) { base.List.CopyTo(array, index); } /// /// Retrieves the index of a specified object in the collection. /// /// The object for which the index is returned. /// /// The index of the specified . If the is not currently a member of the collection, it returns -1. /// public int IndexOf(Package item) { return base.List.IndexOf(item); } /// /// Inserts a into the collection at the specified index. /// /// The zero-based index at which should be inserted. /// The to insert. public void Insert(int index, Package item) { base.List.Insert(index, item); } /// /// Returns an enumerator that can iterate through the collection. /// /// /// A for the entire collection. /// public new PackageEnumerator GetEnumerator() { return new PackageEnumerator(this); } /// /// Removes a member from the collection. /// /// The to remove from the collection. public void Remove(Package item) { base.List.Remove(item); } #endregion Public Instance Methods } /// /// Enumerates the elements of a . /// public class PackageEnumerator : IEnumerator { #region Internal Instance Constructors /// /// Initializes a new instance of the class /// with the specified . /// /// The collection that should be enumerated. internal PackageEnumerator(PackageCollection arguments) { IEnumerable temp = (IEnumerable) (arguments); _baseEnumerator = temp.GetEnumerator(); } #endregion Internal Instance Constructors #region Implementation of IEnumerator /// /// Gets the current element in the collection. /// /// /// The current element in the collection. /// public Package Current { get { return (Package) _baseEnumerator.Current; } } object IEnumerator.Current { get { return _baseEnumerator.Current; } } /// /// Advances the enumerator to the next element of the collection. /// /// /// if the enumerator was successfully advanced /// to the next element; if the enumerator has /// passed the end of the collection. /// public bool MoveNext() { return _baseEnumerator.MoveNext(); } bool IEnumerator.MoveNext() { return _baseEnumerator.MoveNext(); } /// /// Sets the enumerator to its initial position, which is before the /// first element in the collection. /// public void Reset() { _baseEnumerator.Reset(); } void IEnumerator.Reset() { _baseEnumerator.Reset(); } #endregion Implementation of IEnumerator #region Private Instance Fields private IEnumerator _baseEnumerator; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.DotNet/Types/AssemblyFileSet.cs0000644000175000017500000002200211757302273022335 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian MacLean ( ian_maclean@another.com ) using System; using System.Globalization; using System.IO; using System.Text; using NAnt.Core.Attributes; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.DotNet.Types { /// /// A specialized used for setting the lib directories. /// /// /// The primary reason for this class is to allow the /// to always be the same value as the parent /// /// [Serializable()] public class LibDirectorySet : FileSet { #region Public Instance Constructors /// /// Initializes a new instance of the class. /// /// public LibDirectorySet(AssemblyFileSet parent) { _parent = parent; } #endregion Public Instance Constructors #region Overrides from FileSet /// /// override this. We will always use the base directory of the parent. /// overriding without the TaskAttribute attribute prevents it being set /// in the source xml /// public override DirectoryInfo BaseDirectory { get { return _parent.BaseDirectory; } } #endregion Overrides from FileSet #region Private Instance Fields private AssemblyFileSet _parent; #endregion Private Instance Fields } /// /// Specialized class for managing assembly files. /// /// /// /// If an include pattern does not contain any wildcard characters then /// the assembly will be searched for in following locations (in the order listed): /// /// /// /// /// The base directory of the fileset. /// /// /// /// /// The directories specified using the nested <lib> element. /// /// /// /// /// The list of reference assemblies of the current target framework. /// /// /// /// /// The reference assemblies of a given target framework are defined using /// <reference-assemblies> filesets in the <framework> node /// of the NAnt configuration file. /// /// /// /// /// Define a reference with name "sys.assemblies", holding /// a set of system assemblies. /// /// /// /// /// /// /// /// ]]> /// /// /// Use the predefined set of assemblies to compile a C# assembly. /// /// /// /// /// /// /// /// /// ]]> /// /// /// /// /// Compile a C# assembly using assembly references that are searched for /// in the "Third Party Assemblies" and "Company Assemblies" /// directories. /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// ]]> /// /// /// [Serializable()] [ElementName("assemblyfileset")] public class AssemblyFileSet : FileSet, ICloneable { #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public AssemblyFileSet() : base() { // set the parent reference to point back to us _lib = new LibDirectorySet(this); } /// /// copy constructor for FileSet. Required in order to /// assign references of FileSet type where /// AssemblyFileSets are used /// /// public AssemblyFileSet(FileSet fs) : base(fs) { _lib = new LibDirectorySet(this); } #endregion Public Instance Constructors #region Public Instance Properties /// /// Additional directories to search in for assembly references. /// /// /// /// loosely Corresponds with the /lib[path]: flag of the various compiler tasks. /// /// [BuildElement("lib")] public LibDirectorySet Lib { get { return _lib; } set { _lib = value; } } #endregion Public Instance Properties #region Overrides from FileSet /// /// Do a normal scan and then resolve assemblies. /// public override void Scan() { base.Scan(); ResolveReferences(); } #endregion Overrides from FileSet #region private intance methods /// /// Resolves references to system assemblies and assemblies that can be /// resolved using directories specified in . /// protected void ResolveReferences() { foreach (string pattern in Includes) { if (Path.GetFileName(pattern) == pattern) { string localPath = Path.Combine(BaseDirectory.FullName, pattern); // check if a file match the pattern exists in the // base directory of the references fileset if (File.Exists(localPath)) { // the file will already be included as part of // the fileset scan process continue; } foreach (string libPath in Lib.DirectoryNames) { string fullPath = Path.Combine(libPath, pattern); // check whether an assembly matching the pattern // exists in the assembly directory of the current // framework if (File.Exists(fullPath)) { // found a system reference this.FileNames.Add(fullPath); // continue with the next pattern continue; } } if (Project.TargetFramework != null) { string resolveAssembly = Project.TargetFramework. ResolveAssembly (pattern); if (resolveAssembly != null) { // found reference assembly this.FileNames.Add(resolveAssembly); // continue with the next pattern continue; } } } } } #endregion private intance methods #region Private Instance Fields private LibDirectorySet _lib = null; #endregion Private Instance Fields } }nant-0.92-rc1/src/NAnt.DotNet/Types/EmbeddedResource.cs0000644000175000017500000000445011757302273022512 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2006 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) namespace NAnt.DotNet.Types { /// /// Represents an embedded resource. /// /// /// Do not yet expose this to build authors. /// public class EmbeddedResource { /// /// Initializes a new instance of the /// with the specified file name and manifest resource name. /// /// The path of the compiled resource. /// The manifest resource name of the embedded resource. public EmbeddedResource(string file, string manifestResourceName) { _file = file; _manifestResourceName = manifestResourceName; } /// /// Gets the physical location of the resource to embed. /// /// /// The physical location of the resource to embed. /// public string File { get { return _file; } } /// /// Gets the manifest resource name to use when embedding the resource. /// /// /// The manifest resource name to use when embedding the resource. /// public string ManifestResourceName { get { return _manifestResourceName; } } private readonly string _file; private readonly string _manifestResourceName; } } nant-0.92-rc1/src/NAnt.DotNet/Types/Package.cs0000644000175000017500000000517611757302273020652 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections.Specialized; using NAnt.Core; using NAnt.Core.Attributes; namespace NAnt.DotNet.Types { /// /// Represents a package. /// public class Package : Element { #region Private Instance Fields private string _name; private bool _ifDefined = true; private bool _unlessDefined; #endregion Private Instance Fields #region Public Instance Properties /// /// Name of the package to reference. Multiple package can be specified /// with a single element as a semi-colon separated list of /// package names. /// [TaskAttribute("name", Required=true)] [StringValidator(AllowEmpty=false)] public string PackageName { get { return _name; } set { _name = value; } } /// /// Indicates if the package should be passed to the task. /// If then the package will be passed; /// otherwise, skipped. The default is . /// [TaskAttribute("if")] [BooleanValidator()] public bool IfDefined { get { return _ifDefined; } set { _ifDefined = value; } } /// /// Indicates if the package should not be passed to the task. /// If then the package will be passed; /// otherwise, skipped. The default is . /// [TaskAttribute("unless")] [BooleanValidator()] public bool UnlessDefined { get { return _unlessDefined; } set { _unlessDefined = value; } } #endregion Public Instance Properties } } nant-0.92-rc1/src/NAnt.DotNet/Types/WarningAsError.cs0000644000175000017500000000427011757302273022214 0ustar jtaylorjtaylorusing System; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.DotNet.Tasks; namespace NAnt.DotNet.Types { /// /// Controls the behaviour of a compiler with regards to the reporting of /// warnings. /// /// /// /// Instruct a compiler to report warning 0519 as an error. /// /// /// /// /// /// ]]> /// /// /// /// /// Instruct a compiler not to report warning 0519 as an error, if the /// release property is . /// /// /// /// /// /// ]]> /// /// [ElementName("warnaserror")] public class WarningAsError : DataTypeBase { #region Private Instance Fields private CompilerWarningCollection _includes = new CompilerWarningCollection(); private CompilerWarningCollection _excludes = new CompilerWarningCollection(); #endregion Private Instance Fields #region Public Instance Properties /// /// Specifies a list of warnings that the compiler should treat as /// errors. This overrides the /// attribute. Only supported when targeting .NET 2.0 or higher. /// [BuildElementArray("include")] public CompilerWarningCollection Includes { get { return _includes; } } /// /// Specifies a list of warnings that the compiler should NOT treat as /// errors. This is only useful if /// is . Only supported when targeting .NET 2.0 /// or higher. /// [BuildElementArray("exclude")] public CompilerWarningCollection Excludes { get { return _excludes; } } #endregion Public Instance Properties } } nant-0.92-rc1/src/NAnt.DotNet/Resources/0000755000175000017500000000000011757310030017613 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.DotNet/Resources/Strings.resx0000644000175000017500000003147311757302273022171 0ustar jtaylorjtaylor text/microsoft-resx 1.0 System.Resources.ResXResourceReader System.Resources.ResXResourceWriter Assembly attribute with type '{0}' could not be loaded. An invalid type {0} was specified. Value of assembly attribute '{0}' cannot be set as it has no constructor accepting a primitive type or string. AssemblyInfo file '{0}' could not be generated. Assembly attribute '{0}' has no default public constructor. Value '{0}' cannot be converted to type '{1}' of assembly attribute {2}. The specified code language is not supported. Generating a JSCript AssemblyInfo file is not supported at this moment. Resource '{0}' does not exist. The manifest resource name for '{0}' could not be determined. Invalid value "{0}" for attribute "debug". Either 'keyfile' or 'keycontainer' must be specified. 'target' is a required attribute of <{0} ... />. Input file '{0}' does not exist. Could not determine output file from target '{0}'. Failed to locate type {0}. Type {0} is not a licensed component. Failed to create license for type '{0}'. Failed to create license file for '{0}'. There must be at least one included assembly. Could not create NDoc Project. Failed to read ndoc namespace summary file '{0}'. Error building documentation. Error loading documenter '{0}'. There are no NDoc documenters available. Error loading documenter '{0}' from available documenters ({1}). Is the NDoc documenter assembly available? 'output' attribute is incompatible with fileset use. Resource generator needs either an input attribute, or a non-empty fileset. Error loading assembly '{0}'. Compilation failed: Invalid main class '{0}'. Missing entry point. Invalid entry point declaration (should be static). Invalid entry point declaration (wrong number of parameters). Invalid entry point declaration (invalid parameter type '{0}', '{1}' expected). Failure executing script. CodeDomProvider for '{0}' could not be created. Assembly '{0}' could not be loaded with partial name. Type '{0}' is not a valid CodeDomProvider. Assembly attribute with type '{0}' could not be loaded. Should it be '{0}Attribute'? The assembly linker for {0} does not support a command line option to specify an assembly from which to get all options except the culture field. Generated file '{0}'. File '{0}' is up-to-date. Output file '{0}' is not up-to-date, rebuilding. Output file '{0}' does not exist, rebuilding. Compiling {0} files to '{1}'. Contents of {0}. '{0}' has been updated, recompiling. The compiler for {0} does not support package references. The compiler for {0} does not support a command line option to specify a list of warnings to treat as errors. The compiler for {0} does not support a command line option to specify a list of warnings to suppress. The compiler for {0} does not support the /keyfile option. The compiler for {0} does not support the /keycontainer option. The compiler for {0} does not support the /delaysign option. 'rebuild' attribute set to true, recompiling. Did not find dependent file {0}. Found resource linkage '{0}' in dependent file '{1}'. Could not find any resource linkage in dependent file '{0}'. The compiler for "{0}" does not support the /nostdlib option. The compiler for "{0}" does not support generation of XML Documentation file. The compiler for "{0}" does not support limiting the platform on which the compiled code can run. The compiler for "{0}" does not support accepting only a specific language syntax. Doc file '{0}' does not exist, recompiling. Delay-signing {0} assemblies. Compiling license file '{0}' to '{1}' using target '{2}'. Loading assemblies ... {0} (loaded) Creating licenses ... Created new license file {0}. Writing project settings to '{0}'. NDoc project file: file://{0} % complete Creating COM+ application '{0}'. Finding or creating COM+ application '{0}'. Uninstalling COM+ application '{0}'. The resource compiler for {0} does not support external file references. Generated code for the script looks like: The JScript.NET compiler does not support linking modules. nant-0.92-rc1/src/NAnt.DotNet/Tasks/0000755000175000017500000000000011757310030016726 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.DotNet/Tasks/ScriptTask.cs0000644000175000017500000006161211757302273021364 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Sergey Chaban (serge@wildwestsoftware.com) // Gerry Shaw (gerry_shaw@yahoo.com) // Ian MacLean (ian at maclean.ms) // Giuseppe Greco (giuseppe.greco@agamura.com) // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.CodeDom; using System.CodeDom.Compiler; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Reflection; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Types; using NAnt.Core.Util; using NAnt.DotNet.Types; namespace NAnt.DotNet.Tasks { /// /// Executes the code contained within the task. /// /// ///
Code
/// /// The must contain a single code /// element, which in turn contains the script code. /// /// /// This code can include extensions such as functions, or tasks. Once /// the script task has executed those extensions will be available for /// use in the buildfile. /// /// /// If no extensions have been defined, a static entry point named /// ScriptMain - which must have a single /// argument - is required. /// ///
Namespaces
/// /// The following namespaces are imported by default: /// /// /// /// System /// /// /// System.Collections /// /// /// System.IO /// /// /// System.Text /// /// /// NAnt.Core /// /// /// NAnt.Core.Attributes /// /// ///
Assembly References
/// /// The assembly references that are specified will be used to compile /// the script, and will be loaded into the NAnt appdomain. /// /// /// By default, only the NAnt.Core and mscorlib assemblies /// are referenced. /// ///
/// /// Run C# code that writes a message to the build log. /// /// <script language="C#"> /// <code> /// <![CDATA[ /// public static void ScriptMain(Project project) { /// project.Log(Level.Info, "Hello World from a script task using C#"); /// } /// ]]> /// </code> /// </script> /// /// /// /// Define a custom function and call it using C#. /// /// <script language="C#" prefix="test" > /// <code> /// <![CDATA[ /// [Function("test-func")] /// public static string Testfunc( ) { /// return "some result !!!!!!!!"; /// } /// ]]> /// </code> /// </script> /// <echo message='${test::test-func()}'/> /// /// /// /// Use a custom namespace in C# to create a database /// /// <script language="C#" > /// <references> /// <include name="System.Data.dll" /> /// </references> /// <imports> /// <import namespace="System.Data.SqlClient" /> /// </imports> /// <code> /// <![CDATA[ /// public static void ScriptMain(Project project) { /// string dbUserName = "nant"; /// string dbPassword = "nant"; /// string dbServer = "(local)"; /// string dbDatabaseName = "NAntSample"; /// string connectionString = String.Format("Server={0};uid={1};pwd={2};", dbServer, dbUserName, dbPassword); /// /// SqlConnection connection = new SqlConnection(connectionString); /// string createDbQuery = "CREATE DATABASE " + dbDatabaseName; /// SqlCommand createDatabaseCommand = new SqlCommand(createDbQuery); /// createDatabaseCommand.Connection = connection; /// /// connection.Open(); /// /// try { /// createDatabaseCommand.ExecuteNonQuery(); /// project.Log(Level.Info, "Database added successfully: " + dbDatabaseName); /// } catch (Exception e) { /// project.Log(Level.Error, e.ToString()); /// } finally { /// connection.Close(); /// } /// } /// ]]> /// </code> /// </script> /// /// /// /// /// Run Visual Basic.NET code that writes a message to the build log. /// /// /// <script language="VB"> /// <code> /// <![CDATA[ /// Public Shared Sub ScriptMain(project As Project) /// project.Log(Level.Info, "Hello World from a script task using Visual Basic.NET") /// End Sub /// ]]> /// </code> /// </script> /// /// /// /// Define a custom task and call it using C#. /// /// <script language="C#" prefix="test" > /// <code> /// <![CDATA[ /// [TaskName("usertask")] /// public class TestTask : Task { /// #region Private Instance Fields /// /// private string _message; /// /// #endregion Private Instance Fields /// /// #region Public Instance Properties /// /// [TaskAttribute("message", Required=true)] /// public string FileName { /// get { return _message; } /// set { _message = value; } /// } /// /// #endregion Public Instance Properties /// /// #region Override implementation of Task /// /// protected override void ExecuteTask() { /// Log(Level.Info, _message.ToUpper()); /// } /// #endregion Override implementation of Task /// } /// ]]> /// </code> /// </script> /// <usertask message='Hello from UserTask'/> /// /// /// /// /// Define a custom function and call it using Boo. /// /// /// <script language="Boo.CodeDom.BooCodeProvider, Boo.CodeDom, Version=1.0.0.0, Culture=neutral, PublicKeyToken=32c39770e9a21a67" /// failonerror="true"> /// <code> /// <![CDATA[ /// /// [Function("test-func")] /// def MyFunc(): /// return "Hello from Boo !!!!!!" /// ]]> /// </code> /// </script> /// <echo message='${script::test-func()}'/> /// /// [TaskName("script")] public class ScriptTask : Task { #region Private Instance Fields private string _language = null; private AssemblyFileSet _references = new AssemblyFileSet(); private string _mainClass = ""; private string _rootClassName; private string _prefix = "script"; private NamespaceImportCollection _imports = new NamespaceImportCollection(); private RawXml _code; #endregion Private Instance Fields #region Private Static Fields private static readonly string[] _defaultNamespaces = { "System", "System.Collections", "System.IO", "System.Text", "NAnt.Core", "NAnt.Core.Attributes"}; #endregion Private Static Fields #region Public Instance Properties /// /// The language of the script block. Possible values are "VB", "vb", "VISUALBASIC", "C#", "c#", "CSHARP". /// "JS", "js", "JSCRIPT" "VJS", "vjs", "JSHARP" or a fully-qualified name for a class implementing /// . /// [TaskAttribute("language", Required=true)] public string Language { get { return _language; } set { _language = StringUtils.ConvertEmptyToNull(value); } } /// /// Any required references. /// [BuildElement("references")] public AssemblyFileSet References { get { return _references; } set { _references = value; } } /// /// The name of the main class containing the static ScriptMain /// entry point. /// [TaskAttribute("mainclass", Required=false)] public string MainClass { get { return _mainClass; } set { _mainClass = StringUtils.ConvertEmptyToNull(value); } } /// /// The namespace prefix for any custom functions defined in the script. /// If ommitted the prefix will default to 'script' /// [TaskAttribute("prefix", Required=false)] public string Prefix { get { return _prefix; } set { _prefix = StringUtils.ConvertEmptyToNull(value); } } /// /// The namespaces to import. /// [BuildElement("imports")] public NamespaceImportCollection Imports { get { return _imports; } set { _imports = value; } } /// /// The code to execute. /// [BuildElement("code", Required=true)] public RawXml Code { get { return _code; } set { _code = value; } } #endregion Public Instance Properties #region Override implementation of Task /// /// Initializes the task. /// protected override void Initialize() { _rootClassName = "nant" + Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture); } /// /// Executes the script block. /// protected override void ExecuteTask() { // create compiler info for user-specified language CompilerInfo compilerInfo = CreateCompilerInfo(Language); // ensure base directory is set, even if fileset was not initialized // from XML if (References.BaseDirectory == null) { References.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } ICodeCompiler compiler = compilerInfo.Compiler; CompilerParameters options = new CompilerParameters(); options.GenerateExecutable = false; options.GenerateInMemory = true; options.MainClass = MainClass; // implicitly reference the NAnt.Core assembly options.ReferencedAssemblies.Add (typeof (Project).Assembly.Location); // Log the assembly being added to the CompilerParameters Log(Level.Verbose, "Adding assembly {0}", typeof (Project).Assembly.GetName().Name); // add (and load) assemblies specified by user foreach (string assemblyFile in References.FileNames) { try { // load the assembly into current AppDomain to ensure it is // available when executing the emitted assembly Assembly asm = Assembly.LoadFrom(assemblyFile); // Log the assembly being added to the CompilerParameters Log(Level.Verbose, "Adding assembly {0}", asm.GetName().Name); // add the location of the loaded assembly if (!String.IsNullOrEmpty(asm.Location)) { options.ReferencedAssemblies.Add(asm.Location); } } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2028"), assemblyFile), Location, ex); } } StringCollection imports = new StringCollection(); foreach (NamespaceImport import in Imports) { if (import.IfDefined && !import.UnlessDefined) { imports.Add(import.Namespace); } } // generate the code CodeCompileUnit compileUnit = compilerInfo.GenerateCode(_rootClassName, Code.Xml.InnerText, imports, Prefix); StringWriter sw = new StringWriter(CultureInfo.InvariantCulture); compilerInfo.CodeGen.GenerateCodeFromCompileUnit(compileUnit, sw, null); string code = sw.ToString(); Log(Level.Debug, ResourceUtils.GetString("String_GeneratedCodeLooksLike") + "\n{0}", code); CompilerResults results = compiler.CompileAssemblyFromDom(options, compileUnit); Assembly compiled = null; if (results.Errors.Count > 0) { string errors = ResourceUtils.GetString("NA2029") + Environment.NewLine; foreach (CompilerError err in results.Errors) { errors += err.ToString() + Environment.NewLine; } errors += code; throw new BuildException(errors, Location); } else { compiled = results.CompiledAssembly; } // scan the new assembly for tasks, types and functions // Its unlikely that tasks will be defined in buildfiles though. bool extensionAssembly = TypeFactory.ScanAssembly(compiled, this); string mainClass = _rootClassName; if (!String.IsNullOrEmpty(MainClass)) { mainClass += "+" + MainClass; } Type mainType = compiled.GetType(mainClass); if (mainType == null) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2030"), mainClass), Location); } MethodInfo entry = mainType.GetMethod("ScriptMain"); // check for task or function definitions. if (entry == null) { if (!extensionAssembly) { throw new BuildException(ResourceUtils.GetString("NA2031"), Location); } else { return; // no entry point so nothing to do here beyond loading task and function defs } } if (!entry.IsStatic) { throw new BuildException(ResourceUtils.GetString("NA2032"), Location); } ParameterInfo[] entryParams = entry.GetParameters(); if (entryParams.Length != 1) { throw new BuildException(ResourceUtils.GetString("NA2033"), Location); } if (entryParams[0].ParameterType.FullName != typeof(Project).FullName) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2034"), entryParams[0].ParameterType.FullName, typeof(Project).FullName), Location); } try { // invoke Main method entry.Invoke(null, new object[] {Project}); } catch (Exception ex) { // this exception is not likely to tell us much, BUT the // InnerException normally contains the runtime exception // thrown by the executed script code. throw new BuildException(ResourceUtils.GetString("NA2035"), Location, ex.InnerException); } } #endregion Override implementation of Task #region Private Instance Methods private CompilerInfo CreateCompilerInfo(string language) { CodeDomProvider provider = null; try { switch (language) { case "vb": case "VB": case "VISUALBASIC": provider = CreateCodeDomProvider( "Microsoft.VisualBasic.VBCodeProvider", "System, Culture=neutral"); break; case "c#": case "C#": case "CSHARP": provider = CreateCodeDomProvider( "Microsoft.CSharp.CSharpCodeProvider", "System, Culture=neutral"); break; case "js": case "JS": case "JSCRIPT": provider = CreateCodeDomProvider( "Microsoft.JScript.JScriptCodeProvider", "Microsoft.JScript, Culture=neutral"); break; case "vjs": case "VJS": case "JSHARP": provider = CreateCodeDomProvider( "Microsoft.VJSharp.VJSharpCodeProvider", "VJSharpCodeProvider, Culture=neutral"); break; default: // if its not one of the above then it must be a fully // qualified provider class name provider = CreateCodeDomProvider(language); break; } return new CompilerInfo(provider); } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2036"), language), Location, ex); } } #endregion Private Instance Methods #region Private Static Methods private static CodeDomProvider CreateCodeDomProvider(string typeName, string assemblyName) { Assembly providerAssembly = Assembly.LoadWithPartialName(assemblyName); if (providerAssembly == null) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2037"), assemblyName)); } Type providerType = providerAssembly.GetType(typeName, true, true); return CreateCodeDomProvider(providerType); } private static CodeDomProvider CreateCodeDomProvider(string assemblyQualifiedTypeName) { Type providerType = Type.GetType(assemblyQualifiedTypeName, true, true); return CreateCodeDomProvider(providerType); } private static CodeDomProvider CreateCodeDomProvider(Type providerType) { object provider = Activator.CreateInstance(providerType); if (!(provider is CodeDomProvider)) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2038"), providerType.FullName)); } return (CodeDomProvider) provider; } #endregion Private Static Methods internal class CompilerInfo { public readonly ICodeCompiler Compiler; public readonly ICodeGenerator CodeGen; public CompilerInfo(CodeDomProvider provider) { Compiler = provider.CreateCompiler(); CodeGen = provider.CreateGenerator(); } public CodeCompileUnit GenerateCode(string typeName, string codeBody, StringCollection imports, string prefix) { CodeCompileUnit compileUnit = new CodeCompileUnit(); CodeTypeDeclaration typeDecl = new CodeTypeDeclaration(typeName); typeDecl.IsClass = true; typeDecl.TypeAttributes = TypeAttributes.Public; // create constructor CodeConstructor constructMember = new CodeConstructor(); constructMember.Attributes = MemberAttributes.Public; constructMember.Parameters.Add(new CodeParameterDeclarationExpression("NAnt.Core.Project", "project")); constructMember.Parameters.Add(new CodeParameterDeclarationExpression("NAnt.Core.PropertyDictionary", "propDict")); constructMember.BaseConstructorArgs.Add(new CodeVariableReferenceExpression("project")); constructMember.BaseConstructorArgs.Add(new CodeVariableReferenceExpression ("propDict")); typeDecl.Members.Add(constructMember); typeDecl.BaseTypes.Add(typeof(FunctionSetBase)); // add FunctionSet attribute CodeAttributeDeclaration attrDecl = new CodeAttributeDeclaration("FunctionSet"); attrDecl.Arguments.Add(new CodeAttributeArgument( new CodeVariableReferenceExpression("\"" + prefix + "\""))); attrDecl.Arguments.Add(new CodeAttributeArgument( new CodeVariableReferenceExpression("\"" + prefix + "\""))); typeDecl.CustomAttributes.Add(attrDecl); // pump in the user specified code as a snippet CodeSnippetTypeMember literalMember = new CodeSnippetTypeMember(codeBody); typeDecl.Members.Add( literalMember ); CodeNamespace nspace = new CodeNamespace(); //Add default imports foreach (string nameSpace in ScriptTask._defaultNamespaces) { nspace.Imports.Add(new CodeNamespaceImport(nameSpace)); } foreach (string nameSpace in imports) { nspace.Imports.Add(new CodeNamespaceImport(nameSpace)); } compileUnit.Namespaces.Add( nspace ); nspace.Types.Add(typeDecl); return compileUnit; } } } } nant-0.92-rc1/src/NAnt.DotNet/Tasks/NDocTask.cs0000644000175000017500000005026311757302273020743 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Ian MacLean (ian_maclean@another.com) // Giuseppe Greco (giuseppe.greco@agamura.com) using System; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Text; using System.Xml; using NDoc.Core; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Types; using NAnt.Core.Util; using NAnt.DotNet.Types; using System.Reflection; namespace NAnt.DotNet.Tasks { /// /// Runs NDoc V1.3.1 to create documentation. /// /// /// /// See the NDoc home page for more /// information. /// /// /// By default, only the NDoc MSDN documenter ships as part of the NAnt /// distribution. To make another NDoc documenter from the NDoc V1.3.1 /// distribution available to the , copy the /// documenter assembly (and possible dependencies) to the "lib" /// directory corresponding with the CLR you're running NAnt on /// (eg. <nant root>/bin/lib/net/1.1). /// /// /// /// /// Document two assemblies using the MSDN documenter. The namespaces are /// documented in NamespaceSummary.xml. /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// ]]> /// /// Content of NamespaceSummary.xml : /// /// /// /// The Foo.Bar namespace reinvents the wheel. /// /// /// The Foo.Bar.Tests namespace ensures that the Foo.Bar namespace reinvents the wheel correctly. /// /// /// ]]> /// /// [TaskName("ndoc")] public class NDocTask : Task { #region Private Instance Fields private XmlNodeList _docNodes; private AssemblyFileSet _assemblies = new AssemblyFileSet(); private FileSet _summaries = new FileSet(); private RawXml _documenters; private DirSet _referencePaths = new DirSet(); private string _hhcexe; #endregion Private Instance Fields #region Public Instance Properties /// /// The set of assemblies to document. /// [BuildElement("assemblies", Required=true)] public AssemblyFileSet Assemblies { get { return _assemblies; } set { _assemblies = value; } } /// /// The set of namespace summary files. /// [BuildElement("summaries")] public FileSet Summaries { get { return _summaries; } set { _summaries = value; } } /// /// Specifies the formats in which the documentation should be generated. /// [BuildElement("documenters", Required=true)] public RawXml Documenters { get { return _documenters; } set { _documenters = value; } } /// /// Collection of additional directories to search for referenced /// assemblies. /// [BuildElement("referencepaths")] public DirSet ReferencePaths { get { return _referencePaths; } set { _referencePaths = value; } } #endregion Public Instance Properties #region Override implementation of Task /// /// Initializes the taks and verifies the parameters. /// protected override void Initialize() { // expand and store clone of the xml node _docNodes = Documenters.Xml.Clone().SelectNodes("nant:documenter", NamespaceManager); ExpandPropertiesInNodes(_docNodes); _hhcexe = ResolveHhcExe(); } /// /// Generates an NDoc project and builds the documentation. /// protected override void ExecuteTask() { // ensure base directory is set, even if fileset was not initialized // from XML if (Assemblies.BaseDirectory == null) { Assemblies.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } if (Summaries.BaseDirectory == null) { Summaries.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } if (ReferencePaths.BaseDirectory == null) { ReferencePaths.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } // Make sure there is at least one included assembly. This can't // be done in the Initialize() method because the files might // not have been built at startup time. if (Assemblies.FileNames.Count == 0) { throw new BuildException(ResourceUtils.GetString("NA2020"), Location); } // create NDoc Project NDoc.Core.Project project = null; try { project = new NDoc.Core.Project(); } catch (Exception ex) { throw new BuildException(ResourceUtils.GetString("NA2021"), Location, ex); } // set-up probe path, meaning list of directories where NDoc searches // for documenters // by default, NDoc scans the startup path of the app, so we do not // need to add this explicitly string privateBinPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath; if (privateBinPath != null) { // have NDoc also probe for documenters in the privatebinpath foreach (string relativePath in privateBinPath.Split(Path.PathSeparator)) { project.AppendProbePath(Path.Combine( AppDomain.CurrentDomain.BaseDirectory, relativePath)); } } // check for valid documenters (any other validation can be done by NDoc itself at project load time) foreach (XmlNode node in _docNodes) { //skip non-nant namespace elements and special elements like comments, pis, text, etc. if (!(node.NodeType == XmlNodeType.Element) || !node.NamespaceURI.Equals(NamespaceManager.LookupNamespace("nant"))) { continue; } string documenterName = node.Attributes["name"].Value; CheckAndGetDocumenter(project, documenterName); } // write documenter project settings to temp file string projectFileName = Path.GetTempFileName(); Log(Level.Verbose, ResourceUtils.GetString("String_WritingProjectSettings"), projectFileName); XmlTextWriter writer = new XmlTextWriter(projectFileName, Encoding.UTF8); writer.Formatting = Formatting.Indented; writer.WriteStartDocument(); writer.WriteStartElement("project"); // write assemblies section writer.WriteStartElement("assemblies"); foreach (string assemblyPath in Assemblies.FileNames) { string docPath = Path.ChangeExtension(assemblyPath, ".xml"); writer.WriteStartElement("assembly"); writer.WriteAttributeString("location", assemblyPath); if (File.Exists(docPath)) { writer.WriteAttributeString("documentation", docPath); } writer.WriteEndElement(); } writer.WriteEndElement(); // write summaries section StringBuilder sb = new StringBuilder(); foreach (string summaryPath in Summaries.FileNames) { // write out the namespace summary nodes try { XmlTextReader tr = new XmlTextReader(summaryPath); tr.MoveToContent(); // skip XmlDeclaration and Processing Instructions sb.Append(tr.ReadOuterXml()); tr.Close(); } catch (IOException ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2022"), summaryPath), Location, ex); } } writer.WriteRaw(sb.ToString()); // write out the documenters section writer.WriteStartElement("documenters"); foreach (XmlNode node in _docNodes) { //skip non-nant namespace elements and special elements like comments, pis, text, etc. if (!(node.NodeType == XmlNodeType.Element) || !node.NamespaceURI.Equals(NamespaceManager.LookupNamespace("nant"))) { continue; } writer.WriteRaw(node.OuterXml); } writer.WriteEndElement(); // end project element writer.WriteEndElement(); writer.Close(); try { // read NDoc project file Log(Level.Verbose, ResourceUtils.GetString("String_NDocProjectFile"), Path.GetFullPath(projectFileName)); project.Read(projectFileName); // add additional directories to search for referenced assemblies if (ReferencePaths.DirectoryNames.Count > 0) { foreach (string directory in ReferencePaths.DirectoryNames) { project.ReferencePaths.Add(new ReferencePath(directory)); } } foreach (XmlNode node in _docNodes) { //skip non-nant namespace elements and special elements like comments, pis, text, etc. if (!(node.NodeType == XmlNodeType.Element) || !node.NamespaceURI.Equals(NamespaceManager.LookupNamespace("nant"))) { continue; } string documenterName = node.Attributes["name"].Value; IDocumenter documenter = CheckAndGetDocumenter(project, documenterName); // hook up events for feedback during the build documenter.DocBuildingStep += new DocBuildingEventHandler(OnDocBuildingStep); documenter.DocBuildingProgress += new DocBuildingEventHandler(OnDocBuildingProgress); // build documentation documenter.Build(project); } } catch (Exception ex) { throw new BuildException(ResourceUtils.GetString("NA2023"), Location, ex); } } #endregion Override implementation of Task #region Private Instance Methods /// /// Represents the method that will be called to update the overall /// percent complete value and the current step name. /// /// The source of the event. /// A that contains the event data. private void OnDocBuildingStep(object sender, ProgressArgs e) { Log(Level.Info, e.Status); if (e.Progress == 25 && null != _hhcexe) { // right before progress step 25 HtmlHelp object will be created in MSDN Documentor // so we can set path to hhc.exe per reflection // determined with ILSpy SetHtmlHelpCompiler(sender, _hhcexe); } } /// /// Represents the method that will be called to update the current /// step's precent complete value. /// /// The source of the event. /// A that contains the event data. private void OnDocBuildingProgress(object sender, ProgressArgs e) { Log(Level.Verbose, e.Progress + ResourceUtils.GetString("String_PercentageComplete")); } /// /// Returns the documenter for the given project. /// /// /// Documenter is not found. /// /// /// is . /// private IDocumenter CheckAndGetDocumenter(NDoc.Core.Project project, string documenterName){ IDocumenter documenter = null; if (project == null) { throw new ArgumentNullException("project"); } StringCollection documenters = new StringCollection(); foreach (IDocumenter d in project.Documenters) { documenters.Add(d.Name); // ignore case when comparing documenter names if (string.Compare(d.Name, documenterName, true, CultureInfo.InvariantCulture) == 0) { documenter = (IDocumenter) d; break; } } // throw an exception if the documenter could not be found. if (documenter == null) { if (documenters.Count == 0) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2024"), documenterName), Location); } else { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2025"), documenterName, StringUtils.Join(", ", documenters)), Location); } } return documenter; } /// /// Performs macro expansion for the given nodes. /// /// for which expansion should be performed. private void ExpandPropertiesInNodes(XmlNodeList nodes) { foreach (XmlNode node in nodes) { // do not process comment nodes, or entities and other internal element types. if (node.NodeType == XmlNodeType.Element) { ExpandPropertiesInNodes(node.ChildNodes); foreach (XmlAttribute attr in node.Attributes) { // use "this" keyword as workaround for Mono bug #71992 attr.Value = this.Project.ExpandProperties(attr.Value, Location); } // convert output directory to full path relative to project base directory XmlNode outputDirProperty = (XmlNode) node.SelectSingleNode("property[@name='OutputDirectory']"); if (outputDirProperty != null) { XmlAttribute valueAttribute = (XmlAttribute) outputDirProperty.Attributes.GetNamedItem("value"); if (valueAttribute != null) { // use "this" keyword as workaround for Mono bug #71992 valueAttribute.Value = this.Project.GetFullPath(valueAttribute.Value); } } } } } /// /// Use Reflection to set HtmplHelp._htmlHelpCompiler private field for MSDN Documentor. /// Ndoc could not handle 64bit installations and is not actively developed anymore. /// /// Active documentor /// Path to hhc.exe private void SetHtmlHelpCompiler(object sender, string hhcexe) { Log(Level.Debug, "Setting Html Help Compiler per reflection"); FieldInfo fi = sender.GetType().GetField("htmlHelp", BindingFlags.NonPublic | BindingFlags.Instance); if (null == fi) return; Log(Level.Debug, "Found MSDNDocumenter.htmlHelp field"); object htmlHelp = fi.GetValue(sender); FieldInfo hhc = fi.FieldType.GetField("_htmlHelpCompiler", BindingFlags.NonPublic | BindingFlags.Instance); if (null == hhc) return; Log(Level.Debug, "Found HtmlHelp._htmlHelpCompiler field"); hhc.SetValue(htmlHelp, hhcexe); Log(Level.Verbose, "Set Html Help Compiler to '{0}'", hhcexe); } /// /// Searches in %ProgramFiles(x86)%\HTML Help Workshop and %ProgramFiles%\HTML Help Workshop /// for hhc.exe. If not found let ndoc msdn documentor search itself /// /// the path to hhc.exe if found, null otherwise private string ResolveHhcExe() { StringCollection folders = new StringCollection(); string hhwx86 = Environment.GetEnvironmentVariable("ProgramFiles(x86)"); if (!String.IsNullOrEmpty(hhwx86)) { folders.Add(Path.Combine(hhwx86, "HTML Help Workshop")); } string hhw = Environment.GetEnvironmentVariable("ProgramFiles"); if (!String.IsNullOrEmpty(hhw)) { folders.Add(Path.Combine(hhw, "HTML Help Workshop")); } string[] searchFolders = new string[folders.Count]; for (int i = 0; i < folders.Count; i++) { searchFolders[i] = folders[i]; } return FileUtils.ResolveFile(searchFolders, "hhc.exe", false); } #endregion Private Instance Methods } } nant-0.92-rc1/src/NAnt.DotNet/Tasks/JscTask.cs0000644000175000017500000003424711757302273020643 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Mike Krueger (mike@icsharpcode.net) // Giuseppe Greco (giuseppe.greco@agamura.com) using System; using System.IO; using System.Text.RegularExpressions; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Util; using NAnt.DotNet.Types; namespace NAnt.DotNet.Tasks { /// /// Compiles JScript.NET programs. /// /// /// Compile helloworld.js to helloworld.exe. /// /// /// /// /// /// /// ]]> /// /// [TaskName("jsc")] [ProgramLocation(LocationType.FrameworkDir)] public class JscTask : CompilerBase { #region Private Instance Fields private bool _autoRef; private bool _nostdlib; private string _warningLevel; private string _codepage; private string _platform; private bool _versionSafe; // framework configuration settings private bool _supportsPlatform; #endregion Private Instance Fields #region Private Static Fields private static Regex _classNameRegex = new Regex(@"^((?/\*.*?(\*/|$))|[\s\.\{]+|class\s+(?\w+)|(?\w+))*"); private static Regex _namespaceRegex = new Regex(@"^((?/\*.*?(\*/|$))|[\s\.\{]+|namespace\s+(?(\w+(\.\w+)*)+)|(?\w+))*"); #endregion Private Static Fields #region Public Instance Properties /// /// Automatically references assemblies if they have the same name as /// an imported namespace or as a type annotation when declaring a /// variable. The default is . /// /// /// /// Corresponds with the /autoref flag. /// /// [TaskAttribute("autoref")] [BooleanValidator()] public bool AutoRef { get { return _autoRef; } set { _autoRef = value; } } /// /// Instructs the compiler not to import standard library, and changes /// to . The default is /// . /// /// /// /// Corresponds with the /noconfig flag. /// /// [TaskAttribute("nostdlib")] [BooleanValidator()] public bool NoStdLib { get { return _nostdlib; } set { _nostdlib = value; } } /// /// Specifies which platform version of common language runtime (CLR) /// can run the output file. /// /// /// The platform version of common language runtime (CLR) that can run /// the output file. /// /// /// /// Corresponds with the /platform flag. /// /// [TaskAttribute("platform")] public string Platform { get { return _platform; } set { _platform = StringUtils.ConvertEmptyToNull(value); } } /// /// Causes the compiler to generate errors for implicit method /// overrides. The default is . /// /// /// /// Corresponds with the /versionsafe flag. /// /// [TaskAttribute("versionsafe")] [BooleanValidator()] public bool VersionSafe { get { return _versionSafe; } set { _versionSafe = value; } } /// /// Specifies the warning level for the compiler to display. Valid /// values are 0-4. The default is 4. /// /// /// The warning level for the compiler to display. /// /// /// /// Corresponds with the /warn flag. /// /// [TaskAttribute("warninglevel")] [Int32Validator(0, 4)] public string WarningLevel { get { return _warningLevel; } set { _warningLevel = StringUtils.ConvertEmptyToNull(value); } } /// /// Controls which warnings should be reported as errors. /// /// /// Override to avoid exposing this to build authors, as the JScript.NET /// compiler does not allow control over which warnings should be /// reported as errors. /// public override WarningAsError WarningAsError { get { return base.WarningAsError; } } /// /// Specifies a comma-separated list of warnings that should be suppressed /// by the compiler. /// /// /// Override to avoid exposing this to build authors, as the JScript.NET /// compiler does not support package references. /// [Obsolete("Use the element instead.", false)] public override string NoWarn { get { return base.NoWarn; } set { base.NoWarn = value; } } /// /// Specifies a list of warnings that you want the compiler to suppress. /// /// /// Override to avoid exposing this to build authors, as the JScript.NET /// compiler does not support suppressing warnings. /// public override CompilerWarningCollection SuppressWarnings { get { return base.SuppressWarnings; } } /// /// Specifies the code page to use for all source code files in the /// compilation. /// /// /// /// Corresponds with the /codepage flag. /// /// [TaskAttribute("codepage")] public string Codepage { get { return _codepage; } set { _codepage = StringUtils.ConvertEmptyToNull(value); } } /// /// Specifies the key pair container used to strongname the assembly. /// /// /// Override to avoid exposing this to build authors, as the JScript.NET /// does not support this. /// public override string KeyContainer { get { return base.KeyContainer; } set { base.KeyContainer = value; } } /// /// Specifies a strong name key file. /// /// /// Override to avoid exposing this to build authors, as the JScript.NET /// does not support this. /// public override FileInfo KeyFile { get { return base.KeyFile; } set { base.KeyFile = value; } } /// /// Specifies whether to delay sign the assembly using only the public /// portion of the strong name key. /// /// /// Override to avoid exposing this to build authors, as the JScript.NET /// does not support this. /// public override DelaySign DelaySign { get { return base.DelaySign; } set { base.DelaySign = value; } } /// /// Indicates whether the compiler for a given target framework supports /// the "keycontainer" option. The default is . /// /// /// . /// /// /// Override to avoid exposing this to build authors, as the JScript.NET /// does not support this. /// public override bool SupportsKeyContainer { get { return false; } set { } } /// /// Indicates whether the compiler for a given target framework supports /// the "keyfile" option. The default is . /// /// /// . /// /// /// Override to avoid exposing this to build authors, as the JScript.NET /// does not support this. /// public override bool SupportsKeyFile { get { return false; } set { } } /// /// Indicates whether the compiler for a given target framework supports /// the "delaysign" option. The default is . /// /// /// . /// /// /// Override to avoid exposing this to build authors, as the JScript.NET /// does not support this. /// public override bool SupportsDelaySign { get { return false; } set { } } /// /// Specifies whether the compiler for the active target framework /// supports limiting the platform on which the compiled code can run. /// The default is . /// [FrameworkConfigurable("supportsplatform")] public bool SupportsPlatform { get { return _supportsPlatform; } set { _supportsPlatform = value; } } #endregion Public Instance Properties #region Override implementation of CompilerBase /// /// Link the specified modules into this assembly. /// /// /// Override to avoid exposing this to build authors, as the JScript.NET /// compiler does not support linking modules. /// public override AssemblyFileSet Modules { get { return base.Modules; } set { base.Modules = value; } } /// /// Writes module references to the specified . /// /// The to which the module references should be written. protected override void WriteModuleReferences(TextWriter writer) { if (Modules.FileNames.Count > 0) { Log(Level.Warning, ResourceUtils.GetString("String_JscDoesNotSupportLinkingModules")); } } /// /// Writes the compiler options to the specified . /// /// to which the compiler options should be written. protected override void WriteOptions(TextWriter writer) { if (Debug) { WriteOption(writer, "debug"); WriteOption(writer, "define", "DEBUG"); WriteOption(writer, "define", "TRACE"); } if (NoStdLib) { WriteOption(writer, "nostdlib"); } else if (AutoRef) { WriteOption(writer, "autoref"); } if (WarningLevel != null) { WriteOption(writer, "warn" , WarningLevel); } if (Codepage != null) { WriteOption(writer, "codepage", Codepage); } // platform if (Platform != null) { if (SupportsPlatform) { WriteOption(writer, "platform", Platform); } else { Log(Level.Warning, ResourceUtils.GetString("String_CompilerDoesNotSupportPlatform"), Project.TargetFramework.Description); } } if (VersionSafe) { WriteOption(writer, "versionsafe"); } // win32res if (Win32Res != null) { WriteOption (writer, "win32res", Win32Res.FullName); } } /// /// Gets the file extension required by the current compiler. /// /// /// For the JScript.NET compiler, the file extension is always js. /// public override string Extension { get { return "js"; } } /// /// Gets the class name regular expression for the language of the /// current compiler. /// /// /// Class name regular expression for the language of the current /// compiler. /// protected override Regex ClassNameRegex { get { return _classNameRegex; } } /// /// Gets the namespace regular expression for the language of the /// current compiler. /// /// /// Namespace regular expression for the language of the current /// compiler. /// protected override Regex NamespaceRegex { get { return _namespaceRegex; } } #endregion Override implementation of CompilerBase } } nant-0.92-rc1/src/NAnt.DotNet/Tasks/VbcTask.cs0000644000175000017500000005446011757302273020635 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Gert Driesen (drieseng@users.sourceforge.net) // Mike Krueger (mike@icsharpcode.net) // Aaron A. Anderson (aaron@skypoint.com | aaron.anderson@farmcreditbank.com) // Giuseppe Greco (giuseppe.greco@agamura.com) using System; using System.Globalization; using System.IO; using System.Text.RegularExpressions; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Types; using NAnt.Core.Util; using NAnt.DotNet.Types; namespace NAnt.DotNet.Tasks { /// /// Compiles Visual Basic.NET programs. /// /// /// /// In order to have generate manifest resource names /// that match those generated by Microsoft Visual Studio.NET, the value of /// the attribute of the <> /// element should match the "Root namespace" of the VB.NET project, and the /// value of the attribute /// should be set to "". /// /// /// /// Example build file using this task. /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// ///
/// ]]> /// /// [TaskName("vbc")] [ProgramLocation(LocationType.FrameworkDir)] public class VbcTask : CompilerBase { #region Private Instance Fields private string _baseAddress; private DebugOutput _debugOutput = DebugOutput.None; private FileInfo _docFile; private bool _nostdlib; private string _optionCompare; private bool _optionExplicit; private bool _optionStrict; private bool _optionOptimize; private bool _removeintchecks; private string _rootNamespace; private string _platform; private NamespaceImportCollection _imports = new NamespaceImportCollection(); // framework configuration settings private bool _supportsDocGeneration; private bool _supportsNoStdLib; private bool _supportsPlatform; #endregion Private Instance Fields #region Private Static Fields private static Regex _classNameRegex = new Regex(@"^((?/\*.*?(\*/|$))|[\s\.]+|Class\s+(?\w+)|(?\w+))*"); private static Regex _namespaceRegex = new Regex(@"^((?/\*.*?(\*/|$))|[\s\.]+|Namespace\s+(?(\w+(\.\w+)*)+)|(?\w+))*"); #endregion Private Static Fields #region Public Instance Properties /// /// The preferred base address at which to load a DLL. The default base /// address for a DLL is set by the .NET Framework common language /// runtime. /// /// /// The preferred base address at which to load a DLL. /// /// /// This address must be specified as a hexadecimal number. /// [TaskAttribute("baseaddress")] public string BaseAddress { get { return _baseAddress; } set { _baseAddress = StringUtils.ConvertEmptyToNull(value); } } /// /// Specifies the type of debugging information generated by the /// compiler. The default is . /// [TaskAttribute("debug")] public DebugOutput DebugOutput { get { return _debugOutput; } set { _debugOutput = value; } } /// /// No longer expose this to build authors. Use /// instead. /// public override bool Debug { get { return DebugOutput != DebugOutput.None; } set { DebugOutput = DebugOutput.Enable; } } /// /// The name of the XML documentation file to generate. Only supported /// when targeting .NET 2.0 (or higher). /// /// /// /// Corresponds with the /doc: flag. /// /// [TaskAttribute("doc")] public FileInfo DocFile { get { return _docFile; } set { _docFile = value; } } /// /// Specifies whether the /imports option gets passed to the /// compiler. /// /// /// The value of this attribute is a string that contains one or more /// namespaces separated by commas. /// /// ///
See the Microsoft.NET Framework SDK documentation for details. /// /// Example of an imports attribute /// /// [TaskAttribute("imports")] [Obsolete("Use the element instead.", false)] public string ImportsString { set { if (!String.IsNullOrEmpty(value)) { string[] imports = value.Split(','); foreach (string import in imports) { Imports.Add(new NamespaceImport(import)); } } } } /// /// The namespaces to import. /// [BuildElement("imports")] public NamespaceImportCollection Imports { get { return _imports; } set { _imports = value; } } /// /// Instructs the compiler not to reference standard libraries /// (system.dll and VBC.RSP). The default is . /// Only supported when targeting .NET 2.0 (or higher). /// /// /// /// Corresponds with the /nostdlib flag. /// /// [FrameworkConfigurable("nostdlib")] [TaskAttribute("nostdlib")] [BooleanValidator()] public bool NoStdLib { get { return _nostdlib; } set { _nostdlib = value; } } /// /// Specifies whether /optioncompare option gets passed to the /// compiler. /// /// /// text, binary, or an empty string. If the value is /// or an empty string, the option will not be /// passed to the compiler. /// /// See the Microsoft.NET Framework SDK documentation for details. [TaskAttribute("optioncompare")] public string OptionCompare { get { return _optionCompare; } set { _optionCompare = StringUtils.ConvertEmptyToNull(value); } } /// /// Specifies whether the /optionexplicit option gets passed to /// the compiler. The default is . /// /// /// if the option should be passed to the compiler; /// otherwise, . /// /// See the Microsoft.NET Framework SDK documentation for details. [TaskAttribute("optionexplicit")] [BooleanValidator()] public bool OptionExplicit { get { return _optionExplicit; } set { _optionExplicit = value; } } /// /// Specifies whether the /optimize option gets passed to the /// compiler. The default is . /// /// /// if the option should be passed to the compiler; /// otherwise, . /// /// See the Microsoft.NET Framework SDK documentation for details. [TaskAttribute("optionoptimize")] [BooleanValidator()] public bool OptionOptimize { get { return _optionOptimize; } set { _optionOptimize = value; } } /// /// Specifies whether the /optionstrict option gets passed to /// the compiler. The default is . /// /// /// if the option should be passed to the compiler; /// otherwise, . /// /// See the Microsoft.NET Framework SDK documentation for details. [TaskAttribute("optionstrict")] [BooleanValidator()] public bool OptionStrict { get { return _optionStrict; } set { _optionStrict = value; } } /// /// Specifies which platform version of common language runtime (CLR) /// can run the output file. /// /// /// The platform version of common language runtime (CLR) that can run /// the output file. /// /// /// /// Corresponds with the /platform flag. /// /// [TaskAttribute("platform")] public string Platform { get { return _platform; } set { _platform = StringUtils.ConvertEmptyToNull(value); } } /// /// Specifies whether the /removeintchecks option gets passed to /// the compiler. The default is . /// /// /// if the option should be passed to the compiler; /// otherwise, . /// /// See the Microsoft.NET Framework SDK documentation for details. [TaskAttribute("removeintchecks")] [BooleanValidator()] public bool RemoveIntChecks { get { return _removeintchecks; } set { _removeintchecks = value; } } /// /// Specifies whether the /rootnamespace option gets passed to /// the compiler. /// /// /// The value of this attribute is a string that contains the root /// namespace of the project. /// /// See the Microsoft.NET Framework SDK documentation for details. [TaskAttribute("rootnamespace")] public string RootNamespace { get { return _rootNamespace; } set { _rootNamespace = StringUtils.ConvertEmptyToNull(value); } } /// /// Specifies whether the compiler for the active target framework /// supports generation of XML Documentation file. The default is /// . /// [FrameworkConfigurable("supportsdocgeneration")] public bool SupportsDocGeneration { get { return _supportsDocGeneration; } set { _supportsDocGeneration = value; } } /// /// Specifies whether the compiler for the active target framework /// supports NOT referencing standard libraries (system.dll and VBC.RSP). /// The default is . /// [FrameworkConfigurable("supportsnostdlib")] public bool SupportsNoStdLib { get { return _supportsNoStdLib; } set { _supportsNoStdLib = value; } } /// /// Specifies whether the compiler for the active target framework /// supports limiting the platform on which the compiled code can run. /// The default is . /// [FrameworkConfigurable("supportsplatform")] public bool SupportsPlatform { get { return _supportsPlatform; } set { _supportsPlatform = value; } } #endregion Public Instance Properties #region Override implementation of CompilerBase /// /// Finds the correct namespace/classname for a resource file from the /// given dependent source file, and ensure the /// is prefixed. /// /// The file from which the resource linkage of the resource file should be determined. /// The culture of the resource file for which the resource linkage should be determined. /// /// The namespace/classname of the source file matching the resource or /// if the dependent source file does not exist. /// protected override ResourceLinkage GetResourceLinkage(string dependentFile, CultureInfo resourceCulture) { // determine resource linkage from dependent file ResourceLinkage resourceLinkage = base.GetResourceLinkage(dependentFile, resourceCulture); // check if resource linkage could be determined at all if (resourceLinkage != null) { // for VB.NET, the root namespace always needs to be used if (!String.IsNullOrEmpty(RootNamespace)) { if (resourceLinkage.HasNamespaceName) { resourceLinkage.NamespaceName = RootNamespace + "." + resourceLinkage.NamespaceName; } else { resourceLinkage.NamespaceName = RootNamespace; } } } return resourceLinkage; } /// /// Writes conditional compilation constants to the specified /// . /// /// The to which the conditional compilation constants should be written. protected override void WriteConditionalCompilationConstants(TextWriter writer) { if (Define != null) { string[] constants = Define.Split(','); foreach (string constant in constants) { WriteOption(writer, "define", constant); } } } /// /// Writes the compiler options to the specified . /// /// to which the compiler options should be written. protected override void WriteOptions(TextWriter writer) { // the base address for the DLL if (BaseAddress != null) { WriteOption(writer, "baseaddress", BaseAddress); } // XML documentation if (DocFile != null) { if (SupportsDocGeneration) { WriteOption(writer, "doc", DocFile.FullName); } else { Log(Level.Warning, ResourceUtils.GetString("String_CompilerDoesNotSupportXmlDoc"), Project.TargetFramework.Description); } } if (NoStdLib) { if (SupportsNoStdLib) { WriteOption(writer, "nostdlib"); } else { Log(Level.Warning, ResourceUtils.GetString("String_CompilerDoesNotSupportNoStdLib"), Project.TargetFramework.Description); } } // platform if (Platform != null) { if (SupportsPlatform) { WriteOption(writer, "platform", Platform); } else { Log(Level.Warning, ResourceUtils.GetString("String_CompilerDoesNotSupportPlatform"), Project.TargetFramework.Description); } } // win32res if (Win32Res != null) { WriteOption (writer, "win32resource", Win32Res.FullName); } // handle debug builds. switch (DebugOutput) { case DebugOutput.None: break; case DebugOutput.Enable: WriteOption(writer, "debug"); WriteOption(writer, "define", "DEBUG=True"); WriteOption(writer, "define", "TRACE=True"); break; case DebugOutput.Full: WriteOption(writer, "debug"); break; case DebugOutput.PdbOnly: WriteOption(writer, "debug", "pdbonly"); break; default: throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2011"), DebugOutput), Location); } string imports = Imports.ToString(); if (!String.IsNullOrEmpty(imports)) { WriteOption(writer, "imports", imports); } if (OptionCompare != null && OptionCompare.ToUpper(CultureInfo.InvariantCulture) != "FALSE") { WriteOption(writer, "optioncompare", OptionCompare); } if (OptionExplicit) { WriteOption(writer, "optionexplicit"); } if (OptionStrict) { WriteOption(writer, "optionstrict"); } if (RemoveIntChecks) { WriteOption(writer, "removeintchecks"); } if (OptionOptimize) { WriteOption(writer, "optimize"); } if (RootNamespace != null) { WriteOption(writer, "rootnamespace", RootNamespace); } if (Project.TargetFramework.Family == "netcf") { WriteOption(writer, "netcf"); WriteOption(writer, "sdkpath", Project.TargetFramework. FrameworkAssemblyDirectory.FullName); } } /// /// Determines whether compilation is needed. /// protected override bool NeedsCompiling() { if (base.NeedsCompiling()) { return true; } if (DocFile != null && SupportsDocGeneration) { if (!DocFile.Exists) { Log(Level.Verbose, ResourceUtils.GetString("String_DocFileDoesNotExist"), DocFile.FullName); return true; } } return base.NeedsCompiling(); } /// /// Gets the file extension required by the current compiler. /// /// /// For the VB.NET compiler, the file extension is always vb. /// public override string Extension { get { return "vb"; } } /// /// Gets the class name regular expression for the language of the /// current compiler. /// /// /// Class name regular expression for the language of the current /// compiler. /// protected override Regex ClassNameRegex { get { return _classNameRegex; } } /// /// Gets the namespace regular expression for the language of the /// current compiler. /// /// /// Namespace regular expression for the language of the current /// compiler. /// protected override Regex NamespaceRegex { get { return _namespaceRegex; } } #endregion Override implementation of CompilerBase } } nant-0.92-rc1/src/NAnt.DotNet/Tasks/LicenseTask.cs0000644000175000017500000007222311757302273021502 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Matthew Mastracci (mmastrac@canada.com) // Sascha Andres (sa@programmers-world.com) // Gert Driesen (drieseng@users.sourceforge.net) // Giuseppe Greco (giuseppe.greco@agamura.com) using System; using System.Collections; using System.Collections.Specialized; using System.ComponentModel; using System.ComponentModel.Design; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.Remoting.Lifetime; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Xml; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Tasks; using NAnt.Core.Types; using NAnt.Core.Util; using NAnt.DotNet.Types; namespace NAnt.DotNet.Tasks { /// /// Generates a .licence file from a .licx file. /// /// /// /// If no output file is specified, the default filename is the name of the /// target file with the extension .licenses appended. /// /// /// /// /// Generate the file component.exe.licenses file from component.licx. /// /// /// /// ]]> /// /// [Serializable()] [TaskName("license")] [ProgramLocation(LocationType.FrameworkSdkDir)] public class LicenseTask : ExternalProgramBase { #region Private Instance Fields private AssemblyFileSet _assemblies = new AssemblyFileSet(); private FileInfo _inputFile; private FileInfo _outputFile; private string _target; private string _programFileName; private DirectoryInfo _workingDirectory; // framework configuration settings private bool _supportsAssemblyReferences; private bool _hasCommandLineCompiler = true; #endregion Private Instance Fields #region Public Instance Properties /// /// Input file to process. /// [TaskAttribute("input", Required=true)] public FileInfo InputFile { get { return _inputFile; } set { _inputFile = value; } } /// /// Name of the license file to output. /// [TaskAttribute("output", Required=false)] public FileInfo OutputFile { get { return _outputFile; } set { _outputFile = value; } } /// /// Names of the references to scan for the licensed component. /// [BuildElement("assemblies")] public AssemblyFileSet Assemblies { get { return _assemblies; } set { _assemblies = value; } } /// /// Specifies the executable for which the .licenses file is generated. /// [TaskAttribute("licensetarget", Required=false)] [StringValidator(AllowEmpty=false)] [Obsolete("Use the \"target\" attribute instead.", false)] public string LicenseTarget { get { return Target; } set { Target = value; } } // TODO: we need to mark "target" as required after the release of // NAnt 0.85 // // We can't do this right now, as it would be a major breaking change // (build authors still use "licensetarget" right now). /// /// Specifies the executable for which the .licenses file is generated. /// [TaskAttribute("target", Required=false)] [StringValidator(AllowEmpty=false)] public string Target { get { return _target; } set { _target = StringUtils.ConvertEmptyToNull(value); } } /// /// Indicates whether assembly references are supported by the current /// target framework. The default is . /// /// /// Applies only to frameworks having a command line tool for compiling /// licenses files. /// [FrameworkConfigurable("supportsassemblyreferences")] public bool SupportsAssemblyReferences { get { return _supportsAssemblyReferences; } set { _supportsAssemblyReferences = value; } } /// /// Indicates whether the current target framework has a command line /// tool for compiling licenses files. The default is /// . /// [FrameworkConfigurable("hascommandlinecompiler")] public bool HasCommandLineCompiler { get { return _hasCommandLineCompiler; } set { _hasCommandLineCompiler = value; } } #endregion Public Instance Properties #region Override implementation of Task /// /// Initializes the class. /// protected override void Initialize() { // check if target was specified // TODO: remove this check after NAnt 0.85 as this should be handled // by setting Required to "true" if (Target == null) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2013"), Name), Location); } // check if input file exists if (!InputFile.Exists) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2014"), InputFile.FullName), Location); } } #endregion Override implementation of Task #region Override implementation of ExternalProgramBase /// /// Gets the working directory for the application. /// /// /// The working directory for the application. /// public override DirectoryInfo BaseDirectory { get { if (_workingDirectory == null) { return base.BaseDirectory; } return _workingDirectory; } set { _workingDirectory = value; } } /// /// The command-line arguments for the external program. /// /// /// Override to avoid exposing these elements in build file. /// public override ArgumentCollection Arguments { get { return base.Arguments; } } /// /// Gets the command-line arguments for the external program. /// /// /// The command-line arguments for the external program. /// public override string ProgramArguments { get { return string.Empty; } } /// /// Gets the filename of the external program to start. /// /// /// The filename of the external program. /// /// /// Override in derived classes to explicitly set the location of the /// external tool. /// public override string ProgramFileName { get { if (_programFileName == null) { _programFileName = base.ProgramFileName; } return _programFileName; } } /// /// Updates the of the specified /// . /// /// The of which the should be updated. protected override void PrepareProcess(Process process) { if (!SupportsAssemblyReferences) { // create instance of Copy task CopyTask ct = new CopyTask(); // inherit project from current task ct.Project = Project; // inherit namespace manager from current task ct.NamespaceManager = NamespaceManager; // parent is current task ct.Parent = this; // inherit verbose setting from license task ct.Verbose = Verbose; // only output warning messages or higher, unless we're running // in verbose mode if (!ct.Verbose) { ct.Threshold = Level.Warning; } // make sure framework specific information is set ct.InitializeTaskConfiguration(); // set parent of child elements ct.CopyFileSet.Parent = ct; // inherit project from solution task for child elements ct.CopyFileSet.Project = ct.Project; // inherit namespace manager from solution task ct.CopyFileSet.NamespaceManager = ct.NamespaceManager; // set base directory of fileset ct.CopyFileSet.BaseDirectory = Assemblies.BaseDirectory; // copy all files to base directory itself ct.Flatten = true; // copy referenced assemblies foreach (string file in Assemblies.FileNames) { ct.CopyFileSet.Includes.Add(file); } // copy command line tool to working directory ct.CopyFileSet.Includes.Add(base.ProgramFileName); // set destination directory ct.ToDirectory = BaseDirectory; // increment indentation level ct.Project.Indent(); try { // execute task ct.Execute(); } finally { // restore indentation level ct.Project.Unindent(); } // change program to execute the tool in working directory as // that will allow this tool to resolve assembly references // using assemblies stored in the same directory _programFileName = Path.Combine(BaseDirectory.FullName, Path.GetFileName(base.ProgramFileName)); // determine target directory string targetDir = Path.GetDirectoryName(Path.Combine( BaseDirectory.FullName, Target)); // ensure target directory exists if (!String.IsNullOrEmpty(targetDir) && !Directory.Exists(targetDir)) { Directory.CreateDirectory(targetDir); } } else { foreach (string assembly in Assemblies.FileNames) { Arguments.Add(new Argument(string.Format(CultureInfo.InvariantCulture, "/i:\"{0}\"", assembly))); } } // further delegate preparation to base class base.PrepareProcess(process); } /// /// Generates the license file. /// protected override void ExecuteTask() { FileInfo licensesFile = null; // ensure base directory is set, even if fileset was not initialized // from XML if (Assemblies.BaseDirectory == null) { Assemblies.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } // get the output .licenses file if (OutputFile == null) { try { licensesFile = new FileInfo(Project.GetFullPath(Target + ".licenses")); } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2015"), Target), Location, ex); } } else { licensesFile = OutputFile; } // make sure the directory for the .licenses file exists if (!licensesFile.Directory.Exists) { licensesFile.Directory.Create(); } // determine whether .licenses file need to be recompiled if (!NeedsCompiling(licensesFile)) { return; } Log(Level.Verbose, ResourceUtils.GetString("String_CompilingLicenseUsingTarget"), InputFile.FullName, licensesFile.FullName, Target); if (HasCommandLineCompiler) { // the command line compiler does not allow us to specify the // full path to the output file, so we have it create the licenses // file in a temp directory, and copy it to its actual output // location // use a newly created temporary directory as working directory BaseDirectory = FileUtils.GetTempDirectory(); try { // set target assembly for generated licenses file Arguments.Add(new Argument(string.Format(CultureInfo.InvariantCulture, "/target:\"{0}\"", Target))); // set input filename Arguments.Add(new Argument(string.Format(CultureInfo.InvariantCulture, "/complist:\"{0}\"", InputFile.FullName))); // set output directory Arguments.Add(new Argument(string.Format(CultureInfo.InvariantCulture, "/outdir:\"{0}\"", BaseDirectory.FullName))); // suppress display of startup banner Arguments.Add(new Argument("/nologo")); // adjust verbosity of tool if necessary if (Verbose) { Arguments.Add(new Argument("/v")); } // use command line tool to compile licenses file base.ExecuteTask(); // delete any existing output file if (File.Exists(licensesFile.FullName)) { File.Delete(licensesFile.FullName); } // copy licenses file to output file (with overwrite) File.Copy(Path.Combine(BaseDirectory.FullName, Target + ".licenses"), licensesFile.FullName, true); } finally { // delete temporary directory and all files in it DeleteTask deleteTask = new DeleteTask(); deleteTask.Project = Project; deleteTask.Parent = this; deleteTask.InitializeTaskConfiguration(); deleteTask.Directory = BaseDirectory; deleteTask.Threshold = Level.None; // no output in build log deleteTask.Execute(); } } else { // create new domain #if (NET_4_0) AppDomain newDomain = AppDomain.CreateDomain("LicenseGatheringDomain"); LicenseGatherer licenseGatherer = (LicenseGatherer) newDomain.CreateInstanceAndUnwrap(typeof(LicenseGatherer).Assembly.FullName, typeof(LicenseGatherer).FullName, false, BindingFlags.Public | BindingFlags.Instance, null, new object[0], CultureInfo.InvariantCulture, new object[0]); #else AppDomain newDomain = AppDomain.CreateDomain("LicenseGatheringDomain", AppDomain.CurrentDomain.Evidence); LicenseGatherer licenseGatherer = (LicenseGatherer) newDomain.CreateInstanceAndUnwrap(typeof(LicenseGatherer).Assembly.FullName, typeof(LicenseGatherer).FullName, false, BindingFlags.Public | BindingFlags.Instance, null, new object[0], CultureInfo.InvariantCulture, new object[0], AppDomain.CurrentDomain.Evidence); #endif licenseGatherer.CreateLicenseFile(this, licensesFile.FullName); // unload newly created domain AppDomain.Unload(newDomain); } } #endregion Override implementation of ExternalProgramBase #region Private Instance Methods /// /// Determines whether the .licenses file needs to be recompiled /// or is uptodate. /// /// The .licenses file. /// /// if the .licenses file needs compiling; /// otherwise, . /// private bool NeedsCompiling(FileInfo licensesFile) { if (!licensesFile.Exists) { Log(Level.Verbose, ResourceUtils.GetString("String_OutputFileDoesNotExist"), licensesFile.FullName); return true; } // check if assembly references were updated string fileName = FileSet.FindMoreRecentLastWriteTime(Assemblies.FileNames, licensesFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, ResourceUtils.GetString("String_FileHasBeenUpdated"), fileName); return true; } // check if input file was updated if (InputFile != null) { fileName = FileSet.FindMoreRecentLastWriteTime(InputFile.FullName, licensesFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, ResourceUtils.GetString("String_FileHasBeenUpdated"), fileName); return true; } } // if we made it here then we don't have to recompile return false; } #endregion Private Instance Methods /// /// Responsible for reading the license and writing them to a license /// file. /// private class LicenseGatherer : MarshalByRefObject { #region Override implementation of MarshalByRefObject /// /// Obtains a lifetime service object to control the lifetime policy for /// this instance. /// /// /// An object of type used to control the lifetime /// policy for this instance. This is the current lifetime service object /// for this instance if one exists; otherwise, a new lifetime service /// object initialized with a lease that will never time out. /// public override Object InitializeLifetimeService() { ILease lease = (ILease) base.InitializeLifetimeService(); if (lease.CurrentState == LeaseState.Initial) { lease.InitialLeaseTime = TimeSpan.Zero; } return lease; } #endregion Override implementation of MarshalByRefObject #region Public Instance Methods /// /// Creates the whole license file. /// /// The instance for which the license file should be created. /// The .licenses file to create. public void CreateLicenseFile(LicenseTask licenseTask, string licensesFile) { ArrayList assemblies = new ArrayList(); // create assembly resolver AssemblyResolver assemblyResolver = new AssemblyResolver(licenseTask); // attach assembly resolver to the current domain assemblyResolver.Attach(); licenseTask.Log(Level.Verbose, ResourceUtils.GetString("String_LoadingAssemblies")); try { // first, load all the assemblies so that we can search for the // licensed component foreach (string assemblyFileName in licenseTask.Assemblies.FileNames) { Assembly assembly = Assembly.LoadFrom(assemblyFileName); if (assembly != null) { // output assembly filename to build log licenseTask.Log(Level.Verbose, ResourceUtils.GetString("String_AssemblyLoaded"), assemblyFileName); // add assembly to list of loaded assemblies assemblies.Add(assembly); } } DesigntimeLicenseContext dlc = new DesigntimeLicenseContext(); LicenseManager.CurrentContext = dlc; // read the input file using (StreamReader sr = new StreamReader(licenseTask.InputFile.FullName)) { Hashtable licenseTypes = new Hashtable(); licenseTask.Log(Level.Verbose, ResourceUtils.GetString("String_CreatingLicenses")); while (true) { string line = sr.ReadLine(); if (line == null) { break; } line = line.Trim(); // Skip comments, empty lines and already processed assemblies if (line.StartsWith("#") || line.Length == 0 || licenseTypes.Contains(line)) { continue; } licenseTask.Log(Level.Verbose, line + ": "); // Strip off the assembly name, if it exists string typeName; if (line.IndexOf(',') != -1) { typeName = line.Split(',')[0]; } else { typeName = line; } Type tp = null; // try to locate the type in each assembly foreach (Assembly assembly in assemblies) { if (tp == null) { tp = assembly.GetType(typeName, false, true); } if (tp != null) { break; } } if (tp == null) { try { // final attempt, assuming line contains // assembly qualfied name tp = Type.GetType(line, false, false); } catch { // ignore error, we'll report the load // failure later } } if (tp == null) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2016"), typeName), licenseTask.Location); } else { // add license type to list of processed license types licenseTypes[line] = tp; } // ensure that we've got a licensed component if (tp.GetCustomAttributes(typeof(LicenseProviderAttribute), true).Length == 0) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2017"), tp.FullName), licenseTask.Location); } try { LicenseManager.CreateWithContext(tp, dlc); } catch (Exception ex) { if (IsSerializable(ex)) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2018"), tp.FullName), licenseTask.Location, ex); } // do not directly pass the exception as inner // exception to BuildException as the exception // is not serializable, so construct a new // exception with message set to message of // original exception throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2018"), tp.FullName), licenseTask.Location, new Exception(ex.Message)); } } } // overwrite the existing file, if it exists - is there a better way? if (File.Exists(licensesFile)) { File.SetAttributes(licensesFile, FileAttributes.Normal); File.Delete(licensesFile); } // write out the license file, keyed to the appropriate output // target filename // this .license file will only be valid for this exe/dll using (FileStream fs = new FileStream(licensesFile, FileMode.Create)) { DesigntimeLicenseContextSerializer.Serialize(fs, licenseTask.Target, dlc); licenseTask.Log(Level.Verbose, ResourceUtils.GetString("String_CreatedNewLicense"), licensesFile); } dlc = null; } catch (BuildException) { // re-throw exception throw; } catch (Exception ex) { if (IsSerializable(ex)) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2019"), licenseTask.InputFile.FullName), licenseTask.Location, ex); } else { // do not directly pass the exception as inner exception to // BuildException as the exception might not be serializable, // so construct a // new exception with message set to message of // original exception throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2019"), licenseTask.InputFile.FullName), licenseTask.Location, new Exception(ex.Message)); } } finally { // detach assembly resolver from the current domain assemblyResolver.Detach(); } } #endregion Public Instance Methods #region Private Instance Methods /// /// Determines whether the given object is serializable in binary /// format. /// /// The object to check. /// /// if is /// serializable in binary format; otherwise, . /// private bool IsSerializable(object value) { BinaryFormatter formatter = new BinaryFormatter(); MemoryStream stream = new MemoryStream(); try { formatter.Serialize(stream, value); return true; } catch (SerializationException) { return false; } finally { stream.Close(); } } #endregion Private Instance Methods } } } nant-0.92-rc1/src/NAnt.DotNet/Tasks/RegSvcsTask.cs0000644000175000017500000002615611757302273021500 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Arjen Poutsma (poutsma@yahoo.com) // Giuseppe Greco (giuseppe.greco@agamura.com) using System; using System.Globalization; using System.IO; using System.Text; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Tasks; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.DotNet.Tasks { /// /// Installs or removes .NET Services. /// /// /// /// This tasks provides the same functionality as the regsvcs tool /// provided in the .NET SDK. /// /// /// It performs the following actions: /// /// /// /// Loads and registers an assembly. /// /// /// Generates, registers, and installs a type library into a specified COM+ application. /// /// /// Configures services that are added programmatically to your class. /// /// /// /// Refer to the .NET Services Installation Tool (Regsvcs.exe) for more information. /// /// /// /// /// Adds all public classes contained in myTest.dll to a COM+ /// application and produces the myTest.tlb type library. If the /// application already exists, it is overwritten. /// /// /// /// ]]> /// /// /// /// /// Adds all public classes contained in myTest.dll to myTargetApp /// and produces the myTest.tlb type library. If the application already /// exists, it is overwritten. /// /// /// /// ]]> /// /// /// /// /// Adds all public classes contained in myTest.dll to a COM+ /// application and produces the myTest.tlb type library. A new /// application is always created. /// /// /// /// ]]> /// /// /// /// /// Uninstalls the COM+ application contained in myTest.dll. /// /// /// /// ]]> /// /// [TaskName("regsvcs")] [ProgramLocation(LocationType.FrameworkDir)] public class RegsvcsTask : ExternalProgramBase { /// /// Defines the possible actions for a .NET Service. /// public enum ActionType { /// /// Finds or creates the target application. /// FindOrCreate, /// /// Creates the target application. /// Create, /// /// Uninstalls the target application. /// Uninstall } #region Private Instance Fields private StringBuilder _argumentBuilder = null; private ActionType _action = ActionType.FindOrCreate; private FileInfo _assemblyFile; private string _applicationName; private FileInfo _typeLibrary; private bool _existingTlb = false; private bool _existingApplication = false; private bool _noreconfig = false; private bool _componentsOnly = false; private string _partitionName = null; #endregion Private Instance Fields #region Public Instance Properties /// /// Defines the action to take with the assembly. The default is /// . /// [TaskAttribute("action")] public ActionType Action { get { return _action; } set { if (!Enum.IsDefined(typeof(ActionType), value)) { throw new ArgumentException(string.Format( CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2002"), value)); } else { this._action = value; } } } /// /// The source assembly file. /// /// /// The assembly must be signed with a strong name. /// [TaskAttribute("assembly", Required=true)] [StringValidator(AllowEmpty=false)] public FileInfo AssemblyFile { get { return _assemblyFile; } set { _assemblyFile = value; } } /// /// Specifies the type library file to install. /// [TaskAttribute("tlb")] public FileInfo TypeLibrary { get { return _typeLibrary; } set { _typeLibrary = value; } } /// /// Uses an existing type library. The default is . /// [TaskAttribute("existingtlb")] [BooleanValidator()] public bool ExistingTypeLibrary { get { return _existingTlb; } set { _existingTlb = value; } } /// /// Do not reconfigure an existing target application. /// The default is . /// [TaskAttribute("noreconfig")] [BooleanValidator()] public bool NoReconfig { get { return _noreconfig; } set {_noreconfig = value; } } /// /// Configures components only; ignores methods and interfaces. /// The default is . /// [TaskAttribute("componentsonly")] [BooleanValidator()] public bool ComponentsOnly { get { return _componentsOnly; } set { _componentsOnly = value; } } /// /// Expect an existing application. The default is . /// [TaskAttribute("existingapp")] [BooleanValidator()] public bool ExistingApplication { get { return _existingApplication; } set { _existingApplication = value; } } /// /// Specifies the name of the COM+ application to either find or create. /// [TaskAttribute("application")] public string ApplicationName { get { return _applicationName; } set { _applicationName = StringUtils.ConvertEmptyToNull(value); } } /// /// Specifies the name or id of the COM+ application to either find or /// create. /// [TaskAttribute("partition")] public string PartitionName { get { return _partitionName; } set { _partitionName = StringUtils.ConvertEmptyToNull(value); } } #endregion Public Instance Properties #region Override implementation of ExternalProgramBase /// /// Gets the command-line arguments for the external program. /// /// /// The command-line arguments for the external program. /// public override string ProgramArguments { get { if (_argumentBuilder != null) { return _argumentBuilder.ToString(); } else { return null; } } } /// /// Performs the specified action. /// protected override void ExecuteTask() { _argumentBuilder = new StringBuilder(); switch (Action) { case ActionType.Create: _argumentBuilder.Append("/c "); Log(Level.Info, ResourceUtils.GetString("String_CreatingCOM+Application"), AssemblyFile.FullName); break; case ActionType.FindOrCreate: _argumentBuilder.Append("/fc "); Log(Level.Info, ResourceUtils.GetString("String_FindingCOM+Application"), AssemblyFile.FullName); break; case ActionType.Uninstall: _argumentBuilder.Append("/u "); Log(Level.Info, ResourceUtils.GetString("String_UninstallingCOM+Application"), AssemblyFile.FullName); break; } if (TypeLibrary != null) { _argumentBuilder.AppendFormat("/tlb:\"{0}\" ", TypeLibrary.FullName); } if (ExistingTypeLibrary) { _argumentBuilder.Append("/extlb "); } if (NoReconfig) { _argumentBuilder.Append("/noreconfig "); } if (ComponentsOnly) { _argumentBuilder.Append("/componly "); } if (ApplicationName != null) { _argumentBuilder.AppendFormat("/appname:\"{0}\" ", ApplicationName); } if (ExistingApplication) { _argumentBuilder.Append("/exapp "); } if (PartitionName != null) { _argumentBuilder.AppendFormat("/parname:\"{0}\" ", PartitionName); } if (!Verbose) { _argumentBuilder.Append("/quiet "); } // suppresses display of the sign-on banner _argumentBuilder.Append("/nologo "); // output the assembly name enclosed with quotes _argumentBuilder.Append("\"" + AssemblyFile.FullName + "\""); // call base class to do perform the actual call base.ExecuteTask(); } #endregion Override implementation of ExternalProgramBase } } nant-0.92-rc1/src/NAnt.DotNet/Tasks/DelaySignTask.cs0000644000175000017500000001273011757302273021774 0ustar jtaylorjtaylor// NAntContrib // Copyright (C) 2003 David Waite // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU Library General Public License as // published by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Library General Public License for more details. // // You should have received a copy of the GNU Library General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Giuseppe Greco (giuseppe.greco@agamura.com) using System.Globalization; using System.IO; using System.Text; using NAnt.Core; using NAnt.Core.Tasks; using NAnt.Core.Attributes; using NAnt.Core.Types; using NAnt.Core.Util; using NAnt.DotNet.Tasks; namespace NAnt.DotNet.Tasks { /// /// Signs delay-signed .NET Assemblies, or re-signs existing assemblies. /// /// /// /// The delay-signing mechanism takes a fileset (named targets) /// and either a attribute for a file containing the /// public and private keys, or to name a key /// container. /// /// /// /// Sign partially-signed foo.dll with bar.snk. /// /// /// /// /// /// /// ]]> /// /// [TaskName("delay-sign")] [ProgramLocation(LocationType.FrameworkSdkDir)] public class DelaySignTask : ExternalProgramBase { #region Private Instance Fields private FileSet _targets = new FileSet(); private FileInfo _keyFile; private string _keyContainer; private StringBuilder _argumentBuilder; #endregion Private Instance Fields #region Public Instance Properties /// /// List of assemblies/executables to sign. /// [BuildElement("targets")] public FileSet Targets { get { return _targets; } set { _targets = value; } } /// /// Specifies the filesystem path to the signing key. /// [TaskAttribute("keyfile")] public FileInfo KeyFile { get { return _keyFile; } set { _keyFile = value; } } /// /// Specifies the key container. /// [TaskAttribute("keycontainer")] public string KeyContainer { get { return _keyContainer; } set { _keyContainer = StringUtils.ConvertEmptyToNull(value); } } #endregion Public Instance Properties #region Override implementation of ExternalProgramBase /// /// Gets the command line arguments for the external program. /// /// /// The command line arguments for the external program. /// public override string ProgramArguments { get { if (_argumentBuilder != null) { return _argumentBuilder.ToString(); } else { return null; } } } /// /// Converts a single file or group of files. /// protected override void ExecuteTask() { bool keyAvail = KeyFile != null; bool containerAvail = KeyContainer != null; string keyname = containerAvail ? KeyContainer : KeyFile.FullName; // ensure base directory is set, even if fileset was not initialized // from XML if (Targets.BaseDirectory == null) { Targets.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } if ((keyAvail && containerAvail) || (! keyAvail && ! containerAvail)) { throw new BuildException(ResourceUtils.GetString("NA2012"), Location); } Log(Level.Info, ResourceUtils.GetString("String_DelaySigningAssemblies"), Targets.FileNames.Count); foreach (string filename in Targets.FileNames) { // Try to guess the buffer length // Add 12 for "-R", maybe 'c' and "-q", and spaces/quotes. _argumentBuilder = new StringBuilder(9 + filename.Length + keyname.Length); if (!Verbose) { _argumentBuilder.Append("-q "); } // indicate that we want to resign a previously signed or delay-signed assembly _argumentBuilder.Append("-R"); if (containerAvail) { _argumentBuilder.Append('c'); } _argumentBuilder.Append(" \"").Append(filename).Append("\" \""); _argumentBuilder.Append(keyname).Append('\"'); // call base class to do perform the actual call base.ExecuteTask(); } } #endregion Override implementation of ExternalProgramBase } } nant-0.92-rc1/src/NAnt.DotNet/Tasks/IlasmTask.cs0000644000175000017500000004641211757302273021166 0ustar jtaylorjtaylor// IlasmTask.cs // // Giuseppe Greco // Copyright (C) 2004 Agamura, Inc. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Giuseppe Greco (giuseppe.greco@agamura.com) using System.IO; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Tasks; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.DotNet.Tasks { /// /// Compiles ILASM programs. /// /// /// /// Compiles helloworld.il to helloworld.exe. /// /// /// /// /// /// /// /// ]]> /// /// [TaskName("ilasm")] [ProgramLocation(LocationType.FrameworkDir)] public class IlasmTask : ExternalProgramBase { #region Private Instance Fields private bool _clock; private bool _debug; private bool _error; private bool _forceRebuild; private bool _listing; private int _alignment; private int _base; private int _flags; private int _subsystem; private string _target; private string _keySource; private FileInfo _keyFile; private FileInfo _outputFile; private FileInfo _resourceFile; private FileSet _sources; private string _options; #endregion Private Instance Fields #region Public Instance Properties /// /// Specifies whether or not the compiler should measure and report /// the compilation times. /// /// /// if the compilation times should be /// measured and reported; otherwise, . The /// default is . /// /// /// /// Corresponds to the /CLOCK flag. /// /// [TaskAttribute("clock")] [BooleanValidator()] public bool Clock { get { return _clock; } set { _clock = value; } } /// /// Specifies whether or not the compiler should generate debug /// information. /// /// /// if debug information should be generated; /// otherwise, . The default is /// . /// /// /// /// Corresponds to the /DEBUG flag. /// /// [TaskAttribute("debug")] [BooleanValidator()] public bool Debug { get { return _debug; } set { _debug = value; } } /// /// Specifies whether or not the compiler should attempt to create a /// PE file even if compilation errors have been reported. /// /// /// if a PE file has to be created even if /// compilation errors have been reported; otherwise, /// . The default is . /// /// /// /// Corresponds to the /ERROR flag. /// /// [TaskAttribute("error")] [BooleanValidator()] public bool Error { get { return _error; } set { _error = value; } } /// /// Instructs NAnt to recompile the output file regardless of the file /// timestamps. /// /// /// if the output file should be recompiled /// regardless of its timestamps; otherwise . /// The default is . /// [TaskAttribute("rebuild")] [BooleanValidator()] public bool ForceRebuild { get { return _forceRebuild; } set { _forceRebuild = value; } } /// /// Specifies whether or not the compiler should type a formatted /// listing of the compilation result. /// /// /// if a formatted listing of the compilation /// result should be typed; otherwise, . The /// default is . /// /// /// /// Corresponds to the /LISTING flag. /// /// [TaskAttribute("listing")] [BooleanValidator()] public bool Listing { get { return _listing; } set { _listing = value; } } /// /// Instructs the compiler to set the FileAlignment value in /// the PE header. /// /// /// An that represents the FileAlignment /// value to set in the PE header. The value must be a power of 2, in /// range from 512 to 65536. /// /// /// /// Corresponds to the /ALIGNMENT flag. /// /// [TaskAttribute("alignment")] [Int32Validator()] public int Alignment { get { return _alignment; } set { _alignment = value; } } /// /// Instructs the compiler to set the ImageBase value in /// the PE header. /// /// /// A that represents the ImageBase /// value to set in the PE header. /// /// /// /// Corresponds to the /BASE flag. /// /// [TaskAttribute("base")] [Int32Validator()] public int Base { get { return _base; } set { _base = value; } } /// /// Instructs the compiler to set the Flags value in the CLR /// header. /// /// /// An that represents the Flags /// value to set in the CLR header. The most frequently value are 1 /// (pre-IL code) and 2 (mixed code). The third bit indicating that /// the PE file is strong signed, is ignored. /// /// /// /// Corresponds to the /FLAGS flag. /// /// [TaskAttribute("flags")] [Int32Validator()] public int Flags { get { return _flags; } set { _flags = value; } } /// /// Instructs the compiler to set the Subsystem value in the PE /// header. /// /// /// An that represents the Subsystem /// value to set in the PE header. The most frequently value are 3 /// (console application) and 2 (GUI application). /// /// /// /// Corresponds to the /SUBSYSTEM flag. /// /// [TaskAttribute("subsystem")] [Int32Validator()] public int Subsystem { get { return _subsystem; } set { _subsystem = value; } } /// /// Specifies which output type should be generated. /// /// /// A that contains the target type. /// Possible values are dll and exe. /// /// /// /// Corresponds to the /OUTPUT flag. /// /// [TaskAttribute("target", Required=true)] [StringValidator(AllowEmpty=false)] public string Target { get { return _target; } set { _target = StringUtils.ConvertEmptyToNull(value); } } /// /// Instructs the compiler to generate a strong signature of the PE /// file. /// /// /// A that contains the private /// encryption key. /// /// /// /// Corresponds to the /KEY=keysource]]> /// flag. /// /// [TaskAttribute("keysource")] public string KeySource { get { return _keySource; } set { _keySource = value; } } /// /// Instructs the compiler to generate a strong signature of the PE /// file. /// /// /// A that represents the file /// containing the private encryption key. /// /// /// /// Corresponds to the /KEY=keyfile]]> /// flag. /// /// [TaskAttribute("keyfile")] public FileInfo KeyFile { get { return _keyFile; } set { _keyFile = value; } } /// /// Specifies the name of the output file created by the compiler. /// /// /// A that represents the name of /// the output file. /// /// /// /// Corresponds to the /OUTPUT flag. /// /// [TaskAttribute("output", Required=true)] public FileInfo OutputFile { get { return _outputFile; } set { _outputFile = value; } } /// /// Instructs the compiler to link the specified unmanaged resource /// file into the resulting PE file. /// /// /// A that represents the unmanaged /// resource file to link. /// /// /// /// Corresponds to the /RESOURCE flag. /// /// [TaskAttribute("resourcefile")] public FileInfo ResourceFile { get { return _resourceFile; } set { _resourceFile = value; } } /// /// Specifies the set of source files to compile. /// /// /// A that represents the set /// of source files to compile. /// [BuildElement("sources", Required=true)] public FileSet Sources { get { return _sources; } set { _sources = value; } } #endregion Public Instance Properties #region Override implementation of ExternalProgramBase /// /// Gets the command-line arguments for the external program. /// /// /// A that contains the command-line /// arguments for the external program. /// public override string ProgramArguments { get { return _options; } } /// /// Compiles the sources. /// protected override void ExecuteTask() { if (NeedsCompiling()) { // // ensure base directory is set, even if fileset has not been // initialized in build file // if (Sources.BaseDirectory == null) { Sources.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } Log(Level.Info, ResourceUtils.GetString("String_CompilingFiles"), Sources.FileNames.Count, OutputFile.FullName); // // set command-line arguments for the ILASM compiler // WriteOptions(); // // call base class to do the work // base.ExecuteTask(); } } #endregion Override implementation of ExternalProgramBase #region Private Instance Methods /// /// Writes the compiler options. /// private void WriteOptions() { StringWriter writer = new StringWriter(); try { // // always suppress logo and copyright statements // WriteOption(writer, "NOLOGO"); // // suppress reporting compilation progress // unless Verbose is true // if (!Verbose) { WriteOption(writer, "QUIET"); } if (Clock) { WriteOption(writer, "CLOCK"); } if (Debug) { WriteOption(writer, "DEBUG"); } if (Error) { WriteOption(writer, "ERROR"); } if (Listing) { WriteOption(writer, "LISTING"); } if (Alignment > 0) { WriteOption(writer, "ALIGNMENT", Alignment.ToString()); } if (Base > 0) { WriteOption(writer, "BASE", Base.ToString()); } if (Flags > 0) { WriteOption(writer, "FLAGS", Flags.ToString()); } if (Subsystem > 0) { WriteOption(writer, "SUBSYSTEM", Subsystem.ToString()); } if (Target != null) { WriteOption(writer, Target.ToUpper()); } if (KeySource != null) { WriteOption(writer, "KEY", "@" + KeySource); } if (KeyFile != null) { WriteOption(writer, "KEY", KeyFile.FullName); } if (OutputFile != null) { WriteOption(writer, "OUTPUT", OutputFile.FullName); } if (ResourceFile != null) { WriteOption(writer, "RESOURCE", ResourceFile.FullName); } foreach (string fileName in Sources.FileNames) { writer.Write(" \"" + fileName + "\" "); } _options = writer.ToString(); } finally { // // close the StringWriter and the underlying stream // writer.Close(); } } /// /// Writes an option using the default output format. /// /// /// The to which the compiler options should /// be written. /// /// /// A that contains the name of the /// option which should be passed to the compiler. /// private void WriteOption(StringWriter writer, string name) { writer.Write("/{0} ", name); } /// /// Writes an option and its value using the default output format. /// /// /// The to which the compiler options should /// be written. /// /// /// A that contains the name of the /// option which should be passed to the compiler. /// /// /// A that contains the value of the /// option which should be passed to the compiler. /// private void WriteOption(StringWriter writer, string name, string arg) { // // always quote arguments // writer.Write("\"/{0}={1}\" ", name, arg); } /// /// Determines whether or not compilation is needed. /// /// /// if compilation is needed; otherwise, /// . /// private bool NeedsCompiling() { if (ForceRebuild) { Log(Level.Verbose, ResourceUtils.GetString("String_RebuildAttributeSetToTrue")); return true; } // check if output file exists if (!OutputFile.Exists) { Log(Level.Verbose, ResourceUtils.GetString("String_OutputFileDoesNotExist"), OutputFile.FullName); return true; } // check if sources have been updated string fileName = FileSet.FindMoreRecentLastWriteTime( Sources.FileNames, OutputFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, ResourceUtils.GetString("String_FileHasBeenUpdated"), fileName); return true; } // check if unmanaged resources have been updated if (ResourceFile != null) { fileName = FileSet.FindMoreRecentLastWriteTime( ResourceFile.FullName, OutputFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, ResourceUtils.GetString("String_FileHasBeenUpdated"), fileName); return true; } } // check if strong name signature has been updated if (KeyFile != null) { fileName = FileSet.FindMoreRecentLastWriteTime( KeyFile.FullName, OutputFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, ResourceUtils.GetString("String_FileHasBeenUpdated"), fileName); return true; } } // compilation not needed return false; } #endregion Private Instance Methods } } nant-0.92-rc1/src/NAnt.DotNet/Tasks/CscTask.cs0000644000175000017500000004364211757302273020633 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Mike Krueger (mike@icsharpcode.net) // Gert Driesen (drieseng@users.sourceforge.net) // Ian MacLean (ian_maclean@another.com) // Giuseppe Greco (giuseppe.greco@agamura.com) using System; using System.Globalization; using System.IO; using System.Text.RegularExpressions; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Types; using NAnt.Core.Util; using NAnt.DotNet.Types; namespace NAnt.DotNet.Tasks { /// /// Compiles C# programs. /// /// /// /// In order to have generate manifest resource names /// that match those generated by Microsoft Visual Studio.NET, the value of /// the attribute of the <> /// element should match the "Default Namespace" of the C# project, and the /// value of the attribute /// should be set to "". /// /// /// /// Compile a "HelloWorld" application, including embedded resources. /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// ]]> /// /// [TaskName("csc")] [ProgramLocation(LocationType.FrameworkDir)] public class CscTask : CompilerBase { #region Private Instance Fields private DebugOutput _debugOutput = DebugOutput.None; private FileInfo _docFile; private int _fileAlign; private bool _nostdlib; private bool _noconfig; private bool _checked; private bool _unsafe; private bool _optimize; private string _warningLevel; private string _codepage; private string _baseAddress; private string _platform; private string _langVersion; // framework configuration settings private bool _supportsDocGeneration = true; private bool _supportsPlatform; private bool _supportsLangVersion; #endregion Private Instance Fields #region Private Static Fields private static Regex _classNameRegex = new Regex(@"^((?/\*.*?(\*/|$))|[\s\.\{]+|class\s+(?\w+)|(?\w+))*"); private static Regex _namespaceRegex = new Regex(@"^((?/\*.*?(\*/|$))|[\s\.\{]+|namespace\s+(?(\w+(\.\w+)*)+)|(?\w+))*"); #endregion Private Static Fields #region Public Instance Properties /// /// The preferred base address at which to load a DLL. The default base /// address for a DLL is set by the .NET Framework common language /// runtime. /// /// /// The preferred base address at which to load a DLL. /// /// /// This address can be specified as a decimal, hexadecimal, or octal /// number. /// [TaskAttribute("baseaddress")] public string BaseAddress { get { return _baseAddress; } set { _baseAddress = StringUtils.ConvertEmptyToNull(value); } } /// /// Specifies the type of debugging information generated by the /// compiler. The default is . /// [TaskAttribute("debug")] public DebugOutput DebugOutput { get { return _debugOutput; } set { _debugOutput = value; } } /// /// No longer expose this to build authors. Use /// instead. /// public override bool Debug { get { return DebugOutput != DebugOutput.None; } set { DebugOutput = DebugOutput.Enable; } } /// /// The name of the XML documentation file to generate. /// /// /// /// Corresponds with the /doc: flag. /// /// [TaskAttribute("doc")] public FileInfo DocFile { get { return _docFile; } set { _docFile = value; } } /// /// Specifies the size of sections in the output file. Valid values are /// 512, 1024, 2048, 4096, and 8192. /// /// /// The size of sections in the output file. /// [TaskAttribute("filealign")] [Int32Validator(512, 8192)] public int FileAlign { get { return _fileAlign; } set { _fileAlign = value; } } /// /// Instructs the compiler not to import mscorlib.dll. The default is /// . /// /// /// /// Corresponds with the /nostdlib[+|-] flag. /// /// [FrameworkConfigurable("nostdlib")] [TaskAttribute("nostdlib")] [BooleanValidator()] public bool NoStdLib { get { return _nostdlib; } set { _nostdlib = value; } } /// /// Instructs the compiler not to use implicit references to assemblies. /// The default is . /// /// /// /// Corresponds with the /noconfig flag. /// /// [FrameworkConfigurable("noconfig")] [TaskAttribute("noconfig")] [BooleanValidator()] public bool NoConfig { get { return _noconfig; } set { _noconfig = value; } } /// /// Specifies whether an integer arithmetic statement that is not in /// the scope of the checked or unchecked keywords and /// that results in a value outside the range of the data type should /// cause a run-time exception. The default is . /// /// /// /// Corresponds with the /checked[+|-] flag. /// /// [TaskAttribute("checked")] [BooleanValidator()] public bool Checked { get { return _checked; } set { _checked = value; } } /// /// Instructs the compiler to allow code that uses the unsafe /// keyword. The default is . /// /// /// /// Corresponds with the /unsafe[+|-] flag. /// /// [TaskAttribute("unsafe")] [BooleanValidator()] public bool Unsafe { get { return _unsafe; } set { _unsafe = value; } } /// /// Causes the compiler to only accept syntax that is included in a /// given specification. /// /// /// /// Corresponds with the /langversion flag. /// /// [TaskAttribute("langversion")] public string LangVersion { get { return _langVersion; } set { _langVersion = StringUtils.ConvertEmptyToNull(value); } } /// /// Specifies whether the compiler should perform optimizations to the /// make output files smaller, faster, and more effecient. The default /// is . /// /// /// if the compiler should perform optimizations; /// otherwise, . /// /// /// /// Corresponds with the /optimize[+|-] flag. /// /// [TaskAttribute("optimize")] [BooleanValidator()] public bool Optimize { get { return _optimize; } set { _optimize = value; } } /// /// Specifies which platform version of common language runtime (CLR) /// can run the output file. /// /// /// The platform version of common language runtime (CLR) that can run /// the output file. /// /// /// /// Corresponds with the /platform flag. /// /// [TaskAttribute("platform")] public string Platform { get { return _platform; } set { _platform = StringUtils.ConvertEmptyToNull(value); } } /// /// Specifies the warning level for the compiler to display. Valid values /// are 0-4. The default is 4. /// /// /// The warning level for the compiler to display. /// /// /// /// Corresponds with the /warn flag. /// /// [TaskAttribute("warninglevel")] [Int32Validator(0, 4)] public string WarningLevel { get { return _warningLevel; } set { _warningLevel = StringUtils.ConvertEmptyToNull(value); } } /// /// Specifies the code page to use for all source code files in the /// compilation. /// /// /// /// Corresponds with the /codepage flag. /// /// [TaskAttribute("codepage")] public string Codepage { get { return _codepage; } set { _codepage = StringUtils.ConvertEmptyToNull(value); } } /// /// Specifies whether the compiler for the active target framework /// supports generation of XML Documentation file. The default is /// . /// [FrameworkConfigurable("supportsdocgeneration")] public bool SupportsDocGeneration { get { return _supportsDocGeneration; } set { _supportsDocGeneration = value; } } /// /// Specifies whether the compiler for the active target framework /// supports limiting the platform on which the compiled code can run. /// The default is . /// [FrameworkConfigurable("supportsplatform")] public bool SupportsPlatform { get { return _supportsPlatform; } set { _supportsPlatform = value; } } /// /// Specifies whether the compiler for the active target framework /// supports accepting only a specific language syntax. /// The default is . /// [FrameworkConfigurable("supportslangversion")] public bool SupportsLangVersion { get { return _supportsLangVersion; } set { _supportsLangVersion = value; } } #endregion Public Instance Properties #region Override implementation of CompilerBase /// /// Writes the compiler options to the specified . /// /// to which the compiler options should be written. protected override void WriteOptions(TextWriter writer) { // causes the compiler to specify the full path of the file in which // an error was found WriteOption(writer, "fullpaths"); // the base address for the DLL if (BaseAddress != null) { WriteOption(writer, "baseaddress", BaseAddress); } // XML documentation if (DocFile != null) { if (SupportsDocGeneration) { WriteOption(writer, "doc", DocFile.FullName); } else { Log(Level.Warning, ResourceUtils.GetString("String_CompilerDoesNotSupportXmlDoc"), Project.TargetFramework.Description); } } // langversion if (LangVersion != null) { if (SupportsLangVersion) { WriteOption(writer, "langversion", LangVersion); } else { Log(Level.Warning, ResourceUtils.GetString("String_CompilerDoesNotSupportLangVersion"), Project.TargetFramework.Description); } } // platform if (Platform != null) { if (SupportsPlatform) { WriteOption(writer, "platform", Platform); } else { Log(Level.Warning, ResourceUtils.GetString("String_CompilerDoesNotSupportPlatform"), Project.TargetFramework.Description); } } // win32res if (Win32Res != null) { WriteOption (writer, "win32res", Win32Res.FullName); } // handle debug builds. switch (DebugOutput) { case DebugOutput.None: break; case DebugOutput.Enable: WriteOption(writer, "debug"); WriteOption(writer, "define", "DEBUG"); WriteOption(writer, "define", "TRACE"); break; case DebugOutput.Full: WriteOption(writer, "debug"); break; case DebugOutput.PdbOnly: WriteOption(writer, "debug", "pdbonly"); break; default: throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2011"), DebugOutput), Location); } if (FileAlign > 0) { WriteOption(writer, "filealign", FileAlign.ToString(CultureInfo.InvariantCulture)); } if (NoStdLib) { WriteOption(writer, "nostdlib"); } if (Checked) { WriteOption(writer, "checked"); } if (Unsafe) { WriteOption(writer, "unsafe"); } if (Optimize) { WriteOption(writer, "optimize"); } if (WarningLevel != null) { WriteOption(writer, "warn", WarningLevel); } if (Codepage != null) { WriteOption(writer, "codepage", Codepage); } if (NoConfig && !Arguments.Contains("/noconfig")) { Arguments.Add(new Argument("/noconfig")); } } /// /// Determines whether compilation is needed. /// protected override bool NeedsCompiling() { if (base.NeedsCompiling()) { return true; } if (DocFile != null && SupportsDocGeneration) { if (!DocFile.Exists) { Log(Level.Verbose, ResourceUtils.GetString("String_DocFileDoesNotExist"), DocFile.FullName); return true; } } return false; } /// /// Gets the file extension required by the current compiler. /// /// /// For the C# compiler, the file extension is always cs. /// public override string Extension { get { return "cs"; } } /// /// Gets the class name regular expression for the language of the /// current compiler. /// /// /// Class name regular expression for the language of the current /// compiler. /// protected override Regex ClassNameRegex { get { return _classNameRegex; } } /// /// Gets the namespace regular expression for the language of the current compiler. /// /// /// Namespace regular expression for the language of the current /// compiler. /// protected override Regex NamespaceRegex { get { return _namespaceRegex; } } #endregion Override implementation of CompilerBase } } nant-0.92-rc1/src/NAnt.DotNet/Tasks/AssemblyInfoTask.cs0000644000175000017500000007243511757302273022520 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2002-2003 Gordon Weakliem // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gordon Weakliem (gweakliem@oddpost.com) // Gert Driesen (drieseng@users.sourceforge.net) // Ian MacLean (ian_maclean@another.com) // Giuseppe Greco (giuseppe.greco@agamura.com) using System; using System.CodeDom; using System.CodeDom.Compiler; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.Remoting.Lifetime; using System.Security.Cryptography; using System.Text; using System.Security; using System.Security.Permissions; using System.Security.Policy; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Types; using NAnt.Core.Util; using NAnt.DotNet.Types; namespace NAnt.DotNet.Tasks { /// /// Generates an AssemblyInfo file using the attributes given. /// /// /// /// Create a C# AssemblyInfo file containing the specified assembly-level /// attributes. /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// ]]> /// /// /// /// /// Create a C# AssemblyInfo file containing an attribute with multiple /// named properties by setting the /// attribute on the element to /// . /// /// /// /// /// /// /// /// /// /// /// /// /// /// ]]> /// /// [TaskName("asminfo")] [Serializable()] public class AssemblyInfoTask : Task { #region Private Instance Fields private FileInfo _output; private CodeLanguage _language = CodeLanguage.CSharp; private AssemblyAttributeCollection _attributes = new AssemblyAttributeCollection(); private NamespaceImportCollection _imports = new NamespaceImportCollection(); private AssemblyFileSet _references = new AssemblyFileSet(); #endregion Private Instance Fields #region Public Instance Properties /// /// Name of the AssemblyInfo file to generate. /// /// /// The name of the AssemblyInfo file to generate. /// [TaskAttribute("output", Required=true)] public FileInfo Output { get { return _output; } set { _output = value; } } /// /// The code language in which the AssemblyInfo file should be /// generated. /// [TaskAttribute("language", Required=true)] [StringValidator(AllowEmpty=false)] public CodeLanguage Language { get { return _language; } set { if (!Enum.IsDefined(typeof(CodeLanguage), value)) { throw new ArgumentException(string.Format( CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2002"), value)); } else { _language = value; } } } /// /// The assembly-level attributes to generate. /// /// /// The assembly-level attributes to generate. /// [BuildElementCollection("attributes", "attribute")] public AssemblyAttributeCollection AssemblyAttributes { get { return _attributes; } } /// /// The namespaces to import. /// /// /// The namespaces to import. /// [BuildElement("imports")] public NamespaceImportCollection Imports { get { return _imports; } set { _imports = value; } } /// /// Assembly files used to locate the types of the specified attributes. /// [BuildElement("references")] public AssemblyFileSet References { get { return _references; } set { _references = value; } } #endregion Public Instance Properties #region Override implementation of Task /// /// Generates an AssemblyInfo file. /// protected override void ExecuteTask() { try { StringCollection imports = new StringCollection(); foreach (NamespaceImport import in Imports) { if (import.IfDefined && !import.UnlessDefined) { imports.Add(import.Namespace); } } // ensure base directory is set, even if fileset was not initialized // from XML if (References.BaseDirectory == null) { References.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } // write out code to memory stream, so we can compare it later // to what is already present (if necessary) MemoryStream generatedAsmInfoStream = new MemoryStream(); using (StreamWriter writer = new StreamWriter(generatedAsmInfoStream, Encoding.Default)) { // create new instance of CodeProviderInfo for specified CodeLanguage CodeProvider codeProvider = new CodeProvider(this, Language); // only generate imports here for C#, for VB we create the // imports as part of the assembly attributes compile unit if (Language == CodeLanguage.CSharp) { // generate imports code codeProvider.GenerateImportCode(imports, writer); } // generate code for assembly attributes codeProvider.GenerateAssemblyAttributesCode(AssemblyAttributes, imports, References.FileNames, writer); // flush writer.Flush(); // check whether generated source should be persisted if (NeedsPersisting(generatedAsmInfoStream)) { using (FileStream fs = new FileStream(Output.FullName, FileMode.Create, FileAccess.Write)) { byte[] buffer = generatedAsmInfoStream.ToArray(); fs.Write(buffer, 0, buffer.Length); fs.Flush(); fs.Close(); generatedAsmInfoStream.Close(); } Log(Level.Info, ResourceUtils.GetString("String_GeneratedFile"), Output.FullName); } else { Log(Level.Verbose, ResourceUtils.GetString("String_FileUpToDate"), Output.FullName); } } } catch (Exception ex) { throw new BuildException(string.Format( CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2004"), Output.FullName), Location, ex); } } #endregion Override implementation of Task #region Private Instance Methods /// /// Determines whether the specified AssemblyInfo file in the given /// needs to be persisted. /// /// holding the newly generated AssemblyInfo source. /// /// if the generated AssemblyInfo source needs /// to be persisted; otherwise, . /// private bool NeedsPersisting(Stream generatedAsmInfoStream) { // if output file doesn't exist, the stream will always need to be // persisted to the filesystem. if (!Output.Exists) { Log(Level.Verbose, ResourceUtils.GetString("String_OutputFileDoesNotExist"), Output.FullName); return true; } byte[] existingAssemblyInfoHash = null; byte[] generatedAssemblyInfoHash = null; SHA1 hasher = new SHA1CryptoServiceProvider(); // hash existing AssemblyInfo source using (FileStream fs = new FileStream(Output.FullName, FileMode.Open, FileAccess.Read)) { existingAssemblyInfoHash = hasher.ComputeHash(fs); } // hash generated AssemblyInfo source generatedAsmInfoStream.Position = 0; generatedAssemblyInfoHash = hasher.ComputeHash(generatedAsmInfoStream); // release all resources hasher.Clear(); //compare hash of generated source with of existing source if (Convert.ToBase64String(generatedAssemblyInfoHash) != Convert.ToBase64String(existingAssemblyInfoHash)) { Log(Level.Verbose, ResourceUtils.GetString("String_OutputFileNotUpToDate"), Output.FullName); return true; } else { return false; } } #endregion Private Instance Methods /// /// Defines the supported code languages for generating an AssemblyInfo /// file. /// public enum CodeLanguage : int { /// /// A value for generating C# code. /// CSharp = 0, /// /// A value for generating JScript code. /// JScript = 1, /// /// A value for generating Visual Basic code. /// VB = 2, } /// /// Encapsulates functionality to generate a code file with imports /// and assembly-level attributes. /// internal class CodeProvider { #region Private Instance Fields private readonly CodeLanguage _language; private readonly ICodeGenerator _generator; #endregion Private Instance Fields #region Public Instance Constructors /// /// Initializes a new instance of the /// for the specified . /// /// The for which an instance of the class should be initialized. /// The for which an instance of the class should be initialized. public CodeProvider(AssemblyInfoTask assemblyInfoTask, CodeLanguage codeLanguage) { CodeDomProvider provider = null; switch (codeLanguage) { case CodeLanguage.CSharp: provider = new Microsoft.CSharp.CSharpCodeProvider(); break; case CodeLanguage.JScript: throw new NotSupportedException(ResourceUtils.GetString("NA2008")); case CodeLanguage.VB: provider = new Microsoft.VisualBasic.VBCodeProvider(); break; default: throw new NotSupportedException(ResourceUtils.GetString("NA2007")); } _generator = provider.CreateGenerator(); _language = codeLanguage; } #endregion Public Instance Constructors #region Private Instance Properties /// /// Gets the in which the AssemblyInfo /// code will be generated. /// private CodeLanguage Language { get { return _language; } } /// /// Gets the that will be used to /// generate the AssemblyInfo code. /// private ICodeGenerator Generator { get { return _generator; } } #endregion Private Instance Properties #region Public Instance Methods /// /// Generates code for the specified imports. /// /// The imports for which code should be generated. /// The to which the generated code will be written. public void GenerateImportCode(StringCollection imports, TextWriter writer) { CodeNamespace codeNamespace = new CodeNamespace(); foreach (string import in imports) { codeNamespace.Imports.Add(new CodeNamespaceImport(import)); } Generator.GenerateCodeFromNamespace(codeNamespace, writer, new CodeGeneratorOptions()); } /// /// Generates code for the specified assembly attributes. /// /// The assembly attributes for which code should be generated. /// Imports used to resolve the assembly attribute names to fully qualified type names. /// Assembly that will be used to resolve the attribute names to instances. /// The to which the generated code will be written. public void GenerateAssemblyAttributesCode(AssemblyAttributeCollection assemblyAttributes, StringCollection imports, StringCollection assemblies, TextWriter writer) { CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); // for C# the imports were already generated, as the # generator // will otherwise output the imports after the assembly attributes if (Language == CodeLanguage.VB) { CodeNamespace codeNamespace = new CodeNamespace(); foreach (string import in imports) { codeNamespace.Imports.Add(new CodeNamespaceImport(import)); } codeCompileUnit.Namespaces.Add(codeNamespace); } foreach (AssemblyAttribute assemblyAttribute in assemblyAttributes) { if (assemblyAttribute.IfDefined && !assemblyAttribute.UnlessDefined) { // create new assembly-level attribute CodeAttributeDeclaration codeAttributeDeclaration = new CodeAttributeDeclaration(assemblyAttribute.TypeName); if (assemblyAttribute.AsIs) { codeAttributeDeclaration.Arguments.Add(new CodeAttributeArgument(new CodeSnippetExpression(assemblyAttribute.Value))); } else { // convert string value to type expected by attribute constructor object typedValue = GetTypedValue(assemblyAttribute, assemblies, imports); if (typedValue != null) { // add typed value to attribute arguments codeAttributeDeclaration.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(typedValue))); } } // add assembly-level argument to code compile unit codeCompileUnit.AssemblyCustomAttributes.Add(codeAttributeDeclaration); } } Generator.GenerateCodeFromCompileUnit(codeCompileUnit, writer, new CodeGeneratorOptions()); } #endregion Public Instance Methods #region Private Instance Methods private object GetTypedValue(AssemblyAttribute attribute, StringCollection assemblies, StringCollection imports) { // locate type assuming TypeName is fully qualified typename PermissionSet domainPermSet = new PermissionSet(PermissionState.Unrestricted); AppDomain newDomain = AppDomain.CreateDomain("TypeGatheringDomain", AppDomain.CurrentDomain.Evidence, AppDomain.CurrentDomain.SetupInformation, domainPermSet); #if NET_4_0 TypedValueGatherer typedValueGatherer = (TypedValueGatherer) newDomain.CreateInstanceAndUnwrap(typeof(TypedValueGatherer).Assembly.FullName, typeof(TypedValueGatherer).FullName, false, BindingFlags.Public | BindingFlags.Instance, null, new object[0], CultureInfo.InvariantCulture, new object[0]); #else TypedValueGatherer typedValueGatherer = (TypedValueGatherer) newDomain.CreateInstanceAndUnwrap(typeof(TypedValueGatherer).Assembly.FullName, typeof(TypedValueGatherer).FullName, false, BindingFlags.Public | BindingFlags.Instance, null, new object[0], CultureInfo.InvariantCulture, new object[0], AppDomain.CurrentDomain.Evidence); #endif object typedValue = typedValueGatherer.GetTypedValue( assemblies, imports, attribute.TypeName, attribute.Value); // unload newly created AppDomain AppDomain.Unload(newDomain); return typedValue; } #endregion Private Instance Methods } /// /// Responsible for returning the specified value converted to a /// accepted by a constructor for a given /// . /// private class TypedValueGatherer : MarshalByRefObject { #region Override implementation of MarshalByRefObject /// /// Obtains a lifetime service object to control the lifetime policy for /// this instance. /// /// /// An object of type used to control the lifetime /// policy for this instance. This is the current lifetime service object /// for this instance if one exists; otherwise, a new lifetime service /// object initialized with a lease that will never time out. /// public override Object InitializeLifetimeService() { ILease lease = (ILease) base.InitializeLifetimeService(); if (lease.CurrentState == LeaseState.Initial) { lease.InitialLeaseTime = TimeSpan.Zero; } return lease; } #endregion Override implementation of MarshalByRefObject #region Public Instance Methods /// /// Retrieves the specified corresponding with the specified /// type name from a list of assemblies. /// /// The collection of assemblies that the type should tried to be instantiated from. /// The list of imports that can be used to resolve the typename to a full typename. /// The typename that should be used to determine the type to which the specified value should be converted. /// The value that should be converted to a typed value. /// /// /// is and the identified by has no default public constructor. /// -or- /// cannot be converted to a value that's suitable for one of the constructors of the identified by . /// -or- /// The identified by has no suitable constructor. /// -or- /// A identified by could not be located or loaded. /// public object GetTypedValue(StringCollection assemblies, StringCollection imports, string typename, string value) { // create assembly resolver AssemblyResolver assemblyResolver = new AssemblyResolver(); // attach assembly resolver to the current domain assemblyResolver.Attach(); try { // Try to find the type from typename parameter. Type type = FindType(assemblies, imports, typename); if (type != null) { object typedValue = null; if (value == null) { ConstructorInfo defaultConstructor = type.GetConstructor( BindingFlags.Public | BindingFlags.Instance, null, new Type[0], new ParameterModifier[0]); if (defaultConstructor == null) { throw new BuildException(string.Format( CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2005"), type.FullName), Location.UnknownLocation); } typedValue = null; } else { ConstructorInfo[] constructors = type.GetConstructors(BindingFlags.Public | BindingFlags.Instance); for (int counter = 0; counter < constructors.Length; counter++) { ParameterInfo[] parameters = constructors[counter].GetParameters(); if (parameters.Length == 1) { if (parameters[0].ParameterType.IsPrimitive || parameters[0].ParameterType == typeof(string)) { try { // convert value to type of constructor parameter typedValue = Convert.ChangeType(value, parameters[0].ParameterType, CultureInfo.InvariantCulture); break; } catch (Exception ex) { throw new BuildException(string.Format( CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2006"), value, parameters[0].ParameterType.FullName, type.FullName), Location.UnknownLocation, ex); } } } } if (typedValue == null) { throw new BuildException(string.Format( CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2003"), typename), Location.UnknownLocation); } } return typedValue; } else { if (!typename.EndsWith("Attribute")) { throw new BuildException(string.Format( CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2039"),typename), Location.UnknownLocation); } else { throw new BuildException(string.Format( CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2001"),typename), Location.UnknownLocation); } } } finally { // detach assembly resolver from the current domain assemblyResolver.Detach(); } } #endregion Public Instance Methods #region Private Instance Methods /// /// Finds a given type from a given list of assemblies and import statements. /// /// /// A list of assemblies to search for a given type. /// /// /// A list of import statements to search for a given type. /// /// /// The name of the type to locate. /// /// /// The type object found from assemblies and import statements based /// on the name of the type. /// private Type FindType(StringCollection assemblies, StringCollection imports, string typename) { Type type = null; // load each assembly and try to get type from it foreach (string assemblyFileName in assemblies) { // load assembly from filesystem Assembly assembly = Assembly.LoadFrom(assemblyFileName); // try to load type from assembly type = assembly.GetType(typename, false, false); if (type == null) { foreach (string import in imports) { type = assembly.GetType(import + "." + typename, false, false); if (type != null) { break; } } } if (type != null) { break; } } // try to load type from all assemblies loaded from disk, if // it was not loaded from the references assemblies if (type == null) { type = Type.GetType(typename, false, false); if (type == null) { foreach (string import in imports) { type = Type.GetType(import + "." + typename, false, false); if (type != null) { break; } } } } return type; } #endregion Private Instance Methods } } } nant-0.92-rc1/src/NAnt.DotNet/Tasks/VjcTask.cs0000644000175000017500000003703411757302273020643 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Tom Jordan (tdjordan@users.sourceforge.net) // Giuseppe Greco (giuseppe.greco@agamura.com) using System.Globalization; using System.IO; using System.Text.RegularExpressions; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Util; using NAnt.DotNet.Types; namespace NAnt.DotNet.Tasks { /// /// Compiles Visual J# programs using vjc, Microsoft's J# compiler. /// /// /// /// In order to have generate manifest resource names /// that match those generated by Microsoft Visual Studio.NET, the value of /// the attribute of the <> /// element should match the "Default Package" of the J#.NET project, and /// the value of the attribute /// should be set to "". /// /// /// /// Compile a "HelloWorld" application, including embedded resources. /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// ]]> /// /// [TaskName("vjc")] [ProgramLocation(LocationType.FrameworkDir)] public class VjcTask : CompilerBase { #region Private Instance Fields private string _baseAddress; private DebugOutput _debugOutput = DebugOutput.None; private bool _secureScoping; private string _x; private string _libPath; private string _jcpa; private string _codepage; private string _warningLevel; #endregion Private Instance Fields #region Private Static Fields private static Regex _classNameRegex = new Regex(@"^((?/\*.*?(\*/|$))|[\s\.\{]+|class\s+(?\w+)|(?\w+))*"); private static Regex _namespaceRegex = new Regex(@"^((?/\*.*?(\*/|$))|[\s\.\{]+|package\s+(?(\w+(\.\w+)*)+)|(?\w+))*"); #endregion Private Static Fields #region Public Instance Properties /// /// The preferred base address at which to load a DLL. The default base /// address for a DLL is set by the .NET Framework common language /// runtime. /// /// /// The preferred base address at which to load a DLL. /// /// /// This address can be specified as a decimal, hexadecimal, or octal /// number. /// public string BaseAddress { get { return _baseAddress; } set { _baseAddress = StringUtils.ConvertEmptyToNull(value); } } /// /// Specifies the type of debugging information generated by the /// compiler. The default is . /// [TaskAttribute("debug")] public DebugOutput DebugOutput { get { return _debugOutput; } set { _debugOutput = value; } } /// /// No longer expose this to build authors. Use /// instead. /// public override bool Debug { get { return DebugOutput != DebugOutput.None; } set { DebugOutput = DebugOutput.Enable; } } /// /// Specifies whether package-scoped members are accessible outside of /// the assembly. In other words, package scope is treated as assembly /// scope when emitting metadata. The default is . /// /// /// if the option should be passed to the compiler; /// otherwise, . /// /// /// /// Corresponds to the /securescoping flag. /// /// /// See the Visual J# Reference for details. /// /// /// /// ]]> /// [TaskAttribute("securescoping")] [BooleanValidator()] public bool SecureScoping { get { return _secureScoping; } set { _secureScoping = value; } } /// /// Specifies whether to disable language extensions. /// /// /// The value of this property must be either all, net, /// or an empty string. /// /// /// /// Corresponds to the /x flag. /// /// /// See the Visual J# Reference for details. /// /// /// /// To disable only the .NET Framework extensions: /// ]]> /// To disable the .NET Framework extensions and the VJ++ 6.0 extensions: /// ]]> /// [TaskAttribute("x")] public string X { get { return _x; } set { _x = StringUtils.ConvertEmptyToNull(value); } } /// /// Specifies the location of assemblies referenced by way of the /reference flag. /// /// /// /// Corresponds to the /libpath:dir[;dir2] flag. /// /// /// See the Visual J# Reference for details. /// /// [TaskAttribute("libpath")] public string LibPath { get { return _libPath; } set { _libPath = StringUtils.ConvertEmptyToNull(value); } } /// /// Associate Java-language/COM package names. /// /// /// The value of this propery. must be package=namespace, @filename, /// or an empty string. /// /// /// /// Corresponds to the /jcpa:package=namespace and /jcpa:@filename flags. /// /// /// See the Visual J# Reference for details. /// /// /// /// Map package 'x' to namespace 'y': /// ]]> /// [TaskAttribute("jcpa")] public string Jcpa { get { return _jcpa; } set { _jcpa = StringUtils.ConvertEmptyToNull(value); } } /// /// Specifies the code page to use for all source code files in the /// compilation. /// /// /// /// Corresponds with the /codepage flag. /// /// /// See the Visual J# Reference for details. /// /// [TaskAttribute("codepage")] public string Codepage { get { return _codepage; } set { _codepage = StringUtils.ConvertEmptyToNull(value); } } /// /// Specifies the warning level for the compiler to display. Valid values /// are 0-4. The default is 4. /// /// /// The warning level for the compiler to display. /// /// /// /// Corresponds with the /warn option. /// /// [TaskAttribute("warninglevel")] [Int32Validator(0, 4)] public string WarningLevel { get { return _warningLevel; } set { _warningLevel = StringUtils.ConvertEmptyToNull(value); } } /// /// Controls which warnings should be reported as errors. /// /// /// Override to avoid exposing this to build authors, as the Visual J# /// compiler does not allow control over which warnings should be /// reported as errors. /// public override WarningAsError WarningAsError { get { return base.WarningAsError; } } #endregion Public Instance Properties #region Override implementation of CompilerBase /// /// Reference packages /// /// /// Override to avoid exposing this to build authors, as the Visual J# /// compiler does not support package references. /// public override PackageCollection Packages { get { return base.Packages; } set { base.Packages = value; } } /// /// Link the specified modules into this assembly. /// /// /// Override to avoid exposing this to build authors, as the Visual J# /// compiler does not support linking modules. /// public override AssemblyFileSet Modules { get { return base.Modules; } set { base.Modules = value; } } /// /// Writes module references to the specified . /// /// The to which the module references should be written. protected override void WriteModuleReferences(TextWriter writer) { if (Modules.FileNames.Count > 0) { Log(Level.Warning, ResourceUtils.GetString("String_JscDoesNotSupportLinkingModules")); } } /// /// Writes the compiler options to the specified . /// /// to which the compiler options should be written. protected override void WriteOptions(TextWriter writer) { // the base address for the DLL if (BaseAddress != null) { WriteOption(writer, "baseaddress", BaseAddress); } // handle secure scoping. if (SecureScoping) { WriteOption(writer, "securescoping"); } // handle the disable framework extensions option. if (X != null) { WriteOption(writer, "x", X); } // handle the libpath option. if (LibPath != null ) { WriteOption(writer, "libpath", LibPath); } // handle the jcpa option. if (Jcpa != null) { WriteOption(writer, "jcpa", Jcpa); } // handle the codepage option. if (Codepage != null) { WriteOption(writer, "codepage", Codepage); } // handle debug builds. switch (DebugOutput) { case DebugOutput.None: break; case DebugOutput.Enable: WriteOption(writer, "debug"); WriteOption(writer, "define", "DEBUG"); WriteOption(writer, "define", "TRACE"); break; case DebugOutput.Full: WriteOption(writer, "debug"); break; case DebugOutput.PdbOnly: WriteOption(writer, "debug", "pdbonly"); break; default: throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2011"), DebugOutput), Location); } if (WarningLevel != null) { WriteOption(writer, "warn", WarningLevel); } // win32res if (Win32Res != null) { WriteOption (writer, "win32res", Win32Res.FullName); } } /// /// Gets the file extension required by the current compiler. /// /// /// For the J# compiler, the file extension is always jsl. /// public override string Extension { get { return "jsl"; } } /// /// Gets the class name regular expression for the language of the /// current compiler. /// /// /// Class name regular expression for the language of the current /// compiler. /// protected override Regex ClassNameRegex { get { return _classNameRegex; } } /// /// Gets the namespace regular expression for the language of the /// current compiler. /// /// /// Namespace regular expression for the language of the current /// compiler. /// protected override Regex NamespaceRegex { get { return _namespaceRegex; } } /// /// Override to avoid exposing the configuration setting for this /// task as Visual J# will never support package references. /// /// /// , as the Visual J# compiler will never /// support package references. /// public override bool SupportsPackageReferences { get { return false; } set { } } #endregion Override implementation of CompilerBase } } nant-0.92-rc1/src/NAnt.DotNet/Tasks/CompilerBase.cs0000644000175000017500000021032211757302273021634 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Mike Krueger (mike@icsharpcode.net) // Ian MacLean (ian_maclean@another.com) // Giuseppe Greco (giuseppe.greco@agamura.com) using System; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Text; using System.Text.RegularExpressions; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Tasks; using NAnt.Core.Types; using NAnt.Core.Util; using NAnt.DotNet.Types; namespace NAnt.DotNet.Tasks { /// /// Provides the abstract base class for compiler tasks. /// public abstract class CompilerBase : ExternalProgramBase { #region Private Instance Fields private string _responseFileName; private FileInfo _outputFile; private string _target; private bool _debug; private string _define; private FileInfo _win32icon; private FileInfo _win32res; private bool _warnAsError; private WarningAsError _warningAsError = new WarningAsError(); private string _noWarn; private CompilerWarningCollection _suppressWarnings = new CompilerWarningCollection(); private bool _forceRebuild; private string _mainType; private string _keyContainer; private FileInfo _keyFile; private DelaySign _delaySign = DelaySign.NotSet; private AssemblyFileSet _references = new AssemblyFileSet(); private FileSet _lib = new FileSet(); private AssemblyFileSet _modules = new AssemblyFileSet(); private FileSet _sources = new FileSet(); private ResourceFileSetCollection _resourcesList = new ResourceFileSetCollection(); private PackageCollection _packages = new PackageCollection(); // framework configuration settings private bool _supportsPackageReferences; private bool _supportsWarnAsErrorList; private bool _supportsNoWarnList; private bool _supportsKeyContainer; private bool _supportsKeyFile; private bool _supportsDelaySign; #endregion Private Instance Fields #region Protected Static Fields /// /// Contains a list of extensions for all file types that should be treated as /// 'code-behind' when looking for resources. Ultimately this will determine /// if we use the "namespace+filename" or "namespace+classname" algorithm, since /// code-behind will use the "namespace+classname" algorithm. /// protected static string[] CodebehindExtensions = {".aspx", ".asax", ".ascx", ".asmx"}; /// /// Case-insensitive list of valid culture names for this platform. /// /// /// The key of the is the culture name and /// the value is . /// protected readonly static Hashtable CultureNames; #endregion Protected Static Fields #region Static Constructor /// /// Class constructor for . /// static CompilerBase() { CultureInfo[] allCultures = CultureInfo.GetCultures(CultureTypes.AllCultures); // initialize hashtable to necessary size CultureNames = CollectionsUtil.CreateCaseInsensitiveHashtable( allCultures.Length); // fill the culture list foreach (CultureInfo ci in allCultures) { CultureNames[ci.Name] = null; } } #endregion Static Constructor #region Public Instance Properties /// /// Generate debug output. The default is . /// /// /// Only used for <jsc> tasks, but retained for backward /// compatibility (Clover.NET). /// [TaskAttribute("debug")] [BooleanValidator()] public virtual bool Debug { get { return _debug; } set { _debug = value; } } /// /// The output file created by the compiler. /// [TaskAttribute("output", Required=true)] public FileInfo OutputFile { get { return _outputFile; } set { _outputFile = value; } } /// /// Output type. Possible values are exe, winexe, /// library or module. /// [TaskAttribute("target", Required=true)] [StringValidator(AllowEmpty=false)] public string OutputTarget { get { return _target; } set { _target = StringUtils.ConvertEmptyToNull(value); } } /// /// Define conditional compilation symbol(s). /// /// /// /// Corresponds to /d[efine]: flag. /// /// [TaskAttribute("define")] public string Define { get { return _define; } set { _define = StringUtils.ConvertEmptyToNull(value); } } /// /// Icon to associate with the application. /// /// /// /// Corresponds to /win32icon: flag. /// /// [TaskAttribute("win32icon")] public FileInfo Win32Icon { get { return _win32icon; } set { _win32icon = value; } } /// /// Specifies a Win32 resource file (.res). /// /// /// /// Corresponds to /win32res[ource]: flag. /// /// [TaskAttribute("win32res")] public FileInfo Win32Res { get { return _win32res; } set { _win32res = value; } } /// /// Instructs the compiler to treat all warnings as errors. The default /// is . /// /// /// /// Corresponds to the /warnaserror[+|-] flag of the compiler. /// /// /// When this property is set to , any messages /// that would ordinarily be reported as warnings will instead be /// reported as errors. /// /// [TaskAttribute("warnaserror")] [BooleanValidator()] public bool WarnAsError { get { return _warnAsError; } set { _warnAsError = value; } } /// /// Controls which warnings should be reported as errors. /// [BuildElement("warnaserror")] public virtual WarningAsError WarningAsError { get { return _warningAsError; } } /// /// Specifies a comma-separated list of warnings that should be suppressed /// by the compiler. /// /// /// Comma-separated list of warnings that should be suppressed by the /// compiler. /// /// /// /// Corresponds with the /nowarn flag. /// /// [TaskAttribute("nowarn")] [Obsolete("Use the element instead.", false)] public virtual string NoWarn { get { return _noWarn; } set { _noWarn = StringUtils.ConvertEmptyToNull(value); } } /// /// Specifies a list of warnings that you want the compiler to suppress. /// [BuildElementCollection("nowarn", "warning")] public virtual CompilerWarningCollection SuppressWarnings { get { return _suppressWarnings; } } /// /// Instructs NAnt to recompile the output file regardless of the file timestamps. /// /// /// When this parameter is to , NAnt will always /// run the compiler to rebuild the output file, regardless of the file timestamps. /// [TaskAttribute("rebuild")] [BooleanValidator()] public bool ForceRebuild { get { return _forceRebuild; } set { _forceRebuild = value; } } /// /// Specifies which type contains the Main method that you want to use /// as the entry point into the program. /// /// /// /// Corresponds to the /m[ain]: flag of the compiler. /// /// /// Use this property when creating an executable file. If this property /// is not set, the compiler searches for a valid Main method in all /// public classes. /// /// [TaskAttribute("main")] public string MainType { get { return _mainType; } set { _mainType = StringUtils.ConvertEmptyToNull(value); } } /// /// Specifies the key pair container used to strongname the assembly. /// [TaskAttribute("keycontainer")] public virtual string KeyContainer { get { return _keyContainer; } set { _keyContainer = StringUtils.ConvertEmptyToNull(value); } } /// /// Specifies a strong name key file. /// [TaskAttribute("keyfile")] public virtual FileInfo KeyFile { get { return _keyFile; } set { _keyFile = value; } } /// /// Specifies whether to delay sign the assembly using only the public /// portion of the strong name key. The default is /// . /// [TaskAttribute("delaysign")] public virtual DelaySign DelaySign { get { return _delaySign; } set { _delaySign = value; } } /// /// Additional directories to search in for assembly references. /// /// /// /// Corresponds with the /lib[path]: flag. /// /// [BuildElement("lib")] [Obsolete("Use the element in and instead.", false)] public FileSet Lib { get { return _lib; } set {_lib = value; } } /// /// Reference metadata from the specified assembly files. /// [BuildElement("references")] public AssemblyFileSet References { get { return _references; } set { _references = value; } } /// /// Specifies list of packages to reference. /// [BuildElementCollection("pkg-references", "package")] public virtual PackageCollection Packages { get { return _packages; } set { _packages = value; } } /// /// Resources to embed. /// /// /// /// This can be a combination of resx files and file resources. /// /// /// .resx files will be compiled by and then /// embedded into the resulting executable. /// /// /// The property is used to make /// up the resource name added to the assembly manifest for non-resx /// files. /// /// /// For .resx files the namespace from the matching source file is used /// as prefix. This matches the behaviour of Visual Studio. /// /// /// Multiple resources tags with different namespace prefixes may be /// specified. /// /// [BuildElementArray("resources")] public ResourceFileSetCollection ResourcesList { get { return _resourcesList; } } /// /// Link the specified modules into this assembly. /// [BuildElement("modules")] public virtual AssemblyFileSet Modules { get { return _modules; } set { _modules = value; } } /// /// The set of source files for compilation. /// [BuildElement("sources", Required=true)] public FileSet Sources { get { return _sources; } set { _sources = value; } } /// /// Indicates whether package references are supported by compiler for /// a given target framework. The default is . /// [FrameworkConfigurable("supportspackagereferences")] public virtual bool SupportsPackageReferences { get { return _supportsPackageReferences; } set { _supportsPackageReferences = value; } } /// /// Indicates whether the compiler for a given target framework supports /// the "warnaserror" option that takes a list of warnings. The default /// is . /// [FrameworkConfigurable("supportswarnaserrorlist")] public virtual bool SupportsWarnAsErrorList { get { return _supportsWarnAsErrorList; } set { _supportsWarnAsErrorList = value; } } /// /// Indicates whether the compiler for a given target framework supports /// a command line option that allows a list of warnings to be /// suppressed. The default is . /// [FrameworkConfigurable("supportsnowarnlist")] public virtual bool SupportsNoWarnList { get { return _supportsNoWarnList; } set { _supportsNoWarnList = value; } } /// /// Indicates whether the compiler for a given target framework supports /// the "keycontainer" option. The default is . /// [FrameworkConfigurable("supportskeycontainer")] public virtual bool SupportsKeyContainer { get { return _supportsKeyContainer; } set { _supportsKeyContainer = value; } } /// /// Indicates whether the compiler for a given target framework supports /// the "keyfile" option. The default is . /// [FrameworkConfigurable("supportskeyfile")] public virtual bool SupportsKeyFile { get { return _supportsKeyFile; } set { _supportsKeyFile = value; } } /// /// Indicates whether the compiler for a given target framework supports /// the "delaysign" option. The default is . /// [FrameworkConfigurable("supportsdelaysign")] public virtual bool SupportsDelaySign { get { return _supportsDelaySign; } set { _supportsDelaySign = value; } } #endregion Public Instance Properties #region Protected Instance Properties /// /// Gets the file extension required by the current compiler. /// /// /// The file extension required by the current compiler. /// public abstract string Extension { get; } /// /// Gets the class name regular expression for the language of the current compiler. /// /// class name regular expression for the language of the current compiler protected abstract Regex ClassNameRegex { get; } /// /// Gets the namespace regular expression for the language of the current compiler. /// /// namespace regular expression for the language of the current compiler protected abstract Regex NamespaceRegex { get; } #endregion Protected Instance Properties #region Override implementation of ExternalProgramBase /// /// Gets the command-line arguments for the external program. /// /// /// The command-line arguments for the external program. /// public override string ProgramArguments { get { return "@" + "\"" + _responseFileName + "\""; } } /// /// Compiles the sources and resources. /// protected override void ExecuteTask() { if (NeedsCompiling()) { // create temp response file to hold compiler options _responseFileName = Path.GetTempFileName(); StreamWriter writer = new StreamWriter(_responseFileName); // culture names are not case-sensitive Hashtable cultureResources = CollectionsUtil.CreateCaseInsensitiveHashtable(); // will hold temporary compiled resources StringCollection compiledResourceFiles = new StringCollection(); try { // ensure base directory is set, even if fileset was not initialized // from XML if (References.BaseDirectory == null) { References.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } if (Lib.BaseDirectory == null) { Lib.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } if (Modules.BaseDirectory == null) { Modules.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } if (Sources.BaseDirectory == null) { Sources.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } // copy lib path details across to the children Assembly filesets foreach(string directoryName in Lib.DirectoryNames){ References.Lib.DirectoryNames.Add(directoryName); Modules.Lib.DirectoryNames.Add(directoryName); } // rescan to ensure correct assembly resolution References.Scan(); Modules.Scan(); // create the base directory if it does not exist if (!Directory.Exists(OutputFile.DirectoryName)) { Directory.CreateDirectory(OutputFile.DirectoryName); } Log(Level.Info, ResourceUtils.GetString("String_CompilingFiles"), Sources.FileNames.Count, OutputFile.FullName); // specific compiler options WriteOptions(writer); // suppresses display of the sign-on banner WriteOption(writer, "nologo"); // specify output file format WriteOption(writer, "target", OutputTarget); WriteConditionalCompilationConstants(writer); // the name of the output file WriteOption(writer, "out", OutputFile.FullName); if (Win32Icon != null) { WriteOption(writer, "win32icon", Win32Icon.FullName); } // writes the option that specifies the class containing // the Main method that should be called when the program // starts. if (MainType != null) { WriteOption(writer, "main", MainType); } if (KeyContainer != null) { if (SupportsKeyContainer) { WriteOption(writer, "keycontainer", KeyContainer); } else { Log(Level.Warning, ResourceUtils.GetString("String_CompilerDoesNotSupportKeyContainer"), Project.TargetFramework.Description); } } if (KeyFile != null) { if (SupportsKeyFile) { WriteOption(writer, "keyfile", KeyFile.FullName); } else { Log(Level.Warning, ResourceUtils.GetString("String_CompilerDoesNotSupportKeyFile"), Project.TargetFramework.Description); } } if (DelaySign != DelaySign.NotSet) { if (SupportsDelaySign) { switch (DelaySign) { case DelaySign.Yes: WriteOption(writer, "delaysign+"); break; case DelaySign.No: WriteOption(writer, "delaysign-"); break; default: throw new NotSupportedException (string.Format ( CultureInfo.InvariantCulture, "The {0}" + "value for \"delaysign\" is not supported.", DelaySign)); } } else { Log(Level.Warning, ResourceUtils.GetString("String_CompilerDoesNotSupportDelaySign"), Project.TargetFramework.Description); } } // writes package references to the response file WritePackageReferences(writer); // write warnings to (not) treat as errors to the response file WriteWarningsAsError(writer); // write list of warnings to suppress WriteNoWarnList(writer); // writes assembly references to the response file foreach (string fileName in References.FileNames) { WriteOption(writer, "reference", fileName); } // writes module references to the response file WriteModuleReferences(writer); // compile resources foreach (ResourceFileSet resources in ResourcesList) { // resx files if (resources.ResxFiles.FileNames.Count > 0) { // compile the resx files to .resources files in the // same dir as the input files CompileResxResources(resources.ResxFiles.FileNames); // Resx args foreach (string fileName in resources.ResxFiles.FileNames) { // determine manifest resource name string manifestResourceName = this.GetManifestResourceName( resources, fileName); // determine the filenames of the .resources file // generated by the task string tmpResourcePath = Path.ChangeExtension(fileName, ".resources"); compiledResourceFiles.Add(tmpResourcePath); // check if resource is localized CultureInfo resourceCulture = CompilerBase.GetResourceCulture(fileName, Path.ChangeExtension(fileName, Extension)); if (resourceCulture != null) { if (!cultureResources.ContainsKey(resourceCulture.Name)) { // initialize collection for holding // resource file for this culture cultureResources.Add(resourceCulture.Name, new Hashtable()); } // store resulting .resources file for later linking ((Hashtable) cultureResources[resourceCulture.Name])[manifestResourceName] = tmpResourcePath; } else { // regular embedded resources (using filename and manifest resource name). string resourceoption = string.Format(CultureInfo.InvariantCulture, "{0},{1}", tmpResourcePath, manifestResourceName); // write resource option to response file WriteOption(writer, "resource", resourceoption); } } } // other resources foreach (string fileName in resources.NonResxFiles.FileNames) { // determine manifest resource name string manifestResourceName = this.GetManifestResourceName( resources, fileName); // check if resource is localized CultureInfo resourceCulture = CompilerBase.GetResourceCulture(fileName, Path.ChangeExtension(fileName, Extension)); if (resourceCulture != null) { if (!cultureResources.ContainsKey(resourceCulture.Name)) { // initialize collection for holding // resource file for this culture cultureResources.Add(resourceCulture.Name, new Hashtable()); } // store resource filename for later linking ((Hashtable) cultureResources[resourceCulture.Name])[manifestResourceName] = fileName; } else { string resourceoption = string.Format(CultureInfo.InvariantCulture, "{0},{1}",fileName, manifestResourceName); WriteOption(writer, "resource", resourceoption); } } } // write sources to compile to response file foreach (string fileName in Sources.FileNames) { writer.WriteLine("\"" + fileName + "\""); } // make sure to close the response file otherwise contents // will not be written to disk and ExecuteTask() will fail. writer.Close(); if (Verbose) { // display response file contents Log(Level.Info, ResourceUtils.GetString("String_ContentsOf"), _responseFileName); StreamReader reader = File.OpenText(_responseFileName); Log(Level.Info, reader.ReadToEnd()); reader.Close(); } // call base class to do the work base.ExecuteTask(); // create a satellite assembly for each culture name foreach (string culture in cultureResources.Keys) { // determine directory for satellite assembly string culturedir = Path.Combine(OutputFile.DirectoryName, culture); // ensure diretory for satellite assembly exists Directory.CreateDirectory(culturedir); // determine filename of satellite assembly FileInfo outputFile = new FileInfo(Path.Combine(culturedir, Path.GetFileNameWithoutExtension(OutputFile.Name) + ".resources.dll")); // generate satellite assembly LinkResourceAssembly((Hashtable)cultureResources[culture], outputFile, culture); } } finally { // cleanup .resource files foreach (string compiledResourceFile in compiledResourceFiles) { File.Delete(compiledResourceFile); } // make sure we delete response file even if an exception is thrown writer.Close(); // make sure stream is closed or file cannot be deleted File.Delete(_responseFileName); _responseFileName = null; } } } #endregion Override implementation of ExternalProgramBase #region Public Instance Methods /// /// Determines the manifest resource name of the given resource file. /// /// The containing information that will used to assemble the manifest resource name. /// The resource file of which the manifest resource name should be determined. /// The logical location of the resource file. /// The source file on which the resource file depends. /// /// The manifest resource name of the specified resource file. /// public string GetManifestResourceName(ResourceFileSet resources, string resourcePhysicalFile, string resourceLogicalFile, string dependentFile) { if (resources == null) { throw new ArgumentNullException("resources"); } if (resourcePhysicalFile == null) { throw new ArgumentNullException("resourcePhysicalFile"); } if (resourceLogicalFile == null) { throw new ArgumentNullException("resourceLogicalFile"); } // make sure the resource file exists if (!File.Exists(resourcePhysicalFile)) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2009"), resourcePhysicalFile), Location); } // will hold the manifest resource name string manifestResourceName = null; // check if we're dealing with a localized resource CultureInfo resourceCulture = CompilerBase.GetResourceCulture( resourceLogicalFile, dependentFile); // determine the resource type switch (Path.GetExtension(resourcePhysicalFile).ToLower(CultureInfo.InvariantCulture)) { case ".resx": // try and get manifest resource name from dependent file ResourceLinkage resourceLinkage = GetResourceLinkage( dependentFile, resourceCulture); if (resourceLinkage == null || !resourceLinkage.IsValid) { // no resource linkage could be determined (no dependent // file or dependent file does not exist) or dependent // file is no (valid) source file manifestResourceName = Path.ChangeExtension( resources.GetManifestResourceName(resourcePhysicalFile, resourceLogicalFile), "resources"); } else { if (!resourceLinkage.HasClassName) { // use filename of resource file to determine class name string className = Path.GetFileNameWithoutExtension( resourcePhysicalFile); // cater for asax/aspx special cases. eg. a resource file // named "WebForm1.aspx(.resx)" will here be transformed to // "WebForm1" // we assume that the class name of a codebehind file // is equal to the file name of that codebehind file // (without extension) if (Path.GetExtension(className) != string.Empty) { string codebehindExtension = Path.GetExtension( className).ToLower(CultureInfo.InvariantCulture); foreach (string extension in CodebehindExtensions) { if (extension == codebehindExtension) { className = Path.GetFileNameWithoutExtension( className); break; } } } resourceLinkage.ClassName = className; } // ensure we have information necessary to determine the // manifest resource name if (resourceLinkage.IsValid) { manifestResourceName = resourceLinkage.ToString() + ".resources"; } else { // we should actually never get here, but just in case ... throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2010"), resourcePhysicalFile), Location); } } break; case ".resources": // determine resource name, and leave culture information // in manifest resource name manifestResourceName = resources.GetManifestResourceName( resourcePhysicalFile, resourceLogicalFile); break; default: // VS.NET handles an embedded resource file named licenses.licx // in the root of the project and without culture in a special // way if (Path.GetFileName(resourcePhysicalFile) == "licenses.licx") { // the manifest resource name will be .licenses // eg. TestAssembly.exe.licenses manifestResourceName = Path.GetFileName(OutputFile.FullName) + ".licenses"; } else { // check if resource is localized if (resourceCulture != null) { // determine resource name manifestResourceName = resources.GetManifestResourceName( resourcePhysicalFile, resourceLogicalFile); // remove culture name from name of resource int cultureIndex = manifestResourceName.LastIndexOf("." + resourceCulture.Name); manifestResourceName = manifestResourceName.Substring(0, cultureIndex) + manifestResourceName.Substring(cultureIndex).Replace("." + resourceCulture.Name, string.Empty); } else { manifestResourceName = resources.GetManifestResourceName( resourcePhysicalFile, resourceLogicalFile); } } break; } return manifestResourceName; } /// /// Determines the manifest resource name of the given resource file. /// /// The containing information that will used to assemble the manifest resource name. /// The resource file of which the manifest resource name should be determined. /// /// The manifest resource name of the specified resource file. /// /// /// For .resx resources, the name of the dependent is determined by /// replacing the extension of the file with the extension of the /// source files for the compiler, and removing the culture name from /// the file name for localized resources. /// public string GetManifestResourceName(ResourceFileSet resources, string resourceFile) { if (resources == null) { throw new ArgumentNullException("resources"); } if (resourceFile == null) { throw new ArgumentNullException("resourceFile"); } // make sure the resource file exists if (!File.Exists(resourceFile)) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2009"), resourceFile), Location); } // determine the resource type switch (Path.GetExtension(resourceFile).ToLower(CultureInfo.InvariantCulture)) { case ".resx": // open matching source file if it exists string dependentFile = Path.ChangeExtension(resourceFile, Extension); // check if we're dealing with a localized resource CultureInfo resourceCulture = CompilerBase.GetResourceCulture(resourceFile, dependentFile); // remove last occurrence of culture name from dependent file // for localized resources if (resourceCulture != null) { int index = dependentFile.LastIndexOf("." + resourceCulture.Name); if (index >= 0) { if ((index + resourceCulture.Name.Length + 1) < dependentFile.Length) { dependentFile = dependentFile.Substring(0, index) + dependentFile.Substring(index + resourceCulture.Name.Length + 1); } else { dependentFile = dependentFile.Substring(0, index); } } } // determine the manifest resource name using the given // dependent file return GetManifestResourceName(resources, resourceFile, resourceFile, dependentFile); default: // for non-resx resources, a dependent file has no influence // on the manifest resource name return GetManifestResourceName(resources, resourceFile, resourceFile, null); } } /// /// Extracts the associated namespace/classname linkage found in the /// given stream. /// /// The read-only stream of the source file to search. /// /// The namespace/classname of the source file matching the resource. /// public virtual ResourceLinkage PerformSearchForResourceLinkage(TextReader sr) { Regex matchNamespaceRE = NamespaceRegex; Regex matchClassNameRE = ClassNameRegex; string namespaceName = ""; string className = ""; while (sr.Peek() > -1) { string str = sr.ReadLine(); Match matchNamespace = matchNamespaceRE.Match(str); if (matchNamespace.Success) { Group group = matchNamespace.Groups["namespace"]; if (group.Success) { foreach (Capture capture in group.Captures) { namespaceName += (namespaceName.Length > 0 ? "." : "") + capture.Value; } } } Match matchClassName = matchClassNameRE.Match(str); if (matchClassName.Success) { Group group = matchClassName.Groups["class"]; if (group.Success) { className = group.Value; break; } } } return new ResourceLinkage(namespaceName, className); } #endregion Public Instance Methods #region Protected Instance Methods /// /// Writes package references to the specified . /// /// The to which the package references should be written. protected virtual void WritePackageReferences(TextWriter writer) { StringCollection packages = new StringCollection(); foreach (Package package in Packages) { if (package.IfDefined && !package.UnlessDefined) { packages.AddRange(package.PackageName.Split(';')); } } if (packages.Count == 0) { return; } if (SupportsPackageReferences) { // write package references to the TextWriter WriteOption(writer, "pkg", StringUtils.Join(",", packages)); } else { Log(Level.Warning, ResourceUtils.GetString("String_CompilerDoesNotSupportPackageReferences"), Project.TargetFramework.Description); } } /// /// Writes list of warnings to (not) treat as errors to the specified /// . /// /// The to which the list of warnings should be written. protected virtual void WriteWarningsAsError(TextWriter writer) { // check if all warnings should be treated as errors if (WarnAsError) { // ignore setting if a specific list of warnings that should be // treated as errors has been set if (WarningAsError.Includes.Count == 0) { WriteOption(writer, "warnaserror"); } } // initialize warnings list StringCollection warnings = new StringCollection(); // // warnings that should be treated as error // foreach (CompilerWarning warning in WarningAsError.Includes) { if (warning.IfDefined && !warning.UnlessDefined) { warnings.AddRange(warning.Number.Split(',')); } } if (warnings.Count > 0) { if (SupportsWarnAsErrorList) { // write list of warnings to the TextWriter writer.WriteLine("/warnaserror+:" + StringUtils.Join(",", warnings)); } else { Log(Level.Warning, ResourceUtils.GetString("String_CompilerDoesNotSupportWarningsAsErrors"), Project.TargetFramework.Description); } } // clear list of warnings warnings.Clear(); // // warnings that should NOT be treated as error // foreach (CompilerWarning warning in WarningAsError.Excludes) { if (warning.IfDefined && !warning.UnlessDefined) { warnings.AddRange(warning.Number.Split(',')); } } if (warnings.Count > 0) { if (SupportsWarnAsErrorList) { // write list of warnings to the TextWriter writer.WriteLine("/warnaserror-:" + StringUtils.Join(",", warnings)); } else { Log(Level.Warning, ResourceUtils.GetString("String_CompilerDoesNotSupportWarningsAsErrors"), Project.TargetFramework.Description); } } // clear list of warnings warnings.Clear(); } /// /// Writes list of warnings to suppress to the specified /// . /// /// The to which the list of warnings to suppress should be written. protected virtual void WriteNoWarnList(TextWriter writer) { // initialize warnings list StringCollection warnings = new StringCollection(); foreach (CompilerWarning warning in SuppressWarnings) { if (warning.IfDefined && !warning.UnlessDefined) { warnings.AddRange(warning.Number.Split(',')); } } if (NoWarn != null) { warnings.AddRange(NoWarn.Split(',')); } if (warnings.Count > 0) { if (SupportsNoWarnList) { // write list of warnings to suppress to the TextWriter writer.WriteLine("/nowarn:" + StringUtils.Join(",", warnings)); } else { Log(Level.Warning, ResourceUtils.GetString("String_CompilerDoesNotSupportWarningsToSuppress"), Project.TargetFramework.Description); } } } /// /// Writes conditional compilation constants to the specified /// . /// /// The to which the conditional compilation constants should be written. protected virtual void WriteConditionalCompilationConstants(TextWriter writer) { if (Define != null) { WriteOption(writer, "define", Define); } } /// /// Writes module references to the specified . /// /// The to which the module references should be written. protected virtual void WriteModuleReferences(TextWriter writer) { // write references to the TextWriter foreach (string fileName in Modules.FileNames) { WriteOption(writer, "addmodule", fileName); } } /// /// Allows derived classes to provide compiler-specific options. /// /// The to which the compiler options should be written. protected virtual void WriteOptions(TextWriter writer) { } /// /// Writes an option using the default output format. /// /// The to which the compiler options should be written. /// The name of the option which should be passed to the compiler. protected virtual void WriteOption(TextWriter writer, string name) { writer.WriteLine("/{0}", name); } /// /// Writes an option and its value using the default output format. /// /// The to which the compiler options should be written. /// The name of the option which should be passed to the compiler. /// The value of the option which should be passed to the compiler. /// /// The combination of and /// (separated by a colon) is quoted /// unless is already surrounded by quotes. /// protected virtual void WriteOption(TextWriter writer, string name, string value) { // quote argument if value is not already quoted if (!value.StartsWith("\"") || !value.EndsWith("\"")) { writer.WriteLine("\"/{0}:{1}\"", name, value); } else { writer.WriteLine("/{0}:{1}", name, value); } } /// /// Determines whether compilation is needed. /// protected virtual bool NeedsCompiling() { // return true as soon as we know we need to compile if (ForceRebuild) { Log(Level.Verbose, ResourceUtils.GetString("String_RebuildAttributeSetToTrue")); return true; } if (!OutputFile.Exists) { Log(Level.Verbose, ResourceUtils.GetString("String_OutputFileDoesNotExist"), OutputFile.FullName); return true; } // check if sources were updated string fileName = FileSet.FindMoreRecentLastWriteTime(Sources.FileNames, OutputFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, ResourceUtils.GetString("String_FileHasBeenUpdated"), fileName); return true; } // check if key file was updated if (KeyFile != null) { fileName = FileSet.FindMoreRecentLastWriteTime(KeyFile.FullName, OutputFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, ResourceUtils.GetString("String_FileHasBeenUpdated"), fileName); return true; } } // check if reference assemblies were updated fileName = FileSet.FindMoreRecentLastWriteTime(References.FileNames, OutputFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, ResourceUtils.GetString("String_FileHasBeenUpdated"), fileName); return true; } // check if modules were updated fileName = FileSet.FindMoreRecentLastWriteTime(Modules.FileNames, OutputFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, ResourceUtils.GetString("String_FileHasBeenUpdated"), fileName); return true; } // check if resources were updated foreach (ResourceFileSet resources in ResourcesList) { fileName = FileSet.FindMoreRecentLastWriteTime(resources.FileNames, OutputFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, ResourceUtils.GetString("String_FileHasBeenUpdated"), fileName); return true; } } // check if win32icon was updated if (Win32Icon != null) { fileName = FileSet.FindMoreRecentLastWriteTime(Win32Icon.FullName, OutputFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, ResourceUtils.GetString("String_FileHasBeenUpdated"), fileName); return true; } } // check if win32 resource was updated if (Win32Res != null) { fileName = FileSet.FindMoreRecentLastWriteTime(Win32Res.FullName, OutputFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, ResourceUtils.GetString("String_FileHasBeenUpdated"), fileName); return true; } } // check the args for /res or /resource options. StringCollection resourceFileNames = new StringCollection(); foreach (Argument argument in Arguments) { if (argument.IfDefined && !argument.UnlessDefined) { string argumentValue = argument.Value; // check whether argument specified resource file to embed if (argumentValue != null && (argumentValue.StartsWith("/res:") || argumentValue.StartsWith("/resource:"))) { // determine path to resource file string path = argumentValue.Substring(argumentValue.IndexOf(':') + 1); int indexOfComma = path.IndexOf(','); if (indexOfComma != -1) { path = path.Substring(0, indexOfComma); } // resolve path to full path (relative to project base dir) path = Project.GetFullPath(path); // add path to collection of resource files resourceFileNames.Add(path); } } } fileName = FileSet.FindMoreRecentLastWriteTime(resourceFileNames, OutputFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, ResourceUtils.GetString("String_FileHasBeenUpdated"), fileName); return true; } // if we made it here then we don't have to recompile return false; } /// /// Finds the correct namespace/classname for a resource file from the /// given dependent source file. /// /// The file from which the resource linkage of the resource file should be determined. /// The culture of the resource file for which the resource linkage should be determined. /// /// The namespace/classname of the source file matching the resource or /// if the dependent source file does not exist. /// /// /// This behaviour may be overidden by each particular compiler to /// support the namespace/classname syntax for that language. /// protected virtual ResourceLinkage GetResourceLinkage(string dependentFile, CultureInfo resourceCulture) { StreamReader sr = null; ResourceLinkage resourceLinkage = null; // resource linkage cannot be determined if there's no dependent file if (dependentFile == null) { return null; } try { // open matching source file sr = new StreamReader(dependentFile, Encoding.Default, true); // get resource linkage resourceLinkage = PerformSearchForResourceLinkage(sr); // set resource culture resourceLinkage.Culture = resourceCulture; } catch (FileNotFoundException) { // if no matching file, dump out Log(Level.Debug, ResourceUtils.GetString("String_DependentFileNotFound"), dependentFile); return null; } finally { if (sr != null) { sr.Close(); } } // output some debug information about resource linkage found... if (resourceLinkage.IsValid) { Log(Level.Debug, ResourceUtils.GetString("String_FoundResourceLinkageInDependentFile"), resourceLinkage.ToString(), dependentFile); } else { Log(Level.Debug, ResourceUtils.GetString("String_ResourceLinkageInDependentFileNotFound"), dependentFile); } return resourceLinkage; } /// /// Link a list of files into a resource assembly. /// /// The collection of resources. /// Resource assembly to generate /// Culture of the generated assembly. protected void LinkResourceAssembly(Hashtable resourceFiles, FileInfo resourceAssemblyFile, string culture) { // defer to the assembly linker task AssemblyLinkerTask alink = new AssemblyLinkerTask(); // inherit project from current task alink.Project = Project; // inherit namespace manager from current task alink.NamespaceManager = NamespaceManager; // current task is parent alink.Parent = this; // make sure framework specific information is set alink.InitializeTaskConfiguration(); // set task properties alink.OutputFile = resourceAssemblyFile; alink.Culture = culture; alink.OutputTarget = "lib"; alink.TemplateFile = OutputFile; alink.KeyFile = KeyFile; alink.KeyContainer = KeyContainer; alink.DelaySign = DelaySign; // add resource files using the Arguments collection. foreach (string manifestname in resourceFiles.Keys) { string resourcefile = (string) resourceFiles[manifestname]; // add resources to embed EmbeddedResource embeddedResource = new EmbeddedResource( resourcefile, manifestname); alink.EmbeddedResources.Add(embeddedResource); } // increment indentation level Project.Indent(); try { // execute the nested task alink.Execute(); } finally { // restore indentation level Project.Unindent(); } } /// /// Compiles a set of resx files to a .resources files. /// /// The set of resx files to compile. protected void CompileResxResources(StringCollection resxFiles) { ResGenTask resgen = new ResGenTask(); // inherit project from current task resgen.Project = Project; // inherit namespace manager from current task resgen.NamespaceManager = NamespaceManager; // current task is parent resgen.Parent = this; // make sure framework specific information is set resgen.InitializeTaskConfiguration(); // inherit Verbose setting from current task resgen.Verbose = Verbose; // set parent of child elements resgen.Assemblies.Parent = resgen; // inherit project from parent task resgen.Assemblies.Project = resgen.Project; // inherit namespace manager from parent task resgen.Assemblies.NamespaceManager = resgen.NamespaceManager; // set base directory for filesets resgen.Assemblies.BaseDirectory = References.BaseDirectory; resgen.Resources.BaseDirectory = References.BaseDirectory; // if resource compiler for current target framework supports external // file references, then use source file's directory as current // directory for resolving relative file paths if (resgen.SupportsExternalFileReferences) { resgen.UseSourcePath = true; } // inherit assembly references from current task foreach (string assemblyFile in References.FileNames) { resgen.Assemblies.Includes.Add(assemblyFile); } // set the resx files to compile foreach (string resxFile in resxFiles) { resgen.Resources.Includes.Add(resxFile); } // increment indentation level Project.Indent(); try { // execute the task resgen.Execute(); } finally { // restore indentation level Project.Unindent(); } } #endregion Protected Instance Methods #region Public Static Methods /// /// Determines the culture associated with a given resource file by /// scanning the filename for valid culture names. /// /// The resource file path to check for culture info. /// The file on which the resource file depends. /// /// A valid instance if the resource is /// associated with a specific culture; otherwise, . /// public static CultureInfo GetResourceCulture(string resourceFile, string dependentFile) { string noextpath = Path.GetFileNameWithoutExtension(resourceFile); if (dependentFile != null && File.Exists(dependentFile)) { // there might be cases where the dependent file actually has // a filename containing a valid culture name (eg. Form2.nl-BE.cs) // in this case resx files for that file will have filenames // containing culture names too (eg. Form2.nl-BE.resx), // although the files are not localized if (Path.GetFileNameWithoutExtension(dependentFile) == noextpath) { return null; } } int index = noextpath.LastIndexOf('.'); if (index >= 0 && index <= noextpath.Length) { string possibleculture = noextpath.Substring(index + 1, noextpath.Length - (index + 1)); // check that its in our list of culture names if (CultureNames.ContainsKey(possibleculture)) { return new CultureInfo(possibleculture); } } return null; } #endregion Public Static Methods /// /// Holds class and namespace information for resource (*.resx) linkage. /// public class ResourceLinkage { #region Private Instance Fields private string _namespaceName; private string _className; private CultureInfo _culture; #endregion Private Instance Fields #region Public Instance Constructors /// /// Initializes a new instance of the /// class. /// /// The namespace the resource is under. /// The class name the resource is associated with. public ResourceLinkage(string namespaceName, string className) { _namespaceName = namespaceName; _className = className; } #endregion Public Instance Constructors #region Override implementation of Object /// /// Returns the resource linkage as a string. /// /// /// A string representation of the resource linkage. /// public override string ToString() { string resourceName; if (!IsValid) { return string.Empty; } if (HasNamespaceName) { if (HasClassName) { resourceName = NamespaceName + "." + ClassName; } else { resourceName = NamespaceName; } } else { resourceName = ClassName; } if (Culture != null) { resourceName = string.Format("{0}.{1}", resourceName, Culture.Name); } return resourceName; } #endregion Override implementation of Object #region Public Instance Properties /// /// Gets a value indicating whether the /// instances contains valid data. /// /// /// if the /// instance contains valid data; otherwise, . /// public bool IsValid { get { return !String.IsNullOrEmpty(_namespaceName) || !String.IsNullOrEmpty(_className); } } /// /// Gets a value indicating whether a namespace name is available /// for this instance. /// /// /// if a namespace name is available for /// this instance; otherwise, /// . /// public bool HasNamespaceName { get { return !String.IsNullOrEmpty(_namespaceName); } } /// /// Gets a value indicating whether a class name is available /// for this instance. /// /// /// if a class name is available for /// this instance; otherwise, /// . /// public bool HasClassName { get { return !String.IsNullOrEmpty(_className); } } /// /// Gets the name of namespace the resource is under. /// /// /// The name of namespace the resource is under. /// public string NamespaceName { get { return _namespaceName; } set { _namespaceName = (value != null) ? value.Trim() : null; } } /// /// Gets the name of the class (most likely a form) that the resource /// is associated with. /// /// /// The name of the class the resource is associated with. /// public string ClassName { get { return _className; } set { _className = (value != null) ? value.Trim() : null; } } /// /// Gets the culture that the resource is associated with. /// /// /// The culture that the resource is associated with. /// public CultureInfo Culture { get { return _culture; } set { _culture = value; } } #endregion Public Instance Properties } } } nant-0.92-rc1/src/NAnt.DotNet/Tasks/ResGenTask.cs0000644000175000017500000007447611757302273021317 0ustar jtaylorjtaylor//// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Joe Jones (joejo@microsoft.com) // Gerry Shaw (gerry_shaw@yahoo.com) // Klemen Zagar (klemen@zagar.ws) // Ian MacLean (ian_maclean@another.com) // Gert Driesen (drieseng@ardatis.com) // Giuseppe Greco (giuseppe.greco@agamura.com) using System; using System.Collections; using System.Collections.Specialized; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; using System.Xml; using System.Xml.XPath; using NAnt.Core; using NAnt.Core.Tasks; using NAnt.Core.Attributes; using NAnt.Core.Types; using NAnt.Core.Util; using NAnt.DotNet.Types; namespace NAnt.DotNet.Tasks { /// /// Converts files from one resource format to another. /// /// /// /// If no is specified, the resource file will /// be created next to the input file. /// /// /// /// /// Convert a resource file from the .resx to the .resources /// format. /// /// /// /// ]]> /// /// /// /// /// Convert a set of .resx files to the .resources format. /// /// /// /// /// /// /// /// ]]> /// /// [TaskName("resgen")] [ProgramLocation(LocationType.FrameworkSdkDir)] public class ResGenTask : ExternalProgramBase { #region Private Instance Fields private StringBuilder _arguments = new StringBuilder(); private AssemblyFileSet _assemblies = new AssemblyFileSet(); private FileInfo _inputFile; private FileInfo _outputFile; private string _programFileName; private ResourceFileSet _resources = new ResourceFileSet(); private string _targetExt = "resources"; private DirectoryInfo _toDir; private DirectoryInfo _workingDirectory; private bool _useSourcePath; private ArrayList _qualifiedResources = new ArrayList(); // framework configuration settings private bool _supportsAssemblyReferences; private bool _supportsExternalFileReferences; #endregion Private Instance Fields #region Private Static Fields private const int _maxCmdLineLength = 30000; #endregion Private Static Fields #region Public Instance Properties /// /// Input file to process. /// /// /// The full path to the input file. /// [TaskAttribute("input", Required=false)] public FileInfo InputFile { get { return _inputFile; } set { _inputFile = value; } } /// /// The resource file to output. /// [TaskAttribute("output", Required=false)] public FileInfo OutputFile { get { return _outputFile; } set { _outputFile = value; } } /// /// The target type. The default is resources. /// [TaskAttribute("target", Required=false)] public string TargetExt { get { return _targetExt; } set { _targetExt = StringUtils.ConvertEmptyToNull(value); } } /// /// The directory to which outputs will be stored. /// [TaskAttribute("todir", Required=false)] public DirectoryInfo ToDirectory { get { return _toDir; } set { _toDir = value; } } /// /// Use each source file's directory as the current directory for /// resolving relative file paths. The default is . /// Only supported when targeting .NET 2.0 (or higher). /// [TaskAttribute("usesourcepath", Required=false)] public bool UseSourcePath { get { return _useSourcePath; } set { _useSourcePath = value; } } /// /// Takes a list of .resx or .txt files to convert to .resources files. /// [BuildElement("resources")] public ResourceFileSet Resources { get { return _resources; } set { _resources = value; } } /// /// Reference metadata from the specified assembly files. /// [BuildElement("assemblies")] public AssemblyFileSet Assemblies { get { return _assemblies; } set { _assemblies = value; } } /// /// Indicates whether assembly references are supported by the /// resgen tool for the current target framework. The default /// is . /// [FrameworkConfigurable("supportsassemblyreferences")] public bool SupportsAssemblyReferences { get { return _supportsAssemblyReferences; } set { _supportsAssemblyReferences = value; } } /// /// Indicates whether external file references are supported by the /// resgen tool for the current target framework. The default /// is . /// [FrameworkConfigurable("supportsexternalfilereferences")] public bool SupportsExternalFileReferences { get { return _supportsExternalFileReferences; } set { _supportsExternalFileReferences = value; } } /// /// For internal use only ! /// public ArrayList QualifiedResources { get { return _qualifiedResources; } } #endregion Public Instance Properties #region Private Instance Properties private bool RequiresAssemblyReferences { get { if (Resources.FileNames.Count > 0 || QualifiedResources.Count > 0) { foreach (string resourceFile in Resources.FileNames) { if (ReferencesThirdPartyAssemblies(resourceFile)) { return true; } } foreach (QualifiedResource resource in QualifiedResources) { if (ReferencesThirdPartyAssemblies(resource.Input.FullName)) { return true; } } } else if (InputFile != null) { return ReferencesThirdPartyAssemblies(InputFile.FullName); } return false; } } #endregion Private Instance Properties #region Override implementation of ExternalProgramBase /// /// Gets the working directory for the application. /// /// /// The working directory for the application. /// public override DirectoryInfo BaseDirectory { get { if (_workingDirectory == null) { return base.BaseDirectory; } return _workingDirectory; } set { _workingDirectory = value; } } /// /// Gets the command line arguments for the external program. /// /// /// The command line arguments for the external program. /// public override string ProgramArguments { get { return _arguments.ToString(); } } /// /// Gets the filename of the external program to start. /// /// /// The filename of the external program. /// /// /// Override in derived classes to explicitly set the location of the /// external tool. /// public override string ProgramFileName { get { if (_programFileName == null) { _programFileName = base.ProgramFileName; } return _programFileName; } } /// /// Updates the of the specified /// . /// /// The of which the should be updated. protected override void PrepareProcess(Process process) { if (!SupportsAssemblyReferences) { // avoid copying the assembly references (and resgen) to a // temporary directory if not necessary if (Assemblies.FileNames.Count == 0 || !RequiresAssemblyReferences) { // further delegate preparation to base class base.PrepareProcess(process); // no further processing required return; } // use a newly created temporary directory as working directory BaseDirectory = FileUtils.GetTempDirectory(); // create instance of Copy task CopyTask ct = new CopyTask(); // inherit project from current task ct.Project = Project; // inherit namespace manager from current task ct.NamespaceManager = NamespaceManager; // parent is current task ct.Parent = this; // inherit verbose setting from resgen task ct.Verbose = Verbose; // only output warning messages or higher, unless we're running // in verbose mode if (!ct.Verbose) { ct.Threshold = Level.Warning; } // make sure framework specific information is set ct.InitializeTaskConfiguration(); // set parent of child elements ct.CopyFileSet.Parent = ct; // inherit project from solution task for child elements ct.CopyFileSet.Project = ct.Project; // inherit namespace manager from solution task ct.CopyFileSet.NamespaceManager = ct.NamespaceManager; // set base directory of fileset ct.CopyFileSet.BaseDirectory = Assemblies.BaseDirectory; // copy all files to base directory itself ct.Flatten = true; // copy referenced assemblies foreach (string file in Assemblies.FileNames) { ct.CopyFileSet.Includes.Add(file); } // copy command line tool (and related files) to working directory, eg.: // /resgen.exe // /resgen.exe.manifest ct.CopyFileSet.Includes.Add(base.ProgramFileName + "*"); // set destination directory ct.ToDirectory = BaseDirectory; // increment indentation level ct.Project.Indent(); try { // execute task ct.Execute(); } finally { // restore indentation level ct.Project.Unindent(); } // change program to execute the tool in working directory as // that will allow this tool to resolve assembly references // using assemblies stored in the same directory _programFileName = Path.Combine(BaseDirectory.FullName, Path.GetFileName(base.ProgramFileName)); } // further delegate preparation to base class base.PrepareProcess(process); } /// /// Converts a single file or group of files. /// protected override void ExecuteTask() { // ensure base directory is set, even if fileset was not initialized // from XML if (Assemblies.BaseDirectory == null) { Assemblies.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } if (Resources.BaseDirectory == null) { Resources.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } // clear buffer _arguments.Length = 0; if (Resources.FileNames.Count > 0 || QualifiedResources.Count > 0) { if (OutputFile != null) { throw new BuildException(ResourceUtils.GetString("NA2026"), Location); } foreach (string fileName in Resources.FileNames) { FileInfo inputFile = new FileInfo(fileName); FileInfo outputFile = GetOutputFile(new FileInfo(Path.Combine( inputFile.DirectoryName, Resources.GetManifestResourceName(fileName)))); WriteCommandLineOptions(inputFile, outputFile); } // used by task foreach (QualifiedResource resource in QualifiedResources) { WriteCommandLineOptions(resource.Input, resource.Output); } } else { // Single file situation if (InputFile == null) { throw new BuildException(ResourceUtils.GetString("NA2027"), Location); } FileInfo outputFile = GetOutputFile(InputFile); if (NeedsCompiling(InputFile, outputFile)) { // ensure output directory exists if (!outputFile.Directory.Exists) { outputFile.Directory.Create(); } if (UseSourcePath) { if (SupportsExternalFileReferences) { _arguments.Append("/useSourcePath"); } else { Log(Level.Warning, ResourceUtils.GetString( "String_ResourceCompilerDoesNotSupportExternalReferences"), Project.TargetFramework.Description); } } _arguments.Append(string.Format(CultureInfo.InvariantCulture, " \"{0}\" \"{1}\"", InputFile.FullName, outputFile.FullName)); } } if (_arguments.Length != 0) { try { // call base class to do the work base.ExecuteTask(); } finally { // we only need to remove temporary directory if it was // actually created if (_workingDirectory != null) { // delete temporary directory and all files in it DeleteTask deleteTask = new DeleteTask(); deleteTask.Project = Project; deleteTask.Parent = this; deleteTask.InitializeTaskConfiguration(); deleteTask.Directory = _workingDirectory; deleteTask.Threshold = Level.None; // no output in build log deleteTask.Execute(); } } } } #endregion Override implementation of ExternalProgramBase #region Public Instance Methods /// /// Cleans up generated files. /// public void RemoveOutputs() { foreach (string filename in Resources.FileNames) { FileInfo outputFile = GetOutputFile(new FileInfo(Path.Combine( Path.GetDirectoryName(filename), Resources.GetManifestResourceName(filename)))); if (filename != outputFile.FullName) { outputFile.Delete(); } } foreach (QualifiedResource resource in QualifiedResources) { resource.Output.Delete(); } if (InputFile != null) { FileInfo outputFile = GetOutputFile(InputFile); if (InputFile.FullName != outputFile.FullName) { outputFile.Delete(); } } } #endregion Public Instance Methods #region Protected Instance Methods /// /// Determines whether the specified input file needs to be compiled. /// /// The input file. /// The output file. /// /// if the input file need to be compiled; /// otherwise . /// protected virtual bool NeedsCompiling(FileInfo inputFile, FileInfo outputFile) { if (!outputFile.Exists) { Log(Level.Verbose, ResourceUtils.GetString("String_OutputFileDoesNotExist"), outputFile.FullName); return true; } // check if input file was updated string fileName = FileSet.FindMoreRecentLastWriteTime(inputFile.FullName, outputFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, ResourceUtils.GetString("String_FileHasBeenUpdated"), fileName); return true; } // check if reference assemblies were updated fileName = FileSet.FindMoreRecentLastWriteTime(Assemblies.FileNames, outputFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, ResourceUtils.GetString("String_FileHasBeenUpdated"), fileName); return true; } // check if we're dealing with a resx file if (string.Compare(inputFile.Extension, ".resx", true, CultureInfo.InvariantCulture) == 0) { StringCollection externalFileReferences = GetExternalFileReferences(inputFile); if (externalFileReferences != null) { fileName = FileSet.FindMoreRecentLastWriteTime(externalFileReferences, outputFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, ResourceUtils.GetString("String_FileHasBeenUpdated"), fileName); return true; } } } // if we made it here then we don't have to recompile return false; } #endregion Protected Instance Methods #region Private Instance Methods /// /// Determines the full path and extension for the output file. /// /// The output file for which the full path and extension should be determined. /// /// The full path (with extensions) for the specified file. /// private FileInfo GetOutputFile(FileInfo file) { FileInfo outputFile; // if output is empty just change the extension if (OutputFile == null) { if (ToDirectory == null) { outputFile = file; } else { outputFile = new FileInfo(Path.Combine(ToDirectory.FullName, file.Name)); } outputFile = new FileInfo(Path.ChangeExtension(outputFile.FullName, TargetExt)); } else { outputFile = OutputFile; } return outputFile; } /// /// Determines whether the specified resource file references third /// party assemblies by checking whether a <data> element exists /// with a "type" attribute that does not start with /// "System.". /// /// The resource file to check. /// /// if the resource file references third party /// assemblies, or an error occurred; otherwise, . /// /// /// This check will only be accurate for 1.0 resource file, but the /// 2.0 resx files can only be compiled with a resgen tool that supports /// assembly references, so this method will not be used anyway. /// private bool ReferencesThirdPartyAssemblies(string resourceFile) { try { if (!File.Exists(resourceFile)) { return false; } // only resx files require assembly references if (string.Compare(Path.GetExtension(resourceFile), ".resx", true, CultureInfo.InvariantCulture) != 0) { return false; } using (StreamReader sr = new StreamReader(resourceFile, true)) { XPathDocument xpathDoc = new XPathDocument(new XmlTextReader(sr)); // determine the number of elements that either have // a "mimetype" attribute (meaning it contains a serialized // instance that might be of a referenced assembly) or a // "type" attribute with a value that does not start with // "System." and is not fully qualified int count = xpathDoc.CreateNavigator().Select("/root/data[@mimetype or (@type and not(starts-with(@type, 'System.') and contains(@type,'PublicKeyToken=')))]").Count; // if there are no elements of a third party type, we // assume that the resource file does not reference types from // third party assemblies return count > 0; } } catch (Exception) { // have the resgen tool deal with issues (eg. invalid xml) return true; } } /// /// Returns a list of external file references for the specified file. /// /// The resx file for which a list of external file references should be returned. /// /// A list of external file references for the specified file, or /// if does not /// exist or does not support external file references. /// private StringCollection GetExternalFileReferences(FileInfo resxFile) { if (!resxFile.Exists) { return null; } using (StreamReader sr = new StreamReader(resxFile.FullName, true)) { XPathDocument xpathDoc = new XPathDocument(new XmlTextReader(sr)); XPathNavigator xpathNavigator = xpathDoc.CreateNavigator(); // check resheader version xpathNavigator.Select("/root/resheader[@name = 'version']/value"); XPathNodeIterator nodeIterator = xpathNavigator.Select("/root/resheader[@name = 'version']/value"); if (nodeIterator.MoveNext()) { string version = nodeIterator.Current.Value; // 1.0 resx files do not support external file references if (version == "1.0.0.0") { return null; } } StringCollection externalFiles = new StringCollection(); string baseExternalFileDirectory = UseSourcePath ? resxFile.DirectoryName : Project.BaseDirectory; // determine the number of elements that have a "type" // attribute with a value that does not start with "System." XPathNodeIterator xfileIterator = xpathNavigator.Select("/root/data[@type = 'System.Resources.ResXFileRef, System.Windows.Forms']/value"); while (xfileIterator.MoveNext()) { string[] parts = xfileIterator.Current.Value.Split(';'); if (parts.Length <= 1) { continue; } externalFiles.Add(Path.Combine(baseExternalFileDirectory, parts[0])); } return externalFiles; } } private void WriteCommandLineOptions(FileInfo inputFile, FileInfo outputFile) { if (!NeedsCompiling(inputFile, outputFile)) { return; } // ensure output directory exists if (!outputFile.Directory.Exists) { outputFile.Directory.Create(); } string cmdLineArg = string.Format(CultureInfo.InvariantCulture, "\"{0},{1}\" ", inputFile, outputFile.FullName); // check if adding arguments to compile current resx to // total command line would cause it to exceed maximum // length bool maxCmdLineExceeded = (_arguments.Length + cmdLineArg.Length > _maxCmdLineLength); // if this is the first resx that we're compiling, or the // first one of the next execution of the resgen tool, then // add options to command line if (_arguments.Length == 0 || maxCmdLineExceeded) { StringBuilder sb = new StringBuilder (); // bug #1415272: first write assembly references, to make sure these // are taken into account when calculating the length of the command // line if (SupportsAssemblyReferences) { foreach (string assembly in Assemblies.FileNames) { sb.AppendFormat (CultureInfo.InvariantCulture, "/r:\"{0}\" ", assembly); } } if (UseSourcePath) { if (SupportsExternalFileReferences) { sb.Append ("/useSourcePath "); } else { Log(Level.Warning, ResourceUtils.GetString( "String_ResourceCompilerDoesNotSupportExternalReferences"), Project.TargetFramework.Description); } } sb.Append ("/compile "); sb.Append (cmdLineArg); cmdLineArg = sb.ToString (); } // if maximum length would have been exceeded by compiling // the current resx file, then first execute the resgen // tool if (maxCmdLineExceeded) { try { // call base class to do the work base.ExecuteTask(); } catch { // we only need to remove temporary directory when // an error occurred and if it was actually created if (_workingDirectory != null) { // delete temporary directory and all files in it DeleteTask deleteTask = new DeleteTask(); deleteTask.Project = Project; deleteTask.Parent = this; deleteTask.InitializeTaskConfiguration(); deleteTask.Directory = _workingDirectory; deleteTask.Threshold = Level.None; // no output in build log deleteTask.Execute(); } // rethrow exception throw; } // reset command line arguments as we've processed them _arguments.Length = 0; } // append command line arguments to compile current resx // file to the total command line _arguments.Append(cmdLineArg); } #endregion Private Instance Methods } /// /// For internal use only ! /// public class QualifiedResource { #region Private Instance Fields private FileInfo _inputFile; private FileInfo _outputFile; #endregion Private Instance Fields #region Public Instance Constructors /// /// Initializes a new instance of the /// class for a given input and output file. /// /// The resource to compile. /// The compiled resource. public QualifiedResource(FileInfo input, FileInfo output) { _inputFile = input; _outputFile = output; } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets the resource file to compile. /// /// /// The resource file to compile. /// public FileInfo Input { get { return _inputFile; } } /// /// Gets the compiled resource file. /// /// /// The compiled resource file. /// public FileInfo Output { get { return _outputFile; } } #endregion Public Instance Properties } } nant-0.92-rc1/src/NAnt.DotNet/Tasks/AssemblyLinkerTask.cs0000644000175000017500000007524011757302273023046 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Joe Jones (joejo@microsoft.com) // Gerry Shaw (gerry_shaw@yahoo.com) // Gert Driesen (drieseng@users.sourceforge.net) // Giuseppe Greco (giuseppe.greco@agamura.com) using System; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Text; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Types; using NAnt.Core.Util; using NAnt.DotNet.Types; namespace NAnt.DotNet.Tasks { /// /// Wraps al.exe, the assembly linker for the .NET Framework. /// /// /// /// All specified sources will be embedded using the /embed flag. /// Other source types are not supported. /// /// /// /// /// Create a library containing all icon files in the current directory. /// /// /// /// /// /// /// /// ]]> /// /// /// /// /// Create an executable assembly manifest from modules. /// /// /// /// /// /// /// /// /// ]]> /// /// [TaskName("al")] [ProgramLocation(LocationType.FrameworkDir)] public class AssemblyLinkerTask : NAnt.Core.Tasks.ExternalProgramBase { #region Private Instance Fields private string _responseFileName; private FileInfo _outputFile; private string _target; private string _algorithmID; private string _company; private string _configuration; private string _copyright; private string _culture; private DelaySign _delaySign; private string _description; private FileInfo _evidenceFile; private string _fileVersion; private string _flags; private string _keyContainer; private FileInfo _keyfile; private string _mainMethod; private ModuleSet _modules = new ModuleSet(); private string _product; private string _productVersion; private FileSet _resources = new FileSet(); private EmbeddedResourceCollection _embeddedResources = new EmbeddedResourceCollection(); private FileInfo _templateFile; private string _title; private string _trademark; private string _version; private FileInfo _win32Icon; private FileInfo _win32Res; // framework configuration settings private bool _supportsTemplate = true; #endregion Private Instance Fields #region Public Instance Properties /// /// Specifies an algorithm (in hexadecimal) to hash all files in a /// multifile assembly except the file that contains the assembly /// manifest. The default algorithm is CALG_SHA1. /// [TaskAttribute("algid", Required=false)] [Int32Validator(Base=16)] public string AlgorithmID { get { return _algorithmID; } set { _algorithmID = StringUtils.ConvertEmptyToNull(value); } } /// /// Specifies a string for the Company field in the assembly. /// /// /// A string for the Company field in the assembly. /// /// /// If is an empty string (""), the Win32 /// Company resource appears as a single space. /// [TaskAttribute("company", Required=false)] public string Company { get { return _company; } set { _company = value; } } /// /// Specifies a string for the Configuration field in the assembly. /// /// /// A string for the Configuration field in the assembly. /// /// /// If is an empty string (""), the Win32 /// Configuration resource appears as a single space. /// [TaskAttribute("configuration", Required=false)] public string Configuration { get { return _configuration; } set { _configuration = value; } } /// /// Specifies a string for the Copyright field in the assembly. /// /// /// A string for the Copyright field in the assembly. /// /// /// If is an empty string (""), the Win32 /// Copyright resource appears as a single space. /// [TaskAttribute("copyright", Required=false)] public string Copyright { get { return _copyright; } set { _copyright = value; } } /// /// The culture string associated with the output assembly. /// The string must be in RFC 1766 format, such as "en-US". /// /// /// /// Corresponds with the /c[ulture]: flag. /// /// [TaskAttribute("culture", Required=false)] public string Culture { get { return _culture; } set { _culture = StringUtils.ConvertEmptyToNull(value); } } /// /// Specifies whether the assembly should be partially signed. The default /// is . /// [TaskAttribute("delaysign", Required=false)] public DelaySign DelaySign { get { return _delaySign; } set { _delaySign = value; } } /// /// Specifies a string for the Description field in the assembly. /// /// /// A string for the Description field in the assembly. /// /// /// If is an empty string (""), the Win32 /// Description resource appears as a single space. /// [TaskAttribute("description", Required=false)] public string Description { get { return _description; } set { _description = value; } } /// /// Security evidence file to embed. /// /// /// The security evidence file to embed. /// /// /// /// Corresponds with the /e[vidence] flag. /// /// [TaskAttribute("evidence", Required=false)] public FileInfo EvidenceFile { get { return _evidenceFile; } set { _evidenceFile = value; } } /// /// Specifies a string for the File Version field in the assembly. /// /// /// A string for the File Version field in the assembly. /// [TaskAttribute("fileversion", Required=false)] public string FileVersion { get { return _fileVersion; } set { _fileVersion = StringUtils.ConvertEmptyToNull(value); } } /// /// Specifies a value (in hexadecimal) for the Flags field in /// the assembly. /// /// /// A value (in hexadecimal) for the Flags field in the assembly. /// [TaskAttribute("flags", Required=false)] [Int32Validator(Base=16)] public string Flags { get { return _flags; } set { _flags = StringUtils.ConvertEmptyToNull(value); } } /// /// Specifies a container that holds a key pair. /// [TaskAttribute("keycontainer")] public string KeyContainer { get { return _keyContainer; } set { _keyContainer = StringUtils.ConvertEmptyToNull(value); } } /// /// Specifies a file (filename) that contains a key pair or /// just a public key to sign an assembly. /// /// /// The complete path to the key file. /// /// /// /// Corresponds with the /keyf[ile]: flag. /// /// [TaskAttribute("keyfile", Required=false)] public FileInfo KeyFile { get { return _keyfile; } set { _keyfile = value; } } /// /// Specifies the fully-qualified name (class.method) of the method to /// use as an entry point when converting a module to an executable file. /// /// /// The fully-qualified name (class.method) of the method to use as an /// entry point when converting a module to an executable file. /// [TaskAttribute("main")] public string MainMethod { get { return _mainMethod; } set { _mainMethod = StringUtils.ConvertEmptyToNull(value); } } /// /// One or more modules to be compiled into an assembly. /// [BuildElement("modules")] public ModuleSet ModuleSet { get { return _modules; } set { _modules = value; } } /// /// The name of the output file for the assembly manifest. /// /// /// The complete output path for the assembly manifest. /// /// /// /// Corresponds with the /out flag. /// /// [TaskAttribute("output", Required=true)] public FileInfo OutputFile { get { return _outputFile; } set { _outputFile = value; } } /// /// The target type (one of lib, exe, or winexe). /// /// /// /// Corresponds with the /t[arget]: flag. /// /// [TaskAttribute("target", Required=true)] [StringValidator(AllowEmpty=false)] public string OutputTarget { get { return _target; } set { _target = StringUtils.ConvertEmptyToNull(value); } } /// /// Specifies a string for the Product field in the assembly. /// /// /// A string for the Product field in the assembly. /// [TaskAttribute("product", Required=false)] public string Product { get { return _product; } set { _product = value; } } /// /// Specifies a string for the Product Version field in the assembly. /// /// /// A string for the Product Version field in the assembly. /// [TaskAttribute("productversion", Required=false)] public string ProductVersion { get { return _productVersion; } set { _productVersion = StringUtils.ConvertEmptyToNull(value); } } /// /// The set of resources to embed. /// [BuildElement("sources")] public FileSet Resources { get { return _resources; } set { _resources = value; } } /// /// The set of compiled resources to embed. /// /// /// Do not yet expose this to build authors. /// public EmbeddedResourceCollection EmbeddedResources { get { return _embeddedResources; } set { _embeddedResources = value; } } /// /// Indicates whether the assembly linker for a given target framework /// supports the "template" option, which takes an assembly from which /// to get all options except the culture field. /// The default is . /// /// /// TODO: remove this once Mono bug #74814 is fixed. /// [FrameworkConfigurable("supportstemplate")] public bool SupportsTemplate { get { return _supportsTemplate; } set { _supportsTemplate = value; } } /// /// Specifies an assembly from which to get all options except the /// culture field. /// /// /// The complete path to the assembly template. /// /// /// /// Corresponds with the /template: flag. /// /// [TaskAttribute("template", Required=false)] public FileInfo TemplateFile { get { return _templateFile; } set { _templateFile = value; } } /// /// Specifies a string for the Title field in the assembly. /// /// /// A string for the Title field in the assembly. /// [TaskAttribute("title", Required=false)] public string Title { get { return _title; } set { _title = value; } } /// /// Specifies a string for the Trademark field in the assembly. /// /// /// A string for the Trademark field in the assembly. /// [TaskAttribute("trademark", Required=false)] public string Trademark { get { return _trademark; } set { _trademark = value; } } /// /// Specifies version information for the assembly. The format of the /// version string is major.minor.build.revision. /// [TaskAttribute("version", Required=false)] public string Version { get { return _version; } set { _version = StringUtils.ConvertEmptyToNull(value); } } /// /// Icon to associate with the assembly. /// [TaskAttribute("win32icon", Required=false)] public FileInfo Win32Icon { get { return _win32Icon; } set { _win32Icon = value; } } /// /// Inserts a Win32 resource (.res file) in the output file. /// [TaskAttribute("win32res", Required=false)] public FileInfo Win32Res { get { return _win32Res; } set { _win32Res = value; } } #endregion Public Instance Properties #region Override implementation of ExternalProgramBase /// /// Gets the command-line arguments for the external program. /// /// /// The command-line arguments for the external program or /// if the task is not being executed. /// public override string ProgramArguments { get { if (_responseFileName != null) { return "@" + "\"" + _responseFileName + "\""; } else { return null; } } } /// /// Generates an assembly manifest. /// protected override void ExecuteTask() { // ensure base directory is set, even if fileset was not initialized // from XML if (Resources.BaseDirectory == null) { Resources.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } // ensure base directory is set, even if fileset was not initialized // from XML if (ModuleSet.Dir == null) { ModuleSet.Dir = new DirectoryInfo(Project.BaseDirectory); } if (NeedsCompiling()) { // create temp response file to hold compiler options _responseFileName = Path.GetTempFileName(); StreamWriter writer = new StreamWriter(_responseFileName); try { Log(Level.Info, ResourceUtils.GetString("String_CompilingFiles"), Resources.FileNames.Count + EmbeddedResources.Count + ModuleSet.Modules.Count, OutputFile.FullName); // write modules to compile into assembly foreach (Module module in ModuleSet.Modules) { writer.WriteLine("\"{0}\"", module.ToString()); } // write output target writer.WriteLine("/target:\"{0}\"", OutputTarget); // write output file writer.WriteLine("/out:\"{0}\"", OutputFile.FullName); // algorithm (in hexadecimal) if (AlgorithmID != null) { writer.WriteLine("/algid:\"{0}\"", AlgorithmID); } // company field if (Company != null) { writer.WriteLine("/company:\"{0}\"", Company); } // configuration field if (Configuration != null) { writer.WriteLine("/configuration:\"{0}\"", Configuration); } // copyright field if (Copyright != null) { writer.WriteLine("/copyright:\"{0}\"", Copyright); } // write culture associated with output assembly if (Culture != null) { writer.WriteLine("/culture:\"{0}\"", Culture); } // delay sign the assembly switch (DelaySign) { case DelaySign.NotSet: break; case DelaySign.Yes: writer.WriteLine("/delaysign+"); break; case DelaySign.No: writer.WriteLine("/delaysign-"); break; default: throw new BuildException (string.Format (CultureInfo.InvariantCulture, "Value {0} is not supported for \"delaysign\".", DelaySign), Location); } // description field if (Description != null) { writer.WriteLine("/description:\"{0}\"", Description); } // write path to security evidence file if (EvidenceFile != null) { writer.WriteLine("/evidence:\"{0}\"", EvidenceFile.FullName); } // file version field if (FileVersion != null) { writer.WriteLine("/fileversion:\"{0}\"", FileVersion); } // flags field if (Flags != null) { writer.WriteLine("/flags:\"{0}\"", Flags); } // main method if (MainMethod != null) { writer.WriteLine("/main:\"{0}\"", MainMethod); } // keycontainer if (KeyContainer != null) { writer.WriteLine("/keyname:\"{0}\"", KeyContainer); } // product field if (Product != null) { writer.WriteLine("/product:\"{0}\"", Product); } // product version field if (ProductVersion != null) { writer.WriteLine("/productversion:\"{0}\"", ProductVersion); } // write path to template assembly if (TemplateFile != null) { if (SupportsTemplate) { writer.WriteLine("/template:\"{0}\"", TemplateFile.FullName); } else { Log(Level.Warning, ResourceUtils.GetString("String_LinkerDoesNotSupportTemplateAssembly"), Project.TargetFramework.Description); } } // title field if (Title != null) { writer.WriteLine("/title:\"{0}\"", Title); } // trademark field if (Trademark != null) { writer.WriteLine("/trademark:\"{0}\"", Trademark); } // key file if (KeyFile != null) { writer.WriteLine("/keyfile:\"{0}\"", KeyFile.FullName); } // assembly version if (Version != null) { writer.WriteLine("/version:\"{0}\"", Version); } // win32 icon if (Win32Icon != null) { writer.WriteLine("/win32icon:\"{0}\"", Win32Icon.FullName); } // win32 resource if (Win32Res != null) { writer.WriteLine("/win32res:\"{0}\"", Win32Res.FullName); } // write embedded resources to response file foreach (string resourceFile in Resources.FileNames) { writer.WriteLine("/embed:\"{0}\"", resourceFile); } // write embedded resources to response file foreach (EmbeddedResource embeddedResource in EmbeddedResources) { writer.WriteLine("/embed:\"{0}\",{1}", embeddedResource.File, embeddedResource.ManifestResourceName); } // suppresses display of the sign-on banner writer.WriteLine("/nologo"); // make sure to close the response file otherwise contents // Will not be written to disk and ExecuteTask() will fail. writer.Close(); if (Verbose) { // display response file contents Log(Level.Verbose, ResourceUtils.GetString("String_ContentsOf"), _responseFileName); StreamReader reader = File.OpenText(_responseFileName); Log(Level.Verbose, reader.ReadToEnd()); reader.Close(); } // call base class to do the work base.ExecuteTask(); } finally { // make sure stream is closed or response file cannot be deleted writer.Close(); // make sure we delete response file even if an exception is thrown File.Delete(_responseFileName); // initialize name of response file _responseFileName = null; } } } #endregion Override implementation of ExternalProgramBase #region Protected Instance Methods /// /// Determines whether the assembly manifest needs compiling or is /// uptodate. /// /// /// if the assembly manifest needs compiling; /// otherwise, . /// protected virtual bool NeedsCompiling() { if (!OutputFile.Exists) { Log(Level.Verbose, ResourceUtils.GetString("String_OutputFileDoesNotExist"), OutputFile.FullName); return true; } string fileName = null; // check if modules were updated foreach (Module module in ModuleSet.Modules) { fileName = FileSet.FindMoreRecentLastWriteTime(module.File, OutputFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, ResourceUtils.GetString("String_FileHasBeenUpdated"), fileName); return true; } } // check if (embedded)resources were updated fileName = FileSet.FindMoreRecentLastWriteTime(Resources.FileNames, OutputFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, ResourceUtils.GetString("String_FileHasBeenUpdated"), fileName); return true; } // check if evidence file was updated if (EvidenceFile != null) { fileName = FileSet.FindMoreRecentLastWriteTime(EvidenceFile.FullName, OutputFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, ResourceUtils.GetString("String_FileHasBeenUpdated"), fileName); return true; } } // check if template file was updated if (TemplateFile != null) { fileName = FileSet.FindMoreRecentLastWriteTime(TemplateFile.FullName, OutputFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, ResourceUtils.GetString("String_FileHasBeenUpdated"), fileName); return true; } } // check if key file was updated if (KeyFile != null) { fileName = FileSet.FindMoreRecentLastWriteTime(KeyFile.FullName, OutputFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, ResourceUtils.GetString("String_FileHasBeenUpdated"), fileName); return true; } } // check if win32 icon file was updated if (Win32Icon != null) { fileName = FileSet.FindMoreRecentLastWriteTime(Win32Icon.FullName, OutputFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, ResourceUtils.GetString("String_FileHasBeenUpdated"), fileName); return true; } } // check if win32 resource file was updated if (Win32Res != null) { fileName = FileSet.FindMoreRecentLastWriteTime(Win32Res.FullName, OutputFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, ResourceUtils.GetString("String_FileHasBeenUpdated"), fileName); return true; } } // check if embedded resource files were updated foreach (EmbeddedResource embeddedResource in EmbeddedResources) { fileName = FileSet.FindMoreRecentLastWriteTime(embeddedResource.File, OutputFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, ResourceUtils.GetString("String_FileHasBeenUpdated"), fileName); return true; } } // check the arguments for /embed or /embedresource options StringCollection embeddedResourceFiles = new StringCollection(); foreach (Argument argument in Arguments) { if (argument.IfDefined && !argument.UnlessDefined) { string argumentValue = argument.Value; // check whether argument specifies resource file to embed if (argumentValue != null && (argumentValue.StartsWith("/embed:") || argumentValue.StartsWith("/embedresource:"))) { // determine path to resource file string path = argumentValue.Substring(argumentValue.IndexOf(':') + 1); int indexOfComma = path.IndexOf(','); if (indexOfComma != -1) { path = path.Substring(0, indexOfComma); } bool isQuoted = path.Length > 2 && path.StartsWith("\"") && path.EndsWith("\""); if (isQuoted) { path = path.Substring(1, path.Length - 2); } // resolve path to full path (relative to project base dir) path = Project.GetFullPath(path); // add path to collection of resource files embeddedResourceFiles.Add(path); } } } // check if embedded resources passed as arguments were updated fileName = FileSet.FindMoreRecentLastWriteTime(embeddedResourceFiles, OutputFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, ResourceUtils.GetString("String_FileHasBeenUpdated"), fileName); return true; } // if we made it here then we don't have to recompile return false; } #endregion Protected Instance Methods } } nant-0.92-rc1/src/NAnt.DotNet/NAnt.DotNet.csproj0000644000175000017500000001336711757302273021143 0ustar jtaylorjtaylor Debug AnyCPU 2.0 {B50A1067-785B-4686-8FFC-5AF424BEF163} NAnt.DotNet NAnt.DotNetTasks Library OnSuccessfulBuild false 8.0.50727 v2.0 2.0 publish\ true Disk false Foreground 7 Days false false true 0 1.0.0.%2a false false true true full false 4 ..\..\build\Debug\ AllRules.ruleset TRACE;DEBUG ..\..\build\Debug\NAnt.DotNetTasks.xml true pdbonly true ..\..\build\Release\ 4 AllRules.ruleset TRACE ..\..\build\Release\NAnt.DotNetTasks.xml ..\..\lib\common\neutral\NDoc.Core.dll CommonAssemblyInfo.cs False .NET Framework 3.5 SP1 Client Profile false False .NET Framework 3.5 SP1 true False Windows Installer 3.1 true {8F5F8375-4097-4952-B860-784EB9961ABE} NAnt.Core nant-0.92-rc1/src/NAnt.DotNet/NAnt.DotNet.build0000644000175000017500000000313211757302273020727 0ustar jtaylorjtaylor nant-0.92-rc1/src/NAnt.SourceControl/0000755000175000017500000000000011757310030017245 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.SourceControl/AssemblyInfo.cs0000644000175000017500000000233211757302274022202 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Scott Hernandez (ScottHernandez@hotmail.com) // Gert Driesen (drieseng@users.sourceforge.net) using System.Reflection; // This will not compile with Visual Studio. If you want to build a signed // executable use the NAnt build file. To build under Visual Studio just // exclude this file from the build. [assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile(@"..\NAnt.key")] [assembly: AssemblyKeyName("")]nant-0.92-rc1/src/NAnt.SourceControl/Types/0000755000175000017500000000000011757310030020351 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.SourceControl/Types/CvsFileSet.cs0000644000175000017500000000742511757302274022732 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2005 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Clayton Harbour (claytonharbour@sporadicism.com) using System; using System.Collections; using System.IO; using System.Xml; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Types; using NAnt.Core.Util; using NAnt.SourceControl.Tasks; namespace NAnt.SourceControl.Types { /// /// A is a with extra /// attributes useful in the context of the . /// [ElementName("cvsfileset")] public class CvsFileSet : FileSet { #region Private Instance Fields private bool _useCvsIgnore = true; #endregion Private Instance Fields #region Public Instance Properties /// /// Indicates whether the entires in the .cvsignore should be used to limit the /// file list; to exclude files in .cvsignore, otherwise /// . The default is . /// [TaskAttribute("usecvsignore", Required=false)] public bool UseCvsIgnore{ get { return this._useCvsIgnore; } set { this._useCvsIgnore = value; } } #endregion Public Instance Properties #region Override Implementation of Element /// /// Initialize the object and locate the .cvsignore /// files to add to the exclude list. /// protected override void Initialize() { if (UseCvsIgnore) { ArrayList ignoreFiles = new ArrayList(); this.ScanCvsIgnores(base.BaseDirectory, ignoreFiles); foreach (string ignoreFile in ignoreFiles) { Excludes.Add(ignoreFile); } } base.Initialize(); } #endregion Override Implementation of Element #region Private Instance Methods private void ScanCvsIgnores(DirectoryInfo dir, ArrayList ignoreFiles) { foreach (FileInfo file in dir.GetFiles("*.cvsignore")) { AddCvsIgnores(file, ignoreFiles); } foreach (DirectoryInfo subDir in dir.GetDirectories()) { this.ScanCvsIgnores(subDir, ignoreFiles); } } private void AddCvsIgnores(FileInfo file, ArrayList ignoreFiles) { using (StreamReader reader = new StreamReader(file.FullName)) { string line; while ((line = reader.ReadLine()) != null) { // if the .cvsignore is at the start of the file then // exclude a *.[extension] pattern if (line.IndexOf(".") == 0) { ignoreFiles.Add(Path.Combine(file.DirectoryName, "*" + line)); } else { ignoreFiles.Add(Path.Combine(file.DirectoryName, line)); } } } } #endregion Private Instance Methods } } nant-0.92-rc1/src/NAnt.SourceControl/NAnt.SourceControl.build0000644000175000017500000000271011757302274023741 0ustar jtaylorjtaylor nant-0.92-rc1/src/NAnt.SourceControl/Tasks/0000755000175000017500000000000011757310030020332 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.SourceControl/Tasks/CheckoutTask.cs0000644000175000017500000001432711757302274023273 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Clayton Harbour (claytonharbour@sporadicism.com) using System; using System.Globalization; using NAnt.Core.Attributes; using NAnt.Core.Tasks; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.SourceControl.Tasks { /// /// Checks out a CVS module to the required directory. /// /// /// Checkout NAnt. /// /// /// ]]> /// /// /// /// /// Checkout NAnt revision named 0_85 to the /// folder c:\src\nant\v0.85. /// /// /// /// ]]> /// /// So the nant module tagged with revision 0_85 will be checked /// out in the folder v0.85 under the working/ destination directory. ///
This could be used to work on different /// branches of a repository at the same time.
///
/// /// /// Checkout NAnt with specified revision date to the /// folder c:\src\nant\2003_08_16. /// /// /// /// ]]> /// /// [TaskName("cvs-checkout")] public class CheckoutTask : AbstractCvsTask { #region Internal Static Fields /// /// The command being executed. /// internal const string CvsCommandName = "checkout"; #endregion Internal Static Fields #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public CheckoutTask() { } #endregion Public Instance Constructors #region Public Instance Properties /// /// Specify the revision to checkout. This corresponds to the "sticky-tag" /// of the file. /// [TaskAttribute("revision", Required=false)] [StringValidator(AllowEmpty=true, Expression=@"^[A-Za-z0-9][A-Za-z0-9._\-]*$")] public string Revision { get { if (CommandOptions.ContainsKey("revision")) { return ((Option)CommandOptions["revision"]).Value; } return null; } set { if (String.IsNullOrEmpty(value)) { CommandOptions.Remove("revision"); } else { SetCommandOption("revision", string.Format(CultureInfo.InvariantCulture, "-r {0}", value), true); } } } /// /// Sticky tag or revision to checkout. /// [TaskAttribute("sticky-tag", Required=false)] [StringValidator(AllowEmpty=true, Expression=@"^[A-Za-z0-9][A-Za-z0-9._\-]*$")] public string StickyTag { get { return Revision; } set { Revision = value; } } /// /// Specify the revision date to checkout. The date specified is validated /// and then passed to the cvs binary in a standard format recognized by /// cvs. /// [TaskAttribute("date", Required=false)] [DateTimeValidator()] public DateTime Date { get { return Convert.ToDateTime(((Option)CommandOptions["date"]).Value); } set { SetCommandOption("date", String.Format(CultureInfo.InvariantCulture,"-D \"{0}\"", ToCvsDateTimeString(value)), true); } } /// /// Specify a directory name to replace the module name. Valid names /// include any valid filename, excluding path information. /// [TaskAttribute("overridedir", Required=false)] [StringValidator(AllowEmpty=false)] public string OverrideDir { get { return ((Option)CommandOptions["overridedir"]).Value; } set { SetCommandOption("overridedir", String.Format(CultureInfo.InvariantCulture,"-d{0}", value), true); } } /// /// Specify a directory name to replace the module name. Valid names /// include any valid filename, excluding path information. /// [TaskAttribute("override-directory", Required=false)] public string OverrideDirectory { get { return OverrideDir; } set { OverrideDir = value; } } #endregion #region Override implementation of AbstractCvsTask /// /// The name of the cvs command that is going to be executed. /// public override string CommandName { get { return CvsCommandName; } } #endregion Override implementation of AbstractCvsTask } } nant-0.92-rc1/src/NAnt.SourceControl/Tasks/AbstractSourceControlTask.cs0000644000175000017500000004451011757302274026010 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Clayton Harbour (claytonharbour@sporadicism.com) using System; using System.Collections; using System.Diagnostics; using System.IO; using System.Text; using System.Globalization; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Tasks; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.SourceControl.Tasks { /// /// A base class for creating tasks for executing CVS client commands on a /// CVS repository. /// public abstract class AbstractSourceControlTask : ExternalProgramBase { #region Protected Static Fields /// /// Name of the environmental variable specifying a users' home /// in a *nix environment. /// protected const String EnvHome = "HOME"; /// /// Used on windows to specify the location of application data. /// protected const string AppData = "APPDATA"; /// /// The environment variable that holds path information. /// protected const String PathVariable = "PATH"; /// /// The environment variable that holds the location of the /// .cvspass file. /// protected const string CvsPassFileVariable = "CVS_PASSFILE"; /// /// Property name used to specify the source control executable. This is /// used as a readonly property. /// protected const string PropExeName = "sourcecontrol.exename"; #endregion #region Private Instance Fields private string _exeName; private string _root; private DirectoryInfo _destinationDirectory; private string _password; private FileInfo _passFile; private string _commandName; private string _commandLine = null; private Hashtable _commandOptions = new Hashtable(); private string _commandLineArguments; private Hashtable _globalOptions = new Hashtable(); private FileInfo _ssh; private FileSet _fileset = new FileSet(); #endregion Private Instance Fields #region Private Static Fields private static readonly log4net.ILog Logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion Private Static Fields #region Protected Instance Constructors /// /// Initializes a new instance of the /// class. /// protected AbstractSourceControlTask () : base() { } #endregion Protected Instance Constructors #region Protected Instance Properties /// /// The name of the passfile, overriden for each version control system (VCS). /// protected abstract string PassFileName {get;} /// /// The path to the specific home directory of the version control system, /// this can be where the binary files are kept, or other app /// information. /// protected DirectoryInfo VcsHome { get { string vcsHome = Environment.GetEnvironmentVariable(VcsHomeEnv); if (null != vcsHome) { if (Directory.Exists(vcsHome)) { return new DirectoryInfo(vcsHome); } } return null; } } /// /// The environment variable that defines where the version control system /// (VCS) home variable is kept. /// protected abstract string VcsHomeEnv {get;} /// /// The name of the version control system (VCS) executable file. /// protected abstract string VcsExeName {get;} #endregion #region Public Instance Properties /// /// /// The root variable contains information on how to locate a repository. /// Although this information is in different formats it typically must /// define the following: /// /// server location /// protocol used to communicate with the repository /// repository location on the server /// project location in the repository /// /// /// [StringValidator(AllowEmpty=false)] public virtual string Root { get {return _root;} set {_root = value;} } /// /// Destination directory for the local sandbox. If destination is not specified /// then the current directory is used. /// /// /// Root path of the local sandbox. /// /// /// /// Root path of the local sandbox. /// /// [TaskAttribute("destination", Required=false)] public virtual DirectoryInfo DestinationDirectory { get { if (null == this._destinationDirectory) { this._destinationDirectory = new DirectoryInfo(Environment.CurrentDirectory); } return this._destinationDirectory; } set { this._destinationDirectory = value; } } /// /// The password for logging in to the repository. /// /// /// The password for logging in to the repository. /// [TaskAttribute("password", Required=false)] [Obsolete("Use task instead.", true)] public virtual string Password { get { return _password;} set { _password = StringUtils.ConvertEmptyToNull(value); } } /// /// The full path to the cached password file. If not specified then the /// environment variables are used to try and locate the file. /// [TaskAttribute("passfile")] public virtual FileInfo PassFile { get { return _passFile; } set { _passFile = value; } } /// /// Holds a collection of globally available options. /// public Hashtable GlobalOptions { get {return _globalOptions;} set {_globalOptions = value;} } /// /// A collection of options that can be used to modify the default behavoir /// of the version control commands. See the sub-tasks for implementation /// specifics. /// public Hashtable CommandOptions { get { return _commandOptions;} set { _commandOptions = value; } } /// /// Command-line arguments for the program. The command line arguments are used to specify /// any cvs command options that are not available as attributes. These are appended /// after the command itself and are additive to whatever attributes are currently specified. /// /// /// <cvs-checkout cvsroot=":pserver:anonymous@cvs.sourceforge.net:/cvsroot/nant" /// module="nant" /// destination="e:\test\merillcornish\working" /// readonly="true" /// quiet="true" /// commandline="-n" /// cvsfullpath="C:\Program Files\TortoiseCVS\cvs.exe" /// /> ///
/// Produces the cvs command: /// c:\Program Files\TortoiseCVS\cvs.exe -d:pserver:anonymous@cvs.sourceforge.net:/cvsroot/nant -q checkout -n nant ///
[TaskAttribute("commandline")] public string CommandLineArguments { get {return _commandLineArguments;} set {_commandLineArguments = StringUtils.ConvertEmptyToNull(value);} } /// /// The name of the command that is going to be executed. /// public virtual string CommandName { get {return _commandName;} set {_commandName = value;} } /// /// Used to specify the version control system (VCS) files that are going /// to be acted on. /// [BuildElement("fileset")] public virtual FileSet VcsFileSet { get { return _fileset; } set { _fileset = value; } } /// /// The executable to use for ssh communication. /// [TaskAttribute("ssh", Required=false)] public virtual FileInfo Ssh { get {return _ssh;} set {_ssh = value;} } #endregion Public Instance Properties #region Protected Instance Properties /// /// The environment name for the ssh variable. /// protected abstract string SshEnv { get; } #endregion Protected Instance Properties #region Override implementation of ExternalProgramBase /// /// The name of the version control system executable. /// public override string ExeName { get {return _exeName;} set {_exeName = value;} } /// /// Get the command line arguments for the task. /// public override string ProgramArguments { get {return _commandLine;} } /// /// Build up the command line arguments, determine which executable is being /// used and find the path to that executable and set the working /// directory. /// /// The process to prepare. protected override void PrepareProcess (Process process) { base.PrepareProcess(process); SetEnvironment(process); } #endregion Override implementation of ExternalProgramBase #region Protected Instance Methods /// /// Adds a new global option if none exists. If one does exist then /// the use switch is toggled on or of. /// /// The common name of the option. /// The option value or command line switch /// of the option. /// true if the option should be /// appended to the commandline, otherwise false. protected void SetGlobalOption (String name, String value, bool on) { Option option; Log(Level.Debug, "Name: {0}", name); Log(Level.Debug, "Value: {0}",value); Log(Level.Debug, "On: {0}", on); if (GlobalOptions.Contains(name)) { option = (Option)GlobalOptions[name]; } else { option = new Option(); option.OptionName = name; option.Value = value; GlobalOptions.Add(option.OptionName, option); } option.IfDefined = on; } /// /// Adds a new command option if none exists. If one does exist then /// the use switch is toggled on or of. /// /// The common name of the option. /// The option value or command line switch /// of the option. /// true if the option should be /// appended to the commandline, otherwise false. protected void SetCommandOption (String name, String value, bool on) { Option option; if (CommandOptions.Contains(name)) { option = (Option)CommandOptions[name]; } else { option = new Option(); option.OptionName = name; option.Value = value; CommandOptions.Add(name, option); } option.IfDefined = on; } /// /// Set up the environment variables for a process. /// /// A process to setup. protected virtual void SetEnvironment (Process process) { if (Ssh != null && !Ssh.Exists) { FileInfo tempLookup = DeriveFullPathFromEnv(PathVariable, Ssh.Name); if (null == tempLookup) { tempLookup = DeriveFullPathFromEnv(PathVariable, Ssh.Name + ".exe"); } if (null != tempLookup) { Ssh = tempLookup; } } if (Ssh != null) { try { process.StartInfo.EnvironmentVariables.Add(SshEnv, Ssh.FullName); } catch (System.ArgumentException e) { Logger.Warn("Possibility cvs_rsh key has already been added.", e); } } if (null != this.PassFile) { if (process.StartInfo.EnvironmentVariables.ContainsKey(CvsPassFileVariable)) { process.StartInfo.EnvironmentVariables[CvsPassFileVariable] = this.PassFile.FullName; } else { process.StartInfo.EnvironmentVariables.Add(CvsPassFileVariable, PassFile.FullName); } } Log(Level.Verbose, "Using ssh binary: {0}", process.StartInfo.EnvironmentVariables[SshEnv]); Log(Level.Verbose, "Using .cvspass file: {0}", process.StartInfo.EnvironmentVariables[CvsPassFileVariable]); } /// /// Append the files specified in the fileset to the command line argument. /// Files are changed to use a relative path from the working directory /// that the task is spawned in. /// protected void AppendFiles () { foreach (string pathname in VcsFileSet.FileNames) { string relativePath = pathname.Replace(DestinationDirectory.FullName, ""); if (relativePath.IndexOf('/') == 0 || relativePath.IndexOf('\\') == 0) { relativePath = relativePath.Substring(1, relativePath.Length - 1); } relativePath = relativePath.Replace("\\", "/"); Arguments.Add(new Argument("\"" + relativePath + "\"")); } } /// /// Derive the location of the version control system from the environment /// variable PATH. /// /// The file information of the version control system, /// or null if this cannot be found. protected FileInfo DeriveVcsFromEnvironment () { FileInfo vcsFile = DeriveFullPathFromEnv(VcsHomeEnv, VcsExeName); if (null == vcsFile) { vcsFile = DeriveFullPathFromEnv(PathVariable, VcsExeName); } return vcsFile; } #endregion Protected Instance Methods #region Private Instance Methods private FileInfo DeriveFullPathFromEnv(string environmentVar, string fileName) { string environmentValue = StringUtils.ConvertEmptyToNull( System.Environment.GetEnvironmentVariable(environmentVar)); Log(Level.Debug, "Environment variable: {0}", environmentVar); Log(Level.Debug, "Environment value: {0}", environmentValue); if (environmentValue != null) { string[] environmentPaths = environmentValue.Split(Path.PathSeparator); foreach (string environmentPath in environmentPaths) { if (environmentPath == null) { continue; } // remove leading or trailing quotes, which are valid for // individual entries in PATH but are considered invalid // path characters string cleanPath = environmentPath.Trim('\"'); Log(Level.Debug, "Environment Path: {0}", cleanPath); Log(Level.Debug, "FileName: {0}", fileName); string fileFullName = Path.Combine(cleanPath, fileName); Log(Level.Debug, "FileFullName: {0}", fileFullName); if (environmentPath.IndexOf(fileName) > -1 && File.Exists(fileName)) { if (!(Path.GetDirectoryName(fileName).IndexOf( Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory)) > 1)) { return new FileInfo(fileName); } } if (fileFullName.IndexOf(fileName) > -1 && File.Exists(fileFullName)) { if (Path.GetDirectoryName(fileFullName).IndexOf( Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory)) == -1) { return new FileInfo(fileFullName); } } } } return null; } #endregion Private Instance Methods } }nant-0.92-rc1/src/NAnt.SourceControl/Tasks/CvsPass.cs0000644000175000017500000001156211757302274022263 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Clayton Harbour (claytonharbour@sporadicism.com) using System; using System.Text; using System.IO; using System.Diagnostics; using System.Xml; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Tasks; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.SourceControl.Tasks { /// /// Executes the cvs login command which appends or updates an entry to the /// specified .cvspass file. /// /// /// Update .cvspass file to include the NAnt anonymous login. /// /// /// ]]> /// /// [TaskName("cvs-pass")] public class CvsPass : Task { #region Private Instance Fields private string _password; private FileInfo _passFile; private string _cvsRoot; #endregion Private Instance Fields #region Public Instance Properties /// /// Password to append or update to the .cvspass file. /// [TaskAttribute("password", Required=true)] public string Password { get { return _password; } set { _password = value; } } /// /// The full path to the .cvspass file. The default is ~/.cvspass. /// /// [TaskAttribute("passfile", Required=false)] public FileInfo PassFile { get { return this._passFile; } set { this._passFile = value; } } /// /// The current working directory. /// public virtual DirectoryInfo DestinationDirectory { get { return new DirectoryInfo(Environment.CurrentDirectory); } } /// /// The repository root string. /// [TaskAttribute("cvsroot", Required=false)] [StringValidator(AllowEmpty=false)] public string Root { get { return this._cvsRoot; } set { this._cvsRoot = value; } } #endregion Public Instance Properties #region Override implementation of Task /// /// Ensures all information is available to execute the . /// protected override void Initialize() { // ensure passfile was either set by user or could be discovered from // environment or located in HOME directory if (PassFile == null) { throw new BuildException("'passfile' was not explicitly specified" + " and could not be determined from environment, or found in" + " home directory.", Location); } } /// /// Update the .cvspass file with the given password. If the passfile /// is not specified then the default search locations are used: /// /// CVS_PASSFILE/.cvspass /// HOME/.cvspass /// USERPROFILE/.cvspass TODO: Confirm that this is valid /// behavior or if it is going to give problems with the /// cvsnt implementation. /// /// protected override void ExecuteTask () { ICSharpCode.SharpCvsLib.FileSystem.Manager manager = new ICSharpCode.SharpCvsLib.FileSystem.Manager(this.DestinationDirectory); if (this.PassFile == null) { manager.UpdatePassFile(this.Password, new ICSharpCode.SharpCvsLib.Misc.CvsRoot(this.Root)); } else { Log(Level.Verbose, "Updating .cvspass file '{0}'.", this.PassFile.FullName); manager.UpdatePassFile(this.Password, new ICSharpCode.SharpCvsLib.Misc.CvsRoot(this.Root), this.PassFile); } } #endregion Override implementation of Task } } nant-0.92-rc1/src/NAnt.SourceControl/Tasks/CvsTask.cs0000644000175000017500000000547211757302274022262 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Clayton Harbour (claytonharbour@sporadicism.com) using NAnt.Core.Attributes; namespace NAnt.SourceControl.Tasks { /// /// Executes the cvs command specified by the command attribute. /// /// /// Checkout NAnt. /// /// /// ]]> /// /// [TaskName("cvs")] public class CvsTask : AbstractCvsTask { #region Private Instance Fields private string _commandName; #endregion Private Instance Fields #region Override implementation of AbstractCvsTask /// /// The cvs command to execute. /// [TaskAttribute("command", Required=true)] public override string CommandName { get { return _commandName; } set { _commandName = value; } } /// /// Specify if the module is needed for this cvs command. /// protected override bool IsModuleNeeded { get { bool moduleNeeded; switch (this.CommandName) { case CheckoutTask.CvsCommandName: moduleNeeded = true; break; case UpdateTask.CvsCommandName: moduleNeeded = false; break; case "commit": moduleNeeded = false; break; case TagTask.CvsCommandName: moduleNeeded = false; break; default: moduleNeeded = true; break; } return moduleNeeded; } } #endregion Override implementation of AbstractCvsTask } } nant-0.92-rc1/src/NAnt.SourceControl/Tasks/RTagTask.cs0000644000175000017500000002031311757302274022353 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Clayton Harbour (claytonharbour@sporadicism.com) using System; using System.Globalization; using NAnt.Core.Tasks; using NAnt.Core.Attributes; using NAnt.Core.Util; using NAnt.Core.Types; namespace NAnt.SourceControl.Tasks { /// /// Tags all sources in the remote repository with a given tag. /// /// /// /// Unlike tag, the rtag command acts only on sources that are in the repository. /// Any modified sources on the local file system will NOT be tagged with this /// command, so a commit should be performed before an rtag is done. /// /// /// NOTE: Although a working directory is not necessary to perform the command /// one must be specified in order to remain in compliance with the cvs library. /// /// /// /// Tag NAnt sources remotely. /// /// /// ]]> /// /// /// /// Remove a tag from the remote repository. /// /// /// ]]> /// /// [TaskName("cvs-rtag")] public class RTagTask : AbstractCvsTask { #region Private Instance Fields private string _tag; #endregion Private Instance Fields #region Private Static Fields private const string CvsCommandName = "rtag"; #endregion Private Static Fields #region Public Instance Constructors /// /// Initializes a new instance of the /// class. /// public RTagTask() { } #endregion Public Instance Constructors #region Public Instance Properties /// /// The name of the tag to assign or remove. /// /// /// The name of the tag to assign or remove. /// [TaskAttribute("tag", Required=true)] [StringValidator(AllowEmpty=false, Expression=@"^[A-Za-z0-9][A-Za-z0-9._\-]*$")] public string Tag { get { return this._tag; } set { this._tag = value; } } /// /// Indicates whether the tag specified in should /// be removed or not. /// /// /// if the specified tag should be removed; /// otherwise, . The default is . /// [TaskAttribute("remove", Required=false)] [BooleanValidator()] public bool Remove { get { return ((Option)CommandOptions["remove"]).IfDefined; } set { SetCommandOption("remove", "-d", value); } } /// /// Indicates whether the tag specified in should /// be moved to the current file revision. If the tag does not exist /// then it is created. /// /// /// if the specified tag should be moved; /// otherwise, . The default is . /// [TaskAttribute("move-if-exists", Required=false)] [BooleanValidator()] public bool MoveIfExists { get { return ((Option)CommandOptions["move-if-exists"]).IfDefined; } set { SetCommandOption("move-if-exists", "-F", value); } } /// /// If a directory is specified indicates whether sub-directories should /// also be processed. /// /// /// if the sub-directories should be tagged; /// otherwise, . The default is . /// [TaskAttribute("recursive", Required=false)] [BooleanValidator()] public bool Recursive { get { return ((Option)CommandOptions["recursive"]).IfDefined; } set { SetCommandOption("recursive", "-R", value); SetCommandOption("local-only", "-l", !value); } } /// /// Indicates the repository that is acted on /// for the tag command. Note if is /// then the tag specified is moved to the revision /// of the file on the HEAD of the branch specified. /// /// /// The tag (or more likely) branch that should be used to apply the new tag. /// [TaskAttribute("act-on-tag", Required=false)] [StringValidator(AllowEmpty=false, Expression=@"^[A-Za-z0-9][A-Za-z0-9._\-]*$")] public string ActOnTag { get { return ((Option)CommandOptions["act-on-tag"]).Value; } set { SetCommandOption("act-on-tag", String.Format(CultureInfo.InvariantCulture,"-r {0}", value), true); } } /// /// Indicates the revision date of the file that the tag should be /// applied to. /// /// /// A valid date which specifies the revision point that the tag will /// be applied to. /// [TaskAttribute("act-on-date", Required=false)] [DateTimeValidator()] public DateTime ActOnDate { get { return Convert.ToDateTime(((Option)CommandOptions["act-on-date"]).Value); } set { SetCommandOption("act-on-date", String.Format(CultureInfo.InvariantCulture,"-D {0}", ToCvsDateTimeString(value)), true); } } /// /// Indicates whether the head revision should be used if the /// or the tags are not /// found. /// /// /// if the specified tag should be moved; /// otherwise, . The default is . /// [TaskAttribute("force-head", Required=false)] [BooleanValidator()] public bool ForceHead { get { return ((Option)CommandOptions["force-head"]).IfDefined; } set { SetCommandOption("force-head", "-f", value); } } #endregion Public Instance Properties #region Override implementation of AbstractCvsTask /// /// The name of the cvs command that is going to be executed. /// public override string CommandName { get {return CvsCommandName;} } /// /// Append the tag information to the commandline. /// protected override void AppendSubCommandArgs() { base.AppendSubCommandArgs (); if (this.Tag != null && this.Tag != string.Empty) { this.AddArg(this.Tag); } } #endregion Override implementation of AbstractCvsTask } } nant-0.92-rc1/src/NAnt.SourceControl/Tasks/ExportTask.cs0000644000175000017500000001706011757302274023004 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Clayton Harbour (claytonharbour@sporadicism.com) using System; using System.Text; using System.IO; using System.Diagnostics; using System.Globalization; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Tasks; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.SourceControl.Tasks { /// /// Exports a cvs module in preperation for a release (i.e. the CVS version /// folders are not exported). /// /// /// Export the most recent NAnt sources from cvs. /// /// /// ]]> /// /// /// /// /// Export NAnt revision named your_favorite_revision_here to the /// folder c:\src\nant\replacement_for_module_directory_name. /// /// **NOTE**: filesets names for the export task must be /// prefixed with the module name. This is different than other tasks. /// /// /// /// /// /// /// /// /// ]]> /// /// [TaskName("cvs-export")] public class ExportTask : AbstractCvsTask { #region Private Static Fields /// /// The command being executed. /// private const string CvsCommandName = "export"; #endregion Private Static Fields #region Public Instance Constructors /// /// Create a new instance of the . /// /// /// The following values are set by default: ///
    ///
  • Recursive:
  • ///
///
public ExportTask() { Recursive = true; } #endregion Public Instance Constructors #region Public Instance Properties /// /// No shortening. Do not shorten module paths if -d specified. /// [TaskAttribute("no-shortening", Required=false)] [BooleanValidator()] public bool NoShortening { get { return ((Option)CommandOptions["no-shortening"]).IfDefined; } set { SetCommandOption("no-shortening", "-N", value); } } /// /// Indicates whether the head revision should be used if the revison specified by /// or the tags are not /// found. The default is . /// /// /// if the specified tag should be moved; /// otherwise, . The default is . /// [TaskAttribute("force-head", Required=false)] [BooleanValidator()] public bool ForceHead { get { return ((Option)CommandOptions["force-head"]).IfDefined; } set { SetCommandOption("force-head", "-f", value); } } /// /// If a directory is specified indicates whether sub-directories should /// also be processed. /// /// /// if the sub-directories should be tagged; /// otherwise, . The default is . /// [TaskAttribute("recursive", Required=false)] [BooleanValidator()] public bool Recursive { get { return ((Option)CommandOptions["recursive"]).IfDefined; } set { SetCommandOption("recursive", "-R", value); SetCommandOption("local-only", "-l", !value); } } /// /// Specify the revision to update the file to. This corresponds to the "sticky-tag" /// of the file. /// [TaskAttribute("revision", Required=false)] [StringValidator(AllowEmpty=true, Expression=@"^[A-Za-z0-9][A-Za-z0-9._\-]*$")] public string Revision { get { if (null == CommandOptions["revision"]) { return null; } return ((Option)CommandOptions["revision"]).Value;} set { if (String.IsNullOrEmpty(value)) { CommandOptions.Remove("revision"); } else { SetCommandOption("revision", string.Format(CultureInfo.InvariantCulture, "-r {0}", value), true); } } } /// /// Specify the revision date to update to. The version of the file that /// existed at the date specified is retrieved. /// /// /// A valid date time value, which is then converted to a format that /// cvs can parse. /// [TaskAttribute("date", Required=false)] [DateTimeValidator()] public DateTime Date { get { return Convert.ToDateTime(((Option)CommandOptions["date"]).Value); } set { SetCommandOption("date", String.Format(CultureInfo.InvariantCulture,"\"-D {0}\"", ToCvsDateTimeString(value)), true); } } /// /// Specify a directory name to replace the module name. Valid names /// include any valid filename, excluding path information. /// [TaskAttribute("overridedir", Required=false)] [StringValidator(AllowEmpty=false, Expression=@"^[A-Za-z0-9][A-Za-z0-9._\-]*$")] public string OverrideDir { get { return ((Option)CommandOptions["overridedir"]).Value; } set { SetCommandOption("overridedir", String.Format(CultureInfo.InvariantCulture,"-d{0}", value), true); } } #endregion Public Instance Properties #region Override implementation of AbstractCvsTask /// /// The export command name for the cvs client. /// public override string CommandName { get { return CvsCommandName; } } #endregion Override implementation of AbstractCvsTask } } nant-0.92-rc1/src/NAnt.SourceControl/Tasks/ChangeLogTask.cs0000644000175000017500000001434411757302274023354 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Clayton Harbour (claytonharbour@sporadicism.com) using System; using System.Globalization; using System.IO; using System.Text; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Tasks; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.SourceControl.Tasks { /// /// Produces an XML report that represents the cvs changes from the given /// start day, to a given end date. /// /// /// Report changes in NAnt from 1st of June 2004 until 25th of July 2004. /// /// /// ]]> /// /// [TaskName("cvs-changelog")] public class ChangeLogTask : AbstractCvsTask { #region Private Static Fields /// /// The command being executed. /// private const string CvsCommandName = "xml"; #endregion Private Static Fields #region Public Instance Properties /// /// Name of the xml file that will contain the cvs log information. /// [TaskAttribute("xmlfile", Required=true)] public FileInfo DestFile { get { if (!CommandOptions.ContainsKey("destfile")) { return null; } return new FileInfo(((Option) CommandOptions["destfile"]).Value); } set { if (null == this.DestinationDirectory) { this.DestinationDirectory = new DirectoryInfo(value.DirectoryName); } SetCommandOption("destfile", string.Format(CultureInfo.InvariantCulture, "\"-oxml\" \"{0}\"", value.FullName), true); } } /// /// The earliest change to use in the cvs log command. /// [TaskAttribute("start", Required=true)] [DateTimeValidator()] public DateTime StartDate { get { return Convert.ToDateTime(((Option)CommandOptions["start"]).Value); } set { SetCommandOption("start", string.Format(CultureInfo.InvariantCulture,"-D \"{0}\"", ToCvsDateTimeString(value)), true); } } /// /// The latest date to use in the cvs log command. /// [TaskAttribute("end", Required=true)] [DateTimeValidator()] public DateTime EndDate { get { return Convert.ToDateTime(((Option)CommandOptions["end"]).Value); } set { SetCommandOption("end", string.Format(CultureInfo.InvariantCulture,"-D \"{0}\"", ToCvsDateTimeString(value)), true); } } #endregion Public Instance Properties #region Override implementation of AbstractCvsTask /// /// The cvs command to execute. /// public override string CommandName { get { return CvsCommandName; } } /// /// Override use of sharpcvslib, needs to be true. /// public override bool UseSharpCvsLib { get { return true; } set { /* can only use sharpcvslib for changelog */ } } /// /// /// The cvs root variable has the following components: /// /// /// [protocol]:[username]@[servername]:[server path] ///
    ///
  • protocol: ext, pserver, ssh (sharpcvslib); if you are not using sharpcvslib consult your cvs documentation.
  • ///
  • username: [username]
  • ///
  • servername: cvs.sourceforge.net
  • ///
  • server path: /cvsroot/nant
  • ///
///
/// /// If the cvsroot is not specified then the directory specified by the /// attribute /// is searched for CVS\Root. /// ///
/// /// NAnt anonymous cvsroot: /// /// :pserver:anonymous@cvs.sourceforge.net:/cvsroot/nant /// /// [TaskAttribute("cvsroot", Required=false)] public override string Root { get { if (null == base.Root && this.DestinationDirectory.Exists) { try { ICSharpCode.SharpCvsLib.FileSystem.Manager manager = new ICSharpCode.SharpCvsLib.FileSystem.Manager(this.DestinationDirectory.FullName); ICSharpCode.SharpCvsLib.FileSystem.Root root = manager.FetchRoot(this.DestinationDirectory.FullName); base.Root = root.FileContents; } catch (Exception e) { throw new BuildException (e.Message); } } return base.Root; } set { base.Root = value; } } #endregion Override implementation of AbstractCvsTask } } nant-0.92-rc1/src/NAnt.SourceControl/Tasks/TagTask.cs0000644000175000017500000002266011757302274022240 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Clayton Harbour (claytonharbour@sporadicism.com) using System; using System.Globalization; using NAnt.Core.Tasks; using NAnt.Core.Attributes; using NAnt.Core.Util; using NAnt.Core.Types; namespace NAnt.SourceControl.Tasks { /// /// Tags all local sources with the specified tag. /// /// /// /// This differs from the /// in that it acts on references to the cvs files /// contained in your local filesystem. As such the sticky tags and local /// revisions can be considered in commits. It also allows you to verify that /// all local files have been checked in before a tag is performed. /// /// /// /// Tag NAnt sources remotely. /// /// /// ]]> /// /// /// /// Remove a tag from the remote repository. /// /// /// ]]> /// /// [TaskName("cvs-tag")] public class TagTask : AbstractCvsTask { #region Private Instance Fields private string _tag; #endregion Private Instance Fields #region Internal Static Fields /// /// Cvs command to be executed. /// internal const string CvsCommandName = "tag"; #endregion Internal Static Fields #region Public Instance Constructors /// /// Initializes a new instance of the /// class. /// public TagTask() { } #endregion Public Instance Constructors #region Public Instance Properties /// /// The name of the tag to assign or remove. /// /// /// The name of the tag to assign or remove. /// [TaskAttribute("tag", Required=true)] [StringValidator(AllowEmpty=false, Expression=@"^[A-Za-z0-9][A-Za-z0-9._\-]*$")] public string Tag { get { return this._tag; } set { this._tag = value; } } /// /// Indicates whether the tag specified in should /// be removed or not. /// /// /// if the specified tag should be removed; /// otherwise, . The default is . /// [TaskAttribute("remove", Required=false)] [BooleanValidator()] public bool Remove { get { return ((Option)CommandOptions["remove"]).IfDefined; } set { SetCommandOption("remove", "-d", value); } } /// /// Indicates whether the tag specified in should /// be moved to the current file revision. If the tag does not exist /// then it is created. /// /// /// if the specified tag should be moved; /// otherwise, . The default is . /// [TaskAttribute("move-if-exists", Required=false)] [BooleanValidator()] public bool MoveIfExists { get { return ((Option)CommandOptions["move-if-exists"]).IfDefined; } set { SetCommandOption("move-if-exists", "-F", value); } } /// /// If a directory is specified indicates whether sub-directories should /// also be processed. /// /// /// if the sub-directories should be tagged; /// otherwise, . The default is . /// [TaskAttribute("recursive", Required=false)] [BooleanValidator()] public bool Recursive { get { return ((Option)CommandOptions["recursive"]).IfDefined; } set { SetCommandOption("recursive", "-R", value); SetCommandOption("local-only", "-l", !value); } } /// /// Indicates the repository that is acted on /// for the tag command. Note if is /// then the tag specified is moved to the revision /// of the file on the HEAD of the branch specified. /// /// /// The tag (or more likely) branch that should be used to apply the new tag. /// [TaskAttribute("act-on-tag", Required=false)] [StringValidator(AllowEmpty=false, Expression=@"^[A-Za-z0-9][A-Za-z0-9._\-]*$")] public string ActOnTag { get { return ((Option)CommandOptions["act-on-tag"]).Value; } set { SetCommandOption("act-on-tag", String.Format(CultureInfo.InvariantCulture,"-r {0}", value), true); } } /// /// Indicates the revision date of the file that the tag should be /// applied to. /// /// /// A valid date which specifies the revision point that the tag will /// be applied to. /// [TaskAttribute("act-on-date", Required=false)] [DateTimeValidator()] public DateTime ActOnDate { get { return Convert.ToDateTime(((Option)CommandOptions["act-on-date"]).Value); } set { SetCommandOption("act-on-date", String.Format(CultureInfo.InvariantCulture,"-D {0}", ToCvsDateTimeString(value)), true); } } /// /// Indicates whether the head revision should be used if the revision specified by /// or the tags are not /// found. /// /// /// if the specified tag should be moved; /// otherwise, . The default is . /// [TaskAttribute("force-head", Required=false)] [BooleanValidator()] public bool ForceHead { get { return ((Option)CommandOptions["force-head"]).IfDefined; } set { SetCommandOption("force-head", "-f", value); } } /// /// Indicates whether the head revision should be used if the /// or the tags are not /// found. /// /// /// if the specified tag should be moved; /// otherwise, . The default is . /// [TaskAttribute("fail-if-modified", Required=false)] [BooleanValidator()] public bool FailIfModified { get { return ((Option)CommandOptions["fail-if-modified"]).IfDefined; } set { SetCommandOption("fail-if-modified", "-c", value); } } #endregion Public Instance Properties #region Override implementation of AbstractCvsTask /// /// The name of the cvs command that is going to be executed. /// public override string CommandName { get { return CvsCommandName; } } /// /// Not used /// public override string Module { get { return null; } set { /* module not used for cvs-tag */ } } /// /// Append the tag information to the commandline. /// protected override void AppendSubCommandArgs() { base.AppendSubCommandArgs (); if (this.Tag != null && this.Tag != string.Empty) { this.AddArg(this.Tag); } } /// /// Specify if the module is needed for this cvs command. It is /// only needed if there is no module information on the local file /// system. /// protected override bool IsModuleNeeded { get { return false; } } #endregion Override implementation of AbstractCvsTask } } nant-0.92-rc1/src/NAnt.SourceControl/Tasks/UpdateTask.cs0000644000175000017500000001763611757302274022756 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Clayton Harbour (claytonharbour@sporadicism.com) using System; using System.Globalization; using System.IO; using NAnt.Core.Attributes; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.SourceControl.Tasks { /// /// Updates a CVS module in a local working directory. /// /// /// Update nant. /// /// /// ]]> /// /// /// /// /// Update your NAnt revision named your_favorite_revision_here in /// the folder c:\src\nant\replacement_for_module_directory_name. /// /// /// /// /// /// /// /// ]]> /// /// [TaskName("cvs-update")] public class UpdateTask : AbstractCvsTask { #region Internal Static Fields /// /// The command being executed. /// internal const string CvsCommandName = "update"; #endregion Internal Static Fields #region Public Instance Constructors /// /// Initializes a new instance of the /// class. /// /// /// Sets the build directory and prune empty directory properties to /// . /// public UpdateTask() { BuildDirs = true; PruneEmpty = true; } #endregion Public Instance Constructors #region Public Instance Properties /// /// If . new directories will be created on the local /// sandbox. The default is . /// [TaskAttribute("builddirs", Required=false)] [BooleanValidator()] public bool BuildDirs { get { return ((Option)CommandOptions["builddirs"]).IfDefined; } set { SetCommandOption("builddirs", "-d", value); } } /// /// If empty directories copied down from the /// remote repository will be removed from the local sandbox. /// The default is . /// [TaskAttribute("pruneempty", Required=false)] [BooleanValidator()] public bool PruneEmpty { get { return ((Option)CommandOptions["pruneempty"]).IfDefined; } set { SetCommandOption("pruneempty", "-P", value); } } /// /// If the local copy of the file will be /// overwritten with the copy from the remote repository. The default /// is . /// [TaskAttribute("overwritelocal", Required=false)] [BooleanValidator()] public bool OverwriteLocal { get { return ((Option)CommandOptions["overwritelocal"]).IfDefined; } set { SetCommandOption("overwritelocal", "-C", value); } } /// /// Specifies if the command should be executed recursively. The /// default is . /// /// /// The -R option is on by default in cvs. /// [TaskAttribute("recursive", Required=false)] [BooleanValidator()] public bool Recursive { get { Option option = (Option) CommandOptions["recursive"]; if (option == null || option.Value == "-R") { return true; } return false; } set { if (value) { // update should be executed recursive SetCommandOption("recursive", "-R", true); } else { // update should be executed locally (not recursive) SetCommandOption("recursive", "-l", true); } } } /// /// Specify the revision to update the file to. This corresponds to the /// "sticky-tag" of the file. /// [TaskAttribute("revision", Required=false)] [StringValidator(AllowEmpty=true, Expression=@"^[A-Za-z0-9][A-Za-z0-9._\-]*$")] public string Revision { get { if (CommandOptions.ContainsKey("revision")) { return ((Option)CommandOptions["revision"]).Value; } return null; } set { if (String.IsNullOrEmpty(value)) { CommandOptions.Remove("revision"); } else { SetCommandOption("revision", string.Format(CultureInfo.InvariantCulture, "-r {0}", value), true); } } } /// /// Sticky tag or revision to update the local file to. /// /// /// A valid cvs tag. /// [TaskAttribute("sticky-tag", Required=false)] public string StickyTag { get { return Revision; } set { Revision = value; } } /// /// Specify the revision date to update to. The version of the file that /// existed at the date specified is retrieved. /// /// /// A valid date time value, which is then converted to a format that /// cvs can parse. /// [TaskAttribute("date", Required=false)] [DateTimeValidator()] public DateTime Date { get { return Convert.ToDateTime(((Option)CommandOptions["date"]).Value); } set { SetCommandOption("date", String.Format(CultureInfo.InvariantCulture,"-D \"{0}\"", ToCvsDateTimeString(value)), true); } } #endregion #region Override implementation of AbstractCvsTask /// /// Specify if the module is needed for this cvs command. It is /// only needed if there is no module information on the local file /// system. /// protected override bool IsModuleNeeded { get {return false;} } /// /// The name of the cvs command that is going to be executed. /// public override string CommandName { get {return CvsCommandName;} } #endregion Override implementation of AbstractCvsTask } } nant-0.92-rc1/src/NAnt.SourceControl/Tasks/AbstractCvsTask.cs0000644000175000017500000005313611757302274023746 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Clayton Harbour (claytonharbour@sporadicism.com) using System; using System.Diagnostics; using System.IO; using System.Text; using System.Globalization; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Tasks; using NAnt.Core.Types; using NAnt.Core.Util; using NAnt.SourceControl.Types; using ICSharpCode.SharpCvsLib.FileSystem; namespace NAnt.SourceControl.Tasks { /// /// A base class for creating tasks for executing CVS client commands on a /// CVS repository. /// public abstract class AbstractCvsTask : AbstractSourceControlTask { #region Private Static Fields private static readonly log4net.ILog Logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion Private Static Fields #region Protected Static Fields /// /// Default value for the recursive directive. The default is /// . /// protected const bool DefaultRecursive = false; /// /// Default value for the quiet command. /// protected const bool DefaultQuiet = false; /// /// Default value for the really quiet command. /// protected const bool DefaultReallyQuiet = false; /// /// An environment variable that holds path information about where /// cvs is located. /// protected const string CvsHome = "CVS_HOME"; /// /// Name of the password file that cvs stores pserver /// cvsroot/ password pairings. /// protected const String CvsPassfile = ".cvspass"; /// /// The default compression level to use for cvs commands. /// protected const int DefaultCompressionLevel = 3; /// /// The default use of binaries, defaults to use sharpcvs. /// protected const bool DefaultUseSharpCvsLib = true; /// /// The name of the cvs executable. /// protected const string CvsExe = "cvs.exe"; /// /// The temporary name of the sharpcvslib binary file, to avoid /// conflicts in the path variable. /// protected const string SharpCvsExe = "scvs.exe"; /// /// Environment variable that holds the executable name that is used for /// ssh communication. /// protected const string CvsRsh = "CVS_RSH"; /// /// Property name used to specify on a project level whether sharpcvs is /// used or not. /// protected const string UseSharpCvsLibProp = "sourcecontrol.usesharpcvslib"; #endregion "Protected Static Fields #region Private Instance Fields private string _module; private bool _useSharpCvsLib = DefaultUseSharpCvsLib; private bool _isUseSharpCvsLibSet = false; private FileInfo _cvsFullPath; private string _sharpcvslibExeName; private CvsFileSet _cvsFileSet = new CvsFileSet(); #endregion Private Instance Fields #region Protected Instance Contructors /// /// Initializes a new instance of the /// class. /// protected AbstractCvsTask () : base() { _sharpcvslibExeName = Path.Combine (System.AppDomain.CurrentDomain.BaseDirectory, SharpCvsExe); } #endregion Protected Instance Constructors #region Protected Instance Properties /// /// The environment name for the ssh variable. /// protected override string SshEnv { get { return CvsRsh; } } /// /// The name of the cvs binary, or cvs.exe at the time this /// was written. /// protected override string VcsExeName { get { return CvsExe; } } /// /// The name of the pass file, or .cvspass at the time /// of this writing. /// protected override string PassFileName { get { return CvsPassfile; } } /// /// The name of the version control system specific home environment /// variable. /// protected override string VcsHomeEnv { get { return CvsHome; } } /// /// Specify if the module is needed for this cvs command. It is /// only needed if there is no module information on the local file /// system. /// protected virtual bool IsModuleNeeded { get { return true; } } #endregion #region Protected Instance Methods /// /// Converts a date value to a string representation that can be /// interpreted by cvs. /// /// Date to convert. /// /// String interpretation of . /// protected string ToCvsDateTimeString(DateTime item) { return string.Format("{0} {1,2} {2}", item.ToString("ddd MMM"), item.Day.ToString(), item.ToString("HH:mm:ss yyyy")); } #endregion Protected Instance Methods #region Public Instance Properties /// /// Used to specify the version control system (VCS) files that are going /// to be acted on. /// [BuildElement("fileset")] public CvsFileSet CvsFileSet { get { return this._cvsFileSet; } set { this._cvsFileSet = value; } } /// /// Get the cvs file set. /// public override FileSet VcsFileSet{ get { return this.CvsFileSet; } } /// /// The name of the cvs executable. /// public override string ExeName { get { if (null != CvsFullPath) { return CvsFullPath.FullName; } string _exeNameTemp; if (UseSharpCvsLib) { _exeNameTemp = _sharpcvslibExeName; } else { FileInfo vcsFile = DeriveVcsFromEnvironment(); if (vcsFile == null) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "'{0}' could not be found on the system.", VcsExeName), Location); } _exeNameTemp = vcsFile.FullName; } Logger.Debug("_sharpcvslibExeName: " + _sharpcvslibExeName); Logger.Debug("_exeNameTemp: " + _exeNameTemp); Properties[PropExeName] = _exeNameTemp; return _exeNameTemp; } } /// /// The full path to the cvs binary used. The cvs tasks will attempt to /// "guess" the location of your cvs binary based on your path. If the /// task is unable to resolve the location, or resolves it incorrectly /// this can be used to manually specify the path. /// /// /// A full path (i.e. including file name) of your cvs binary: /// On Windows: c:\vcs\cvs\cvs.exe /// On *nix: /usr/bin/cvs /// [TaskAttribute("cvsfullpath", Required=false)] public FileInfo CvsFullPath { get { return _cvsFullPath; } set { _cvsFullPath = value; } } /// /// /// The cvs root variable has the following components: /// /// /// [protocol]:[username]@[servername]:[server path] ///
    ///
  • protocol: ext, pserver, ssh (sharpcvslib); if you are not using sharpcvslib consult your cvs documentation.
  • ///
  • username: [username]
  • ///
  • servername: cvs.sourceforge.net
  • ///
  • server path: /cvsroot/nant
  • ///
///
///
/// /// NAnt anonymous cvsroot: /// /// :pserver:anonymous@cvs.sourceforge.net:/cvsroot/nant /// /// [TaskAttribute("cvsroot", Required=false)] [StringValidator(AllowEmpty=false)] public override string Root { get { if (null == base.Root) { try { ICSharpCode.SharpCvsLib.FileSystem.Root root = ICSharpCode.SharpCvsLib.FileSystem.Root.Load(this.DestinationDirectory); this.Root = root.FileContents; } catch (ICSharpCode.SharpCvsLib.Exceptions.CvsFileNotFoundException) { throw new BuildException (string.Format("Cvs/Root file not found in {0}, please perform a checkout.", this.DestinationDirectory.FullName)); } } return base.Root; } set { base.Root = StringUtils.ConvertEmptyToNull(value); } } /// /// The module to perform an operation on. /// /// /// The module to perform an operation on. This is a normal file/folder /// name without path information. /// /// /// In NAnt the module name would be: /// nant /// [TaskAttribute("module", Required=false)] [StringValidator(AllowEmpty=true)] public virtual string Module { get { if (null == _module) { try { Repository repository = Repository.Load(this.DestinationDirectory); this._module = repository.ModuleName; } catch (ICSharpCode.SharpCvsLib.Exceptions.CvsFileNotFoundException) { throw new BuildException (string.Format("Cvs/Repository file not found in {0}, please perform a checkout.", this.DestinationDirectory.FullName)); } } return _module; } set { _module = StringUtils.ConvertEmptyToNull(value); } } /// /// /// if the SharpCvsLib binaries that come bundled /// with NAnt should be used to perform the cvs commands, /// otherwise. /// /// /// You may also specify an override value for all cvs tasks instead /// of specifying a value for each. To do this set the property /// sourcecontrol.usesharpcvslib to . /// /// /// If you choose not to use SharpCvsLib to checkout from cvs you will /// need to include a cvs.exe binary in your path. /// /// /// /// To use a cvs client in your path instead of sharpcvslib specify /// the property: /// >property name="sourcecontrol.usesharpcvslib" value="false"< /// /// The default settings is to use sharpcvslib and the setting closest /// to the task execution is used to determine which value is used /// to execute the process. /// /// For instance if the attribute usesharpcvslib was set to false /// and the global property was set to true, the usesharpcvslib is /// closes to the point of execution and would be used and is false. /// Therefore the sharpcvslib binary would NOT be used. /// [TaskAttribute("usesharpcvslib", Required=false)] public virtual bool UseSharpCvsLib { get { return _useSharpCvsLib; } set { _isUseSharpCvsLibSet = true; _useSharpCvsLib = value; } } /// /// The executable to use for ssh communication. /// [TaskAttribute("cvsrsh", Required=false)] public override FileInfo Ssh { get { return base.Ssh; } set { base.Ssh = value; } } /// /// Indicates if the output from the cvs command should be supressed. /// The default is . /// [TaskAttribute("quiet", Required=false)] [BooleanValidator()] public bool Quiet { get { Option option = (Option)GlobalOptions["quiet"]; return null == option ? false : option.IfDefined; } set { SetGlobalOption("quiet", "-q", value); } } /// /// Indicates if the output from the cvs command should be stopped. /// The default is . /// [TaskAttribute("reallyquiet", Required=false)] [BooleanValidator()] public bool ReallyQuiet { get { Option option = (Option)GlobalOptions["reallyquiet"]; return null == option ? false : option.IfDefined; } set { SetGlobalOption("reallyquiet", "-Q", value); } } /// /// if the sandbox files should be checked out in /// read only mode. The default is . /// [TaskAttribute("readonly", Required=false)] [BooleanValidator()] public bool ReadOnly { get { Option option = (Option)GlobalOptions["readonly"]; return null == option ? false : option.IfDefined; } set { SetGlobalOption("readonly", "-r", value); } } /// /// if the sandbox files should be checked out in /// read/write mode. The default is . /// [TaskAttribute("readwrite", Required=false)] [BooleanValidator()] public bool ReadWrite { get { Option option = (Option)GlobalOptions["readwrite"]; return null == option ? false : option.IfDefined; } set { SetGlobalOption("readwrite", "-w", value); } } /// /// Compression level to use for all net traffic. This should be a value from 1-9. ///
///
/// NOTE: This is not available on sharpcvslib. ///
[TaskAttribute("compressionlevel")] public int CompressionLevel { get { Option option = (Option)GlobalOptions["compressionlevel"]; return null == option ? DefaultCompressionLevel : Convert.ToInt32(option.Value); } set { SetGlobalOption("readwrite", String.Format("-z{0}", value), true); } } #endregion Public Instance Properties #region Override Task Implementation /// /// Build up the command line arguments, determine which executable is being /// used and find the path to that executable and set the working /// directory. /// /// The process to prepare. protected override void PrepareProcess (Process process) { // Although a global property can be set, take the property closest // to the task execution, which is the attribute on the task itself. if (!_isUseSharpCvsLibSet && (null == Properties || null == Properties[UseSharpCvsLibProp])) { // if not set and the global property is null then use the default _useSharpCvsLib = UseSharpCvsLib; } else if (!_isUseSharpCvsLibSet && null != Properties[UseSharpCvsLibProp]){ try { _useSharpCvsLib = System.Convert.ToBoolean(Properties[UseSharpCvsLibProp]); } catch (Exception) { throw new BuildException (UseSharpCvsLib + " must be convertable to a boolean."); } } Logger.Debug("number of arguments: " + Arguments.Count); // if set, pass cvsroot to command line tool if (Root != null) { Arguments.Add(new Argument(string.Format(CultureInfo.InvariantCulture, "-d{0}", Root))); } if (this.UseSharpCvsLib) { Managed = ManagedExecution.Auto; } // Set verbose logging on the #cvslib client if used. if (this.UseSharpCvsLib && this.Verbose) { SetGlobalOption("verbose", String.Format("-verbose"), true); } AppendGlobalOptions(); Arguments.Add(new Argument(CommandName)); AppendCommandOptions(); Log(Level.Debug, "Commandline args are null: {0}", ((null == CommandLineArguments) ? "yes" : "no")); Log(Level.Debug, "Commandline: {0}", CommandLineArguments); if (null != CommandLineArguments) { Arguments.Add(new Argument(CommandLineArguments)); } AppendSubCommandArgs(); AppendFiles(); if (IsModuleNeeded && null == Module) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Cvs module is required for this action."), Location); } if (IsModuleNeeded) { Arguments.Add(new Argument(Module)); } if (!Directory.Exists(DestinationDirectory.FullName)) { Directory.CreateDirectory(DestinationDirectory.FullName); } base.PrepareProcess(process); process.StartInfo.FileName = ExeName; process.StartInfo.WorkingDirectory = DestinationDirectory.FullName; Log(Level.Verbose, "Working directory: {0}", process.StartInfo.WorkingDirectory); Log(Level.Verbose, "Executable: {0}", process.StartInfo.FileName); Log(Level.Verbose, "Arguments: {0}", process.StartInfo.Arguments); } /// /// Override to append any commands before the modele and files. /// protected virtual void AppendSubCommandArgs() { } #endregion #region Private Instance Methods private void AppendGlobalOptions () { foreach (Option option in GlobalOptions.Values) { // Log(Level.Verbose, "Type '{0}'.", optionte.GetType()); if (!option.IfDefined || option.UnlessDefined) { // skip option continue; } AddArg(option.Value); } } /// /// Append the command line options or commen names for the options /// to the generic options collection. This is then piped to the /// command line as a switch. /// private void AppendCommandOptions () { foreach (Option option in CommandOptions.Values) { if (!option.IfDefined || option.UnlessDefined) { // skip option continue; } AddArg(option.Value); } } /// /// Add the given argument to the command line options. Note that are not explicitly /// quoted are split into seperate arguments. This is to resolve a recent issue /// with quoting command line arguments. /// /// protected void AddArg (String arg) { if (arg.IndexOf(" ") > -1 && arg.IndexOf("\"") == -1) { string[] args = arg.Split(' '); foreach (string targ in args) { Arguments.Add( new Argument(String.Format(CultureInfo.InvariantCulture,"{0}", targ))); } } else { Arguments.Add(new Argument(String.Format(CultureInfo.InvariantCulture,"{0}", arg))); } } #endregion Private Instance Methods } } nant-0.92-rc1/src/NAnt.SourceControl/NAnt.SourceControl.csproj0000644000175000017500000001166611757302274024154 0ustar jtaylorjtaylor Debug AnyCPU 2.0 {6B2EC648-8D69-4096-B4F9-6EDC0B2F98EF} NAnt.SourceControl NAnt.SourceControlTasks Library OnSuccessfulBuild false 8.0.50727 v2.0 2.0 publish\ true Disk false Foreground 7 Days false false true 0 1.0.0.%2a false false true true full false 4 ..\..\build\Debug\ AllRules.ruleset TRACE;DEBUG ..\..\build\Debug\NAnt.SourceControlTasks.xml true pdbonly true ..\..\build\Release\ 4 AllRules.ruleset TRACE ..\..\build\Release\NAnt.SourceControlTasks.xml ..\..\lib\common\neutral\log4net.dll ..\..\lib\common\neutral\ICSharpCode.SharpCvsLib.dll ..\..\lib\common\neutral\ICSharpCode.SharpZipLib.dll CommonAssemblyInfo.cs False .NET Framework 3.5 SP1 Client Profile false False .NET Framework 3.5 SP1 true False Windows Installer 3.1 true {8F5F8375-4097-4952-B860-784EB9961ABE} NAnt.Core nant-0.92-rc1/src/NAnt.NUnit/0000755000175000017500000000000011757310030015501 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.NUnit/NAnt.NUnit.build0000644000175000017500000000665011757302274020440 0ustar jtaylorjtaylor nant-0.92-rc1/src/NAnt.NUnit/NUnit1/0000755000175000017500000000000011757310030016617 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.NUnit/NUnit1/XmlResultFormatter.cs0000644000175000017500000001464711757302274023020 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Ian MacLean (ian_maclean@another.com) // Gerry Shaw (gerry_shaw@yahoo.com) using System; using System.Globalization; using System.IO; using System.Text; using System.Xml; using NUnit.Framework; using NAnt.Core.Util; namespace NAnt.NUnit1.Types { /// /// Prints detailed information about running tests in XML format. /// public class XmlResultFormatter : IResultFormatter { #region Public Instance Constructors /// /// Initializes a new instance of the /// class. /// public XmlResultFormatter() { _document = new XmlDocument(); } #endregion Public Instance Constructors #region Public Instance Properties public TextWriter Writer { get { return _writer; } set { _writer = value; } } #endregion Public Instance Properties #region Implemenation of IResultFormatter /// /// Sets the the formatter is supposed to /// write its results to. /// public void SetOutput(TextWriter writer) { Writer = writer; } /// /// Called when the whole test suite has started. /// public void StartTestSuite(NUnitTestData suite) { XmlDeclaration decl = _document.CreateXmlDeclaration("1.0", null, null); _document.AppendChild(decl); _suiteElement = _document.CreateElement(ElementTestSuite); // // if this is a testsuite, use it's name // string suiteName = suite.Suite.ToString(); if (String.IsNullOrEmpty(suiteName)) { suiteName = "test"; } _suiteElement.SetAttribute(AttributeName, suiteName ); } /// /// Called when the whole test suite has ended. /// public void EndTestSuite(TestResultExtra result) { _suiteElement.SetAttribute(AttributeTests , result.RunCount.ToString(NumberFormatInfo.InvariantInfo)); double time = result.RunTime; time /= 1000D; _suiteElement.SetAttribute(AttributeTime, time.ToString("#####0.000", NumberFormatInfo.InvariantInfo)); _document.AppendChild(_suiteElement); _suiteElement.SetAttribute(AttributeErrors , result.ErrorCount.ToString(NumberFormatInfo.InvariantInfo)); _suiteElement.SetAttribute(AttributeFailures , result.FailureCount.ToString(NumberFormatInfo.InvariantInfo)); // Send all output to here _document.Save(Writer); Writer.Flush(); Writer.Close(); } #endregion Implemenation of IResultFormatter #region Implemenation of ITestListener public void AddError(ITest test, Exception t) { FormatError(ElementError, test, t); } public void AddFailure(ITest test, AssertionFailedError t) { FormatError(ElementFailure, test, (Exception)t); } public void StartTest(ITest test) { _testStartTime = DateTime.Now; _currentTest = _document.CreateElement(ElementTestCase); _currentTest.SetAttribute(AttributeName, ((TestCase ) test).ToString()); string className = test.GetType().FullName; _currentTest.SetAttribute(AttributeClassname, className); _suiteElement.AppendChild(_currentTest); } public void EndTest(ITest test) { TimeSpan elapsedTime = DateTime.Now - _testStartTime; double time = elapsedTime.Milliseconds; time /= 1000D; _currentTest.SetAttribute(AttributeTime, time.ToString("#####0.000", NumberFormatInfo.InvariantInfo)); } #endregion Implemenation of ITestListener #region Private Instance Methods private void FormatError(string type, ITest test, Exception t) { if (test != null) { EndTest(test); } XmlElement nested = _document.CreateElement(type); if (test != null) { _currentTest.AppendChild(nested); } else { _suiteElement.AppendChild(nested); } string message = t.Message; if (message != null && message.Length > 0) { nested.SetAttribute( AttributeMessage, message ); } nested.SetAttribute(AttributeType, t.GetType().FullName); XmlText traceElement = _document.CreateTextNode(t.StackTrace); nested.AppendChild(traceElement); } #endregion Private Instance Methods #region Private Instance Fields TextWriter _writer; XmlDocument _document; XmlElement _suiteElement; XmlElement _currentTest; DateTime _testStartTime; #endregion Private Instance Fields #region Private Static Fields const string ElementTestSuite = "testsuite"; const string ElementTestCase = "testcase"; const string ElementError = "error"; const string ElementFailure = "failure"; const string AttributeName = "name"; const string AttributeTime = "time"; const string AttributeErrors = "errors"; const string AttributeFailures = "failures"; const string AttributeTests = "tests"; const string AttributeType = "type"; const string AttributeMessage = "message"; const string AttributeClassname = "classname"; #endregion Private Static Fields } } nant-0.92-rc1/src/NAnt.NUnit/NUnit1/AssemblyInfo.cs0000644000175000017500000000233211757302274021554 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Scott Hernandez (ScottHernandez@hotmail.com) // Gert Driesen (drieseng@users.sourceforge.net) using System.Reflection; // This will not compile with Visual Studio. If you want to build a signed // executable use the NAnt build file. To build under Visual Studio just // exclude this file from the build. [assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile(@"..\NAnt.key")] [assembly: AssemblyKeyName("")]nant-0.92-rc1/src/NAnt.NUnit/NUnit1/TestResultExtra.cs0000644000175000017500000000345411757302274022311 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian MacLean (ian_maclean@another.com) using NUnit.Framework; namespace NAnt.NUnit1.Types { /// /// Decorates NUnits with extra information such as /// run-time. /// public class TestResultExtra : TestResult { #region Public Instance Constructors /// /// Initializes a new instance of the /// class. /// public TestResultExtra() { } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets the total run-time of a test. /// /// The total run-time of a test. public long RunTime { get { return _runTime; } set { _runTime = value; } } #endregion Public Instance Properties #region Private Instance Fields private long _runTime; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.NUnit/NUnit1/PlainTextFormatter.cs0000644000175000017500000001070111757302274022754 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) using System; using System.IO; using System.Text.RegularExpressions; using NUnit.Framework; namespace NAnt.NUnit1.Types { /// /// Prints information about running tests in plain text. /// public class PlainTextFormatter : IResultFormatter { #region Public Instance Constructors public PlainTextFormatter() { } #endregion Public Instance Constructors #region Public Instance Properties public TextWriter Writer { get { return _writer; } set { _writer = value; } } #endregion Public Instance Properties #region Implementation of IResultFormatter /// Sets the Writer the formatter is supposed to write its results to. public void SetOutput(TextWriter writer) { Writer = writer; } /// Called when the whole test suite has started. public void StartTestSuite(NUnitTestData suite) { } /// Called when the whole test suite has ended. public void EndTestSuite(TestResultExtra result) { Writer.WriteLine("------------------------------------------"); if (result.WasSuccessful) { Writer.WriteLine("{0} tests: ALL SUCCESSFUL", result.RunCount); } else { Writer.WriteLine("{0} tests: FAILURES: {1} ERRORS: {2}", result.RunCount, result.FailureCount, result.ErrorCount); } Writer.Flush(); Writer.Close(); } #endregion Implementation of IResultFormatter #region Implementation of ITestListener public void AddError(ITest test, Exception e) { Writer.WriteLine("ERROR: " + test.ToString()); Writer.WriteLine(FormatError(e.StackTrace, e.Message)); } public void AddFailure(ITest test, AssertionFailedError e) { Writer.WriteLine("FAILURE: " + test.ToString()); Writer.WriteLine(FormatError(e.StackTrace, e.Message)); } public void StartTest(ITest test) { // TODO: the output from ToString is hard to read, change this to output ClassName.TestName Writer.WriteLine(test.ToString()); } public void EndTest(ITest test) { } #endregion Implementation of ITestListener #region Private Static Methods /// Convert a stack trace line into something that can be clicked on in an IDE output window. /// The StackTrace string, see . /// The string that gets appended to the end of file(line): portion. private static string FormatError(string trace, string message) { // if we can't find a filename(line#) string, then at least display the message string line = message; string[] lines = trace.Split(new char[] {'\n'}); // search the stack trace for the first filename(linenumber) like string Regex r = new Regex(@"^\s+at (?.+) in (?.+):line (?\d+)$"); foreach (string str in lines) { Match match = r.Match(str); if (match.Success) { line = match.Result("${file}(${line}): ") + message; break; // no need to continue } } return line; } #endregion Private Static Methods #region Private Instance Fields TextWriter _writer = null; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.NUnit/NUnit1/IResultFormatter.cs0000644000175000017500000000270311757302274022436 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian MacLean (ian_maclean@another.com) // Gerry Shaw (gerry_shaw@yahoo.com) using System.IO; using NUnit.Framework; namespace NAnt.NUnit1.Types { public interface IResultFormatter : ITestListener { /// /// The whole test suite started. /// void StartTestSuite(NUnitTestData suite); /// /// The whole test suite ended. /// void EndTestSuite(TestResultExtra result); /// /// Sets the the formatter is supposed to write /// its results to. /// void SetOutput(TextWriter writer); } } nant-0.92-rc1/src/NAnt.NUnit/NUnit1/NUnitTask.cs0000644000175000017500000002222011757302274021037 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian MacLean (ian_maclean@another.com) // Gerry Shaw (gerry_shaw@yahoo.com) // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Globalization; using System.Runtime.Remoting; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.NUnit.Types; using NAnt.NUnit1.Types; using System.Security; using System.Security.Permissions; using System.Security.Policy; namespace NAnt.NUnit1.Tasks { /// /// Runs tests using the NUnit V1.0 framework. /// /// /// /// See the NUnit home page for more /// information. /// /// /// The or /// attributes are only used to stop more than one test suite to stop /// running. If any test suite fails a build error will be thrown. /// Set to to /// ignore test errors and continue build. /// /// /// /// /// Run tests in the MyProject.Tests.dll assembly. /// /// /// The test results are logged in results.xml and results.txt /// using the and /// formatters, respectively. /// /// /// /// /// /// /// /// ]]> /// /// [TaskName("nunit")] [Obsolete("In a future release, this task will be moved to NAntContrib. However, we strongly advise you to upgrade to NUnit 2.x.")] public class NUnitTask : Task { #region Private Instance Fields private bool _haltOnError = false; private bool _haltOnFailure = false; private int _timeout = 0; private bool _failuresPresent = false; private bool _errorsPresent = false; private NUnitTestCollection _tests = new NUnitTestCollection(); private FormatterElementCollection _formatterElements = new FormatterElementCollection(); #endregion Private Instance Fields #region Public Instance Properties /// /// Stops running tests when a test causes an error. The default is /// . /// /// /// Implies haltonfailure. /// [TaskAttribute("haltonerror")] [BooleanValidator()] public bool HaltOnError { get { return _haltOnError; } set { _haltOnError = value; } } /// /// Stops running tests if a test fails (errors are considered failures /// as well). The default is . /// [TaskAttribute("haltonfailure")] [BooleanValidator()] public bool HaltOnFailure { get { return _haltOnFailure; } set { _haltOnFailure = value; } } /// /// Cancel the individual tests if they do not finish in the specified /// time (measured in milliseconds). Ignored if fork is disabled. /// [TaskAttribute("timeout")] public int Timeout { get { return _timeout; } set { _timeout = value; } } /// /// Tests to run. /// [BuildElementArray("test")] public NUnitTestCollection Tests { get { return _tests; } } /// /// Formatters to output results of unit tests. /// [BuildElementArray("formatter")] public FormatterElementCollection FormatterElements { get { return _formatterElements; } } #endregion Public Instance Properties #region Override implementation of Task protected override void ExecuteTask() { foreach (NUnitTest test in _tests) { ExecuteTest(test); } if (_failuresPresent) { throw new BuildException("Unit test failed, see build log.", Location); } if (_errorsPresent) { throw new BuildException("Unit test had errors, see build log.", Location); } } #endregion Override implementation of Task #region Private Instance Methods private void ExecuteTest(NUnitTest test) { // Set Defaults RunnerResult result = RunnerResult.Success; if (test.ToDir == null) { test.ToDir = Project.BaseDirectory; } if (test.OutFile == null) { test.OutFile = "TEST-" + test.Class; } NUnitTestData testData = test.GetTestData(); foreach (FormatterElement element in FormatterElements) { testData.Formatters.Add(element.Data); } if (testData.Fork == true) { result = ExecuteInAppDomain(testData); } else { result = ExecuteInProc(testData); } // Handle return code: // If there is an error/failure and that it should halt, stop // everything otherwise just log a statement. bool errorOccurred = (result == RunnerResult.Errors); bool failureOccurred = (result != RunnerResult.Success); if ((errorOccurred && test.HaltOnError) || (failureOccurred && test.HaltOnFailure)) { // Only thrown if this test should halt as soon as the first // error/failure is detected. In most cases all tests will // be run to get a full list of problems. throw new BuildException("Test " + testData.Class + " Failed" , Location); } // Used for reporting the final result from the task. if (errorOccurred) { _errorsPresent = true; } if (failureOccurred) { _failuresPresent = true; } } // TODO implement launching in a seperate App Domain private RunnerResult ExecuteInAppDomain(NUnitTestData test) { // spawn new domain in specified directory AppDomainSetup domSetup = new AppDomainSetup(); domSetup.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase; domSetup.ConfigurationFile = Project.GetFullPath(test.AppConfigFile); domSetup.ApplicationName = "NAnt Remote Domain"; PermissionSet domainPermSet = new PermissionSet(PermissionState.Unrestricted); AppDomain newDomain = AppDomain.CreateDomain(domSetup.ApplicationName, AppDomain.CurrentDomain.Evidence, domSetup, domainPermSet); // instantiate subclassed test runner in new domain Type runnerType = typeof(RemoteNUnitTestRunner); ObjectHandle oh = newDomain.CreateInstance ( runnerType.Assembly.FullName, runnerType.FullName, false, 0, null, new object[] { test }, null, null, null ); RemoteNUnitTestRunner runner = (RemoteNUnitTestRunner)(oh.Unwrap()); Log(Level.Info, "Running '{0}'.", test.Class); runner.Run(string.Empty, Verbose); return runner.ResultCode; } private RunnerResult ExecuteInProc(NUnitTestData test) { try { NUnitTestRunner runner = new NUnitTestRunner(test); if (runner.NeedsRunning()) { Log(Level.Info, "Running '{0}'.", test.Class); runner.Run(string.Empty, Verbose); } else { Log(Level.Info, "Skipping '{0}' because tests haven't changed.", test.Class); } return runner.ResultCode; } catch (Exception ex) { throw new BuildException("Error running unit test.", Location, ex); } } #endregion Private Instance Methods } } nant-0.92-rc1/src/NAnt.NUnit/NUnit1/LogFormatter.cs0000644000175000017500000001276211757302274021576 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // // TO-DO : replace Console.WriteLine methods with logging method calls using System; using System.IO; using System.Text.RegularExpressions; using NUnit.Framework; namespace NAnt.NUnit1.Types { /// /// Prints information about running tests directly to the build log. /// public class LogFormatter : IResultFormatter { #region Public Instance Constructors public LogFormatter(string prefix, bool verbose) { if (prefix != null) { _prefix = prefix; } else { _prefix = String.Empty; } _verbose = verbose; } #endregion Public Instance Constructors #region Protected Instance Properties protected bool Verbose { get { return _verbose; } } protected string Prefix { get { return _prefix; } } #endregion Protected Instance Properties #region Implementation of IResultFormatter /// Not used, all output goes to Log class. public void SetOutput(TextWriter writer) { } /// Called when the whole test suite has started. public void StartTestSuite(NUnitTestData suite) { if (Verbose) { Console.WriteLine(Prefix + "------------------------------------------"); } } /// Called when the whole test suite has ended. public void EndTestSuite(TestResultExtra result) { if (Verbose) { Console.WriteLine(Prefix + "------------------------------------------"); } if (result.WasSuccessful) { Console.WriteLine(Prefix + "{0} tests: ALL SUCCESSFUL", result.RunCount); } else { Console.WriteLine(Prefix + "{0} tests: FAILURES: {1} ERRORS: {2}", result.RunCount, result.FailureCount, result.ErrorCount); } } #endregion Implementation of IResultFormatter #region Implementation of ITestListener public void AddError(ITest test, Exception e) { Console.WriteLine(Prefix + "ERROR: " + GetTestSummary(test)); Console.WriteLine(FormatError(e.StackTrace, e.Message)); if (Verbose) { Console.WriteLine(e.StackTrace); } } public void AddFailure(ITest test, AssertionFailedError e) { Console.WriteLine(Prefix + "FAILURE: " + GetTestSummary(test)); Console.WriteLine(FormatError(e.StackTrace, e.Message)); if (Verbose) { Console.WriteLine(e.StackTrace); } } public void StartTest(ITest test) { if (Verbose) { Console.WriteLine(Prefix + GetTestSummary(test)); } } public void EndTest(ITest test) { } #endregion Implementation of ITestListener #region Private Static Methods // NOTE: When test.ToString() displays something less stupid than // MethodName(Namespace.ClassName) think about changing to that. As it // is now its impossible to sort the test output. // The workaround is to use this method. private static string GetTestSummary(ITest test) { string nunitInfo = test.ToString(); return test.GetType().Name + "." + nunitInfo.Substring(0, nunitInfo.IndexOf('(')); } /// Convert a stack trace line into something that can be clicked on in an IDE output window. /// The StackTrace string, see . /// The string that gets appended to the end of file(line): portion. private static string FormatError(string trace, string message) { // if we can't find a filename(line#) string, then at least display the message string line = message; string[] lines = trace.Split(new char[] {'\n'}); // search the stack trace for the first filename(linenumber) like string Regex r = new Regex(@"^\s+at (?.+) in (?.+):line (?\d+)$"); foreach (string str in lines) { Match match = r.Match(str); if (match.Success) { line = match.Result("${file}(${line}): ") + message; break; // no need to continue } } return line; } #endregion Private Static Methods #region Private Instance Fields private string _prefix; private bool _verbose; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.NUnit/NUnit1/NUnitTestCollection.cs0000644000175000017500000002147111757302274023077 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; namespace NAnt.NUnit1.Types { /// /// Contains a strongly typed collection of objects. /// [Serializable] public class NUnitTestCollection : CollectionBase { #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public NUnitTestCollection() { } /// /// Initializes a new instance of the class /// with the specified instance. /// public NUnitTestCollection(NUnitTestCollection value) { AddRange(value); } /// /// Initializes a new instance of the class /// with the specified array of instances. /// public NUnitTestCollection(NUnitTest[] value) { AddRange(value); } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets the element at the specified index. /// /// The zero-based index of the element to get or set. [System.Runtime.CompilerServices.IndexerName("Item")] public NUnitTest this[int index] { get {return ((NUnitTest)(base.List[index]));} set {base.List[index] = value;} } #endregion Public Instance Properties #region Public Instance Methods /// /// Adds a to the end of the collection. /// /// The to be added to the end of the collection. /// The position into which the new element was inserted. public int Add(NUnitTest item) { return base.List.Add(item); } /// /// Adds the elements of a array to the end of the collection. /// /// The array of elements to be added to the end of the collection. public void AddRange(NUnitTest[] items) { for (int i = 0; (i < items.Length); i = (i + 1)) { Add(items[i]); } } /// /// Adds the elements of a to the end of the collection. /// /// The to be added to the end of the collection. public void AddRange(NUnitTestCollection items) { for (int i = 0; (i < items.Count); i = (i + 1)) { Add(items[i]); } } /// /// Determines whether a is in the collection. /// /// The to locate in the collection. /// /// if is found in the /// collection; otherwise, . /// public bool Contains(NUnitTest item) { return base.List.Contains(item); } /// /// Copies the entire collection to a compatible one-dimensional array, starting at the specified index of the target array. /// /// The one-dimensional array that is the destination of the elements copied from the collection. The array must have zero-based indexing. /// The zero-based index in at which copying begins. public void CopyTo(NUnitTest[] array, int index) { base.List.CopyTo(array, index); } /// /// Retrieves the index of a specified object in the collection. /// /// The object for which the index is returned. /// /// The index of the specified . If the is not currently a member of the collection, it returns -1. /// public int IndexOf(NUnitTest item) { return base.List.IndexOf(item); } /// /// Inserts a into the collection at the specified index. /// /// The zero-based index at which should be inserted. /// The to insert. public void Insert(int index, NUnitTest item) { base.List.Insert(index, item); } /// /// Returns an enumerator that can iterate through the collection. /// /// /// A for the entire collection. /// public new NUnitTestEnumerator GetEnumerator() { return new NUnitTestEnumerator(this); } /// /// Removes a member from the collection. /// /// The to remove from the collection. public void Remove(NUnitTest item) { base.List.Remove(item); } #endregion Public Instance Methods } /// /// Enumerates the elements of a . /// public class NUnitTestEnumerator : IEnumerator { #region Internal Instance Constructors /// /// Initializes a new instance of the class /// with the specified . /// /// The collection that should be enumerated. internal NUnitTestEnumerator(NUnitTestCollection arguments) { IEnumerable temp = (IEnumerable) (arguments); _baseEnumerator = temp.GetEnumerator(); } #endregion Internal Instance Constructors #region Implementation of IEnumerator /// /// Gets the current element in the collection. /// /// /// The current element in the collection. /// public NUnitTest Current { get { return (NUnitTest) _baseEnumerator.Current; } } object IEnumerator.Current { get { return _baseEnumerator.Current; } } /// /// Advances the enumerator to the next element of the collection. /// /// /// if the enumerator was successfully advanced /// to the next element; if the enumerator has /// passed the end of the collection. /// public bool MoveNext() { return _baseEnumerator.MoveNext(); } bool IEnumerator.MoveNext() { return _baseEnumerator.MoveNext(); } /// /// Sets the enumerator to its initial position, which is before the /// first element in the collection. /// public void Reset() { _baseEnumerator.Reset(); } void IEnumerator.Reset() { _baseEnumerator.Reset(); } #endregion Implementation of IEnumerator #region Private Instance Fields private IEnumerator _baseEnumerator; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.NUnit/NUnit1/IResultFormatterCollection.cs0000644000175000017500000002222011757302274024446 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; namespace NAnt.NUnit1.Types { /// /// Contains a strongly typed collection of objects. /// [Serializable] public class IResultFormatterCollection : CollectionBase { #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public IResultFormatterCollection() { } /// /// Initializes a new instance of the class /// with the specified instance. /// public IResultFormatterCollection(IResultFormatterCollection value) { AddRange(value); } /// /// Initializes a new instance of the class /// with the specified array of instances. /// public IResultFormatterCollection(IResultFormatter[] value) { AddRange(value); } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets the element at the specified index. /// /// The zero-based index of the element to get or set. [System.Runtime.CompilerServices.IndexerName("Item")] public IResultFormatter this[int index] { get {return ((IResultFormatter)(base.List[index]));} set {base.List[index] = value;} } #endregion Public Instance Properties #region Public Instance Methods /// /// Adds a to the end of the collection. /// /// The to be added to the end of the collection. /// The position into which the new element was inserted. public int Add(IResultFormatter item) { return base.List.Add(item); } /// /// Adds the elements of a array to the end of the collection. /// /// The array of elements to be added to the end of the collection. public void AddRange(IResultFormatter[] items) { for (int i = 0; (i < items.Length); i = (i + 1)) { Add(items[i]); } } /// /// Adds the elements of a to the end of the collection. /// /// The to be added to the end of the collection. public void AddRange(IResultFormatterCollection items) { for (int i = 0; (i < items.Count); i = (i + 1)) { Add(items[i]); } } /// /// Determines whether a is in the collection. /// /// The to locate in the collection. /// /// if is found in the /// collection; otherwise, . /// public bool Contains(IResultFormatter item) { return base.List.Contains(item); } /// /// Copies the entire collection to a compatible one-dimensional array, starting at the specified index of the target array. /// /// The one-dimensional array that is the destination of the elements copied from the collection. The array must have zero-based indexing. /// The zero-based index in at which copying begins. public void CopyTo(IResultFormatter[] array, int index) { base.List.CopyTo(array, index); } /// /// Retrieves the index of a specified object in the collection. /// /// The object for which the index is returned. /// /// The index of the specified . If the is not currently a member of the collection, it returns -1. /// public int IndexOf(IResultFormatter item) { return base.List.IndexOf(item); } /// /// Inserts a into the collection at the specified index. /// /// The zero-based index at which should be inserted. /// The to insert. public void Insert(int index, IResultFormatter item) { base.List.Insert(index, item); } /// /// Returns an enumerator that can iterate through the collection. /// /// /// A for the entire collection. /// public new IResultFormatterEnumerator GetEnumerator() { return new IResultFormatterEnumerator(this); } /// /// Removes a member from the collection. /// /// The to remove from the collection. public void Remove(IResultFormatter item) { base.List.Remove(item); } #endregion Public Instance Methods } /// /// Enumerates the elements of a . /// public class IResultFormatterEnumerator : IEnumerator { #region Internal Instance Constructors /// /// Initializes a new instance of the class /// with the specified . /// /// The collection that should be enumerated. internal IResultFormatterEnumerator(IResultFormatterCollection arguments) { IEnumerable temp = (IEnumerable) (arguments); _baseEnumerator = temp.GetEnumerator(); } #endregion Internal Instance Constructors #region Implementation of IEnumerator /// /// Gets the current element in the collection. /// /// /// The current element in the collection. /// public IResultFormatter Current { get { return (IResultFormatter) _baseEnumerator.Current; } } object IEnumerator.Current { get { return _baseEnumerator.Current; } } /// /// Advances the enumerator to the next element of the collection. /// /// /// if the enumerator was successfully advanced /// to the next element; if the enumerator has /// passed the end of the collection. /// public bool MoveNext() { return _baseEnumerator.MoveNext(); } bool IEnumerator.MoveNext() { return _baseEnumerator.MoveNext(); } /// /// Sets the enumerator to its initial position, which is before the /// first element in the collection. /// public void Reset() { _baseEnumerator.Reset(); } void IEnumerator.Reset() { _baseEnumerator.Reset(); } #endregion Implementation of IEnumerator #region Private Instance Fields private IEnumerator _baseEnumerator; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.NUnit/NUnit1/RemoteNUnitTestRunner.cs0000644000175000017500000000342011757302274023423 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Tomas Restrepo (tomasr@mvps.org) using System; using NAnt.NUnit1.Types; namespace NAnt.NUnit1.Tasks { public class RemoteNUnitTestRunner : MarshalByRefObject { #region Public Instance Constructors public RemoteNUnitTestRunner(NUnitTestData testData) { _runner = new NUnitTestRunner(testData); } #endregion Public Instance Constructors #region Public Instance Properties public RunnerResult ResultCode { get { return _runner.ResultCode; } } public IResultFormatterCollection Formatters { get { return _runner.Formatters; } } #endregion Public Instance Properties #region Public Instance Methods public void Run(string logPrefix, bool verbose) { _runner.Run(logPrefix, verbose); } #endregion Public Instance Methods #region Private Instance Fields private NUnitTestRunner _runner; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.NUnit/NUnit1/NUnitTest.cs0000644000175000017500000001110611757302274021055 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian MacLean (ian_maclean@another.com) // Gert Driesen (drieseng@users.sourceforge.net) using System; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.NUnit1.Tasks; namespace NAnt.NUnit1.Types { /// /// Represents a test element of an . /// [ElementName("test")] public class NUnitTest : Element { #region Private Instance Fields private string _class = null; private string _assembly = null; private bool _fork = false; private bool _haltonerror = false; private bool _haltonfailure = false; private string _appConfigFile = null; private string _todir = null; private string _outfile = null; #endregion Private Instance Fields #region Public Instance Properties /// /// Base name of the test result. The full filename is determined by this /// attribute and the extension of formatter. /// [TaskAttribute("outfile")] public string OutFile { get { return _outfile; } set { _outfile = value; } } /// /// Directory to write the reports to. /// [TaskAttribute("todir")] public string ToDir { get { return _todir; } set { _todir = value; } } /// /// Class name of the test. /// [TaskAttribute("class", Required=true)] [StringValidator(AllowEmpty=false)] public string Class { get { return _class; } set { _class = value; } } /// /// Assembly to load the test from. /// [TaskAttribute("assembly", Required=true)] [StringValidator(AllowEmpty=false)] public string Assembly { get { return Project.GetFullPath(_assembly); } set { _assembly = value; } } /// /// Run the tests in a separate . /// [TaskAttribute("fork")] [BooleanValidator()] public bool Fork { get { return _fork; } set { _fork = value; } } /// /// Stop the build process if an error occurs during the test run. /// [TaskAttribute("haltonerror")] [BooleanValidator()] public bool HaltOnError { get { return _haltonerror; } set { _haltonerror = value; } } /// /// Stop the build process if a test fails (errors are considered failures /// as well). /// [TaskAttribute("haltonfailure")] [BooleanValidator()] public bool HaltOnFailure { get { return _haltonfailure; } set { _haltonfailure = value; } } /// /// The application configuration file to use for the NUnit test domain. /// [TaskAttribute("appconfig")] public string AppConfigFile { get { return _appConfigFile; } set { _appConfigFile = value; } } #endregion Public Instance Properties #region Internal Instance Methods internal NUnitTestData GetTestData() { NUnitTestData data = new NUnitTestData(); data.OutFile = OutFile; data.ToDir = ToDir; data.Class = Class; data.Assembly = Assembly; data.Fork = Fork; data.HaltOnError = HaltOnError; data.HaltOnFailure = HaltOnFailure; data.AppConfigFile = AppConfigFile; return data; } #endregion Internal Instance Methods } } nant-0.92-rc1/src/NAnt.NUnit/NUnit1/NUnitTestRunner.cs0000644000175000017500000002516311757302274022257 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian MacLean (ian_maclean@another.com) // Gerry Shaw (gerry_shaw@yahoo.com) using System; using System.Globalization; using System.IO; using System.Xml; using NUnit.Framework; using NUnit.Runner; using NAnt.NUnit.Types; using NAnt.NUnit1.Types; namespace NAnt.NUnit1.Tasks { public enum RunnerResult { Success, Failures, Errors, } public class NUnitTestRunner : BaseTestRunner { #region Public Instance Constructors public NUnitTestRunner(NUnitTestData testData) { _nunittest = testData; string nunitsuite = testData.Class + "," + testData.Assembly; _suite = GetSuite(nunitsuite); testData.Suite = _suite; } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets the collection of registered formatters. /// /// Collection of registered formatters. public IResultFormatterCollection Formatters { get { return _formatters; } } /// /// Gets the result of the test. /// /// The result of the test. public RunnerResult ResultCode { get { return _resultCode; } } #endregion Public Instance Properties #region Override implementation of BaseTestRunner protected override void RunFailed(string message) { } #endregion Override implementation of BaseTestRunner #region Override implementation of IListener public override void AddError(ITest test, Exception t) { foreach (IResultFormatter formatter in Formatters) { formatter.AddError(test, t); } if (_nunittest.HaltOnError) { _result.Stop(); } } public override void AddFailure(ITest test, AssertionFailedError t) { foreach (IResultFormatter formatter in Formatters) { formatter.AddFailure(test, t); } if (_nunittest.HaltOnFailure) { _result.Stop(); } } public override void StartTest(ITest test) { foreach (IResultFormatter formatter in Formatters) { formatter.StartTest(test); } } public override void EndTest(ITest test) { foreach (IResultFormatter formatter in Formatters) { formatter.EndTest(test); } } #endregion Override implementation of IListener #region Public Instance Methods /// /// Determines if the unit test needs running. /// /// /// if unit test needs running, otherwise, /// . /// /// /// /// Determines if the test needs running by looking at the date stamp /// of the test assembly and the test results log. /// /// public bool NeedsRunning() { // assume we need to run unless proven otherwise bool needsRunning = true; string assemblyFileName = _nunittest.Assembly; string logFileName = _nunittest.OutFile + ".xml"; if (File.Exists(logFileName) && File.Exists(assemblyFileName)) { DateTime assemblyDateStamp = File.GetLastWriteTime(assemblyFileName); DateTime logDataStamp = File.GetLastWriteTime(logFileName); // simple check of datestamps normally works if (logDataStamp > assemblyDateStamp) { // date stamps are ok // look inside results to see if there were failures or errors try { XmlDocument doc = new XmlDocument(); doc.Load(logFileName); // check for errors or failures // int errors = Convert.ToInt32(doc.DocumentElement.Attributes["errors"].Value, NumberFormatInfo.InvariantInfo); int failuers = Convert.ToInt32(doc.DocumentElement.Attributes["failures"].Value, NumberFormatInfo.InvariantInfo); if (errors == 0 && failuers == 0) { // no previous errors or failures and the assembly date stamp is older // than the log so it should be safe to skip running the tests this time. needsRunning = false; } } catch { // some sort of error parsing xml, so just run the tests again } } } return needsRunning; } /// /// Runs a Suite extracted from a TestCase subclass. /// public void Run(string logPrefix, bool verbose) { CreateFormatters(_nunittest, logPrefix, verbose); _result = new TestResultExtra(); _result.AddListener(this); long startTime = System.DateTime.Now.Ticks; // Handle start OnStartTestSuite(); _suite.Run(_result); // finished test long endTime = System.DateTime.Now.Ticks; long runTime = (endTime-startTime) / 10000; _result.RunTime = runTime; // Handle completion OnEndTestSuite(); if (_result.WasSuccessful == false) { if (_result.ErrorCount != 0) { _resultCode = RunnerResult.Errors; } else if (_result.FailureCount !=0) { _resultCode = RunnerResult.Failures; } } } #endregion Public Instance Methods #region Protected Instance Methods /// /// Creates the formatters to be used when running this test. /// protected void CreateFormatters(NUnitTestData testData, string logPrefix, bool verbose) { // Now add the specified formatters foreach (FormatterData formatterData in testData.Formatters) { // determine file FileInfo outFile = GetOutput(formatterData, testData); IResultFormatter formatter = CreateFormatter(formatterData.Type, outFile); Formatters.Add(formatter); } // Add default formatter // The Log formatter is special in that it always writes to the // Log class rather than the TextWriter set in SetOutput(). // HACK! LogFormatter logFormatter = new LogFormatter(logPrefix, verbose); Formatters.Add(logFormatter); } /// /// Returns the output file or null if does not use a file. /// protected FileInfo GetOutput(FormatterData formatterData, NUnitTestData test) { if (formatterData.UseFile) { string filename = test.OutFile + formatterData.Extension; string absFilename = Path.Combine(test.ToDir, filename); return new FileInfo(absFilename); } return null; } protected IResultFormatter CreateFormatter(FormatterType type, FileInfo outfile) { IResultFormatter retFormatter = null; switch (type) { case FormatterType.Plain: retFormatter = (IResultFormatter) new PlainTextFormatter(); break; case FormatterType.Xml: retFormatter = (IResultFormatter) new XmlResultFormatter(); break; default: break; } if (outfile == null) { // TO-DO : find solution for creating LogWriter without access to Task or Project // for dispatching logging events // retFormatter.SetOutput(new LogWriter()); retFormatter.SetOutput(Console.Out); } else { retFormatter.SetOutput(new StreamWriter(outfile.Create())); } return retFormatter; } #endregion Protected Instance Methods #region Private Instance Methods /// /// Returns the test suite from a given class. /// /// /// The assemblyQualifiedName parameter needs to be in form: /// "full.qualified.class.name,Assembly" /// private ITest GetSuite(string assemblyQualifiedName) { // Don't worry about catching exceptions in this method. The // NUnitTask will catch them and throw a BuildException back to // NAnt with the correct location in the build file. [gs] StandardLoader loader = new StandardLoader(); ITest test = loader.LoadTest(assemblyQualifiedName); return test; } private void OnStartTestSuite() { foreach (IResultFormatter formatter in Formatters) { formatter.StartTestSuite(_nunittest); } } private void OnEndTestSuite() { foreach (IResultFormatter formatter in Formatters) { formatter.EndTestSuite(_result); } } #endregion Private Instance Methods #region Private Instance Fields IResultFormatterCollection _formatters = new IResultFormatterCollection(); NUnitTestData _nunittest = null; ITest _suite = null; TestResultExtra _result = null; RunnerResult _resultCode = RunnerResult.Success; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.NUnit/NUnit1/NAnt.NUnit1.csproj0000644000175000017500000001131311757302274022030 0ustar jtaylorjtaylor Debug AnyCPU 2.0 {0F3EA7A9-C5F6-4254-820C-B5E0409B5B9D} NAnt.NUnit1 NAnt.NUnit1Tasks Library OnSuccessfulBuild false 8.0.50727 v2.0 2.0 publish\ true Disk false Foreground 7 Days false false true 0 1.0.0.%2a false false true true full false 4 ..\..\build\Debug\ AllRules.ruleset TRACE;DEBUG ..\..\build\Debug\NAnt.NUnit1Tasks.xml true pdbonly true ..\..\build\Release\ 4 AllRules.ruleset TRACE ..\..\build\Release\NAnt.NUnit1Tasks.xml ..\..\..\lib\common\neutral\NUnitCore.dll CommonAssemblyInfo.cs False .NET Framework 3.5 SP1 Client Profile false False .NET Framework 3.5 SP1 true False Windows Installer 3.1 true {8F5F8375-4097-4952-B860-784EB9961ABE} NAnt.Core {00F5C075-9874-4BCE-909A-99C1F600E047} NAnt.NUnit nant-0.92-rc1/src/NAnt.NUnit/NUnit1/NUnitTestData.cs0000644000175000017500000000552011757302274021652 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Tomas Restrepo (tomasr@mvps.org) // Gert Driesen (drieseng@users.sourceforge.net) using System; using NUnit.Framework; using NAnt.NUnit.Types; namespace NAnt.NUnit1.Types { /// /// Carries data specified through the test element. /// [Serializable] public class NUnitTestData { #region Public Instance Properties public ITest Suite { get { return _suite; } set { _suite = value; } } public string OutFile { get { return _outfile; } set {_outfile = value;} } public string ToDir { get { return _todir; } set {_todir = value;} } public string Class { get { return _class; } set { _class = value; } } public string Assembly { get { return _assembly; } set { _assembly = value; } } public bool Fork { get { return _fork; } set { _fork = value; } } public bool HaltOnError { get { return _haltonerror; } set { _haltonerror = value; } } public bool HaltOnFailure { get { return _haltonfailure; } set { _haltonfailure = value; } } public FormatterDataCollection Formatters { get { return _formatters; } } public string AppConfigFile { get { return _appConfigFile; } set { _appConfigFile = value; } } #endregion Public Instance Properties #region Private Instance Fields string _todir = null; string _outfile = null; string _class = null; string _assembly = null; bool _fork = false; bool _haltonerror = false; bool _haltonfailure = false; ITest _suite = null; FormatterDataCollection _formatters = new FormatterDataCollection(); string _appConfigFile = null; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.NUnit/NAnt.NUnit.csproj0000644000175000017500000001010211757302274020624 0ustar jtaylorjtaylor Debug AnyCPU 2.0 {00F5C075-9874-4BCE-909A-99C1F600E047} NAnt.NUnit NAnt.NUnit Library OnSuccessfulBuild false 8.0.50727 v2.0 2.0 publish\ true Disk false Foreground 7 Days false false true 0 1.0.0.%2a false false true true full false 4 ..\..\build\Debug\ AllRules.ruleset TRACE;DEBUG ..\..\build\Debug\NAnt.NUnit.xml true pdbonly true ..\..\build\Release\ 4 AllRules.ruleset TRACE ..\..\build\Release\NAnt.NUnit.xml CommonAssemblyInfo.cs False .NET Framework 3.5 SP1 Client Profile false False .NET Framework 3.5 SP1 true False Windows Installer 3.1 true {8F5F8375-4097-4952-B860-784EB9961ABE} NAnt.Core nant-0.92-rc1/src/NAnt.NUnit/FormatterElement.cs0000644000175000017500000000650511757302274021326 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian MacLean (ian_maclean@another.com) using System; using System.IO; using System.Xml; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Util; namespace NAnt.NUnit.Types { /// /// The built-in formatter types. /// public enum FormatterType { /// /// A plaintext formatter. /// Plain, /// /// An XML formatter. /// Xml } /// /// Represents the FormatterElement of the NUnit task. /// [ElementName("formatter")] public class FormatterElement : NAnt.Core.Element { #region Private Instance Fields private FormatterData _data = new FormatterData(); #endregion Private Instance Fields #region Public Instance Properties /// /// Type of formatter. /// [TaskAttribute("type", Required=true)] public FormatterType Type { get { return _data.Type; } set { _data.Type = value; } } /// /// Extension to append to the output filename. /// [TaskAttribute("extension", Required=false)] public string Extension { get { return StringUtils.ConvertNullToEmpty(_data.Extension); } set { _data.Extension = value; } } /// /// Determines whether output should be persisted to a file. The default /// is . /// [TaskAttribute("usefile", Required=false)] [BooleanValidator()] public bool UseFile { get { return _data.UseFile; } set { _data.UseFile = value; } } /// /// Specifies the directory where the output file should be written to, /// if is . If not /// specified, the output file will be written to the directory where /// the test module is located. /// [TaskAttribute("outputdir", Required=false)] public DirectoryInfo OutputDirectory { get { return _data.OutputDirectory; } set { _data.OutputDirectory = value; } } /// /// Gets the underlying for the element. /// public FormatterData Data { get { return _data; } } #endregion Public Instance Properties } } nant-0.92-rc1/src/NAnt.NUnit/FormatterElementCollection.cs0000644000175000017500000002221711757302274023340 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; namespace NAnt.NUnit.Types { /// /// Contains a strongly typed collection of objects. /// [Serializable] public class FormatterElementCollection : CollectionBase { #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public FormatterElementCollection() { } /// /// Initializes a new instance of the class /// with the specified instance. /// public FormatterElementCollection(FormatterElementCollection value) { AddRange(value); } /// /// Initializes a new instance of the class /// with the specified array of instances. /// public FormatterElementCollection(FormatterElement[] value) { AddRange(value); } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets the element at the specified index. /// /// The zero-based index of the element to get or set. [System.Runtime.CompilerServices.IndexerName("Item")] public FormatterElement this[int index] { get {return ((FormatterElement)(base.List[index]));} set {base.List[index] = value;} } #endregion Public Instance Properties #region Public Instance Methods /// /// Adds a to the end of the collection. /// /// The to be added to the end of the collection. /// The position into which the new element was inserted. public int Add(FormatterElement item) { return base.List.Add(item); } /// /// Adds the elements of a array to the end of the collection. /// /// The array of elements to be added to the end of the collection. public void AddRange(FormatterElement[] items) { for (int i = 0; (i < items.Length); i = (i + 1)) { Add(items[i]); } } /// /// Adds the elements of a to the end of the collection. /// /// The to be added to the end of the collection. public void AddRange(FormatterElementCollection items) { for (int i = 0; (i < items.Count); i = (i + 1)) { Add(items[i]); } } /// /// Determines whether a is in the collection. /// /// The to locate in the collection. /// /// if is found in the /// collection; otherwise, . /// public bool Contains(FormatterElement item) { return base.List.Contains(item); } /// /// Copies the entire collection to a compatible one-dimensional array, starting at the specified index of the target array. /// /// The one-dimensional array that is the destination of the elements copied from the collection. The array must have zero-based indexing. /// The zero-based index in at which copying begins. public void CopyTo(FormatterElement[] array, int index) { base.List.CopyTo(array, index); } /// /// Retrieves the index of a specified object in the collection. /// /// The object for which the index is returned. /// /// The index of the specified . If the is not currently a member of the collection, it returns -1. /// public int IndexOf(FormatterElement item) { return base.List.IndexOf(item); } /// /// Inserts a into the collection at the specified index. /// /// The zero-based index at which should be inserted. /// The to insert. public void Insert(int index, FormatterElement item) { base.List.Insert(index, item); } /// /// Returns an enumerator that can iterate through the collection. /// /// /// A for the entire collection. /// public new FormatterElementEnumerator GetEnumerator() { return new FormatterElementEnumerator(this); } /// /// Removes a member from the collection. /// /// The to remove from the collection. public void Remove(FormatterElement item) { base.List.Remove(item); } #endregion Public Instance Methods } /// /// Enumerates the elements of a . /// public class FormatterElementEnumerator : IEnumerator { #region Internal Instance Constructors /// /// Initializes a new instance of the class /// with the specified . /// /// The collection that should be enumerated. internal FormatterElementEnumerator(FormatterElementCollection arguments) { IEnumerable temp = (IEnumerable) (arguments); _baseEnumerator = temp.GetEnumerator(); } #endregion Internal Instance Constructors #region Implementation of IEnumerator /// /// Gets the current element in the collection. /// /// /// The current element in the collection. /// public FormatterElement Current { get { return (FormatterElement) _baseEnumerator.Current; } } object IEnumerator.Current { get { return _baseEnumerator.Current; } } /// /// Advances the enumerator to the next element of the collection. /// /// /// if the enumerator was successfully advanced /// to the next element; if the enumerator has /// passed the end of the collection. /// public bool MoveNext() { return _baseEnumerator.MoveNext(); } bool IEnumerator.MoveNext() { return _baseEnumerator.MoveNext(); } /// /// Sets the enumerator to its initial position, which is before the /// first element in the collection. /// public void Reset() { _baseEnumerator.Reset(); } void IEnumerator.Reset() { _baseEnumerator.Reset(); } #endregion Implementation of IEnumerator #region Private Instance Fields private IEnumerator _baseEnumerator; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.NUnit/FormatterDataCollection.cs0000644000175000017500000002177411757302274022627 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; namespace NAnt.NUnit.Types { /// /// Contains a strongly typed collection of objects. /// [Serializable] public class FormatterDataCollection : CollectionBase { #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public FormatterDataCollection() { } /// /// Initializes a new instance of the class /// with the specified instance. /// public FormatterDataCollection(FormatterDataCollection value) { AddRange(value); } /// /// Initializes a new instance of the class /// with the specified array of instances. /// public FormatterDataCollection(FormatterData[] value) { AddRange(value); } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets the element at the specified index. /// /// The zero-based index of the element to get or set. [System.Runtime.CompilerServices.IndexerName("Item")] public FormatterData this[int index] { get {return ((FormatterData)(base.List[index]));} set {base.List[index] = value;} } #endregion Public Instance Properties #region Public Instance Methods /// /// Adds a to the end of the collection. /// /// The to be added to the end of the collection. /// The position into which the new element was inserted. public int Add(FormatterData item) { return base.List.Add(item); } /// /// Adds the elements of a array to the end of the collection. /// /// The array of elements to be added to the end of the collection. public void AddRange(FormatterData[] items) { for (int i = 0; (i < items.Length); i = (i + 1)) { Add(items[i]); } } /// /// Adds the elements of a to the end of the collection. /// /// The to be added to the end of the collection. public void AddRange(FormatterDataCollection items) { for (int i = 0; (i < items.Count); i = (i + 1)) { Add(items[i]); } } /// /// Determines whether a is in the collection. /// /// The to locate in the collection. /// /// if is found in the /// collection; otherwise, . /// public bool Contains(FormatterData item) { return base.List.Contains(item); } /// /// Copies the entire collection to a compatible one-dimensional array, starting at the specified index of the target array. /// /// The one-dimensional array that is the destination of the elements copied from the collection. The array must have zero-based indexing. /// The zero-based index in at which copying begins. public void CopyTo(FormatterData[] array, int index) { base.List.CopyTo(array, index); } /// /// Retrieves the index of a specified object in the collection. /// /// The object for which the index is returned. /// /// The index of the specified . If the is not currently a member of the collection, it returns -1. /// public int IndexOf(FormatterData item) { return base.List.IndexOf(item); } /// /// Inserts a into the collection at the specified index. /// /// The zero-based index at which should be inserted. /// The to insert. public void Insert(int index, FormatterData item) { base.List.Insert(index, item); } /// /// Returns an enumerator that can iterate through the collection. /// /// /// A for the entire collection. /// public new FormatterDataEnumerator GetEnumerator() { return new FormatterDataEnumerator(this); } /// /// Removes a member from the collection. /// /// The to remove from the collection. public void Remove(FormatterData item) { base.List.Remove(item); } #endregion Public Instance Methods } /// /// Enumerates the elements of a . /// public class FormatterDataEnumerator : IEnumerator { #region Internal Instance Constructors /// /// Initializes a new instance of the class /// with the specified . /// /// The collection that should be enumerated. internal FormatterDataEnumerator(FormatterDataCollection arguments) { IEnumerable temp = (IEnumerable) (arguments); _baseEnumerator = temp.GetEnumerator(); } #endregion Internal Instance Constructors #region Implementation of IEnumerator /// /// Gets the current element in the collection. /// /// /// The current element in the collection. /// public FormatterData Current { get { return (FormatterData) _baseEnumerator.Current; } } object IEnumerator.Current { get { return _baseEnumerator.Current; } } /// /// Advances the enumerator to the next element of the collection. /// /// /// if the enumerator was successfully advanced /// to the next element; if the enumerator has /// passed the end of the collection. /// public bool MoveNext() { return _baseEnumerator.MoveNext(); } bool IEnumerator.MoveNext() { return _baseEnumerator.MoveNext(); } /// /// Sets the enumerator to its initial position, which is before the /// first element in the collection. /// public void Reset() { _baseEnumerator.Reset(); } void IEnumerator.Reset() { _baseEnumerator.Reset(); } #endregion Implementation of IEnumerator #region Private Instance Fields private IEnumerator _baseEnumerator; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.NUnit/NUnit2/0000755000175000017500000000000011757310030016620 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.NUnit/NUnit2/NAnt.NUnit2.csproj0000644000175000017500000001205411757302274022035 0ustar jtaylorjtaylor Debug AnyCPU 2.0 {47503BEE-27D9-4D1C-B8E1-6C9CCC19AEAA} NAnt.NUnit2 NAnt.NUnit2Tasks Library OnSuccessfulBuild false 8.0.50727 v2.0 2.0 publish\ true Disk false Foreground 7 Days false false true 0 1.0.0.%2a false false true true full false 4 ..\..\build\Debug\ AllRules.ruleset TRACE;DEBUG ..\..\build\Debug\NAnt.NUnit2Tasks.xml true pdbonly true ..\..\build\Release\ 4 AllRules.ruleset TRACE ..\..\build\Release\NAnt.NUnit2Tasks.xml ..\..\..\lib\common\2.0\nunit.core.dll ..\..\..\lib\common\2.0\nunit.core.interfaces.dll ..\..\..\lib\common\2.0\nunit.framework.dll ..\..\..\lib\common\2.0\nunit.util.dll CommonAssemblyInfo.cs False .NET Framework 3.5 SP1 Client Profile false False .NET Framework 3.5 SP1 true False Windows Installer 3.1 true {8F5F8375-4097-4952-B860-784EB9961ABE} NAnt.Core {B50A1067-785B-4686-8FFC-5AF424BEF163} NAnt.DotNet {00F5C075-9874-4BCE-909A-99C1F600E047} NAnt.NUnit nant-0.92-rc1/src/NAnt.NUnit/NUnit2/NUNit2TestCollection.cs0000644000175000017500000002155211757302274023122 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; namespace NAnt.NUnit2.Types { /// /// Contains a strongly typed collection of objects. /// [Serializable] public class NUnit2TestCollection : CollectionBase { #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public NUnit2TestCollection() { } /// /// Initializes a new instance of the class /// with the specified instance. /// public NUnit2TestCollection(NUnit2TestCollection value) { AddRange(value); } /// /// Initializes a new instance of the class /// with the specified array of instances. /// public NUnit2TestCollection(NUnit2Test[] value) { AddRange(value); } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets the element at the specified index. /// /// The zero-based index of the element to get or set. [System.Runtime.CompilerServices.IndexerName("Item")] public NUnit2Test this[int index] { get {return ((NUnit2Test)(base.List[index]));} set {base.List[index] = value;} } #endregion Public Instance Properties #region Public Instance Methods /// /// Adds a to the end of the collection. /// /// The to be added to the end of the collection. /// The position into which the new element was inserted. public int Add(NUnit2Test item) { return base.List.Add(item); } /// /// Adds the elements of a array to the end of the collection. /// /// The array of elements to be added to the end of the collection. public void AddRange(NUnit2Test[] items) { for (int i = 0; (i < items.Length); i = (i + 1)) { Add(items[i]); } } /// /// Adds the elements of a to the end of the collection. /// /// The to be added to the end of the collection. public void AddRange(NUnit2TestCollection items) { for (int i = 0; (i < items.Count); i = (i + 1)) { Add(items[i]); } } /// /// Determines whether a is in the collection. /// /// The to locate in the collection. /// /// if is found in the /// collection; otherwise, . /// public bool Contains(NUnit2Test item) { return base.List.Contains(item); } /// /// Copies the entire collection to a compatible one-dimensional array, starting at the specified index of the target array. /// /// The one-dimensional array that is the destination of the elements copied from the collection. The array must have zero-based indexing. /// The zero-based index in at which copying begins. public void CopyTo(NUnit2Test[] array, int index) { base.List.CopyTo(array, index); } /// /// Retrieves the index of a specified object in the collection. /// /// The object for which the index is returned. /// /// The index of the specified . If the is not currently a member of the collection, it returns -1. /// public int IndexOf(NUnit2Test item) { return base.List.IndexOf(item); } /// /// Inserts a into the collection at the specified index. /// /// The zero-based index at which should be inserted. /// The to insert. public void Insert(int index, NUnit2Test item) { base.List.Insert(index, item); } /// /// Returns an enumerator that can iterate through the collection. /// /// /// A for the entire collection. /// public new NUnit2TestEnumerator GetEnumerator() { return new NUnit2TestEnumerator(this); } /// /// Removes a member from the collection. /// /// The to remove from the collection. public void Remove(NUnit2Test item) { base.List.Remove(item); } #endregion Public Instance Methods } /// /// Enumerates the elements of a . /// public class NUnit2TestEnumerator : IEnumerator { #region Internal Instance Constructors /// /// Initializes a new instance of the class /// with the specified . /// /// The collection that should be enumerated. internal NUnit2TestEnumerator(NUnit2TestCollection arguments) { IEnumerable temp = (IEnumerable) (arguments); _baseEnumerator = temp.GetEnumerator(); } #endregion Internal Instance Constructors #region Implementation of IEnumerator /// /// Gets the current element in the collection. /// /// /// The current element in the collection. /// public NUnit2Test Current { get { return (NUnit2Test) _baseEnumerator.Current; } } object IEnumerator.Current { get { return _baseEnumerator.Current; } } /// /// Advances the enumerator to the next element of the collection. /// /// /// if the enumerator was successfully advanced /// to the next element; if the enumerator has /// passed the end of the collection. /// public bool MoveNext() { return _baseEnumerator.MoveNext(); } bool IEnumerator.MoveNext() { return _baseEnumerator.MoveNext(); } /// /// Sets the enumerator to its initial position, which is before the /// first element in the collection. /// public void Reset() { _baseEnumerator.Reset(); } void IEnumerator.Reset() { _baseEnumerator.Reset(); } #endregion Implementation of IEnumerator #region Private Instance Fields private IEnumerator _baseEnumerator; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.NUnit/NUnit2/AssemblyInfo.cs0000644000175000017500000000233211757302274021555 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Scott Hernandez (ScottHernandez@hotmail.com) // Gert Driesen (drieseng@users.sourceforge.net) using System.Reflection; // This will not compile with Visual Studio. If you want to build a signed // executable use the NAnt build file. To build under Visual Studio just // exclude this file from the build. [assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile(@"..\NAnt.key")] [assembly: AssemblyKeyName("")]nant-0.92-rc1/src/NAnt.NUnit/NUnit2/Types/0000755000175000017500000000000011757310030017724 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.NUnit/NUnit2/Types/Category.cs0000644000175000017500000000462311757302274022050 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2005 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Util; namespace NAnt.NUnit2.Types { /// /// Represents a certain group of test cases or fixtures. /// public class Category : Element { #region Private Instance Fields private string _name; private bool _ifDefined = true; private bool _unlessDefined; #endregion Private Instance Fields #region Public Instance Properties /// /// A name of a category, or comma-separated list of names. /// [TaskAttribute("name", Required=true)] public string CategoryName { get { return _name; } set { _name = StringUtils.ConvertEmptyToNull(value); } } /// /// If then the category will be processed; /// otherwise, skipped. The default is . /// [TaskAttribute("if")] [BooleanValidator()] public bool IfDefined { get { return _ifDefined; } set { _ifDefined = value; } } /// /// If then the category will be skipped; /// otherwise, processed. The default is . /// [TaskAttribute("unless")] [BooleanValidator()] public bool UnlessDefined { get { return _unlessDefined; } set { _unlessDefined = value; } } #endregion Public Instance Properties } } nant-0.92-rc1/src/NAnt.NUnit/NUnit2/Types/CategoryCollection.cs0000644000175000017500000001172711757302274024067 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2005 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) // Ryan Boggs (rmboggs@users.sourceforge.net) using System; using System.Collections; using System.Collections.ObjectModel; using System.Collections.Generic; using NAnt.Core.Util; namespace NAnt.NUnit2.Types { /// /// Contains a collection of elements. /// [Serializable()] public class CategoryCollection : Collection { #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public CategoryCollection() : base() { } /// /// Initializes a new instance of the /// class as a wrapper for /// the specified list. /// /// /// The list that is wrapped by the newly created instance. /// public CategoryCollection(IList value) : base(value) { } /// /// Initializes a new instance of the class /// with the specified instance. /// /// /// The collection to use to initialize the new instance with. /// public CategoryCollection(CategoryCollection value) : base(value) { } /// /// Initializes a new instance of the class /// with the specified array of instances. /// /// /// The collection to use to initialize the new instance with. /// public CategoryCollection(Category[] value) : base() { AddRange(value); } #endregion Public Instance Constructors #region Override implementation of Object /// /// Returns a comma-delimited list of categories. /// /// /// A comma-delimited list of categories, or an empty /// if there are no categories. /// public override string ToString() { List categories = new List(this.Count); foreach (Category category in this) { if (category.IfDefined && !category.UnlessDefined) { categories.Add(category.CategoryName); } } return String.Join(",", categories.ToArray()); } #endregion Override implementation of Object #region Public Instance Properties /// /// Gets the with the specified name. /// /// The name of the to get. [System.Runtime.CompilerServices.IndexerName("Item")] public Category this[string value] { get { if (value != null) { // Try to locate instance using Value foreach (Category category in this) { if (value.Equals(category.CategoryName)) { return category; } } } return null; } } #endregion Public Instance Properties #region Public Instance Methods /// /// Adds the elements of a array to the end of the /// collection. /// /// /// The array of elements to be added to the end of /// the collection. /// public void AddRange(IEnumerable items) { foreach (Category item in items) { Add(item); } } #endregion Public Instance Methods } }nant-0.92-rc1/src/NAnt.NUnit/NUnit2/Types/Categories.cs0000644000175000017500000000500311757302274022351 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2005 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.NUnit2.Tasks; namespace NAnt.NUnit2.Types { /// /// Controls the categories of tests to execute using the . /// /// /// /// Only include test cases and fixtures that require no internet access. /// /// /// /// /// /// ]]> /// /// /// /// /// Exclude test cases and fixtures that are known to fail. /// /// /// /// /// /// ]]> /// /// [ElementName("categories")] public class Categories : DataTypeBase { #region Private Instance Fields private CategoryCollection _includes = new CategoryCollection(); private CategoryCollection _excludes = new CategoryCollection(); #endregion Private Instance Fields #region Public Instance Properties /// /// Specifies a list of categories to include. /// [BuildElementArray("include")] public CategoryCollection Includes { get { return _includes; } } /// /// Specifies a list of categories to exclude. /// [BuildElementArray("exclude")] public CategoryCollection Excludes { get { return _excludes; } } #endregion Public Instance Properties } } nant-0.92-rc1/src/NAnt.NUnit/NUnit2/NUnit2Test.cs0000644000175000017500000001156311757302274021147 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Mike Two (2@thoughtworks.com or mike2@nunit.org) // Scott Hernandez (ScottHernandez@hotmail.com) using System.Collections.Specialized; using System.IO; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Types; using NAnt.DotNet.Types; using NAnt.NUnit.Types; using NAnt.NUnit2.Tasks; using NAnt.NUnit2.Types; namespace NAnt.NUnit2.Types { /// /// Represents a test element of an . /// [ElementName("test")] public class NUnit2Test : Element { #region Private Instance Fields private FileInfo _assemblyFile; private string _testname; private bool _haltOnFailure = true; private FileInfo _xsltFile; private AssemblyFileSet _assemblies = new AssemblyFileSet(); private AssemblyFileSet _references = new AssemblyFileSet(); private FileInfo _appConfigFile; private Categories _categories = new Categories(); #endregion Private Instance Fields #region Public Instance Properties /// /// Name of the assembly to search for tests. /// [TaskAttribute("assemblyname")] public FileInfo AssemblyFile { get { return _assemblyFile; } set { _assemblyFile = value; } } /// /// Name of a specific testfixture to run. If not specified then all /// testfixtures are run. /// [TaskAttribute("testname")] public string TestName { get { return _testname; } set { _testname = value; } } /// /// Assemblies to include in test. /// [BuildElement("assemblies")] public AssemblyFileSet Assemblies { get { return _assemblies; } set { _assemblies = value; } } /// /// Assemblies to scan for missing assembly references. /// [BuildElement("references")] public AssemblyFileSet References { get { return _references; } set { _references = value; } } /// /// Categories of test cases to include or exclude. /// [BuildElement("categories")] public Categories Categories { get { return _categories; } set { _categories = value; } } /// /// Build fails on failure. The default is . /// [TaskAttribute("haltonfailure")] [BooleanValidator()] public bool HaltOnFailure { get { return _haltOnFailure; } set { _haltOnFailure = value; } } /// /// XSLT transform file to use when using the /// formatter. /// [TaskAttribute("transformfile")] public FileInfo XsltFile { get { return _xsltFile; } set { _xsltFile = value; } } /// /// The application configuration file to use for the NUnit test domain. /// If not specified, NAnt will try to use a configuration name matching /// the file name of the assembly with extension ".config". /// [TaskAttribute("appconfig")] public FileInfo AppConfigFile { get { return _appConfigFile; } set { _appConfigFile = value; } } /// /// Gets all assemblies specified for these tests. /// /// /// All assemblies specified for these tests. /// public StringCollection TestAssemblies { get { StringCollection files = new StringCollection(); if (AssemblyFile != null) { files.Add(AssemblyFile.FullName); } else { files = Assemblies.FileNames; } return files; } } #endregion Public Instance Properties } } nant-0.92-rc1/src/NAnt.NUnit/NUnit2/NUnit2TestDomain.cs0000644000175000017500000003037011757302274022274 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Tomas Restrepo (tomasr@mvps.org) using System; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.Remoting; using NUnit.Core; using System.Security; using System.Security.Permissions; using System.Security.Policy; namespace NAnt.NUnit2.Tasks { /// /// Custom TestDomain, similar to the one included with NUnit, in order /// to workaround some limitations in it. /// internal class NUnit2TestDomain { #region Public Instance Constructors /// /// Initializes a new instance of the /// class. /// public NUnit2TestDomain() { } #endregion Public Instance Constructors #region Public Instance Methods /// /// Runs a single testcase. /// /// The test assembly. /// The application configuration file for the test domain. /// List of files to scan for missing assembly references. /// /// The result of the test. /// public TestRunner CreateRunner(FileInfo assemblyFile, FileInfo configFile, StringCollection referenceAssemblies) { // create test domain _domain = CreateDomain(assemblyFile.Directory, assemblyFile, configFile); // assemble directories which can be probed for missing unresolved // assembly references string[] probePaths = null; if (AppDomain.CurrentDomain.SetupInformation.PrivateBinPath != null) { string [] privateBinPaths = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath.Split(Path.PathSeparator); probePaths = new string [privateBinPaths.Length + 1]; for (int i = 0; i < privateBinPaths.Length; i++) { probePaths[i] = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, privateBinPaths[i]); } } else { probePaths = new string[1]; } string[] references = new string[referenceAssemblies.Count]; referenceAssemblies.CopyTo (references, 0); // add base directory of current AppDomain as probe path probePaths [probePaths.Length - 1] = AppDomain.CurrentDomain.BaseDirectory; // create an instance of our custom Assembly Resolver in the target domain. #if NET_4_0 _domain.CreateInstanceFrom(Assembly.GetExecutingAssembly().CodeBase, typeof(AssemblyResolveHandler).FullName, false, BindingFlags.Public | BindingFlags.Instance, null, new object[] {probePaths, references}, CultureInfo.InvariantCulture, null); #else _domain.CreateInstanceFrom(Assembly.GetExecutingAssembly().CodeBase, typeof(AssemblyResolveHandler).FullName, false, BindingFlags.Public | BindingFlags.Instance, null, new object[] {probePaths, references}, CultureInfo.InvariantCulture, null, AppDomain.CurrentDomain.Evidence); #endif // create testrunner return CreateTestRunner(_domain); } public void Unload() { if (_domain != null) { try { AppDomain.Unload(_domain); } catch (CannotUnloadAppDomainException) { // ignore exceptions during unload, this matches the // behaviour of the NUnit TestDomain } finally { _domain = null; } } } #endregion Public Instance Methods #region Private Instance Methods private AppDomain CreateDomain(DirectoryInfo basedir, FileInfo assemblyFile, FileInfo configFile) { // spawn new domain in specified directory AppDomainSetup domSetup = new AppDomainSetup(); domSetup.ApplicationBase = basedir.FullName; domSetup.ApplicationName = "NAnt NUnit Remote Domain"; // use explicitly specified configuration file, or fall back to // configuration file for given assembly file if (configFile != null) { domSetup.ConfigurationFile = configFile.FullName; } else { domSetup.ConfigurationFile = assemblyFile.FullName + ".config"; } PermissionSet myDomainPermSet = new PermissionSet(PermissionState.Unrestricted); return AppDomain.CreateDomain(domSetup.ApplicationName, AppDomain.CurrentDomain.Evidence, domSetup, myDomainPermSet); } private RemoteTestRunner CreateTestRunner(AppDomain domain) { ObjectHandle oh; Type rtrType = typeof(RemoteTestRunner); #if NET_4_0 oh = domain.CreateInstance( rtrType.Assembly.FullName, rtrType.FullName, false, BindingFlags.Public | BindingFlags.Instance, null, null, CultureInfo.InvariantCulture, null); #else oh = domain.CreateInstance( rtrType.Assembly.FullName, rtrType.FullName, false, BindingFlags.Public | BindingFlags.Instance, null, null, CultureInfo.InvariantCulture, null, AppDomain.CurrentDomain.Evidence); #endif return (RemoteTestRunner) oh.Unwrap(); } #endregion Private Instance Methods #region Private Instance Fields private AppDomain _domain; #endregion Private Instance Fields /// /// Helper class called when an assembly resolve event is raised. /// [Serializable()] private class AssemblyResolveHandler { #region Public Instance Constructors /// /// Initializes an instanse of the /// class. /// public AssemblyResolveHandler(string[] probePaths, string[] referenceAssemblies) { _assemblyCache = new Hashtable(); _probePaths = probePaths; _referenceAssemblies = referenceAssemblies; // attach handlers for the current domain. AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(ResolveAssembly); AppDomain.CurrentDomain.AssemblyLoad += new AssemblyLoadEventHandler(AssemblyLoad); } #endregion Public Instance Constructors #region Public Instance Methods /// /// Called back when the CLR cannot resolve a given assembly. /// /// The source of the event. /// A that contains the event data. /// /// The nunit.framework we know to be in NAnts bin directory, if /// that is the assembly that needs to be resolved; otherwise, /// . /// public Assembly ResolveAssembly(Object sender, ResolveEventArgs args) { bool isFullName = args.Name.IndexOf("Version=") != -1; // find assembly in cache if (isFullName) { if (_assemblyCache.Contains(args.Name)) { // return assembly from cache return (Assembly) _assemblyCache[args.Name]; } } else { foreach (Assembly assembly in _assemblyCache.Values) { if (assembly.GetName(false).Name == args.Name) { // return assembly from cache return assembly; } } } // find assembly in reference assemblies foreach (string assemblyFile in _referenceAssemblies) { Assembly assembly = TryLoad (assemblyFile, args.Name, isFullName); if (assembly != null) return assembly; } // find assembly in probe paths foreach (string path in _probePaths) { if (!Directory.Exists(path)) { continue; } string[] assemblies = Directory.GetFiles(path, "*.dll"); foreach (string assemblyFile in assemblies) { Assembly assembly = TryLoad (assemblyFile, args.Name, isFullName); if (assembly != null) return assembly; } } // assembly reference could not be resolved return null; } static Assembly TryLoad (string assemblyFile, string name, bool isFullName) { Assembly assembly = null; try { AssemblyName assemblyName = AssemblyName.GetAssemblyName(assemblyFile); if (isFullName) { if (assemblyName.FullName == name) { assembly = Assembly.LoadFrom(assemblyFile); } } else { if (assemblyName.Name == name) { assembly = Assembly.LoadFrom(assemblyFile); } } } catch { // ignore assembly load failures } return assembly; } /// /// Occurs when an assembly is loaded. The loaded assembly is added /// to the assembly cache. /// /// The source of the event. /// An that contains the event data. private void AssemblyLoad(object sender, AssemblyLoadEventArgs args) { // store assembly in cache _assemblyCache[args.LoadedAssembly.FullName] = args.LoadedAssembly; } #endregion Public Instance Methods #region Private Instance Fields /// /// Holds the list of directories that will be scanned for missing /// assembly references. /// private readonly string[] _probePaths; /// /// Holds the list of assemblies that can be scanned for missing /// assembly references. /// private readonly string[] _referenceAssemblies; /// /// Holds the loaded assemblies. /// private readonly Hashtable _assemblyCache; #endregion Private Instance Fields } } } nant-0.92-rc1/src/NAnt.NUnit/NUnit2/NUnit2Task.cs0000644000175000017500000005415411757302274021135 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Mike Two (2@thoughtworks.com or mike2@nunit.org) // Tomas Restrepo (tomasr@mvps.org) // Ryan Boggs (rmboggs@users.sourceforge.net) using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Reflection; using System.Resources; using System.Text; using System.Xml; using System.Xml.Xsl; using System.Xml.XPath; using NUnit.Core; using NUnit.Core.Filters; using TestOutput = NUnit.Core.TestOutput; using NUnit.Framework; using NUnit.Util; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Util; using NAnt.NUnit.Types; using NAnt.NUnit2.Types; namespace NAnt.NUnit2.Tasks { /// /// Runs tests using the NUnit V2.6 framework. /// /// /// /// The attribute is only useful when more /// than one test suite is used, and you want to continue running other /// test suites although a test failed. /// /// /// Set to to /// ignore any errors and continue the build. /// /// /// In order to run a test assembly built with NUnit 2.0 or 2.1 using /// , you must add the following node to your /// test config file : /// /// /// /// ... /// /// /// /// /// /// /// /// /// /// ... /// /// ]]> /// /// /// See the NUnit home page for more /// information. /// /// /// /// /// Run tests in the MyProject.Tests.dll assembly. /// /// /// /// /// /// /// ]]> /// /// /// /// /// Only run tests that are not known to fail in files listed in the tests.txt /// file. /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// ]]> /// /// [TaskName("nunit2")] public class NUnit2Task : Task { #region Private Instance Fields private bool _labels = false; private bool _haltOnFailure = false; private List _tests = new List(); private List _formatterElements = new List(); //private NUnit2TestCollection _tests = new NUnit2TestCollection(); //private FormatterElementCollection _formatterElements = new FormatterElementCollection(); #endregion Private Instance Fields #region Public Instance Properties /// /// Stop the test run if a test fails. The default is . /// [TaskAttribute("haltonfailure")] [BooleanValidator()] public bool HaltOnFailure { get { return _haltOnFailure; } set { _haltOnFailure = value; } } /// /// Indicate whether or not to label the text output as the tests run. /// [TaskAttribute("labels")] [BooleanValidator()] public bool Labels { get { return _labels; } set { _labels = value; } } /// /// Tests to run. /// [BuildElementArray("test")] public List Tests { get { return _tests; } } /// /// Formatters to output results of unit tests. /// [BuildElementArray("formatter")] public List FormatterElements { get { return _formatterElements; } } #endregion Public Instance Properties #region Override implementation of Task /// /// Runs the tests and sets up the formatters. /// protected override void ExecuteTask() { if (FormatterElements.Count == 0) { FormatterElement defaultFormatter = new FormatterElement(); defaultFormatter.Project = Project; defaultFormatter.NamespaceManager = NamespaceManager; defaultFormatter.Type = FormatterType.Plain; defaultFormatter.UseFile = false; FormatterElements.Add(defaultFormatter); Log(Level.Warning, "No element was specified." + " A plain-text formatter was added to prevent losing output of the" + " test results."); Log(Level.Warning, "Add a element to the" + " task to prevent this warning from being output and" + " to ensure forward compatibility with future revisions of NAnt."); } LogWriter logWriter = new LogWriter(this, Level.Info, CultureInfo.InvariantCulture); EventListener listener = GetListener(logWriter); foreach (NUnit2Test testElement in Tests) { // Setup the test filter var to setup include/exclude filters. ITestFilter testFilter = null; // If the include categories contains values, setup the category // filter with the include categories. string includes = testElement.Categories.Includes.ToString(); if (!String.IsNullOrEmpty(includes)) { testFilter = new CategoryFilter(includes.Split(',')); } else { // If the include categories does not have includes but // contains excludes, setup the category filter with the excludes // and use the Not filter to tag the categories for exclude. string excludes = testElement.Categories.Excludes.ToString(); if (!String.IsNullOrEmpty(excludes)) { ITestFilter excludeFilter = new CategoryFilter(excludes.Split(',')); testFilter = new NotFilter(excludeFilter); } else { // If the categories do not contain includes or excludes, // assign the testFilter var with an empty filter. testFilter = TestFilter.Empty; } } foreach (string testAssembly in testElement.TestAssemblies) { // Setup the NUnit2TestDomain var. NUnit2TestDomain domain = new NUnit2TestDomain(); // Setup the TestPackage var to use with the testrunner var TestPackage package = new TestPackage(testAssembly); try { // Create the TestRunner var TestRunner runner = domain.CreateRunner( new FileInfo(testAssembly), testElement.AppConfigFile, testElement.References.FileNames); // If the name of the current test element is not null, // use it for the package test name. if (!String.IsNullOrEmpty(testElement.TestName)) { package.TestName = testElement.TestName; } // Bool var containing the result of loading the test package // in the TestRunner var. bool successfulLoad = runner.Load(package); // If the test package load was successful, proceed with the // testing. if (successfulLoad) { // If the runner does not contain any tests, proceed // to the next assembly. if (runner.Test == null) { Log(Level.Warning, "Assembly \"{0}\" contains no tests.", testAssembly); continue; } // Setup and run tests TestResult result = runner.Run(listener, testFilter, true, GetLoggingThreshold()); // flush test output to log logWriter.Flush(); // format test results using specified formatters FormatResult(testElement, result); if (result.IsFailure && (testElement.HaltOnFailure || HaltOnFailure)) { throw new BuildException("Tests Failed.", Location); } } else { // If the package load failed, throw a build exception. throw new BuildException("Test Package Load Failed.", Location); } } catch (BuildException) { // re-throw build exceptions throw; } catch (Exception ex) { if (!FailOnError) { // just log error and continue with next test // TODO: (RMB) Need to make sure that this is the correct way to proceed with displaying NUnit errors. string logMessage = String.Concat("[", Name, "] NUnit Error: ", ex.ToString()); Log(Level.Error, logMessage.PadLeft(Project.IndentationSize)); continue; } Version nunitVersion = typeof(TestResult).Assembly.GetName().Version; throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Failure executing test(s). If you assembly is not built using" + " NUnit version {0}, then ensure you have redirected assembly" + " bindings. Consult the documentation of the task" + " for more information.", nunitVersion), Location, ex); } finally { domain.Unload(); // flush test output to log logWriter.Flush(); } } } } #endregion Override implementation of Task #region Protected Instance Methods /// /// Gets a new EventListener to use for the unit tests. /// /// /// A new EventListener created with a new EventCollector that /// is initialized with . /// /// /// Log writer to send test output to. /// protected virtual EventListener GetListener(LogWriter logWriter) { return new EventCollector(logWriter, logWriter, _labels); } #endregion Protected Instance Methods #region Private Instance Methods /// /// Gets the logging threshold to use for a test runner based on /// the current threshold of this task. /// /// /// The logging threshold to use when running a test runner. /// private LoggingThreshold GetLoggingThreshold() { LoggingThreshold result; // TODO: (RMB) May need to re-evaluate these mappings switch (Threshold) { case Level.None: result = LoggingThreshold.Fatal; break; case Level.Info: result = LoggingThreshold.Info; break; case Level.Verbose: result = LoggingThreshold.All; break; case Level.Debug: result = LoggingThreshold.Debug; break; case Level.Warning: result = LoggingThreshold.Warn; break; case Level.Error: result = LoggingThreshold.Error; break; default: result = LoggingThreshold.Off; break; } return result; } private void FormatResult(NUnit2Test testElement, TestResult result) { // temp file for storing test results string xmlResultFile = Path.GetTempFileName(); try { XmlResultWriter resultWriter = new XmlResultWriter(xmlResultFile); resultWriter.SaveTestResult(result); foreach (FormatterElement formatter in FormatterElements) { // permanent file for storing test results string outputFile = result.Name + "-results" + formatter.Extension; if (formatter.Type == FormatterType.Xml) { if (formatter.UseFile) { if (formatter.OutputDirectory != null) { // ensure output directory exists if (!formatter.OutputDirectory.Exists) { formatter.OutputDirectory.Create(); } // combine output directory and result filename outputFile = Path.Combine(formatter.OutputDirectory.FullName, Path.GetFileName(outputFile)); } // copy the temp result file to permanent location File.Copy(xmlResultFile, outputFile, true); } else { using (StreamReader reader = new StreamReader(xmlResultFile)) { // strip off the xml header reader.ReadLine(); StringBuilder builder = new StringBuilder(); while (reader.Peek() > -1) { builder.Append(reader.ReadLine().Trim()).Append( Environment.NewLine); } Log(Level.Info, builder.ToString()); } } } else if (formatter.Type == FormatterType.Plain) { TextWriter writer; if (formatter.UseFile) { if (formatter.OutputDirectory != null) { // ensure output directory exists if (!formatter.OutputDirectory.Exists) { formatter.OutputDirectory.Create(); } // combine output directory and result filename outputFile = Path.Combine(formatter.OutputDirectory.FullName, Path.GetFileName(outputFile)); } writer = new StreamWriter(outputFile); } else { writer = new LogWriter(this, Level.Info, CultureInfo.InvariantCulture); } CreateSummaryDocument(xmlResultFile, writer, testElement); writer.Close(); } } } catch (Exception ex) { throw new BuildException("Test results could not be formatted.", Location, ex); } finally { // make sure temp file with test results is removed File.Delete(xmlResultFile); } } private void CreateSummaryDocument(string resultFile, TextWriter writer, NUnit2Test test) { XPathDocument originalXPathDocument = new XPathDocument(resultFile); // Using XslTransform instead of XslCompiledTransform because the latter // does not display nunit output for unknown reasons. XslTransform summaryXslTransform = new XslTransform(); XmlTextReader transformReader = GetTransformReader(test); summaryXslTransform.Load(transformReader); summaryXslTransform.Transform(originalXPathDocument, null, writer); } private XmlTextReader GetTransformReader(NUnit2Test test) { XmlTextReader transformReader; if (test.XsltFile == null) { Assembly assembly = Assembly.GetAssembly(typeof(XmlResultWriter)); ResourceManager resourceManager = new ResourceManager("NUnit.Util.Transform", assembly); string xmlData = (string) resourceManager.GetObject("Summary.xslt", CultureInfo.InvariantCulture); transformReader = new XmlTextReader(new StringReader(xmlData)); } else { if (!test.XsltFile.Exists) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Transform file '{0}' does not exist.", test.XsltFile.FullName), Location); } transformReader = new XmlTextReader(test.XsltFile.FullName); } return transformReader; } #endregion Private Instance Methods private class EventCollector : MarshalByRefObject, EventListener { private TextWriter outWriter; private TextWriter errorWriter; private string currentTestName; private bool _printLabel; public EventCollector(TextWriter outWriter, TextWriter errorWriter) : this(outWriter, errorWriter, false) {} public EventCollector(TextWriter outWriter, TextWriter errorWriter, bool labels) { this.outWriter = outWriter; this.errorWriter = errorWriter; this.currentTestName = string.Empty; this._printLabel = labels; } public void RunStarted( string name, int testCount ) { } public void RunFinished(TestResult results) { } public void RunFinished(Exception exception) { } public void TestFinished(TestResult result) { currentTestName = string.Empty; } public void TestStarted(TestName testName) { currentTestName = testName.FullName; if (this._printLabel) { outWriter.WriteLine("***** {0}", currentTestName ); } } public void SuiteStarted(TestName testName) { } public void SuiteFinished(TestResult result) { } public void UnhandledException( Exception exception ) { string msg = string.Format("##### Unhandled Exception while running {0}", currentTestName); errorWriter.WriteLine(msg); errorWriter.WriteLine(exception.ToString()); } public void TestOutput(TestOutput output) { switch (output.Type) { case TestOutputType.Out: outWriter.Write(output.Text); break; case TestOutputType.Error: errorWriter.Write(output.Text); break; } } public override object InitializeLifetimeService() { return null; } } } } nant-0.92-rc1/src/NAnt.NUnit/AssemblyInfo.cs0000644000175000017500000000233211757302274020436 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Scott Hernandez (ScottHernandez@hotmail.com) // Gert Driesen (drieseng@users.sourceforge.net) using System.Reflection; // This will not compile with Visual Studio. If you want to build a signed // executable use the NAnt build file. To build under Visual Studio just // exclude this file from the build. [assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile(@"..\NAnt.key")] [assembly: AssemblyKeyName("")]nant-0.92-rc1/src/NAnt.NUnit/FormatterData.cs0000644000175000017500000000555511757302274020612 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Tomas Restrepo (tomasr@mvps.org) using System; using System.IO; namespace NAnt.NUnit.Types { /// /// Carries data specified through the formatter element. /// [Serializable] public class FormatterData { #region Private Instance Fields private string _extension; private bool _usefile; private FormatterType _formatterType = FormatterType.Plain; private DirectoryInfo _outputDirectory; #endregion Private Instance Fields #region Public Instance Properties /// /// Gets or sets the type of the formatter. /// /// The type of the formatter. public FormatterType Type { get { return _formatterType; } set { _formatterType = value; } } /// /// Gets or sets a value indicating whether output should be persisted /// to a file. /// /// /// if output should be written to a file; otherwise, /// . The default is . /// public bool UseFile { get { return _usefile; } set { _usefile = value; } } /// /// Gets or sets the extension to append to the output filename. /// /// The extension to append to the output filename. public string Extension { get { return _extension; } set { _extension = value; } } /// /// Gets or sets the directory where the output file should be written /// to, if is . /// /// /// The directory where the output file should be written to. /// public DirectoryInfo OutputDirectory { get { return _outputDirectory; } set { _outputDirectory = value; } } #endregion Public Instance Properties } } nant-0.92-rc1/src/NAnt.Compression/0000755000175000017500000000000011757310030016745 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.Compression/AssemblyInfo.cs0000644000175000017500000000233211757302272021700 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Scott Hernandez (ScottHernandez@hotmail.com) // Gert Driesen (drieseng@users.sourceforge.net) using System.Reflection; // This will not compile with Visual Studio. If you want to build a signed // executable use the NAnt build file. To build under Visual Studio just // exclude this file from the build. [assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile(@"..\NAnt.key")] [assembly: AssemblyKeyName("")]nant-0.92-rc1/src/NAnt.Compression/Types/0000755000175000017500000000000011757310030020051 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.Compression/Types/TarFileSetCollection.cs0000644000175000017500000002225211757302272024432 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; namespace NAnt.Compression.Types { /// /// Contains a collection of elements. /// [Serializable()] public class TarFileSetCollection : CollectionBase { #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public TarFileSetCollection() { } /// /// Initializes a new instance of the class /// with the specified instance. /// public TarFileSetCollection(TarFileSetCollection value) { AddRange(value); } /// /// Initializes a new instance of the class /// with the specified array of instances. /// public TarFileSetCollection(TarFileSet[] value) { AddRange(value); } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets the element at the specified index. /// /// The zero-based index of the element to get or set. [System.Runtime.CompilerServices.IndexerName("Item")] public TarFileSet this[int index] { get { return ((TarFileSet)(base.List[index])); } set { base.List[index] = value; } } /// /// Get the total number of files that are represented by the /// filesets in this collection. /// public int FileCount { get { int fileCount = 0; foreach (TarFileSet fileset in base.List) { fileCount += fileset.FileNames.Count; } return fileCount; } } #endregion Public Instance Properties #region Public Instance Methods /// /// Adds a to the end of the collection. /// /// The to be added to the end of the collection. /// The position into which the new element was inserted. public int Add(TarFileSet item) { return base.List.Add(item); } /// /// Adds the elements of a array to the end of the collection. /// /// The array of elements to be added to the end of the collection. public void AddRange(TarFileSet[] items) { for (int i = 0; (i < items.Length); i = (i + 1)) { Add(items[i]); } } /// /// Adds the elements of a to the end of the collection. /// /// The to be added to the end of the collection. public void AddRange(TarFileSetCollection items) { for (int i = 0; (i < items.Count); i = (i + 1)) { Add(items[i]); } } /// /// Determines whether a is in the collection. /// /// The to locate in the collection. /// /// if is found in the /// collection; otherwise, . /// public bool Contains(TarFileSet item) { return base.List.Contains(item); } /// /// Copies the entire collection to a compatible one-dimensional array, starting at the specified index of the target array. /// /// The one-dimensional array that is the destination of the elements copied from the collection. The array must have zero-based indexing. /// The zero-based index in at which copying begins. public void CopyTo(TarFileSet[] array, int index) { base.List.CopyTo(array, index); } /// /// Retrieves the index of a specified object in the collection. /// /// The object for which the index is returned. /// /// The index of the specified . If the is not currently a member of the collection, it returns -1. /// public int IndexOf(TarFileSet item) { return base.List.IndexOf(item); } /// /// Inserts a into the collection at the specified index. /// /// The zero-based index at which should be inserted. /// The to insert. public void Insert(int index, TarFileSet item) { base.List.Insert(index, item); } /// /// Returns an enumerator that can iterate through the collection. /// /// /// A for the entire collection. /// public new TarFileSetEnumerator GetEnumerator() { return new TarFileSetEnumerator(this); } /// /// Removes a member from the collection. /// /// The to remove from the collection. public void Remove(TarFileSet item) { base.List.Remove(item); } #endregion Public Instance Methods } /// /// Enumerates the elements of a . /// public class TarFileSetEnumerator : IEnumerator { #region Internal Instance Constructors /// /// Initializes a new instance of the class /// with the specified . /// /// The collection that should be enumerated. internal TarFileSetEnumerator(TarFileSetCollection TarFileSets) { IEnumerable temp = (IEnumerable) (TarFileSets); _baseEnumerator = temp.GetEnumerator(); } #endregion Internal Instance Constructors #region Implementation of IEnumerator /// /// Gets the current element in the collection. /// /// /// The current element in the collection. /// public TarFileSet Current { get { return (TarFileSet) _baseEnumerator.Current; } } object IEnumerator.Current { get { return _baseEnumerator.Current; } } /// /// Advances the enumerator to the next element of the collection. /// /// /// if the enumerator was successfully advanced /// to the next element; if the enumerator has /// passed the end of the collection. /// public bool MoveNext() { return _baseEnumerator.MoveNext(); } bool IEnumerator.MoveNext() { return _baseEnumerator.MoveNext(); } /// /// Sets the enumerator to its initial position, which is before the /// first element in the collection. /// public void Reset() { _baseEnumerator.Reset(); } void IEnumerator.Reset() { _baseEnumerator.Reset(); } #endregion Implementation of IEnumerator #region Private Instance Fields private IEnumerator _baseEnumerator; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.Compression/Types/DuplicateHandling.cs0000644000175000017500000000573111757302272023776 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2003 Scott Hernandez // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.ComponentModel; using System.Globalization; namespace NAnt.Compression.Types { /// /// Specifies how entries with the same name should be processed. /// [TypeConverter(typeof(DuplicateHandlingConverter))] public enum DuplicateHandling { /// /// Overwrite existing entry with same name. /// Add = 0, /// /// Preserve existing entry with the same name. /// Preserve = 1, /// /// Report failure when two entries have the same name. /// Fail = 2 } /// /// Specialized for /// that ignores case when converting from string. /// internal class DuplicateHandlingConverter : EnumConverter { /// /// Initializes a new instance of the /// class. /// public DuplicateHandlingConverter() : base(typeof(DuplicateHandling)) { } /// /// Converts the given object to the type of this converter, using the /// specified context and culture information. /// /// An that provides a format context. /// A object. If a is passed, the current culture is assumed. /// The to convert. /// /// An that represents the converted value. /// public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { string stringValue = value as string; if (stringValue != null) return Enum.Parse(EnumType, stringValue, true); // default to EnumConverter behavior return base.ConvertFrom(context, culture, value); } } } nant-0.92-rc1/src/NAnt.Compression/Types/TarCompressionMethod.cs0000644000175000017500000000423711757302272024530 0ustar jtaylorjtaylorusing System; using System.ComponentModel; using System.Globalization; using NAnt.Compression.Tasks; namespace NAnt.Compression.Types { /// /// Specifies the compression methods supported by /// and . /// [TypeConverter(typeof(TarCompressionMethodConverter))] public enum TarCompressionMethod { /// /// No compression. /// None = 0, /// /// GZIP compression. /// GZip = 1, /// /// BZIP2 compression. /// BZip2 = 2 } /// /// Specialized for /// that ignores case when converting from string. /// internal class TarCompressionMethodConverter : EnumConverter { /// /// Initializes a new instance of the /// class. /// public TarCompressionMethodConverter() : base(typeof(TarCompressionMethod)) { } /// /// Converts the given object to the type of this converter, using the /// specified context and culture information. /// /// An that provides a format context. /// A object. If a is passed, the current culture is assumed. /// The to convert. /// /// An that represents the converted value. /// public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { string stringValue = value as string; if (stringValue != null) return Enum.Parse(EnumType, stringValue, true); // default to EnumConverter behavior return base.ConvertFrom(context, culture, value); } } } nant-0.92-rc1/src/NAnt.Compression/Types/ZipFileSetCollection.cs0000644000175000017500000002226211757302272024447 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; namespace NAnt.Compression.Types { /// /// Contains a collection of elements. /// [Serializable()] public class ZipFileSetCollection : CollectionBase { #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public ZipFileSetCollection() { } /// /// Initializes a new instance of the class /// with the specified instance. /// public ZipFileSetCollection(ZipFileSetCollection value) { AddRange(value); } /// /// Initializes a new instance of the class /// with the specified array of instances. /// public ZipFileSetCollection(ZipFileSet[] value) { AddRange(value); } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets the element at the specified index. /// /// The zero-based index of the element to get or set. [System.Runtime.CompilerServices.IndexerName("Item")] public ZipFileSet this[int index] { get { return ((ZipFileSet)(base.List[index])); } set { base.List[index] = value; } } /// /// Get the total number of files that are represented by the /// filesets in this collection. /// public int FileCount { get { int fileCount = 0; foreach (ZipFileSet fileset in base.List) { fileCount += fileset.FileNames.Count; } return fileCount; } } #endregion Public Instance Properties #region Public Instance Methods /// /// Adds a to the end of the collection. /// /// The to be added to the end of the collection. /// The position into which the new element was inserted. public int Add(ZipFileSet item) { return base.List.Add(item); } /// /// Adds the elements of a array to the end of the collection. /// /// The array of elements to be added to the end of the collection. public void AddRange(ZipFileSet[] items) { for (int i = 0; (i < items.Length); i = (i + 1)) { Add(items[i]); } } /// /// Adds the elements of a to the end of the collection. /// /// The to be added to the end of the collection. public void AddRange(ZipFileSetCollection items) { for (int i = 0; (i < items.Count); i = (i + 1)) { Add(items[i]); } } /// /// Determines whether a is in the collection. /// /// The to locate in the collection. /// /// if is found in the /// collection; otherwise, . /// public bool Contains(ZipFileSet item) { return base.List.Contains(item); } /// /// Copies the entire collection to a compatible one-dimensional array, starting at the specified index of the target array. /// /// The one-dimensional array that is the destination of the elements copied from the collection. The array must have zero-based indexing. /// The zero-based index in at which copying begins. public void CopyTo(ZipFileSet[] array, int index) { base.List.CopyTo(array, index); } /// /// Retrieves the index of a specified object in the collection. /// /// The object for which the index is returned. /// /// The index of the specified . If the is not currently a member of the collection, it returns -1. /// public int IndexOf(ZipFileSet item) { return base.List.IndexOf(item); } /// /// Inserts a into the collection at the specified index. /// /// The zero-based index at which should be inserted. /// The to insert. public void Insert(int index, ZipFileSet item) { base.List.Insert(index, item); } /// /// Returns an enumerator that can iterate through the collection. /// /// /// A for the entire collection. /// public new ZipFileSetEnumerator GetEnumerator() { return new ZipFileSetEnumerator(this); } /// /// Removes a member from the collection. /// /// The to remove from the collection. public void Remove(ZipFileSet item) { base.List.Remove(item); } #endregion Public Instance Methods } /// /// Enumerates the elements of a . /// public class ZipFileSetEnumerator : IEnumerator { #region Internal Instance Constructors /// /// Initializes a new instance of the class /// with the specified . /// /// The collection that should be enumerated. internal ZipFileSetEnumerator(ZipFileSetCollection ZipFileSets) { IEnumerable temp = (IEnumerable) (ZipFileSets); _baseEnumerator = temp.GetEnumerator(); } #endregion Internal Instance Constructors #region Implementation of IEnumerator /// /// Gets the current element in the collection. /// /// /// The current element in the collection. /// public ZipFileSet Current { get { return (ZipFileSet) _baseEnumerator.Current; } } object IEnumerator.Current { get { return _baseEnumerator.Current; } } /// /// Advances the enumerator to the next element of the collection. /// /// /// if the enumerator was successfully advanced /// to the next element; if the enumerator has /// passed the end of the collection. /// public bool MoveNext() { return _baseEnumerator.MoveNext(); } bool IEnumerator.MoveNext() { return _baseEnumerator.MoveNext(); } /// /// Sets the enumerator to its initial position, which is before the /// first element in the collection. /// public void Reset() { _baseEnumerator.Reset(); } void IEnumerator.Reset() { _baseEnumerator.Reset(); } #endregion Implementation of IEnumerator #region Private Instance Fields private IEnumerator _baseEnumerator; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.Compression/Types/ZipFileSet.cs0000644000175000017500000000406311757302272022432 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2003 Scott Hernandez // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Types; using NAnt.Core.Util; using NAnt.Compression.Tasks; namespace NAnt.Compression.Types { /// /// A is a with extra /// attributes useful in the context of the . /// [ElementName("zipfileset")] public class ZipFileSet : FileSet { #region Private Instance Fields private string _prefix; #endregion Private Instance Fields #region Public Instance Properties /// /// The top level directory prefix. If set, all file and directory paths /// in the fileset will have this value prepended. Can either be a single /// directory name or a "/" separated path. /// [TaskAttribute("prefix", Required=false)] public string Prefix { get { return _prefix; } set { _prefix = StringUtils.ConvertEmptyToNull(value); if (_prefix != null && !_prefix.EndsWith("/") && !_prefix.EndsWith("\\")) { _prefix += "/"; } } } #endregion Public Instance Properties } } nant-0.92-rc1/src/NAnt.Compression/Types/TarFileSet.cs0000644000175000017500000001054711757302272022422 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2003 Scott Hernandez // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Types; using NAnt.Core.Util; using NAnt.Compression.Tasks; namespace NAnt.Compression.Types { /// /// A is a with extra /// attributes useful in the context of the . /// [ElementName("tarfileset")] public class TarFileSet : FileSet { #region Private Instance Fields private int _fileMode = _fileFlag | 420; // = 644 octal private int _dirMode = _dirFlag | 493; // = 755 octal private string _userName; private int _uid; private string _groupName; private int _gid; private string _prefix; #endregion Private Instance Fields #region Private Static Fields private const int _dirFlag = 16384; // = 40000 octal private const int _fileFlag = 32768; // = 100000 octal #endregion Private Static Fields #region Public Instance Properties /// /// A 3 digit octal string, specify the user, group and other modes /// in the standard Unix fashion. Only applies to plain files. The /// default is 644. /// [TaskAttribute("filemode")] public int FileMode { get { return _fileMode; } set { _fileMode = _fileFlag | Convert.ToInt32(Convert.ToString(value), 8); } } /// /// A 3 digit octal string, specify the user, group and other modes /// in the standard Unix fashion. Only applies to directories. The /// default is 755. /// [TaskAttribute("dirmode")] public int DirMode { get { return _dirMode; } set { _dirMode = _dirFlag | Convert.ToInt32(Convert.ToString(value), 8); } } /// /// The username for the tar entry. /// [TaskAttribute("username")] public string UserName { get { return _userName; } set { _userName = StringUtils.ConvertEmptyToNull(value); } } /// /// The user identifier (UID) for the tar entry. /// [TaskAttribute("uid")] public int Uid { get { return _uid; } set { _uid = value; } } /// /// The groupname for the tar entry. /// [TaskAttribute("groupname")] public string GroupName { get { return _groupName; } set { _groupName = StringUtils.ConvertEmptyToNull(value); } } /// /// The group identifier (GID) for the tar entry. /// [TaskAttribute("gid")] public int Gid { get { return _gid; } set { _gid = value; } } /// /// The top level directory prefix. If set, all file and directory paths /// in the fileset will have this value prepended. Can either be a single /// directory name or a "/" separated path. /// [TaskAttribute("prefix")] public string Prefix { get { return _prefix; } set { _prefix = StringUtils.ConvertEmptyToNull(value); if (_prefix != null && !_prefix.EndsWith("/") && !_prefix.EndsWith("\\")) { _prefix += "/"; } } } #endregion Public Instance Properties } } nant-0.92-rc1/src/NAnt.Compression/Tasks/0000755000175000017500000000000011757310030020032 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.Compression/Tasks/ExpandBaseTask.cs0000644000175000017500000001360411757302272023233 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2009 Gert Driesen // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // using System; using System.Globalization; using System.IO; using NAnt.Core; using NAnt.Core.Attributes; namespace NAnt.Compression.Tasks { /// /// Summary description for ExpandTask. /// public abstract class ExpandBaseTask : Task { private bool _overwrite = true; /// /// Overwrite files, even if they are newer than the corresponding /// entries in the archive. The default is . /// [TaskAttribute("overwrite", Required=false)] public virtual bool Overwrite { get { return _overwrite; } set { _overwrite = value; } } /// /// Extracts a file entry from the specified stream. /// /// The containing the compressed entry. /// The directory where to store the expanded file. /// The name of the entry including directory information. /// The date of the entry. /// The uncompressed size of the entry. /// /// The destination directory for the entry could not be created. /// -or- /// The entry could not be extracted. /// /// /// We cannot rely on the fact that the directory entry of a given file /// is created before the file is extracted, so we should create the /// directory if it doesn't yet exist. /// protected void ExtractFile(Stream inputStream, string destDirectory, string entryName, DateTime entryDate, long entrySize) { // determine destination file FileInfo destFile = new FileInfo(Path.Combine(destDirectory, entryName)); // ensure destination directory exists if (!destFile.Directory.Exists) { try { destFile.Directory.Create(); destFile.Directory.LastWriteTime = entryDate; destFile.Directory.Refresh(); } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Directory '{0}' could not be created.", destFile.DirectoryName), Location, ex); } } // determine if entry actually needs to be extracted if (!Overwrite && destFile.Exists && destFile.LastWriteTime >= entryDate) { Log(Level.Debug, "Skipping '{0}' as it is up-to-date.", destFile.FullName); return; } Log(Level.Verbose, "Extracting '{0}' to '{1}'.", entryName, destDirectory); try { // extract the entry using (FileStream sw = new FileStream(destFile.FullName, FileMode.Create, FileAccess.Write)) { int size = 2048; byte[] data = new byte[2048]; while (true) { size = inputStream.Read(data, 0, data.Length); if (size == 0) { break; } sw.Write(data, 0, size); } sw.Close(); } } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Unable to expand '{0}' to '{1}'.", entryName, destDirectory), Location, ex); } destFile.LastWriteTime = entryDate; } /// /// Extracts a directory entry from the specified stream. /// /// The containing the directory entry. /// The directory where to create the subdirectory. /// The name of the directory entry. /// The date of the entry. /// /// The destination directory for the entry could not be created. /// protected void ExtractDirectory(Stream inputStream, string destDirectory, string entryName, DateTime entryDate) { DirectoryInfo destDir = new DirectoryInfo(Path.Combine( destDirectory, entryName)); if (!destDir.Exists) { try { destDir.Create(); destDir.LastWriteTime = entryDate; destDir.Refresh(); } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Directory '{0}' could not be created.", destDir.FullName), Location, ex); } } } } } nant-0.92-rc1/src/NAnt.Compression/Tasks/UnTarTask.cs0000644000175000017500000001420011757302272022243 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2009 Gert Driesen // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // using System; using System.Globalization; using System.IO; using System.Text; using ICSharpCode.SharpZipLib; using ICSharpCode.SharpZipLib.BZip2; using ICSharpCode.SharpZipLib.GZip; using ICSharpCode.SharpZipLib.Tar; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Util; using NAnt.Compression.Types; namespace NAnt.Compression.Tasks { /// /// Extracts files from a tar archive. /// /// /// /// Uses #ziplib /// (SharpZipLib), an open source Zip/GZip library written entirely in C#. /// /// /// /// Extracts all files from a gzipped tar, preserving the directory structure. /// /// /// ]]> /// /// [TaskName("untar")] public class UnTarTask : ExpandBaseTask { #region Private Instance Fields private FileInfo _srcFile; private DirectoryInfo _destDir; private TarCompressionMethod _compressionMethod = TarCompressionMethod.None; #endregion Private Instance Fields #region Public Instance Properties /// /// The archive file to expand. /// [TaskAttribute("src", Required=true)] public FileInfo SrcFile { get { return _srcFile; } set { _srcFile = value; } } /// /// The directory where to store the expanded file(s). The default is /// the project base directory. /// [TaskAttribute("dest", Required=false)] public DirectoryInfo DestinationDirectory { get { if (_destDir == null) _destDir = new DirectoryInfo(Project.BaseDirectory); return _destDir; } set { _destDir = value; } } /// /// The compression method. The default is . /// [TaskAttribute("compression")] public TarCompressionMethod CompressionMethod { get { return _compressionMethod; } set { _compressionMethod = value; } } #endregion Public Instance Properties #region Override implementation of Task /// /// Extracts the files from the archive. /// protected override void ExecuteTask() { Stream fs = null; Stream instream = null; try { // ensure archive exists if (!SrcFile.Exists) throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Tar file '{0}' does not exist.", SrcFile.FullName), Location); fs = SrcFile.OpenRead(); // wrap inputstream with corresponding compression method switch (CompressionMethod) { case TarCompressionMethod.GZip: instream = new GZipInputStream(fs); break; case TarCompressionMethod.BZip2: instream = new BZip2InputStream(fs); break; default: instream = fs; break; } using (TarInputStream s = new TarInputStream(instream)) { Log(Level.Info, "Expanding '{0}' to '{1}'.", SrcFile.FullName, DestinationDirectory.FullName); TarEntry entry; // extract the file or directory entry while ((entry = s.GetNextEntry()) != null) { if (entry.IsDirectory) { ExtractDirectory(s, DestinationDirectory.FullName, entry.Name, entry.ModTime); } else { ExtractFile(s, DestinationDirectory.FullName, entry.Name, entry.ModTime, entry.Size); } } } } catch (IOException ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Failed to expand '{0}' to '{1}'.", SrcFile.FullName, DestinationDirectory.FullName), Location, ex); } catch (TarException ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Invalid tar file '{0}'.", SrcFile.FullName), Location, ex); } catch (BZip2Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Invalid bzip2'd tar file '{0}'.", SrcFile.FullName), Location, ex); } catch (GZipException ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Invalid gzipped tar file '{0}'.", SrcFile.FullName), Location, ex); } finally { // close the filestream if (fs != null) fs.Close (); } } #endregion Override implementation of Task } } nant-0.92-rc1/src/NAnt.Compression/Tasks/UnZipTask.cs0000644000175000017500000001232511757302272022265 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2003 Scott Hernandez // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Scott Hernandez (ScottHernandez@hotmail.com) using System; using System.Globalization; using System.IO; using System.Text; using ICSharpCode.SharpZipLib; using ICSharpCode.SharpZipLib.Zip; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Util; namespace NAnt.Compression.Tasks { /// /// Extracts files from a zip archive. /// /// /// /// Uses #ziplib /// (SharpZipLib), an open source Zip/GZip library written entirely in C#. /// /// /// /// Extracts all the file from the zip, preserving the directory structure. /// /// /// ]]> /// /// [TaskName("unzip")] public class UnZipTask : ExpandBaseTask { #region Private Instance Fields private FileInfo _zipfile; private DirectoryInfo _toDir; private Encoding _encoding; #endregion Private Instance Fields #region Public Instance Properties /// /// The archive file to expand. /// [TaskAttribute("zipfile", Required=true)] public FileInfo ZipFile { get { return _zipfile; } set { _zipfile = value; } } /// /// The directory where the expanded files should be stored. The /// default is the project base directory. /// [TaskAttribute("todir", Required=false)] public DirectoryInfo ToDirectory { get { if (_toDir == null) _toDir = new DirectoryInfo(Project.BaseDirectory); return _toDir; } set { _toDir = value; } } /// /// The character encoding that has been used for filenames inside the /// zip file. The default is the system's OEM code page. /// [TaskAttribute("encoding")] public Encoding Encoding { get { if (_encoding == null) { _encoding = Encoding.GetEncoding(CultureInfo.CurrentCulture.TextInfo.OEMCodePage); } return _encoding; } set { _encoding = value; } } #endregion Public Instance Properties #region Override implementation of Task /// /// Extracts the files from the zip file. /// protected override void ExecuteTask() { try { // ensure zip file exists if (!ZipFile.Exists) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Zip file '{0}' does not exist.", ZipFile.FullName), Location); } // set encoding of filenames and comment ZipConstants.DefaultCodePage = Encoding.CodePage; using (ZipInputStream s = new ZipInputStream(ZipFile.OpenRead())) { Log(Level.Info, "Unzipping '{0}' to '{1}'.", ZipFile.FullName, ToDirectory.FullName); ZipEntry entry; // extract the file or directory entry while ((entry = s.GetNextEntry()) != null) { if (entry.IsDirectory) { ExtractDirectory(s, ToDirectory.FullName, entry.Name, entry.DateTime); } else { ExtractFile(s, ToDirectory.FullName, entry.Name, entry.DateTime, entry.Size); } } // close the zip stream s.Close(); } } catch (IOException ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Failed to expand '{0}' to '{1}'.", ZipFile.FullName, ToDirectory.FullName), Location, ex); } catch (ZipException ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Invalid zip file '{0}'.", ZipFile.FullName), Location, ex); } } #endregion Override implementation of Task } } nant-0.92-rc1/src/NAnt.Compression/Tasks/GUnzip.cs0000644000175000017500000000767111757302272021621 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System.Globalization; using System.IO; using ICSharpCode.SharpZipLib.GZip; using NAnt.Core; using NAnt.Core.Attributes; namespace NAnt.Compression.Tasks { /// /// Expands a file packed using GZip compression. /// /// /// Expands "test.tar.gz" to "test2.tar". /// /// /// ]]> /// /// [TaskName("gunzip")] public class GUnzip : Task { #region Private Instance Fields private FileInfo _srcFile; private FileInfo _destFile; #endregion Private Instance Fields #region Public Instance Properties /// /// The file to expand. /// [TaskAttribute("src", Required=true)] public FileInfo SrcFile { get { return _srcFile; } set { _srcFile = value; } } /// /// The destination file. /// [TaskAttribute("dest", Required=true)] public FileInfo DestFile { get { return _destFile; } set { _destFile = value; } } #endregion Public Instance Properties #region Override implementation of Task /// /// Extracts the file from the gzip archive. /// protected override void ExecuteTask() { try { using (GZipInputStream gzs = new GZipInputStream(SrcFile.OpenRead())) { Log(Level.Info, "Expanding '{0}' to '{1}' ({2} bytes).", SrcFile.FullName, DestFile.FullName, gzs.Length); // holds data from src file byte[] data = new byte[8 * 1024]; // first read from input to ensure we're dealing with valid // src file before we actually create the dest file int size = gzs.Read(data, 0, data.Length); // write expanded data to dest file using (FileStream fs = new FileStream(DestFile.FullName, FileMode.Create, FileAccess.Write, FileShare.None)) { while (size > 0) { fs.Write(data, 0, size); size = gzs.Read(data, 0, data.Length); } // close output stream fs.Close(); } // close input stream gzs.Close(); } } catch (IOException ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Failed to expand '{0}' to '{1}'.", SrcFile.FullName, DestFile.FullName), Location, ex); } catch (GZipException ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Invalid gzip file '{0}'.", SrcFile.FullName), Location, ex); } } #endregion Override implementation of Task } } nant-0.92-rc1/src/NAnt.Compression/Tasks/ZipTask.cs0000644000175000017500000003536711757302272021775 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Mike Krueger (mike@icsharpcode.net) // Gerry Shaw (gerry_shaw@yahoo.com) using System; using System.Collections; using System.Globalization; using System.IO; using System.Text; using ICSharpCode.SharpZipLib.Checksums; using ICSharpCode.SharpZipLib.Zip; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Types; using NAnt.Core.Util; using NAnt.Compression.Types; namespace NAnt.Compression.Tasks { /// /// Creates a zip file from the specified filesets. /// /// /// /// Uses #ziplib /// (SharpZipLib), an open source Tar/Zip/GZip library written entirely in C#. /// /// /// /// /// Zip all files in ${build.dir} and ${doc.dir} into a file /// called "backup.zip". /// /// /// /// /// /// /// /// /// /// /// ]]> /// /// [TaskName("zip")] public class ZipTask : Task { #region Private Instance Fields private FileInfo _zipfile; private int _ziplevel = 6; private ZipFileSetCollection _filesets = new ZipFileSetCollection(); private DateTime _stampDateTime; private string _comment; private bool _includeEmptyDirs; private bool _flatten; private DuplicateHandling _duplicateHandling = DuplicateHandling.Add; private Encoding _encoding; private Hashtable _addedDirs = new Hashtable(); private Hashtable _fileEntries = new Hashtable(); #endregion Private Instance Fields #region Public Instance Properties /// /// The zip file to create. /// [TaskAttribute("zipfile", Required=true)] public FileInfo ZipFile { get { return _zipfile; } set { _zipfile = value; } } /// /// The comment for the file. /// [TaskAttribute("comment")] public string Comment { get { return _comment; } set { _comment = StringUtils.ConvertEmptyToNull(value); } } /// /// Date/time stamp for the files in the format MM/DD/YYYY HH:MM:SS. /// [TaskAttribute("stampdatetime")] [DateTimeValidator()] public DateTime Stamp { get { return _stampDateTime; } set { _stampDateTime = value; } } /// /// Desired level of compression. Possible values are 0 (STORE only) /// to 9 (highest). The default is 6. /// [TaskAttribute("ziplevel")] [Int32ValidatorAttribute(0, 9)] public int ZipLevel { get { return _ziplevel; } set { _ziplevel = value; } } /// /// Include empty directories in the generated zip file. The default is /// . /// [TaskAttribute("includeemptydirs")] [BooleanValidator()] public bool IncludeEmptyDirs { get { return _includeEmptyDirs; } set { _includeEmptyDirs = value; } } /// /// Ignore directory structure of source directory, compress all files /// into a single directory. /// The default value is . /// [TaskAttribute("flatten")] [BooleanValidator()] public virtual bool Flatten { get { return _flatten; } set { _flatten = value; } } /// /// The set of files to be included in the archive. /// [BuildElementArray("fileset")] public ZipFileSetCollection ZipFileSets { get { return _filesets; } set { _filesets = value; } } /// /// Specifies the behaviour when a duplicate file is found. The default /// is . /// [TaskAttribute("duplicate")] public DuplicateHandling DuplicateHandling { get { return _duplicateHandling; } set { _duplicateHandling = value; } } /// /// The character encoding to use for filenames and comment inside the /// zip file. The default is the system's OEM code page. /// [TaskAttribute("encoding")] public Encoding Encoding { get { if (_encoding == null) { _encoding = Encoding.GetEncoding(CultureInfo.CurrentCulture.TextInfo.OEMCodePage); } return _encoding; } set { _encoding = value; } } #endregion Public Instance Properties #region Override implementation of Task /// /// Creates the zip file. /// protected override void ExecuteTask() { ZipOutputStream zOutstream = null; Log(Level.Info, "Zipping {0} files to '{1}'.", ZipFileSets.FileCount, ZipFile.FullName); try { if (!Directory.Exists(ZipFile.DirectoryName)) { Directory.CreateDirectory(ZipFile.DirectoryName); } // set encoding to use for filenames and comment ZipConstants.DefaultCodePage = Encoding.CodePage; zOutstream = new ZipOutputStream(ZipFile.Create()); // set compression level zOutstream.SetLevel(ZipLevel); // set comment if (!String.IsNullOrEmpty(Comment)) { zOutstream.SetComment(Comment); } foreach (ZipFileSet fileset in ZipFileSets) { string basePath = fileset.BaseDirectory.FullName; if (Path.GetPathRoot(basePath) != basePath) { basePath = Path.GetDirectoryName(basePath + Path.DirectorySeparatorChar); } // add files to zip foreach (string file in fileset.FileNames) { // ensure file exists (in case "asis" was used) if (!File.Exists(file)) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "File '{0}' does not exist.", file), Location); } // the name of the zip entry string entryName; // determine name of the zip entry if (!Flatten && file.StartsWith(basePath)) { entryName = file.Substring(basePath.Length); if (entryName.Length > 0 && entryName[0] == Path.DirectorySeparatorChar) { entryName = entryName.Substring(1); } // remember that directory was added to zip file, so // that we won't add it again later string dir = Path.GetDirectoryName(file); if (_addedDirs[dir] == null) { _addedDirs[dir] = dir; } } else { // flatten directory structure entryName = Path.GetFileName(file); } // add prefix if specified if (fileset.Prefix != null) { entryName = fileset.Prefix + entryName; } // ensure directory separators are understood on linux if (Path.DirectorySeparatorChar == '\\') { entryName = entryName.Replace(@"\", "/"); } // perform duplicate checking if (_fileEntries.ContainsKey(entryName)) { switch (DuplicateHandling) { case DuplicateHandling.Add: break; case DuplicateHandling.Fail: throw new BuildException(string.Format( CultureInfo.InvariantCulture, "Duplicate file '{0}' was found.", entryName), Location.UnknownLocation); case DuplicateHandling.Preserve: // skip current entry continue; default: throw new BuildException(string.Format( CultureInfo.InvariantCulture, "Duplicate value '{0}' is not supported.", DuplicateHandling.ToString()), Location.UnknownLocation); } } // create zip entry ZipEntry entry = new ZipEntry(entryName); // store entry (to allow for duplicate checking) _fileEntries[entryName] = null; // set date/time stamp on zip entry if (Stamp != DateTime.MinValue) { entry.DateTime = Stamp; } else { entry.DateTime = File.GetLastWriteTime(file); } // write file content to stream in small chuncks using (FileStream fs = File.OpenRead(file)) { // set size for backward compatibility with older unzip entry.Size = fs.Length; Log(Level.Verbose, "Adding {0}.", entryName); // write file to zip file zOutstream.PutNextEntry(entry); byte[] buffer = new byte[50000]; while (true) { int bytesRead = fs.Read(buffer, 0, buffer.Length); if (bytesRead == 0) break; zOutstream.Write(buffer, 0, bytesRead); } } } // add (possibly empty) directories to zip if (IncludeEmptyDirs) { foreach (string directory in fileset.DirectoryNames) { // skip directories that were already added when the // files were added if (_addedDirs[directory] != null) { continue; } // skip directories that are not located beneath the base // directory if (!directory.StartsWith(basePath) || directory.Length <= basePath.Length) { continue; } // determine zip entry name string entryName = directory.Substring(basePath.Length + 1); // add prefix if specified if (fileset.Prefix != null) { entryName = fileset.Prefix + entryName; } // ensure directory separators are understood on linux if (Path.DirectorySeparatorChar == '\\') { entryName = entryName.Replace(@"\", "/"); } if (!entryName.EndsWith("/")) { // trailing directory signals to #ziplib that we're // dealing with directory entry entryName += "/"; } // create directory entry ZipEntry entry = new ZipEntry(entryName); // set size for backward compatibility with older unzip entry.Size = 0L; // write directory to zip file zOutstream.PutNextEntry(entry); } } } zOutstream.Close(); zOutstream.Finish(); } catch (Exception ex) { // close the zip output stream if (zOutstream != null) { zOutstream.Close(); } // delete the (possibly corrupt) zip file if (ZipFile.Exists) { ZipFile.Delete(); } throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Zip file '{0}' could not be created.", ZipFile.FullName), Location, ex); } finally { CleanUp(); } } #endregion Override implementation of Task #region Private Instance Methods private void CleanUp() { _addedDirs.Clear(); _fileEntries.Clear(); } #endregion Private Instance Methods } } nant-0.92-rc1/src/NAnt.Compression/Tasks/TarTask.cs0000644000175000017500000003030211757302272021741 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; using System.Globalization; using System.IO; using ICSharpCode.SharpZipLib.BZip2; using ICSharpCode.SharpZipLib.Checksums; using ICSharpCode.SharpZipLib.GZip; using ICSharpCode.SharpZipLib.Tar; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Types; using NAnt.Core.Util; using NAnt.Compression.Types; namespace NAnt.Compression.Tasks { /// /// Creates a tar file from the specified filesets. /// /// /// Uses #ziplib (SharpZipLib), an open source Tar/Zip/GZip library written entirely in C#. /// /// /// /// Tar all files in ${build.dir} and ${doc.dir} into a file /// called "backup.tar.gz", and apply gzip compression to it. /// /// /// /// /// /// /// /// /// /// /// ]]> /// /// [TaskName("tar")] public class TarTask : Task { #region Private Instance Fields private FileInfo _destFile; private TarFileSetCollection _filesets = new TarFileSetCollection(); private bool _flatten = false; private bool _includeEmptyDirs = false; private TarCompressionMethod _compressionMethod = TarCompressionMethod.None; private Hashtable _addedDirs = new Hashtable(); #endregion Private Instance Fields #region Public Instance Properties /// /// The tar file to create. /// [TaskAttribute("destfile", Required=true)] public FileInfo DestFile { get { return _destFile; } set { _destFile = value; } } /// /// Include empty directories in the generated tar file. The default is /// . /// [TaskAttribute("includeemptydirs", Required=false)] [BooleanValidator()] public bool IncludeEmptyDirs { get { return _includeEmptyDirs; } set { _includeEmptyDirs = value; } } /// /// Ignore directory structure of source directory, compress all files /// into a single directory. /// The default value is . /// [TaskAttribute("flatten")] [BooleanValidator()] public virtual bool Flatten { get { return _flatten; } set { _flatten = value; } } /// /// The set of files to be included in the archive. /// [BuildElementArray("fileset")] public TarFileSetCollection TarFileSets { get { return _filesets; } } /// /// The compression method. The default is . /// [TaskAttribute("compression")] public TarCompressionMethod CompressionMethod { get { return _compressionMethod; } set { _compressionMethod = value; } } #endregion Public Instance Properties #region Override implementation of Task /// /// Creates the tar file. /// protected override void ExecuteTask() { TarArchive archive = null; Stream outstream = null; Log(Level.Info, "Tarring {0} files to '{1}'.", TarFileSets.FileCount, DestFile.FullName); try { if (!Directory.Exists(DestFile.DirectoryName)) { Directory.CreateDirectory(DestFile.DirectoryName); } outstream = File.Create(DestFile.FullName); // wrap outputstream with corresponding compression method switch (CompressionMethod) { case TarCompressionMethod.GZip: outstream = new GZipOutputStream(outstream); break; case TarCompressionMethod.BZip2: outstream = new BZip2OutputStream(outstream); break; } // create tar archive archive = TarArchive.CreateOutputTarArchive(outstream, TarBuffer.DefaultBlockFactor); // do not use convert line endings of text files to \n, as this // converts all content to ASCII archive.AsciiTranslate = false; // process all filesets foreach (TarFileSet fileset in TarFileSets) { string basePath = fileset.BaseDirectory.FullName; if (Path.GetPathRoot(basePath) != basePath) { basePath = Path.GetDirectoryName(basePath + Path.DirectorySeparatorChar); } // add files to tar foreach (string file in fileset.FileNames) { // ensure file exists (in case "asis" was used) if (!File.Exists(file)) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "File '{0}' does not exist.", file), Location); } // the filename of the tar entry string entryFileName; // the directory of the tar entry string entryDirName = string.Empty; // determine name of the tar entry if (!Flatten && file.StartsWith(basePath)) { entryFileName = file.Substring(basePath.Length); if (entryFileName.Length > 0 && entryFileName[0] == Path.DirectorySeparatorChar) { entryFileName = entryFileName.Substring(1); } // get directory part of entry entryDirName = Path.GetDirectoryName(entryFileName); // ensure directory separators are understood on linux if (Path.DirectorySeparatorChar == '\\') { entryDirName = entryDirName.Replace(@"\", "/"); } // get filename part of entry entryFileName = Path.GetFileName(entryFileName); } else { entryFileName = Path.GetFileName(file); } // add prefix if specified if (fileset.Prefix != null) { entryDirName = fileset.Prefix + entryDirName; } // ensure directory has trailing slash if (entryDirName.Length != 0) { if (!entryDirName.EndsWith("/")) { entryDirName += '/'; } // create directory entry in archive CreateDirectoryEntry(archive, entryDirName, fileset); } TarEntry entry = TarEntry.CreateEntryFromFile(file); entry.Name = entryDirName + entryFileName; entry.GroupId = fileset.Gid; entry.GroupName = fileset.GroupName; entry.UserId = fileset.Uid; entry.UserName = fileset.UserName; entry.TarHeader.Mode = fileset.FileMode; // write file to tar file archive.WriteEntry(entry, true); } // add (possibly empty) directories to zip if (IncludeEmptyDirs) { // add (possibly empty) directories to tar foreach (string directory in fileset.DirectoryNames) { // skip directories that are not located beneath the base // directory if (!directory.StartsWith(basePath) || directory.Length <= basePath.Length) { continue; } // determine tar entry name string entryName = directory.Substring(basePath.Length + 1); // add prefix if specified if (fileset.Prefix != null) { entryName = fileset.Prefix + entryName; } // ensure directory separators are understood on linux if (Path.DirectorySeparatorChar == '\\') { entryName = entryName.Replace(@"\", "/"); } if (!entryName.EndsWith("/")) { // trailing directory signals to #ziplib that we're // dealing with directory entry entryName += "/"; } // create directory entry in archive CreateDirectoryEntry(archive, entryName, fileset); } } } // close the tar archive archive.Close(); } catch (Exception ex) { // close the tar output stream if (outstream != null) { outstream.Close(); } // close the tar archive if (archive != null) { archive.Close(); } // delete the (possibly corrupt) tar file if (DestFile.Exists) { DestFile.Delete(); } throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Tar file '{0}' could not be created.", DestFile.FullName), Location, ex); } } #endregion Override implementation of Task #region Private Instance Methods private void CreateDirectoryEntry(TarArchive archive, string entryName, TarFileSet fileset) { // skip directories that were already added before if (_addedDirs.ContainsKey(entryName)) { return; } // create directory entry TarEntry entry = TarEntry.CreateTarEntry(entryName); entry.GroupId = fileset.Gid; entry.GroupName = fileset.GroupName; entry.UserId = fileset.Uid; entry.UserName = fileset.UserName; entry.TarHeader.Mode = fileset.DirMode; // write directory to tar file archive.WriteEntry(entry, false); // remember that directory entry was added _addedDirs[entryName] = null; } #endregion Private Instance Methods } } nant-0.92-rc1/src/NAnt.Compression/NAnt.Compression.build0000644000175000017500000000244011757302272023137 0ustar jtaylorjtaylor nant-0.92-rc1/src/NAnt.Compression/NAnt.Compression.csproj0000644000175000017500000001121511757302272023340 0ustar jtaylorjtaylor Debug AnyCPU 2.0 {8F80C098-94A4-44DB-A25D-C9E455FC3120} NAnt.Compression NAnt.CompressionTasks Library OnSuccessfulBuild false 8.0.50727 v2.0 2.0 publish\ true Disk false Foreground 7 Days false false true 0 1.0.0.%2a false false true true full false ..\..\build\Debug\ 4 AllRules.ruleset TRACE;DEBUG ..\..\build\Debug\NAnt.CompressionTasks.xml true pdbonly true ..\..\build\Release\ 4 AllRules.ruleset TRACE ..\..\build\Release\NAnt.CompressionTasks.xml ..\..\lib\common\neutral\ICSharpCode.SharpZipLib.dll CommonAssemblyInfo.cs False .NET Framework 3.5 SP1 Client Profile false False .NET Framework 3.5 SP1 true False Windows Installer 3.1 true {8F5F8375-4097-4952-B860-784EB9961ABE} NAnt.Core nant-0.92-rc1/src/NAnt.Win32/0000755000175000017500000000000011757310030015346 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.Win32/NAnt.Win32.build0000644000175000017500000000252711757302274020151 0ustar jtaylorjtaylor nant-0.92-rc1/src/NAnt.Win32/AssemblyInfo.cs0000644000175000017500000000255711757302274020314 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Scott Hernandez (ScottHernandez@hotmail.com) // Gert Driesen (drieseng@users.sourceforge.net) using System.Reflection; using System.Security.Permissions; // This will not compile with Visual Studio. If you want to build a signed // executable use the NAnt build file. To build under Visual Studio just // exclude this file from the build. [assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile(@"..\NAnt.key")] [assembly: AssemblyKeyName("")] #if (!NET_4_0) [assembly: RegistryPermissionAttribute(SecurityAction.RequestMinimum , Unrestricted=true)] #endifnant-0.92-rc1/src/NAnt.Win32/NAnt.Win32.csproj0000644000175000017500000001077611757302274020357 0ustar jtaylorjtaylor Debug AnyCPU 2.0 {C66545A2-6FEC-4A38-937A-5B25E61EE8A1} NAnt.Win32 NAnt.Win32Tasks Library OnSuccessfulBuild false 8.0.50727 v2.0 2.0 publish\ true Disk false Foreground 7 Days false false true 0 1.0.0.%2a false false true true full false 4 ..\..\build\Debug\ AllRules.ruleset TRACE;DEBUG ..\..\build\Debug\NAnt.Win32Tasks.xml true pdbonly true ..\..\build\Release\ 4 AllRules.ruleset TRACE ..\..\build\Release\NAnt.Win32Tasks.xml CommonAssemblyInfo.cs False .NET Framework 3.5 SP1 Client Profile false False .NET Framework 3.5 SP1 true False Windows Installer 3.1 true {8F5F8375-4097-4952-B860-784EB9961ABE} NAnt.Core {B50A1067-785B-4686-8FFC-5AF424BEF163} NAnt.DotNet nant-0.92-rc1/src/NAnt.Win32/Functions/0000755000175000017500000000000011757310030017316 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.Win32/Functions/CygpathFunctions.cs0000644000175000017500000001430511757302274023153 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian Maclean (imaclean@gmail.com) // Jaroslaw Kowalski (jkowalski@users.sourceforge.net) // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.ComponentModel; using System.IO; using System.Collections; using System.Reflection; using System.Globalization; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Tasks; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.Win32.Functions { /// /// Groups a set of functions that convert Windows native filenames to /// Cygwin POSIX-style pathnames and vice versa. /// /// /// It can be used when a Cygwin program needs to pass a file name to a /// native Windows program, or expects to get a file name from a native /// Windows program. /// [FunctionSet("cygpath", "Unix/Cygwin")] public class CygpathFunctions : FunctionSetBase { #region Public Instance Constructors /// /// Initializes a new instance of the /// class with the specified and properties. /// /// The in which the class is used. /// The set of properties to use for macro expansion. public CygpathFunctions(Project project, PropertyDictionary properties) : base(project, properties) { } #endregion Public Instance Constructors #region Public Instance Methods /// /// Gets the DOS (short) form of the specified path. /// /// The path to convert. /// /// The DOS (short) form of the specified path. /// /// cygpath could not be started. /// could not be converted to a short form. [Function("get-dos-path")] public string GetDosPath(string path) { return RunCygpathString(new Argument[] { new Argument("--dos \"" + path + "\"") }); } /// /// Gets the Unix form of the specified path. /// /// The path to convert. /// /// The Unix form of the specified path. /// /// cygpath could not be started. /// could not be converted to a Unix form. [Function("get-unix-path")] public string GetUnixPath(string path) { return RunCygpathString(new Argument[] { new Argument("--unix \"" + path + "\"") }); } /// /// Gets the Windows form of the specified path. /// /// The path to convert. /// /// The Windows form of the specified path. /// /// cygpath could not be started. /// could not be converted to a Windows form. [Function("get-windows-path")] public string GetWindowsPath(string path) { return RunCygpathString(new Argument[] { new Argument("--windows \"" + path + "\"") }); } #endregion Public Instance Methods #region Private Instance Methods /// /// Runs cygpath with the specified arguments and returns the result /// as a . /// /// The arguments to pass to cygpath. /// /// The result of running cygpath with the specified arguments. /// private string RunCygpathString(Argument[] args) { MemoryStream ms = new MemoryStream(); ExecTask execTask = GetTask(ms); execTask.Arguments.AddRange(args); try { execTask.Execute(); ms.Position = 0; StreamReader sr = new StreamReader(ms); string output = sr.ReadLine(); sr.Close(); return output; } catch (Exception ex) { ms.Position = 0; StreamReader sr = new StreamReader(ms); string output = sr.ReadToEnd(); sr.Close(); if (output.Length != 0) { throw new BuildException(output, ex); } else { throw; } } } /// /// Factory method to return a new instance of ExecTask /// /// /// private ExecTask GetTask(Stream stream) { ExecTask execTask = new ExecTask(); execTask.Parent = Project; execTask.Project = Project; execTask.FileName = "cygpath"; execTask.Threshold = Level.None; execTask.ErrorWriter = execTask.OutputWriter = new StreamWriter(stream); return execTask; } #endregion Private Instance Methods } } nant-0.92-rc1/src/NAnt.Win32/Tasks/0000755000175000017500000000000011757310030016433 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.Win32/Tasks/RegAsmTask.cs0000644000175000017500000003456011757302274021006 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2006 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian MacLean (ian@maclean.ms) // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections.Specialized; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Types; using NAnt.Core.Tasks; using NAnt.Core.Util; using NAnt.DotNet.Types; namespace NAnt.Win32.Tasks { /// /// Registers an assembly, or set of assemblies for use from COM clients. /// /// /// /// Refer to the Regasm /// documentation for more information on the regasm tool. /// /// /// /// /// Register types in a single assembly. /// /// /// /// ]]> /// /// /// /// /// Register types of an assembly and generate a type library containing /// definitions of accessible types defined within the assembly. /// /// /// /// ]]> /// /// /// /// /// Register types of set of assemblies at once, while specifying a set /// of reference assemblies. /// /// /// /// /// /// /// /// /// /// /// /// ]]> /// /// [TaskName("regasm")] [ProgramLocation(LocationType.FrameworkDir)] public class RegAsmTask : ExternalProgramBase { #region Private Instance Fields private StringBuilder _arguments = new StringBuilder(); private string _programFileName; private DirectoryInfo _workingDirectory; private FileInfo _assemblyFile; private FileInfo _regfile; private FileInfo _typelib; private bool _codebase; private bool _unregister; private bool _registered; private AssemblyFileSet _assemblies = new AssemblyFileSet(); private AssemblyFileSet _references = new AssemblyFileSet(); #endregion Private Instance Fields #region Public Instance Properties /// /// The name of the file to register. This is provided as an alternate /// to using the task's . /// [TaskAttribute("assembly")] public FileInfo AssemblyFile { get { return _assemblyFile; } set { _assemblyFile = value; } } /// /// Registry file to export to instead of entering the types directly /// into the registry. /// [TaskAttribute("regfile")] public FileInfo RegistryFile { get { return _regfile; } set { _regfile = value; } } /// /// Set the code base registry setting. /// [TaskAttribute("codebase")] [BooleanValidator()] public bool CodeBase { get { return _codebase; } set { _codebase = value; } } /// /// Only refer to already registered type libraries. /// [TaskAttribute("registered")] [BooleanValidator()] public bool Registered { get { return _registered; } set { _registered = value; } } /// /// Export the assemblies to the specified type library and register it. /// [TaskAttribute("typelib")] public FileInfo TypeLib { get { return _typelib; } set { _typelib = value; } } /// /// Unregister the assembly. The default is . /// [TaskAttribute("unregister")] [BooleanValidator()] public bool Unregister { get { return _unregister; } set { _unregister = value; } } /// /// The set of assemblies to register, or unregister. /// [BuildElement("assemblies")] public AssemblyFileSet Assemblies { get { return _assemblies; } set { _assemblies = value; } } /// /// The set of assembly references. /// [BuildElement("references")] public AssemblyFileSet References { get { return _references; } set { _references = value; } } #endregion Public Instance Properties #region Override implementation of ExternalProgramBase /// /// Gets the working directory for the application. /// /// /// The working directory for the application. /// public override DirectoryInfo BaseDirectory { get { if (_workingDirectory == null) { return base.BaseDirectory; } return _workingDirectory; } set { _workingDirectory = value; } } /// /// Gets the command line arguments for the external program. /// /// /// The command line arguments for the external program. /// public override string ProgramArguments { get { return _arguments.ToString(); } } /// /// Gets the filename of the external program to start. /// /// /// The filename of the external program. /// /// /// Override in derived classes to explicitly set the location of the /// external tool. /// public override string ProgramFileName { get { if (_programFileName == null) { _programFileName = base.ProgramFileName; } return _programFileName; } } /// /// Updates the of the specified /// . /// /// The of which the should be updated. protected override void PrepareProcess(Process process) { // avoid copying the assembly references (and regasm) to a // temporary directory if not necessary if (References.FileNames.Count == 0) { // further delegate preparation to base class base.PrepareProcess(process); // no further processing required return; } // create instance of Copy task CopyTask ct = new CopyTask(); // inherit project from current task ct.Project = Project; // inherit namespace manager from current task ct.NamespaceManager = NamespaceManager; // parent is current task ct.Parent = this; // inherit verbose setting from resgen task ct.Verbose = Verbose; // only output warning messages or higher, unless we're running // in verbose mode if (!ct.Verbose) { ct.Threshold = Level.Warning; } // make sure framework specific information is set ct.InitializeTaskConfiguration(); // set parent of child elements ct.CopyFileSet.Parent = ct; // inherit project from solution task for child elements ct.CopyFileSet.Project = ct.Project; // inherit namespace manager from solution task ct.CopyFileSet.NamespaceManager = ct.NamespaceManager; // set base directory of fileset ct.CopyFileSet.BaseDirectory = Assemblies.BaseDirectory; // copy all files to base directory itself ct.Flatten = true; // copy referenced assemblies foreach (string file in References.FileNames) { ct.CopyFileSet.Includes.Add(file); } // copy assemblies to register foreach (string file in Assemblies.FileNames) { ct.CopyFileSet.Includes.Add(file); } if (AssemblyFile != null) { ct.CopyFileSet.Includes.Add(AssemblyFile.FullName); } // copy command line tool to working directory ct.CopyFileSet.Includes.Add(base.ProgramFileName); // set destination directory ct.ToDirectory = BaseDirectory; // increment indentation level ct.Project.Indent(); try { // execute task ct.Execute(); } finally { // restore indentation level ct.Project.Unindent(); } // change program to execute the tool in working directory as // that will allow this tool to resolve assembly references // using assemblies stored in the same directory _programFileName = Path.Combine(BaseDirectory.FullName, Path.GetFileName(base.ProgramFileName)); // further delegate preparation to base class base.PrepareProcess(process); } #endregion Override implementation of ExternalProgramBase #region Override implementation of Task /// /// Registers or unregisters a single assembly, or a group of assemblies. /// protected override void ExecuteTask() { if (AssemblyFile == null && Assemblies.FileNames.Count == 0) { return; } // when reference assembly are specified, we copy all references // and all assemblies to a temp directory and run regasm from there if (References.FileNames.Count != 0) { // use a newly created temporary directory as working directory BaseDirectory = FileUtils.GetTempDirectory(); } if (Unregister) { _arguments.Append(" /unregister"); } if (TypeLib != null) { _arguments.AppendFormat(CultureInfo.InvariantCulture, " /tlb:\"{0}\"", TypeLib.FullName); } if (CodeBase) { _arguments.Append(" /codebase"); } if (RegistryFile != null) { _arguments.AppendFormat(CultureInfo.InvariantCulture, " /regfile:\"{0}\"", RegistryFile.FullName); } if (Registered) { _arguments.Append(" /registered"); } if (Verbose) { _arguments.Append(" /verbose"); } else { _arguments.Append(" /silent"); } _arguments.Append(" /nologo"); if (AssemblyFile != null) { Log(Level.Info, "{0} '{1}' for COM Interop", Unregister ? "Unregistering" : "Registering", AssemblyFile.FullName); _arguments.AppendFormat(" \"{0}\"", GetAssemblyPath( AssemblyFile.FullName)); } else { // display build log message Log(Level.Info, "{0} {1} files for COM interop", Unregister ? "UnRegistering" : "Registering", Assemblies.FileNames.Count); // add files to command line foreach (string path in Assemblies.FileNames) { Log(Level.Verbose, "{0} '{1}' for COM Interop", Unregister ? "UnRegistering" : "Registering", path); _arguments.AppendFormat(" \"{0}\"", GetAssemblyPath(path)); } } try { // call base class to do the work base.ExecuteTask(); } finally { // we only need to remove temporary directory if it was // actually created if (_workingDirectory != null) { // delete temporary directory and all files in it DeleteTask deleteTask = new DeleteTask(); deleteTask.Project = Project; deleteTask.Parent = this; deleteTask.InitializeTaskConfiguration(); deleteTask.Directory = _workingDirectory; deleteTask.Threshold = Level.None; // no output in build log deleteTask.Execute(); } } } #endregion Override implementation of Task #region Private Instance Methods private string GetAssemblyPath(string assembly) { if (_workingDirectory == null) { return assembly; } return Path.Combine(_workingDirectory.FullName, Path.GetFileName(assembly)); } #endregion Private Instance Methods } } nant-0.92-rc1/src/NAnt.Win32/Tasks/MonoRegistryTask.cs0000644000175000017500000000706111757302274022265 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2002 Ryan Boggs // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ryan Boggs (rmboggs@users.sourceforge.net) using System; using System.IO; using NAnt.Core; using NAnt.Core.Util; using NAnt.Core.Attributes; using Microsoft.Win32; namespace NAnt.Win32.Tasks { /// /// Reads the mono registry path into a NAnt property. /// /// /// The mono registry keyes can exist in one of two places depending on the platform. This /// task will check to see which registry path that Mono is using. /// /// /// /// /// ]]> /// /// [TaskName("monoregistry")] internal class MonoRegistryTask : Task { #region Private Static Fields /// /// The Mono reg key to default to if none of the keys in _regKeys are found /// in the running machine. /// private const string _defaultRegKey = @"SOFTWARE\Mono"; #endregion Private Static Fields #region Private Instance Fields /// /// Private property name to assign the Mono registry path to. /// private string _propName; /// /// Private array of Mono registry paths to test in order. /// /// /// If new registry paths are used by the Mono team, add them to this array. /// private string[] _regKeys = new string[] { @"SOFTWARE\Wow6432Node\Novell\Mono", @"SOFTWARE\Novell\Mono" }; #endregion Private Instance Fields #region Public Instance Properties /// /// /// The property to set to the Mono registry path. /// /// [TaskAttribute("property", Required=true)] [StringValidator(AllowEmpty=false)] public virtual string PropertyName { get { return _propName; } set { _propName = value; } } #endregion Public Instance Properties #region Override implementation of Task /// /// Locates the appropriate Mono registry path to use. /// protected override void ExecuteTask() { foreach(string key in _regKeys) { RegistryKey checkKey = Registry.LocalMachine.OpenSubKey(key); if (checkKey != null) { Properties[_propName] = key; return; } } // If none of the paths found in the _regKeys array, assign the default value // to the property. Properties[_propName] = _defaultRegKey; } #endregion Override implementation of Task } }nant-0.92-rc1/src/NAnt.Win32/Tasks/TlbExpTask.cs0000644000175000017500000001735311757302274021027 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Aaron Anderson (aaron@skypoint.com | aaron.anderson@farmcreditbank.com) using System.Collections.Specialized; using System.IO; using System.Text; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Tasks; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.Win32.Tasks { /// /// Exports a .NET assembly to a type library that can be used from unmanaged /// code (wraps Microsoft's tlbexp.exe). /// /// /// /// See the Microsoft.NET Framework SDK documentation for details. /// /// /// /// Export DotNetAssembly.dll to LegacyCOM.dll. /// /// /// ]]> /// /// [TaskName("tlbexp")] [ProgramLocation(LocationType.FrameworkSdkDir)] public class TlbExpTask : ExternalProgramBase { #region Private Instance Fields private FileInfo _assemblyFile; private FileInfo _outputFile; private FileInfo _namesFile; private StringBuilder _argumentBuilder; #endregion Private Instance Fields #region Public Instance Properties /// /// Specifies the assembly for which to export a type library. /// /// /// The assembly for which to export a type library. /// /// See the Microsoft.NET Framework SDK documentation for details. [TaskAttribute("assembly", Required=true)] public FileInfo AssemblyFile { get { return _assemblyFile; } set { _assemblyFile = value; } } /// /// Specifies the name of the type library file to generate. /// /// /// The name of the type library file to generate. /// /// See the Microsoft.NET Framework SDK documentation for details. [TaskAttribute("output", Required=true)] public FileInfo OutputFile { get { return _outputFile; } set { _outputFile = value; } } /// /// Specifies the file used to determine capitalization of names in a /// type library. /// /// /// The file used to determine capitalization of names in a type library. /// /// See the Microsoft.NET Framework SDK documentation for details. [TaskAttribute("names")] public FileInfo NamesFile { get { return _namesFile; } set { _namesFile = value; } } #endregion Public Instance Properties #region Override implementation of ExternalProgramBase /// /// Gets the command line arguments for the external program. /// /// /// The command line arguments for the external program. /// public override string ProgramArguments { get { if (_argumentBuilder != null) { return _argumentBuilder.ToString(); } else { return null; } } } /// /// Exports the type library. /// protected override void ExecuteTask() { //Check to see if any of the underlying interop dlls or the typelibs have changed //Otherwise, it's not necessary to reimport. if (NeedsCompiling()) { //Using a stringbuilder vs. StreamWriter since this program will not accept response files. _argumentBuilder = new StringBuilder(); _argumentBuilder.Append("\"" + AssemblyFile.FullName + "\""); // Any option that specifies a file name must be wrapped in quotes // to handle cases with spaces in the path. _argumentBuilder.AppendFormat(" /out:\"{0}\"", OutputFile.FullName); // suppresses the Microsoft startup banner display _argumentBuilder.Append(" /nologo"); if (Verbose) { // displays extra information _argumentBuilder.Append(" /verbose"); } else { // suppresses all output except for errors _argumentBuilder.Append(" /silent"); } // filename used to determine capitalization of names in typelib if (NamesFile != null) { _argumentBuilder.AppendFormat(" /names:\"{0}\"", NamesFile.FullName); } // call base class to do the work base.ExecuteTask(); } } #endregion Override implementation of ExternalProgramBase #region Protected Instance Methods /// /// Determines whether the assembly needs to be exported to a type /// library again. /// /// /// if the assembly needs to be exported to a /// type library; otherwise, . /// protected virtual bool NeedsCompiling() { // return true as soon as we know we need to compile if (!OutputFile.Exists) { Log(Level.Verbose, "Output file '{0}' does not exist, recompiling.", OutputFile.FullName); return true; } // check if the assembly was changed since the typelib was generated string fileName = FileSet.FindMoreRecentLastWriteTime(AssemblyFile.FullName, OutputFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, "'{0}' has been updated, recompiling.", fileName); return true; } // check if the names file was changed since the typelib was generated if (NamesFile != null) { fileName = FileSet.FindMoreRecentLastWriteTime(NamesFile.FullName, OutputFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, "'{0}' has been updated, recompiling.", fileName); return true; } } // if we made it here then we don't have to export the assembly again. return false; } #endregion Protected Instance Methods } } nant-0.92-rc1/src/NAnt.Win32/Tasks/LocateSdkTask.cs0000644000175000017500000003043711757302274021500 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2002 Ryan Boggs // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ryan Boggs (rmboggs@users.sourceforge.net) using System; using System.Text.RegularExpressions; using System.IO; using System.Xml; using System.Globalization; using NAnt.Core; using NAnt.Core.Util; using NAnt.Core.Attributes; using Microsoft.Win32; namespace NAnt.Win32.Tasks { /// /// Reads the most recent Windows SDK InstallationFolder key into a NAnt property /// /// /// /// /// ]]> /// /// [TaskName("locatesdk")] internal class LocateSdkTask : Task { #region Private Instance Fields private string _propName; private string _minWinSdkVer = "v6.0"; private string _maxWinSdkVer; private string _minNetFxVer = "2.0"; private string _maxNetFxVer; private readonly string _registryBase = @"SOFTWARE\Microsoft\Microsoft SDKs\Windows"; private readonly string _regexNetFxTools = @"^WinSDK.*NetFx.*Tools.*$"; #endregion Private Instance Fields #region Public Instance Properties /// /// /// The property to set to the value stored in the InstalledFolder key of the located WinSDK version. /// /// [TaskAttribute("property", Required=true)] [StringValidator(AllowEmpty=false)] public virtual string PropertyName { get { return _propName; } set { _propName = value; } } /// /// /// The minimum acceptable Windows SDK version. /// /// [TaskAttribute("minwinsdkver")] public string MinWinSdkVersion { get { return _minWinSdkVer; } set { _minWinSdkVer = value; } } /// /// /// The maximum acceptable Windows SDK version. /// /// [TaskAttribute("maxwinsdkver")] public string MaxWinSdkVersion { get { return _maxWinSdkVer; } set { _maxWinSdkVer = value; } } /// /// /// The minimum acceptable .NET sdk version. /// /// [TaskAttribute("minnetfxver")] public string MinNetFxVersion { get { return _minNetFxVer; } set { _minNetFxVer = value; } } /// /// /// The maximum acceptable .NET sdk version. /// /// [TaskAttribute("maxnetfxver")] public string MaxNetFxVersion { get { return _maxNetFxVer; } set { _maxNetFxVer = value; } } #endregion Public Instance Properties #region Override implementation of Task /// /// locate the most recent WinSDK installed /// protected override void ExecuteTask() { // Initialize all necessary Version objects // These will hold the min, max, and loop WinSDK versions found Version minSdkVersion = StringToVersion(_minWinSdkVer); Version maxSdkVersion = StringToVersion(_maxWinSdkVer); Version loopSdkVersion = null; // These will hold the min, max, and loop .NET versions found Version minNetVersion = StringToVersion(_minNetFxVer); Version maxNetVersion = StringToVersion(_maxNetFxVer); Version loopNetVersion = null; // Bool variable used to indicate that a valid SDK was found bool sdkFound = false; // Get all of the WinSDK version keys from the user's registry and // load them into a string array. RegistryKey sdkRegSubKey = Registry.LocalMachine.OpenSubKey(_registryBase, false); string[] installedWinSdkVersions = sdkRegSubKey.GetSubKeyNames(); // Sort and reverse the WinSDK version key array to make sure that // the latest version is reviewed first before reviewing earlier // versions. Array.Sort(installedWinSdkVersions); Array.Reverse(installedWinSdkVersions); // Loop through all of the WinSDK version keys. for(int i = 0; i < installedWinSdkVersions.Length; i++) { loopSdkVersion = StringToVersion(installedWinSdkVersions[i]); // If a maxVersion was indicated and the loopVersion is greater than // the maxVersion, skip to the next item in the installedVersion array. if (maxSdkVersion != null) { if (loopSdkVersion > maxSdkVersion) { continue; } } // If the loopVersion is greater than or equal to the minVersion, loop through the subkeys // for a valid .NET sdk path if (minSdkVersion <= loopSdkVersion) { // Gets all of the current WinSdk loop subkeys string[] installedWinSdkSubKeys = sdkRegSubKey.OpenSubKey(installedWinSdkVersions[i]).GetSubKeyNames(); // Sort and reverse the order of the subkeys to go from greatest to least Array.Sort(installedWinSdkSubKeys); Array.Reverse(installedWinSdkSubKeys); // Loop through all of the current WinSdk loop subkeys for(int j = 0; j < installedWinSdkSubKeys.Length; j++) { // Check to see if the current subkey matches the RegEx string if (Regex.IsMatch(installedWinSdkSubKeys[j], _regexNetFxTools)) { // Initialize the necessary string array to hold all // possible directory locations string[] netFxDirs = new string[] { sdkRegSubKey.OpenSubKey(installedWinSdkVersions[i]).OpenSubKey(installedWinSdkSubKeys[j]).GetValue("InstallationFolder").ToString(), Path.Combine(sdkRegSubKey.OpenSubKey(installedWinSdkVersions[i]).OpenSubKey(installedWinSdkSubKeys[j]).GetValue("InstallationFolder").ToString(), "bin") }; // Loop through all of the directories in the possible directory // locations array foreach(string netFxDir in netFxDirs) { // Set the full path to the gacutil.exe.config file based on the current // directory in the directories array string netFxXmlFile = Path.Combine(netFxDir, "gacutil.exe.config"); // If the full file path exists, load the gacutil.exe.config xml file if (File.Exists(netFxXmlFile)) { XmlDocument gacXmlDoc = new XmlDocument(); gacXmlDoc.Load(netFxXmlFile); // Get the supported runtime version from the version attribute // and load it into the loopNetVersion Version object to use for // comparisons XmlNode gacVersion = gacXmlDoc.SelectSingleNode("/configuration/startup/requiredRuntime"); XmlAttribute versionAttribute = gacVersion.Attributes["version"]; loopNetVersion = StringToVersion(versionAttribute.Value.ToString()); // If the maxNetVersion object is not null and is less than // the loopNetVersion, continue to the next iteration of the // inner loop if (maxNetVersion != null) { if (loopNetVersion > maxNetVersion) { continue; } } // If loopNetVersion is greater than or equal to minNetVersion // assign the value of the InstallationFolder key of the current subfolder // to the property name and exit the inner loop if (minNetVersion <= loopNetVersion) { Properties[_propName] = netFxDir; sdkFound = true; break; } } } } } // If a valid Sdk version was found within the current Sdk subkeys, break // the outer loop. if (sdkFound) { break; } } } // if the Properties dictionary does not contain the _propName as a key, throw an error. if (!sdkFound) { throw new BuildException(String.Format(CultureInfo.InvariantCulture,"System does not have minimum specified Windows SDK {0}!", _minWinSdkVer)); } } #endregion Override implementation of Task #region Private Instance Methods /// /// Converts a version expressed as a string into a Version object /// /// /// A containing the version to convert. /// /// /// A object representing the version string. /// private Version StringToVersion(string sdkVersion) { if (!String.IsNullOrEmpty(sdkVersion)) { // Make any non-numeric characters uppercase sdkVersion = sdkVersion.Trim().ToUpper(); // Remove the leading v from the sdkVersion string if (sdkVersion.StartsWith("V")) { sdkVersion = sdkVersion.Substring(1); } // Return a new Version object based on the sdkVersion string // If the sdkVersion string ends with an alphanumeric, it is // converted to a revision number for comparison purposes if (!char.IsNumber(sdkVersion, sdkVersion.Length - 1)) { string sdkVerFormat = sdkVersion.Substring(0, sdkVersion.Length -1) + "." + ((int)sdkVersion.ToCharArray()[sdkVersion.Length - 1]).ToString(); return new Version(sdkVerFormat); } else { return new Version(sdkVersion); } // If the sdkVersion parameter is null or empty, return null } else { return null; } } #endregion Private Instance Methods } } nant-0.92-rc1/src/NAnt.Win32/Tasks/AxImpTask.cs0000644000175000017500000002554211757302274020646 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Jayme C. Edwards (jedwards@wi.rr.com) // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Globalization; using System.IO; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Tasks; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.Win32.Tasks { /// /// Generates a Windows Forms Control that wraps ActiveX Controls defined /// in an OCX. /// /// /// /// /// ]]> /// /// [TaskName("aximp")] [ProgramLocation(LocationType.FrameworkSdkDir)] public class AxImpTask : ExternalProgramBase { #region Private Instance Fields private FileInfo _ocxFile; private FileInfo _outputFile; private FileInfo _publicKeyFile; private FileInfo _keyFile; private FileInfo _rcwFile; private string _keyContainer; private bool _delaySign; private bool _generateSource; // framework configuration settings private bool _supportsRcw = true; #endregion Private Instance Fields #region Public Instance Properties /// /// Filename of the .ocx file. /// [TaskAttribute("ocx", Required=true)] public FileInfo OcxFile { get { return _ocxFile; } set { _ocxFile = value; } } /// /// Filename of the generated assembly. /// [TaskAttribute("output")] public FileInfo OutputFile { get { return _outputFile; } set { _outputFile = value; } } /// /// Specifies the file containing the public key to use to sign the /// resulting assembly. /// /// /// The file containing the public key to use to sign the resulting /// assembly. /// [TaskAttribute("publickey")] public FileInfo PublicKeyFile { get { return _publicKeyFile; } set { _publicKeyFile = value; } } /// /// Specifies the publisher's official public/private key pair with which /// the resulting assembly should be signed with a strong name. /// /// /// The keyfile to use to sign the resulting assembly with a strong name. /// /// See the Microsoft.NET Framework SDK documentation for details. [TaskAttribute("keyfile")] public FileInfo KeyFile { get { return _keyFile; } set { _keyFile = value; } } /// /// Specifies the key container in which the public/private key pair /// should be found that should be used to sign the resulting assembly /// with a strong name. /// /// /// The key container containing a public/private key pair that should /// be used to sign the resulting assembly. /// [TaskAttribute("keycontainer")] public string KeyContainer { get { return _keyContainer; } set { _keyContainer = StringUtils.ConvertEmptyToNull(value); } } /// /// Specifies to sign the resulting control using delayed signing. /// [TaskAttribute("delaysign")] [BooleanValidator()] public bool DelaySign { get { return _delaySign; } set { _delaySign = value; } } /// /// Determines whether C# source code for the Windows Form wrapper should /// be generated. The default is . /// [TaskAttribute("generatesource")] [BooleanValidator()] public bool GenerateSource { get { return _generateSource; } set { _generateSource = value; } } /// /// Assembly to use for Runtime Callable Wrapper rather than generating /// new one [.NET 1.1 or higher]. /// [TaskAttribute("rcw")] public FileInfo RcwFile { get { return _rcwFile; } set { _rcwFile = value; } } /// /// Indicates whether aximp supports using an existing Runtime /// Callable Wrapper for a given target framework. The default is /// . /// [FrameworkConfigurable("supportsrcw")] public bool SupportsRcw { get { return _supportsRcw; } set { _supportsRcw = value; } } #endregion Public Instance Properties #region Override implementation of ExternalProgramBase /// /// Gets the command-line arguments for the external program. /// /// /// The command-line arguments for the external program. /// public override string ProgramArguments { get { return ""; } } /// /// Import the ActiveX control. /// protected override void ExecuteTask() { Log(Level.Info, "Generating Windows Forms Control wrapping '{0}'.", OcxFile.FullName); if (!NeedsCompiling()) { return; } if (DelaySign) { Arguments.Add(new Argument("/delaysign")); } if (GenerateSource) { Arguments.Add(new Argument("/source")); } if (Verbose) { Arguments.Add(new Argument("/verbose")); } else { Arguments.Add(new Argument("/silent")); } if (OutputFile != null) { Arguments.Add(new Argument(string.Format(CultureInfo.InvariantCulture, "/out:\"{0}\"", OutputFile.FullName))); } if (PublicKeyFile != null) { Arguments.Add(new Argument(string.Format(CultureInfo.InvariantCulture, "/publickey:\"{0}\"", PublicKeyFile.FullName))); } if (KeyFile != null) { Arguments.Add(new Argument(string.Format(CultureInfo.InvariantCulture, "/keyfile:\"{0}\"", KeyFile.FullName))); } if (KeyContainer != null) { Arguments.Add(new Argument(string.Format(CultureInfo.InvariantCulture, "/keycontainer:\"{0}\"", KeyContainer))); } if (RcwFile != null) { if (SupportsRcw) { Arguments.Add(new Argument(string.Format(CultureInfo.InvariantCulture, "/rcw:\"{0}\"", RcwFile.FullName))); } } // suppresses display of the sign-on banner Arguments.Add(new Argument("/nologo")); Arguments.Add(new Argument(OcxFile)); try { base.ExecuteTask(); } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Error importing ActiveX control from '{0}'.", OcxFile.FullName), Location, ex); } } #endregion Override implementation of ExternalProgramBase #region Protected Instance Methods /// /// Determines whether the assembly needs to be created again. /// /// /// if the assembly needs to be created again; /// otherwise, . /// protected virtual bool NeedsCompiling() { // return true as soon as we know we need to compile if (!OutputFile.Exists) { Log(Level.Verbose, "Output file '{0}' does not exist, recompiling.", OutputFile.FullName); return true; } // check if the ocx was changed since the assembly was generated string fileName = FileSet.FindMoreRecentLastWriteTime(OcxFile.FullName, OutputFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, "'{0}' has been updated, recompiling.", fileName); return true; } // check if the public key file was changed since the assembly was // generated if (PublicKeyFile != null) { fileName = FileSet.FindMoreRecentLastWriteTime(PublicKeyFile.FullName, OutputFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, "'{0}' has been updated, recompiling.", fileName); return true; } } // check if the key file was changed since the assembly was generated if (KeyFile != null) { fileName = FileSet.FindMoreRecentLastWriteTime(KeyFile.FullName, OutputFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, "'{0}' has been updated, recompiling.", fileName); return true; } } // check if the Runtime Callable Wrapper file was changed since the // assembly was generated if (RcwFile != null) { fileName = FileSet.FindMoreRecentLastWriteTime(RcwFile.FullName, OutputFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, "'{0}' has been updated, recompiling.", fileName); return true; } } // if we made it here then we don't have to export the assembly again. return false; } #endregion Protected Instance Methods } } nant-0.92-rc1/src/NAnt.Win32/Tasks/ReadRegistryTask.cs0000644000175000017500000002046711757302274022235 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2002 Scott Hernandez // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Scott Hernandez (ScottHernandez@hotmail.com) using System; using System.Globalization; using System.Security.Permissions; using Microsoft.Win32; using NAnt.Core; using NAnt.Core.Attributes; #if (!NET_4_0) [assembly: RegistryPermissionAttribute(SecurityAction.RequestMinimum , Unrestricted=true)] #endif namespace NAnt.Win32.Tasks { /// /// Reads a value or set of values from the Windows Registry into one or /// more NAnt properties. /// /// /// Read a single value from the registry. /// /// /// ]]> /// /// Read all the registry values in a key. /// /// /// ]]> /// /// [TaskName("readregistry")] public class ReadRegistryTask : Task { #region Private Instance Fields private string _propName; private string _propPrefix; private string _regKey; private string _regKeyValueName; private RegistryHive[] _regHive = {RegistryHive.LocalMachine}; private string _regHiveString = RegistryHive.LocalMachine.ToString(); #endregion Private Instance Fields #region Public Instance Properties /// /// The property to set to the specified registry key value. /// If this attribute is used then a single value will be read. /// [TaskAttribute("property")] public virtual string PropertyName { get { return _propName; } set { _propName = value; } } /// /// The prefix to use for the specified registry key values. /// If this attribute is used then all registry values will be read and stored as properties with this prefix. /// /// /// Registry values a, b, c will be turned into prefixa, prefixb, prefixc named properties /// [TaskAttribute("prefix")] public virtual string PropertyPrefix { get { return _propPrefix; } set { _propPrefix = value; } } /// /// The registry key to read, including the path. /// /// /// SOFTWARE\Microsoft\.NETFramework\sdkInstallRoot /// [TaskAttribute("key", Required=true)] [StringValidator(AllowEmpty=false)] public virtual string RegistryKey { get { return _regKey; } set { string key = value; if(value.StartsWith("\\")) { key = value.Substring(1); } string[] pathParts = key.Split("\\".ToCharArray(0,1)[0]); //split the key/path apart. _regKeyValueName = pathParts[pathParts.Length - 1]; _regKey = key.Substring(0, (value.Length - _regKeyValueName.Length)); } } /// /// Space separated list of registry hives to search for . /// For a list of possible values, see . The /// default is . /// /// /// /// [TaskAttribute("hive")] public virtual string RegistryHiveName { get { return _regHiveString; } set { _regHiveString = value; string[] tempRegHive = _regHiveString.Split(" ".ToCharArray()[0]); _regHive = (RegistryHive[]) Array.CreateInstance(typeof(RegistryHive), tempRegHive.Length); for (int x=0; x /// read the specified registry value ///
protected override void ExecuteTask() { object regKeyValue = null; if (_regKey == null) { throw new BuildException("Missing registry key!"); } RegistryKey mykey = null; if (_propName != null) { mykey = LookupRegKey(_regKey, _regHive); regKeyValue = mykey.GetValue(_regKeyValueName); if (regKeyValue != null) { string val = regKeyValue.ToString(); Properties[_propName] = val; } else { throw new BuildException(String.Format(CultureInfo.InvariantCulture, "Registry Value Not Found! - key='{0}';hive='{1}';", _regKey + "\\" + _regKeyValueName, _regHiveString)); } } else if (_propName == null && _propPrefix != null) { mykey = LookupRegKey(_regKey, _regHive); foreach (string name in mykey.GetValueNames()) { Properties[_propPrefix + "." + name] = mykey.GetValue(name).ToString(); } } else { throw new BuildException("Missing both a property name and property prefix; atleast one if required!"); } } #endregion Override implementation of Task #region Protected Instance Methods /// /// Returns the hive for a given key. /// /// /// /// /// The hive for a given key. /// protected RegistryKey LookupRegKey(string key, RegistryHive[] registries) { foreach (RegistryHive hive in registries) { Log(Level.Verbose, "Opening {0}:{1}.", hive.ToString(), key); RegistryKey returnkey = GetHiveKey(hive).OpenSubKey(key, false); if (returnkey != null) { return returnkey; } } throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Registry Path Not Found! - key='{0}';hive='{1}';", key, _regHiveString)); } /// /// Returns the key for a given registry hive. /// /// The registry hive to return the key for. /// /// The key for a given registry hive. /// protected RegistryKey GetHiveKey(RegistryHive hive) { switch(hive) { case RegistryHive.LocalMachine: return Registry.LocalMachine; case RegistryHive.Users: return Registry.Users; case RegistryHive.CurrentUser: return Registry.CurrentUser; case RegistryHive.ClassesRoot: return Registry.ClassesRoot; default: Log(Level.Verbose, "Registry not found for {0}.", hive.ToString()); return null; } } #endregion Protected Instance Methods } } nant-0.92-rc1/src/NAnt.Win32/Tasks/TlbImpTask.cs0000644000175000017500000004771611757302274021026 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Aaron Anderson (gerry_shaw@yahoo.com) // Ian MacLean (ian@maclean.ms) using System.Collections.Specialized; using System.IO; using System.Text; using System.Text.RegularExpressions; using NAnt.DotNet.Types; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Tasks; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.Win32.Tasks { /// /// Imports a type library to a .NET assembly (wraps Microsoft's tlbimp.exe). /// /// /// /// This task lets you easily create interop assemblies. By default, it will /// not reimport if the underlying COM TypeLib or reference has not changed. /// /// /// See the Microsoft.NET Framework SDK documentation for details. /// /// /// /// Import LegacyCOM.dll to DotNetAssembly.dll. /// /// /// ]]> /// /// /// /// /// Generate an assembly named "Interop.MSVidCtlLib.dll" for the /// MS Video Control 1.0 Type Library, transforming any [out, retval] /// parameters of methods on dispinterfaces in the type library into /// return values in the managed library. /// /// /// /// /// /// /// /// ]]> /// /// [TaskName("tlbimp")] [ProgramLocation(LocationType.FrameworkSdkDir)] public class TlbImpTask : ExternalProgramBase { #region Private Instance Fields private FileInfo _outputFile; private string _namespace; private string _asmVersion; private bool _delaySign; private bool _primary; private FileInfo _publicKeyFile; private FileInfo _keyFile; private string _keyContainer; private AssemblyFileSet _references = new AssemblyFileSet(); private bool _strictref; private bool _sysarray; private string _transform; private bool _unsafe; private FileInfo _typelib; private StringBuilder _argumentBuilder; // framework configuration settings private bool _supportsTransform = true; #endregion Private Instance Fields #region Public Instance Properties /// /// Specifies the name of the output file. /// /// /// The name of the output file. /// /// See the Microsoft.NET Framework SDK documentation for details. [TaskAttribute("output", Required=true)] public FileInfo OutputFile { get { return _outputFile; } set { _outputFile = value; } } /// /// Specifies the namespace in which to produce the assembly. /// /// /// The namespace in which to produce the assembly. /// /// See the Microsoft.NET Framework SDK documentation for details. [TaskAttribute("namespace")] public string Namespace { get { return _namespace; } set { _namespace = StringUtils.ConvertEmptyToNull(value); } } /// /// Specifies the version number of the assembly to produce. /// /// /// /// The version number of the assembly to produce. /// /// /// The version number should be in the format major.minor.build.revision. /// /// /// See the Microsoft.NET Framework SDK documentation for details. /// /// [TaskAttribute("asmversion")] public string AsmVersion { get { return _asmVersion; } set { _asmVersion = StringUtils.ConvertEmptyToNull(value); } } /// /// Specifies whether the resulting assembly should be signed with a /// strong name using delayed signing. The default is . /// /// /// if the resulting assembly should be signed /// with a strong name using delayed signing; otherwise, . /// /// See the Microsoft.NET Framework SDK documentation for details. [TaskAttribute("delaysign")] [BooleanValidator()] public bool DelaySign { get { return _delaySign; } set { _delaySign = value; } } /// /// Specifies whether a primary interop assembly should be produced for /// the specified type library. The default is . /// /// /// if a primary interop assembly should be /// produced; otherwise, . /// /// See the Microsoft.NET Framework SDK documentation for details. [TaskAttribute("primary")] [BooleanValidator()] public bool Primary { get { return _primary; } set { _primary = value; } } /// /// Specifies the file containing the public key to use to sign the /// resulting assembly. /// /// /// The file containing the public key to use to sign the resulting /// assembly. /// /// See the Microsoft.NET Framework SDK documentation for details. [TaskAttribute("publickey")] public FileInfo PublicKeyFile { get { return _publicKeyFile; } set { _publicKeyFile = value; } } /// /// Specifies the publisher's official public/private key pair with which /// the resulting assembly should be signed with a strong name. /// /// /// The keyfile to use to sign the resulting assembly with a strong name. /// /// See the Microsoft.NET Framework SDK documentation for details. [TaskAttribute("keyfile")] public FileInfo KeyFile { get { return _keyFile; } set { _keyFile = value; } } /// /// Specifies the key container in which the public/private key pair /// should be found that should be used to sign the resulting assembly /// with a strong name. /// /// /// The key container containing a public/private key pair that should /// be used to sign the resulting assembly. /// /// See the Microsoft.NET Framework SDK documentation for details. [TaskAttribute("keycontainer")] public string KeyContainer { get { return _keyContainer; } set {_keyContainer = StringUtils.ConvertEmptyToNull(value); } } /// /// Specifies the assembly files to use to resolve references to types /// defined outside the current type library. /// /// /// The assembly files to use to resolve references to types defined /// outside the current type library. /// /// See the Microsoft.NET Framework SDK documentation for details. [BuildElement("references")] public AssemblyFileSet References { get { return _references; } set { _references = value; } } /// /// Specifies whether a type library should not be imported if all /// references within the current assembly or the reference assemblies /// cannot be resolved. The default is . /// /// /// if a type library should not be imported if /// all references cannot be resolved; otherwise, . /// /// See the Microsoft.NET Framework SDK documentation for details. [TaskAttribute("strictref")] [BooleanValidator()] public bool StrictRef { get { return _strictref; } set { _strictref = value; } } /// /// Specifies whether to import a COM style SafeArray as a managed /// class type. The default is . /// /// /// if a COM style SafeArray should be imported /// as a managed class type; otherwise, /// . /// /// See the Microsoft.NET Framework SDK documentation for details. [TaskAttribute("sysarray")] [BooleanValidator()] public bool SysArray { get { return _sysarray; } set { _sysarray = value; } } /// /// Specifies how to transform the metadata [.NET 1.1 or higher]. /// [TaskAttribute("transform")] public string Transform { get { return _transform; } set { _transform = StringUtils.ConvertEmptyToNull(value); } } /// /// Specifies the source type library that gets passed to the type /// library importer. /// /// /// The source type library that gets passed to the type library /// importer. /// /// See the Microsoft.NET Framework SDK documentation for details. [TaskAttribute("typelib", Required=true)] public FileInfo TypeLib { get { return _typelib; } set { _typelib = value; } } /// /// Specifies whether interfaces should be produced without .NET Framework /// security checks. The default is . /// /// /// if interfaces without .NET Framework security /// checks should be produced; otherwise, . /// /// See the Microsoft.NET Framework SDK documentation for details. [TaskAttribute("unsafe")] [BooleanValidator()] public bool Unsafe { get { return _unsafe; } set { _unsafe = value; } } /// /// Indicates whether tlbimp supports transforming metadata for /// a given target framework. The default is . /// [FrameworkConfigurable("supportstransform")] public bool SupportsTransform { get { return _supportsTransform; } set { _supportsTransform = value; } } #endregion Public Instance Properties #region Override implementation of ExternalProgramBase /// /// Gets the command line arguments for the external program. /// /// /// The command line arguments for the external program. /// public override string ProgramArguments { get { if (_argumentBuilder != null) { return _argumentBuilder.ToString(); } else { return null; } } } /// /// Imports the type library to a .NET assembly. /// protected override void ExecuteTask() { // ensure base directory is set, even if fileset was not initialized // from XML if (References.BaseDirectory == null) { References.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } // check to see if any of the underlying interop dlls or the typelibs have changed // otherwise, it's not necessary to reimport. if (NeedsCompiling()) { // using a stringbuilder vs. StreamWriter since this program will not accept response files. _argumentBuilder = new StringBuilder(); _argumentBuilder.Append("\"" + TypeLib.FullName + "\""); // any option that specifies a file name must be wrapped in quotes // to handle cases with spaces in the path. _argumentBuilder.AppendFormat(" /out:\"{0}\"", OutputFile.FullName); // suppresses the Microsoft startup banner display _argumentBuilder.Append(" /nologo"); if (AsmVersion != null) { _argumentBuilder.AppendFormat(" /asmversion:\"{0}\"", AsmVersion); } if (Namespace != null) { _argumentBuilder.AppendFormat(" /namespace:\"{0}\"", Namespace); } if (Primary) { _argumentBuilder.Append(" /primary"); } if (Unsafe) { _argumentBuilder.Append(" /unsafe"); } if (DelaySign) { _argumentBuilder.Append(" /delaysign"); } if (PublicKeyFile != null) { _argumentBuilder.AppendFormat(" /publickey:\"{0}\"", PublicKeyFile.FullName); } if (KeyFile != null) { _argumentBuilder.AppendFormat(" /keyfile:\"{0}\"", KeyFile.FullName); } if (KeyContainer != null) { _argumentBuilder.AppendFormat(" /keycontainer:\"{0}\"", KeyContainer); } if (StrictRef) { _argumentBuilder.Append(" /strictref"); } if (SysArray) { _argumentBuilder.Append(" /sysarray"); } if (Transform != null) { if (SupportsTransform) { _argumentBuilder.AppendFormat(" /transform:\"{0}\"", Transform); } } if (Verbose) { // displays extra information _argumentBuilder.Append(" /verbose"); } else { // suppresses all output except for errors _argumentBuilder.Append(" /silent"); } foreach (string fileName in References.FileNames) { _argumentBuilder.AppendFormat(" /reference:\"{0}\"", fileName); } // call base class to do the work base.ExecuteTask(); } } #endregion Override implementation of ExternalProgramBase #region Public Static Methods /// /// Returns the path of the type library, removing the identifier of /// the type library from the specified string. /// /// The path from which to extract the path of the type library. /// /// The path of the type library without the type library identifier. /// /// /// An example of a path which includes the identifier of the type /// library (in this case "2") is /// C:\WINDOWS\system32\msvidctl.dll\2. /// public static string ExtractTypeLibPath(string path) { Regex regex = new Regex(@"^.*\\\d+$", RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline | RegexOptions.IgnoreCase); if (regex.IsMatch(path)) { return path.Substring(0, path.LastIndexOf("\\")); } return path; } #endregion Public Static Methods #region Protected Instance Methods /// /// Determines whether the type library needs to be imported again. /// /// /// if the type library needs to be imported; /// otherwise, . /// protected virtual bool NeedsCompiling() { // return true as soon as we know we need to compile if (!OutputFile.Exists) { Log(Level.Verbose, "Output file '{0}' does not exist, recompiling.", OutputFile.FullName); return true; } string typeLibPath = ExtractTypeLibPath(TypeLib.FullName); // check if the type library was updated since the interop assembly was generated string fileName = FileSet.FindMoreRecentLastWriteTime(typeLibPath, OutputFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, "'{0}' has been updated, recompiling.", fileName); return true; } // check if the reference assemblies were updated since the interop assembly was generated fileName = FileSet.FindMoreRecentLastWriteTime(References.FileNames, OutputFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, "'{0}' has been updated, recompiling.", fileName); return true; } // if we made it here then we don't have to reimport the typelib. return false; } #endregion Protected Instance Methods } } nant-0.92-rc1/src/CommonAssemblyInfo.cs0000644000175000017500000000213711757303362017715 0ustar jtaylorjtaylorusing System; using System.Reflection; using System.Runtime.InteropServices; //------------------------------------------------------------------------------ // // This code was generated by a tool. // Runtime Version:4.0.30319.269 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ [assembly: ComVisibleAttribute(false)] [assembly: CLSCompliantAttribute(true)] [assembly: AssemblyTitleAttribute("NAnt")] [assembly: AssemblyDescriptionAttribute("A .NET Build Tool")] [assembly: AssemblyConfigurationAttribute("rc1")] [assembly: AssemblyCompanyAttribute("http://nant.sourceforge.net")] [assembly: AssemblyProductAttribute("NAnt")] [assembly: AssemblyCopyrightAttribute("Copyright (C) 2001-2012 Gerry Shaw")] [assembly: AssemblyTrademarkAttribute("")] [assembly: AssemblyCultureAttribute("")] [assembly: AssemblyVersionAttribute("0.92.4526.0")] [assembly: AssemblyInformationalVersionAttribute("0.92")] nant-0.92-rc1/src/NAnt.MSNet/0000755000175000017500000000000011757310030015432 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.MSNet/AssemblyInfo.cs0000644000175000017500000000220511757302274020366 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System.Reflection; // This will not compile with Visual Studio. If you want to build a signed // executable use the NAnt build file. To build under Visual Studio just // exclude this file from the build. [assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile(@"..\NAnt.key")] [assembly: AssemblyKeyName("")]nant-0.92-rc1/src/NAnt.MSNet/Resources/0000755000175000017500000000000011757310030017404 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.MSNet/Resources/Strings.resx0000644000175000017500000001264711757302274021765 0ustar jtaylorjtaylor text/microsoft-resx 1.0 System.Resources.ResXResourceReader System.Resources.ResXResourceWriter The 'todir' should be set when using the <assemblies> element to specify the list of PE files to disassemble. The 'todir' should be set when using the <assemblies> element to specify the list of PE files to disassemble. The 'input' attribute and the <assemblies> element cannot be combined. The 'input' attribute and the <assemblies> element cannot be combined. Either the 'output' or 'todir' attribute should be set. Either the 'output' or 'todir' attribute should be set. The 'output' and 'todir' attribute cannot both be set. The 'output' and 'todir' attribute cannot both be set. Input file '{0}' does not exist. Input file '{0}' does not exist. The output file for '{0}' could not be determined. The output file for '{0}' could not be determined. Cannot start service {0} on computer '{1}'. Cannot start service {0} on computer '{1}'. Cannot stop service {0} on computer '{1}'. Cannot stop service {0} on computer '{1}'. Cannot pause service {0} on computer '{1}'. Cannot pause service {0} on computer '{1}'. Cannot pause service {0} on computer '{1}' as its not currently started. Cannot pause service {0} on computer '{1}' as its not currently started. Cannot pause service {0} on computer '{1}' as it does not support the pause and continue mechanism. Cannot pause service {0} on computer '{1}' as it does not support the pause and continue mechanism. Cannot continue service {0} on computer '{1}'. Cannot continue service {0} on computer '{1}'. Cannot continue service {0} on computer '{1} as its not currently started. Cannot continue service {0} on computer '{1} as its not currently started. Cannot continue service {0} on computer '{1} as it does not support the pause and continue mechanism. Cannot continue service {0} on computer '{1} as it does not support the pause and continue mechanism. Cannot continue service {0} on computer '{1} as its not currently running or paused. Cannot continue service {0} on computer '{1} as its not currently running or paused. Disassembling '{0}' to '{1}'. Disassembling '{0}' to '{1}'. 'rebuild' attribute set to true, disassembling. 'rebuild' attribute set to true, disassembling. Output file '{0}' does not exist, disassembling. Output file '{0}' does not exist, disassembling. '{0}' has been updated, disassembling. '{0}' has been updated, disassembling. nant-0.92-rc1/src/NAnt.MSNet/NAnt.MSNet.build0000644000175000017500000000354311757302274020320 0ustar jtaylorjtaylor nant-0.92-rc1/src/NAnt.MSNet/Tasks/0000755000175000017500000000000011757310030016517 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.MSNet/Tasks/IldasmTask.cs0000644000175000017500000006543511757302274021132 0ustar jtaylorjtaylor// IldasmTask.cs // // Giuseppe Greco // Copyright (C) 2004 Agamura, Inc. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Giuseppe Greco (giuseppe.greco@agamura.com) using System.Globalization; using System.IO; using System.Xml; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Tasks; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.MSNet.Tasks { /// /// Disassembles any portable executable (PE) file that contains /// intermediate language (IL) code. /// /// /// /// Files are only disassembled if the input file is newer than the output /// file, or if the output file does not exist. However, you can /// explicitly force files to be disassembled with the /// attribute. /// /// /// A can be used to select files to disassemble. /// To use a , the /// attribute must be set. The file name of the output file will be equal /// to the file name of the input file, but with extension ".il". /// /// /// /// /// Disassembles helloworld.exe to helloworld.il. /// /// /// /// ]]> /// /// /// /// /// Disassembles a set of PE files into the specified directory. /// /// /// /// /// /// /// /// /// ]]> /// /// [TaskName("ildasm")] [ProgramLocation(LocationType.FrameworkSdkDir)] public class IldasmTask : ExternalProgramBase { #region Private Instance Fields private const string _TargetExt = "il"; private bool _all; private bool _bytes; private bool _forceRebuild; private bool _header; private bool _lineNumbers; private bool _noIL; private bool _publicOnly; private bool _quoteAllNames; private bool _rawExceptionHandling; private bool _source; private bool _tokens; private bool _unicode; private bool _utf8; private string _item; private string _visibility; private DirectoryInfo _toDir; private FileInfo _inputFile; private FileInfo _outputFile; private FileSet _assemblies; private string _options; #endregion Private Instance Fields #region Public Instance Properties /// /// Specifies whether or not the disassembler should combine the /// /HEADER, /BYTE, and /TOKENS options. The default /// is . /// /// /// if the disassembler should combine the /// /HEADER, /BYTE, and /TOKENS options; /// otherwise, . The default is /// . /// /// /// /// Corresponds to the /ALL flag. /// /// [TaskAttribute("all")] [BooleanValidator()] public bool All { get { return _all; } set { _all = value; } } /// /// Specifies whether or not the disassembler should generate the /// IL stream bytes (in hexadecimal notation) as instruction comments. /// The default is . /// /// /// if the IL stream bytes should be generated /// as instruction comments; otherwise, . The /// default is . /// /// /// /// Corresponds to the /BYTE flag. /// /// [TaskAttribute("bytes")] [BooleanValidator()] public bool Bytes { get { return _bytes; } set { _bytes = value; } } /// /// Instructs NAnt to rebuild the output file regardless of the file /// timestamps. The default is . /// /// /// if the output file should be rebuilt /// regardless of its timestamps; otherwise . /// The default is . /// [TaskAttribute("rebuild")] [BooleanValidator()] public bool ForceRebuild { get { return _forceRebuild; } set { _forceRebuild = value; } } /// /// Specifies whether or not the disassembler should include PE header /// information and runtime header information in the output. The default /// is . /// /// /// if PE header information and runtime header /// information should be included in the output; otherwise, /// . The default is . /// /// /// /// Corresponds to the /HEADER flag. /// /// [TaskAttribute("header")] [BooleanValidator()] public bool Header { get { return _header; } set { _header = value; } } /// /// Specifies the PE file to disassemble. /// /// /// A that represents the PE file /// to disassemble. /// [TaskAttribute("input", Required=false)] public FileInfo InputFile { get { return _inputFile; } set { _inputFile = value; } } /// /// Specifies whether or not the disassembler should include /// references to original source lines. The default is . /// /// /// if references to original source lines /// should be included; otherwise, . The /// default is . /// /// /// /// Corresponds to the /LINENUM flag. /// /// [TaskAttribute("linenumbers")] [BooleanValidator()] public bool LineNumbers { get { return _lineNumbers; } set { _lineNumbers = value; } } /// /// Specifies whether or not the disassembler should suppress ILASM /// code output. The default is . /// /// /// if ILASM code output should be suppresses; /// otherwise, . The default is /// . /// /// /// /// Corresponds to the /NOIL flag. /// /// [TaskAttribute("noil")] [BooleanValidator()] public bool NoIL { get { return _noIL; } set { _noIL = value; } } /// /// Specifies whether or not the disassembler should disassemble /// public items only. This is a shortcut for ="pub". /// The default is . /// /// /// if only public items should be /// disassembled; otherwise, . The default is /// . /// /// /// /// Corresponds to the /PUBONLY flag. /// /// [TaskAttribute("publiconly")] [BooleanValidator()] public bool PublicOnly { get { return _publicOnly; } set { _publicOnly = value; } } /// /// Specifies whether or not the disassembler should enclose all names /// in single quotation marks. By default, only names that don't match /// the ILASM definition of a simple name are quoted. The default is /// . /// /// /// if all names should be enclosed in single /// quotation marks; otherwise, . The default /// is . /// /// /// /// Corresponds to the /QUOTEALLNAMES flag. /// /// [TaskAttribute("quoteallnames")] [BooleanValidator()] public bool QuoteAllNames { get { return _quoteAllNames; } set { _quoteAllNames = value; } } /// /// Specifies whether or not the disassembler should generate /// structured exception handling clauses in canonical (label) form. /// The default is . /// /// /// if structured exception handling clauses /// should be generated in canonical form; otherwise, /// . The default is . /// /// /// /// Corresponds to the /RAWEH flag. /// /// [TaskAttribute("rawexceptionhandling")] [BooleanValidator()] public bool RawExceptionHandling { get { return _rawExceptionHandling; } set { _rawExceptionHandling = value; } } /// /// Specifies whether or not the disassembler should generate /// original source lines as comments. The default is . /// /// /// if original source lines should be /// generated as comments; otherwise, . /// The default is . /// /// /// /// Corresponds to the /SOURCE flag. /// /// [TaskAttribute("source")] [BooleanValidator()] public bool Source { get { return _source; } set { _source = value; } } /// /// Specifies whether or not the disassembler should generate metadata /// token values as comments. The default is . /// /// /// if metadata token values should be /// generated as comments; otherwise, . The /// default is . /// /// /// /// Corresponds to the /TOKENS flag. /// /// [TaskAttribute("tokens")] [BooleanValidator()] public bool Tokens { get { return _tokens; } set { _tokens = value; } } /// /// Specifies whether or not the disassembler should use the UNICODE /// encoding when generating the output. The default is ANSI. /// /// /// if the output should be generated using /// the UNICODE encoding; otherwise, . The /// default is . /// /// /// /// Corresponds to the /UNICODE flag. /// /// [TaskAttribute("unicode")] [BooleanValidator()] public bool Unicode { get { return _unicode; } set { _unicode = value; } } /// /// Specifies whether or not the disassembler should use the UTF-8 /// encoding when generating the output. The default is ANSI. /// /// /// if the output should be generated using /// the UTF-8 encoding; otherwise, . The /// default is . /// /// /// /// Corresponds to the /UTF8 flag. /// /// [TaskAttribute("utf8")] [BooleanValidator()] public bool Utf8 { get { return _utf8; } set { _utf8 = value; } } /// /// Instructs the disassembler to disassemble the specified item only. /// /// /// A that specifies the item to /// disassemble. /// /// /// /// Corresponds to the /ITEM flag. /// /// [TaskAttribute("item", Required=false)] [StringValidator(AllowEmpty=false)] public string Item { get { return _item; } set { _item = value; } } /// /// Instructs the disassembler to disassemble only the items with the /// specified visibility. Possible values are PUB, PRI, /// FAM, ASM, FAA, FOA, PSC, /// or any combination of them separated by +. /// /// /// A that contains the visibility /// suboptions. /// /// /// /// Corresponds to the /VISIBILITY flag. /// /// [TaskAttribute("visibility", Required=false)] [StringValidator(AllowEmpty=false)] public string Visibility { get { return _visibility; } set { _visibility = value; } } /// /// Specifies the name of the output file created by the disassembler. /// /// /// A that represents the name of /// the output file. /// /// /// /// Corresponds to the /OUT flag. /// /// [TaskAttribute("output", Required=false)] public FileInfo OutputFile { get { return _outputFile; } set { _outputFile = value; } } /// /// Specifies the directory to which outputs will be stored. /// /// /// A that represents the /// directory to which outputs will be stored. /// [TaskAttribute("todir", Required=false)] public DirectoryInfo ToDirectory { get { return _toDir; } set { _toDir = value; } } /// /// Specifies a list of PE files to disassemble. To use a , /// the attribute must be specified. /// /// /// A that represents the set /// of PE files to disassemble. /// [BuildElement("assemblies")] public FileSet Assemblies { get { return _assemblies; } set { _assemblies = value; } } #endregion Public Instance Properties #region Override implementation of ExternalProgramBase /// /// The command-line arguments for the external program. /// /// /// Overridden to ensure the <arg> elements would not be exposed /// to build authors. /// public override ArgumentCollection Arguments { get { return base.Arguments; } } /// /// Gets the command-line arguments for the external program. /// /// /// A that contains the command-line /// arguments for the external program. /// public override string ProgramArguments { get { return _options; } } /// /// Checks whether the task is initialized with valid attributes. /// protected override void Initialize() { if (ToDirectory == null && Assemblies != null && Assemblies.Includes.Count > 0) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA3001")), Location); } if (InputFile != null && Assemblies != null && Assemblies.Includes.Count > 0) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA3002")), Location); } if (OutputFile == null && ToDirectory == null) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA3003")), Location); } if (OutputFile != null && ToDirectory != null) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA3004")), Location); } } /// /// Disassembles the PE file(s). /// protected override void ExecuteTask() { // disassemble a single PE file if (InputFile != null) { DisassemblyFile(InputFile); } else { foreach (string inputFile in Assemblies.FileNames) { DisassemblyFile(new FileInfo(inputFile)); } } } #endregion Override implementation of ExternalProgramBase #region Private Instance Methods /// /// Disassembles the specified PE file. /// /// The PE file to disassemble. private void DisassemblyFile(FileInfo inputFile) { // verify if input file actually exists if (!inputFile.Exists) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA3005"), inputFile.FullName), Location); } // determine output file corresponding with PE file FileInfo outputFile = GetOutputFile(inputFile); // only actually perform disassembly if necessary if (NeedsDisassembling(inputFile, outputFile)) { Log(Level.Info, ResourceUtils.GetString("String_Disassembling"), inputFile.FullName, outputFile.FullName); // ensure output directory exists if (!outputFile.Directory.Exists) { outputFile.Directory.Create(); } // set command-line arguments for the disassembler WriteOptions(inputFile, outputFile); // call base class to do the work base.ExecuteTask(); } } /// /// Determines the full path and extension for the output file. /// /// /// A that represents the PE file /// file for which the corresponding output file should be determined. /// /// /// A that represents the full path /// for the output file. /// /// The path of the output file could not be determined. private FileInfo GetOutputFile(FileInfo inputFile) { FileInfo outputFile; if (OutputFile != null) { outputFile = new FileInfo(OutputFile.FullName); } else if (ToDirectory != null) { outputFile = new FileInfo(Path.Combine(ToDirectory.FullName, inputFile.Name)); outputFile = new FileInfo(Path.ChangeExtension(outputFile.FullName, _TargetExt)); } else { // we should never actually get here (if the checks in // Initialize have been executed throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA3006"), inputFile.FullName), Location); } return outputFile; } /// /// Writes the disassembler options. /// private void WriteOptions(FileInfo inputFile, FileInfo outputFile) { using (StringWriter writer = new StringWriter()) { // always direct the output to console WriteOption(writer, "TEXT"); WriteOption(writer, "NOBAR"); if (All) { WriteOption(writer, "ALL"); } if (Bytes) { WriteOption(writer, "BYTES"); } if (Header) { WriteOption(writer, "HEADER"); } if (LineNumbers) { WriteOption(writer, "LINENUM"); } if (NoIL) { WriteOption(writer, "NOIL"); } if (PublicOnly) { WriteOption(writer, "PUBONLY"); } if (QuoteAllNames) { WriteOption(writer, "QUOTEALLNAMES"); } if (RawExceptionHandling) { WriteOption(writer, "RAWEH"); } if (Source) { WriteOption(writer, "SOURCE"); } if (Tokens) { WriteOption(writer, "TOKENS"); } if (Unicode) { WriteOption(writer, "UNICODE"); } if (Utf8) { WriteOption(writer, "UTF8"); } if (Item != null) { WriteOption(writer, "ITEM", Item); } if (Visibility != null) { WriteOption(writer, "VISIBILITY", Visibility.ToUpper()); } // specifiy path of output file WriteOption(writer, "OUT", outputFile.FullName); // specify path of PE file to disassembly writer.Write(" \"" + inputFile.FullName + "\" "); _options = writer.ToString(); // close the StringWriter and the underlying stream writer.Close(); } } /// /// Writes an option using the default output format. /// /// /// The to which the disassembler options /// should be written. /// /// /// A that contains the name of the /// option which should be passed to the disassembler. /// private void WriteOption(StringWriter writer, string name) { writer.Write("/{0} ", name); } /// /// Writes an option and its value using the default output format. /// /// /// The to which the disassembler options /// should be written. /// /// /// A that contains the name of the /// option which should be passed to the disassembler. /// /// /// A that contains the value of the /// option which should be passed to the disassembler. /// private void WriteOption(StringWriter writer, string name, string arg) { // always quote arguments writer.Write("\"/{0}={1}\" ", name, arg); } /// /// Determines whether or not disassembling is needed. /// /// /// if disassembling is needed; otherwise, /// . /// private bool NeedsDisassembling(FileInfo inputFile, FileInfo outputFile) { if (ForceRebuild) { Log(Level.Verbose, ResourceUtils.GetString("String_RebuildAttributeSetToTrue")); return true; } // check if output file already exists if (!outputFile.Exists) { Log(Level.Verbose, ResourceUtils.GetString("String_OutputFileDoesNotExist"), outputFile.FullName); return true; } // check if the source assembly has been updated string fileName = FileSet.FindMoreRecentLastWriteTime( inputFile.FullName, outputFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, ResourceUtils.GetString("String_FileHasBeenUpdated"), fileName); return true; } // no need to disassembly the input file return false; } #endregion Private Instance Methods } } nant-0.92-rc1/src/NAnt.MSNet/Tasks/ServiceControllerTask.cs0000644000175000017500000003641311757302274023357 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gert Driesen // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) // Giuseppe Greco (giuseppe.greco@agamura.com) using System; using System.ComponentModel; using System.Globalization; using System.ServiceProcess; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Util; namespace NAnt.MSNet.Tasks { /// /// Allows a Windows service to be controlled. /// /// /// Starts the World Wide Web Publishing Service on the local computer. /// /// /// ]]> /// /// /// /// Stops the Alerter service on computer 'MOTHER'. /// /// /// ]]> /// /// [TaskName("servicecontroller")] public class ServiceControllerTask : Task { /// /// Defines the actions that can be performed on a service. /// public enum ActionType { /// /// Starts a service. /// Start, /// /// Stops a service. /// Stop, /// /// Restarts a service. /// Restart, /// /// Pauses a running service. /// Pause, /// /// Continues a paused service. /// Continue } #region Public Instance Constructors /// /// Initializes a new instance of the /// class. /// public ServiceControllerTask() { } #endregion Public Instance Constructors #region Public Instance Properties /// /// The name of the service that should be controlled. /// [TaskAttribute("service", Required=true)] [StringValidator(AllowEmpty=false)] public string ServiceName { get { return _serviceName; } set { _serviceName = StringUtils.ConvertEmptyToNull(value); } } /// /// The name of the computer on which the service resides. The default /// is the local computer. /// [TaskAttribute("machine")] public string MachineName { get { return (_machineName == null) ? "." : _machineName; } set { _machineName = StringUtils.ConvertEmptyToNull(value); } } /// /// The action that should be performed on the service. /// [TaskAttribute("action", Required=true)] public ActionType Action { get { return _action; } set { _action = value; } } /// /// The time, in milliseconds, the task will wait for the service to /// reach the desired status. The default is 5000 milliseconds. /// [TaskAttribute("timeout", Required=false)] public double Timeout { get { return _timeout; } set { _timeout = value; } } #endregion Public Instance Properties #region Override implementation of Task /// /// Peforms actions on the service in order to reach the desired status. /// protected override void ExecuteTask() { // get handle to service using (ServiceController serviceController = new ServiceController(ServiceName, MachineName)) { // determine desired status ServiceControllerStatus desiredStatus = DetermineDesiredStatus(); try { // determine current status, this is also verifies if the service // is available ServiceControllerStatus currentStatus = serviceController.Status; } catch (Exception ex) { throw new BuildException(ex.Message, Location, ex.InnerException); } // we only need to take action if the service status differs from // the desired status or if the service should be restarted if (serviceController.Status != desiredStatus || Action == ActionType.Restart) { switch (Action) { case ActionType.Start: StartService(serviceController); break; case ActionType.Pause: PauseService(serviceController); break; case ActionType.Continue: ContinueService(serviceController); break; case ActionType.Stop: StopService(serviceController); break; case ActionType.Restart: RestartService(serviceController); break; } // refresh current service status serviceController.Refresh(); } } } #endregion Override implementation of Task #region Private Instance Methods /// /// Determines the desired status of the service based on the action /// that should be performed on it. /// /// /// The that should be reached /// in order for the to be considered successful. /// private ServiceControllerStatus DetermineDesiredStatus() { switch (Action) { case ActionType.Stop: return ServiceControllerStatus.Stopped; case ActionType.Pause: return ServiceControllerStatus.Paused; default: return ServiceControllerStatus.Running; } } /// /// Starts the service identified by and /// . /// /// instance for controlling the service identified by and . private void StartService(ServiceController serviceController) { try { if (serviceController.Status == ServiceControllerStatus.Paused) { serviceController.Continue(); } else { serviceController.Start(); } // wait until service is running or timeout expired serviceController.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromMilliseconds(Timeout)); } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA3007"), ServiceName, MachineName), Location, ex); } } /// /// Stops the service identified by and /// . /// /// instance for controlling the service identified by and . private void StopService(ServiceController serviceController) { try { if (serviceController.CanStop) { serviceController.Stop(); } else { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA3008"), ServiceName, MachineName), Location); } // wait until service is stopped or timeout expired serviceController.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromMilliseconds(Timeout)); } catch (BuildException ex) { // rethrow exception throw ex; } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA3008"), ServiceName, MachineName), Location, ex); } } /// /// Restarts the service identified by and /// . /// /// instance for controlling the service identified by and . private void RestartService(ServiceController serviceController) { // only stop service if its not already stopped if (serviceController.Status != ServiceControllerStatus.Stopped) { StopService(serviceController); } // start the service StartService(serviceController); } /// /// Pauses the service identified by and /// . /// /// instance for controlling the service identified by and . private void PauseService(ServiceController serviceController) { try { if (serviceController.Status == ServiceControllerStatus.Running) { if (serviceController.CanPauseAndContinue) { if (serviceController.Status != ServiceControllerStatus.Running) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA3010"), ServiceName, MachineName), Location); } else { serviceController.Pause(); } } else { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA3011"), ServiceName, MachineName), Location); } } else { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA3010"), ServiceName, MachineName), Location); } // wait until service is paused or timeout expired serviceController.WaitForStatus(ServiceControllerStatus.Paused, TimeSpan.FromMilliseconds(Timeout)); } catch (BuildException ex) { // rethrow exception throw ex; } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA3009"), ServiceName, MachineName), Location, ex); } } /// /// Continues the service identified by and /// . /// /// instance for controlling the service identified by and . private void ContinueService(ServiceController serviceController) { try { if (serviceController.Status == ServiceControllerStatus.Paused) { if (serviceController.CanPauseAndContinue) { if (serviceController.Status == ServiceControllerStatus.Paused) { serviceController.Continue(); } else if (serviceController.Status != ServiceControllerStatus.Running) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA3013"), ServiceName, MachineName), Location); } else { // do nothing as service is already running } } else { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA3014"), ServiceName, MachineName), Location); } } else { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA3015"), ServiceName, MachineName), Location); } // wait until service is running or timeout expired serviceController.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromMilliseconds(Timeout)); } catch (BuildException ex) { // rethrow exception throw ex; } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA3012"), ServiceName, MachineName), Location, ex); } } #endregion Private Instance Methods #region Private Instance Fields /// /// Holds the name of the service that should be controlled. /// private string _serviceName; /// /// Holds the name of the computer on which the service resides. /// private string _machineName; /// /// Holds the action that should be performed on the service. /// private ActionType _action; /// /// Holds the time, in milliseconds, the task will wait for a service /// to reach the desired status. /// private double _timeout = 5000; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.MSNet/NAnt.MSNet.csproj0000644000175000017500000001017311757302274020516 0ustar jtaylorjtaylor Debug AnyCPU 2.0 {ED13C268-36DE-49CE-B347-C2BE03F814B9} NAnt.MSNet NAnt.MSNetTasks Library OnSuccessfulBuild false 8.0.50727 v2.0 2.0 publish\ true Disk false Foreground 7 Days false false true 0 1.0.0.%2a false false true true full false 4 ..\..\build\Debug\ AllRules.ruleset TRACE;DEBUG ..\..\build\Debug\NAnt.MSNetTasks.xml true pdbonly true 4 ..\..\build\Release\ AllRules.ruleset TRACE ..\..\build\Release\NAnt.MSNetTasks.xml CommonAssemblyInfo.cs False .NET Framework 3.5 SP1 Client Profile false False .NET Framework 3.5 SP1 true False Windows Installer 3.1 true {8F5F8375-4097-4952-B860-784EB9961ABE} NAnt.Core nant-0.92-rc1/src/NDoc.Documenter.NAnt/0000755000175000017500000000000011757310030017373 5ustar jtaylorjtaylornant-0.92-rc1/src/NDoc.Documenter.NAnt/NAntDocumenter.cs0000644000175000017500000004760611757302275022641 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian MacLean (ian@maclean.ms) // Gerry Shaw (gerry_shaw@yahoo.com) // Gert Driesen (drieseng@users.sourceforge.net) // Scott Hernandez (ScottHernandez_hotmail_com) using System; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using System.Xml; using System.Xml.Xsl; using NDoc.Core; using NDoc.Core.Reflection; using NAnt.Core; using NAnt.Core.Attributes; namespace NDoc.Documenter.NAnt { /// /// NDoc Documenter for building custom NAnt User documentation. /// public class NAntDocumenter : BaseReflectionDocumenter { #region Private Instance Fields private XslTransform _xsltTaskIndex; private XslTransform _xsltTypeIndex; private XslTransform _xsltFunctionIndex; private XslTransform _xsltFilterIndex; private XslTransform _xsltTypeDoc; private XslTransform _xsltFunctionDoc; private XmlDocument _xmlDocumentation; private string _resourceDirectory; private StringDictionary _writtenFiles = new StringDictionary(); #endregion Private Instance Fields #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public NAntDocumenter() : base("NAnt") { Clear(); } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets the documenter's output directory. /// /// /// The documenter's output directory. /// public string OutputDirectory { get { return ((NAntDocumenterConfig) Config).OutputDirectory; } } /// /// Gets or sets the root namespace to document. /// /// /// The root namespace to document, or a empty /// if no restriction should be set on the namespace to document. /// public string NamespaceFilter { get { return ((NAntDocumenterConfig) Config).NamespaceFilter; } } /// /// Gets the name of the product for which documentation should be /// generated. /// /// /// The name of the product for which documentation should be /// generated. /// public string ProductName { get { return ((NAntDocumenterConfig) Config).ProductName; } } /// /// Gets the version of the product for which documentation should be /// generated. /// /// /// The version of the product for which documentation should be /// generated. /// public string ProductVersion { get { return ((NAntDocumenterConfig) Config).ProductVersion; } } /// /// Gets the URL of the website of the product for which documentation /// should be generated. /// /// /// The URL of the website of the product for which documentation should /// be generated. /// public string ProductUrl { get { return ((NAntDocumenterConfig) Config).ProductUrl; } } #endregion Public Instance Properties #region Override implementation of IDocumenter /// /// Gets the documenter's main output file. /// /// /// The documenter's main output file. /// public override string MainOutputFile { get { return ""; } } /// /// Resets the documenter to a clean state. /// public override void Clear() { Config = new NAntDocumenterConfig(); } /// /// Builds the documentation. /// public override void Build(NDoc.Core.Project project) { int buildStepProgress = 0; OnDocBuildingStep(buildStepProgress, "Initializing..."); _resourceDirectory = Path.Combine(Path.Combine(Environment.GetFolderPath( Environment.SpecialFolder.ApplicationData), "NDoc"), "NAnt"); // get assembly in which documenter is defined Assembly assembly = this.GetType().Module.Assembly; // write xslt files to resource directory EmbeddedResources.WriteEmbeddedResources(assembly, "Documenter.xslt", Path.Combine(_resourceDirectory, "xslt")); // create the html output directories try { Directory.CreateDirectory(OutputDirectory); Directory.CreateDirectory(Path.Combine(OutputDirectory, "elements")); Directory.CreateDirectory(Path.Combine(OutputDirectory, "functions")); Directory.CreateDirectory(Path.Combine(OutputDirectory, "types")); Directory.CreateDirectory(Path.Combine(OutputDirectory, "tasks")); Directory.CreateDirectory(Path.Combine(OutputDirectory, "enums")); Directory.CreateDirectory(Path.Combine(OutputDirectory, "filters")); } catch (Exception ex) { throw new DocumenterException("The output directories could not" + " be created.", ex); } buildStepProgress += 10; OnDocBuildingStep(buildStepProgress, "Merging XML documentation..."); // load the stylesheets that will convert the master xml into html pages MakeTransforms(); // will hold the file name containing the NDoc generated XML string tempFile = null; try { // determine temporary file name tempFile = Path.GetTempFileName(); // create the master XML document MakeXmlFile(project, tempFile); // create a xml document that will be transformed using xslt using (FileStream fs = new FileStream(tempFile, FileMode.Open, FileAccess.Read, FileShare.Read)) { _xmlDocumentation = new XmlDocument(); _xmlDocumentation.Load(fs); } } finally { // ensure temporary file is removed if (tempFile != null) { File.Delete(tempFile); } } // build the file mapping buildStepProgress += 15; OnDocBuildingStep(buildStepProgress, "Building mapping..."); // create arguments for nant index page transform XsltArgumentList indexArguments = CreateXsltArgumentList(); // add extension object for NAnt utilities NAntXsltUtilities indexUtilities = NAntXsltUtilities.CreateInstance( _xmlDocumentation, (NAntDocumenterConfig) Config); // add extension object to Xslt arguments indexArguments.AddExtensionObject("urn:NAntUtil", indexUtilities); buildStepProgress += 15; OnDocBuildingStep(buildStepProgress, "Creating Task Index Page..."); // transform nant task index page transform TransformAndWriteResult(_xsltTaskIndex, indexArguments, "tasks/index.html"); buildStepProgress += 10; OnDocBuildingStep(buildStepProgress, "Creating Type Index Page..."); // transform nant type index page transform TransformAndWriteResult(_xsltTypeIndex, indexArguments, "types/index.html"); buildStepProgress += 10; OnDocBuildingStep(buildStepProgress, "Creating Filter Index Page..."); // transform nant type index page transform TransformAndWriteResult(_xsltFilterIndex, indexArguments, "filters/index.html"); OnDocBuildingStep(buildStepProgress, "Creating Function Index Page..."); // transform nant function index page transform TransformAndWriteResult(_xsltFunctionIndex, indexArguments, "functions/index.html"); buildStepProgress += 10; OnDocBuildingStep(buildStepProgress, "Generating Task Documents..."); // generate a page for each marked task XmlNodeList typeNodes = _xmlDocumentation.SelectNodes("//class[starts-with(substring(@id, 3, string-length(@id) - 2), '" + NamespaceFilter + "')]"); foreach (XmlNode typeNode in typeNodes) { ElementDocType elementDocType = indexUtilities.GetElementDocType(typeNode); DocumentType(typeNode, elementDocType, indexUtilities); } OnDocBuildingStep(buildStepProgress, "Generating Function Documents..."); // generate a page for each function - TODO - change the XPath expression to select more functions XmlNodeList functionNodes = _xmlDocumentation.SelectNodes("//method[attribute/@name = 'NAnt.Core.Attributes.FunctionAttribute' and ancestor::class[starts-with(substring(@id, 3, string-length(@id) - 2), '" + NamespaceFilter + "')]]"); foreach (XmlElement function in functionNodes) { DocumentFunction(function, indexUtilities); } OnDocBuildingStep(100, "Complete"); } #endregion Override implementation of IDocumenter #region Private Instance Methods private void DocumentType(XmlNode typeNode, ElementDocType docType, NAntXsltUtilities utilities) { if (typeNode == null) { throw new ArgumentNullException("typeNode"); } if (docType == ElementDocType.None || docType == ElementDocType.FunctionSet) { // we don't need to document this type return; } string classID = typeNode.Attributes["id"].Value; if (!classID.Substring(2).StartsWith(NamespaceFilter)) { // we don't need to types in this namespace return; } string filename = utilities.GetFileNameForType(typeNode, false); if (filename == null) { // we should never get here, but just in case ... return; } if (_writtenFiles.ContainsValue(classID)) { return; } else { _writtenFiles.Add(filename, classID); } // create arguments for nant task page transform (valid args are class-id, refType, imagePath, relPathAdjust) XsltArgumentList arguments = CreateXsltArgumentList(); arguments.AddParam("class-id", String.Empty, classID); string refTypeString; switch (docType) { case ElementDocType.DataTypeElement: refTypeString = "Type"; break; case ElementDocType.Element: refTypeString = "Element"; break; case ElementDocType.Task: refTypeString = "Task"; break; case ElementDocType.Enum: refTypeString = "Enum"; break; case ElementDocType.Filter: refTypeString = "Filter"; break; default: refTypeString = "Other?"; break; } arguments.AddParam("refType", string.Empty, refTypeString); // add extension object to Xslt arguments arguments.AddExtensionObject("urn:NAntUtil", utilities); // Process all sub-elements and generate docs for them. :) // Just look for properties with attributes to narrow down the foreach loop. // (This is a restriction of NAnt.Core.Attributes.BuildElementAttribute) foreach (XmlNode propertyNode in typeNode.SelectNodes("property[attribute]")) { //get the xml element string elementName = utilities.GetElementNameForProperty(propertyNode); if (elementName != null) { // try to get attribute info if it is an array/collection. // strip the array brakets "[]" to get the type string elementType = "T:" + propertyNode.Attributes["type"].Value.Replace("[]",""); // check whether property is an element array XmlNode nestedElementNode = propertyNode.SelectSingleNode("attribute[@name='" + typeof(BuildElementArrayAttribute).FullName + "']"); if (nestedElementNode == null) { // check whether property is an element collection nestedElementNode = propertyNode.SelectSingleNode("attribute[@name='" + typeof(BuildElementCollectionAttribute).FullName + "']"); } // if property is either array or collection type element if (nestedElementNode != null) { // select the item type in the collection XmlAttribute elementTypeAttribute = _xmlDocumentation.SelectSingleNode("//class[@id='" + elementType + "']/method[@name='Add']/parameter/@type") as XmlAttribute; if (elementTypeAttribute != null) { // get type of collection elements elementType = "T:" + elementTypeAttribute.Value; } // if it contains a ElementType attribute then it is an array or collection // if it is a collection, then we care about the child type. XmlNode explicitElementType = propertyNode.SelectSingleNode("attribute/property[@ElementType]"); if (explicitElementType != null) { // ndoc is inconsistent about how classes are named. elementType = explicitElementType.Attributes["value"].Value.Replace("+","."); } } XmlNode elementTypeNode = utilities.GetTypeNodeByID(elementType); if (elementTypeNode != null) { ElementDocType elementDocType = utilities.GetElementDocType(elementTypeNode); if (elementDocType != ElementDocType.None) { DocumentType(elementTypeNode, elementDocType, utilities); } } } } // create the page TransformAndWriteResult(_xsltTypeDoc, arguments, filename); } private void DocumentFunction(XmlElement functionElement, NAntXsltUtilities utilities) { if (functionElement == null) { throw new ArgumentNullException("functionElement"); } string methodID = functionElement.GetAttribute("id"); string filename = utilities.GetFileNameForFunction(functionElement, false); XsltArgumentList arguments = CreateXsltArgumentList(); arguments.AddParam("method-id", string.Empty, methodID); arguments.AddParam("refType", string.Empty, "Function"); arguments.AddParam("functionName", string.Empty, functionElement.GetAttribute("name")); // add extension object to Xslt arguments arguments.AddExtensionObject("urn:NAntUtil", utilities); // document parameter types foreach (XmlAttribute paramTypeAttribute in functionElement.SelectNodes("parameter/@type")) { string paramType = "T:" + paramTypeAttribute.Value; XmlNode typeNode = utilities.GetTypeNodeByID(paramType); if (typeNode != null) { ElementDocType paramDocType = utilities.GetElementDocType(typeNode); if (paramDocType != ElementDocType.None) { DocumentType(typeNode, paramDocType, utilities); } } } // document return type XmlAttribute returnTypeAttribute = functionElement.Attributes["returnType"]; if (returnTypeAttribute != null) { string returnType = "T:" + returnTypeAttribute.Value; XmlNode returnTypeNode = utilities.GetTypeNodeByID(returnType); if (returnTypeNode != null) { ElementDocType returnDocType = utilities.GetElementDocType(returnTypeNode); if (returnDocType != ElementDocType.None) { DocumentType(returnTypeNode, returnDocType, utilities); } } } // create the page TransformAndWriteResult(_xsltFunctionDoc, arguments, filename); } private void MakeTransforms() { OnDocBuildingProgress(0); _xsltTaskIndex = new XslTransform(); _xsltTypeIndex = new XslTransform(); _xsltFunctionIndex = new XslTransform(); _xsltFilterIndex = new XslTransform(); _xsltTypeDoc = new XslTransform(); _xsltFunctionDoc = new XslTransform(); MakeTransform(_xsltTaskIndex, "task-index.xslt"); OnDocBuildingProgress(20); MakeTransform(_xsltTypeIndex, "type-index.xslt"); OnDocBuildingProgress(40); MakeTransform(_xsltFilterIndex, "filter-index.xslt"); OnDocBuildingProgress(50); MakeTransform(_xsltFunctionIndex, "function-index.xslt"); OnDocBuildingProgress(60); MakeTransform(_xsltTypeDoc, "type-doc.xslt"); OnDocBuildingProgress(80); MakeTransform(_xsltFunctionDoc, "function-doc.xslt"); OnDocBuildingProgress(100); } private void MakeTransform(XslTransform transform, string fileName) { transform.Load(Path.Combine(Path.Combine(_resourceDirectory, "xslt"), fileName)); } private XsltArgumentList CreateXsltArgumentList() { XsltArgumentList arguments = new XsltArgumentList(); arguments.AddParam("productName", string.Empty, ProductName); arguments.AddParam("productVersion", string.Empty, ProductVersion); arguments.AddParam("productUrl", string.Empty, ProductUrl); return arguments; } private void TransformAndWriteResult(XslTransform transform, XsltArgumentList arguments, string filename) { string path = Path.Combine(OutputDirectory, filename); using (StreamWriter writer = new StreamWriter(path, false, Encoding.UTF8)) { transform.Transform(_xmlDocumentation, arguments, writer); } } #endregion Private Instance Methods } public enum ElementDocType { None = 0, Task = 1, DataTypeElement = 2, Element = 3, Enum = 4, Filter = 5, FunctionSet = 6 } } nant-0.92-rc1/src/NDoc.Documenter.NAnt/NAntDocumenterConfig.cs0000644000175000017500000001540411757302275023756 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian MacLean (ian@maclean.ms) // Gerry Shaw (gerry_shaw@yahoo.com) // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.ComponentModel; using System.Globalization; using System.Xml; using NDoc.Core; using NDoc.Core.Reflection; namespace NDoc.Documenter.NAnt { /// /// NDoc configuration class for . /// public class NAntDocumenterConfig : BaseReflectionDocumenterConfig { #region Private Instance Fields private string _outputDirectory = @"doc/help/tasks"; private bool _sdkLinksOnWeb; private string _productName = "NAnt"; private string _productVersion = ""; private string _productUrl = ""; private string _nantBaseUri = ""; private string _namespaceFilter = ""; #endregion Private Instance Fields #region Public Instance Constructors /// /// Initializes a new instance of the /// class. /// public NAntDocumenterConfig() : base("NAnt") { // set reasonable ndoc defaults so we don't have to do this in the build file CopyrightText = String.Format(CultureInfo.InvariantCulture, "Copyright (C) 2001-{0} Gerry Shaw", DateTime.Now.Year); CopyrightHref = "http://nant.sourceforge.net/"; ShowMissingParams = false; ShowMissingRemarks = false; ShowMissingReturns = false; ShowMissingSummaries = false; ShowMissingValues = false; DocumentAttributes = true; DocumentEmptyNamespaces = false; DocumentInternals = false; DocumentPrivates = false; DocumentProtected = true; SkipNamespacesWithoutSummaries = false; EditorBrowsableFilter = EditorBrowsableFilterLevel.HideAdvanced; } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets the output directory. /// /// /// The output directory. /// [Category("Documentation Main Settings")] [Description("The path to the output directory where the generated docs will be placed.")] public string OutputDirectory { get { return _outputDirectory; } set { _outputDirectory = value; SetDirty(); } } /// /// Gets or sets a value indicating whether .NET Framework SDK links /// should point to the online MSDN library. /// [Category("Documentation Main Settings")] [Description("Turning this flag on will point all SDK links to the online MSDN library")] [DefaultValue(false)] public bool SdkLinksOnWeb { get { return _sdkLinksOnWeb; } set { _sdkLinksOnWeb= value; SetDirty(); } } /// /// Gets or sets the name of the product for which documentation /// should be generated. /// /// /// The name of the product for which documentation should be /// generated. The default is "NAnt". /// [Category("Output")] [Description("The name of the product for which documentation should be generated.")] [DefaultValue("NAnt")] public string ProductName { get { return _productName; } set { _productName = value; SetDirty(); } } /// /// Gets or sets the version of the product for which documentation /// should be generated. /// /// /// The version of the product for which documentation should be /// generated. /// [Category("Output")] [Description("The version of the product for which documentation should be generated.")] [DefaultValue("")] public string ProductVersion { get { return _productVersion; } set { _productVersion = value; SetDirty(); } } /// /// Gets or sets the URL of product website. /// /// /// The URL of the website of the product for which documentation should /// be generated. /// [Category("Output")] [Description("The URL of the website of the product for which documentation should be generated.")] [DefaultValue("")] public string ProductUrl { get { return _productUrl; } set { _productUrl = value; SetDirty(); } } /// /// Gets or sets the base URI for linking to NAnt docs. /// /// /// The base URI for linking to NAnt docs. /// [Category("Output")] [Description("The base URI for linking to NAnt docs.")] public string NAntBaseUri { get { return _nantBaseUri; } set { _nantBaseUri = value; SetDirty(); } } /// /// Gets or sets the root namespace to document. /// /// /// The root namespace to document, or a empty /// if no restriction should be set on the namespace to document. /// [Category("Output")] [Description("The root namespace to document, or an empty string to document all namespaces.")] public string NamespaceFilter { get { return _namespaceFilter; } set { _namespaceFilter = value; SetDirty(); } } #endregion Public Instance Properties } } nant-0.92-rc1/src/NDoc.Documenter.NAnt/AssemblyInfo.cs0000644000175000017500000000225411757302275022334 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Ian MaceLean (ian@maclean.ms) // Gert Driesen (drieseng@users.sourceforge.net) using System.Reflection; // This will not compile with Visual Studio. If you want to build a signed // executable use the NAnt build file. To build under Visual Studio just // exclude this file from the build. [assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile(@"..\NAnt.key")] [assembly: AssemblyKeyName("")] nant-0.92-rc1/src/NDoc.Documenter.NAnt/NAntXsltUtilities.cs0000644000175000017500000007771511757302275023366 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) // Scott Hernandez ScottHernandez_At_hOtmail.d.o.t.com using System.Collections; using System.Collections.Specialized; using System.Text; using System.Web; using System.Xml; using System.Xml.XPath; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Filters; using NDoc.Core.Reflection; namespace NDoc.Documenter.NAnt { /// /// Provides an extension object for the XSLT transformations. /// public class NAntXsltUtilities { #region Private Instance Fields private string _sdkDocBaseUrl; private string _sdkDocExt; private StringDictionary _elementNames = new StringDictionary(); private XmlDocument _doc; private NAntDocumenterConfig _config; #endregion Private Instance Fields #region Private Static Fields private const string SdkDoc10BaseUrl = "ms-help://MS.NETFrameworkSDK/cpref/html/frlrf"; private const string SdkDoc11BaseUrl = "ms-help://MS.NETFrameworkSDKv1.1/cpref/html/frlrf"; private const string SdkDocPageExt = ".htm"; private const string MsdnOnlineSdkBaseUrl = "http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrf"; private const string MsdnOnlineSdkPageExt = ".asp"; private const string SystemPrefix = "System."; private const string MicrosoftWin32Prefix = "Microsoft.Win32."; private static ArrayList Instances = new ArrayList(3); #endregion Private Static Fields #region Public Instance Constructors /// /// Initializes a new instance of the /// class. /// private NAntXsltUtilities(XmlDocument doc, NAntDocumenterConfig config) { _doc = doc; _config = config; if (config.SdkLinksOnWeb) { _sdkDocBaseUrl = MsdnOnlineSdkBaseUrl; _sdkDocExt = MsdnOnlineSdkPageExt; } else { switch (config.SdkDocVersion) { case SdkVersion.SDK_v1_0: _sdkDocBaseUrl = SdkDoc10BaseUrl; _sdkDocExt = SdkDocPageExt; break; case SdkVersion.SDK_v1_1: _sdkDocBaseUrl = SdkDoc11BaseUrl; _sdkDocExt = SdkDocPageExt; break; } } // create a list of element names by id XmlNodeList types = Document.SelectNodes("//class"); foreach (XmlElement typeNode in types) { string typeId = typeNode.Attributes["id"].Value; _elementNames[typeId] = GetElementNameForType(typeNode); XmlNodeList members = typeNode.SelectNodes("*[@id]"); foreach (XmlElement memberNode in members) { string id = memberNode.Attributes["id"].Value; switch (memberNode.Name) { case "constructor": _elementNames[id] = _elementNames[typeId]; break; case "field": _elementNames[id] = memberNode.Attributes["name"].Value; break; case "property": _elementNames[id] = GetElementNameForProperty(memberNode); break; case "method": _elementNames[id] = GetElementNameForMethod(memberNode); break; case "operator": _elementNames[id] = memberNode.Attributes["name"].Value; break; case "event": _elementNames[id] = memberNode.Attributes["name"].Value; break; } } } } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets the base url for links to system types. /// /// /// The base url for links to system types. /// public string SdkDocBaseUrl { get { return _sdkDocBaseUrl; } } /// /// Gets the page file extension for links to system types. /// public string SdkDocExt { get { return _sdkDocExt; } } #endregion Public Instance Properties #region Private Instance Properties private XmlDocument Document { get { return _doc; } } private NAntDocumenterConfig Config { get { return _config; } } #endregion Private Instance Properties #region Public Instance Methods /// /// Gets the root namespace to document. /// /// /// The root namespace to document, or a empty /// if no restriction should be set on the namespace to document. /// public string GetNamespaceFilter() { return Config.NamespaceFilter; } /// /// Searches the document for the <class> node with the /// given id. /// /// Type.FullName of class to return /// /// The <class> node with the given id, or /// if the node does not exist. /// public XPathNodeIterator GetClassNode(string id) { if (!id.StartsWith("T:")) { id = "T:" + id; } XmlNode typeNode = Document.SelectSingleNode("//class[@id='" + id + "']"); if (typeNode == null) { return null; } return typeNode.CreateNavigator().Select("."); } /// /// Returns an href for a cref. /// /// The cref for which the href will be looked up. /// /// The href for the specified cref. /// public string GetHRef(string cref) { if ((cref.Length < 2) || (cref[1] != ':')) { return string.Empty; } // get the underlying type of the array if (cref.EndsWith("[]")){ cref=cref.Replace("[]",""); } // check if the ref is for a system namespaced element or not if (cref.Length < 9 || (!cref.Substring(2).StartsWith(SystemPrefix) && !cref.Substring(2).StartsWith(MicrosoftWin32Prefix))) { // not a system one. // will hold the filename to link to string fileName = null; switch (cref.Substring(0, 2)) { case "T:": fileName = GetFileNameForType(cref, true); break; case "M:": fileName = GetFileNameForFunction(cref, true); break; } if (fileName == null) { return string.Empty; } else { if (cref.Substring(2).StartsWith("NAnt.") && !cref.Substring(2).StartsWith("NAnt.Contrib")) { return Config.NAntBaseUri + fileName; } else { return "../" + fileName; } } } else { // a system cref switch (cref.Substring(0, 2)) { case "N:": // Namespace return SdkDocBaseUrl + cref.Substring(2).Replace(".", "") + SdkDocExt; case "T:": // Type: class, interface, struct, enum, delegate return SdkDocBaseUrl + cref.Substring(2).Replace(".", "") + "ClassTopic" + SdkDocExt; case "F:": // Field // do not generate href for fields, as the .NET SDK does // not have separate pages for enum fields, and we have no // way of knowing whether it's a reference to an enum field // or class field. return string.Empty; case "P:": // Property case "M:": // Method case "E:": // Event return this.GetFilenameForSystemMember(cref); default: return string.Empty; } } } /// /// Returns the name for a given cref. /// /// The cref for which the name will be looked up. /// /// The name for the specified cref. /// public string GetName(string cref) { if (cref.Length < 2) { return cref; } if (cref[1] == ':') { if (cref.Length < 9 || (!cref.Substring(2).StartsWith(SystemPrefix) && !cref.Substring(2).StartsWith(MicrosoftWin32Prefix))) { //what name should be found? string name = _elementNames[cref]; if (name != null) { return name; } } int index; if ((index = cref.IndexOf(".#c")) >= 0) { cref = cref.Substring(2, index - 2); } else if ((index = cref.IndexOf("(")) >= 0) { cref = cref.Substring(2, index - 2); } else { cref = cref.Substring(2); } } return cref.Substring(cref.LastIndexOf(".") + 1); } /// /// Returns the NAnt task name for a given cref. /// /// The cref for the task name will be looked up. /// /// The NAnt task name for the specified cref. /// public string GetTaskName(string cref) { return GetTaskNameForType(GetTypeNodeByID(cref)); } /// /// Returns the NAnt element name for a given cref. /// /// The cref for the element name will be looked up. /// /// The NAnt element name for the specified cref. /// public string GetElementName(string cref) { return GetElementNameForType(GetTypeNodeByID(cref)); } public XmlNode GetTypeNodeByID(string cref) { if (cref[1] == ':' && !cref.StartsWith("T:")) { return null; } if (!cref.StartsWith("T:")) { cref = "T:" + cref; } XmlNode typeNode = Document.SelectSingleNode("//class[@id='" + cref + "']"); if (typeNode == null) { typeNode = Document.SelectSingleNode("//enumeration[@id='" + cref + "']"); } return typeNode; } public XmlNode GetMethodNodeByID(string cref) { if (cref[1] == ':' && !cref.StartsWith("M:")) { return null; } if (!cref.StartsWith("M:")) { cref = "M:" + cref; } return Document.SelectSingleNode("//method[@id='" + cref + "']"); } /// /// Determines the of the given type node. /// /// The type node for which to determine the . /// /// The of the given type node. /// public ElementDocType GetElementDocType(XmlNode typeNode) { if (typeNode == null) { return ElementDocType.None; } // check if type is an enum if (typeNode.LocalName == "enumeration") { return ElementDocType.Enum; } // check if type is a task if (GetTaskNameForType(typeNode) != null) { return ElementDocType.Task; } // check if type is a datatype if (typeNode.SelectSingleNode("descendant::base[@id='T:" + typeof(DataTypeBase).FullName + "']") != null) { if (typeNode.SelectSingleNode("attribute[@name='" + typeof(ElementNameAttribute).FullName + "']") != null) { return ElementDocType.DataTypeElement; } else { return ElementDocType.Element; } } // check if type is a filter if (typeNode.SelectSingleNode("descendant::base[@id='T:" + typeof(Filter).FullName + "']") != null) { if (typeNode.SelectSingleNode("attribute[@name='" + typeof(ElementNameAttribute).FullName + "']") != null) { return ElementDocType.Filter; } else { return ElementDocType.Element; } } // check if type is an element if (typeNode.SelectSingleNode("descendant::base[@id='T:" + typeof(Element).FullName + "']") != null) { return ElementDocType.Element; } // check if type is a functionset if (typeNode.SelectSingleNode("attribute[@name='" + typeof(FunctionSetAttribute).FullName + "']/property[@name='Prefix']/@value") != null) { return ElementDocType.FunctionSet; } return ElementDocType.None; } /// /// Determines the of the type to which /// the given cref points. /// /// The cref for which to determine the . /// /// The of the type to which the given /// cref points. /// public ElementDocType GetElementDocTypeByID(string cref) { return GetElementDocType(GetTypeNodeByID(cref)); } /// /// Determines whether the given cref points to a datatype. /// /// The cref to check. /// /// if the given cref points to a datatype; /// otherwise, . /// public bool IsDataType(string cref) { return GetElementDocTypeByID(cref) == ElementDocType.DataTypeElement; } /// /// Determines whether the given cref points to an element. /// /// The cref to check. /// /// if the given cref points to an element; /// otherwise, . /// /// /// When the cref points to a or /// this method returns . /// public bool IsElement(string cref) { return GetElementDocTypeByID(cref) == ElementDocType.Element; } /// /// Determines whether the given cref points to a datatype. /// /// The cref to check. /// /// if the given cref points to a datatype; /// otherwise, . /// public bool IsFilter(string cref) { return GetElementDocTypeByID(cref) == ElementDocType.Filter; } /// /// Determines whether the given cref points to a task. /// /// The cref to check. /// /// if the given cref points to a task; /// otherwise, . /// public bool IsTask(string cref) { return GetElementDocTypeByID(cref) == ElementDocType.Task; } /// /// Determines whether the given cref points to a functionset. /// /// The cref to check. /// /// if the given cref points to a functionset; /// otherwise, . /// public bool IsFunctionSet(string cref) { return GetElementDocTypeByID(cref) == ElementDocType.FunctionSet; } /// /// Encodes a URL string using for reliable /// HTTP transmission from the Web server to a client. /// /// The text to encode. /// /// The encoded string. /// public string UrlEncode(string value) { return HttpUtility.UrlEncode(value, Encoding.UTF8); } #endregion Public Instance Methods #region Internal Instance Methods /// /// Gets the BuildElementAttribute name for the "class/property" XmlNode /// /// The XmlNode to look for a name. /// The BuildElementAttrbute.Name if the attribute exists for the node. internal string GetElementNameForProperty(XmlNode propertyNode) { // check whether property is a task attribute XmlAttribute taskAttributeNode = propertyNode.SelectSingleNode("attribute[@name='" + typeof(TaskAttributeAttribute).FullName + "']/property[@name='Name']/@value") as XmlAttribute; if (taskAttributeNode != null) { return taskAttributeNode.Value; } // check whether property is a element array XmlAttribute elementArrayNode = propertyNode.SelectSingleNode("attribute[@name='" + typeof(BuildElementArrayAttribute).FullName + "']/property[@name='Name']/@value") as XmlAttribute; if (elementArrayNode != null) { return elementArrayNode.Value; } // check whether property is a element collection XmlAttribute elementCollectionNode = propertyNode.SelectSingleNode("attribute[@name='" + typeof(BuildElementCollectionAttribute).FullName + "']/property[@name='Name']/@value") as XmlAttribute; if (elementCollectionNode != null) { return elementCollectionNode.Value; } // check whether property is an xml element XmlAttribute buildElementNode = propertyNode.SelectSingleNode("attribute[@name='" + typeof(BuildElementAttribute).FullName + "']/property[@name='Name']/@value") as XmlAttribute; if (buildElementNode != null) { return buildElementNode.Value; } // check whether property is a Framework configurable attribute XmlAttribute frameworkConfigAttributeNode = propertyNode.SelectSingleNode("attribute[@name='" + typeof(FrameworkConfigurableAttribute).FullName + "']/property[@name='Name']/@value") as XmlAttribute; if (frameworkConfigAttributeNode != null) { return frameworkConfigAttributeNode.Value; } return null; } /// /// Returns the filename to use for the given function XmlElement /// /// The "method" element to find the filename for. /// Specified whether to URLencode the filename. internal string GetFileNameForFunction(XmlNode functionNode, bool urlEncode) { StringBuilder sb = new StringBuilder(); XmlNode n = functionNode.SelectSingleNode("../attribute[@name='NAnt.Core.Attributes.FunctionSetAttribute']/property[@name='Prefix']/@value"); if (n != null && n.InnerText != "") { sb.Append(n.InnerText); sb.Append('.'); } n = functionNode.SelectSingleNode("attribute[@name='NAnt.Core.Attributes.FunctionAttribute']/property[@name='Name']/@value"); if (n != null && n.InnerText != "") { sb.Append(n.InnerText); } else { sb.Append(functionNode.Attributes["name"].Value); } sb.Append('('); XmlNodeList parameters = functionNode.SelectNodes("parameter"); for (int i = 0; i < parameters.Count; i++) { if (i > 0) sb.Append(','); XmlElement param = (XmlElement) parameters[i]; sb.Append(param.GetAttribute("type")); } sb.Append(')'); string file = sb.ToString (); return string.Concat("functions/", (urlEncode ? UrlEncode (file) : file), ".html"); } /// /// Returns the filename to use for the given class XmlNode /// /// The "Class" element to find the filename for. /// /// The relative path and filename where this type is stored in the /// documentation. /// /// /// For a type that is neither a task, enum, global type, filter or /// functionset, the returned filename will point to the SDK docs for /// that type. /// internal string GetFileNameForType(XmlNode typeNode, bool urlEncode) { if (typeNode == null) { return null; } string partialURL = null; // if type is task use name set using TaskNameAttribute string taskName = GetTaskNameForType(typeNode); if (taskName != null) { return "tasks/" + (urlEncode ? UrlEncode(taskName) : taskName) + ".html"; } // check if type is an enum if (typeNode.LocalName == "enumeration") { string enumFile = typeNode.Attributes["id"].Value.Substring(2); return "enums/" + (urlEncode ? UrlEncode(enumFile) : enumFile) + ".html"; } // check if type derives from NAnt.Core.DataTypeBase if (typeNode.SelectSingleNode("descendant::base[@id='T:" + typeof(DataTypeBase).FullName + "']") != null) { // make sure the type has a ElementName assigned to it XmlAttribute elementNameAttribute = typeNode.SelectSingleNode("attribute[@name='" + typeof(ElementNameAttribute).FullName + "']/property[@name='Name']/@value") as XmlAttribute; if (elementNameAttribute != null) { string dtFile = elementNameAttribute.Value; return "types/" + (urlEncode ? UrlEncode(dtFile) : dtFile) + ".html"; } } // check if type derives from NAnt.Core.Filters.Filter if (typeNode.SelectSingleNode("descendant::base[@id='T:" + typeof(Filter).FullName + "']") != null) { // make sure the type has a ElementName assigned to it XmlAttribute elementNameAttribute = typeNode.SelectSingleNode("attribute[@name='" + typeof(ElementNameAttribute).FullName + "']/property[@name='Name']/@value") as XmlAttribute; if (elementNameAttribute != null) { string filterFile = elementNameAttribute.Value; return "filters/" + (urlEncode ? UrlEncode(filterFile) : filterFile) + ".html"; } } // check if type is a functionset partialURL = GetHRefForFunctionSet(typeNode); if (partialURL != null) { return partialURL; } // check if type derives from NAnt.Core.Element if (typeNode.SelectSingleNode("descendant::base[@id='T:" + typeof(Element).FullName + "']") != null) { string elementFile = typeNode.Attributes["id"].Value.Substring(2); return "elements/" + (urlEncode ? UrlEncode(elementFile) : elementFile) + ".html"; } string sdkFile = typeNode.Attributes["id"].Value.Substring(2); return "../sdk/" + (urlEncode ? UrlEncode(sdkFile) : sdkFile) + ".html"; } #endregion Internal Instance Methods #region Private Instance Methods private string GetElementNameForType(XmlNode typeNode) { if (typeNode == null) { return string.Empty; } // if type is task use name set using TaskNameAttribute string taskName = GetTaskNameForType(typeNode); if (taskName != null) { return "<" + taskName + ">"; } // make sure the type has a ElementNameAttribute assigned to it XmlAttribute elementNameAttribute = typeNode.SelectSingleNode("attribute[@name='" + typeof(ElementNameAttribute).FullName + "']/property[@name='Name']/@value") as XmlAttribute; if (elementNameAttribute != null) { // check if we're dealing with a data type if (typeNode.SelectSingleNode("descendant::base[@id='T:" + typeof(DataTypeBase).FullName + "']")!= null) { return "<" + elementNameAttribute.Value + ">"; } // check if we're dealing with a filter if (typeNode.SelectSingleNode("descendant::base[@id='T:" + typeof(Filter).FullName + "']")!= null) { return "<" + elementNameAttribute.Value + ">"; } } // if we're dealing with a FunctionSet, use category as name instead // of prefix XmlAttribute categoryNameAttribute = typeNode.SelectSingleNode("attribute[@name='" + typeof(FunctionSetAttribute).FullName + "']/property[@name='Category']/@value") as XmlAttribute; if (categoryNameAttribute != null) { return categoryNameAttribute.Value; } return null; } private string GetFileNameForFunction(string type, bool urlEncode) { XmlNode functionNode = GetMethodNodeByID(type); if (functionNode != null) { return GetFileNameForFunction(functionNode, true); } return null; } private string GetFileNameForType(string type, bool urlEncode) { return GetFileNameForType(GetTypeNodeByID(type), urlEncode); } private string GetFilenameForSystemMember(string cref) { string crefName; int index; if ((index = cref.IndexOf(".#c")) >= 0) { crefName = cref.Substring(2, index - 2) + ".ctor"; } else if ((index = cref.IndexOf("(")) >= 0) { crefName = cref.Substring(2, index - 2); } else { crefName = cref.Substring(2); } index = crefName.LastIndexOf("."); string crefType = crefName.Substring(0, index); string crefMember = crefName.Substring(index + 1); return SdkDocBaseUrl + crefType.Replace(".", "") + "Class" + crefMember + "Topic" + SdkDocExt; } /// /// Gets the TaskNameAttrbute name for the "class" XmlNode /// /// The XmlNode to look for a name. /// The if the attribute exists for the node. /// /// The class is also checked to make sure it is derived from /// private string GetTaskNameForType(XmlNode typeNode) { if (typeNode == null) { return null; } // make sure the type actually derives from NAnt.Core.Task if (typeNode.SelectSingleNode("descendant::base[@id='T:" + typeof(Task).FullName + "']") != null) { // make sure the type has a TaskNameAttribute assigned to it XmlAttribute taskNameAttribute = typeNode.SelectSingleNode("attribute[@name='" + typeof(TaskNameAttribute).FullName + "']/property[@name='Name']/@value") as XmlAttribute; if (taskNameAttribute != null) { return taskNameAttribute.Value; } } return null; } /// /// Gets the function name for methods that represent a NAtn function. /// /// The XmlNode to look for a name. /// /// The function name if represent a /// NAnt function. /// private string GetElementNameForMethod(XmlNode methodNode) { XmlNode functionNameAttribute = methodNode.SelectSingleNode("attribute[@name='" + typeof(FunctionAttribute).FullName + "']/property[@name='Name']/@value"); if (functionNameAttribute == null) { return methodNode.Attributes["name"].Value; } XmlNode prefixAttribute = methodNode.SelectSingleNode("../attribute[@name='" + typeof(FunctionSetAttribute).FullName + "']/property[@name='Prefix']/@value"); if (prefixAttribute == null) { return methodNode.Attributes["name"].Value; } return prefixAttribute.InnerText + "::" + functionNameAttribute.InnerText + "()"; } /// /// Returns a partial URL to link to the functionset in the function index. /// /// The "Class" element to find the filename for. private string GetHRefForFunctionSet(XmlNode functionNode) { XmlAttribute categoryValueAttribute = functionNode.SelectSingleNode("attribute[@name='NAnt.Core.Attributes.FunctionSetAttribute']/property[@name='Category']/@value") as XmlAttribute; if (categoryValueAttribute != null && categoryValueAttribute.Value != "") { return "functions/index.html#" + UrlEncode(categoryValueAttribute.Value); } return null; } #endregion Private Instance Methods #region Internal Static Methods internal static NAntXsltUtilities CreateInstance(XmlDocument doc, NAntDocumenterConfig config){ // just in case... but we should never see this happen. lock (Instances) { foreach (NAntXsltUtilities util in Instances) { if (util.Document == doc && util.Config.SdkDocVersion.Equals(config.SdkDocVersion) && util.Config.SdkLinksOnWeb == config.SdkLinksOnWeb) { return util; } } NAntXsltUtilities inst = new NAntXsltUtilities(doc, config); Instances.Add(inst); return inst; } } #endregion Internal Static Methods } } nant-0.92-rc1/src/NDoc.Documenter.NAnt/Resources/0000755000175000017500000000000011757310030021345 5ustar jtaylorjtaylornant-0.92-rc1/src/NDoc.Documenter.NAnt/Resources/filter-index.xslt0000644000175000017500000001346011757302275024673 0ustar jtaylorjtaylor Filter Reference

Filter Reference

Filter Summary
.html .html
nant-0.92-rc1/src/NDoc.Documenter.NAnt/Resources/function-index.xslt0000644000175000017500000002450511757302275025235 0ustar jtaylorjtaylor Function Reference

Function Reference

# Functions

Functions

Name Summary
:: ::
nant-0.92-rc1/src/NDoc.Documenter.NAnt/Resources/function-doc.xslt0000644000175000017500000001774111757302275024677 0ustar jtaylorjtaylor Function Documenting :: <xsl:value-of select="$name" /> Function

(Deprecated)

Usage

(, )

Parameters

Name Type Description

Return Value

Remarks

Examples

Requirements

Assembly: ()

Exceptions

The function will fail in any of the following circumstances:
  •  
nant-0.92-rc1/src/NDoc.Documenter.NAnt/Resources/tags.xslt0000644000175000017500000003701011757302275023234 0ustar jtaylorjtaylor A normal paragraph. This ends up being a p tag. (Did we really need the extra three letters?)

Use the lang attribute to indicate that the text of the paragraph is only appropriate for a specific language.

[ ]  

Multiple lines of code.
            
        
Use the lang attribute to indicate that the code sample is only appropriate for a specific language.
            
                [
                
                    
                
                ]
            
            
        
See XmlDocument.Load for an example of a note.

CAUTION: Notes to Inheritors: Notes to Implementers: Note:

  • -
  • -
    task functions a null reference ( Nothing in Visual Basic) sealed ( NotInheritable in Visual Basic) static ( Shared in Visual Basic) abstract ( MustInherit in Visual Basic) virtual ( CanOverride in Visual Basic)
    nant-0.92-rc1/src/NDoc.Documenter.NAnt/Resources/nant-attributes.xslt0000644000175000017500000003377111757302275025434 0ustar jtaylorjtaylor Element Element Array Collection NestedElementArray=

    <> <>

    </> </>

    <>

    <>
    </>
    </>

    </>

    <> <>

    </> </>

    top required

    This attribute's properties will not be automatically expanded!

    nant-0.92-rc1/src/NDoc.Documenter.NAnt/Resources/type-index.xslt0000644000175000017500000001343411757302275024370 0ustar jtaylorjtaylor Data Type Reference

    Type Reference

    Type Summary
    .html .html
    nant-0.92-rc1/src/NDoc.Documenter.NAnt/Resources/common.xslt0000644000175000017500000001754411757302275023600 0ustar jtaylorjtaylor byte byte sbyte sbyte short short ushort ushort int int uint uint long long ulong ulong float float double double decimal decimal string string char char bool bool void void object object file directory datetime timespan
  • See Also

    Functions |

    [This is preliminary documentation and subject to change.]

    nant-0.92-rc1/src/NDoc.Documenter.NAnt/Resources/task-index.xslt0000644000175000017500000001457411757302275024357 0ustar jtaylorjtaylor Task Reference

    Task Reference

    Task Summary
    .html .html
    nant-0.92-rc1/src/NDoc.Documenter.NAnt/Resources/type-doc.xslt0000644000175000017500000004042511757302275024026 0ustar jtaylorjtaylor T:NAnt.Core.Types.FileSet Type Documenting <> ../tasks/index.html ../types/index.html ../filters/index.html <xsl:value-of select="$name" /><xsl:text> </xsl:text><xsl:value-of select="$refType" />

    Requirements

    Assembly: ()

    (Deprecated)

    Parameters

    Attribute Type Description Required

    Framework-configurable parameters

    Attribute Type Description Required

    Nested Elements:

    Examples

    Deprecated. Deprecated. Deprecated. Deprecated. ../index.html <xsl:value-of select="$name" /> enum

    Requirements

    Assembly: ()

    (Deprecated)

    Fields

    Field Description
    Deprecated. top
    nant-0.92-rc1/src/NDoc.Documenter.NAnt/NDoc.Documenter.NAnt.build0000644000175000017500000000336311757302275024223 0ustar jtaylorjtaylor nant-0.92-rc1/src/NDoc.Documenter.NAnt/NDoc.Documenter.NAnt.csproj0000644000175000017500000001126011757302275024417 0ustar jtaylorjtaylor Debug AnyCPU 2.0 {841FAEBA-4527-410A-B765-E2EDA47ABDCE} NDoc.Documenter.NAnt NDoc.Documenter.NAnt Library OnSuccessfulBuild false 8.0.50727 v2.0 2.0 publish\ true Disk false Foreground 7 Days false false true 0 1.0.0.%2a false false true true full false 4 ..\..\build\Debug\ AllRules.ruleset TRACE;DEBUG ..\..\build\Debug\NDoc.Documenter.NAnt.xml true pdbonly true ..\..\build\Release\ 4 AllRules.ruleset TRACE ..\..\build\Release\NDoc.Documenter.NAnt.xml ..\..\lib\common\neutral\NDoc.Core.dll CommonAssemblyInfo.cs False .NET Framework 3.5 SP1 Client Profile false False .NET Framework 3.5 SP1 true False Windows Installer 3.1 true {8F5F8375-4097-4952-B860-784EB9961ABE} NAnt.Core nant-0.92-rc1/src/NAnt.VSNet/0000755000175000017500000000000011757310030015443 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.VSNet/VcProject.cs0000644000175000017500000025345611757302274017723 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Dmitry Jemerov // Scott Ford (sford@RJKTECH.com) // Gert Driesen (drieseng@users.sourceforge.net) // Hani Atassi (haniatassi@users.sourceforge.net) using System; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Text; using System.Xml; using NAnt.Core; using NAnt.Core.Tasks; using NAnt.Core.Types; using NAnt.Core.Util; using NAnt.VisualCpp.Tasks; using NAnt.VisualCpp.Types; using NAnt.VSNet.Tasks; using NAnt.VSNet.Types; namespace NAnt.VSNet { /// /// Visual C++ project. /// public class VcProject: ProjectBase { #region Public Instance Constructors public VcProject(SolutionBase solution, string projectPath, XmlElement xmlDefinition, SolutionTask solutionTask, TempFileCollection tfc, GacCache gacCache, ReferencesResolver refResolver, DirectoryInfo outputDir) : base(xmlDefinition, solutionTask, tfc, gacCache, refResolver, outputDir) { if (projectPath == null) { throw new ArgumentNullException("projectPath"); } _references = new ArrayList(); _clArgMap = VcArgumentMap.CreateCLArgumentMap(); _linkerArgMap = VcArgumentMap.CreateLinkerArgumentMap(); _midlArgMap = VcArgumentMap.CreateMidlArgumentMap(); _projectPath = FileUtils.GetFullPath(projectPath); _name = xmlDefinition.GetAttribute("Name"); _guid = xmlDefinition.GetAttribute("ProjectGUID"); XmlNodeList configurationNodes = xmlDefinition.SelectNodes("//Configurations/Configuration"); foreach (XmlElement configElem in configurationNodes) { VcProjectConfiguration config = new VcProjectConfiguration(configElem, this, OutputDir); ProjectConfigurations[new Configuration (config.Name, config.PlatformName)] = config; } XmlNodeList references = xmlDefinition.SelectNodes("//References/child::*"); foreach (XmlElement referenceElem in references) { ReferenceBase reference = CreateReference(solution, referenceElem); _references.Add(reference); } XmlNodeList fileNodes = xmlDefinition.SelectNodes("//File"); _projectFiles = new ArrayList(fileNodes.Count); foreach (XmlElement fileElem in fileNodes) { string parentName = Name; // determine name of parent if (fileElem.ParentNode != null && fileElem.ParentNode.Name == "Filter") { XmlNode filterName = fileElem.ParentNode.Attributes.GetNamedItem("Name"); if (filterName != null) { parentName = filterName.Value; } } string relPath = fileElem.GetAttribute("RelativePath"); Hashtable htFileConfigurations = null; XmlNodeList fileConfigList = fileElem.GetElementsByTagName("FileConfiguration"); if (fileConfigList.Count > 0) { htFileConfigurations = CollectionsUtil.CreateCaseInsensitiveHashtable(fileConfigList.Count); foreach (XmlElement fileConfigElem in fileConfigList) { Configuration fileConfig = Configuration.Parse ( fileConfigElem.GetAttribute("Name")); VcProjectConfiguration projectConfig = (VcProjectConfiguration) ProjectConfigurations[fileConfig]; htFileConfigurations[projectConfig.Name] = new VcFileConfiguration( relPath, parentName, fileConfigElem, projectConfig, outputDir); } } // TODO: refactor this together with the Build methods // we'll always create a file configuration for IDL and res // files as macro's in the configuration properties for these // files will always need to be expanded on the file level string ext = Path.GetExtension(relPath).ToLower(CultureInfo.InvariantCulture); switch (ext) { case ".idl": case ".odl": case ".rc": // ensure there's a file configuration for each project // configuration foreach (VcProjectConfiguration projectConfig in ProjectConfigurations.Values) { // if file configuration for project config existed // in project file, then skip this project config if (htFileConfigurations != null && htFileConfigurations.ContainsKey(projectConfig.Name)) { continue; } // lazy initialize hashtable if (htFileConfigurations == null) { htFileConfigurations = CollectionsUtil.CreateCaseInsensitiveHashtable(); } // create the file configuration htFileConfigurations[projectConfig.Name] = new VcFileConfiguration(relPath, parentName, projectConfig, outputDir); } break; } if (htFileConfigurations != null) { _projectFiles.Add(htFileConfigurations); } else { _projectFiles.Add(relPath); } } } #endregion Public Instance Constructors #region Override implementation of ProjectBase /// /// Gets the name of the Visual C++ project. /// public override string Name { get { return _name; } } /// /// Gets the type of the project. /// /// /// The type of the project. /// public override ProjectType Type { get { return ProjectType.VisualC; } } /// /// Gets the path of the Visual C++ project. /// public override string ProjectPath { get { return _projectPath; } } /// /// Gets the directory containing the VS.NET project. /// public override DirectoryInfo ProjectDirectory { get { return new DirectoryInfo(Path.GetDirectoryName(_projectPath)); } } /// /// Get the location of the project. /// /// /// . /// /// /// For now, we only support local Visual C++ projects. /// public override ProjectLocation ProjectLocation { get { return ProjectLocation.Local; } } /// /// Get the directory in which intermediate build output that is not /// specific to the build configuration will be stored. /// /// /// This is a directory relative to the project directory, /// named temp\. /// public override DirectoryInfo ObjectDir { get { return new DirectoryInfo( FileUtils.CombinePaths(ProjectDirectory.FullName, "temp")); } } /// /// Gets or sets the unique identifier of the Visual C++ project. /// public override string Guid { get { return _guid; } set { _guid = value; } } public override ArrayList References { get { return _references; } } public override ProjectReferenceBase CreateProjectReference(ProjectBase project, bool isPrivateSpecified, bool isPrivate) { return new VcProjectReference(project, this, isPrivateSpecified, isPrivate); } /// /// Gets a value indicating whether building the project for the specified /// build configuration results in managed output. /// /// The solution configuration that is built. /// /// if the project output for the specified build /// configuration is either a Dynamic Library (dll) or an Application /// (exe), and Managed Extensions are enabled; otherwise, /// . /// public override bool IsManaged(Configuration solutionConfiguration) { VcProjectConfiguration projectConfig = (VcProjectConfiguration) BuildConfigurations[solutionConfiguration]; return (projectConfig.Type == VcProjectConfiguration.ConfigurationType.DynamicLibrary || projectConfig.Type == VcProjectConfiguration.ConfigurationType.Application) && projectConfig.ManagedExtensions; } /// /// Verifies whether the specified XML fragment represents a valid project /// that is supported by this . /// /// XML fragment representing the project file. /// /// The XML fragment is not supported by this . /// -or- /// The XML fragment does not represent a valid project (for this ). /// protected override void VerifyProjectXml(XmlElement docElement) { if (!IsSupported(docElement)) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Project '{0}' is not a valid Visual C++ project.", ProjectPath), Location.UnknownLocation); } } /// /// Returns the Visual Studio product version of the specified project /// XML fragment. /// /// The document element of the project. /// /// The Visual Studio product version of the specified project XML /// fragment. /// /// /// The product version could not be determined. /// -or- /// The product version is not supported. /// protected override ProductVersion DetermineProductVersion(XmlElement docElement) { return GetProductVersion(docElement); } protected override BuildResult Build(Configuration solutionConfiguration) { // prepare the project for build Prepare(solutionConfiguration); // obtain project configuration (corresponding with solution configuration) VcProjectConfiguration projectConfig = (VcProjectConfiguration) BuildConfigurations[solutionConfiguration]; // perform pre-build actions if (!PreBuild(projectConfig)) { return BuildResult.Failed; } string nmakeCommand = projectConfig.GetToolSetting(VcConfigurationBase.NMakeTool, "BuildCommandLine"); if (!String.IsNullOrEmpty(nmakeCommand)) { RunNMake(nmakeCommand); return BuildResult.Success; } VcConfigurationBase stdafxConfig = null; // build idl files before everything else foreach (VcConfigurationBase idlConfig in projectConfig.IdlConfigs.Keys) { BuildIDLFiles((ArrayList) projectConfig.IdlConfigs[idlConfig], projectConfig, idlConfig); } // If VC project uses precompiled headers then the precompiled header // output (.pch file) must be generated before compiling any other // source files. foreach (VcConfigurationBase vcConfig in projectConfig.SourceConfigs.Keys) { if (vcConfig.UsePrecompiledHeader == UsePrecompiledHeader.Create) { BuildCPPFiles((ArrayList) projectConfig.SourceConfigs[vcConfig], solutionConfiguration, vcConfig); stdafxConfig = vcConfig; } } foreach (VcConfigurationBase vcConfig in projectConfig.SourceConfigs.Keys) { if (vcConfig != stdafxConfig) { BuildCPPFiles((ArrayList) projectConfig.SourceConfigs[vcConfig], solutionConfiguration, vcConfig); } } // build resource files foreach (VcConfigurationBase rcConfig in projectConfig.RcConfigs.Keys) { BuildResourceFiles((ArrayList) projectConfig.RcConfigs[rcConfig], projectConfig, rcConfig); } switch (projectConfig.Type) { case VcProjectConfiguration.ConfigurationType.StaticLibrary: RunLibrarian(projectConfig); break; case VcProjectConfiguration.ConfigurationType.Application: case VcProjectConfiguration.ConfigurationType.DynamicLibrary: // perform pre-link actions if (!PreLink(projectConfig)) { return BuildResult.Failed; } RunLinker(solutionConfiguration); break; } Log(Level.Verbose, "Copying references:"); foreach (ReferenceBase reference in _references) { if (reference.CopyLocal) { Log(Level.Verbose, " - " + reference.Name); Hashtable outputFiles = CollectionsUtil.CreateCaseInsensitiveHashtable(); reference.GetOutputFiles(solutionConfiguration, outputFiles); foreach (DictionaryEntry de in outputFiles) { // determine file to copy FileInfo srcFile = new FileInfo((string) de.Key); // determine destination file FileInfo destFile = new FileInfo(FileUtils.CombinePaths( projectConfig.OutputDir.FullName, (string) de.Value)); // perform actual copy CopyFile(srcFile, destFile, SolutionTask); } } } // run custom build steps if (!RunCustomBuildStep(solutionConfiguration, projectConfig)) { return BuildResult.Failed; } // perform post-build actions if (!PostBuild(projectConfig)) { return BuildResult.Failed; } return BuildResult.Success; } #endregion Override implementation of ProjectBase #region Internal Instance Properties internal ArrayList ProjectFiles { get { return _projectFiles; } } #endregion Internal Instance Properties #region Protected Internal Instance Methods /// /// Expands the given macro. /// /// The macro to expand. /// /// The expanded macro or if the macro is not /// supported. /// protected internal override string ExpandMacro(string macro) { // perform case-insensitive expansion of macros switch (macro.ToLower(CultureInfo.InvariantCulture)) { case "inputdir": return Path.GetDirectoryName(ProjectPath) + Path.DirectorySeparatorChar; case "inputname": return Path.GetFileNameWithoutExtension(ProjectPath); case "inputpath": return ProjectPath; case "inputfilename": // E.g. Inc.vcproj return Path.GetFileName(ProjectPath); case "inputext": // E.g. .vcproj return Path.GetExtension(ProjectPath); case "safeparentname": return Name; case "safeinputname": return Path.GetFileNameWithoutExtension(ProjectPath); default: return base.ExpandMacro(macro); } } #endregion Protected Internal Instance Methods #region Internal Instance Methods internal string GetObjOutputFile(string fileName, VcConfigurationBase fileConfig, string intermediateDir) { string objectFile = GetObjectFile(fileConfig); if (objectFile == null) { objectFile = intermediateDir; } return ClTask.GetObjOutputFile(fileName, objectFile); } internal string GetResourceOutputFile(string fileName, VcConfigurationBase fileConfig) { return FileUtils.CombinePaths(ProjectDirectory.FullName, fileConfig.GetToolSetting(VcConfigurationBase.ResourceCompilerTool, "ResourceOutputFileName", "$(IntDir)/$(InputName).res")); } #endregion Internal Instance Methods #region Protected Instance Methods protected virtual ReferenceBase CreateReference(SolutionBase solution, XmlElement xmlDefinition) { if (solution == null) { throw new ArgumentNullException("solution"); } if (xmlDefinition == null) { throw new ArgumentNullException("xmlDefinition"); } switch (xmlDefinition.Name) { case "ProjectReference": // project reference return new VcProjectReference(xmlDefinition, ReferencesResolver, this, solution, solution.TemporaryFiles, GacCache, OutputDir); case "AssemblyReference": // assembly reference return new VcAssemblyReference(xmlDefinition, ReferencesResolver, this, GacCache); case "ActiveXReference": // ActiveX reference return new VcWrapperReference(xmlDefinition, ReferencesResolver, this, GacCache); default: throw new BuildException(string.Format(CultureInfo.InvariantCulture, "\"{0}\" reference not supported.", xmlDefinition.Name), Location.UnknownLocation); } } #endregion Protected Instance Methods #region Private Instance Methods private void RunNMake(string nmakeCommand) { // store current directory string originalCurrentDirectory = Directory.GetCurrentDirectory(); try { // change current directory to directory containing // project file Directory.SetCurrentDirectory(ProjectDirectory.FullName); // execute command ExecTask nmakeTask = new ExecTask(); nmakeTask.Project = SolutionTask.Project; nmakeTask.Parent = SolutionTask; nmakeTask.Verbose = SolutionTask.Verbose; nmakeTask.CommandLineArguments = "/c \"" + nmakeCommand + "\""; nmakeTask.FileName = "cmd.exe"; ExecuteInProjectDirectory(nmakeTask); } finally { // restore original current directory Directory.SetCurrentDirectory(originalCurrentDirectory); } } private void BuildCPPFiles(ArrayList fileNames, Configuration solutionConfiguration, VcConfigurationBase fileConfig) { // obtain project configuration (corresponding with solution configuration) VcProjectConfiguration projectConfig = (VcProjectConfiguration) BuildConfigurations[solutionConfiguration]; string intermediateDir = FileUtils.CombinePaths(ProjectDirectory.FullName, projectConfig.IntermediateDir); // create instance of Cl task ClTask clTask = new ClTask(); // inherit project from solution task clTask.Project = SolutionTask.Project; // inherit namespace manager from solution task clTask.NamespaceManager = SolutionTask.NamespaceManager; // parent is solution task clTask.Parent = SolutionTask; // inherit verbose setting from solution task clTask.Verbose = SolutionTask.Verbose; // make sure framework specific information is set clTask.InitializeTaskConfiguration(); // set parent of child elements clTask.IncludeDirs.Parent = clTask; clTask.Sources.Parent = clTask; clTask.MetaDataIncludeDirs.Parent = clTask; clTask.ForcedUsingFiles.Parent = clTask; // inherit project from solution task for child elements clTask.IncludeDirs.Project = clTask.Project; clTask.Sources.Project = clTask.Project; clTask.MetaDataIncludeDirs.Project = clTask.Project; clTask.ForcedUsingFiles.Project = clTask.Project; // set namespace manager of child elements clTask.IncludeDirs.NamespaceManager = clTask.NamespaceManager; clTask.Sources.NamespaceManager = clTask.NamespaceManager; clTask.MetaDataIncludeDirs.NamespaceManager = clTask.NamespaceManager; clTask.ForcedUsingFiles.NamespaceManager = clTask.NamespaceManager; // set base directories clTask.IncludeDirs.BaseDirectory = ProjectDirectory; clTask.Sources.BaseDirectory = ProjectDirectory; clTask.MetaDataIncludeDirs.BaseDirectory = ProjectDirectory; clTask.ForcedUsingFiles.BaseDirectory = ProjectDirectory; // set task properties clTask.OutputDir = new DirectoryInfo(intermediateDir); // TODO: add support for disabling specific warnings !!! // check if precompiled headers are used if (fileConfig.UsePrecompiledHeader != UsePrecompiledHeader.No && fileConfig.UsePrecompiledHeader != UsePrecompiledHeader.Unspecified) { // get location of precompiled header file string pchFile = fileConfig.GetToolSetting(VcConfigurationBase.CLCompilerTool, "PrecompiledHeaderFile", "$(IntDir)/$(TargetName).pch"); // we must set an absolute path for the PCH location file, // otherwise assumes a location relative to the output // directory - not the project directory. if (!String.IsNullOrEmpty(pchFile)) { clTask.PchFile = FileUtils.CombinePaths(ProjectDirectory.FullName, pchFile); } // check if a header file is specified for the precompiled header // file, use "StdAfx.h" as default value string headerThrough = fileConfig.GetToolSetting(VcConfigurationBase.CLCompilerTool, "PrecompiledHeaderThrough", "StdAfx.h"); if (!String.IsNullOrEmpty(headerThrough)) { clTask.PchThroughFile = headerThrough; } switch (fileConfig.UsePrecompiledHeader) { case UsePrecompiledHeader.Use: clTask.PchMode = ClTask.PrecompiledHeaderMode.Use; break; case UsePrecompiledHeader.AutoCreate: clTask.PchMode = ClTask.PrecompiledHeaderMode.AutoCreate; break; case UsePrecompiledHeader.Create: clTask.PchMode = ClTask.PrecompiledHeaderMode.Create; break; } } clTask.CharacterSet = projectConfig.CharacterSet; // ensure output directory exists if (!clTask.OutputDir.Exists) { clTask.OutputDir.Create(); clTask.OutputDir.Refresh(); } string includeDirs = MergeToolSetting(projectConfig, fileConfig, VcConfigurationBase.CLCompilerTool, "AdditionalIncludeDirectories"); if (!String.IsNullOrEmpty(includeDirs)) { foreach (string includeDir in includeDirs.Split(',', ';')) { if (includeDir.Length == 0) { continue; } clTask.IncludeDirs.DirectoryNames.Add(FileUtils.CombinePaths( ProjectDirectory.FullName, CleanPath(includeDir))); } } string metadataDirs = MergeToolSetting(projectConfig, fileConfig, VcConfigurationBase.CLCompilerTool, "AdditionalUsingDirectories"); if (!String.IsNullOrEmpty(metadataDirs)) { foreach (string metadataDir in metadataDirs.Split(';')) { if (metadataDir.Length == 0) { continue; } clTask.MetaDataIncludeDirs.DirectoryNames.Add( CleanPath(fileConfig.ExpandMacros(metadataDir))); } } string forcedUsingFiles = MergeToolSetting(projectConfig, fileConfig, VcConfigurationBase.CLCompilerTool, "ForcedUsingFiles"); if (!String.IsNullOrEmpty(forcedUsingFiles)) { foreach (string forcedUsingFile in forcedUsingFiles.Split(';')) { if (forcedUsingFile.Length == 0) { continue; } clTask.ForcedUsingFiles.Includes.Add( CleanPath(fileConfig.ExpandMacros(forcedUsingFile))); } } // add project and assembly references foreach (ReferenceBase reference in References) { if (!reference.IsManaged(solutionConfiguration)) { continue; } StringCollection assemblyReferences = reference.GetAssemblyReferences( solutionConfiguration); foreach (string assemblyFile in assemblyReferences) { clTask.ForcedUsingFiles.Includes.Add(assemblyFile); } } // Since the name of the pdb file is based on the VS version, we need to see // which version we are targeting to make sure the right pdb file is used. string pdbTargetFileName; switch (ProductVersion) { case ProductVersion.Rosario: pdbTargetFileName = "$(IntDir)/vc100.pdb"; break; case ProductVersion.Orcas: pdbTargetFileName = "$(IntDir)/vc90.pdb"; break; case ProductVersion.Whidbey: pdbTargetFileName = "$(IntDir)/vc80.pdb"; break; default: pdbTargetFileName = "$(IntDir)/vc70.pdb"; break; } // set name of program database file // // we must set an absolute path for the program database file, // otherwise assumes a location relative to the output // directory - not the project directory. string pdbFile = fileConfig.GetToolSetting(VcConfigurationBase.CLCompilerTool, "ProgramDataBaseFileName", pdbTargetFileName); if (!String.IsNullOrEmpty(pdbFile)) { clTask.ProgramDatabaseFile = FileUtils.CombinePaths(ProjectDirectory.FullName, pdbFile); } // set path of object file or directory (can be null) clTask.ObjectFile = GetObjectFile(fileConfig); string asmOutput = fileConfig.GetToolSetting(VcConfigurationBase.CLCompilerTool, "AssemblerOutput"); string asmListingLocation = fileConfig.GetToolSetting(VcConfigurationBase.CLCompilerTool, "AssemblerListingLocation"); if (!String.IsNullOrEmpty(asmOutput) && asmOutput != "0" && !String.IsNullOrEmpty(asmListingLocation)) { // parameter for AssemblerOutput itself will be handled by the map clTask.Arguments.Add(new Argument("/Fa\"" + asmListingLocation + "\"")); } foreach (string fileName in fileNames) { clTask.Sources.FileNames.Add(FileUtils.CombinePaths( ProjectDirectory.FullName, fileName)); } string preprocessorDefs = MergeToolSetting(projectConfig, fileConfig, VcConfigurationBase.CLCompilerTool, "PreprocessorDefinitions"); if (!String.IsNullOrEmpty(preprocessorDefs)) { foreach (string def in preprocessorDefs.Split(';', ',')) { if (def.Length != 0) { Option op = new Option(); op.OptionName = def; clTask.Defines.Add(op); } } } string undefinePreprocessorDefs = MergeToolSetting(projectConfig, fileConfig, VcConfigurationBase.CLCompilerTool, "UndefinePreprocessorDefinitions"); if (!String.IsNullOrEmpty(undefinePreprocessorDefs)) { foreach (string def in undefinePreprocessorDefs.Split(';', ',')) { Option op = new Option(); op.OptionName = def; clTask.Undefines.Add(op); } } string addOptions = fileConfig.GetToolSetting(VcConfigurationBase.CLCompilerTool, "AdditionalOptions"); if (!String.IsNullOrEmpty(addOptions)) { using (StringReader reader = new StringReader(addOptions)) { string addOptionsLine = reader.ReadLine(); while (addOptionsLine != null) { foreach (string addOption in addOptionsLine.Split(' ')) { clTask.Arguments.Add(new Argument(addOption)); } addOptionsLine = reader.ReadLine(); } } } //exception handling stuff string exceptionHandling = fileConfig.GetToolSetting(VcConfigurationBase.CLCompilerTool, "ExceptionHandling"); if (exceptionHandling == null) { if (ProductVersion >= ProductVersion.Whidbey) { exceptionHandling = "2"; } else { exceptionHandling = "false"; } } else { exceptionHandling = exceptionHandling.ToLower(); } switch(exceptionHandling) { case "0": case "false": break; case "1": case "true": clTask.Arguments.Add(new Argument("/EHsc")); break; case "2": clTask.Arguments.Add(new Argument("/EHa")); break; } string browseInformation = fileConfig.GetToolSetting(VcConfigurationBase.CLCompilerTool, "BrowseInformation"); if (!String.IsNullOrEmpty(browseInformation) && browseInformation != "0") { // determine file name of browse information file string browseInformationFile = fileConfig.GetToolSetting( VcConfigurationBase.CLCompilerTool, "BrowseInformationFile", "$(IntDir)/"); if (!String.IsNullOrEmpty(browseInformationFile)) { switch (browseInformation) { case "1": // Include All Browse Information clTask.Arguments.Add(new Argument("/FR\"" + browseInformationFile + "\"")); break; case "2": // No Local Symbols clTask.Arguments.Add(new Argument("/Fr\"" + browseInformationFile + "\"")); break; } } else { switch (browseInformation) { case "1": // Include All Browse Information clTask.Arguments.Add(new Argument("/FR")); break; case "2": // No Local Symbols clTask.Arguments.Add(new Argument("/Fr")); break; } } } if (projectConfig.Type == VcProjectConfiguration.ConfigurationType.DynamicLibrary) { clTask.Arguments.Add(new Argument("/D")); clTask.Arguments.Add(new Argument("_WINDLL")); } if (projectConfig.WholeProgramOptimization) { clTask.Arguments.Add(new Argument("/GL")); } // used to ignore some arguments VcArgumentMap.ArgGroup vcArgIgnoreGroup = VcArgumentMap.ArgGroup.Unassigned; // if optimzation level is Minimum Size (1) or Maximum size (2), we // need to ignore all the arguments of the group "OptiIgnoreGroup" string optimization = fileConfig.GetToolSetting(VcConfigurationBase.CLCompilerTool, "Optimization"); if (!String.IsNullOrEmpty(optimization)) { int optimizationLevel = int.Parse(optimization); if (optimizationLevel == 1 || optimizationLevel == 2) { vcArgIgnoreGroup |= VcArgumentMap.ArgGroup.OptiIgnoreGroup; } } Hashtable compilerArgs = fileConfig.GetToolArguments(VcConfigurationBase.CLCompilerTool, _clArgMap, vcArgIgnoreGroup); foreach (string arg in compilerArgs.Values) { Argument compilerArg = new Argument(); compilerArg.Line = arg; clTask.Arguments.Add(compilerArg); } // check for shared MFC if (projectConfig.UseOfMFC == UseOfMFC.Shared) { clTask.Arguments.Add(new Argument("/D")); clTask.Arguments.Add(new Argument("_AFXDLL")); } // check for shared ATL switch (projectConfig.UseOfATL) { case UseOfATL.Shared: clTask.Arguments.Add(new Argument("/D")); clTask.Arguments.Add(new Argument("_ATL_DLL")); break; case UseOfATL.Static: clTask.Arguments.Add(new Argument("/D")); clTask.Arguments.Add(new Argument("_ATL_STATIC_REGISTRY")); break; } // enable/disable Managed Extensions for C++ clTask.ManagedExtensions = projectConfig.ManagedExtensions; // execute the task ExecuteInProjectDirectory(clTask); } /// /// Build resource files for the given configuration. /// /// The resource files to build. /// The project configuration. /// The build configuration. /// /// TODO: refactor this as we should always get only one element in the /// list. Each res file should be built /// with its own file configuration. /// private void BuildResourceFiles(ArrayList fileNames, VcProjectConfiguration projectConfig, VcConfigurationBase fileConfig) { // create instance of RC task RcTask rcTask = new RcTask(); // inherit project from solution task rcTask.Project = SolutionTask.Project; // Set the base directory rcTask.BaseDirectory = ProjectDirectory; // inherit namespace manager from solution task rcTask.NamespaceManager = SolutionTask.NamespaceManager; // parent is solution task rcTask.Parent = SolutionTask; // inherit verbose setting from solution task rcTask.Verbose = SolutionTask.Verbose; // make sure framework specific information is set rcTask.InitializeTaskConfiguration(); // set parent of child elements rcTask.IncludeDirs.Parent = rcTask; // inherit project from solution task for child elements rcTask.IncludeDirs.Project = rcTask.Project; // set namespace manager of child elements rcTask.IncludeDirs.NamespaceManager = rcTask.NamespaceManager; // set base directories rcTask.IncludeDirs.BaseDirectory = ProjectDirectory; // Store the options to pass to the resource compiler in the options variable StringBuilder options = new StringBuilder(); // Collect options string ignoreStandardIncludePath = fileConfig.GetToolSetting(VcConfigurationBase.ResourceCompilerTool, "IgnoreStandardIncludePath"); if (ignoreStandardIncludePath != null && string.Compare(ignoreStandardIncludePath, "true", true, CultureInfo.InvariantCulture) == 0) { options.Append("/X "); } string culture = fileConfig.GetToolSetting(VcConfigurationBase.ResourceCompilerTool, "Culture"); if (!String.IsNullOrEmpty(culture)) { int cultureId = Convert.ToInt32(culture); rcTask.LangId = cultureId; } string preprocessorDefs = fileConfig.GetToolSetting(VcConfigurationBase.ResourceCompilerTool, "PreprocessorDefinitions"); if (!String.IsNullOrEmpty(preprocessorDefs)) { foreach (string preprocessorDef in preprocessorDefs.Split(';')) { if (preprocessorDef.Length == 0) { continue; } Option op = new Option(); op.OptionName = preprocessorDef; rcTask.Defines.Add(op); } } string showProgress = fileConfig.GetToolSetting(VcConfigurationBase.ResourceCompilerTool, "ShowProgress"); if (showProgress != null && string.Compare(showProgress, "true", true, CultureInfo.InvariantCulture) == 0) { rcTask.Verbose = true; } string addIncludeDirs = MergeToolSetting(projectConfig, fileConfig, VcConfigurationBase.ResourceCompilerTool, "AdditionalIncludeDirectories"); if (!String.IsNullOrEmpty(addIncludeDirs)) { foreach (string includeDir in addIncludeDirs.Split(';')) { if (includeDir.Length == 0) { continue; } rcTask.IncludeDirs.DirectoryNames.Add(FileUtils.CombinePaths( ProjectDirectory.FullName, CleanPath(includeDir))); } } // check for shared MFC if (projectConfig.UseOfMFC == UseOfMFC.Shared) { options.AppendFormat("/d \"_AFXDLL\""); } if (options.Length > 0) { rcTask.Options = options.ToString(); } // Compile each resource file foreach (string rcFile in fileNames) { rcTask.OutputFile = new FileInfo(GetResourceOutputFile(rcFile, fileConfig)); rcTask.RcFile = new FileInfo(FileUtils.CombinePaths(ProjectDirectory.FullName, rcFile)); // execute the task ExecuteInProjectDirectory(rcTask); } } /// /// Build Interface Definition Language files for the given /// configuration. /// /// The IDL files to build. /// The project configuration. /// The build configuration. /// /// TODO: refactor this as we should always get only one element in the /// list. Each IDL file should be built /// with its own file configuration. /// private void BuildIDLFiles(ArrayList fileNames, VcProjectConfiguration projectConfig, VcConfigurationBase fileConfig) { // create instance of MIDL task MidlTask midlTask = new MidlTask(); // inherit project from solution task midlTask.Project = SolutionTask.Project; // Set the base directory midlTask.BaseDirectory = ProjectDirectory; // inherit namespace manager from solution task midlTask.NamespaceManager = SolutionTask.NamespaceManager; // parent is solution task midlTask.Parent = SolutionTask; // inherit verbose setting from solution task midlTask.Verbose = SolutionTask.Verbose; // make sure framework specific information is set midlTask.InitializeTaskConfiguration(); // set parent of child elements midlTask.IncludeDirs.Parent = midlTask; // inherit project from solution task for child elements midlTask.IncludeDirs.Project = midlTask.Project; // set namespace manager of child elements midlTask.IncludeDirs.NamespaceManager = midlTask.NamespaceManager; // set base directories midlTask.IncludeDirs.BaseDirectory = ProjectDirectory; // If outputDirectory is not supplied in the configuration, assume // it's the project directory string outputDirectory = fileConfig.GetToolSetting(VcConfigurationBase.MIDLTool, "OutputDirectory"); if (String.IsNullOrEmpty(outputDirectory)) { outputDirectory = ProjectDirectory.FullName; } else { outputDirectory = FileUtils.CombinePaths(ProjectDirectory.FullName, outputDirectory); } // ensure output directory exists if (!Directory.Exists(outputDirectory)) { Directory.CreateDirectory(outputDirectory); } midlTask.Arguments.Add(new Argument("/out")); midlTask.Arguments.Add(new Argument(outputDirectory)); string typeLibraryName = fileConfig.GetToolSetting(VcConfigurationBase.MIDLTool, "TypeLibraryName", "$(IntDir)/$(ProjectName).tlb"); if (!String.IsNullOrEmpty(typeLibraryName)) { midlTask.Tlb = new FileInfo(FileUtils.CombinePaths(outputDirectory, typeLibraryName)); // ensure tlb directory exists if (!midlTask.Tlb.Directory.Exists) { midlTask.Tlb.Directory.Create(); midlTask.Tlb.Directory.Refresh(); } } string proxyFileName = fileConfig.GetToolSetting(VcConfigurationBase.MIDLTool, "ProxyFileName"); if (!String.IsNullOrEmpty(proxyFileName)) { midlTask.Proxy = new FileInfo(FileUtils.CombinePaths(outputDirectory, proxyFileName)); // ensure proxy directory exists if (!midlTask.Proxy.Directory.Exists) { midlTask.Proxy.Directory.Create(); midlTask.Proxy.Directory.Refresh(); } } string interfaceIdentifierFileName = fileConfig.GetToolSetting(VcConfigurationBase.MIDLTool, "InterfaceIdentifierFileName"); if (!String.IsNullOrEmpty(interfaceIdentifierFileName)) { midlTask.Iid = new FileInfo(FileUtils.CombinePaths(outputDirectory, interfaceIdentifierFileName)); // ensure IID directory exists if (!midlTask.Iid.Directory.Exists) { midlTask.Iid.Directory.Create(); midlTask.Iid.Directory.Refresh(); } } string dllDataFileName = fileConfig.GetToolSetting(VcConfigurationBase.MIDLTool, "DLLDataFileName"); if (!String.IsNullOrEmpty(dllDataFileName)) { midlTask.DllData = new FileInfo(FileUtils.CombinePaths(outputDirectory, dllDataFileName)); // ensure DllData directory exists if (!midlTask.DllData.Directory.Exists) { midlTask.DllData.Directory.Create(); midlTask.DllData.Directory.Refresh(); } } string headerFileName = fileConfig.GetToolSetting(VcConfigurationBase.MIDLTool, "HeaderFileName"); if (!String.IsNullOrEmpty(headerFileName)) { midlTask.Header = new FileInfo(FileUtils.CombinePaths(outputDirectory, headerFileName)); // ensure Header directory exists if (!midlTask.Header.Directory.Exists) { midlTask.Header.Directory.Create(); midlTask.Header.Directory.Refresh(); } } string preprocessorDefs = MergeToolSetting(projectConfig, fileConfig, VcConfigurationBase.MIDLTool, "PreprocessorDefinitions"); if (!String.IsNullOrEmpty(preprocessorDefs)) { foreach (string preprocessorDef in preprocessorDefs.Split(';')) { if (preprocessorDef.Length == 0) { continue; } Option op = new Option(); op.OptionName = preprocessorDef; midlTask.Defines.Add(op); } } string undefinePreprocessorDefs = MergeToolSetting(projectConfig, fileConfig, VcConfigurationBase.MIDLTool, "UndefinePreprocessorDefinitions"); if (!String.IsNullOrEmpty(undefinePreprocessorDefs)) { foreach (string undefinePreprocessorDef in undefinePreprocessorDefs.Split(';')) { if (undefinePreprocessorDef.Length == 0) { continue; } Option op = new Option(); op.OptionName = undefinePreprocessorDef; midlTask.Undefines.Add(op); } } string additionalIncludeDirs = MergeToolSetting(projectConfig, fileConfig, VcConfigurationBase.MIDLTool, "AdditionalIncludeDirectories"); if (!String.IsNullOrEmpty(additionalIncludeDirs)) { foreach (string includeDir in additionalIncludeDirs.Split(';')) { if (includeDir.Length == 0) { continue; } midlTask.IncludeDirs.DirectoryNames.Add(FileUtils.CombinePaths( ProjectDirectory.FullName, CleanPath(includeDir))); } } string cPreprocessOptions = MergeToolSetting(projectConfig, fileConfig, VcConfigurationBase.MIDLTool, "CPreprocessOptions"); if (!String.IsNullOrEmpty(cPreprocessOptions)) { foreach (string cPreprocessOption in cPreprocessOptions.Split(';')) { if (cPreprocessOption.Length == 0) { continue; } midlTask.Arguments.Add(new Argument(string.Format("/cpp_opt\"{0}\"", cPreprocessOption))); } } Hashtable midlArgs = fileConfig.GetToolArguments(VcConfigurationBase.MIDLTool, _midlArgMap); foreach (string key in midlArgs.Keys) { switch (key) { case "TargetEnvironment": midlTask.Env = (string) midlArgs[key]; break; case "DefaultCharType": midlTask.Char = (string) midlArgs[key]; break; default: Argument midlArg = new Argument(); midlArg.Line = (string) midlArgs[key]; midlTask.Arguments.Add(midlArg); break; } } // Compile each idl file foreach (string idlFile in fileNames) { midlTask.Filename = new FileInfo(FileUtils.CombinePaths( ProjectDirectory.FullName, idlFile)); // execute the task ExecuteInProjectDirectory(midlTask); } } private bool RunCustomBuildStep(Configuration solutionConfiguration, VcProjectConfiguration projectConfig) { // check if a custom build step is configured string commandLine = projectConfig.GetToolSetting(VcConfigurationBase.CustomBuildTool, "CommandLine"); if (String.IsNullOrEmpty(commandLine)) { return true; } DateTime oldestOutputFile = DateTime.MinValue; string outputs = projectConfig.GetToolSetting(VcConfigurationBase.CustomBuildTool, "Outputs"); if (!String.IsNullOrEmpty(outputs)) { foreach (string output in outputs.Split(';')) { if (output.Length == 0) { continue; } string outputFile = Path.Combine (ProjectDirectory.FullName, output); if (File.Exists(outputFile)) { DateTime lastWriteTime = File.GetLastWriteTime(outputFile); if (lastWriteTime < oldestOutputFile || oldestOutputFile == DateTime.MinValue) { oldestOutputFile = lastWriteTime; } } } } bool runCustomBuildStep = false; // when at least one of the output files of the custom build step // does not exist or is older than the project output file, then // the custom build step must be executed string projectOutputFile = GetOutputPath(solutionConfiguration); if (projectOutputFile != null && File.Exists (projectOutputFile)) { DateTime lastWriteTime = File.GetLastWriteTime(projectOutputFile); if (lastWriteTime > oldestOutputFile) { runCustomBuildStep = true; } } // if one of the additional dependencies was updated after the oldest // output file of the custom build step, then the custom build step // must also be executed if (!runCustomBuildStep) { string additionalDependencies = projectConfig.GetToolSetting( VcConfigurationBase.CustomBuildTool, "AdditionalDependencies"); if (!String.IsNullOrEmpty(additionalDependencies)) { foreach (string dependency in additionalDependencies.Split(';')) { if (dependency.Length == 0) { continue; } string dependencyFile = Path.Combine (ProjectDirectory.FullName, dependency); if (File.Exists (dependencyFile)) { DateTime lastWriteTime = File.GetLastWriteTime(dependencyFile); if (lastWriteTime > oldestOutputFile) { runCustomBuildStep = true; break; } } } } } if (!runCustomBuildStep) { return true; } string description = projectConfig.GetToolSetting(VcConfigurationBase.CustomBuildTool, "Description", "Performing Custom Build Step"); Log(Level.Info, description); return ExecuteBuildEvent("Custom-Build", commandLine, projectConfig); } private void RunLibrarian(VcProjectConfiguration projectConfig) { // check if there's anything to do if (projectConfig.ObjFiles.Count == 0) { Log(Level.Debug, "No files to compile."); return; } // create instance of Lib task LibTask libTask = new LibTask(); // inherit project from solution task libTask.Project = SolutionTask.Project; // inherit namespace manager from solution task libTask.NamespaceManager = SolutionTask.NamespaceManager; // parent is solution task libTask.Parent = SolutionTask; // inherit verbose setting from solution task libTask.Verbose = SolutionTask.Verbose; // make sure framework specific information is set libTask.InitializeTaskConfiguration(); // set parent of child elements libTask.Sources.Parent = libTask; // inherit project from solution task for child elements libTask.Sources.Project = libTask.Project; // inherit namespace manager from parent libTask.Sources.NamespaceManager = libTask.NamespaceManager; libTask.OutputFile = new FileInfo(projectConfig.OutputPath); // Additional Library Directory string addLibDirs = projectConfig.GetToolSetting(VcConfigurationBase.LibTool, "AdditionalLibraryDirectories"); if (!String.IsNullOrEmpty(addLibDirs)) { foreach (string addLibDir in addLibDirs.Split(',', ';')) { if (addLibDir.Length == 0) { continue; } libTask.LibDirs.DirectoryNames.Add(addLibDir); } } // Additional Dependencies string addDeps = projectConfig.GetToolSetting(VcConfigurationBase.LibTool, "AdditionalDependencies"); if (!String.IsNullOrEmpty(addDeps)) { int insertedDeps = 0; foreach (string addDep in addDeps.Split(' ')) { if (Path.GetExtension(addDep) == ".obj") { projectConfig.ObjFiles.Insert(insertedDeps++, addDep); } else { libTask.Sources.FileNames.Add(addDep); } } } foreach (string objFile in projectConfig.ObjFiles) { libTask.Sources.FileNames.Add(objFile); } // Module Definition File Name string moduleDefinitionFile = projectConfig.GetToolSetting(VcConfigurationBase.LibTool, "ModuleDefinitionFile"); if (!String.IsNullOrEmpty(moduleDefinitionFile)) { libTask.ModuleDefinitionFile = new FileInfo(FileUtils.CombinePaths( ProjectDirectory.FullName, moduleDefinitionFile)); } // Ignore All Default Libraries string ignoreAllDefaultLibraries = projectConfig.GetToolSetting(VcConfigurationBase.LibTool, "IgnoreAllDefaultLibraries"); if (string.Compare(ignoreAllDefaultLibraries, "TRUE", true, CultureInfo.InvariantCulture) == 0) { libTask.Options = "/NODEFAULTLIB"; } // Ignore Specific Libraries string ignoreDefaultLibraries = projectConfig.GetToolSetting(VcConfigurationBase.LibTool, "IgnoreDefaultLibraryNames"); if (!String.IsNullOrEmpty(ignoreDefaultLibraries)) { foreach (string ignoreLibrary in ignoreDefaultLibraries.Split(';')) { libTask.IgnoreLibraries.Add(new Library(ignoreLibrary)); } } // Export Named Functions // TODO // Forced Symbol References string symbolReferences = projectConfig.GetToolSetting(VcConfigurationBase.LibTool, "ForceSymbolReferences"); if (!String.IsNullOrEmpty(symbolReferences)) { foreach (string symbol in symbolReferences.Split(';')) { libTask.Symbols.Add(new Symbol(symbol)); } } // execute the task ExecuteInProjectDirectory(libTask); } private void RunLinker(Configuration solutionConfiguration) { const string noinherit = "$(noinherit)"; // obtain project configuration (corresponding with solution configuration) VcProjectConfiguration projectConfig = (VcProjectConfiguration) BuildConfigurations[solutionConfiguration]; // check if linking needs to be performed if (projectConfig.ObjFiles.Count == 0) { Log(Level.Debug, "No files to link."); return; } // create instance of Link task LinkTask linkTask = new LinkTask(); // inherit project from solution task linkTask.Project = SolutionTask.Project; // inherit namespace manager from solution task linkTask.NamespaceManager = SolutionTask.NamespaceManager; // parent is solution task linkTask.Parent = SolutionTask; // inherit verbose setting from solution task linkTask.Verbose = SolutionTask.Verbose; // make sure framework specific information is set linkTask.InitializeTaskConfiguration(); // set parent of child elements linkTask.Sources.Parent = linkTask; linkTask.LibDirs.Parent = linkTask; linkTask.Modules.Parent = linkTask; linkTask.EmbeddedResources.Project = linkTask.Project; // inherit project from solution task for child elements linkTask.Sources.Project = linkTask.Project; linkTask.LibDirs.Project = linkTask.Project; linkTask.Modules.Project = linkTask.Project; linkTask.EmbeddedResources.Project = linkTask.Project; // inherit namespace manager from parent linkTask.Sources.NamespaceManager = linkTask.NamespaceManager; linkTask.LibDirs.NamespaceManager = linkTask.NamespaceManager; linkTask.Modules.NamespaceManager = linkTask.NamespaceManager; linkTask.EmbeddedResources.NamespaceManager = linkTask.NamespaceManager; // set base directory of filesets linkTask.Sources.BaseDirectory = ProjectDirectory; linkTask.LibDirs.BaseDirectory = ProjectDirectory; linkTask.Modules.BaseDirectory = ProjectDirectory; linkTask.EmbeddedResources.BaseDirectory = ProjectDirectory; string addDeps = projectConfig.GetToolSetting(VcConfigurationBase.LinkerTool, "AdditionalDependencies"); if (!String.IsNullOrEmpty(addDeps)) { // only include default libraries if noinherit is not set if (addDeps.ToLower(CultureInfo.InvariantCulture).IndexOf(noinherit) == -1) { foreach (string defaultLib in _defaultLibraries) { linkTask.Sources.FileNames.Add(defaultLib); } } else { addDeps = addDeps.Remove(addDeps.ToLower(CultureInfo.InvariantCulture).IndexOf(noinherit), noinherit.Length); } foreach (string addDep in addDeps.Split(' ')) { if (Path.GetExtension(addDep) == ".obj") { // skip obj files are these are handled in // VcProjectConfiguration continue; } linkTask.Sources.FileNames.Add(addDep); } } else { // always include default libraries if no additional dependencies // are specified foreach (string defaultLib in _defaultLibraries) { linkTask.Sources.FileNames.Add(defaultLib); } } string delayLoadedDlls = projectConfig.GetToolSetting(VcConfigurationBase.LinkerTool, "DelayLoadDLLs"); if (!String.IsNullOrEmpty(delayLoadedDlls)) { foreach (string dll in delayLoadedDlls.Split(';')) { linkTask.DelayLoadedDlls.FileNames.Add(dll); } } foreach (string objFile in projectConfig.ObjFiles) { linkTask.Sources.FileNames.Add(objFile); } // add output generated by referenced projects and explicit project // dependencies ProjectBaseCollection projectDependencies = GetVcProjectDependencies(); foreach (VcProject vcProject in projectDependencies) { VcProjectConfiguration vcProjectConfig = vcProject.BuildConfigurations[ solutionConfiguration] as VcProjectConfiguration; switch (vcProjectConfig.Type) { case VcProjectConfiguration.ConfigurationType.Application: case VcProjectConfiguration.ConfigurationType.DynamicLibrary: FileInfo dependencyImportLibrary = vcProjectConfig.LinkerConfiguration.ImportLibrary; if (dependencyImportLibrary != null) { linkTask.Sources.FileNames.Add( dependencyImportLibrary.FullName); } break; case VcProjectConfiguration.ConfigurationType.StaticLibrary: linkTask.Sources.FileNames.Add(vcProjectConfig.OutputPath); break; } } linkTask.OutputFile = new FileInfo(projectConfig.OutputPath); // ensure directory exists if (!linkTask.OutputFile.Directory.Exists) { linkTask.OutputFile.Directory.Create(); linkTask.OutputFile.Directory.Refresh(); } // generation of debug information linkTask.Debug = bool.Parse(projectConfig.GetToolSetting(VcConfigurationBase.LinkerTool, "GenerateDebugInformation", "FALSE")); string pdbFile = projectConfig.GetToolSetting(VcConfigurationBase.LinkerTool, "ProgramDatabaseFile"); // use default value if pdb was not explicitly disabled (by setting it to empty string) if (pdbFile == null && linkTask.Debug) { pdbFile = projectConfig.ExpandMacros("$(OutDir)/$(ProjectName).pdb"); } if (!String.IsNullOrEmpty(pdbFile)) { if (OutputDir != null) { pdbFile = FileUtils.CombinePaths(OutputDir.FullName, Path.GetFileName(pdbFile)); } else { pdbFile = FileUtils.CombinePaths(ProjectDirectory.FullName, pdbFile); } linkTask.ProgramDatabaseFile = new FileInfo(pdbFile); // ensure directory exists if (!linkTask.ProgramDatabaseFile.Directory.Exists) { linkTask.ProgramDatabaseFile.Directory.Create(); linkTask.ProgramDatabaseFile.Directory.Refresh(); } } // generation of import library FileInfo importLibrary = projectConfig.LinkerConfiguration.ImportLibrary; if (importLibrary != null) { Argument importLibraryArg = new Argument(); importLibraryArg.Line = "/IMPLIB:" + LinkTask.QuoteArgumentValue( importLibrary.FullName); linkTask.Arguments.Add(importLibraryArg); // ensure directory exists if (!importLibrary.Directory.Exists) { importLibrary.Directory.Create(); importLibrary.Directory.Refresh(); } } // Ignore Specific Libraries string ignoreDefaultLibraries = projectConfig.GetToolSetting(VcConfigurationBase.LinkerTool, "IgnoreDefaultLibraryNames"); if (!String.IsNullOrEmpty(ignoreDefaultLibraries)) { foreach (string ignoreLibrary in ignoreDefaultLibraries.Split(';')) { linkTask.IgnoreLibraries.Add(new Library(ignoreLibrary)); } } // Forced Symbol References string symbolReferences = projectConfig.GetToolSetting(VcConfigurationBase.LinkerTool, "ForceSymbolReferences"); if (!String.IsNullOrEmpty(symbolReferences)) { foreach (string symbol in symbolReferences.Split(';')) { linkTask.Symbols.Add(new Symbol(symbol)); } } // generation of map file during linking bool generateMapFile = bool.Parse(projectConfig.GetToolSetting(VcConfigurationBase.LinkerTool, "GenerateMapFile", "FALSE")); if (generateMapFile) { Argument mapArg = new Argument(); string mapFileName = projectConfig.GetToolSetting(VcConfigurationBase.LinkerTool, "MapFileName"); if (!String.IsNullOrEmpty(mapFileName)) { mapArg.Line = "/MAP:" + LinkTask.QuoteArgumentValue(mapFileName);; } else { mapArg.Line = "/MAP"; } linkTask.Arguments.Add(mapArg); } // total heap allocation size string heapReserveSize = projectConfig.GetToolSetting(VcConfigurationBase.LinkerTool, "HeapReserveSize"); if (!String.IsNullOrEmpty(heapReserveSize)) { Argument heapArg = new Argument(); string heapCommitSize = projectConfig.GetToolSetting(VcConfigurationBase.LinkerTool, "HeapCommitSize"); if (!String.IsNullOrEmpty(heapCommitSize)) { heapArg.Line = string.Format(CultureInfo.InvariantCulture, "/HEAP:{0},{1}", heapReserveSize, heapCommitSize); } else { heapArg.Line = "/HEAP:" + heapReserveSize; } linkTask.Arguments.Add(heapArg); } // total stack allocation size string stackReserveSize = projectConfig.GetToolSetting(VcConfigurationBase.LinkerTool, "StackReserveSize"); if (!String.IsNullOrEmpty(stackReserveSize)) { Argument stackArg = new Argument(); string stackCommitSize = projectConfig.GetToolSetting(VcConfigurationBase.LinkerTool, "StackCommitSize"); if (!String.IsNullOrEmpty(stackCommitSize)) { stackArg.Line = string.Format(CultureInfo.InvariantCulture, "/STACK:{0},{1}", stackReserveSize, stackCommitSize); } else { stackArg.Line = "/STACK:" + stackReserveSize; } linkTask.Arguments.Add(stackArg); } if (projectConfig.Type == VcProjectConfiguration.ConfigurationType.DynamicLibrary) { linkTask.Arguments.Add(new Argument("/DLL")); } string addLibDirs = projectConfig.GetToolSetting(VcConfigurationBase.LinkerTool, "AdditionalLibraryDirectories"); if (!String.IsNullOrEmpty(addLibDirs)) { foreach (string addLibDir in addLibDirs.Split(',', ';')) { if (addLibDir.Length == 0) { continue; } linkTask.LibDirs.DirectoryNames.Add(addLibDir); } } // links to modules string modules = projectConfig.GetToolSetting(VcConfigurationBase.LinkerTool, "AddModuleNamesToAssembly"); if (!String.IsNullOrEmpty(modules)) { foreach (string module in modules.Split(';')) { linkTask.Modules.FileNames.Add(module); } } // embedded resources string embeddedResources = projectConfig.GetToolSetting(VcConfigurationBase.LinkerTool, "EmbedManagedResourceFile"); if (!String.IsNullOrEmpty(embeddedResources)) { foreach (string embeddedResource in embeddedResources.Split(';')) { linkTask.EmbeddedResources.FileNames.Add(embeddedResource); } } Hashtable linkerArgs = projectConfig.GetToolArguments(VcConfigurationBase.LinkerTool, _linkerArgMap); foreach (string arg in linkerArgs.Values) { Argument linkArg = new Argument(); linkArg.Line = (string) arg; linkTask.Arguments.Add(linkArg); } string addOptions = projectConfig.GetToolSetting(VcConfigurationBase.LinkerTool, "AdditionalOptions"); if (!String.IsNullOrEmpty(addOptions)) { using (StringReader reader = new StringReader(addOptions)) { string addOptionsLine = reader.ReadLine(); while (addOptionsLine != null) { foreach (string addOption in addOptionsLine.Split(' ')) { linkTask.Arguments.Add(new Argument(addOption)); } addOptionsLine = reader.ReadLine(); } } } if (projectConfig.WholeProgramOptimization) { linkTask.Arguments.Add(new Argument("/LTCG")); } // execute the task ExecuteInProjectDirectory(linkTask); } private void ExecuteInProjectDirectory(Task task) { string oldBaseDir = SolutionTask.Project.BaseDirectory; SolutionTask.Project.BaseDirectory = ProjectDirectory.FullName; try { // increment indentation level task.Project.Indent(); // execute task task.Execute(); } finally { // restore original base directory SolutionTask.Project.BaseDirectory = oldBaseDir; // restore indentation level task.Project.Unindent(); } } /// /// Merges the specified tool setting of /// with . /// /// /// The merge is suppressed when the flag $(noinherit) is defined in /// . /// private string MergeToolSetting(VcProjectConfiguration projectConfig, VcConfigurationBase fileConfig, string tool, string setting) { const string noinherit = "$(noinherit)"; // get tool setting from either the file configuration or project // configuration (if setting is not defined on file configuration) string settingValue = fileConfig.GetToolSetting(tool, setting); if (settingValue != null) { if (settingValue.ToLower(CultureInfo.InvariantCulture).IndexOf(noinherit) == -1) { // only add project-level setting to value if noherit if // "fileConfig" is not actually the project config if (!object.ReferenceEquals(projectConfig, fileConfig)) { string baseSettingValue = projectConfig.GetToolSetting(tool, setting); if (!String.IsNullOrEmpty(baseSettingValue)) { settingValue += ";" + baseSettingValue; } } } else { settingValue = settingValue.Remove(settingValue.ToLower(CultureInfo.InvariantCulture).IndexOf(noinherit), noinherit.Length); } } else { // if settingValue is null, then its not defined in neither the // file nor the project configuration return null; } // individual values are separated by ';' string[] values = settingValue.Split(';'); // holds filtered setting value settingValue = string.Empty; // filter duplicate setting values Hashtable filteredValues = CollectionsUtil.CreateCaseInsensitiveHashtable(values.Length); foreach (string value in values) { if (!filteredValues.ContainsKey(value)) { filteredValues.Add(value, null); if (settingValue.Length != 0) { settingValue += ';'; } settingValue += value; } } return settingValue; } private bool PreBuild(VcProjectConfiguration projectConfig) { // check if the build event should be executed string excludedFromBuild = projectConfig.GetToolSetting(VcConfigurationBase.PreBuildEventTool, "ExcludedFromBuild"); if (excludedFromBuild != null) { if (string.Compare(excludedFromBuild.Trim(), "true", true, CultureInfo.InvariantCulture) == 0) { return true; } } string commandLine = projectConfig.GetToolSetting(VcConfigurationBase.PreBuildEventTool, "CommandLine"); if (!String.IsNullOrEmpty(commandLine)) { Log(Level.Info, "Performing Pre-Build Event..."); return ExecuteBuildEvent("Pre-Build", commandLine, projectConfig); } return true; } private bool PostBuild(VcProjectConfiguration projectConfig) { // check if the build event should be executed string excludedFromBuild = projectConfig.GetToolSetting(VcConfigurationBase.PostBuildEventTool, "ExcludedFromBuild"); if (excludedFromBuild != null) { if (string.Compare(excludedFromBuild.Trim(), "true", true, CultureInfo.InvariantCulture) == 0) { return true; } } string commandLine = projectConfig.GetToolSetting(VcConfigurationBase.PostBuildEventTool, "CommandLine"); if (!String.IsNullOrEmpty(commandLine)) { Log(Level.Info, "Performing Post-Build Event..."); return ExecuteBuildEvent("Post-Build", commandLine, projectConfig); } return true; } private bool PreLink(VcProjectConfiguration projectConfig) { // check if the build event should be executed string excludedFromBuild = projectConfig.GetToolSetting(VcConfigurationBase.PreLinkEventTool, "ExcludedFromBuild"); if (excludedFromBuild != null) { if (string.Compare(excludedFromBuild.Trim(), "true", true, CultureInfo.InvariantCulture) == 0) { return true; } } string commandLine = projectConfig.GetToolSetting(VcConfigurationBase.PreLinkEventTool, "CommandLine"); if (!String.IsNullOrEmpty(commandLine)) { Log(Level.Info, "Performing Pre-Link Event..."); return ExecuteBuildEvent("Pre-Link", commandLine, projectConfig); } return true; } private bool ExecuteBuildEvent(string buildEvent, string buildCommandLine, ConfigurationBase config) { string batchFile = null; try { // get unique temp file name to write command line of build event to batchFile = Path.GetTempFileName(); // remove temp file File.Delete(batchFile); // change extension to .bat batchFile = Path.ChangeExtension(batchFile, ".bat"); // execute the build event return base.ExecuteBuildEvent(buildEvent, buildCommandLine, batchFile, ProjectDirectory.FullName, config); } finally { if (batchFile != null && File.Exists(batchFile)) { File.Delete(batchFile); } } } /// /// Gets the absolute path to the object file or directory. /// /// The build configuration /// /// The absolute path to the object file or directory, or /// /// /// We use an absolute path for the object file, otherwise /// <cl> assumes a location relative to the output /// directory - not the project directory. /// private string GetObjectFile(VcConfigurationBase fileConfig) { string objectFile = fileConfig.GetToolSetting("VCCLCompilerTool", "ObjectFile", "$(IntDir)/"); if (!String.IsNullOrEmpty(objectFile)) { return FileUtils.CombinePaths(ProjectDirectory.FullName, objectFile); } return null; } private ProjectBaseCollection GetVcProjectDependencies() { ProjectBaseCollection vcProjectDependencies = new ProjectBaseCollection(); foreach (ProjectBase projectDependency in ProjectDependencies) { if (projectDependency is VcProject) { vcProjectDependencies.Add(projectDependency); } } foreach (ReferenceBase reference in References) { // skip non-project reference ProjectReferenceBase projectReference = reference as ProjectReferenceBase; if (projectReference == null) { continue; } // check if we're dealing with reference to VC++ project VcProject vcProject = projectReference.Project as VcProject; if (vcProject == null) { continue; } // skip projects that have already been added to collection if (vcProjectDependencies.Contains(vcProject)) { continue; } vcProjectDependencies.Add(vcProject); } return vcProjectDependencies; } #endregion Private Instance Methods #region Public Static Methods public static string LoadGuid(XmlElement xmlDefinition) { return xmlDefinition.GetAttribute("ProjectGUID"); } /// /// Returns a value indicating whether the project represented by the /// specified XML fragment is supported by . /// /// XML fragment representing the project to check. /// /// if supports the /// specified project; otherwise, . /// /// /// /// A project is identified as as Visual C++ project, if the XML /// fragment at least has the following information: /// /// /// /// /// ]]> /// /// public static bool IsSupported(XmlElement docElement) { if (docElement == null) { return false; } if (docElement.Name != "VisualStudioProject") { return false; } XmlAttribute projectTypeAttribute = docElement.Attributes["ProjectType"]; if (projectTypeAttribute == null || projectTypeAttribute.Value != "Visual C++") { return false; } //MAL 2007/12/20 //this is double check - really needed? In addition, when version check fails, it gives odd error. //2nd check is made in DetermineProductVersion (called from ProjectBase constructor) //try { // GetProductVersion(docElement); // // no need to perform version check here as this is done in // // GetProductVersion //} catch { // // product version could not be determined or is not supported // return false; //} return true; } #endregion Public Static Methods #region Private Static Methods /// /// Removes leading and trailing quotes from the specified path. /// /// The path to clean. private static string CleanPath(string path) { string cleanedPath = path.TrimStart('\"'); return cleanedPath.TrimEnd('\"'); } /// /// Returns the Visual Studio product version of the specified project /// XML fragment. /// /// XML fragment representing the project to check. /// /// The Visual Studio product version of the specified project XML /// fragment. /// /// /// The product version could not be determined. /// -or- /// The product version is not supported. /// private static ProductVersion GetProductVersion(XmlElement docElement) { if (docElement == null) { throw new ArgumentNullException("docElement"); } XmlAttribute productVersionAttribute = docElement.Attributes["Version"]; if (productVersionAttribute == null) { throw new BuildException("The \"Version\" attribute is" + " missing from the node.", Location.UnknownLocation); } // check if we're dealing with a valid version number Version productVersion = null; try { string ver = productVersionAttribute.Value; ver = ver.Replace(',', '.'); //Whidbey (8,00) and Orcas (9,00) are using comma instead of point productVersion = new Version(ver); } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "The value of the \"Version\" attribute ({0}) is not a valid" + " version string.", productVersionAttribute.Value), Location.UnknownLocation, ex); } switch(productVersion.Major) { case 7: switch (productVersion.Minor) { case 0: return ProductVersion.Rainier; case 10: return ProductVersion.Everett; } break; case 8: return ProductVersion.Whidbey; case 9: return ProductVersion.Orcas; } throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Visual Studio version \"{0}\" is not supported.", productVersion.ToString()), Location.UnknownLocation); } #endregion Private Static Methods #region Private Instance Fields private readonly string _name; private readonly string _projectPath; private string _guid; private readonly ArrayList _references; private readonly VcArgumentMap _clArgMap; private readonly VcArgumentMap _linkerArgMap; private readonly VcArgumentMap _midlArgMap; /// /// Holds the files included in the project. /// /// /// /// For project files with no specific file configuration, the relative /// path is added to the list. /// /// /// For project files that have a specific file configuration, a /// containing the /// instance representing the file configurations is added. /// /// private readonly ArrayList _projectFiles; #endregion Private Instance Fields #region Private Static Fields private static string[] _defaultLibraries = new string[] { "kernel32.lib", "user32.lib", "gdi32.lib", "winspool.lib", "comdlg32.lib", "advapi32.lib", "shell32.lib", "ole32.lib", "oleaut32.lib", "uuid.lib", "odbc32.lib", "odbccp32.lib" }; #endregion Private Static Fields } } nant-0.92-rc1/src/NAnt.VSNet/ConfigurationMap.cs0000644000175000017500000001500211757302274021250 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2008 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net.be) using System; using System.Collections; using System.Collections.Specialized; using System.Globalization; namespace NAnt.VSNet { public sealed class ConfigurationMap : IDictionary, ICollection, IEnumerable { #region Private Instance Fields private readonly Hashtable _innerHash; #endregion Private Instance Fields #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public ConfigurationMap() { _innerHash = CollectionsUtil.CreateCaseInsensitiveHashtable(); } /// /// Initializes a new instance of the /// class with the specified initial capacity. /// /// The appropriate number of entries that the can initially contain. public ConfigurationMap(int capacity) { _innerHash = CollectionsUtil.CreateCaseInsensitiveHashtable(capacity); } #endregion Public Instance Constructors #region Internal Instance Properties internal Hashtable InnerHash { get { return _innerHash; } } #endregion Internal Instance Properties #region Implementation of IDictionary public ConfigurationMapEnumerator GetEnumerator() { return new ConfigurationMapEnumerator(this); } IDictionaryEnumerator IDictionary.GetEnumerator() { return GetEnumerator (); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Remove(Configuration configuration) { _innerHash.Remove(configuration); } void IDictionary.Remove(object key) { Remove((Configuration) key); } public bool Contains(Configuration key) { return _innerHash.Contains(key); } bool IDictionary.Contains(object key) { return Contains((Configuration) key); } public void Clear() { _innerHash.Clear(); } public void Add(Configuration key, Configuration value) { _innerHash.Add (key, value); } void IDictionary.Add(object key, object value) { Add((Configuration) key, (Configuration) value); } public bool IsReadOnly { get { return _innerHash.IsReadOnly; } } public Configuration this[Configuration key] { get { return (Configuration) _innerHash[key]; } set { _innerHash[key] = value; } } object IDictionary.this[object key] { get { return this[(Configuration) key]; } set { this[(Configuration) key] = (Configuration) value; } } public ICollection Values { get { return _innerHash.Values; } } public ICollection Keys { get { return _innerHash.Keys; } } public bool IsFixedSize { get { return _innerHash.IsFixedSize; } } #endregion Implementation of IDictionary #region Implementation of ICollection void ICollection.CopyTo(Array array, int index) { _innerHash.CopyTo(array, index); } public bool IsSynchronized { get { return _innerHash.IsSynchronized; } } public int Count { get { return _innerHash.Count; } } public object SyncRoot { get { return _innerHash.SyncRoot; } } #endregion Implementation of ICollection } public class ConfigurationMapEnumerator : IDictionaryEnumerator { #region Private Instance Fields private readonly IDictionaryEnumerator _innerEnumerator; #endregion Private Instance Fields #region Internal Instance Constructors internal ConfigurationMapEnumerator(ConfigurationMap enumerable) { _innerEnumerator = enumerable.InnerHash.GetEnumerator(); } #endregion Internal Instance Constructors #region Implementation of IDictionaryEnumerator public Configuration Key { get { return (Configuration) _innerEnumerator.Key; } } object IDictionaryEnumerator.Key { get { return Key; } } public Configuration Value { get { return (Configuration) _innerEnumerator.Value; } } object IDictionaryEnumerator.Value { get { return Value; } } public DictionaryEntry Entry { get { return new DictionaryEntry (Key, Value); } } #endregion Implementation of IDictionaryEnumerator #region Implementation of IEnumerator public void Reset() { _innerEnumerator.Reset(); } public bool MoveNext() { return _innerEnumerator.MoveNext(); } object IEnumerator.Current { get { return Current; } } public ConfigurationMapEntry Current { get { return new ConfigurationMapEntry (Key, Value); } } #endregion Implementation of IEnumerator } public sealed class ConfigurationMapEntry { private readonly Configuration _key; private readonly Configuration _value; internal ConfigurationMapEntry(Configuration key, Configuration value) { _key = key; _value = value; } public Configuration Key { get { return _key; } } public Configuration Value { get { return _value; } } } } nant-0.92-rc1/src/NAnt.VSNet/Everett/0000755000175000017500000000000011757310030017061 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.VSNet/Everett/SolutionProvider.cs0000644000175000017500000000402311757302274022751 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Martin Aliger (martin_aliger@myrealbox.com) using System; using System.CodeDom.Compiler; using System.Text.RegularExpressions; using System.Xml; using NAnt.Core; using NAnt.Core.Util; using NAnt.VSNet.Extensibility; using NAnt.VSNet.Tasks; namespace NAnt.VSNet.Everett { internal class SolutionProvider : ISolutionBuildProvider { #region Implementation of ISolutionBuildProvider public int IsSupported(string fileContents) { Regex reSolutionFormat = new Regex(@"^\s*Microsoft Visual Studio Solution File, Format Version\s+(?[0-9]+\.[0-9]+)", RegexOptions.Singleline); MatchCollection matches = reSolutionFormat.Matches(fileContents); if (matches.Count == 0) return 0; string formatVersion = matches[0].Groups["formatVersion"].Value; if (formatVersion == "8.00") return 10; return 0; } public SolutionBase GetInstance(string solutionContent, SolutionTask solutionTask, TempFileCollection tfc, GacCache gacCache, ReferencesResolver refResolver) { return new Solution(solutionContent, solutionTask, tfc, gacCache, refResolver); } #endregion Implementation of ISolutionBuildProvider } } nant-0.92-rc1/src/NAnt.VSNet/Everett/Solution.cs0000644000175000017500000001520111757302274021236 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Matthew Mastracci (matt@aclaro.com) // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Text.RegularExpressions; using NAnt.Core; using NAnt.Core.Util; using NAnt.VSNet; using NAnt.VSNet.Tasks; namespace NAnt.VSNet.Everett { /// /// Analyses Microsoft Visual Studio .NET 2003 (Everett) solution files. /// internal class Solution : SolutionBase { public Solution(string solutionContent, SolutionTask solutionTask, TempFileCollection tfc, GacCache gacCache, ReferencesResolver refResolver) : base(solutionTask, tfc, gacCache, refResolver) { Regex reProjects = new Regex(@"Project\(\""(?\{.*?\})\"".*?\""(?.*?)\"".*?\""(?.*?)\"".*?\""(?.*?)\""(?[\s\S]*?)EndProject", RegexOptions.Multiline); MatchCollection projectMatches = reProjects.Matches(solutionContent); Hashtable explicitProjectDependencies = CollectionsUtil.CreateCaseInsensitiveHashtable(); foreach (Match projectMatch in projectMatches) { string project = projectMatch.Groups["project"].Value; string guid = projectMatch.Groups["guid"].Value; // translate partial project path or URL to absolute path string fullProjectPath = TranslateProjectPath(solutionTask.SolutionFile.DirectoryName, project); // check if project file actually exists if (!System.IO.File.Exists(fullProjectPath)) { throw CreateProjectDoesNotExistException(fullProjectPath); } bool isEnterpriseTemplateProject = ManagedProjectBase.IsEnterpriseTemplateProject(fullProjectPath); if (isEnterpriseTemplateProject) { RecursiveLoadTemplateProject(fullProjectPath); } else { // add project entry to collection ProjectEntries.Add(new ProjectEntry(guid, fullProjectPath)); } // set-up project dependencies Regex reDependencies = new Regex(@"^\s+(?\{[0-9a-zA-Z]{8}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{12}\})\s+=\s+(?\{[0-9a-zA-Z]{8}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{12}\})", RegexOptions.Multiline); MatchCollection dependencyMatches = reDependencies.Matches(projectMatch.Value); foreach (Match dependencyMatch in dependencyMatches) { string dependency = dependencyMatch.Groups["dep"].Value; // bug #1534864: an Enterprise Template project actually // defines dependencies for the projects it contains, and // is not added as a project itself // // Note: for non-ET projects both the "guid" and "dep" group // have the same value, which is the guid of the project // that the project containing the dependencies section // depends upon string projectGuid = isEnterpriseTemplateProject ? dependencyMatch.Groups["guid"].Value : guid; if (!explicitProjectDependencies.ContainsKey(projectGuid)) { explicitProjectDependencies[projectGuid] = CollectionsUtil.CreateCaseInsensitiveHashtable(); } ((Hashtable) explicitProjectDependencies[projectGuid])[dependency] = null; } // set-up project configuration Regex reProjectBuildConfig = new Regex(@"^\s+" + guid + @"\.(?[^|]+)\|?(?[^\.]?)\.Build\.0\s*=\s* (?[^|]+)\|(?[\.\w ]+)\s*", RegexOptions.Multiline); MatchCollection projectBuildMatches = reProjectBuildConfig.Matches(solutionContent); ProjectEntry projectEntry = ProjectEntries [guid]; if (projectEntry == null) { // TODO: determine if we should report an error if a build // configuration is defined for a project that does not // exist in the solution continue; } // holds mapping between project configuration(s) and solution(s) ConfigurationMap buildConfigurations = new ConfigurationMap( projectBuildMatches.Count); for (int i = 0; i < projectBuildMatches.Count; i++) { Match projectBuildMatch = projectBuildMatches [i]; string solutionConfigName = projectBuildMatch.Groups["solutionConfiguration"].Value; string solutionPlatform = projectBuildMatch.Groups["solutionPlatform"].Value; string projectConfigName = projectBuildMatch.Groups["projectConfiguration"].Value; string projectPlatform = projectBuildMatch.Groups["projectPlatform"].Value; Configuration solutionConfig = new Configuration( solutionConfigName, solutionPlatform); Configuration projectConfig = new Configuration( projectConfigName, projectPlatform); buildConfigurations [solutionConfig] = projectConfig; } // add map to corresponding project entry projectEntry.BuildConfigurations = buildConfigurations; } LoadProjectGuids(new ArrayList(solutionTask.Projects.FileNames), false); LoadProjectGuids(new ArrayList(solutionTask.ReferenceProjects.FileNames), true); LoadProjects(gacCache, refResolver, explicitProjectDependencies); } } } nant-0.92-rc1/src/NAnt.VSNet/VcArgumentMap.cs0000644000175000017500000006744211757302274020533 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Dmitry Jemerov // Hani Atassi (haniatassi@users.sourceforge.net) using System; using System.Collections; using System.Collections.Specialized; using System.Globalization; using NAnt.Core.Util; using NAnt.VisualCpp.Tasks; using NAnt.VisualCpp.Util; namespace NAnt.VSNet { /// /// A mapping from properties in the .vcproj file to command line arguments. /// public class VcArgumentMap { #region Public Instance Constructors /// /// Initializes a new instance of the /// class. /// public VcArgumentMap() { _htArgs = CollectionsUtil.CreateCaseInsensitiveHashtable(); } #endregion Public Instance Constructors #region Public Instance Methods public void AddString(string propName, string argName) { AddString(ArgGroup.Unassigned, propName, argName); } public void AddString(string propName, string argName, bool ignoreEmptyValue) { AddString(ArgGroup.Unassigned, propName, argName, ignoreEmptyValue); } public void AddString(ArgGroup group, string propName, string argName) { _htArgs [propName] = new VcStringArgument(group, argName); } public void AddString(ArgGroup group, string propName, string argName, bool ignoreEmptyValue) { _htArgs [propName] = new VcStringArgument(group, argName, ignoreEmptyValue); } public void AddLinkerString(string propName, string argName) { AddLinkerString(ArgGroup.Unassigned, propName, argName); } public void AddLinkerString(string propName, string argName, bool ignoreEmptyValue) { AddLinkerString(ArgGroup.Unassigned, propName, argName, ignoreEmptyValue); } public void AddLinkerString(ArgGroup group, string propName, string argName) { _htArgs [propName] = new LinkerStringArgument(group, argName); } public void AddLinkerString(ArgGroup group, string propName, string argName, bool ignoreEmptyValue) { _htArgs [propName] = new LinkerStringArgument(group, argName, ignoreEmptyValue); } public void AddQuotedLinkerString(string propName, string argName) { AddQuotedLinkerString(ArgGroup.Unassigned, propName, argName); } public void AddQuotedLinkerString(string propName, string argName, bool ignoreEmptyValue) { AddQuotedLinkerString(ArgGroup.Unassigned, propName, argName, ignoreEmptyValue); } public void AddQuotedLinkerString(ArgGroup group, string propName, string argName) { _htArgs [propName] = new QuotedLinkerStringArgument(group, argName); } public void AddQuotedLinkerString(ArgGroup group, string propName, string argName, bool ignoreEmptyValue) { _htArgs [propName] = new QuotedLinkerStringArgument(group, argName, ignoreEmptyValue); } public void AddBool(string propName, string argName) { AddBool(ArgGroup.Unassigned, propName, argName); } public void AddBool(string propName, string argName, string match) { AddBool(ArgGroup.Unassigned, propName, argName, match); } public void AddBool(ArgGroup group, string propName, string argName) { _htArgs [propName] = new VcBoolArgument(group, argName); } public void AddBool(ArgGroup group, string propName, string argName, string match) { _htArgs [propName] = new VcBoolArgument(group, argName, match); } public void AddEnum(string propName, string argName, params string[] values) { AddEnum(ArgGroup.Unassigned, propName, argName, values); } public void AddEnum(ArgGroup group, string propName, string argName, params string[] values) { _htArgs [propName] = new VcEnumArgument(group, argName, values); } /// /// Gets the argument string corresponding with a configuration property /// named with value . /// An ignore mask can be used to eliminate some arguments from the search. /// /// The name of the configuration property. /// The value of the configuration property. /// Specify any groups that needs to be ignored. /// /// The argument string corresponding with a configuration property /// named with value , /// or if no corresponding argument exists. /// public string GetArgument(string propName, string propValue, ArgGroup useIgnoreGroup) { VcArgument arg = (VcArgument) _htArgs [propName]; if (arg == null) { return null; } if (arg.Group != ArgGroup.Unassigned && (arg.Group & useIgnoreGroup) != 0) { return null; } return arg.MapValue(propValue); } #endregion Public Instance Methods #region Public Static Methods /// /// Creates a mapping between configuration properties for the Visual /// C++ compiler and corresponding command-line arguments. /// /// /// A mapping between configuration properties for the Visual C++ /// compiler and corresponding command-line arguments. /// /// /// /// The following configuration properties are processed by /// : /// /// /// /// Category /// Property /// /// /// General /// Addtional Include Directories (/I[path]) /// /// /// General /// Resolve #using References (/AI[path]) /// /// /// Preprocessor /// Preprocessor Definitions (/D[macro]) /// /// /// Code Generation /// Enable C++ Exceptions (/EHsc) /// /// /// Precompiled Headers /// Create/Use Precompiled Header /// /// /// Precompiled Headers /// Create/Use PCH Through File /// /// /// Precompiled Headers /// Precompiled Header File /// /// /// Output Files /// Assembler Output /// /// /// Output Files /// ASM List Location /// /// /// Browse Information /// Enable Browse Information /// /// /// Browse Information /// Browse File /// /// /// Advanced /// Force Includes (/FI[name]) /// /// /// Advanced /// Force #using (/FU[name]) /// /// /// Advanced /// Undefine Preprocessor Definitions (/U[macro]) /// /// /// public static VcArgumentMap CreateCLArgumentMap() { VcArgumentMap map = new VcArgumentMap(); // General map.AddEnum("DebugInformationFormat", null, null, "/Z7", "/Zd", "/Zi", "/ZI"); map.AddEnum("CompileAsManaged", null, null, null, "/clr"); // file-level only map.AddEnum("WarningLevel", null, "/W0", "/W1", "/W2", "/W3", "/W4"); map.AddBool("Detect64BitPortabilityProblems", "/Wp64"); map.AddBool("WarnAsError", "/WX"); // Optimization map.AddEnum("Optimization", null, "/Od", "/O1", "/O2", "/Ox"); map.AddBool(ArgGroup.OptiIgnoreGroup, "GlobalOptimizations", "/Og"); map.AddEnum(ArgGroup.OptiIgnoreGroup, "InlineFunctionExpansion", null, "/Ob0", "/Ob1", "/Ob2"); map.AddBool(ArgGroup.OptiIgnoreGroup, "EnableIntrinsicFunctions", "/Oi"); map.AddBool("ImproveFloatingPointConsistency", "/Op"); map.AddEnum("FavorSizeOrSpeed", null, null, "/Ot", "/Os"); map.AddBool(ArgGroup.OptiIgnoreGroup, "OmitFramePointers", "/Oy"); map.AddBool("EnableFiberSafeOptimizations", "/GT"); map.AddEnum("OptimizeForProcessor", null, null, "/G5", "/G6", "/G7"); map.AddBool("OptimizeForWindowsApplication", "/GA"); // Preprocessor map.AddBool("IgnoreStandardIncludePath", "/X"); map.AddEnum("GeneratePreprocessedFile", null, null, "/P", "/EP /P"); map.AddBool("KeepComments", "/C"); // Code Generation map.AddBool(ArgGroup.OptiIgnoreGroup, "StringPooling", "/GF"); map.AddBool("MinimalRebuild", "/Gm"); map.AddBool("SmallerTypeCheck", "/RTCc"); map.AddEnum("BasicRuntimeChecks", null, null, "/RTCs", "/RTCu", "/RTC1"); map.AddEnum("RuntimeLibrary", null, "/MT", "/MTd", "/MD", "/MDd", "/ML", "/MLd"); map.AddEnum("StructMemberAlignment", null, null, "/Zp1", "/Zp2", "/Zp4", "/Zp8", "/Zp16"); map.AddBool("BufferSecurityCheck", "/GS"); map.AddBool(ArgGroup.OptiIgnoreGroup, "EnableFunctionLevelLinking", "/Gy"); map.AddEnum("EnableEnhancedInstructionSet", null, null, "/arch:SSE", "/arch:SSE2"); // Language map.AddBool("DisableLanguageExtensions", "/Za"); map.AddBool("DefaultCharIsUnsigned", "/J"); map.AddBool("TreatWChar_tAsBuiltInType", "/Zc:wchar_t"); map.AddBool("ForceConformanceInForLoopScope", "/Zc:forScope"); map.AddBool("RuntimeTypeInfo", "/GR"); // Output Files map.AddBool("ExpandAttributedSource", "/Fx"); map.AddEnum("AssemblerOutput", null, null, "/FA", "/FAcs", "/FAc", "/FAs"); // Advanced map.AddEnum("CallingConvention", null, null, "/Gr", "/Gz"); map.AddEnum("CompileAs", null, null, "/TC", "/TP"); map.AddBool("ShowIncludes", "/showIncludes"); map.AddBool("UndefineAllPreprocessorDefinitions", "/u"); return map; } /// /// Creates a mapping between configuration properties for the Visual /// C++ linker and corresponding command-line arguments. /// /// /// A mapping between configuration properties for the Visual C++ /// linker and corresponding command-line arguments. /// /// /// /// The following configuration properties are processed by /// : /// /// /// /// Category /// Property /// /// /// General /// Output File (/OUT:[file]) /// /// /// General /// Additional Library Directories (/LIBPATH:[dir]) /// /// /// Input /// Additional Dependencies /// /// /// Input /// Add Module to Assembly (/ASSEMBLYMODULE:file) /// /// /// Input /// Embed Managed Resource File (/ASSEMBLYRESOURCE:file) /// /// /// Debugging /// Generate Debug Info (/DEBUG) /// /// /// Debugging /// Generate Program Database File (/PDB:name) /// /// /// Debugging /// Generate Map File (/MAP) /// /// /// Debugging /// Map File Name (/MAP:[filename]) /// /// /// System /// Heap Reserve Size (/HEAP:reserve) /// /// /// System /// Heap Commit Size (/HEAP:reserve, commit) /// /// /// System /// Stack Reserve Size (/STACK:reserve) /// /// /// System /// Stack Commit Size (/STACK:reserve, commit) /// /// /// /// The following configuration properties are ignored: /// /// /// /// Category /// Property /// /// /// General /// Show Progress (/VERBOSE, /VERBOSE:LIB) /// /// /// General /// Suppress Startup Banner (/NOLOGO) /// /// /// /// Support for the following configuration properties still needs to /// be implemented: /// /// /// /// Category /// Property /// /// /// General /// Ignore Import Library /// /// /// General /// Register Output /// /// /// Input /// Delay Loaded DLLs (/DELAYLOAD:[dll_name]) /// /// /// Embedded IDL /// MIDL Commands (/MIDL:[file]) /// /// /// public static VcArgumentMap CreateLinkerArgumentMap() { VcArgumentMap map = new VcArgumentMap(); // General map.AddEnum("LinkIncremental", null, null, "/INCREMENTAL:NO", "/INCREMENTAL"); map.AddLinkerString("Version", "/VERSION:", true); // Input map.AddBool("IgnoreAllDefaultLibraries", "/NODEFAULTLIB"); map.AddQuotedLinkerString("ModuleDefinitionFile", "/DEF:", true); // Debugging map.AddQuotedLinkerString("StripPrivateSymbols", "/PDBSTRIPPED:", true); map.AddBool("MapExports", "/MAPINFO:EXPORTS"); map.AddBool("MapLines", "/MAPINFO:LINES"); map.AddEnum("AssemblyDebug", null, null, "/ASSEMBLYDEBUG", "/ASSEMBLYDEBUG:DISABLE"); // System map.AddEnum("SubSystem", "/SUBSYSTEM:", null, "CONSOLE", "WINDOWS"); map.AddEnum("LargeAddressAware", null, null, "/LARGEADDRESSAWARE:NO", "/LARGEADDRESSAWARE"); map.AddEnum("TerminalServerAware", null, null, "/TSAWARE:NO", "/TSAWARE"); map.AddBool("SwapRunFromCD", "/SWAPRUN:CD"); map.AddBool("SwapRunFromNet", "/SWAPRUN:NET"); // Optimization map.AddEnum("OptimizeReferences", "/OPT:", null, "NOREF", "REF"); map.AddEnum("EnableCOMDATFolding", "/OPT:", null, "NOICF", "ICF"); map.AddEnum("OptimizeForWindows98", "/OPT:", null, "NOWIN98", "WIN98"); map.AddQuotedLinkerString("FunctionOrder", "/ORDER:", true); // Embedded IDL map.AddBool("IgnoreEmbeddedIDL", "/IGNOREIDL"); map.AddQuotedLinkerString("MergedIDLBaseFileName", "/IDLOUT:", true); map.AddQuotedLinkerString("TypeLibraryFile", "/TLBOUT:", true); map.AddLinkerString("TypeLibraryResourceID", "/TLBID:"); // Advanced map.AddQuotedLinkerString("EntryPointSymbol", "/ENTRY:", true); map.AddBool("ResourceOnlyDLL", "/NOENTRY"); map.AddBool("SetChecksum", "/RELEASE"); map.AddQuotedLinkerString("BaseAddress", "/BASE:", true); map.AddEnum("FixedBaseAddress", null, null, "/FIXED:NO", "/FIXED"); map.AddBool("TurnOffAssemblyGeneration", "/NOASSEMBLY"); map.AddBool("SupportUnloadOfDelayLoadedDLL", "/DELAY:UNLOAD"); map.AddQuotedLinkerString("MergeSections", "/MERGE:", true); map.AddEnum("TargetMachine", null, null, "/MACHINE:X86"); return map; } public static VcArgumentMap CreateMidlArgumentMap() { VcArgumentMap map = new VcArgumentMap(); // General map.AddBool("IgnoreStandardIncludePath", "/no_def_idir"); map.AddBool("MkTypLibCompatible", "/mktyplib203"); map.AddEnum("WarningLevel", null, "/W0", "/W1", "/W2", "/W3", "/W4"); map.AddBool("WarnAsError", "/WX"); map.AddEnum("DefaultCharType", null, "unsigned", "signed", "ascii7"); map.AddEnum("TargetEnvironment", null, null, "win32", "win64"); map.AddBool("GenerateStublessProxies", "/Oicf"); // Output map.AddBool("GenerateTypeLibrary", "/notlb", "false"); // Advanced map.AddEnum("EnableErrorChecks", "/error ", null, "none", "all"); map.AddBool("ErrorCheckAllocations", "/error allocation"); map.AddBool("ErrorCheckBounds", "/error bounds_check"); map.AddBool("ErrorCheckEnumRange", "/error enum"); map.AddBool("ErrorCheckRefPointers", "/error ref"); map.AddBool("ErrorCheckStubData", "/error stub_data"); map.AddBool("ValidateParameters", "/robust"); map.AddEnum("StructMemberAlignment", null, null, "/Zp1", "/Zp2", "/Zp4", "/Zp8"); return map; } #endregion Public Static Methods #region Private Instance Fields private Hashtable _htArgs; #endregion Private Instance Fields private abstract class VcArgument { private string _name; private ArgGroup _group; protected VcArgument(ArgGroup group, string name) { _name = name; _group = group; } /// /// Gets the name of the command-line argument. /// /// /// The name of the command-line argument. /// public string Name { get { return _name; } } public ArgGroup Group { get { return _group; } } internal abstract string MapValue(string propValue); protected string FormatOption(string value) { if (_name == null) { return value; } return _name + value; } } private class VcStringArgument: VcArgument { #region Private Instance Fields private bool _ignoreEmptyValue; #endregion Private Instance Fields #region Internal Instance Constructors internal VcStringArgument(ArgGroup group, string name): this(group, name, false) { } internal VcStringArgument(ArgGroup group, string name, bool ignoreEmptyValue): base(group, name) { _ignoreEmptyValue = ignoreEmptyValue; } #endregion Internal Instance Constructors #region Protected Instance Properties protected bool IgnoreEmptyValue { get { return _ignoreEmptyValue; } } #endregion Protected Instance Properties #region Override implementation of VcArgument internal override string MapValue(string propValue) { if (IgnoreEmptyValue && String.IsNullOrEmpty(propValue)) { return null; } return FormatOption(propValue); } #endregion Override implementation of VcArgument } /// /// Represents a command-line arguments of which the trailing backslashes /// in the value should be duplicated. /// private class LinkerStringArgument: VcStringArgument { #region Internal Instance Constructors internal LinkerStringArgument(ArgGroup group, string name): this(group, name, false) { } internal LinkerStringArgument(ArgGroup group, string name, bool ignoreEmptyValue): base(group, name, ignoreEmptyValue) { } #endregion Internal Instance Constructors #region Override implementation of VcArgument internal override string MapValue(string value) { if (IgnoreEmptyValue && String.IsNullOrEmpty(value)) { return null; } if (Name == null) { return ArgumentUtils.DuplicateTrailingBackslash(value); } return Name + ArgumentUtils.DuplicateTrailingBackslash(value); } #endregion Override implementation of VcArgument } /// /// Represents a command-line argument of which the value should be /// quoted, and of which trailing backslahes should be duplicated. /// private class QuotedLinkerStringArgument: VcStringArgument { #region Internal Instance Constructors internal QuotedLinkerStringArgument(ArgGroup group, string name): this(group, name, false) { } internal QuotedLinkerStringArgument(ArgGroup group, string name, bool ignoreEmptyValue): base(group, name, ignoreEmptyValue) { } #endregion Internal Instance Constructors #region Override implementation of VcArgument internal override string MapValue(string value) { if (IgnoreEmptyValue && String.IsNullOrEmpty(value)) { return null; } if (Name == null) { return LinkTask.QuoteArgumentValue(value); } return Name + LinkTask.QuoteArgumentValue(value); } #endregion Override implementation of VcArgument } private class VcBoolArgument: VcArgument { #region Internal Instance Constructors internal VcBoolArgument(ArgGroup group, string name): this(group, name, "true") { } internal VcBoolArgument(ArgGroup group, string name, string match): base(group, name) { _match = match; } #endregion Internal Instance Constructors #region Internal Instance Properties /// /// Gets the string that the configuration setting should match in /// order for the command line argument to be set. /// public string Match { get { return _match; } } #endregion Internal Instance Properties #region Override implementation of VcArgument internal override string MapValue(string propValue) { if (string.Compare(propValue, Match, true, CultureInfo.InvariantCulture) == 0) { return FormatOption(string.Empty); } return null; } #endregion Override implementation of VcArgument #region Private Instance Methods private string _match = "true"; #endregion Private Instance Methods } private class VcEnumArgument: VcArgument { #region Internal Instance Constructors internal VcEnumArgument(ArgGroup group, string name, string[] values): base(group, name) { _values = values; } #endregion Internal Instance Constructors #region Override implementation of VcArgument internal override string MapValue(string propValue) { int iValue = -1; try { iValue = Int32.Parse(propValue); } catch(FormatException) { return null; } if (iValue < 0 || iValue >= _values.Length || _values [iValue] == null) { return null; } return FormatOption(_values [iValue]); } #endregion Override implementation of VcArgument #region Private Instance Methods private string[] _values; #endregion Private Instance Methods } /// /// Allow us to assign an argument to a specific group. /// [Flags] public enum ArgGroup { /// /// The argument is not assigned to any group. /// Unassigned = 0, /// /// The argument is ignored when the optimization level is set to /// Minimum Size (1) or Maximum Size (2). /// OptiIgnoreGroup = 1 } } } nant-0.92-rc1/src/NAnt.VSNet/VcFileConfiguration.cs0000644000175000017500000002402611757302274021711 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2005 Gert Driesen // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Xml; using NAnt.Core; using NAnt.Core.Util; using NAnt.VSNet.Types; namespace NAnt.VSNet { /// /// Represents the configuration of a file. /// public class VcFileConfiguration : VcConfigurationBase { #region Internal Instance Constructors internal VcFileConfiguration(string relativePath, string parentName, XmlElement elem, VcProjectConfiguration parentConfig, DirectoryInfo outputDir) : base(elem, parentConfig.Project, outputDir) { if (relativePath == null) { throw new ArgumentNullException("relativePath"); } if (parentName == null) { throw new ArgumentNullException("parentName"); } if (parentConfig == null) { throw new ArgumentNullException("parentConfig"); } _relativePath = relativePath; _parentName = parentName; string excludeFromBuild = elem.GetAttribute("ExcludedFromBuild"); if (excludeFromBuild.Length != 0) { _excludeFromBuild = string.Compare(excludeFromBuild.Trim(), "true", true, CultureInfo.InvariantCulture) == 0; } _parentConfig = parentConfig; } internal VcFileConfiguration(string relativePath, string parentName, VcProjectConfiguration parentConfig, DirectoryInfo outputDir) : base(parentConfig.Name, parentConfig.Project, outputDir) { if (relativePath == null) { throw new ArgumentNullException("relativePath"); } if (parentName == null) { throw new ArgumentNullException("parentName"); } if (parentConfig == null) { throw new ArgumentNullException("parentConfig"); } _relativePath = relativePath; _parentName = parentName; _parentConfig = parentConfig; } #endregion Internal Instance Constructors #region Public Instance Properties /// /// Gets a value indication whether the file should be excluded from /// the build for this configuration. /// /// /// if the file should be excluded from the /// build for this configuration; otherwise, . /// public bool ExcludeFromBuild { get { return _excludeFromBuild; } } /// /// Gets the relative path of the file. /// /// /// The path of the file relative to the project directory. /// public string RelativePath { get { return _relativePath; } } #endregion Public Instance Properties #region Override implementation of ConfigurationBase /// /// Get the path of the output directory relative to the project /// directory. /// public override string RelativeOutputDir { get { return ExpandMacros(_parentConfig.RawRelativeOutputDir) ; } } /// /// Expands the given macro. /// /// The macro to expand. /// /// The expanded macro. /// /// /// The macro is not supported. /// -or- /// The macro is not implemented. /// -or- /// The macro cannot be expanded. /// protected internal override string ExpandMacro(string macro) { // perform case-insensitive expansion of macros switch (macro.ToLower(CultureInfo.InvariantCulture)) { case "inputdir": return Path.GetDirectoryName(FileUtils.CombinePaths(Project.ProjectDirectory.FullName, _relativePath)) + Path.DirectorySeparatorChar; case "inputname": return Path.GetFileNameWithoutExtension(_relativePath); case "inputpath": return FileUtils.CombinePaths(Project.ProjectDirectory.FullName, _relativePath); case "inputfilename": return Path.GetFileName(_relativePath); case "inputext": return Path.GetExtension(_relativePath); case "safeparentname": return _parentName.Replace(" ", string.Empty); case "safeinputname": return Path.GetFileNameWithoutExtension(_relativePath); default: return _parentConfig.ExpandMacro(macro); } } #endregion Override implementation of ConfigurationBase #region Override implementation of VcConfigurationBase /// /// Gets the intermediate directory, specified relative to project /// directory. /// /// /// The intermediate directory, specified relative to project directory. /// public override string IntermediateDir { get { return ExpandMacros(_parentConfig.RawIntermediateDir); } } /// /// Gets the path for the output file. /// /// /// The path for the output file, or if there's /// no output file for this configuration. /// public override string OutputPath { get { return _parentConfig.OutputPath; } } /// /// Gets a comma-separated list of directories to scan for assembly /// references. /// /// /// A comma-separated list of directories to scan for assembly /// references, or if no additional directories /// should scanned. /// public override string ReferencesPath { get { return ExpandMacros(_parentConfig.RawReferencesPath); } } /// /// Gets the value of a given setting for a specified tool. /// /// The name of the tool. /// The name of the setting. /// The value to return if setting is not defined in both the file and project configuration. /// /// The value of a setting for the specified tool, or /// if the setting is not defined in /// both the file and project configuration. /// /// /// /// If the setting is not defined in the file configuration, then /// the project level setting will be used. /// /// /// An empty setting value, which is used as a means to override the /// project default, will be returned as a empty . /// /// public override string GetToolSetting(string toolName, string settingName, string projectDefault) { string setting = null; Hashtable toolSettings = (Hashtable) Tools[toolName]; if (toolSettings != null) { setting = (string) toolSettings[settingName]; if (setting != null) { // expand macros return ExpandMacros(setting); } } setting = _parentConfig.GetToolSetting(toolName, settingName, projectDefault, new ExpansionHandler(ExpandMacros)); return setting; } public override Hashtable GetToolArguments(string toolName, VcArgumentMap argMap, VcArgumentMap.ArgGroup ignoreGroup) { ExpansionHandler expander = new ExpansionHandler(ExpandMacros); Hashtable args; if (_parentConfig != null) { args = _parentConfig.GetToolArguments(toolName, argMap, ignoreGroup, expander); } else { args = CollectionsUtil.CreateCaseInsensitiveHashtable(); } Hashtable toolSettings = (Hashtable) Tools[toolName]; if (toolSettings != null) { foreach (DictionaryEntry de in toolSettings) { string arg = argMap.GetArgument((string) de.Key, ExpandMacros((string) de.Value), ignoreGroup); if (arg != null) { args[(string) de.Key] = arg; } } } return args; } #endregion Override implementation of VcConfigurationBase #region Private Instance Fields private readonly string _relativePath; private readonly string _parentName; private readonly bool _excludeFromBuild; private readonly VcProjectConfiguration _parentConfig; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.VSNet/ConfigurationBase.cs0000644000175000017500000002130611757302274021411 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Text.RegularExpressions; using NAnt.Core; using NAnt.Core.Util; using NAnt.VSNet.Tasks; namespace NAnt.VSNet { public abstract class ConfigurationBase { #region Protected Instance Constructors /// /// Initializes a new instance of the /// class with the given . /// /// The project of the configuration. protected ConfigurationBase(ProjectBase project) { if (project == null) { throw new ArgumentNullException("project"); } _project = project; _extraOutputFiles = CollectionsUtil.CreateCaseInsensitiveHashtable(); } #endregion Protected Instance Constructors #region Public Instance Properties /// /// Gets the project. /// public ProjectBase Project { get { return _project;} } /// /// Gets the name of the configuration. /// public abstract string Name { get; } /// /// Get the directory in which intermediate build output will be stored /// for this configuration. /// /// /// /// This is a directory relative to the project directory named /// obj\<configuration name>. /// /// /// .resx and .licx files will only be recompiled if the /// compiled resource files in the are not /// uptodate. /// /// public virtual DirectoryInfo ObjectDir { get { return new DirectoryInfo(FileUtils.CombinePaths(Project.ObjectDir.FullName, Name)); } } /// /// Gets the output directory. /// public abstract DirectoryInfo OutputDir { get; } /// /// Gets the path for the output file. /// public abstract string OutputPath { get; } /// /// Gets the path in which the output file will be created before its /// copied to the actual output path. /// public abstract string BuildPath { get; } /// /// Get the path of the output directory relative to the project /// directory. /// public abstract string RelativeOutputDir { get; } /// /// Gets the platform that the configuration targets. /// /// /// The platform targeted by the configuration. /// public abstract string PlatformName { get; } /// /// Gets the set of output files that is specific to the project /// configuration. /// /// /// The set of output files that is specific to the project /// configuration. /// /// /// The key of the case-insensitive is the /// full path of the output file and the value is the path relative to /// the output directory. /// public Hashtable ExtraOutputFiles { get { return _extraOutputFiles; } } #endregion Public Instance Properties #region Protected Instance Properties protected SolutionTask SolutionTask { get { return Project.SolutionTask; } } #endregion Protected Instance Properties #region Public Instance Methods public string ExpandMacros(string s) { if (s == null) { return s; } return _rxMacro.Replace(s, new MatchEvaluator(EvaluateMacro)); } #endregion Public Instance Methods #region Protected Instance Methods /// /// Expands the given macro. /// /// The macro to expand. /// /// The expanded macro. /// /// /// The macro is not supported. /// -or- /// The macro is not implemented. /// -or- /// The macro cannot be expanded. /// /// /// Expansion of a given macro is not yet implemented. /// protected internal virtual string ExpandMacro(string macro) { // perform case-insensitive expansion of macros switch (macro.ToLower(CultureInfo.InvariantCulture)) { case "outdir": // E.g. bin\Debug\ return RelativeOutputDir; case "configurationname": // E.g. Debug return Name; case "targetname": // E.g. WindowsApplication1 return Path.GetFileNameWithoutExtension(Path.GetFileName( OutputPath)); case "targetpath": // E.g. C:\Doc...\Visual Studio Projects\WindowsApplications1\bin\Debug\WindowsApplications1.exe return OutputPath; case "targetext": // E.g. .exe return Path.GetExtension(OutputPath); case "targetfilename": // E.g. WindowsApplications1.exe return Path.GetFileName(OutputPath); case "targetdir": // Absolute path to OutDir return OutputDir.FullName + (OutputDir.FullName.EndsWith( Path.DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture)) ? string.Empty : Path.DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture)); case "platformname": // .NET, does this value ever change? return PlatformName; } // expand using solution level macro's string expandedMacro = Project.SolutionTask.ExpandMacro(macro); if (expandedMacro != null) { return expandedMacro; } // expand using project level macro's expandedMacro = Project.ExpandMacro(macro); if (expandedMacro != null) { return expandedMacro; } throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Macro \"{0}\" is not supported.", macro), Location.UnknownLocation); } #endregion Protected Instance Methods #region Private Instance Methods /// /// Is called each time a regular expression match is found during a /// operation. /// /// The resulting from a single regular expression match during a . /// /// The expanded . /// private string EvaluateMacro(Match m) { return ExpandMacro(m.Groups[1].Value); } #endregion Private Instance Methods #region Private Instance Fields private readonly ProjectBase _project; private readonly Regex _rxMacro = new Regex(@"\$\((\w+)\)"); private Hashtable _extraOutputFiles; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.VSNet/ManagedAssemblyReference.cs0000644000175000017500000003351311757302274022665 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Xml; using Microsoft.Win32; using NAnt.Core; using NAnt.Core.Util; using NAnt.VSNet.Tasks; namespace NAnt.VSNet { public class ManagedAssemblyReference : AssemblyReferenceBase { public ManagedAssemblyReference(XmlElement xmlDefinition, ReferencesResolver referencesResolver, ProjectBase parent, GacCache gacCache) : base(xmlDefinition, referencesResolver, parent, gacCache) { XmlAttribute privateAttribute = xmlDefinition.Attributes["Private"]; if (privateAttribute != null) { _isPrivateSpecified = true; _isPrivate = bool.Parse(privateAttribute.Value); } // determine name of reference XmlAttribute assemblyNameAttribute = XmlDefinition.Attributes["AssemblyName"]; if (assemblyNameAttribute != null) { _name = assemblyNameAttribute.Value; } _assemblyFile = ResolveAssemblyReference(); } #region Override implementation of AssemblyReferenceBase protected override bool IsPrivate { get { return _isPrivate; } } protected override bool IsPrivateSpecified { get { return _isPrivateSpecified; } } /// /// Resolves an assembly reference. /// /// /// The full path to the resolved assembly, or /// if the assembly reference could not be resolved. /// /// /// /// Visual Studio .NET uses the following search mechanism : /// /// /// /// /// The project directory. /// /// /// /// /// The directories specified in the "ReferencePath" property, /// which is stored in the .USER file. /// /// /// /// /// The .NET Framework directory (see KB306149) /// /// /// /// /// /// The directories specified under the following registry /// keys: /// /// /// /// /// HKLM\SOFTWARE\Microsoft\.NETFramework\AssemblyFolders /// /// /// /// /// HKCU\SOFTWARE\Microsoft\.NETFramework\AssemblyFolders /// /// /// /// /// HKLM\SOFTWARE\Microsoft\VisualStudio\<major version>.<minor version>\AssemblyFolders /// /// /// /// /// HKCU\SOFTWARE\Microsoft\VisualStudio\<major version>.<minor version>\AssemblyFolders /// /// /// /// /// Future versions of Visual Studio .NET will also check /// in: /// /// /// /// /// HKLM\SOFTWARE\Microsoft\.NETFramework\AssemblyFoldersEx /// /// /// /// /// HKCU\SOFTWARE\Microsoft\.NETFramework\AssemblyFoldersEx /// /// /// /// /// /// /// /// The HintPath. /// /// /// /// protected override string ResolveAssemblyReference() { // check if assembly reference was resolved before if (_assemblyFile != null) { // if assembly file actually exists, there's no need to resolve // the assembly reference again if (File.Exists(_assemblyFile)) { return _assemblyFile; } } XmlElement referenceElement = XmlDefinition; string assemblyFileName = Name + ".dll"; // 1. The project directory // NOT SURE IF THIS IS CORRECT // 2. The ReferencePath // NOT SURE WE SHOULD DO THIS ONE // 3. The .NET Framework directory string resolvedAssemblyFile = ResolveFromFramework(assemblyFileName); if (resolvedAssemblyFile != null) { return resolvedAssemblyFile; } // 4. AssemblyFolders resolvedAssemblyFile = ResolveFromAssemblyFolders(referenceElement, assemblyFileName); if (resolvedAssemblyFile != null) { return resolvedAssemblyFile; } // ResolveFromRelativePath will return a path regardless of // whether the file actually exists // // the file might actually be created as result of building // a project resolvedAssemblyFile = ResolveFromRelativePath( referenceElement.GetAttribute("HintPath")); if (resolvedAssemblyFile != null) { return resolvedAssemblyFile; } // assembly reference could not be resolved return null; } #endregion Override implementation of AssemblyReferenceBase #region Override implementation of ReferenceBase /// /// Gets the name of the referenced assembly. /// /// /// The name of the referenced assembly, or if /// the name could not be determined. /// public override string Name { get { return _name; } } #endregion Override implementation of ReferenceBase #region Private Instance Properties /// /// Gets the Visual Studio .NET AssemblyFolders registry key matching /// the current target framework. /// /// /// The Visual Studio .NET AssemblyFolders registry key matching the /// current target framework. /// /// The current target framework is not supported. /// /// We use the target framework instead of the product version of the /// containing project file to determine what registry key to scan, as /// we don't want to use assemblies meant for uplevel framework versions. /// private string AssemblyFoldersKey { get { string visualStudioVersion = Parent.SolutionTask.Project. TargetFramework.VisualStudioVersion.ToString(); return string.Format(CultureInfo.InvariantCulture, @"SOFTWARE\Microsoft\VisualStudio\{0}\AssemblyFolders", visualStudioVersion); } } #endregion Private Instance Properties #region Private Instance Methods private string GetComponentAssemblyFolder(XmlElement referenceElement) { string componentAssemblyFolder = null; if (referenceElement.Attributes["AssemblyFolderKey"] != null) { string assemblyFolderKey = referenceElement.Attributes["AssemblyFolderKey"].Value; RegistryKey registryHive = null; string[] assemblyFolderKeyParts = assemblyFolderKey.Split('\\'); if (assemblyFolderKeyParts.Length < 2 || assemblyFolderKeyParts.Length > 3) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Invalid AssemblyFolderKey \"{0}\" for assembly" + " reference \"{1}\", referenced by project" + " \"{2}\".", assemblyFolderKey, Name, Parent.Name), Location.UnknownLocation); } switch (assemblyFolderKeyParts[0]) { case "hklm": registryHive = Registry.LocalMachine; break; case "hkcu": registryHive = Registry.CurrentUser; break; default: throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Invalid AssemblyFolderKey \"{0}\" for assembly" + " reference \"{1}\", referenced by project" + " \"{2}\".", assemblyFolderKey, Name, Parent.Name), Location.UnknownLocation); } RegistryKey repositoryKey = null; // if AssemblyFolderKey has three parts, then the second // parts specifies the registry key to search if (assemblyFolderKeyParts.Length == 3) { switch (assemblyFolderKeyParts[1]) { case "dn": repositoryKey = registryHive.OpenSubKey(@"SOFTWARE\Microsoft\.NETFramework\AssemblyFolders"); break; default: throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Invalid AssemblyFolderKey \"{0}\" for assembly" + " reference \"{1}\", referenced by project" + " \"{2}\".", assemblyFolderKey, Name, Parent.Name), Location.UnknownLocation); } } else { repositoryKey = registryHive.OpenSubKey(AssemblyFoldersKey); } if (repositoryKey != null) { RegistryKey componentKey = repositoryKey.OpenSubKey( assemblyFolderKeyParts[assemblyFolderKeyParts.Length - 1]); if (componentKey != null) { string folder = componentKey.GetValue(string.Empty) as string; if (folder != null) { componentAssemblyFolder = folder; } else { Log(Level.Debug, "Default value for AssemblyFolder" + " \"{0}\" does not exist or is not a string" + " value.", assemblyFolderKey); } } else { Log(Level.Debug, "Component key for AssemblyFolder \"{0}\"" + " does not exist.", assemblyFolderKey); } } else { Log(Level.Debug, "Repository for AssemblyFolder \"{0}\" does" + " not exist.", assemblyFolderKey); } } return componentAssemblyFolder; } protected override string ResolveFromAssemblyFolders(XmlElement referenceElement, string fileName) { string resolvedAssemblyFile = null; string componentAssemblyFolder = GetComponentAssemblyFolder( referenceElement); if (componentAssemblyFolder != null) { StringCollection folderList = new StringCollection(); folderList.Add(componentAssemblyFolder); resolvedAssemblyFile = ResolveFromFolderList(folderList, fileName); } if (resolvedAssemblyFile == null) { resolvedAssemblyFile = base.ResolveFromAssemblyFolders( referenceElement, fileName); } return resolvedAssemblyFile; } #endregion Private Instance Methods #region Private Instance Fields private readonly string _assemblyFile; private readonly bool _isPrivateSpecified; private readonly bool _isPrivate; private readonly string _name = string.Empty; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.VSNet/JSharpProject.cs0000644000175000017500000002217111757302274020526 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Laurent Arnal (laurent@clae.net) using System; using System.CodeDom.Compiler; using System.Diagnostics; using System.Globalization; using System.IO; using System.Xml; using NAnt.Core; using NAnt.Core.Util; using NAnt.VSNet.Tasks; namespace NAnt.VSNet { public class JSharpProject : ManagedProjectBase { #region Public Instance Constructors public JSharpProject(SolutionBase solution, string projectPath, XmlElement xmlDefinition, SolutionTask solutionTask, TempFileCollection tfc, GacCache gacCache, ReferencesResolver refResolver, DirectoryInfo outputDir) : base(solution, projectPath, xmlDefinition, solutionTask, tfc, gacCache, refResolver, outputDir) { } #endregion Public Instance Constructors #region Override implementation of ProjectBase /// /// Gets the type of the project. /// /// /// The type of the project. /// public override ProjectType Type { get { return ProjectType.JSharp; } } /// /// Verifies whether the specified XML fragment represents a valid project /// that is supported by this . /// /// XML fragment representing the project file. /// /// The XML fragment is not supported by this . /// -or- /// The XML fragment does not represent a valid project (for this ). /// protected override void VerifyProjectXml(XmlElement docElement) { if (!IsSupported(docElement)) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Project '{0}' is not a valid J# project.", ProjectPath), Location.UnknownLocation); } } /// /// Returns the Visual Studio product version of the specified project /// XML fragment. /// /// The document element of the project. /// /// The Visual Studio product version of the specified project XML /// fragment. /// /// /// The product version could not be determined. /// -or- /// The product version is not supported. /// protected override ProductVersion DetermineProductVersion(XmlElement docElement) { return GetProductVersion(docElement.SelectSingleNode("./VISUALJSHARP")); } /// /// Prepares the project for being built. /// /// The solution configuration that is built. /// /// Ensures the configuration-level object directory exists and ensures /// that none of the output files are marked read-only. /// protected override void Prepare(Configuration solutionConfiguration) { // Visual J#.NET uses the \obj\ // as working directory, so we should do the same to make // sure relative paths are resolved correctly // (eg. AssemblyKeyFile attribute) // obtain project configuration (corresponding with solution configuration) ConfigurationBase config = BuildConfigurations[solutionConfiguration]; // ensure configuration-level object directory exists if (!config.ObjectDir.Exists) { config.ObjectDir.Create(); config.ObjectDir.Refresh(); } } /// /// Returns a for launching the compiler /// for this project. /// /// The configuration to build. /// The response file for the compiler. /// /// A for launching the compiler for /// this project. /// protected override ProcessStartInfo GetProcessStartInfo(ConfigurationBase config, string responseFile) { ProcessStartInfo psi = new ProcessStartInfo(FileUtils.CombinePaths(SolutionTask. Project.TargetFramework.FrameworkDirectory.FullName, "vjc.exe"), "@\"" + responseFile + "\""); // to resolve the path to the file specified in the AssemblyKeyFile // attribute, the command line compilers try to resolve that relative // path using the output directory and the current directory // // VS.NET compiles assembly to the intermediate output directory and // uses the solution directory as current directory if (SolutionTask.SolutionFile != null) { psi.WorkingDirectory = Path.GetDirectoryName(SolutionTask.SolutionFile.FullName); } else { psi.WorkingDirectory = ProjectDirectory.FullName; } return psi; } #endregion Override implementation of ProjectBase #region Override implementation of ManagedProjectBase /// /// Gets the default file extension of sources for this project. /// /// /// For J# projects, the default file extension is ".jsl". /// protected override string FileExtension { get { return ".jsl"; } } /// /// Returns the project location from the specified project XML fragment. /// /// XML fragment representing the project file. /// /// The project location of the specified project XML file. /// /// /// The project location could not be determined. /// -or- /// The project location is invalid. /// protected override ProjectLocation DetermineProjectLocation(XmlElement docElement) { return GetProjectLocation(docElement.SelectSingleNode("./VISUALJSHARP")); } #endregion Override implementation of ManagedProjectBase #region Public Static Methods /// /// Returns a value indicating whether the project represented by the /// specified XML fragment is supported by . /// /// XML fragment representing the project to check. /// /// if supports /// the specified project; otherwise, . /// /// /// /// A project is identified as as J# project, if the XML fragment at /// least has the following information: /// /// /// /// /// ... /// /// /// ]]> /// /// public static bool IsSupported(XmlElement docElement) { if (docElement == null) { return false; } if (docElement.Name != "VisualStudioProject") { return false; } XmlNode projectNode = docElement.SelectSingleNode("./VISUALJSHARP"); if (projectNode == null) { return false; } try { GetProductVersion(projectNode); // no need to perform version check here as this is done in // GetProductVersion } catch { // product version could not be determined or is not supported return false; } return true; } #endregion Public Static Methods } } nant-0.92-rc1/src/NAnt.VSNet/ManagedProjectBase.cs0000644000175000017500000016725111757302274021477 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Matthew Mastracci (matt@aclaro.com) using System; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Specialized; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; using System.Xml; using NAnt.Core; using NAnt.Core.Tasks; using NAnt.Core.Types; using NAnt.Core.Util; using NAnt.DotNet.Tasks; using NAnt.DotNet.Types; using NAnt.Win32.Tasks; using NAnt.VSNet.Tasks; namespace NAnt.VSNet { public abstract class ManagedProjectBase : ProjectBase { #region Public Instance Constructors protected ManagedProjectBase(SolutionBase solution, string projectPath, XmlElement xmlDefinition, SolutionTask solutionTask, TempFileCollection tfc, GacCache gacCache, ReferencesResolver refResolver, DirectoryInfo outputDir) : base(xmlDefinition, solutionTask, tfc, gacCache, refResolver, outputDir) { if (projectPath == null) { throw new ArgumentNullException("projectPath"); } if (xmlDefinition == null) { throw new ArgumentNullException("xmlDefinition"); } _references = new ArrayList(); _neutralResources = new ArrayList(); _localizedResources = new ArrayList(); _sourceFiles = CollectionsUtil.CreateCaseInsensitiveHashtable(); _projectPath = projectPath; _projectLocation = DetermineProjectLocation(xmlDefinition); if (!IsWebProject) { _projectDirectory = new FileInfo(projectPath).Directory; } else { string projectDirectory = projectPath.Replace(":", "_"); projectDirectory = projectDirectory.Replace("/", "_"); projectDirectory = projectDirectory.Replace("\\", "_"); _projectDirectory = new DirectoryInfo(FileUtils.CombinePaths( TemporaryFiles.BasePath, projectDirectory)); // ensure project directory exists if (!_projectDirectory.Exists) { _projectDirectory.Create(); _projectDirectory.Refresh(); } _webProjectBaseUrl = projectPath.Substring(0, projectPath.LastIndexOf("/")); } _projectSettings = new ProjectSettings(xmlDefinition, (XmlElement) xmlDefinition.SelectSingleNode("//Build/Settings"), this); XmlNodeList nlConfigurations = xmlDefinition.SelectNodes("//Config"); foreach (XmlElement elemConfig in nlConfigurations) { ConfigurationSettings cs = new ConfigurationSettings(this, elemConfig, OutputDir); ProjectConfigurations[Configuration.Parse(cs.Name)] = cs; } XmlNodeList nlReferences = xmlDefinition.SelectNodes("//References/Reference"); foreach (XmlElement elemReference in nlReferences) { ReferenceBase reference = CreateReference(solution, elemReference); _references.Add(reference); } XmlNodeList nlFiles = xmlDefinition.SelectNodes("//Files/Include/File"); foreach (XmlElement elemFile in nlFiles) { string buildAction = StringUtils.ConvertEmptyToNull(elemFile.GetAttribute("BuildAction")); string sourceFile; if (!String.IsNullOrEmpty(elemFile.GetAttribute("Link"))) { sourceFile = FileUtils.GetFullPath(FileUtils.CombinePaths( ProjectDirectory.FullName, elemFile.GetAttribute("Link"))); } else { sourceFile = FileUtils.GetFullPath(FileUtils.CombinePaths( ProjectDirectory.FullName, elemFile.GetAttribute("RelPath"))); } if (IsWebProject) { WebDavClient wdc = new WebDavClient(new Uri(_webProjectBaseUrl)); wdc.DownloadFile(sourceFile, elemFile.Attributes["RelPath"].Value); switch (buildAction) { case "Compile": _sourceFiles[sourceFile] = null; break; case "EmbeddedResource": RegisterEmbeddedResource(sourceFile, elemFile); break; case null: if (string.Compare(Path.GetExtension(sourceFile), FileExtension, true, CultureInfo.InvariantCulture) == 0) { _sourceFiles[sourceFile] = null; } break; } } else { switch (buildAction) { case "Compile": _sourceFiles[sourceFile] = null; break; case "EmbeddedResource": RegisterEmbeddedResource(sourceFile, elemFile); break; case null: if (string.Compare(Path.GetExtension(sourceFile), FileExtension, true, CultureInfo.InvariantCulture) == 0) { _sourceFiles[sourceFile] = null; } break; } // check if file is "App.config" (using case-insensitive comparison) if (string.Compare("App.config", elemFile.GetAttribute("RelPath"), true, CultureInfo.InvariantCulture) == 0) { // App.config is only an output file for executable projects if (ProjectSettings.OutputType == ManagedOutputType.Executable || ProjectSettings.OutputType == ManagedOutputType.WindowsExecutable) { ExtraOutputFiles[sourceFile] = ProjectSettings.OutputFileName + ".config"; } } } } } #endregion Public Instance Constructors #region Public Instance Properties public ProjectSettings ProjectSettings { get { return _projectSettings; } } #endregion Public Instance Properties #region Protected Instance Properties /// /// Gets the default file extension of sources for this project. /// /// /// The default file extension of sources for this project. /// protected abstract string FileExtension { get; } #endregion Protected Instance Properties #region Private Instance Properties /// /// Gets a value indicating if this is a web project. /// /// /// if this is a web project; otherwise, /// . /// /// /// If the url of a web project has been mapped to a local path /// (using the <webmap> element), then this property will return /// for a /// project. /// private bool IsWebProject { get { return ProjectFactory.IsUrl(_projectPath); } } #endregion Private Instance Properties #region Override implementation of ProjectBase /// /// Gets the name of the VS.NET project. /// public override string Name { get { string projectPath; if (ProjectFactory.IsUrl(_projectPath)) { // construct uri for project path Uri projectUri = new Uri(_projectPath); // get last segment of the uri (which should be the // project file itself) projectPath = projectUri.LocalPath; } else { projectPath = ProjectPath; } // return file part without extension return Path.GetFileNameWithoutExtension(projectPath); } } /// /// Gets the path of the VS.NET project. /// public override string ProjectPath { get { if (ProjectFactory.IsUrl(_projectPath)) { return _projectPath; } else { return FileUtils.GetFullPath(_projectPath); } } } /// /// Gets the directory containing the VS.NET project. /// public override DirectoryInfo ProjectDirectory { get { return _projectDirectory; } } /// /// Get the location of the project. /// public override ProjectLocation ProjectLocation { get { return _projectLocation; } } /// /// Gets or sets the unique identifier of the VS.NET project. /// public override string Guid { get { return ProjectSettings.Guid; } set { throw new InvalidOperationException( "It is not allowed to change the GUID of a C#/VB.NET project" ); } } public override ArrayList References { get { return _references; } } /// /// Gets a value indicating whether building the project for the specified /// build configuration results in managed output. /// /// The solution configuration that is built. /// /// . /// public override bool IsManaged(Configuration solutionConfiguration) { return true; } /// /// Prepares the project for being built. /// /// The solution configuration that is built. /// /// Ensures the configuration-level object directory exists and ensures /// that none of the output files are marked read-only. /// protected override void Prepare(Configuration solutionConfiguration) { // obtain project configuration (corresponding with solution configuration) ConfigurationBase config = BuildConfigurations[solutionConfiguration]; // ensure configuration-level object directory exists if (!config.ObjectDir.Exists) { config.ObjectDir.Create(); config.ObjectDir.Refresh(); } // ensure that none of the output files in the configuration-level // object directory are marked read-only base.Prepare(solutionConfiguration); } /// /// Gets the complete set of output files for the project configuration /// matching the specified solution configuration. /// /// The solution configuration that is built. /// The set of output files to be updated. /// /// /// The key of the case-insensitive is the /// full path of the output file and the value is the path relative to /// the output directory. /// /// /// If the project is not configured to be built for the specified /// solution configuration, then no output files are added. /// /// public override void GetOutputFiles(Configuration solutionConfiguration, Hashtable outputFiles) { base.GetOutputFiles (solutionConfiguration, outputFiles); // obtain project configuration (corresponding with solution configuration) ConfigurationSettings projectConfig = (ConfigurationSettings) BuildConfigurations[solutionConfiguration]; if (projectConfig == null) { // the project is not configured to be built for the specified // solution configuration return; } // add type library if (projectConfig.RegisterForComInterop) { string typeLib = GetTypeLibraryPath(projectConfig); if (!outputFiles.ContainsKey(typeLib)) { outputFiles.Add(typeLib, Path.GetFileName(typeLib)); } } // add satellite assemblies Hashtable resourceSets = GetLocalizedResources(); foreach (LocalizedResourceSet localizedResourceSet in resourceSets.Values) { FileInfo satelliteAssembly = localizedResourceSet.GetSatelliteAssemblyPath( projectConfig, ProjectSettings); // skip files that do not exist, or are already in hashtable if (satelliteAssembly.Exists && !outputFiles.ContainsKey(satelliteAssembly.FullName)) { string relativePath = localizedResourceSet.GetRelativePath( ProjectSettings); outputFiles.Add(satelliteAssembly.FullName, relativePath); } } } protected override BuildResult Build(Configuration solutionConfiguration) { bool bSuccess = true; bool outputUpdated; string tempFile = null; GacCache.RecreateDomain(); try { // obtain project configuration (corresponding with solution configuration) ConfigurationSettings cs = (ConfigurationSettings) BuildConfigurations[solutionConfiguration]; // perform prebuild actions (for VS.NET 2003 and higher) if (!PreBuild(cs)) { // no longer bother trying to build the project and do not // execute any post-build events return BuildResult.Failed; } // unregister types exposed to COM, and unregister type // library (if it exists) UnregisterForComInterop(cs, solutionConfiguration); // ensure temp directory exists if (!Directory.Exists(TemporaryFiles.BasePath)) { Directory.CreateDirectory(TemporaryFiles.BasePath); } // compile neutral and localized resx files CompileResXFiles(solutionConfiguration); // check if project output needs to be rebuilt if (CheckUpToDate(solutionConfiguration)) { Log(Level.Verbose, "Project is up-to-date."); // project output is up-to-date outputUpdated = false; } else { // prepare the project for build Prepare(solutionConfiguration); // check if project does not contain any sources if (_sourceFiles.Count == 0) { // create temp file tempFile = Path.GetTempFileName(); // add temp file to collection of sources to compile // as command line compilers require a least one source // file to be specified, but VS.NET supports empty // projects _sourceFiles[tempFile] = null; } string tempResponseFile = FileUtils.CombinePaths(TemporaryFiles.BasePath, CommandFile); using (StreamWriter sw = File.CreateText(tempResponseFile)) { // write compiler options WriteCompilerOptions(sw, solutionConfiguration); } Log(Level.Verbose, "Starting compiler..."); if (SolutionTask.Verbose) { using (StreamReader sr = new StreamReader(tempResponseFile)) { Log(Level.Verbose, "Commands:"); // increment indentation level SolutionTask.Project.Indent(); try { while (true) { // read line string line = sr.ReadLine(); if (line == null) { break; } // display line Log(Level.Verbose, " " + line); } } finally { // restore indentation level SolutionTask.Project.Unindent(); } } } ProcessStartInfo psi = GetProcessStartInfo(cs, tempResponseFile); psi.UseShellExecute = false; psi.RedirectStandardOutput = true; // start compiler Process p = Process.Start(psi); while (true) { // read line string line = p.StandardOutput.ReadLine(); if (line == null) { break; } // display line Log(Level.Info, line); } p.WaitForExit(); int exitCode = p.ExitCode; Log(Level.Verbose, "{0}! (exit code = {1})", (exitCode == 0) ? "Success" : "Failure", exitCode); if (exitCode > 0) { bSuccess = false; } // project output has been updated outputUpdated = true; } #region Process culture-specific resource files Log(Level.Verbose, "Building satellite assemblies..."); Hashtable resourceSets = GetLocalizedResources(); foreach (LocalizedResourceSet localizedResourceSet in resourceSets.Values) { AssemblyLinkerTask al = new AssemblyLinkerTask(); al.Project = SolutionTask.Project; al.NamespaceManager = SolutionTask.NamespaceManager; al.Parent = SolutionTask; al.BaseDirectory = cs.OutputDir; al.InitializeTaskConfiguration(); DirectoryInfo satelliteBuildDir = localizedResourceSet. GetBuildDirectory(cs); // ensure satellite build directory exists if (!satelliteBuildDir.Exists) { satelliteBuildDir.Create(); } al.OutputFile = localizedResourceSet.GetSatelliteAssemblyPath( cs, ProjectSettings); al.OutputTarget = "lib"; al.Culture = localizedResourceSet.Culture.Name; al.TemplateFile = new FileInfo(cs.BuildPath); foreach (Resource resource in localizedResourceSet.Resources) { FileInfo compiledResourceFile = null; if (resource.IsResX) { // localized resx files have already been compiled compiledResourceFile = resource.GetCompiledResourceFile( solutionConfiguration); } else { // compile resource compiledResourceFile = resource.Compile(solutionConfiguration); } // add resources to embed EmbeddedResource embeddedResource = new EmbeddedResource( compiledResourceFile.FullName, resource.GetManifestResourceName(solutionConfiguration)); al.EmbeddedResources.Add(embeddedResource); } // increment indentation level SolutionTask.Project.Indent(); try { Log(Level.Verbose, " - {0}", al.Culture); // run assembly linker al.Execute(); } finally { // restore indentation level SolutionTask.Project.Unindent(); } } #endregion Process culture-specific resource files #region Register project output for COM Interop // check if we need to build type library if (cs.RegisterForComInterop) { // create type library in output dir, and register it using // that path to match VS.NET string typeLibPath = GetTypeLibraryPath(cs); RegisterForComInterop(cs, solutionConfiguration, typeLibPath); // copy generated type library to object directory to match // VS.NET string objTypeLibPath = Path.ChangeExtension(cs.BuildPath, ".tlb"); CopyFile(new FileInfo(typeLibPath), new FileInfo (objTypeLibPath), SolutionTask); } #endregion Register project output for COM Interop #region Deploy project and configuration level output files // copy primary project output (and related files) Hashtable outputFiles = CollectionsUtil.CreateCaseInsensitiveHashtable(); GetOutputFiles(solutionConfiguration, outputFiles); foreach (DictionaryEntry de in outputFiles) { string srcPath = (string) de.Key; string relativePath = (string) de.Value; if (IsWebProject) { WebDavClient wdc = new WebDavClient(new Uri(_webProjectBaseUrl)); wdc.UploadFile(srcPath, FileUtils.CombinePaths(cs.RelativeOutputDir, relativePath).Replace(@"\", "/")); } else { // determine destination file FileInfo destFile = new FileInfo(FileUtils.CombinePaths(cs.OutputDir.FullName, relativePath)); // copy file using task CopyFile(new FileInfo(srcPath), destFile, SolutionTask); } } #endregion Deploy project and configuration level output files if (ProjectSettings.RunPostBuildEvent != null) { if (!PostBuild(cs, !outputUpdated || bSuccess, outputUpdated)) { bSuccess = false; } } if (!bSuccess) { Log(Level.Error, "Build failed."); return BuildResult.Failed; } return outputUpdated ? BuildResult.SuccessOutputUpdated : BuildResult.Success; } finally { // check if temporary file was created to support empty projects if (tempFile != null) { // ensure temp file is deleted File.Delete(tempFile); } } } #endregion Override implementation of ProjectBase #region Protected Instance Methods /// /// Returns a for launching the compiler /// for this project. /// /// The configuration to build. /// The response file for the compiler. /// /// A for launching the compiler for /// this project. /// protected abstract ProcessStartInfo GetProcessStartInfo(ConfigurationBase config, string responseFile); protected virtual ReferenceBase CreateReference(SolutionBase solution, XmlElement xmlDefinition) { if (solution == null) { throw new ArgumentNullException("solution"); } if (xmlDefinition == null) { throw new ArgumentNullException("xmlDefinition"); } if (xmlDefinition.Attributes["Project"] != null) { return new ManagedProjectReference(xmlDefinition, ReferencesResolver, this, solution, ProjectSettings.TemporaryFiles, GacCache, OutputDir); } else if (xmlDefinition.Attributes["WrapperTool"] != null) { // wrapper return new ManagedWrapperReference(xmlDefinition, ReferencesResolver, this, GacCache, ProjectSettings); } else { // assembly reference return new ManagedAssemblyReference(xmlDefinition, ReferencesResolver, this, GacCache); } } public override ProjectReferenceBase CreateProjectReference(ProjectBase project, bool isPrivateSpecified, bool isPrivate) { return new ManagedProjectReference(project, this, isPrivateSpecified, isPrivate); } protected virtual void WriteCompilerOptions(StreamWriter sw, Configuration solutionConfiguration) { // obtain project configuration (corresponding with solution configuration) ConfigurationSettings config = (ConfigurationSettings) BuildConfigurations[solutionConfiguration]; // write project level options (eg. /target) foreach (string setting in ProjectSettings.Settings) { sw.WriteLine(setting); } // write configuration-level compiler options foreach (string setting in config.Settings) { sw.WriteLine(setting); } // write assembly references to response file foreach (string assemblyReference in GetAssemblyReferences(solutionConfiguration)) { sw.WriteLine("/r:\"{0}\"", assemblyReference); } if (ProjectSettings.ApplicationIcon != null) { sw.WriteLine(@"/win32icon:""{0}""", ProjectSettings.ApplicationIcon.FullName); } if (_neutralResources.Count > 0) { WriteNeutralResourceOptions(sw, solutionConfiguration); } // before writing files to response file, allow project specific // options to be written (eg. VB specific options) WriteProjectOptions(sw); // add the files to compile foreach (string file in _sourceFiles.Keys) { sw.WriteLine(@"""" + file + @""""); } } protected virtual void WriteProjectOptions(StreamWriter sw) { } /// /// Returns the project location from the specified project XML fragment. /// /// XML fragment representing the project file. /// /// The project location of the specified project XML file. /// /// /// The project location could not be determined. /// -or- /// The project location is invalid. /// protected abstract ProjectLocation DetermineProjectLocation(XmlElement docElement); #endregion Protected Instance Methods #region Private Instance Methods /// /// Gets the absolute path of the type library for the project /// output. /// /// The configuration to build. /// /// The absolute path of the type library for the project output. /// private string GetTypeLibraryPath(ConfigurationSettings config) { if (config == null) { throw new ArgumentNullException("config"); } return Path.ChangeExtension(config.OutputPath, ".tlb"); } /// /// Generates a type library for the specified assembly, registers it. /// /// The project configuration that is built. /// The solution configuration that is built. /// The path of the type library to generate. /// /// The regasm tool is used to generate the type library. /// private void RegisterForComInterop(ConfigurationSettings config, Configuration solutionConfiguration, string typelibPath) { Log(Level.Verbose, "Registering project output for COM Interop..."); // create and initialize regasm task RegAsmTask regasm = CreateRegAsmTask(); // add assembly references foreach (ReferenceBase reference in References) { StringCollection assemblyReferences = reference.GetAssemblyReferences( solutionConfiguration); foreach (string assemblyFile in assemblyReferences) { regasm.References.Includes.Add(assemblyFile); } } // assembly to register for COM interop regasm.AssemblyFile = new FileInfo(config.BuildPath); // type library to create regasm.TypeLib = new FileInfo(typelibPath); // increment indentation level regasm.Project.Indent(); try { // execute task regasm.Execute(); } finally { // restore indentation level regasm.Project.Unindent(); } } /// /// Unregister a type library for the specified assembly, and the types /// in that assembly. /// /// The project configuration that is built. /// The solution configuration that is built. /// /// The regasm tool is used to unregister the type library, and /// remove the COM registration for types in the specified assembly. /// private void UnregisterForComInterop(ConfigurationSettings config, Configuration solutionConfiguration) { // if COM interop registration is not enabled or the previous project // output does not exist, then there's nothing to do if (!config.RegisterForComInterop || !File.Exists(config.OutputPath)) { return; } Log(Level.Verbose, "Unregistering project output for COM Interop..."); // create and initialize regasm task RegAsmTask regasm = CreateRegAsmTask(); // add assembly references foreach (ReferenceBase reference in References) { StringCollection assemblyReferences = reference.GetAssemblyReferences( solutionConfiguration); foreach (string assemblyFile in assemblyReferences) { regasm.References.Includes.Add(assemblyFile); } } // unregister types regasm.Unregister = true; // assembly to unregister regasm.AssemblyFile = new FileInfo(config.OutputPath); // determine path for type library string typeLibPath = GetTypeLibraryPath(config); // if the type library exists, unregister it if (File.Exists(typeLibPath)) { regasm.TypeLib = new FileInfo(typeLibPath); } // increment indentation level regasm.Project.Indent(); try { regasm.Execute(); } finally { // restore indentation level regasm.Project.Unindent(); } } private void RegisterEmbeddedResource(string resourceFile, XmlElement elemFile) { FileInfo fi = new FileInfo(resourceFile); if (fi.Exists && string.Compare(".resx", fi.Extension, true) == 0 && fi.Length == 0) { Log(Level.Verbose, "Skipping zero-byte embedded resource '{0}'.", fi.FullName); } else { string dependentOn = (elemFile.Attributes["DependentUpon"] != null) ? FileUtils.CombinePaths(fi.DirectoryName, elemFile.Attributes["DependentUpon"].Value) : null; Resource r = new Resource(this, fi, elemFile.Attributes["RelPath"].Value, dependentOn, SolutionTask, GacCache); if (r.Culture != null) { _localizedResources.Add(r); } else { _neutralResources.Add(r); } } } private void CompileResXFiles(Configuration solutionConfiguration) { Log(Level.Verbose, "Compiling resources:"); Hashtable resxResources = new Hashtable(); // neutral resources foreach (Resource resource in _neutralResources) { if (!resource.IsResX) { continue; } Log(Level.Verbose, " - {0}", resource.InputFile); // determine filename of output file FileInfo compiledResxFile = resource.GetCompiledResourceFile(solutionConfiguration); // add to list of resx files to compile resxResources.Add(resource, compiledResxFile); } // localized resources foreach (Resource resource in _localizedResources) { if (!resource.IsResX) { continue; } Log(Level.Verbose, " - {0}", resource.InputFile); // determine filename of output file FileInfo compiledResxFile = resource.GetCompiledResourceFile(solutionConfiguration); // add to list of resx files to compile resxResources.Add(resource, compiledResxFile); } // no further processing required if there are no resx files to // compile if (resxResources.Count == 0) { return; } // create instance of ResGen task ResGenTask rt = new ResGenTask(); // inherit project from solution task rt.Project = SolutionTask.Project; // inherit namespace manager from solution task rt.NamespaceManager = SolutionTask.NamespaceManager; // parent is solution task rt.Parent = SolutionTask; // inherit verbose setting from solution task rt.Verbose = SolutionTask.Verbose; // make sure framework specific information is set rt.InitializeTaskConfiguration(); // set parent of child elements rt.Assemblies.Parent = rt; // inherit project from solution task from parent task rt.Assemblies.Project = rt.Project; // inherit namespace manager from parent task rt.Assemblies.NamespaceManager = rt.NamespaceManager; // set base directory for filesets rt.Assemblies.BaseDirectory = ProjectDirectory; // set resx files to compile foreach (DictionaryEntry entry in resxResources) { Resource resource = (Resource) entry.Key; FileInfo outputFile = (FileInfo) entry.Value; QualifiedResource qualifiedResource = new QualifiedResource( resource.InputFile, outputFile); rt.QualifiedResources.Add(qualifiedResource); } // inherit assembly references from project foreach (ReferenceBase reference in References) { StringCollection assemblyReferences = reference.GetAssemblyReferences( solutionConfiguration); foreach (string assemblyFile in assemblyReferences) { rt.Assemblies.Includes.Add(assemblyFile); } } // increment indentation level rt.Project.Indent(); try { // execute task rt.Execute(); } finally { // restore indentation level rt.Project.Unindent(); } } private void WriteNeutralResourceOptions(StreamWriter sw, Configuration solutionConfiguration) { // no further processing required if there are no neutral resource // files if (_neutralResources.Count == 0) { return; } foreach (Resource resource in _neutralResources) { Log(Level.Verbose, " - {0}", resource.InputFile); if (resource.IsResX) { // determine filename of compiled file FileInfo compiledResxFile = resource.GetCompiledResourceFile(solutionConfiguration); // determine manifest resource name string manifestResourceName = resource.GetManifestResourceName( solutionConfiguration); // write option to response file sw.WriteLine(string.Format(CultureInfo.InvariantCulture, "/res:\"{0}\",\"{1}\"", compiledResxFile.FullName, manifestResourceName)); } else { // compile resource FileInfo compiledResourceFile = resource.Compile( solutionConfiguration); // write option to response file sw.WriteLine(string.Format(CultureInfo.InvariantCulture, "/res:\"{0}\",\"{1}\"", compiledResourceFile.FullName, resource.GetManifestResourceName(solutionConfiguration))); } } } private bool PreBuild(ConfigurationSettings cs) { string buildCommandLine = ProjectSettings.PreBuildEvent; // check if there are pre build commands to be run if (buildCommandLine != null) { string batchFile = FileUtils.CombinePaths(cs.OutputDir.FullName, "PreBuildEvent.bat"); string workingDirectory = cs.OutputDir.FullName; return ExecuteBuildEvent("PreBuildEvent", buildCommandLine, batchFile, workingDirectory, cs); } // nothing to do, signal success return true; } private bool PostBuild(ConfigurationSettings cs, bool bCompileSuccess, bool bOutputUpdated) { string buildCommandLine = ProjectSettings.PostBuildEvent; // check if there are post build commands to be run if (buildCommandLine != null) { Log(Level.Debug, "PostBuild commandline: {0}", buildCommandLine); string batchFile = FileUtils.CombinePaths(cs.OutputDir.FullName, "PostBuildEvent.bat"); string workingDirectory = cs.OutputDir.FullName; bool bBuildEventSuccess; // there are three different settings for when the PostBuildEvent should be run switch (ProjectSettings.RunPostBuildEvent) { case "OnBuildSuccess": // post-build event will run if the build succeeds. Thus, // the event will even run for a project that is up-to-date, // as long as the build succeeds if (bCompileSuccess) { Log(Level.Debug, "PostBuild+OnBuildSuccess+bCompileSuccess"); bBuildEventSuccess = ExecuteBuildEvent("PostBuildEvent", buildCommandLine, batchFile, workingDirectory, cs); } else { Log(Level.Debug, "PostBuild+OnBuildSuccess"); bBuildEventSuccess = true; } break; case "Always": // post-build event will run regardless of whether the // build succeeded Log(Level.Debug, "PostBuild+Always"); bBuildEventSuccess = ExecuteBuildEvent("PostBuildEvent", buildCommandLine, batchFile, workingDirectory, cs); break; case "OnOutputUpdated": // post-build event will only run when the compiler's // output file (.exe or .dll) is different than the // previous compiler output file. Thus, a post-build // event will not run if a project is up-to-date if (bOutputUpdated) { Log(Level.Debug, "PostBuild+OnOutputUpdated+bOutputUpdated"); bBuildEventSuccess = ExecuteBuildEvent("PostBuildEvent", buildCommandLine, batchFile, workingDirectory, cs); } else { Log(Level.Debug, "PostBuild+OnOutputUpdated"); bBuildEventSuccess = true; } break; default: // getting here means unknown values in the RunPostBuildEvent // property bBuildEventSuccess = false; break; } return bBuildEventSuccess; } // nothing to do, signal success return true; } private bool CheckUpToDate(Configuration solutionConfiguration) { DateTime dtOutputTimeStamp; // obtain project configuration (corresponding with solution configuration) ConfigurationSettings cs = (ConfigurationSettings) BuildConfigurations[solutionConfiguration]; // check if project build output exists if (File.Exists(cs.BuildPath)) { dtOutputTimeStamp = File.GetLastWriteTime(cs.BuildPath); } else { return false; } // check if project file was updated after the output file was // built string fileName = FileSet.FindMoreRecentLastWriteTime(ProjectPath, dtOutputTimeStamp); if (fileName != null) { Log(Level.Debug, "Project file \"0\" has been updated, recompiling.", fileName); return false; } // check all of the input files foreach (string file in _sourceFiles.Keys) { if (dtOutputTimeStamp < File.GetLastWriteTime(file)) { return false; } } // check all culture-neutral resources foreach (Resource resource in _neutralResources) { // check if input file was updated since last compile if (dtOutputTimeStamp < resource.InputFile.LastWriteTime) { return false; } // check if compiled resource file exists FileInfo compiledResourceFile = resource.GetCompiledResourceFile(solutionConfiguration); if (!compiledResourceFile.Exists) { return false; } // check if compiled resource file is up-to-date if (dtOutputTimeStamp < compiledResourceFile.LastWriteTime) { return false; } } // check all of the input references foreach (ReferenceBase reference in _references) { if (dtOutputTimeStamp < reference.GetTimestamp(solutionConfiguration)) { return false; } } // check extra output files foreach (DictionaryEntry de in cs.ExtraOutputFiles) { string extraOutputFile = (string) de.Key; // check if extra output file exists if (!File.Exists(extraOutputFile)) { return false; } } return true; } /// /// Returns containing culture-specific resources. /// /// /// A containing culture-specific resources. /// /// /// The key of the is /// and the value is an instance /// for that culture. /// private Hashtable GetLocalizedResources() { Hashtable localizedResourceSets = new Hashtable(); foreach (Resource resource in _localizedResources) { CultureInfo resourceCulture = resource.Culture; LocalizedResourceSet resourceSet = (LocalizedResourceSet) localizedResourceSets[resourceCulture]; if (resourceSet == null) { resourceSet = new LocalizedResourceSet(resourceCulture); localizedResourceSets.Add(resourceCulture, resourceSet); } resourceSet.Resources.Add(resource); } return localizedResourceSets; } /// /// Creates and initializes a instance. /// /// /// An initialized instance. /// private RegAsmTask CreateRegAsmTask() { RegAsmTask regasm = new RegAsmTask(); // parent is solution task regasm.Parent = SolutionTask; // inherit project from solution task regasm.Parent = regasm.Project = SolutionTask.Project; // inherit verbose setting from solution task regasm.Verbose = SolutionTask.Verbose; // inherit namespace manager from solution task regasm.NamespaceManager = SolutionTask.NamespaceManager; // initialize framework configuration regasm.InitializeTaskConfiguration(); // inherit project from parent task regasm.Assemblies.Project = regasm.Project; // set parent of child elements regasm.Assemblies.Parent = regasm; // inherit namespace manager from parent task regasm.Assemblies.NamespaceManager = regasm.NamespaceManager; // set base directory for filesets regasm.Assemblies.BaseDirectory = ProjectDirectory; // inherit project from parent task regasm.References.Project = regasm.Project; // set parent of child elements regasm.References.Parent = regasm; // inherit namespace manager from parent task regasm.References.NamespaceManager = regasm.NamespaceManager; // set base directory for filesets regasm.References.BaseDirectory = ProjectDirectory; // only output warning messages or higher, unless // we're running in verbose mode if (!regasm.Verbose) { regasm.Threshold = Level.Warning; } return regasm; } #endregion Private Instance Methods #region Public Static Methods public static bool IsEnterpriseTemplateProject(string fileName) { try { using (StreamReader sr = new StreamReader(fileName, Encoding.Default, true)) { XmlTextReader xtr = new XmlTextReader(sr); xtr.MoveToContent(); if (xtr.NodeType == XmlNodeType.Element && xtr.LocalName == "EFPROJECT") { return true; } } return false; } catch (XmlException) { // when the project isn't a valid XML document, it definitely // isn't an enterprise template project return false; } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Error checking whether '{0}' is an enterprise template project.", fileName), Location.UnknownLocation, ex); } } public static string LoadGuid(XmlElement xmlDefinition) { XmlReader guidReader = new XmlNodeReader(xmlDefinition); return LoadGuid(guidReader); } private static string LoadGuid(XmlReader guidReader) { while (guidReader.Read()) { if (guidReader.NodeType == XmlNodeType.Element) { while (guidReader.Read()) { if (guidReader.NodeType == XmlNodeType.Element) { if (guidReader.MoveToAttribute( "ProjectGuid" )) return guidReader.Value; } } } } throw new BuildException("Couldn't locate project GUID.", Location.UnknownLocation); } #endregion Public Static Methods #region Protected Static Methods /// /// Returns the Visual Studio product version of the specified project /// XML fragment. /// /// XML fragment representing the project to check. /// /// The Visual Studio product version of the specified project XML /// fragment. /// /// /// The product version could not be determined. /// -or- /// The product version is not supported. /// protected static ProductVersion GetProductVersion(XmlNode projectNode) { if (projectNode == null) { throw new ArgumentNullException("projectNode"); } XmlAttribute productVersionAttribute = projectNode.Attributes["ProductVersion"]; if (productVersionAttribute == null) { throw new BuildException("The \"ProductVersion\" attribute is" + " missing from the project node.", Location.UnknownLocation); } // check if we're dealing with a valid version number Version productVersion = null; try { productVersion = new Version(productVersionAttribute.Value); } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "The value of the \"Version\" attribute ({0}) is not a valid" + " version string.", productVersionAttribute.Value), Location.UnknownLocation, ex); } if (productVersion.Major == 7) { switch (productVersion.Minor) { case 0: return ProductVersion.Rainier; case 10: return ProductVersion.Everett; } } throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Visual Studio version \"{0\" is not supported.", productVersion.ToString()), Location.UnknownLocation); } /// /// Returns the of the specified project /// XML fragment. /// /// XML fragment representing the project to check. /// /// The of the specified project XML /// fragment. /// /// /// The project location could not be determined. /// -or- /// The project location is invalid. /// protected static ProjectLocation GetProjectLocation(XmlNode projectNode) { if (projectNode == null) { throw new ArgumentNullException("projectNode"); } XmlAttribute projectTypeAttribute = projectNode.Attributes["ProjectType"]; if (projectTypeAttribute == null) { throw new BuildException("The \"ProjectType\" attribute is" + " missing from the project node.", Location.UnknownLocation); } try { return (ProjectLocation) Enum.Parse(typeof(ProjectLocation), projectTypeAttribute.Value, true); } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "The value of the \"ProjectType\" attribute ({0}) is not a valid" + " location string.", projectTypeAttribute.Value), Location.UnknownLocation, ex); } } #endregion Protected Static Methods #region Private Instance Fields private ArrayList _references; /// /// Holds a case-insensitive list of source files. /// /// /// The key of the is the full path of the /// source file and the value is . /// private readonly Hashtable _sourceFiles; private readonly ArrayList _neutralResources; private readonly ArrayList _localizedResources; private readonly string _projectPath; private readonly DirectoryInfo _projectDirectory; private readonly string _webProjectBaseUrl; private readonly ProjectSettings _projectSettings; private readonly ProjectLocation _projectLocation; #endregion Private Instance Fields #region Private Static Fields private const string CommandFile = "compile-commands.txt"; #endregion Private Static Fields /// /// Groups a set of instances for a specific /// culture. /// private class LocalizedResourceSet { #region Private Instance Fields private readonly CultureInfo _culture; private readonly ArrayList _resources; #endregion Private Instance Fields #region Public Instance Constructors /// /// Initializes a new instance /// for the specified culture. /// /// A . public LocalizedResourceSet(CultureInfo culture) { if (culture == null) { throw new ArgumentNullException("culture"); } _culture = culture; _resources = new ArrayList(); } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets the of the /// . /// public CultureInfo Culture { get { return _culture; } } /// /// Gets the set of localized resources. /// public ArrayList Resources { get { return _resources; } } #endregion Public Instance Properties #region Public Instance Methods /// /// Gets the intermediate build directory in which the satellite /// assembly is built. /// /// The project build configuration. /// /// The intermediate build directory in which the satellite assembly /// is built. /// public DirectoryInfo GetBuildDirectory(ConfigurationSettings projectConfig) { return new DirectoryInfo(FileUtils.CombinePaths( projectConfig.ObjectDir.FullName, Culture.Name)); } /// /// Gets a representing the path to the /// intermediate file location of the satellite assembly. /// /// The project build configuration. /// The project settings. /// /// A representing the path to the /// intermediate file location of the satellite assembly. /// public FileInfo GetSatelliteAssemblyPath(ConfigurationSettings projectConfig, ProjectSettings projectSettings) { DirectoryInfo buildDir = GetBuildDirectory(projectConfig); return new FileInfo(FileUtils.CombinePaths(buildDir.FullName, GetSatelliteFileName(projectSettings))); } /// /// Gets path of the satellite assembly, relative to the output /// directory. /// /// The project settings. /// /// The path of the satellite assembly, relative to the output /// directory. /// public string GetRelativePath(ProjectSettings projectSettings) { return FileUtils.CombinePaths(Culture.Name, GetSatelliteFileName( projectSettings)); } #endregion Public Instance Methods #region Private Instance Methods private string GetSatelliteFileName(ProjectSettings projectSettings) { return string.Format(CultureInfo.InvariantCulture, "{0}.resources.dll", projectSettings.AssemblyName); } #endregion Private Instance Methods } } /// /// Indentifies the different output types of a managed project. /// /// /// Visual Studio .NET does not support modules. /// public enum ManagedOutputType { /// /// A class library. /// Library = 1, /// /// A console application. /// Executable = 2, /// /// A Windows program. /// WindowsExecutable = 3 } } nant-0.92-rc1/src/NAnt.VSNet/VcAssemblyReference.cs0000644000175000017500000001663411757302274021706 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Globalization; using System.IO; using System.Text.RegularExpressions; using System.Xml; using NAnt.Core; using NAnt.Core.Util; using NAnt.VSNet.Tasks; namespace NAnt.VSNet { public class VcAssemblyReference : AssemblyReferenceBase { public VcAssemblyReference(XmlElement xmlDefinition, ReferencesResolver referencesResolver, ProjectBase parent, GacCache gacCache) : base(xmlDefinition, referencesResolver, parent, gacCache) { XmlAttribute privateAttribute = xmlDefinition.Attributes["CopyLocal"]; if (privateAttribute != null) { _isPrivateSpecified = true; _isPrivate = bool.Parse(privateAttribute.Value); } // determine name of reference by taking filename part of relative // path, without extension XmlAttribute relativePathAttribute = XmlDefinition.Attributes["RelativePath"]; if (relativePathAttribute != null) { _name = Path.GetFileNameWithoutExtension(relativePathAttribute.Value); } _assemblyFile = ResolveAssemblyReference(); } #region Override implementation of AssemblyReferenceBase protected override bool IsPrivate { get { return _isPrivate; } } protected override bool IsPrivateSpecified { get { return _isPrivateSpecified; } } /// /// Resolves an assembly reference. /// /// /// The full path to the resolved assembly, or /// if the assembly reference could not be resolved. /// protected override string ResolveAssemblyReference() { // check if assembly reference was resolved before if (_assemblyFile != null) { // if assembly file actually exists, there's no need to resolve // the assembly reference again if (File.Exists(_assemblyFile)) { return _assemblyFile; } } XmlElement referenceElement = XmlDefinition; string assemblyFileName = null; string relativePath = referenceElement.GetAttribute("RelativePath"); if (relativePath == null) { throw new BuildException("For Visual C++ projects only assembly" + " references using relative paths are supported.", Location.UnknownLocation); } else { // expand macro's in RelativePath assemblyFileName = _rxMacro.Replace(relativePath, new MatchEvaluator(EvaluateMacro)); // TODO: support locating assemblies in VCConfiguration.ReferencesPath, // but for now just remove it from reference filename and // search all assembly folders assemblyFileName = assemblyFileName.Replace("{ReferencesPath}\\", string.Empty); } // 1. The RelativePath might be fully qualified (after macro expansion) if (Path.IsPathRooted(assemblyFileName)) { // consider assembly resolve although we're not sure whether // the file actually exists // // the file might actually be created as result of building // a project return assemblyFileName; } // 2. The project directory // NOT SURE IF THIS IS CORRECT // 3. The ReferencePath // NOT SURE WE SHOULD DO THIS ONE // 4. The .NET Framework directory string resolvedAssemblyFile = ResolveFromFramework(assemblyFileName); if (resolvedAssemblyFile != null) { return resolvedAssemblyFile; } // 5. AssemblyFolders resolvedAssemblyFile = ResolveFromAssemblyFolders(referenceElement, Path.GetFileName(assemblyFileName)); if (resolvedAssemblyFile != null) { return resolvedAssemblyFile; } // assembly reference could not be resolved return null; } #endregion Override implementation of AssemblyReferenceBase #region Override implementation of ReferenceBase /// /// Gets the name of the referenced assembly. /// /// /// The name of the referenced assembly, or if /// the name could not be determined. /// public override string Name { get { return _name; } } #endregion Override implementation of ReferenceBase #region Private Instance Methods /// /// Is called each time a regular expression match is found during a /// operation. /// /// The resulting from a single regular expression match during a . /// /// The expanded . /// /// The macro is not supported. /// Expansion of a given macro is not yet implemented. private string EvaluateMacro(Match m) { string macro = m.Groups[1].Value; // expand using solution level macro's string expandedMacro = SolutionTask.ExpandMacro(macro); if (expandedMacro != null) { return expandedMacro; } // expand using project level macro's expandedMacro = Parent.ExpandMacro(macro); if (expandedMacro != null) { return expandedMacro; } throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Macro \"{0}\", used by assembly reference \"{1}\" in project" + " \"{2}\" is not supported in assembly references.", macro, Name, Parent.Name), Location.UnknownLocation); } #endregion Private Instance Methods #region Private Instance Fields private string _assemblyFile; private readonly bool _isPrivateSpecified; private readonly bool _isPrivate; private readonly string _name = string.Empty; private readonly Regex _rxMacro = new Regex(@"\$\((\w+)\)"); #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.VSNet/VcProjectReference.cs0000644000175000017500000000771611757302274021536 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.CodeDom.Compiler; using System.IO; using System.Xml; using NAnt.Core; using NAnt.Core.Util; namespace NAnt.VSNet { public class VcProjectReference : ProjectReferenceBase { #region Public Instance Constructors public VcProjectReference(XmlElement xmlDefinition, ReferencesResolver referencesResolver, ProjectBase parent, SolutionBase solution, TempFileCollection tfc, GacCache gacCache, DirectoryInfo outputDir) : base(referencesResolver, parent) { if (xmlDefinition == null) { throw new ArgumentNullException("xmlDefinition"); } if (solution == null) { throw new ArgumentNullException("solution"); } if (tfc == null) { throw new ArgumentNullException("tfc"); } if (gacCache == null) { throw new ArgumentNullException("gacCache"); } XmlAttribute privateAttribute = xmlDefinition.Attributes["CopyLocal"]; if (privateAttribute != null) { _isPrivateSpecified = true; _isPrivate = bool.Parse(privateAttribute.Value); } // determine path of project file string projectFile = solution.GetProjectFileFromGuid( xmlDefinition.GetAttribute("ReferencedProjectIdentifier")); // load referenced project _project = LoadProject(solution, tfc, gacCache, outputDir, projectFile); } public VcProjectReference(ProjectBase project, ProjectBase parent, bool isPrivateSpecified, bool isPrivate) : base(project.ReferencesResolver, parent) { _project = project; _isPrivateSpecified = isPrivateSpecified; _isPrivate = isPrivate; } #endregion Public Instance Constructors #region Override implementation of ReferenceBase /// /// Gets a value indicating whether the reference is managed for the /// specified configuration. /// /// The build configuration of the reference. /// /// if the reference is managed for the /// specified configuration; otherwise, . /// public override bool IsManaged(Configuration config) { return Project.IsManaged(config); } #endregion Override implementation of ReferenceBase #region Override implementation of ProjectReferenceBase public override ProjectBase Project { get { return _project; } } protected override bool IsPrivate { get { return _isPrivate; } } protected override bool IsPrivateSpecified { get { return _isPrivateSpecified; } } #endregion Override implementation of ProjectReferenceBase #region Private Instance Fields private readonly ProjectBase _project; private readonly bool _isPrivateSpecified; private readonly bool _isPrivate; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.VSNet/SolutionFactory.cs0000644000175000017500000000722611757302274021160 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.CodeDom.Compiler; using System.Collections; using System.Globalization; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Xml; using NAnt.Core; using NAnt.Core.Util; using NAnt.VSNet.Extensibility; using NAnt.VSNet.Tasks; namespace NAnt.VSNet { /// /// Factory class for VS.NET solutions. /// internal sealed class SolutionFactory { #region Private Instance Constructor /// /// Initializes a new instance of the /// class. /// private SolutionFactory() { } #endregion Private Instance Constructor #region Internal Static Methods internal static SolutionFactory Create () { return new SolutionFactory(); } #endregion Internal Static Methods #region Public Instance Methods public SolutionBase LoadSolution(SolutionTask solutionTask, TempFileCollection tfc, GacCache gacCache, ReferencesResolver refResolver) { if (solutionTask.SolutionFile == null) { return new GenericSolution(solutionTask, tfc, gacCache, refResolver); } else { // determine the solution file format version // will hold the content of the solution file string fileContents; using (StreamReader sr = new StreamReader(solutionTask.SolutionFile.FullName, Encoding.Default, true)) { fileContents = sr.ReadToEnd(); } ISolutionBuildProvider provider = FindProvider(fileContents); if (provider != null) { return provider.GetInstance(fileContents, solutionTask, tfc, gacCache, refResolver); } throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Solution format of file '{0}' is not supported.", solutionTask.SolutionFile), Location.UnknownLocation); } } public void RegisterProvider(ISolutionBuildProvider provider) { _projectProviders.Add(provider); } #endregion Public Instance Methods #region Private Instance Methods private ISolutionBuildProvider FindProvider(string fileContents) { int max = 0; ISolutionBuildProvider res = null; foreach (ISolutionBuildProvider provider in _projectProviders) { int pri = provider.IsSupported(fileContents); if (pri > max) { max = pri; res = provider; } } return res; } #endregion Private Instance Methods private readonly ArrayList _projectProviders = new ArrayList(); } } nant-0.92-rc1/src/NAnt.VSNet/AssemblyReferenceBase.cs0000644000175000017500000003001211757302274022172 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Matthew Mastracci (matt@aclaro.com) // Scott Ford (sford@RJKTECH.com) // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Xml; using Microsoft.Win32; using NAnt.Core; using NAnt.Core.Util; using NAnt.VSNet.Tasks; namespace NAnt.VSNet { public abstract class AssemblyReferenceBase : FileReferenceBase { #region Protected Instance Constructors protected AssemblyReferenceBase(XmlElement xmlDefinition, ReferencesResolver referencesResolver, ProjectBase parent, GacCache gacCache) : base(xmlDefinition, referencesResolver, parent, gacCache) { } #endregion Protected Instance Constructors #region Protected Instance Properties protected abstract bool IsPrivate { get; } protected abstract bool IsPrivateSpecified { get; } #endregion Protected Instance Properties #region Override implementation of ReferenceBase /// /// Gets a value indicating whether the output file(s) of this reference /// should be copied locally. /// /// /// if the output file(s) of this reference /// should be copied locally; otherwise, . /// public override bool CopyLocal { get { if (IsPrivateSpecified) { return IsPrivate; } else { // only copy local if assembly reference could be resolved, // if not a system assembly and is not in the GAC string assemblyFile = ResolveAssemblyReference(); return assemblyFile != null && !IsSystem && !GacCache.IsAssemblyInGac(assemblyFile); } } } /// /// Gets a value indicating whether this reference represents a system /// assembly. /// /// /// if this reference represents a system /// assembly; otherwise, . /// protected override bool IsSystem { get { // if the assembly cannot be resolved, we consider it not to // be a system assembly string assemblyFile = ResolveAssemblyReference(); if (assemblyFile == null) { return false; } // check if assembly is stored in the framework assembly // directory return string.Compare(Path.GetDirectoryName(assemblyFile), SolutionTask.Project.TargetFramework.FrameworkAssemblyDirectory.FullName, true, CultureInfo.InvariantCulture) == 0; } } /// /// Gets the path of the reference, without taking the "copy local" /// setting into consideration. /// /// The solution configuration that is built. /// /// The output path of the reference. /// public override string GetPrimaryOutputFile(Configuration solutionConfiguration) { return ResolveAssemblyReference(); } /// /// Gets the complete set of output files for the referenced project. /// /// The solution configuration that is built. /// The set of output files to be updated. /// /// The key of the case-insensitive is the /// full path of the output file and the value is the path relative to /// the output directory. /// public override void GetOutputFiles(Configuration solutionConfiguration, Hashtable outputFiles) { string assemblyFile = ResolveAssemblyReference(); if (assemblyFile != null) { base.GetAssemblyOutputFiles(assemblyFile, outputFiles); } } /// /// Gets the complete set of assemblies that need to be referenced when /// a project references this component. /// /// The solution configuration that is built. /// /// The complete set of assemblies that need to be referenced when a /// project references this component. /// public override StringCollection GetAssemblyReferences(Configuration solutionConfiguration) { // if we're dealing with an assembly reference, then we only // need to reference that assembly itself as VS.NET forces users // to add all dependent assemblies to the project itself StringCollection assemblyReferences = new StringCollection(); // attempt to resolve assembly reference string assemblyFile = ResolveAssemblyReference(); if (assemblyFile == null) { Log(Level.Warning, "Assembly \"{0}\", referenced" + " by project \"{1}\", could not be resolved.", Name, Parent.Name); return assemblyReferences; } // ensure assembly actually exists if (!File.Exists(assemblyFile)) { Log(Level.Warning, "Assembly \"{0}\", referenced" + " by project \"{1}\", does not exist.", assemblyFile, Parent.Name); return assemblyReferences; } // add referenced assembly to list of reference assemblies assemblyReferences.Add(assemblyFile); return assemblyReferences; } /// /// Gets the timestamp of the reference. /// /// The solution configuration that is built. /// /// The timestamp of the reference. /// public override DateTime GetTimestamp(Configuration solutionConfiguration) { string assemblyFile = ResolveAssemblyReference(); if (assemblyFile == null) { return DateTime.MaxValue; } return GetFileTimestamp(assemblyFile); } #endregion Override implementation of ReferenceBase #region Public Instance Methods public ProjectReferenceBase CreateProjectReference(ProjectBase project) { return project.CreateProjectReference(project, IsPrivateSpecified, IsPrivate); } #endregion Public Instance Methods #region Protected Instance Methods /// /// Resolves an assembly reference. /// /// /// The full path to the resolved assembly, or /// if the assembly reference could not be resolved. /// protected abstract string ResolveAssemblyReference(); /// /// Searches for the given file in all paths in . /// /// The folders to search. /// The file to search for. /// /// The path of the assembly if was found /// in ; otherwise, . /// protected string ResolveFromFolderList(StringCollection folderList, string fileName) { Log(Level.Debug, "Attempting to resolve \"{0}\" in AssemblyFolders...", fileName); foreach (string path in folderList) { Log(Level.Debug, "Checking \"{0}\"...", path); try { string assemblyFile = FileUtils.CombinePaths(path, fileName); if (File.Exists(assemblyFile)) { Log(Level.Debug, "Assembly found in \"{0}\".", path); return assemblyFile; } else { Log(Level.Debug, "Assembly not found in \"{0}\".", path); } } catch (Exception ex) { Log(Level.Verbose, "Error resolving reference to \"{0}\"" + " in directory \"{1}\".", fileName, path); Log(Level.Debug, ex.ToString()); } } return null; } /// /// Resolves an assembly reference in the framework assembly directory /// of the target framework. /// /// The file to search for. /// /// The full path of the assembly file if the assembly could be located /// in the framework assembly directory; otherwise, . /// protected string ResolveFromFramework(string fileName) { //string systemAssembly = FileUtils.CombinePaths(SolutionTask.Project.TargetFramework. // FrameworkAssemblyDirectory.FullName, fileName); string systemAssembly = SolutionTask.Project.TargetFramework.ResolveAssembly(fileName); if (File.Exists(systemAssembly)) { return systemAssembly; } return null; } /// /// Resolves an assembly reference using a path relative to the project /// directory. /// /// /// The full path of the assembly, or if /// is or an /// empty . /// protected string ResolveFromRelativePath(string relativePath) { if (!String.IsNullOrEmpty(relativePath)) { // TODO: VS.NET seems to be able to handle a project dir / hint // path combination that is more than 260 characters long // // eg. ../Assemblies/..Assemblies/../...... string combinedPath = FileUtils.CombinePaths(Parent.ProjectDirectory.FullName, relativePath); try { return FileUtils.GetFullPath(combinedPath); } catch (PathTooLongException ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Assembly \"{0}\", referenced by project \"{1}\", could not be" + " resolved using path \"{2}\".", Name, Parent.Name, combinedPath), Location.UnknownLocation, ex); } } return null; } protected virtual string ResolveFromAssemblyFolders(XmlElement referenceElement, string fileName) { return ResolveFromFolderList(SolutionTask.AssemblyFolderList, fileName); } #endregion Protected Instance Methods } } nant-0.92-rc1/src/NAnt.VSNet/AssemblyInfo.cs0000644000175000017500000000233211757302274020400 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Scott Hernandez (ScottHernandez@hotmail.com) // Gert Driesen (drieseng@users.sourceforge.net) using System.Reflection; // This will not compile with Visual Studio. If you want to build a signed // executable use the NAnt build file. To build under Visual Studio just // exclude this file from the build. [assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile(@"..\NAnt.key")] [assembly: AssemblyKeyName("")]nant-0.92-rc1/src/NAnt.VSNet/CSharpProjectProvider.cs0000644000175000017500000000371111757302274022231 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2006 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Martin Aliger (martin_aliger@myrealbox.com) using System; using System.CodeDom.Compiler; using System.IO; using System.Xml; using NAnt.Core; using NAnt.Core.Util; using NAnt.VSNet.Extensibility; using NAnt.VSNet.Tasks; namespace NAnt.VSNet { internal class CSharpProjectProvider : IProjectBuildProvider { #region Implementation of IProjectBuildProvider public int IsSupported(string projectExt, XmlElement xmlDefinition) { if (projectExt == ".csproj") return 5; if (CSharpProject.IsSupported(xmlDefinition)) return 10; return 0; } public ProjectBase GetInstance(SolutionBase solution, string projectPath, XmlElement xmlDefinition, SolutionTask solutionTask, TempFileCollection tfc, GacCache gacCache, ReferencesResolver refResolver, DirectoryInfo outputDir) { return new CSharpProject(solution, projectPath, xmlDefinition, solutionTask, tfc, gacCache, refResolver, outputDir); } public string LoadGuid(XmlElement xmlDefinition) { return CSharpProject.LoadGuid(xmlDefinition); } #endregion Implementation of IProjectBuildProvider } } nant-0.92-rc1/src/NAnt.VSNet/NAnt.VSNet.csproj0000644000175000017500000001564711757302274020553 0ustar jtaylorjtaylor Debug AnyCPU 2.0 {DD434690-B4DF-4BF9-91FE-F139A41E2474} NAnt.VSNet NAnt.VSNetTasks Library OnSuccessfulBuild false 8.0.50727 v2.0 2.0 publish\ true Disk false Foreground 7 Days false false true 0 1.0.0.%2a false false true true full false 4 ..\..\build\Debug\ AllRules.ruleset TRACE;DEBUG ..\..\build\Debug\NAnt.VSNetTasks.xml true pdbonly true ..\..\build\Release\ 4 AllRules.ruleset TRACE ..\..\build\Release\NAnt.VSNetTasks.xml CommonAssemblyInfo.cs False .NET Framework 3.5 SP1 Client Profile false False .NET Framework 3.5 SP1 true False Windows Installer 3.1 true {8F5F8375-4097-4952-B860-784EB9961ABE} NAnt.Core {B50A1067-785B-4686-8FFC-5AF424BEF163} NAnt.DotNet {A154DB17-7263-44E3-838E-1E4C4946B7D8} NAnt.VisualCpp {C66545A2-6FEC-4A38-937A-5B25E61EE8A1} NAnt.Win32 nant-0.92-rc1/src/NAnt.VSNet/Rainier/0000755000175000017500000000000011757310030017034 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.VSNet/Rainier/SolutionProvider.cs0000644000175000017500000000406311757302274022730 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Martin Aliger (martin_aliger@myrealbox.com) using System; using System.CodeDom.Compiler; using System.Text.RegularExpressions; using System.Xml; using NAnt.Core; using NAnt.Core.Util; using NAnt.VSNet.Extensibility; using NAnt.VSNet.Tasks; namespace NAnt.VSNet.Rainier { internal class SolutionProvider : ISolutionBuildProvider { #region Implementation of ISolutionBuildProvider public int IsSupported(string fileContents) { Regex reSolutionFormat = new Regex(@"^\s*Microsoft Visual Studio Solution File, Format Version\s+(?[0-9]+\.[0-9]+)", RegexOptions.Singleline); MatchCollection matches = reSolutionFormat.Matches(fileContents); if (matches.Count == 0) { return 0; } string formatVersion = matches[0].Groups["formatVersion"].Value; if (formatVersion == "7.00") { return 10; } return 0; } public SolutionBase GetInstance(string solutionContent, SolutionTask solutionTask, TempFileCollection tfc, GacCache gacCache, ReferencesResolver refResolver) { return new Solution(solutionContent, solutionTask, tfc, gacCache, refResolver); } #endregion Implementation of ISolutionBuildProvider } } nant-0.92-rc1/src/NAnt.VSNet/Rainier/Solution.cs0000644000175000017500000001340511757302274021215 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Matthew Mastracci (matt@aclaro.com) // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Text.RegularExpressions; using NAnt.Core; using NAnt.Core.Util; using NAnt.VSNet; using NAnt.VSNet.Tasks; namespace NAnt.VSNet.Rainier { /// /// Analyses Microsoft Visual Studio .NET 2002 (Rainier) solution files. /// internal class Solution : SolutionBase { public Solution(string solutionContent, SolutionTask solutionTask, TempFileCollection tfc, GacCache gacCache, ReferencesResolver refResolver) : base(solutionTask, tfc, gacCache, refResolver) { Regex reProjects = new Regex(@"Project\(\""(?\{.*?\})\"".*?\""(?.*?)\"".*?\""(?.*?)\"".*?\""(?.*?)\""(?[\s\S]*?)EndProject", RegexOptions.Multiline); MatchCollection projectMatches = reProjects.Matches(solutionContent); Hashtable explicitProjectDependencies = CollectionsUtil.CreateCaseInsensitiveHashtable(); foreach (Match projectMatch in projectMatches) { string project = projectMatch.Groups["project"].Value; string guid = projectMatch.Groups["guid"].Value; // translate partial project path or URL to absolute path string fullProjectPath = TranslateProjectPath(solutionTask.SolutionFile.DirectoryName, project); // check if project file actually exists if (!System.IO.File.Exists(fullProjectPath)) { throw CreateProjectDoesNotExistException(fullProjectPath); } if (ManagedProjectBase.IsEnterpriseTemplateProject(fullProjectPath)) { RecursiveLoadTemplateProject(fullProjectPath); } else { // add project path to collection ProjectEntries.Add(new ProjectEntry(guid, fullProjectPath)); } // set-up project dependencies Regex reDependencies = new Regex(@"^\s+" + guid + @"\.[0-9]+ = (?\{\S*\}?)\s*$", RegexOptions.Multiline); MatchCollection dependencyMatches = reDependencies.Matches(solutionContent); foreach (Match dependencyMatch in dependencyMatches) { string dependency = dependencyMatch.Groups["dep"].Value; if (!explicitProjectDependencies.ContainsKey(guid)) { explicitProjectDependencies[guid] = CollectionsUtil.CreateCaseInsensitiveHashtable(); } ((Hashtable) explicitProjectDependencies[guid])[dependency] = null; } // set-up project configuration Regex reProjectBuildConfig = new Regex(@"^\s+" + guid + @"\.(?[^|]+)\|?(?[^\.]?)\.Build\.0\s*=\s*(?[^|]+)\|(?[\.\w ]+)\s*", RegexOptions.Multiline); MatchCollection projectBuildMatches = reProjectBuildConfig.Matches(solutionContent); ProjectEntry projectEntry = ProjectEntries [guid]; if (projectEntry == null) { // TODO: determine if we should report an error if a build // configuration is defined for a project that does not // exist in the solution continue; } // holds mapping between project configuration(s) and solution(s) ConfigurationMap buildConfigurations = new ConfigurationMap( projectBuildMatches.Count); for (int i = 0; i < projectBuildMatches.Count; i++) { Match projectBuildMatch = projectBuildMatches [i]; string solutionConfigName = projectBuildMatch.Groups["solutionConfiguration"].Value; string solutionPlatform = projectBuildMatch.Groups["solutionPlatform"].Value; string projectConfigName = projectBuildMatch.Groups["projectConfiguration"].Value; string projectPlatform = projectBuildMatch.Groups["projectPlatform"].Value; Configuration solutionConfig = new Configuration( solutionConfigName, solutionPlatform); Configuration projectConfig = new Configuration( projectConfigName, projectPlatform); buildConfigurations [solutionConfig] = projectConfig; } // add map to corresponding project entry projectEntry.BuildConfigurations = buildConfigurations; } LoadProjectGuids(new ArrayList(solutionTask.Projects.FileNames), false); LoadProjectGuids(new ArrayList(solutionTask.ReferenceProjects.FileNames), true); LoadProjects(gacCache, refResolver, explicitProjectDependencies); } } } nant-0.92-rc1/src/NAnt.VSNet/ConfigurationSettings.cs0000644000175000017500000002403711757302274022343 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Matthew Mastracci (matt@aclaro.com) using System; using System.Globalization; using System.IO; using System.Collections; using System.Xml; using NAnt.Core; using NAnt.Core.Util; using NAnt.VSNet.Tasks; namespace NAnt.VSNet { public class ConfigurationSettings : ConfigurationBase { #region Public Instance Constructors public ConfigurationSettings(ManagedProjectBase project, XmlElement elemConfig, DirectoryInfo outputDir) : base(project) { _settings = new ArrayList(); if (outputDir == null) { _relativeOutputDir = elemConfig.Attributes["OutputPath"].Value; if (!_relativeOutputDir.EndsWith(Path.DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture))) { _relativeOutputDir = _relativeOutputDir + Path.DirectorySeparatorChar; } _outputDir = new DirectoryInfo(FileUtils.CombinePaths( project.ProjectDirectory.FullName, _relativeOutputDir)); } else { _relativeOutputDir = outputDir.FullName; if (!_relativeOutputDir.EndsWith(Path.DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture))) { _relativeOutputDir = _relativeOutputDir + Path.DirectorySeparatorChar; } _outputDir = outputDir; } _name = elemConfig.GetAttribute("Name"); string documentationFile = elemConfig.GetAttribute("DocumentationFile"); if (!String.IsNullOrEmpty(documentationFile)) { // to match VS.NET, the XML Documentation file will be output // in the project directory, and only later copied to the output // directory string xmlDocBuildFile = FileUtils.CombinePaths(project.ProjectDirectory.FullName, documentationFile); // add compiler option to build XML Documentation file _settings.Add(@"/doc:""" + xmlDocBuildFile + @""""); // make sure the output directory for the doc file exists if (!Directory.Exists(Path.GetDirectoryName(xmlDocBuildFile))) { Directory.CreateDirectory(Path.GetDirectoryName(xmlDocBuildFile)); } // add built documentation file as extra output file ExtraOutputFiles[xmlDocBuildFile] = Path.GetFileName(xmlDocBuildFile); } // determine whether we need to register project output for use with // COM components _registerForComInterop = string.Compare(elemConfig.GetAttribute("RegisterForComInterop"), "true", true, CultureInfo.InvariantCulture) == 0; SolutionTask.Log(Level.Debug, "Project: {0} Relative Output Path: {1} Output Path: {2} Documentation Path: {3}", Project.Name, _relativeOutputDir, _outputDir.FullName, documentationFile); Hashtable htStringSettings = new Hashtable(); Hashtable htBooleanSettings = new Hashtable(); htStringSettings["BaseAddress"] = "/baseaddress:{0}"; // is only supported by csc (all versions) and vbc (2.0 or higher) htStringSettings["FileAlignment"] = "/filealign:{0}"; htStringSettings["DefineConstants"] = "/define:{0}"; switch (project.Type) { case ProjectType.CSharp: htStringSettings["WarningLevel"] = "/warn:{0}"; htStringSettings["NoWarn"] = "/nowarn:{0}"; htBooleanSettings["IncrementalBuild"] = "/incremental"; htBooleanSettings["AllowUnsafeBlocks"] = "/unsafe"; htBooleanSettings["CheckForOverflowUnderflow"] = "/checked"; break; case ProjectType.JSharp: htStringSettings["WarningLevel"] = "/warn:{0}"; htStringSettings["NoWarn"] = "/nowarn:{0}"; htBooleanSettings["IncrementalBuild"] = "/incremental"; break; case ProjectType.VB: htStringSettings["DefineDebug"] = "/d:DEBUG={0}"; htStringSettings["DefineTrace"] = "/d:TRACE={0}"; htBooleanSettings["RemoveIntegerChecks"] = "/removeintchecks"; break; } htBooleanSettings["DebugSymbols"] = "/debug"; htBooleanSettings["TreatWarningsAsErrors"] = "/warnaserror"; htBooleanSettings["Optimize"] = "/optimize"; foreach (DictionaryEntry de in htStringSettings) { string name = de.Key.ToString(); string value = elemConfig.GetAttribute(de.Key.ToString()); if (!String.IsNullOrEmpty(value)) { switch (name) { case "BaseAddress": // vbc and vjs expect the base address to be specified // as a hexadecimal number, csc supports decimal, // hexadecimal, or octal number // // so use hexadecimal as all compiler support this uint intvalue = Convert.ToUInt32(value, CultureInfo.InvariantCulture); value = "0x" + intvalue.ToString("x", CultureInfo.InvariantCulture); break; case "DefineConstants": // vbc fails when the symbol contains spaces value = value.Replace(" ", string.Empty); break; } _settings.Add(string.Format(CultureInfo.InvariantCulture, de.Value.ToString(), value)); } } foreach (DictionaryEntry de in htBooleanSettings) { string name = de.Key.ToString(); switch (name) { case "IncrementalBuild": // ignore if not supported if (!IncrementalBuildSupported) { continue; } break; } string value = elemConfig.GetAttribute(name); if (string.Compare(value, "true", true, CultureInfo.InvariantCulture) == 0) { _settings.Add(de.Value.ToString() + "+"); } else if (string.Compare(value, "false", true, CultureInfo.InvariantCulture) == 0) { _settings.Add(de.Value.ToString() + "-"); } } _settings.Add(string.Format(CultureInfo.InvariantCulture, "/out:\"{0}\"", BuildPath)); } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets the platform that the configuration targets. /// /// /// The platform targeted by the configuration. /// public override string PlatformName { get { return ".NET"; } } public override string RelativeOutputDir { get { return _relativeOutputDir; } } public override DirectoryInfo OutputDir { get { return _outputDir; } } public override string OutputPath { get { return FileUtils.CombinePaths(OutputDir.FullName, ((ManagedProjectBase) Project).ProjectSettings.OutputFileName); } } /// /// Gets the path in which the output file will be created before its /// copied to the actual output path. /// public override string BuildPath { get { return FileUtils.CombinePaths(ObjectDir.FullName, Path.GetFileName(OutputPath)); } } public string[] Settings { get { return (string[]) _settings.ToArray(typeof(string)); } } public override string Name { get { return _name; } } /// /// Gets a value indicating whether to register the project output for /// use with COM components. /// /// /// if the project output should be registered /// for use with COM components; otherwise, . /// public bool RegisterForComInterop { get { return _registerForComInterop; } } #endregion Public Instance Properties #region Private Instance Properties private bool IncrementalBuildSupported { get { FrameworkInfo tf = SolutionTask.Project.TargetFramework; // only supported up until .NET Framework 2.0 return (tf.Family == "net" && tf.Version <= new Version (2, 0)); } } #endregion Private Instance Properties #region Private Instance Fields private readonly ArrayList _settings; private readonly string _relativeOutputDir; private readonly DirectoryInfo _outputDir; private readonly string _name; private readonly bool _registerForComInterop; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.VSNet/VBProject.cs0000644000175000017500000002264411757302274017653 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.CodeDom.Compiler; using System.Diagnostics; using System.Globalization; using System.IO; using System.Xml; using NAnt.Core; using NAnt.Core.Util; using NAnt.DotNet.Types; using NAnt.VSNet.Tasks; namespace NAnt.VSNet { public class VBProject : ManagedProjectBase { #region Public Instance Constructors public VBProject(SolutionBase solution, string projectPath, XmlElement xmlDefinition, SolutionTask solutionTask, TempFileCollection tfc, GacCache gacCache, ReferencesResolver refResolver, DirectoryInfo outputDir) : base(solution, projectPath, xmlDefinition, solutionTask, tfc, gacCache, refResolver, outputDir) { _imports = new NamespaceImportCollection(); // process namespace imports XmlNodeList imports = xmlDefinition.SelectNodes("//Imports/Import"); foreach (XmlElement import in imports) { XmlAttribute nsAttribute = import.Attributes["Namespace"]; if (nsAttribute != null) { string nameSpace = nsAttribute.Value.ToString( CultureInfo.InvariantCulture); _imports.Add(new NamespaceImport(nameSpace)); } } } #endregion Public Instance Constructors #region Override implementation of ManagedProjectBase protected override void WriteProjectOptions(StreamWriter sw) { // write namespace imports if (_imports.Count > 0) { sw.WriteLine("/imports:{0}", _imports.ToString()); } } #endregion Override implementation of ManagedProjectBase #region Override implementation of ProjectBase /// /// Gets the type of the project. /// /// /// The type of the project. /// public override ProjectType Type { get { return ProjectType.VB; } } /// /// Verifies whether the specified XML fragment represents a valid project /// that is supported by this . /// /// XML fragment representing the project file. /// /// The XML fragment is not supported by this . /// -or- /// The XML fragment does not represent a valid project (for this ). /// protected override void VerifyProjectXml(XmlElement docElement) { if (!IsSupported(docElement)) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Project '{0}' is not a valid VB.NET project.", ProjectPath), Location.UnknownLocation); } } /// /// Returns the Visual Studio product version of the specified project /// XML fragment. /// /// The document element of the project. /// /// The Visual Studio product version of the specified project XML /// fragment. /// /// /// The product version could not be determined. /// -or- /// The product version is not supported. /// /// /// This method is called from the ctor, and /// at that time we're not sure the XML that is passed in, is indeed a /// valid Visual Basic project. /// protected override ProductVersion DetermineProductVersion(XmlElement docElement) { if (docElement == null) { throw new ArgumentNullException("docElement"); } return GetProductVersion(docElement.SelectSingleNode("./VisualBasic")); } #endregion Override implementation of ProjectBase #region Override implemenation of ManagedProjectBase /// /// Gets the default file extension of sources for this project. /// /// /// For VB projects, the default file extension is ".vb". /// protected override string FileExtension { get { return ".vb"; } } /// /// Returns the project location from the specified project XML fragment. /// /// XML fragment representing the project file. /// /// The project location of the specified project XML file. /// /// /// The project location could not be determined. /// -or- /// The project location is invalid. /// protected override ProjectLocation DetermineProjectLocation(XmlElement docElement) { return GetProjectLocation(docElement.SelectSingleNode("./VisualBasic")); } /// /// Returns a for launching the compiler /// for this project. /// /// The configuration to build. /// The response file for the compiler. /// /// A for launching the compiler for /// this project. /// protected override ProcessStartInfo GetProcessStartInfo(ConfigurationBase config, string responseFile) { ProcessStartInfo psi = new ProcessStartInfo(FileUtils.CombinePaths(SolutionTask. Project.TargetFramework.FrameworkDirectory.FullName, "vbc.exe"), "@\"" + responseFile + "\""); // Visual Basic.NET uses the directory from which VS.NET // was launched as working directory, the closest match // and best behaviour for us is to use the // as working directory and fallback to the // if the project was explicitly specified if (SolutionTask.SolutionFile != null) { psi.WorkingDirectory = SolutionTask.SolutionFile.DirectoryName; } else { psi.WorkingDirectory = ProjectDirectory.FullName; } return psi; } #endregion Override implemenation of ManagedProjectBase #region Public Static Methods /// /// Returns a value indicating whether the project represented by the /// specified XML fragment is supported by . /// /// XML fragment representing the project to check. /// /// if supports the /// specified project; otherwise, . /// /// /// /// A project is identified as as Visual Basic project, if the XML /// fragment at least has the following information: /// /// /// /// /// ... /// /// /// ]]> /// /// public static bool IsSupported(XmlElement docElement) { if (docElement == null) { return false; } if (docElement.Name != "VisualStudioProject") { return false; } XmlNode projectNode = docElement.SelectSingleNode("./VisualBasic"); if (projectNode == null) { return false; } try { GetProductVersion(projectNode); // no need to perform version check here as this is done in // GetProductVersion } catch { // product version could not be determined or is not supported return false; } return true; } #endregion Public Static Methods #region Private Instance Fields private readonly NamespaceImportCollection _imports; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.VSNet/ProjectSettings.cs0000644000175000017500000003410011757302274021132 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Matthew Mastracci (matt@aclaro.com) using System; using System.CodeDom.Compiler; using System.Collections; using System.Globalization; using System.IO; using System.Xml; using NAnt.Core; using NAnt.Core.Util; namespace NAnt.VSNet { public class ProjectSettings { #region Public Instance Constructors public ProjectSettings(XmlElement elemRoot, XmlElement elemSettings, ManagedProjectBase project) { _project = project; _settings = new ArrayList(); // check whether build file is valid if (elemRoot.FirstChild == null) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Project file '{0}' is not valid.", Project.ProjectPath), Location.UnknownLocation); } _guid = ProjectSettings.GetProjectGuid(project.ProjectPath, elemRoot); // determine output type of this project _outputType = GetOutputType(elemSettings); // initialize hashtable for holding string settings Hashtable htStringSettings = new Hashtable(); switch (_outputType) { case ManagedOutputType.Library: _settings.Add("/target:library"); break; case ManagedOutputType.Executable: _settings.Add("/target:exe"); // startup object only makes sense for executable assemblies htStringSettings["StartupObject"] = @"/main:""{0}"""; break; case ManagedOutputType.WindowsExecutable: _settings.Add("/target:winexe"); // startup object only makes sense for executable assemblies htStringSettings["StartupObject"] = @"/main:""{0}"""; break; } // suppresses display of Microsoft startup banner _settings.Add("/nologo"); _assemblyName = elemSettings.Attributes["AssemblyName"].Value; // the key file to use to sign ActiveX/COM wrappers _assemblyOriginatorKeyFile = StringUtils.ConvertEmptyToNull( elemSettings.Attributes["AssemblyOriginatorKeyFile"].Value); // the key container to use to sign ActiveX/COM wrappers _assemblyKeyContainerName = StringUtils.ConvertEmptyToNull( elemSettings.Attributes["AssemblyKeyContainerName"].Value); // pre and post build events are VS .NET 2003 specific, so do not // assume they are there if (elemSettings.Attributes["RunPostBuildEvent"] != null) { _runPostBuildEvent = StringUtils.ConvertEmptyToNull( elemSettings.Attributes["RunPostBuildEvent"].Value); } if (elemSettings.Attributes["PreBuildEvent"] != null) { _preBuildEvent = StringUtils.ConvertEmptyToNull( elemSettings.Attributes["PreBuildEvent"].Value); } if (elemSettings.Attributes["PostBuildEvent"] != null) { _postBuildEvent = StringUtils.ConvertEmptyToNull( elemSettings.Attributes["PostBuildEvent"].Value); } if (elemSettings.Attributes["RootNamespace"] != null) { _rootNamespace = StringUtils.ConvertEmptyToNull( elemSettings.Attributes["RootNamespace"].Value); if (RootNamespace != null && Project.Type == ProjectType.VB) { _settings.Add("/rootnamespace:" + _rootNamespace); } } if (elemSettings.Attributes["ApplicationIcon"] != null) { string value = StringUtils.ConvertEmptyToNull( elemSettings.Attributes["ApplicationIcon"].Value); if (value != null) { _applicationIcon = new FileInfo(FileUtils.CombinePaths( Project.ProjectDirectory.FullName, value)); } } // process VB.NET specific project settings if (Project.Type == ProjectType.VB) { if (elemSettings.Attributes["OptionExplicit"] != null) { if (elemSettings.Attributes ["OptionExplicit"].Value == "Off") { _settings.Add("/optionexplicit-"); } else { _settings.Add("/optionexplicit+"); } } if (elemSettings.Attributes["OptionStrict"] != null) { if (elemSettings.Attributes ["OptionStrict"].Value == "Off") { _settings.Add("/optionstrict-"); } else { _settings.Add("/optionstrict+"); } } if (elemSettings.Attributes["OptionCompare"] != null) { if (elemSettings.Attributes ["OptionCompare"].Value == "Text") { _settings.Add("/optioncompare:text"); } else { _settings.Add("/optioncompare:binary"); } } } foreach (DictionaryEntry de in htStringSettings) { string value = elemSettings.GetAttribute(de.Key.ToString()); if (String.IsNullOrEmpty(value)) { // skip empty values continue; } _settings.Add(string.Format(de.Value.ToString(), value)); } } #endregion Public Instance Constructors #region Public Instance Properties public string[] Settings { get { return (string[]) _settings.ToArray(typeof(string)); } } /// /// Gets the .ico file to use as application icon. /// /// /// The .ico file to use as application icon, or /// if no application icon should be used. /// public FileInfo ApplicationIcon { get { return _applicationIcon; } } public string AssemblyName { get { return _assemblyName; } } /// /// Gets the key file to use to sign ActiveX/COM wrappers. /// /// /// The path of the key file to use to sign ActiveX/COM wrappers, /// relative to the project root directory, or /// if the wrapper assembly should not be signed using a key file. /// public string AssemblyOriginatorKeyFile { get { return _assemblyOriginatorKeyFile; } } /// /// Gets the key name to use to sign ActiveX/COM wrappers. /// /// /// The name of the key container to use to sign ActiveX/COM wrappers, /// or if the wrapper assembly should not be /// signed using a key container. /// public string AssemblyKeyContainerName { get { return _assemblyKeyContainerName; } } public TempFileCollection TemporaryFiles { get { return Project.TemporaryFiles; } } public string OutputFileName { get { return string.Concat(AssemblyName, OutputExtension); } } /// /// Gets the output type of this project. /// public ManagedOutputType OutputType { get { return _outputType; } } public string OutputExtension { get { switch (OutputType) { case ManagedOutputType.Library: return ".dll"; case ManagedOutputType.Executable: case ManagedOutputType.WindowsExecutable: default: return ".exe"; } } } public string RootNamespace { get { return _rootNamespace; } } public string Guid { get { return _guid; } } /// /// Designates when the command line should /// be run. Possible values are "OnBuildSuccess", "Always" or /// "OnOutputUpdated". /// public string RunPostBuildEvent { get { return _runPostBuildEvent; } } /// /// Contains commands to be run before a build takes place. /// /// /// Valid commands are those in a .bat file. For more info see MSDN. /// public string PreBuildEvent { get { return _preBuildEvent; } } /// /// Contains commands to be ran after a build has taken place. /// /// /// Valid commands are those in a .bat file. For more info see MSDN. /// public string PostBuildEvent { get { return _postBuildEvent; } } #endregion Public Instance Properties #region Private Instance Properties private ManagedProjectBase Project { get { return _project; } } #endregion Private Instance Properties #region Protected Instance Methods /// /// Determines the output type of the project from its XML definition. /// /// The XML definition of the project settings. /// /// The output type of the project. /// /// /// /// The output type of the project is not set in the specified XML /// definition. /// /// -or- /// /// The output type of the project is not supported. /// /// protected virtual ManagedOutputType GetOutputType(XmlElement settingsXml) { XmlAttribute outputTypeAttribute = settingsXml.Attributes["OutputType"]; if (outputTypeAttribute == null) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Project \"{0}\" is invalid: the output type is not set.", Project.Name), Location.UnknownLocation); } switch (outputTypeAttribute.Value.ToLower(CultureInfo.InvariantCulture)) { case "library": return ManagedOutputType.Library; case "exe": return ManagedOutputType.Executable; case "winexe": return ManagedOutputType.WindowsExecutable; default: throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Output type \"{0}\" of project \"{1}\" is not supported.", outputTypeAttribute.Value, Project.Name), Location.UnknownLocation); } } #endregion Protected Instance Methods #region Public Static Methods /// /// Gets the project GUID from the given /// holding a <VisualStudioProject> node. /// /// The path of the project file. /// The <VisualStudioProject> node from which the project GUID should be retrieved. /// /// The project GUID from specified <VisualStudioProject> node. /// public static string GetProjectGuid(string projectFile, XmlElement elemRoot) { XmlAttribute projectGuid = (XmlAttribute) elemRoot.FirstChild. Attributes["ProjectGuid"]; if (projectGuid == null) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Project file '{0}' is not valid. There's no \"ProjectGuid\"" + " attribute on the <{1} ... /> node.", projectFile, elemRoot.FirstChild.Name), Location.UnknownLocation); } return projectGuid.Value.ToUpper(CultureInfo.InvariantCulture); } #endregion Public Static Methods #region Public Instance Methods public string GetTemporaryFilename(string fileName) { return FileUtils.CombinePaths(TemporaryFiles.BasePath, fileName); } #endregion Public Instance Methods #region Private Instance Fields private readonly ArrayList _settings; private readonly FileInfo _applicationIcon; private readonly ManagedProjectBase _project; private readonly string _assemblyName; private readonly string _assemblyOriginatorKeyFile; private readonly string _assemblyKeyContainerName; private readonly string _rootNamespace; private readonly string _guid; private readonly string _runPostBuildEvent; private readonly string _preBuildEvent; private readonly string _postBuildEvent; private readonly ManagedOutputType _outputType; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.VSNet/WebDavClient.cs0000644000175000017500000001203511757302274020315 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Matthew Mastracci (matt@aclaro.com) using System; using System.IO; using System.Net; namespace NAnt.VSNet { public class WebDavClient { #region Public Instance Constructors public WebDavClient(Uri uriBase) { _webProjectBaseUrl = uriBase.ToString(); } #endregion Public Instance Constructors #region Public Instance Methods public void UploadFile(string localFileName, string remoteFileName) { WebRequest request = WebRequest.Create(_webProjectBaseUrl + "/" + remoteFileName); request.Method = "PUT"; request.Headers.Add("Translate: f"); request.Credentials = CredentialCache.DefaultCredentials; FileInfo fi = new FileInfo(localFileName); request.ContentLength = fi.Length; int bufferSize = 100 * 1024; byte[] buffer = new byte[bufferSize]; using (FileStream fsInput = new FileStream(fi.FullName, FileMode.Open)) { using (Stream s = request.GetRequestStream()) { int nRead; do { nRead = fsInput.Read(buffer, 0, bufferSize); s.Write(buffer, 0, nRead); } while (nRead > 0); } } buffer = null; try { using (request.GetResponse()) { } } catch (WebException we) { HttpWebResponse hwr = ( HttpWebResponse )we.Response; if ((int) hwr.StatusCode != 423) { throw; } } } public void DeleteFile(string localFileName, string remoteFileName) { WebRequest request = WebRequest.Create(_webProjectBaseUrl + "/" + remoteFileName); request.Method = "DELETE"; request.Headers.Add("Translate: f"); request.Credentials = CredentialCache.DefaultCredentials; using (request.GetResponse()) { } } public void DownloadFile(string localFileName, string remoteFileName) { WebRequest request = WebRequest.Create(_webProjectBaseUrl + "/" + remoteFileName); request.Method = "GET"; request.Headers.Add("Translate: f"); request.Credentials = CredentialCache.DefaultCredentials; FileInfo fi = new FileInfo(localFileName); if (!Directory.Exists(fi.DirectoryName)) { Directory.CreateDirectory(fi.DirectoryName); } int bufferSize = 100 * 1024; byte[] buffer = new byte[bufferSize]; using (FileStream fsOutput = new FileStream(fi.FullName, FileMode.OpenOrCreate)) { using (Stream s = request.GetResponse().GetResponseStream()) { int nRead; do { nRead = s.Read(buffer, 0, bufferSize); fsOutput.Write(buffer, 0, nRead); } while (nRead > 0); } } buffer = null; } public string GetFileContents(string remoteFileName) { WebRequest request = WebRequest.Create(_webProjectBaseUrl + "/" + remoteFileName); request.Method = "GET"; request.Headers.Add("Translate: f"); request.Credentials = CredentialCache.DefaultCredentials; using (StreamReader sr = new StreamReader(request.GetResponse().GetResponseStream())) { return sr.ReadToEnd(); } } #endregion Public Instance Methods #region Public Static Methods public static string GetFileContentsStatic(string remoteFileName) { WebRequest request = WebRequest.Create(remoteFileName); request.Method = "GET"; request.Headers.Add("Translate: f"); request.Credentials = CredentialCache.DefaultCredentials; using (StreamReader sr = new StreamReader(request.GetResponse().GetResponseStream())) { return sr.ReadToEnd(); } } #endregion Public Static Methods #region Private Instance Fields private string _webProjectBaseUrl; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.VSNet/ManagedProjectReference.cs0000644000175000017500000000737011757302274022516 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.CodeDom.Compiler; using System.IO; using System.Xml; using NAnt.Core; using NAnt.Core.Util; namespace NAnt.VSNet { public class ManagedProjectReference : ProjectReferenceBase { public ManagedProjectReference(XmlElement xmlDefinition, ReferencesResolver referencesResolver, ProjectBase parent, SolutionBase solution, TempFileCollection tfc, GacCache gacCache, DirectoryInfo outputDir) : base(referencesResolver, parent) { if (xmlDefinition == null) { throw new ArgumentNullException("xmlDefinition"); } if (solution == null) { throw new ArgumentNullException("solution"); } if (tfc == null) { throw new ArgumentNullException("tfc"); } if (gacCache == null) { throw new ArgumentNullException("gacCache"); } XmlAttribute privateAttribute = xmlDefinition.Attributes["Private"]; if (privateAttribute != null) { _isPrivateSpecified = true; _isPrivate = bool.Parse(privateAttribute.Value); } // determine path of project file string projectFile = solution.GetProjectFileFromGuid( xmlDefinition.GetAttribute("Project")); // load referenced project _project = LoadProject(solution, tfc, gacCache, outputDir, projectFile); } public ManagedProjectReference(ProjectBase project, ProjectBase parent, bool isPrivateSpecified, bool isPrivate) : base(project.ReferencesResolver, parent) { _project = project; _isPrivateSpecified = isPrivateSpecified; _isPrivate = isPrivate; } #region Override implementation of ProjectReferenceBase public override ProjectBase Project { get { return _project; } } protected override bool IsPrivate { get { return _isPrivate; } } protected override bool IsPrivateSpecified { get { return _isPrivateSpecified; } } #endregion Override implementation of ProjectReferenceBase #region Override implementation of ReferenceBase /// /// Gets a value indicating whether the reference is managed for the /// specified configuration. /// /// The solution configuration that is built. /// /// . /// public override bool IsManaged(Configuration solutionConfiguration) { return true; } #endregion Override implementation of ReferenceBase #region Private Instance Fields private readonly ProjectBase _project; private readonly bool _isPrivateSpecified; private readonly bool _isPrivate; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.VSNet/Types/0000755000175000017500000000000011757310030016547 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.VSNet/Types/UseOfMFC.cs0000644000175000017500000000242211757302274020460 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Hani Atassi (haniatassi@users.sourceforge.net) namespace NAnt.VSNet.Types { /// /// Defines how the project is using the MFC library. /// public enum UseOfMFC { /// /// Don't use MFC. /// NotUsing = 0, /// /// Use MFC in a Static Library. /// Static = 1, /// /// Use MFC in a Shared DLL. /// Shared = 2 } } nant-0.92-rc1/src/NAnt.VSNet/Types/WebMap.cs0000644000175000017500000000755011757302274020273 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Tom Cabanski (tcabanski@OAI.cc) using System; using System.Collections.Specialized; using System.IO; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Types; using NAnt.Core.Util; namespace NAnt.VSNet.Types { /// /// Represents a single mapping from URL project path to physical project /// path. /// [Serializable()] public class WebMap : Element { #region Private Instance Fields private string _url; private FileInfo _path; private bool _caseSensitive; private bool _ifDefined = true; private bool _unlessDefined; #endregion Private Instance Fields #region Public Instance Properties /// /// Specifies the URL of the project file, or a URL fragment to match. /// /// /// The URL of the project file or the URL fragment to match. /// [TaskAttribute("url", Required=true)] [StringValidator(AllowEmpty=false)] public string Url { get { return _url; } set { _url = StringUtils.ConvertEmptyToNull(value); } } /// /// Specifies the actual path to the project file, or the path fragment /// to replace. /// /// /// The actual path to the project file or the path fragment to replace /// the URL fragment with. /// [TaskAttribute("path", Required=true)] public FileInfo Path { get { return _path; } set { _path = value; } } /// /// Specifies whether the mapping is case-sensitive or not. /// /// /// A boolean flag representing the case-sensitivity of the mapping. Default is . /// [TaskAttribute("casesensitive", Required=false)] [BooleanValidator()] public bool CaseSensitive { get { return _caseSensitive; } set { _caseSensitive = value; } } /// /// Indicates if the URL of the project file should be mapped. /// /// /// if the URL of the project file should be /// mapped; otherwise, . /// [TaskAttribute("if")] [BooleanValidator()] public bool IfDefined { get { return _ifDefined; } set { _ifDefined = value; } } /// /// Indicates if the URL of the project file should not be mapped. /// /// /// if the URL of the project file should not /// be mapped; otherwise, . /// [TaskAttribute("unless")] [BooleanValidator()] public bool UnlessDefined { get { return _unlessDefined; } set { _unlessDefined = value; } } #endregion Public Instance Properties } } nant-0.92-rc1/src/NAnt.VSNet/Types/WebMapCollection.cs0000644000175000017500000002610311757302274022302 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; using System.Globalization; namespace NAnt.VSNet.Types { /// /// Contains a strongly typed collection of /// objects. /// [Serializable()] public class WebMapCollection : CollectionBase { #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public WebMapCollection() { } /// /// Initializes a new instance of the class /// with the specified instance. /// public WebMapCollection(WebMapCollection value) { AddRange(value); } /// /// Initializes a new instance of the class /// with the specified array of instances. /// public WebMapCollection(WebMap[] value) { AddRange(value); } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets the element at the specified index. /// /// The zero-based index of the element to get or set. [System.Runtime.CompilerServices.IndexerName("Item")] public WebMap this[int index] { get { return ((WebMap)(base.List[index])); } set { base.List[index] = value; } } /// /// Gets the with the specified value. /// /// The value of the to get. [System.Runtime.CompilerServices.IndexerName("Item")] public WebMap this[string value] { get { if (value != null) { // Try to locate instance using Value foreach (WebMap WebMap in base.List) { if (string.Compare(WebMap.Url, value, !WebMap.CaseSensitive, CultureInfo.InvariantCulture) == 0) { return WebMap; } } } return null; } } /// /// Find the best matching for the given Uri. /// /// The value to match against the objects in the collection. public string FindBestMatch(string uri) { string bestMatch = null; int bestMatchLength = Int32.MinValue; foreach (WebMap webMap in base.List) { if (!webMap.IfDefined || webMap.UnlessDefined) continue; string testSubject = webMap.CaseSensitive ? uri : uri.ToUpper(CultureInfo.InvariantCulture); string testTarget = webMap.CaseSensitive ? webMap.Url : webMap.Url.ToUpper(CultureInfo.InvariantCulture); if (testSubject.StartsWith(testTarget) && testTarget.Length > bestMatchLength) { bestMatchLength = testTarget.Length; bestMatch = webMap.Path.FullName + uri.Substring(testTarget.Length); } } return bestMatch; } #endregion Public Instance Properties #region Public Instance Methods /// /// Adds a to the end of the collection. /// /// The to be added to the end of the collection. /// The position into which the new element was inserted. public int Add(WebMap item) { return base.List.Add(item); } /// /// Adds the elements of a array to the end of the collection. /// /// The array of elements to be added to the end of the collection. public void AddRange(WebMap[] items) { for (int i = 0; (i < items.Length); i = (i + 1)) { Add(items[i]); } } /// /// Adds the elements of a to the end of the collection. /// /// The to be added to the end of the collection. public void AddRange(WebMapCollection items) { for (int i = 0; (i < items.Count); i = (i + 1)) { Add(items[i]); } } /// /// Determines whether a is in the collection. /// /// The to locate in the collection. /// /// if is found in the /// collection; otherwise, . /// public bool Contains(WebMap item) { return base.List.Contains(item); } /// /// Determines whether a with the specified /// value is in the collection. /// /// The argument value to locate in the collection. /// /// if a with value /// is found in the collection; otherwise, /// . /// public bool Contains(string value) { return this[value] != null; } /// /// Copies the entire collection to a compatible one-dimensional array, starting at the specified index of the target array. /// /// The one-dimensional array that is the destination of the elements copied from the collection. The array must have zero-based indexing. /// The zero-based index in at which copying begins. public void CopyTo(WebMap[] array, int index) { base.List.CopyTo(array, index); } /// /// Retrieves the index of a specified object in the collection. /// /// The object for which the index is returned. /// /// The index of the specified . If the is not currently a member of the collection, it returns -1. /// public int IndexOf(WebMap item) { return base.List.IndexOf(item); } /// /// Inserts a into the collection at the specified index. /// /// The zero-based index at which should be inserted. /// The to insert. public void Insert(int index, WebMap item) { base.List.Insert(index, item); } /// /// Returns an enumerator that can iterate through the collection. /// /// /// A for the entire collection. /// public new WebMapEnumerator GetEnumerator() { return new WebMapEnumerator(this); } /// /// Removes a member from the collection. /// /// The to remove from the collection. public void Remove(WebMap item) { base.List.Remove(item); } #endregion Public Instance Methods } /// /// Enumerates the elements of a . /// public class WebMapEnumerator : IEnumerator { #region Internal Instance Constructors /// /// Initializes a new instance of the class /// with the specified . /// /// The collection that should be enumerated. internal WebMapEnumerator(WebMapCollection arguments) { IEnumerable temp = (IEnumerable) (arguments); _baseEnumerator = temp.GetEnumerator(); } #endregion Internal Instance Constructors #region Implementation of IEnumerator /// /// Gets the current element in the collection. /// /// /// The current element in the collection. /// public WebMap Current { get { return (WebMap) _baseEnumerator.Current; } } object IEnumerator.Current { get { return _baseEnumerator.Current; } } /// /// Advances the enumerator to the next element of the collection. /// /// /// if the enumerator was successfully advanced /// to the next element; if the enumerator has /// passed the end of the collection. /// public bool MoveNext() { return _baseEnumerator.MoveNext(); } bool IEnumerator.MoveNext() { return _baseEnumerator.MoveNext(); } /// /// Sets the enumerator to its initial position, which is before the /// first element in the collection. /// public void Reset() { _baseEnumerator.Reset(); } void IEnumerator.Reset() { _baseEnumerator.Reset(); } #endregion Implementation of IEnumerator #region Private Instance Fields private IEnumerator _baseEnumerator; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.VSNet/Types/UseOfATL.cs0000644000175000017500000000242211757302274020473 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Hani Atassi (haniatassi@users.sourceforge.net) namespace NAnt.VSNet.Types { /// /// Defines how the project is using the ATL library. /// public enum UseOfATL { /// /// Don't use ATL. /// NotUsing = 0, /// /// Use ATL in a Static Library. /// Static = 1, /// /// Use ATL in a Shared DLL. /// Shared = 2 } } nant-0.92-rc1/src/NAnt.VSNet/Types/UsePrecompiledHeader.cs0000644000175000017500000000473711757302274023155 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Simon Keary (simonkeary@post.com) namespace NAnt.VSNet.Types { /// /// Indicates the possible ways in which precompiled header file use is /// specified in a Visual C++ project. /// /// /// The integer values assigned match those specified in the Visual C++ /// project file for each setting. /// > public enum UsePrecompiledHeader { /// /// Precompiled header file use not specified. /// Unspecified = -1, /// /// Don't use a precompiled header file. /// /// /// For further information on the use of this option /// see the Microsoft documentation on the C++ compiler flag /Yc. /// No = 0, /// /// Create precompiled header file. /// /// /// For further information on the use of this option /// see the Microsoft documentation on the C++ compiler flag /Yc. /// Create = 1, /// /// Automatically create precompiled header file if necessary. /// /// /// For further information on the use of this option /// see the Microsoft documentation on the C++ compiler flag /Yc. /// AutoCreate = 2, /// /// Use a precompiled header file. /// /// /// For further information on the use of this option /// see the Microsoft documentation on the C++ compiler flag /Yu. /// Use = 3 } } nant-0.92-rc1/src/NAnt.VSNet/ManagedWrapperReference.cs0000644000175000017500000003414011757302274022523 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Matthew Mastracci (matt@aclaro.com) // Scott Ford (sford@RJKTECH.com) // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Globalization; using System.IO; using System.Xml; using Microsoft.Win32; using NAnt.Core; using NAnt.Core.Tasks; using NAnt.Core.Util; using NAnt.Core.Types; using NAnt.Win32.Tasks; namespace NAnt.VSNet { public class ManagedWrapperReference : WrapperReferenceBase { #region Public Instance Constructors public ManagedWrapperReference(XmlElement xmlDefinition, ReferencesResolver referencesResolver, ProjectBase parent, GacCache gacCache, ProjectSettings projectSettings) : base(xmlDefinition, referencesResolver, parent, gacCache) { if (projectSettings == null) { throw new ArgumentNullException("projectSettings"); } _projectSettings = projectSettings; // determine name of wrapper reference XmlAttribute wrapperNameAttribute = XmlDefinition.Attributes["Name"]; if (wrapperNameAttribute != null) { _name = wrapperNameAttribute.Value; } // determine wrapper tool XmlAttribute toolAttribute = XmlDefinition.Attributes["WrapperTool"]; if (toolAttribute == null) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Wrapper tool for reference \"{0}\" in project \"{1}\" could" + " not be determined.", Name, Parent.Name), Location.UnknownLocation); } _wrapperTool = toolAttribute.Value; // determine if there's a primary interop assembly for the typelib _primaryInteropAssembly = GetPrimaryInteropAssembly(); // determine filename of wrapper assembly _wrapperAssembly = ResolveWrapperAssembly(); } #endregion Public Instance Constructors #region Override implementation of ReferenceBase /// /// Gets the name of the referenced assembly. /// /// /// The name of the referenced assembly, or if /// the name could not be determined. /// public override string Name { get { return _name; } } #endregion Override implementation of ReferenceBase #region Override implementation of WrapperReferenceBase /// /// Gets the name of the tool that should be used to create the /// . /// /// /// The name of the tool that should be used to create the /// . /// public override string WrapperTool { get { return _wrapperTool; } } /// /// Gets the path of the wrapper assembly. /// /// /// The path of the wrapper assembly. /// /// /// The wrapper assembly is stored in the object directory of the /// project. /// public override string WrapperAssembly { get { return _wrapperAssembly; } } /// /// Gets the path of the Primary Interop Assembly. /// /// /// The path of the Primary Interop Assembly, or /// if not available. /// protected override string PrimaryInteropAssembly { get { return _primaryInteropAssembly; } } /// /// Gets the hex version of the type library as defined in the definition /// of the reference. /// /// /// The hex version of the type library. /// /// /// /// The definition of the reference does not contain a "VersionMajor" attribute. /// /// -or /// /// The definition of the reference does not contain a "VersionMinor" attribute. /// /// protected override string TypeLibVersion { get { XmlAttribute majorAttribute = XmlDefinition.Attributes["VersionMajor"]; if (majorAttribute == null) { throw new BuildException("The definition of the reference" + " does not contain a \"VersionMajor\" attribute."); } XmlAttribute minorAttribute = XmlDefinition.Attributes["VersionMinor"]; if (minorAttribute == null) { throw new BuildException("The definition of the reference" + " does not contain a \"VersionMinor\" attribute."); } string majorVersion = (int.Parse(majorAttribute.Value, CultureInfo.InvariantCulture)).ToString("x", CultureInfo.InvariantCulture); string minorVersion = (int.Parse(minorAttribute.Value, CultureInfo.InvariantCulture)).ToString("x", CultureInfo.InvariantCulture); return majorVersion + "." + minorVersion; } } /// /// Gets the GUID of the type library as defined in the definition /// of the reference. /// /// /// The GUID of the type library. /// protected override string TypeLibGuid { get { XmlAttribute guidAttribute = XmlDefinition.Attributes["Guid"]; if (guidAttribute == null) { throw new BuildException("The definition of the reference" + " does not contain a \"Guid\" attribute."); } return guidAttribute.Value; } } /// /// Gets the locale of the type library in hex notation. /// /// /// The locale of the type library. /// protected override string TypeLibLocale { get { XmlAttribute localeAttribute = XmlDefinition.Attributes["Lcid"]; if (localeAttribute == null) { throw new BuildException("The definition of the reference" + " does not contain a \"Lcid\" attribute."); } return int.Parse(localeAttribute.Value).ToString("x"); } } #endregion Override implementation of WrapperReferenceBase #region Private Instance Properties private ProjectSettings ProjectSettings { get { return _projectSettings; } } #endregion Private Instance Properties #region Private Instance Methods protected override void ImportTypeLibrary() { TlbImpTask tlbImp = new TlbImpTask(); // parent is solution task tlbImp.Parent = SolutionTask; // inherit project from solution task tlbImp.Project = SolutionTask.Project; // inherit namespace manager from solution task tlbImp.NamespaceManager = SolutionTask.NamespaceManager; // inherit verbose setting from solution task tlbImp.Verbose = SolutionTask.Verbose; // make sure framework specific information is set tlbImp.InitializeTaskConfiguration(); tlbImp.TypeLib = new FileInfo(GetTypeLibrary()); tlbImp.OutputFile = new FileInfo(WrapperAssembly); tlbImp.Namespace = TypeLibraryName; // according to "COM Programming with Microsoft .NET" (page 59) // the /sysarray option should always be set in order to // generate wrappers that match those generated by VS.NET tlbImp.SysArray = true; // transform [out, retval] parameters of methods on dispatch-only // interfaces (dispinterfaces) into return values. // // this only affects .NET 1.1 or higher, as tlbimp does not expose // this on .NET 1.0. tlbImp.Transform = "dispret"; // use other imported type libraries to resolve references // // there's one serious limitation in the current implementation: // // if type library A references type library B, then we should // first import type library B and use a reference to that // imported type library when we import type library A. // // however, we have no way to find out in which order the type // libraries should be imported. So only if type library B is // first listed in the project file, it will work fine. // // we should find a way to analyse a type library to determine // dependencies on other type libraries // // according to JR (jrv72@users.sourceforge.net) a possible // solution could be to "use TypeLibConverter.ConvertTypeLibToAssembly. // This has a callback of type ITypeLibImporterNotifySink, which I // speculate allows one to recognize when one type library // depends on another. I believe what you have to do is start // with an arbitrary type library, and if that type library calls // back on the ResolveRef() method, and if that type library is // one you were planning to add later, you compile it // immediately and pass the assembly back out of ResolveRef. I // haven't tested this yet, but it's my best understanding of // how it all works. foreach (ReferenceBase reference in Parent.References) { // we're only interested in imported type libraries WrapperReferenceBase wrapper = reference as WrapperReferenceBase; // avoid stack overflow causes by mutual dependencies if (wrapper == null || !wrapper.IsCreated || wrapper.WrapperTool != "tlbimp") { continue; } tlbImp.References.Includes.Add(wrapper.WrapperAssembly); } if (ProjectSettings.AssemblyOriginatorKeyFile != null) { tlbImp.KeyFile = new FileInfo(FileUtils.CombinePaths(Parent.ProjectDirectory.FullName, ProjectSettings.AssemblyOriginatorKeyFile)); } if (ProjectSettings.AssemblyKeyContainerName != null) { tlbImp.KeyContainer = ProjectSettings.AssemblyKeyContainerName; } // increment indentation level tlbImp.Project.Indent(); try { // execute task tlbImp.Execute(); } finally { // restore indentation level tlbImp.Project.Unindent(); } } protected override void ImportActiveXLibrary() { AxImpTask axImp = new AxImpTask(); // parent is solution task axImp.Parent = SolutionTask; // inherit project from solution task axImp.Project = SolutionTask.Project; // inherit namespace manager from solution task axImp.NamespaceManager = SolutionTask.NamespaceManager; // inherit verbose setting from solution task axImp.Verbose = SolutionTask.Verbose; // make sure framework specific information is set axImp.InitializeTaskConfiguration(); axImp.OcxFile = new FileInfo(GetTypeLibrary()); axImp.OutputFile = new FileInfo(WrapperAssembly); if (ProjectSettings.AssemblyOriginatorKeyFile != null) { axImp.KeyFile = new FileInfo(FileUtils.CombinePaths(Parent.ProjectDirectory.FullName, ProjectSettings.AssemblyOriginatorKeyFile)); } if (ProjectSettings.AssemblyKeyContainerName != null) { axImp.KeyContainer = ProjectSettings.AssemblyKeyContainerName; } string rcw = PrimaryInteropAssembly; if (rcw == null) { // if no primary interop assembly is provided for ActiveX control, // then use the imported type library (if available) rcw = FileUtils.CombinePaths(Parent.ObjectDir.FullName, "Interop." + TypeLibraryName + ".dll"); } if (File.Exists(rcw)) { axImp.RcwFile = new FileInfo(rcw); } // increment indentation level axImp.Project.Indent(); try { // execute task axImp.Execute(); } finally { // restore indentation level axImp.Project.Unindent(); } } #endregion Private Instance Methods #region Private Instance Fields private string _name; private readonly string _wrapperTool; private readonly string _wrapperAssembly; private readonly ProjectSettings _projectSettings; private string _primaryInteropAssembly; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.VSNet/VcProjectConfiguration.cs0000644000175000017500000007675611757302274022461 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2005 Gert Driesen // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Xml; using NAnt.Core; using NAnt.Core.Util; using NAnt.VisualCpp.Types; using NAnt.VSNet.Types; namespace NAnt.VSNet { /// /// Represents a Visual C++ project configuration. /// public class VcProjectConfiguration : VcConfigurationBase { #region Internal Instance Constructors internal VcProjectConfiguration(XmlElement elem, VcProject parentProject, DirectoryInfo outputDir) : base(elem, parentProject, outputDir) { // determine relative output directory (outdir) XmlAttribute outputDirAttribute = elem.Attributes["OutputDirectory"]; if (outputDirAttribute != null) { _rawRelativeOutputDir = outputDirAttribute.Value; } // get intermediate directory and expand macros XmlAttribute intermidiateDirAttribute = elem.Attributes["IntermediateDirectory"]; if (intermidiateDirAttribute != null) { _rawIntermediateDir = intermidiateDirAttribute.Value; } // get referencespath directory and expand macros XmlAttribute referencesPathAttribute = elem.Attributes["ReferencesPath"]; if (referencesPathAttribute != null) { _rawReferencesPath = StringUtils.ConvertEmptyToNull(referencesPathAttribute.Value); } string managedExtentions = GetXmlAttributeValue(elem, "ManagedExtensions"); if (managedExtentions != null) { switch(managedExtentions.ToLower()) { case "false": case "0": _managedExtensions = false; break; case "true": case "1": _managedExtensions = true; break; default: throw new BuildException(String.Format("ManagedExtensions '{0}' is not supported yet.",managedExtentions)); } } // get configuration type string type = GetXmlAttributeValue(elem, "ConfigurationType"); if (type != null) { _type = (ConfigurationType) Enum.ToObject(typeof(ConfigurationType), int.Parse(type, CultureInfo.InvariantCulture)); } string wholeProgramOptimization = GetXmlAttributeValue(elem, "WholeProgramOptimization"); if (wholeProgramOptimization != null) { _wholeProgramOptimization = string.Compare(wholeProgramOptimization.Trim(), "true", true, CultureInfo.InvariantCulture) == 0; } string characterSet = GetXmlAttributeValue(elem, "CharacterSet"); if (characterSet != null) { _characterSet = (CharacterSet) Enum.ToObject(typeof(CharacterSet), int.Parse(characterSet, CultureInfo.InvariantCulture)); } // get MFC settings string useOfMFC = GetXmlAttributeValue(elem, "UseOfMFC"); if (useOfMFC != null) { _useOfMFC = (UseOfMFC) Enum.ToObject(typeof(UseOfMFC), int.Parse(useOfMFC, CultureInfo.InvariantCulture)); } // get ATL settings string useOfATL = GetXmlAttributeValue(elem, "UseOfATL"); if (useOfATL != null) { _useOfATL = (UseOfATL) Enum.ToObject(typeof(UseOfATL), int.Parse(useOfATL, CultureInfo.InvariantCulture)); } _linkerConfiguration = new LinkerConfig(this); } #endregion Internal Instance Constructors #region Public Instance Properties public ConfigurationType Type { get { return _type; } } public bool WholeProgramOptimization { get { return _wholeProgramOptimization; } } /// /// Tells the compiler which character set to use. /// public CharacterSet CharacterSet { get { return _characterSet; } } /// /// Gets a value indicating whether Managed Extensions for C++ are /// enabled. /// public bool ManagedExtensions { get { return _managedExtensions; } } /// /// Gets a value indicating how MFC is used by the configuration. /// public UseOfMFC UseOfMFC { get { return _useOfMFC; } } /// /// Gets a value indicating how ATL is used by the configuration. /// public UseOfATL UseOfATL { get { return _useOfATL; } } #endregion Public Instance Properties #region Internal Instance Properties internal string RawRelativeOutputDir { get { return _rawRelativeOutputDir;} } internal string RawIntermediateDir { get { return _rawIntermediateDir;} } internal string RawReferencesPath { get { return _rawReferencesPath; } } internal LinkerConfig LinkerConfiguration { get { return _linkerConfiguration; } } /// /// Gets the list of files to link in the order in which they are /// defined in the project file. /// internal ArrayList ObjFiles { get { // lazy init if (!_initialized) { Initialize(); } return _objFiles; } } /// /// Holds the C++ sources for each build configuration. /// /// /// The key of the hashtable is a build configuration, and the /// value is an ArrayList holding the C++ source files for that /// build configuration. /// internal Hashtable SourceConfigs { get { // lazy init if (!_initialized) { Initialize(); } return _sourceConfigs; } } /// /// Gets the resources for each build configuration. /// /// /// The key of the hashtable is a build configuration, and the /// value is an ArrayList holding the resources files for that /// build configuration. /// internal Hashtable RcConfigs { get { // lazy init if (!_initialized) { Initialize(); } return _rcConfigs; } } /// /// Get the IDL files for each build configuration. /// /// /// The key of the hashtable is a build configuration, and the /// value is an ArrayList holding the IDL files for that build /// configuration. /// internal Hashtable IdlConfigs { get { // lazy init if (!_initialized) { Initialize(); } return _idlConfigs; } } #endregion Internal Instance Properties #region Private Instance Properties /// /// Gets the target path for usage in macro expansion. /// /// /// The target path, or a zero-length string if there's no output file /// for this configuration. /// private string TargetPath { get { string targetPath = string.Empty; switch (Type) { case ConfigurationType.Application: string applicationOutput = GetToolSetting(VcConfigurationBase.LinkerTool, "OutputFile"); if (String.IsNullOrEmpty(applicationOutput)) { applicationOutput = ExpandMacros("$(OutDir)/$(ProjectName).exe"); } targetPath = FileUtils.CombinePaths(Project.ProjectDirectory.FullName, applicationOutput); break; case ConfigurationType.DynamicLibrary: string libraryOutput = GetToolSetting(VcConfigurationBase.LinkerTool, "OutputFile"); if (String.IsNullOrEmpty(libraryOutput)) { libraryOutput = ExpandMacros("$(OutDir)/$(ProjectName).dll"); } targetPath = FileUtils.CombinePaths(Project.ProjectDirectory.FullName, libraryOutput); break; case ConfigurationType.StaticLibrary: string librarianOutput = GetToolSetting(VcConfigurationBase.LibTool, "OutputFile"); if (String.IsNullOrEmpty(librarianOutput)) { librarianOutput = ExpandMacros("$(OutDir)/$(ProjectName).lib"); } targetPath = FileUtils.CombinePaths(Project.ProjectDirectory.FullName, librarianOutput); break; case ConfigurationType.Makefile: string nmakeOutput = GetToolSetting(VcConfigurationBase.NMakeTool, "Output"); if (!String.IsNullOrEmpty(nmakeOutput)) { targetPath = FileUtils.CombinePaths(Project.ProjectDirectory.FullName, nmakeOutput); } break; case ConfigurationType.Utility: break; } return targetPath; } } #endregion Private Instance Properties #region Override implementation of ConfigurationBase /// /// Get the directory in which intermediate build output will be stored /// for this configuration. /// /// /// /// This is a directory relative to the project directory named /// obj\<configuration name>. /// /// /// .resx and .licx files will only be recompiled if the /// compiled resource files in the are not /// uptodate. /// /// public override DirectoryInfo ObjectDir { get { return new DirectoryInfo(FileUtils.CombinePaths(Project.ProjectDirectory.FullName, IntermediateDir)); } } /// /// Get the path of the output directory relative to the project /// directory. /// public override string RelativeOutputDir { get { return ExpandMacros(RawRelativeOutputDir); } } #endregion Override implementation of ConfigurationBase #region Override implementation of VcConfigurationBase /// /// Gets the intermediate directory, specified relative to project /// directory. /// /// /// The intermediate directory, specified relative to project directory. /// public override string IntermediateDir { get { return ExpandMacros(RawIntermediateDir); } } /// /// Gets the absolute path for the output file. /// /// /// The absolute path for the output file, or /// if there's no output file for this configuration. /// public override string OutputPath { get { // lazy init if (!_initialized) { Initialize(); } return _outputPath; } } /// /// Gets a comma-separated list of directories to scan for assembly /// references. /// /// /// A comma-separated list of directories to scan for assembly /// references, or if no additional directories /// should scanned. /// public override string ReferencesPath { get { return ExpandMacros(RawReferencesPath); } } internal string GetToolSetting(string toolName, string settingName, ExpansionHandler expander) { return GetToolSetting(toolName, settingName, (string) null, expander); } public override string GetToolSetting(string toolName, string settingName, string defaultValue) { return GetToolSetting(toolName, settingName, defaultValue, new ExpansionHandler(ExpandMacros)); } internal string GetToolSetting(string toolName, string settingName, string defaultValue, ExpansionHandler expander) { string setting = null; Hashtable toolSettings = (Hashtable) Tools[toolName]; if (toolSettings != null) { setting = (string) toolSettings[settingName]; if (setting != null) { // expand macros return expander(setting); } } if (setting == null && defaultValue != null) { return expander(defaultValue); } return setting; } public override Hashtable GetToolArguments(string toolName, VcArgumentMap argMap, VcArgumentMap.ArgGroup ignoreGroup) { return GetToolArguments(toolName, argMap, ignoreGroup, new ExpansionHandler(ExpandMacros)); } internal Hashtable GetToolArguments(string toolName, VcArgumentMap argMap, VcArgumentMap.ArgGroup ignoreGroup, ExpansionHandler expander) { Hashtable args = CollectionsUtil.CreateCaseInsensitiveHashtable(); Hashtable toolSettings = (Hashtable) Tools[toolName]; if (toolSettings != null) { foreach (DictionaryEntry de in toolSettings) { string arg = argMap.GetArgument((string) de.Key, expander((string) de.Value), ignoreGroup); if (arg != null) { args[(string) de.Key] = arg; } } } return args; } /// /// Expands the given macro. /// /// The macro to expand. /// /// The expanded macro. /// /// /// The macro is not supported. /// -or- /// The macro is not implemented. /// -or- /// The macro cannot be expanded. /// /// /// Expansion of a given macro is not yet implemented. /// protected internal override string ExpandMacro(string macro) { // perform case-insensitive expansion of macros switch (macro.ToLower(CultureInfo.InvariantCulture)) { case "targetname": // E.g. WindowsApplication1 return Path.GetFileNameWithoutExtension(Path.GetFileName( TargetPath)); case "targetpath": // E.g. C:\Doc...\Visual Studio Projects\WindowsApplications1\bin\Debug\WindowsApplications1.exe return TargetPath; case "targetext": // E.g. .exe return Path.GetExtension(TargetPath); case "targetfilename": // E.g. WindowsApplications1.exe return Path.GetFileName(TargetPath); case "targetdir": // E.g. C:\Doc...\Visual Studio Projects\WindowsApplications1\bin\Debug return Path.GetDirectoryName(TargetPath) + (TargetPath.EndsWith( Path.DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture)) ? string.Empty : Path.DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture)); default: return base.ExpandMacro(macro); } } #endregion Override implementation of VcConfigurationBase #region Private Instance Methods private void Initialize() { VcProject vcProject = (VcProject) Project; // determine directory for storing intermediate build output for // current project build configuration string intermediateDir = FileUtils.CombinePaths(vcProject.ProjectDirectory.FullName, IntermediateDir); foreach (object projectFile in vcProject.ProjectFiles) { string fileName = null; VcConfigurationBase fileConfig = null; // the array list contains either strings or hashtables if (projectFile is string) { fileName = (string) projectFile; } else { Hashtable fileConfigurations = (Hashtable) projectFile; // obtain file configuration for current build configuration VcFileConfiguration configuration = (VcFileConfiguration) fileConfigurations[Name]; if (configuration != null && configuration.ExcludeFromBuild) { continue; } fileConfig = configuration; // determine relative path if (configuration == null) { // obtain relative path for other build configuration // as the relative is the same anyway foreach (DictionaryEntry de in fileConfigurations) { configuration = (VcFileConfiguration) de.Value; break; } } fileName = configuration.RelativePath; } string ext = Path.GetExtension(fileName).ToLower(CultureInfo.InvariantCulture); // if there's no specific file configuration (for the current // build configuration), then use the project configuration if (fileConfig == null) { fileConfig = this; } switch (ext) { case ".cpp": case ".c": if (!_sourceConfigs.ContainsKey(fileConfig)) { _sourceConfigs[fileConfig] = new ArrayList(1); } // add file to list of sources to build with this config ((ArrayList) _sourceConfigs[fileConfig]).Add(fileName); // register output file for linking _objFiles.Add(vcProject.GetObjOutputFile(fileName, fileConfig, intermediateDir)); break; case ".rc": if (!_rcConfigs.ContainsKey(fileConfig)) { _rcConfigs[fileConfig] = new ArrayList(1); } // add file to list of resources to build with this config ((ArrayList) _rcConfigs[fileConfig]).Add(fileName); // register output file for linking _objFiles.Add(vcProject.GetResourceOutputFile(fileName, fileConfig)); break; case ".idl": case ".odl": // ODL is used for old OLE objects if (!_idlConfigs.ContainsKey(fileConfig)) { _idlConfigs[fileConfig] = new ArrayList(1); } // add file to list of idl's to build with this config ((ArrayList) _idlConfigs[fileConfig]).Add(fileName); break; } } switch (Type) { case ConfigurationType.StaticLibrary: _outputPath = GetLibrarianOutputFile(intermediateDir); break; case ConfigurationType.Application: case ConfigurationType.DynamicLibrary: _outputPath = GetLinkerOutputFile(); break; case ConfigurationType.Makefile: string nmakeOutput = GetToolSetting(VcConfigurationBase.NMakeTool, "Output"); if (!String.IsNullOrEmpty(nmakeOutput)) { _outputPath = FileUtils.CombinePaths(Project.ProjectDirectory.FullName, nmakeOutput); } break; } // mark initialization complete _initialized = true; } private string GetLibrarianOutputFile(string intermediateDir) { if (_objFiles.Count == 0) { return null; } string outFile = GetToolSetting(VcConfigurationBase.LibTool, "OutputFile", "$(OutDir)/$(ProjectName).lib"); // if OutputFile is explicitly set to an empty string, VS.NET // uses file name of first obj file (in intermediate directory) if (String.IsNullOrEmpty(outFile)) { outFile = FileUtils.CombinePaths(intermediateDir, Path.GetFileNameWithoutExtension((string) _objFiles[0]) + ".lib"); } else { outFile = FileUtils.CombinePaths(Project.ProjectDirectory.FullName, outFile); } return outFile; } private string GetLinkerOutputFile() { const string noinherit = "$(noinherit)"; string addDeps = GetToolSetting(VcConfigurationBase.LinkerTool, "AdditionalDependencies"); if (!String.IsNullOrEmpty(addDeps)) { // remove noherit macro from addDeps if (addDeps.ToLower(CultureInfo.InvariantCulture).IndexOf(noinherit) != -1) { addDeps = addDeps.Remove(addDeps.ToLower(CultureInfo.InvariantCulture).IndexOf(noinherit), noinherit.Length); } string[] depParts = addDeps.Split(' '); for (int i = 0; i < depParts.Length; i++) { string addDep = depParts[i]; if (Path.GetExtension(addDep) == ".obj") { _objFiles.Insert(i, addDep); } } } if (_objFiles.Count == 0) { return null; } string extension = string.Empty; switch (Type) { case ConfigurationType.Application: extension = ".exe"; break; case ConfigurationType.DynamicLibrary: extension = ".dll"; break; } // output file name string outFile = GetToolSetting(VcConfigurationBase.LinkerTool, "OutputFile", "$(OutDir)/$(ProjectName)" + extension); // if OutputFile is explicitly set to an empty string, VS.NET // uses file name of first obj file (in the current directory) and // extention based on configuration type if (String.IsNullOrEmpty(outFile)) { outFile = FileUtils.CombinePaths(Project.ProjectDirectory.FullName, Path.GetFileNameWithoutExtension((string) _objFiles[0]) + extension); } if (SolutionTask.OutputDir != null) { outFile = FileUtils.CombinePaths(SolutionTask.OutputDir.FullName, Path.GetFileName(outFile)); } else { outFile = FileUtils.CombinePaths(Project.ProjectDirectory.FullName, outFile); } return outFile; } #endregion Private Instance Methods #region Private Static Methods /// /// Gets the value of the specified attribute from the specified node. /// /// The node of which the attribute value should be retrieved. /// The attribute of which the value should be returned. /// /// The value of the attribute with the specified name or /// if the attribute does not exist or has no value. /// private static string GetXmlAttributeValue(XmlNode xmlNode, string attributeName) { string attributeValue = null; if (xmlNode != null) { XmlAttribute xmlAttribute = (XmlAttribute) xmlNode.Attributes.GetNamedItem(attributeName); if (xmlAttribute != null) { attributeValue = StringUtils.ConvertEmptyToNull(xmlAttribute.Value); } } return attributeValue; } #endregion Private Static Methods #region Private Instance Fields private readonly string _rawRelativeOutputDir; private readonly string _rawIntermediateDir; private readonly string _rawReferencesPath; private readonly ConfigurationType _type; private readonly bool _wholeProgramOptimization; private readonly bool _managedExtensions; private readonly CharacterSet _characterSet = CharacterSet.NotSet; private readonly UseOfMFC _useOfMFC = UseOfMFC.NotUsing; private readonly UseOfATL _useOfATL = UseOfATL.NotUsing; private readonly LinkerConfig _linkerConfiguration; private bool _initialized; /// /// Holds the output path for this build configuration. /// /// /// Lazy initialized by . /// private string _outputPath; /// /// Holds list of files to link in the order in which they are defined /// in the project file. /// private readonly ArrayList _objFiles = new ArrayList(); /// /// Holds the C++ sources for each build configuration. /// /// /// The key of the hashtable is a build configuration, and the /// value is an ArrayList holding the C++ source files for that /// build configuration. /// private readonly Hashtable _sourceConfigs = new Hashtable(); /// /// Holds the resources for each build configuration. /// /// /// The key of the hashtable is a build configuration, and the /// value is an ArrayList holding the resources files for that /// build configuration. /// private readonly Hashtable _rcConfigs = new Hashtable(); /// /// Holds the IDL files for each build configuration. /// /// /// The key of the hashtable is a build configuration, and the /// value is an ArrayList holding the IDL files for that build /// configuration. /// private readonly Hashtable _idlConfigs = new Hashtable(); #endregion Private Instance Fields /// /// The type of output for a given configuration. /// public enum ConfigurationType { /// /// A Makefile. /// Makefile = 0, /// /// Application (.exe). /// Application = 1, /// /// Dynamic Library (.dll). /// DynamicLibrary = 2, /// /// Static Library (.lib). /// StaticLibrary = 4, /// /// Utility. /// Utility = 10 } internal class LinkerConfig { #region Private Instance Constructor internal LinkerConfig(VcProjectConfiguration projectConfig) { _projectConfig = projectConfig; } #endregion Private Instance Constructor #region Public Instance Properties /// /// Gets a instance representing the /// absolute path to the import library to generate. /// /// /// A representing the absolute path to the /// import library to generate, or if no /// import library must be generated. /// public FileInfo ImportLibrary { get { string defaultImportLibrary = null; if (!Project.IsManaged(_projectConfig.SolutionTask.SolutionConfig)) { defaultImportLibrary = "$(OutDir)/$(TargetName).lib"; } string importLibrary = StringUtils.ConvertEmptyToNull( _projectConfig.GetToolSetting(VcConfigurationBase.LinkerTool, "ImportLibrary", defaultImportLibrary)); if (importLibrary == null) { // no import library must be generated return null; } if (_projectConfig.SolutionTask.OutputDir != null) { importLibrary = FileUtils.CombinePaths( _projectConfig.SolutionTask.OutputDir.FullName, Path.GetFileName(importLibrary)); } else { importLibrary = FileUtils.CombinePaths( Project.ProjectDirectory.FullName, importLibrary); } return new FileInfo(importLibrary); } } #endregion Public Instance Properties #region Private Instance Properties private VcProject Project { get { return (VcProject) _projectConfig.Project; } } #endregion Private Instance Properties #region Private Instance Fields private readonly VcProjectConfiguration _projectConfig; #endregion Private Instance Fields } } } nant-0.92-rc1/src/NAnt.VSNet/GenericSolution.cs0000644000175000017500000000266611757302274021130 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.CodeDom.Compiler; using System.Collections; using NAnt.Core; using NAnt.Core.Util; using NAnt.VSNet.Tasks; namespace NAnt.VSNet { /// /// Supports grouping of individual projects, and treating them as a solution. /// public class GenericSolution : SolutionBase { #region Public Instance Constructors public GenericSolution(SolutionTask solutionTask, TempFileCollection tfc, GacCache gacCache, ReferencesResolver refResolver) : base(solutionTask, tfc, gacCache, refResolver) { } #endregion Public Instance Constructors } } nant-0.92-rc1/src/NAnt.VSNet/Tasks/0000755000175000017500000000000011757310030016530 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.VSNet/Tasks/SolutionTask.cs0000644000175000017500000006265711757302274021551 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Matthew Mastracci (mmastrac at users.sourceforge.net) // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.Reflection; using System.IO; using Microsoft.Win32; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Extensibility; using NAnt.Core.Tasks; using NAnt.Core.Types; using NAnt.Core.Util; using NAnt.VSNet.Extensibility; using NAnt.VSNet.Types; using System.Security; using System.Security.Permissions; using System.Security.Policy; namespace NAnt.VSNet.Tasks { /// /// Compiles VS.NET solutions (or sets of projects), automatically determining /// project dependencies from inter-project references. /// /// /// /// This task support the following projects: /// /// /// /// Visual Basic .NET /// /// /// Visual C# .NET /// /// /// Visual J# .NET /// /// /// Visual C++ .NET /// /// /// /// Right now, only Microsoft Visual Studio .NET 2002 and 2003 solutions /// and projects are supported. Support for .NET Compact Framework projects /// is also not available at this time. /// /// /// The also supports the model of referencing /// projects by their output filenames, rather than referencing them inside /// the solution. It will automatically detect the existance of a file /// reference and convert it to a project reference. For example, if project /// "A" references the file in the release output directory of /// project "B", the will automatically /// convert this to a project dependency on project "B" and will /// reference the appropriate configuration output directory at the final /// build time (ie: reference the debug version of "B" if the /// solution is built as debug). /// /// /// The expects all project files to be valid /// XML files. /// ///

    Resx Files

    /// /// When building a project for a down-level target framework, special care /// should be given to resx files. Resx files (can) contain references to /// a specific version of CLR types, and as such are only upward compatible. /// /// /// For example: if you want to be able to build a project both as a .NET 1.0 /// and .NET 1.1 assembly, the resx files should only contain references to /// .NET 1.0 CLR types. Failure to do this may result in a /// failure at runtime on machines with only the .NET Framework 1.0 installed. /// ///
    /// /// /// Compiles all of the projects in test.sln, in release mode, in /// the proper order. /// /// /// /// ]]> /// /// /// /// /// Compiles all of the projects in projects.txt, in the proper /// order. /// /// /// /// /// /// ///
    /// ]]> /// /// /// /// /// Compiles projects A, B and C, using the output of project X as a /// reference. /// /// /// /// /// /// /// /// /// /// /// /// /// ]]> /// /// /// /// /// Compiles all of the projects in the solution except for project A. /// /// /// /// /// /// /// /// ]]> /// /// /// /// /// Compiles all of the projects in the solution mapping the specific project at /// http://localhost/A/A.csproj to c:\inetpub\wwwroot\A\A.csproj and any URLs under /// http://localhost/B/[remainder] to c:\other\B\[remainder]. This allows the build /// to work without WebDAV. /// /// /// /// /// /// /// /// /// ]]> /// /// /// /// /// Compiles all of the projects in the solution placing compiled outputs /// in c:\temp. /// /// /// ]]> /// /// [Serializable()] [TaskName("solution")] [PluginConsumer(typeof(IProjectBuildProvider))] [PluginConsumer(typeof(ISolutionBuildProvider))] public class SolutionTask : Task, IPluginConsumer { /// /// Private var containing custom properties. /// ArrayList _customproperties; #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public SolutionTask() { _customproperties = new ArrayList(); _projects = new FileSet(); _referenceProjects = new FileSet(); _excludeProjects = new FileSet(); _assemblyFolders = new FileSet(); _webMaps = new WebMapCollection(); _projectFactory = ProjectFactory.Create(this); _solutionFactory = SolutionFactory.Create(); _configuration = new Configuration (); } #endregion Public Instance Constructors #region Public Instance Properties /// /// The projects to build. /// [BuildElement("projects", Required=false)] public FileSet Projects { get { return _projects; } set { _projects = value; } } /// /// The projects to scan, but not build. /// /// /// These projects are used to resolve project references and are /// generally external to the solution being built. References to /// these project's output files are converted to use the appropriate /// solution configuration at build time. /// [BuildElement("referenceprojects", Required=false)] public FileSet ReferenceProjects { get { return _referenceProjects; } set { _referenceProjects = value; } } /// /// The name of the VS.NET solution file to build. /// /// /// /// The can be used instead to supply a list /// of Visual Studio.NET projects that should be built. /// /// [TaskAttribute("solutionfile", Required=false)] public FileInfo SolutionFile { get { return _solutionFile; } set { _solutionFile = value; } } /// /// The name of the solution configuration to build. /// /// /// /// Generally release or debug. Not case-sensitive. /// /// [TaskAttribute("configuration", Required=true)] [StringValidator(AllowEmpty=false)] public string Configuration { get { return _configuration.Name; } set { _configuration.Name = StringUtils.ConvertEmptyToNull(value); } } /// /// The name of platform to build the solution for. /// [TaskAttribute("platform", Required=false)] [StringValidator(AllowEmpty=true)] public string Platform { get { return _configuration.Platform; } set { _configuration.Platform = value; } } /// /// Gets the solution configuration to build. /// public Configuration SolutionConfig { get { return _configuration; } } /// /// The directory where compiled targets will be placed. This /// overrides path settings contained in the solution/project. /// [TaskAttribute("outputdir", Required=false)] public DirectoryInfo OutputDir { get { return _outputDir; } set { _outputDir = value; } } /// /// WebMap of URL's to project references. /// [BuildElementCollection("webmap", "map")] public WebMapCollection WebMaps { get { return _webMaps; } } /// /// Fileset of projects to exclude. /// [BuildElement("excludeprojects", Required=false)] public FileSet ExcludeProjects { get { return _excludeProjects; } set { _excludeProjects = value; } } /// /// Set of folders where references are searched when not found in path /// from project file (HintPath). /// [BuildElement("assemblyfolders", Required=false)] public FileSet AssemblyFolders { get { return _assemblyFolders; } set { _assemblyFolders = value; } } /// /// Includes Visual Studio search folders in reference search path. /// The default is . /// [TaskAttribute("includevsfolders")] [BooleanValidator()] public bool IncludeVSFolders { get { return _includeVSFolders; } set { _includeVSFolders = value; } } /// /// Allow the task to use WebDAV for retrieving/compiling the projects within solution. Use of /// is preferred over WebDAV. The default is . /// /// /// WebDAV support requires permission changes to be made on your project server. These changes may affect /// the security of the server and should not be applied to a public installation. /// Consult your web server or the NAnt Wiki documentation for more information. /// [TaskAttribute("enablewebdav", Required = false)] [BooleanValidator()] public bool EnableWebDav { get { return _enableWebDav; } set { _enableWebDav = value; } } /// /// Set of properties set at solution level. Builders for projects in solution may or may not use them. /// /// /// /// TODO: some documentataion which properties could be defined here. /// /// [BuildElementArray("property", ElementType = typeof(PropertyTask))] public ArrayList CustomProperties { get { return _customproperties; } } /// /// Gets the list of folders to scan for assembly references. /// /// /// The list of folders to scan for assembly references. /// public StringCollection AssemblyFolderList { get { if (_assemblyFolderList == null) { _assemblyFolderList = new StringCollection(); foreach (string folder in AssemblyFolders.DirectoryNames) { if (!_assemblyFolderList.Contains(folder)) { _assemblyFolderList.Add(folder); Log(Level.Debug, "Added \"{0}\" to AssemblyFolders.", folder); } } if (IncludeVSFolders) { StringCollection vsAssemblyFolders = BuildAssemblyFolders(); foreach (string folder in vsAssemblyFolders) { if (!_assemblyFolderList.Contains(folder)) { _assemblyFolderList.Add(folder); Log(Level.Debug, "Added \"{0}\" to AssemblyFolders.", folder); } } } } return _assemblyFolderList; } } #endregion Public Instance Properties #region Internal Instance Properties internal ProjectFactory ProjectFactory { get { return _projectFactory; } } internal SolutionFactory SolutionFactory { get { return _solutionFactory; } } #endregion Internal Instance Properties #region Implementation of IPluginConsumer void IPluginConsumer.ConsumePlugin(IPlugin plugin) { if (plugin is IProjectBuildProvider) ProjectFactory.RegisterProvider((IProjectBuildProvider) plugin); if (plugin is ISolutionBuildProvider) SolutionFactory.RegisterProvider((ISolutionBuildProvider) plugin); } #endregion Implementation of IPluginConsumer #region Override implementation of Task protected override void ExecuteTask() { Log(Level.Info, "Starting solution build."); if (SolutionFile != null) { if (!SolutionFile.Exists) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Couldn't find solution file '{0}'.", SolutionFile.FullName), Location); } } if (Projects.FileNames.Count > 0) { Log(Level.Verbose, "Included projects:" ); foreach (string projectFile in Projects.FileNames) { Log(Level.Verbose, " - " + projectFile); } } if (ReferenceProjects.FileNames.Count > 0) { Log(Level.Verbose, "Reference projects:"); foreach (string projectFile in ReferenceProjects.FileNames) { Log(Level.Verbose, " - " + projectFile); } } string basePath = null; try { using (TempFileCollection tfc = new TempFileCollection()) { // store the temp dir so we can clean it up later basePath = tfc.BasePath; // ensure temp directory exists if (!Directory.Exists(tfc.BasePath)) { Directory.CreateDirectory(tfc.BasePath); } // create temporary domain PermissionSet tempDomainPermSet = new PermissionSet(PermissionState.Unrestricted); AppDomain temporaryDomain = AppDomain.CreateDomain("temporaryDomain", AppDomain.CurrentDomain.Evidence, AppDomain.CurrentDomain.SetupInformation, tempDomainPermSet); try { ReferencesResolver referencesResolver = ((ReferencesResolver) temporaryDomain.CreateInstanceFrom(Assembly.GetExecutingAssembly().Location, typeof(ReferencesResolver).FullName).Unwrap()); using (GacCache gacCache = new GacCache(this.Project)) { SolutionBase sln = SolutionFactory.LoadSolution(this, tfc, gacCache, referencesResolver); if (!sln.Compile(_configuration)) { throw new BuildException("Project build failed.", Location); } } } finally { // unload temporary domain AppDomain.Unload(temporaryDomain); } } } finally { if (basePath != null && Directory.Exists(basePath)) { Log(Level.Debug, "Cleaning up temp folder '{0}'.", basePath); // delete temporary directory and all files in it DeleteTask deleteTask = new DeleteTask(); deleteTask.Project = Project; deleteTask.Parent = this; deleteTask.InitializeTaskConfiguration(); deleteTask.Directory = new DirectoryInfo(basePath); deleteTask.Threshold = Level.None; // no output in build log deleteTask.Execute(); } } } #endregion Override implementation of Task #region Internal Instance Methods /// /// Expands the given macro. /// /// The macro to expand. /// /// The expanded macro or if the macro is not /// supported. /// /// The macro cannot be expanded. internal string ExpandMacro(string macro) { // perform case-insensitive expansion of macros switch (macro.ToLower(CultureInfo.InvariantCulture)) { case "solutionfilename": // E.g. WindowsApplication1.sln if (SolutionFile != null) { return Path.GetFileName(SolutionFile.FullName); } else { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Macro \"{0}\" cannot be expanded, no solution file specified.", macro), Location.UnknownLocation); } case "solutionpath": // Absolute path for SolutionFileName if (SolutionFile != null) { return SolutionFile.FullName; } else { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Macro \"{0}\" cannot be expanded, no solution file specified.", macro), Location.UnknownLocation); } case "solutiondir": // SolutionPath without SolutionFileName appended if (SolutionFile != null) { return Path.GetDirectoryName(SolutionFile.FullName) + Path.DirectorySeparatorChar; } else { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Macro \"{0}\" cannot be expanded, no solution file specified.", macro), Location.UnknownLocation); } case "solutionname": // E.g. WindowsApplication1 if (SolutionFile != null) { return Path.GetFileNameWithoutExtension( SolutionFile.FullName); } else { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Macro \"{0}\" cannot be expanded, no solution file specified.", macro), Location.UnknownLocation); } case "solutionext": // Is this ever anything but .sln? if (SolutionFile != null) { return Path.GetExtension(SolutionFile.FullName); } else { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Macro \"{0}\" cannot be expanded, no solution file specified.", macro), Location.UnknownLocation); } default: return null; } } #endregion Internal Instance Methods #region Private Instance Methods /// /// Builds the list of folders that should be scanned for assembly /// references. /// /// /// The list of folders that should be scanned for assembly references. /// private StringCollection BuildAssemblyFolders() { StringCollection folderList = new StringCollection(); // determine version of Visual Studio .NET corresponding with // current target framework Version visualStudioVersion = Project.TargetFramework.VisualStudioVersion; // check HKCU BuildVisualStudioAssemblyFolders(folderList, Registry.CurrentUser, visualStudioVersion.ToString(2)); // check HKLM BuildVisualStudioAssemblyFolders(folderList, Registry.LocalMachine, visualStudioVersion.ToString(2)); // check HKCU for .NET Framework AssemblyFolders BuildDotNetAssemblyFolders(folderList, Registry.CurrentUser); // check HKLM for .NET Framework AssemblyFolders BuildDotNetAssemblyFolders(folderList, Registry.LocalMachine); return folderList; } private void BuildVisualStudioAssemblyFolders(StringCollection folderList, RegistryKey hive, string visualStudioVersion) { RegistryKey assemblyFolders = hive.OpenSubKey(@"SOFTWARE\Microsoft\VisualStudio\" + visualStudioVersion + @"\AssemblyFolders"); if (assemblyFolders == null) { return; } string[] subKeyNames = assemblyFolders.GetSubKeyNames(); foreach (string subKeyName in subKeyNames) { RegistryKey subKey = assemblyFolders.OpenSubKey(subKeyName); string folder = subKey.GetValue(string.Empty) as string; if (folder != null && !folderList.Contains(folder)) { folderList.Add(folder); } } } private void BuildDotNetAssemblyFolders(StringCollection folderList, RegistryKey hive) { RegistryKey assemblyFolders = hive.OpenSubKey(@"SOFTWARE\Microsoft\" + @".NETFramework\AssemblyFolders"); if (assemblyFolders == null) { return; } string[] subKeyNames = assemblyFolders.GetSubKeyNames(); foreach (string subKeyName in subKeyNames) { RegistryKey subKey = assemblyFolders.OpenSubKey(subKeyName); string folder = subKey.GetValue(string.Empty) as string; if (folder != null && !folderList.Contains(folder)) { folderList.Add(folder); } } } #endregion Private Instance Methods #region Private Instance Fields private FileInfo _solutionFile; private Configuration _configuration; private DirectoryInfo _outputDir; private FileSet _projects; private FileSet _referenceProjects; private FileSet _excludeProjects; private FileSet _assemblyFolders; private StringCollection _assemblyFolderList; private WebMapCollection _webMaps; private bool _includeVSFolders = true; private bool _enableWebDav; private readonly SolutionFactory _solutionFactory; private readonly ProjectFactory _projectFactory; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.VSNet/ProjectBase.cs0000644000175000017500000012301711757302274020212 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Dmitry Jemerov using System; using System.Collections; using System.Collections.Specialized; using System.CodeDom.Compiler; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Xml; using Microsoft.Win32; using NAnt.Core; using NAnt.Core.Functions; using NAnt.Core.Tasks; using NAnt.Core.Util; using NAnt.VSNet.Tasks; namespace NAnt.VSNet { /// /// Base class for all project classes. /// public abstract class ProjectBase { #region Protected Instance Constructors /// /// Initializes a new instance of the class. /// protected ProjectBase(XmlElement xmlDefinition, SolutionTask solutionTask, TempFileCollection temporaryFiles, GacCache gacCache, ReferencesResolver referencesResolver, DirectoryInfo outputDir) { if (xmlDefinition == null) { throw new ArgumentNullException("xmlDefinition"); } if (solutionTask == null) { throw new ArgumentNullException("solutionTask"); } if (temporaryFiles == null) { throw new ArgumentNullException("temporaryFiles"); } if (gacCache == null) { throw new ArgumentNullException("gacCache"); } if (referencesResolver == null) { throw new ArgumentNullException("referencesResolver"); } _projectConfigurations = new ConfigurationDictionary(); _buildConfigurations = new ConfigurationDictionary(); _extraOutputFiles = CollectionsUtil.CreateCaseInsensitiveHashtable(); // ensure the specified project is actually supported by this project VerifyProjectXml(xmlDefinition); _solutionTask = solutionTask; _temporaryFiles = temporaryFiles; _outputDir = outputDir; _gacCache = gacCache; _refResolver = referencesResolver; _productVersion = DetermineProductVersion(xmlDefinition); } #endregion Protected Instance Constructors #region Public Instance Properties /// /// Gets the Visual Studio product version of the project. /// /// /// The Visual Studio product version of the project. /// public ProductVersion ProductVersion { get { return _productVersion; } } /// /// Gets the name of the VS.NET project. /// public abstract string Name { get; } /// /// Gets the type of the project. /// /// /// The type of the project. /// public abstract ProjectType Type { get; } /// /// Gets the path of the VS.NET project. /// public abstract string ProjectPath { get; } /// /// Gets the directory containing the VS.NET project. /// public abstract DirectoryInfo ProjectDirectory { get; } /// /// Get the location of the project. /// public abstract ProjectLocation ProjectLocation { get; } /// /// Get the directory in which intermediate build output that is not /// specific to the build configuration will be stored. /// /// /// /// For projects, this is defined /// as <Project Directory<\obj. /// /// /// For projects, this is defined /// as %HOMEPATH%\VSWebCache\<Machine Name>\<Project Directory>\obj. /// /// public virtual DirectoryInfo ObjectDir { get { switch (ProjectLocation) { case ProjectLocation.Web: string webCachePath = FileUtils.CombinePaths( FileUtils.GetHomeDirectory(), "VSWebCache"); string machinePath= FileUtils.CombinePaths(webCachePath, Environment.MachineName); string projectPath = FileUtils.CombinePaths(machinePath, Name); return new DirectoryInfo(FileUtils.CombinePaths(projectPath, "obj")); case ProjectLocation.Local: return new DirectoryInfo( FileUtils.CombinePaths(ProjectDirectory.FullName, "obj")); default: throw new NotSupportedException(ProjectLocation.ToString()); } } } /// /// Gets or sets the unique identifier of the VS.NET project. /// public abstract string Guid { get; set; } /// /// Gets a list of all configurations defined in the project. /// public ConfigurationDictionary ProjectConfigurations { get { return _projectConfigurations; } } /// /// Gets a list of project configurations that can be build. /// /// /// /// Project configurations that are not in this list do not need to be /// compiled. /// /// public ConfigurationDictionary BuildConfigurations { get { return _buildConfigurations; } } public abstract ArrayList References { get; } public SolutionTask SolutionTask { get { return _solutionTask; } } public TempFileCollection TemporaryFiles { get { return _temporaryFiles; } } /// /// Gets the extra set of output files for the project. /// /// /// The extra set of output files for the project. /// /// /// The key of the case-insensitive is the /// full path of the output file and the value is the path relative to /// the output directory. /// public Hashtable ExtraOutputFiles { get { return _extraOutputFiles; } } #endregion Public Instance Properties #region Protected Instance Properties protected DirectoryInfo OutputDir { get { return _outputDir; } } protected GacCache GacCache { get { return _gacCache; } } public ReferencesResolver ReferencesResolver { get { return _refResolver; } } /// /// Gets the set of projects that the project depends on. /// /// /// The set of projects that the project depends on. /// public ProjectBaseCollection ProjectDependencies { get { return _projectDependencies; } } protected virtual string DevEnvDir { get { string vs7CommonDirKeyName = @"SOFTWARE\Microsoft\VisualStudio\" + ProductVersionNumber + @"\Setup\VS"; RegistryKey vs7CommonDirKey = Registry.LocalMachine.OpenSubKey( vs7CommonDirKeyName); if (vs7CommonDirKey == null) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Registry key \"{0}\" could not be found.", vs7CommonDirKeyName), Location.UnknownLocation); } string vs7CommonDir = vs7CommonDirKey.GetValue("VS7CommonDir") as string; if (vs7CommonDir == null) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Value \"VS7CommonDir\" does not exist in registry key" + " \"{0}\".", vs7CommonDirKeyName), Location.UnknownLocation); } return FileUtils.CombinePaths(vs7CommonDir, @"IDE\"); } } #endregion Protected Instance Properties #region Private Instance Properties /// /// TODO: refactor this !!! /// private Version ProductVersionNumber { get { switch (ProductVersion) { case ProductVersion.Rainier: return new Version(7, 0); case ProductVersion.Everett: return new Version(7, 1); default: throw new Exception("Invalid product version \"" + ProductVersion + "\"."); } } } #endregion Private Instance Properties #region Public Instance Methods public abstract ProjectReferenceBase CreateProjectReference( ProjectBase project, bool isPrivateSpecified, bool isPrivate); public bool Compile(Configuration solutionConfiguration) { ConfigurationBase projectConfig = BuildConfigurations[solutionConfiguration]; if (projectConfig == null) { Log(Level.Info, "Skipping '{0}' [{1}] ...", Name, solutionConfiguration); return true; } Log(Level.Info, "Building '{0}' [{1}] ...", Name, projectConfig.Name); // ensure project-level object directory exists, no need to do this // for the project-level output directory as we already this before if (!ObjectDir.Exists) { ObjectDir.Create(); ObjectDir.Refresh(); } // build the project BuildResult result = Build(solutionConfiguration); return (result != BuildResult.Failed); } public string GetOutputPath(Configuration solutionConfiguration) { // obtain project configuration (corresponding with solution configuration) ConfigurationBase config = BuildConfigurations[solutionConfiguration]; if (config == null) { return null; } return config.OutputPath; } public ConfigurationBase GetConfiguration(Configuration solutionConfiguration) { // obtain project configuration (corresponding with solution configuration) return BuildConfigurations[solutionConfiguration]; } public StringCollection GetAssemblyReferences(Configuration solutionConfiguration) { Hashtable uniqueReferences = CollectionsUtil.CreateCaseInsensitiveHashtable(); foreach (ReferenceBase reference in References) { StringCollection references = reference.GetAssemblyReferences(solutionConfiguration); // avoid ambiguous references when the same assembly is // referenced multiple times // // this should only be possible for VB.NET project, as they // also include the assemblies referenced by referenced projects // // Project A references // Assembly 1 // Assembly 2 // Project B references // Assembly 3 // Project A // // then to compile Project B, VB.NET will use the following // assembly references: // // Assembly 1 // Assembly 2 // Assembly 3 // Project Output of Project A // // see bug #1178862 foreach (string assemblyFile in references) { try { // try to obtain AssemblyName of referenced assembly AssemblyName assemblyName = AssemblyName.GetAssemblyName(assemblyFile); if (!uniqueReferences.ContainsKey(assemblyName.FullName)) { uniqueReferences.Add(assemblyName.FullName, assemblyFile); } } catch (Exception ex) { // ignore assemblies that cannot be found or loaded Log(Level.Warning, "Referenced assembly \"{0}\" could not" + " be loaded: {1}", assemblyFile, ex.Message); } } } StringCollection assemblyReferences = new StringCollection(); foreach (DictionaryEntry entry in uniqueReferences) { assemblyReferences.Add((string) entry.Value); } return assemblyReferences; } /// /// Gets the complete set of output files for the project configuration /// matching the specified solution configuration. /// /// The solution configuration that is built. /// The set of output files to be updated. /// /// /// The key of the case-insensitive is the /// full path of the output file and the value is the path relative to /// the output directory. /// /// /// If the project is not configured to be built for the specified /// solution configuration, then no output files are added. /// /// public virtual void GetOutputFiles(Configuration solutionConfiguration, Hashtable outputFiles) { // obtain project configuration (corresponding with solution configuration) ConfigurationBase config = BuildConfigurations[solutionConfiguration]; if (config == null) { // the project is not configured to be built for the specified // solution configuration return; } foreach (ReferenceBase reference in References) { if (!reference.CopyLocal) { continue; } // only add output files of reference if we did not add them // already if (!outputFiles.ContainsKey(config.BuildPath)) { reference.GetOutputFiles(solutionConfiguration, outputFiles); } } // determine output file of project string projectOutputFile = config.BuildPath; // check if project has output file (eg. NMake project does not // necessarily have an output file) if (projectOutputFile != null && File.Exists(projectOutputFile)) { // get list of files related to project output file (eg. debug symbols, // xml doc, ...), this will include the project output file itself ReferenceBase.GetRelatedFiles(projectOutputFile, outputFiles); // NOTE: // // for now we assume that the extra output files do not need // to be copied/deployed if there's no main output file or // the main output file does not exist (eg. because of a compile // error) // add extra project-level output files foreach (DictionaryEntry de in ExtraOutputFiles) { outputFiles[(string) de.Key] = (string) de.Value; } // add extra configuration-level output files foreach (DictionaryEntry de in config.ExtraOutputFiles) { outputFiles[(string) de.Key] = (string) de.Value; } } } /// /// Gets a value indicating whether building the project for the specified /// build configuration results in managed output. /// /// The build configuration. /// /// if the project output for the given build /// configuration is managed; otherwise, . /// public abstract bool IsManaged(Configuration configuration); #endregion Public Instance Methods #region Protected Internal Instance Methods /// /// Expands the given macro. /// /// The macro to expand. /// /// The expanded macro or if the macro is not /// supported. /// protected internal virtual string ExpandMacro(string macro) { // perform case-insensitive expansion of macros switch (macro.ToLower(CultureInfo.InvariantCulture)) { case "projectname": // E.g. WindowsApplication1 return Name; case "projectpath": // E.g. C:\Doc...\Visual Studio Projects\WindowsApplications1\WindowsApplications1.csproj return ProjectPath; case "projectfilename": // E.g. WindowsApplication1.csproj return Path.GetFileName(ProjectPath); case "projectext": // .csproj return Path.GetExtension(ProjectPath); case "projectdir": // ProjectPath without ProjectFileName at the end return Path.GetDirectoryName(ProjectPath) + Path.DirectorySeparatorChar; case "devenvdir": return DevEnvDir; default: return null; } } #endregion Protected Internal Instance Methods #region Protected Instance Methods /// /// Returns the Visual Studio product version of the specified project /// XML fragment. /// /// XML fragment representing the project file. /// /// The Visual Studio product version of the specified project XML /// file. /// /// /// The product version could not be determined. /// -or- /// The product version is not supported. /// protected abstract ProductVersion DetermineProductVersion(XmlElement docElement); /// /// Verifies whether the specified XML fragment represents a valid project /// that is supported by this . /// /// XML fragment representing the project file. /// /// The XML fragment is not supported by this . /// -or- /// The XML fragment does not represent a valid project (for this ). /// protected abstract void VerifyProjectXml(XmlElement docElement); /// /// Prepares the project for being built. /// /// The solution configuration that is built. /// /// The default implementation will ensure that none of the output files /// are marked read-only. /// protected virtual void Prepare(Configuration solutionConfiguration) { // determine the output files of the project Hashtable outputFiles = CollectionsUtil.CreateCaseInsensitiveHashtable(); GetOutputFiles(solutionConfiguration, outputFiles); // use the task to ensure none of the output files are // marked read-only AttribTask attribTask = new AttribTask(); // parent is solution task attribTask.Parent = SolutionTask; // inherit project from solution task attribTask.Project = SolutionTask.Project; // inherit namespace manager from solution task attribTask.NamespaceManager = SolutionTask.NamespaceManager; // inherit verbose setting from solution task attribTask.Verbose = SolutionTask.Verbose; // only output warning messages or higher, unless // we're running in verbose mode if (!attribTask.Verbose) { attribTask.Threshold = Level.Warning; } // make sure framework specific information is set attribTask.InitializeTaskConfiguration(); // set parent of child elements attribTask.AttribFileSet.Parent = attribTask; // inherit project for child elements from containing task attribTask.AttribFileSet.Project = attribTask.Project; // inherit namespace manager from containing task attribTask.AttribFileSet.NamespaceManager = attribTask.NamespaceManager; // we want to reset the read-only attribute of all output files attribTask.ReadOnlyAttrib = false; // obtain project configuration (corresponding with solution configuration) ConfigurationBase config = BuildConfigurations[solutionConfiguration]; // add all output files to the fileset foreach (DictionaryEntry de in outputFiles) { attribTask.AttribFileSet.Includes.Add(FileUtils.CombinePaths( config.OutputDir.FullName, (string) de.Value)); } // increment indentation level attribTask.Project.Indent(); try { // execute task attribTask.Execute(); } finally { // restore indentation level attribTask.Project.Unindent(); } } protected abstract BuildResult Build(Configuration solutionConfiguration); /// /// Copies the specified file if the destination file does not exist, or /// the source file has been modified since it was previously copied. /// /// The file to copy. /// The destination file. /// The in which context the operation will be performed. protected void CopyFile(FileInfo srcFile, FileInfo destFile, Task parent) { // create instance of Copy task CopyTask ct = new CopyTask(); // parent is solution task ct.Parent = parent; // inherit project from parent task ct.Project = parent.Project; // inherit namespace manager from parent task ct.NamespaceManager = parent.NamespaceManager; // inherit verbose setting from parent task ct.Verbose = parent.Verbose; // only output warning messages or higher, unless // we're running in verbose mode if (!ct.Verbose) { ct.Threshold = Level.Warning; } // make sure framework specific information is set ct.InitializeTaskConfiguration(); // set parent of child elements ct.CopyFileSet.Parent = ct; // inherit project for child elements from containing task ct.CopyFileSet.Project = ct.Project; // inherit namespace manager from containing task ct.CopyFileSet.NamespaceManager = ct.NamespaceManager; // set file to copy ct.SourceFile = srcFile; // set file ct.ToFile = destFile; // increment indentation level ct.Project.Indent(); try { // execute task ct.Execute(); } finally { // restore indentation level ct.Project.Unindent(); } } protected bool ExecuteBuildEvent(string buildEvent, string buildCommandLine, string batchFile, string workingDirectory, ConfigurationBase config) { // create the batch file using (StreamWriter sw = new StreamWriter(batchFile)) { sw.WriteLine("@echo off"); // replace any VS macros in the command line with real values buildCommandLine = config.ExpandMacros(buildCommandLine); // handle linebreak charaters buildCommandLine = buildCommandLine.Replace(" ", "\n"); sw.WriteLine(buildCommandLine); sw.WriteLine("if errorlevel 1 goto EventReportError"); sw.WriteLine("goto EventEnd"); sw.WriteLine(":EventReportError"); sw.WriteLine("echo Project error: A tool returned an error code from the build event"); sw.WriteLine("exit 1"); sw.WriteLine(":EventEnd"); } // execute the batch file ProcessStartInfo psi = new ProcessStartInfo(batchFile); psi.UseShellExecute = false; psi.RedirectStandardOutput = true; // For logging psi.WorkingDirectory = workingDirectory; // start the process now Process batchEvent = Process.Start(psi); // keep logging output from the process for as long as it exists while (true) { string logContents = batchEvent.StandardOutput.ReadLine(); if (logContents == null) { break; } Log(Level.Verbose, " [" + buildEvent.ToLower(CultureInfo.InvariantCulture) + "] " + logContents); } batchEvent.WaitForExit(); // notify if there where problems running the batch file or it // returned errors int exitCode = batchEvent.ExitCode; if (exitCode == 0) { Log(Level.Verbose, "{0} succeeded (exit code = 0)", buildEvent); } else { Log(Level.Error, "{0} failed with exit code = {1}", buildEvent, exitCode); } return (exitCode == 0) ? true : false; } /// /// Logs a message with the given priority. /// /// The message priority at which the specified message is to be logged. /// The message to be logged. /// /// The actual logging is delegated to the underlying task. /// protected void Log(Level messageLevel, string message) { if (SolutionTask != null) { SolutionTask.Log(messageLevel, message); } } /// /// Logs a message with the given priority. /// /// The message priority at which the specified message is to be logged. /// The message to log, containing zero or more format items. /// An array containing zero or more objects to format. /// /// The actual logging is delegated to the underlying task. /// protected void Log(Level messageLevel, string message, params object[] args) { if (SolutionTask != null) { SolutionTask.Log(messageLevel, message, args); } } #endregion Protected Instance Methods #region Private Instance Fields private readonly ProductVersion _productVersion; private readonly SolutionTask _solutionTask; private readonly TempFileCollection _temporaryFiles; private readonly DirectoryInfo _outputDir; private readonly ConfigurationDictionary _projectConfigurations; private readonly ConfigurationDictionary _buildConfigurations; private readonly GacCache _gacCache; private readonly ReferencesResolver _refResolver; private readonly Hashtable _extraOutputFiles; private readonly ProjectBaseCollection _projectDependencies = new ProjectBaseCollection(); #endregion Private Instance Fields } /// /// Specifies the type of the project. /// public enum ProjectType { /// /// A Visual Basic.NET project. /// VB = 0, /// /// A Visual C# project. /// CSharp = 1, /// /// A Visual C++ project. /// VisualC = 2, /// /// A Visual J# project. /// JSharp = 3, /// /// MSBuild project. /// MSBuild = 4 } /// /// Specifies the result of the build. /// public enum BuildResult { /// /// The build failed. /// Failed = 0, /// /// The build succeeded. /// Success = 1, /// /// The build succeeded and the output was updated. /// SuccessOutputUpdated = 2, } public enum ProductVersion { /// /// Visual Studio.NET 2002 /// Rainier = 70, /// /// Visual Studio.NET 2003 /// Everett = 71, /// /// Visual Studio 2005 /// Whidbey = 80, /// /// Visual Studio 2008 /// Orcas = 90, /// /// Visual Studio 2010 /// Rosario = 100, } /// /// Indentifies the physical location of a managed project. /// public enum ProjectLocation { /// /// A local project. /// Local = 1, /// /// A web project. /// Web = 2, } /// /// Contains a collection of elements. /// [Serializable()] public class ProjectBaseCollection : CollectionBase { #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public ProjectBaseCollection() { } /// /// Initializes a new instance of the class /// with the specified instance. /// public ProjectBaseCollection(ProjectBaseCollection value) { AddRange(value); } /// /// Initializes a new instance of the class /// with the specified array of instances. /// public ProjectBaseCollection(ProjectBase[] value) { AddRange(value); } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets the element at the specified index. /// /// The zero-based index of the element to get or set. [System.Runtime.CompilerServices.IndexerName("Item")] public ProjectBase this[int index] { get { return (ProjectBase) base.List[index]; } set { base.List[index] = value; } } /// /// Gets the with the specified GUID. /// /// The GUID of the to get. /// /// Performs a case-insensitive lookup. /// [System.Runtime.CompilerServices.IndexerName("Item")] public ProjectBase this[string guid] { get { if (guid == null) { throw new ArgumentNullException("guid"); } // try to locate instance by guid (case-insensitive) foreach (ProjectBase project in base.List) { if (string.Compare(project.Guid, guid, true, CultureInfo.InvariantCulture) == 0) { return project; } } return null; } } #endregion Public Instance Properties #region Public Instance Methods /// /// Adds a to the end of the collection. /// /// The to be added to the end of the collection. /// The position into which the new element was inserted. public int Add(ProjectBase item) { return base.List.Add(item); } /// /// Adds the elements of a array to the end of the collection. /// /// The array of elements to be added to the end of the collection. public void AddRange(ProjectBase[] items) { for (int i = 0; (i < items.Length); i = (i + 1)) { Add(items[i]); } } /// /// Adds the elements of a to the end of the collection. /// /// The to be added to the end of the collection. public void AddRange(ProjectBaseCollection items) { for (int i = 0; (i < items.Count); i = (i + 1)) { Add(items[i]); } } /// /// Determines whether a is in the collection. /// /// The to locate in the collection. /// /// if is found in the /// collection; otherwise, . /// public bool Contains(ProjectBase item) { return base.List.Contains(item); } /// /// Determines whether a with the specified /// GUID is in the collection, using a case-insensitive lookup. /// /// The GUID to locate in the collection. /// /// if a with GUID /// is found in the collection; otherwise, /// . /// public bool Contains(string value) { return this[value] != null; } /// /// Copies the entire collection to a compatible one-dimensional array, starting at the specified index of the target array. /// /// The one-dimensional array that is the destination of the elements copied from the collection. The array must have zero-based indexing. /// The zero-based index in at which copying begins. public void CopyTo(ProjectBase[] array, int index) { base.List.CopyTo(array, index); } /// /// Retrieves the index of a specified object in the collection. /// /// The object for which the index is returned. /// /// The index of the specified . If the is not currently a member of the collection, it returns -1. /// public int IndexOf(ProjectBase item) { return base.List.IndexOf(item); } /// /// Inserts a into the collection at the specified index. /// /// The zero-based index at which should be inserted. /// The to insert. public void Insert(int index, ProjectBase item) { base.List.Insert(index, item); } /// /// Returns an enumerator that can iterate through the collection. /// /// /// A for the entire collection. /// public new ProjectBaseEnumerator GetEnumerator() { return new ProjectBaseEnumerator(this); } /// /// Removes a member from the collection. /// /// The to remove from the collection. public void Remove(ProjectBase item) { base.List.Remove(item); } /// /// Remove items with the specified guid from the collection. /// /// The guid of the project to remove from the collection. public void Remove(string guid) { ProjectBase removeProject = null; // try to locate instance by guid (case-insensitive) foreach (ProjectBase project in base.List) { if (string.Compare(project.Guid, guid, true, CultureInfo.InvariantCulture) == 0) { removeProject = project; break; } } if (removeProject != null) { base.InnerList.Remove(removeProject); } } #endregion Public Instance Methods } /// /// Enumerates the elements of a . /// public class ProjectBaseEnumerator : IEnumerator { #region Internal Instance Constructors /// /// Initializes a new instance of the class /// with the specified . /// /// The collection that should be enumerated. internal ProjectBaseEnumerator(ProjectBaseCollection arguments) { IEnumerable temp = (IEnumerable) (arguments); _baseEnumerator = temp.GetEnumerator(); } #endregion Internal Instance Constructors #region Implementation of IEnumerator /// /// Gets the current element in the collection. /// /// /// The current element in the collection. /// public ProjectBase Current { get { return (ProjectBase) _baseEnumerator.Current; } } object IEnumerator.Current { get { return _baseEnumerator.Current; } } /// /// Advances the enumerator to the next element of the collection. /// /// /// if the enumerator was successfully advanced /// to the next element; if the enumerator has /// passed the end of the collection. /// public bool MoveNext() { return _baseEnumerator.MoveNext(); } bool IEnumerator.MoveNext() { return _baseEnumerator.MoveNext(); } /// /// Sets the enumerator to its initial position, which is before the /// first element in the collection. /// public void Reset() { _baseEnumerator.Reset(); } void IEnumerator.Reset() { _baseEnumerator.Reset(); } #endregion Implementation of IEnumerator #region Private Instance Fields private IEnumerator _baseEnumerator; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.VSNet/VcConfigurationBase.cs0000644000175000017500000003242611757302274021707 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Dmitry Jemerov // Scott Ford (sford@RJKTECH.com) // Gert Driesen (drieseng@users.sourceforge.net) // Hani Atassi (haniatassi@users.sourceforge.net) using System; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Xml; using NAnt.Core; using NAnt.Core.Util; using NAnt.VisualCpp.Types; using NAnt.VSNet.Types; namespace NAnt.VSNet { /// /// A single build configuration for a Visual C++ project or for a specific /// file in the project. /// public abstract class VcConfigurationBase : ConfigurationBase { #region Delegates public delegate string ExpansionHandler(string value); #endregion Delegates #region Protected Instance Constructors protected VcConfigurationBase(XmlElement elem, ProjectBase parentProject, DirectoryInfo outputDir) : base(parentProject) { if (elem == null) { throw new ArgumentNullException("elem"); } // output directory override (if specified) _outputDir = outputDir; // get name of configuration (also contains the targeted platform) _name = elem.GetAttribute("Name"); XmlNodeList tools = elem.GetElementsByTagName("Tool"); foreach (XmlElement toolElem in tools) { string toolName = toolElem.GetAttribute("Name"); Hashtable htToolSettings = CollectionsUtil.CreateCaseInsensitiveHashtable(); foreach(XmlAttribute attr in toolElem.Attributes) { if (attr.Name != "Name") { htToolSettings[attr.Name] = attr.Value; } } Tools[toolName] = htToolSettings; } } protected VcConfigurationBase(string configName, ProjectBase parentProject, DirectoryInfo outputDir) : base(parentProject) { _name = configName; // set output directory (if specified) _outputDir = outputDir; } #endregion Protected Instance Constructors #region Public Instance Properties /// /// Gets the intermediate directory, specified relative to project /// directory. /// /// /// The intermediate directory, specified relative to project directory. /// public abstract string IntermediateDir { get; } /// /// Gets a comma-separated list of directories to scan for assembly /// references. /// /// /// A comma-separated list of directories to scan for assembly /// references, or if no additional directories /// should scanned. /// public abstract string ReferencesPath { get; } public UsePrecompiledHeader UsePrecompiledHeader { get { string usePCHString = GetToolSetting("VCCLCompilerTool", "UsePrecompiledHeader"); if (usePCHString == null) { return UsePrecompiledHeader.Unspecified; } int intVal = int.Parse(usePCHString, CultureInfo.InvariantCulture); if (this.Project.ProductVersion >= ProductVersion.Whidbey) { switch(intVal) { case 0 : return UsePrecompiledHeader.No; case 1: return UsePrecompiledHeader.Create; case 2: return UsePrecompiledHeader.Use; } } return (UsePrecompiledHeader) Enum.ToObject(typeof(UsePrecompiledHeader), intVal); } } #endregion Public Instance Properties #region Internal Instance Properties /// /// Gets the name of the configuration, including the platform it /// targets. /// /// /// Tthe name of the configuration, including the platform it targets. /// internal string FullName { get { return _name; } } #endregion Internal Instance Properties #region Override implementation of ConfigurationBase /// /// Gets the output directory. /// public override DirectoryInfo OutputDir { get { if (_outputDir == null) { if (RelativeOutputDir != null) { _outputDir = new DirectoryInfo(FileUtils.CombinePaths( Project.ProjectDirectory.FullName, RelativeOutputDir)); } else { throw new BuildException("The output directory could not be" + " determined.", Location.UnknownLocation); } } return _outputDir; } } /// /// Gets the path in which the output file will be created before its /// copied to the actual output path. /// /// /// For Visual C++ projects, the output file will be immediately /// created in the output path. /// public override string BuildPath { get { return OutputPath; } } /// /// Gets the name of the configuration. /// /// /// The name of the configuration. /// public override string Name { get { int index = _name.IndexOf("|"); if (index >= 0) { return _name.Substring(0, index); } else { return _name; } } } /// /// Gets the platform that the configuration targets. /// /// /// The platform targeted by the configuration. /// public override string PlatformName { get { int index = _name.IndexOf("|"); if (index >= 0) { if (index < _name.Length) { return _name.Substring(index + 1, _name.Length - 1 - index); } else { return string.Empty; } } else { return string.Empty; } } } /// /// Expands the given macro. /// /// The macro to expand. /// /// The expanded macro. /// /// /// The macro is not supported. /// -or- /// The macro is not implemented. /// -or- /// The macro cannot be expanded. /// protected internal override string ExpandMacro(string macro) { // perform case-insensitive expansion of macros switch (macro.ToLower(CultureInfo.InvariantCulture)) { case "noinherit": return "$(noinherit)"; case "intdir": return IntermediateDir; case "vcinstalldir": throw new NotImplementedException(string.Format(CultureInfo.InvariantCulture, "\"{0}\" macro is not yet implemented.", macro)); case "vsinstalldir": throw new NotImplementedException(string.Format(CultureInfo.InvariantCulture, "\"{0}\" macro is not yet implemented.", macro)); case "frameworkdir": return SolutionTask.Project.TargetFramework.FrameworkDirectory. Parent.FullName; case "frameworkversion": return "v" + SolutionTask.Project.TargetFramework.ClrVersion; case "frameworksdkdir": if (SolutionTask.Project.TargetFramework.SdkDirectory != null) { return SolutionTask.Project.TargetFramework.SdkDirectory.FullName; } else { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Macro \"{0}\" cannot be expanded: the SDK for {0}" + " is not installed.", SolutionTask.Project.TargetFramework.Description), Location.UnknownLocation); } default: try { return base.ExpandMacro(macro); } catch (BuildException) { // Visual C++ also supports environment variables string envvar = Environment.GetEnvironmentVariable(macro); if (envvar != null) { return envvar; } else { // re-throw build exception throw; } } } } #endregion Override implementation of ConfigurationBase #region Public Instance Methods /// /// Gets the value of a given setting for a specified tool. /// /// The name of the tool. /// The name of the setting. /// /// The value of a setting for the specified tool, or /// if the setting is not defined for the specified tool. /// /// /// An empty setting value, which is used as a means to override the /// project default, will be returned as a empty . /// public string GetToolSetting(string toolName, string settingName) { return GetToolSetting(toolName, settingName, (string) null); } /// /// Gets the value of a given setting for a specified tool. /// /// The name of the tool. /// The name of the setting. /// The value to return if setting is not defined. /// /// The value of a setting for the specified tool, or /// if the setting is not defined for /// the specified tool. /// /// /// An empty setting value, which is used as a means to override the /// project default, will be returned as a empty . /// public abstract string GetToolSetting(string toolName, string settingName, string defaultValue); public Hashtable GetToolArguments(string toolName, VcArgumentMap argMap) { return GetToolArguments(toolName, argMap, VcArgumentMap.ArgGroup.Unassigned); } public abstract Hashtable GetToolArguments(string toolName, VcArgumentMap argMap, VcArgumentMap.ArgGroup ignoreGroup); #endregion Public Instance Methods #region Protected Instance Fields protected readonly Hashtable Tools = CollectionsUtil.CreateCaseInsensitiveHashtable(); #endregion Protected Instance Fields #region Private Instance Fields private readonly string _name; private DirectoryInfo _outputDir; #endregion Private Instance Fields #region Internal Static Fields internal const string CLCompilerTool = "VCCLCompilerTool"; internal const string CustomBuildTool = "VCCustomBuildTool"; internal const string LinkerTool = "VCLinkerTool"; internal const string LibTool = "VCLibrarianTool"; internal const string ResourceCompilerTool = "VCResourceCompilerTool"; internal const string MIDLTool = "VCMIDLTool"; internal const string PreBuildEventTool = "VCPreBuildEventTool"; internal const string PostBuildEventTool = "VCPostBuildEventTool"; internal const string PreLinkEventTool = "VCPreLinkEventTool"; internal const string NMakeTool = "VCNMakeTool"; #endregion Internal Static Fields } } nant-0.92-rc1/src/NAnt.VSNet/VBProjectProvider.cs0000644000175000017500000000367111757302274021365 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Martin Aliger (martin_aliger@myrealbox.com) using System; using System.CodeDom.Compiler; using System.IO; using System.Xml; using NAnt.Core; using NAnt.Core.Util; using NAnt.VSNet.Extensibility; using NAnt.VSNet.Tasks; namespace NAnt.VSNet { internal class VBProjectProvider : IProjectBuildProvider { #region Implementation of IProjectBuildProvider public int IsSupported(string projectExt, XmlElement xmlDefinition) { if (projectExt == ".vbproj") return 5; if (VBProject.IsSupported(xmlDefinition)) return 10; return 0; } public ProjectBase GetInstance(SolutionBase solution, string projectPath, XmlElement xmlDefinition, SolutionTask solutionTask, TempFileCollection tfc, GacCache gacCache, ReferencesResolver refResolver, DirectoryInfo outputDir) { return new VBProject(solution, projectPath, xmlDefinition, solutionTask, tfc, gacCache, refResolver, outputDir); } public string LoadGuid(XmlElement xmlDefinition) { return VBProject.LoadGuid(xmlDefinition); } #endregion Implementation of IProjectBuildProvider } } nant-0.92-rc1/src/NAnt.VSNet/ProjectEntry.cs0000644000175000017500000003532411757302274020444 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2008 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net.be) using System; using System.Collections; using System.Globalization; using System.Runtime.CompilerServices; using NAnt.Core; namespace NAnt.VSNet { public class ProjectEntry { #region Private Instance Fields private readonly string _guid; private readonly string _path; private ProjectBase _project; private ConfigurationMap _buildConfigurations; #endregion Private Instance Fields #region Public Instance Constructors public ProjectEntry(string guid, string path) { if (guid == null) { throw new ArgumentNullException("guid"); } if (path == null) { throw new ArgumentNullException("path"); } _guid = guid; _path = path; } #endregion Public Instance Constructors #region Public Instance Properties public string Guid { get { return _guid; } } public string Path { get { return _path; } } /// /// Gets or sets the in memory representation of the project. /// /// /// The in memory representation of the project, or /// if the project is not (yet) loaded. /// /// /// This property will always be for /// projects that are not supported. /// public ProjectBase Project { get { return _project; } set { if (value != null) { // if the project GUID from the solution file doesn't match the // project GUID from the project file we will run into problems. // Alert the user to fix this as it is basically a corruption // probably caused by user manipulation of the solution file // i.e. copy and paste if (string.Compare(Guid, value.Guid, true, CultureInfo.InvariantCulture) != 0) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "GUID corruption detected for project '{0}'. GUID values" + " in project file and solution file do not match ('{1}'" + " and '{2}'). Please correct this manually.", value.Name, value.Guid, Guid), Location.UnknownLocation); } } _project = value; } } /// /// Return a mapping between the configurations defined in the /// solution file and the project build configurations. /// /// /// Mapping between configurations defined in the solution file /// and the project build configurations, or /// if the project is not defined in a solution file. /// /// /// This mapping only includes project build configurations that /// are configured to be built for a given solution configuration. /// public ConfigurationMap BuildConfigurations { get { return _buildConfigurations; } set { _buildConfigurations = value; } } #endregion Public Instance Properties } /// /// Contains a collection of elements. /// [Serializable()] public class ProjectEntryCollection : CollectionBase { #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public ProjectEntryCollection() { } /// /// Initializes a new instance of the class /// with the specified instance. /// public ProjectEntryCollection(ProjectEntryCollection value) { AddRange(value); } /// /// Initializes a new instance of the class /// with the specified array of instances. /// public ProjectEntryCollection(ProjectEntry[] value) { AddRange(value); } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets the element at the specified index. /// /// The zero-based index of the element to get or set. [IndexerName("Item")] public ProjectEntry this[int index] { get { return (ProjectEntry) base.List[index]; } set { base.List[index] = value; } } /// /// Gets the with the specified GUID. /// /// The GUID of the to get. /// /// Performs a case-insensitive lookup. /// [IndexerName("Item")] public ProjectEntry this[string guid] { get { if (guid != null) { // try to locate instance by guid (case-insensitive) for (int i = 0; i < base.Count; i++) { ProjectEntry projectEntry = (ProjectEntry) base.List[i]; if (string.Compare(projectEntry.Guid, guid, true, CultureInfo.InvariantCulture) == 0) { return projectEntry; } } } return null; } set { if (guid == null) { throw new ArgumentNullException ("guid"); } if (value == null) { throw new ArgumentNullException ("value"); } if (!Contains (guid)) { Add(value); } } } #endregion Public Instance Properties #region Public Instance Methods /// /// Adds a to the end of the collection. /// /// The to be added to the end of the collection. /// /// The position into which the new element was inserted. /// public int Add(ProjectEntry item) { if (item == null) { throw new ArgumentNullException("item"); } // fail if a project with the same GUID exists in the collection ProjectEntry existingEntry = this[item.Guid]; if (existingEntry != null) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "The GUIDs of projects \"{0}\" and \"{1}\" are identical." + " Please correct this manually.", item.Path, existingEntry.Path), Location.UnknownLocation); } return base.List.Add(item); } /// /// Adds the elements of a array to the end of the collection. /// /// The array of elements to be added to the end of the collection. public void AddRange(ProjectEntry[] items) { for (int i = 0; (i < items.Length); i = (i + 1)) { Add(items[i]); } } /// /// Adds the elements of a to the end of the collection. /// /// The to be added to the end of the collection. public void AddRange(ProjectEntryCollection items) { for (int i = 0; (i < items.Count); i = (i + 1)) { Add(items[i]); } } /// /// Determines whether a is in the collection. /// /// The to locate in the collection. /// /// if is found in the /// collection; otherwise, . /// public bool Contains(ProjectEntry item) { return base.List.Contains(item); } /// /// Determines whether a with the specified /// GUID is in the collection, using a case-insensitive lookup. /// /// The GUID to locate in the collection. /// /// if a with GUID /// is found in the collection; otherwise, /// . /// public bool Contains(string value) { return this[value] != null; } /// /// Copies the entire collection to a compatible one-dimensional array, starting at the specified index of the target array. /// /// The one-dimensional array that is the destination of the elements copied from the collection. The array must have zero-based indexing. /// The zero-based index in at which copying begins. public void CopyTo(ProjectEntry[] array, int index) { base.List.CopyTo(array, index); } /// /// Retrieves the index of a specified object in the collection. /// /// The object for which the index is returned. /// /// The index of the specified . If the is not currently a member of the collection, it returns -1. /// public int IndexOf(ProjectEntry item) { return base.List.IndexOf(item); } /// /// Inserts a into the collection at the specified index. /// /// The zero-based index at which should be inserted. /// The to insert. public void Insert(int index, ProjectEntry item) { base.List.Insert(index, item); } /// /// Returns an enumerator that can iterate through the collection. /// /// /// A for the entire collection. /// public new ProjectEntryEnumerator GetEnumerator() { return new ProjectEntryEnumerator(this); } /// /// Removes a member from the collection. /// /// The to remove from the collection. public void Remove(ProjectEntry item) { base.List.Remove(item); } #endregion Public Instance Methods } /// /// Enumerates the elements of a . /// public class ProjectEntryEnumerator : IEnumerator { #region Internal Instance Constructors /// /// Initializes a new instance of the class /// with the specified . /// /// The collection that should be enumerated. internal ProjectEntryEnumerator(ProjectEntryCollection arguments) { IEnumerable temp = (IEnumerable) (arguments); _baseEnumerator = temp.GetEnumerator(); } #endregion Internal Instance Constructors #region Implementation of IEnumerator /// /// Gets the current element in the collection. /// /// /// The current element in the collection. /// public ProjectEntry Current { get { return (ProjectEntry) _baseEnumerator.Current; } } object IEnumerator.Current { get { return _baseEnumerator.Current; } } /// /// Advances the enumerator to the next element of the collection. /// /// /// if the enumerator was successfully advanced /// to the next element; if the enumerator has /// passed the end of the collection. /// public bool MoveNext() { return _baseEnumerator.MoveNext(); } bool IEnumerator.MoveNext() { return _baseEnumerator.MoveNext(); } /// /// Sets the enumerator to its initial position, which is before the /// first element in the collection. /// public void Reset() { _baseEnumerator.Reset(); } void IEnumerator.Reset() { _baseEnumerator.Reset(); } #endregion Implementation of IEnumerator #region Private Instance Fields private IEnumerator _baseEnumerator; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.VSNet/VcWrapperReference.cs0000644000175000017500000002630011757302274021536 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Matthew Mastracci (matt@aclaro.com) // Scott Ford (sford@RJKTECH.com) // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Globalization; using System.IO; using System.Xml; using NAnt.Core; using NAnt.Core.Tasks; using NAnt.Core.Util; using NAnt.Core.Types; using NAnt.Win32.Tasks; namespace NAnt.VSNet { public class VcWrapperReference : WrapperReferenceBase { #region Public Instance Constructors public VcWrapperReference(XmlElement xmlDefinition, ReferencesResolver referencesResolver, ProjectBase parent, GacCache gacCache) : base(xmlDefinition, referencesResolver, parent, gacCache) { // determine name of type library _name = GetTypeLibraryName(GetTypeLibrary()); // determine wrapper tool XmlAttribute toolAttribute = XmlDefinition.Attributes["WrapperTool"]; if (toolAttribute == null) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Wrapper tool for reference \"{0}\" in project \"{1}\" could" + " not be determined.", Name, Parent.Name), Location.UnknownLocation); } _wrapperTool = toolAttribute.Value; // determine if there's a primary interop assembly for the typelib _primaryInteropAssembly = GetPrimaryInteropAssembly(); // determine filename of wrapper assembly _wrapperAssembly = ResolveWrapperAssembly(); } #endregion Public Instance Constructors #region Override implementation of ReferenceBase /// /// Gets the name of the referenced assembly. /// /// /// The name of the referenced assembly. /// public override string Name { get { return _name; } } #endregion Override implementation of ReferenceBase #region Override implementation of WrapperReferenceBase /// /// Gets the name of the tool that should be used to create the /// . /// /// /// The name of the tool that should be used to create the /// . /// public override string WrapperTool { get { return _wrapperTool; } } /// /// Gets the path of the wrapper assembly. /// /// /// The path of the wrapper assembly. /// /// /// The wrapper assembly is stored in the object directory of the /// project. /// public override string WrapperAssembly { get { return _wrapperAssembly; } } /// /// Gets the path of the Primary Interop Assembly. /// /// /// The path of the Primary Interop Assembly, or /// if not available. /// protected override string PrimaryInteropAssembly { get { return _primaryInteropAssembly; } } /// /// Gets the hex version of the type library as defined in the definition /// of the reference. /// /// /// The hex version of the type library. /// /// The definition of the reference does not contain a "ControlVersion" attribute. protected override string TypeLibVersion { get { XmlAttribute versionAttribute = XmlDefinition.Attributes["ControlVersion"]; if (versionAttribute == null) { throw new BuildException("The definition of the reference" + " does not contain a \"ControlVersion\" attribute."); } Version version = new Version(versionAttribute.Value); return version.Major.ToString("x") + "." + version.Minor.ToString("x"); } } /// /// Gets the GUID of the type library as defined in the definition /// of the reference. /// /// /// The GUID of the type library. /// protected override string TypeLibGuid { get { XmlAttribute guidAttribute = XmlDefinition.Attributes["ControlGUID"]; if (guidAttribute == null) { throw new BuildException("The definition of the reference" + " does not contain a \"ControlGUID\" attribute."); } return guidAttribute.Value; } } /// /// Gets the locale of the type library in hex notation. /// /// /// The locale of the type library. /// protected override string TypeLibLocale { get { XmlAttribute localeAttribute = XmlDefinition.Attributes["ControlLocale"]; if (localeAttribute != null) { return int.Parse(localeAttribute.Value).ToString("x"); } return "0"; } } #endregion Override implementation of WrapperReferenceBase #region Private Instance Methods protected override void ImportTypeLibrary() { TlbImpTask tlbImp = new TlbImpTask(); // parent is solution task tlbImp.Parent = SolutionTask; // inherit project from solution task tlbImp.Project = SolutionTask.Project; // inherit namespace manager from solution task tlbImp.NamespaceManager = SolutionTask.NamespaceManager; // inherit verbose setting from solution task tlbImp.Verbose = SolutionTask.Verbose; // make sure framework specific information is set tlbImp.InitializeTaskConfiguration(); tlbImp.TypeLib = new FileInfo(GetTypeLibrary()); tlbImp.OutputFile = new FileInfo(WrapperAssembly); // use other imported type libraries to resolve references // // there's one serious limitation in the current implementation: // // if type library A references type library B, then we should // first import type library B and use a reference to that // imported type library when we import type library A. // // however, we have no way to find out in which order the type // libraries should be imported. So only if type library B is // first listed in the project file, it will work fine. // // we should find a way to analyse a type library to determine // dependencies on other type libraries // // according to JR (jrv72@users.sourceforge.net) a possible // solution could be to "use TypeLibConverter.ConvertTypeLibToAssembly. // This has a callback of type ITypeLibImporterNotifySink, which I // speculate allows one to recognize when one type library // depends on another. I believe what you have to do is start // with an arbitrary type library, and if that type library calls // back on the ResolveRef() method, and if that type library is // one you were planning to add later, you compile it // immediately and pass the assembly back out of ResolveRef. I // haven't tested this yet, but it's my best understanding of // how it all works. foreach (ReferenceBase reference in Parent.References) { // we're only interested in imported type libraries WrapperReferenceBase wrapper = reference as WrapperReferenceBase; // avoid stack overflow causes by mutual dependencies if (wrapper == null || !wrapper.IsCreated || wrapper.WrapperTool != "tlbimp") { continue; } tlbImp.References.Includes.Add(wrapper.WrapperAssembly); } // increment indentation level tlbImp.Project.Indent(); try { // execute task tlbImp.Execute(); } finally { // restore indentation level tlbImp.Project.Unindent(); } } protected override void ImportActiveXLibrary() { AxImpTask axImp = new AxImpTask(); // parent is solution task axImp.Parent = SolutionTask; // inherit project from solution task axImp.Project = SolutionTask.Project; // inherit namespace manager from solution task axImp.NamespaceManager = SolutionTask.NamespaceManager; // inherit verbose setting from solution task axImp.Verbose = SolutionTask.Verbose; // make sure framework specific information is set axImp.InitializeTaskConfiguration(); axImp.OcxFile = new FileInfo(GetTypeLibrary()); axImp.OutputFile = new FileInfo(WrapperAssembly); string rcw = PrimaryInteropAssembly; if (rcw == null) { // if no primary interop assembly is provided for ActiveX control, // trust the fact that VS.NET uses Interop..dll // for the imported typelibrary rcw = FileUtils.CombinePaths(Parent.ObjectDir.FullName, "Interop." + TypeLibraryName + ".dll"); } if (File.Exists(rcw)) { axImp.RcwFile = new FileInfo(rcw); } // increment indentation level axImp.Project.Indent(); try { // execute task axImp.Execute(); } finally { // restore indentation level axImp.Project.Unindent(); } } #endregion Private Instance Methods #region Private Instance Fields private readonly string _name = string.Empty; private readonly string _wrapperTool; private readonly string _wrapperAssembly; private readonly string _primaryInteropAssembly; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.VSNet/Resource.cs0000644000175000017500000003302611757302274017600 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Matthew Mastracci (matt@aclaro.com) using System; using System.Collections.Specialized; using System.Globalization; using System.IO; using NAnt.Core.Util; using NAnt.DotNet.Tasks; using NAnt.DotNet.Types; using NAnt.VSNet.Tasks; namespace NAnt.VSNet { public class Resource { #region Public Instance Constructors public Resource(ManagedProjectBase project, FileInfo resourceSourceFile, string resourceSourceFileRelativePath, string dependentFile, SolutionTask solutionTask, GacCache gacCache) { _project = project; _resourceSourceFile = resourceSourceFile; _resourceSourceFileRelativePath = resourceSourceFileRelativePath; _dependentFile = dependentFile; _solutionTask = solutionTask; _culture = CompilerBase.GetResourceCulture(resourceSourceFile.FullName, dependentFile); } #endregion Public Instance Constructors #region Public Instance Properties public CultureInfo Culture { get { return _culture; } } /// /// Gets a representing the physical location /// of the resource file. /// public FileInfo InputFile { get { return _resourceSourceFile; } } public ManagedProjectBase Project { get { return _project; } } /// /// Gets a representing the logical location /// of the resource file in the project. /// /// /// When the resource file is not linked, this matches the /// . /// public FileInfo LogicalFile { get { return new FileInfo(FileUtils.CombinePaths(Path.GetDirectoryName( Project.ProjectPath), _resourceSourceFileRelativePath)); } } /// /// Gets a value indicating whether the resource is in fact a ResX file. /// /// /// if the resource is a ResX file; otherwise, /// . /// public bool IsResX { get { return InputFile.Extension.ToLower(CultureInfo.InvariantCulture) == ".resx"; } } #endregion Public Instance Properties #region Public Instance Methods /// /// Compiles the resource file. /// /// The solution configuration that is built. /// /// A representing the compiled resource file. /// public FileInfo Compile(Configuration solutionConfiguration) { FileInfo compiledResourceFile = null; switch (InputFile.Extension.ToLower(CultureInfo.InvariantCulture)) { case ".resx": compiledResourceFile = CompileResx(solutionConfiguration); break; case ".licx": compiledResourceFile = CompileLicx(solutionConfiguration); break; default: compiledResourceFile = CompileResource(solutionConfiguration); break; } return compiledResourceFile; } /// /// Returns a representing the compiled resource /// file. /// /// The solution configuration that is built. /// /// A representing the compiled resource file. /// /// /// Calling this method does not force compilation of the resource file. /// public FileInfo GetCompiledResourceFile(Configuration solutionConfiguration) { string compiledResourceFile = null; // obtain project configuration (corresponding with solution configuration) ConfigurationSettings config = (ConfigurationSettings) Project.BuildConfigurations[solutionConfiguration]; switch (InputFile.Extension.ToLower(CultureInfo.InvariantCulture)) { case ".resx": compiledResourceFile = FileUtils.CombinePaths(config.ObjectDir.FullName, GetManifestResourceName(solutionConfiguration)); break; case ".licx": compiledResourceFile = FileUtils.CombinePaths(config.ObjectDir.FullName, Project.ProjectSettings.OutputFileName + ".licenses"); break; default: compiledResourceFile = InputFile.FullName; break; } return new FileInfo(compiledResourceFile); } public string GetManifestResourceName(Configuration solutionConfiguration) { // obtain project configuration (corresponding with solution configuration) ConfigurationSettings projectConfig = (ConfigurationSettings) Project.BuildConfigurations[solutionConfiguration]; switch (Project.Type) { case ProjectType.CSharp: return GetManifestResourceNameCSharp(projectConfig, _dependentFile); case ProjectType.VB: return GetManifestResourceNameVB(projectConfig, _dependentFile); case ProjectType.JSharp: return GetManifestResourceNameJSharp(projectConfig, _dependentFile); default: throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Unsupported project type '{0}'.", Project.Type)); } } #endregion Public Instance Methods #region Private Instance Methods private string GetManifestResourceNameCSharp(ConfigurationSettings configSetting, string dependentFile) { // defer to the resource management code in CscTask CscTask csc = new CscTask(); csc.Project = _solutionTask.Project; csc.NamespaceManager = _solutionTask.NamespaceManager; csc.OutputFile = new FileInfo(FileUtils.CombinePaths(configSetting.OutputDir.FullName, Project.ProjectSettings.OutputFileName)); // set-up resource fileset ResourceFileSet resources = new ResourceFileSet(); resources.Project = _solutionTask.Project; resources.NamespaceManager = _solutionTask.NamespaceManager; resources.Parent = csc; resources.BaseDirectory = new DirectoryInfo(Path.GetDirectoryName(Project.ProjectPath)); resources.Prefix = Project.ProjectSettings.RootNamespace; resources.DynamicPrefix = true; // bug #1042917: use logical location of resource file to determine // manifest resource name return csc.GetManifestResourceName(resources, InputFile.FullName, LogicalFile.FullName, dependentFile); } private string GetManifestResourceNameVB(ConfigurationSettings configSetting, string dependentFile) { // defer to the resource management code in VbcTask VbcTask vbc = new VbcTask(); vbc.Project = _solutionTask.Project; vbc.NamespaceManager = _solutionTask.NamespaceManager; vbc.OutputFile = new FileInfo(FileUtils.CombinePaths(configSetting.OutputDir.FullName, Project.ProjectSettings.OutputFileName)); vbc.RootNamespace = Project.ProjectSettings.RootNamespace; // set-up resource fileset ResourceFileSet resources = new ResourceFileSet(); resources.Project = _solutionTask.Project; resources.NamespaceManager = _solutionTask.NamespaceManager; resources.Parent = vbc; resources.BaseDirectory = new DirectoryInfo(Path.GetDirectoryName(Project.ProjectPath)); resources.Prefix = Project.ProjectSettings.RootNamespace; resources.DynamicPrefix = false; // bug #1042917: use logical location of resource file to determine // manifest resource name return vbc.GetManifestResourceName(resources, InputFile.FullName, LogicalFile.FullName, dependentFile); } private string GetManifestResourceNameJSharp(ConfigurationSettings configSetting, string dependentFile) { // defer to the resource management code in VjcTask VjcTask vjc = new VjcTask(); vjc.Project = _solutionTask.Project; vjc.NamespaceManager = _solutionTask.NamespaceManager; vjc.OutputFile = new FileInfo(FileUtils.CombinePaths(configSetting.OutputDir.FullName, Project.ProjectSettings.OutputFileName)); // set-up resource fileset ResourceFileSet resources = new ResourceFileSet(); resources.Project = _solutionTask.Project; resources.NamespaceManager = _solutionTask.NamespaceManager; resources.Parent = vjc; resources.BaseDirectory = new DirectoryInfo(Path.GetDirectoryName( Project.ProjectPath)); resources.Prefix = Project.ProjectSettings.RootNamespace; resources.DynamicPrefix = true; // bug #1042917: use logical location of resource file to determine // manifest resource name return vjc.GetManifestResourceName(resources, InputFile.FullName, LogicalFile.FullName, dependentFile); } private FileInfo CompileResource(Configuration solutionConfiguration) { return GetCompiledResourceFile(solutionConfiguration); } private FileInfo CompileLicx(Configuration solutionConfiguration) { // create instance of License task LicenseTask lt = new LicenseTask(); // inherit project from solution task lt.Project = _solutionTask.Project; // inherit namespace manager from solution task lt.NamespaceManager = _solutionTask.NamespaceManager; // parent is solution task lt.Parent = _solutionTask; // inherit verbose setting from solution task lt.Verbose = _solutionTask.Verbose; // make sure framework specific information is set lt.InitializeTaskConfiguration(); // set parent of child elements lt.Assemblies.Parent = lt; // inherit project from solution task from parent task lt.Assemblies.Project = lt.Project; // inherit namespace manager from parent task lt.Assemblies.NamespaceManager = lt.NamespaceManager; // set base directory for filesets lt.Assemblies.BaseDirectory = new DirectoryInfo(Path.GetDirectoryName(Project.ProjectPath)); // set task properties lt.InputFile = InputFile; lt.OutputFile = GetCompiledResourceFile(solutionConfiguration); // convert target to uppercase to match VS.NET lt.Target = Path.GetFileName(Project.ProjectSettings.OutputFileName). ToUpper(CultureInfo.InvariantCulture); // inherit assembly references from project foreach (ReferenceBase reference in Project.References) { StringCollection assemblyReferences = reference.GetAssemblyReferences( solutionConfiguration); foreach (string assemblyFile in assemblyReferences) { lt.Assemblies.Includes.Add(assemblyFile); } } // increment indentation level lt.Project.Indent(); try { // execute task lt.Execute(); } finally { // restore indentation level lt.Project.Unindent(); } return lt.OutputFile; } private FileInfo CompileResx(Configuration solutionConfiguration) { // for performance reasons, compilation of resx files is done in // batch using the ResGen task in ManagedProjectBase throw new InvalidOperationException(); } #endregion Private Instance Methods #region Private Instance Fields private readonly CultureInfo _culture; private readonly FileInfo _resourceSourceFile; private readonly string _dependentFile; private readonly string _resourceSourceFileRelativePath; private readonly ManagedProjectBase _project; private readonly SolutionTask _solutionTask; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.VSNet/ReferenceBase.cs0000644000175000017500000002270711757302274020506 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Matthew Mastracci (matt@aclaro.com) // Scott Ford (sford@RJKTECH.com) // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Xml; using NAnt.Core; using NAnt.Core.Util; using NAnt.VSNet.Tasks; namespace NAnt.VSNet { public abstract class ReferenceBase { #region Protected Instance Constructors protected ReferenceBase(ReferencesResolver referencesResolver, ProjectBase parent) { _referencesResolver = referencesResolver; _parent = parent; } #endregion Protected Instance Constructors #region Public Instance Properties /// /// Gets a value indicating whether the output file(s) of this reference /// should be copied locally. /// /// /// if the output file(s) of this reference /// should be copied locally; otherwise, . /// public abstract bool CopyLocal { get; } /// /// Gets a value indicating whether this reference represents a system /// assembly. /// /// /// if this reference represents a system /// assembly; otherwise, . /// protected abstract bool IsSystem { get; } public abstract string Name { get; } #endregion Public Instance Properties #region Protected Instance Properties /// /// Gets the project in which the reference is defined. /// protected ProjectBase Parent { get { return _parent; } } protected SolutionTask SolutionTask { get { return Parent.SolutionTask; } } protected ReferencesResolver ReferencesResolver { get { return _referencesResolver; } } #endregion Protected Instance Properties #region Public Instance Methods /// /// Gets the output path of the reference, without taking the "copy local" /// setting into consideration. /// /// The solution configuration that is built. /// /// The full output path of the reference. /// public abstract string GetPrimaryOutputFile(Configuration solutionConfiguration); /// /// Gets the complete set of output files of the reference for the /// specified configuration. /// /// The solution configuration that is built. /// The set of output files to be updated. /// /// The key of the case-insensitive is the /// full path of the output file and the value is the path relative to /// the output directory. /// public abstract void GetOutputFiles(Configuration solutionConfiguration, Hashtable outputFiles); /// /// Gets the complete set of assemblies that need to be referenced when /// a project references this component. /// /// The solution configuration that is built. /// /// The complete set of assemblies that need to be referenced when a /// project references this component. /// public abstract StringCollection GetAssemblyReferences(Configuration solutionConfiguration); /// /// Gets the timestamp of the reference. /// /// The solution configuration that is built. /// /// The timestamp of the reference. /// public abstract DateTime GetTimestamp(Configuration solutionConfiguration); /// /// Gets a value indicating whether the reference is managed for the /// specified configuration. /// /// The solution configuration that is built. /// /// if the reference is managed for the /// specified configuration; otherwise, . /// public abstract bool IsManaged(Configuration solutionConfiguration); #endregion Public Instance Methods #region Protected Instance Methods /// /// Returns the date and time the specified file was last written to. /// /// The file for which to obtain write date and time information. /// /// A structure set to the date and time that /// the specified file was last written to, or /// if the specified file does not /// exist. /// protected DateTime GetFileTimestamp(string fileName) { if (!File.Exists(fileName)) { return DateTime.MaxValue; } return File.GetLastWriteTime(fileName); } /// /// Logs a message with the given priority. /// /// The message priority at which the specified message is to be logged. /// The message to be logged. /// /// The actual logging is delegated to the underlying task. /// protected void Log(Level messageLevel, string message) { SolutionTask.Log(messageLevel, message); } /// /// Logs a message with the given priority. /// /// The message priority at which the specified message is to be logged. /// The message to log, containing zero or more format items. /// An array containing zero or more objects to format. /// /// The actual logging is delegated to the underlying task. /// protected void Log(Level messageLevel, string message, params object[] args) { SolutionTask.Log(messageLevel, message, args); } #endregion Protected Instance Methods #region Public Static Methods public static void GetRelatedFiles(string file, Hashtable relatedFiles) { // determine directory of specified file string directory = Path.GetDirectoryName(file); // check whether the directory of the specified file actually // exists if (StringUtils.ConvertEmptyToNull(directory) == null || !Directory.Exists(directory)) { return; } // file itself should always be added relatedFiles[file] = Path.GetFileName(file); // pattern indicating what files to scan string relatedFilesPattern = Path.GetFileName(Path.ChangeExtension(file, ".*")); // iterate over each file matching the pattern foreach (string relatedFile in Directory.GetFiles(Path.GetDirectoryName(file), relatedFilesPattern)) { // ignore files that do not have same base filename as reference file // eg. when reference file is MS.Runtime.dll, we do not want files // named MS.Runtime.Interop.dll if (string.Compare(Path.GetFileNameWithoutExtension(relatedFile), Path.GetFileNameWithoutExtension(file), true, CultureInfo.InvariantCulture) != 0) { continue; } // ignore any other the garbage files created string fileExtension = Path.GetExtension(relatedFile).ToLower(CultureInfo.InvariantCulture); if (fileExtension != ".dll" && fileExtension != ".xml" && fileExtension != ".pdb" && fileExtension != ".mdb") { continue; } relatedFiles[relatedFile] = Path.GetFileName(relatedFile); } } #endregion Public Static Methods #region Private Instance Fields private ProjectBase _parent; private ReferencesResolver _referencesResolver; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.VSNet/ProjectFactory.cs0000644000175000017500000002313311757302274020745 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Dmitry Jemerov using System; using System.Xml; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Text; using NAnt.Core; using NAnt.Core.Util; using NAnt.VSNet.Extensibility; using NAnt.VSNet.Tasks; namespace NAnt.VSNet { /// /// Factory class for VS.NET projects. /// internal sealed class ProjectFactory { #region Private Instance Constructor /// /// Initializes a new instance of the /// class. /// private ProjectFactory(SolutionTask solutionTask) { _cachedProjects = CollectionsUtil.CreateCaseInsensitiveHashtable(); _cachedProjectGuids = CollectionsUtil.CreateCaseInsensitiveHashtable(); _cachedProjectXml = CollectionsUtil.CreateCaseInsensitiveHashtable(); } #endregion Private Instance Constructor #region Public Static Methods public static ProjectFactory Create(SolutionTask solutionTask) { return new ProjectFactory(solutionTask); } public static bool IsUrl(string fileName) { if (fileName.StartsWith(Uri.UriSchemeFile) || fileName.StartsWith(Uri.UriSchemeHttp) || fileName.StartsWith(Uri.UriSchemeHttps)) { return true; } return false; } #endregion Public Static Methods #region Public Instance Methods public XmlDocument LoadProjectXml(string path) { if (!_cachedProjectXml.Contains(path)) { XmlDocument doc = new XmlDocument(); if (!ProjectFactory.IsUrl(path)) { using (StreamReader sr = new StreamReader(path, Encoding.Default, true)) { doc.Load(sr); } } else { Uri uri = new Uri(path); if (uri.Scheme == Uri.UriSchemeFile) { using (StreamReader sr = new StreamReader(uri.LocalPath, Encoding.Default, true)) { doc.Load(sr); } } else { doc.LoadXml(WebDavClient.GetFileContentsStatic(path)); } } _cachedProjectXml[path] = doc; } return (XmlDocument) _cachedProjectXml[path]; } public ProjectBase LoadProject(SolutionBase solution, SolutionTask solutionTask, TempFileCollection tfc, GacCache gacCache, ReferencesResolver referencesResolver, DirectoryInfo outputDir, string path) { // check if this a new project if (!_cachedProjects.Contains(path)) { ProjectBase project = CreateProject(solution, solutionTask, tfc, gacCache, referencesResolver, outputDir, path); _cachedProjects[path] = project; } return (ProjectBase) _cachedProjects[path]; } public string LoadGuid(string fileName) { // check if a project with specified file is already cached if (_cachedProjects.ContainsKey(fileName)) { // return the guid of the cached project return ((ProjectBase) _cachedProjects[fileName]).Guid; } string projectFileName = ProjectFactory.GetProjectFileName(fileName); string projectExt = Path.GetExtension(projectFileName).ToLower( CultureInfo.InvariantCulture); // holds the XML definition of the project XmlElement xmlDefinition; try { XmlDocument doc = LoadProjectXml(fileName); xmlDefinition = doc.DocumentElement; } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Error loading project '{0}'.", fileName), Location.UnknownLocation, ex); } IProjectBuildProvider provider = FindProvider(projectExt, xmlDefinition); if (provider != null) { _cachedProjectGuids[fileName] = provider.LoadGuid(xmlDefinition); } // return project GUID from cache return (string) _cachedProjectGuids[fileName]; } public void RegisterProvider(IProjectBuildProvider provider) { _projectprovs.Add(provider); } #endregion Public Instance Methods #region Private Instance Methods private ProjectBase CreateProject(SolutionBase solution, SolutionTask solutionTask, TempFileCollection tfc, GacCache gacCache, ReferencesResolver referencesResolver, DirectoryInfo outputDir, string projectPath) { // determine the filename of the project string projectFileName = ProjectFactory.GetProjectFileName(projectPath); // determine the extension of the project file string projectExt = Path.GetExtension(projectFileName).ToLower( CultureInfo.InvariantCulture); // fast-skip setup projects since the project files is not XML-based if (projectExt == ".vdproj") { return null; } // holds the XML definition of the project XmlElement xmlDefinition; try { XmlDocument doc = LoadProjectXml(projectPath); xmlDefinition = doc.DocumentElement; } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Error loading project '{0}'.", projectPath), Location.UnknownLocation, ex); } IProjectBuildProvider provider = FindProvider(projectExt, xmlDefinition); if (provider != null) { return provider.GetInstance(solution, projectPath, xmlDefinition, solutionTask, tfc, gacCache, referencesResolver, outputDir); } // either the project file is invalid or we don't support it throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Project '{0}' is invalid or not supported (at this time).", projectPath), Location.UnknownLocation); } private IProjectBuildProvider FindProvider(string projectExt, XmlElement xmlDefinition) { int max = 0; IProjectBuildProvider res = null; foreach (IProjectBuildProvider provider in _projectprovs) { int pri = provider.IsSupported(projectExt, xmlDefinition); if (pri > max) { max = pri; res = provider; } } return res; } #endregion Private Instance Methods #region Private Static Methods private static string GetProjectFileName(string fileName) { string projectPath = null; if (ProjectFactory.IsUrl(fileName)) { // construct uri for project path Uri projectUri = new Uri(fileName); // get last segment of the uri (which should be the // project file itself) projectPath = projectUri.LocalPath; } else { projectPath = fileName; } // return filename part return Path.GetFileName(projectPath); } #endregion Private Static Methods #region Private Instance Fields /// /// Holds a case-insensitive list of cached projects. /// /// /// The key of the is the path of the project /// file (for web projects this can be a URL) and the value is a /// instance. /// private readonly Hashtable _cachedProjects; /// /// Holds a case-insensitive list of cached project GUIDs. /// /// /// The key of the is the path of the project /// file (for web projects this can be a URL) and the value is the GUID /// of the project. /// private readonly Hashtable _cachedProjectGuids; /// /// Holds a case-insensitive list of cached project GUIDs. /// /// /// The key of the is the path of the project /// file (for web projects this can be a URL) and the value is the Xml /// of the project. /// private readonly Hashtable _cachedProjectXml; private readonly ArrayList _projectprovs = new ArrayList(); #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.VSNet/Extensibility/0000755000175000017500000000000011757310030020277 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.VSNet/Extensibility/IProjectBuildProvider.cs0000644000175000017500000000353611757302274025062 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Martin Aliger (martin_aliger@myrealbox.com) using System; using System.CodeDom.Compiler; using System.IO; using System.Xml; using NAnt.Core; using NAnt.Core.Extensibility; using NAnt.Core.Util; using NAnt.VSNet.Tasks; namespace NAnt.VSNet.Extensibility { public interface IProjectBuildProvider : IPlugin { /// /// Returns a number representing how much this file fits this project type. /// /// /// /// /// /// This enables the override in other providers. Do not return big numbers, mainly when compring only on filename. /// int IsSupported(string projectExt, XmlElement xmlDefinition); ProjectBase GetInstance(SolutionBase solution, string projectPath, XmlElement xmlDefinition, SolutionTask solutionTask, TempFileCollection tfc, GacCache gacCache, ReferencesResolver refResolver, DirectoryInfo outputDir); string LoadGuid(XmlElement xmlDefinition); } } nant-0.92-rc1/src/NAnt.VSNet/Extensibility/ISolutionBuildProvider.cs0000644000175000017500000000242411757302274025263 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Martin Aliger (martin_aliger@myrealbox.com) using System; using System.CodeDom.Compiler; using System.Xml; using NAnt.Core; using NAnt.Core.Extensibility; using NAnt.Core.Util; using NAnt.VSNet.Tasks; namespace NAnt.VSNet.Extensibility { public interface ISolutionBuildProvider : IPlugin { int IsSupported(string fileContents); SolutionBase GetInstance(string solutionContent, SolutionTask solutionTask, TempFileCollection tfc, GacCache gacCache, ReferencesResolver refResolver); } } nant-0.92-rc1/src/NAnt.VSNet/CSharpProject.cs0000644000175000017500000002006211757302274020514 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.CodeDom.Compiler; using System.Diagnostics; using System.Globalization; using System.IO; using System.Xml; using NAnt.Core; using NAnt.Core.Util; using NAnt.VSNet.Tasks; namespace NAnt.VSNet { public class CSharpProject : ManagedProjectBase { #region Public Instance Constructors public CSharpProject(SolutionBase solution, string projectPath, XmlElement xmlDefinition, SolutionTask solutionTask, TempFileCollection tfc, GacCache gacCache, ReferencesResolver refResolver, DirectoryInfo outputDir) : base(solution, projectPath, xmlDefinition, solutionTask, tfc, gacCache, refResolver, outputDir) { } #endregion Public Instance Constructors #region Override implementation of ProjectBase /// /// Gets the type of the project. /// /// /// The type of the project. /// public override ProjectType Type { get { return ProjectType.CSharp; } } /// /// Verifies whether the specified XML fragment represents a valid project /// that is supported by this . /// /// XML fragment representing the project file. /// /// The XML fragment is not supported by this . /// -or- /// The XML fragment does not represent a valid project (for this ). /// protected override void VerifyProjectXml(XmlElement docElement) { if (!IsSupported(docElement)) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Project '{0}' is not a valid C# project.", ProjectPath), Location.UnknownLocation); } } /// /// Returns the Visual Studio product version of the specified project /// XML fragment. /// /// The document element of the project. /// /// The Visual Studio product version of the specified project XML /// fragment. /// /// /// The product version could not be determined. /// -or- /// The product version is not supported. /// protected override ProductVersion DetermineProductVersion(XmlElement docElement) { return GetProductVersion(docElement.SelectSingleNode("./CSHARP")); } /// /// Returns a for launching the compiler /// for this project. /// /// The configuration to build. /// The response file for the compiler. /// /// A for launching the compiler for /// this project. /// protected override ProcessStartInfo GetProcessStartInfo(ConfigurationBase config, string responseFile) { ProcessStartInfo psi = new ProcessStartInfo(FileUtils.CombinePaths(SolutionTask. Project.TargetFramework.FrameworkDirectory.FullName, "csc.exe"), "/noconfig @\"" + responseFile + "\""); // to resolve the path to the file specified in the AssemblyKeyFile // attribute, the command line compilers try to resolve that relative // path using the output directory and the current directory // // VS.NET compiles assembly to the intermediate output directory and // uses the solution directory as current directory if (SolutionTask.SolutionFile != null) { psi.WorkingDirectory = Path.GetDirectoryName(SolutionTask.SolutionFile.FullName); } else { psi.WorkingDirectory = ProjectDirectory.FullName; } return psi; } #endregion Override implementation of ProjectBase #region Override implementation of ManagedProjectBase /// /// Gets the default file extension of sources for this project. /// /// /// For C# projects, the default file extension is ".cs". /// protected override string FileExtension { get { return ".cs"; } } /// /// Returns the project location from the specified project XML fragment. /// /// XML fragment representing the project file. /// /// The project location of the specified project XML file. /// /// /// The project location could not be determined. /// -or- /// The project location is invalid. /// protected override ProjectLocation DetermineProjectLocation(XmlElement docElement) { return GetProjectLocation(docElement.SelectSingleNode("./CSHARP")); } #endregion Override implementation of ManagedProjectBase #region Public Static Methods /// /// Returns a value indicating whether the project represented by the /// specified XML fragment is supported by . /// /// XML fragment representing the project to check. /// /// if supports /// the specified project; otherwise, . /// /// /// /// A project is identified as as C# project, if the XML fragment at /// least has the following information: /// /// /// /// /// ... /// /// /// ]]> /// /// public static bool IsSupported(XmlElement docElement) { if (docElement == null) { return false; } if (docElement.Name != "VisualStudioProject") { return false; } XmlNode projectNode = docElement.SelectSingleNode("./CSHARP"); if (projectNode == null) { return false; } try { GetProductVersion(projectNode); // no need to perform version check here as this is done in // GetProductVersion } catch { // product version could not be determined or is not supported return false; } return true; } #endregion Public Static Methods } } nant-0.92-rc1/src/NAnt.VSNet/WrapperReferenceBase.cs0000644000175000017500000005013411757302274022042 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Matthew Mastracci (matt@aclaro.com) // Scott Ford (sford@RJKTECH.com) // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Runtime.InteropServices; #if NET_2_0 using System.Runtime.InteropServices.ComTypes; #endif using System.Xml; using Microsoft.Win32; using NAnt.Core; using NAnt.Core.Tasks; using NAnt.Core.Util; using NAnt.Core.Types; using NAnt.Win32.Tasks; namespace NAnt.VSNet { public abstract class WrapperReferenceBase : FileReferenceBase { #region Protected Instance Constructors protected WrapperReferenceBase(XmlElement xmlDefinition, ReferencesResolver referencesResolver, ProjectBase parent, GacCache gacCache) : base(xmlDefinition, referencesResolver, parent, gacCache) { } #endregion Protected Instance Constructors #region Override implementation of ReferenceBase /// /// Gets a value indicating whether the output file(s) of this reference /// should be copied locally. /// /// /// if the reference wraps a Primary Interop /// Assembly; otherwise, . /// public override bool CopyLocal { get { return (WrapperTool != "primary"); } } /// /// Gets a value indicating whether this reference represents a system /// assembly. /// /// /// as none of the system assemblies are wrappers /// or Primary Interop Assemblies anyway. /// protected override bool IsSystem { get { return false; } } /// /// Gets the path of the reference, without taking the "copy local" /// setting into consideration. /// /// The solution configuration that is built. /// /// The output path of the reference. /// public override string GetPrimaryOutputFile(Configuration solutionConfiguration) { return WrapperAssembly; } /// /// Gets the complete set of output files for the referenced project. /// /// The solution configuration that is built. /// The set of output files to be updated. /// /// The key of the case-insensitive is the /// full path of the output file and the value is the path relative to /// the output directory. /// public override void GetOutputFiles(Configuration solutionConfiguration, Hashtable outputFiles) { // obtain project configuration (corresponding with solution configuration) ConfigurationBase config = Parent.BuildConfigurations[solutionConfiguration]; base.GetAssemblyOutputFiles(CreateWrapper(config), outputFiles); } /// /// Gets the complete set of assemblies that need to be referenced when /// a project references this component. /// /// The solution configuration that is built. /// /// The complete set of assemblies that need to be referenced when a /// project references this component. /// public override StringCollection GetAssemblyReferences(Configuration solutionConfiguration) { // obtain project configuration (corresponding with solution configuration) ConfigurationBase config = Parent.BuildConfigurations[solutionConfiguration]; // ensure wrapper is actually created string assemblyFile = CreateWrapper(config); if (!File.Exists(assemblyFile)) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Couldn't find assembly \"{0}\", referenced by project \"{1}\".", assemblyFile, Parent.Name), Location.UnknownLocation); } // add referenced assembly to list of reference assemblies StringCollection assemblyReferences = new StringCollection(); assemblyReferences.Add(assemblyFile); return assemblyReferences; } /// /// Gets the timestamp of the reference. /// /// The solution configuration that is built. /// /// The timestamp of the reference. /// public override DateTime GetTimestamp(Configuration solutionConfiguration) { return GetFileTimestamp(WrapperAssembly); } #endregion Override implementation of ReferenceBase #region Public Instance Properties /// /// Gets the name of the tool that should be used to create the /// . /// /// /// The name of the tool that should be used to create the /// . /// public abstract string WrapperTool { get; } /// /// Gets the path of the wrapper assembly. /// /// /// The path of the wrapper assembly. /// /// /// The wrapper assembly is stored in the object directory of the /// project. /// public abstract string WrapperAssembly { get; } /// /// Gets a value indicating whether the wrapper assembly has already been /// created. /// public bool IsCreated { get { return _isCreated; } } #endregion Public Instance Properties #region Protected Instance Properties /// /// Gets the path of the Primary Interop Assembly. /// /// /// The path of the Primary Interop Assembly, or /// if not available. /// protected abstract string PrimaryInteropAssembly { get; } /// /// Gets the hex version of the type library as defined in the definition /// of the reference. /// /// /// The hex version of the type library. /// protected abstract string TypeLibVersion { get; } /// /// Gets the GUID of the type library as defined in the definition /// of the reference. /// /// /// The GUID of the type library. /// protected abstract string TypeLibGuid { get; } /// /// Gets the locale of the type library in hex notation. /// /// /// The locale of the type library. /// protected abstract string TypeLibLocale { get; } /// /// Gets the name of the type library. /// /// /// The name of the type library. /// protected virtual string TypeLibraryName { get { return GetTypeLibraryName(GetTypeLibrary()); } } #endregion Protected Instance Properties #region Protected Instance Methods protected abstract void ImportTypeLibrary(); protected abstract void ImportActiveXLibrary(); protected string ResolveWrapperAssembly() { string wrapperAssembly = null; switch (WrapperTool) { case "primary": wrapperAssembly = PrimaryInteropAssembly; if (wrapperAssembly == null) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Couldn't find Primary Interop Assembly \"{0}\"," + " referenced by project \"{1}\".", Name, Parent.Name), Location.UnknownLocation); } return wrapperAssembly; case "aximp": wrapperAssembly = "AxInterop." + TypeLibraryName + ".dll"; break; default: wrapperAssembly = "Interop." + TypeLibraryName + ".dll"; break; } // resolve to full path return FileUtils.CombinePaths(Parent.ObjectDir.FullName, wrapperAssembly); } protected string GetPrimaryInteropAssembly() { string typeLibVersionKey = string.Format(CultureInfo.InvariantCulture, @"TYPELIB\{0}\{1}", TypeLibGuid, TypeLibVersion); string assemblyFile = null; using (RegistryKey registryKey = Registry.ClassesRoot.OpenSubKey(typeLibVersionKey)) { if (registryKey != null && registryKey.GetValue("PrimaryInteropAssemblyName") != null) { string primaryInteropAssemblyName = (string) registryKey.GetValue("PrimaryInteropAssemblyName"); try { // get filename of primary interop assembly assemblyFile = ReferencesResolver.GetAssemblyFileName( primaryInteropAssemblyName); } catch (Exception ex) { // only have build fail if we're actually dealing with a // reference to a primary interop assembly // // certain tools (such as Office) register the name of // the primary interop assembly of the typelib, but the // actual primary interop assembly is not always installed if (WrapperTool == "primary") { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Primary Interop Assembly \"{0}\", referenced by project" + " \"{1}\", could not be loaded.", primaryInteropAssemblyName, Parent.Name), Location.UnknownLocation, ex); } } } } return assemblyFile; } protected string GetTypeLibrary() { string typeLibKey = string.Format(CultureInfo.InvariantCulture, @"TYPELIB\{0}\{1}\{2}\win32", TypeLibGuid, TypeLibVersion, TypeLibLocale); using (RegistryKey registryKey = Registry.ClassesRoot.OpenSubKey(typeLibKey)) { // TODO: if there's no direct match, then use a type library // with the same major version, and the highest minor version // TODO: check if the library identifier matches the one of the // reference if (registryKey == null) { throw CreateTypeLibraryNotRegisteredException(); } string typeLibValue = (string) registryKey.GetValue(null); if (String.IsNullOrEmpty(typeLibValue)) { throw CreateInvalidTypeLibraryRegistrationException(); } // extract path to type library from reg value string typeLibPath = TlbImpTask.ExtractTypeLibPath(typeLibValue); // check if the typelib actually exists if (!File.Exists(typeLibPath)) { throw CreateTypeLibraryPathDoesNotExistException(typeLibPath); } return typeLibValue; } } protected string GetTypeLibraryName(string typeLibraryPath) { Object typeLib; try { LoadTypeLibEx(typeLibraryPath, 0, out typeLib); } catch (COMException ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Type library \"{0}\" could not be loaded.", typeLibraryPath), Location.UnknownLocation, ex); } if (typeLib == null) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Type library \"{0}\" could not be loaded.", typeLibraryPath), Location.UnknownLocation); } #if NET_2_0 return Marshal.GetTypeLibName((ITypeLib) typeLib); #else return Marshal.GetTypeLibName((UCOMITypeLib) typeLib); #endif } #endregion Protected Instance Methods #region Private Instance Methods private string CreateWrapper(ConfigurationBase config) { // if wrapper assembly was created during the current build, then // there's no need to create it again if (IsCreated) { return WrapperAssembly; } // synchronize build and output directory Sync(config); switch (WrapperTool) { case "primary": // nothing to do for Primary Interop Assembly break; case "tlbimp": if (PrimaryInteropAssembly != null) { // if tlbimp is defined as import tool, but a primary // interop assembly is available, then output a // warning Log(Level.Warning, "The component \"{0}\", referenced by" + " project \"{1}\" has an updated custom wrapper" + " available.", Name, Parent.Name); } ImportTypeLibrary(); break; case "aximp": ImportActiveXLibrary(); break; default: throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Wrapper tool \"{0}\" for reference \"{1}\" in project" + " \"{2}\" is not supported.", WrapperTool, Name, Parent.Name), Location.UnknownLocation); } // mark wrapper as completed _isCreated = true; return WrapperAssembly; } /// /// Removes wrapper assembly from build directory, if wrapper assembly /// no longer exists in output directory or is not in sync with build /// directory, to force rebuild. /// /// The project configuration. private void Sync(ConfigurationBase config) { if (!CopyLocal || !File.Exists(WrapperAssembly)) { // nothing to synchronize return; } // determine path where wrapper assembly should be deployed to string outputFile = FileUtils.CombinePaths(config.OutputDir.FullName, Path.GetFileName(WrapperAssembly)); // determine last modification date/time of built wrapper assembly DateTime wrapperModTime = File.GetLastWriteTime(WrapperAssembly); // rebuild wrapper assembly if output assembly is more recent, // or have been removed (by the user) to force a rebuild if (FileSet.FindMoreRecentLastWriteTime(outputFile, wrapperModTime) != null) { // remove wrapper assembly to ensure a rebuild is performed DeleteTask deleteTask = new DeleteTask(); deleteTask.Project = SolutionTask.Project; deleteTask.Parent = SolutionTask; deleteTask.InitializeTaskConfiguration(); deleteTask.File = new FileInfo(WrapperAssembly); deleteTask.Threshold = Level.None; // no output in build log deleteTask.Execute(); } } private BuildException CreateTypeLibraryNotRegisteredException() { string msg = null; if (String.IsNullOrEmpty(Name)) { msg = string.Format(CultureInfo.InvariantCulture, "Couldn't" + " find type library \"{0}\" with version {1}, referenced" + " by project \"{2}\".", TypeLibGuid, TypeLibVersion, Parent.Name); } else { msg = string.Format(CultureInfo.InvariantCulture, "Couldn't" + " find type library \"{0}\" ({1} with version {2}), referenced" + " by project \"{3}\".", Name, TypeLibGuid, TypeLibVersion, Parent.Name); } return new BuildException(msg, Location.UnknownLocation); } private BuildException CreateInvalidTypeLibraryRegistrationException() { string msg = null; if (String.IsNullOrEmpty(Name)) { msg = string.Format(CultureInfo.InvariantCulture, "Couldn't" + " find path of type library \"{0}\" with version {1}, referenced" + " by project \"{2}\". Ensure the type library is registered" + "correctly.", TypeLibGuid, TypeLibVersion, Parent.Name); } else { msg = string.Format(CultureInfo.InvariantCulture, "Couldn't" + " find path of type library \"{0}\" ({1} with version {2})," + " referenced by project \"{3}\". Ensure the type library is" + " registered correctly.", Name, TypeLibGuid, TypeLibVersion, Parent.Name); } return new BuildException(msg, Location.UnknownLocation); } private BuildException CreateTypeLibraryPathDoesNotExistException(string typeLibraryPath) { string msg = null; if (String.IsNullOrEmpty(Name)) { msg = string.Format(CultureInfo.InvariantCulture, "Type library" + " \"{0}\" with version {1}, referenced by project \"{2}\"," + " no longer exists at registered path \"{3}\".", TypeLibGuid, TypeLibVersion, Parent.Name, typeLibraryPath); } else { msg = string.Format(CultureInfo.InvariantCulture, "Type library" + " \"{0}\" ({1} with version {2}), referenced by project \"{3}\"," + " no longer exists at registered path \"{4}\".", Name, TypeLibGuid, TypeLibVersion, Parent.Name, typeLibraryPath); } return new BuildException(msg, Location.UnknownLocation); } #endregion Private Instance Methods #region Private Static Methods [DllImport( "oleaut32.dll", CharSet=CharSet.Unicode, PreserveSig=false)] private static extern void LoadTypeLibEx(string strTypeLibName, int regKind, [MarshalAs(UnmanagedType.Interface)] out Object typeLib); #endregion Private Static Methods #region Private Instance Fields private bool _isCreated; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.VSNet/VCProjectProvider.cs0000644000175000017500000000373011757302274021362 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Martin Aliger (martin_aliger@myrealbox.com) using System; using System.CodeDom.Compiler; using System.IO; using System.Xml; using NAnt.Core; using NAnt.Core.Extensibility; using NAnt.Core.Util; using NAnt.VSNet.Extensibility; using NAnt.VSNet.Tasks; namespace NAnt.VSNet { internal class VCProjectProvider : IProjectBuildProvider { #region Implementation of IProjectBuildProvider public int IsSupported(string projectExt, XmlElement xmlDefinition) { if (projectExt == ".vcproj") return 5; if (VcProject.IsSupported(xmlDefinition)) return 10; return 0; } public ProjectBase GetInstance(SolutionBase solution, string projectPath, XmlElement xmlDefinition, SolutionTask solutionTask, TempFileCollection tfc, GacCache gacCache, ReferencesResolver refResolver, DirectoryInfo outputDir) { return new VcProject(solution, projectPath, xmlDefinition, solutionTask, tfc, gacCache, refResolver, outputDir); } public string LoadGuid(XmlElement xmlDefinition) { return VcProject.LoadGuid(xmlDefinition); } #endregion Implementation of IProjectBuildProvider } } nant-0.92-rc1/src/NAnt.VSNet/ProjectReferenceBase.cs0000644000175000017500000002141111757302274022024 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Matthew Mastracci (matt@aclaro.com) // Scott Ford (sford@RJKTECH.com) // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Xml; using NAnt.Core; using NAnt.Core.Util; namespace NAnt.VSNet { public abstract class ProjectReferenceBase : ReferenceBase { #region Protected Instance Constructors protected ProjectReferenceBase(ReferencesResolver referencesResolver, ProjectBase parent) : base(referencesResolver, parent) { } #endregion Protected Instance Constructors #region Protected Instance Properties protected abstract bool IsPrivate { get; } protected abstract bool IsPrivateSpecified { get; } #endregion Protected Instance Properties #region Override implementation of ReferenceBase /// /// Gets a value indicating whether the output file(s) of this reference /// should be copied locally. /// /// /// if the output file(s) of this reference /// should be copied locally; otherwise, . /// public override bool CopyLocal { get { return IsPrivateSpecified ? IsPrivate : true; } } public override string Name { get { return Project.Name; } } /// /// Gets a value indicating whether this reference represents a system /// assembly. /// /// /// as a project by itself can never be a /// system assembly. /// protected override bool IsSystem { get { return false; } } /// /// Gets the output path of the reference, without taking the "copy local" /// setting into consideration. /// /// The solution configuration that is built. /// /// The output path of the reference. /// public override string GetPrimaryOutputFile(Configuration solutionConfiguration) { return Project.GetOutputPath(solutionConfiguration); } /// /// Gets the complete set of output files for the referenced project. /// /// The solution configuration that is built. /// The set of output files to be updated. /// /// The complete set of output files for the referenced project. /// /// /// The key of the case-insensitive is the /// full path of the output file and the value is the path relative to /// the output directory. /// public override void GetOutputFiles(Configuration solutionConfiguration, Hashtable outputFiles) { Project.GetOutputFiles(solutionConfiguration, outputFiles); } /// /// Gets the complete set of assemblies that need to be referenced when /// a project references this project. /// /// The solution configuration that is built. /// /// The complete set of assemblies that need to be referenced when a /// project references this project. /// /// /// /// Apparently, there's some hack in VB.NET that allows a type to be used /// that derives from a type in an assembly that is not referenced by the /// project. /// /// /// When building from the command line (using vbc), the following error /// is reported "error BC30007: Reference required to assembly 'X' /// containing the base class 'X'. Add one to your project". /// /// /// Somehow VB.NET can workaround this issue, without actually adding a /// reference to that assembly. I verified this with both VS.NET 2003 and /// VS.NET 2005. /// /// /// For now, we have no other option than to return all assembly /// references of the referenced project if the parent is a VB.NET /// project. /// /// public override StringCollection GetAssemblyReferences(Configuration solutionConfiguration) { StringCollection assemblyReferences = null; // check if parent is a VB.NET project if (typeof(VBProject).IsAssignableFrom(Parent.GetType())) { assemblyReferences = Project.GetAssemblyReferences(solutionConfiguration); } else { assemblyReferences = new StringCollection(); } ConfigurationBase projectConfig = Project.GetConfiguration( solutionConfiguration); // check if project is actual configured to be built if (projectConfig != null) { string projectOutputFile = projectConfig.BuildPath; // check if project has output file if (projectOutputFile != null) { if (File.Exists(projectOutputFile)) { // add primary output to list of reference assemblies assemblyReferences.Add(projectOutputFile); } } } // return assembly references return assemblyReferences; } /// /// Gets the timestamp of the reference. /// /// The solution configuration that is built. /// /// The timestamp of the reference. /// public override DateTime GetTimestamp(Configuration solutionConfiguration) { string projectOutputFile = Project.GetOutputPath(solutionConfiguration); if (projectOutputFile != null) { return GetFileTimestamp(projectOutputFile); } else { // if project has no output file, then we assume that it creates // a file through another way (eg. by launching an application // that creates an assembly) return DateTime.MaxValue; } } #endregion Override implementation of ReferenceBase #region Public Instance Properties public abstract ProjectBase Project { get; } #endregion Public Instance Properties #region Protected Instance Methods protected ProjectBase LoadProject(SolutionBase solution, TempFileCollection tfc, GacCache gacCache, DirectoryInfo outputDir, string projectFile) { if (ProjectStack.Contains(projectFile)) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Circular reference to \"{0}\" detected in project \"{1}\".", Path.GetFileNameWithoutExtension(projectFile), Parent.Name), Location.UnknownLocation); } try { ProjectStack.Push(projectFile); Log(Level.Verbose, "Loading referenced project '{0}'.", projectFile); return SolutionTask.ProjectFactory.LoadProject(solution, SolutionTask, tfc, gacCache, ReferencesResolver, outputDir, projectFile); } finally { ProjectStack.Pop(); } } #endregion Protected Instance Methods #region Private Static Fields private static readonly Stack ProjectStack = new Stack(); #endregion Private Static Fields } } nant-0.92-rc1/src/NAnt.VSNet/ConfigurationDictionary.cs0000644000175000017500000001725111757302274022650 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2008 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net.be) using System; using System.Collections; using System.Collections.Specialized; using System.Globalization; namespace NAnt.VSNet { public sealed class ConfigurationDictionary : IDictionary, ICollection, IEnumerable { #region Private Instance Fields private readonly Hashtable _innerHash; #endregion Private Instance Fields #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public ConfigurationDictionary() { _innerHash = CollectionsUtil.CreateCaseInsensitiveHashtable(); } #endregion Public Instance Constructors #region Internal Instance Properties internal Hashtable InnerHash { get { return _innerHash; } } #endregion Internal Instance Properties #region Implementation of IDictionary public ConfigurationDictionaryEnumerator GetEnumerator() { return new ConfigurationDictionaryEnumerator(this); } IDictionaryEnumerator IDictionary.GetEnumerator() { return GetEnumerator (); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Remove(Configuration configuration) { _innerHash.Remove(configuration); } void IDictionary.Remove(object key) { Remove((Configuration) key); } public bool Contains(Configuration key) { return _innerHash.Contains(key); } bool IDictionary.Contains(object key) { return Contains((Configuration) key); } public void Clear() { _innerHash.Clear(); } public void Add(Configuration key, ConfigurationBase value) { _innerHash.Add (key, value); } void IDictionary.Add(object key, object value) { Add((Configuration) key, (ConfigurationBase) value); } public bool IsReadOnly { get { return _innerHash.IsReadOnly; } } public ConfigurationBase this[Configuration key] { get { ConfigurationBase foundConfig = (ConfigurationBase) _innerHash[key]; if (foundConfig == null) { // if no exact match for build configuration and platform // was found, then only match on the name of the configuration // // we need this for two reasons: // 1) when no platform is specified on the task, // but we still want to match project configurations with // a platform. // 2) when a platform is specified on the task, // but we want to match any given project configuration // with the same configuration name. foreach (DictionaryEntry de in _innerHash) { Configuration config = (Configuration) de.Key; if (string.Compare (config.Name, key.Name, true, CultureInfo.InvariantCulture) == 0) { foundConfig = (ConfigurationBase) de.Value; break; } } } return foundConfig; } set { _innerHash[key] = value; } } object IDictionary.this[object key] { get { return this[(Configuration) key]; } set { this[(Configuration) key] = (ConfigurationBase) value; } } public ICollection Values { get { return _innerHash.Values; } } public ICollection Keys { get { return _innerHash.Keys; } } public bool IsFixedSize { get { return _innerHash.IsFixedSize; } } #endregion Implementation of IDictionary #region Implementation of ICollection void ICollection.CopyTo(Array array, int index) { _innerHash.CopyTo(array, index); } public bool IsSynchronized { get { return _innerHash.IsSynchronized; } } public int Count { get { return _innerHash.Count; } } public object SyncRoot { get { return _innerHash.SyncRoot; } } #endregion Implementation of ICollection #region HashTable Methods public bool ContainsKey (Configuration key) { return _innerHash.ContainsKey(key); } public bool ContainsValue(ConfigurationBase value) { return _innerHash.ContainsValue(value); } #endregion HashTable Methods } public class ConfigurationDictionaryEnumerator : IDictionaryEnumerator { #region Private Instance Fields private readonly IDictionaryEnumerator _innerEnumerator; #endregion Private Instance Fields #region Internal Instance Constructors internal ConfigurationDictionaryEnumerator(ConfigurationDictionary enumerable) { _innerEnumerator = enumerable.InnerHash.GetEnumerator(); } #endregion Internal Instance Constructors #region Implementation of IDictionaryEnumerator public Configuration Key { get { return (Configuration) _innerEnumerator.Key; } } object IDictionaryEnumerator.Key { get { return Key; } } public ConfigurationBase Value { get { return (ConfigurationBase) _innerEnumerator.Value; } } object IDictionaryEnumerator.Value { get { return Value; } } public DictionaryEntry Entry { get { return new DictionaryEntry (Key, Value); } } #endregion Implementation of IDictionaryEnumerator #region Implementation of IEnumerator public void Reset() { _innerEnumerator.Reset(); } public bool MoveNext() { return _innerEnumerator.MoveNext(); } object IEnumerator.Current { get { return Current; } } public ConfigurationDictionaryEntry Current { get { return new ConfigurationDictionaryEntry (Key, Value); } } #endregion Implementation of IEnumerator } public sealed class ConfigurationDictionaryEntry { private readonly Configuration _name; private readonly ConfigurationBase _config; internal ConfigurationDictionaryEntry(Configuration name, ConfigurationBase config) { _name = name; _config = config; } public Configuration Name { get { return _name; } } public ConfigurationBase Config { get { return _config; } } } } nant-0.92-rc1/src/NAnt.VSNet/NAnt.VSNet.build0000644000175000017500000000275711757302274020350 0ustar jtaylorjtaylor nant-0.92-rc1/src/NAnt.VSNet/ReferencesResolver.cs0000644000175000017500000001020711757302274021610 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Matthew Mastracci (matt@aclaro.com) // Scott Ford (sford@RJKTECH.com) // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.Remoting.Lifetime; using System.Xml; using Microsoft.Win32; using NAnt.Core; using NAnt.Core.Util; using NAnt.VSNet.Tasks; namespace NAnt.VSNet { public class ReferencesResolver : MarshalByRefObject { #region Override implementation of MarshalByRefObject /// /// Obtains a lifetime service object to control the lifetime policy for /// this instance. /// /// /// An object of type used to control the lifetime /// policy for this instance. This is the current lifetime service object /// for this instance if one exists; otherwise, a new lifetime service /// object initialized with a lease that will never time out. /// public override Object InitializeLifetimeService() { ILease lease = (ILease) base.InitializeLifetimeService(); if (lease.CurrentState == LeaseState.Initial) { lease.InitialLeaseTime = TimeSpan.Zero; } return lease; } #endregion Override implementation of MarshalByRefObject #region Public Instance Methods public void AppendReferencedModulesLocatedInGivenDirectory(string moduleDirectory, string moduleName, ref Hashtable allReferences, ref Hashtable unresolvedReferences) { Assembly module = null; try { module = Assembly.LoadFrom(moduleName); } catch (FileLoadException) { // for now ignore assemblies that cannot be loaded. A better // solution might be to disable signature verification and try // again, that way we can load assemblies that are delay-signed return; } AssemblyName[] referencedAssemblies = module.GetReferencedAssemblies(); foreach (AssemblyName referencedAssemblyName in referencedAssemblies) { string fullPathToReferencedAssembly = FileUtils.CombinePaths(moduleDirectory, referencedAssemblyName.Name + ".dll"); // we only add referenced assemblies which are located in given directory if (File.Exists(fullPathToReferencedAssembly) && !allReferences.ContainsKey(fullPathToReferencedAssembly)) { allReferences.Add(fullPathToReferencedAssembly, null); unresolvedReferences.Add(fullPathToReferencedAssembly, null); } } } /// /// Gets the file name of the assembly with the given assembly name. /// /// The assembly name of the assembly of which the file name should be returned. /// /// The file name of the assembly with the given assembly name. /// public string GetAssemblyFileName(string assemblyName) { Assembly assembly = Assembly.Load(assemblyName); return (new Uri(assembly.CodeBase)).LocalPath; } #endregion Public Instance Methods } }nant-0.92-rc1/src/NAnt.VSNet/SolutionBase.cs0000644000175000017500000011057611757302274020426 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Matthew Mastracci (matt@aclaro.com) using System; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Xml; using NAnt.Core; using NAnt.Core.Types; using NAnt.Core.Util; using NAnt.VSNet.Tasks; using NAnt.VSNet.Types; namespace NAnt.VSNet { public abstract class SolutionBase { #region Protected Instance Constructors protected SolutionBase(SolutionTask solutionTask, TempFileCollection tfc, GacCache gacCache, ReferencesResolver refResolver) : this(tfc, solutionTask) { if (solutionTask.SolutionFile != null) { _file = solutionTask.SolutionFile; } else { LoadProjectGuids(new ArrayList(solutionTask.Projects.FileNames), false); LoadProjectGuids(new ArrayList(solutionTask.ReferenceProjects.FileNames), true); LoadProjects(gacCache, refResolver, CollectionsUtil.CreateCaseInsensitiveHashtable()); } } #endregion Protected Instance Constructors #region Private Instance Constructors private SolutionBase(TempFileCollection tfc, SolutionTask solutionTask) { _htOutputFiles = CollectionsUtil.CreateCaseInsensitiveHashtable(); _projectEntries = new ProjectEntryCollection(); _htReferenceProjects = CollectionsUtil.CreateCaseInsensitiveHashtable(); _tfc = tfc; _solutionTask = solutionTask; _outputDir = solutionTask.OutputDir; _webMaps = solutionTask.WebMaps; } #endregion Private Instance Constructors #region Public Instance Properties public FileInfo File { get { return _file; } } public TempFileCollection TemporaryFiles { get { return _tfc; } } #endregion Public Instance Properties #region Protected Instance Properties { protected WebMapCollection WebMaps { get { return _webMaps; } } public ProjectEntryCollection ProjectEntries { get { return _projectEntries; } } #endregion Protected Instance Properties { #region Public Instance Methods public void RecursiveLoadTemplateProject(string fileName) { XmlDocument doc = _solutionTask.ProjectFactory.LoadProjectXml(fileName); foreach (XmlNode node in doc.SelectNodes("//Reference")) { XmlNode projectGuidNode = node.SelectSingleNode("GUIDPROJECTID"); XmlNode fileNode = node.SelectSingleNode("FILE"); if (fileNode == null) { Log(Level.Warning, "Reference with missing node. Skipping."); continue; } // check if we're dealing with project or assembly reference if (projectGuidNode != null) { string subProjectFilename = node.SelectSingleNode("FILE").InnerText; string fullPath; // translate URLs to physical paths if using a webmap string map = _webMaps.FindBestMatch(subProjectFilename); if (map != null) { Log(Level.Debug, "Found webmap match '{0}' for '{1}.", map, subProjectFilename); subProjectFilename = map; } try { Uri uri = new Uri(subProjectFilename); if (uri.Scheme == Uri.UriSchemeFile) { fullPath = FileUtils.GetFullPath(FileUtils.CombinePaths( Path.GetDirectoryName(fileName), uri.LocalPath)); } else { fullPath = subProjectFilename; if (!_solutionTask.EnableWebDav) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Cannot build web project '{0}'. Please use" + " to map the given URL to a project-relative" + " path, or specify enablewebdav=\"true\" on the" + " task element to use WebDAV.", fullPath)); } } } catch (UriFormatException) { fullPath = FileUtils.GetFullPath(FileUtils.CombinePaths( Path.GetDirectoryName(fileName), subProjectFilename)); } // check if project file actually exists if (!System.IO.File.Exists(fullPath)) { throw CreateProjectDoesNotExistException(fullPath); } if (ManagedProjectBase.IsEnterpriseTemplateProject(fullPath)) { RecursiveLoadTemplateProject(fullPath); } else { ProjectEntries.Add(new ProjectEntry(projectGuidNode.InnerText, fullPath)); } } else { Log(Level.Verbose, "Skipping file reference '{0}'.", fileNode.InnerText); } } } /// /// Gets the project file of the project with the given unique identifier. /// /// The unique identifier of the project for which the project file should be retrieves. /// /// The project file of the project with the given unique identifier. /// /// No project with unique identifier could be located. public string GetProjectFileFromGuid(string projectGuid) { // locate project entry using the project guid ProjectEntry projectEntry = ProjectEntries[projectGuid]; // TODO : as an emergency patch throw a build error when a GUID fails // to return a project file. This should be sanity checked when the // HashTable is populated and not at usage time to avoid internal // errors during build. if (projectEntry == null) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Project with GUID '{0}' must be included for the build to" + " work.", projectGuid), Location.UnknownLocation); } return projectEntry.Path; } public ProjectBase GetProjectFromGuid(string projectGuid) { ProjectEntry projectEntry = ProjectEntries[projectGuid]; if (projectEntry == null || projectEntry.Project == null) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Project with GUID '{0}' is not loaded.", projectGuid), Location.UnknownLocation); } return projectEntry.Project; } public bool Compile(Configuration solutionConfiguration) { Hashtable htProjectsDone = CollectionsUtil.CreateCaseInsensitiveHashtable(); Hashtable htFailedProjects = CollectionsUtil.CreateCaseInsensitiveHashtable(); ArrayList failedProjects = new ArrayList(); bool success = true; GetDependenciesFromProjects(solutionConfiguration); while (true) { bool compiledThisRound = false; foreach (ProjectEntry projectEntry in ProjectEntries) { ProjectBase project = projectEntry.Project; if (project == null) { // mark project done htProjectsDone[projectEntry.Guid] = null; // skip projects that are not loaded/supported continue; } if (htProjectsDone.Contains(project.Guid)) { continue; } bool failed = htFailedProjects.Contains(project.Guid); if (!failed) { // attempt to convert assembly references to project // references // // this might affect the build order as it can add // project dependencies if (FixProjectReferences(project, solutionConfiguration, htProjectsDone, htFailedProjects)) { // mark project failed if it references a project that // failed to build // // this can only happen when assembly reference was // was fixed to a project reference (that already failed // to build before the fix-up) failed = true; // avoid running through the fix-up next time htFailedProjects[project.Guid] = null; } } if (!HasDirtyProjectDependency(project, htProjectsDone)) { try { if (!_htReferenceProjects.Contains(project.Guid) && (failed || !project.Compile(solutionConfiguration))) { if (!failed) { Log(Level.Error, "Project '{0}' failed!", project.Name); Log(Level.Error, "Continuing build with non-dependent projects."); failedProjects.Add(project.Name); } success = false; htFailedProjects[project.Guid] = null; // mark the projects referencing this one as failed foreach (ProjectEntry entry in ProjectEntries) { ProjectBase dependentProject = entry.Project; if (dependentProject == null) { // skip projects that are not loaded/supported } // if the project depends on the failed // project, then also mark it failed if (dependentProject.ProjectDependencies.Contains(project)) { htFailedProjects[dependentProject.Guid] = null; } } } } catch (BuildException) { // Re-throw build exceptions throw; } catch (Exception e) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Unexpected error while compiling project '{0}'", project.Name), Location.UnknownLocation, e); } compiledThisRound = true; // mark project done htProjectsDone[project.Guid] = null; } } if (ProjectEntries.Count == htProjectsDone.Count) { break; } if (!compiledThisRound) { throw new BuildException("Circular dependency detected.", Location.UnknownLocation); } } if (failedProjects.Count > 0) { Log(Level.Error, string.Empty); Log(Level.Error, "Solution failed to build! Failed projects were:" ); foreach (string projectName in failedProjects) Log(Level.Error, " - " + projectName ); } return success; } #endregion Public Instance Methods #region Protected Instance Methods /// /// Logs a message with the given priority. /// /// The message priority at which the specified message is to be logged. /// The message to be logged. /// /// The actual logging is delegated to the underlying task. /// protected void Log(Level messageLevel, string message) { if (_solutionTask != null) { _solutionTask.Log(messageLevel, message); } } /// /// Logs a message with the given priority. /// /// The message priority at which the specified message is to be logged. /// The message to log, containing zero or more format items. /// An array containing zero or more objects to format. /// /// The actual logging is delegated to the underlying task. /// protected void Log(Level messageLevel, string message, params object[] args) { if (_solutionTask != null) { _solutionTask.Log(messageLevel, message, args); } } protected void LoadProjectGuids(ArrayList projects, bool isReferenceProject) { foreach (string projectFileName in projects) { string projectGuid = _solutionTask.ProjectFactory.LoadGuid(projectFileName); // locate project entry using the project guid ProjectEntry projectEntry = ProjectEntries[projectGuid]; if (projectEntry != null) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Error loading project {0}. " + " Project GUID {1} already exists! Conflicting project is {2}.", projectFileName, projectGuid, projectEntry.Path)); } ProjectEntries.Add(new ProjectEntry(projectGuid, projectFileName)); if (isReferenceProject) _htReferenceProjects[projectGuid] = null; } } /// /// Loads the projects from the file system and stores them in an /// instance variable. /// /// instance to use to determine whether an assembly is located in the Global Assembly Cache. /// instance to use to determine location and references of assemblies. /// TODO /// A project GUID in the solution file does not match the actual GUID of the project in the project file. protected void LoadProjects(GacCache gacCache, ReferencesResolver refResolver, Hashtable explicitProjectDependencies) { Log(Level.Verbose, "Loading projects..."); FileSet excludes = _solutionTask.ExcludeProjects; foreach (ProjectEntry projectEntry in ProjectEntries) { string projectPath = projectEntry.Path; string projectGuid = projectEntry.Guid; // determine whether project is on case-sensitive filesystem, bool caseSensitive = PlatformHelper.IsVolumeCaseSensitive(projectPath); // indicates whether the project should be skipped (excluded) bool skipProject = false; // check whether project should be excluded from build foreach (string excludedProjectFile in excludes.FileNames) { if (string.Compare(excludedProjectFile, projectPath, !caseSensitive, CultureInfo.InvariantCulture) == 0) { Log(Level.Verbose, "Excluding project '{0}'.", projectPath); // do not load project skipProject = true; // we have a match, so quit looking break; } } if (skipProject) { // remove dependencies for excluded projects if (explicitProjectDependencies.ContainsKey(projectGuid)) { explicitProjectDependencies.Remove(projectGuid); } // project was excluded, move on to next project continue; } Log(Level.Verbose, "Loading project '{0}'.", projectPath); ProjectBase p = _solutionTask.ProjectFactory.LoadProject(this, _solutionTask, _tfc, gacCache, refResolver, _outputDir, projectPath); if (p == null) { Log(Level.Warning, "Project '{0}' is of unsupported type. Skipping.", projectPath); // skip the project continue; } if (p.Guid == null || p.Guid == string.Empty) { p.Guid = FindGuidFromPath(projectPath); } // add project to entry projectEntry.Project = p; // set project build configuration SetProjectBuildConfiguration(projectEntry); } // add explicit dependencies (as set in VS.NET) to individual projects foreach (DictionaryEntry dependencyEntry in explicitProjectDependencies) { string projectGuid = (string) dependencyEntry.Key; Hashtable dependencies = (Hashtable) dependencyEntry.Value; ProjectEntry projectEntry = ProjectEntries[projectGuid]; if (projectEntry == null) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Dependencies for project \'{0}\' could not be analyzed." + " Project is not included.", projectGuid), Location.UnknownLocation); } ProjectBase project = projectEntry.Project; // make sure project is loaded if (project == null) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Dependencies for project \'{0}\' could not be analyzed." + " Project is not loaded.", projectGuid), Location.UnknownLocation); } foreach (string dependentProjectGuid in dependencies.Keys) { ProjectEntry dependentEntry = ProjectEntries[dependentProjectGuid]; if (dependentEntry == null || dependentEntry.Project == null) { Log(Level.Warning, "Project \"{0}\": ignored dependency" + " on project \"{1}\", which is not included.", project.Name, dependentProjectGuid); continue; } project.ProjectDependencies.Add(dependentEntry.Project); } } } protected void GetDependenciesFromProjects(Configuration solutionConfiguration) { Log(Level.Verbose, "Gathering additional dependencies..."); // first get all of the output files foreach (ProjectEntry projectEntry in ProjectEntries) { ProjectBase project = projectEntry.Project; if (project == null) { // skip projects that are not loaded/supported continue; } foreach (ConfigurationBase projectConfig in project.ProjectConfigurations.Values) { string projectOutputFile = projectConfig.OutputPath; if (projectOutputFile != null) { _htOutputFiles[projectOutputFile] = project.Guid; } } } // if one of output files resides in reference search path - circle began // we must build project with that outputFile before projects referencing it // (similar to project dependency) VS.NET 7.0/7.1 do not address this problem // build list of output which reside in such folders Hashtable outputsInAssemblyFolders = CollectionsUtil.CreateCaseInsensitiveHashtable(); foreach (DictionaryEntry de in _htOutputFiles) { string outputfile = (string) de.Key; string folder = Path.GetDirectoryName(outputfile); if (_solutionTask.AssemblyFolderList.Contains(folder)) { outputsInAssemblyFolders[Path.GetFileName(outputfile)] = (string) de.Value; } } // build the dependency list foreach (ProjectEntry projectEntry in ProjectEntries) { ProjectBase project = projectEntry.Project; if (project == null) { // skip projects that are not loaded/supported continue; } // check if project actually supports the build configuration ConfigurationBase projectConfig = project.BuildConfigurations[solutionConfiguration]; if (projectConfig == null) { continue; } // ensure output directory exists. VS creates output directories // before it starts compiling projects if (!projectConfig.OutputDir.Exists) { projectConfig.OutputDir.Create(); projectConfig.OutputDir.Refresh(); } foreach (ReferenceBase reference in project.References) { ProjectReferenceBase projectReference = reference as ProjectReferenceBase; if (projectReference != null) { project.ProjectDependencies.Add(projectReference.Project); } else { string outputFile = reference.GetPrimaryOutputFile( solutionConfiguration); // if we reference an assembly in an AssemblyFolder // that is an output directory of another project, // then add dependency on that project if (outputFile == null) { continue; } string dependencyGuid = (string) outputsInAssemblyFolders[Path.GetFileName(outputFile)]; if (dependencyGuid == null) { continue; } ProjectEntry dependencyEntry = ProjectEntries[dependencyGuid]; if (dependencyEntry != null && dependencyEntry.Project != null) { project.ProjectDependencies.Add(dependencyEntry.Project); } } } } } /// /// Translates a project path, in the form of a relative file path or /// a URL, to an absolute file path. /// /// The directory of the solution. /// The project path to translate to an absolute file path. /// /// The project path translated to an absolute file path. /// protected string TranslateProjectPath(string solutionDir, string projectPath) { if (solutionDir == null) { throw new ArgumentNullException("solutionDir"); } if (projectPath == null) { throw new ArgumentNullException("projectPath"); } string translatedPath = null; // translate URLs to physical paths if using a webmap string map = WebMaps.FindBestMatch(projectPath); if (map != null) { Log(Level.Debug, "Found webmap match '{0}' for '{1}.", map, projectPath); translatedPath = map; } else { translatedPath = projectPath; } try { #if NET_2_0 Uri uri = null; Uri.TryCreate(translatedPath, UriKind.Absolute, out uri); #else Uri uri = new Uri(translatedPath); #endif if(uri==null) { translatedPath = FileUtils.GetFullPath(FileUtils.CombinePaths( solutionDir, translatedPath)); } else if (uri.Scheme == Uri.UriSchemeFile) { translatedPath = FileUtils.GetFullPath(FileUtils.CombinePaths( solutionDir, uri.LocalPath)); } else { if (!_solutionTask.EnableWebDav) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Cannot build web project '{0}'. Please use" + " to map the given URL to a project-relative" + " path, or specify enablewebdav=\"true\" on the" + " task element to use WebDAV.", translatedPath)); } } } catch (UriFormatException) { translatedPath = FileUtils.GetFullPath(FileUtils.CombinePaths( solutionDir, translatedPath)); } return translatedPath; } /// /// Converts assembly references to projects to project references, adding /// a build dependency.c /// /// The to analyze. /// The solution configuration that is built. /// containing list of projects that have been built. /// containing list of projects that failed to build. protected bool FixProjectReferences(ProjectBase project, Configuration solutionConfiguration, Hashtable builtProjects, Hashtable failedProjects) { // check if the project still has dependencies that have not been // built if (HasDirtyProjectDependency(project, builtProjects)) { return false; } ConfigurationBase projectConfig = project.BuildConfigurations[solutionConfiguration]; // check if the project actually supports the build configuration if (projectConfig == null) { return false; } Log(Level.Verbose, "Fixing up references..."); ArrayList projectReferences = (ArrayList) project.References.Clone(); bool referencesFailedProject = false; foreach (ReferenceBase reference in projectReferences) { AssemblyReferenceBase assemblyReference = reference as AssemblyReferenceBase; if (assemblyReference == null) { // project references and wrappers don't // need to be fixed continue; } ProjectBase projectRef = null; string outputFile = assemblyReference.GetPrimaryOutputFile( solutionConfiguration); if (outputFile == null) { continue; } if (_htOutputFiles.Contains(outputFile)) { // if the reference is an output file of // another build configuration of a project // and this output file wasn't built before // then use the output file for the current // build configuration // // eg. a project file might be referencing the // the debug assembly of a given project as an // assembly reference, but the projects are now // being built in release configuration, so // instead of failing the build we use the // release assembly of that project // Note that this was designed to intentionally // deviate from VS.NET's building strategy. // See "Reference Configuration Matching" at http://nant.sourceforge.net/wiki/index.php/SolutionTask // for why we must always convert file references to project references // If we want a different behaviour, this // should be controlled by a flag projectRef = ProjectEntries[(string) _htOutputFiles[outputFile]].Project; } else if (_outputDir != null) { // if an output directory is set, then the // assembly reference might not have been // resolved during Reference initialization, // as the output file of the project might // not have existed at that time // // this will perform matching on file name // only, so its really tricky (VS.NET does // not support this) string projectOutput = FileUtils.CombinePaths( _outputDir.FullName, Path.GetFileName( outputFile)); if (_htOutputFiles.Contains(projectOutput)) { projectRef = (ProjectBase) ProjectEntries[ (string) _htOutputFiles[projectOutput]].Project; } } // try matching assembly reference and project on assembly name // if the assembly file does not exist if (projectRef == null && !System.IO.File.Exists(outputFile)) { foreach (ProjectEntry projectEntry in ProjectEntries) { // we can only do this for managed projects, as we only have // an assembly name for these ManagedProjectBase managedProject = projectEntry.Project as ManagedProjectBase; if (managedProject == null) { continue; } // check if the assembly names match if (assemblyReference.Name == managedProject.ProjectSettings.AssemblyName) { projectRef = managedProject; break; } } } if (projectRef != null) { if (!referencesFailedProject && failedProjects.ContainsKey(projectRef.Guid)) { referencesFailedProject = true; } ProjectReferenceBase projectReference = assemblyReference. CreateProjectReference(projectRef); Log(Level.Verbose, "Converted assembly reference to project reference: {0} -> {1}", assemblyReference.Name, projectReference.Name); // remove assembly reference from project project.References.Remove(assemblyReference); // add project reference instead project.References.Add(projectReference); // unless referenced project has already been build, add // referenced project as project dependency if (!builtProjects.Contains(projectReference.Project.Guid)) { project.ProjectDependencies.Add(projectReference.Project); } } } return referencesFailedProject; } protected BuildException CreateProjectDoesNotExistException(string projectPath) { return new BuildException(string.Format(CultureInfo.InvariantCulture, "Project '{0}' does not exist.", projectPath)); } protected virtual void SetProjectBuildConfiguration(ProjectEntry projectEntry) { if (projectEntry.BuildConfigurations == null) { // project was not loaded from solution file, and as a result // there's no project configuration section available, so we'll // consider all project configurations as valid build // configurations ProjectBase project = projectEntry.Project; project.BuildConfigurations.Clear(); foreach (ConfigurationDictionaryEntry ce in project.ProjectConfigurations) { project.BuildConfigurations[ce.Name] = ce.Config; } } else { // project was loaded from solution file, so only add build // configurations that were listed in project configuration // section ProjectBase project = projectEntry.Project; foreach (ConfigurationMapEntry ce in projectEntry.BuildConfigurations) { Configuration solutionConfig = ce.Key; Configuration projectConfig = ce.Value; ConfigurationBase conf = project.ProjectConfigurations [projectConfig]; if (conf != null) { project.BuildConfigurations[solutionConfig] = conf; } } } } #endregion Protected Instance Methods #region Private Instance Methods /// /// Determines whether any of the project dependencies of the specified /// project still needs to be built. /// /// The to analyze. /// containing list of projects that have been built. /// /// if one of the project dependencies has not /// yet been built; otherwise, . /// private bool HasDirtyProjectDependency(ProjectBase project, Hashtable builtProjects) { foreach (ProjectBase projectDependency in project.ProjectDependencies) { if (!builtProjects.ContainsKey(projectDependency.Guid)) { return true; } } return false; } private string FindGuidFromPath(string projectPath) { foreach (ProjectEntry projectEntry in ProjectEntries) { if (string.Compare(projectEntry.Path, projectPath, true, CultureInfo.InvariantCulture) == 0) { return projectEntry.Guid; } } return string.Empty; } #endregion Private Instance Methods #region Private Instance Fields private readonly FileInfo _file; private readonly ProjectEntryCollection _projectEntries; private readonly Hashtable _htOutputFiles; private readonly Hashtable _htReferenceProjects; private readonly SolutionTask _solutionTask; private readonly WebMapCollection _webMaps; private readonly DirectoryInfo _outputDir; private readonly TempFileCollection _tfc; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.VSNet/FileReferenceBase.cs0000644000175000017500000001460711757302274021306 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Matthew Mastracci (matt@aclaro.com) // Scott Ford (sford@RJKTECH.com) // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Xml; using NAnt.Core; using NAnt.Core.Util; namespace NAnt.VSNet { public abstract class FileReferenceBase : ReferenceBase { #region Protected Instance Constructors protected FileReferenceBase(XmlElement xmlDefinition, ReferencesResolver referencesResolver, ProjectBase parent, GacCache gacCache) : base(referencesResolver, parent) { if (xmlDefinition == null) { throw new ArgumentNullException("xmlDefinition"); } if (gacCache == null) { throw new ArgumentNullException("gacCache"); } _xmlDefinition = xmlDefinition; _gacCache = gacCache; } #endregion Protected Instance Constructors #region Protected Instance Properties protected XmlElement XmlDefinition { get { return _xmlDefinition; } } protected GacCache GacCache { get { return _gacCache; } } #endregion Protected Instance Properties #region Override implementation of ReferenceBase /// /// Gets a value indicating whether the reference is managed for the /// specified configuration. /// /// The build configuration of the reference. /// /// . /// public override bool IsManaged(Configuration config) { return true; } #endregion Override implementation of ReferenceBase #region Protected Instance Methods /// /// Gets the complete set of output files for the specified assembly /// and adds them to collection. /// /// The path of the assembly to get the output files for. /// The set of output files to be updated. /// /// The key of the case-insensitive is the /// full path of the output file and the value is the path relative to /// the output directory. /// protected void GetAssemblyOutputFiles(string assemblyFile, Hashtable outputFiles) { if (!File.Exists(assemblyFile)) { // no need to output warning if set of output files cannot be // generated return; } if (!outputFiles.ContainsKey(assemblyFile)) { string[] referencedModules = GetAllReferencedModules(assemblyFile); // get a list of the references in the output directory foreach (string referenceFile in referencedModules) { // skip module if module is not the assembly referenced by // the project and is installed in GAC if (string.Compare(referenceFile, assemblyFile, true, CultureInfo.InvariantCulture) != 0) { // skip referenced module if the assembly referenced by // the project is a system reference or the module itself // is installed in the GAC if (IsSystem || GacCache.IsAssemblyInGac(referenceFile)) { continue; } } // get list of files related to referenceFile, this will include // referenceFile itself GetRelatedFiles(referenceFile, outputFiles); } } } #endregion Protected Instance Methods #region Private Instance Methods private string[] GetAllReferencedModules(string module) { string fullPathToModule = FileUtils.GetFullPath(module); string moduleDirectory = Path.GetDirectoryName(fullPathToModule); Hashtable allReferences = new Hashtable(); Hashtable unresolvedReferences = new Hashtable(); try { allReferences.Add(fullPathToModule, null); unresolvedReferences.Add(fullPathToModule, null); while (unresolvedReferences.Count > 0) { IDictionaryEnumerator unresolvedEnumerator = unresolvedReferences.GetEnumerator(); unresolvedEnumerator.MoveNext(); string referenceToResolve = (string) unresolvedEnumerator.Key; unresolvedReferences.Remove(referenceToResolve); ReferencesResolver.AppendReferencedModulesLocatedInGivenDirectory( moduleDirectory, referenceToResolve, ref allReferences, ref unresolvedReferences); } } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Error resolving module references of '{0}'.", fullPathToModule), Location.UnknownLocation, ex); } string[] result = new string[allReferences.Keys.Count]; allReferences.Keys.CopyTo(result, 0); return result; } #endregion Private Instance Methods #region Private Instance Fields private readonly XmlElement _xmlDefinition; private readonly GacCache _gacCache; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.VSNet/JSharpProjectProvider.cs0000644000175000017500000000371211757302274022241 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Martin Aliger (martin_aliger@myrealbox.com) using System; using System.CodeDom.Compiler; using System.IO; using System.Xml; using NAnt.Core; using NAnt.Core.Util; using NAnt.VSNet.Extensibility; using NAnt.VSNet.Tasks; namespace NAnt.VSNet { internal class JSharpProjectProvider : IProjectBuildProvider { #region Implementation of IProjectBuildProvider public int IsSupported(string projectExt, XmlElement xmlDefinition) { if (projectExt == ".vjsproj") return 5; if (JSharpProject.IsSupported(xmlDefinition)) return 10; return 0; } public ProjectBase GetInstance(SolutionBase solution, string projectPath, XmlElement xmlDefinition, SolutionTask solutionTask, TempFileCollection tfc, GacCache gacCache, ReferencesResolver refResolver, DirectoryInfo outputDir) { return new JSharpProject(solution, projectPath, xmlDefinition, solutionTask, tfc, gacCache, refResolver, outputDir); } public string LoadGuid(XmlElement xmlDefinition) { return JSharpProject.LoadGuid(xmlDefinition); } #endregion Implementation of IProjectBuildProvider } } nant-0.92-rc1/src/NAnt.VSNet/Configuration.cs0000644000175000017500000000726411757302274020625 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2008 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net.be) using System; using System.Globalization; namespace NAnt.VSNet { public class Configuration : IComparable { public Configuration() { } public Configuration(string name, string platform) { if (name == null) throw new ArgumentNullException ("name"); _name = name; _platform = platform; } public string Name { get { return _name; } set { if (value == null) throw new ArgumentNullException ("value"); _name = value; } } public string Platform { get { if (_platform == null) return string.Empty; return _platform; } set { _platform = value; } } #region Implementation of IComparable public int CompareTo(object obj) { if (this.Equals(obj)) return 0; return 1; } #endregion Implementation of IComparable #region Override implementation of Object public override bool Equals(object obj) { if (obj == null) return false; Configuration config = obj as Configuration; if (config == null) return false; return (string.Compare (Name, config.Name, true, CultureInfo.InvariantCulture) == 0) && (string.Compare (Platform, config.Platform, true, CultureInfo.InvariantCulture) == 0); } public override int GetHashCode() { return Name.ToLower (CultureInfo.InvariantCulture).GetHashCode () ^ Platform.ToLower (CultureInfo.InvariantCulture).GetHashCode (); } public override string ToString() { if (Platform.Length == 0) { return Name; } return Name + "|" + Platform; } #endregion Override implementation of Object public static bool operator == (Configuration c1, Configuration c2) { if ((object) c1 == null) { return ((object) c2 == null); } return c1.Equals (c2); } public static bool operator != (Configuration c1, Configuration c2) { return !(c1 == c2); } public static Configuration Parse (string config) { if (config == null) { throw new ArgumentNullException ("config"); } int index = config.IndexOf("|"); if (index > 0 && index < config.Length) { return new Configuration (config.Substring(0, index), config.Substring (index + 1)); } else { return new Configuration (config, null); } } private string _name; private string _platform; } } nant-0.92-rc1/src/NAnt.Console/0000755000175000017500000000000011757310030016046 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.Console/NAnt.Console.csproj0000644000175000017500000001516311757302272021550 0ustar jtaylorjtaylor Debug AnyCPU 2.0 {859696F8-F405-4018-A155-D34561498A3E} NAnt.Console NAnt Exe OnSuccessfulBuild false 8.0.50727 v2.0 2.0 publish\ true Disk false Foreground 7 Days false false true 0 1.0.0.%2a false false true true full false 4 ..\..\build\Debug\ AllRules.ruleset TRACE;DEBUG ..\..\build\Debug\NAnt.xml true pdbonly true ..\..\build\Release\ 4 AllRules.ruleset TRACE ..\..\build\Release\NAnt.xml ..\..\lib\common\neutral\log4net.dll CommonAssemblyInfo.cs False .NET Framework 3.5 SP1 Client Profile false False .NET Framework 3.5 SP1 true False Windows Installer 3.1 true {8F80C098-94A4-44DB-A25D-C9E455FC3120} NAnt.Compression {8F5F8375-4097-4952-B860-784EB9961ABE} NAnt.Core {B50A1067-785B-4686-8FFC-5AF424BEF163} NAnt.DotNet {318C04B2-D982-4243-9C6A-CA7E035E927D} NAnt.MSBuild {ED13C268-36DE-49CE-B347-C2BE03F814B9} NAnt.MSNet {00F5C075-9874-4BCE-909A-99C1F600E047} NAnt.NUnit {0F3EA7A9-C5F6-4254-820C-B5E0409B5B9D} NAnt.NUnit1 {47503BEE-27D9-4D1C-B8E1-6C9CCC19AEAA} NAnt.NUnit2 {6B2EC648-8D69-4096-B4F9-6EDC0B2F98EF} NAnt.SourceControl {F77EA08E-9473-436A-BBA3-880139A341B1} NAnt.Tests {A154DB17-7263-44E3-838E-1E4C4946B7D8} NAnt.VisualCpp {DD434690-B4DF-4BF9-91FE-F139A41E2474} NAnt.VSNet {C66545A2-6FEC-4A38-937A-5B25E61EE8A1} NAnt.Win32 {841FAEBA-4527-410A-B765-E2EDA47ABDCE} NDoc.Documenter.NAnt nant-0.92-rc1/src/NAnt.Console/AssemblyInfo.cs0000644000175000017500000000315711757302272021007 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Scott Hernandez (ScottHernandez@hotmail.com) // Gert Driesen (drieseng@users.sourceforge.net) using System.Reflection; // Configure log4net using the application configuration file // (AppDomain.CurrentDomain.SetupInformation.ConfigurationFile). // The application configuration file will be directly accessed // by log4net (not using the System.Configuration namespace). // The log4net configuration will be reloaded whenever the // configuration file is changed. [assembly: log4net.Config.XmlConfigurator(Watch=true)] // This will not compile with Visual Studio. If you want to build a signed // executable use the NAnt build file. To build under Visual Studio just // exclude this file from the build. [assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile(@"..\NAnt.key")] [assembly: AssemblyKeyName("")] nant-0.92-rc1/src/NAnt.Console/NAnt.Console.build0000644000175000017500000000615411757302272021347 0ustar jtaylorjtaylor nant-0.92-rc1/src/NAnt.Console/App.config0000644000175000017500000052717511757302272020007 0ustar jtaylorjtaylor
    true true sn lc false false true true sn lc true true true true true true true true true true true true true true true true true true true true true true sn lc true true true true true true true true true true true true true true true true true true true true true true true sn lc true true true true true true true true true true true true true true true true true true true true true true true sn lc true The .NET Framework 1.1 SDK is not installed. true true true cfresgen sn lc The .NET Framework 2.0 SDK is not installed. true true true true true true true true true true true true true true true true true true true true sn lc true true true true true true true true true true true true true true true true true true true true true true true true true true sn lc true true true true true true true true true true true true true true true true true true true true true true true true true true sn lc true true true true true true true true true true true true true true true true true true true true true true true true true true sn lc true true true true true true true true true true true true true true true true true true true true true true true true true true sn lc true true ${csc.tool} true true true ${csc.supportsdocgeneration} true true true true mjs true ${mbas.tool} true ${resgen.tool} true sn true false true true gmcs true true true ${csc.supportsdocgeneration} true true true true mjs strict vbnc true ${resgen.tool} true ${resgen.supportsexternalfilereferences} sn true false true true gmcs true linq true true true true true true true mjs strict vbnc true true true sn true false true true dmcs true linq true true true true true true true mjs strict vbnc true true true sn true false true smcs true true true true true true true true true true sn false true true sn false true true Unable to locate 'mono' module using pkg-config. Download the Mono development packages from http://www.mono-project.com/downloads/. true ${path::combine(prefix, 'lib/mono/1.0/mcs.exe')} true true true ${csc.supportsdocgeneration} true true true true mjs true ${path::combine(prefix, 'lib/mono/1.0/mbas.exe')} true ${resgen.tool} true sn true false true Unable to locate 'mono' module using pkg-config. Download the Mono development packages from http://www.mono-project.com/downloads/. true gmcs true true true ${csc.supportsdocgeneration} true true true true mjs strict vbnc true ${resgen.tool} true ${resgen.supportsexternalfilereferences} sn true false true Unable to locate 'mono' module using pkg-config. Download the Mono development packages from http://www.mono-project.com/downloads/. true gmcs true linq true true true true true true true mjs strict vbnc true true true sn true false true Unable to locate 'mono' module using pkg-config. Download the Mono development packages from http://www.mono-project.com/downloads/. true dmcs true linq true true true true true true true mjs strict vbnc true true true sn true false true Unable to locate 'mono' module using pkg-config. Download the Mono development packages from http://www.mono-project.com/downloads/. smcs true true true true true true true true true true sn false nant-0.92-rc1/src/NAnt.Console/ConsoleStub.cs0000644000175000017500000005277011757302272020661 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2002-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Scott Hernandez (ScottHernandez@hotmail.com) // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.IO; using System.Collections; using System.Configuration; using System.Reflection; using System.Globalization; using System.Text; using System.Xml; using System.Security; using System.Security.Permissions; using System.Security.Policy; namespace NAnt.Console { /// /// Stub used to created and launch real ConsoleDriver /// class in Core assembly. /// public class ConsoleStub { #region Static Constructor static ConsoleStub() { // check a class in mscorlib to determine if we're running on Mono if (Type.GetType("System.MonoType", false) != null) { FrameworkFamily = "mono"; } else { FrameworkFamily = "net"; } // check for non-Unix platforms - see FAQ for more details // http://www.mono-project.com/FAQ:_Technical#How_to_detect_the_execution_platform_.3F int platform = (int) Environment.OSVersion.Platform; if (platform != 4 && platform != 128) { Platform = "win32"; } else { Platform = "unix"; } } #endregion Static Constructor #region Public Static Methods /// /// Entry point for executable /// /// Command Line arguments /// The result of the real execution [STAThread] public static int Main(string[] args) { AppDomain cd = AppDomain.CurrentDomain; AppDomain executionAD = cd; string nantShadowCopyFilesSetting = ConfigurationManager.AppSettings.Get("nant.shadowfiles"); string nantCleanupShadowCopyFilesSetting = ConfigurationManager.AppSettings.Get("nant.shadowfiles.cleanup"); Framework runtimeFramework = Framework.GetRuntimeFramework(); if (runtimeFramework == null) { // signal error return 1; } string privateBinPath = ConstructPrivateBinPath(runtimeFramework, AppDomain.CurrentDomain.BaseDirectory); if (nantShadowCopyFilesSetting != null && bool.Parse(nantShadowCopyFilesSetting) == true) { logger.Debug(string.Format( CultureInfo.InvariantCulture, "Shadowing files({0}) -- cleanup={1}", nantShadowCopyFilesSetting, nantCleanupShadowCopyFilesSetting)); System.AppDomainSetup myDomainSetup = new System.AppDomainSetup(); myDomainSetup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory; logger.Debug(string.Format( CultureInfo.InvariantCulture, "NAntDomain.PrivateBinPath={0}", myDomainSetup.PrivateBinPath)); myDomainSetup.PrivateBinPath = privateBinPath; myDomainSetup.ApplicationName = "NAnt"; // copy the config file location myDomainSetup.ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile; logger.Debug(string.Format( CultureInfo.InvariantCulture, "NAntDomain.ConfigurationFile={0}", myDomainSetup.ConfigurationFile)); // yes, cache the files myDomainSetup.ShadowCopyFiles = "true"; // shadowcopy everything in base directory of appdomain and // privatebinpath myDomainSetup.ShadowCopyDirectories = myDomainSetup.ApplicationBase + Path.PathSeparator + myDomainSetup.PrivateBinPath; logger.Debug(string.Format( CultureInfo.InvariantCulture, "NAntDomain.ShadowCopyDirectories={0}", myDomainSetup.ShadowCopyDirectories)); // try to cache in .\cache folder, if that fails, let the system // figure it out. string cachePath = Path.Combine(myDomainSetup.ApplicationBase, "cache"); DirectoryInfo cachePathInfo = null; try { cachePathInfo = Directory.CreateDirectory(cachePath); } catch (Exception e) { System.Console.WriteLine("Failed to create: {0}. Using default CachePath." + e.ToString(), cachePath); } finally { if(cachePathInfo != null) { myDomainSetup.CachePath = cachePathInfo.FullName; } logger.Debug(string.Format( CultureInfo.InvariantCulture, "NAntDomain.CachePath={0}", myDomainSetup.CachePath)); } // create the domain. PermissionSet myDomainPermSet = new PermissionSet(PermissionState.Unrestricted); executionAD = AppDomain.CreateDomain(myDomainSetup.ApplicationName, AppDomain.CurrentDomain.Evidence, myDomainSetup, myDomainPermSet); logger.Debug(string.Format( CultureInfo.InvariantCulture, "NAntDomain.SetupInfo:\n{0}", executionAD.SetupInformation)); } // use helper object to hold (and serialize) args for callback. logger.Debug(string.Format( CultureInfo.InvariantCulture, "Creating HelperArgs({0})", args.ToString())); HelperArguments helper = new HelperArguments(args, privateBinPath); executionAD.DoCallBack(new CrossAppDomainDelegate(helper.CallConsoleRunner)); // unload if remote/new appdomain if (!cd.Equals(executionAD)) { string cachePath = executionAD.SetupInformation.CachePath; logger.Debug(string.Format( CultureInfo.InvariantCulture, "Unloading '{0}' AppDomain", executionAD.FriendlyName)); AppDomain.Unload(executionAD); if (nantCleanupShadowCopyFilesSetting != null && bool.Parse(nantCleanupShadowCopyFilesSetting) == true) { logger.Debug(string.Format( CultureInfo.InvariantCulture, "Unloading '{0}' AppDomain", executionAD.FriendlyName)); try { logger.Debug(string.Format( CultureInfo.InvariantCulture, "Cleaning up CacheFiles in '{0}'", cachePath)); Directory.Delete(cachePath, true); } catch (FileNotFoundException ex) { logger.Error("Files not found.", ex); } catch (Exception ex) { System.Console.WriteLine("Unable to delete cache path '{1}'.\n\n{0}.", ex.ToString(), cachePath); } } } if (helper == null || helper.ExitCode == -1) { logger.Debug(string.Format( CultureInfo.InvariantCulture, "Return Code null or -1")); throw new ApplicationException("No return code set!"); } else { logger.Debug(string.Format( CultureInfo.InvariantCulture, "Return Code = {0}", helper.ExitCode)); return helper.ExitCode; } } #endregion Public Static Methods #region Private Static Methods /// /// Constructs the privatebinpath. /// /// /// /// For the common version dir, we do not use the framework version /// as defined in the NAnt configuration file but the CLR version /// since the assemblies in that directory are not specific to a /// certain family and the framwork version might differ between /// families (eg. mono 1.0 == .NET 1.1). /// /// /// The runtime framework. /// The base directory of the domain. /// /// The privatebinpath. /// private static string ConstructPrivateBinPath (Framework runtimeFramework, string baseDir) { StringBuilder sb = new StringBuilder (); foreach (string probePath in runtimeFramework.ProbePaths) { string fullDir = Path.Combine (baseDir, probePath); AppendPrivateBinDir(baseDir, fullDir, sb); } // add privatebinpath of current domain to privatebinpath if (AppDomain.CurrentDomain.SetupInformation.PrivateBinPath != null) { if (sb.Length > 0) { sb.Append(Path.PathSeparator); } sb.Append(AppDomain.CurrentDomain.SetupInformation.PrivateBinPath); } return sb.ToString(); } private static void AppendPrivateBinDir(string baseDir, string dir, StringBuilder sb) { if (!Directory.Exists (dir)) { return; } if (sb.Length != 0) { sb.Append(Path.PathSeparator); } sb.Append(GetRelativePath(baseDir, dir)); string[] subDirs = Directory.GetDirectories(dir); for (int i = 0; i < subDirs.Length; i++) { AppendPrivateBinDir(baseDir, subDirs[i], sb); } } /// /// Given an absolute directory and an absolute file name, returns a /// relative file name. /// /// An absolute directory. /// An absolute file name. /// /// A relative file name for the given absolute file name. /// private static string GetRelativePath(string basePath, string absolutePath) { string fullBasePath = Path.GetFullPath(basePath); string fullAbsolutePath = Path.GetFullPath(absolutePath); bool caseInsensitive = false; // check if we're not on unix if ((int) Environment.OSVersion.Platform != 128) { // for simplicity, we'll consider all filesystems on windows // to be case-insensitive caseInsensitive = true; // on windows, paths with different roots are located on different // drives, so only absolute names will do if (string.Compare(Path.GetPathRoot(fullBasePath), Path.GetPathRoot(fullAbsolutePath), caseInsensitive) != 0) { return fullAbsolutePath; } } int baseLen = fullBasePath.Length; int absoluteLen = fullAbsolutePath.Length; // they are on the same "volume", find out how much of the base path // is in the absolute path int i = 0; while (i < absoluteLen && i < baseLen && string.Compare(fullBasePath[i].ToString(), fullAbsolutePath[i].ToString(), caseInsensitive) == 0) { i++; } if (i == baseLen && (fullAbsolutePath[i] == Path.DirectorySeparatorChar || fullAbsolutePath[i-1] == Path.DirectorySeparatorChar)) { // the whole current directory name is in the file name, // so we just trim off the current directory name to get the // current file name. if (fullAbsolutePath[i] == Path.DirectorySeparatorChar) { // a directory name might have a trailing slash but a relative // file name should not have a leading one... i++; } return fullAbsolutePath.Substring(i); } // The file is not in a child directory of the current directory, so we // need to step back the appropriate number of parent directories by // using ".."s. First find out how many levels deeper we are than the // common directory string commonPath = fullBasePath.Substring(0, i); int levels = 0; string parentPath = fullBasePath; // remove trailing directory separator character if (parentPath[parentPath.Length - 1] == Path.DirectorySeparatorChar) { parentPath = parentPath.Substring(0, parentPath.Length - 1); } while (string.Compare(parentPath,commonPath, caseInsensitive) != 0) { levels++; DirectoryInfo parentDir = Directory.GetParent(parentPath); if (parentDir != null) { parentPath = parentDir.FullName; } else { parentPath = null; } } string relativePath = ""; for (i = 0; i < levels; i++) { relativePath += ".." + Path.DirectorySeparatorChar; } relativePath += fullAbsolutePath.Substring(commonPath.Length); return relativePath; } #endregion Private Static Methods #region Private Static Fields private static readonly string FrameworkFamily; private static readonly string Platform; private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion Private Static Fields /// /// Helper class for invoking the application entry point in NAnt.Core /// and passing the command-line arguments. /// [Serializable()] private class HelperArguments : MarshalByRefObject { #region Public Instance Constructors /// /// Initializes a new instance of the /// class with the specified command-line arguments. /// /// The commandline arguments passed to NAnt.exe. /// Directories relative to the base directory of the AppDomain to probe for missing assembly references. public HelperArguments(string[] args, string probePaths) { _args = args; _probePaths = probePaths; } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets the status that the build process returned when it exited. /// /// /// The code that the build process specified when it terminated. /// public int ExitCode { get { return _exitCode; } } #endregion Public Instance Properties #region Public Instance Methods /// /// Invokes the application entry point in NAnt.Core. /// public void CallConsoleRunner() { // explicitly add the lib directory to privatebinpath although // its added to privatebinpath in the config file, as entries // in the config file are not reflected in SetupInformation if (Directory.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "lib"))) { AppDomain.CurrentDomain.AppendPrivatePath("lib"); } // add framework specific entries to privatebinpath if (_probePaths != null) { foreach (string probePath in _probePaths.Split(Path.PathSeparator)) { logger.Debug(string.Format(CultureInfo.InvariantCulture, "Adding '{0}' to private bin path.", probePath)); AppDomain.CurrentDomain.AppendPrivatePath(probePath); } } MethodInfo mainMethodInfo = null; //load the core by name! Assembly nantCore = AppDomain.CurrentDomain.Load("NAnt.Core"); logger.Info(string.Format( CultureInfo.InvariantCulture, "NAnt.Core Loaded: {0}", nantCore.FullName)); //get the ConsoleDriver by name Type consoleDriverType = nantCore.GetType("NAnt.Core.ConsoleDriver", true, true); //find the Main Method, this method is less than optimal, but other methods failed. foreach (MethodInfo methodInfo in consoleDriverType.GetMethods(BindingFlags.Static | BindingFlags.Public)) { if (methodInfo.Name.Equals("Main")) { mainMethodInfo = methodInfo; break; } } // invoke the Main method and pass the command-line arguments as parameter. _exitCode = (int) mainMethodInfo.Invoke(null, new object[] {_args}); logger.Debug(string.Format( CultureInfo.InvariantCulture, "'{0}' returned {1}", mainMethodInfo.ToString(), ExitCode)); } #endregion Public Instance Methods #region Private Instance Fields private string[] _args; private string _probePaths; private int _exitCode = -1; #endregion Private Instance Fields #region Private Static Fields private static readonly log4net.ILog logger = log4net.LogManager.GetLogger( System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion Private Static Fields } private class Framework { private readonly string _version; private readonly string[] _probePaths; private Framework (string version, string [] probePaths) { _version = version; _probePaths = probePaths; } public string Version { get { return _version; } } public string [] ProbePaths { get { return _probePaths; } } public static Framework GetRuntimeFramework () { XmlNode nantNode = (XmlNode) ConfigurationManager.GetSection("nant"); if (nantNode == null) { System.Console.WriteLine("The \"nant\" section in the NAnt" + " configuration file ({0}) is not available.", AppDomain.CurrentDomain.SetupInformation.ConfigurationFile); return null; } XmlElement frameworkNode = (XmlElement) nantNode.SelectSingleNode("frameworks/platform[@name='" + Platform + "']/framework[@family='" + FrameworkFamily + "' and @clrversion='" + Environment.Version.ToString(3) + "']"); if (frameworkNode == null) { System.Console.WriteLine("The NAnt configuration file ({0})" + " does not have a node for the current" + " runtime framework.", AppDomain.CurrentDomain.SetupInformation.ConfigurationFile); System.Console.WriteLine(string.Empty); System.Console.WriteLine("Please add a node" + " with family '{0}' and clrversion '{1}' under the" + " '{2}' platform node.", FrameworkFamily, Environment.Version.ToString(3), Platform); return null; } string frameworkVersion = frameworkNode.GetAttribute("version"); XmlNodeList includeNodes = frameworkNode.SelectNodes("runtime/probing-paths/directory"); ArrayList includes = new ArrayList (includeNodes.Count); foreach (XmlNode node in includeNodes) { XmlElement includeNode = (XmlElement) node; string name = includeNode.GetAttribute("name"); includes.Add (name); } string[] probePaths = new string[includes.Count]; includes.CopyTo (probePaths, 0); return new Framework(frameworkVersion, probePaths); } } } } nant-0.92-rc1/src/NAnt.VisualCpp/0000755000175000017500000000000011757310030016352 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.VisualCpp/AssemblyInfo.cs0000644000175000017500000000233211757302274021307 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gerry Shaw (gerry_shaw@yahoo.com) // Scott Hernandez (ScottHernandez@hotmail.com) // Gert Driesen (drieseng@users.sourceforge.net) using System.Reflection; // This will not compile with Visual Studio. If you want to build a signed // executable use the NAnt build file. To build under Visual Studio just // exclude this file from the build. [assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile(@"..\NAnt.key")] [assembly: AssemblyKeyName("")]nant-0.92-rc1/src/NAnt.VisualCpp/Types/0000755000175000017500000000000011757310030017456 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.VisualCpp/Types/Symbol.cs0000644000175000017500000000603311757302274021267 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2005 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using NAnt.Core; using NAnt.Core.Attributes; namespace NAnt.VisualCpp.Types { /// /// Represents a symbol. /// public class Symbol : Element { #region Private Instance Fields private string _symbolName; private bool _ifDefined = true; private bool _unlessDefined; #endregion Private Instance Fields #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public Symbol() { } /// /// Initializes a new instance of the class with /// the specified name. /// /// is . public Symbol(string name) { if (name == null) { throw new ArgumentNullException("name"); } _symbolName = name; } #endregion Public Instance Constructors #region Public Instance Properties /// /// The name of the symbol. /// [TaskAttribute("name", Required=true)] [StringValidator(AllowEmpty=false)] public string SymbolName { get { return _symbolName; } set { _symbolName = value; } } /// /// If then the element will be processed; /// otherwise, skipped. The default is . /// [TaskAttribute("if")] [BooleanValidator()] public bool IfDefined { get { return _ifDefined; } set { _ifDefined = value; } } /// /// If then the element will be skipped; /// otherwise, processed. The default is . /// [TaskAttribute("unless")] [BooleanValidator()] public bool UnlessDefined { get { return _unlessDefined; } set { _unlessDefined = value; } } #endregion Public Instance Properties } } nant-0.92-rc1/src/NAnt.VisualCpp/Types/CharacterSet.cs0000644000175000017500000000102111757302274022362 0ustar jtaylorjtaylorusing System; namespace NAnt.VisualCpp.Types { /// /// Defines the character sets that can be used by the C++ compiler. /// public enum CharacterSet { /// /// Have the compiler determine the character set. /// NotSet = 0, /// /// Unicode character set. /// Unicode = 1, /// /// Multi-byte character set. /// MultiByte = 2 } } nant-0.92-rc1/src/NAnt.VisualCpp/Types/SymbolCollection.cs0000644000175000017500000002123511757302274023304 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2005 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; namespace NAnt.VisualCpp.Types { /// /// Contains a collection of elements. /// [Serializable()] public class SymbolCollection : CollectionBase { #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public SymbolCollection() { } /// /// Initializes a new instance of the class /// with the specified instance. /// public SymbolCollection(SymbolCollection value) { AddRange(value); } /// /// Initializes a new instance of the class /// with the specified array of instances. /// public SymbolCollection(Symbol[] value) { AddRange(value); } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets the element at the specified index. /// /// The zero-based index of the element to get or set. [System.Runtime.CompilerServices.IndexerName("Item")] public Symbol this[int index] { get {return ((Symbol)(base.List[index]));} set {base.List[index] = value;} } #endregion Public Instance Properties #region Public Instance Methods /// /// Adds a to the end of the collection. /// /// The to be added to the end of the collection. /// The position into which the new element was inserted. public int Add(Symbol item) { return base.List.Add(item); } /// /// Adds the elements of a array to the end of the collection. /// /// The array of elements to be added to the end of the collection. public void AddRange(Symbol[] items) { for (int i = 0; (i < items.Length); i = (i + 1)) { Add(items[i]); } } /// /// Adds the elements of a to the end of the collection. /// /// The to be added to the end of the collection. public void AddRange(SymbolCollection items) { for (int i = 0; (i < items.Count); i = (i + 1)) { Add(items[i]); } } /// /// Determines whether a is in the collection. /// /// The to locate in the collection. /// /// if is found in the /// collection; otherwise, . /// public bool Contains(Symbol item) { return base.List.Contains(item); } /// /// Copies the entire collection to a compatible one-dimensional array, starting at the specified index of the target array. /// /// The one-dimensional array that is the destination of the elements copied from the collection. The array must have zero-based indexing. /// The zero-based index in at which copying begins. public void CopyTo(Symbol[] array, int index) { base.List.CopyTo(array, index); } /// /// Retrieves the index of a specified object in the collection. /// /// The object for which the index is returned. /// /// The index of the specified . If the is not currently a member of the collection, it returns -1. /// public int IndexOf(Symbol item) { return base.List.IndexOf(item); } /// /// Inserts a into the collection at the specified index. /// /// The zero-based index at which should be inserted. /// The to insert. public void Insert(int index, Symbol item) { base.List.Insert(index, item); } /// /// Returns an enumerator that can iterate through the collection. /// /// /// A for the entire collection. /// public new SymbolEnumerator GetEnumerator() { return new SymbolEnumerator(this); } /// /// Removes a member from the collection. /// /// The to remove from the collection. public void Remove(Symbol item) { base.List.Remove(item); } #endregion Public Instance Methods } /// /// Enumerates the elements of a . /// public class SymbolEnumerator : IEnumerator { #region Internal Instance Constructors /// /// Initializes a new instance of the class /// with the specified . /// /// The collection that should be enumerated. internal SymbolEnumerator(SymbolCollection arguments) { IEnumerable temp = (IEnumerable) (arguments); _baseEnumerator = temp.GetEnumerator(); } #endregion Internal Instance Constructors #region Implementation of IEnumerator /// /// Gets the current element in the collection. /// /// /// The current element in the collection. /// public Symbol Current { get { return (Symbol) _baseEnumerator.Current; } } object IEnumerator.Current { get { return _baseEnumerator.Current; } } /// /// Advances the enumerator to the next element of the collection. /// /// /// if the enumerator was successfully advanced /// to the next element; if the enumerator has /// passed the end of the collection. /// public bool MoveNext() { return _baseEnumerator.MoveNext(); } bool IEnumerator.MoveNext() { return _baseEnumerator.MoveNext(); } /// /// Sets the enumerator to its initial position, which is before the /// first element in the collection. /// public void Reset() { _baseEnumerator.Reset(); } void IEnumerator.Reset() { _baseEnumerator.Reset(); } #endregion Implementation of IEnumerator #region Private Instance Fields private IEnumerator _baseEnumerator; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.VisualCpp/Types/Library.cs0000644000175000017500000000604711757302274021433 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2005 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using NAnt.Core; using NAnt.Core.Attributes; namespace NAnt.VisualCpp.Types { /// /// Represents a library. /// public class Library : Element { #region Private Instance Fields private string _libraryName; private bool _ifDefined = true; private bool _unlessDefined; #endregion Private Instance Fields #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public Library() { } /// /// Initializes a new instance of the class with /// the specified name. /// /// is . public Library(string name) { if (name == null) { throw new ArgumentNullException("name"); } _libraryName = name; } #endregion Public Instance Constructors #region Public Instance Properties /// /// The name of the library. /// [TaskAttribute("name", Required=true)] [StringValidator(AllowEmpty=false)] public string LibraryName { get { return _libraryName; } set { _libraryName = value; } } /// /// If then the element will be processed; /// otherwise, skipped. The default is . /// [TaskAttribute("if")] [BooleanValidator()] public bool IfDefined { get { return _ifDefined; } set { _ifDefined = value; } } /// /// If then the element will be skipped; /// otherwise, processed. The default is . /// [TaskAttribute("unless")] [BooleanValidator()] public bool UnlessDefined { get { return _unlessDefined; } set { _unlessDefined = value; } } #endregion Public Instance Properties } } nant-0.92-rc1/src/NAnt.VisualCpp/Types/LibraryCollection.cs0000644000175000017500000002131611757302274023443 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2005 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Gert Driesen (drieseng@users.sourceforge.net) using System; using System.Collections; namespace NAnt.VisualCpp.Types { /// /// Contains a collection of elements. /// [Serializable()] public class LibraryCollection : CollectionBase { #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public LibraryCollection() { } /// /// Initializes a new instance of the class /// with the specified instance. /// public LibraryCollection(LibraryCollection value) { AddRange(value); } /// /// Initializes a new instance of the class /// with the specified array of instances. /// public LibraryCollection(Library[] value) { AddRange(value); } #endregion Public Instance Constructors #region Public Instance Properties /// /// Gets or sets the element at the specified index. /// /// The zero-based index of the element to get or set. [System.Runtime.CompilerServices.IndexerName("Item")] public Library this[int index] { get {return ((Library)(base.List[index]));} set {base.List[index] = value;} } #endregion Public Instance Properties #region Public Instance Methods /// /// Adds a to the end of the collection. /// /// The to be added to the end of the collection. /// The position into which the new element was inserted. public int Add(Library item) { return base.List.Add(item); } /// /// Adds the elements of a array to the end of the collection. /// /// The array of elements to be added to the end of the collection. public void AddRange(Library[] items) { for (int i = 0; (i < items.Length); i = (i + 1)) { Add(items[i]); } } /// /// Adds the elements of a to the end of the collection. /// /// The to be added to the end of the collection. public void AddRange(LibraryCollection items) { for (int i = 0; (i < items.Count); i = (i + 1)) { Add(items[i]); } } /// /// Determines whether a is in the collection. /// /// The to locate in the collection. /// /// if is found in the /// collection; otherwise, . /// public bool Contains(Library item) { return base.List.Contains(item); } /// /// Copies the entire collection to a compatible one-dimensional array, starting at the specified index of the target array. /// /// The one-dimensional array that is the destination of the elements copied from the collection. The array must have zero-based indexing. /// The zero-based index in at which copying begins. public void CopyTo(Library[] array, int index) { base.List.CopyTo(array, index); } /// /// Retrieves the index of a specified object in the collection. /// /// The object for which the index is returned. /// /// The index of the specified . If the is not currently a member of the collection, it returns -1. /// public int IndexOf(Library item) { return base.List.IndexOf(item); } /// /// Inserts a into the collection at the specified index. /// /// The zero-based index at which should be inserted. /// The to insert. public void Insert(int index, Library item) { base.List.Insert(index, item); } /// /// Returns an enumerator that can iterate through the collection. /// /// /// A for the entire collection. /// public new LibraryEnumerator GetEnumerator() { return new LibraryEnumerator(this); } /// /// Removes a member from the collection. /// /// The to remove from the collection. public void Remove(Library item) { base.List.Remove(item); } #endregion Public Instance Methods } /// /// Enumerates the elements of a . /// public class LibraryEnumerator : IEnumerator { #region Internal Instance Constructors /// /// Initializes a new instance of the class /// with the specified . /// /// The collection that should be enumerated. internal LibraryEnumerator(LibraryCollection arguments) { IEnumerable temp = (IEnumerable) (arguments); _baseEnumerator = temp.GetEnumerator(); } #endregion Internal Instance Constructors #region Implementation of IEnumerator /// /// Gets the current element in the collection. /// /// /// The current element in the collection. /// public Library Current { get { return (Library) _baseEnumerator.Current; } } object IEnumerator.Current { get { return _baseEnumerator.Current; } } /// /// Advances the enumerator to the next element of the collection. /// /// /// if the enumerator was successfully advanced /// to the next element; if the enumerator has /// passed the end of the collection. /// public bool MoveNext() { return _baseEnumerator.MoveNext(); } bool IEnumerator.MoveNext() { return _baseEnumerator.MoveNext(); } /// /// Sets the enumerator to its initial position, which is before the /// first element in the collection. /// public void Reset() { _baseEnumerator.Reset(); } void IEnumerator.Reset() { _baseEnumerator.Reset(); } #endregion Implementation of IEnumerator #region Private Instance Fields private IEnumerator _baseEnumerator; #endregion Private Instance Fields } } nant-0.92-rc1/src/NAnt.VisualCpp/Util/0000755000175000017500000000000011757310030017267 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.VisualCpp/Util/ArgumentUtils.cs0000644000175000017500000001510111757302274022432 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2004 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Hani Atassi (haniatassi@users.sourceforge.net) using System; using System.ComponentModel; namespace NAnt.VisualCpp.Util { /// /// Defines how to deal with backslashes in values of command line /// arguments. /// public enum BackslashProcessingMethod { /// /// Does not perform any processing on backslashes. /// None = 0, /// /// Duplicates the trailing backslash. /// Duplicate = 1, /// /// Fixes the trailing backslash by replaces trailing double backslashes /// with only one backslash and removing single trailing backslashes. /// Fix = 2, /// /// Removes all the trailing backslashes. /// Clean = 3 } /// /// Groups a set of useful manipulation methods for /// command-line arguments. /// public class ArgumentUtils { /// /// Performs backslash processing on the specified value using a given /// method. /// /// The to process. /// The to use. /// /// with backslashes processed using the given /// . /// public static string ProcessTrailingBackslash(string value, BackslashProcessingMethod processingMethod) { string processedValue = null; switch (processingMethod) { case BackslashProcessingMethod.None: processedValue = value; break; case BackslashProcessingMethod.Duplicate: processedValue = DuplicateTrailingBackslash(value); break; case BackslashProcessingMethod.Fix: processedValue = FixTrailingBackslash(value); break; case BackslashProcessingMethod.Clean: processedValue = CleanTrailingBackslash(value); break; default: throw new InvalidEnumArgumentException("processingMethod", (int) processingMethod, typeof(BackslashProcessingMethod)); } return processedValue; } /// /// Duplicates the trailing backslash. /// /// The input string to check and duplicate the trailing backslash if necessary. /// The result string after being processed. /// /// Also duplicates trailing backslash in quoted value. /// public static string DuplicateTrailingBackslash(string value) { if (value == null) { throw new ArgumentNullException("value"); } if (value.Length == 0) { return value; } bool isQuoted = value.Length > 2 && value.StartsWith("\"") && value.EndsWith("\""); int lastIndex = (isQuoted ? value.Length - 2 : value.Length - 1); if (value[lastIndex] == '\\') { return value.Insert(lastIndex, @"\"); } return value; } /// /// Fixes the trailing backslash. This function replaces the trailing double backslashes with /// only one backslash. It also, removes the single trailing backslash. /// /// The input string. /// The result string after being processed. public static string FixTrailingBackslash(string value) { if (value == null) { throw new ArgumentNullException("value"); } if (value.Length == 0) { return value; } if (value.EndsWith(@"\\")) { return value.Remove(value.Length - 2, 2) + @"\"; } else if (value.EndsWith(@"\")) { return value.Remove(value.Length - 1, 1); } else { return value; } } /// /// Removes all the trailing backslashes from the input. /// /// The input string. /// The result string without trailing backslashes. public static string CleanTrailingBackslash(string value) { if (value == null) { throw new ArgumentNullException("value"); } return value.TrimEnd('\\'); } /// /// Quotes an argument value and processes backslashes using a given /// . /// /// The argument value to quote. /// The to use. /// /// The quoted argument value. /// public static string QuoteArgumentValue(string value, BackslashProcessingMethod processingMethod) { // duplicate trailing backslashes (even if value is quoted) string quotedValue = ArgumentUtils.ProcessTrailingBackslash(value, processingMethod); // determine if value is already quoted bool isQuoted = value.StartsWith("\"") && value.EndsWith("\""); if (!isQuoted) { quotedValue = "\"" + quotedValue + "\""; } return quotedValue; } } } nant-0.92-rc1/src/NAnt.VisualCpp/Tasks/0000755000175000017500000000000011757310030017437 5ustar jtaylorjtaylornant-0.92-rc1/src/NAnt.VisualCpp/Tasks/RcTask.cs0000644000175000017500000002506111757302274021174 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Shawn Van Ness (nantluver@arithex.com) // Gerry Shaw (gerry_shaw@yahoo.com) // Ian MacLean ( ian@maclean.ms ) // Eric V. Smith (ericsmith@windsor.com) // Hani Atassi (haniatassi@users.sourceforge.net) // TODO: review interface for future compatibility/customizations issues using System; using System.Globalization; using System.IO; using System.Text; using System.Text.RegularExpressions; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Tasks; using NAnt.Core.Types; using NAnt.VisualCpp.Util; namespace NAnt.VisualCpp.Tasks { /// /// Compiles resources using rc.exe, Microsoft's Win32 resource /// compiler. /// /// /// /// Compile text.rc to text.res using the default options. /// /// /// /// ]]> /// /// /// /// /// Compile text.rc, passing an additional option. /// /// /// /// ]]> /// /// [TaskName("rc")] public class RcTask : ExternalProgramBase { #region Private Instance Fields private FileInfo _outputFile; private string _options; private int _langId = 0; private FileInfo _rcFile; private FileSet _includeDirs = new FileSet(); private OptionCollection _defines = new OptionCollection(); #endregion Private Instance Fields #region Public Instance Properties /// /// Options to pass to the compiler. /// [TaskAttribute("options")] public string Options { get { return _options; } set { _options = value; } } /// /// Output file. /// [TaskAttribute("output")] public FileInfo OutputFile { get { if (_outputFile == null) { _outputFile = new FileInfo(Path.ChangeExtension(RcFile.FullName, "RES")); } return _outputFile; } set { _outputFile = value; } } /// /// The resource file to compile. /// [TaskAttribute("rcfile", Required=true)] public FileInfo RcFile { get { return _rcFile; } set { _rcFile = value; } } /// /// Default language ID. /// [TaskAttribute("langid", Required=false)] public int LangId { get { return _langId; } set { _langId = value; } } /// /// The list of directories in which to search for include files. /// [BuildElement("includedirs")] public FileSet IncludeDirs { get { return _includeDirs; } set { _includeDirs = value; } } /// /// Macro definitions to pass to rc.exe. /// Each entry will generate a /d /// [BuildElementCollection("defines", "define")] public OptionCollection Defines { get { return _defines; } } #endregion Public Instance Properties #region Override implementation of ExternalProgramBase /// /// Filename of program to execute /// public override string ProgramFileName { get { return Name; } } /// /// Arguments of program to execute /// public override string ProgramArguments { get { StringBuilder str = new StringBuilder(); if (Verbose) { str.Append("/v "); } str.AppendFormat(CultureInfo.InvariantCulture, "/fo\"{0}\" ", OutputFile.FullName); if (Options != null) { str.AppendFormat(CultureInfo.InvariantCulture, "{0} ", Options); } if (LangId != 0) { str.AppendFormat("/l 0x{0:X} ", LangId); } // append user provided include directories foreach (string include in IncludeDirs.DirectoryNames) { str.AppendFormat("/i {0} ", ArgumentUtils.QuoteArgumentValue( include, BackslashProcessingMethod.Duplicate)); } // append user definitions foreach (Option define in Defines) { if (!define.IfDefined || define.UnlessDefined) { continue; } if (define.Value == null) { str.AppendFormat("/d {0} ", ArgumentUtils.DuplicateTrailingBackslash(define.OptionName)); } else { str.AppendFormat("/d {0}={1} ", define.OptionName, ArgumentUtils.DuplicateTrailingBackslash(define.Value)); } } str.AppendFormat(CultureInfo.InvariantCulture, "\"{0}\" ", RcFile.FullName); return str.ToString(); } } /// /// Compile the resource file /// protected override void ExecuteTask() { if (IncludeDirs.BaseDirectory == null) { IncludeDirs.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } if (NeedsCompiling()) { Log(Level.Info, "Compiling \"{0}\" to \"{1}\".", RcFile.FullName, OutputFile.FullName); base.ExecuteTask(); } } #endregion Override implementation of ExternalProgramBase #region Protected Instance Methods /// /// Determines if the resource need compiling. /// protected virtual bool NeedsCompiling() { if (!OutputFile.Exists) { Log(Level.Verbose, "'{0}' does not exist, recompiling.", OutputFile.FullName); return true; } // if output file file is older the resource file, it is stale string fileName = FileSet.FindMoreRecentLastWriteTime( RcFile.FullName, OutputFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, "'{0}' is out of date, recompiling.", fileName); return true; } // if resource file does not exist, then let compiler handle error if (!RcFile.Exists) { return true; } // check whether external files have been updated Regex regBitmap = new Regex("IDB_(?\\w+)\\s+BITMAP\\s+\\\"(?[^\\\"]+)\\\"", RegexOptions.Singleline | RegexOptions.IgnoreCase); Regex regIcon = new Regex("IDI_(?\\w+)\\s+ICON\\s+\\\"(?[^\\\"]+)\\\"", RegexOptions.Singleline | RegexOptions.IgnoreCase); Regex regBinary = new Regex("IDR_(?\\w+)\\s+(?\\w+)\\s+\\\"(?[^\\\"]+)\\\"", RegexOptions.Singleline | RegexOptions.IgnoreCase); using (StreamReader sr = new StreamReader(RcFile.FullName)) { while (sr.Peek() != -1) { string line = sr.ReadLine(); Match resourceMatch = regBitmap.Match(line); if (resourceMatch.Success) { return CheckResourceTimeStamp(resourceMatch.Groups["file"].Value); } resourceMatch = regIcon.Match(line); if (resourceMatch.Success) { return CheckResourceTimeStamp(resourceMatch.Groups["file"].Value); } resourceMatch = regBinary.Match(line); if (resourceMatch.Success) { return CheckResourceTimeStamp(resourceMatch.Groups["file"].Value); } } } // output file is up-to-date return false; } /// /// Check if a resource file has been updated. /// /// /// private bool CheckResourceTimeStamp(string filePath ) { string fileName; string externalFile = Path.Combine(RcFile.DirectoryName, filePath); fileName = FileSet.FindMoreRecentLastWriteTime( externalFile, OutputFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, "'{0}' has been updated, recompiling.", fileName); return true; } return false; } #endregion Protected Instance Methods } } #if unused Microsoft (R) Windows (R) Resource Compiler, Version 5.1.2264.1 - Build 2264 Copyright (C) Microsoft Corp. 1985-1998. All rights reserved. Usage: rc [options] .RC input file Switches: /r Emit .RES file (optional) /v Verbose (print progress messages) /d Define a symbol /u Undefine a symbol /fo Rename .RES file /l Default language ID in hex /i Add a path for INCLUDE searches /x Ignore INCLUDE environment variable /c Define a code page used by NLS conversion /w Warn on Invalid codepage in .rc (default is an error) /y Don't warn if there are duplicate control ID's /n Append null's to all strings in the string tables. Flags may be either upper or lower case #endif nant-0.92-rc1/src/NAnt.VisualCpp/Tasks/LibTask.cs0000644000175000017500000002365611757302274021346 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Shawn Van Ness (nantluver@arithex.com) // Gerry Shaw (gerry_shaw@yahoo.com) // Ian MacLean (ian@maclean.ms) // Eric V. Smith (ericsmith@windsor.com) // // TODO: review interface for future compatibility/customizations issues using System; using System.IO; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Tasks; using NAnt.Core.Types; using NAnt.VisualCpp.Types; using NAnt.VisualCpp.Util; namespace NAnt.VisualCpp.Tasks { /// /// Run lib.exe, Microsoft's Library Manager. /// /// /// Create a library. /// /// /// /// /// /// /// ]]> /// /// [TaskName("lib")] public class LibTask : ExternalProgramBase { #region Private Instance Fields private string _responseFileName; private FileInfo _outputFile; private FileInfo _moduleDefinitionFile; private FileSet _sources = new FileSet(); private SymbolCollection _symbols = new SymbolCollection(); private LibraryCollection _ignoreLibraries = new LibraryCollection(); private FileSet _libdirs = new FileSet(); private string _options; #endregion Private Instance Fields #region Public Instance Properties /// /// Options to pass to the compiler. /// [TaskAttribute("options")] public string Options { get { return _options; } set { _options = value; } } /// /// The output file. /// [TaskAttribute("output", Required=true)] public FileInfo OutputFile { get { return _outputFile; } set { _outputFile = value; } } /// /// The module definition file. /// [TaskAttribute("moduledefinition")] public FileInfo ModuleDefinitionFile { get { return _moduleDefinitionFile; } set { _moduleDefinitionFile = value; } } /// /// The list of files to combine into the output file. /// [BuildElement("sources")] public FileSet Sources { get { return _sources; } set { _sources = value; } } /// /// Symbols to add to the symbol table. /// [BuildElementCollection("symbols", "symbol")] public SymbolCollection Symbols { get { return _symbols; } set { _symbols = value; } } /// /// Names of default libraries to ignore. /// [BuildElementCollection("ignorelibraries", "library")] public LibraryCollection IgnoreLibraries { get { return _ignoreLibraries; } set { _ignoreLibraries = value; } } /// /// The list of additional library directories to search. /// [BuildElement("libdirs")] public FileSet LibDirs { get { return _libdirs; } set { _libdirs = value; } } #endregion Public Instance Properties #region Override implementation of ExternalProgramBase /// /// Gets the filename of the external program to start. /// /// The filename of the external program. public override string ProgramFileName { get { return Name; } } /// /// Gets the command-line arguments for the external program. /// /// /// The command-line arguments for the external program. /// public override string ProgramArguments { get { return "@" + "\"" + _responseFileName + "\""; } } #endregion Override implementation of ExternalProgramBase #region Override implementation of Task /// /// Creates the library. /// protected override void ExecuteTask() { // ensure base directory is set, even if fileset was not initialized // from XML if (Sources.BaseDirectory == null) { Sources.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } if (LibDirs.BaseDirectory == null) { LibDirs.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } if (!NeedsCompiling()) { return; } Log(Level.Info, "Combining {0} files to '{1}'.", Sources.FileNames.Count, OutputFile.FullName); // Create temp response file to hold compiler options _responseFileName = Path.GetTempFileName(); StreamWriter writer = new StreamWriter(_responseFileName); try { // specify the output file writer.WriteLine("/OUT:\"{0}\"", OutputFile.FullName); // write user provided options if (Options != null) { writer.WriteLine(Options); } // write each of the filenames foreach (string filename in Sources.FileNames) { writer.WriteLine(ArgumentUtils.QuoteArgumentValue(filename, BackslashProcessingMethod.None)); } // write symbols foreach (Symbol symbol in Symbols) { if (symbol.IfDefined && !symbol.UnlessDefined) { writer.WriteLine("/INCLUDE:{0}", ArgumentUtils.QuoteArgumentValue( symbol.SymbolName, BackslashProcessingMethod.Duplicate)); } } // names of default libraries to ignore foreach (Library ignoreLibrary in IgnoreLibraries) { if (ignoreLibrary.IfDefined && !ignoreLibrary.UnlessDefined) { writer.WriteLine("/NODEFAULTLIB:{0}", ArgumentUtils.QuoteArgumentValue( ignoreLibrary.LibraryName, BackslashProcessingMethod.Duplicate)); } } // write each of the libdirs foreach (string libdir in LibDirs.DirectoryNames) { writer.WriteLine("/LIBPATH:{0}", ArgumentUtils.QuoteArgumentValue( libdir, BackslashProcessingMethod.None)); } if (ModuleDefinitionFile != null) { writer.WriteLine("/DEF:\"{0}\"", ModuleDefinitionFile.FullName); } // suppresses display of the sign-on banner writer.WriteLine("/nologo"); writer.Close(); if (Verbose) { // display response file contents Log(Level.Info, "Contents of {0}.", _responseFileName); StreamReader reader = File.OpenText(_responseFileName); Log(Level.Info, reader.ReadToEnd()); reader.Close(); } // call base class to do the actual work base.ExecuteTask(); } finally { // make sure we delete response file even if an exception is thrown writer.Close(); // make sure stream is closed or file cannot be deleted File.Delete(_responseFileName); _responseFileName = null; } } #endregion Override implementation of Task #region Protected Instance Methods /// /// Determines if the sources need to be linked. /// protected virtual bool NeedsCompiling() { // check if output file exists - if not, rebuild if (!OutputFile.Exists) { Log(Level.Verbose, "Output file '{0}' does not exist, rebuilding library.", OutputFile.FullName); return true; } // check if .OBJ files were updated string fileName = FileSet.FindMoreRecentLastWriteTime( Sources.FileNames, OutputFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, "'{0}' has been updated, relinking.", fileName); return true; } return false; } #endregion Protected Instance Methods } } #if unused Microsoft (R) Library Manager Version 7.00.9466 Copyright (C) Microsoft Corporation. All rights reserved. usage: LIB [options] [files] options: /DEF[:filename] /EXPORT:symbol /EXTRACT:membername /INCLUDE:symbol /LIBPATH:dir /LIST[:filename] /MACHINE:{AM33|ARM|IA64|M32R|MIPS|MIPS16|MIPSFPU|MIPSFPU16|MIPSR41XX| PPC|PPCFP|SH3|SH3DSP|SH4|SH5|THUMB|TRICORE|X86} /NAME:filename /NODEFAULTLIB[:library] /NOLOGO /OUT:filename /REMOVE:membername /SUBSYSTEM:{CONSOLE|EFI_APPLICATION|EFI_BOOT_SERVICE_DRIVER| EFI_ROM|EFI_RUNTIME_DRIVER|NATIVE|POSIX|WINDOWS| WINDOWSCE}[,#[.##]] /VERBOSE #endif nant-0.92-rc1/src/NAnt.VisualCpp/Tasks/McTask.cs0000644000175000017500000002056511757302274021173 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Kevin Connors (connors@karmet.com) // Ian MacLean (ian_maclean@another.com) using System.Globalization; using System.IO; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Tasks; using NAnt.Core.Util; namespace NAnt.VisualCpp.Tasks { /// /// Compiles messages using mc.exe, Microsoft's Win32 message compiler. /// /// /// /// Compile text.mc using the default options. /// /// /// /// ]]> /// /// /// Compile text.mc, passing a path to store the header, the rc /// file and some additonal options. /// /// /// /// ]]> /// /// [TaskName("mc")] public class McTask : ExternalProgramBase { #region Private Instance Fields private DirectoryInfo _headerPath; private DirectoryInfo _rcPath; private string _options; private FileInfo _mcFile; #endregion Private Instance Fields #region Public Instance Properties /// /// Options to pass to the compiler. /// [TaskAttribute("options")] public string Options { get { return _options; } set { _options = value; } } /// /// Path to store header file. The default is the project base directory. /// [TaskAttribute("headerpath")] public DirectoryInfo HeaderPath { get { if (_headerPath == null) { return new DirectoryInfo(Project.BaseDirectory); } return _headerPath; } set { _headerPath = value; } } /// /// Path to store RC file. The default is the project base directory. /// [TaskAttribute("rcpath")] public DirectoryInfo RCPath { get { if (_rcPath == null) { return new DirectoryInfo(Project.BaseDirectory); } return _rcPath; } set { _rcPath = value; } } /// /// Input filename. /// [TaskAttribute("mcfile", Required=true)] public FileInfo McFile { get { return _mcFile; } set { _mcFile = value; } } #endregion Public Instance Properties #region Override implementation of ExternalProgramBase /// /// Gets the filename of the external program to start. /// /// /// The filename of the external program. /// public override string ProgramFileName { get { return Name; } } /// /// Gets the command-line arguments for the external program. /// /// /// The command-line arguments for the external program. /// public override string ProgramArguments { get { string str = ""; if (Verbose) { str += "/v "; } if (HeaderPath != null) { str += string.Format(CultureInfo.InvariantCulture, "-h \"{0}\" ", HeaderPath.FullName); } if (RCPath != null) { str += string.Format(CultureInfo.InvariantCulture, "-r \"{0}\" ", RCPath.FullName); } if (Options != null) { str += string.Format(CultureInfo.InvariantCulture, "{0} ", Options); } str += string.Format(CultureInfo.InvariantCulture, "\"{0}\" ", McFile.FullName); return str.ToString(); } } #endregion Override implementation of ExternalProgramBase #region Override implementation of Task /// /// Compiles the sources. /// protected override void ExecuteTask() { string header = Path.Combine(HeaderPath.FullName, Path.GetFileNameWithoutExtension(McFile.FullName)) + ".h"; string rc = Path.Combine(RCPath.FullName, Path.GetFileNameWithoutExtension(McFile.FullName)) + ".rc"; if (!NeedsCompiling(header) && !NeedsCompiling(rc)) { Log(Level.Info, "Target(s) up-to-date, not compiling '{0}'.", McFile.FullName); } else { Log(Level.Info, "Target out of date, compiling '{0}'.", McFile.FullName); if (HeaderPath != null) { Log(Level.Info, "Header file to '{0}'.", HeaderPath.FullName); } if (RCPath != null) { Log(Level.Info, "RC file to '{0}'.", RCPath.FullName); } Log(Level.Info, ""); base.ExecuteTask(); } } #endregion Override implementation of Task #region Private Instance Methods /// /// Determine if source files need re-building. /// private bool NeedsCompiling(string destinationFile) { if (McFile.Exists) { FileInfo dstInfo = new FileInfo(Project.GetFullPath(destinationFile)); if ((!dstInfo.Exists) || (McFile.LastWriteTime > dstInfo.LastWriteTime)) { return true; } else { return false; } } else { // if the source file doesn't exist, let the compiler throw the error Log(Level.Info, "Source file '{0}' doesn't exist!", McFile.FullName); return true; } } #endregion Private Instance Methods } } #if unused Microsoft (R) Message Compiler Version 1.00.5239 Copyright (c) Microsoft Corp 1992-1995. All rights reserved. usage: MC [-?vcdwso] [-m maxmsglen] [-h dirspec] [-e extension] [-r dirspec] [-x dbgFileSpec] [-u] [-U] filename.mc -? - displays this message -v - gives verbose output. -c - sets the Customer bit in all the message Ids. -d - FACILTY and SEVERITY values in header file in decimal. Sets message values in header to decimal initially. -w - warns if message text contains non-OS/2 compatible inserts. -s - insert symbolic name as first line of each message. -o - generate OLE2 header file (use HRESULT definition instead of status code definition) -m maxmsglen - generate a warning if the size of any message exceeds maxmsglen characters. -h pathspec - gives the path of where to create the C include file Default is .\ -e extension - Specify the extension for the header file. From 1 - 3 chars. -r pathspec - gives the path of where to create the RC include file and the binary message resource files it includes. Default is .\ -x pathspec - gives the path of where to create the .dbg C include file that maps message Ids to their symbolic name. -u - input file is Unicode. -U - messages in .BIN file should be Unicode. filename.mc - gives the names of a message text file to compile. Generated files have the Archive bit cleared. #endif nant-0.92-rc1/src/NAnt.VisualCpp/Tasks/ClTask.cs0000644000175000017500000010746311757302274021175 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2002 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Shawn Van Ness (nantluver@arithex.com) // Gerry Shaw (gerry_shaw@yahoo.com) // Ian MacLean (ian@maclean.ms) // Eric V. Smith (ericsmith@windsor.com) // Anthony LoveFrancisco (ants@fu.org) // Hani Atassi (haniatassi@users.sourceforge.net) // // TODO: review interface for future compatibility/customizations issues using System; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Text.RegularExpressions; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Tasks; using NAnt.Core.Types; using NAnt.Core.Util; using NAnt.VisualCpp.Types; using NAnt.VisualCpp.Util; namespace NAnt.VisualCpp.Tasks { /// /// Compiles C/C++ programs using cl.exe, Microsoft's C/C++ compiler. /// /// /// This task is intended for version 13.00.9466 of cl.exe. /// /// /// Compiles helloworld.cpp for the Common Language Runtime. /// /// /// /// /// /// /// ]]> /// /// [TaskName("cl")] public class ClTask : ExternalProgramBase { #region Private Instance Fields private string _responseFileName; private DirectoryInfo _outputDir; private string _pchFile; private PrecompiledHeaderMode _precompileHeaderMode = PrecompiledHeaderMode.Use; private string _pchThroughFile; private FileSet _sources = new FileSet(); private FileSet _includeDirs = new FileSet(); private FileSet _metaDataIncludeDirs = new FileSet(); private FileSet _forcedUsingFiles = new FileSet(); private bool _managedExtensions; private CharacterSet _characterSet = CharacterSet.NotSet; private string _options; private OptionCollection _defines = new OptionCollection(); private OptionCollection _undefines = new OptionCollection(); private string _objectFile; private string _pdbFile; private Hashtable _resolvedIncludes; private Regex _includeRegex; private StringCollection _dirtySources = new StringCollection(); #endregion Private Instance Fields #region Public Instance Constructors /// /// Initializes a new instance of the class. /// public ClTask() { _resolvedIncludes = CollectionsUtil.CreateCaseInsensitiveHashtable(); _includeRegex = new Regex("^[\\s]*#include[\\s]*[\"<](?'includefile'[^\">]+)[\">][\\S\\s]*$"); } #endregion Public Instance Constructors #region Public Instance Properties /// /// Directory where all output files are placed. /// [TaskAttribute("outputdir", Required=true)] public DirectoryInfo OutputDir { get { return _outputDir; } set { _outputDir = value; } } /// /// Specifies the path and/or name of the generated precompiled header /// file - given either relative to or as an /// absolute path. /// [TaskAttribute("pchfile")] public string PchFile { get { return (_pchFile != null) ? Path.Combine(OutputDir.FullName, _pchFile) : null; } set { _pchFile = StringUtils.ConvertEmptyToNull(value); } } /// /// The path of the boundary file when generating/using the /// specified . If a precompiled header file is /// not specified then this attribute is ignored. /// [TaskAttribute("pchthroughfile")] public string PchThroughFile { get { return _pchThroughFile; } set { _pchThroughFile = StringUtils.ConvertEmptyToNull(value); } } /// /// The mode in which the specified (if any) is /// used. The default is . /// [TaskAttribute("pchmode")] public PrecompiledHeaderMode PchMode { get { return _precompileHeaderMode; } set { if (!Enum.IsDefined(typeof(PrecompiledHeaderMode), value)) { throw new ArgumentException(string.Format( CultureInfo.InvariantCulture, "An invalid type {0} was specified.", value)); } else { _precompileHeaderMode = value; } } } /// /// Specifies whether Managed Extensions for C++ should be enabled. /// The default is . /// [TaskAttribute("managedextensions")] [BooleanValidator()] public bool ManagedExtensions { get { return _managedExtensions; } set { _managedExtensions = value;} } /// /// Tells the compiler to use the specified character set. /// [TaskAttribute("characterset", Required=false)] public CharacterSet CharacterSet { get { return _characterSet; } set { if (!Enum.IsDefined(typeof(CharacterSet), value)) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "An invalid character set '{0}' was specified.", value)); } else { this._characterSet = value; } } } /// /// Options to pass to the compiler. /// [TaskAttribute("options")] public string Options { get { return _options; } set { _options = value; } } /// /// The list of files to compile. /// [BuildElement("sources")] public FileSet Sources { get { return _sources; } set { _sources = value; } } /// /// The list of directories in which to search for include files. /// [BuildElement("includedirs")] public FileSet IncludeDirs { get { return _includeDirs; } set { _includeDirs = value; } } /// /// Directories that the compiler will search to resolve file references /// passed to the #using directive. /// [BuildElement("metadataincludedirs")] public FileSet MetaDataIncludeDirs { get { return _metaDataIncludeDirs; } set { _metaDataIncludeDirs = value; } } /// /// Specifies metadata files to reference in this compilation as an /// alternative to passing a file name to #using in source code. /// [BuildElement("forcedusingfiles")] public FileSet ForcedUsingFiles { get { return _forcedUsingFiles; } set { _forcedUsingFiles = value; } } /// /// Macro definitions to pass to cl.exe. /// Each entry will generate a /D /// [BuildElementCollection("defines", "define")] public OptionCollection Defines { get { return _defines; } } /// /// Macro undefines (/U) to pass to cl.exe. /// [BuildElementCollection("undefines", "undefine")] public OptionCollection Undefines { get { return _undefines; } } /// /// A name to override the default object file name; can be either a file /// or directory name. The default is the output directory. /// [TaskAttribute("objectfile")] public string ObjectFile { get { return (_objectFile != null ? Path.Combine(OutputDir.FullName, _objectFile) : OutputDir.FullName + "/"); } set { _objectFile = StringUtils.ConvertEmptyToNull(value); } } /// /// A name for the compiler-generated PDB file; can be either a file or /// directory name. The default is the output directory. /// [TaskAttribute("pdbfile")] public string ProgramDatabaseFile { get { return (_pdbFile != null ? Path.Combine(OutputDir.FullName, _pdbFile) : OutputDir.FullName + "/"); } set { _pdbFile = StringUtils.ConvertEmptyToNull(value); } } #endregion Public Instance Properties #region Override implementation of ExternalProgramBase /// /// Gets the filename of the external program to start. /// /// The filename of the external program. public override string ProgramFileName {get {return Name;}} /// /// Gets the command-line arguments for the external program. /// /// /// The command-line arguments for the external program. /// public override string ProgramArguments { get { return "@" + "\"" + _responseFileName + "\""; } } #endregion Override implementation of ExternalProgramBase #region Override implementation of Task /// /// Compiles the sources. /// protected override void ExecuteTask() { // ensure base directory is set, even if fileset was not initialized // from XML if (Sources.BaseDirectory == null) { Sources.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } if (IncludeDirs.BaseDirectory == null) { IncludeDirs.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } if (MetaDataIncludeDirs.BaseDirectory == null) { MetaDataIncludeDirs.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } if (ForcedUsingFiles.BaseDirectory == null) { ForcedUsingFiles.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } if (NeedsCompiling()) { Log(Level.Info, "Compiling {0} files to '{1}'.", _dirtySources.Count, OutputDir.FullName); // create temp response file to hold compiler options _responseFileName = Path.GetTempFileName(); StreamWriter writer = new StreamWriter(_responseFileName); try { // write basic switches writer.WriteLine("/c"); // compile only if (Options != null) { // write user defined options writer.WriteLine(Options); } if (ManagedExtensions) { // enables Managed Extensions for C++ writer.WriteLine("/clr"); } // write preprocesser define(s) foreach (Option define in Defines) { if (!define.IfDefined || define.UnlessDefined) { continue; } if (define.Value == null) { writer.WriteLine("/D " + QuoteArgumentValue(define.OptionName)); } else { writer.WriteLine("/D " + QuoteArgumentValue(define.OptionName + "=" + ArgumentUtils.DuplicateTrailingBackslash(define.Value))); } } // write preprocesser undefine(s) foreach (Option undefine in Undefines) { if (!undefine.IfDefined || undefine.UnlessDefined) { continue; } writer.WriteLine("/U " + QuoteArgumentValue(undefine.OptionName)); } // write user provided include directories foreach (string include in IncludeDirs.DirectoryNames) { writer.WriteLine("/I {0}", QuoteArgumentValue(include)); } // write directories that the compiler will search to resolve // file references passed to the #using directive foreach (string metaDataIncludeDir in MetaDataIncludeDirs.DirectoryNames) { writer.WriteLine("/AI {0}", QuoteArgumentValue(metaDataIncludeDir)); } // writes metadata files to reference in this compilation // as an alternative to passing a file name to #using in // source code foreach (string forcedUsingFile in ForcedUsingFiles.FileNames) { writer.WriteLine("/FU {0}", QuoteArgumentValue(forcedUsingFile)); } // program database file writer.WriteLine("/Fd{0}", QuoteArgumentValue(ProgramDatabaseFile)); // the object file or output directory writer.WriteLine("/Fo{0}", QuoteArgumentValue(ObjectFile)); // specify pch file, if user specified one if (PchFile != null) { writer.WriteLine("/Fp{0}", QuoteArgumentValue(PchFile)); switch (PchMode) { case PrecompiledHeaderMode.Use: writer.Write("/Yu"); break; case PrecompiledHeaderMode.Create: writer.Write("/Yc"); break; case PrecompiledHeaderMode.AutoCreate: writer.Write("/YX"); break; } if (PchThroughFile != null) { writer.WriteLine("{0}", QuoteArgumentValue(PchThroughFile)); } } // write each of the filenames foreach (string filename in _dirtySources) { writer.WriteLine(QuoteArgumentValue(filename)); } // tell compiler which character set to use switch (CharacterSet) { case CharacterSet.Unicode: writer.WriteLine("/D \"_UNICODE\""); writer.WriteLine("/D \"UNICODE\""); break; case CharacterSet.MultiByte: writer.WriteLine("/D \"_MBCS\""); break; } writer.Close(); if (Verbose) { // display response file contents Log(Level.Info, "Contents of {0}.", _responseFileName); StreamReader reader = File.OpenText(_responseFileName); Log(Level.Info, reader.ReadToEnd()); reader.Close(); } // suppresses display of the sign-on banner // (this has no effect in response file) this.Arguments.Add(new Argument("/nologo")); // call base class to do the actual work base.ExecuteTask(); } finally { // make sure we delete response file even if an exception is thrown writer.Close(); // make sure stream is closed or file cannot be deleted File.Delete(_responseFileName); _responseFileName = null; } } } #endregion Override implementation of Task #region Protected Instance Methods /// /// Determines if the sources need to be compiled. /// protected virtual bool NeedsCompiling() { if (!IsPchfileUpToDate()) { // if pch file is not up-to-date, then mark all sources as dirty Log(Level.Verbose, "PCH out of date, recompiling all sources."); _dirtySources = StringUtils.Clone(Sources.FileNames); return true; } return !AreObjsUpToDate(); } #endregion Protected Instance Methods #region Private Instance Methods /// /// Determines whether the precompiled header file is up-to-date. /// /// /// if no precompiled header file was specified; /// otherwise, . /// /// /// In order to determine accurately whether the precompile header file /// is up-to-date, we'd need scan all the header files that are pulled /// in. As this is not implemented right now, its safer to always /// recompile. /// private bool IsPchfileUpToDate() { // TODO: also check for updated metadata includes (#using directives) // if no pch file, then then it is theoretically up to date if (PchFile == null) { return true; } // if pch file declared, but doesn't exist, it must be stale FileInfo pchFileInfo = new FileInfo(PchFile); if (!pchFileInfo.Exists) { Log(Level.Verbose, "'{0}' does not exist, recompiling.", pchFileInfo.FullName); return false; } // if an existing pch file is used, then pch file must never be // recompiled if (PchMode == PrecompiledHeaderMode.Use) { return true; } // check if sources fresher than pch file string fileName = FileSet.FindMoreRecentLastWriteTime(Sources.FileNames, pchFileInfo.LastWriteTime); if (fileName != null) { Log(Level.Verbose, "'{0}' is newer than pch file, recompiling.", fileName); return false; } // check if assembly references are fresher than pch file fileName = FileSet.FindMoreRecentLastWriteTime(ForcedUsingFiles.FileNames, pchFileInfo.LastWriteTime); if (fileName != null) { Log(Level.Verbose, "'{0}' is newer than pch file, recompiling.", fileName); return false; } // check if included headers in source are modified after pch was compiled foreach (string sourceFile in Sources.FileNames) { fileName = FindUpdatedInclude(sourceFile, pchFileInfo.LastWriteTime); if (fileName != null) { Log(Level.Verbose, "'{0}' has been updated, recompiling.", fileName); return false; } } return true; } private bool IsObjUpToDate(string srcFileName) { // TODO: also check for updated metadata includes (#using directives) FileInfo objFileInfo = new FileInfo(GetObjOutputFile(srcFileName, ObjectFile)); // if obj file doesn't exist, it must be stale if (!objFileInfo.Exists) { Log(Level.Verbose, "'{0}' does not exist, recompiling.", objFileInfo.FullName); return false; } // if obj file is older than the source file, it is stale string fileName = FileSet.FindMoreRecentLastWriteTime(srcFileName, objFileInfo.LastWriteTime); if (fileName != null) { Log(Level.Verbose, "'{0}' has been updated, recompiling.", fileName); return false; } // check if assembly references are fresher than pch file fileName = FileSet.FindMoreRecentLastWriteTime(ForcedUsingFiles.FileNames, objFileInfo.LastWriteTime); if (fileName != null) { Log(Level.Verbose, "'{0}' has been updated, recompiling.", fileName); return false; } // check if included headers in source are modified after obj was compiled fileName = FindUpdatedInclude(srcFileName, objFileInfo.LastWriteTime); if (fileName != null) { Log(Level.Verbose, "'{0}' has been updated, recompiling.", fileName); return false; } if (PchFile != null && PchMode == PrecompiledHeaderMode.Use) { // check if precompiled header is modified after obj was compiled fileName = FileSet.FindMoreRecentLastWriteTime(PchFile, objFileInfo.LastWriteTime); if (fileName != null) { Log(Level.Verbose, "'{0}' has been updated, recompiling.", fileName); return false; } } return true; } private bool AreObjsUpToDate() { foreach (string filename in Sources.FileNames) { // if the source file does not exist, then we'll consider it // not up-to-date if (!File.Exists(filename)) { Log(Level.Verbose, "'{0}' does not exist, recompiling.", filename); _dirtySources.Add(filename); continue; } if (!IsObjUpToDate(filename)) { _dirtySources.Add(filename); continue; } } // if there are no outdated files, then the OBJs are up to date return _dirtySources.Count == 0; } /// /// Determines whether any file that are includes in the specified /// source file has been updated after the obj was compiled. /// /// The source file to check. /// The last write time of the compiled obj. /// /// The full path to the include file that was modified after the obj /// was compiled, or if no include files were /// modified since the obj was compiled. /// /// /// /// To determine what includes are defined in a source file, conditional /// directives are not honored. /// /// /// If a given include cannot be resolved to an existing file, then /// it will be considered stable. /// /// private string FindUpdatedInclude(string srcFileName, DateTime objLastWriteTime) { // quick and dirty code to check whether includes have been modified // after the source was last modified // TODO: recursively check includes Log(Level.Debug, "Checking whether includes of \"{0}\" have been" + " updated.", srcFileName); // holds the line we're parsing string line; // locate include directives in source file using (StreamReader sr = new StreamReader(srcFileName, true)) { while ((line = sr.ReadLine()) != null) { Match match = _includeRegex.Match(line); if (match.Groups.Count != 2) { continue; } string includeFile = match.Groups["includefile"].Value; Log(Level.Debug, "Checking include \"{0}\"...", includeFile); string resolvedInclude = _resolvedIncludes[includeFile] as string; if (resolvedInclude == null) { foreach (string includeDir in IncludeDirs.DirectoryNames) { string foundIncludeFile = FileUtils.CombinePaths(includeDir, includeFile); if (File.Exists(foundIncludeFile)) { Log(Level.Debug, "Found include \"{0}\" in" + " includedirs.", includeFile); resolvedInclude = foundIncludeFile; break; } } // if we could not locate include in include dirs and // source dir, then try to locate include in INCLUDE // env var if (resolvedInclude == null) { PathScanner pathScanner = new PathScanner(); pathScanner.Add(includeFile); StringCollection includes = pathScanner.Scan("INCLUDE"); if (includes.Count > 0) { Log(Level.Debug, "Found include \"{0}\" in" + " INCLUDE.", includeFile); resolvedInclude = includes[0]; } } // if we could not locate include in include dirs // and INCLUDE env var then check for include in base // directory (which is used as working dir) if (resolvedInclude == null) { string foundIncludeFile = FileUtils.CombinePaths( BaseDirectory.FullName, includeFile); if (File.Exists(foundIncludeFile)) { Log(Level.Debug, "Found include \"{0}\" in" + " working directory.", includeFile); resolvedInclude = foundIncludeFile; } } if (resolvedInclude != null) { _resolvedIncludes.Add(includeFile, resolvedInclude); } } if (resolvedInclude != null) { if (File.GetLastWriteTime(resolvedInclude) > objLastWriteTime) { return resolvedInclude; } } else { // TODO: what do we do if the include cannot be located ? // // for now we'll consider the obj file to be up-to-date Log(Level.Debug, "Include \"{0}\" could not be located.", includeFile); } } } return null; } #endregion Private Instance Methods #region Public Static Methods /// /// Quotes an argument value and duplicates trailing backslahes. /// /// The argument value to quote. /// /// The quotes argument value. /// public static string QuoteArgumentValue(string value) { return ArgumentUtils.QuoteArgumentValue(value, BackslashProcessingMethod.Duplicate); } /// /// Determines the file name of the OBJ file for the specified source /// file. /// /// The source file for which the OBJ file should be determined. /// The path of the object file. /// /// The file name of the OBJ file for the specified source file. /// public static string GetObjOutputFile(string srcFile, string objectPath) { if (srcFile == null) { throw new ArgumentNullException("srcFile"); } if (objectPath == null) { throw new ArgumentNullException("objectPath"); } // check if objectPath is file if (!objectPath.EndsWith("/") && Path.GetFileName(objectPath).Length != 0) { // if object file has no extension then use .obj, otherwise // use objectPath as is if (Path.GetExtension(objectPath).Length == 0) { return Path.ChangeExtension(objectPath, ".obj"); } else { return objectPath; } } else { return FileUtils.CombinePaths(objectPath, Path.GetFileNameWithoutExtension(srcFile) + ".obj"); } } #endregion Public Static Methods /// /// Defines the supported modes for the use of precompiled header files. /// public enum PrecompiledHeaderMode : int { /// /// Create a precompiled header file. /// /// /// For further information on the use of this option /// see the Microsoft documentation on the C++ compiler flag /Yc. /// Create = 1, /// /// Automatically create a precompiled header file if necessary. /// /// /// For further information on the use of this option /// see the Microsoft documentation on the C++ compiler flag /YX. /// AutoCreate = 2, /// /// Use a (previously generated) precompiled header file. /// /// /// For further information on the use of this option /// see the Microsoft documentation on the C++ compiler flag /Yu. /// Use = 0 } } } #if unused Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 13.00.9466 for 80x86 Copyright (C) Microsoft Corporation 1984-2001. All rights reserved. C/C++ COMPILER OPTIONS -OPTIMIZATION- /O1 minimize space /Op[-] improve floating-pt consistency /O2 maximize speed /Os favor code space /Oa assume no aliasing /Ot favor code speed /Ob inline expansion (default n=0) /Ow assume cross-function aliasing /Od disable optimizations (default) /Ox maximum opts. (/Ogityb2 /Gs) /Og enable global optimization /Oy[-] enable frame pointer omission /Oi enable intrinsic functions -CODE GENERATION- /G3 optimize for 80386 /GH enable _pexit function call /G4 optimize for 80486 /GR[-] enable C++ RTTI /G5 optimize for Pentium /GX[-] enable C++ EH (same as /EHsc) /G6 optimize for PPro, P-II, P-III /EHs enable C++ EH (no SEH exceptions) /GB optimize for blended model (default) /EHa enable C++ EH (w/ SEH exceptions) /Gd __cdecl calling convention /EHc extern "C" defaults to nothrow /Gr __fastcall calling convention /GT generate fiber-safe TLS accesses /Gz __stdcall calling convention /Gm[-] enable minimal rebuild /GA optimize for Windows Application /GL[-] enable link-time code generation /Gf enable string pooling /QIfdiv[-] enable Pentium FDIV fix /GF enable read-only string pooling /QI0f[-] enable Pentium 0x0f fix /Gy separate functions for linker /QIfist[-] use FIST instead of ftol() /GZ Enable stack checks (/RTCs) /RTC1 Enable fast checks (/RTCsu) /Ge force stack checking for all funcs /RTCc Convert to smaller type checks /Gs[num] control stack checking calls /RTCs Stack Frame runtime checking /GS enable security checks /RTCu Uninitialized local usage checks /Gh enable _penter function call /clr[:noAssembly] compile for the common language runtime noAssembly - do not produce an assembly -OUTPUT FILES- /Fa[file] name assembly listing file /Fo name object file /FA[sc] configure assembly listing /Fp name precompiled header file /Fd[file] name .PDB file /Fr[file] name source browser file /Fe name executable file /FR[file] name extended .SBR file /Fm[file] name map file -PREPROCESSOR- /AI add to assembly search path /Fx merge injected code to file /FU forced using assembly/module /FI name forced include file /C don't strip comments /U remove predefined macro /D{=|#} define macro /u remove all predefined macros /E preprocess to stdout /I add to include search path /EP preprocess to stdout, no #line /X ignore "standard places" /P preprocess to file -LANGUAGE- /Zi enable debugging information /Zl omit default library name in .OBJ /ZI enable Edit and Continue debug info /Zg generate function prototypes /Z7 enable old-style debug info /Zs syntax check only /Zd line number debugging info only /vd{0|1} disable/enable vtordisp /Zp[n] pack structs on n-byte boundary /vm type of pointers to members /Za disable extensions (implies /Op) /noBool disable "bool" keyword /Ze enable extensions (default) /Zc:arg1[,arg2] C++ language conformance, where arguments can be: forScope - enforce Standard C++ for scoping rules wchar_t - wchar_t is the native type, not a typedef -MISCELLANEOUS- @ options response file /wo issue warning n once /?, /help print this help message /w set warning level 1-4 for n /c compile only, no link /W set warning level (default n=1) /H max external name length /Wall enable all warnings /J default char type is unsigned /Wp64 enable 64 bit porting warnings /nologo suppress copyright message /WX treat warnings as errors /showIncludes show include file names /WL enable one line diagnostics /Tc compile file as .c /Yc[file] create .PCH file /Tp compile file as .cpp /Yd put debug info in every .OBJ /TC compile all files as .c /Yl[sym] inject .PCH ref for debug lib /TP compile all files as .cpp /Yu[file] use .PCH file /V set version string /YX[file] automatic .PCH /w disable all warnings /Y- disable all PCH options /wd disable warning n /Zm max memory alloc (% of default) /we treat warning n as an error -LINKING- /MD link with MSVCRT.LIB /MDd link with MSVCRTD.LIB debug lib /ML link with LIBC.LIB /MLd link with LIBCD.LIB debug lib /MT link with LIBCMT.LIB /MTd link with LIBCMTD.LIB debug lib /LD Create .DLL /F set stack size /LDd Create .DLL debug library /link [linker options and libraries] #endif nant-0.92-rc1/src/NAnt.VisualCpp/Tasks/MidlTask.cs0000644000175000017500000003764211757302274021525 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // original author unknown // Ian MacLean (ian_maclean@another.com) // Hani Atassi (haniatassi@users.sourceforge.net) using System; using System.IO; using System.Text; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Tasks; using NAnt.Core.Types; using NAnt.VisualCpp.Util; namespace NAnt.VisualCpp.Tasks { /// /// This tasks allows you to run MIDL.exe. /// /// /// /// This task only supports a small subset of the MIDL.EXE command line /// switches, but you can use the options element to specify any other /// unsupported commands you want to specify. /// /// /// /// /// /// /// /// /// /// /// /// /// ]]> /// /// [TaskName("midl")] public class MidlTask : ExternalProgramBase { #region Private Instance Fields private string _responseFileName; private string _acf; private string _align; private bool _appConfig; private string _char; private string _client; private string _cstub; // TODO: /D!!!!! private FileInfo _dlldata; private string _env = "win32"; // TODO: /error private string _Oi; private FileInfo _header; private FileInfo _iid; private FileInfo _proxy; private FileInfo _tlb; private FileInfo _filename; private OptionCollection _options = new OptionCollection(); private OptionCollection _defines = new OptionCollection(); private OptionCollection _undefines = new OptionCollection(); private FileSet _includeDirs = new FileSet(); #endregion Private Instance Fields #region Private Static Fields private const string PROG_FILE_NAME = "midl.exe"; #endregion Private Static Fields #region Public Instance Properties /// /// The /acf switch allows the user to supply an /// explicit ACF file name. The switch also /// allows the use of different interface names in /// the IDL and ACF files. /// [TaskAttribute("acf")] public string Acf { get { return _acf; } set { _acf = value; } } /// /// The /align switch is functionally the same as the /// MIDL /Zp option and is recognized by the MIDL compiler /// solely for backward compatibility with MkTypLib. /// /// The alignment value can be 1, 2, 4, or 8. [TaskAttribute("align")] public string Align { get { return _align; } set { _align = value; } } /// /// The /app_config switch selects application-configuration /// mode, which allows you to use some ACF keywords in the /// IDL file. With this MIDL compiler switch, you can omit /// the ACF and specify an interface in a single IDL file. /// [TaskAttribute("app_config"), BooleanValidator()] public bool AppConfig { get { return _appConfig; } set { _appConfig = value; } } /// /// The /char switch helps to ensure that the MIDL compiler /// and C compiler operate together correctly for all char /// and small types. /// /// Can be one of signed | unsigned | ascii7 [TaskAttribute("char")] public string Char { get { return _char; } set { _char = value; } } /// /// The /client switch directs the MIDL compiler to generate /// client-side C source files for an RPC interface /// /// can be one of stub | none [TaskAttribute("client")] public string Client { get { return _client; } set { _client = value; } } /// /// The /cstub switch specifies the name of the client /// stub file for an RPC interface. /// [TaskAttribute("cstub")] public string CStub { get { return _cstub; } set { _cstub = value; } } /// /// Specifies the file name for the generated dlldata file for a proxy /// DLL. The default file name Dlldata.c is used if /// is not specified. /// [TaskAttribute("dlldata")] public FileInfo DllData { get { return _dlldata; } set { _dlldata = value; } } /// /// The /env switch selects the /// environment in which the application runs. /// /// It can take the values win32 and win64 [TaskAttribute("env")] public string Env { get { return _env; } set { _env = value; } } /// /// The /Oi switch directs the MIDL compiler to /// use a fully-interpreted marshaling method. /// The /Oic and /Oicf switches provide additional /// performance enhancements. /// /// /// If you specify the Oi attribute, you must set it to /// one of the values: /// - Oi="" /// - Oi="c" /// - Oi="f" /// - Oi="cf" /// [TaskAttribute("Oi")] public string Oi { get { return _Oi; } set { _Oi = value; } } /// /// Specifies a file name for the type library generated by the MIDL /// compiler. /// [TaskAttribute("tlb")] public FileInfo Tlb { get { return _tlb; } set { _tlb = value; } } /// /// Specifies the name of the header file. /// [TaskAttribute("header")] public FileInfo Header { get { return _header; } set { _header = value; } } /// /// Specifies the name of the interface identifier file for a COM /// interface, overriding the default name obtained by adding _i.c /// to the IDL file name. /// [TaskAttribute("iid")] public FileInfo Iid { get { return _iid; } set { _iid = value; } } /// /// Specifies the name of the interface proxy file for a COM interface. /// [TaskAttribute("proxy")] public FileInfo Proxy { get { return _proxy; } set { _proxy = value; } } /// /// Name of .IDL file to process. /// [TaskAttribute("filename", Required=true)] public FileInfo Filename { get { return _filename; } set { _filename = value; } } /// /// Additional options to pass to midl.exe. /// [BuildElementCollection("options", "option")] public OptionCollection Options { get { return _options; } } /// /// Macro definitions to pass to mdil.exe. /// Each entry will generate a /D /// [BuildElementCollection("defines", "define")] public OptionCollection Defines { get { return _defines; } } /// /// Macro undefines (/U) to pass to mdil. /// [BuildElementCollection("undefines", "undefine")] public OptionCollection Undefines { get { return _undefines; } } /// /// The list of directories in which to search for include files. /// [BuildElement("includedirs")] public FileSet IncludeDirs { get { return _includeDirs; } set { _includeDirs = value; } } #endregion Public Instance Properties #region Override implementation of ExternalProgramBase /// /// Filename of program to execute /// public override string ProgramFileName { get { return PROG_FILE_NAME; } } /// /// Gets the command-line arguments for the external program. /// /// /// The command-line arguments for the external program. /// public override string ProgramArguments { get { return "@" + "\"" + _responseFileName + "\""; } } /// /// This is where the work is done. /// protected override void ExecuteTask() { if (IncludeDirs.BaseDirectory == null) { IncludeDirs.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } if (NeedsCompiling()) { // create temp response file to hold compiler options _responseFileName = Path.GetTempFileName(); try { using (StreamWriter writer = new StreamWriter(_responseFileName)) { WriteResponseFile(writer); } if (Verbose) { // display response file contents Log(Level.Info, "Contents of " + _responseFileName); StreamReader reader = File.OpenText(_responseFileName); Log(Level.Info, reader.ReadToEnd()); reader.Close(); } base.ExecuteTask(); } finally { // make sure we delete the response file File.Delete(_responseFileName); _responseFileName = null; } } } #endregion Override implementation of ExternalProgramBase #region Private Instance Methods /// /// Check output files to see if we need rebuilding. /// /// if a rebuild is needed; otherwise, /// . private bool NeedsCompiling() { if (Tlb != null && NeedsCompiling(Tlb)) { return true; } else if (Header != null && NeedsCompiling(Header)) { return true; } else if (Iid != null && NeedsCompiling(Iid)) { return true; } // up-to-date check for proxy and dlldata should not be performed, // as, even though specified, the compiler might not output these // files (why ? no idea) return false; } /// /// Check output files to see if we need rebuilding. /// /// /// if a rebuild is needed; otherwise, /// . /// private bool NeedsCompiling(FileInfo outputFile) { if (!outputFile.Exists) { Log(Level.Verbose, "Output file '{0}' does not exist, recompiling.", outputFile.FullName); return true; } string fileName = FileSet.FindMoreRecentLastWriteTime(Filename.FullName, outputFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, "'{0}' is out of date, recompiling.", fileName); return true; } return false; } /// /// Writes the response file for midl.exe. /// private void WriteResponseFile(TextWriter writer) { // suppresses display of the sign-on banner writer.WriteLine("/nologo"); writer.WriteLine("/env " + _env); if (_acf != null) writer.WriteLine("/acf {0}", _acf); if (_align != null) writer.WriteLine("/align {0}", _align); if (_appConfig) writer.WriteLine("/app_config"); if (_char != null) writer.WriteLine("/char {0}", _char); if (_client != null) writer.WriteLine("/client {0}", _client); if (_cstub != null) writer.WriteLine("/cstub {0}", _cstub); if (_dlldata != null) { writer.WriteLine("/dlldata \"{0}\"", DllData.FullName); } if (_Oi != null) writer.WriteLine("/Oi" + _Oi); if (Tlb != null) writer.WriteLine("/tlb \"{0}\"", Tlb.FullName); if (_header != null) writer.WriteLine("/header \"{0}\"", Header.FullName); if (Iid != null) writer.WriteLine("/iid \"{0}\"", Iid.FullName); if (Proxy != null) writer.WriteLine("/proxy \"{0}\"", Proxy.FullName); foreach (Option define in Defines) { if (!define.IfDefined || define.UnlessDefined) { continue; } if (define.Value == null) { writer.WriteLine("/D " + ArgumentUtils.FixTrailingBackslash(define.OptionName)); } else { writer.WriteLine("/D " + define.OptionName + "=" + ArgumentUtils.FixTrailingBackslash(define.Value)); } } foreach (Option undefine in Undefines) { if (!undefine.IfDefined || undefine.UnlessDefined) { continue; } writer.WriteLine("/U " + ArgumentUtils.QuoteArgumentValue( undefine.OptionName, BackslashProcessingMethod.Fix)); } foreach (Option option in _options) { if (IfDefined && !UnlessDefined) { if (option.Value == null) { writer.WriteLine(option.OptionName); } else { writer.WriteLine(option.OptionName + " " + option.Value); } } } // append user provided include directories foreach (string include in IncludeDirs.DirectoryNames) { writer.WriteLine("/I {0}", ArgumentUtils.QuoteArgumentValue( include, BackslashProcessingMethod.Clean)); } writer.WriteLine("\"{0}\"", Filename.FullName); } #endregion Private Instance Methods } } nant-0.92-rc1/src/NAnt.VisualCpp/Tasks/LinkTask.cs0000644000175000017500000004050311757302274021523 0ustar jtaylorjtaylor// NAnt - A .NET build tool // Copyright (C) 2001-2003 Gerry Shaw // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Shawn Van Ness (nantluver@arithex.com) // Gerry Shaw (gerry_shaw@yahoo.com) // Ian MacLean (ian@maclean.ms) // Eric V. Smith (ericsmith@windsor.com) // // TODO: review interface for future compatibility/customizations issues using System; using System.IO; using NAnt.Core; using NAnt.Core.Attributes; using NAnt.Core.Tasks; using NAnt.Core.Types; using NAnt.Core.Util; using NAnt.VisualCpp.Types; using NAnt.VisualCpp.Util; namespace NAnt.VisualCpp.Tasks { /// /// Links files using link.exe, Microsoft's Incremental Linker. /// /// /// This task is intended for version 7.00.9466 of link.exe. /// /// /// /// Combine all object files in the current directory into helloworld.exe. /// /// /// /// /// /// /// /// ]]> /// /// [TaskName("link")] public class LinkTask : ExternalProgramBase { #region Private Instance Fields private string _responseFileName; private FileInfo _outputFile; private FileInfo _pdbFile; private FileInfo _moduleDefinition; private bool _debug; private FileSet _sources = new FileSet(); private FileSet _libdirs = new FileSet(); private FileSet _modules = new FileSet(); private FileSet _delayLoadedDlls = new FileSet(); private FileSet _embeddedResources = new FileSet(); private SymbolCollection _symbols = new SymbolCollection(); private LibraryCollection _ignoreLibraries = new LibraryCollection(); private string _options; #endregion Private Instance Fields #region Public Instance Properties /// /// Options to pass to the compiler. /// [TaskAttribute("options")] public string Options { get { return _options; } set { _options = value; } } /// /// Create debugging information for the .exe file or DLL. The default is /// . /// public bool Debug { get { return _debug; } set { _debug = value; } } /// /// The output file. /// [TaskAttribute("output", Required=true)] public FileInfo OutputFile { get { return _outputFile; } set { _outputFile = value; } } /// /// A user-specified name for the program database (PDB) that the linker /// creates. The default file name for the PDB has the base name of the /// and the extension .pdb. /// [TaskAttribute("pdbfile")] public FileInfo ProgramDatabaseFile { get { if (Debug && _pdbFile == null) { _pdbFile = new FileInfo(Path.ChangeExtension(OutputFile.FullName, ".pdb")); } return _pdbFile; } set { _pdbFile = value; } } /// /// The name of a module-definition file (.def) to be passed to the /// linker. /// [TaskAttribute("moduledefinition")] public FileInfo ModuleDefinition { get { return _moduleDefinition; } set { _moduleDefinition = value; } } /// /// Specified DLLs for delay loading. /// [BuildElement("delayloaded")] public FileSet DelayLoadedDlls { get { return _delayLoadedDlls; } set { _delayLoadedDlls = value; } } /// /// The list of files to combine into the output file. /// [BuildElement("sources")] public FileSet Sources { get { return _sources; } set { _sources = value; } } /// /// The list of additional library directories to search. /// [BuildElement("libdirs")] public FileSet LibDirs { get { return _libdirs; } set { _libdirs = value; } } /// /// Link the specified modules into this assembly. /// [BuildElement("modules")] public FileSet Modules { get { return _modules; } set { _modules = value; } } /// /// Embed the specified resources into this assembly. /// [BuildElement("embeddedresources")] public FileSet EmbeddedResources { get { return _embeddedResources; } set { _embeddedResources = value; } } /// /// Symbols to add to the symbol table. /// [BuildElementCollection("symbols", "symbol")] public SymbolCollection Symbols { get { return _symbols; } set { _symbols = value; } } /// /// Names of libraries that you want the linker to ignore when it /// resolves external references. /// [BuildElementCollection("ignorelibraries", "library")] public LibraryCollection IgnoreLibraries { get { return _ignoreLibraries; } set { _ignoreLibraries = value; } } #endregion Public Instance Properties #region Override implementation of ExternalProgramBase /// /// Gets the filename of the external program to start. /// /// The filename of the external program. public override string ProgramFileName { get { return Name; } } /// /// Gets the command-line arguments for the external program. /// /// /// The command-line arguments for the external program. /// public override string ProgramArguments { get { return "@" + "\"" + _responseFileName + "\""; } } #endregion Override implementation of ExternalProgramBase #region Override implementation of Task /// /// Links the sources. /// protected override void ExecuteTask() { // ensure base directory is set, even if fileset was not initialized // from XML if (Sources.BaseDirectory == null) { Sources.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } if (LibDirs.BaseDirectory == null) { LibDirs.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } if (Modules.BaseDirectory == null) { Modules.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } if (EmbeddedResources.BaseDirectory == null) { EmbeddedResources.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } if (NeedsLinking()) { Log(Level.Info, "Linking {0} files.", Sources.FileNames.Count); // create temp response file to hold compiler options _responseFileName = Path.GetTempFileName(); StreamWriter writer = new StreamWriter(_responseFileName); try { // specify the output file writer.WriteLine("/OUT:\"{0}\"", OutputFile.FullName); // write user provided options if (Options != null) { writer.WriteLine(Options); } // module definition file if (ModuleDefinition != null) { writer.WriteLine("/DEF:\"{0}\"", ModuleDefinition.FullName); } // write each of the libdirs foreach (string libdir in LibDirs.DirectoryNames) { writer.WriteLine("/LIBPATH:{0}", QuoteArgumentValue(libdir)); } // write each of the module references foreach (string module in Modules.FileNames) { writer.WriteLine("/ASSEMBLYMODULE:{0}", QuoteArgumentValue(module)); } // write delay loaded DLLs foreach (string dll in DelayLoadedDlls.FileNames) { writer.WriteLine("/DELAYLOAD:{0}", QuoteArgumentValue(dll)); } // write each of the embedded resources foreach (string resource in EmbeddedResources.FileNames) { writer.WriteLine("/ASSEMBLYRESOURCE:{0}", QuoteArgumentValue(resource)); } // write symbols foreach (Symbol symbol in Symbols) { if (symbol.IfDefined && !symbol.UnlessDefined) { writer.WriteLine("/INCLUDE:{0}", QuoteArgumentValue( symbol.SymbolName)); } } // names of default libraries to ignore foreach (Library ignoreLibrary in IgnoreLibraries) { if (ignoreLibrary.IfDefined && !ignoreLibrary.UnlessDefined) { writer.WriteLine("/NODEFAULTLIB:{0}", QuoteArgumentValue( ignoreLibrary.LibraryName)); } } if (Debug) { writer.WriteLine("/DEBUG"); } // write program database file if (ProgramDatabaseFile != null) { writer.WriteLine("/PDB:{0}", QuoteArgumentValue( ProgramDatabaseFile.FullName)); } // suppresses display of the sign-on banner writer.WriteLine("/nologo"); // write each of the filenames foreach (string filename in Sources.FileNames) { writer.WriteLine(QuoteArgumentValue(filename)); } writer.Close(); if (Verbose) { // display response file contents Log(Level.Info, "Contents of {0}.", _responseFileName); StreamReader reader = File.OpenText(_responseFileName); Log(Level.Info, reader.ReadToEnd()); reader.Close(); } // call base class to do the actual work base.ExecuteTask(); } finally { // make sure we delete response file even if an exception is thrown writer.Close(); // make sure stream is closed or file cannot be deleted File.Delete(_responseFileName); _responseFileName = null; } } } #endregion Override implementation of Task #region Protected Instance Methods /// /// Determines if the output needs linking. /// protected virtual bool NeedsLinking() { string fileName; // return true as soon as we know we need to compile if (ProgramDatabaseFile != null) { if (!ProgramDatabaseFile.Exists) { Log(Level.Verbose, "PDB file '{0}' does not exist, relinking.", ProgramDatabaseFile.FullName); return true; } // check if sources were updated fileName = FileSet.FindMoreRecentLastWriteTime(Sources.FileNames, ProgramDatabaseFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, "'{0}' has been updated, relinking.", fileName); return true; } } if (!OutputFile.Exists) { Log(Level.Verbose, "Output file '{0}' does not exist, relinking.", OutputFile.FullName); return true; } // check if sources were updated fileName = FileSet.FindMoreRecentLastWriteTime(Sources.FileNames, OutputFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, "'{0}' has been updated, relinking.", fileName); return true; } if (ModuleDefinition != null) { fileName = FileSet.FindMoreRecentLastWriteTime(ModuleDefinition.FullName, OutputFile.LastWriteTime); if (fileName != null) { Log(Level.Verbose, ResourceUtils.GetString("String_FileHasBeenUpdated"), fileName); return true; } } return false; } #endregion Protected Instance Methods #region Public Static Methods /// /// Quotes an argument value and duplicates trailing backslahes. /// /// The argument value to quote. /// /// The quotes argument value. /// public static string QuoteArgumentValue(string value) { return ArgumentUtils.QuoteArgumentValue(value, BackslashProcessingMethod.Duplicate); } #endregion Public Static Methods } } #if unused Microsoft (R) Incremental Linker Version 7.00.9466 Copyright (C) Microsoft Corporation. All rights reserved. usage: LINK [options] [files] [@commandfile] options: /ALIGN:# /ALLOWBIND[:NO] /ASSEMBLYMODULE:filename /ASSEMBLYRESOURCE:filename /BASE:{address|@filename,key} /DEBUG /DEF:filename /DEFAULTLIB:library /DELAY:{NOBIND|UNLOAD} /DELAYLOAD:dll /DLL /DRIVER[:{UPONLY|WDM}] /ENTRY:symbol /EXETYPE:DYNAMIC /EXPORT:symbol /FIXED[:NO] /FORCE[:{MULTIPLE|UNRESOLVED}] /HEAP:reserve[,commit] /IDLOUT:filename /IGNOREIDL /IMPLIB:filename /INCLUDE:symbol /INCREMENTAL[:NO] /LARGEADDRESSAWARE[:NO] /LIBPATH:dir /LTCG[:{NOSTATUS|PGINSTRUMENT|PGOPTIMIZE|STATUS}] (PGINSTRUMENT and PGOPTIMIZE are only available for IA64) /MACHINE:{AM33|ARM|IA64|M32R|MIPS|MIPS16|MIPSFPU|MIPSFPU16|MIPSR41XX| PPC|PPCFP|SH3|SH3DSP|SH4|SH5|THUMB|TRICORE|X86} /MAP[:filename] /MAPINFO:{EXPORTS|LINES} /MERGE:from=to /MIDL:@commandfile /NOASSEMBLY /NODEFAULTLIB[:library] /NOENTRY /NOLOGO /OPT:{ICF[=iterations]|NOICF|NOREF|NOWIN98|REF|WIN98} /ORDER:@filename /OUT:filename /PDB:filename /PDBSTRIPPED:filename /PGD:filename /RELEASE /SECTION:name,[E][R][W][S][D][K][L][P][X][,ALIGN=#] /STACK:reserve[,commit] /STUB:filename /SUBSYSTEM:{CONSOLE|EFI_APPLICATION|EFI_BOOT_SERVICE_DRIVER| EFI_ROM|EFI_RUNTIME_DRIVER|NATIVE|POSIX|WINDOWS| WINDOWSCE}[,#[.##]] /SWAPRUN:{CD|NET} /TLBOUT:filename /TSAWARE[:NO] /TLBID:# /VERBOSE[:LIB] /VERSION:#[.#] /VXD /WINDOWSCE:{CONVERT|EMULATION} /WS:AGGRESSIVE #endif nant-0.92-rc1/src/NAnt.VisualCpp/NAnt.VisualCpp.csproj0000644000175000017500000001070711757302274022361 0ustar jtaylorjtaylor Debug AnyCPU 2.0 {A154DB17-7263-44E3-838E-1E4C4946B7D8} NAnt.VisualCpp NAnt.VisualCppTasks Library OnSuccessfulBuild false 8.0.50727 v2.0 2.0 publish\ true Disk false Foreground 7 Days false false true 0 1.0.0.%2a false false true true full false 4 ..\..\build\Debug\ AllRules.ruleset TRACE;DEBUG ..\..\build\Debug\NAnt.VisualCppTasks.xml true pdbonly true ..\..\build\Release\ 4 AllRules.ruleset TRACE ..\..\build\Release\NAnt.VisualCppTasks.xml CommonAssemblyInfo.cs False .NET Framework 3.5 SP1 Client Profile false False .NET Framework 3.5 SP1 true False Windows Installer 3.1 true {8F5F8375-4097-4952-B860-784EB9961ABE} NAnt.Core nant-0.92-rc1/src/NAnt.VisualCpp/NAnt.VisualCpp.build0000644000175000017500000000225511757302274022157 0ustar jtaylorjtaylor