Skip to content

Commit 15a6d25

Browse files
committed
use custom annotation for aliases
Cobra allows for aliases to be defined for a command, but only allows these to be defined at the same level (for example, `docker image ls` as alias for `docker image list`). Our CLI has some commands that are available both as a top-level shorthand as well as `docker <object> <verb>` subcommands. For example, `docker ps` is a shorthand for `docker container ps` / `docker container ls`. This patch introduces a custom "aliases" annotation that can be used to print all available aliases for a command. While this requires these aliases to be defined manually, in practice the list of aliases rarely changes, so maintenance should be minimal. As a convention, we could consider the first command in this list to be the canonical command, so that we can use this information to add redirects in our documentation in future. Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
1 parent 5add522 commit 15a6d25

4 files changed

Lines changed: 13 additions & 2 deletions

File tree

clidocstool.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import (
1818
"errors"
1919
"io"
2020
"os"
21+
"strings"
2122

2223
"github.com/spf13/cobra"
2324
)
@@ -99,6 +100,13 @@ func copyFile(src string, dst string) error {
99100
}
100101

101102
func getAliases(cmd *cobra.Command) []string {
103+
if a := cmd.Annotations["aliases"]; a != "" {
104+
aliases := strings.Split(a, ",")
105+
for i := 0; i < len(aliases); i++ {
106+
aliases[i] = strings.TrimSpace(aliases[i])
107+
}
108+
return aliases
109+
}
102110
if len(cmd.Aliases) == 0 {
103111
return cmd.Aliases
104112
}

clidocstool_test.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,9 @@ func init() {
5858
Aliases: []string{"b"},
5959
Short: "Start a build",
6060
Run: func(cmd *cobra.Command, args []string) {},
61+
Annotations: map[string]string{
62+
"aliases": "docker image build, docker buildx build, docker buildx b, docker build",
63+
},
6164
}
6265
buildxStopCmd = &cobra.Command{
6366
Use: "stop [NAME]",

fixtures/buildx_build.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ Start a build
55

66
### Aliases
77

8-
`docker buildx build`, `docker buildx b`
8+
`docker image build`, `docker buildx build`, `docker buildx b`, `docker build`
99

1010
### Options
1111

fixtures/docker_buildx_build.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
command: docker buildx build
2-
aliases: docker buildx build, docker buildx b
2+
aliases: docker image build, docker buildx build, docker buildx b, docker build
33
short: Start a build
44
long: Start a build
55
usage: docker buildx build [OPTIONS] PATH | URL | -

0 commit comments

Comments
 (0)