Skip to content
This repository was archived by the owner on Jul 18, 2025. It is now read-only.

Commit 225b55e

Browse files
surajssdvdemeester
authored andcommitted
Validate compose v2 input
Compose v1 has input validation but in the composev2 merge function validation was missing so added it. Fixes #357 Signed-off-by: Suraj Deshmukh <[email protected]> Signed-off-by: Vincent Demeester <[email protected]>
1 parent d37dc41 commit 225b55e

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

config/merge_v2.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package config
33
import (
44
"fmt"
55
"path"
6+
"strings"
67

78
"github.com/Sirupsen/logrus"
89
"github.com/docker/libcompose/utils"
@@ -49,6 +50,19 @@ func MergeServicesV2(existingServices *ServiceConfigs, environmentLookup Environ
4950
datas[name] = data
5051
}
5152

53+
if options.Validate {
54+
var errs []string
55+
for name, data := range datas {
56+
err := validateServiceConstraintsv2(data, name)
57+
if err != nil {
58+
errs = append(errs, err.Error())
59+
}
60+
}
61+
if len(errs) != 0 {
62+
return nil, fmt.Errorf(strings.Join(errs, "\n"))
63+
}
64+
}
65+
5266
serviceConfigs := make(map[string]*ServiceConfig)
5367
if err := utils.Convert(datas, &serviceConfigs); err != nil {
5468
return nil, err

config/validation.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -287,3 +287,36 @@ func validateServiceConstraints(service RawService, serviceName string) error {
287287

288288
return nil
289289
}
290+
291+
func validateServiceConstraintsv2(service RawService, serviceName string) error {
292+
if err := setupSchemaLoaders(servicesSchemaDataV2, &schemaV2, &schemaLoaderV2, &constraintSchemaLoaderV2); err != nil {
293+
return err
294+
}
295+
296+
service = convertServiceKeysToStrings(service)
297+
298+
var validationErrors []string
299+
300+
dataLoader := gojsonschema.NewGoLoader(service)
301+
302+
result, err := gojsonschema.Validate(constraintSchemaLoaderV2, dataLoader)
303+
if err != nil {
304+
return err
305+
}
306+
307+
if !result.Valid() {
308+
for _, err := range result.Errors() {
309+
if err.Type() == "required" {
310+
_, containsImage := service["image"]
311+
_, containsBuild := service["build"]
312+
313+
if containsBuild || !containsImage && !containsBuild {
314+
validationErrors = append(validationErrors, fmt.Sprintf("Service '%s' has neither an image nor a build context specified. At least one must be provided.", serviceName))
315+
}
316+
}
317+
}
318+
return fmt.Errorf(strings.Join(validationErrors, "\n"))
319+
}
320+
321+
return nil
322+
}

0 commit comments

Comments
 (0)