Skip to content

Commit 979d6d3

Browse files
committed
feat(commands): rich shell autocompletion for presets, modes, files, talosconfig
Cobra's __complete subcommand was wired (via cobra defaults) but talm registered no per-flag or per-positional completion targets. Operators tab-completing flag values got the generic file completion fallback, even for fixed enums (--mode) or enumerable sets (--preset). This change adds a per-target completion module (pkg/commands/completion.go) with: - --preset (talm init): enumerate generated.AvailablePresets() - --mode (talm apply): fixed enum {auto, no-reboot, reboot, staged, try} matching upstream helpers.AddModeFlags - --file, --values, --template, --with-secrets: filter file completion to *.yaml / *.yml - positional file args on apply / template / upgrade: scan the project's nodes/ directory, return only YAML files with a talm modeline - --nodes, --endpoints (root persistent): load the in-scope talosconfig (--talosconfig > $TALOSCONFIG > project-local talosconfig) and return the union of the requested field across every context Closes #170. Assisted-By: Claude <[email protected]> Signed-off-by: Aleksei Sviridkin <[email protected]>
1 parent 38ddab0 commit 979d6d3

8 files changed

Lines changed: 530 additions & 8 deletions

File tree

‎main.go‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,14 @@ func registerRootFlags(cmd *cobra.Command) {
114114
cmd.PersistentFlags().StringVar(&commands.GlobalArgs.Cluster, "cluster", "", "Cluster to connect to if a proxy endpoint is used.")
115115
cmd.PersistentFlags().BoolVar(&commands.GlobalArgs.SkipVerify, "skip-verify", false, "skip TLS certificate verification (keeps client authentication)")
116116
cmd.PersistentFlags().Bool("version", false, "Print the version number of the application")
117+
118+
// Shell completion for root persistent flags (#170). --nodes /
119+
// --endpoints draw from the in-scope talosconfig contexts;
120+
// --talosconfig narrows the file-completion fallback to any
121+
// readable file (yaml or otherwise — talosconfig has no fixed
122+
// extension).
123+
_ = cmd.RegisterFlagCompletionFunc("nodes", commands.CompleteTalosconfigNodes)
124+
_ = cmd.RegisterFlagCompletionFunc("endpoints", commands.CompleteTalosconfigEndpoints)
117125
}
118126

119127
func Execute() error {

‎pkg/commands/apply.go‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1034,5 +1034,14 @@ func init() {
10341034
applyCmd.Flags().BoolVar(&applyCmdFlags.showSecretsInDrift, "show-secrets-in-drift", false, "show secret-bearing field values verbatim in drift preview / post-apply verify output (default: redacted; cluster.token, cluster.ca.key, machine.token, Wireguard private keys, etc.)")
10351035
helpers.AddModeFlags(&applyCmdFlags.Mode, applyCmd)
10361036

1037+
// Shell completion for `talm apply` flags + positional args (#170).
1038+
// Errors are best-effort: nothing breaks if a flag name disappears
1039+
// upstream — completion just falls back to defaults.
1040+
_ = applyCmd.RegisterFlagCompletionFunc("mode", completeApplyMode)
1041+
_ = applyCmd.RegisterFlagCompletionFunc("file", completeYAMLFiles)
1042+
_ = applyCmd.RegisterFlagCompletionFunc("with-secrets", completeYAMLFiles)
1043+
1044+
applyCmd.ValidArgsFunction = completeNodeFiles
1045+
10371046
addCommand(applyCmd)
10381047
}

‎pkg/commands/completion.go‎

Lines changed: 238 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,238 @@
1+
// Copyright Cozystack Authors
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
package commands
16+
17+
import (
18+
"os"
19+
"path/filepath"
20+
"strings"
21+
22+
"github.com/cozystack/talm/pkg/generated"
23+
"github.com/cozystack/talm/pkg/modeline"
24+
"github.com/siderolabs/talos/pkg/machinery/client/config"
25+
"github.com/spf13/cobra"
26+
)
27+
28+
// Field names reused across completion helpers and the shadow-flags
29+
// map in talosctl_wrapper.go. Hoisted to constants to satisfy
30+
// goconst across the package.
31+
const (
32+
flagNameNodes = "nodes"
33+
flagNameEndpoints = "endpoints"
34+
yamlExt = "yaml"
35+
ymlExt = "yml"
36+
nodesDirName = "nodes"
37+
)
38+
39+
// applyModeOptions enumerates the apply / patch / edit `--mode`
40+
// values upstream talosctl exposes via helpers.AddModeFlags. Pinned
41+
// here rather than imported because upstream's keys live inside a
42+
// per-call map, not a package-level constant — we cannot reflect
43+
// them at completion time without instantiating the Mode flag.
44+
//
45+
//nolint:gochecknoglobals // immutable lookup table used by completeApplyMode at completion time.
46+
var applyModeOptions = []string{"auto", "no-reboot", "reboot", "staged", "try"}
47+
48+
// completePresetNames implements shell completion for the `--preset`
49+
// flag of `talm init`: the available presets are baked into the
50+
// binary at build time, so the completion is deterministic and the
51+
// directive disables file-completion fallback.
52+
func completePresetNames(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
53+
presets, err := generated.AvailablePresets()
54+
if err != nil {
55+
// Surfaces no completions plus the error so the shell
56+
// does not silently fall back to file completion.
57+
return nil, cobra.ShellCompDirectiveError
58+
}
59+
60+
return presets, cobra.ShellCompDirectiveNoFileComp
61+
}
62+
63+
// completeApplyMode implements shell completion for the `--mode`
64+
// flag of `talm apply`. Fixed enum, no file fallback.
65+
func completeApplyMode(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
66+
return applyModeOptions, cobra.ShellCompDirectiveNoFileComp
67+
}
68+
69+
// completeYAMLFiles implements shell completion for flags that
70+
// accept YAML file paths (`-f / --file`, `--values`, `-t / --template`,
71+
// `--with-secrets`). The directive narrows the file-completion
72+
// fallback to `*.yaml` and `*.yml`.
73+
func completeYAMLFiles(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
74+
return []string{yamlExt, ymlExt}, cobra.ShellCompDirectiveFilterFileExt
75+
}
76+
77+
// completeNodeFiles is the ValidArgsFunction for `apply` / `template`
78+
// / `upgrade`'s positional file argument. Walks `nodes/` under the
79+
// detected project root, filters to YAML files whose first line is
80+
// a talm modeline. Operator types `talm upgrade <TAB>` and gets the
81+
// list of modelined node files, not every yaml in the project.
82+
func completeNodeFiles(_ *cobra.Command, _ []string, toComplete string) ([]string, cobra.ShellCompDirective) {
83+
root := Config.RootDir
84+
if root == "" {
85+
// Pre-PreRunE invocation (cobra's __complete path may
86+
// fire before our root detection runs). Best-effort
87+
// fallback: walk from CWD.
88+
cwd, err := os.Getwd()
89+
if err != nil {
90+
return nil, cobra.ShellCompDirectiveError
91+
}
92+
93+
root = cwd
94+
}
95+
96+
nodesDir := filepath.Join(root, nodesDirName)
97+
98+
entries, err := os.ReadDir(nodesDir)
99+
if err != nil {
100+
// `nodes/` may not exist on a brand-new project; fall
101+
// back to default file completion so the operator can
102+
// still pick files manually.
103+
return []string{yamlExt, ymlExt}, cobra.ShellCompDirectiveFilterFileExt
104+
}
105+
106+
var matches []string
107+
108+
for _, entry := range entries {
109+
if entry.IsDir() {
110+
continue
111+
}
112+
113+
name := entry.Name()
114+
if !strings.HasSuffix(name, "."+yamlExt) && !strings.HasSuffix(name, "."+ymlExt) {
115+
continue
116+
}
117+
118+
path := filepath.Join(nodesDirName, name)
119+
if !strings.HasPrefix(path, toComplete) && toComplete != "" {
120+
continue
121+
}
122+
123+
// FindAndParseModeline accepts leading operator comments per
124+
// #178; using a strict first-line-only parser would hide
125+
// files that `talm template -I` just produced from
126+
// `talm apply <TAB>` / `talm upgrade <TAB>`. Both
127+
// ErrModelineNotFound and malformed-modeline parse errors
128+
// drop the candidate from the completion list — completion
129+
// must not block on individual-file parse failures, and a
130+
// malformed modeline is still not a useful tab target.
131+
if _, _, err := modeline.FindAndParseModeline(filepath.Join(root, path)); err != nil {
132+
continue
133+
}
134+
135+
matches = append(matches, path)
136+
}
137+
138+
return matches, cobra.ShellCompDirectiveNoFileComp
139+
}
140+
141+
// CompleteTalosconfigNodes is the exported entry point for
142+
// completion of the root `--nodes` persistent flag (#170). main.go
143+
// wires it via cobra.RegisterFlagCompletionFunc.
144+
//
145+
//nolint:gochecknoglobals // package-level var holding the closure produced by completeTalosconfigField; the alternative (per-call construction) re-allocates on every shell completion invocation.
146+
var CompleteTalosconfigNodes = completeTalosconfigField(flagNameNodes)
147+
148+
// CompleteTalosconfigEndpoints is the exported entry point for
149+
// completion of the root `--endpoints` persistent flag (#170).
150+
//
151+
//nolint:gochecknoglobals // see CompleteTalosconfigNodes.
152+
var CompleteTalosconfigEndpoints = completeTalosconfigField(flagNameEndpoints)
153+
154+
// completeTalosconfigField builds the completion function for the
155+
// `--nodes` / `--endpoints` root persistent flags. Loads the
156+
// in-scope talosconfig and returns the union of the requested field
157+
// across every context. Closes over `field` so the call sites stay
158+
// one-liners.
159+
//
160+
// `field` must be "nodes" or "endpoints"; any other value yields an
161+
// empty completion list (caller error).
162+
func completeTalosconfigField(field string) func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) {
163+
return func(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
164+
path := resolveTalosconfigPathForCompletion()
165+
if path == "" {
166+
return nil, cobra.ShellCompDirectiveNoFileComp
167+
}
168+
169+
cfg, err := config.Open(path)
170+
if err != nil {
171+
return nil, cobra.ShellCompDirectiveError
172+
}
173+
174+
seen := map[string]struct{}{}
175+
out := []string{}
176+
177+
for _, ctx := range cfg.Contexts {
178+
var values []string
179+
180+
switch field {
181+
case flagNameNodes:
182+
values = ctx.Nodes
183+
case flagNameEndpoints:
184+
values = ctx.Endpoints
185+
default:
186+
return nil, cobra.ShellCompDirectiveError
187+
}
188+
189+
for _, item := range values {
190+
if _, dup := seen[item]; dup {
191+
continue
192+
}
193+
194+
seen[item] = struct{}{}
195+
out = append(out, item)
196+
}
197+
}
198+
199+
return out, cobra.ShellCompDirectiveNoFileComp
200+
}
201+
}
202+
203+
// resolveTalosconfigPathForCompletion returns the talosconfig path
204+
// the completion should read. Mirrors the in-process precedence:
205+
// 1. --talosconfig flag (already in GlobalArgs.Talosconfig)
206+
// 2. $TALOSCONFIG env var (cobra parses the flag default into
207+
// GlobalArgs.Talosconfig only if the operator passed --talosconfig
208+
// at invocation; for completion we have to consult the env
209+
// explicitly)
210+
// 3. project-local talosconfig (Config.RootDir/talosconfig)
211+
//
212+
// Returns the empty string if no candidate is readable. Completion
213+
// callers translate empty into an empty completion list rather than
214+
// an error — completion must not block on missing files.
215+
func resolveTalosconfigPathForCompletion() string {
216+
if GlobalArgs.Talosconfig != "" {
217+
if _, err := os.Stat(GlobalArgs.Talosconfig); err == nil {
218+
return GlobalArgs.Talosconfig
219+
}
220+
}
221+
222+
if env := os.Getenv("TALOSCONFIG"); env != "" {
223+
// $TALOSCONFIG is operator-controlled, not network-tainted;
224+
// the lint is a false positive for env-derived paths.
225+
if _, err := os.Stat(env); err == nil { //nolint:gosec // G304: operator-supplied env, not network-tainted
226+
return env
227+
}
228+
}
229+
230+
if Config.RootDir != "" {
231+
candidate := filepath.Join(Config.RootDir, "talosconfig")
232+
if _, err := os.Stat(candidate); err == nil {
233+
return candidate
234+
}
235+
}
236+
237+
return ""
238+
}

0 commit comments

Comments
 (0)