repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
docker/cli
cli/command/stack/remove.go
RunRemove
func RunRemove(dockerCli command.Cli, flags *pflag.FlagSet, commonOrchestrator command.Orchestrator, opts options.Remove) error { return runOrchestratedCommand(dockerCli, flags, commonOrchestrator, func() error { return swarm.RunRemove(dockerCli, opts) }, func(kli *kubernetes.KubeCli) error { return kubernetes.RunRemove(kli, opts) }) }
go
func RunRemove(dockerCli command.Cli, flags *pflag.FlagSet, commonOrchestrator command.Orchestrator, opts options.Remove) error { return runOrchestratedCommand(dockerCli, flags, commonOrchestrator, func() error { return swarm.RunRemove(dockerCli, opts) }, func(kli *kubernetes.KubeCli) error { return kubernetes.RunRemove(kli, opts) }) }
[ "func", "RunRemove", "(", "dockerCli", "command", ".", "Cli", ",", "flags", "*", "pflag", ".", "FlagSet", ",", "commonOrchestrator", "command", ".", "Orchestrator", ",", "opts", "options", ".", "Remove", ")", "error", "{", "return", "runOrchestratedCommand", "(", "dockerCli", ",", "flags", ",", "commonOrchestrator", ",", "func", "(", ")", "error", "{", "return", "swarm", ".", "RunRemove", "(", "dockerCli", ",", "opts", ")", "}", ",", "func", "(", "kli", "*", "kubernetes", ".", "KubeCli", ")", "error", "{", "return", "kubernetes", ".", "RunRemove", "(", "kli", ",", "opts", ")", "}", ")", "\n", "}" ]
// RunRemove performs a stack remove against the specified orchestrator
[ "RunRemove", "performs", "a", "stack", "remove", "against", "the", "specified", "orchestrator" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/stack/remove.go#L35-L39
train
docker/cli
cli/command/image/save.go
NewSaveCommand
func NewSaveCommand(dockerCli command.Cli) *cobra.Command { var opts saveOptions cmd := &cobra.Command{ Use: "save [OPTIONS] IMAGE [IMAGE...]", Short: "Save one or more images to a tar archive (streamed to STDOUT by default)", Args: cli.RequiresMinArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.images = args return RunSave(dockerCli, opts) }, } flags := cmd.Flags() flags.StringVarP(&opts.output, "output", "o", "", "Write to a file, instead of STDOUT") return cmd }
go
func NewSaveCommand(dockerCli command.Cli) *cobra.Command { var opts saveOptions cmd := &cobra.Command{ Use: "save [OPTIONS] IMAGE [IMAGE...]", Short: "Save one or more images to a tar archive (streamed to STDOUT by default)", Args: cli.RequiresMinArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.images = args return RunSave(dockerCli, opts) }, } flags := cmd.Flags() flags.StringVarP(&opts.output, "output", "o", "", "Write to a file, instead of STDOUT") return cmd }
[ "func", "NewSaveCommand", "(", "dockerCli", "command", ".", "Cli", ")", "*", "cobra", ".", "Command", "{", "var", "opts", "saveOptions", "\n\n", "cmd", ":=", "&", "cobra", ".", "Command", "{", "Use", ":", "\"", "\"", ",", "Short", ":", "\"", "\"", ",", "Args", ":", "cli", ".", "RequiresMinArgs", "(", "1", ")", ",", "RunE", ":", "func", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "error", "{", "opts", ".", "images", "=", "args", "\n", "return", "RunSave", "(", "dockerCli", ",", "opts", ")", "\n", "}", ",", "}", "\n\n", "flags", ":=", "cmd", ".", "Flags", "(", ")", "\n\n", "flags", ".", "StringVarP", "(", "&", "opts", ".", "output", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "return", "cmd", "\n", "}" ]
// NewSaveCommand creates a new `docker save` command
[ "NewSaveCommand", "creates", "a", "new", "docker", "save", "command" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/image/save.go#L19-L37
train
docker/cli
cli/command/image/save.go
RunSave
func RunSave(dockerCli command.Cli, opts saveOptions) error { if opts.output == "" && dockerCli.Out().IsTerminal() { return errors.New("cowardly refusing to save to a terminal. Use the -o flag or redirect") } if err := command.ValidateOutputPath(opts.output); err != nil { return errors.Wrap(err, "failed to save image") } responseBody, err := dockerCli.Client().ImageSave(context.Background(), opts.images) if err != nil { return err } defer responseBody.Close() if opts.output == "" { _, err := io.Copy(dockerCli.Out(), responseBody) return err } return command.CopyToFile(opts.output, responseBody) }
go
func RunSave(dockerCli command.Cli, opts saveOptions) error { if opts.output == "" && dockerCli.Out().IsTerminal() { return errors.New("cowardly refusing to save to a terminal. Use the -o flag or redirect") } if err := command.ValidateOutputPath(opts.output); err != nil { return errors.Wrap(err, "failed to save image") } responseBody, err := dockerCli.Client().ImageSave(context.Background(), opts.images) if err != nil { return err } defer responseBody.Close() if opts.output == "" { _, err := io.Copy(dockerCli.Out(), responseBody) return err } return command.CopyToFile(opts.output, responseBody) }
[ "func", "RunSave", "(", "dockerCli", "command", ".", "Cli", ",", "opts", "saveOptions", ")", "error", "{", "if", "opts", ".", "output", "==", "\"", "\"", "&&", "dockerCli", ".", "Out", "(", ")", ".", "IsTerminal", "(", ")", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "err", ":=", "command", ".", "ValidateOutputPath", "(", "opts", ".", "output", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "responseBody", ",", "err", ":=", "dockerCli", ".", "Client", "(", ")", ".", "ImageSave", "(", "context", ".", "Background", "(", ")", ",", "opts", ".", "images", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "responseBody", ".", "Close", "(", ")", "\n\n", "if", "opts", ".", "output", "==", "\"", "\"", "{", "_", ",", "err", ":=", "io", ".", "Copy", "(", "dockerCli", ".", "Out", "(", ")", ",", "responseBody", ")", "\n", "return", "err", "\n", "}", "\n\n", "return", "command", ".", "CopyToFile", "(", "opts", ".", "output", ",", "responseBody", ")", "\n", "}" ]
// RunSave performs a save against the engine based on the specified options
[ "RunSave", "performs", "a", "save", "against", "the", "engine", "based", "on", "the", "specified", "options" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/image/save.go#L40-L61
train
docker/cli
cmd/docker/docker.go
findCommand
func findCommand(cmd *cobra.Command, commands []string) bool { if cmd == nil { return false } for _, c := range commands { if c == cmd.Name() { return true } } return findCommand(cmd.Parent(), commands) }
go
func findCommand(cmd *cobra.Command, commands []string) bool { if cmd == nil { return false } for _, c := range commands { if c == cmd.Name() { return true } } return findCommand(cmd.Parent(), commands) }
[ "func", "findCommand", "(", "cmd", "*", "cobra", ".", "Command", ",", "commands", "[", "]", "string", ")", "bool", "{", "if", "cmd", "==", "nil", "{", "return", "false", "\n", "}", "\n", "for", "_", ",", "c", ":=", "range", "commands", "{", "if", "c", "==", "cmd", ".", "Name", "(", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "findCommand", "(", "cmd", ".", "Parent", "(", ")", ",", "commands", ")", "\n", "}" ]
// Checks if a command or one of its ancestors is in the list
[ "Checks", "if", "a", "command", "or", "one", "of", "its", "ancestors", "is", "in", "the", "list" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cmd/docker/docker.go#L371-L381
train
docker/cli
cmd/docker/docker.go
hasTags
func hasTags(cmd *cobra.Command) bool { for curr := cmd; curr != nil; curr = curr.Parent() { if len(curr.Annotations) > 0 { return true } } return false }
go
func hasTags(cmd *cobra.Command) bool { for curr := cmd; curr != nil; curr = curr.Parent() { if len(curr.Annotations) > 0 { return true } } return false }
[ "func", "hasTags", "(", "cmd", "*", "cobra", ".", "Command", ")", "bool", "{", "for", "curr", ":=", "cmd", ";", "curr", "!=", "nil", ";", "curr", "=", "curr", ".", "Parent", "(", ")", "{", "if", "len", "(", "curr", ".", "Annotations", ")", ">", "0", "{", "return", "true", "\n", "}", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// hasTags return true if any of the command's parents has tags
[ "hasTags", "return", "true", "if", "any", "of", "the", "command", "s", "parents", "has", "tags" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cmd/docker/docker.go#L470-L478
train
docker/cli
docs/yaml/generate.go
visitAll
func visitAll(root *cobra.Command, fn func(*cobra.Command)) { for _, cmd := range root.Commands() { visitAll(cmd, fn) } fn(root) }
go
func visitAll(root *cobra.Command, fn func(*cobra.Command)) { for _, cmd := range root.Commands() { visitAll(cmd, fn) } fn(root) }
[ "func", "visitAll", "(", "root", "*", "cobra", ".", "Command", ",", "fn", "func", "(", "*", "cobra", ".", "Command", ")", ")", "{", "for", "_", ",", "cmd", ":=", "range", "root", ".", "Commands", "(", ")", "{", "visitAll", "(", "cmd", ",", "fn", ")", "\n", "}", "\n", "fn", "(", "root", ")", "\n", "}" ]
// visitAll will traverse all commands from the root. // This is different from the VisitAll of cobra.Command where only parents // are checked.
[ "visitAll", "will", "traverse", "all", "commands", "from", "the", "root", ".", "This", "is", "different", "from", "the", "VisitAll", "of", "cobra", ".", "Command", "where", "only", "parents", "are", "checked", "." ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/docs/yaml/generate.go#L46-L51
train
docker/cli
cli/command/container/start.go
NewStartCommand
func NewStartCommand(dockerCli command.Cli) *cobra.Command { var opts startOptions cmd := &cobra.Command{ Use: "start [OPTIONS] CONTAINER [CONTAINER...]", Short: "Start one or more stopped containers", Args: cli.RequiresMinArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.containers = args return runStart(dockerCli, &opts) }, } flags := cmd.Flags() flags.BoolVarP(&opts.attach, "attach", "a", false, "Attach STDOUT/STDERR and forward signals") flags.BoolVarP(&opts.openStdin, "interactive", "i", false, "Attach container's STDIN") flags.StringVar(&opts.detachKeys, "detach-keys", "", "Override the key sequence for detaching a container") flags.StringVar(&opts.checkpoint, "checkpoint", "", "Restore from this checkpoint") flags.SetAnnotation("checkpoint", "experimental", nil) flags.SetAnnotation("checkpoint", "ostype", []string{"linux"}) flags.StringVar(&opts.checkpointDir, "checkpoint-dir", "", "Use a custom checkpoint storage directory") flags.SetAnnotation("checkpoint-dir", "experimental", nil) flags.SetAnnotation("checkpoint-dir", "ostype", []string{"linux"}) return cmd }
go
func NewStartCommand(dockerCli command.Cli) *cobra.Command { var opts startOptions cmd := &cobra.Command{ Use: "start [OPTIONS] CONTAINER [CONTAINER...]", Short: "Start one or more stopped containers", Args: cli.RequiresMinArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.containers = args return runStart(dockerCli, &opts) }, } flags := cmd.Flags() flags.BoolVarP(&opts.attach, "attach", "a", false, "Attach STDOUT/STDERR and forward signals") flags.BoolVarP(&opts.openStdin, "interactive", "i", false, "Attach container's STDIN") flags.StringVar(&opts.detachKeys, "detach-keys", "", "Override the key sequence for detaching a container") flags.StringVar(&opts.checkpoint, "checkpoint", "", "Restore from this checkpoint") flags.SetAnnotation("checkpoint", "experimental", nil) flags.SetAnnotation("checkpoint", "ostype", []string{"linux"}) flags.StringVar(&opts.checkpointDir, "checkpoint-dir", "", "Use a custom checkpoint storage directory") flags.SetAnnotation("checkpoint-dir", "experimental", nil) flags.SetAnnotation("checkpoint-dir", "ostype", []string{"linux"}) return cmd }
[ "func", "NewStartCommand", "(", "dockerCli", "command", ".", "Cli", ")", "*", "cobra", ".", "Command", "{", "var", "opts", "startOptions", "\n\n", "cmd", ":=", "&", "cobra", ".", "Command", "{", "Use", ":", "\"", "\"", ",", "Short", ":", "\"", "\"", ",", "Args", ":", "cli", ".", "RequiresMinArgs", "(", "1", ")", ",", "RunE", ":", "func", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "error", "{", "opts", ".", "containers", "=", "args", "\n", "return", "runStart", "(", "dockerCli", ",", "&", "opts", ")", "\n", "}", ",", "}", "\n\n", "flags", ":=", "cmd", ".", "Flags", "(", ")", "\n", "flags", ".", "BoolVarP", "(", "&", "opts", ".", "attach", ",", "\"", "\"", ",", "\"", "\"", ",", "false", ",", "\"", "\"", ")", "\n", "flags", ".", "BoolVarP", "(", "&", "opts", ".", "openStdin", ",", "\"", "\"", ",", "\"", "\"", ",", "false", ",", "\"", "\"", ")", "\n", "flags", ".", "StringVar", "(", "&", "opts", ".", "detachKeys", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "flags", ".", "StringVar", "(", "&", "opts", ".", "checkpoint", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "flags", ".", "SetAnnotation", "(", "\"", "\"", ",", "\"", "\"", ",", "nil", ")", "\n", "flags", ".", "SetAnnotation", "(", "\"", "\"", ",", "\"", "\"", ",", "[", "]", "string", "{", "\"", "\"", "}", ")", "\n", "flags", ".", "StringVar", "(", "&", "opts", ".", "checkpointDir", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "flags", ".", "SetAnnotation", "(", "\"", "\"", ",", "\"", "\"", ",", "nil", ")", "\n", "flags", ".", "SetAnnotation", "(", "\"", "\"", ",", "\"", "\"", ",", "[", "]", "string", "{", "\"", "\"", "}", ")", "\n", "return", "cmd", "\n", "}" ]
// NewStartCommand creates a new cobra.Command for `docker start`
[ "NewStartCommand", "creates", "a", "new", "cobra", ".", "Command", "for", "docker", "start" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/container/start.go#L30-L55
train
docker/cli
cli/compose/template/template.go
SubstituteWith
func SubstituteWith(template string, mapping Mapping, pattern *regexp.Regexp, subsFuncs ...SubstituteFunc) (string, error) { var err error result := pattern.ReplaceAllStringFunc(template, func(substring string) string { matches := pattern.FindStringSubmatch(substring) groups := matchGroups(matches, pattern) if escaped := groups["escaped"]; escaped != "" { return escaped } substitution := groups["named"] if substitution == "" { substitution = groups["braced"] } if substitution == "" { err = &InvalidTemplateError{Template: template} return "" } for _, f := range subsFuncs { var ( value string applied bool ) value, applied, err = f(substitution, mapping) if err != nil { return "" } if !applied { continue } return value } value, _ := mapping(substitution) return value }) return result, err }
go
func SubstituteWith(template string, mapping Mapping, pattern *regexp.Regexp, subsFuncs ...SubstituteFunc) (string, error) { var err error result := pattern.ReplaceAllStringFunc(template, func(substring string) string { matches := pattern.FindStringSubmatch(substring) groups := matchGroups(matches, pattern) if escaped := groups["escaped"]; escaped != "" { return escaped } substitution := groups["named"] if substitution == "" { substitution = groups["braced"] } if substitution == "" { err = &InvalidTemplateError{Template: template} return "" } for _, f := range subsFuncs { var ( value string applied bool ) value, applied, err = f(substitution, mapping) if err != nil { return "" } if !applied { continue } return value } value, _ := mapping(substitution) return value }) return result, err }
[ "func", "SubstituteWith", "(", "template", "string", ",", "mapping", "Mapping", ",", "pattern", "*", "regexp", ".", "Regexp", ",", "subsFuncs", "...", "SubstituteFunc", ")", "(", "string", ",", "error", ")", "{", "var", "err", "error", "\n", "result", ":=", "pattern", ".", "ReplaceAllStringFunc", "(", "template", ",", "func", "(", "substring", "string", ")", "string", "{", "matches", ":=", "pattern", ".", "FindStringSubmatch", "(", "substring", ")", "\n", "groups", ":=", "matchGroups", "(", "matches", ",", "pattern", ")", "\n", "if", "escaped", ":=", "groups", "[", "\"", "\"", "]", ";", "escaped", "!=", "\"", "\"", "{", "return", "escaped", "\n", "}", "\n\n", "substitution", ":=", "groups", "[", "\"", "\"", "]", "\n", "if", "substitution", "==", "\"", "\"", "{", "substitution", "=", "groups", "[", "\"", "\"", "]", "\n", "}", "\n\n", "if", "substitution", "==", "\"", "\"", "{", "err", "=", "&", "InvalidTemplateError", "{", "Template", ":", "template", "}", "\n", "return", "\"", "\"", "\n", "}", "\n\n", "for", "_", ",", "f", ":=", "range", "subsFuncs", "{", "var", "(", "value", "string", "\n", "applied", "bool", "\n", ")", "\n", "value", ",", "applied", ",", "err", "=", "f", "(", "substitution", ",", "mapping", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "if", "!", "applied", "{", "continue", "\n", "}", "\n", "return", "value", "\n", "}", "\n\n", "value", ",", "_", ":=", "mapping", "(", "substitution", ")", "\n", "return", "value", "\n", "}", ")", "\n\n", "return", "result", ",", "err", "\n", "}" ]
// SubstituteWith subsitute variables in the string with their values. // It accepts additional substitute function.
[ "SubstituteWith", "subsitute", "variables", "in", "the", "string", "with", "their", "values", ".", "It", "accepts", "additional", "substitute", "function", "." ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/compose/template/template.go#L50-L89
train
docker/cli
cli/compose/template/template.go
Substitute
func Substitute(template string, mapping Mapping) (string, error) { return SubstituteWith(template, mapping, defaultPattern, DefaultSubstituteFuncs...) }
go
func Substitute(template string, mapping Mapping) (string, error) { return SubstituteWith(template, mapping, defaultPattern, DefaultSubstituteFuncs...) }
[ "func", "Substitute", "(", "template", "string", ",", "mapping", "Mapping", ")", "(", "string", ",", "error", ")", "{", "return", "SubstituteWith", "(", "template", ",", "mapping", ",", "defaultPattern", ",", "DefaultSubstituteFuncs", "...", ")", "\n", "}" ]
// Substitute variables in the string with their values
[ "Substitute", "variables", "in", "the", "string", "with", "their", "values" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/compose/template/template.go#L92-L94
train
docker/cli
cli/command/trust/common.go
lookupTrustInfo
func lookupTrustInfo(cli command.Cli, remote string) ([]trustTagRow, []client.RoleWithSignatures, []data.Role, error) { ctx := context.Background() imgRefAndAuth, err := trust.GetImageReferencesAndAuth(ctx, nil, image.AuthResolver(cli), remote) if err != nil { return []trustTagRow{}, []client.RoleWithSignatures{}, []data.Role{}, err } tag := imgRefAndAuth.Tag() notaryRepo, err := cli.NotaryClient(imgRefAndAuth, trust.ActionsPullOnly) if err != nil { return []trustTagRow{}, []client.RoleWithSignatures{}, []data.Role{}, trust.NotaryError(imgRefAndAuth.Reference().Name(), err) } if err = clearChangeList(notaryRepo); err != nil { return []trustTagRow{}, []client.RoleWithSignatures{}, []data.Role{}, err } defer clearChangeList(notaryRepo) // Retrieve all released signatures, match them, and pretty print them allSignedTargets, err := notaryRepo.GetAllTargetMetadataByName(tag) if err != nil { logrus.Debug(trust.NotaryError(remote, err)) // print an empty table if we don't have signed targets, but have an initialized notary repo if _, ok := err.(client.ErrNoSuchTarget); !ok { return []trustTagRow{}, []client.RoleWithSignatures{}, []data.Role{}, fmt.Errorf("No signatures or cannot access %s", remote) } } signatureRows := matchReleasedSignatures(allSignedTargets) // get the administrative roles adminRolesWithSigs, err := notaryRepo.ListRoles() if err != nil { return []trustTagRow{}, []client.RoleWithSignatures{}, []data.Role{}, fmt.Errorf("No signers for %s", remote) } // get delegation roles with the canonical key IDs delegationRoles, err := notaryRepo.GetDelegationRoles() if err != nil { logrus.Debugf("no delegation roles found, or error fetching them for %s: %v", remote, err) } return signatureRows, adminRolesWithSigs, delegationRoles, nil }
go
func lookupTrustInfo(cli command.Cli, remote string) ([]trustTagRow, []client.RoleWithSignatures, []data.Role, error) { ctx := context.Background() imgRefAndAuth, err := trust.GetImageReferencesAndAuth(ctx, nil, image.AuthResolver(cli), remote) if err != nil { return []trustTagRow{}, []client.RoleWithSignatures{}, []data.Role{}, err } tag := imgRefAndAuth.Tag() notaryRepo, err := cli.NotaryClient(imgRefAndAuth, trust.ActionsPullOnly) if err != nil { return []trustTagRow{}, []client.RoleWithSignatures{}, []data.Role{}, trust.NotaryError(imgRefAndAuth.Reference().Name(), err) } if err = clearChangeList(notaryRepo); err != nil { return []trustTagRow{}, []client.RoleWithSignatures{}, []data.Role{}, err } defer clearChangeList(notaryRepo) // Retrieve all released signatures, match them, and pretty print them allSignedTargets, err := notaryRepo.GetAllTargetMetadataByName(tag) if err != nil { logrus.Debug(trust.NotaryError(remote, err)) // print an empty table if we don't have signed targets, but have an initialized notary repo if _, ok := err.(client.ErrNoSuchTarget); !ok { return []trustTagRow{}, []client.RoleWithSignatures{}, []data.Role{}, fmt.Errorf("No signatures or cannot access %s", remote) } } signatureRows := matchReleasedSignatures(allSignedTargets) // get the administrative roles adminRolesWithSigs, err := notaryRepo.ListRoles() if err != nil { return []trustTagRow{}, []client.RoleWithSignatures{}, []data.Role{}, fmt.Errorf("No signers for %s", remote) } // get delegation roles with the canonical key IDs delegationRoles, err := notaryRepo.GetDelegationRoles() if err != nil { logrus.Debugf("no delegation roles found, or error fetching them for %s: %v", remote, err) } return signatureRows, adminRolesWithSigs, delegationRoles, nil }
[ "func", "lookupTrustInfo", "(", "cli", "command", ".", "Cli", ",", "remote", "string", ")", "(", "[", "]", "trustTagRow", ",", "[", "]", "client", ".", "RoleWithSignatures", ",", "[", "]", "data", ".", "Role", ",", "error", ")", "{", "ctx", ":=", "context", ".", "Background", "(", ")", "\n", "imgRefAndAuth", ",", "err", ":=", "trust", ".", "GetImageReferencesAndAuth", "(", "ctx", ",", "nil", ",", "image", ".", "AuthResolver", "(", "cli", ")", ",", "remote", ")", "\n", "if", "err", "!=", "nil", "{", "return", "[", "]", "trustTagRow", "{", "}", ",", "[", "]", "client", ".", "RoleWithSignatures", "{", "}", ",", "[", "]", "data", ".", "Role", "{", "}", ",", "err", "\n", "}", "\n", "tag", ":=", "imgRefAndAuth", ".", "Tag", "(", ")", "\n", "notaryRepo", ",", "err", ":=", "cli", ".", "NotaryClient", "(", "imgRefAndAuth", ",", "trust", ".", "ActionsPullOnly", ")", "\n", "if", "err", "!=", "nil", "{", "return", "[", "]", "trustTagRow", "{", "}", ",", "[", "]", "client", ".", "RoleWithSignatures", "{", "}", ",", "[", "]", "data", ".", "Role", "{", "}", ",", "trust", ".", "NotaryError", "(", "imgRefAndAuth", ".", "Reference", "(", ")", ".", "Name", "(", ")", ",", "err", ")", "\n", "}", "\n\n", "if", "err", "=", "clearChangeList", "(", "notaryRepo", ")", ";", "err", "!=", "nil", "{", "return", "[", "]", "trustTagRow", "{", "}", ",", "[", "]", "client", ".", "RoleWithSignatures", "{", "}", ",", "[", "]", "data", ".", "Role", "{", "}", ",", "err", "\n", "}", "\n", "defer", "clearChangeList", "(", "notaryRepo", ")", "\n\n", "// Retrieve all released signatures, match them, and pretty print them", "allSignedTargets", ",", "err", ":=", "notaryRepo", ".", "GetAllTargetMetadataByName", "(", "tag", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "Debug", "(", "trust", ".", "NotaryError", "(", "remote", ",", "err", ")", ")", "\n", "// print an empty table if we don't have signed targets, but have an initialized notary repo", "if", "_", ",", "ok", ":=", "err", ".", "(", "client", ".", "ErrNoSuchTarget", ")", ";", "!", "ok", "{", "return", "[", "]", "trustTagRow", "{", "}", ",", "[", "]", "client", ".", "RoleWithSignatures", "{", "}", ",", "[", "]", "data", ".", "Role", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "remote", ")", "\n", "}", "\n", "}", "\n", "signatureRows", ":=", "matchReleasedSignatures", "(", "allSignedTargets", ")", "\n\n", "// get the administrative roles", "adminRolesWithSigs", ",", "err", ":=", "notaryRepo", ".", "ListRoles", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "[", "]", "trustTagRow", "{", "}", ",", "[", "]", "client", ".", "RoleWithSignatures", "{", "}", ",", "[", "]", "data", ".", "Role", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "remote", ")", "\n", "}", "\n\n", "// get delegation roles with the canonical key IDs", "delegationRoles", ",", "err", ":=", "notaryRepo", ".", "GetDelegationRoles", "(", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "Debugf", "(", "\"", "\"", ",", "remote", ",", "err", ")", "\n", "}", "\n\n", "return", "signatureRows", ",", "adminRolesWithSigs", ",", "delegationRoles", ",", "nil", "\n", "}" ]
// lookupTrustInfo returns processed signature and role information about a notary repository. // This information is to be pretty printed or serialized into a machine-readable format.
[ "lookupTrustInfo", "returns", "processed", "signature", "and", "role", "information", "about", "a", "notary", "repository", ".", "This", "information", "is", "to", "be", "pretty", "printed", "or", "serialized", "into", "a", "machine", "-", "readable", "format", "." ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/trust/common.go#L54-L95
train
docker/cli
opts/hosts.go
ParseHost
func ParseHost(defaultToTLS bool, val string) (string, error) { host := strings.TrimSpace(val) if host == "" { if defaultToTLS { host = DefaultTLSHost } else { host = DefaultHost } } else { var err error host, err = parseDockerDaemonHost(host) if err != nil { return val, err } } return host, nil }
go
func ParseHost(defaultToTLS bool, val string) (string, error) { host := strings.TrimSpace(val) if host == "" { if defaultToTLS { host = DefaultTLSHost } else { host = DefaultHost } } else { var err error host, err = parseDockerDaemonHost(host) if err != nil { return val, err } } return host, nil }
[ "func", "ParseHost", "(", "defaultToTLS", "bool", ",", "val", "string", ")", "(", "string", ",", "error", ")", "{", "host", ":=", "strings", ".", "TrimSpace", "(", "val", ")", "\n", "if", "host", "==", "\"", "\"", "{", "if", "defaultToTLS", "{", "host", "=", "DefaultTLSHost", "\n", "}", "else", "{", "host", "=", "DefaultHost", "\n", "}", "\n", "}", "else", "{", "var", "err", "error", "\n", "host", ",", "err", "=", "parseDockerDaemonHost", "(", "host", ")", "\n", "if", "err", "!=", "nil", "{", "return", "val", ",", "err", "\n", "}", "\n", "}", "\n", "return", "host", ",", "nil", "\n", "}" ]
// ParseHost and set defaults for a Daemon host string
[ "ParseHost", "and", "set", "defaults", "for", "a", "Daemon", "host", "string" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/opts/hosts.go#L45-L61
train
docker/cli
cli/command/cli.go
ShowHelp
func ShowHelp(err io.Writer) func(*cobra.Command, []string) error { return func(cmd *cobra.Command, args []string) error { cmd.SetOutput(err) cmd.HelpFunc()(cmd, args) return nil } }
go
func ShowHelp(err io.Writer) func(*cobra.Command, []string) error { return func(cmd *cobra.Command, args []string) error { cmd.SetOutput(err) cmd.HelpFunc()(cmd, args) return nil } }
[ "func", "ShowHelp", "(", "err", "io", ".", "Writer", ")", "func", "(", "*", "cobra", ".", "Command", ",", "[", "]", "string", ")", "error", "{", "return", "func", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "error", "{", "cmd", ".", "SetOutput", "(", "err", ")", "\n", "cmd", ".", "HelpFunc", "(", ")", "(", "cmd", ",", "args", ")", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// ShowHelp shows the command help.
[ "ShowHelp", "shows", "the", "command", "help", "." ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/cli.go#L120-L126
train
docker/cli
cli/command/cli.go
BuildKitEnabled
func BuildKitEnabled(si ServerInfo) (bool, error) { buildkitEnabled := si.BuildkitVersion == types.BuilderBuildKit if buildkitEnv := os.Getenv("DOCKER_BUILDKIT"); buildkitEnv != "" { var err error buildkitEnabled, err = strconv.ParseBool(buildkitEnv) if err != nil { return false, errors.Wrap(err, "DOCKER_BUILDKIT environment variable expects boolean value") } } return buildkitEnabled, nil }
go
func BuildKitEnabled(si ServerInfo) (bool, error) { buildkitEnabled := si.BuildkitVersion == types.BuilderBuildKit if buildkitEnv := os.Getenv("DOCKER_BUILDKIT"); buildkitEnv != "" { var err error buildkitEnabled, err = strconv.ParseBool(buildkitEnv) if err != nil { return false, errors.Wrap(err, "DOCKER_BUILDKIT environment variable expects boolean value") } } return buildkitEnabled, nil }
[ "func", "BuildKitEnabled", "(", "si", "ServerInfo", ")", "(", "bool", ",", "error", ")", "{", "buildkitEnabled", ":=", "si", ".", "BuildkitVersion", "==", "types", ".", "BuilderBuildKit", "\n", "if", "buildkitEnv", ":=", "os", ".", "Getenv", "(", "\"", "\"", ")", ";", "buildkitEnv", "!=", "\"", "\"", "{", "var", "err", "error", "\n", "buildkitEnabled", ",", "err", "=", "strconv", ".", "ParseBool", "(", "buildkitEnv", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "return", "buildkitEnabled", ",", "nil", "\n", "}" ]
// BuildKitEnabled returns whether buildkit is enabled either through a daemon setting // or otherwise the client-side DOCKER_BUILDKIT environment variable
[ "BuildKitEnabled", "returns", "whether", "buildkit", "is", "enabled", "either", "through", "a", "daemon", "setting", "or", "otherwise", "the", "client", "-", "side", "DOCKER_BUILDKIT", "environment", "variable" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/cli.go#L152-L162
train
docker/cli
cli/command/cli.go
ManifestStore
func (cli *DockerCli) ManifestStore() manifeststore.Store { // TODO: support override default location from config file return manifeststore.NewStore(filepath.Join(config.Dir(), "manifests")) }
go
func (cli *DockerCli) ManifestStore() manifeststore.Store { // TODO: support override default location from config file return manifeststore.NewStore(filepath.Join(config.Dir(), "manifests")) }
[ "func", "(", "cli", "*", "DockerCli", ")", "ManifestStore", "(", ")", "manifeststore", ".", "Store", "{", "// TODO: support override default location from config file", "return", "manifeststore", ".", "NewStore", "(", "filepath", ".", "Join", "(", "config", ".", "Dir", "(", ")", ",", "\"", "\"", ")", ")", "\n", "}" ]
// ManifestStore returns a store for local manifests
[ "ManifestStore", "returns", "a", "store", "for", "local", "manifests" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/cli.go#L165-L168
train
docker/cli
cli/command/cli.go
RegistryClient
func (cli *DockerCli) RegistryClient(allowInsecure bool) registryclient.RegistryClient { resolver := func(ctx context.Context, index *registrytypes.IndexInfo) types.AuthConfig { return ResolveAuthConfig(ctx, cli, index) } return registryclient.NewRegistryClient(resolver, UserAgent(), allowInsecure) }
go
func (cli *DockerCli) RegistryClient(allowInsecure bool) registryclient.RegistryClient { resolver := func(ctx context.Context, index *registrytypes.IndexInfo) types.AuthConfig { return ResolveAuthConfig(ctx, cli, index) } return registryclient.NewRegistryClient(resolver, UserAgent(), allowInsecure) }
[ "func", "(", "cli", "*", "DockerCli", ")", "RegistryClient", "(", "allowInsecure", "bool", ")", "registryclient", ".", "RegistryClient", "{", "resolver", ":=", "func", "(", "ctx", "context", ".", "Context", ",", "index", "*", "registrytypes", ".", "IndexInfo", ")", "types", ".", "AuthConfig", "{", "return", "ResolveAuthConfig", "(", "ctx", ",", "cli", ",", "index", ")", "\n", "}", "\n", "return", "registryclient", ".", "NewRegistryClient", "(", "resolver", ",", "UserAgent", "(", ")", ",", "allowInsecure", ")", "\n", "}" ]
// RegistryClient returns a client for communicating with a Docker distribution // registry
[ "RegistryClient", "returns", "a", "client", "for", "communicating", "with", "a", "Docker", "distribution", "registry" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/cli.go#L172-L177
train
docker/cli
cli/command/cli.go
WithInitializeClient
func WithInitializeClient(makeClient func(dockerCli *DockerCli) (client.APIClient, error)) InitializeOpt { return func(dockerCli *DockerCli) error { var err error dockerCli.client, err = makeClient(dockerCli) return err } }
go
func WithInitializeClient(makeClient func(dockerCli *DockerCli) (client.APIClient, error)) InitializeOpt { return func(dockerCli *DockerCli) error { var err error dockerCli.client, err = makeClient(dockerCli) return err } }
[ "func", "WithInitializeClient", "(", "makeClient", "func", "(", "dockerCli", "*", "DockerCli", ")", "(", "client", ".", "APIClient", ",", "error", ")", ")", "InitializeOpt", "{", "return", "func", "(", "dockerCli", "*", "DockerCli", ")", "error", "{", "var", "err", "error", "\n", "dockerCli", ".", "client", ",", "err", "=", "makeClient", "(", "dockerCli", ")", "\n", "return", "err", "\n", "}", "\n", "}" ]
// WithInitializeClient is passed to DockerCli.Initialize by callers who wish to set a particular API Client for use by the CLI.
[ "WithInitializeClient", "is", "passed", "to", "DockerCli", ".", "Initialize", "by", "callers", "who", "wish", "to", "set", "a", "particular", "API", "Client", "for", "use", "by", "the", "CLI", "." ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/cli.go#L183-L189
train
docker/cli
cli/command/cli.go
Initialize
func (cli *DockerCli) Initialize(opts *cliflags.ClientOptions, ops ...InitializeOpt) error { var err error for _, o := range ops { if err := o(cli); err != nil { return err } } cliflags.SetLogLevel(opts.Common.LogLevel) if opts.ConfigDir != "" { cliconfig.SetDir(opts.ConfigDir) } if opts.Common.Debug { debug.Enable() } cli.configFile = cliconfig.LoadDefaultConfigFile(cli.err) baseContextSore := store.New(cliconfig.ContextStoreDir(), cli.contextStoreConfig) cli.contextStore = &ContextStoreWithDefault{ Store: baseContextSore, Resolver: func() (*DefaultContext, error) { return resolveDefaultContext(opts.Common, cli.ConfigFile(), cli.Err()) }, } cli.currentContext, err = resolveContextName(opts.Common, cli.configFile, cli.contextStore) if err != nil { return err } cli.dockerEndpoint, err = resolveDockerEndpoint(cli.contextStore, cli.currentContext) if err != nil { return errors.Wrap(err, "unable to resolve docker endpoint") } if cli.client == nil { cli.client, err = newAPIClientFromEndpoint(cli.dockerEndpoint, cli.configFile) if tlsconfig.IsErrEncryptedKey(err) { passRetriever := passphrase.PromptRetrieverWithInOut(cli.In(), cli.Out(), nil) newClient := func(password string) (client.APIClient, error) { cli.dockerEndpoint.TLSPassword = password return newAPIClientFromEndpoint(cli.dockerEndpoint, cli.configFile) } cli.client, err = getClientWithPassword(passRetriever, newClient) } if err != nil { return err } } var experimentalValue string // Environment variable always overrides configuration if experimentalValue = os.Getenv("DOCKER_CLI_EXPERIMENTAL"); experimentalValue == "" { experimentalValue = cli.configFile.Experimental } hasExperimental, err := isEnabled(experimentalValue) if err != nil { return errors.Wrap(err, "Experimental field") } cli.clientInfo = ClientInfo{ DefaultVersion: cli.client.ClientVersion(), HasExperimental: hasExperimental, } cli.initializeFromClient() return nil }
go
func (cli *DockerCli) Initialize(opts *cliflags.ClientOptions, ops ...InitializeOpt) error { var err error for _, o := range ops { if err := o(cli); err != nil { return err } } cliflags.SetLogLevel(opts.Common.LogLevel) if opts.ConfigDir != "" { cliconfig.SetDir(opts.ConfigDir) } if opts.Common.Debug { debug.Enable() } cli.configFile = cliconfig.LoadDefaultConfigFile(cli.err) baseContextSore := store.New(cliconfig.ContextStoreDir(), cli.contextStoreConfig) cli.contextStore = &ContextStoreWithDefault{ Store: baseContextSore, Resolver: func() (*DefaultContext, error) { return resolveDefaultContext(opts.Common, cli.ConfigFile(), cli.Err()) }, } cli.currentContext, err = resolveContextName(opts.Common, cli.configFile, cli.contextStore) if err != nil { return err } cli.dockerEndpoint, err = resolveDockerEndpoint(cli.contextStore, cli.currentContext) if err != nil { return errors.Wrap(err, "unable to resolve docker endpoint") } if cli.client == nil { cli.client, err = newAPIClientFromEndpoint(cli.dockerEndpoint, cli.configFile) if tlsconfig.IsErrEncryptedKey(err) { passRetriever := passphrase.PromptRetrieverWithInOut(cli.In(), cli.Out(), nil) newClient := func(password string) (client.APIClient, error) { cli.dockerEndpoint.TLSPassword = password return newAPIClientFromEndpoint(cli.dockerEndpoint, cli.configFile) } cli.client, err = getClientWithPassword(passRetriever, newClient) } if err != nil { return err } } var experimentalValue string // Environment variable always overrides configuration if experimentalValue = os.Getenv("DOCKER_CLI_EXPERIMENTAL"); experimentalValue == "" { experimentalValue = cli.configFile.Experimental } hasExperimental, err := isEnabled(experimentalValue) if err != nil { return errors.Wrap(err, "Experimental field") } cli.clientInfo = ClientInfo{ DefaultVersion: cli.client.ClientVersion(), HasExperimental: hasExperimental, } cli.initializeFromClient() return nil }
[ "func", "(", "cli", "*", "DockerCli", ")", "Initialize", "(", "opts", "*", "cliflags", ".", "ClientOptions", ",", "ops", "...", "InitializeOpt", ")", "error", "{", "var", "err", "error", "\n\n", "for", "_", ",", "o", ":=", "range", "ops", "{", "if", "err", ":=", "o", "(", "cli", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "cliflags", ".", "SetLogLevel", "(", "opts", ".", "Common", ".", "LogLevel", ")", "\n\n", "if", "opts", ".", "ConfigDir", "!=", "\"", "\"", "{", "cliconfig", ".", "SetDir", "(", "opts", ".", "ConfigDir", ")", "\n", "}", "\n\n", "if", "opts", ".", "Common", ".", "Debug", "{", "debug", ".", "Enable", "(", ")", "\n", "}", "\n\n", "cli", ".", "configFile", "=", "cliconfig", ".", "LoadDefaultConfigFile", "(", "cli", ".", "err", ")", "\n\n", "baseContextSore", ":=", "store", ".", "New", "(", "cliconfig", ".", "ContextStoreDir", "(", ")", ",", "cli", ".", "contextStoreConfig", ")", "\n", "cli", ".", "contextStore", "=", "&", "ContextStoreWithDefault", "{", "Store", ":", "baseContextSore", ",", "Resolver", ":", "func", "(", ")", "(", "*", "DefaultContext", ",", "error", ")", "{", "return", "resolveDefaultContext", "(", "opts", ".", "Common", ",", "cli", ".", "ConfigFile", "(", ")", ",", "cli", ".", "Err", "(", ")", ")", "\n", "}", ",", "}", "\n", "cli", ".", "currentContext", ",", "err", "=", "resolveContextName", "(", "opts", ".", "Common", ",", "cli", ".", "configFile", ",", "cli", ".", "contextStore", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "cli", ".", "dockerEndpoint", ",", "err", "=", "resolveDockerEndpoint", "(", "cli", ".", "contextStore", ",", "cli", ".", "currentContext", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "cli", ".", "client", "==", "nil", "{", "cli", ".", "client", ",", "err", "=", "newAPIClientFromEndpoint", "(", "cli", ".", "dockerEndpoint", ",", "cli", ".", "configFile", ")", "\n", "if", "tlsconfig", ".", "IsErrEncryptedKey", "(", "err", ")", "{", "passRetriever", ":=", "passphrase", ".", "PromptRetrieverWithInOut", "(", "cli", ".", "In", "(", ")", ",", "cli", ".", "Out", "(", ")", ",", "nil", ")", "\n", "newClient", ":=", "func", "(", "password", "string", ")", "(", "client", ".", "APIClient", ",", "error", ")", "{", "cli", ".", "dockerEndpoint", ".", "TLSPassword", "=", "password", "\n", "return", "newAPIClientFromEndpoint", "(", "cli", ".", "dockerEndpoint", ",", "cli", ".", "configFile", ")", "\n", "}", "\n", "cli", ".", "client", ",", "err", "=", "getClientWithPassword", "(", "passRetriever", ",", "newClient", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "var", "experimentalValue", "string", "\n", "// Environment variable always overrides configuration", "if", "experimentalValue", "=", "os", ".", "Getenv", "(", "\"", "\"", ")", ";", "experimentalValue", "==", "\"", "\"", "{", "experimentalValue", "=", "cli", ".", "configFile", ".", "Experimental", "\n", "}", "\n", "hasExperimental", ",", "err", ":=", "isEnabled", "(", "experimentalValue", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "cli", ".", "clientInfo", "=", "ClientInfo", "{", "DefaultVersion", ":", "cli", ".", "client", ".", "ClientVersion", "(", ")", ",", "HasExperimental", ":", "hasExperimental", ",", "}", "\n", "cli", ".", "initializeFromClient", "(", ")", "\n", "return", "nil", "\n", "}" ]
// Initialize the dockerCli runs initialization that must happen after command // line flags are parsed.
[ "Initialize", "the", "dockerCli", "runs", "initialization", "that", "must", "happen", "after", "command", "line", "flags", "are", "parsed", "." ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/cli.go#L193-L258
train
docker/cli
cli/command/cli.go
NewAPIClientFromFlags
func NewAPIClientFromFlags(opts *cliflags.CommonOptions, configFile *configfile.ConfigFile) (client.APIClient, error) { store := &ContextStoreWithDefault{ Store: store.New(cliconfig.ContextStoreDir(), defaultContextStoreConfig()), Resolver: func() (*DefaultContext, error) { return resolveDefaultContext(opts, configFile, ioutil.Discard) }, } contextName, err := resolveContextName(opts, configFile, store) if err != nil { return nil, err } endpoint, err := resolveDockerEndpoint(store, contextName) if err != nil { return nil, errors.Wrap(err, "unable to resolve docker endpoint") } return newAPIClientFromEndpoint(endpoint, configFile) }
go
func NewAPIClientFromFlags(opts *cliflags.CommonOptions, configFile *configfile.ConfigFile) (client.APIClient, error) { store := &ContextStoreWithDefault{ Store: store.New(cliconfig.ContextStoreDir(), defaultContextStoreConfig()), Resolver: func() (*DefaultContext, error) { return resolveDefaultContext(opts, configFile, ioutil.Discard) }, } contextName, err := resolveContextName(opts, configFile, store) if err != nil { return nil, err } endpoint, err := resolveDockerEndpoint(store, contextName) if err != nil { return nil, errors.Wrap(err, "unable to resolve docker endpoint") } return newAPIClientFromEndpoint(endpoint, configFile) }
[ "func", "NewAPIClientFromFlags", "(", "opts", "*", "cliflags", ".", "CommonOptions", ",", "configFile", "*", "configfile", ".", "ConfigFile", ")", "(", "client", ".", "APIClient", ",", "error", ")", "{", "store", ":=", "&", "ContextStoreWithDefault", "{", "Store", ":", "store", ".", "New", "(", "cliconfig", ".", "ContextStoreDir", "(", ")", ",", "defaultContextStoreConfig", "(", ")", ")", ",", "Resolver", ":", "func", "(", ")", "(", "*", "DefaultContext", ",", "error", ")", "{", "return", "resolveDefaultContext", "(", "opts", ",", "configFile", ",", "ioutil", ".", "Discard", ")", "\n", "}", ",", "}", "\n", "contextName", ",", "err", ":=", "resolveContextName", "(", "opts", ",", "configFile", ",", "store", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "endpoint", ",", "err", ":=", "resolveDockerEndpoint", "(", "store", ",", "contextName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "newAPIClientFromEndpoint", "(", "endpoint", ",", "configFile", ")", "\n", "}" ]
// NewAPIClientFromFlags creates a new APIClient from command line flags
[ "NewAPIClientFromFlags", "creates", "a", "new", "APIClient", "from", "command", "line", "flags" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/cli.go#L261-L277
train
docker/cli
cli/command/cli.go
NotaryClient
func (cli *DockerCli) NotaryClient(imgRefAndAuth trust.ImageRefAndAuth, actions []string) (notaryclient.Repository, error) { return trust.GetNotaryRepository(cli.In(), cli.Out(), UserAgent(), imgRefAndAuth.RepoInfo(), imgRefAndAuth.AuthConfig(), actions...) }
go
func (cli *DockerCli) NotaryClient(imgRefAndAuth trust.ImageRefAndAuth, actions []string) (notaryclient.Repository, error) { return trust.GetNotaryRepository(cli.In(), cli.Out(), UserAgent(), imgRefAndAuth.RepoInfo(), imgRefAndAuth.AuthConfig(), actions...) }
[ "func", "(", "cli", "*", "DockerCli", ")", "NotaryClient", "(", "imgRefAndAuth", "trust", ".", "ImageRefAndAuth", ",", "actions", "[", "]", "string", ")", "(", "notaryclient", ".", "Repository", ",", "error", ")", "{", "return", "trust", ".", "GetNotaryRepository", "(", "cli", ".", "In", "(", ")", ",", "cli", ".", "Out", "(", ")", ",", "UserAgent", "(", ")", ",", "imgRefAndAuth", ".", "RepoInfo", "(", ")", ",", "imgRefAndAuth", ".", "AuthConfig", "(", ")", ",", "actions", "...", ")", "\n", "}" ]
// NotaryClient provides a Notary Repository to interact with signed metadata for an image
[ "NotaryClient", "provides", "a", "Notary", "Repository", "to", "interact", "with", "signed", "metadata", "for", "an", "image" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/cli.go#L380-L382
train
docker/cli
cli/command/cli.go
NewContainerizedEngineClient
func (cli *DockerCli) NewContainerizedEngineClient(sockPath string) (clitypes.ContainerizedClient, error) { return cli.newContainerizeClient(sockPath) }
go
func (cli *DockerCli) NewContainerizedEngineClient(sockPath string) (clitypes.ContainerizedClient, error) { return cli.newContainerizeClient(sockPath) }
[ "func", "(", "cli", "*", "DockerCli", ")", "NewContainerizedEngineClient", "(", "sockPath", "string", ")", "(", "clitypes", ".", "ContainerizedClient", ",", "error", ")", "{", "return", "cli", ".", "newContainerizeClient", "(", "sockPath", ")", "\n", "}" ]
// NewContainerizedEngineClient returns a containerized engine client
[ "NewContainerizedEngineClient", "returns", "a", "containerized", "engine", "client" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/cli.go#L385-L387
train
docker/cli
cli/command/cli.go
StackOrchestrator
func (cli *DockerCli) StackOrchestrator(flagValue string) (Orchestrator, error) { currentContext := cli.CurrentContext() ctxRaw, err := cli.ContextStore().GetMetadata(currentContext) if store.IsErrContextDoesNotExist(err) { // case where the currentContext has been removed (CLI behavior is to fallback to using DOCKER_HOST based resolution) return GetStackOrchestrator(flagValue, "", cli.ConfigFile().StackOrchestrator, cli.Err()) } if err != nil { return "", err } ctxMeta, err := GetDockerContext(ctxRaw) if err != nil { return "", err } ctxOrchestrator := string(ctxMeta.StackOrchestrator) return GetStackOrchestrator(flagValue, ctxOrchestrator, cli.ConfigFile().StackOrchestrator, cli.Err()) }
go
func (cli *DockerCli) StackOrchestrator(flagValue string) (Orchestrator, error) { currentContext := cli.CurrentContext() ctxRaw, err := cli.ContextStore().GetMetadata(currentContext) if store.IsErrContextDoesNotExist(err) { // case where the currentContext has been removed (CLI behavior is to fallback to using DOCKER_HOST based resolution) return GetStackOrchestrator(flagValue, "", cli.ConfigFile().StackOrchestrator, cli.Err()) } if err != nil { return "", err } ctxMeta, err := GetDockerContext(ctxRaw) if err != nil { return "", err } ctxOrchestrator := string(ctxMeta.StackOrchestrator) return GetStackOrchestrator(flagValue, ctxOrchestrator, cli.ConfigFile().StackOrchestrator, cli.Err()) }
[ "func", "(", "cli", "*", "DockerCli", ")", "StackOrchestrator", "(", "flagValue", "string", ")", "(", "Orchestrator", ",", "error", ")", "{", "currentContext", ":=", "cli", ".", "CurrentContext", "(", ")", "\n", "ctxRaw", ",", "err", ":=", "cli", ".", "ContextStore", "(", ")", ".", "GetMetadata", "(", "currentContext", ")", "\n", "if", "store", ".", "IsErrContextDoesNotExist", "(", "err", ")", "{", "// case where the currentContext has been removed (CLI behavior is to fallback to using DOCKER_HOST based resolution)", "return", "GetStackOrchestrator", "(", "flagValue", ",", "\"", "\"", ",", "cli", ".", "ConfigFile", "(", ")", ".", "StackOrchestrator", ",", "cli", ".", "Err", "(", ")", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "ctxMeta", ",", "err", ":=", "GetDockerContext", "(", "ctxRaw", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "ctxOrchestrator", ":=", "string", "(", "ctxMeta", ".", "StackOrchestrator", ")", "\n", "return", "GetStackOrchestrator", "(", "flagValue", ",", "ctxOrchestrator", ",", "cli", ".", "ConfigFile", "(", ")", ".", "StackOrchestrator", ",", "cli", ".", "Err", "(", ")", ")", "\n", "}" ]
// StackOrchestrator resolves which stack orchestrator is in use
[ "StackOrchestrator", "resolves", "which", "stack", "orchestrator", "is", "in", "use" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/cli.go#L400-L416
train
docker/cli
cli/command/cli.go
Apply
func (cli *DockerCli) Apply(ops ...DockerCliOption) error { for _, op := range ops { if err := op(cli); err != nil { return err } } return nil }
go
func (cli *DockerCli) Apply(ops ...DockerCliOption) error { for _, op := range ops { if err := op(cli); err != nil { return err } } return nil }
[ "func", "(", "cli", "*", "DockerCli", ")", "Apply", "(", "ops", "...", "DockerCliOption", ")", "error", "{", "for", "_", ",", "op", ":=", "range", "ops", "{", "if", "err", ":=", "op", "(", "cli", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Apply all the operation on the cli
[ "Apply", "all", "the", "operation", "on", "the", "cli" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/cli.go#L424-L431
train
docker/cli
cli/command/cli.go
NewDockerCli
func NewDockerCli(ops ...DockerCliOption) (*DockerCli, error) { cli := &DockerCli{} defaultOps := []DockerCliOption{ WithContentTrustFromEnv(), WithContainerizedClient(containerizedengine.NewClient), } cli.contextStoreConfig = defaultContextStoreConfig() ops = append(defaultOps, ops...) if err := cli.Apply(ops...); err != nil { return nil, err } if cli.out == nil || cli.in == nil || cli.err == nil { stdin, stdout, stderr := term.StdStreams() if cli.in == nil { cli.in = streams.NewIn(stdin) } if cli.out == nil { cli.out = streams.NewOut(stdout) } if cli.err == nil { cli.err = stderr } } return cli, nil }
go
func NewDockerCli(ops ...DockerCliOption) (*DockerCli, error) { cli := &DockerCli{} defaultOps := []DockerCliOption{ WithContentTrustFromEnv(), WithContainerizedClient(containerizedengine.NewClient), } cli.contextStoreConfig = defaultContextStoreConfig() ops = append(defaultOps, ops...) if err := cli.Apply(ops...); err != nil { return nil, err } if cli.out == nil || cli.in == nil || cli.err == nil { stdin, stdout, stderr := term.StdStreams() if cli.in == nil { cli.in = streams.NewIn(stdin) } if cli.out == nil { cli.out = streams.NewOut(stdout) } if cli.err == nil { cli.err = stderr } } return cli, nil }
[ "func", "NewDockerCli", "(", "ops", "...", "DockerCliOption", ")", "(", "*", "DockerCli", ",", "error", ")", "{", "cli", ":=", "&", "DockerCli", "{", "}", "\n", "defaultOps", ":=", "[", "]", "DockerCliOption", "{", "WithContentTrustFromEnv", "(", ")", ",", "WithContainerizedClient", "(", "containerizedengine", ".", "NewClient", ")", ",", "}", "\n", "cli", ".", "contextStoreConfig", "=", "defaultContextStoreConfig", "(", ")", "\n", "ops", "=", "append", "(", "defaultOps", ",", "ops", "...", ")", "\n", "if", "err", ":=", "cli", ".", "Apply", "(", "ops", "...", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "cli", ".", "out", "==", "nil", "||", "cli", ".", "in", "==", "nil", "||", "cli", ".", "err", "==", "nil", "{", "stdin", ",", "stdout", ",", "stderr", ":=", "term", ".", "StdStreams", "(", ")", "\n", "if", "cli", ".", "in", "==", "nil", "{", "cli", ".", "in", "=", "streams", ".", "NewIn", "(", "stdin", ")", "\n", "}", "\n", "if", "cli", ".", "out", "==", "nil", "{", "cli", ".", "out", "=", "streams", ".", "NewOut", "(", "stdout", ")", "\n", "}", "\n", "if", "cli", ".", "err", "==", "nil", "{", "cli", ".", "err", "=", "stderr", "\n", "}", "\n", "}", "\n", "return", "cli", ",", "nil", "\n", "}" ]
// NewDockerCli returns a DockerCli instance with all operators applied on it. // It applies by default the standard streams, the content trust from // environment and the default containerized client constructor operations.
[ "NewDockerCli", "returns", "a", "DockerCli", "instance", "with", "all", "operators", "applied", "on", "it", ".", "It", "applies", "by", "default", "the", "standard", "streams", "the", "content", "trust", "from", "environment", "and", "the", "default", "containerized", "client", "constructor", "operations", "." ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/cli.go#L450-L474
train
docker/cli
cli/command/config/create.go
RunConfigCreate
func RunConfigCreate(dockerCli command.Cli, options CreateOptions) error { client := dockerCli.Client() ctx := context.Background() var in io.Reader = dockerCli.In() if options.File != "-" { file, err := system.OpenSequential(options.File) if err != nil { return err } in = file defer file.Close() } configData, err := ioutil.ReadAll(in) if err != nil { return errors.Errorf("Error reading content from %q: %v", options.File, err) } spec := swarm.ConfigSpec{ Annotations: swarm.Annotations{ Name: options.Name, Labels: opts.ConvertKVStringsToMap(options.Labels.GetAll()), }, Data: configData, } if options.TemplateDriver != "" { spec.Templating = &swarm.Driver{ Name: options.TemplateDriver, } } r, err := client.ConfigCreate(ctx, spec) if err != nil { return err } fmt.Fprintln(dockerCli.Out(), r.ID) return nil }
go
func RunConfigCreate(dockerCli command.Cli, options CreateOptions) error { client := dockerCli.Client() ctx := context.Background() var in io.Reader = dockerCli.In() if options.File != "-" { file, err := system.OpenSequential(options.File) if err != nil { return err } in = file defer file.Close() } configData, err := ioutil.ReadAll(in) if err != nil { return errors.Errorf("Error reading content from %q: %v", options.File, err) } spec := swarm.ConfigSpec{ Annotations: swarm.Annotations{ Name: options.Name, Labels: opts.ConvertKVStringsToMap(options.Labels.GetAll()), }, Data: configData, } if options.TemplateDriver != "" { spec.Templating = &swarm.Driver{ Name: options.TemplateDriver, } } r, err := client.ConfigCreate(ctx, spec) if err != nil { return err } fmt.Fprintln(dockerCli.Out(), r.ID) return nil }
[ "func", "RunConfigCreate", "(", "dockerCli", "command", ".", "Cli", ",", "options", "CreateOptions", ")", "error", "{", "client", ":=", "dockerCli", ".", "Client", "(", ")", "\n", "ctx", ":=", "context", ".", "Background", "(", ")", "\n\n", "var", "in", "io", ".", "Reader", "=", "dockerCli", ".", "In", "(", ")", "\n", "if", "options", ".", "File", "!=", "\"", "\"", "{", "file", ",", "err", ":=", "system", ".", "OpenSequential", "(", "options", ".", "File", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "in", "=", "file", "\n", "defer", "file", ".", "Close", "(", ")", "\n", "}", "\n\n", "configData", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "in", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "options", ".", "File", ",", "err", ")", "\n", "}", "\n\n", "spec", ":=", "swarm", ".", "ConfigSpec", "{", "Annotations", ":", "swarm", ".", "Annotations", "{", "Name", ":", "options", ".", "Name", ",", "Labels", ":", "opts", ".", "ConvertKVStringsToMap", "(", "options", ".", "Labels", ".", "GetAll", "(", ")", ")", ",", "}", ",", "Data", ":", "configData", ",", "}", "\n", "if", "options", ".", "TemplateDriver", "!=", "\"", "\"", "{", "spec", ".", "Templating", "=", "&", "swarm", ".", "Driver", "{", "Name", ":", "options", ".", "TemplateDriver", ",", "}", "\n", "}", "\n", "r", ",", "err", ":=", "client", ".", "ConfigCreate", "(", "ctx", ",", "spec", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "fmt", ".", "Fprintln", "(", "dockerCli", ".", "Out", "(", ")", ",", "r", ".", "ID", ")", "\n", "return", "nil", "\n", "}" ]
// RunConfigCreate creates a config with the given options.
[ "RunConfigCreate", "creates", "a", "config", "with", "the", "given", "options", "." ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/config/create.go#L50-L88
train
docker/cli
cli/command/container/port.go
NewPortCommand
func NewPortCommand(dockerCli command.Cli) *cobra.Command { var opts portOptions cmd := &cobra.Command{ Use: "port CONTAINER [PRIVATE_PORT[/PROTO]]", Short: "List port mappings or a specific mapping for the container", Args: cli.RequiresRangeArgs(1, 2), RunE: func(cmd *cobra.Command, args []string) error { opts.container = args[0] if len(args) > 1 { opts.port = args[1] } return runPort(dockerCli, &opts) }, } return cmd }
go
func NewPortCommand(dockerCli command.Cli) *cobra.Command { var opts portOptions cmd := &cobra.Command{ Use: "port CONTAINER [PRIVATE_PORT[/PROTO]]", Short: "List port mappings or a specific mapping for the container", Args: cli.RequiresRangeArgs(1, 2), RunE: func(cmd *cobra.Command, args []string) error { opts.container = args[0] if len(args) > 1 { opts.port = args[1] } return runPort(dockerCli, &opts) }, } return cmd }
[ "func", "NewPortCommand", "(", "dockerCli", "command", ".", "Cli", ")", "*", "cobra", ".", "Command", "{", "var", "opts", "portOptions", "\n\n", "cmd", ":=", "&", "cobra", ".", "Command", "{", "Use", ":", "\"", "\"", ",", "Short", ":", "\"", "\"", ",", "Args", ":", "cli", ".", "RequiresRangeArgs", "(", "1", ",", "2", ")", ",", "RunE", ":", "func", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "error", "{", "opts", ".", "container", "=", "args", "[", "0", "]", "\n", "if", "len", "(", "args", ")", ">", "1", "{", "opts", ".", "port", "=", "args", "[", "1", "]", "\n", "}", "\n", "return", "runPort", "(", "dockerCli", ",", "&", "opts", ")", "\n", "}", ",", "}", "\n", "return", "cmd", "\n", "}" ]
// NewPortCommand creates a new cobra.Command for `docker port`
[ "NewPortCommand", "creates", "a", "new", "cobra", ".", "Command", "for", "docker", "port" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/container/port.go#L22-L38
train
docker/cli
cli/command/stack/kubernetes/remove.go
RunRemove
func RunRemove(dockerCli *KubeCli, opts options.Remove) error { composeClient, err := dockerCli.composeClient() if err != nil { return err } stacks, err := composeClient.Stacks(false) if err != nil { return err } for _, stack := range opts.Namespaces { fmt.Fprintf(dockerCli.Out(), "Removing stack: %s\n", stack) if err := stacks.Delete(stack); err != nil { return errors.Wrapf(err, "Failed to remove stack %s", stack) } } return nil }
go
func RunRemove(dockerCli *KubeCli, opts options.Remove) error { composeClient, err := dockerCli.composeClient() if err != nil { return err } stacks, err := composeClient.Stacks(false) if err != nil { return err } for _, stack := range opts.Namespaces { fmt.Fprintf(dockerCli.Out(), "Removing stack: %s\n", stack) if err := stacks.Delete(stack); err != nil { return errors.Wrapf(err, "Failed to remove stack %s", stack) } } return nil }
[ "func", "RunRemove", "(", "dockerCli", "*", "KubeCli", ",", "opts", "options", ".", "Remove", ")", "error", "{", "composeClient", ",", "err", ":=", "dockerCli", ".", "composeClient", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "stacks", ",", "err", ":=", "composeClient", ".", "Stacks", "(", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "_", ",", "stack", ":=", "range", "opts", ".", "Namespaces", "{", "fmt", ".", "Fprintf", "(", "dockerCli", ".", "Out", "(", ")", ",", "\"", "\\n", "\"", ",", "stack", ")", "\n", "if", "err", ":=", "stacks", ".", "Delete", "(", "stack", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "stack", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// RunRemove is the kubernetes implementation of docker stack remove
[ "RunRemove", "is", "the", "kubernetes", "implementation", "of", "docker", "stack", "remove" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/stack/kubernetes/remove.go#L11-L27
train
docker/cli
cli/registry/client/fetcher.go
fetchManifest
func fetchManifest(ctx context.Context, repo distribution.Repository, ref reference.Named) (types.ImageManifest, error) { manifest, err := getManifest(ctx, repo, ref) if err != nil { return types.ImageManifest{}, err } switch v := manifest.(type) { // Removed Schema 1 support case *schema2.DeserializedManifest: imageManifest, err := pullManifestSchemaV2(ctx, ref, repo, *v) if err != nil { return types.ImageManifest{}, err } return imageManifest, nil case *manifestlist.DeserializedManifestList: return types.ImageManifest{}, errors.Errorf("%s is a manifest list", ref) } return types.ImageManifest{}, errors.Errorf("%s is not a manifest", ref) }
go
func fetchManifest(ctx context.Context, repo distribution.Repository, ref reference.Named) (types.ImageManifest, error) { manifest, err := getManifest(ctx, repo, ref) if err != nil { return types.ImageManifest{}, err } switch v := manifest.(type) { // Removed Schema 1 support case *schema2.DeserializedManifest: imageManifest, err := pullManifestSchemaV2(ctx, ref, repo, *v) if err != nil { return types.ImageManifest{}, err } return imageManifest, nil case *manifestlist.DeserializedManifestList: return types.ImageManifest{}, errors.Errorf("%s is a manifest list", ref) } return types.ImageManifest{}, errors.Errorf("%s is not a manifest", ref) }
[ "func", "fetchManifest", "(", "ctx", "context", ".", "Context", ",", "repo", "distribution", ".", "Repository", ",", "ref", "reference", ".", "Named", ")", "(", "types", ".", "ImageManifest", ",", "error", ")", "{", "manifest", ",", "err", ":=", "getManifest", "(", "ctx", ",", "repo", ",", "ref", ")", "\n", "if", "err", "!=", "nil", "{", "return", "types", ".", "ImageManifest", "{", "}", ",", "err", "\n", "}", "\n\n", "switch", "v", ":=", "manifest", ".", "(", "type", ")", "{", "// Removed Schema 1 support", "case", "*", "schema2", ".", "DeserializedManifest", ":", "imageManifest", ",", "err", ":=", "pullManifestSchemaV2", "(", "ctx", ",", "ref", ",", "repo", ",", "*", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "types", ".", "ImageManifest", "{", "}", ",", "err", "\n", "}", "\n", "return", "imageManifest", ",", "nil", "\n", "case", "*", "manifestlist", ".", "DeserializedManifestList", ":", "return", "types", ".", "ImageManifest", "{", "}", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "ref", ")", "\n", "}", "\n", "return", "types", ".", "ImageManifest", "{", "}", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "ref", ")", "\n", "}" ]
// fetchManifest pulls a manifest from a registry and returns it. An error // is returned if no manifest is found matching namedRef.
[ "fetchManifest", "pulls", "a", "manifest", "from", "a", "registry", "and", "returns", "it", ".", "An", "error", "is", "returned", "if", "no", "manifest", "is", "found", "matching", "namedRef", "." ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/registry/client/fetcher.go#L25-L43
train
docker/cli
cli/registry/client/fetcher.go
validateManifestDigest
func validateManifestDigest(ref reference.Named, mfst distribution.Manifest) (ocispec.Descriptor, error) { mediaType, canonical, err := mfst.Payload() if err != nil { return ocispec.Descriptor{}, err } desc := ocispec.Descriptor{ Digest: digest.FromBytes(canonical), Size: int64(len(canonical)), MediaType: mediaType, } // If pull by digest, then verify the manifest digest. if digested, isDigested := ref.(reference.Canonical); isDigested { if digested.Digest() != desc.Digest { err := fmt.Errorf("manifest verification failed for digest %s", digested.Digest()) return ocispec.Descriptor{}, err } } return desc, nil }
go
func validateManifestDigest(ref reference.Named, mfst distribution.Manifest) (ocispec.Descriptor, error) { mediaType, canonical, err := mfst.Payload() if err != nil { return ocispec.Descriptor{}, err } desc := ocispec.Descriptor{ Digest: digest.FromBytes(canonical), Size: int64(len(canonical)), MediaType: mediaType, } // If pull by digest, then verify the manifest digest. if digested, isDigested := ref.(reference.Canonical); isDigested { if digested.Digest() != desc.Digest { err := fmt.Errorf("manifest verification failed for digest %s", digested.Digest()) return ocispec.Descriptor{}, err } } return desc, nil }
[ "func", "validateManifestDigest", "(", "ref", "reference", ".", "Named", ",", "mfst", "distribution", ".", "Manifest", ")", "(", "ocispec", ".", "Descriptor", ",", "error", ")", "{", "mediaType", ",", "canonical", ",", "err", ":=", "mfst", ".", "Payload", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "ocispec", ".", "Descriptor", "{", "}", ",", "err", "\n", "}", "\n", "desc", ":=", "ocispec", ".", "Descriptor", "{", "Digest", ":", "digest", ".", "FromBytes", "(", "canonical", ")", ",", "Size", ":", "int64", "(", "len", "(", "canonical", ")", ")", ",", "MediaType", ":", "mediaType", ",", "}", "\n\n", "// If pull by digest, then verify the manifest digest.", "if", "digested", ",", "isDigested", ":=", "ref", ".", "(", "reference", ".", "Canonical", ")", ";", "isDigested", "{", "if", "digested", ".", "Digest", "(", ")", "!=", "desc", ".", "Digest", "{", "err", ":=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "digested", ".", "Digest", "(", ")", ")", "\n", "return", "ocispec", ".", "Descriptor", "{", "}", ",", "err", "\n", "}", "\n", "}", "\n\n", "return", "desc", ",", "nil", "\n", "}" ]
// validateManifestDigest computes the manifest digest, and, if pulling by // digest, ensures that it matches the requested digest.
[ "validateManifestDigest", "computes", "the", "manifest", "digest", "and", "if", "pulling", "by", "digest", "ensures", "that", "it", "matches", "the", "requested", "digest", "." ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/registry/client/fetcher.go#L120-L140
train
docker/cli
cli/compose/convert/compose.go
Descope
func (n Namespace) Descope(name string) string { return strings.TrimPrefix(name, n.name+"_") }
go
func (n Namespace) Descope(name string) string { return strings.TrimPrefix(name, n.name+"_") }
[ "func", "(", "n", "Namespace", ")", "Descope", "(", "name", "string", ")", "string", "{", "return", "strings", ".", "TrimPrefix", "(", "name", ",", "n", ".", "name", "+", "\"", "\"", ")", "\n", "}" ]
// Descope returns the name without the namespace prefix
[ "Descope", "returns", "the", "name", "without", "the", "namespace", "prefix" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/compose/convert/compose.go#L29-L31
train
docker/cli
cli/compose/convert/compose.go
AddStackLabel
func AddStackLabel(namespace Namespace, labels map[string]string) map[string]string { if labels == nil { labels = make(map[string]string) } labels[LabelNamespace] = namespace.name return labels }
go
func AddStackLabel(namespace Namespace, labels map[string]string) map[string]string { if labels == nil { labels = make(map[string]string) } labels[LabelNamespace] = namespace.name return labels }
[ "func", "AddStackLabel", "(", "namespace", "Namespace", ",", "labels", "map", "[", "string", "]", "string", ")", "map", "[", "string", "]", "string", "{", "if", "labels", "==", "nil", "{", "labels", "=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "}", "\n", "labels", "[", "LabelNamespace", "]", "=", "namespace", ".", "name", "\n", "return", "labels", "\n", "}" ]
// AddStackLabel returns labels with the namespace label added
[ "AddStackLabel", "returns", "labels", "with", "the", "namespace", "label", "added" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/compose/convert/compose.go#L44-L50
train
docker/cli
cli/compose/convert/compose.go
Networks
func Networks(namespace Namespace, networks networkMap, servicesNetworks map[string]struct{}) (map[string]types.NetworkCreate, []string) { if networks == nil { networks = make(map[string]composetypes.NetworkConfig) } externalNetworks := []string{} result := make(map[string]types.NetworkCreate) for internalName := range servicesNetworks { network := networks[internalName] if network.External.External { externalNetworks = append(externalNetworks, network.Name) continue } createOpts := types.NetworkCreate{ Labels: AddStackLabel(namespace, network.Labels), Driver: network.Driver, Options: network.DriverOpts, Internal: network.Internal, Attachable: network.Attachable, } if network.Ipam.Driver != "" || len(network.Ipam.Config) > 0 { createOpts.IPAM = &networktypes.IPAM{} } if network.Ipam.Driver != "" { createOpts.IPAM.Driver = network.Ipam.Driver } for _, ipamConfig := range network.Ipam.Config { config := networktypes.IPAMConfig{ Subnet: ipamConfig.Subnet, } createOpts.IPAM.Config = append(createOpts.IPAM.Config, config) } networkName := namespace.Scope(internalName) if network.Name != "" { networkName = network.Name } result[networkName] = createOpts } return result, externalNetworks }
go
func Networks(namespace Namespace, networks networkMap, servicesNetworks map[string]struct{}) (map[string]types.NetworkCreate, []string) { if networks == nil { networks = make(map[string]composetypes.NetworkConfig) } externalNetworks := []string{} result := make(map[string]types.NetworkCreate) for internalName := range servicesNetworks { network := networks[internalName] if network.External.External { externalNetworks = append(externalNetworks, network.Name) continue } createOpts := types.NetworkCreate{ Labels: AddStackLabel(namespace, network.Labels), Driver: network.Driver, Options: network.DriverOpts, Internal: network.Internal, Attachable: network.Attachable, } if network.Ipam.Driver != "" || len(network.Ipam.Config) > 0 { createOpts.IPAM = &networktypes.IPAM{} } if network.Ipam.Driver != "" { createOpts.IPAM.Driver = network.Ipam.Driver } for _, ipamConfig := range network.Ipam.Config { config := networktypes.IPAMConfig{ Subnet: ipamConfig.Subnet, } createOpts.IPAM.Config = append(createOpts.IPAM.Config, config) } networkName := namespace.Scope(internalName) if network.Name != "" { networkName = network.Name } result[networkName] = createOpts } return result, externalNetworks }
[ "func", "Networks", "(", "namespace", "Namespace", ",", "networks", "networkMap", ",", "servicesNetworks", "map", "[", "string", "]", "struct", "{", "}", ")", "(", "map", "[", "string", "]", "types", ".", "NetworkCreate", ",", "[", "]", "string", ")", "{", "if", "networks", "==", "nil", "{", "networks", "=", "make", "(", "map", "[", "string", "]", "composetypes", ".", "NetworkConfig", ")", "\n", "}", "\n\n", "externalNetworks", ":=", "[", "]", "string", "{", "}", "\n", "result", ":=", "make", "(", "map", "[", "string", "]", "types", ".", "NetworkCreate", ")", "\n", "for", "internalName", ":=", "range", "servicesNetworks", "{", "network", ":=", "networks", "[", "internalName", "]", "\n", "if", "network", ".", "External", ".", "External", "{", "externalNetworks", "=", "append", "(", "externalNetworks", ",", "network", ".", "Name", ")", "\n", "continue", "\n", "}", "\n\n", "createOpts", ":=", "types", ".", "NetworkCreate", "{", "Labels", ":", "AddStackLabel", "(", "namespace", ",", "network", ".", "Labels", ")", ",", "Driver", ":", "network", ".", "Driver", ",", "Options", ":", "network", ".", "DriverOpts", ",", "Internal", ":", "network", ".", "Internal", ",", "Attachable", ":", "network", ".", "Attachable", ",", "}", "\n\n", "if", "network", ".", "Ipam", ".", "Driver", "!=", "\"", "\"", "||", "len", "(", "network", ".", "Ipam", ".", "Config", ")", ">", "0", "{", "createOpts", ".", "IPAM", "=", "&", "networktypes", ".", "IPAM", "{", "}", "\n", "}", "\n\n", "if", "network", ".", "Ipam", ".", "Driver", "!=", "\"", "\"", "{", "createOpts", ".", "IPAM", ".", "Driver", "=", "network", ".", "Ipam", ".", "Driver", "\n", "}", "\n", "for", "_", ",", "ipamConfig", ":=", "range", "network", ".", "Ipam", ".", "Config", "{", "config", ":=", "networktypes", ".", "IPAMConfig", "{", "Subnet", ":", "ipamConfig", ".", "Subnet", ",", "}", "\n", "createOpts", ".", "IPAM", ".", "Config", "=", "append", "(", "createOpts", ".", "IPAM", ".", "Config", ",", "config", ")", "\n", "}", "\n\n", "networkName", ":=", "namespace", ".", "Scope", "(", "internalName", ")", "\n", "if", "network", ".", "Name", "!=", "\"", "\"", "{", "networkName", "=", "network", ".", "Name", "\n", "}", "\n", "result", "[", "networkName", "]", "=", "createOpts", "\n", "}", "\n\n", "return", "result", ",", "externalNetworks", "\n", "}" ]
// Networks from the compose-file type to the engine API type
[ "Networks", "from", "the", "compose", "-", "file", "type", "to", "the", "engine", "API", "type" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/compose/convert/compose.go#L55-L99
train
docker/cli
cli/compose/convert/compose.go
Secrets
func Secrets(namespace Namespace, secrets map[string]composetypes.SecretConfig) ([]swarm.SecretSpec, error) { result := []swarm.SecretSpec{} for name, secret := range secrets { if secret.External.External { continue } var obj swarmFileObject var err error if secret.Driver != "" { obj, err = driverObjectConfig(namespace, name, composetypes.FileObjectConfig(secret)) } else { obj, err = fileObjectConfig(namespace, name, composetypes.FileObjectConfig(secret)) } if err != nil { return nil, err } spec := swarm.SecretSpec{Annotations: obj.Annotations, Data: obj.Data} if secret.Driver != "" { spec.Driver = &swarm.Driver{ Name: secret.Driver, Options: secret.DriverOpts, } } if secret.TemplateDriver != "" { spec.Templating = &swarm.Driver{ Name: secret.TemplateDriver, } } result = append(result, spec) } return result, nil }
go
func Secrets(namespace Namespace, secrets map[string]composetypes.SecretConfig) ([]swarm.SecretSpec, error) { result := []swarm.SecretSpec{} for name, secret := range secrets { if secret.External.External { continue } var obj swarmFileObject var err error if secret.Driver != "" { obj, err = driverObjectConfig(namespace, name, composetypes.FileObjectConfig(secret)) } else { obj, err = fileObjectConfig(namespace, name, composetypes.FileObjectConfig(secret)) } if err != nil { return nil, err } spec := swarm.SecretSpec{Annotations: obj.Annotations, Data: obj.Data} if secret.Driver != "" { spec.Driver = &swarm.Driver{ Name: secret.Driver, Options: secret.DriverOpts, } } if secret.TemplateDriver != "" { spec.Templating = &swarm.Driver{ Name: secret.TemplateDriver, } } result = append(result, spec) } return result, nil }
[ "func", "Secrets", "(", "namespace", "Namespace", ",", "secrets", "map", "[", "string", "]", "composetypes", ".", "SecretConfig", ")", "(", "[", "]", "swarm", ".", "SecretSpec", ",", "error", ")", "{", "result", ":=", "[", "]", "swarm", ".", "SecretSpec", "{", "}", "\n", "for", "name", ",", "secret", ":=", "range", "secrets", "{", "if", "secret", ".", "External", ".", "External", "{", "continue", "\n", "}", "\n\n", "var", "obj", "swarmFileObject", "\n", "var", "err", "error", "\n", "if", "secret", ".", "Driver", "!=", "\"", "\"", "{", "obj", ",", "err", "=", "driverObjectConfig", "(", "namespace", ",", "name", ",", "composetypes", ".", "FileObjectConfig", "(", "secret", ")", ")", "\n", "}", "else", "{", "obj", ",", "err", "=", "fileObjectConfig", "(", "namespace", ",", "name", ",", "composetypes", ".", "FileObjectConfig", "(", "secret", ")", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "spec", ":=", "swarm", ".", "SecretSpec", "{", "Annotations", ":", "obj", ".", "Annotations", ",", "Data", ":", "obj", ".", "Data", "}", "\n", "if", "secret", ".", "Driver", "!=", "\"", "\"", "{", "spec", ".", "Driver", "=", "&", "swarm", ".", "Driver", "{", "Name", ":", "secret", ".", "Driver", ",", "Options", ":", "secret", ".", "DriverOpts", ",", "}", "\n", "}", "\n", "if", "secret", ".", "TemplateDriver", "!=", "\"", "\"", "{", "spec", ".", "Templating", "=", "&", "swarm", ".", "Driver", "{", "Name", ":", "secret", ".", "TemplateDriver", ",", "}", "\n", "}", "\n", "result", "=", "append", "(", "result", ",", "spec", ")", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// Secrets converts secrets from the Compose type to the engine API type
[ "Secrets", "converts", "secrets", "from", "the", "Compose", "type", "to", "the", "engine", "API", "type" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/compose/convert/compose.go#L102-L134
train
docker/cli
cli/connhelper/connhelper.go
GetCommandConnectionHelper
func GetCommandConnectionHelper(cmd string, flags ...string) (*ConnectionHelper, error) { return &ConnectionHelper{ Dialer: func(ctx context.Context, network, addr string) (net.Conn, error) { return commandconn.New(ctx, cmd, flags...) }, Host: "http://docker", }, nil }
go
func GetCommandConnectionHelper(cmd string, flags ...string) (*ConnectionHelper, error) { return &ConnectionHelper{ Dialer: func(ctx context.Context, network, addr string) (net.Conn, error) { return commandconn.New(ctx, cmd, flags...) }, Host: "http://docker", }, nil }
[ "func", "GetCommandConnectionHelper", "(", "cmd", "string", ",", "flags", "...", "string", ")", "(", "*", "ConnectionHelper", ",", "error", ")", "{", "return", "&", "ConnectionHelper", "{", "Dialer", ":", "func", "(", "ctx", "context", ".", "Context", ",", "network", ",", "addr", "string", ")", "(", "net", ".", "Conn", ",", "error", ")", "{", "return", "commandconn", ".", "New", "(", "ctx", ",", "cmd", ",", "flags", "...", ")", "\n", "}", ",", "Host", ":", "\"", "\"", ",", "}", ",", "nil", "\n", "}" ]
// GetCommandConnectionHelper returns Docker-specific connection helper constructed from an arbitrary command.
[ "GetCommandConnectionHelper", "returns", "Docker", "-", "specific", "connection", "helper", "constructed", "from", "an", "arbitrary", "command", "." ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/connhelper/connhelper.go#L48-L55
train
docker/cli
cli/command/checkpoint/formatter.go
NewFormat
func NewFormat(source string) formatter.Format { switch source { case formatter.TableFormatKey: return defaultCheckpointFormat } return formatter.Format(source) }
go
func NewFormat(source string) formatter.Format { switch source { case formatter.TableFormatKey: return defaultCheckpointFormat } return formatter.Format(source) }
[ "func", "NewFormat", "(", "source", "string", ")", "formatter", ".", "Format", "{", "switch", "source", "{", "case", "formatter", ".", "TableFormatKey", ":", "return", "defaultCheckpointFormat", "\n", "}", "\n", "return", "formatter", ".", "Format", "(", "source", ")", "\n", "}" ]
// NewFormat returns a format for use with a checkpoint Context
[ "NewFormat", "returns", "a", "format", "for", "use", "with", "a", "checkpoint", "Context" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/checkpoint/formatter.go#L15-L21
train
docker/cli
cli/command/checkpoint/formatter.go
FormatWrite
func FormatWrite(ctx formatter.Context, checkpoints []types.Checkpoint) error { render := func(format func(subContext formatter.SubContext) error) error { for _, checkpoint := range checkpoints { if err := format(&checkpointContext{c: checkpoint}); err != nil { return err } } return nil } return ctx.Write(newCheckpointContext(), render) }
go
func FormatWrite(ctx formatter.Context, checkpoints []types.Checkpoint) error { render := func(format func(subContext formatter.SubContext) error) error { for _, checkpoint := range checkpoints { if err := format(&checkpointContext{c: checkpoint}); err != nil { return err } } return nil } return ctx.Write(newCheckpointContext(), render) }
[ "func", "FormatWrite", "(", "ctx", "formatter", ".", "Context", ",", "checkpoints", "[", "]", "types", ".", "Checkpoint", ")", "error", "{", "render", ":=", "func", "(", "format", "func", "(", "subContext", "formatter", ".", "SubContext", ")", "error", ")", "error", "{", "for", "_", ",", "checkpoint", ":=", "range", "checkpoints", "{", "if", "err", ":=", "format", "(", "&", "checkpointContext", "{", "c", ":", "checkpoint", "}", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "return", "ctx", ".", "Write", "(", "newCheckpointContext", "(", ")", ",", "render", ")", "\n", "}" ]
// FormatWrite writes formatted checkpoints using the Context
[ "FormatWrite", "writes", "formatted", "checkpoints", "using", "the", "Context" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/checkpoint/formatter.go#L24-L34
train
docker/cli
cli/command/image/history.go
NewHistoryCommand
func NewHistoryCommand(dockerCli command.Cli) *cobra.Command { var opts historyOptions cmd := &cobra.Command{ Use: "history [OPTIONS] IMAGE", Short: "Show the history of an image", Args: cli.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.image = args[0] return runHistory(dockerCli, opts) }, } flags := cmd.Flags() flags.BoolVarP(&opts.human, "human", "H", true, "Print sizes and dates in human readable format") flags.BoolVarP(&opts.quiet, "quiet", "q", false, "Only show numeric IDs") flags.BoolVar(&opts.noTrunc, "no-trunc", false, "Don't truncate output") flags.StringVar(&opts.format, "format", "", "Pretty-print images using a Go template") return cmd }
go
func NewHistoryCommand(dockerCli command.Cli) *cobra.Command { var opts historyOptions cmd := &cobra.Command{ Use: "history [OPTIONS] IMAGE", Short: "Show the history of an image", Args: cli.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.image = args[0] return runHistory(dockerCli, opts) }, } flags := cmd.Flags() flags.BoolVarP(&opts.human, "human", "H", true, "Print sizes and dates in human readable format") flags.BoolVarP(&opts.quiet, "quiet", "q", false, "Only show numeric IDs") flags.BoolVar(&opts.noTrunc, "no-trunc", false, "Don't truncate output") flags.StringVar(&opts.format, "format", "", "Pretty-print images using a Go template") return cmd }
[ "func", "NewHistoryCommand", "(", "dockerCli", "command", ".", "Cli", ")", "*", "cobra", ".", "Command", "{", "var", "opts", "historyOptions", "\n\n", "cmd", ":=", "&", "cobra", ".", "Command", "{", "Use", ":", "\"", "\"", ",", "Short", ":", "\"", "\"", ",", "Args", ":", "cli", ".", "ExactArgs", "(", "1", ")", ",", "RunE", ":", "func", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "error", "{", "opts", ".", "image", "=", "args", "[", "0", "]", "\n", "return", "runHistory", "(", "dockerCli", ",", "opts", ")", "\n", "}", ",", "}", "\n\n", "flags", ":=", "cmd", ".", "Flags", "(", ")", "\n\n", "flags", ".", "BoolVarP", "(", "&", "opts", ".", "human", ",", "\"", "\"", ",", "\"", "\"", ",", "true", ",", "\"", "\"", ")", "\n", "flags", ".", "BoolVarP", "(", "&", "opts", ".", "quiet", ",", "\"", "\"", ",", "\"", "\"", ",", "false", ",", "\"", "\"", ")", "\n", "flags", ".", "BoolVar", "(", "&", "opts", ".", "noTrunc", ",", "\"", "\"", ",", "false", ",", "\"", "\"", ")", "\n", "flags", ".", "StringVar", "(", "&", "opts", ".", "format", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "return", "cmd", "\n", "}" ]
// NewHistoryCommand creates a new `docker history` command
[ "NewHistoryCommand", "creates", "a", "new", "docker", "history", "command" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/image/history.go#L22-L43
train
docker/cli
cli/command/formatter/buildcache.go
NewBuildCacheFormat
func NewBuildCacheFormat(source string, quiet bool) Format { switch source { case TableFormatKey: if quiet { return DefaultQuietFormat } return Format(defaultBuildCacheTableFormat) case RawFormatKey: if quiet { return `build_cache_id: {{.ID}}` } format := `build_cache_id: {{.ID}} parent_id: {{.Parent}} build_cache_type: {{.CacheType}} description: {{.Description}} created_at: {{.CreatedAt}} created_since: {{.CreatedSince}} last_used_at: {{.LastUsedAt}} last_used_since: {{.LastUsedSince}} usage_count: {{.UsageCount}} in_use: {{.InUse}} shared: {{.Shared}} ` return Format(format) } return Format(source) }
go
func NewBuildCacheFormat(source string, quiet bool) Format { switch source { case TableFormatKey: if quiet { return DefaultQuietFormat } return Format(defaultBuildCacheTableFormat) case RawFormatKey: if quiet { return `build_cache_id: {{.ID}}` } format := `build_cache_id: {{.ID}} parent_id: {{.Parent}} build_cache_type: {{.CacheType}} description: {{.Description}} created_at: {{.CreatedAt}} created_since: {{.CreatedSince}} last_used_at: {{.LastUsedAt}} last_used_since: {{.LastUsedSince}} usage_count: {{.UsageCount}} in_use: {{.InUse}} shared: {{.Shared}} ` return Format(format) } return Format(source) }
[ "func", "NewBuildCacheFormat", "(", "source", "string", ",", "quiet", "bool", ")", "Format", "{", "switch", "source", "{", "case", "TableFormatKey", ":", "if", "quiet", "{", "return", "DefaultQuietFormat", "\n", "}", "\n", "return", "Format", "(", "defaultBuildCacheTableFormat", ")", "\n", "case", "RawFormatKey", ":", "if", "quiet", "{", "return", "`build_cache_id: {{.ID}}`", "\n", "}", "\n", "format", ":=", "`build_cache_id: {{.ID}}\nparent_id: {{.Parent}}\nbuild_cache_type: {{.CacheType}}\ndescription: {{.Description}}\ncreated_at: {{.CreatedAt}}\ncreated_since: {{.CreatedSince}}\nlast_used_at: {{.LastUsedAt}}\nlast_used_since: {{.LastUsedSince}}\nusage_count: {{.UsageCount}}\nin_use: {{.InUse}}\nshared: {{.Shared}}\n`", "\n", "return", "Format", "(", "format", ")", "\n", "}", "\n", "return", "Format", "(", "source", ")", "\n", "}" ]
// NewBuildCacheFormat returns a Format for rendering using a Context
[ "NewBuildCacheFormat", "returns", "a", "Format", "for", "rendering", "using", "a", "Context" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/formatter/buildcache.go#L27-L53
train
docker/cli
cli/command/formatter/buildcache.go
BuildCacheWrite
func BuildCacheWrite(ctx Context, buildCaches []*types.BuildCache) error { render := func(format func(subContext SubContext) error) error { buildCacheSort(buildCaches) for _, bc := range buildCaches { err := format(&buildCacheContext{trunc: ctx.Trunc, v: bc}) if err != nil { return err } } return nil } return ctx.Write(newBuildCacheContext(), render) }
go
func BuildCacheWrite(ctx Context, buildCaches []*types.BuildCache) error { render := func(format func(subContext SubContext) error) error { buildCacheSort(buildCaches) for _, bc := range buildCaches { err := format(&buildCacheContext{trunc: ctx.Trunc, v: bc}) if err != nil { return err } } return nil } return ctx.Write(newBuildCacheContext(), render) }
[ "func", "BuildCacheWrite", "(", "ctx", "Context", ",", "buildCaches", "[", "]", "*", "types", ".", "BuildCache", ")", "error", "{", "render", ":=", "func", "(", "format", "func", "(", "subContext", "SubContext", ")", "error", ")", "error", "{", "buildCacheSort", "(", "buildCaches", ")", "\n", "for", "_", ",", "bc", ":=", "range", "buildCaches", "{", "err", ":=", "format", "(", "&", "buildCacheContext", "{", "trunc", ":", "ctx", ".", "Trunc", ",", "v", ":", "bc", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "return", "ctx", ".", "Write", "(", "newBuildCacheContext", "(", ")", ",", "render", ")", "\n", "}" ]
// BuildCacheWrite renders the context for a list of containers
[ "BuildCacheWrite", "renders", "the", "context", "for", "a", "list", "of", "containers" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/formatter/buildcache.go#L74-L86
train
docker/cli
cli/config/configfile/file.go
New
func New(fn string) *ConfigFile { return &ConfigFile{ AuthConfigs: make(map[string]types.AuthConfig), HTTPHeaders: make(map[string]string), Filename: fn, Plugins: make(map[string]map[string]string), Aliases: make(map[string]string), } }
go
func New(fn string) *ConfigFile { return &ConfigFile{ AuthConfigs: make(map[string]types.AuthConfig), HTTPHeaders: make(map[string]string), Filename: fn, Plugins: make(map[string]map[string]string), Aliases: make(map[string]string), } }
[ "func", "New", "(", "fn", "string", ")", "*", "ConfigFile", "{", "return", "&", "ConfigFile", "{", "AuthConfigs", ":", "make", "(", "map", "[", "string", "]", "types", ".", "AuthConfig", ")", ",", "HTTPHeaders", ":", "make", "(", "map", "[", "string", "]", "string", ")", ",", "Filename", ":", "fn", ",", "Plugins", ":", "make", "(", "map", "[", "string", "]", "map", "[", "string", "]", "string", ")", ",", "Aliases", ":", "make", "(", "map", "[", "string", "]", "string", ")", ",", "}", "\n", "}" ]
// New initializes an empty configuration file for the given filename 'fn'
[ "New", "initializes", "an", "empty", "configuration", "file", "for", "the", "given", "filename", "fn" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/config/configfile/file.go#L70-L78
train
docker/cli
cli/config/configfile/file.go
LegacyLoadFromReader
func (configFile *ConfigFile) LegacyLoadFromReader(configData io.Reader) error { b, err := ioutil.ReadAll(configData) if err != nil { return err } if err := json.Unmarshal(b, &configFile.AuthConfigs); err != nil { arr := strings.Split(string(b), "\n") if len(arr) < 2 { return errors.Errorf("The Auth config file is empty") } authConfig := types.AuthConfig{} origAuth := strings.Split(arr[0], " = ") if len(origAuth) != 2 { return errors.Errorf("Invalid Auth config file") } authConfig.Username, authConfig.Password, err = decodeAuth(origAuth[1]) if err != nil { return err } authConfig.ServerAddress = defaultIndexServer configFile.AuthConfigs[defaultIndexServer] = authConfig } else { for k, authConfig := range configFile.AuthConfigs { authConfig.Username, authConfig.Password, err = decodeAuth(authConfig.Auth) if err != nil { return err } authConfig.Auth = "" authConfig.ServerAddress = k configFile.AuthConfigs[k] = authConfig } } return nil }
go
func (configFile *ConfigFile) LegacyLoadFromReader(configData io.Reader) error { b, err := ioutil.ReadAll(configData) if err != nil { return err } if err := json.Unmarshal(b, &configFile.AuthConfigs); err != nil { arr := strings.Split(string(b), "\n") if len(arr) < 2 { return errors.Errorf("The Auth config file is empty") } authConfig := types.AuthConfig{} origAuth := strings.Split(arr[0], " = ") if len(origAuth) != 2 { return errors.Errorf("Invalid Auth config file") } authConfig.Username, authConfig.Password, err = decodeAuth(origAuth[1]) if err != nil { return err } authConfig.ServerAddress = defaultIndexServer configFile.AuthConfigs[defaultIndexServer] = authConfig } else { for k, authConfig := range configFile.AuthConfigs { authConfig.Username, authConfig.Password, err = decodeAuth(authConfig.Auth) if err != nil { return err } authConfig.Auth = "" authConfig.ServerAddress = k configFile.AuthConfigs[k] = authConfig } } return nil }
[ "func", "(", "configFile", "*", "ConfigFile", ")", "LegacyLoadFromReader", "(", "configData", "io", ".", "Reader", ")", "error", "{", "b", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "configData", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "b", ",", "&", "configFile", ".", "AuthConfigs", ")", ";", "err", "!=", "nil", "{", "arr", ":=", "strings", ".", "Split", "(", "string", "(", "b", ")", ",", "\"", "\\n", "\"", ")", "\n", "if", "len", "(", "arr", ")", "<", "2", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "authConfig", ":=", "types", ".", "AuthConfig", "{", "}", "\n", "origAuth", ":=", "strings", ".", "Split", "(", "arr", "[", "0", "]", ",", "\"", "\"", ")", "\n", "if", "len", "(", "origAuth", ")", "!=", "2", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "authConfig", ".", "Username", ",", "authConfig", ".", "Password", ",", "err", "=", "decodeAuth", "(", "origAuth", "[", "1", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "authConfig", ".", "ServerAddress", "=", "defaultIndexServer", "\n", "configFile", ".", "AuthConfigs", "[", "defaultIndexServer", "]", "=", "authConfig", "\n", "}", "else", "{", "for", "k", ",", "authConfig", ":=", "range", "configFile", ".", "AuthConfigs", "{", "authConfig", ".", "Username", ",", "authConfig", ".", "Password", ",", "err", "=", "decodeAuth", "(", "authConfig", ".", "Auth", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "authConfig", ".", "Auth", "=", "\"", "\"", "\n", "authConfig", ".", "ServerAddress", "=", "k", "\n", "configFile", ".", "AuthConfigs", "[", "k", "]", "=", "authConfig", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// LegacyLoadFromReader reads the non-nested configuration data given and sets up the // auth config information with given directory and populates the receiver object
[ "LegacyLoadFromReader", "reads", "the", "non", "-", "nested", "configuration", "data", "given", "and", "sets", "up", "the", "auth", "config", "information", "with", "given", "directory", "and", "populates", "the", "receiver", "object" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/config/configfile/file.go#L82-L116
train
docker/cli
cli/config/configfile/file.go
LoadFromReader
func (configFile *ConfigFile) LoadFromReader(configData io.Reader) error { if err := json.NewDecoder(configData).Decode(&configFile); err != nil { return err } var err error for addr, ac := range configFile.AuthConfigs { ac.Username, ac.Password, err = decodeAuth(ac.Auth) if err != nil { return err } ac.Auth = "" ac.ServerAddress = addr configFile.AuthConfigs[addr] = ac } return checkKubernetesConfiguration(configFile.Kubernetes) }
go
func (configFile *ConfigFile) LoadFromReader(configData io.Reader) error { if err := json.NewDecoder(configData).Decode(&configFile); err != nil { return err } var err error for addr, ac := range configFile.AuthConfigs { ac.Username, ac.Password, err = decodeAuth(ac.Auth) if err != nil { return err } ac.Auth = "" ac.ServerAddress = addr configFile.AuthConfigs[addr] = ac } return checkKubernetesConfiguration(configFile.Kubernetes) }
[ "func", "(", "configFile", "*", "ConfigFile", ")", "LoadFromReader", "(", "configData", "io", ".", "Reader", ")", "error", "{", "if", "err", ":=", "json", ".", "NewDecoder", "(", "configData", ")", ".", "Decode", "(", "&", "configFile", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "var", "err", "error", "\n", "for", "addr", ",", "ac", ":=", "range", "configFile", ".", "AuthConfigs", "{", "ac", ".", "Username", ",", "ac", ".", "Password", ",", "err", "=", "decodeAuth", "(", "ac", ".", "Auth", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "ac", ".", "Auth", "=", "\"", "\"", "\n", "ac", ".", "ServerAddress", "=", "addr", "\n", "configFile", ".", "AuthConfigs", "[", "addr", "]", "=", "ac", "\n", "}", "\n", "return", "checkKubernetesConfiguration", "(", "configFile", ".", "Kubernetes", ")", "\n", "}" ]
// LoadFromReader reads the configuration data given and sets up the auth config // information with given directory and populates the receiver object
[ "LoadFromReader", "reads", "the", "configuration", "data", "given", "and", "sets", "up", "the", "auth", "config", "information", "with", "given", "directory", "and", "populates", "the", "receiver", "object" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/config/configfile/file.go#L120-L135
train
docker/cli
cli/config/configfile/file.go
ContainsAuth
func (configFile *ConfigFile) ContainsAuth() bool { return configFile.CredentialsStore != "" || len(configFile.CredentialHelpers) > 0 || len(configFile.AuthConfigs) > 0 }
go
func (configFile *ConfigFile) ContainsAuth() bool { return configFile.CredentialsStore != "" || len(configFile.CredentialHelpers) > 0 || len(configFile.AuthConfigs) > 0 }
[ "func", "(", "configFile", "*", "ConfigFile", ")", "ContainsAuth", "(", ")", "bool", "{", "return", "configFile", ".", "CredentialsStore", "!=", "\"", "\"", "||", "len", "(", "configFile", ".", "CredentialHelpers", ")", ">", "0", "||", "len", "(", "configFile", ".", "AuthConfigs", ")", ">", "0", "\n", "}" ]
// ContainsAuth returns whether there is authentication configured // in this file or not.
[ "ContainsAuth", "returns", "whether", "there", "is", "authentication", "configured", "in", "this", "file", "or", "not", "." ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/config/configfile/file.go#L139-L143
train
docker/cli
cli/config/configfile/file.go
SaveToWriter
func (configFile *ConfigFile) SaveToWriter(writer io.Writer) error { // Encode sensitive data into a new/temp struct tmpAuthConfigs := make(map[string]types.AuthConfig, len(configFile.AuthConfigs)) for k, authConfig := range configFile.AuthConfigs { authCopy := authConfig // encode and save the authstring, while blanking out the original fields authCopy.Auth = encodeAuth(&authCopy) authCopy.Username = "" authCopy.Password = "" authCopy.ServerAddress = "" tmpAuthConfigs[k] = authCopy } saveAuthConfigs := configFile.AuthConfigs configFile.AuthConfigs = tmpAuthConfigs defer func() { configFile.AuthConfigs = saveAuthConfigs }() data, err := json.MarshalIndent(configFile, "", "\t") if err != nil { return err } _, err = writer.Write(data) return err }
go
func (configFile *ConfigFile) SaveToWriter(writer io.Writer) error { // Encode sensitive data into a new/temp struct tmpAuthConfigs := make(map[string]types.AuthConfig, len(configFile.AuthConfigs)) for k, authConfig := range configFile.AuthConfigs { authCopy := authConfig // encode and save the authstring, while blanking out the original fields authCopy.Auth = encodeAuth(&authCopy) authCopy.Username = "" authCopy.Password = "" authCopy.ServerAddress = "" tmpAuthConfigs[k] = authCopy } saveAuthConfigs := configFile.AuthConfigs configFile.AuthConfigs = tmpAuthConfigs defer func() { configFile.AuthConfigs = saveAuthConfigs }() data, err := json.MarshalIndent(configFile, "", "\t") if err != nil { return err } _, err = writer.Write(data) return err }
[ "func", "(", "configFile", "*", "ConfigFile", ")", "SaveToWriter", "(", "writer", "io", ".", "Writer", ")", "error", "{", "// Encode sensitive data into a new/temp struct", "tmpAuthConfigs", ":=", "make", "(", "map", "[", "string", "]", "types", ".", "AuthConfig", ",", "len", "(", "configFile", ".", "AuthConfigs", ")", ")", "\n", "for", "k", ",", "authConfig", ":=", "range", "configFile", ".", "AuthConfigs", "{", "authCopy", ":=", "authConfig", "\n", "// encode and save the authstring, while blanking out the original fields", "authCopy", ".", "Auth", "=", "encodeAuth", "(", "&", "authCopy", ")", "\n", "authCopy", ".", "Username", "=", "\"", "\"", "\n", "authCopy", ".", "Password", "=", "\"", "\"", "\n", "authCopy", ".", "ServerAddress", "=", "\"", "\"", "\n", "tmpAuthConfigs", "[", "k", "]", "=", "authCopy", "\n", "}", "\n\n", "saveAuthConfigs", ":=", "configFile", ".", "AuthConfigs", "\n", "configFile", ".", "AuthConfigs", "=", "tmpAuthConfigs", "\n", "defer", "func", "(", ")", "{", "configFile", ".", "AuthConfigs", "=", "saveAuthConfigs", "}", "(", ")", "\n\n", "data", ",", "err", ":=", "json", ".", "MarshalIndent", "(", "configFile", ",", "\"", "\"", ",", "\"", "\\t", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "_", ",", "err", "=", "writer", ".", "Write", "(", "data", ")", "\n", "return", "err", "\n", "}" ]
// SaveToWriter encodes and writes out all the authorization information to // the given writer
[ "SaveToWriter", "encodes", "and", "writes", "out", "all", "the", "authorization", "information", "to", "the", "given", "writer" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/config/configfile/file.go#L152-L175
train
docker/cli
cli/config/configfile/file.go
ParseProxyConfig
func (configFile *ConfigFile) ParseProxyConfig(host string, runOpts map[string]*string) map[string]*string { var cfgKey string if _, ok := configFile.Proxies[host]; !ok { cfgKey = "default" } else { cfgKey = host } config := configFile.Proxies[cfgKey] permitted := map[string]*string{ "HTTP_PROXY": &config.HTTPProxy, "HTTPS_PROXY": &config.HTTPSProxy, "NO_PROXY": &config.NoProxy, "FTP_PROXY": &config.FTPProxy, } m := runOpts if m == nil { m = make(map[string]*string) } for k := range permitted { if *permitted[k] == "" { continue } if _, ok := m[k]; !ok { m[k] = permitted[k] } if _, ok := m[strings.ToLower(k)]; !ok { m[strings.ToLower(k)] = permitted[k] } } return m }
go
func (configFile *ConfigFile) ParseProxyConfig(host string, runOpts map[string]*string) map[string]*string { var cfgKey string if _, ok := configFile.Proxies[host]; !ok { cfgKey = "default" } else { cfgKey = host } config := configFile.Proxies[cfgKey] permitted := map[string]*string{ "HTTP_PROXY": &config.HTTPProxy, "HTTPS_PROXY": &config.HTTPSProxy, "NO_PROXY": &config.NoProxy, "FTP_PROXY": &config.FTPProxy, } m := runOpts if m == nil { m = make(map[string]*string) } for k := range permitted { if *permitted[k] == "" { continue } if _, ok := m[k]; !ok { m[k] = permitted[k] } if _, ok := m[strings.ToLower(k)]; !ok { m[strings.ToLower(k)] = permitted[k] } } return m }
[ "func", "(", "configFile", "*", "ConfigFile", ")", "ParseProxyConfig", "(", "host", "string", ",", "runOpts", "map", "[", "string", "]", "*", "string", ")", "map", "[", "string", "]", "*", "string", "{", "var", "cfgKey", "string", "\n\n", "if", "_", ",", "ok", ":=", "configFile", ".", "Proxies", "[", "host", "]", ";", "!", "ok", "{", "cfgKey", "=", "\"", "\"", "\n", "}", "else", "{", "cfgKey", "=", "host", "\n", "}", "\n\n", "config", ":=", "configFile", ".", "Proxies", "[", "cfgKey", "]", "\n", "permitted", ":=", "map", "[", "string", "]", "*", "string", "{", "\"", "\"", ":", "&", "config", ".", "HTTPProxy", ",", "\"", "\"", ":", "&", "config", ".", "HTTPSProxy", ",", "\"", "\"", ":", "&", "config", ".", "NoProxy", ",", "\"", "\"", ":", "&", "config", ".", "FTPProxy", ",", "}", "\n", "m", ":=", "runOpts", "\n", "if", "m", "==", "nil", "{", "m", "=", "make", "(", "map", "[", "string", "]", "*", "string", ")", "\n", "}", "\n", "for", "k", ":=", "range", "permitted", "{", "if", "*", "permitted", "[", "k", "]", "==", "\"", "\"", "{", "continue", "\n", "}", "\n", "if", "_", ",", "ok", ":=", "m", "[", "k", "]", ";", "!", "ok", "{", "m", "[", "k", "]", "=", "permitted", "[", "k", "]", "\n", "}", "\n", "if", "_", ",", "ok", ":=", "m", "[", "strings", ".", "ToLower", "(", "k", ")", "]", ";", "!", "ok", "{", "m", "[", "strings", ".", "ToLower", "(", "k", ")", "]", "=", "permitted", "[", "k", "]", "\n", "}", "\n", "}", "\n", "return", "m", "\n", "}" ]
// ParseProxyConfig computes proxy configuration by retrieving the config for the provided host and // then checking this against any environment variables provided to the container
[ "ParseProxyConfig", "computes", "proxy", "configuration", "by", "retrieving", "the", "config", "for", "the", "provided", "host", "and", "then", "checking", "this", "against", "any", "environment", "variables", "provided", "to", "the", "container" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/config/configfile/file.go#L202-L234
train
docker/cli
cli/config/configfile/file.go
encodeAuth
func encodeAuth(authConfig *types.AuthConfig) string { if authConfig.Username == "" && authConfig.Password == "" { return "" } authStr := authConfig.Username + ":" + authConfig.Password msg := []byte(authStr) encoded := make([]byte, base64.StdEncoding.EncodedLen(len(msg))) base64.StdEncoding.Encode(encoded, msg) return string(encoded) }
go
func encodeAuth(authConfig *types.AuthConfig) string { if authConfig.Username == "" && authConfig.Password == "" { return "" } authStr := authConfig.Username + ":" + authConfig.Password msg := []byte(authStr) encoded := make([]byte, base64.StdEncoding.EncodedLen(len(msg))) base64.StdEncoding.Encode(encoded, msg) return string(encoded) }
[ "func", "encodeAuth", "(", "authConfig", "*", "types", ".", "AuthConfig", ")", "string", "{", "if", "authConfig", ".", "Username", "==", "\"", "\"", "&&", "authConfig", ".", "Password", "==", "\"", "\"", "{", "return", "\"", "\"", "\n", "}", "\n\n", "authStr", ":=", "authConfig", ".", "Username", "+", "\"", "\"", "+", "authConfig", ".", "Password", "\n", "msg", ":=", "[", "]", "byte", "(", "authStr", ")", "\n", "encoded", ":=", "make", "(", "[", "]", "byte", ",", "base64", ".", "StdEncoding", ".", "EncodedLen", "(", "len", "(", "msg", ")", ")", ")", "\n", "base64", ".", "StdEncoding", ".", "Encode", "(", "encoded", ",", "msg", ")", "\n", "return", "string", "(", "encoded", ")", "\n", "}" ]
// encodeAuth creates a base64 encoded string to containing authorization information
[ "encodeAuth", "creates", "a", "base64", "encoded", "string", "to", "containing", "authorization", "information" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/config/configfile/file.go#L237-L247
train
docker/cli
cli/config/configfile/file.go
decodeAuth
func decodeAuth(authStr string) (string, string, error) { if authStr == "" { return "", "", nil } decLen := base64.StdEncoding.DecodedLen(len(authStr)) decoded := make([]byte, decLen) authByte := []byte(authStr) n, err := base64.StdEncoding.Decode(decoded, authByte) if err != nil { return "", "", err } if n > decLen { return "", "", errors.Errorf("Something went wrong decoding auth config") } arr := strings.SplitN(string(decoded), ":", 2) if len(arr) != 2 { return "", "", errors.Errorf("Invalid auth configuration file") } password := strings.Trim(arr[1], "\x00") return arr[0], password, nil }
go
func decodeAuth(authStr string) (string, string, error) { if authStr == "" { return "", "", nil } decLen := base64.StdEncoding.DecodedLen(len(authStr)) decoded := make([]byte, decLen) authByte := []byte(authStr) n, err := base64.StdEncoding.Decode(decoded, authByte) if err != nil { return "", "", err } if n > decLen { return "", "", errors.Errorf("Something went wrong decoding auth config") } arr := strings.SplitN(string(decoded), ":", 2) if len(arr) != 2 { return "", "", errors.Errorf("Invalid auth configuration file") } password := strings.Trim(arr[1], "\x00") return arr[0], password, nil }
[ "func", "decodeAuth", "(", "authStr", "string", ")", "(", "string", ",", "string", ",", "error", ")", "{", "if", "authStr", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "\"", "\"", ",", "nil", "\n", "}", "\n\n", "decLen", ":=", "base64", ".", "StdEncoding", ".", "DecodedLen", "(", "len", "(", "authStr", ")", ")", "\n", "decoded", ":=", "make", "(", "[", "]", "byte", ",", "decLen", ")", "\n", "authByte", ":=", "[", "]", "byte", "(", "authStr", ")", "\n", "n", ",", "err", ":=", "base64", ".", "StdEncoding", ".", "Decode", "(", "decoded", ",", "authByte", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "\"", "\"", ",", "err", "\n", "}", "\n", "if", "n", ">", "decLen", "{", "return", "\"", "\"", ",", "\"", "\"", ",", "errors", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "arr", ":=", "strings", ".", "SplitN", "(", "string", "(", "decoded", ")", ",", "\"", "\"", ",", "2", ")", "\n", "if", "len", "(", "arr", ")", "!=", "2", "{", "return", "\"", "\"", ",", "\"", "\"", ",", "errors", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "password", ":=", "strings", ".", "Trim", "(", "arr", "[", "1", "]", ",", "\"", "\\x00", "\"", ")", "\n", "return", "arr", "[", "0", "]", ",", "password", ",", "nil", "\n", "}" ]
// decodeAuth decodes a base64 encoded string and returns username and password
[ "decodeAuth", "decodes", "a", "base64", "encoded", "string", "and", "returns", "username", "and", "password" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/config/configfile/file.go#L250-L271
train
docker/cli
cli/config/configfile/file.go
GetCredentialsStore
func (configFile *ConfigFile) GetCredentialsStore(registryHostname string) credentials.Store { if helper := getConfiguredCredentialStore(configFile, registryHostname); helper != "" { return newNativeStore(configFile, helper) } return credentials.NewFileStore(configFile) }
go
func (configFile *ConfigFile) GetCredentialsStore(registryHostname string) credentials.Store { if helper := getConfiguredCredentialStore(configFile, registryHostname); helper != "" { return newNativeStore(configFile, helper) } return credentials.NewFileStore(configFile) }
[ "func", "(", "configFile", "*", "ConfigFile", ")", "GetCredentialsStore", "(", "registryHostname", "string", ")", "credentials", ".", "Store", "{", "if", "helper", ":=", "getConfiguredCredentialStore", "(", "configFile", ",", "registryHostname", ")", ";", "helper", "!=", "\"", "\"", "{", "return", "newNativeStore", "(", "configFile", ",", "helper", ")", "\n", "}", "\n", "return", "credentials", ".", "NewFileStore", "(", "configFile", ")", "\n", "}" ]
// GetCredentialsStore returns a new credentials store from the settings in the // configuration file
[ "GetCredentialsStore", "returns", "a", "new", "credentials", "store", "from", "the", "settings", "in", "the", "configuration", "file" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/config/configfile/file.go#L275-L280
train
docker/cli
cli/config/configfile/file.go
GetAuthConfig
func (configFile *ConfigFile) GetAuthConfig(registryHostname string) (types.AuthConfig, error) { return configFile.GetCredentialsStore(registryHostname).Get(registryHostname) }
go
func (configFile *ConfigFile) GetAuthConfig(registryHostname string) (types.AuthConfig, error) { return configFile.GetCredentialsStore(registryHostname).Get(registryHostname) }
[ "func", "(", "configFile", "*", "ConfigFile", ")", "GetAuthConfig", "(", "registryHostname", "string", ")", "(", "types", ".", "AuthConfig", ",", "error", ")", "{", "return", "configFile", ".", "GetCredentialsStore", "(", "registryHostname", ")", ".", "Get", "(", "registryHostname", ")", "\n", "}" ]
// GetAuthConfig for a repository from the credential store
[ "GetAuthConfig", "for", "a", "repository", "from", "the", "credential", "store" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/config/configfile/file.go#L288-L290
train
docker/cli
cli/config/configfile/file.go
getConfiguredCredentialStore
func getConfiguredCredentialStore(c *ConfigFile, registryHostname string) string { if c.CredentialHelpers != nil && registryHostname != "" { if helper, exists := c.CredentialHelpers[registryHostname]; exists { return helper } } return c.CredentialsStore }
go
func getConfiguredCredentialStore(c *ConfigFile, registryHostname string) string { if c.CredentialHelpers != nil && registryHostname != "" { if helper, exists := c.CredentialHelpers[registryHostname]; exists { return helper } } return c.CredentialsStore }
[ "func", "getConfiguredCredentialStore", "(", "c", "*", "ConfigFile", ",", "registryHostname", "string", ")", "string", "{", "if", "c", ".", "CredentialHelpers", "!=", "nil", "&&", "registryHostname", "!=", "\"", "\"", "{", "if", "helper", ",", "exists", ":=", "c", ".", "CredentialHelpers", "[", "registryHostname", "]", ";", "exists", "{", "return", "helper", "\n", "}", "\n", "}", "\n", "return", "c", ".", "CredentialsStore", "\n", "}" ]
// getConfiguredCredentialStore returns the credential helper configured for the // given registry, the default credsStore, or the empty string if neither are // configured.
[ "getConfiguredCredentialStore", "returns", "the", "credential", "helper", "configured", "for", "the", "given", "registry", "the", "default", "credsStore", "or", "the", "empty", "string", "if", "neither", "are", "configured", "." ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/config/configfile/file.go#L295-L302
train
docker/cli
cli/config/configfile/file.go
GetAllCredentials
func (configFile *ConfigFile) GetAllCredentials() (map[string]types.AuthConfig, error) { auths := make(map[string]types.AuthConfig) addAll := func(from map[string]types.AuthConfig) { for reg, ac := range from { auths[reg] = ac } } defaultStore := configFile.GetCredentialsStore("") newAuths, err := defaultStore.GetAll() if err != nil { return nil, err } addAll(newAuths) // Auth configs from a registry-specific helper should override those from the default store. for registryHostname := range configFile.CredentialHelpers { newAuth, err := configFile.GetAuthConfig(registryHostname) if err != nil { return nil, err } auths[registryHostname] = newAuth } return auths, nil }
go
func (configFile *ConfigFile) GetAllCredentials() (map[string]types.AuthConfig, error) { auths := make(map[string]types.AuthConfig) addAll := func(from map[string]types.AuthConfig) { for reg, ac := range from { auths[reg] = ac } } defaultStore := configFile.GetCredentialsStore("") newAuths, err := defaultStore.GetAll() if err != nil { return nil, err } addAll(newAuths) // Auth configs from a registry-specific helper should override those from the default store. for registryHostname := range configFile.CredentialHelpers { newAuth, err := configFile.GetAuthConfig(registryHostname) if err != nil { return nil, err } auths[registryHostname] = newAuth } return auths, nil }
[ "func", "(", "configFile", "*", "ConfigFile", ")", "GetAllCredentials", "(", ")", "(", "map", "[", "string", "]", "types", ".", "AuthConfig", ",", "error", ")", "{", "auths", ":=", "make", "(", "map", "[", "string", "]", "types", ".", "AuthConfig", ")", "\n", "addAll", ":=", "func", "(", "from", "map", "[", "string", "]", "types", ".", "AuthConfig", ")", "{", "for", "reg", ",", "ac", ":=", "range", "from", "{", "auths", "[", "reg", "]", "=", "ac", "\n", "}", "\n", "}", "\n\n", "defaultStore", ":=", "configFile", ".", "GetCredentialsStore", "(", "\"", "\"", ")", "\n", "newAuths", ",", "err", ":=", "defaultStore", ".", "GetAll", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "addAll", "(", "newAuths", ")", "\n\n", "// Auth configs from a registry-specific helper should override those from the default store.", "for", "registryHostname", ":=", "range", "configFile", ".", "CredentialHelpers", "{", "newAuth", ",", "err", ":=", "configFile", ".", "GetAuthConfig", "(", "registryHostname", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "auths", "[", "registryHostname", "]", "=", "newAuth", "\n", "}", "\n", "return", "auths", ",", "nil", "\n", "}" ]
// GetAllCredentials returns all of the credentials stored in all of the // configured credential stores.
[ "GetAllCredentials", "returns", "all", "of", "the", "credentials", "stored", "in", "all", "of", "the", "configured", "credential", "stores", "." ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/config/configfile/file.go#L306-L330
train
docker/cli
cli/config/configfile/file.go
PluginConfig
func (configFile *ConfigFile) PluginConfig(pluginname, option string) (string, bool) { if configFile.Plugins == nil { return "", false } pluginConfig, ok := configFile.Plugins[pluginname] if !ok { return "", false } value, ok := pluginConfig[option] return value, ok }
go
func (configFile *ConfigFile) PluginConfig(pluginname, option string) (string, bool) { if configFile.Plugins == nil { return "", false } pluginConfig, ok := configFile.Plugins[pluginname] if !ok { return "", false } value, ok := pluginConfig[option] return value, ok }
[ "func", "(", "configFile", "*", "ConfigFile", ")", "PluginConfig", "(", "pluginname", ",", "option", "string", ")", "(", "string", ",", "bool", ")", "{", "if", "configFile", ".", "Plugins", "==", "nil", "{", "return", "\"", "\"", ",", "false", "\n", "}", "\n", "pluginConfig", ",", "ok", ":=", "configFile", ".", "Plugins", "[", "pluginname", "]", "\n", "if", "!", "ok", "{", "return", "\"", "\"", ",", "false", "\n", "}", "\n", "value", ",", "ok", ":=", "pluginConfig", "[", "option", "]", "\n", "return", "value", ",", "ok", "\n", "}" ]
// PluginConfig retrieves the requested option for the given plugin.
[ "PluginConfig", "retrieves", "the", "requested", "option", "for", "the", "given", "plugin", "." ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/config/configfile/file.go#L338-L348
train
docker/cli
cli/config/configfile/file.go
SetPluginConfig
func (configFile *ConfigFile) SetPluginConfig(pluginname, option, value string) { if configFile.Plugins == nil { configFile.Plugins = make(map[string]map[string]string) } pluginConfig, ok := configFile.Plugins[pluginname] if !ok { pluginConfig = make(map[string]string) configFile.Plugins[pluginname] = pluginConfig } if value != "" { pluginConfig[option] = value } else { delete(pluginConfig, option) } if len(pluginConfig) == 0 { delete(configFile.Plugins, pluginname) } }
go
func (configFile *ConfigFile) SetPluginConfig(pluginname, option, value string) { if configFile.Plugins == nil { configFile.Plugins = make(map[string]map[string]string) } pluginConfig, ok := configFile.Plugins[pluginname] if !ok { pluginConfig = make(map[string]string) configFile.Plugins[pluginname] = pluginConfig } if value != "" { pluginConfig[option] = value } else { delete(pluginConfig, option) } if len(pluginConfig) == 0 { delete(configFile.Plugins, pluginname) } }
[ "func", "(", "configFile", "*", "ConfigFile", ")", "SetPluginConfig", "(", "pluginname", ",", "option", ",", "value", "string", ")", "{", "if", "configFile", ".", "Plugins", "==", "nil", "{", "configFile", ".", "Plugins", "=", "make", "(", "map", "[", "string", "]", "map", "[", "string", "]", "string", ")", "\n", "}", "\n", "pluginConfig", ",", "ok", ":=", "configFile", ".", "Plugins", "[", "pluginname", "]", "\n", "if", "!", "ok", "{", "pluginConfig", "=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "configFile", ".", "Plugins", "[", "pluginname", "]", "=", "pluginConfig", "\n", "}", "\n", "if", "value", "!=", "\"", "\"", "{", "pluginConfig", "[", "option", "]", "=", "value", "\n", "}", "else", "{", "delete", "(", "pluginConfig", ",", "option", ")", "\n", "}", "\n", "if", "len", "(", "pluginConfig", ")", "==", "0", "{", "delete", "(", "configFile", ".", "Plugins", ",", "pluginname", ")", "\n", "}", "\n", "}" ]
// SetPluginConfig sets the option to the given value for the given // plugin. Passing a value of "" will remove the option. If removing // the final config item for a given plugin then also cleans up the // overall plugin entry.
[ "SetPluginConfig", "sets", "the", "option", "to", "the", "given", "value", "for", "the", "given", "plugin", ".", "Passing", "a", "value", "of", "will", "remove", "the", "option", ".", "If", "removing", "the", "final", "config", "item", "for", "a", "given", "plugin", "then", "also", "cleans", "up", "the", "overall", "plugin", "entry", "." ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/config/configfile/file.go#L354-L371
train
docker/cli
cli/command/context/inspect.go
newInspectCommand
func newInspectCommand(dockerCli command.Cli) *cobra.Command { var opts inspectOptions cmd := &cobra.Command{ Use: "inspect [OPTIONS] [CONTEXT] [CONTEXT...]", Short: "Display detailed information on one or more contexts", RunE: func(cmd *cobra.Command, args []string) error { opts.refs = args if len(opts.refs) == 0 { if dockerCli.CurrentContext() == "" { return errors.New("no context specified") } opts.refs = []string{dockerCli.CurrentContext()} } return runInspect(dockerCli, opts) }, } flags := cmd.Flags() flags.StringVarP(&opts.format, "format", "f", "", "Format the output using the given Go template") return cmd }
go
func newInspectCommand(dockerCli command.Cli) *cobra.Command { var opts inspectOptions cmd := &cobra.Command{ Use: "inspect [OPTIONS] [CONTEXT] [CONTEXT...]", Short: "Display detailed information on one or more contexts", RunE: func(cmd *cobra.Command, args []string) error { opts.refs = args if len(opts.refs) == 0 { if dockerCli.CurrentContext() == "" { return errors.New("no context specified") } opts.refs = []string{dockerCli.CurrentContext()} } return runInspect(dockerCli, opts) }, } flags := cmd.Flags() flags.StringVarP(&opts.format, "format", "f", "", "Format the output using the given Go template") return cmd }
[ "func", "newInspectCommand", "(", "dockerCli", "command", ".", "Cli", ")", "*", "cobra", ".", "Command", "{", "var", "opts", "inspectOptions", "\n\n", "cmd", ":=", "&", "cobra", ".", "Command", "{", "Use", ":", "\"", "\"", ",", "Short", ":", "\"", "\"", ",", "RunE", ":", "func", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "error", "{", "opts", ".", "refs", "=", "args", "\n", "if", "len", "(", "opts", ".", "refs", ")", "==", "0", "{", "if", "dockerCli", ".", "CurrentContext", "(", ")", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "opts", ".", "refs", "=", "[", "]", "string", "{", "dockerCli", ".", "CurrentContext", "(", ")", "}", "\n", "}", "\n", "return", "runInspect", "(", "dockerCli", ",", "opts", ")", "\n", "}", ",", "}", "\n\n", "flags", ":=", "cmd", ".", "Flags", "(", ")", "\n", "flags", ".", "StringVarP", "(", "&", "opts", ".", "format", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "cmd", "\n", "}" ]
// newInspectCommand creates a new cobra.Command for `docker image inspect`
[ "newInspectCommand", "creates", "a", "new", "cobra", ".", "Command", "for", "docker", "image", "inspect" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/context/inspect.go#L18-L39
train
docker/cli
cli/command/manifest/inspect.go
newInspectCommand
func newInspectCommand(dockerCli command.Cli) *cobra.Command { var opts inspectOptions cmd := &cobra.Command{ Use: "inspect [OPTIONS] [MANIFEST_LIST] MANIFEST", Short: "Display an image manifest, or manifest list", Args: cli.RequiresRangeArgs(1, 2), RunE: func(cmd *cobra.Command, args []string) error { switch len(args) { case 1: opts.ref = args[0] case 2: opts.list = args[0] opts.ref = args[1] } return runInspect(dockerCli, opts) }, } flags := cmd.Flags() flags.BoolVar(&opts.insecure, "insecure", false, "Allow communication with an insecure registry") flags.BoolVarP(&opts.verbose, "verbose", "v", false, "Output additional info including layers and platform") return cmd }
go
func newInspectCommand(dockerCli command.Cli) *cobra.Command { var opts inspectOptions cmd := &cobra.Command{ Use: "inspect [OPTIONS] [MANIFEST_LIST] MANIFEST", Short: "Display an image manifest, or manifest list", Args: cli.RequiresRangeArgs(1, 2), RunE: func(cmd *cobra.Command, args []string) error { switch len(args) { case 1: opts.ref = args[0] case 2: opts.list = args[0] opts.ref = args[1] } return runInspect(dockerCli, opts) }, } flags := cmd.Flags() flags.BoolVar(&opts.insecure, "insecure", false, "Allow communication with an insecure registry") flags.BoolVarP(&opts.verbose, "verbose", "v", false, "Output additional info including layers and platform") return cmd }
[ "func", "newInspectCommand", "(", "dockerCli", "command", ".", "Cli", ")", "*", "cobra", ".", "Command", "{", "var", "opts", "inspectOptions", "\n\n", "cmd", ":=", "&", "cobra", ".", "Command", "{", "Use", ":", "\"", "\"", ",", "Short", ":", "\"", "\"", ",", "Args", ":", "cli", ".", "RequiresRangeArgs", "(", "1", ",", "2", ")", ",", "RunE", ":", "func", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "error", "{", "switch", "len", "(", "args", ")", "{", "case", "1", ":", "opts", ".", "ref", "=", "args", "[", "0", "]", "\n", "case", "2", ":", "opts", ".", "list", "=", "args", "[", "0", "]", "\n", "opts", ".", "ref", "=", "args", "[", "1", "]", "\n", "}", "\n", "return", "runInspect", "(", "dockerCli", ",", "opts", ")", "\n", "}", ",", "}", "\n\n", "flags", ":=", "cmd", ".", "Flags", "(", ")", "\n", "flags", ".", "BoolVar", "(", "&", "opts", ".", "insecure", ",", "\"", "\"", ",", "false", ",", "\"", "\"", ")", "\n", "flags", ".", "BoolVarP", "(", "&", "opts", ".", "verbose", ",", "\"", "\"", ",", "\"", "\"", ",", "false", ",", "\"", "\"", ")", "\n", "return", "cmd", "\n", "}" ]
// NewInspectCommand creates a new `docker manifest inspect` command
[ "NewInspectCommand", "creates", "a", "new", "docker", "manifest", "inspect", "command" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/manifest/inspect.go#L27-L50
train
docker/cli
cli/command/plugin/create.go
validateTag
func validateTag(rawRepo string) error { _, err := reference.ParseNormalizedNamed(rawRepo) return err }
go
func validateTag(rawRepo string) error { _, err := reference.ParseNormalizedNamed(rawRepo) return err }
[ "func", "validateTag", "(", "rawRepo", "string", ")", "error", "{", "_", ",", "err", ":=", "reference", ".", "ParseNormalizedNamed", "(", "rawRepo", ")", "\n\n", "return", "err", "\n", "}" ]
// validateTag checks if the given repoName can be resolved.
[ "validateTag", "checks", "if", "the", "given", "repoName", "can", "be", "resolved", "." ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/plugin/create.go#L22-L26
train
docker/cli
cli/command/plugin/create.go
validateConfig
func validateConfig(path string) error { dt, err := os.Open(filepath.Join(path, "config.json")) if err != nil { return err } m := types.PluginConfig{} err = json.NewDecoder(dt).Decode(&m) dt.Close() return err }
go
func validateConfig(path string) error { dt, err := os.Open(filepath.Join(path, "config.json")) if err != nil { return err } m := types.PluginConfig{} err = json.NewDecoder(dt).Decode(&m) dt.Close() return err }
[ "func", "validateConfig", "(", "path", "string", ")", "error", "{", "dt", ",", "err", ":=", "os", ".", "Open", "(", "filepath", ".", "Join", "(", "path", ",", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "m", ":=", "types", ".", "PluginConfig", "{", "}", "\n", "err", "=", "json", ".", "NewDecoder", "(", "dt", ")", ".", "Decode", "(", "&", "m", ")", "\n", "dt", ".", "Close", "(", ")", "\n\n", "return", "err", "\n", "}" ]
// validateConfig ensures that a valid config.json is available in the given path
[ "validateConfig", "ensures", "that", "a", "valid", "config", ".", "json", "is", "available", "in", "the", "given", "path" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/plugin/create.go#L29-L40
train
docker/cli
cli/command/plugin/create.go
validateContextDir
func validateContextDir(contextDir string) (string, error) { absContextDir, err := filepath.Abs(contextDir) if err != nil { return "", err } stat, err := os.Lstat(absContextDir) if err != nil { return "", err } if !stat.IsDir() { return "", errors.Errorf("context must be a directory") } return absContextDir, nil }
go
func validateContextDir(contextDir string) (string, error) { absContextDir, err := filepath.Abs(contextDir) if err != nil { return "", err } stat, err := os.Lstat(absContextDir) if err != nil { return "", err } if !stat.IsDir() { return "", errors.Errorf("context must be a directory") } return absContextDir, nil }
[ "func", "validateContextDir", "(", "contextDir", "string", ")", "(", "string", ",", "error", ")", "{", "absContextDir", ",", "err", ":=", "filepath", ".", "Abs", "(", "contextDir", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "stat", ",", "err", ":=", "os", ".", "Lstat", "(", "absContextDir", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "if", "!", "stat", ".", "IsDir", "(", ")", "{", "return", "\"", "\"", ",", "errors", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "absContextDir", ",", "nil", "\n", "}" ]
// validateContextDir validates the given dir and returns abs path on success.
[ "validateContextDir", "validates", "the", "given", "dir", "and", "returns", "abs", "path", "on", "success", "." ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/plugin/create.go#L43-L58
train
docker/cli
cli/command/context/update.go
RunUpdate
func RunUpdate(cli command.Cli, o *UpdateOptions) error { if err := validateContextName(o.Name); err != nil { return err } s := cli.ContextStore() c, err := s.GetMetadata(o.Name) if err != nil { return err } dockerContext, err := command.GetDockerContext(c) if err != nil { return err } if o.DefaultStackOrchestrator != "" { stackOrchestrator, err := command.NormalizeOrchestrator(o.DefaultStackOrchestrator) if err != nil { return errors.Wrap(err, "unable to parse default-stack-orchestrator") } dockerContext.StackOrchestrator = stackOrchestrator } if o.Description != "" { dockerContext.Description = o.Description } c.Metadata = dockerContext tlsDataToReset := make(map[string]*store.EndpointTLSData) if o.Docker != nil { dockerEP, dockerTLS, err := getDockerEndpointMetadataAndTLS(cli, o.Docker) if err != nil { return errors.Wrap(err, "unable to create docker endpoint config") } c.Endpoints[docker.DockerEndpoint] = dockerEP tlsDataToReset[docker.DockerEndpoint] = dockerTLS } if o.Kubernetes != nil { kubernetesEP, kubernetesTLS, err := getKubernetesEndpointMetadataAndTLS(cli, o.Kubernetes) if err != nil { return errors.Wrap(err, "unable to create kubernetes endpoint config") } if kubernetesEP == nil { delete(c.Endpoints, kubernetes.KubernetesEndpoint) } else { c.Endpoints[kubernetes.KubernetesEndpoint] = kubernetesEP tlsDataToReset[kubernetes.KubernetesEndpoint] = kubernetesTLS } } if err := validateEndpointsAndOrchestrator(c); err != nil { return err } if err := s.CreateOrUpdate(c); err != nil { return err } for ep, tlsData := range tlsDataToReset { if err := s.ResetEndpointTLSMaterial(o.Name, ep, tlsData); err != nil { return err } } fmt.Fprintln(cli.Out(), o.Name) fmt.Fprintf(cli.Err(), "Successfully updated context %q\n", o.Name) return nil }
go
func RunUpdate(cli command.Cli, o *UpdateOptions) error { if err := validateContextName(o.Name); err != nil { return err } s := cli.ContextStore() c, err := s.GetMetadata(o.Name) if err != nil { return err } dockerContext, err := command.GetDockerContext(c) if err != nil { return err } if o.DefaultStackOrchestrator != "" { stackOrchestrator, err := command.NormalizeOrchestrator(o.DefaultStackOrchestrator) if err != nil { return errors.Wrap(err, "unable to parse default-stack-orchestrator") } dockerContext.StackOrchestrator = stackOrchestrator } if o.Description != "" { dockerContext.Description = o.Description } c.Metadata = dockerContext tlsDataToReset := make(map[string]*store.EndpointTLSData) if o.Docker != nil { dockerEP, dockerTLS, err := getDockerEndpointMetadataAndTLS(cli, o.Docker) if err != nil { return errors.Wrap(err, "unable to create docker endpoint config") } c.Endpoints[docker.DockerEndpoint] = dockerEP tlsDataToReset[docker.DockerEndpoint] = dockerTLS } if o.Kubernetes != nil { kubernetesEP, kubernetesTLS, err := getKubernetesEndpointMetadataAndTLS(cli, o.Kubernetes) if err != nil { return errors.Wrap(err, "unable to create kubernetes endpoint config") } if kubernetesEP == nil { delete(c.Endpoints, kubernetes.KubernetesEndpoint) } else { c.Endpoints[kubernetes.KubernetesEndpoint] = kubernetesEP tlsDataToReset[kubernetes.KubernetesEndpoint] = kubernetesTLS } } if err := validateEndpointsAndOrchestrator(c); err != nil { return err } if err := s.CreateOrUpdate(c); err != nil { return err } for ep, tlsData := range tlsDataToReset { if err := s.ResetEndpointTLSMaterial(o.Name, ep, tlsData); err != nil { return err } } fmt.Fprintln(cli.Out(), o.Name) fmt.Fprintf(cli.Err(), "Successfully updated context %q\n", o.Name) return nil }
[ "func", "RunUpdate", "(", "cli", "command", ".", "Cli", ",", "o", "*", "UpdateOptions", ")", "error", "{", "if", "err", ":=", "validateContextName", "(", "o", ".", "Name", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "s", ":=", "cli", ".", "ContextStore", "(", ")", "\n", "c", ",", "err", ":=", "s", ".", "GetMetadata", "(", "o", ".", "Name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "dockerContext", ",", "err", ":=", "command", ".", "GetDockerContext", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "o", ".", "DefaultStackOrchestrator", "!=", "\"", "\"", "{", "stackOrchestrator", ",", "err", ":=", "command", ".", "NormalizeOrchestrator", "(", "o", ".", "DefaultStackOrchestrator", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "dockerContext", ".", "StackOrchestrator", "=", "stackOrchestrator", "\n", "}", "\n", "if", "o", ".", "Description", "!=", "\"", "\"", "{", "dockerContext", ".", "Description", "=", "o", ".", "Description", "\n", "}", "\n\n", "c", ".", "Metadata", "=", "dockerContext", "\n\n", "tlsDataToReset", ":=", "make", "(", "map", "[", "string", "]", "*", "store", ".", "EndpointTLSData", ")", "\n\n", "if", "o", ".", "Docker", "!=", "nil", "{", "dockerEP", ",", "dockerTLS", ",", "err", ":=", "getDockerEndpointMetadataAndTLS", "(", "cli", ",", "o", ".", "Docker", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "c", ".", "Endpoints", "[", "docker", ".", "DockerEndpoint", "]", "=", "dockerEP", "\n", "tlsDataToReset", "[", "docker", ".", "DockerEndpoint", "]", "=", "dockerTLS", "\n", "}", "\n", "if", "o", ".", "Kubernetes", "!=", "nil", "{", "kubernetesEP", ",", "kubernetesTLS", ",", "err", ":=", "getKubernetesEndpointMetadataAndTLS", "(", "cli", ",", "o", ".", "Kubernetes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "kubernetesEP", "==", "nil", "{", "delete", "(", "c", ".", "Endpoints", ",", "kubernetes", ".", "KubernetesEndpoint", ")", "\n", "}", "else", "{", "c", ".", "Endpoints", "[", "kubernetes", ".", "KubernetesEndpoint", "]", "=", "kubernetesEP", "\n", "tlsDataToReset", "[", "kubernetes", ".", "KubernetesEndpoint", "]", "=", "kubernetesTLS", "\n", "}", "\n", "}", "\n", "if", "err", ":=", "validateEndpointsAndOrchestrator", "(", "c", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "s", ".", "CreateOrUpdate", "(", "c", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "ep", ",", "tlsData", ":=", "range", "tlsDataToReset", "{", "if", "err", ":=", "s", ".", "ResetEndpointTLSMaterial", "(", "o", ".", "Name", ",", "ep", ",", "tlsData", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "fmt", ".", "Fprintln", "(", "cli", ".", "Out", "(", ")", ",", "o", ".", "Name", ")", "\n", "fmt", ".", "Fprintf", "(", "cli", ".", "Err", "(", ")", ",", "\"", "\\n", "\"", ",", "o", ".", "Name", ")", "\n", "return", "nil", "\n", "}" ]
// RunUpdate updates a Docker context
[ "RunUpdate", "updates", "a", "Docker", "context" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/context/update.go#L70-L133
train
docker/cli
cli/command/service/update.go
removeConfigs
func removeConfigs(flags *pflag.FlagSet, spec *swarm.ContainerSpec, credSpecName, credSpecID string) []*swarm.ConfigReference { keepConfigs := []*swarm.ConfigReference{} toRemove := buildToRemoveSet(flags, flagConfigRemove) // all configs in spec.Configs should have both a Name and ID, because // they come from an already-accepted spec. for _, config := range spec.Configs { // if the config is a Runtime target, make sure it's still in use right // now, the only use for Runtime target is credential specs. if, in // the future, more uses are added, then this check will need to be // made more intelligent. if config.Runtime != nil { // if we're carrying over a credential spec explicitly (because the // user passed --credential-spec with the same config name) then we // should match on credSpecName. if we're carrying over a // credential spec implicitly (because the user did not pass any // --credential-spec flag) then we should match on credSpecID. in // either case, we're keeping the config that already exists. if config.ConfigName == credSpecName || config.ConfigID == credSpecID { keepConfigs = append(keepConfigs, config) } // continue the loop, to skip the part where we check if the config // is in toRemove. continue } if _, exists := toRemove[config.ConfigName]; !exists { keepConfigs = append(keepConfigs, config) } } return keepConfigs }
go
func removeConfigs(flags *pflag.FlagSet, spec *swarm.ContainerSpec, credSpecName, credSpecID string) []*swarm.ConfigReference { keepConfigs := []*swarm.ConfigReference{} toRemove := buildToRemoveSet(flags, flagConfigRemove) // all configs in spec.Configs should have both a Name and ID, because // they come from an already-accepted spec. for _, config := range spec.Configs { // if the config is a Runtime target, make sure it's still in use right // now, the only use for Runtime target is credential specs. if, in // the future, more uses are added, then this check will need to be // made more intelligent. if config.Runtime != nil { // if we're carrying over a credential spec explicitly (because the // user passed --credential-spec with the same config name) then we // should match on credSpecName. if we're carrying over a // credential spec implicitly (because the user did not pass any // --credential-spec flag) then we should match on credSpecID. in // either case, we're keeping the config that already exists. if config.ConfigName == credSpecName || config.ConfigID == credSpecID { keepConfigs = append(keepConfigs, config) } // continue the loop, to skip the part where we check if the config // is in toRemove. continue } if _, exists := toRemove[config.ConfigName]; !exists { keepConfigs = append(keepConfigs, config) } } return keepConfigs }
[ "func", "removeConfigs", "(", "flags", "*", "pflag", ".", "FlagSet", ",", "spec", "*", "swarm", ".", "ContainerSpec", ",", "credSpecName", ",", "credSpecID", "string", ")", "[", "]", "*", "swarm", ".", "ConfigReference", "{", "keepConfigs", ":=", "[", "]", "*", "swarm", ".", "ConfigReference", "{", "}", "\n\n", "toRemove", ":=", "buildToRemoveSet", "(", "flags", ",", "flagConfigRemove", ")", "\n", "// all configs in spec.Configs should have both a Name and ID, because", "// they come from an already-accepted spec.", "for", "_", ",", "config", ":=", "range", "spec", ".", "Configs", "{", "// if the config is a Runtime target, make sure it's still in use right", "// now, the only use for Runtime target is credential specs. if, in", "// the future, more uses are added, then this check will need to be", "// made more intelligent.", "if", "config", ".", "Runtime", "!=", "nil", "{", "// if we're carrying over a credential spec explicitly (because the", "// user passed --credential-spec with the same config name) then we", "// should match on credSpecName. if we're carrying over a", "// credential spec implicitly (because the user did not pass any", "// --credential-spec flag) then we should match on credSpecID. in", "// either case, we're keeping the config that already exists.", "if", "config", ".", "ConfigName", "==", "credSpecName", "||", "config", ".", "ConfigID", "==", "credSpecID", "{", "keepConfigs", "=", "append", "(", "keepConfigs", ",", "config", ")", "\n", "}", "\n", "// continue the loop, to skip the part where we check if the config", "// is in toRemove.", "continue", "\n", "}", "\n\n", "if", "_", ",", "exists", ":=", "toRemove", "[", "config", ".", "ConfigName", "]", ";", "!", "exists", "{", "keepConfigs", "=", "append", "(", "keepConfigs", ",", "config", ")", "\n", "}", "\n", "}", "\n\n", "return", "keepConfigs", "\n", "}" ]
// removeConfigs figures out which configs in the existing spec should be kept // after the update.
[ "removeConfigs", "figures", "out", "which", "configs", "in", "the", "existing", "spec", "should", "be", "kept", "after", "the", "update", "." ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/service/update.go#L800-L832
train
docker/cli
cli/command/service/update.go
updateLogDriver
func updateLogDriver(flags *pflag.FlagSet, taskTemplate *swarm.TaskSpec) error { if !flags.Changed(flagLogDriver) { return nil } name, err := flags.GetString(flagLogDriver) if err != nil { return err } if name == "" { return nil } taskTemplate.LogDriver = &swarm.Driver{ Name: name, Options: opts.ConvertKVStringsToMap(flags.Lookup(flagLogOpt).Value.(*opts.ListOpts).GetAll()), } return nil }
go
func updateLogDriver(flags *pflag.FlagSet, taskTemplate *swarm.TaskSpec) error { if !flags.Changed(flagLogDriver) { return nil } name, err := flags.GetString(flagLogDriver) if err != nil { return err } if name == "" { return nil } taskTemplate.LogDriver = &swarm.Driver{ Name: name, Options: opts.ConvertKVStringsToMap(flags.Lookup(flagLogOpt).Value.(*opts.ListOpts).GetAll()), } return nil }
[ "func", "updateLogDriver", "(", "flags", "*", "pflag", ".", "FlagSet", ",", "taskTemplate", "*", "swarm", ".", "TaskSpec", ")", "error", "{", "if", "!", "flags", ".", "Changed", "(", "flagLogDriver", ")", "{", "return", "nil", "\n", "}", "\n\n", "name", ",", "err", ":=", "flags", ".", "GetString", "(", "flagLogDriver", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "name", "==", "\"", "\"", "{", "return", "nil", "\n", "}", "\n\n", "taskTemplate", ".", "LogDriver", "=", "&", "swarm", ".", "Driver", "{", "Name", ":", "name", ",", "Options", ":", "opts", ".", "ConvertKVStringsToMap", "(", "flags", ".", "Lookup", "(", "flagLogOpt", ")", ".", "Value", ".", "(", "*", "opts", ".", "ListOpts", ")", ".", "GetAll", "(", ")", ")", ",", "}", "\n\n", "return", "nil", "\n", "}" ]
// updateLogDriver updates the log driver only if the log driver flag is set. // All options will be replaced with those provided on the command line.
[ "updateLogDriver", "updates", "the", "log", "driver", "only", "if", "the", "log", "driver", "flag", "is", "set", ".", "All", "options", "will", "be", "replaced", "with", "those", "provided", "on", "the", "command", "line", "." ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/service/update.go#L1174-L1194
train
docker/cli
cli/command/trust/key.go
newTrustKeyCommand
func newTrustKeyCommand(dockerCli command.Streams) *cobra.Command { cmd := &cobra.Command{ Use: "key", Short: "Manage keys for signing Docker images", Args: cli.NoArgs, RunE: command.ShowHelp(dockerCli.Err()), } cmd.AddCommand( newKeyGenerateCommand(dockerCli), newKeyLoadCommand(dockerCli), ) return cmd }
go
func newTrustKeyCommand(dockerCli command.Streams) *cobra.Command { cmd := &cobra.Command{ Use: "key", Short: "Manage keys for signing Docker images", Args: cli.NoArgs, RunE: command.ShowHelp(dockerCli.Err()), } cmd.AddCommand( newKeyGenerateCommand(dockerCli), newKeyLoadCommand(dockerCli), ) return cmd }
[ "func", "newTrustKeyCommand", "(", "dockerCli", "command", ".", "Streams", ")", "*", "cobra", ".", "Command", "{", "cmd", ":=", "&", "cobra", ".", "Command", "{", "Use", ":", "\"", "\"", ",", "Short", ":", "\"", "\"", ",", "Args", ":", "cli", ".", "NoArgs", ",", "RunE", ":", "command", ".", "ShowHelp", "(", "dockerCli", ".", "Err", "(", ")", ")", ",", "}", "\n", "cmd", ".", "AddCommand", "(", "newKeyGenerateCommand", "(", "dockerCli", ")", ",", "newKeyLoadCommand", "(", "dockerCli", ")", ",", ")", "\n", "return", "cmd", "\n", "}" ]
// newTrustKeyCommand returns a cobra command for `trust key` subcommands
[ "newTrustKeyCommand", "returns", "a", "cobra", "command", "for", "trust", "key", "subcommands" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/trust/key.go#L10-L22
train
docker/cli
cli/command/formatter/custom.go
Label
func (c SubHeaderContext) Label(name string) string { n := strings.Split(name, ".") r := strings.NewReplacer("-", " ", "_", " ") h := r.Replace(n[len(n)-1]) return h }
go
func (c SubHeaderContext) Label(name string) string { n := strings.Split(name, ".") r := strings.NewReplacer("-", " ", "_", " ") h := r.Replace(n[len(n)-1]) return h }
[ "func", "(", "c", "SubHeaderContext", ")", "Label", "(", "name", "string", ")", "string", "{", "n", ":=", "strings", ".", "Split", "(", "name", ",", "\"", "\"", ")", "\n", "r", ":=", "strings", ".", "NewReplacer", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "h", ":=", "r", ".", "Replace", "(", "n", "[", "len", "(", "n", ")", "-", "1", "]", ")", "\n\n", "return", "h", "\n", "}" ]
// Label returns the header label for the specified string
[ "Label", "returns", "the", "header", "label", "for", "the", "specified", "string" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/formatter/custom.go#L30-L36
train
docker/cli
cli/command/volume/cmd.go
NewVolumeCommand
func NewVolumeCommand(dockerCli command.Cli) *cobra.Command { cmd := &cobra.Command{ Use: "volume COMMAND", Short: "Manage volumes", Args: cli.NoArgs, RunE: command.ShowHelp(dockerCli.Err()), Annotations: map[string]string{"version": "1.21"}, } cmd.AddCommand( newCreateCommand(dockerCli), newInspectCommand(dockerCli), newListCommand(dockerCli), newRemoveCommand(dockerCli), NewPruneCommand(dockerCli), ) return cmd }
go
func NewVolumeCommand(dockerCli command.Cli) *cobra.Command { cmd := &cobra.Command{ Use: "volume COMMAND", Short: "Manage volumes", Args: cli.NoArgs, RunE: command.ShowHelp(dockerCli.Err()), Annotations: map[string]string{"version": "1.21"}, } cmd.AddCommand( newCreateCommand(dockerCli), newInspectCommand(dockerCli), newListCommand(dockerCli), newRemoveCommand(dockerCli), NewPruneCommand(dockerCli), ) return cmd }
[ "func", "NewVolumeCommand", "(", "dockerCli", "command", ".", "Cli", ")", "*", "cobra", ".", "Command", "{", "cmd", ":=", "&", "cobra", ".", "Command", "{", "Use", ":", "\"", "\"", ",", "Short", ":", "\"", "\"", ",", "Args", ":", "cli", ".", "NoArgs", ",", "RunE", ":", "command", ".", "ShowHelp", "(", "dockerCli", ".", "Err", "(", ")", ")", ",", "Annotations", ":", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "\"", "\"", "}", ",", "}", "\n", "cmd", ".", "AddCommand", "(", "newCreateCommand", "(", "dockerCli", ")", ",", "newInspectCommand", "(", "dockerCli", ")", ",", "newListCommand", "(", "dockerCli", ")", ",", "newRemoveCommand", "(", "dockerCli", ")", ",", "NewPruneCommand", "(", "dockerCli", ")", ",", ")", "\n", "return", "cmd", "\n", "}" ]
// NewVolumeCommand returns a cobra command for `volume` subcommands
[ "NewVolumeCommand", "returns", "a", "cobra", "command", "for", "volume", "subcommands" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/volume/cmd.go#L10-L26
train
docker/cli
opts/config.go
Set
func (o *ConfigOpt) Set(value string) error { csvReader := csv.NewReader(strings.NewReader(value)) fields, err := csvReader.Read() if err != nil { return err } options := &swarmtypes.ConfigReference{ File: &swarmtypes.ConfigReferenceFileTarget{ UID: "0", GID: "0", Mode: 0444, }, } // support a simple syntax of --config foo if len(fields) == 1 { options.File.Name = fields[0] options.ConfigName = fields[0] o.values = append(o.values, options) return nil } for _, field := range fields { parts := strings.SplitN(field, "=", 2) key := strings.ToLower(parts[0]) if len(parts) != 2 { return fmt.Errorf("invalid field '%s' must be a key=value pair", field) } value := parts[1] switch key { case "source", "src": options.ConfigName = value case "target": options.File.Name = value case "uid": options.File.UID = value case "gid": options.File.GID = value case "mode": m, err := strconv.ParseUint(value, 0, 32) if err != nil { return fmt.Errorf("invalid mode specified: %v", err) } options.File.Mode = os.FileMode(m) default: return fmt.Errorf("invalid field in config request: %s", key) } } if options.ConfigName == "" { return fmt.Errorf("source is required") } o.values = append(o.values, options) return nil }
go
func (o *ConfigOpt) Set(value string) error { csvReader := csv.NewReader(strings.NewReader(value)) fields, err := csvReader.Read() if err != nil { return err } options := &swarmtypes.ConfigReference{ File: &swarmtypes.ConfigReferenceFileTarget{ UID: "0", GID: "0", Mode: 0444, }, } // support a simple syntax of --config foo if len(fields) == 1 { options.File.Name = fields[0] options.ConfigName = fields[0] o.values = append(o.values, options) return nil } for _, field := range fields { parts := strings.SplitN(field, "=", 2) key := strings.ToLower(parts[0]) if len(parts) != 2 { return fmt.Errorf("invalid field '%s' must be a key=value pair", field) } value := parts[1] switch key { case "source", "src": options.ConfigName = value case "target": options.File.Name = value case "uid": options.File.UID = value case "gid": options.File.GID = value case "mode": m, err := strconv.ParseUint(value, 0, 32) if err != nil { return fmt.Errorf("invalid mode specified: %v", err) } options.File.Mode = os.FileMode(m) default: return fmt.Errorf("invalid field in config request: %s", key) } } if options.ConfigName == "" { return fmt.Errorf("source is required") } o.values = append(o.values, options) return nil }
[ "func", "(", "o", "*", "ConfigOpt", ")", "Set", "(", "value", "string", ")", "error", "{", "csvReader", ":=", "csv", ".", "NewReader", "(", "strings", ".", "NewReader", "(", "value", ")", ")", "\n", "fields", ",", "err", ":=", "csvReader", ".", "Read", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "options", ":=", "&", "swarmtypes", ".", "ConfigReference", "{", "File", ":", "&", "swarmtypes", ".", "ConfigReferenceFileTarget", "{", "UID", ":", "\"", "\"", ",", "GID", ":", "\"", "\"", ",", "Mode", ":", "0444", ",", "}", ",", "}", "\n\n", "// support a simple syntax of --config foo", "if", "len", "(", "fields", ")", "==", "1", "{", "options", ".", "File", ".", "Name", "=", "fields", "[", "0", "]", "\n", "options", ".", "ConfigName", "=", "fields", "[", "0", "]", "\n", "o", ".", "values", "=", "append", "(", "o", ".", "values", ",", "options", ")", "\n", "return", "nil", "\n", "}", "\n\n", "for", "_", ",", "field", ":=", "range", "fields", "{", "parts", ":=", "strings", ".", "SplitN", "(", "field", ",", "\"", "\"", ",", "2", ")", "\n", "key", ":=", "strings", ".", "ToLower", "(", "parts", "[", "0", "]", ")", "\n\n", "if", "len", "(", "parts", ")", "!=", "2", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "field", ")", "\n", "}", "\n\n", "value", ":=", "parts", "[", "1", "]", "\n", "switch", "key", "{", "case", "\"", "\"", ",", "\"", "\"", ":", "options", ".", "ConfigName", "=", "value", "\n", "case", "\"", "\"", ":", "options", ".", "File", ".", "Name", "=", "value", "\n", "case", "\"", "\"", ":", "options", ".", "File", ".", "UID", "=", "value", "\n", "case", "\"", "\"", ":", "options", ".", "File", ".", "GID", "=", "value", "\n", "case", "\"", "\"", ":", "m", ",", "err", ":=", "strconv", ".", "ParseUint", "(", "value", ",", "0", ",", "32", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "options", ".", "File", ".", "Mode", "=", "os", ".", "FileMode", "(", "m", ")", "\n", "default", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "key", ")", "\n", "}", "\n", "}", "\n\n", "if", "options", ".", "ConfigName", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "o", ".", "values", "=", "append", "(", "o", ".", "values", ",", "options", ")", "\n", "return", "nil", "\n", "}" ]
// Set a new config value
[ "Set", "a", "new", "config", "value" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/opts/config.go#L19-L78
train
docker/cli
cli/command/stack/kubernetes/watcher.go
Watch
func (w *deployWatcher) Watch(name string, serviceNames []string, statusUpdates chan serviceStatus) error { errC := make(chan error, 1) defer close(errC) handlers := runtimeutil.ErrorHandlers // informer errors are reported using global error handlers runtimeutil.ErrorHandlers = append(handlers, func(err error) { errC <- err }) defer func() { runtimeutil.ErrorHandlers = handlers }() ctx, cancel := context.WithCancel(context.Background()) wg := sync.WaitGroup{} defer func() { cancel() wg.Wait() }() wg.Add(2) go func() { defer wg.Done() w.watchStackStatus(ctx, name, errC) }() go func() { defer wg.Done() w.waitForPods(ctx, name, serviceNames, errC, statusUpdates) }() return <-errC }
go
func (w *deployWatcher) Watch(name string, serviceNames []string, statusUpdates chan serviceStatus) error { errC := make(chan error, 1) defer close(errC) handlers := runtimeutil.ErrorHandlers // informer errors are reported using global error handlers runtimeutil.ErrorHandlers = append(handlers, func(err error) { errC <- err }) defer func() { runtimeutil.ErrorHandlers = handlers }() ctx, cancel := context.WithCancel(context.Background()) wg := sync.WaitGroup{} defer func() { cancel() wg.Wait() }() wg.Add(2) go func() { defer wg.Done() w.watchStackStatus(ctx, name, errC) }() go func() { defer wg.Done() w.waitForPods(ctx, name, serviceNames, errC, statusUpdates) }() return <-errC }
[ "func", "(", "w", "*", "deployWatcher", ")", "Watch", "(", "name", "string", ",", "serviceNames", "[", "]", "string", ",", "statusUpdates", "chan", "serviceStatus", ")", "error", "{", "errC", ":=", "make", "(", "chan", "error", ",", "1", ")", "\n", "defer", "close", "(", "errC", ")", "\n\n", "handlers", ":=", "runtimeutil", ".", "ErrorHandlers", "\n\n", "// informer errors are reported using global error handlers", "runtimeutil", ".", "ErrorHandlers", "=", "append", "(", "handlers", ",", "func", "(", "err", "error", ")", "{", "errC", "<-", "err", "\n", "}", ")", "\n", "defer", "func", "(", ")", "{", "runtimeutil", ".", "ErrorHandlers", "=", "handlers", "\n", "}", "(", ")", "\n\n", "ctx", ",", "cancel", ":=", "context", ".", "WithCancel", "(", "context", ".", "Background", "(", ")", ")", "\n", "wg", ":=", "sync", ".", "WaitGroup", "{", "}", "\n", "defer", "func", "(", ")", "{", "cancel", "(", ")", "\n", "wg", ".", "Wait", "(", ")", "\n", "}", "(", ")", "\n", "wg", ".", "Add", "(", "2", ")", "\n", "go", "func", "(", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n", "w", ".", "watchStackStatus", "(", "ctx", ",", "name", ",", "errC", ")", "\n", "}", "(", ")", "\n", "go", "func", "(", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n", "w", ".", "waitForPods", "(", "ctx", ",", "name", ",", "serviceNames", ",", "errC", ",", "statusUpdates", ")", "\n", "}", "(", ")", "\n\n", "return", "<-", "errC", "\n", "}" ]
// Watch watches a stuck deployement and return a chan that will holds the state of the stack
[ "Watch", "watches", "a", "stuck", "deployement", "and", "return", "a", "chan", "that", "will", "holds", "the", "state", "of", "the", "stack" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/stack/kubernetes/watcher.go#L38-L69
train
docker/cli
cli/context/store/storeconfig.go
EndpointTypeGetter
func EndpointTypeGetter(name string, getter TypeGetter) NamedTypeGetter { return NamedTypeGetter{ name: name, typeGetter: getter, } }
go
func EndpointTypeGetter(name string, getter TypeGetter) NamedTypeGetter { return NamedTypeGetter{ name: name, typeGetter: getter, } }
[ "func", "EndpointTypeGetter", "(", "name", "string", ",", "getter", "TypeGetter", ")", "NamedTypeGetter", "{", "return", "NamedTypeGetter", "{", "name", ":", "name", ",", "typeGetter", ":", "getter", ",", "}", "\n", "}" ]
// EndpointTypeGetter returns a NamedTypeGetter with the spcecified name and getter
[ "EndpointTypeGetter", "returns", "a", "NamedTypeGetter", "with", "the", "spcecified", "name", "and", "getter" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/context/store/storeconfig.go#L15-L20
train
docker/cli
cli/context/store/storeconfig.go
SetEndpoint
func (c Config) SetEndpoint(name string, getter TypeGetter) { c.endpointTypes[name] = getter }
go
func (c Config) SetEndpoint(name string, getter TypeGetter) { c.endpointTypes[name] = getter }
[ "func", "(", "c", "Config", ")", "SetEndpoint", "(", "name", "string", ",", "getter", "TypeGetter", ")", "{", "c", ".", "endpointTypes", "[", "name", "]", "=", "getter", "\n", "}" ]
// SetEndpoint set an endpoint typing information
[ "SetEndpoint", "set", "an", "endpoint", "typing", "information" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/context/store/storeconfig.go#L29-L31
train
docker/cli
cli/context/store/storeconfig.go
NewConfig
func NewConfig(contextType TypeGetter, endpoints ...NamedTypeGetter) Config { res := Config{ contextType: contextType, endpointTypes: make(map[string]TypeGetter), } for _, e := range endpoints { res.endpointTypes[e.name] = e.typeGetter } return res }
go
func NewConfig(contextType TypeGetter, endpoints ...NamedTypeGetter) Config { res := Config{ contextType: contextType, endpointTypes: make(map[string]TypeGetter), } for _, e := range endpoints { res.endpointTypes[e.name] = e.typeGetter } return res }
[ "func", "NewConfig", "(", "contextType", "TypeGetter", ",", "endpoints", "...", "NamedTypeGetter", ")", "Config", "{", "res", ":=", "Config", "{", "contextType", ":", "contextType", ",", "endpointTypes", ":", "make", "(", "map", "[", "string", "]", "TypeGetter", ")", ",", "}", "\n", "for", "_", ",", "e", ":=", "range", "endpoints", "{", "res", ".", "endpointTypes", "[", "e", ".", "name", "]", "=", "e", ".", "typeGetter", "\n", "}", "\n", "return", "res", "\n", "}" ]
// NewConfig creates a config object
[ "NewConfig", "creates", "a", "config", "object" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/context/store/storeconfig.go#L34-L43
train
docker/cli
cli/command/swarm/cmd.go
NewSwarmCommand
func NewSwarmCommand(dockerCli command.Cli) *cobra.Command { cmd := &cobra.Command{ Use: "swarm", Short: "Manage Swarm", Args: cli.NoArgs, RunE: command.ShowHelp(dockerCli.Err()), Annotations: map[string]string{ "version": "1.24", "swarm": "", }, } cmd.AddCommand( newInitCommand(dockerCli), newJoinCommand(dockerCli), newJoinTokenCommand(dockerCli), newUnlockKeyCommand(dockerCli), newUpdateCommand(dockerCli), newLeaveCommand(dockerCli), newUnlockCommand(dockerCli), newCACommand(dockerCli), ) return cmd }
go
func NewSwarmCommand(dockerCli command.Cli) *cobra.Command { cmd := &cobra.Command{ Use: "swarm", Short: "Manage Swarm", Args: cli.NoArgs, RunE: command.ShowHelp(dockerCli.Err()), Annotations: map[string]string{ "version": "1.24", "swarm": "", }, } cmd.AddCommand( newInitCommand(dockerCli), newJoinCommand(dockerCli), newJoinTokenCommand(dockerCli), newUnlockKeyCommand(dockerCli), newUpdateCommand(dockerCli), newLeaveCommand(dockerCli), newUnlockCommand(dockerCli), newCACommand(dockerCli), ) return cmd }
[ "func", "NewSwarmCommand", "(", "dockerCli", "command", ".", "Cli", ")", "*", "cobra", ".", "Command", "{", "cmd", ":=", "&", "cobra", ".", "Command", "{", "Use", ":", "\"", "\"", ",", "Short", ":", "\"", "\"", ",", "Args", ":", "cli", ".", "NoArgs", ",", "RunE", ":", "command", ".", "ShowHelp", "(", "dockerCli", ".", "Err", "(", ")", ")", ",", "Annotations", ":", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "\"", "\"", ",", "}", ",", "}", "\n", "cmd", ".", "AddCommand", "(", "newInitCommand", "(", "dockerCli", ")", ",", "newJoinCommand", "(", "dockerCli", ")", ",", "newJoinTokenCommand", "(", "dockerCli", ")", ",", "newUnlockKeyCommand", "(", "dockerCli", ")", ",", "newUpdateCommand", "(", "dockerCli", ")", ",", "newLeaveCommand", "(", "dockerCli", ")", ",", "newUnlockCommand", "(", "dockerCli", ")", ",", "newCACommand", "(", "dockerCli", ")", ",", ")", "\n", "return", "cmd", "\n", "}" ]
// NewSwarmCommand returns a cobra command for `swarm` subcommands
[ "NewSwarmCommand", "returns", "a", "cobra", "command", "for", "swarm", "subcommands" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/swarm/cmd.go#L11-L33
train
docker/cli
cli/command/trust/inspect_pretty.go
printSignatures
func printSignatures(out io.Writer, signatureRows []trustTagRow) error { trustTagCtx := formatter.Context{ Output: out, Format: NewTrustTagFormat(), } // convert the formatted type before printing formattedTags := []SignedTagInfo{} for _, sigRow := range signatureRows { formattedSigners := sigRow.Signers if len(formattedSigners) == 0 { formattedSigners = append(formattedSigners, fmt.Sprintf("(%s)", releasedRoleName)) } formattedTags = append(formattedTags, SignedTagInfo{ Name: sigRow.SignedTag, Digest: sigRow.Digest, Signers: formattedSigners, }) } return TagWrite(trustTagCtx, formattedTags) }
go
func printSignatures(out io.Writer, signatureRows []trustTagRow) error { trustTagCtx := formatter.Context{ Output: out, Format: NewTrustTagFormat(), } // convert the formatted type before printing formattedTags := []SignedTagInfo{} for _, sigRow := range signatureRows { formattedSigners := sigRow.Signers if len(formattedSigners) == 0 { formattedSigners = append(formattedSigners, fmt.Sprintf("(%s)", releasedRoleName)) } formattedTags = append(formattedTags, SignedTagInfo{ Name: sigRow.SignedTag, Digest: sigRow.Digest, Signers: formattedSigners, }) } return TagWrite(trustTagCtx, formattedTags) }
[ "func", "printSignatures", "(", "out", "io", ".", "Writer", ",", "signatureRows", "[", "]", "trustTagRow", ")", "error", "{", "trustTagCtx", ":=", "formatter", ".", "Context", "{", "Output", ":", "out", ",", "Format", ":", "NewTrustTagFormat", "(", ")", ",", "}", "\n", "// convert the formatted type before printing", "formattedTags", ":=", "[", "]", "SignedTagInfo", "{", "}", "\n", "for", "_", ",", "sigRow", ":=", "range", "signatureRows", "{", "formattedSigners", ":=", "sigRow", ".", "Signers", "\n", "if", "len", "(", "formattedSigners", ")", "==", "0", "{", "formattedSigners", "=", "append", "(", "formattedSigners", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "releasedRoleName", ")", ")", "\n", "}", "\n", "formattedTags", "=", "append", "(", "formattedTags", ",", "SignedTagInfo", "{", "Name", ":", "sigRow", ".", "SignedTag", ",", "Digest", ":", "sigRow", ".", "Digest", ",", "Signers", ":", "formattedSigners", ",", "}", ")", "\n", "}", "\n", "return", "TagWrite", "(", "trustTagCtx", ",", "formattedTags", ")", "\n", "}" ]
// pretty print with ordered rows
[ "pretty", "print", "with", "ordered", "rows" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/trust/inspect_pretty.go#L55-L74
train
docker/cli
cli/command/formatter/formatter.go
Contains
func (f Format) Contains(sub string) bool { return strings.Contains(string(f), sub) }
go
func (f Format) Contains(sub string) bool { return strings.Contains(string(f), sub) }
[ "func", "(", "f", "Format", ")", "Contains", "(", "sub", "string", ")", "bool", "{", "return", "strings", ".", "Contains", "(", "string", "(", "f", ")", ",", "sub", ")", "\n", "}" ]
// Contains returns true if the format contains the substring
[ "Contains", "returns", "true", "if", "the", "format", "contains", "the", "substring" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/formatter/formatter.go#L32-L34
train
docker/cli
cli/command/formatter/formatter.go
Write
func (c *Context) Write(sub SubContext, f SubFormat) error { c.buffer = bytes.NewBufferString("") c.preFormat() tmpl, err := c.parseFormat() if err != nil { return err } subFormat := func(subContext SubContext) error { return c.contextFormat(tmpl, subContext) } if err := f(subFormat); err != nil { return err } c.postFormat(tmpl, sub) return nil }
go
func (c *Context) Write(sub SubContext, f SubFormat) error { c.buffer = bytes.NewBufferString("") c.preFormat() tmpl, err := c.parseFormat() if err != nil { return err } subFormat := func(subContext SubContext) error { return c.contextFormat(tmpl, subContext) } if err := f(subFormat); err != nil { return err } c.postFormat(tmpl, sub) return nil }
[ "func", "(", "c", "*", "Context", ")", "Write", "(", "sub", "SubContext", ",", "f", "SubFormat", ")", "error", "{", "c", ".", "buffer", "=", "bytes", ".", "NewBufferString", "(", "\"", "\"", ")", "\n", "c", ".", "preFormat", "(", ")", "\n\n", "tmpl", ",", "err", ":=", "c", ".", "parseFormat", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "subFormat", ":=", "func", "(", "subContext", "SubContext", ")", "error", "{", "return", "c", ".", "contextFormat", "(", "tmpl", ",", "subContext", ")", "\n", "}", "\n", "if", "err", ":=", "f", "(", "subFormat", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "c", ".", "postFormat", "(", "tmpl", ",", "sub", ")", "\n", "return", "nil", "\n", "}" ]
// Write the template to the buffer using this Context
[ "Write", "the", "template", "to", "the", "buffer", "using", "this", "Context" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/formatter/formatter.go#L101-L119
train
docker/cli
cli/command/stack/swarm/ps.go
RunPS
func RunPS(dockerCli command.Cli, opts options.PS) error { filter := getStackFilterFromOpt(opts.Namespace, opts.Filter) ctx := context.Background() client := dockerCli.Client() tasks, err := client.TaskList(ctx, types.TaskListOptions{Filters: filter}) if err != nil { return err } if len(tasks) == 0 { return fmt.Errorf("nothing found in stack: %s", opts.Namespace) } format := opts.Format if len(format) == 0 { format = task.DefaultFormat(dockerCli.ConfigFile(), opts.Quiet) } return task.Print(ctx, dockerCli, tasks, idresolver.New(client, opts.NoResolve), !opts.NoTrunc, opts.Quiet, format) }
go
func RunPS(dockerCli command.Cli, opts options.PS) error { filter := getStackFilterFromOpt(opts.Namespace, opts.Filter) ctx := context.Background() client := dockerCli.Client() tasks, err := client.TaskList(ctx, types.TaskListOptions{Filters: filter}) if err != nil { return err } if len(tasks) == 0 { return fmt.Errorf("nothing found in stack: %s", opts.Namespace) } format := opts.Format if len(format) == 0 { format = task.DefaultFormat(dockerCli.ConfigFile(), opts.Quiet) } return task.Print(ctx, dockerCli, tasks, idresolver.New(client, opts.NoResolve), !opts.NoTrunc, opts.Quiet, format) }
[ "func", "RunPS", "(", "dockerCli", "command", ".", "Cli", ",", "opts", "options", ".", "PS", ")", "error", "{", "filter", ":=", "getStackFilterFromOpt", "(", "opts", ".", "Namespace", ",", "opts", ".", "Filter", ")", "\n\n", "ctx", ":=", "context", ".", "Background", "(", ")", "\n", "client", ":=", "dockerCli", ".", "Client", "(", ")", "\n", "tasks", ",", "err", ":=", "client", ".", "TaskList", "(", "ctx", ",", "types", ".", "TaskListOptions", "{", "Filters", ":", "filter", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "len", "(", "tasks", ")", "==", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "opts", ".", "Namespace", ")", "\n", "}", "\n\n", "format", ":=", "opts", ".", "Format", "\n", "if", "len", "(", "format", ")", "==", "0", "{", "format", "=", "task", ".", "DefaultFormat", "(", "dockerCli", ".", "ConfigFile", "(", ")", ",", "opts", ".", "Quiet", ")", "\n", "}", "\n\n", "return", "task", ".", "Print", "(", "ctx", ",", "dockerCli", ",", "tasks", ",", "idresolver", ".", "New", "(", "client", ",", "opts", ".", "NoResolve", ")", ",", "!", "opts", ".", "NoTrunc", ",", "opts", ".", "Quiet", ",", "format", ")", "\n", "}" ]
// RunPS is the swarm implementation of docker stack ps
[ "RunPS", "is", "the", "swarm", "implementation", "of", "docker", "stack", "ps" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/stack/swarm/ps.go#L15-L35
train
docker/cli
cli/command/engine/licenses.go
NewSubscriptionsFormat
func NewSubscriptionsFormat(source string, quiet bool) formatter.Format { switch source { case formatter.TableFormatKey: if quiet { return defaultSubscriptionsQuietFormat } return defaultSubscriptionsTableFormat case formatter.RawFormatKey: if quiet { return `license: {{.ID}}` } return `license: {{.ID}}\nname: {{.Name}}\nowner: {{.Owner}}\ncomponents: {{.ComponentsString}}\n` } return formatter.Format(source) }
go
func NewSubscriptionsFormat(source string, quiet bool) formatter.Format { switch source { case formatter.TableFormatKey: if quiet { return defaultSubscriptionsQuietFormat } return defaultSubscriptionsTableFormat case formatter.RawFormatKey: if quiet { return `license: {{.ID}}` } return `license: {{.ID}}\nname: {{.Name}}\nowner: {{.Owner}}\ncomponents: {{.ComponentsString}}\n` } return formatter.Format(source) }
[ "func", "NewSubscriptionsFormat", "(", "source", "string", ",", "quiet", "bool", ")", "formatter", ".", "Format", "{", "switch", "source", "{", "case", "formatter", ".", "TableFormatKey", ":", "if", "quiet", "{", "return", "defaultSubscriptionsQuietFormat", "\n", "}", "\n", "return", "defaultSubscriptionsTableFormat", "\n", "case", "formatter", ".", "RawFormatKey", ":", "if", "quiet", "{", "return", "`license: {{.ID}}`", "\n", "}", "\n", "return", "`license: {{.ID}}\\nname: {{.Name}}\\nowner: {{.Owner}}\\ncomponents: {{.ComponentsString}}\\n`", "\n", "}", "\n", "return", "formatter", ".", "Format", "(", "source", ")", "\n", "}" ]
// NewSubscriptionsFormat returns a Format for rendering using a license Context
[ "NewSubscriptionsFormat", "returns", "a", "Format", "for", "rendering", "using", "a", "license", "Context" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/engine/licenses.go#L31-L45
train
docker/cli
cli/command/engine/licenses.go
SubscriptionsWrite
func SubscriptionsWrite(ctx formatter.Context, subs []licenseutils.LicenseDisplay) error { render := func(format func(subContext formatter.SubContext) error) error { for _, sub := range subs { licenseCtx := &licenseContext{trunc: ctx.Trunc, l: sub} if err := format(licenseCtx); err != nil { return err } } return nil } licenseCtx := licenseContext{} licenseCtx.Header = map[string]string{ "Num": numHeader, "Owner": ownerHeader, "Name": licenseNameHeader, "ID": idHeader, "DockerID": dockerIDHeader, "ProductID": productIDHeader, "ProductRatePlan": productRatePlanHeader, "ProductRatePlanID": productRatePlanIDHeader, "Start": startHeader, "Expires": expiresHeader, "State": stateHeader, "Eusa": eusaHeader, "ComponentsString": pricingComponentsHeader, } return ctx.Write(&licenseCtx, render) }
go
func SubscriptionsWrite(ctx formatter.Context, subs []licenseutils.LicenseDisplay) error { render := func(format func(subContext formatter.SubContext) error) error { for _, sub := range subs { licenseCtx := &licenseContext{trunc: ctx.Trunc, l: sub} if err := format(licenseCtx); err != nil { return err } } return nil } licenseCtx := licenseContext{} licenseCtx.Header = map[string]string{ "Num": numHeader, "Owner": ownerHeader, "Name": licenseNameHeader, "ID": idHeader, "DockerID": dockerIDHeader, "ProductID": productIDHeader, "ProductRatePlan": productRatePlanHeader, "ProductRatePlanID": productRatePlanIDHeader, "Start": startHeader, "Expires": expiresHeader, "State": stateHeader, "Eusa": eusaHeader, "ComponentsString": pricingComponentsHeader, } return ctx.Write(&licenseCtx, render) }
[ "func", "SubscriptionsWrite", "(", "ctx", "formatter", ".", "Context", ",", "subs", "[", "]", "licenseutils", ".", "LicenseDisplay", ")", "error", "{", "render", ":=", "func", "(", "format", "func", "(", "subContext", "formatter", ".", "SubContext", ")", "error", ")", "error", "{", "for", "_", ",", "sub", ":=", "range", "subs", "{", "licenseCtx", ":=", "&", "licenseContext", "{", "trunc", ":", "ctx", ".", "Trunc", ",", "l", ":", "sub", "}", "\n", "if", "err", ":=", "format", "(", "licenseCtx", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "licenseCtx", ":=", "licenseContext", "{", "}", "\n", "licenseCtx", ".", "Header", "=", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "numHeader", ",", "\"", "\"", ":", "ownerHeader", ",", "\"", "\"", ":", "licenseNameHeader", ",", "\"", "\"", ":", "idHeader", ",", "\"", "\"", ":", "dockerIDHeader", ",", "\"", "\"", ":", "productIDHeader", ",", "\"", "\"", ":", "productRatePlanHeader", ",", "\"", "\"", ":", "productRatePlanIDHeader", ",", "\"", "\"", ":", "startHeader", ",", "\"", "\"", ":", "expiresHeader", ",", "\"", "\"", ":", "stateHeader", ",", "\"", "\"", ":", "eusaHeader", ",", "\"", "\"", ":", "pricingComponentsHeader", ",", "}", "\n", "return", "ctx", ".", "Write", "(", "&", "licenseCtx", ",", "render", ")", "\n", "}" ]
// SubscriptionsWrite writes the context
[ "SubscriptionsWrite", "writes", "the", "context" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/engine/licenses.go#L48-L75
train
docker/cli
cli/cobra.go
setupCommonRootCommand
func setupCommonRootCommand(rootCmd *cobra.Command) (*cliflags.ClientOptions, *pflag.FlagSet, *cobra.Command) { opts := cliflags.NewClientOptions() flags := rootCmd.Flags() flags.StringVar(&opts.ConfigDir, "config", cliconfig.Dir(), "Location of client config files") opts.Common.InstallFlags(flags) cobra.AddTemplateFunc("add", func(a, b int) int { return a + b }) cobra.AddTemplateFunc("hasSubCommands", hasSubCommands) cobra.AddTemplateFunc("hasManagementSubCommands", hasManagementSubCommands) cobra.AddTemplateFunc("hasInvalidPlugins", hasInvalidPlugins) cobra.AddTemplateFunc("operationSubCommands", operationSubCommands) cobra.AddTemplateFunc("managementSubCommands", managementSubCommands) cobra.AddTemplateFunc("invalidPlugins", invalidPlugins) cobra.AddTemplateFunc("wrappedFlagUsages", wrappedFlagUsages) cobra.AddTemplateFunc("vendorAndVersion", vendorAndVersion) cobra.AddTemplateFunc("invalidPluginReason", invalidPluginReason) cobra.AddTemplateFunc("isPlugin", isPlugin) cobra.AddTemplateFunc("decoratedName", decoratedName) rootCmd.SetUsageTemplate(usageTemplate) rootCmd.SetHelpTemplate(helpTemplate) rootCmd.SetFlagErrorFunc(FlagErrorFunc) rootCmd.SetHelpCommand(helpCommand) rootCmd.PersistentFlags().BoolP("help", "h", false, "Print usage") rootCmd.PersistentFlags().MarkShorthandDeprecated("help", "please use --help") rootCmd.PersistentFlags().Lookup("help").Hidden = true return opts, flags, helpCommand }
go
func setupCommonRootCommand(rootCmd *cobra.Command) (*cliflags.ClientOptions, *pflag.FlagSet, *cobra.Command) { opts := cliflags.NewClientOptions() flags := rootCmd.Flags() flags.StringVar(&opts.ConfigDir, "config", cliconfig.Dir(), "Location of client config files") opts.Common.InstallFlags(flags) cobra.AddTemplateFunc("add", func(a, b int) int { return a + b }) cobra.AddTemplateFunc("hasSubCommands", hasSubCommands) cobra.AddTemplateFunc("hasManagementSubCommands", hasManagementSubCommands) cobra.AddTemplateFunc("hasInvalidPlugins", hasInvalidPlugins) cobra.AddTemplateFunc("operationSubCommands", operationSubCommands) cobra.AddTemplateFunc("managementSubCommands", managementSubCommands) cobra.AddTemplateFunc("invalidPlugins", invalidPlugins) cobra.AddTemplateFunc("wrappedFlagUsages", wrappedFlagUsages) cobra.AddTemplateFunc("vendorAndVersion", vendorAndVersion) cobra.AddTemplateFunc("invalidPluginReason", invalidPluginReason) cobra.AddTemplateFunc("isPlugin", isPlugin) cobra.AddTemplateFunc("decoratedName", decoratedName) rootCmd.SetUsageTemplate(usageTemplate) rootCmd.SetHelpTemplate(helpTemplate) rootCmd.SetFlagErrorFunc(FlagErrorFunc) rootCmd.SetHelpCommand(helpCommand) rootCmd.PersistentFlags().BoolP("help", "h", false, "Print usage") rootCmd.PersistentFlags().MarkShorthandDeprecated("help", "please use --help") rootCmd.PersistentFlags().Lookup("help").Hidden = true return opts, flags, helpCommand }
[ "func", "setupCommonRootCommand", "(", "rootCmd", "*", "cobra", ".", "Command", ")", "(", "*", "cliflags", ".", "ClientOptions", ",", "*", "pflag", ".", "FlagSet", ",", "*", "cobra", ".", "Command", ")", "{", "opts", ":=", "cliflags", ".", "NewClientOptions", "(", ")", "\n", "flags", ":=", "rootCmd", ".", "Flags", "(", ")", "\n\n", "flags", ".", "StringVar", "(", "&", "opts", ".", "ConfigDir", ",", "\"", "\"", ",", "cliconfig", ".", "Dir", "(", ")", ",", "\"", "\"", ")", "\n", "opts", ".", "Common", ".", "InstallFlags", "(", "flags", ")", "\n\n", "cobra", ".", "AddTemplateFunc", "(", "\"", "\"", ",", "func", "(", "a", ",", "b", "int", ")", "int", "{", "return", "a", "+", "b", "}", ")", "\n", "cobra", ".", "AddTemplateFunc", "(", "\"", "\"", ",", "hasSubCommands", ")", "\n", "cobra", ".", "AddTemplateFunc", "(", "\"", "\"", ",", "hasManagementSubCommands", ")", "\n", "cobra", ".", "AddTemplateFunc", "(", "\"", "\"", ",", "hasInvalidPlugins", ")", "\n", "cobra", ".", "AddTemplateFunc", "(", "\"", "\"", ",", "operationSubCommands", ")", "\n", "cobra", ".", "AddTemplateFunc", "(", "\"", "\"", ",", "managementSubCommands", ")", "\n", "cobra", ".", "AddTemplateFunc", "(", "\"", "\"", ",", "invalidPlugins", ")", "\n", "cobra", ".", "AddTemplateFunc", "(", "\"", "\"", ",", "wrappedFlagUsages", ")", "\n", "cobra", ".", "AddTemplateFunc", "(", "\"", "\"", ",", "vendorAndVersion", ")", "\n", "cobra", ".", "AddTemplateFunc", "(", "\"", "\"", ",", "invalidPluginReason", ")", "\n", "cobra", ".", "AddTemplateFunc", "(", "\"", "\"", ",", "isPlugin", ")", "\n", "cobra", ".", "AddTemplateFunc", "(", "\"", "\"", ",", "decoratedName", ")", "\n\n", "rootCmd", ".", "SetUsageTemplate", "(", "usageTemplate", ")", "\n", "rootCmd", ".", "SetHelpTemplate", "(", "helpTemplate", ")", "\n", "rootCmd", ".", "SetFlagErrorFunc", "(", "FlagErrorFunc", ")", "\n", "rootCmd", ".", "SetHelpCommand", "(", "helpCommand", ")", "\n\n", "rootCmd", ".", "PersistentFlags", "(", ")", ".", "BoolP", "(", "\"", "\"", ",", "\"", "\"", ",", "false", ",", "\"", "\"", ")", "\n", "rootCmd", ".", "PersistentFlags", "(", ")", ".", "MarkShorthandDeprecated", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "rootCmd", ".", "PersistentFlags", "(", ")", ".", "Lookup", "(", "\"", "\"", ")", ".", "Hidden", "=", "true", "\n\n", "return", "opts", ",", "flags", ",", "helpCommand", "\n", "}" ]
// setupCommonRootCommand contains the setup common to // SetupRootCommand and SetupPluginRootCommand.
[ "setupCommonRootCommand", "contains", "the", "setup", "common", "to", "SetupRootCommand", "and", "SetupPluginRootCommand", "." ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/cobra.go#L20-L50
train
docker/cli
cli/cobra.go
SetupPluginRootCommand
func SetupPluginRootCommand(rootCmd *cobra.Command) (*cliflags.ClientOptions, *pflag.FlagSet) { opts, flags, _ := setupCommonRootCommand(rootCmd) return opts, flags }
go
func SetupPluginRootCommand(rootCmd *cobra.Command) (*cliflags.ClientOptions, *pflag.FlagSet) { opts, flags, _ := setupCommonRootCommand(rootCmd) return opts, flags }
[ "func", "SetupPluginRootCommand", "(", "rootCmd", "*", "cobra", ".", "Command", ")", "(", "*", "cliflags", ".", "ClientOptions", ",", "*", "pflag", ".", "FlagSet", ")", "{", "opts", ",", "flags", ",", "_", ":=", "setupCommonRootCommand", "(", "rootCmd", ")", "\n", "return", "opts", ",", "flags", "\n", "}" ]
// SetupPluginRootCommand sets default usage, help and error handling for a plugin root command.
[ "SetupPluginRootCommand", "sets", "default", "usage", "help", "and", "error", "handling", "for", "a", "plugin", "root", "command", "." ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/cobra.go#L63-L66
train
docker/cli
cli/cobra.go
NewTopLevelCommand
func NewTopLevelCommand(cmd *cobra.Command, dockerCli *command.DockerCli, opts *cliflags.ClientOptions, flags *pflag.FlagSet) *TopLevelCommand { return &TopLevelCommand{cmd, dockerCli, opts, flags, os.Args[1:]} }
go
func NewTopLevelCommand(cmd *cobra.Command, dockerCli *command.DockerCli, opts *cliflags.ClientOptions, flags *pflag.FlagSet) *TopLevelCommand { return &TopLevelCommand{cmd, dockerCli, opts, flags, os.Args[1:]} }
[ "func", "NewTopLevelCommand", "(", "cmd", "*", "cobra", ".", "Command", ",", "dockerCli", "*", "command", ".", "DockerCli", ",", "opts", "*", "cliflags", ".", "ClientOptions", ",", "flags", "*", "pflag", ".", "FlagSet", ")", "*", "TopLevelCommand", "{", "return", "&", "TopLevelCommand", "{", "cmd", ",", "dockerCli", ",", "opts", ",", "flags", ",", "os", ".", "Args", "[", "1", ":", "]", "}", "\n", "}" ]
// NewTopLevelCommand returns a new TopLevelCommand object
[ "NewTopLevelCommand", "returns", "a", "new", "TopLevelCommand", "object" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/cobra.go#L97-L99
train
docker/cli
cli/cobra.go
SetFlag
func (tcmd *TopLevelCommand) SetFlag(name, value string) { tcmd.cmd.Flags().Set(name, value) }
go
func (tcmd *TopLevelCommand) SetFlag(name, value string) { tcmd.cmd.Flags().Set(name, value) }
[ "func", "(", "tcmd", "*", "TopLevelCommand", ")", "SetFlag", "(", "name", ",", "value", "string", ")", "{", "tcmd", ".", "cmd", ".", "Flags", "(", ")", ".", "Set", "(", "name", ",", "value", ")", "\n", "}" ]
// SetFlag sets a flag in the local flag set of the top-level command
[ "SetFlag", "sets", "a", "flag", "in", "the", "local", "flag", "set", "of", "the", "top", "-", "level", "command" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/cobra.go#L108-L110
train
docker/cli
cli/cobra.go
Initialize
func (tcmd *TopLevelCommand) Initialize(ops ...command.InitializeOpt) error { tcmd.opts.Common.SetDefaultOptions(tcmd.flags) return tcmd.dockerCli.Initialize(tcmd.opts, ops...) }
go
func (tcmd *TopLevelCommand) Initialize(ops ...command.InitializeOpt) error { tcmd.opts.Common.SetDefaultOptions(tcmd.flags) return tcmd.dockerCli.Initialize(tcmd.opts, ops...) }
[ "func", "(", "tcmd", "*", "TopLevelCommand", ")", "Initialize", "(", "ops", "...", "command", ".", "InitializeOpt", ")", "error", "{", "tcmd", ".", "opts", ".", "Common", ".", "SetDefaultOptions", "(", "tcmd", ".", "flags", ")", "\n", "return", "tcmd", ".", "dockerCli", ".", "Initialize", "(", "tcmd", ".", "opts", ",", "ops", "...", ")", "\n", "}" ]
// Initialize finalises global option parsing and initializes the docker client.
[ "Initialize", "finalises", "global", "option", "parsing", "and", "initializes", "the", "docker", "client", "." ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/cobra.go#L153-L156
train
docker/cli
cli/cobra.go
VisitAll
func VisitAll(root *cobra.Command, fn func(*cobra.Command)) { for _, cmd := range root.Commands() { VisitAll(cmd, fn) } fn(root) }
go
func VisitAll(root *cobra.Command, fn func(*cobra.Command)) { for _, cmd := range root.Commands() { VisitAll(cmd, fn) } fn(root) }
[ "func", "VisitAll", "(", "root", "*", "cobra", ".", "Command", ",", "fn", "func", "(", "*", "cobra", ".", "Command", ")", ")", "{", "for", "_", ",", "cmd", ":=", "range", "root", ".", "Commands", "(", ")", "{", "VisitAll", "(", "cmd", ",", "fn", ")", "\n", "}", "\n", "fn", "(", "root", ")", "\n", "}" ]
// VisitAll will traverse all commands from the root. // This is different from the VisitAll of cobra.Command where only parents // are checked.
[ "VisitAll", "will", "traverse", "all", "commands", "from", "the", "root", ".", "This", "is", "different", "from", "the", "VisitAll", "of", "cobra", ".", "Command", "where", "only", "parents", "are", "checked", "." ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/cobra.go#L161-L166
train
docker/cli
cli/cobra.go
DisableFlagsInUseLine
func DisableFlagsInUseLine(cmd *cobra.Command) { VisitAll(cmd, func(ccmd *cobra.Command) { // do not add a `[flags]` to the end of the usage line. ccmd.DisableFlagsInUseLine = true }) }
go
func DisableFlagsInUseLine(cmd *cobra.Command) { VisitAll(cmd, func(ccmd *cobra.Command) { // do not add a `[flags]` to the end of the usage line. ccmd.DisableFlagsInUseLine = true }) }
[ "func", "DisableFlagsInUseLine", "(", "cmd", "*", "cobra", ".", "Command", ")", "{", "VisitAll", "(", "cmd", ",", "func", "(", "ccmd", "*", "cobra", ".", "Command", ")", "{", "// do not add a `[flags]` to the end of the usage line.", "ccmd", ".", "DisableFlagsInUseLine", "=", "true", "\n", "}", ")", "\n", "}" ]
// DisableFlagsInUseLine sets the DisableFlagsInUseLine flag on all // commands within the tree rooted at cmd.
[ "DisableFlagsInUseLine", "sets", "the", "DisableFlagsInUseLine", "flag", "on", "all", "commands", "within", "the", "tree", "rooted", "at", "cmd", "." ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/cobra.go#L170-L175
train
docker/cli
cli/command/stack/swarm/deploy.go
RunDeploy
func RunDeploy(dockerCli command.Cli, opts options.Deploy, cfg *composetypes.Config) error { ctx := context.Background() if err := validateResolveImageFlag(dockerCli, &opts); err != nil { return err } return deployCompose(ctx, dockerCli, opts, cfg) }
go
func RunDeploy(dockerCli command.Cli, opts options.Deploy, cfg *composetypes.Config) error { ctx := context.Background() if err := validateResolveImageFlag(dockerCli, &opts); err != nil { return err } return deployCompose(ctx, dockerCli, opts, cfg) }
[ "func", "RunDeploy", "(", "dockerCli", "command", ".", "Cli", ",", "opts", "options", ".", "Deploy", ",", "cfg", "*", "composetypes", ".", "Config", ")", "error", "{", "ctx", ":=", "context", ".", "Background", "(", ")", "\n\n", "if", "err", ":=", "validateResolveImageFlag", "(", "dockerCli", ",", "&", "opts", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "deployCompose", "(", "ctx", ",", "dockerCli", ",", "opts", ",", "cfg", ")", "\n", "}" ]
// RunDeploy is the swarm implementation of docker stack deploy
[ "RunDeploy", "is", "the", "swarm", "implementation", "of", "docker", "stack", "deploy" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/stack/swarm/deploy.go#L25-L33
train
docker/cli
cli/command/stack/swarm/deploy.go
validateResolveImageFlag
func validateResolveImageFlag(dockerCli command.Cli, opts *options.Deploy) error { if opts.ResolveImage != ResolveImageAlways && opts.ResolveImage != ResolveImageChanged && opts.ResolveImage != ResolveImageNever { return errors.Errorf("Invalid option %s for flag --resolve-image", opts.ResolveImage) } // client side image resolution should not be done when the supported // server version is older than 1.30 if versions.LessThan(dockerCli.Client().ClientVersion(), "1.30") { opts.ResolveImage = ResolveImageNever } return nil }
go
func validateResolveImageFlag(dockerCli command.Cli, opts *options.Deploy) error { if opts.ResolveImage != ResolveImageAlways && opts.ResolveImage != ResolveImageChanged && opts.ResolveImage != ResolveImageNever { return errors.Errorf("Invalid option %s for flag --resolve-image", opts.ResolveImage) } // client side image resolution should not be done when the supported // server version is older than 1.30 if versions.LessThan(dockerCli.Client().ClientVersion(), "1.30") { opts.ResolveImage = ResolveImageNever } return nil }
[ "func", "validateResolveImageFlag", "(", "dockerCli", "command", ".", "Cli", ",", "opts", "*", "options", ".", "Deploy", ")", "error", "{", "if", "opts", ".", "ResolveImage", "!=", "ResolveImageAlways", "&&", "opts", ".", "ResolveImage", "!=", "ResolveImageChanged", "&&", "opts", ".", "ResolveImage", "!=", "ResolveImageNever", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "opts", ".", "ResolveImage", ")", "\n", "}", "\n", "// client side image resolution should not be done when the supported", "// server version is older than 1.30", "if", "versions", ".", "LessThan", "(", "dockerCli", ".", "Client", "(", ")", ".", "ClientVersion", "(", ")", ",", "\"", "\"", ")", "{", "opts", ".", "ResolveImage", "=", "ResolveImageNever", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// validateResolveImageFlag validates the opts.resolveImage command line option // and also turns image resolution off if the version is older than 1.30
[ "validateResolveImageFlag", "validates", "the", "opts", ".", "resolveImage", "command", "line", "option", "and", "also", "turns", "image", "resolution", "off", "if", "the", "version", "is", "older", "than", "1", ".", "30" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/stack/swarm/deploy.go#L37-L47
train
docker/cli
cli/command/stack/swarm/deploy.go
checkDaemonIsSwarmManager
func checkDaemonIsSwarmManager(ctx context.Context, dockerCli command.Cli) error { info, err := dockerCli.Client().Info(ctx) if err != nil { return err } if !info.Swarm.ControlAvailable { return errors.New("this node is not a swarm manager. Use \"docker swarm init\" or \"docker swarm join\" to connect this node to swarm and try again") } return nil }
go
func checkDaemonIsSwarmManager(ctx context.Context, dockerCli command.Cli) error { info, err := dockerCli.Client().Info(ctx) if err != nil { return err } if !info.Swarm.ControlAvailable { return errors.New("this node is not a swarm manager. Use \"docker swarm init\" or \"docker swarm join\" to connect this node to swarm and try again") } return nil }
[ "func", "checkDaemonIsSwarmManager", "(", "ctx", "context", ".", "Context", ",", "dockerCli", "command", ".", "Cli", ")", "error", "{", "info", ",", "err", ":=", "dockerCli", ".", "Client", "(", ")", ".", "Info", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "!", "info", ".", "Swarm", ".", "ControlAvailable", "{", "return", "errors", ".", "New", "(", "\"", "\\\"", "\\\"", "\\\"", "\\\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// checkDaemonIsSwarmManager does an Info API call to verify that the daemon is // a swarm manager. This is necessary because we must create networks before we // create services, but the API call for creating a network does not return a // proper status code when it can't create a network in the "global" scope.
[ "checkDaemonIsSwarmManager", "does", "an", "Info", "API", "call", "to", "verify", "that", "the", "daemon", "is", "a", "swarm", "manager", ".", "This", "is", "necessary", "because", "we", "must", "create", "networks", "before", "we", "create", "services", "but", "the", "API", "call", "for", "creating", "a", "network", "does", "not", "return", "a", "proper", "status", "code", "when", "it", "can", "t", "create", "a", "network", "in", "the", "global", "scope", "." ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/stack/swarm/deploy.go#L53-L62
train
docker/cli
cli/command/stack/swarm/deploy.go
pruneServices
func pruneServices(ctx context.Context, dockerCli command.Cli, namespace convert.Namespace, services map[string]struct{}) { client := dockerCli.Client() oldServices, err := getStackServices(ctx, client, namespace.Name()) if err != nil { fmt.Fprintf(dockerCli.Err(), "Failed to list services: %s\n", err) } pruneServices := []swarm.Service{} for _, service := range oldServices { if _, exists := services[namespace.Descope(service.Spec.Name)]; !exists { pruneServices = append(pruneServices, service) } } removeServices(ctx, dockerCli, pruneServices) }
go
func pruneServices(ctx context.Context, dockerCli command.Cli, namespace convert.Namespace, services map[string]struct{}) { client := dockerCli.Client() oldServices, err := getStackServices(ctx, client, namespace.Name()) if err != nil { fmt.Fprintf(dockerCli.Err(), "Failed to list services: %s\n", err) } pruneServices := []swarm.Service{} for _, service := range oldServices { if _, exists := services[namespace.Descope(service.Spec.Name)]; !exists { pruneServices = append(pruneServices, service) } } removeServices(ctx, dockerCli, pruneServices) }
[ "func", "pruneServices", "(", "ctx", "context", ".", "Context", ",", "dockerCli", "command", ".", "Cli", ",", "namespace", "convert", ".", "Namespace", ",", "services", "map", "[", "string", "]", "struct", "{", "}", ")", "{", "client", ":=", "dockerCli", ".", "Client", "(", ")", "\n\n", "oldServices", ",", "err", ":=", "getStackServices", "(", "ctx", ",", "client", ",", "namespace", ".", "Name", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Fprintf", "(", "dockerCli", ".", "Err", "(", ")", ",", "\"", "\\n", "\"", ",", "err", ")", "\n", "}", "\n\n", "pruneServices", ":=", "[", "]", "swarm", ".", "Service", "{", "}", "\n", "for", "_", ",", "service", ":=", "range", "oldServices", "{", "if", "_", ",", "exists", ":=", "services", "[", "namespace", ".", "Descope", "(", "service", ".", "Spec", ".", "Name", ")", "]", ";", "!", "exists", "{", "pruneServices", "=", "append", "(", "pruneServices", ",", "service", ")", "\n", "}", "\n", "}", "\n", "removeServices", "(", "ctx", ",", "dockerCli", ",", "pruneServices", ")", "\n", "}" ]
// pruneServices removes services that are no longer referenced in the source
[ "pruneServices", "removes", "services", "that", "are", "no", "longer", "referenced", "in", "the", "source" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/stack/swarm/deploy.go#L65-L80
train
docker/cli
opts/network.go
Set
func (n *NetworkOpt) Set(value string) error { longSyntax, err := regexp.MatchString(`\w+=\w+(,\w+=\w+)*`, value) if err != nil { return err } var netOpt NetworkAttachmentOpts if longSyntax { csvReader := csv.NewReader(strings.NewReader(value)) fields, err := csvReader.Read() if err != nil { return err } netOpt.Aliases = []string{} for _, field := range fields { parts := strings.SplitN(field, "=", 2) if len(parts) < 2 { return fmt.Errorf("invalid field %s", field) } key := strings.TrimSpace(strings.ToLower(parts[0])) value := strings.TrimSpace(strings.ToLower(parts[1])) switch key { case networkOptName: netOpt.Target = value case networkOptAlias: netOpt.Aliases = append(netOpt.Aliases, value) case driverOpt: key, value, err = parseDriverOpt(value) if err == nil { if netOpt.DriverOpts == nil { netOpt.DriverOpts = make(map[string]string) } netOpt.DriverOpts[key] = value } else { return err } default: return fmt.Errorf("invalid field key %s", key) } } if len(netOpt.Target) == 0 { return fmt.Errorf("network name/id is not specified") } } else { netOpt.Target = value } n.options = append(n.options, netOpt) return nil }
go
func (n *NetworkOpt) Set(value string) error { longSyntax, err := regexp.MatchString(`\w+=\w+(,\w+=\w+)*`, value) if err != nil { return err } var netOpt NetworkAttachmentOpts if longSyntax { csvReader := csv.NewReader(strings.NewReader(value)) fields, err := csvReader.Read() if err != nil { return err } netOpt.Aliases = []string{} for _, field := range fields { parts := strings.SplitN(field, "=", 2) if len(parts) < 2 { return fmt.Errorf("invalid field %s", field) } key := strings.TrimSpace(strings.ToLower(parts[0])) value := strings.TrimSpace(strings.ToLower(parts[1])) switch key { case networkOptName: netOpt.Target = value case networkOptAlias: netOpt.Aliases = append(netOpt.Aliases, value) case driverOpt: key, value, err = parseDriverOpt(value) if err == nil { if netOpt.DriverOpts == nil { netOpt.DriverOpts = make(map[string]string) } netOpt.DriverOpts[key] = value } else { return err } default: return fmt.Errorf("invalid field key %s", key) } } if len(netOpt.Target) == 0 { return fmt.Errorf("network name/id is not specified") } } else { netOpt.Target = value } n.options = append(n.options, netOpt) return nil }
[ "func", "(", "n", "*", "NetworkOpt", ")", "Set", "(", "value", "string", ")", "error", "{", "longSyntax", ",", "err", ":=", "regexp", ".", "MatchString", "(", "`\\w+=\\w+(,\\w+=\\w+)*`", ",", "value", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "var", "netOpt", "NetworkAttachmentOpts", "\n", "if", "longSyntax", "{", "csvReader", ":=", "csv", ".", "NewReader", "(", "strings", ".", "NewReader", "(", "value", ")", ")", "\n", "fields", ",", "err", ":=", "csvReader", ".", "Read", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "netOpt", ".", "Aliases", "=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "field", ":=", "range", "fields", "{", "parts", ":=", "strings", ".", "SplitN", "(", "field", ",", "\"", "\"", ",", "2", ")", "\n\n", "if", "len", "(", "parts", ")", "<", "2", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "field", ")", "\n", "}", "\n\n", "key", ":=", "strings", ".", "TrimSpace", "(", "strings", ".", "ToLower", "(", "parts", "[", "0", "]", ")", ")", "\n", "value", ":=", "strings", ".", "TrimSpace", "(", "strings", ".", "ToLower", "(", "parts", "[", "1", "]", ")", ")", "\n\n", "switch", "key", "{", "case", "networkOptName", ":", "netOpt", ".", "Target", "=", "value", "\n", "case", "networkOptAlias", ":", "netOpt", ".", "Aliases", "=", "append", "(", "netOpt", ".", "Aliases", ",", "value", ")", "\n", "case", "driverOpt", ":", "key", ",", "value", ",", "err", "=", "parseDriverOpt", "(", "value", ")", "\n", "if", "err", "==", "nil", "{", "if", "netOpt", ".", "DriverOpts", "==", "nil", "{", "netOpt", ".", "DriverOpts", "=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "}", "\n", "netOpt", ".", "DriverOpts", "[", "key", "]", "=", "value", "\n", "}", "else", "{", "return", "err", "\n", "}", "\n", "default", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "key", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "netOpt", ".", "Target", ")", "==", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "else", "{", "netOpt", ".", "Target", "=", "value", "\n", "}", "\n", "n", ".", "options", "=", "append", "(", "n", ".", "options", ",", "netOpt", ")", "\n", "return", "nil", "\n", "}" ]
// Set networkopts value
[ "Set", "networkopts", "value" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/opts/network.go#L33-L85
train
docker/cli
opts/network.go
NetworkMode
func (n *NetworkOpt) NetworkMode() string { networkIDOrName := "default" netOptVal := n.Value() if len(netOptVal) > 0 { networkIDOrName = netOptVal[0].Target } return networkIDOrName }
go
func (n *NetworkOpt) NetworkMode() string { networkIDOrName := "default" netOptVal := n.Value() if len(netOptVal) > 0 { networkIDOrName = netOptVal[0].Target } return networkIDOrName }
[ "func", "(", "n", "*", "NetworkOpt", ")", "NetworkMode", "(", ")", "string", "{", "networkIDOrName", ":=", "\"", "\"", "\n", "netOptVal", ":=", "n", ".", "Value", "(", ")", "\n", "if", "len", "(", "netOptVal", ")", ">", "0", "{", "networkIDOrName", "=", "netOptVal", "[", "0", "]", ".", "Target", "\n", "}", "\n", "return", "networkIDOrName", "\n", "}" ]
// NetworkMode return the network mode for the network option
[ "NetworkMode", "return", "the", "network", "mode", "for", "the", "network", "option" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/opts/network.go#L103-L110
train
docker/cli
cli/command/secret/cmd.go
NewSecretCommand
func NewSecretCommand(dockerCli command.Cli) *cobra.Command { cmd := &cobra.Command{ Use: "secret", Short: "Manage Docker secrets", Args: cli.NoArgs, RunE: command.ShowHelp(dockerCli.Err()), Annotations: map[string]string{ "version": "1.25", "swarm": "", }, } cmd.AddCommand( newSecretListCommand(dockerCli), newSecretCreateCommand(dockerCli), newSecretInspectCommand(dockerCli), newSecretRemoveCommand(dockerCli), ) return cmd }
go
func NewSecretCommand(dockerCli command.Cli) *cobra.Command { cmd := &cobra.Command{ Use: "secret", Short: "Manage Docker secrets", Args: cli.NoArgs, RunE: command.ShowHelp(dockerCli.Err()), Annotations: map[string]string{ "version": "1.25", "swarm": "", }, } cmd.AddCommand( newSecretListCommand(dockerCli), newSecretCreateCommand(dockerCli), newSecretInspectCommand(dockerCli), newSecretRemoveCommand(dockerCli), ) return cmd }
[ "func", "NewSecretCommand", "(", "dockerCli", "command", ".", "Cli", ")", "*", "cobra", ".", "Command", "{", "cmd", ":=", "&", "cobra", ".", "Command", "{", "Use", ":", "\"", "\"", ",", "Short", ":", "\"", "\"", ",", "Args", ":", "cli", ".", "NoArgs", ",", "RunE", ":", "command", ".", "ShowHelp", "(", "dockerCli", ".", "Err", "(", ")", ")", ",", "Annotations", ":", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "\"", "\"", ",", "}", ",", "}", "\n", "cmd", ".", "AddCommand", "(", "newSecretListCommand", "(", "dockerCli", ")", ",", "newSecretCreateCommand", "(", "dockerCli", ")", ",", "newSecretInspectCommand", "(", "dockerCli", ")", ",", "newSecretRemoveCommand", "(", "dockerCli", ")", ",", ")", "\n", "return", "cmd", "\n", "}" ]
// NewSecretCommand returns a cobra command for `secret` subcommands
[ "NewSecretCommand", "returns", "a", "cobra", "command", "for", "secret", "subcommands" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/secret/cmd.go#L11-L29
train
docker/cli
cli/trust/trust.go
certificateDirectory
func certificateDirectory(server string) (string, error) { u, err := url.Parse(server) if err != nil { return "", err } return filepath.Join(cliconfig.Dir(), "tls", u.Host), nil }
go
func certificateDirectory(server string) (string, error) { u, err := url.Parse(server) if err != nil { return "", err } return filepath.Join(cliconfig.Dir(), "tls", u.Host), nil }
[ "func", "certificateDirectory", "(", "server", "string", ")", "(", "string", ",", "error", ")", "{", "u", ",", "err", ":=", "url", ".", "Parse", "(", "server", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "return", "filepath", ".", "Join", "(", "cliconfig", ".", "Dir", "(", ")", ",", "\"", "\"", ",", "u", ".", "Host", ")", ",", "nil", "\n", "}" ]
// certificateDirectory returns the directory containing // TLS certificates for the given server. An error is // returned if there was an error parsing the server string.
[ "certificateDirectory", "returns", "the", "directory", "containing", "TLS", "certificates", "for", "the", "given", "server", ".", "An", "error", "is", "returned", "if", "there", "was", "an", "error", "parsing", "the", "server", "string", "." ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/trust/trust.go#L56-L63
train
docker/cli
cli/trust/trust.go
Server
func Server(index *registrytypes.IndexInfo) (string, error) { if s := os.Getenv("DOCKER_CONTENT_TRUST_SERVER"); s != "" { urlObj, err := url.Parse(s) if err != nil || urlObj.Scheme != "https" { return "", errors.Errorf("valid https URL required for trust server, got %s", s) } return s, nil } if index.Official { return NotaryServer, nil } return "https://" + index.Name, nil }
go
func Server(index *registrytypes.IndexInfo) (string, error) { if s := os.Getenv("DOCKER_CONTENT_TRUST_SERVER"); s != "" { urlObj, err := url.Parse(s) if err != nil || urlObj.Scheme != "https" { return "", errors.Errorf("valid https URL required for trust server, got %s", s) } return s, nil } if index.Official { return NotaryServer, nil } return "https://" + index.Name, nil }
[ "func", "Server", "(", "index", "*", "registrytypes", ".", "IndexInfo", ")", "(", "string", ",", "error", ")", "{", "if", "s", ":=", "os", ".", "Getenv", "(", "\"", "\"", ")", ";", "s", "!=", "\"", "\"", "{", "urlObj", ",", "err", ":=", "url", ".", "Parse", "(", "s", ")", "\n", "if", "err", "!=", "nil", "||", "urlObj", ".", "Scheme", "!=", "\"", "\"", "{", "return", "\"", "\"", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "s", ")", "\n", "}", "\n\n", "return", "s", ",", "nil", "\n", "}", "\n", "if", "index", ".", "Official", "{", "return", "NotaryServer", ",", "nil", "\n", "}", "\n", "return", "\"", "\"", "+", "index", ".", "Name", ",", "nil", "\n", "}" ]
// Server returns the base URL for the trust server.
[ "Server", "returns", "the", "base", "URL", "for", "the", "trust", "server", "." ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/trust/trust.go#L66-L79
train
docker/cli
cli/trust/trust.go
GetNotaryRepository
func GetNotaryRepository(in io.Reader, out io.Writer, userAgent string, repoInfo *registry.RepositoryInfo, authConfig *types.AuthConfig, actions ...string) (client.Repository, error) { server, err := Server(repoInfo.Index) if err != nil { return nil, err } var cfg = tlsconfig.ClientDefault() cfg.InsecureSkipVerify = !repoInfo.Index.Secure // Get certificate base directory certDir, err := certificateDirectory(server) if err != nil { return nil, err } logrus.Debugf("reading certificate directory: %s", certDir) if err := registry.ReadCertsDirectory(cfg, certDir); err != nil { return nil, err } base := &http.Transport{ Proxy: http.ProxyFromEnvironment, Dial: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, DualStack: true, }).Dial, TLSHandshakeTimeout: 10 * time.Second, TLSClientConfig: cfg, DisableKeepAlives: true, } // Skip configuration headers since request is not going to Docker daemon modifiers := registry.Headers(userAgent, http.Header{}) authTransport := transport.NewTransport(base, modifiers...) pingClient := &http.Client{ Transport: authTransport, Timeout: 5 * time.Second, } endpointStr := server + "/v2/" req, err := http.NewRequest("GET", endpointStr, nil) if err != nil { return nil, err } challengeManager := challenge.NewSimpleManager() resp, err := pingClient.Do(req) if err != nil { // Ignore error on ping to operate in offline mode logrus.Debugf("Error pinging notary server %q: %s", endpointStr, err) } else { defer resp.Body.Close() // Add response to the challenge manager to parse out // authentication header and register authentication method if err := challengeManager.AddResponse(resp); err != nil { return nil, err } } scope := auth.RepositoryScope{ Repository: repoInfo.Name.Name(), Actions: actions, Class: repoInfo.Class, } creds := simpleCredentialStore{auth: *authConfig} tokenHandlerOptions := auth.TokenHandlerOptions{ Transport: authTransport, Credentials: creds, Scopes: []auth.Scope{scope}, ClientID: registry.AuthClientID, } tokenHandler := auth.NewTokenHandlerWithOptions(tokenHandlerOptions) basicHandler := auth.NewBasicHandler(creds) modifiers = append(modifiers, auth.NewAuthorizer(challengeManager, tokenHandler, basicHandler)) tr := transport.NewTransport(base, modifiers...) return client.NewFileCachedRepository( GetTrustDirectory(), data.GUN(repoInfo.Name.Name()), server, tr, GetPassphraseRetriever(in, out), trustpinning.TrustPinConfig{}) }
go
func GetNotaryRepository(in io.Reader, out io.Writer, userAgent string, repoInfo *registry.RepositoryInfo, authConfig *types.AuthConfig, actions ...string) (client.Repository, error) { server, err := Server(repoInfo.Index) if err != nil { return nil, err } var cfg = tlsconfig.ClientDefault() cfg.InsecureSkipVerify = !repoInfo.Index.Secure // Get certificate base directory certDir, err := certificateDirectory(server) if err != nil { return nil, err } logrus.Debugf("reading certificate directory: %s", certDir) if err := registry.ReadCertsDirectory(cfg, certDir); err != nil { return nil, err } base := &http.Transport{ Proxy: http.ProxyFromEnvironment, Dial: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, DualStack: true, }).Dial, TLSHandshakeTimeout: 10 * time.Second, TLSClientConfig: cfg, DisableKeepAlives: true, } // Skip configuration headers since request is not going to Docker daemon modifiers := registry.Headers(userAgent, http.Header{}) authTransport := transport.NewTransport(base, modifiers...) pingClient := &http.Client{ Transport: authTransport, Timeout: 5 * time.Second, } endpointStr := server + "/v2/" req, err := http.NewRequest("GET", endpointStr, nil) if err != nil { return nil, err } challengeManager := challenge.NewSimpleManager() resp, err := pingClient.Do(req) if err != nil { // Ignore error on ping to operate in offline mode logrus.Debugf("Error pinging notary server %q: %s", endpointStr, err) } else { defer resp.Body.Close() // Add response to the challenge manager to parse out // authentication header and register authentication method if err := challengeManager.AddResponse(resp); err != nil { return nil, err } } scope := auth.RepositoryScope{ Repository: repoInfo.Name.Name(), Actions: actions, Class: repoInfo.Class, } creds := simpleCredentialStore{auth: *authConfig} tokenHandlerOptions := auth.TokenHandlerOptions{ Transport: authTransport, Credentials: creds, Scopes: []auth.Scope{scope}, ClientID: registry.AuthClientID, } tokenHandler := auth.NewTokenHandlerWithOptions(tokenHandlerOptions) basicHandler := auth.NewBasicHandler(creds) modifiers = append(modifiers, auth.NewAuthorizer(challengeManager, tokenHandler, basicHandler)) tr := transport.NewTransport(base, modifiers...) return client.NewFileCachedRepository( GetTrustDirectory(), data.GUN(repoInfo.Name.Name()), server, tr, GetPassphraseRetriever(in, out), trustpinning.TrustPinConfig{}) }
[ "func", "GetNotaryRepository", "(", "in", "io", ".", "Reader", ",", "out", "io", ".", "Writer", ",", "userAgent", "string", ",", "repoInfo", "*", "registry", ".", "RepositoryInfo", ",", "authConfig", "*", "types", ".", "AuthConfig", ",", "actions", "...", "string", ")", "(", "client", ".", "Repository", ",", "error", ")", "{", "server", ",", "err", ":=", "Server", "(", "repoInfo", ".", "Index", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "cfg", "=", "tlsconfig", ".", "ClientDefault", "(", ")", "\n", "cfg", ".", "InsecureSkipVerify", "=", "!", "repoInfo", ".", "Index", ".", "Secure", "\n\n", "// Get certificate base directory", "certDir", ",", "err", ":=", "certificateDirectory", "(", "server", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "logrus", ".", "Debugf", "(", "\"", "\"", ",", "certDir", ")", "\n\n", "if", "err", ":=", "registry", ".", "ReadCertsDirectory", "(", "cfg", ",", "certDir", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "base", ":=", "&", "http", ".", "Transport", "{", "Proxy", ":", "http", ".", "ProxyFromEnvironment", ",", "Dial", ":", "(", "&", "net", ".", "Dialer", "{", "Timeout", ":", "30", "*", "time", ".", "Second", ",", "KeepAlive", ":", "30", "*", "time", ".", "Second", ",", "DualStack", ":", "true", ",", "}", ")", ".", "Dial", ",", "TLSHandshakeTimeout", ":", "10", "*", "time", ".", "Second", ",", "TLSClientConfig", ":", "cfg", ",", "DisableKeepAlives", ":", "true", ",", "}", "\n\n", "// Skip configuration headers since request is not going to Docker daemon", "modifiers", ":=", "registry", ".", "Headers", "(", "userAgent", ",", "http", ".", "Header", "{", "}", ")", "\n", "authTransport", ":=", "transport", ".", "NewTransport", "(", "base", ",", "modifiers", "...", ")", "\n", "pingClient", ":=", "&", "http", ".", "Client", "{", "Transport", ":", "authTransport", ",", "Timeout", ":", "5", "*", "time", ".", "Second", ",", "}", "\n", "endpointStr", ":=", "server", "+", "\"", "\"", "\n", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"", "\"", ",", "endpointStr", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "challengeManager", ":=", "challenge", ".", "NewSimpleManager", "(", ")", "\n\n", "resp", ",", "err", ":=", "pingClient", ".", "Do", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "// Ignore error on ping to operate in offline mode", "logrus", ".", "Debugf", "(", "\"", "\"", ",", "endpointStr", ",", "err", ")", "\n", "}", "else", "{", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n\n", "// Add response to the challenge manager to parse out", "// authentication header and register authentication method", "if", "err", ":=", "challengeManager", ".", "AddResponse", "(", "resp", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "scope", ":=", "auth", ".", "RepositoryScope", "{", "Repository", ":", "repoInfo", ".", "Name", ".", "Name", "(", ")", ",", "Actions", ":", "actions", ",", "Class", ":", "repoInfo", ".", "Class", ",", "}", "\n", "creds", ":=", "simpleCredentialStore", "{", "auth", ":", "*", "authConfig", "}", "\n", "tokenHandlerOptions", ":=", "auth", ".", "TokenHandlerOptions", "{", "Transport", ":", "authTransport", ",", "Credentials", ":", "creds", ",", "Scopes", ":", "[", "]", "auth", ".", "Scope", "{", "scope", "}", ",", "ClientID", ":", "registry", ".", "AuthClientID", ",", "}", "\n", "tokenHandler", ":=", "auth", ".", "NewTokenHandlerWithOptions", "(", "tokenHandlerOptions", ")", "\n", "basicHandler", ":=", "auth", ".", "NewBasicHandler", "(", "creds", ")", "\n", "modifiers", "=", "append", "(", "modifiers", ",", "auth", ".", "NewAuthorizer", "(", "challengeManager", ",", "tokenHandler", ",", "basicHandler", ")", ")", "\n", "tr", ":=", "transport", ".", "NewTransport", "(", "base", ",", "modifiers", "...", ")", "\n\n", "return", "client", ".", "NewFileCachedRepository", "(", "GetTrustDirectory", "(", ")", ",", "data", ".", "GUN", "(", "repoInfo", ".", "Name", ".", "Name", "(", ")", ")", ",", "server", ",", "tr", ",", "GetPassphraseRetriever", "(", "in", ",", "out", ")", ",", "trustpinning", ".", "TrustPinConfig", "{", "}", ")", "\n", "}" ]
// GetNotaryRepository returns a NotaryRepository which stores all the // information needed to operate on a notary repository. // It creates an HTTP transport providing authentication support.
[ "GetNotaryRepository", "returns", "a", "NotaryRepository", "which", "stores", "all", "the", "information", "needed", "to", "operate", "on", "a", "notary", "repository", ".", "It", "creates", "an", "HTTP", "transport", "providing", "authentication", "support", "." ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/trust/trust.go#L99-L184
train
docker/cli
cli/trust/trust.go
GetPassphraseRetriever
func GetPassphraseRetriever(in io.Reader, out io.Writer) notary.PassRetriever { aliasMap := map[string]string{ "root": "root", "snapshot": "repository", "targets": "repository", "default": "repository", } baseRetriever := passphrase.PromptRetrieverWithInOut(in, out, aliasMap) env := map[string]string{ "root": os.Getenv("DOCKER_CONTENT_TRUST_ROOT_PASSPHRASE"), "snapshot": os.Getenv("DOCKER_CONTENT_TRUST_REPOSITORY_PASSPHRASE"), "targets": os.Getenv("DOCKER_CONTENT_TRUST_REPOSITORY_PASSPHRASE"), "default": os.Getenv("DOCKER_CONTENT_TRUST_REPOSITORY_PASSPHRASE"), } return func(keyName string, alias string, createNew bool, numAttempts int) (string, bool, error) { if v := env[alias]; v != "" { return v, numAttempts > 1, nil } // For non-root roles, we can also try the "default" alias if it is specified if v := env["default"]; v != "" && alias != data.CanonicalRootRole.String() { return v, numAttempts > 1, nil } return baseRetriever(keyName, alias, createNew, numAttempts) } }
go
func GetPassphraseRetriever(in io.Reader, out io.Writer) notary.PassRetriever { aliasMap := map[string]string{ "root": "root", "snapshot": "repository", "targets": "repository", "default": "repository", } baseRetriever := passphrase.PromptRetrieverWithInOut(in, out, aliasMap) env := map[string]string{ "root": os.Getenv("DOCKER_CONTENT_TRUST_ROOT_PASSPHRASE"), "snapshot": os.Getenv("DOCKER_CONTENT_TRUST_REPOSITORY_PASSPHRASE"), "targets": os.Getenv("DOCKER_CONTENT_TRUST_REPOSITORY_PASSPHRASE"), "default": os.Getenv("DOCKER_CONTENT_TRUST_REPOSITORY_PASSPHRASE"), } return func(keyName string, alias string, createNew bool, numAttempts int) (string, bool, error) { if v := env[alias]; v != "" { return v, numAttempts > 1, nil } // For non-root roles, we can also try the "default" alias if it is specified if v := env["default"]; v != "" && alias != data.CanonicalRootRole.String() { return v, numAttempts > 1, nil } return baseRetriever(keyName, alias, createNew, numAttempts) } }
[ "func", "GetPassphraseRetriever", "(", "in", "io", ".", "Reader", ",", "out", "io", ".", "Writer", ")", "notary", ".", "PassRetriever", "{", "aliasMap", ":=", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "\"", "\"", ",", "}", "\n", "baseRetriever", ":=", "passphrase", ".", "PromptRetrieverWithInOut", "(", "in", ",", "out", ",", "aliasMap", ")", "\n", "env", ":=", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "os", ".", "Getenv", "(", "\"", "\"", ")", ",", "\"", "\"", ":", "os", ".", "Getenv", "(", "\"", "\"", ")", ",", "\"", "\"", ":", "os", ".", "Getenv", "(", "\"", "\"", ")", ",", "\"", "\"", ":", "os", ".", "Getenv", "(", "\"", "\"", ")", ",", "}", "\n\n", "return", "func", "(", "keyName", "string", ",", "alias", "string", ",", "createNew", "bool", ",", "numAttempts", "int", ")", "(", "string", ",", "bool", ",", "error", ")", "{", "if", "v", ":=", "env", "[", "alias", "]", ";", "v", "!=", "\"", "\"", "{", "return", "v", ",", "numAttempts", ">", "1", ",", "nil", "\n", "}", "\n", "// For non-root roles, we can also try the \"default\" alias if it is specified", "if", "v", ":=", "env", "[", "\"", "\"", "]", ";", "v", "!=", "\"", "\"", "&&", "alias", "!=", "data", ".", "CanonicalRootRole", ".", "String", "(", ")", "{", "return", "v", ",", "numAttempts", ">", "1", ",", "nil", "\n", "}", "\n", "return", "baseRetriever", "(", "keyName", ",", "alias", ",", "createNew", ",", "numAttempts", ")", "\n", "}", "\n", "}" ]
// GetPassphraseRetriever returns a passphrase retriever that utilizes Content Trust env vars
[ "GetPassphraseRetriever", "returns", "a", "passphrase", "retriever", "that", "utilizes", "Content", "Trust", "env", "vars" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/trust/trust.go#L187-L212
train
docker/cli
cli/trust/trust.go
NotaryError
func NotaryError(repoName string, err error) error { switch err.(type) { case *json.SyntaxError: logrus.Debugf("Notary syntax error: %s", err) return errors.Errorf("Error: no trust data available for remote repository %s. Try running notary server and setting DOCKER_CONTENT_TRUST_SERVER to its HTTPS address?", repoName) case signed.ErrExpired: return errors.Errorf("Error: remote repository %s out-of-date: %v", repoName, err) case trustmanager.ErrKeyNotFound: return errors.Errorf("Error: signing keys for remote repository %s not found: %v", repoName, err) case storage.NetworkError: return errors.Errorf("Error: error contacting notary server: %v", err) case storage.ErrMetaNotFound: return errors.Errorf("Error: trust data missing for remote repository %s or remote repository not found: %v", repoName, err) case trustpinning.ErrRootRotationFail, trustpinning.ErrValidationFail, signed.ErrInvalidKeyType: return errors.Errorf("Warning: potential malicious behavior - trust data mismatch for remote repository %s: %v", repoName, err) case signed.ErrNoKeys: return errors.Errorf("Error: could not find signing keys for remote repository %s, or could not decrypt signing key: %v", repoName, err) case signed.ErrLowVersion: return errors.Errorf("Warning: potential malicious behavior - trust data version is lower than expected for remote repository %s: %v", repoName, err) case signed.ErrRoleThreshold: return errors.Errorf("Warning: potential malicious behavior - trust data has insufficient signatures for remote repository %s: %v", repoName, err) case client.ErrRepositoryNotExist: return errors.Errorf("Error: remote trust data does not exist for %s: %v", repoName, err) case signed.ErrInsufficientSignatures: return errors.Errorf("Error: could not produce valid signature for %s. If Yubikey was used, was touch input provided?: %v", repoName, err) } return err }
go
func NotaryError(repoName string, err error) error { switch err.(type) { case *json.SyntaxError: logrus.Debugf("Notary syntax error: %s", err) return errors.Errorf("Error: no trust data available for remote repository %s. Try running notary server and setting DOCKER_CONTENT_TRUST_SERVER to its HTTPS address?", repoName) case signed.ErrExpired: return errors.Errorf("Error: remote repository %s out-of-date: %v", repoName, err) case trustmanager.ErrKeyNotFound: return errors.Errorf("Error: signing keys for remote repository %s not found: %v", repoName, err) case storage.NetworkError: return errors.Errorf("Error: error contacting notary server: %v", err) case storage.ErrMetaNotFound: return errors.Errorf("Error: trust data missing for remote repository %s or remote repository not found: %v", repoName, err) case trustpinning.ErrRootRotationFail, trustpinning.ErrValidationFail, signed.ErrInvalidKeyType: return errors.Errorf("Warning: potential malicious behavior - trust data mismatch for remote repository %s: %v", repoName, err) case signed.ErrNoKeys: return errors.Errorf("Error: could not find signing keys for remote repository %s, or could not decrypt signing key: %v", repoName, err) case signed.ErrLowVersion: return errors.Errorf("Warning: potential malicious behavior - trust data version is lower than expected for remote repository %s: %v", repoName, err) case signed.ErrRoleThreshold: return errors.Errorf("Warning: potential malicious behavior - trust data has insufficient signatures for remote repository %s: %v", repoName, err) case client.ErrRepositoryNotExist: return errors.Errorf("Error: remote trust data does not exist for %s: %v", repoName, err) case signed.ErrInsufficientSignatures: return errors.Errorf("Error: could not produce valid signature for %s. If Yubikey was used, was touch input provided?: %v", repoName, err) } return err }
[ "func", "NotaryError", "(", "repoName", "string", ",", "err", "error", ")", "error", "{", "switch", "err", ".", "(", "type", ")", "{", "case", "*", "json", ".", "SyntaxError", ":", "logrus", ".", "Debugf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "repoName", ")", "\n", "case", "signed", ".", "ErrExpired", ":", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "repoName", ",", "err", ")", "\n", "case", "trustmanager", ".", "ErrKeyNotFound", ":", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "repoName", ",", "err", ")", "\n", "case", "storage", ".", "NetworkError", ":", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "case", "storage", ".", "ErrMetaNotFound", ":", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "repoName", ",", "err", ")", "\n", "case", "trustpinning", ".", "ErrRootRotationFail", ",", "trustpinning", ".", "ErrValidationFail", ",", "signed", ".", "ErrInvalidKeyType", ":", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "repoName", ",", "err", ")", "\n", "case", "signed", ".", "ErrNoKeys", ":", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "repoName", ",", "err", ")", "\n", "case", "signed", ".", "ErrLowVersion", ":", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "repoName", ",", "err", ")", "\n", "case", "signed", ".", "ErrRoleThreshold", ":", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "repoName", ",", "err", ")", "\n", "case", "client", ".", "ErrRepositoryNotExist", ":", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "repoName", ",", "err", ")", "\n", "case", "signed", ".", "ErrInsufficientSignatures", ":", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "repoName", ",", "err", ")", "\n", "}", "\n\n", "return", "err", "\n", "}" ]
// NotaryError formats an error message received from the notary service
[ "NotaryError", "formats", "an", "error", "message", "received", "from", "the", "notary", "service" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/trust/trust.go#L215-L243
train
docker/cli
cli/trust/trust.go
GetSignableRoles
func GetSignableRoles(repo client.Repository, target *client.Target) ([]data.RoleName, error) { var signableRoles []data.RoleName // translate the full key names, which includes the GUN, into just the key IDs allCanonicalKeyIDs := make(map[string]struct{}) for fullKeyID := range repo.GetCryptoService().ListAllKeys() { allCanonicalKeyIDs[path.Base(fullKeyID)] = struct{}{} } allDelegationRoles, err := repo.GetDelegationRoles() if err != nil { return signableRoles, err } // if there are no delegation roles, then just try to sign it into the targets role if len(allDelegationRoles) == 0 { signableRoles = append(signableRoles, data.CanonicalTargetsRole) return signableRoles, nil } // there are delegation roles, find every delegation role we have a key for, and // attempt to sign into into all those roles. for _, delegationRole := range allDelegationRoles { // We do not support signing any delegation role that isn't a direct child of the targets role. // Also don't bother checking the keys if we can't add the target // to this role due to path restrictions if path.Dir(delegationRole.Name.String()) != data.CanonicalTargetsRole.String() || !delegationRole.CheckPaths(target.Name) { continue } for _, canonicalKeyID := range delegationRole.KeyIDs { if _, ok := allCanonicalKeyIDs[canonicalKeyID]; ok { signableRoles = append(signableRoles, delegationRole.Name) break } } } if len(signableRoles) == 0 { return signableRoles, errors.Errorf("no valid signing keys for delegation roles") } return signableRoles, nil }
go
func GetSignableRoles(repo client.Repository, target *client.Target) ([]data.RoleName, error) { var signableRoles []data.RoleName // translate the full key names, which includes the GUN, into just the key IDs allCanonicalKeyIDs := make(map[string]struct{}) for fullKeyID := range repo.GetCryptoService().ListAllKeys() { allCanonicalKeyIDs[path.Base(fullKeyID)] = struct{}{} } allDelegationRoles, err := repo.GetDelegationRoles() if err != nil { return signableRoles, err } // if there are no delegation roles, then just try to sign it into the targets role if len(allDelegationRoles) == 0 { signableRoles = append(signableRoles, data.CanonicalTargetsRole) return signableRoles, nil } // there are delegation roles, find every delegation role we have a key for, and // attempt to sign into into all those roles. for _, delegationRole := range allDelegationRoles { // We do not support signing any delegation role that isn't a direct child of the targets role. // Also don't bother checking the keys if we can't add the target // to this role due to path restrictions if path.Dir(delegationRole.Name.String()) != data.CanonicalTargetsRole.String() || !delegationRole.CheckPaths(target.Name) { continue } for _, canonicalKeyID := range delegationRole.KeyIDs { if _, ok := allCanonicalKeyIDs[canonicalKeyID]; ok { signableRoles = append(signableRoles, delegationRole.Name) break } } } if len(signableRoles) == 0 { return signableRoles, errors.Errorf("no valid signing keys for delegation roles") } return signableRoles, nil }
[ "func", "GetSignableRoles", "(", "repo", "client", ".", "Repository", ",", "target", "*", "client", ".", "Target", ")", "(", "[", "]", "data", ".", "RoleName", ",", "error", ")", "{", "var", "signableRoles", "[", "]", "data", ".", "RoleName", "\n\n", "// translate the full key names, which includes the GUN, into just the key IDs", "allCanonicalKeyIDs", ":=", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", "\n", "for", "fullKeyID", ":=", "range", "repo", ".", "GetCryptoService", "(", ")", ".", "ListAllKeys", "(", ")", "{", "allCanonicalKeyIDs", "[", "path", ".", "Base", "(", "fullKeyID", ")", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n\n", "allDelegationRoles", ",", "err", ":=", "repo", ".", "GetDelegationRoles", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "signableRoles", ",", "err", "\n", "}", "\n\n", "// if there are no delegation roles, then just try to sign it into the targets role", "if", "len", "(", "allDelegationRoles", ")", "==", "0", "{", "signableRoles", "=", "append", "(", "signableRoles", ",", "data", ".", "CanonicalTargetsRole", ")", "\n", "return", "signableRoles", ",", "nil", "\n", "}", "\n\n", "// there are delegation roles, find every delegation role we have a key for, and", "// attempt to sign into into all those roles.", "for", "_", ",", "delegationRole", ":=", "range", "allDelegationRoles", "{", "// We do not support signing any delegation role that isn't a direct child of the targets role.", "// Also don't bother checking the keys if we can't add the target", "// to this role due to path restrictions", "if", "path", ".", "Dir", "(", "delegationRole", ".", "Name", ".", "String", "(", ")", ")", "!=", "data", ".", "CanonicalTargetsRole", ".", "String", "(", ")", "||", "!", "delegationRole", ".", "CheckPaths", "(", "target", ".", "Name", ")", "{", "continue", "\n", "}", "\n\n", "for", "_", ",", "canonicalKeyID", ":=", "range", "delegationRole", ".", "KeyIDs", "{", "if", "_", ",", "ok", ":=", "allCanonicalKeyIDs", "[", "canonicalKeyID", "]", ";", "ok", "{", "signableRoles", "=", "append", "(", "signableRoles", ",", "delegationRole", ".", "Name", ")", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n\n", "if", "len", "(", "signableRoles", ")", "==", "0", "{", "return", "signableRoles", ",", "errors", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "signableRoles", ",", "nil", "\n\n", "}" ]
// GetSignableRoles returns a list of roles for which we have valid signing // keys, given a notary repository and a target
[ "GetSignableRoles", "returns", "a", "list", "of", "roles", "for", "which", "we", "have", "valid", "signing", "keys", "given", "a", "notary", "repository", "and", "a", "target" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/trust/trust.go#L247-L291
train
docker/cli
cli/trust/trust.go
GetImageReferencesAndAuth
func GetImageReferencesAndAuth(ctx context.Context, rs registry.Service, authResolver func(ctx context.Context, index *registrytypes.IndexInfo) types.AuthConfig, imgName string, ) (ImageRefAndAuth, error) { ref, err := reference.ParseNormalizedNamed(imgName) if err != nil { return ImageRefAndAuth{}, err } // Resolve the Repository name from fqn to RepositoryInfo var repoInfo *registry.RepositoryInfo if rs != nil { repoInfo, err = rs.ResolveRepository(ref) } else { repoInfo, err = registry.ParseRepositoryInfo(ref) } if err != nil { return ImageRefAndAuth{}, err } authConfig := authResolver(ctx, repoInfo.Index) return ImageRefAndAuth{ original: imgName, authConfig: &authConfig, reference: ref, repoInfo: repoInfo, tag: getTag(ref), digest: getDigest(ref), }, nil }
go
func GetImageReferencesAndAuth(ctx context.Context, rs registry.Service, authResolver func(ctx context.Context, index *registrytypes.IndexInfo) types.AuthConfig, imgName string, ) (ImageRefAndAuth, error) { ref, err := reference.ParseNormalizedNamed(imgName) if err != nil { return ImageRefAndAuth{}, err } // Resolve the Repository name from fqn to RepositoryInfo var repoInfo *registry.RepositoryInfo if rs != nil { repoInfo, err = rs.ResolveRepository(ref) } else { repoInfo, err = registry.ParseRepositoryInfo(ref) } if err != nil { return ImageRefAndAuth{}, err } authConfig := authResolver(ctx, repoInfo.Index) return ImageRefAndAuth{ original: imgName, authConfig: &authConfig, reference: ref, repoInfo: repoInfo, tag: getTag(ref), digest: getDigest(ref), }, nil }
[ "func", "GetImageReferencesAndAuth", "(", "ctx", "context", ".", "Context", ",", "rs", "registry", ".", "Service", ",", "authResolver", "func", "(", "ctx", "context", ".", "Context", ",", "index", "*", "registrytypes", ".", "IndexInfo", ")", "types", ".", "AuthConfig", ",", "imgName", "string", ",", ")", "(", "ImageRefAndAuth", ",", "error", ")", "{", "ref", ",", "err", ":=", "reference", ".", "ParseNormalizedNamed", "(", "imgName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "ImageRefAndAuth", "{", "}", ",", "err", "\n", "}", "\n\n", "// Resolve the Repository name from fqn to RepositoryInfo", "var", "repoInfo", "*", "registry", ".", "RepositoryInfo", "\n", "if", "rs", "!=", "nil", "{", "repoInfo", ",", "err", "=", "rs", ".", "ResolveRepository", "(", "ref", ")", "\n", "}", "else", "{", "repoInfo", ",", "err", "=", "registry", ".", "ParseRepositoryInfo", "(", "ref", ")", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "return", "ImageRefAndAuth", "{", "}", ",", "err", "\n", "}", "\n\n", "authConfig", ":=", "authResolver", "(", "ctx", ",", "repoInfo", ".", "Index", ")", "\n", "return", "ImageRefAndAuth", "{", "original", ":", "imgName", ",", "authConfig", ":", "&", "authConfig", ",", "reference", ":", "ref", ",", "repoInfo", ":", "repoInfo", ",", "tag", ":", "getTag", "(", "ref", ")", ",", "digest", ":", "getDigest", "(", "ref", ")", ",", "}", ",", "nil", "\n", "}" ]
// GetImageReferencesAndAuth retrieves the necessary reference and auth information for an image name // as an ImageRefAndAuth struct
[ "GetImageReferencesAndAuth", "retrieves", "the", "necessary", "reference", "and", "auth", "information", "for", "an", "image", "name", "as", "an", "ImageRefAndAuth", "struct" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/trust/trust.go#L305-L335
train
docker/cli
cli/command/swarm/opts.go
Set
func (a *NodeAddrOption) Set(value string) error { addr, err := opts.ParseTCPAddr(value, a.addr) if err != nil { return err } a.addr = addr return nil }
go
func (a *NodeAddrOption) Set(value string) error { addr, err := opts.ParseTCPAddr(value, a.addr) if err != nil { return err } a.addr = addr return nil }
[ "func", "(", "a", "*", "NodeAddrOption", ")", "Set", "(", "value", "string", ")", "error", "{", "addr", ",", "err", ":=", "opts", ".", "ParseTCPAddr", "(", "value", ",", "a", ".", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "a", ".", "addr", "=", "addr", "\n", "return", "nil", "\n", "}" ]
// Set the value for this flag
[ "Set", "the", "value", "for", "this", "flag" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/swarm/opts.go#L61-L68
train
docker/cli
cli/command/swarm/opts.go
String
func (m *ExternalCAOption) String() string { externalCAs := []string{} for _, externalCA := range m.values { repr := fmt.Sprintf("%s: %s", externalCA.Protocol, externalCA.URL) externalCAs = append(externalCAs, repr) } return strings.Join(externalCAs, ", ") }
go
func (m *ExternalCAOption) String() string { externalCAs := []string{} for _, externalCA := range m.values { repr := fmt.Sprintf("%s: %s", externalCA.Protocol, externalCA.URL) externalCAs = append(externalCAs, repr) } return strings.Join(externalCAs, ", ") }
[ "func", "(", "m", "*", "ExternalCAOption", ")", "String", "(", ")", "string", "{", "externalCAs", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "externalCA", ":=", "range", "m", ".", "values", "{", "repr", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "externalCA", ".", "Protocol", ",", "externalCA", ".", "URL", ")", "\n", "externalCAs", "=", "append", "(", "externalCAs", ",", "repr", ")", "\n", "}", "\n", "return", "strings", ".", "Join", "(", "externalCAs", ",", "\"", "\"", ")", "\n", "}" ]
// String returns a string repr of this option.
[ "String", "returns", "a", "string", "repr", "of", "this", "option", "." ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/swarm/opts.go#L112-L119
train
docker/cli
cli/command/swarm/opts.go
Set
func (p *PEMFile) Set(value string) error { contents, err := ioutil.ReadFile(value) if err != nil { return err } if pemBlock, _ := pem.Decode(contents); pemBlock == nil { return errors.New("file contents must be in PEM format") } p.contents, p.path = string(contents), value return nil }
go
func (p *PEMFile) Set(value string) error { contents, err := ioutil.ReadFile(value) if err != nil { return err } if pemBlock, _ := pem.Decode(contents); pemBlock == nil { return errors.New("file contents must be in PEM format") } p.contents, p.path = string(contents), value return nil }
[ "func", "(", "p", "*", "PEMFile", ")", "Set", "(", "value", "string", ")", "error", "{", "contents", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "value", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "pemBlock", ",", "_", ":=", "pem", ".", "Decode", "(", "contents", ")", ";", "pemBlock", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "p", ".", "contents", ",", "p", ".", "path", "=", "string", "(", "contents", ")", ",", "value", "\n", "return", "nil", "\n", "}" ]
// Set parses a root rotation option
[ "Set", "parses", "a", "root", "rotation", "option" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/swarm/opts.go#L142-L152
train
docker/cli
cli/command/manifest/annotate.go
newAnnotateCommand
func newAnnotateCommand(dockerCli command.Cli) *cobra.Command { var opts annotateOptions cmd := &cobra.Command{ Use: "annotate [OPTIONS] MANIFEST_LIST MANIFEST", Short: "Add additional information to a local image manifest", Args: cli.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { opts.target = args[0] opts.image = args[1] return runManifestAnnotate(dockerCli, opts) }, } flags := cmd.Flags() flags.StringVar(&opts.os, "os", "", "Set operating system") flags.StringVar(&opts.arch, "arch", "", "Set architecture") flags.StringSliceVar(&opts.osFeatures, "os-features", []string{}, "Set operating system feature") flags.StringVar(&opts.variant, "variant", "", "Set architecture variant") return cmd }
go
func newAnnotateCommand(dockerCli command.Cli) *cobra.Command { var opts annotateOptions cmd := &cobra.Command{ Use: "annotate [OPTIONS] MANIFEST_LIST MANIFEST", Short: "Add additional information to a local image manifest", Args: cli.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { opts.target = args[0] opts.image = args[1] return runManifestAnnotate(dockerCli, opts) }, } flags := cmd.Flags() flags.StringVar(&opts.os, "os", "", "Set operating system") flags.StringVar(&opts.arch, "arch", "", "Set architecture") flags.StringSliceVar(&opts.osFeatures, "os-features", []string{}, "Set operating system feature") flags.StringVar(&opts.variant, "variant", "", "Set architecture variant") return cmd }
[ "func", "newAnnotateCommand", "(", "dockerCli", "command", ".", "Cli", ")", "*", "cobra", ".", "Command", "{", "var", "opts", "annotateOptions", "\n\n", "cmd", ":=", "&", "cobra", ".", "Command", "{", "Use", ":", "\"", "\"", ",", "Short", ":", "\"", "\"", ",", "Args", ":", "cli", ".", "ExactArgs", "(", "2", ")", ",", "RunE", ":", "func", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "error", "{", "opts", ".", "target", "=", "args", "[", "0", "]", "\n", "opts", ".", "image", "=", "args", "[", "1", "]", "\n", "return", "runManifestAnnotate", "(", "dockerCli", ",", "opts", ")", "\n", "}", ",", "}", "\n\n", "flags", ":=", "cmd", ".", "Flags", "(", ")", "\n\n", "flags", ".", "StringVar", "(", "&", "opts", ".", "os", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "flags", ".", "StringVar", "(", "&", "opts", ".", "arch", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "flags", ".", "StringSliceVar", "(", "&", "opts", ".", "osFeatures", ",", "\"", "\"", ",", "[", "]", "string", "{", "}", ",", "\"", "\"", ")", "\n", "flags", ".", "StringVar", "(", "&", "opts", ".", "variant", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "return", "cmd", "\n", "}" ]
// NewAnnotateCommand creates a new `docker manifest annotate` command
[ "NewAnnotateCommand", "creates", "a", "new", "docker", "manifest", "annotate", "command" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/manifest/annotate.go#L24-L46
train