Skip to content

Commit ccf727e

Browse files
authored
Merge pull request #50 from redhat-nfvpe/code-refactor-jam
Code jam refactoring
2 parents 5374df8 + a76b97a commit ccf727e

File tree

8 files changed

+98
-99
lines changed

8 files changed

+98
-99
lines changed

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

Lines changed: 16 additions & 12 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,19 +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)
144-
if !ok {
145-
fmt.Println(ok)
145+
if err := templating.OverwriteController(outputDir, kind, apiVersion, rcache); err != nil {
146+
return fmt.Errorf("error while overwriting controller: %v", err)
146147
}
147148
// create templates for writing to file
148149
templates := templating.CacheTemplating(rcache, outputDir, kind, apiVersion)
149150
// templates to files; outputDir is the parent directory where the operator scaffolding lives
150151
resDir := filepath.Join(outputDir, "pkg", "resources")
152+
151153
// create the necessary package resource specific folders
152-
ok = templating.ResourceFileStructure(rcache, resDir)
153-
ok = templating.TemplatesToFiles(templates, resDir)
154-
if !ok {
155-
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)
156156
}
157+
if err := templating.TemplatesToFiles(templates, resDir); err != nil {
158+
return fmt.Errorf("error writing to template: %v", err)
159+
}
160+
157161
return nil
158162
}

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
}

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)

0 commit comments

Comments
 (0)