src/module/manifest/Update-ManifestFunctionsToExportField.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
function Update-ManifestFunctionsToExportField {
    [CmdletBinding()]
    [OutputType([PSModuleInfo])]
    Param
    (
        [Parameter(Mandatory = $true,
            ValueFromPipeline = $true)]
        [PSObject]
        $ManifestUpdate,

        [switch]
        $PassThru
    )
    
    begin {
        # Prevents single space for each item in an iteration:
        # https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_preference_variables?view=powershell-6#ofs
        $OFS = ''
    }
    
    # TODO: have $ManifestUpdate be typed.
    end {
        $ManifestFile = Get-Item -Path $ManifestUpdate.ManifestPath
        $FunctionNames = $ManifestUpdate.TargetFunctionsToExport.FunctionName
        
        # keep the 8 spaces for default VSCode PowerShell preference
        $FunctionNames = $FunctionNames | ForEach-Object -Process {" '$_',`r`n"} | Sort-Object
        
        if ($FunctionNames -is [Object[]]) {
            $Tail = $FunctionNames.Count - 1
            $FunctionNames[$Tail] = $FunctionNames[$Tail].TrimEnd().TrimEnd(',')
        } 
        elseif ($FunctionNames -is [String]) {
            $FunctionNames = $FunctionNames.TrimEnd().TrimEnd(',')
        }

        [regex]$InsertPointRegEx = "(?(?<=(FunctionsToExport))([\w\W]*?)|($))(?(?=\#)(?=\#)|(CmdletsToExport))"
        # PowerShellGet's Update-ModuleManifest currently has a bug that is reverting previous
        # changed values. Because of that, using Content commands.
        # https://github.com/PowerShell/PowerShell/issues/7181
        $ManifestContents = Get-Content -Path $ManifestUpdate.ManifestPath -Raw 

        # becareful with whitespace in this here-string below. as it works perfectly as of now.
        $ManifestContents = $InsertPointRegEx.Replace($ManifestContents, @"
 = @(
$FunctionNames
    )
 
     
"@
, 1)

        Set-Content -Path $ManifestUpdate.ManifestPath -Value $ManifestContents -NoNewline

        if ($PassThru) {
            $ManifestFile
        }

        $OFS = ' '
    }
}