NAnt: How to get target name that was specified on command line

1.6k views Asked by At

From within my NAnt build script, I'm trying to find out the name of that target that was specified on the command line (or the default target if none was specified).

I've been reviewing the documentation at http://nant.sourceforge.net/release/0.85-rc1/help/functions/index.html#NAnt and can't seem to find anything. The only slightly related function I can find is target::get-current-target which returns the name of the target that I'm currently in, not the target that was specified on the command line.

Anyone know if there's a way to access this information? I couldn't find anything in NAntContrib either. Seems like it has to be there somewhere.

Thanks.

3

There are 3 answers

0
Babak Naffas On

One thing you could do is to define a property that will maintain the name for you. For each target you define, check to see if that property has a value set and set it to the current target's name if it's empty.

0
robertburke On

Here is a simple function to see if the target was specified on the command line. Just call myFunctions::isTargetOnCommandLine('foo') substituting the name of your target.

<script language="C#" prefix="myFunctions" >
  <code>
    <![CDATA[
      [Function("isTargetOnCommandLine")]
  public static bool isTargetOnCommandLine(string target) {
    return (Array.IndexOf(Environment.GetCommandLineArgs(), target) != -1);
  }
    ]]>
  </code>
</script>   
0
moudrick On

Just encountered similar task. I solved it this way, hope it helps a little.

<script language="C#"><code><![CDATA[
    public static void ScriptMain(Project project)
    {
        project.Properties["command-line-targets"] = string.Empty;
        StringBuilder sb = new StringBuilder();
        string[] args = Environment.GetCommandLineArgs();
        for (int i = 1; i < args.Length; ++i)
        {   string arg = args[i];
            if (! arg.StartsWith("-"))
            {
                project.Log(Level.Info, "  Command line target: " + arg);
                sb.Append(" ").Append(arg);
            }
        }
        if (sb.Length >= 1)
        {
            project.Properties["command-line-targets"] = sb.ToString(1, sb.Length - 1);
        }
    }
]]></code></script>
<echo message="Command line targets: ${command-line-targets}" />

This code won't show you the default target(s), however.