Skip to content

Commit d89eeaf

Browse files
shamilmjeffryes
andauthored
Fix: excluding files from unneededGoFiles was not working (#120)
## Bug files in `unneededGoFiles` were not excluded. ## Bug Description `unneededGoFiles` string set contain files which are relative to the import path (`kubernetes/*`), while the paths of generated files are relative to `pkg.Name` (`crds/*`). This PR makes sure to use a proper path when comparing files in `unneededGoFiles`. --------- Co-authored-by: Matthew (Matt) Jeffryes <github@mjeffryes.net>
1 parent 4855e54 commit d89eeaf

File tree

6 files changed

+94
-12
lines changed

6 files changed

+94
-12
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
## Unreleased
44

5+
- Fix: excluding files from unneededGoFiles was not working (<https://github.com/pulumi/crd2pulumi/pull/120>)
56
- Support kubernetes provider v4 (<https://github.com/pulumi/crd2pulumi/pull/119>)
67

78
## 1.2.5 (2023-05-31)

cmd/root.go

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ import (
1919
"errors"
2020
"fmt"
2121
"io"
22-
"io/ioutil"
2322
"os"
2423

2524
"github.com/pulumi/crd2pulumi/pkg/codegen"
@@ -29,7 +28,7 @@ import (
2928
// Version specifies the crd2pulumi version. It should be set by the linker via LDFLAGS. This defaults to dev
3029
var Version = "dev"
3130

32-
const long = `crd2pulumi is a CLI tool that generates typed Kubernetes
31+
const long = `crd2pulumi is a CLI tool that generates typed Kubernetes
3332
CustomResources to use in Pulumi programs, based on a
3433
CustomResourceDefinition YAML schema.`
3534

@@ -92,7 +91,7 @@ func Execute() error {
9291
}
9392
var err error
9493
if shouldUseStdin {
95-
err = codegen.Generate(cs, []io.ReadCloser{ioutil.NopCloser(bytes.NewBuffer(stdinData))})
94+
err = codegen.Generate(cs, []io.ReadCloser{io.NopCloser(bytes.NewBuffer(stdinData))})
9695
} else {
9796
err = codegen.GenerateFromFiles(cs, args)
9897
}

pkg/codegen/golang.go

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,14 +17,17 @@ package codegen
1717
import (
1818
"bytes"
1919
"fmt"
20+
"path"
2021
"path/filepath"
22+
"strings"
2123

2224
ijson "github.com/pulumi/crd2pulumi/internal/json"
2325
"github.com/pulumi/pulumi/pkg/v3/codegen"
2426
goGen "github.com/pulumi/pulumi/pkg/v3/codegen/go"
27+
"github.com/pulumi/pulumi/pkg/v3/codegen/schema"
2528
)
2629

27-
var unneededGoFiles = codegen.NewStringSet(
30+
var UnneededGoFiles = codegen.NewStringSet(
2831
// The root directory doesn't define any resources:
2932
"doc.go",
3033
"init.go",
@@ -69,21 +72,47 @@ func GenerateGo(pg *PackageGenerator, name string) (buffers map[string]*bytes.Bu
6972
pkg.Language[langName] = jsonData
7073

7174
files, err := goGen.GeneratePackage("crd2pulumi", pkg)
72-
7375
if err != nil {
7476
return nil, fmt.Errorf("could not generate Go package: %w", err)
7577
}
7678

79+
packageRoot, err := goPackageRoot(pkg.Reference())
80+
if err != nil {
81+
return nil, fmt.Errorf("could not get package root: %w", err)
82+
}
83+
7784
pkg.Name = oldName
7885
delete(pkg.Language, langName)
7986

8087
buffers = map[string]*bytes.Buffer{}
8188
for path, code := range files {
8289
newPath, _ := filepath.Rel(name, path)
83-
if !unneededGoFiles.Has(newPath) {
90+
pkgRelPath := strings.TrimPrefix(path, packageRoot+"/")
91+
92+
if !UnneededGoFiles.Has(pkgRelPath) {
8493
buffers[newPath] = bytes.NewBuffer(code)
8594
}
8695
}
8796

8897
return buffers, err
8998
}
99+
100+
// Similar to "packageRoot" method from pulumi/pkg/codegen/go/gen.go
101+
func goPackageRoot(pkg schema.PackageReference) (string, error) {
102+
def, err := pkg.Definition()
103+
if err != nil {
104+
return "", err
105+
}
106+
var info goGen.GoPackageInfo
107+
if goInfo, ok := def.Language["go"].(goGen.GoPackageInfo); ok {
108+
info = goInfo
109+
}
110+
if info.RootPackageName != "" {
111+
// package structure is flat
112+
return "", nil
113+
}
114+
if info.ImportBasePath != "" {
115+
return path.Base(info.ImportBasePath), nil
116+
}
117+
return strings.ReplaceAll(pkg.Name(), "-", ""), nil
118+
}

tests/crds_test.go

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ package tests
1717
import (
1818
"fmt"
1919
"io/fs"
20-
"io/ioutil"
2120
"os"
2221
"os/exec"
2322
"path/filepath"
@@ -32,7 +31,7 @@ const gkeManagedCertsUrl = "https://raw.githubusercontent.com/GoogleCloudPlatfor
3231

3332
// execCrd2Pulumi runs the crd2pulumi binary in a temporary directory
3433
func execCrd2Pulumi(t *testing.T, lang, path string, additionalValidation func(t *testing.T, path string)) {
35-
tmpdir, err := ioutil.TempDir("", "crd2pulumi_test")
34+
tmpdir, err := os.MkdirTemp("", "crd2pulumi_test")
3635
assert.Nil(t, err, "expected to create a temp dir for the CRD output")
3736
t.Cleanup(func() {
3837
t.Logf("removing temp dir %q for %s test", tmpdir, lang)
@@ -98,7 +97,7 @@ func TestCRDsWithUnderscore(t *testing.T) {
9897
// Ensure inputs are camelCased.
9998
filename := filepath.Join(path, "pulumi_crds", "juice", "v1alpha1", "_inputs.py")
10099
t.Logf("validating underscored field names in %s", filename)
101-
pythonInputs, err := ioutil.ReadFile(filename)
100+
pythonInputs, err := os.ReadFile(filename)
102101
if err != nil {
103102
t.Fatalf("expected to read generated Python code: %s", err)
104103
}
@@ -108,7 +107,7 @@ func TestCRDsWithUnderscore(t *testing.T) {
108107
// Ensure outputs are camelCased.
109108
filename = filepath.Join(path, "pulumi_crds", "juice", "v1alpha1", "outputs.py")
110109
t.Logf("validating underscored field names in %s", filename)
111-
pythonInputs, err = ioutil.ReadFile(filename)
110+
pythonInputs, err = os.ReadFile(filename)
112111
if err != nil {
113112
t.Fatalf("expected to read generated Python code: %s", err)
114113
}

tests/schema_test.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ import (
1818
"bytes"
1919
"encoding/json"
2020
"fmt"
21-
"io/ioutil"
2221
"os"
2322
"testing"
2423

@@ -51,7 +50,7 @@ func UnmarshalSchemas(yamlPath string) (map[string]any, error) {
5150
}
5251

5352
func UnmarshalTypeSpecJSON(jsonPath string) (map[string]pschema.TypeSpec, error) {
54-
jsonFile, err := ioutil.ReadFile(jsonPath)
53+
jsonFile, err := os.ReadFile(jsonPath)
5554
if err != nil {
5655
return nil, fmt.Errorf("could not read file %s: %w", jsonPath, err)
5756
}

tests/unneeded_go_files_test.go

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package tests
2+
3+
import (
4+
"io"
5+
"strings"
6+
"testing"
7+
8+
"github.com/pulumi/crd2pulumi/pkg/codegen"
9+
)
10+
11+
func TestUnneededGoFiles(t *testing.T) {
12+
mockCRDYaml := `---
13+
apiVersion: apiextensions.k8s.io/v1
14+
kind: CustomResourceDefinition
15+
spec:
16+
group: uneeded-go-files-test.pulumi.com
17+
names:
18+
plural: testresources
19+
singular: testresource
20+
kind: TestResource
21+
scope: Namespaced
22+
versions:
23+
- test:
24+
name: test
25+
schema:
26+
openAPIV3Schema:
27+
properties:
28+
testProperty:
29+
type: string`
30+
31+
yamlSources := []io.ReadCloser{
32+
io.NopCloser(strings.NewReader(mockCRDYaml)),
33+
}
34+
35+
// Invoke ReadPackagesFromSource
36+
pg, err := codegen.ReadPackagesFromSource("", yamlSources)
37+
if err != nil {
38+
t.Fatalf("ReadPackagesFromSource failed: %v", err)
39+
}
40+
41+
// Pick a generated file we want to exclude
42+
uneededGoFile := "uneededgofilestest/test/testResource.go"
43+
codegen.UnneededGoFiles.Add(uneededGoFile)
44+
45+
// Generate the code from the mocked CRD
46+
buffers, err := codegen.GenerateGo(pg, "crds")
47+
if err != nil {
48+
t.Fatalf("GenerateGo failed: %v", err)
49+
}
50+
51+
// Assert that buffers do not contain unneeded file
52+
if _, exists := buffers["../kubernetes/"+uneededGoFile]; exists {
53+
t.Errorf("Uneeded GO file was not excluded by GoGenerate, %s", uneededGoFile)
54+
}
55+
}

0 commit comments

Comments
 (0)