nightroman / Invoke-Build

Build Automation in PowerShell

Home Page:https://github.com/nightroman/Invoke-Build/wiki

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Passed parameters validation

GreatTeacherBasshead opened this issue · comments

Hi Roman,

Lets assume these scripts:

  • build.ps1
$params = @{
    File    = 'tasks.ps1'
    Task    = 't1'

    param1  = 'param1'
    param2  = 'param2'
    # param3  = 'param3' - forgot to specify this param
    # lots of other params here
    param99 = 'param99'
}

Invoke-Build @params
  • tasks.ps1
param(
    [Parameter(Mandatory)][string]$param1,
    [Parameter(Mandatory)][string]$param2,
    [Parameter(Mandatory)][string]$param3,
    # another params here
    [Parameter(Mandatory)][string]$param99
)

task t1 {
    Write-Build 'Hello World!'
}

I run build.ps1 on a build server, and it hangs forever.
The reason is that mandatory parameter param3 is not passed to Invoke-Build. 2 problems here:

  1. Was really difficult to identify the reason of the behavior.
  2. With huge amount of parameters, its difficult to find the missing one.

Maybe you have an idea, how to check that all mandatory parameters are passed?

Here's how we do it, we do an assertion in Enter-Build like this:

Enter-Build {
  assert ($buildTimestamp) "buildTimestamp is not defined!";
}

Yes, unfortunately Mandatory is not an option in non-interactive scenarios. (And even in interactive, some prompts do not make practical sense. I think it's the PowerShell usability issue but it's another story.)

There are probably several ways to deal with this. One is suggested by @nsartor (thanks!). Another possible, maybe the simplest and maybe a little lazy, is this:

param(
    [string]$param1 = $(throw),
    [string]$param2 = $(throw),
    [string]$param3 = $(throw),
    # another params here
    [string]$param99 = $(throw)
)

To make it neater, add error messages after throws, depending on a parameter.
But even bare throw is kind of enough because the error normally shows the line (i.e. the parameter name).

Does this help? Closing?

Thanks for suggestions, guys!