Skip to content

Commit

Permalink
Fix issues raised by Go Report Card (mainly comments and style relate…
Browse files Browse the repository at this point in the history
…d changes)

Signed-off-by: Adrian Orive <[email protected]>
  • Loading branch information
Adirio committed Feb 26, 2020
1 parent 8195557 commit ed8438e
Show file tree
Hide file tree
Showing 58 changed files with 156 additions and 86 deletions.
2 changes: 1 addition & 1 deletion cmd/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ func (o *apiOptions) validate(c *config.Config) error {

func (o *apiOptions) scaffolder(c *config.Config) (scaffold.Scaffolder, error) {
// Load the boilerplate
bp, err := ioutil.ReadFile(filepath.Join("hack", "boilerplate.go.txt")) // nolint:gosec
bp, err := ioutil.ReadFile(filepath.Join("hack", "boilerplate.go.txt")) //nolint:gosec
if err != nil {
return nil, fmt.Errorf("unable to load boilerplate: %v", err)
}
Expand Down
2 changes: 1 addition & 1 deletion cmd/edit.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ func (o *editOptions) validate(c *config.Config) error {
return nil
}

func (o *editOptions) scaffolder(c *config.Config) (scaffold.Scaffolder, error) { // nolint:unparam
func (o *editOptions) scaffolder(c *config.Config) (scaffold.Scaffolder, error) { //nolint:unparam
return scaffold.NewEditScaffolder(c, o.multigroup), nil
}

Expand Down
2 changes: 1 addition & 1 deletion cmd/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ func (o *initOptions) validate(c *config.Config) error {
return nil
}

func (o *initOptions) scaffolder(c *config.Config) (scaffold.Scaffolder, error) { // nolint:unparam
func (o *initOptions) scaffolder(c *config.Config) (scaffold.Scaffolder, error) { //nolint:unparam
return scaffold.NewInitScaffolder(c, o.license, o.owner), nil
}

Expand Down
1 change: 1 addition & 0 deletions cmd/internal/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ func ConfiguredAndV1() bool {
return projectConfig.IsV1()
}

// PrintV1DeprecationWarning prints a deprecation warning if some v1 feature is used
func PrintV1DeprecationWarning() {
fmt.Printf(noticeColor, "[Deprecation Notice] The v1 projects are deprecated and will not be supported beyond "+
"Feb 1, 2020.\nSee how to upgrade your project to v2: https://book.kubebuilder.io/migration/guide.html\n")
Expand Down
3 changes: 2 additions & 1 deletion cmd/internal/exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,9 @@ import (
"strings"
)

// RunCmd prints the provided message and command and then executes it binding stdout and stderr
func RunCmd(msg, cmd string, args ...string) error {
c := exec.Command(cmd, args...) // #nolint:gosec
c := exec.Command(cmd, args...) //nolint:gosec
c.Stdout = os.Stdout
c.Stderr = os.Stderr
fmt.Println(msg + ":\n$ " + strings.Join(c.Args, " "))
Expand Down
1 change: 1 addition & 0 deletions cmd/internal/go_version.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
"strings"
)

// ValidateGoVersion verifies that Go is installed and the current go version is supported by kubebuilder
func ValidateGoVersion() error {
err := fetchAndCheckGoVersion()
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion cmd/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ func (o *updateOptions) validate(c *config.Config) error {
return nil
}

func (o *updateOptions) scaffolder(c *config.Config) (scaffold.Scaffolder, error) { // nolint:unparam
func (o *updateOptions) scaffolder(c *config.Config) (scaffold.Scaffolder, error) { //nolint:unparam
return scaffold.NewUpdateScaffolder(&c.Config), nil
}

Expand Down
3 changes: 3 additions & 0 deletions cmd/version/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ var (
buildDate = "1970-01-01T00:00:00Z" // build date in ISO8601 format, output of $(date -u +'%Y-%m-%dT%H:%M:%SZ')
)

// Version contains all the information related to the CLI version
type Version struct {
KubeBuilderVersion string `json:"kubeBuilderVersion"`
KubernetesVendor string `json:"kubernetesVendor"`
Expand All @@ -54,10 +55,12 @@ func getVersion() Version {
}
}

// Print prints the CLI version
func (v Version) Print() {
fmt.Printf("Version: %#v\n", v)
}

// NewVersionCmd creates a new command that prints the CLI version
func NewVersionCmd() *cobra.Command {
return &cobra.Command{
Use: "version",
Expand Down
6 changes: 3 additions & 3 deletions cmd/webhook.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ func (o *webhookV1Options) validate(c *config.Config) error {

func (o *webhookV1Options) scaffolder(c *config.Config) (scaffold.Scaffolder, error) {
// Load the boilerplate
bp, err := ioutil.ReadFile(filepath.Join("hack", "boilerplate.go.txt")) // nolint:gosec
bp, err := ioutil.ReadFile(filepath.Join("hack", "boilerplate.go.txt")) //nolint:gosec
if err != nil {
return nil, fmt.Errorf("unable to load boilerplate: %v", err)
}
Expand Down Expand Up @@ -220,9 +220,9 @@ func (o *webhookV2Options) validate(c *config.Config) error {
return nil
}

func (o *webhookV2Options) scaffolder(c *config.Config) (scaffold.Scaffolder, error) { // nolint:unparam
func (o *webhookV2Options) scaffolder(c *config.Config) (scaffold.Scaffolder, error) { //nolint:unparam
// Load the boilerplate
bp, err := ioutil.ReadFile(filepath.Join("hack", "boilerplate.go.txt")) // nolint:gosec
bp, err := ioutil.ReadFile(filepath.Join("hack", "boilerplate.go.txt")) //nolint:gosec
if err != nil {
return nil, fmt.Errorf("unable to load boilerplate: %v", err)
}
Expand Down
5 changes: 4 additions & 1 deletion docs/book/utils/litgo/literate.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,10 @@ type Literate struct {
BaseSourcePath *url.URL
}

func (_ Literate) SupportsOutput(_ string) bool { return true }
// SupportsOutput implements plugin.Plugin
func (Literate) SupportsOutput(_ string) bool { return true }

// Process implements plugin.Plugin
func (l Literate) Process(input *plugin.Input) error {
bookSrcDir := filepath.Join(input.Context.Root, input.Context.Config.Book.Src)
return plugin.EachCommand(&input.Book, "literatego", func(chapter *plugin.BookChapter, relPath string) (string, error) {
Expand Down
7 changes: 7 additions & 0 deletions docs/book/utils/markerdocs/html.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ type toHTML interface {
// Text is a chunk of text in an HTML doc.
type Text string

// WriteHTML writes the string as HTML to the given Writer
func (t Text) WriteHTML(w io.Writer) error {
_, err := io.WriteString(w, html.EscapeString(string(t)))
return err
Expand All @@ -51,6 +52,7 @@ type Tag struct {
Children []toHTML
}

// WriteHTML writes the tag as HTML to the given Writer
func (t Tag) WriteHTML(w io.Writer) error {
attrsOut := ""
if t.Attrs != nil {
Expand All @@ -76,6 +78,7 @@ func (t Tag) WriteHTML(w io.Writer) error {
// Fragment is some series of tags, text, etc in an HTML doc.
type Fragment []toHTML

// WriteHTML writes the fragment as HTML to the given Writer
func (f Fragment) WriteHTML(w io.Writer) error {
for _, item := range f {
if err := item.WriteHTML(w); err != nil {
Expand All @@ -94,11 +97,13 @@ type Attrs interface {
// classes sets the class attribute to these class names.
type classes []string

// ToAttrs implements Attrs
func (c classes) ToAttrs() string { return fmt.Sprintf("class=%q", strings.Join(c, " ")) }

// optionalClasses sets the the class attribute to these class names, if their values are true.
type optionalClasses map[string]bool

// ToAttrs implements Attrs
func (c optionalClasses) ToAttrs() string {
actualClasses := make([]string, 0, len(c))
for class, active := range c {
Expand All @@ -112,6 +117,7 @@ func (c optionalClasses) ToAttrs() string {
// attrs joins together one or more Attrs.
type attrs []Attrs

// ToAttrs implements Attrs
func (a attrs) ToAttrs() string {
parts := make([]string, len(a))
for i, attr := range a {
Expand All @@ -126,6 +132,7 @@ type dataAttr struct {
Value string
}

// ToAttrs implements Attrs
func (d dataAttr) ToAttrs() string {
return fmt.Sprintf("data-%s=%q", d.Name, d.Value)
}
Expand Down
14 changes: 11 additions & 3 deletions docs/book/utils/markerdocs/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,10 @@ type MarkerDocs struct {
Args map[string][]string
}

func (_ MarkerDocs) SupportsOutput(_ string) bool { return true }
// SupportsOutput implements plugin.Plugin
func (MarkerDocs) SupportsOutput(_ string) bool { return true }

// Process implements plugin.Plugin
func (p MarkerDocs) Process(input *plugin.Input) error {
markerDocs, err := p.getMarkerDocs()
if err != nil {
Expand Down Expand Up @@ -161,7 +164,10 @@ func (p MarkerDocs) Process(input *plugin.Input) error {
content := new(strings.Builder)

// NB(directxman12): wrap this in a div to prevent the markdown processor from inserting extra paragraphs
fmt.Fprintf(content, "<div><input checked type=\"checkbox\" class=\"markers-summarize\" id=\"markers-summarize-%[1]s\"></input><label class=\"markers-summarize\" for=\"markers-summarize-%[1]s\">Show Detailed Argument Help</label><dl class=\"markers\">", categoryAlias)
_, err := fmt.Fprintf(content, "<div><input checked type=\"checkbox\" class=\"markers-summarize\" id=\"markers-summarize-%[1]s\"></input><label class=\"markers-summarize\" for=\"markers-summarize-%[1]s\">Show Detailed Argument Help</label><dl class=\"markers\">", categoryAlias)
if err != nil {
return "", fmt.Errorf("unable to render marker documentation summary: %v", err)
}

// write the markers
for _, marker := range markers {
Expand All @@ -170,7 +176,9 @@ func (p MarkerDocs) Process(input *plugin.Input) error {
}
}

fmt.Fprintf(content, "</dl></div>")
if _, err = fmt.Fprintf(content, "</dl></div>"); err != nil {
return "", fmt.Errorf("unable to render marker documentation: %v", err)
}

usedCategories[category] = struct{}{}

Expand Down
3 changes: 3 additions & 0 deletions docs/book/utils/plugin/input.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ type BookSection struct {
// according to what serde produces/expects.
type BookItem bookItem

// UnmarshalJSON implements encoding/json.Unmarshaler
func (b *BookItem) UnmarshalJSON(input []byte) error {
// match how serde serializes rust enums.
if input[0] == '"' {
Expand All @@ -79,6 +80,7 @@ func (b *BookItem) UnmarshalJSON(input []byte) error {
return nil
}

// MarshalJSON implements encoding/json.Marshaler
func (b BookItem) MarshalJSON() ([]byte, error) {
if b.Separator {
return json.Marshal("Separator")
Expand Down Expand Up @@ -114,6 +116,7 @@ type Input struct {
Book Book
}

// UnmarshalJSON implements encoding/json.Unmarshaler
func (p *Input) UnmarshalJSON(input []byte) error {
// deserialize from the JSON equivalent to the Rust tuple
// `(context, book)`
Expand Down
7 changes: 4 additions & 3 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,10 @@ import (
)

const (
// Default path for the configuration file
// DefaultPath is the default path for the configuration file
DefaultPath = "PROJECT"

// Default version if flag not provided
// DefaultVersion is the version which will be used when the version flag is not provided
DefaultVersion = config.Version2
)

Expand All @@ -52,7 +52,7 @@ func exists(path string) (bool, error) {

func readFrom(path string) (c config.Config, err error) {
// Read the file
in, err := ioutil.ReadFile(path) // nolint: gosec
in, err := ioutil.ReadFile(path) //nolint:gosec
if err != nil {
return
}
Expand Down Expand Up @@ -152,6 +152,7 @@ func (c Config) Save() error {
return nil
}

// Path returns the path for configuration file
func (c Config) Path() string {
return c.path
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/model/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ limitations under the License.

package config

// Scaffolding versions
const (
// Scaffolding versions
Version1 = "1"
Version2 = "2"
)
Expand Down
1 change: 1 addition & 0 deletions pkg/model/file/mixins.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ type TemplateMixin struct {
TemplateBody string
}

// GetBody implements Template
func (t *TemplateMixin) GetBody() string {
return t.TemplateBody
}
Expand Down
11 changes: 7 additions & 4 deletions pkg/model/resource/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ type Options struct {
CreateExampleReconcileBody bool
}

// Validate verifies that all the fields have valid values
func (opts *Options) Validate() error {
// Check that the required flags did not get a flag as their value
// We can safely look for a '-' as the first char as none of the fields accepts it
Expand Down Expand Up @@ -122,28 +123,28 @@ func (opts *Options) Validate() error {

// Check if the version follows the valid pattern
if !versionRegex.MatchString(opts.Version) {
return fmt.Errorf(
"version must match %s (was %s)", versionPattern, opts.Version)
return fmt.Errorf("version must match %s (was %s)", versionPattern, opts.Version)
}

validationErrors := []string{}

// require Kind to start with an uppercase character
if string(opts.Kind[0]) == strings.ToLower(string(opts.Kind[0])) {
validationErrors = append(validationErrors, "Kind must start with an uppercase character")
validationErrors = append(validationErrors, "kind must start with an uppercase character")
}

validationErrors = append(validationErrors, isDNS1035Label(strings.ToLower(opts.Kind))...)

if len(validationErrors) != 0 {
return fmt.Errorf("Invalid Kind: %#v", validationErrors)
return fmt.Errorf("invalid Kind: %#v", validationErrors)
}

// TODO: validate plural strings if provided

return nil
}

// GVK returns the group-version-kind information to check against tracked resources in the configuration file
func (opts *Options) GVK() config.GVK {
return config.GVK{
Group: opts.Group,
Expand All @@ -163,6 +164,7 @@ func (opts *Options) safeImport(unsafe string) string {
return safe
}

// NewV1Resource creates a new resource from the options specific to v1
func (opts *Options) NewV1Resource(c *config.Config, doResource bool) *Resource {
res := opts.newResource()

Expand Down Expand Up @@ -199,6 +201,7 @@ func (opts *Options) NewV1Resource(c *config.Config, doResource bool) *Resource
return res
}

// NewResource creates a new resource from the options
func (opts *Options) NewResource(c *config.Config, doResource bool) *Resource {
res := opts.newResource()

Expand Down
2 changes: 1 addition & 1 deletion pkg/model/resource/options_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ var _ = Describe("Resource Options", func() {
It("should fail if Kind starts with a lowercase character", func() {
options := &Options{Group: "crew", Kind: "lOWERCASESTART", Version: "v1"}
err := options.Validate()
Expect(err).To(MatchError(ContainSubstring("Kind must start with an uppercase character")))
Expect(err).To(MatchError(ContainSubstring("kind must start with an uppercase character")))
})
})
})
1 change: 1 addition & 0 deletions pkg/model/resource/resource.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ type Resource struct {
CreateExampleReconcileBody bool `json:"-"`
}

// GVK returns the group-version-kind information to check against tracked resources in the configuration file
func (r *Resource) GVK() config.GVK {
return config.GVK{
Group: r.Group,
Expand Down
23 changes: 12 additions & 11 deletions pkg/model/universe.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,27 +78,28 @@ func WithResource(resource *resource.Resource) UniverseOption {
}
}

func (u Universe) InjectInto(t file.Builder) {
// InjectInto injects fields from the universe into the builder
func (u Universe) InjectInto(builder file.Builder) {
// Inject project configuration
if u.Config != nil {
if templateWithDomain, hasDomain := t.(file.HasDomain); hasDomain {
templateWithDomain.InjectDomain(u.Config.Domain)
if builderWithDomain, hasDomain := builder.(file.HasDomain); hasDomain {
builderWithDomain.InjectDomain(u.Config.Domain)
}
if templateWithRepository, hasRepository := t.(file.HasRepository); hasRepository {
templateWithRepository.InjectRepository(u.Config.Repo)
if builderWithRepository, hasRepository := builder.(file.HasRepository); hasRepository {
builderWithRepository.InjectRepository(u.Config.Repo)
}
if templateWithMultiGroup, hasMultiGroup := t.(file.HasMultiGroup); hasMultiGroup {
templateWithMultiGroup.InjectMultiGroup(u.Config.MultiGroup)
if builderWithMultiGroup, hasMultiGroup := builder.(file.HasMultiGroup); hasMultiGroup {
builderWithMultiGroup.InjectMultiGroup(u.Config.MultiGroup)
}
}
// Inject boilerplate
if templateWithBoilerplate, hasBoilerplate := t.(file.HasBoilerplate); hasBoilerplate {
templateWithBoilerplate.InjectBoilerplate(u.Boilerplate)
if builderWithBoilerplate, hasBoilerplate := builder.(file.HasBoilerplate); hasBoilerplate {
builderWithBoilerplate.InjectBoilerplate(u.Boilerplate)
}
// Inject resource
if u.Resource != nil {
if templateWithResource, hasResource := t.(file.HasResource); hasResource {
templateWithResource.InjectResource(u.Resource)
if builderWithResource, hasResource := builder.(file.HasResource); hasResource {
builderWithResource.InjectResource(u.Resource)
}
}
}
Loading

0 comments on commit ed8438e

Please sign in to comment.