Skip to content

Commit

Permalink
Adds enviroment structure to allow for thread safe unit testing
Browse files Browse the repository at this point in the history
  • Loading branch information
ForestEckhardt committed Sep 10, 2024
1 parent 143ecb1 commit 1abf6aa
Show file tree
Hide file tree
Showing 8 changed files with 65 additions and 49 deletions.
9 changes: 3 additions & 6 deletions detect.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,13 @@
package gogenerate

import (
"os"

"github.com/paketo-buildpacks/packit/v2"
)

func Detect() packit.DetectFunc {
func Detect(generateEnvironement GenerateEnvironment) packit.DetectFunc {
return func(context packit.DetectContext) (packit.DetectResult, error) {
run := os.Getenv("BP_GO_GENERATE")
if run != "true" {
return packit.DetectResult{}, packit.Fail.WithMessage("BP_GO_GENERATE is empty")
if !generateEnvironement.RunGoGenerate {
return packit.DetectResult{}, packit.Fail.WithMessage("BP_GO_GENERATE is not truthy")
}

return packit.DetectResult{}, nil
Expand Down
12 changes: 7 additions & 5 deletions detect_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@ func testDetect(t *testing.T, context spec.G, it spec.S) {
workingDir, err = os.MkdirTemp("", "working-dir")
Expect(err).NotTo(HaveOccurred())

os.Setenv("BP_GO_GENERATE", "true")

detect = gogenerate.Detect()
detect = gogenerate.Detect(gogenerate.GenerateEnvironment{
RunGoGenerate: true,
})
})

it.After(func() {
Expand All @@ -43,14 +43,16 @@ func testDetect(t *testing.T, context spec.G, it spec.S) {

context("when BP_GO_GENERATE is empty", func() {
it.Before(func() {
os.Unsetenv("BP_GO_GENERATE")
detect = gogenerate.Detect(gogenerate.GenerateEnvironment{
RunGoGenerate: false,
})
})

it("fails detection", func() {
_, err := detect(packit.DetectContext{
WorkingDir: workingDir,
})
Expect(err).To(MatchError(packit.Fail.WithMessage("BP_GO_GENERATE is empty")))
Expect(err).To(MatchError(packit.Fail.WithMessage("BP_GO_GENERATE is not truthy")))
})
})
}
7 changes: 7 additions & 0 deletions environment.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package gogenerate

type GenerateEnvironment struct {
RunGoGenerate bool `env:BP_GO_GENERATE`

Check failure on line 4 in environment.go

View workflow job for this annotation

GitHub Actions / lint

structtag: struct field tag `env:BP_GO_GENERATE` not compatible with reflect.StructTag.Get: bad syntax for struct tag value (govet)
GoGenerateArgs string `env:BP_GO_GENERATE_ARGS`

Check failure on line 5 in environment.go

View workflow job for this annotation

GitHub Actions / lint

structtag: struct field tag `env:BP_GO_GENERATE_ARGS` not compatible with reflect.StructTag.Get: bad syntax for struct tag value (govet)
GoGenerateFlags string `env:BP_GO_GENERATE_FLAGS`

Check failure on line 6 in environment.go

View workflow job for this annotation

GitHub Actions / lint

structtag: struct field tag `env:BP_GO_GENERATE_FLAGS` not compatible with reflect.StructTag.Get: bad syntax for struct tag value (govet)
}
25 changes: 16 additions & 9 deletions generate_configuration_parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package gogenerate

import (
"fmt"
"os"

"github.com/mattn/go-shellwords"
)
Expand All @@ -13,10 +12,18 @@ type GenerateConfiguration struct {
}

type GenerateConfigurationParser struct {
generateEnvironment GenerateEnvironment
}

func NewGenerateConfigurationParser() GenerateConfigurationParser {
return GenerateConfigurationParser{}
func NewGenerateConfigurationParser(generateEnvironment GenerateEnvironment) GenerateConfigurationParser {
return GenerateConfigurationParser{
generateEnvironment: generateEnvironment,
}
}

func (p GenerateConfigurationParser) WithEnvironment(generateEnvironment GenerateEnvironment) GenerateConfigurationParser {
p.generateEnvironment = generateEnvironment
return p
}

func (p GenerateConfigurationParser) Parse() (GenerateConfiguration, error) {
Expand All @@ -30,19 +37,19 @@ func (p GenerateConfigurationParser) Parse() (GenerateConfiguration, error) {
shellwordsParser.ParseEnv = true

generateConfiguration.Args = []string{"./..."}
if val, ok := os.LookupEnv("BP_GO_GENERATE_ARGS"); ok {
generateConfiguration.Args, err = shellwordsParser.Parse(val)
if p.generateEnvironment.GoGenerateArgs != "" {
generateConfiguration.Args, err = shellwordsParser.Parse(p.generateEnvironment.GoGenerateArgs)

if err != nil {
return GenerateConfiguration{}, fmt.Errorf("BP_GO_GENERATE_ARGS=%q: %w", val, err)
return GenerateConfiguration{}, fmt.Errorf("BP_GO_GENERATE_ARGS=%q: %w", p.generateEnvironment.GoGenerateArgs, err)
}
}

if val, ok := os.LookupEnv("BP_GO_GENERATE_FLAGS"); ok {
generateConfiguration.Flags, err = shellwordsParser.Parse(val)
if p.generateEnvironment.GoGenerateFlags != "" {
generateConfiguration.Flags, err = shellwordsParser.Parse(p.generateEnvironment.GoGenerateFlags)

if err != nil {
return GenerateConfiguration{}, fmt.Errorf("BP_GO_GENERATE_FLAGS=%q: %w", val, err)
return GenerateConfiguration{}, fmt.Errorf("BP_GO_GENERATE_FLAGS=%q: %w", p.generateEnvironment.GoGenerateFlags, err)
}
}
return generateConfiguration, nil
Expand Down
45 changes: 18 additions & 27 deletions generate_configuration_parser_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package gogenerate_test

import (
"os"
"testing"

gogenerate "github.com/paketo-buildpacks/go-generate"
Expand All @@ -18,16 +17,14 @@ func testGenerateConfigurationParser(t *testing.T, context spec.G, it spec.S) {
)

it.Before(func() {
parser = gogenerate.NewGenerateConfigurationParser()
parser = gogenerate.NewGenerateConfigurationParser(gogenerate.GenerateEnvironment{})
})

context("BP_GO_GENERATE_ARGS is set", func() {
it.Before(func() {
os.Setenv("BP_GO_GENERATE_ARGS", "somemodule othermodule")
})

it.After(func() {
os.Unsetenv("BP_GO_GENERATE_ARGS")
parser = parser.WithEnvironment(gogenerate.GenerateEnvironment{
GoGenerateArgs: "somemodule othermodule",
})
})

it("uses the values in the env var", func() {
Expand All @@ -37,7 +34,7 @@ func testGenerateConfigurationParser(t *testing.T, context spec.G, it spec.S) {
Args: []string{"somemodule", "othermodule"},
}))
})
}, spec.Sequential())
})

context("BP_GO_GENERATE_ARGS is NOT set", func() {
it("uses the default value", func() {
Expand All @@ -47,15 +44,13 @@ func testGenerateConfigurationParser(t *testing.T, context spec.G, it spec.S) {
Args: []string{"./..."},
}))
})
}, spec.Sequential())
})

context("BP_GO_GENERATE_FLAGS is set", func() {
it.Before(func() {
os.Setenv("BP_GO_GENERATE_FLAGS", `-run="^//go:generate go get" -n`)
})

it.After(func() {
os.Unsetenv("BP_GO_GENERATE_FLAGS")
parser = parser.WithEnvironment(gogenerate.GenerateEnvironment{
GoGenerateFlags: `-run="^//go:generate go get" -n`,
})
})

it("uses the values in the env var", func() {
Expand All @@ -66,38 +61,34 @@ func testGenerateConfigurationParser(t *testing.T, context spec.G, it spec.S) {
Flags: []string{`-run=^//go:generate go get`, "-n"},
}))
})
}, spec.Sequential())
})

context("failure cases", func() {

context("generate args fail to parse", func() {
it.Before(func() {
os.Setenv("BP_GO_GENERATE_ARGS", "\"")
parser = parser.WithEnvironment(gogenerate.GenerateEnvironment{
GoGenerateArgs: "\"",
})
})

it("returns an error", func() {
_, err := parser.Parse()
Expect(err).To(MatchError(ContainSubstring(`BP_GO_GENERATE_ARGS="\"": invalid command line string`)))
})

it.After(func() {
os.Unsetenv("BP_GO_GENERATE_ARGS")
})
}, spec.Sequential())
})

context("generate flags fail to parse", func() {
it.Before(func() {
os.Setenv("BP_GO_GENERATE_FLAGS", "\"")
parser = parser.WithEnvironment(gogenerate.GenerateEnvironment{
GoGenerateFlags: "\"",
})
})

it("returns an error", func() {
_, err := parser.Parse()
Expect(err).To(MatchError(ContainSubstring(`BP_GO_GENERATE_FLAGS="\"": invalid command line string`)))
})

it.After(func() {
os.Unsetenv("BP_GO_GENERATE_ARGS")
})
}, spec.Sequential())
})
})
}
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ require (
github.com/ForestEckhardt/freezer v0.1.0 // indirect
github.com/Masterminds/semver/v3 v3.2.1 // indirect
github.com/Microsoft/go-winio v0.6.2 // indirect
github.com/caarlos0/env/v6 v6.10.1 // indirect
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
github.com/containerd/log v0.1.0 // indirect
github.com/containerd/platforms v0.2.1 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -1021,6 +1021,8 @@ github.com/butuzov/ireturn v0.1.1/go.mod h1:Wh6Zl3IMtTpaIKbmwzqi6olnM9ptYQxxVacM
github.com/bwesterb/go-ristretto v1.2.0/go.mod h1:fUIoIZaG73pV5biE2Blr2xEzDoMj7NFEuV9ekS419A0=
github.com/bytecodealliance/wasmtime-go v0.36.0/go.mod h1:q320gUxqyI8yB+ZqRuaJOEnGkAnHh6WtJjMaT2CW4wI=
github.com/caarlos0/ctrlc v1.0.0/go.mod h1:CdXpj4rmq0q/1Eb44M9zi2nKB0QraNKuRGYGrrHhcQw=
github.com/caarlos0/env/v6 v6.10.1 h1:t1mPSxNpei6M5yAeu1qtRdPAK29Nbcf/n3G7x+b3/II=
github.com/caarlos0/env/v6 v6.10.1/go.mod h1:hvp/ryKXKipEkcuYjs9mI4bBCg+UI0Yhgm5Zu0ddvwc=
github.com/campoy/unique v0.0.0-20180121183637-88950e537e7e/go.mod h1:9IOqJGCPMSc6E5ydlp5NIonxObaeu/Iub/X03EKPVYo=
github.com/carolynvs/magex v0.9.0/go.mod h1:H1LW6RYJ/sNbisMmPe9E73aJZa8geKLKK9mBWLWz3ek=
github.com/casbin/casbin/v2 v2.1.2/go.mod h1:YcPU1XXisHhLzuxH9coDNf2FbKpjGlbCg3n9yuLkIJQ=
Expand Down
13 changes: 11 additions & 2 deletions run/main.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package main

import (
"fmt"
"os"

"github.com/caarlos0/env/v6"
gogenerate "github.com/paketo-buildpacks/go-generate"
"github.com/paketo-buildpacks/packit/v2"
"github.com/paketo-buildpacks/packit/v2/chronos"
Expand All @@ -13,10 +15,17 @@ import (
func main() {
logger := scribe.NewLogger(os.Stdout)

var generateEnvironment gogenerate.GenerateEnvironment
err := env.Parse(&generateEnvironment)
if err != nil {
fmt.Fprintln(os.Stderr, fmt.Errorf("failed to parse build configuration: %w", err))
os.Exit(1)
}

packit.Run(
gogenerate.Detect(),
gogenerate.Detect(generateEnvironment),
gogenerate.Build(
gogenerate.NewGenerateConfigurationParser(),
gogenerate.NewGenerateConfigurationParser(generateEnvironment),
gogenerate.NewGenerate(
pexec.NewExecutable("go"),
logger,
Expand Down

0 comments on commit 1abf6aa

Please sign in to comment.