Skip to content
This repository has been archived by the owner on Sep 26, 2022. It is now read-only.

Commit

Permalink
fix: companion-cli, fixes #234 which allows the latest version to be …
Browse files Browse the repository at this point in the history
…updated when creating a new API (#237)

* fix: Fixes #234, moved latest version info to apis directory

Signed-off-by: Dustin Scott <sdustin@vmware.com>

* refactor: reduce duplicate logic in api scaffolding

Signed-off-by: Dustin Scott <sdustin@vmware.com>

* fix: fixed missing sample input after rebase

Signed-off-by: Dustin Scott <sdustin@vmware.com>

* refactor: finished refactor of api

Signed-off-by: Dustin Scott <sdustin@vmware.com>

* refactor: make api scaffolding more readable

Signed-off-by: Dustin Scott <sdustin@vmware.com>

* chore: rebase with main and fixup api scaffoling with new changes

Signed-off-by: Dustin Scott <sdustin@vmware.com>
  • Loading branch information
Dustin Scott authored Jan 5, 2022
1 parent f2156a6 commit 2922581
Show file tree
Hide file tree
Showing 8 changed files with 420 additions and 421 deletions.
417 changes: 174 additions & 243 deletions internal/plugins/workload/v1/scaffolds/api.go

Large diffs are not rendered by default.

188 changes: 188 additions & 0 deletions internal/plugins/workload/v1/scaffolds/templates/api/kind.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
// Copyright 2021 VMware, Inc.
// SPDX-License-Identifier: MIT

package api

import (
"fmt"
"path/filepath"
"strings"

"sigs.k8s.io/kubebuilder/v3/pkg/machinery"
)

var (
_ machinery.Template = &Kind{}
_ machinery.Template = &KindLatest{}
_ machinery.Inserter = &KindUpdater{}
)

// Code Markers (associated with below fragments).
const (
kindImportsMarker = "operator-builder:imports"
kindGroupVersionsMarker = "operator-builder:groupversions"
)

// Code Fragments (associated with above markers).
const (
kindImportsFragment = `%s "%s/apis/%s/%s"
`
kindGroupVersionsFragment = `%s.GroupVersion,
`
)

// Kind scaffolds the file that defines specific information related to kind regardless of
// the API version.
type Kind struct {
machinery.TemplateMixin
machinery.MultiGroupMixin
machinery.BoilerplateMixin
machinery.ResourceMixin
}

func (f *Kind) SetTemplateDefaults() error {
f.Path = filepath.Join(
"apis",
f.Resource.Group,
fmt.Sprintf("%s.go", strings.ToLower(f.Resource.Kind)),
)

f.TemplateBody = fmt.Sprintf(
kindTemplate,
machinery.NewMarkerFor(f.Path, kindImportsMarker),
machinery.NewMarkerFor(f.Path, kindGroupVersionsMarker),
)

return nil
}

// KindLatest scaffolds the file that defines specific information related to the latest API version
// of a specific kind.
type KindLatest struct {
machinery.TemplateMixin
machinery.MultiGroupMixin
machinery.BoilerplateMixin
machinery.ResourceMixin
machinery.RepositoryMixin

PackageName string
}

func (f *KindLatest) SetTemplateDefaults() error {
f.Path = filepath.Join(
"apis",
f.Resource.Group,
fmt.Sprintf("%s_latest.go", strings.ToLower(f.Resource.Kind)),
)

f.TemplateBody = kindLatestTemplate
f.IfExistsAction = machinery.OverwriteFile

return nil
}

// KindUpdater updates the file with any new version information.
type KindUpdater struct {
machinery.TemplateMixin
machinery.MultiGroupMixin
machinery.BoilerplateMixin
machinery.ResourceMixin
machinery.RepositoryMixin
}

// GetPath implements file.Builder interface.
func (f *KindUpdater) GetPath() string {
return filepath.Join(
"apis",
f.Resource.Group,
fmt.Sprintf("%s.go", strings.ToLower(f.Resource.Kind)),
)
}

// GetIfExistsAction implements file.Builder interface.
func (*KindUpdater) GetIfExistsAction() machinery.IfExistsAction {
return machinery.OverwriteFile
}

// GetMarkers implements file.Inserter interface.
func (f *KindUpdater) GetMarkers() []machinery.Marker {
return []machinery.Marker{
machinery.NewMarkerFor(f.GetPath(), kindImportsMarker),
machinery.NewMarkerFor(f.GetPath(), kindGroupVersionsMarker),
}
}

// GetCodeFragments implements file.Inserter interface.
func (f *KindUpdater) GetCodeFragments() machinery.CodeFragmentsMap {
fragments := make(machinery.CodeFragmentsMap, 1)

// If resource is not being provided we are creating the file, not updating it
if f.Resource == nil {
return fragments
}

versionGroup := fmt.Sprintf("%s%s", f.Resource.Version, f.Resource.Group)

// Generate imports code fragments
imports := make([]string, 0)
imports = append(imports, fmt.Sprintf(kindImportsFragment,
versionGroup,
f.Repo,
f.Resource.Group,
f.Resource.Version,
))

// Generate groupVersions code fragments
groupVersions := make([]string, 0)
groupVersions = append(groupVersions, fmt.Sprintf(kindGroupVersionsFragment, versionGroup))

// Only store code fragments in the map if the slices are non-empty
if len(imports) != 0 {
fragments[machinery.NewMarkerFor(f.GetPath(), kindImportsMarker)] = imports
}

if len(groupVersions) != 0 {
fragments[machinery.NewMarkerFor(f.GetPath(), kindGroupVersionsMarker)] = groupVersions
}

return fragments
}

const (
kindTemplate = `{{ .Boilerplate }}
package {{ .Resource.Group }}
import (
%s
"k8s.io/apimachinery/pkg/runtime/schema"
)
// {{ .Resource.Kind }}GroupVersions returns all group version objects associated with this kind.
func {{ .Resource.Kind }}GroupVersions() []schema.GroupVersion {
return []schema.GroupVersion{
%s
}
}
`
kindLatestTemplate = `{{ .Boilerplate }}
package {{ .Resource.Group }}
import (
{{ .Resource.Version }}{{ .Resource.Group }} "{{ .Repo }}/apis/{{ .Resource.Group }}/{{ .Resource.Version }}"
{{ .Resource.Version }}{{ lower .Resource.Kind }} "{{ .Resource.Path }}/{{ .PackageName }}"
)
// Code generated by operator-builder. DO NOT EDIT.
// {{ .Resource.Kind }}LatestGroupVersion returns the latest group version object associated with this
// particular kind.
var {{ .Resource.Kind }}LatestGroupVersion = {{ .Resource.Version }}{{ .Resource.Group }}.GroupVersion
// {{ .Resource.Kind }}LatestSample returns the latest sample manifest associated with this
// particular kind.
var {{ .Resource.Kind }}LatestSample = {{ .Resource.Version }}{{ lower .Resource.Kind }}.Sample(false)
`
)
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,17 @@ type Definition struct {
machinery.RepositoryMixin
machinery.ResourceMixin

ClusterScoped bool
SourceFile workloadv1.SourceFile
PackageName string
IsComponent bool
Collection *workloadv1.WorkloadCollection
// input fields
Builder workloadv1.WorkloadAPIBuilder
SourceFile workloadv1.SourceFile
}

func (f *Definition) SetTemplateDefaults() error {
f.Path = filepath.Join(
"apis",
f.Resource.Group,
f.Resource.Version,
f.PackageName,
f.Builder.GetPackageName(),
f.SourceFile.Filename,
)

Expand All @@ -45,7 +43,7 @@ func (f *Definition) SetTemplateDefaults() error {
//nolint:lll
const definitionTemplate = `{{ .Boilerplate }}
package {{ .PackageName }}
package {{ .Builder.GetPackageName }}
import (
{{ if .SourceFile.HasStatic }}
Expand All @@ -58,22 +56,22 @@ import (
{{ end }}
{{ .Resource.ImportAlias }} "{{ .Resource.Path }}"
{{- if .IsComponent }}
{{ .Collection.Spec.API.Group }}{{ .Collection.Spec.API.Version }} "{{ .Repo }}/apis/{{ .Collection.Spec.API.Group }}/{{ .Collection.Spec.API.Version }}"
{{- if .Builder.IsComponent }}
{{ .Builder.GetCollection.Spec.API.Group }}{{ .Builder.GetCollection.Spec.API.Version }} "{{ .Repo }}/apis/{{ .Builder.GetCollection.Spec.API.Group }}/{{ .Builder.GetCollection.Spec.API.Version }}"
{{ end -}}
)
{{ range .SourceFile.Children }}
// Create{{ .UniqueName }} creates the {{ .Name }} {{ .Kind }} resource.
func Create{{ .UniqueName }} (
parent *{{ $.Resource.ImportAlias }}.{{ $.Resource.Kind }},
{{- if $.IsComponent }}
collection *{{ $.Collection.Spec.API.Group }}{{ $.Collection.Spec.API.Version }}.{{ $.Collection.Spec.API.Kind }},
{{- if $.Builder.IsComponent }}
collection *{{ $.Builder.GetCollection.Spec.API.Group }}{{ $.Builder.GetCollection.Spec.API.Version }}.{{ $.Builder.GetCollection.Spec.API.Kind }},
{{ end -}}
) (client.Object, error) {
{{- .SourceCode }}
{{ if not $.ClusterScoped }}
{{ if not $.Builder.IsClusterScoped }}
resourceObj.SetNamespace(parent.Namespace)
{{ end }}
Expand Down
18 changes: 8 additions & 10 deletions internal/plugins/workload/v1/scaffolds/templates/api/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,8 @@ type Types struct {
machinery.RepositoryMixin
machinery.ResourceMixin

SpecFields *workloadv1.APIFields
ClusterScoped bool
Dependencies []*workloadv1.ComponentWorkload
IsStandalone bool
// input fields
Builder workloadv1.WorkloadAPIBuilder
}

// SetTemplateDefaults implements file.Template.
Expand Down Expand Up @@ -61,7 +59,7 @@ import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
{{- $Repo := .Repo }}{{- $Added := "" }}{{- range .Dependencies }}
{{- $Repo := .Repo }}{{- $Added := "" }}{{- range .Builder.GetDependencies }}
{{- if ne .Spec.API.Group $.Resource.Group }}
{{- if not (containsString (printf "%s%s" .Spec.API.Group .Spec.API.Version) $Added) }}
{{- $Added = (printf "%s%s" $Added (printf "%s%s" .Spec.API.Group .Spec.API.Version)) }}
Expand All @@ -76,7 +74,7 @@ var ErrUnableToConvert{{ .Resource.Kind }} = errors.New("unable to convert to {{
// EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN!
// NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized.
{{ .SpecFields.GenerateAPISpec .Resource.Kind }}
{{ .Builder.GetAPISpecFields.GenerateAPISpec .Resource.Kind }}
// {{ .Resource.Kind }}Status defines the observed state of {{ .Resource.Kind }}.
type {{ .Resource.Kind }}Status struct {
Expand All @@ -85,13 +83,13 @@ type {{ .Resource.Kind }}Status struct {
Created bool ` + "`" + `json:"created,omitempty"` + "`" + `
DependenciesSatisfied bool ` + "`" + `json:"dependenciesSatisfied,omitempty"` + "`" + `
Conditions []*status.PhaseCondition ` + "`" + `json:"conditions,omitempty"` + "`" + `
Resources []*status.ChildResource ` + "`" + `json:"resources,omitempty"` + "`" + `
Conditions []*status.PhaseCondition ` + "`" + `json:"conditions,omitempty"` + "`" + `
Resources []*status.ChildResource ` + "`" + `json:"resources,omitempty"` + "`" + `
}
// +kubebuilder:object:root=true
// +kubebuilder:subresource:status
{{- if .ClusterScoped }}
{{- if .Builder.IsClusterScoped }}
// +kubebuilder:resource:scope=Cluster
{{ end }}
Expand Down Expand Up @@ -177,7 +175,7 @@ func (component *{{ .Resource.Kind }}) SetChildResourceCondition(resource *statu
// GetDependencies returns the dependencies for a component.
func (*{{ .Resource.Kind }}) GetDependencies() []workload.Workload {
return []workload.Workload{
{{- range .Dependencies }}
{{- range .Builder.GetDependencies }}
{{- if eq .Spec.API.Group $.Resource.Group }}
&{{ .Spec.API.Kind }}{},
{{- else }}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"strings"

"sigs.k8s.io/kubebuilder/v3/pkg/machinery"
"sigs.k8s.io/kubebuilder/v3/pkg/model/resource"

"github.com/vmware-tanzu-labs/operator-builder/internal/utils"
workloadv1 "github.com/vmware-tanzu-labs/operator-builder/internal/workload/v1"
Expand Down Expand Up @@ -37,8 +36,7 @@ type CmdGenerateSub struct {
machinery.ResourceMixin

// input fields
Builder workloadv1.WorkloadAPIBuilder
ComponentResource *resource.Resource
Builder workloadv1.WorkloadAPIBuilder

// template fields
cmdGenerateSubCommon
Expand All @@ -48,10 +46,6 @@ type CmdGenerateSub struct {
}

func (f *CmdGenerateSub) SetTemplateDefaults() error {
if f.Builder.IsComponent() {
f.Resource = f.ComponentResource
}

// set template fields
f.RootCmd = *f.Builder.GetRootCommand()
f.SubCmd = *f.Builder.GetSubCommand()
Expand Down Expand Up @@ -109,8 +103,7 @@ type CmdGenerateSubUpdater struct { //nolint:maligned
machinery.ResourceMixin

// input fields
Builder workloadv1.WorkloadAPIBuilder
ComponentResource *resource.Resource
Builder workloadv1.WorkloadAPIBuilder

// template fields
cmdGenerateSubCommon
Expand All @@ -119,10 +112,6 @@ type CmdGenerateSubUpdater struct { //nolint:maligned

// GetPath implements file.Builder interface.
func (f *CmdGenerateSubUpdater) GetPath() string {
if f.Builder.IsComponent() {
f.Resource = f.ComponentResource
}

return f.SubCmd.GetSubCmdRelativeFileName(
f.Builder.GetRootCommand().Name,
"generate",
Expand Down Expand Up @@ -163,10 +152,6 @@ const (
func (f *CmdGenerateSubUpdater) GetCodeFragments() machinery.CodeFragmentsMap {
fragments := make(machinery.CodeFragmentsMap, 1)

if f.Builder.IsComponent() {
f.Resource = f.ComponentResource
}

// set template fields
f.RootCmd = *f.Builder.GetRootCommand()
f.SubCmd = *f.Builder.GetSubCommand()
Expand Down
Loading

0 comments on commit 2922581

Please sign in to comment.