diff --git a/pkg/scaffold/scaffold.go b/pkg/scaffold/scaffold.go index a0b0bf978cb..6c8936d07f8 100644 --- a/pkg/scaffold/scaffold.go +++ b/pkg/scaffold/scaffold.go @@ -52,6 +52,8 @@ type Scaffold struct { ProjectPath string GetWriter func(path string) (io.Writer, error) + + FileExists func(path string) bool } func (s *Scaffold) setFieldsAndValidate(t input.File) error { @@ -141,6 +143,12 @@ func (s *Scaffold) Execute(options input.Options, files ...input.File) error { if s.GetWriter == nil { s.GetWriter = (&FileWriter{}).WriteCloser } + if s.FileExists == nil { + s.FileExists = func(path string) bool { + _, err := os.Stat(path) + return err == nil + } + } if err := s.defaultOptions(&options); err != nil { return err @@ -181,7 +189,7 @@ func (s *Scaffold) doFile(e input.File) error { } // Check if the file to write already exists - if _, err := os.Stat(i.Path); err == nil { + if s.FileExists(i.Path) { switch i.IfExistsAction { case input.Overwrite: case input.Skip: diff --git a/pkg/scaffold/scaffoldtest/scaffoldtest.go b/pkg/scaffold/scaffoldtest/scaffoldtest.go index 2d9319954e4..c3f6a0193e9 100644 --- a/pkg/scaffold/scaffoldtest/scaffoldtest.go +++ b/pkg/scaffold/scaffoldtest/scaffoldtest.go @@ -42,8 +42,7 @@ type TestResult struct { } func getProjectRoot() string { - gopath := os.Getenv("GOPATH") - return path.Join(gopath, "src", "sigs.k8s.io", "kubebuilder") + return path.Join(build.Default.GOPATH, "src", "sigs.k8s.io", "kubebuilder") } // ProjectPath is the path to the controller-tools/testdata project file @@ -66,6 +65,7 @@ func Options() input.Options { // NewTestScaffold returns a new Scaffold and TestResult instance for testing func NewTestScaffold(writeToPath, goldenPath string) (*scaffold.Scaffold, *TestResult) { + projRoot := getProjectRoot() r := &TestResult{} // Setup scaffold s := &scaffold.Scaffold{ @@ -74,12 +74,20 @@ func NewTestScaffold(writeToPath, goldenPath string) (*scaffold.Scaffold, *TestR gomega.Expect(path).To(gomega.Equal(writeToPath)) return &r.Actual, nil }, - ProjectPath: filepath.Join(getProjectRoot(), "testdata", "gopath", "src", "project"), + FileExists: func(path string) bool { + return path != writeToPath + }, + ProjectPath: filepath.Join(projRoot, "testdata", "gopath", "src", "project"), + } + oldGoPath := build.Default.GOPATH + build.Default.GOPATH = filepath.Join(projRoot, "testdata", "gopath") + defer func() { build.Default.GOPATH = oldGoPath }() + if _, err := os.Stat(build.Default.GOPATH); err != nil { + panic(err) } - build.Default.GOPATH = filepath.Join(getProjectRoot(), "testdata", "gopath") if len(goldenPath) > 0 { - b, err := ioutil.ReadFile(filepath.Join(getProjectRoot(), "testdata", "gopath", "src", "project", goldenPath)) + b, err := ioutil.ReadFile(filepath.Join(projRoot, "testdata", "gopath", "src", "project", goldenPath)) gomega.Expect(err).NotTo(gomega.HaveOccurred()) r.Golden = string(b) }