Skip to content

Commit

Permalink
feat: Use-Module ( Fixes #1130 )
Browse files Browse the repository at this point in the history
Simplifying by narrowing scope.
  • Loading branch information
James Brundage committed Jun 1, 2024
1 parent 1a52341 commit 9f085c8
Showing 1 changed file with 5 additions and 46 deletions.
51 changes: 5 additions & 46 deletions Commands/Module/Use-Module.ps.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,7 @@ function Use-Module
.SYNOPSIS
Uses a module.
.DESCRIPTION
Uses a module.
This can either:
* If present, run a module's `Use` function, method, or script property.
* Otherwise, run a script block in the module's context.
* Run a module's `Use` function, if present
* Call a module's `Use` method, if present
In all cases, the script block should be run in the module's context, using dot-sourcing.
Uses a module's context to run a `[ScriptBlock]` (with dot-sourcing).
.EXAMPLE
Get-Module PipeScript | Use-Module -ScriptBlock { $myInvocation.MyCommand.ScriptBlock.Module }
#>
Expand Down Expand Up @@ -61,43 +51,12 @@ function Use-Module
Get-Module $Name | Select-Object -First 1
}

# Return if there is no module context.
return if -not $moduleContext

# Get the use commands.
$useCommands = $moduleContent.ExportedCommands[@(
"Use-$($moduleContext.Name)",
"Use.$($moduleContext.Name)"
"$($moduleContext.Name).Use"
)]

# Get the use method.
$useMethod = $moduleContext.psobject.methods["Use"]

$ToRun =
# If we have a method
if ($useMethod)
{
$useMethod.Script # use it
# (and pass the script block as an argument)
$ArgumentList = @($ScriptBlock) + @($ArgumentList)
}
# If we have any use commands, use the first one
elseif ($useCommands -ne $null)
{
@($useCommands -ne $null)[0]
# (and pass the script block as an argument)
$ArgumentList = @($ScriptBlock) + @($ArgumentList)
}
else
{
# Otherwise, use the script block
$ScriptBlock
}

# We're running in the module context, and now we know what we want `$toRun`.
# We're running in the module context,
$runningIn = $moduleContext

# and we want `$toRun` the ScriptBlock.
$ToRun = $ScriptBlock

# The rest of the code is tedium.
# If there were arguments and parameters, pass them both with splatting.
if ($ArgumentList) {
Expand Down

0 comments on commit 9f085c8

Please sign in to comment.