Skip to content

Commit

Permalink
Add CI linter (kubernetes-sigs#699)
Browse files Browse the repository at this point in the history
Signed-off-by: Vince Prignano <[email protected]>
  • Loading branch information
vincepri authored and k8s-ci-robot committed Jan 28, 2019
1 parent 6205b2f commit 86f4e2c
Show file tree
Hide file tree
Showing 38 changed files with 253 additions and 101 deletions.
22 changes: 22 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
linters:
enable:
- govet
- gofmt
- goimports
- structcheck
- varcheck
- interfacer
- unconvert
- ineffassign
- goconst
- gocyclo
- misspell
- nakedret
- prealloc
- gosec
disable-all: true
# Run with --fast=false for more extensive checks
fast: true
issue:
max-same-issues: 0
max-per-linter: 0
13 changes: 13 additions & 0 deletions BUILD.bazel
Original file line number Diff line number Diff line change
@@ -1,7 +1,20 @@
load("@bazel_gazelle//:def.bzl", "gazelle")
load("//build:run_in_workspace_with_goroot.bzl", "workspace_binary")

# gazelle:prefix sigs.k8s.io/cluster-api
gazelle(
name = "gazelle",
external = "vendored",
)

workspace_binary(
name = "lint",
args = ["run"],
cmd = "@com_github_golangci_golangci-lint//cmd/golangci-lint",
)

workspace_binary(
name = "lint-full",
args = ["run --fast=false"],
cmd = "@com_github_golangci_golangci-lint//cmd/golangci-lint",
)
11 changes: 11 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,13 @@ fmt: ## Run go fmt against code
vet: ## Run go vet against code
go vet ./pkg/... ./cmd/...

.PHONY: lint
lint: dep-ensure ## Lint codebase
bazel run //:lint $(BAZEL_ARGS)

lint-full: dep-ensure ## Run slower linters to detect possible issues
bazel run //:lint-full $(BAZEL_ARGS)

.PHONY: generate
generate: clientset dep-ensure ## Generate code
go generate ./pkg/... ./cmd/...
Expand All @@ -92,6 +99,10 @@ clientset: ## Generate a typed clientset
--output-package sigs.k8s.io/cluster-api/pkg/client/informers_generated \
--go-header-file=./hack/boilerplate.go.txt

.PHONY: clean
clean: ## Remove all generated files
rm -f bazel-*

.PHONY: docker-build
docker-build: generate fmt vet manifests ## Build the docker image
docker build . -t ${IMG}
Expand Down
12 changes: 10 additions & 2 deletions WORKSPACE
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository")

http_archive(
name = "io_bazel_rules_go",
url = "https://github.com/bazelbuild/rules_go/releases/download/0.16.6/rules_go-0.16.6.tar.gz",
sha256 = "ade51a315fa17347e5c31201fdc55aa5ffb913377aa315dceb56ee9725e620ee",
url = "https://github.com/bazelbuild/rules_go/releases/download/0.16.6/rules_go-0.16.6.tar.gz",
)

http_archive(
Expand All @@ -12,7 +13,7 @@ http_archive(
urls = ["https://github.com/bazelbuild/bazel-gazelle/releases/download/0.15.0/bazel-gazelle-0.15.0.tar.gz"],
)

load("@io_bazel_rules_go//go:def.bzl", "go_rules_dependencies", "go_register_toolchains")
load("@io_bazel_rules_go//go:def.bzl", "go_register_toolchains", "go_rules_dependencies")

go_rules_dependencies()

Expand All @@ -29,3 +30,10 @@ go_repository(
commit = "58492e2d83c59ed63881311f46ad6251f77dabc3",
importpath = "sigs.k8s.io/kustomize",
)

go_repository(
name = "com_github_golangci_golangci-lint",
build_file_generation = "on",
importpath = "github.com/golangci/golangci-lint",
tag = "v1.13",
)
Empty file added build/BUILD
Empty file.
103 changes: 103 additions & 0 deletions build/run_in_workspace_with_goroot.bzl
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
# Copyright 2018 The Kubernetes Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# This is a modified version of the same rule from kubernetes/repo-infra
# modified to add the GO SDK to the PATH environment variable.

# Writes out a script which saves the runfiles directory,
# changes to the workspace root, and then runs a command.

def _workspace_binary_script_impl(ctx):
content = """#!/usr/bin/env bash
set -o errexit
set -o nounset
set -o pipefail
GOBINDIR=$(dirname $(readlink {go_bin}))
export PATH=$GOBINDIR:$PATH
BASE=$(pwd)
cd $(dirname $(readlink {root_file}))
"$BASE/{cmd}" $@
""".format(
cmd = ctx.file.cmd.short_path,
root_file = ctx.file.root_file.short_path,
go_bin = ctx.file.go_bin.short_path,
)
ctx.actions.write(
output = ctx.outputs.executable,
content = content,
is_executable = True,
)
runfiles = ctx.runfiles(
files = [
ctx.file.cmd,
ctx.file.go_bin,
ctx.file.root_file,
],
)
return [DefaultInfo(runfiles = runfiles)]

_workspace_binary_script = rule(
attrs = {
"cmd": attr.label(
mandatory = True,
allow_files = True,
single_file = True,
),
"root_file": attr.label(
mandatory = True,
allow_files = True,
single_file = True,
),
"go_bin": attr.label(
mandatory = True,
allow_files = True,
single_file = True,
),
},
executable = True,
implementation = _workspace_binary_script_impl,
)

# Wraps a binary to be run in the workspace root via bazel run.
#
# For example, one might do something like
#
# workspace_binary(
# name = "dep",
# cmd = "//vendor/github.com/golang/dep/cmd/dep",
# )
#
# which would allow running dep with bazel run.
def workspace_binary(
name,
cmd,
args = None,
visibility = None,
go_bin = "@go_sdk//:bin/go",
root_file = "//:WORKSPACE"):
script_name = name + "_script"
_workspace_binary_script(
name = script_name,
cmd = cmd,
root_file = root_file,
go_bin = go_bin,
tags = ["manual"],
)
native.sh_binary(
name = name,
srcs = [":" + script_name],
args = args,
visibility = visibility,
tags = ["manual"],
)
10 changes: 5 additions & 5 deletions cmd/clusterctl/clientcmd/configutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,10 @@ func NewCoreClientSetForDefaultSearchPath(kubeconfigPath string, overrides clien
return kubernetes.NewForConfig(config)
}

// NewClusterApiClientForDefaultSearchPath creates a Cluster API clientset. If the kubeconfigPath is specified then the configuration is loaded from that path.
// NewClusterAPIClientForDefaultSearchPath creates a Cluster API clientset. If the kubeconfigPath is specified then the configuration is loaded from that path.
// Otherwise the default kubeconfig search path is used.
// The overrides parameter is used to select a specific context of the config, for example, select the context with a given cluster name or namespace.
func NewClusterApiClientForDefaultSearchPath(kubeconfigPath string, overrides clientcmd.ConfigOverrides) (*clientset.Clientset, error) {
func NewClusterAPIClientForDefaultSearchPath(kubeconfigPath string, overrides clientcmd.ConfigOverrides) (*clientset.Clientset, error) {
config, err := newRestConfigForDefaultSearchPath(kubeconfigPath, overrides)
if err != nil {
return nil, err
Expand All @@ -72,16 +72,16 @@ func newRestConfigForDefaultSearchPath(kubeconfigPath string, overrides clientcm
return config, nil
}
}
apiConfig, err := newApiConfigForDefaultSearchPath(kubeconfigPath)
apiConfig, err := newAPIConfigForDefaultSearchPath(kubeconfigPath)
if err != nil {
return nil, err
}
return newRestConfig(apiConfig, overrides)
}

// newApiConfigForDefaultSearchPath creates an api.Config by searching for the kubeconfig on the default search path. If an override 'kubeconfigPath' is
// newAPIConfigForDefaultSearchPath creates an api.Config by searching for the kubeconfig on the default search path. If an override 'kubeconfigPath' is
// given then that path is used instead of the default path.
func newApiConfigForDefaultSearchPath(kubeconfigPath string) (*api.Config, error) {
func newAPIConfigForDefaultSearchPath(kubeconfigPath string) (*api.Config, error) {
configLoader := clientcmd.NewDefaultClientConfigLoadingRules()
configLoader.ExplicitPath = kubeconfigPath
return configLoader.Load()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ func createTempFile(contents string) (string, error) {
return "", err
}
defer f.Close()
f.WriteString(contents)
if _, err := f.WriteString(contents); err != nil {
return "", err
}
return f.Name(), nil
}
3 changes: 1 addition & 2 deletions cmd/clusterctl/clusterdeployer/bootstrap/kind/kind.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,7 @@ import (
)

const (
kubeconfigEnvVar = "KUBECONFIG"
kindClusterName = "clusterapi"
kindClusterName = "clusterapi"
)

type Kind struct {
Expand Down
4 changes: 3 additions & 1 deletion cmd/clusterctl/clusterdeployer/bootstrap/kind/kind_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,8 @@ func createTempFile(contents string) (string, error) {
return "", err
}
defer f.Close()
f.WriteString(contents)
if _, err := f.WriteString(contents); err != nil {
return "", err
}
return f.Name(), nil
}
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,8 @@ func createTempFile(contents string) (string, error) {
return "", err
}
defer f.Close()
f.WriteString(contents)
if _, err := f.WriteString(contents); err != nil {
return "", err
}
return f.Name(), nil
}
2 changes: 1 addition & 1 deletion cmd/clusterctl/clusterdeployer/bootstrap/provisioner.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,6 @@ func Get(o Options) (ClusterProvisioner, error) {
return existing.New(o.KubeConfig)
}

return nil, errors.New("no bootstrap provisioner specified, you can specify `--bootstrap-cluster-kubeconfig` to use an existing Kubernetes cluster or `--bootstrap-type` to use a built-in ephemeral cluster.")
return nil, errors.New("no bootstrap provisioner specified, you can specify `--bootstrap-cluster-kubeconfig` to use an existing Kubernetes cluster or `--bootstrap-type` to use a built-in ephemeral cluster")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ func (c *client) DeleteNamespace(namespaceName string) error {
// NewFromDefaultSearchPath creates and returns a Client. The kubeconfigFile argument is expected to be the path to a
// valid kubeconfig file.
func NewFromDefaultSearchPath(kubeconfigFile string, overrides tcmd.ConfigOverrides) (*client, error) {
c, err := clientcmd.NewClusterApiClientForDefaultSearchPath(kubeconfigFile, overrides)
c, err := clientcmd.NewClusterAPIClientForDefaultSearchPath(kubeconfigFile, overrides)
if err != nil {
return nil, err
}
Expand Down
18 changes: 9 additions & 9 deletions cmd/clusterctl/clusterdeployer/clusterdeployer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,7 @@ func (c *testClusterClient) DeleteNamespace(namespaceName string) error {
return nil
}

var ns []string
ns := make([]string, 0, len(c.namespaces))
for _, n := range c.namespaces {
if n == namespaceName {
continue
Expand Down Expand Up @@ -1210,15 +1210,15 @@ func generateTestNodeMachine(name string) *clusterv1.Machine {
}

func generateTestControlPlaneMachines(controlPlaneNames []string) []*clusterv1.Machine {
var controlPlanes []*clusterv1.Machine
controlPlanes := make([]*clusterv1.Machine, 0, len(controlPlaneNames))
for _, mn := range controlPlaneNames {
controlPlanes = append(controlPlanes, generateTestControlPlaneMachine(mn))
}
return controlPlanes
}

func generateTestNodeMachines(nodeNames []string) []*clusterv1.Machine {
var nodes []*clusterv1.Machine
nodes := make([]*clusterv1.Machine, 0, len(nodeNames))
for _, nn := range nodeNames {
nodes = append(nodes, generateTestNodeMachine(nn))
}
Expand Down Expand Up @@ -1247,8 +1247,8 @@ func generateMachines() []*clusterv1.Machine {

func newMachineSetsFixture() []*clusterv1.MachineSet {
return []*clusterv1.MachineSet{
&clusterv1.MachineSet{ObjectMeta: metav1.ObjectMeta{Name: "machine-set-name-1"}},
&clusterv1.MachineSet{ObjectMeta: metav1.ObjectMeta{Name: "machine-set-name-2"}},
{ObjectMeta: metav1.ObjectMeta{Name: "machine-set-name-1"}},
{ObjectMeta: metav1.ObjectMeta{Name: "machine-set-name-2"}},
}
}

Expand All @@ -1267,15 +1267,15 @@ func getClustersForNamespace(namespace string, count int) []*clusterv1.Cluster {

func newMachineDeploymentsFixture() []*clusterv1.MachineDeployment {
return []*clusterv1.MachineDeployment{
&clusterv1.MachineDeployment{ObjectMeta: metav1.ObjectMeta{Name: "machine-deployment-name-1"}},
&clusterv1.MachineDeployment{ObjectMeta: metav1.ObjectMeta{Name: "machine-deployment-name-2"}},
{ObjectMeta: metav1.ObjectMeta{Name: "machine-deployment-name-1"}},
{ObjectMeta: metav1.ObjectMeta{Name: "machine-deployment-name-2"}},
}
}

func newClustersFixture() []*clusterv1.Cluster {
return []*clusterv1.Cluster{
&clusterv1.Cluster{ObjectMeta: metav1.ObjectMeta{Name: "cluster-name-1"}},
&clusterv1.Cluster{ObjectMeta: metav1.ObjectMeta{Name: "cluster-name-2"}},
{ObjectMeta: metav1.ObjectMeta{Name: "cluster-name-1"}},
{ObjectMeta: metav1.ObjectMeta{Name: "cluster-name-2"}},
}
}

Expand Down
3 changes: 1 addition & 2 deletions cmd/clusterctl/cmd/alpha_phase_create_bootstrap_cluster.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,10 @@ limitations under the License.
package cmd

import (
"sigs.k8s.io/cluster-api/cmd/clusterctl/clusterdeployer/bootstrap"

"github.com/pkg/errors"
"github.com/spf13/cobra"
"k8s.io/klog"
"sigs.k8s.io/cluster-api/cmd/clusterctl/clusterdeployer/bootstrap"
"sigs.k8s.io/cluster-api/cmd/clusterctl/clusterdeployer/clusterclient"
"sigs.k8s.io/cluster-api/cmd/clusterctl/phases"
)
Expand Down
4 changes: 2 additions & 2 deletions cmd/clusterctl/validation/validate_cluster_api_objects.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ func ValidateClusterAPIObjects(w io.Writer, c client.Client, clusterName string,
return validateMachineObjects(w, machines, c)
}

func getClusterObject(c client.Client, clusterName string, namespace string) (*v1alpha1.Cluster, error) {
func getClusterObject(c client.Reader, clusterName string, namespace string) (*v1alpha1.Cluster, error) {
if clusterName != "" {
cluster := &clusterv1alpha1.Cluster{}
err := c.Get(context.TODO(), types.NamespacedName{Name: clusterName, Namespace: namespace}, cluster)
Expand Down Expand Up @@ -97,7 +97,7 @@ func validateMachineObjects(w io.Writer, machines *v1alpha1.MachineList, client
func validateMachineObject(w io.Writer, machine v1alpha1.Machine, client client.Client) bool {
fmt.Fprintf(w, "Checking machine object %q... ", machine.Name)
if machine.Status.ErrorReason != nil || machine.Status.ErrorMessage != nil {
var reason common.MachineStatusError = ""
var reason common.MachineStatusError
if machine.Status.ErrorReason != nil {
reason = *machine.Status.ErrorReason
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import (
"path"
"testing"

"k8s.io/api/core/v1"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/cluster-api/pkg/apis/cluster/common"
Expand Down
Loading

0 comments on commit 86f4e2c

Please sign in to comment.