From 1e0ed31f321ab4e12eb0f83d0c341ce406c751d2 Mon Sep 17 00:00:00 2001 From: montag451 Date: Tue, 3 Dec 2024 23:04:26 +0100 Subject: [PATCH] lxc/completion: Add `cmpImageFingerprintsFromRemote` and completions for `image alias create` Signed-off-by: montag451 (cherry picked from commit 41929ea4d6c78460cd1f555e8f0e814c79f32bf4) Signed-off-by: Kadin Sayani License: Apache-2.0 --- lxc/completion.go | 23 +++++++++++++++++++++++ lxc/image_alias.go | 17 +++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/lxc/completion.go b/lxc/completion.go index c378edc8c457..80ba8519b0c7 100644 --- a/lxc/completion.go +++ b/lxc/completion.go @@ -222,6 +222,29 @@ func (g *cmdGlobal) cmpImages(toComplete string) ([]string, cobra.ShellCompDirec return results, cmpDirectives } +// cmpImageFingerprintsFromRemote provides shell completion for image fingerprints. +// It takes a partial input string and a remote and returns image fingerprints for that remote along with a shell completion directive. +func (g *cmdGlobal) cmpImageFingerprintsFromRemote(toComplete string, remote string) ([]string, cobra.ShellCompDirective) { + if remote == "" { + remote = g.conf.DefaultRemote + } + + remoteServer, _ := g.conf.GetImageServer(remote) + + images, _ := remoteServer.GetImages() + + results := make([]string, 0, len(images)) + for _, image := range images { + if !strings.HasPrefix(image.Fingerprint, toComplete) { + continue + } + + results = append(results, image.Fingerprint) + } + + return results, cobra.ShellCompDirectiveNoFileComp +} + // cmpInstanceKeys provides shell completion for all instance configuration keys. // It takes an instance name to determine instance type and returns a list of all instance configuration keys along with a shell completion directive. func (g *cmdGlobal) cmpInstanceKeys(instanceName string) ([]string, cobra.ShellCompDirective) { diff --git a/lxc/image_alias.go b/lxc/image_alias.go index 42af3c7abc1c..b0b0deeee57c 100644 --- a/lxc/image_alias.go +++ b/lxc/image_alias.go @@ -62,6 +62,23 @@ func (c *cmdImageAliasCreate) command() *cobra.Command { cmd.RunE = c.run + cmd.ValidArgsFunction = func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + if len(args) > 1 { + return nil, cobra.ShellCompDirectiveNoFileComp + } + + if len(args) == 0 { + return c.global.cmpRemotes(toComplete, true) + } + + remote, _, found := strings.Cut(args[0], ":") + if !found { + remote = "" + } + + return c.global.cmpImageFingerprintsFromRemote(toComplete, remote) + } + return cmd }