Skip to content
This repository has been archived by the owner on Dec 26, 2023. It is now read-only.

Validate if all layers dependencies exist #97

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion internal/layerfile/layerfile.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@ import (
"github.com/ergomake/layerform/pkg/data"
)

var ErrInvalidDefinitionName = errors.New("invalid layer definition name")
var (
ErrInvalidDefinitionName = errors.New("invalid layer definition name")
ErrDependencyDoesNotExist = errors.New("dependency does not exist")
)

var alphanumericRegex = regexp.MustCompile("^[A-Za-z0-9][A-Za-z0-9_-]*[A-Za-z0-9]$")

Expand Down Expand Up @@ -40,6 +43,10 @@ func FromFile(sourceFilepath string) (*layerfile, error) {
}

func (lf *layerfile) ToLayers() ([]*data.LayerDefinition, error) {
if err := lf.validateLayersDependencies(); err != nil {
return nil, errors.Wrap(err, "fail to validate layers dependencies")
}

dir := path.Dir(lf.sourceFilepath)

dataLayers := make([]*data.LayerDefinition, len(lf.Layers))
Expand Down Expand Up @@ -89,3 +96,21 @@ func (lf *layerfile) ToLayers() ([]*data.LayerDefinition, error) {

return dataLayers, nil
}

func (lf *layerfile) validateLayersDependencies() error {
names := make(map[string]struct{})

for _, l := range lf.Layers {
names[l.Name] = struct{}{}
}

for _, l := range lf.Layers {
for _, d := range l.Dependencies {
if _, ok := names[d]; !ok {
return errors.Wrap(ErrDependencyDoesNotExist, d)
}
}
}

return nil
}
68 changes: 68 additions & 0 deletions internal/layerfile/layerfile_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,3 +135,71 @@ func TestToLayers_ValidateNameOfLayerDefinitions(t *testing.T) {
})
}
}

func TestToLayers_ValidateAllDependenciesExist(t *testing.T) {
tests := []struct {
name string
lf layerfile
err error
}{
{
name: "Dependencies don't exist",
lf: layerfile{
Layers: []layerfileLayer{
{
Name: "foo",
Dependencies: []string{"bar", "baz"},
},
{
Name: "bar",
},
},
},
err: ErrDependencyDoesNotExist,
},
{
name: "Dependencies exist",
lf: layerfile{
Layers: []layerfileLayer{
{
Name: "foo",
Dependencies: []string{"bar"},
},
{
Name: "bar",
},
},
},
},
{
name: "Layers have no dependencies",
lf: layerfile{
Layers: []layerfileLayer{
{
Name: "foo",
},
{
Name: "bar",
},
},
},
},
{
name: "No layers",
lf: layerfile{
Layers: []layerfileLayer{},
},
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := tt.lf.ToLayers()
if tt.err == nil {
assert.NoError(t, err)
} else {
assert.ErrorIs(t, err, tt.err)
}
})
}
}