Skip to content

Commit e53317f

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 417b577 commit e53317f

8 files changed

Lines changed: 486 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
@@ -897,5 +897,14 @@ func init() {
897897
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.)")
898898
helpers.AddModeFlags(&applyCmdFlags.Mode, applyCmd)
899899

900+
// Shell completion for `talm apply` flags + positional args (#170).
901+
// Errors are best-effort: nothing breaks if a flag name disappears
902+
// upstream — completion just falls back to defaults.
903+
_ = applyCmd.RegisterFlagCompletionFunc("mode", completeApplyMode)
904+
_ = applyCmd.RegisterFlagCompletionFunc("file", completeYAMLFiles)
905+
_ = applyCmd.RegisterFlagCompletionFunc("with-secrets", completeYAMLFiles)
906+
907+
applyCmd.ValidArgsFunction = completeNodeFiles
908+
900909
addCommand(applyCmd)
901910
}

‎pkg/commands/completion.go‎

Lines changed: 230 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,230 @@
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+
if _, err := modeline.ReadAndParseModeline(filepath.Join(root, path)); err != nil {
124+
continue
125+
}
126+
127+
matches = append(matches, path)
128+
}
129+
130+
return matches, cobra.ShellCompDirectiveNoFileComp
131+
}
132+
133+
// CompleteTalosconfigNodes is the exported entry point for
134+
// completion of the root `--nodes` persistent flag (#170). main.go
135+
// wires it via cobra.RegisterFlagCompletionFunc.
136+
//
137+
//nolint:gochecknoglobals // package-level var holding the closure produced by completeTalosconfigField; the alternative (per-call construction) re-allocates on every shell completion invocation.
138+
var CompleteTalosconfigNodes = completeTalosconfigField(flagNameNodes)
139+
140+
// CompleteTalosconfigEndpoints is the exported entry point for
141+
// completion of the root `--endpoints` persistent flag (#170).
142+
//
143+
//nolint:gochecknoglobals // see CompleteTalosconfigNodes.
144+
var CompleteTalosconfigEndpoints = completeTalosconfigField(flagNameEndpoints)
145+
146+
// completeTalosconfigField builds the completion function for the
147+
// `--nodes` / `--endpoints` root persistent flags. Loads the
148+
// in-scope talosconfig and returns the union of the requested field
149+
// across every context. Closes over `field` so the call sites stay
150+
// one-liners.
151+
//
152+
// `field` must be "nodes" or "endpoints"; any other value yields an
153+
// empty completion list (caller error).
154+
func completeTalosconfigField(field string) func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) {
155+
return func(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
156+
path := resolveTalosconfigPathForCompletion()
157+
if path == "" {
158+
return nil, cobra.ShellCompDirectiveNoFileComp
159+
}
160+
161+
cfg, err := config.Open(path)
162+
if err != nil {
163+
return nil, cobra.ShellCompDirectiveError
164+
}
165+
166+
seen := map[string]struct{}{}
167+
out := []string{}
168+
169+
for _, ctx := range cfg.Contexts {
170+
var values []string
171+
172+
switch field {
173+
case flagNameNodes:
174+
values = ctx.Nodes
175+
case flagNameEndpoints:
176+
values = ctx.Endpoints
177+
default:
178+
return nil, cobra.ShellCompDirectiveError
179+
}
180+
181+
for _, item := range values {
182+
if _, dup := seen[item]; dup {
183+
continue
184+
}
185+
186+
seen[item] = struct{}{}
187+
out = append(out, item)
188+
}
189+
}
190+
191+
return out, cobra.ShellCompDirectiveNoFileComp
192+
}
193+
}
194+
195+
// resolveTalosconfigPathForCompletion returns the talosconfig path
196+
// the completion should read. Mirrors the in-process precedence:
197+
// 1. --talosconfig flag (already in GlobalArgs.Talosconfig)
198+
// 2. $TALOSCONFIG env var (cobra parses the flag default into
199+
// GlobalArgs.Talosconfig only if the operator passed --talosconfig
200+
// at invocation; for completion we have to consult the env
201+
// explicitly)
202+
// 3. project-local talosconfig (Config.RootDir/talosconfig)
203+
//
204+
// Returns the empty string if no candidate is readable. Completion
205+
// callers translate empty into an empty completion list rather than
206+
// an error — completion must not block on missing files.
207+
func resolveTalosconfigPathForCompletion() string {
208+
if GlobalArgs.Talosconfig != "" {
209+
if _, err := os.Stat(GlobalArgs.Talosconfig); err == nil {
210+
return GlobalArgs.Talosconfig
211+
}
212+
}
213+
214+
if env := os.Getenv("TALOSCONFIG"); env != "" {
215+
// $TALOSCONFIG is operator-controlled, not network-tainted;
216+
// the lint is a false positive for env-derived paths.
217+
if _, err := os.Stat(env); err == nil { //nolint:gosec // G703: operator-supplied env, not network-tainted
218+
return env
219+
}
220+
}
221+
222+
if Config.RootDir != "" {
223+
candidate := filepath.Join(Config.RootDir, "talosconfig")
224+
if _, err := os.Stat(candidate); err == nil {
225+
return candidate
226+
}
227+
}
228+
229+
return ""
230+
}

0 commit comments

Comments
 (0)