-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathpowershell.go
90 lines (80 loc) · 2.64 KB
/
powershell.go
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package completion
import (
"io"
"os/exec"
"strings"
)
type powershell struct {
goos string
programName string
}
var _ Shell = &powershell{}
// Name implements Shell.
func (p *powershell) Name() string {
return "powershell"
}
func Powershell(goos string, programName string) Shell {
return &powershell{goos: goos, programName: programName}
}
// InstallPath implements Shell.
func (p *powershell) InstallPath() (string, error) {
var (
path []byte
err error
)
cmd := "$PROFILE.CurrentUserAllHosts"
if p.goos == "windows" {
path, err = exec.Command("powershell", cmd).CombinedOutput()
} else {
path, err = exec.Command("pwsh", "-Command", cmd).CombinedOutput()
}
if err != nil {
return "", err
}
return strings.TrimSpace(string(path)), nil
}
// WriteCompletion implements Shell.
func (p *powershell) WriteCompletion(w io.Writer) error {
return configTemplateWriter(w, pshCompletionTemplate, p.programName)
}
// ProgramName implements Shell.
func (p *powershell) ProgramName() string {
return p.programName
}
const pshCompletionTemplate = `
# Escaping output sourced from:
# https://github.com/spf13/cobra/blob/e94f6d0dd9a5e5738dca6bce03c4b1207ffbc0ec/powershell_completions.go#L47
filter _{{.Name}}_escapeStringWithSpecialChars {
` + " $_ -replace '\\s|#|@|\\$|;|,|''|\\{|\\}|\\(|\\)|\"|`|\\||<|>|&','`$&'" + `
}
$_{{.Name}}_completions = {
param(
$wordToComplete,
$commandAst,
$cursorPosition
)
# Legacy space handling sourced from:
# https://github.com/spf13/cobra/blob/e94f6d0dd9a5e5738dca6bce03c4b1207ffbc0ec/powershell_completions.go#L107
if ($PSVersionTable.PsVersion -lt [version]'7.2.0' -or
($PSVersionTable.PsVersion -lt [version]'7.3.0' -and -not [ExperimentalFeature]::IsEnabled("PSNativeCommandArgumentPassing")) -or
(($PSVersionTable.PsVersion -ge [version]'7.3.0' -or [ExperimentalFeature]::IsEnabled("PSNativeCommandArgumentPassing")) -and
$PSNativeCommandArgumentPassing -eq 'Legacy')) {
$Space =` + "' `\"`\"'" + `
} else {
$Space = ' ""'
}
$Command = $commandAst.ToString().Substring(0, $cursorPosition - 1)
if ($wordToComplete -ne "" ) {
$wordToComplete = $Command.Split(" ")[-1]
} else {
$Command = $Command + $Space
}
# Get completions by calling the command with the COMPLETION_MODE environment variable set to 1
$env:COMPLETION_MODE = 1
Invoke-Expression $Command | Where-Object { $_ -like "$wordToComplete*" } | ForEach-Object {
"$_" | _{{.Name}}_escapeStringWithSpecialChars
}
rm env:COMPLETION_MODE
}
Register-ArgumentCompleter -CommandName {{.Name}} -ScriptBlock $_{{.Name}}_completions
`