Search code examples
cakebuild

How do you pass empty arguments in Cake v1?


According to the upgrade document it is no longer possible to ./build.sh arg= as of v1.0. Indeed, that produces:

Error: Expected an option value.

However it also doesn't work with arg=''. I could leave it off and rely on the default value, but that's hard to do from my Azure DevOps pipelines, which read like - script: ./build.sh --arg='$(arg1)' where arg1 is a variable defined elsewhere.

The problem is that the variable arg1 in my DevOps pipeline is defined externally and may or may not be empty.

The best I can think of is passing in at least a space like ./build.sh --arg='$(arg) ' (note the space at the end) and always checking for string.IsNullOrWhiteSpace and always Trimming, but that seems very hacky.

Is there a cleaner solution to pass a possibly empty variable from the command line? If not how can I rewrite my Azure DevOps YML to not pass the argument if it is empty?


Solution

  • TL;DR; Use a (space) instead of = if the value can be empty/null.

    ./build.sh --arg '$(arg1)'
    

    Cake v1.0 supports using a space between the --argumentName and the value as an alternative for the = sign. For example:

    dotnet cake empty-args.cake --arg1 --arg2
    dotnet cake empty-args.cake --arg1 valueA --arg2
    dotnet cake empty-args.cake --arg1 --arg2 valueB
    dotnet cake empty-args.cake --arg1 valueA --arg2 valueB
    

    With a sample Cake script like the below, it will output the following:

    var arg1 = Argument<string>("arg1", null);
    var arg2 = Argument<string>("arg2", null);
    
    Information("arg1: {0}", arg1);
    Information("arg2: {0}", arg2);
    
    dotnet cake empty-args.cake --arg1 --arg2
    arg1: [NULL]
    arg2: [NULL]
    
    dotnet cake empty-args.cake --arg1 --arg2
    arg1: [NULL]
    arg2: [NULL]
    
    dotnet cake empty-args.cake --arg1 valueA --arg2
    arg1: valueA
    arg2: [NULL]
    
    dotnet cake empty-args.cake --arg1 --arg2 valueB
    arg1: [NULL]
    arg2: valueB
    
    dotnet cake empty-args.cake --arg1 valueA --arg2 valueB
    arg1: valueA
    arg2: valueB