Repository navigation
Expand file tree
/
Copy pathcompletion_protocol_test.go
More file actions
189 lines (179 loc) · 8.78 KB
/
Copy pathcompletion_protocol_test.go
File metadata and controls
189 lines (179 loc) · 8.78 KB
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
package cli
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"github.com/echocat/cli4g/codec"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestCompletionProtocolSkipsLifecycleAndUsesContextStreams(t *testing.T) {
app := NewSimpleApplication("tool").WithCompletion(true).WithErrorHandlerEnabled(false).
WithFlag(NewFlag(codec.NewBool(), "verbose")).
WithHandler(func(context.Context, NoOptions) error { panic("not a normal invocation") }).MustCreate()
defer func() { assert.NoError(t, app.Close()) }()
var output bytes.Buffer
ctx := ContextWithStdio(nil, strings.NewReader(`{"words":["--ver"],"word":0,"offset":5}`), &output, nil)
invocation, err := app.Parse(ctx, nil, DefaultCompletionRequestCommandName, "1", "nu")
require.NoError(t, err)
require.Empty(t, output.String())
defer func() { assert.NoError(t, invocation.Close()) }()
require.NoError(t, invocation.Execute(ctx))
var result codec.CompletionResult
require.NoError(t, json.Unmarshal(output.Bytes(), &result))
assert.Equal(t, []string{"--verbose"}, completionTexts(result))
output.Reset()
require.NoError(t, app.ParseAndExecute(ctx, nil, DefaultCompletionRequestCommandName, "1", "bash", "10", "tool --ver", "--ver"))
assert.Equal(t, []string{"1", "0", "0", "0", "", "", "", "--verbose", ""}, strings.Split(output.String(), "\x00"))
}
func TestCompletionProtocolRejectsMalformedRequestsQuietly(t *testing.T) {
app := NewSimpleApplication("tool").WithCompletion(true).MustCreate()
defer func() { assert.NoError(t, app.Close()) }()
for _, input := range []string{``, `{`, `{"words":null,"word":-1}`, `{} {}`, `{"unexpected":true}`} {
var output, diagnostics bytes.Buffer
ctx := ContextWithStdio(nil, strings.NewReader(input), &output, &diagnostics)
require.NoError(t, app.ParseAndExecute(ctx, nil, DefaultCompletionRequestCommandName, "1", "nu"))
var result codec.CompletionResult
require.NoError(t, json.Unmarshal(output.Bytes(), &result))
assert.True(t, result.Handled)
assert.Empty(t, result.Candidates)
assert.Empty(t, diagnostics.String())
}
}
func TestNushellProtocolRetainsDependenciesAfterCursorWhenSupplied(t *testing.T) {
provider := codec.WithCompletionHandler(codec.NewString(), func(ctx context.Context, input codec.CompletionInput) (codec.CompletionResult, error) {
value, _, err := input.Effective.Flag(ctx, "context")
result := codec.CompletionResult{Handled: true}
for _, name := range value.Values {
result.Candidates = append(result.Candidates, codec.CompletionCandidate{Value: name + "-namespace"})
}
return result, err
})
app := NewSimpleApplication("tool").WithCompletion(true).
WithFlag(NewFlag(codec.NewString(), "context")).WithFlag(NewFlag(provider, "namespace")).MustCreate()
defer func() { assert.NoError(t, app.Close()) }()
var output bytes.Buffer
ctx := ContextWithStdio(nil, strings.NewReader(`{"words":["--namespace","cl","--context","cluster-b"],"word":1,"offset":2,"raw":true}`), &output, nil)
require.NoError(t, app.ParseAndExecute(ctx, nil, DefaultCompletionRequestCommandName, "1", "nu"))
var result codec.CompletionResult
require.NoError(t, json.Unmarshal(output.Bytes(), &result))
assert.Equal(t, []string{"cluster-b-namespace"}, completionTexts(result))
}
func TestCompletionInstallationIsIdempotentAndProtectsExistingFiles(t *testing.T) {
app := NewSimpleApplication("tool").WithCompletionRequestCommandName(DefaultCompletionRequestCommandName).MustCreate()
defer func() { assert.NoError(t, app.Close()) }()
for _, shell := range []CompletionShell{CompletionBash, CompletionFish, CompletionNushell, CompletionPowerShell, CompletionZsh} {
directory := t.TempDir()
path, err := app.InstallCompletion(nil, shell, directory)
require.NoError(t, err)
contents, err := os.ReadFile(path)
require.NoError(t, err)
assert.Contains(t, string(contents), completionScriptHeader)
again, err := app.InstallCompletion(nil, shell, directory)
require.NoError(t, err)
assert.Equal(t, path, again)
require.NoError(t, os.WriteFile(path, []byte("user-managed"), 0600))
_, err = app.InstallCompletion(nil, shell, directory)
require.ErrorContains(t, err, "not managed by cli4g")
contents, err = os.ReadFile(path)
require.NoError(t, err)
assert.Equal(t, "user-managed", string(contents))
}
t.Setenv("BASH_COMPLETION_USER_DIR", t.TempDir())
directory, err := completionDirectory(context.Background(), CompletionBash)
require.NoError(t, err)
assert.Equal(t, filepath.Join(os.Getenv("BASH_COMPLETION_USER_DIR"), "completions"), directory)
_, err = app.CompletionScript("unsupported-shell")
require.Error(t, err)
_, err = NewSimpleApplication("../bad").MustCreate().InstallCompletion(nil, CompletionBash, t.TempDir())
require.Error(t, err)
}
func TestPowerShellCompletionProtocolPreservesUnicodeAndRejectsMalformedInput(t *testing.T) {
app := NewApplication[struct {
Format string `flag:"format" enum:"über|two words"`
}]("tool").WithCompletion(true).WithInitializeHandler(func(context.Context, struct {
Format string `flag:"format" enum:"über|two words"`
}) error {
panic("completion must skip initialization")
}).MustCreate()
defer func() { assert.NoError(t, app.Close()) }()
for _, test := range []struct {
input string
want []string
}{
{base64.StdEncoding.EncodeToString([]byte(`{"words":["--format","ü"],"word":1,"offset":2}`)), []string{"über"}},
{base64.StdEncoding.EncodeToString([]byte(`{"words":["--format","two wo"],"word":1,"offset":6}`)), []string{"two words"}},
{"not base64!", []string{}},
{base64.StdEncoding.EncodeToString([]byte(`{} {}`)), []string{}},
{base64.StdEncoding.EncodeToString([]byte(`{"unexpected":true}`)), []string{}},
{base64.StdEncoding.EncodeToString([]byte(`{"words":["--format","ü"],"word":1,"offset":2}` + strings.Repeat(" ", 1<<20))), []string{}},
} {
var output, diagnostics bytes.Buffer
ctx := ContextWithStdio(nil, strings.NewReader(test.input), &output, &diagnostics)
require.NoError(t, app.ParseAndExecute(ctx, nil, DefaultCompletionRequestCommandName, "1", "powershell"))
decoded, err := base64.StdEncoding.DecodeString(output.String())
require.NoError(t, err)
var result codec.CompletionResult
require.NoError(t, json.Unmarshal(decoded, &result))
assert.Equal(t, test.want, completionTexts(result))
assert.Empty(t, diagnostics.String())
}
}
func TestCompletionDoesNotReserveTheFormerProtocolFlag(t *testing.T) {
app := NewSimpleApplication("tool").WithCompletion(true).
WithHandler(func(context.Context, NoOptions) error { return nil }).
WithErrorHandlerEnabled(false).WithStringFlag("cli4g-completion").MustCreate()
defer func() { assert.NoError(t, app.Close()) }()
invocation, err := app.Parse(nil, nil, "--cli4g-completion", "ordinary-value")
require.NoError(t, err)
defer func() { assert.NoError(t, invocation.Close()) }()
_, value := invocation.Flag("cli4g-completion")
assert.Equal(t, "ordinary-value", value)
}
func TestBashCompletionInputQuotesSeparatorsUnicodeAndCursor(t *testing.T) {
for _, test := range []struct {
line string
point int
want CompletionRequest
}{
{"tool --format=ya", len("tool --format=ya"), completionAtEnd("--format=ya")},
{"tool --format 'two wo", len("tool --format 'two wo"), completionAtEnd("--format", "two wo")},
{"tool --format two\\ wo", len("tool --format two\\ wo"), completionAtEnd("--format", "two wo")},
{"tool --format über", len("tool --format über"), completionAtEnd("--format", "über")},
{"other | tool --format ya", len("other | tool --format ya"), completionAtEnd("--format", "ya")},
{"tool --format ya | other", len("tool --format ya"), completionAtEnd("--format", "ya")},
{"tool --format yaml --context production", len("tool --format ya"), CompletionRequest{Words: []string{"--format", "yaml", "--context", "production"}, Word: 1, Offset: 2}},
{"tool ", len("tool "), completionAtEnd("")},
{"tool --flag", len("tool "), CompletionRequest{Words: []string{"", "--flag"}, Word: 0}},
} {
t.Run(test.line, func(t *testing.T) {
request, err := bashCompletionRequest(test.line, test.point)
require.NoError(t, err)
assert.Equal(t, test.want, request)
})
}
}
func TestBashCompletionReplacementPrefixRetainsLiteralWordBreaks(t *testing.T) {
for _, test := range []struct{ prefix, current, want string }{
{"--format=ya", "ya", "--format="},
{"--format=", "", "--format="},
{"--format=", "''", "--format="},
{"--format=", `""`, "--format="},
{"--format=two wo", `'two wo'`, "--format="},
{"--format=a'b", `"a'b"`, "--format="},
{"--format=a'b", "a'b", "--format="},
{"--format=$(printf literal)", `'$(printf literal)'`, "--format="},
{"colon:fi", "fi", "colon:"},
{"--format=ü", "ü", "--format="},
{"--format=two wo", "wrong", ""},
} {
t.Run(test.current, func(t *testing.T) {
assert.Equal(t, test.want, bashCompletionReplacementPrefix(test.prefix, test.current))
})
}
}