Public/New-ESCSSettingsFile.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
61
62
63
64
65
66
67
68
69
70
using namespace System.Diagnostics.CodeAnalysis

function New-ESCSSettingsFile {
    <#
    .EXTERNALHELP EditorServicesCommandSuite-help.xml
    #>

    [CmdletBinding()]
    [SuppressMessage('PSAvoidShouldContinueWithoutForce', '',
                     Justification='ShouldContinue is called from a subroutine without CmdletBinding.')]
    param(
        [ValidateNotNullOrEmpty()]
        [string]
        $Path = $psEditor.Workspace.Path,

        [switch]
        $Force
    )
    begin {
        function HandleFileExists($filePath) {
            if (-not (Test-Path $filePath)) {
                return
            }
            $shouldRemove = $Force.IsPresent -or
                            $PSCmdlet.ShouldContinue(
                                $Strings.ShouldReplaceSettingsMessage,
                                $Strings.ShouldReplaceSettingsCaption)

            if ($shouldRemove) {
                Remove-Item $targetFilePath
                return
            }
            $exception = [System.ArgumentException]::new(
                $Strings.SettingsFileExists -f $psEditor.Workspace.Path)
            ThrowError -Exception $exception `
                       -Id        SettingsFileExists `
                       -Category  InvalidArgument `
                       -Target    $targetFilePath
        }
    }
    end {
        $targetFilePath = Join-Path $Path -ChildPath 'ESCSSettings.psd1'
        HandleFileExists $targetFilePath

        try {
            $groupDefinition = Get-Content $PSScriptRoot\..\Templates\SettingsFile.stg -Raw -ErrorAction Stop

            $templateSplat = @{
                Group = (New-StringTemplateGroup -Definition $groupDefinition)
                Name  = 'Base'
                Parameters = @{
                    Settings = $script:DEFAULT_SETTINGS.GetEnumerator()
                    Strings  = [pscustomobject]$Strings
                }
            }

            $content = Invoke-StringTemplate @templateSplat
        } catch {
            ThrowError -Exception ([InvalidOperationException]::new($Strings.TemplateGroupCompileError)) `
                       -Id        TemplateGroupCompileError `
                       -Category  InvalidOperation `
                       -Target    $groupDefinition
        }

        $null = New-Item $targetFilePath -Value $content
        if ($psEditor) {
            SetEditorLocation $targetFilePath
        }
    }
}