From fe91c34979216f662df2cb536f0b1001229dd812 Mon Sep 17 00:00:00 2001 From: Gabriele Ghibaudo Date: Sat, 26 Oct 2024 15:50:21 +0200 Subject: [PATCH] Add start_with that rule --- internal/arch/file/that/start_with.go | 44 +++++++++++++++ internal/arch/file/that/start_with_test.go | 64 ++++++++++++++++++++++ 2 files changed, 108 insertions(+) create mode 100644 internal/arch/file/that/start_with.go create mode 100644 internal/arch/file/that/start_with_test.go diff --git a/internal/arch/file/that/start_with.go b/internal/arch/file/that/start_with.go new file mode 100644 index 0000000..c13f662 --- /dev/null +++ b/internal/arch/file/that/start_with.go @@ -0,0 +1,44 @@ +package that + +import ( + "path/filepath" + "strings" + + "github.com/omissis/goarkitect/internal/arch/file" + "github.com/omissis/goarkitect/internal/arch/rule" +) + +func StartWith(s string) *StartWithExpression { + return &StartWithExpression{ + prefix: s, + } +} + +type StartWithExpression struct { + prefix string + + errors []error +} + +func (e *StartWithExpression) GetErrors() []error { + return e.errors +} + +func (e *StartWithExpression) Evaluate(rb rule.Builder) { + frb, ok := rb.(*file.RuleBuilder) + if !ok { + e.errors = append(e.errors, file.ErrInvalidRuleBuilder) + + return + } + + files := make([]string, 0) + + for _, f := range frb.GetFiles() { + if strings.HasPrefix(filepath.Base(f), e.prefix) { + files = append(files, f) + } + } + + frb.SetFiles(files) +} diff --git a/internal/arch/file/that/start_with_test.go b/internal/arch/file/that/start_with_test.go new file mode 100644 index 0000000..73d06b7 --- /dev/null +++ b/internal/arch/file/that/start_with_test.go @@ -0,0 +1,64 @@ +package that_test + +import ( + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + + "github.com/omissis/goarkitect/internal/arch/file" + "github.com/omissis/goarkitect/internal/arch/file/that" + "github.com/omissis/goarkitect/internal/arch/rule" +) + +func Test_StartWith(t *testing.T) { + t.Parallel() + + rb := func() *file.RuleBuilder { + rb := file.All() + rb.SetFiles([]string{"Dockerfile", "Makefile", "foo/bar.go"}) + + return rb + } + + testCases := []struct { + desc string + ruleBuilder *file.RuleBuilder + prefix string + want []string + }{ + { + desc: "files starting with 'foo'", + ruleBuilder: rb(), + prefix: "foo", + want: nil, + }, + { + desc: "files starting with 'Make'", + ruleBuilder: rb(), + prefix: "Make", + want: []string{"Makefile"}, + }, + { + desc: "files in a subdirectory starting with 'bar", + ruleBuilder: rb(), + prefix: "bar", + want: []string{"foo/bar.go"}, + }, + } + for _, tC := range testCases { + tC := tC + + t.Run(tC.desc, func(t *testing.T) { + t.Parallel() + + ew := that.StartWith(tC.prefix) + ew.Evaluate(tC.ruleBuilder) + + got := tC.ruleBuilder.GetFiles() + if !cmp.Equal(got, tC.want, cmp.AllowUnexported(rule.Violation{}), cmpopts.EquateEmpty()) { + t.Errorf("want = %+v, got = %+v", tC.want, got) + } + }) + } +}