diff --git a/pkg/api/api.go b/pkg/api/api.go index 03cc5cda7..f08a7f684 100644 --- a/pkg/api/api.go +++ b/pkg/api/api.go @@ -350,7 +350,7 @@ type CreateOptions struct { IgnoreOrphans bool // Recreate define the strategy to apply on existing containers: one of // RecreateDiverged (the default, also used for ""), RecreateForce or - // RecreateNever. + // RecreateNever. Any other value is rejected by Validate. Recreate string // RecreateDependencies define the strategy to apply on dependencies // services, with the same values as Recreate. diff --git a/pkg/api/create_options.go b/pkg/api/create_options.go new file mode 100644 index 000000000..a300eb5b8 --- /dev/null +++ b/pkg/api/create_options.go @@ -0,0 +1,80 @@ +/* + Copyright 2020 Docker Compose CLI authors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package api + +import ( + "errors" + "fmt" + "slices" + "strings" +) + +// InvalidOptionError reports an option set to a value it does not accept. It is +// returned, before any side effect, by CreateOptions.Validate and therefore by +// Compose.Create and Compose.Up. +// +// It matches ErrInvalidOption with errors.Is, and callers needing the details +// can retrieve it with errors.As. +type InvalidOptionError struct { + // Option names the option field, as a Go selector relative to the options + // type that was validated (e.g. "Recreate"). + Option string + // Value is the value that was set. + Value string + // Allowed lists the values the option accepts. + Allowed []string +} + +func (e *InvalidOptionError) Error() string { + return fmt.Sprintf("%s (%s): %q is not one of %s", ErrInvalidOption, e.Option, e.Value, strings.Join(e.Allowed, ", ")) +} + +// Unwrap makes errors.Is(err, ErrInvalidOption) hold. +func (e *InvalidOptionError) Unwrap() error { + return ErrInvalidOption +} + +// Validate checks that the values of the options are among the ones they +// accept: Recreate and RecreateDependencies must be empty (which means +// RecreateDiverged) or one of the Recreate* constants. It is a pure function, +// called by Create and Up before they do anything, and can also be called by +// integrators to fail early. +// +// It returns nil, or an error matching ErrInvalidOption. With several invalid +// options, the errors are joined with errors.Join: errors.Is still holds, but +// errors.As to *InvalidOptionError only yields the first one. +func (o CreateOptions) Validate() error { + var errs []error + errs = append(errs, validateRecreatePolicy("Recreate", o.Recreate)...) + errs = append(errs, validateRecreatePolicy("RecreateDependencies", o.RecreateDependencies)...) + switch len(errs) { + case 0: + return nil + case 1: + return errs[0] + default: + return errors.Join(errs...) + } +} + +func validateRecreatePolicy(option, policy string) []error { + allowed := []string{RecreateDiverged, RecreateForce, RecreateNever} + if policy == "" || slices.Contains(allowed, policy) { + return nil + } + return []error{&InvalidOptionError{Option: option, Value: policy, Allowed: allowed}} +} diff --git a/pkg/api/create_options_test.go b/pkg/api/create_options_test.go new file mode 100644 index 000000000..4346b3e94 --- /dev/null +++ b/pkg/api/create_options_test.go @@ -0,0 +1,87 @@ +/* + Copyright 2020 Docker Compose CLI authors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package api + +import ( + "errors" + "testing" + + "gotest.tools/v3/assert" +) + +func TestCreateOptionsValidate(t *testing.T) { + tests := []struct { + name string + options CreateOptions + // invalid lists the options expected to be rejected, empty when valid + invalid []string + }{ + {name: "zero value is valid", options: CreateOptions{}}, + {name: "diverged", options: CreateOptions{Recreate: RecreateDiverged, RecreateDependencies: RecreateDiverged}}, + {name: "force", options: CreateOptions{Recreate: RecreateForce, RecreateDependencies: RecreateForce}}, + {name: "never", options: CreateOptions{Recreate: RecreateNever, RecreateDependencies: RecreateNever}}, + {name: "unknown recreate", options: CreateOptions{Recreate: "forced"}, invalid: []string{"Recreate"}}, + {name: "unknown dependencies recreate", options: CreateOptions{RecreateDependencies: "always"}, invalid: []string{"RecreateDependencies"}}, + {name: "case matters", options: CreateOptions{Recreate: "Force"}, invalid: []string{"Recreate"}}, + {name: "both unknown", options: CreateOptions{Recreate: "x", RecreateDependencies: "y"}, invalid: []string{"Recreate", "RecreateDependencies"}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := tt.options.Validate() + if len(tt.invalid) == 0 { + assert.NilError(t, err) + return + } + assert.Assert(t, errors.Is(err, ErrInvalidOption), "got %v", err) + assert.Assert(t, IsErrInvalidOption(err)) + + // every invalid option is reported, whether the error is a single + // *InvalidOptionError or several of them joined + var reported []string + var walk func(error) + walk = func(e error) { + if joined, ok := e.(interface{ Unwrap() []error }); ok { + for _, inner := range joined.Unwrap() { + walk(inner) + } + return + } + var invalid *InvalidOptionError + if errors.As(e, &invalid) { + reported = append(reported, invalid.Option) + } + } + walk(err) + assert.DeepEqual(t, reported, tt.invalid) + }) + } +} + +func TestInvalidOptionErrorMessage(t *testing.T) { + err := CreateOptions{Recreate: "forced"}.Validate() + assert.Error(t, err, `invalid option (Recreate): "forced" is not one of diverged, force, never`) +} + +func TestUpOptionsValidateReportsInvalidCreateOptions(t *testing.T) { + err := UpOptions{Create: CreateOptions{Recreate: "forced"}}.Validate() + assert.Assert(t, errors.Is(err, ErrInvalidOption), "got %v", err) + + // invalid values and incompatible combinations are reported together + err = UpOptions{Create: CreateOptions{Recreate: "forced"}, Start: StartOptions{Wait: true, Attach: nopConsumer{}}}.Validate() + assert.Assert(t, errors.Is(err, ErrInvalidOption), "got %v", err) + assert.Assert(t, errors.Is(err, ErrIncompatibleOptions), "got %v", err) +} diff --git a/pkg/api/doc.go b/pkg/api/doc.go index 65f3ae04a..df02a8f79 100644 --- a/pkg/api/doc.go +++ b/pkg/api/doc.go @@ -30,8 +30,8 @@ // flag also forces the recreation of every container). The CLI default // is to retrieve their data from the previous container (Inherit: true). // - [CreateOptions].Recreate and RecreateDependencies: the empty string -// means [RecreateDiverged], and so does any value that is not one of the -// Recreate* constants. +// means [RecreateDiverged]. Any value other than the Recreate* constants +// is rejected by [CreateOptions.Validate] before anything is changed. // - [CreateOptions].RemoveOrphans and IgnoreOrphans: when both are false, // orphan containers are kept and a warning is logged. IgnoreOrphans // silences that warning, RemoveOrphans removes the containers. diff --git a/pkg/api/errors.go b/pkg/api/errors.go index 933cab45a..d75de13bf 100644 --- a/pkg/api/errors.go +++ b/pkg/api/errors.go @@ -48,6 +48,9 @@ var ( // ErrIncompatibleOptions is returned when a set of options that cannot be // honored together is requested. See IncompatibleOptionsError. ErrIncompatibleOptions = errors.New("incompatible options") + // ErrInvalidOption is returned when an option is set to a value it does + // not accept. See InvalidOptionError. + ErrInvalidOption = errors.New("invalid option") ) // IsNotFoundError returns true if the unwrapped error is ErrNotFound @@ -94,3 +97,8 @@ func IsErrCanceled(err error) bool { func IsErrIncompatibleOptions(err error) bool { return errors.Is(err, ErrIncompatibleOptions) } + +// IsErrInvalidOption returns true if the unwrapped error is ErrInvalidOption +func IsErrInvalidOption(err error) bool { + return errors.Is(err, ErrInvalidOption) +} diff --git a/pkg/api/up_options.go b/pkg/api/up_options.go index cf9dfffd3..58f8ccc71 100644 --- a/pkg/api/up_options.go +++ b/pkg/api/up_options.go @@ -58,7 +58,8 @@ func incompatible(reason string, options ...string) error { // Validate checks that the options requested for Up can be honored together. // It is a pure function, called by Up before it does anything, and can also be // called by integrators to fail early. It returns nil, or an error matching -// ErrIncompatibleOptions describing every conflict found. +// ErrIncompatibleOptions describing every conflict found, or ErrInvalidOption +// when Create holds a value that CreateOptions.Validate rejects. // // Up has two modes, selected by Start.Attach: detached (nil) returns once the // containers are started, interactive (set) keeps running a foreground session. @@ -78,6 +79,9 @@ func incompatible(reason string, options ...string) error { // flags; Validate is the safety net for programs using the library directly. func (o UpOptions) Validate() error { var errs []error + if err := o.Create.Validate(); err != nil { + errs = append(errs, err) + } errs = append(errs, validateWaitIsDetached(o.Start)...) errs = append(errs, validateDetachedHasNoSession(o.Start)...) switch len(errs) { diff --git a/pkg/compose/create.go b/pkg/compose/create.go index 548f5152c..45dce35e8 100644 --- a/pkg/compose/create.go +++ b/pkg/compose/create.go @@ -68,6 +68,9 @@ type createConfigs struct { } func (s *composeService) Create(ctx context.Context, project *types.Project, options api.CreateOptions) error { + if err := options.Validate(); err != nil { + return err + } return Run(ctx, func(ctx context.Context) error { return s.create(ctx, project, options) }, "create", s.events) diff --git a/pkg/compose/create_validate_test.go b/pkg/compose/create_validate_test.go new file mode 100644 index 000000000..9cf03d84f --- /dev/null +++ b/pkg/compose/create_validate_test.go @@ -0,0 +1,42 @@ +/* + Copyright 2020 Docker Compose CLI authors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package compose + +import ( + "errors" + "testing" + + "github.com/compose-spec/compose-go/v2/types" + "gotest.tools/v3/assert" + + "github.com/docker/compose/v5/internal/progress" + "github.com/docker/compose/v5/pkg/api" +) + +// An unknown recreate policy must be rejected before the engine is reached: the +// service has no client, so any attempt to go further would panic. +func TestCreateAndUpRejectInvalidOptions(t *testing.T) { + s := &composeService{events: progress.Noop{}} + project := &types.Project{Name: "test"} + invalid := api.CreateOptions{Recreate: "forced"} + + err := s.Create(t.Context(), project, invalid) + assert.Assert(t, errors.Is(err, api.ErrInvalidOption), "got %v", err) + + err = s.Up(t.Context(), project, api.UpOptions{Create: invalid}) + assert.Assert(t, errors.Is(err, api.ErrInvalidOption), "got %v", err) +}