move code into small functions for better readability

Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
This commit is contained in:
Nicolas De Loof 2024-02-28 17:11:50 +01:00 committed by Nicolas De loof
parent 1680f9a874
commit de178267df

View File

@ -136,13 +136,39 @@ func configCommand(p *ProjectOptions, dockerCli command.Cli) *cobra.Command {
}
func runConfig(ctx context.Context, dockerCli command.Cli, opts configOptions, services []string) error {
var content []byte
model, err := opts.ToModel(ctx, dockerCli, services)
if err != nil {
return err
}
if opts.resolveImageDigests {
err = resolveImageDigests(ctx, dockerCli, model)
if err != nil {
return err
}
}
content, err := formatModel(model, opts.Format)
if err != nil {
return err
}
if !opts.noInterpolate {
content = escapeDollarSign(content)
}
if opts.quiet {
return nil
}
if opts.Output != "" && len(content) > 0 {
return os.WriteFile(opts.Output, content, 0o666)
}
_, err = fmt.Fprint(dockerCli.Out(), string(content))
return err
}
func resolveImageDigests(ctx context.Context, dockerCli command.Cli, model map[string]any) (err error) {
// create a pseudo-project so we can rely on WithImagesResolved to resolve images
p := &types.Project{
Services: types.Services{},
@ -162,6 +188,7 @@ func runConfig(ctx context.Context, dockerCli command.Cli, opts configOptions, s
return err
}
// Collect image resolved with digest and update model accordingly
for name, s := range services {
service := s.(map[string]any)
config := p.Services[name]
@ -171,9 +198,11 @@ func runConfig(ctx context.Context, dockerCli command.Cli, opts configOptions, s
services[name] = service
}
model["services"] = services
return nil
}
switch opts.Format {
func formatModel(model map[string]any, format string) (content []byte, err error) {
switch format {
case "json":
content, err = json.MarshalIndent(model, "", " ")
case "yaml":
@ -183,25 +212,9 @@ func runConfig(ctx context.Context, dockerCli command.Cli, opts configOptions, s
err = encoder.Encode(model)
content = buf.Bytes()
default:
return fmt.Errorf("unsupported format %q", opts.Format)
return nil, fmt.Errorf("unsupported format %q", format)
}
if err != nil {
return err
}
if !opts.noInterpolate {
content = escapeDollarSign(content)
}
if opts.quiet {
return nil
}
if opts.Output != "" && len(content) > 0 {
return os.WriteFile(opts.Output, content, 0o666)
}
_, err = fmt.Fprint(dockerCli.Out(), string(content))
return err
return
}
func runServices(ctx context.Context, dockerCli command.Cli, opts configOptions) error {