Skip to content

Commit 8fa751a

Browse files
author
James Brundage
committed
Updating Assert keyword (support for pipelining) (#143)
1 parent 3f8c7a5 commit 8fa751a

File tree

1 file changed

+29
-9
lines changed

1 file changed

+29
-9
lines changed

Transpilers/Keywords/Assert.psx.ps1

Lines changed: 29 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,17 @@
3838
# If the assertion action was a ScriptBlock, no exception is automatically thrown
3939
Invoke-PipeScript {
4040
assert ($false) { Write-Information "I Assert There Is a Problem"}
41-
} -Verbose
41+
} -Verbose
42+
.EXAMPLE
43+
# assert can be used with the object pipeline. $_ will be the current object.
44+
Invoke-PipeScript {
45+
1..4 | assert {$_ % 2} "$_ is not odd!"
46+
} -Debug
47+
.EXAMPLE
48+
# You can provide a ```[ScriptBlock]``` as the second argument to see each failure
49+
Invoke-PipeScript {
50+
1..4 | assert {$_ % 2} { Write-Error "$_ is not odd!" }
51+
} -Debug
4252
#>
4353
[ValidateScript({
4454
# This transpiler should run if the command is literally 'assert'
@@ -99,7 +109,7 @@ process {
99109
elseif ($firstArgTypeName -eq 'ScriptBlockExpressionAst')
100110
{
101111
# put it in parenthesis.
102-
"($($FirstArg -replace '^\{' -replace '\}$'))"
112+
"($($FirstArg.GetScriptBlock()))"
103113
}
104114
# Otherwise
105115
else
@@ -119,22 +129,32 @@ process {
119129
"if $condition { throw '{$($firstArg -replace "'", "''")}' } "
120130
} elseif ($secondArg.GetType().Name -eq 'ScriptBlockExpressionAst') {
121131
# If the second argument was a script, transpile and embed it.
122-
"if $condition {$([ScriptBlock]::Create(
123-
($secondArg -replace '^\{' -replace '\}$')
124-
) | .>Pipescript)}"
132+
"if $condition {$($secondArg.GetScriptBlock().Transpile())}"
125133
} else {
126134
# Otherwise, throw the second argument.
127135
"if $condition { throw $secondArg } "
128136
}
129137

138+
130139
$inPipeline = $false
131140
if ($CommandAst.Parent -is [Management.Automation.Language.PipelineAst] -and
132141
$CommandAst.Parent.PipelineElements.Count -gt 1) {
133142
$inPipeline = $true
134143
}
135-
if ($DebugPreference, $VerbosePreference -ne 'silentlyContinue') {
136-
[scriptblock]::Create($newScript)
137-
} else {
138-
{}
144+
145+
if ($DebugPreference, $VerbosePreference -ne 'silentlyContinue') {
146+
if ($inPipeline) {
147+
[scriptblock]::Create("& { process { $newScript } }")
148+
} else {
149+
[scriptblock]::Create($newScript)
150+
}
151+
152+
} else {
153+
if ($inPipeline) {
154+
{& { process { $_ }}}
155+
} else {
156+
{}
157+
}
158+
139159
}
140160
}

0 commit comments

Comments
 (0)