Skip to content

Commit 76314e5

Browse files
committed
Extract SetModuleContent to wrap reading and joining into a module
1 parent 4b3aea7 commit 76314e5

3 files changed

Lines changed: 419 additions & 260 deletions

File tree

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
function SetModuleContent {
2+
<#
3+
.SYNOPSIS
4+
A wrapper for Set-Content that handles arrays of file paths
5+
.DESCRIPTION
6+
The implementation here is strongly dependent on Build-Module doing the right thing
7+
Build-Module can optionally pass a PREFIX or SUFFIX, but otherwise only passes files
8+
9+
Because of that, SetModuleContent doesn't test for that
10+
11+
The goal here is to pretend this is a pipeline, for the sake of memory and file IO
12+
#>
13+
[CmdletBinding()]
14+
param(
15+
# Where to write the joined output
16+
[Parameter(Position=0, Mandatory)]
17+
[string]$OutputPath,
18+
19+
# Input files, the scripts that will be copied to the output path
20+
# The FIRST and LAST items can be text content instead of file paths.
21+
[Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
22+
[Alias("PSPath", "FullName")]
23+
[string[]]$SourceFile,
24+
25+
# The working directory (allows relative paths for other values)
26+
[string]$WorkingDirectory = $pwd,
27+
28+
# The encoding defaults to UTF8 (or UTF8NoBom on Core)
29+
[Parameter(DontShow)]
30+
[string]$Encoding = $(if($IsCoreCLR) { "UTF8NoBom" } else { "UTF8" })
31+
)
32+
begin {
33+
Push-Location $WorkingDirectory -StackName SetModuleContent
34+
$ContentStarted = $false # There has been no content yet
35+
36+
# Create a proxy command style scriptblock for Set-Content to keep the file handle open
37+
$SetContentCmd = $ExecutionContext.InvokeCommand.GetCommand('Microsoft.PowerShell.Management\Set-Content', [System.Management.Automation.CommandTypes]::Cmdlet)
38+
$SetContent = {& $SetContentCmd -Path $OutputPath -Encoding $Encoding }.GetSteppablePipeline($myInvocation.CommandOrigin)
39+
$SetContent.Begin($true)
40+
}
41+
process {
42+
foreach($file in $SourceFile) {
43+
if($SourceName = Resolve-Path $file -Relative -ErrorAction SilentlyContinue) {
44+
Write-Verbose "Adding $SourceName"
45+
$SetContent.Process("#Region '$SourceName' 0")
46+
Get-Content $SourceName -OutVariable source | ForEach-Object { $SetContent.Process($_) }
47+
$SetContent.Process("#EndRegion '$SourceName' $($Source.Count)")
48+
} else {
49+
if(!$ContentStarted) {
50+
$SetContent.Process("#Region 'PREFIX' 0")
51+
$SetContent.Process($file)
52+
$SetContent.Process("#EndRegion 'PREFIX'")
53+
$ContentStarted = $true
54+
} else {
55+
$SetContent.Process("#Region 'SUFFIX' 0")
56+
$SetContent.Process($file)
57+
$SetContent.Process("#EndRegion 'SUFFIX'")
58+
}
59+
}
60+
}
61+
}
62+
end {
63+
$SetContent.End()
64+
Pop-Location -StackName SetModuleContent
65+
}
66+
}

0 commit comments

Comments
 (0)