Skip to content

Commit 658a979

Browse files
committed
Merge branch 'master' into ginko-testing
2 parents be6d34f + ccf727e commit 658a979

File tree

10 files changed

+152
-114
lines changed

10 files changed

+152
-114
lines changed

cmd/helm2go-operator-sdk/new/chart.go

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,9 @@ type HelmChartClient struct {
3838

3939
//NewChartClient creates a new chart client
4040
func NewChartClient() *HelmChartClient {
41-
return &HelmChartClient{}
41+
client := HelmChartClient{}
42+
client.PathConfig, _ = GetBasePathConfig()
43+
return &client
4244
}
4345

4446
// SetValues ingests alle the necessary values for the client
@@ -53,7 +55,7 @@ func (hc *HelmChartClient) SetValues(helmChartRef, helmChartVersion, helmChartRe
5355
hc.HelmChartKeyFile = helmChartKeyFile
5456
}
5557

56-
//LoadChart ...
58+
//LoadChart uses the chart client's values to retreive the appropriate chart
5759
func (hc *HelmChartClient) LoadChart() error {
5860
var chartPath string
5961
chartPath = hc.HelmChartRef
@@ -112,9 +114,9 @@ func (hc *HelmChartClient) DoHelmGoConversion() (*resourcecache.ResourceCache, e
112114
return nil, fmt.Errorf("error injecting template values: %v", err)
113115
}
114116
// write the rendered charts to output directory
115-
d := hc.PathConfig.GetBasePath()
116-
fmt.Printf("PATH CONFIG BASE: %s\n", d)
117-
temp, err := render.InjectedToTemp(f, d)
117+
basePath := hc.PathConfig.GetBasePath()
118+
119+
temp, err := render.InjectedToTemp(f, basePath)
118120
if err != nil {
119121
return nil, fmt.Errorf("error writing template values to temp files: %v", err)
120122
}
@@ -140,16 +142,21 @@ func (hc *HelmChartClient) DoHelmGoConversion() (*resourcecache.ResourceCache, e
140142

141143
func scaffoldOverwrite(outputDir, kind, apiVersion string, rcache *resourcecache.ResourceCache) error {
142144

143-
ok := templating.OverwriteController(outputDir, kind, apiVersion, rcache)
145+
if err := templating.OverwriteController(outputDir, kind, apiVersion, rcache); err != nil {
146+
return fmt.Errorf("error while overwriting controller: %v", err)
147+
}
144148
// create templates for writing to file
145149
templates := templating.CacheTemplating(rcache, outputDir, kind, apiVersion)
146150
// templates to files; outputDir is the parent directory where the operator scaffolding lives
147151
resDir := filepath.Join(outputDir, "pkg", "resources")
152+
148153
// create the necessary package resource specific folders
149-
ok = templating.ResourceFileStructure(rcache, resDir)
150-
ok = templating.TemplatesToFiles(templates, resDir)
151-
if !ok {
152-
return fmt.Errorf("Writing to File Error")
154+
if err := templating.ResourceFileStructure(rcache, resDir); err != nil {
155+
return fmt.Errorf("error creating resource file structure: %v", err)
153156
}
157+
if err := templating.TemplatesToFiles(templates, resDir); err != nil {
158+
return fmt.Errorf("error writing to template: %v", err)
159+
}
160+
154161
return nil
155162
}

cmd/helm2go-operator-sdk/new/cmd.go

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,11 @@ func GetNewCmd() *cobra.Command {
2727
newCmd.Flags().StringVar(&apiVersion, "api-version", "", "Kubernetes apiVersion and has a format of $GROUP_NAME/$VERSION (e.g app.example.com/v1alpha1)")
2828
newCmd.Flags().StringVar(&kind, "kind", "", "Kubernetes CustomResourceDefintion kind. (e.g AppService)")
2929
newCmd.Flags().BoolVar(&clusterScoped, "cluster-scoped", false, "Operator cluster scoped or not")
30+
31+
// debug flags
3032
newCmd.Flags().BoolVar(&mock, "mock", false, "Used for testing")
33+
// newCmd.Flags().MarkHidden("mock")
34+
3135
return newCmd
3236
}
3337

@@ -52,7 +56,6 @@ func newFunc(cmd *cobra.Command, args []string) error {
5256

5357
chartClient := NewChartClient()
5458
chartClient.SetValues(helmChartRef, helmChartVersion, helmChartRepo, username, password, helmChartCAFile, helmChartCertFile, helmChartKeyFile)
55-
chartClient.PathConfig, _ = GetBasePathConfig()
5659

5760
if err := parse(args); err != nil {
5861
log.Error("error parsing arguments: ", err)
@@ -68,23 +71,29 @@ func newFunc(cmd *cobra.Command, args []string) error {
6871
return err
6972
}
7073

74+
// for testing
75+
if mock {
76+
return nil
77+
}
78+
7179
log.Infof("🤠 Creating Go Operator %s from Helm Chart %s!", operatorName, chartClient.HelmChartRef)
7280

7381
// load the spcecified helm chart
74-
7582
err := chartClient.LoadChart()
7683

7784
if err != nil {
7885
log.Error("error loading chart: ", err)
7986
return err
8087
}
8188

89+
// convert helm resources to Go resource cache
8290
rcache, err := chartClient.DoHelmGoConversion()
8391
if err != nil {
8492
log.Error("error performing chart conversion: ", err)
8593
return err
8694
}
8795

96+
// output directory is the path/to/command/operator-name
8897
outputDir = filepath.Join(chartClient.PathConfig.GetBasePath(), operatorName)
8998

9099
//create the operator-sdk scaffold

cmd/helm2go-operator-sdk/new/cmd_util.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,11 +41,11 @@ func verifyFlags() error {
4141

4242
func parse(args []string) error {
4343
if len(args) != 1 {
44-
return fmt.Errorf("Please Specify Operator Name")
44+
return fmt.Errorf("please specify operator name")
4545
}
4646
operatorName = args[0]
4747
if len(operatorName) == 0 {
48-
return fmt.Errorf("Project Name Must Not Be Empty")
48+
return fmt.Errorf("operator name should not be empty")
4949
}
5050
return nil
5151
}

cmd/helm2go-operator-sdk/new/scaffold.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@ import (
88
)
99

1010
func doGoScaffold() error {
11+
// for testing purposes
12+
fmt.Printf("What is mock")
13+
fmt.Print(mock)
1114
if mock {
1215
return nil
1316
}

docs/CLI-Reference.md

Lines changed: 49 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,66 @@
11
# CLI Guide
22

3-
**_Note:_** Binary has not yet been build.
4-
53
```terminal
64
Usage:
7-
go run main.go [command]
5+
helm2go-operator-sdk [command] [arguments] [flags]
86
```
97

10-
## convert
8+
## new
119
---
1210
Scaffolds a Go Operator for a corresponding Helm Chart.
1311

1412
### Args
1513
* `operator-name` - name of the new operator
1614

1715
### Flags
18-
* `--helm-chart` - Name of the helm chart. If using an external repo, specify the name within the repo i.e. `nginx`. If using a local chart provide `path/to/chart`
19-
* `--helm-chart-repo` - Specify external chart repo if necessary.
20-
* `--helm-chart-version` - Specify external chart version if necessary.
21-
* `--username` - Specify external repo username if necessary.
22-
* `--password` - Specify external repo password if necessary.
23-
* `--helm-chart-cert-file` - Specify Cert File for external repo if necessary.
24-
* `--helm-chart-key-file` - Specify Key File for external repo if necessary.
25-
* `--helm-chart-ca-file` - Specify CA File for external repo if necessary.
26-
* `--api-version` - Kubernetes API Version and has a format of `<groupName>/<version>` i.e. `app.example.com/v1alpha1`
27-
* `--kind` - Kubernetes Custom Resource Definition kind.
16+
* **Required:**` --helm-chart` - Name of the helm chart. If using an external repo, specify the name within the repo i.e. `nginx`. If using a local chart provide `path/to/chart`
17+
* `--helm-chart-repo` - Specify external chart repo if necessary.
18+
* `--helm-chart-version` - Specify external chart version if necessary.
19+
* `--username` - Specify external repo username if necessary.
20+
* `--password` - Specify external repo password if necessary.
21+
* `--helm-chart-cert-file` - Specify Cert File for external repo if necessary.
22+
* `--helm-chart-key-file` - Specify Key File for external repo if necessary.
23+
* `--helm-chart-ca-file` - Specify CA File for external repo if necessary.
24+
* **Required:** `--api-version` - Kubernetes API Version and has a format of `<groupName>/<version>` i.e. `app.example.com/v1alpha1`
25+
* **Required:** `--kind` - Kubernetes Custom Resource Definition kind.
2826
* `--cluster-scoped` - Operator cluster scoped or not.
2927

3028
### Example
3129
```
32-
$ go run main.go convert nginx-operator --helm-chart=path/to/chart --api-version=web.example.com/v1alpha1 --kind=Nginx
33-
```
30+
$ helm2go-operator-sdk new nginx-operator --helm-chart=path/to/chart --api-version=web.example.com/v1alpha1 --kind=Nginx
31+
```
32+
33+
The resulting structure will be:
34+
```
35+
<project-name>
36+
| build/
37+
| | Dockerfile
38+
| | bin/
39+
| | _output/
40+
| cmd/.
41+
| | manager/
42+
| | | main.go
43+
| deploy/
44+
| | operator.yaml
45+
| | role_binding.yaml
46+
| | role.yaml
47+
| | service_account.yaml
48+
| | crds/
49+
| | | <api-version>_<kind>_cr.yaml
50+
| | | <api-version>_<kind>_crd.yaml
51+
| pkg/
52+
| | apis/
53+
| | | <api-version>/
54+
| | | | doc.go
55+
| | | | memcached_types.go
56+
| | | | ...
57+
| | | ...
58+
| | controller/
59+
| | | <kind>/
60+
| | | <kind>_controller.go
61+
| | | ...
62+
| | resources/
63+
| | | ...
64+
| ...
65+
```
66+

internal/pkg/load/convert.go

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,10 @@ import (
1919

2020
// YAMLUnmarshalResources converts a directory of injected YAML files to Kubernetes resources; resouresPath is assumed to be an absolute path
2121
// if conversion of any resource fails method will panic; adds resources to resource cache
22-
func YAMLUnmarshalResources(rp string, validMap *validatemap.ValidateMap, rc *resourcecache.ResourceCache) (*resourcecache.ResourceCache, error) {
22+
func YAMLUnmarshalResources(resourcesPath string, validMap *validatemap.ValidateMap, resourceCache *resourcecache.ResourceCache) (*resourcecache.ResourceCache, error) {
2323

2424
// TODO convert all the files in a directory
25-
files, err := ioutil.ReadDir(rp)
25+
files, err := ioutil.ReadDir(resourcesPath)
2626
if err != nil {
2727
return nil, err
2828
}
@@ -34,7 +34,7 @@ func YAMLUnmarshalResources(rp string, validMap *validatemap.ValidateMap, rc *re
3434
continue
3535
}
3636

37-
file := filepath.Join(rp, f.Name())
37+
file := filepath.Join(resourcesPath, f.Name())
3838
// obtain the converted result resourceKind
3939
rconfig, err := yamlUnmarshalSingleResource(file)
4040
if err != nil {
@@ -43,7 +43,7 @@ func YAMLUnmarshalResources(rp string, validMap *validatemap.ValidateMap, rc *re
4343
} else if err.Error() == "not yaml" {
4444
continue
4545
} else if err.Error() == "unknown type" {
46-
return nil, fmt.Errorf("resource: %v is of unknown type", rconfig.r)
46+
return nil, fmt.Errorf("resource: %v is of unknown type", rconfig.resource)
4747
} else if err.Error() == "deprecated" {
4848
log.Printf("%s contains deprecated api version; exiting", f.Name())
4949
os.Exit(1)
@@ -56,13 +56,13 @@ func YAMLUnmarshalResources(rp string, validMap *validatemap.ValidateMap, rc *re
5656
}
5757
// add resource to cache
5858
// initializes the kind type
59-
rc.SetKindType(rconfig.kt)
59+
resourceCache.SetKindType(rconfig.kindType)
6060
// set the correct cache information
61-
rc.SetResourceForKindType(rconfig.kt, rconfig.pt)
62-
rs := rc.GetResourceForKindType(rconfig.kt)
63-
rs.SetResourceFunctions(string(rconfig.kt), rconfig.r)
61+
resourceCache.SetResourceForKindType(rconfig.kindType, rconfig.packageType)
62+
rs := resourceCache.GetResourceForKindType(rconfig.kindType)
63+
rs.SetResourceFunctions(string(rconfig.kindType), rconfig.resource)
6464
}
65-
return rc, nil
65+
return resourceCache, nil
6666
}
6767

6868
// yamlUnmarshalSingleResource converts injected YAML files to a Kubernetes resource; rp is assumed to be an absolute path

internal/pkg/load/kinds.go

Lines changed: 7 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -10,26 +10,16 @@ import (
1010
var AcceptedK8sTypes = regexp.MustCompile(`(Role|ClusterRole|RoleBinding|ClusterRoleBinding|ServiceAccount|Service|Deployment)`)
1111

1212
type resourceConfig struct {
13-
r interface{}
14-
kt resourcecache.KindType
15-
pt resourcecache.PackageType
13+
resource interface{}
14+
kindType resourcecache.KindType
15+
packageType resourcecache.PackageType
1616
}
1717

1818
func (rc *resourceConfig) toResourceCache() *resourcecache.Resource {
19-
var r resourcecache.Resource
19+
var resource resourcecache.Resource
2020

21-
r.PackageName = rc.pt
22-
r.FileName = string(rc.kt)
21+
resource.PackageName = rc.packageType
22+
resource.FileName = string(rc.kindType)
2323

24-
// put things into resourcecache format
25-
26-
return &r
24+
return &resource
2725
}
28-
29-
// func getKindType(kind string) *resourcecache.KindType {
30-
// var kt resourcecache.KindType
31-
// switch kind {
32-
// case resourcecache.KindTypeConfigMap.(string):
33-
// kt =
34-
// }
35-
// }

internal/pkg/load/validation.go

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -13,42 +13,40 @@ import (
1313
"github.com/redhat-nfvpe/helm2go-operator-sdk/internal/validatemap"
1414
)
1515

16-
var cd string
17-
1816
// PerformResourceValidation validates templated resources to identify deprecated API versions
19-
func PerformResourceValidation(rp string) (*validatemap.ValidateMap, error) {
20-
cd = rp
17+
func PerformResourceValidation(resourcesPath string) (*validatemap.ValidateMap, error) {
2118
// collect all templated files in directory
22-
files, err := ioutil.ReadDir(rp)
19+
// TODO: need to test with nested templates
20+
files, err := ioutil.ReadDir(resourcesPath)
2321
if err != nil {
24-
return nil, fmt.Errorf("error reading files in directory %s: %v", rp, err)
22+
return nil, fmt.Errorf("error reading files in directory %s: %v", resourcesPath, err)
2523
}
2624

2725
var validMap validatemap.ValidateMap
2826

29-
for _, f := range files {
30-
rconfig, err := yamlUnmarshalSingleResource(filepath.Join(rp, f.Name()))
27+
for _, file := range files {
28+
rconfig, err := yamlUnmarshalSingleResource(filepath.Join(resourcesPath, file.Name()))
3129
if err != nil {
3230
reader := bufio.NewReader(os.Stdin)
3331
if e := err.Error(); e == "deprecated" {
34-
fmt.Printf("Resource: %v has a deprecated API version. Please enter 'continue' to proceed without this resource or 'stop' to exit the program: ", reflect.TypeOf(rconfig.r))
32+
fmt.Printf("Resource: %v has a deprecated API version. Please enter 'continue' to proceed without this resource or 'stop' to exit the program: ", reflect.TypeOf(rconfig.resource))
3533
text, _ := reader.ReadString('\n')
3634
if isStop(text) {
37-
cleanUpAndExit()
35+
cleanUpAndExit(resourcesPath)
3836
}
3937
if isContinue(text) {
40-
addResourceToContinue(&validMap, f.Name())
38+
addResourceToContinue(&validMap, file.Name())
4139
}
4240
} else if e == "unsupported" {
4341

44-
fmt.Printf("Resource: %v is unsupported. Please enter 'continue' to proceed without this resource, or 'stop' to exit the program: ", reflect.TypeOf(rconfig.r))
42+
fmt.Printf("Resource: %v is unsupported. Please enter 'continue' to proceed without this resource, or 'stop' to exit the program: ", reflect.TypeOf(rconfig.resource))
4543
text, _ := reader.ReadString('\n')
4644

4745
if isStop(text) {
48-
cleanUpAndExit()
46+
cleanUpAndExit(resourcesPath)
4947
}
5048
if isContinue(text) {
51-
addResourceToContinue(&validMap, f.Name())
49+
addResourceToContinue(&validMap, file.Name())
5250
}
5351
} else if e == "not yaml" || e == "empty" {
5452
continue
@@ -72,11 +70,11 @@ func matchString(text string, contains string) bool {
7270
return strings.Contains(text, contains)
7371
}
7472

75-
func cleanUpAndExit() {
73+
func cleanUpAndExit(resourcesPath string) {
7674
// log exit begin
7775
log.Println("Cleanup Temp Started")
7876
// clean up temp folder
79-
temp := filepath.Dir(filepath.Dir(cd))
77+
temp := filepath.Dir(filepath.Dir(resourcesPath))
8078
err := os.RemoveAll(temp)
8179
if err != nil {
8280
log.Printf("Error While Cleaning Up Temp: %v", err)

internal/pkg/load/validation_test.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package load
22

33
import (
4+
"os"
5+
"path/filepath"
46
"testing"
57

68
. "github.com/onsi/ginkgo"
@@ -14,7 +16,8 @@ func TestValidation(t *testing.T) {
1416

1517
var _ = Describe("Resource Validation", func() {
1618
It("Validates Resources", func() {
17-
_, err := PerformResourceValidation("/home/sjakati/go/src/github.com/redhat-nfvpe/helm2go-operator-sdk/test/resources")
19+
gopath := os.Getenv("GOPATH")
20+
_, err := PerformResourceValidation(filepath.Join(gopath, "/src/github.com/redhat-nfvpe/helm2go-operator-sdk/test/resources"))
1821
Expect(err).ToNot(HaveOccurred())
1922
})
2023
})

0 commit comments

Comments
 (0)