Files
docker-cli/cli/command/registry/search.go
Sebastiaan van Stijn aaa912c9f7 move commonly used top-level commands to the top of --help
This adds a new annotation to commands that are known to be frequently
used, and allows setting a custom weight/order for these commands to
influence in what order they appear in the --help output.

I'm not entirely happy with the implementation (we could at least use
some helpers for this, and/or make it more generic to group commands
in output), but it could be a start.

For now, limiting this to only be used for the top-level --help, but
we can expand this to subcommands as well if we think it makes sense
to highlight "common" / "commonly used" commands.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2022-04-08 16:55:41 +02:00

87 lines
2.2 KiB
Go

package registry
import (
"context"
"github.com/docker/cli/cli"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/command/formatter"
"github.com/docker/cli/opts"
"github.com/docker/docker/api/types"
"github.com/docker/docker/registry"
"github.com/spf13/cobra"
)
type searchOptions struct {
format string
term string
noTrunc bool
limit int
filter opts.FilterOpt
}
// NewSearchCommand creates a new `docker search` command
func NewSearchCommand(dockerCli command.Cli) *cobra.Command {
options := searchOptions{filter: opts.NewFilterOpt()}
cmd := &cobra.Command{
Use: "search [OPTIONS] TERM",
Short: "Search Docker Hub for images",
Args: cli.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
options.term = args[0]
return runSearch(dockerCli, options)
},
Annotations: map[string]string{
"category-top": "10",
},
}
flags := cmd.Flags()
flags.BoolVar(&options.noTrunc, "no-trunc", false, "Don't truncate output")
flags.VarP(&options.filter, "filter", "f", "Filter output based on conditions provided")
flags.IntVar(&options.limit, "limit", 0, "Max number of search results")
flags.StringVar(&options.format, "format", "", "Pretty-print search using a Go template")
return cmd
}
func runSearch(dockerCli command.Cli, options searchOptions) error {
indexInfo, err := registry.ParseSearchIndexInfo(options.term)
if err != nil {
return err
}
ctx := context.Background()
authConfig := command.ResolveAuthConfig(ctx, dockerCli, indexInfo)
requestPrivilege := command.RegistryAuthenticationPrivilegedFunc(dockerCli, indexInfo, "search")
encodedAuth, err := command.EncodeAuthToBase64(authConfig)
if err != nil {
return err
}
searchOptions := types.ImageSearchOptions{
RegistryAuth: encodedAuth,
PrivilegeFunc: requestPrivilege,
Filters: options.filter.Value(),
Limit: options.limit,
}
clnt := dockerCli.Client()
results, err := clnt.ImageSearch(ctx, options.term, searchOptions)
if err != nil {
return err
}
searchCtx := formatter.Context{
Output: dockerCli.Out(),
Format: NewSearchFormat(options.format),
Trunc: !options.noTrunc,
}
return SearchWrite(searchCtx, results)
}