Public/ConvertTo-LocalizationString.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
using namespace Microsoft.PowerShell.EditorServices.Extensions
using namespace System.Management.Automation.Language

function ConvertTo-LocalizationString {
    <#
    .EXTERNALHELP EditorServicesCommandSuite-help.xml
    #>

    [CmdletBinding()]
    [EditorCommand(DisplayName='Add Closest String to Localization File')]
    param(
        [System.Management.Automation.Language.Ast]
        $Ast = (Find-Ast -AtCursor),

        [string]
        $Name
    )
    end {
        $Ast = GetAncestorOrThrow $Ast -AstTypeName StringConstantExpressionAst -ErrorContext $PSCmdlet

        if (-not $Name) {
            if ($Host -is [System.Management.Automation.Host.IHostSupportsInteractiveSession]) {
                $Name = ReadInputPrompt $Strings.StringNamePrompt
            } else {
                $Name = (Split-Path $psEditor.GetEditorContext().CurrentFile.Path -Leaf) +
                         '-' +
                         [guid]::NewGuid().Guid
            }
        }
        if (-not $Name) {
            ThrowError -Exception ([ArgumentException]::new($Strings.StringNamePromptFail)) `
                       -Id        StringNamePromptFail `
                       -Category  InvalidArgument `
                       -Target    $Name
        }

        $originalContents = $Ast.Value
        $Ast | Set-ScriptExtent -Text ('$Strings.{0}' -f $Name)

        try {
            SetEditorLocation (ResolveRelativePath (GetSettings).StringLocalizationManifest)
        } catch {
            ThrowError -Exception ([ArgumentException]::new($Strings.InvalidSettingValue -f 'StringLocalizationManifest')) `
                       -Id         `
                       -Category   `
                       -Target     $null
        }

        $hereString = Find-Ast { 'SingleQuotedHereString' -eq $_.StringConstantType } -First

        $newHereString = $hereString.Extent.Text -replace
            "(\r?\n)'@",
            ('$1' + $Name + '=' + $originalContents + '$1''@')

        $hereString | Set-ScriptExtent -Text $newHereString
    }
}