Merge pull request #958 from captainroy-hy/static-check-action

add staticcheck CI action
This commit is contained in:
Jianbo Sun
2021-01-29 18:14:56 +08:00
committed by GitHub
43 changed files with 136 additions and 115 deletions
+20 -1
View File
@@ -114,6 +114,25 @@ jobs:
- name: Run e2e tests
run: make e2e-test
staticcheck:
runs-on: ubuntu-20.04
steps:
- name: Checkout
uses: actions/checkout@v2
with:
submodules: true
- name: Cache Go Dependencies
uses: actions/cache@v2
with:
path: .work/pkg
key: ${{ runner.os }}-pkg-${{ hashFiles('**/go.sum') }}
restore-keys: ${{ runner.os }}-pkg-
- name: Static Check
run: go run honnef.co/go/tools/cmd/staticcheck -- ./...
lint:
runs-on: ubuntu-20.04
@@ -164,4 +183,4 @@ jobs:
run: go install golang.org/x/tools/cmd/goimports && make fmt
- name: Check Diff
run: make check-diff
run: make check-diff
+19 -3
View File
@@ -37,12 +37,12 @@ endif
all: build
# Run tests
test: vet lint
test: vet lint staticcheck
go test -race -coverprofile=coverage.txt -covermode=atomic ./pkg/... ./cmd/...
@$(OK) unit-tests pass
# Build manager binary
build: fmt vet lint
build: fmt vet lint staticcheck
go run hack/chart/generate.go
go build -o bin/vela -ldflags ${LDFLAGS} cmd/vela/main.go
git checkout cmd/vela/fake/chart_source.go
@@ -102,10 +102,13 @@ fmt: goimports installcue
vet:
go vet ./...
staticcheck: staticchecktool
$(STATICCHECK) ./...
lint: golangci
$(GOLANGCILINT) run ./...
reviewable: manifests fmt vet lint
reviewable: manifests fmt vet lint staticcheck
go mod tidy
# Execute auto-gen code commands and ensure branch is clean.
@@ -206,6 +209,19 @@ else
GOLANGCILINT=$(shell which golangci-lint)
endif
.PHONY: staticchecktool
staticchecktool:
ifeq (, $(shell which staticcheck))
@{ \
set -e ;\
echo 'installing honnef.co/go/tools/cmd/staticcheck ' ;\
GO111MODULE=off go get honnef.co/go/tools/cmd/staticcheck ;\
}
STATICCHECK=$(GOBIN)/staticcheck
else
STATICCHECK=$(shell which staticcheck)
endif
.PHONY: goimports
goimports:
ifeq (, $(shell which goimports))
@@ -18,7 +18,6 @@ package v1alpha1
import (
"github.com/crossplane/crossplane-runtime/apis/core/v1alpha1"
runtimev1alpha1 "github.com/crossplane/crossplane-runtime/apis/core/v1alpha1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
@@ -91,7 +90,7 @@ type AutoscalerSpec struct {
TargetWorkload TargetWorkload `json:"targetWorkload,omitempty"`
// WorkloadReference marks the owner of the workload
WorkloadReference runtimev1alpha1.TypedReference `json:"workloadRef,omitempty"`
WorkloadReference v1alpha1.TypedReference `json:"workloadRef,omitempty"`
}
// TargetWorkload holds the a reference to the scale target Object
@@ -105,7 +104,7 @@ type TargetWorkload struct {
// AutoscalerStatus defines the observed state of Autoscaler
type AutoscalerStatus struct {
runtimev1alpha1.ConditionedStatus `json:",inline"`
v1alpha1.ConditionedStatus `json:",inline"`
}
// +kubebuilder:object:root=true
-2
View File
@@ -2135,8 +2135,6 @@ golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJ
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9 h1:SQFwaSi55rU7vdNs9Yr0Z324VNlrF+0wMqRXT4St8ck=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20200826173525-f9321e4c35a6 h1:DvY3Zkh7KabQE/kfzMvYvKirSiguP9Q/veMtkYyf0o8=
golang.org/x/sys v0.0.0-20200826173525-f9321e4c35a6 h1:DvY3Zkh7KabQE/kfzMvYvKirSiguP9Q/veMtkYyf0o8=
golang.org/x/sys v0.0.0-20200826173525-f9321e4c35a6/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200826173525-f9321e4c35a6/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 h1:v+OssWQX+hTHEmOBgwxdZxK4zHq3yOs8F9J7mk0PY8E=
+1 -1
View File
@@ -125,7 +125,7 @@ func generateSecretFromTerraformOutput(k8sClient client.Client, outputList []str
for _, i := range outputList {
line := strings.Split(i, "=")
if len(line) != 2 {
return fmt.Errorf("Terraform output isn't in the right format")
return fmt.Errorf("terraform output isn't in the right format")
}
k := strings.TrimSpace(line[0])
v := strings.TrimSpace(line[1])
+1 -1
View File
@@ -45,7 +45,7 @@ func TestAppFile(t *testing.T) {
}
var _ = BeforeSuite(func(done Done) {
logf.SetLogger(zap.LoggerTo(GinkgoWriter, true))
logf.SetLogger(zap.New(zap.UseDevMode(true), zap.WriteTo(GinkgoWriter)))
ctx := context.Background()
By("bootstrapping test environment")
useExistCluster := false
+1 -1
View File
@@ -46,6 +46,6 @@ var _ = Describe("Test generateSecretFromTerraformOutput", func() {
It("invalid output list", func() {
outputList := []string{"name"}
err := generateSecretFromTerraformOutput(k8sClient, outputList, name, addonNamespace)
Expect(err).Should(Equal(fmt.Errorf("Terraform output isn't in the right format")))
Expect(err).Should(Equal(fmt.Errorf("terraform output isn't in the right format")))
})
})
+4 -5
View File
@@ -9,7 +9,6 @@ import (
"github.com/stretchr/testify/assert"
v12 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"github.com/oam-dev/kubevela/apis/core.oam.dev/v1alpha2"
@@ -51,10 +50,10 @@ func TestBuildOAMApplication2(t *testing.T) {
},
},
expectApp: &v1alpha2.Application{
TypeMeta: v1.TypeMeta{
TypeMeta: metav1.TypeMeta{
Kind: "Application",
APIVersion: "core.oam.dev/v1alpha2",
}, ObjectMeta: v1.ObjectMeta{
}, ObjectMeta: metav1.ObjectMeta{
Name: "test",
},
Spec: v1alpha2.ApplicationSpec{
@@ -85,10 +84,10 @@ func TestBuildOAMApplication2(t *testing.T) {
},
},
expectApp: &v1alpha2.Application{
TypeMeta: v1.TypeMeta{
TypeMeta: metav1.TypeMeta{
Kind: "Application",
APIVersion: "core.oam.dev/v1alpha2",
}, ObjectMeta: v1.ObjectMeta{
}, ObjectMeta: metav1.ObjectMeta{
Name: "test",
},
Spec: v1alpha2.ApplicationSpec{
+1 -1
View File
@@ -110,7 +110,7 @@ func getApplicationDir(envName string) (string, error) {
appDir := filepath.Join(env.GetEnvDirByName(envName), "applications")
_, err := system.CreateIfNotExist(appDir)
if err != nil {
err = fmt.Errorf("Getting application directory from env %s failed, error: %w ", envName, err)
err = fmt.Errorf("getting application directory from env %s failed, error: %w ", envName, err)
}
return appDir, err
}
+1 -1
View File
@@ -24,7 +24,7 @@ func init() {
tm, _ = template.Load()
afile = api.NewAppFile()
afile.Name = appName
svcs := make(map[string]api.Service, 0)
svcs := make(map[string]api.Service)
svcs["wordpress"] = map[string]interface{}{
"type": "webservice",
"image": "wordpress:php7.4-apache",
+4 -5
View File
@@ -30,7 +30,6 @@ import (
"github.com/stretchr/testify/assert"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
@@ -372,10 +371,10 @@ var _ = Describe("Test appFile parser", func() {
ac, components, err := NewApplicationParser(k8sClient, nil).GenerateApplicationConfiguration(TestApp, "default")
Expect(err).To(BeNil())
expectAppConfig := &v1alpha2.ApplicationConfiguration{
TypeMeta: v1.TypeMeta{
TypeMeta: metav1.TypeMeta{
Kind: "ApplicationConfiguration",
APIVersion: "core.oam.dev/v1alpha2",
}, ObjectMeta: v1.ObjectMeta{
}, ObjectMeta: metav1.ObjectMeta{
Name: "test",
Namespace: "default",
Labels: map[string]string{"application.oam.dev": "test"},
@@ -417,10 +416,10 @@ var _ = Describe("Test appFile parser", func() {
Expect(ac).To(BeEquivalentTo(expectAppConfig))
expectComponent := &v1alpha2.Component{
TypeMeta: v1.TypeMeta{
TypeMeta: metav1.TypeMeta{
Kind: "Component",
APIVersion: "core.oam.dev/v1alpha2",
}, ObjectMeta: v1.ObjectMeta{
}, ObjectMeta: metav1.ObjectMeta{
Name: "myweb",
Namespace: "default",
Labels: map[string]string{"application.oam.dev": "test"},
+1
View File
@@ -84,6 +84,7 @@ func newCallCtx(io util.IOStreams, data map[string]interface{}) CallCtx {
}
}
// Run executes tasks
// Deprecated: Run is deprecated, you should use DoTasks is builtin package, it will automatically register all internal functions
func Run(spec map[string]interface{}, io util.IOStreams) (map[string]interface{}, error) {
var (
+1 -1
View File
@@ -20,7 +20,7 @@ type Meta struct {
Err error
}
// LookupRunner fetch the value of context by filed
// Lookup fetches the value of context by filed
func (m *Meta) Lookup(field string) cue.Value {
f := m.Obj.Lookup(field)
if !f.Exists() {
+1 -2
View File
@@ -18,7 +18,6 @@ import (
"github.com/oam-dev/kubevela/pkg/appfile"
"github.com/oam-dev/kubevela/pkg/appfile/api"
"github.com/oam-dev/kubevela/pkg/commands/util"
velacmdutil "github.com/oam-dev/kubevela/pkg/commands/util"
"github.com/oam-dev/kubevela/pkg/oam"
)
@@ -48,7 +47,7 @@ type VelaExecOptions struct {
}
// NewExecCommand creates `exec` command
func NewExecCommand(c types.Args, ioStreams velacmdutil.IOStreams) *cobra.Command {
func NewExecCommand(c types.Args, ioStreams util.IOStreams) *cobra.Command {
o := &VelaExecOptions{
kcExecOptions: &cmdexec.ExecOptions{
StreamOptions: cmdexec.StreamOptions{
+2 -3
View File
@@ -19,11 +19,10 @@ import (
"github.com/oam-dev/kubevela/pkg/appfile"
"github.com/oam-dev/kubevela/pkg/appfile/api"
"github.com/oam-dev/kubevela/pkg/commands/util"
cmdutil "github.com/oam-dev/kubevela/pkg/commands/util"
)
// NewLogsCommand creates `logs` command to tail logs of application
func NewLogsCommand(c types.Args, ioStreams cmdutil.IOStreams) *cobra.Command {
func NewLogsCommand(c types.Args, ioStreams util.IOStreams) *cobra.Command {
largs := &Args{C: c}
cmd := &cobra.Command{}
cmd.Use = "logs"
@@ -73,7 +72,7 @@ type Args struct {
}
// Run refer to the implementation at https://github.com/oam-dev/stern/blob/master/stern/main.go
func (l *Args) Run(ctx context.Context, ioStreams cmdutil.IOStreams) error {
func (l *Args) Run(ctx context.Context, ioStreams util.IOStreams) error {
clientSet, err := kubernetes.NewForConfig(l.C.Config)
if err != nil {
+3 -4
View File
@@ -27,7 +27,6 @@ import (
"github.com/oam-dev/kubevela/pkg/appfile"
"github.com/oam-dev/kubevela/pkg/appfile/api"
"github.com/oam-dev/kubevela/pkg/commands/util"
velacmdutil "github.com/oam-dev/kubevela/pkg/commands/util"
"github.com/oam-dev/kubevela/pkg/oam"
)
@@ -35,7 +34,7 @@ import (
type VelaPortForwardOptions struct {
Cmd *cobra.Command
Args []string
ioStreams velacmdutil.IOStreams
ioStreams util.IOStreams
context.Context
VelaC types.Args
@@ -50,7 +49,7 @@ type VelaPortForwardOptions struct {
}
// NewPortForwardCommand is vela port-forward command
func NewPortForwardCommand(c types.Args, ioStreams velacmdutil.IOStreams) *cobra.Command {
func NewPortForwardCommand(c types.Args, ioStreams util.IOStreams) *cobra.Command {
o := &VelaPortForwardOptions{
ioStreams: ioStreams,
kcPortForwardOptions: &cmdpf.PortForwardOptions{
@@ -268,7 +267,7 @@ func splitPort(port string) (local, remote string) {
}
type defaultPortForwarder struct {
velacmdutil.IOStreams
util.IOStreams
}
func (f *defaultPortForwarder) ForwardPorts(method string, url *url.URL, opts cmdpf.PortForwardOptions) error {
+2 -6
View File
@@ -7,8 +7,6 @@ import (
"github.com/spf13/cobra"
"github.com/stretchr/testify/assert"
"k8s.io/client-go/kubernetes/scheme"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
"github.com/oam-dev/kubevela/apis/core.oam.dev/v1alpha2"
"github.com/oam-dev/kubevela/apis/types"
@@ -17,7 +15,6 @@ import (
)
func TestUp(t *testing.T) {
client := fake.NewFakeClientWithScheme(scheme.Scheme)
ioStream := util.IOStreams{In: os.Stdin, Out: os.Stdout, ErrOut: os.Stderr}
env := types.EnvMeta{
Name: "up",
@@ -25,9 +22,8 @@ func TestUp(t *testing.T) {
Issuer: "up",
}
o := serverlib.AppfileOptions{
Kubecli: client,
IO: ioStream,
Env: &env,
IO: ioStream,
Env: &env,
}
app := &v1alpha2.Application{}
app.Name = "app-up"
+1 -2
View File
@@ -4,7 +4,6 @@ import (
"context"
corev1 "k8s.io/api/core/v1"
v1 "k8s.io/api/core/v1"
"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@@ -27,7 +26,7 @@ func DoesNamespaceExist(c client.Client, namespace string) (bool, error) {
// NewNamespace create namespace
func NewNamespace(c client.Client, namespace string) error {
ns := &v1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: namespace,
ns := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: namespace,
// marking a special label for prometheus monitoring.
Labels: OAMLabel}}
err := c.Create(context.Background(), ns)
+2
View File
@@ -11,6 +11,8 @@ import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
//lint:ignore SA1019 We will use pkg/envtest before upgrading controller-runtime to v1.0.0
"sigs.k8s.io/controller-runtime/pkg/client/fake"
)
@@ -33,7 +33,6 @@ import (
"sigs.k8s.io/controller-runtime/pkg/source"
"github.com/crossplane/crossplane-runtime/apis/core/v1alpha1"
runtimev1alpha1 "github.com/crossplane/crossplane-runtime/apis/core/v1alpha1"
"github.com/crossplane/crossplane-runtime/pkg/event"
"github.com/crossplane/crossplane-runtime/pkg/logging"
"github.com/crossplane/crossplane-runtime/pkg/meta"
@@ -473,7 +472,7 @@ func (w Workload) Status() v1alpha2.WorkloadStatus {
acw := v1alpha2.WorkloadStatus{
ComponentName: w.ComponentName,
ComponentRevisionName: w.ComponentRevisionName,
Reference: runtimev1alpha1.TypedReference{
Reference: v1alpha1.TypedReference{
APIVersion: w.Workload.GetAPIVersion(),
Kind: w.Workload.GetKind(),
Name: w.Workload.GetName(),
@@ -485,14 +484,14 @@ func (w Workload) Status() v1alpha2.WorkloadStatus {
if tr.Definition.Name == util.Dummy && tr.Definition.Spec.Reference.Name == util.Dummy {
acw.Traits[i].Message = util.DummyTraitMessage
}
acw.Traits[i].Reference = runtimev1alpha1.TypedReference{
acw.Traits[i].Reference = v1alpha1.TypedReference{
APIVersion: w.Traits[i].Object.GetAPIVersion(),
Kind: w.Traits[i].Object.GetKind(),
Name: w.Traits[i].Object.GetName(),
}
}
for i, s := range w.Scopes {
acw.Scopes[i].Reference = runtimev1alpha1.TypedReference{
acw.Scopes[i].Reference = v1alpha1.TypedReference{
APIVersion: s.GetAPIVersion(),
Kind: s.GetKind(),
Name: s.GetName(),
@@ -523,16 +522,16 @@ func IsRevisionWorkload(status v1alpha2.WorkloadStatus) bool {
}
func eligible(namespace string, ws []v1alpha2.WorkloadStatus, w []Workload) []unstructured.Unstructured {
applied := make(map[runtimev1alpha1.TypedReference]bool)
applied := make(map[v1alpha1.TypedReference]bool)
for _, wl := range w {
r := runtimev1alpha1.TypedReference{
r := v1alpha1.TypedReference{
APIVersion: wl.Workload.GetAPIVersion(),
Kind: wl.Workload.GetKind(),
Name: wl.Workload.GetName(),
}
applied[r] = true
for _, t := range wl.Traits {
r := runtimev1alpha1.TypedReference{
r := v1alpha1.TypedReference{
APIVersion: t.Object.GetAPIVersion(),
Kind: t.Object.GetKind(),
Name: t.Object.GetName(),
@@ -10,7 +10,6 @@ import (
"github.com/crossplane/crossplane-runtime/pkg/test"
"github.com/stretchr/testify/assert"
appsv1 "k8s.io/api/apps/v1"
v1 "k8s.io/api/apps/v1"
v12 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
@@ -112,7 +111,7 @@ func TestComponentHandler(t *testing.T) {
}
comp := &v1alpha2.Component{
ObjectMeta: metav1.ObjectMeta{Namespace: "biz", Name: "comp1", Generation: 1},
Spec: v1alpha2.ComponentSpec{Workload: runtime.RawExtension{Object: &v1.Deployment{Spec: v1.DeploymentSpec{Template: v12.PodTemplateSpec{Spec: v12.PodSpec{Containers: []v12.Container{{Image: "nginx:v1"}}}}}}}},
Spec: v1alpha2.ComponentSpec{Workload: runtime.RawExtension{Object: &appsv1.Deployment{Spec: appsv1.DeploymentSpec{Template: v12.PodTemplateSpec{Spec: v12.PodSpec{Containers: []v12.Container{{Image: "nginx:v1"}}}}}}}},
}
// ============ Test Create Event Start ===================
@@ -148,7 +147,7 @@ func TestComponentHandler(t *testing.T) {
comp2 := &v1alpha2.Component{
ObjectMeta: metav1.ObjectMeta{Namespace: "biz", Name: "comp1"},
// change image
Spec: v1alpha2.ComponentSpec{Workload: runtime.RawExtension{Object: &v1.Deployment{Spec: v1.DeploymentSpec{Template: v12.PodTemplateSpec{Spec: v12.PodSpec{Containers: []v12.Container{{Image: "nginx:v2"}}}}}}}},
Spec: v1alpha2.ComponentSpec{Workload: runtime.RawExtension{Object: &appsv1.Deployment{Spec: appsv1.DeploymentSpec{Template: v12.PodTemplateSpec{Spec: v12.PodSpec{Containers: []v12.Container{{Image: "nginx:v2"}}}}}}}},
}
curComp.Status.DeepCopyInto(&comp2.Status)
updateEvt := event.UpdateEvent{
@@ -185,7 +184,7 @@ func TestComponentHandler(t *testing.T) {
// test no changes with component spec
comp3 := &v1alpha2.Component{
ObjectMeta: metav1.ObjectMeta{Namespace: "biz", Name: "comp1", Labels: map[string]string{"bar": "foo"}},
Spec: v1alpha2.ComponentSpec{Workload: runtime.RawExtension{Object: &v1.Deployment{Spec: v1.DeploymentSpec{Template: v12.PodTemplateSpec{Spec: v12.PodSpec{Containers: []v12.Container{{Image: "nginx:v2"}}}}}}}},
Spec: v1alpha2.ComponentSpec{Workload: runtime.RawExtension{Object: &appsv1.Deployment{Spec: appsv1.DeploymentSpec{Template: v12.PodTemplateSpec{Spec: v12.PodSpec{Containers: []v12.Container{{Image: "nginx:v2"}}}}}}}},
}
curComp.Status.DeepCopyInto(&comp3.Status)
updateEvt = event.UpdateEvent{
@@ -204,7 +203,7 @@ func TestComponentHandler(t *testing.T) {
// test clean revision
comp4 := &v1alpha2.Component{
ObjectMeta: metav1.ObjectMeta{Namespace: "biz", Name: "comp1", Labels: map[string]string{"bar": "foo"}},
Spec: v1alpha2.ComponentSpec{Workload: runtime.RawExtension{Object: &v1.Deployment{Spec: v1.DeploymentSpec{Template: v12.PodTemplateSpec{Spec: v12.PodSpec{Containers: []v12.Container{{Image: "nginx:v3"}}}}}}}},
Spec: v1alpha2.ComponentSpec{Workload: runtime.RawExtension{Object: &appsv1.Deployment{Spec: appsv1.DeploymentSpec{Template: v12.PodTemplateSpec{Spec: v12.PodSpec{Containers: []v12.Container{{Image: "nginx:v3"}}}}}}}},
}
curComp.Status.DeepCopyInto(&comp4.Status)
updateEvt = event.UpdateEvent{
@@ -22,7 +22,6 @@ import (
"testing"
"github.com/crossplane/crossplane-runtime/apis/core/v1alpha1"
runtimev1alpha1 "github.com/crossplane/crossplane-runtime/apis/core/v1alpha1"
"github.com/crossplane/crossplane-runtime/pkg/fieldpath"
"github.com/crossplane/crossplane-runtime/pkg/test"
"github.com/google/go-cmp/cmp"
@@ -506,7 +505,7 @@ func TestRenderComponents(t *testing.T) {
oam.LabelAppComponentRevision: revisionName,
oam.LabelOAMResourceType: oam.ResourceTypeTrait,
})
workloadRef := runtimev1alpha1.TypedReference{
workloadRef := v1alpha1.TypedReference{
APIVersion: "traitApiVersion",
Kind: "traitKind",
Name: componentName,
@@ -34,7 +34,7 @@ func TestAPIs(t *testing.T) {
}
var _ = BeforeSuite(func(done Done) {
logf.SetLogger(zap.LoggerTo(GinkgoWriter, true))
logf.SetLogger(zap.New(zap.UseDevMode(true), zap.WriteTo(GinkgoWriter)))
By("bootstrapping test environment")
testEnv = &envtest.Environment{
@@ -35,7 +35,6 @@ import (
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/oam-dev/kubevela/apis/core.oam.dev/v1alpha2"
corev1alpha2 "github.com/oam-dev/kubevela/apis/core.oam.dev/v1alpha2"
"github.com/oam-dev/kubevela/pkg/oam"
@@ -65,7 +64,7 @@ const (
)
var (
kindContainerizedWorkload = corev1alpha2.ContainerizedWorkloadKind
kindContainerizedWorkload = v1alpha2.ContainerizedWorkloadKind
kindDeployment = reflect.TypeOf(apps.Deployment{}).Name()
kindService = reflect.TypeOf(core.Service{}).Name()
kindStatefulSet = reflect.TypeOf(apps.StatefulSet{}).Name()
@@ -119,7 +118,7 @@ func (fn WorkloadHealthCheckFn) Check(ctx context.Context, c client.Client, tr r
// CheckContainerziedWorkloadHealth check health condition of ContainerizedWorkload
func CheckContainerziedWorkloadHealth(ctx context.Context, c client.Client, ref runtimev1alpha1.TypedReference, namespace string) *WorkloadHealthCondition {
if ref.GroupVersionKind() != corev1alpha2.SchemeGroupVersion.WithKind(kindContainerizedWorkload) {
if ref.GroupVersionKind() != v1alpha2.SchemeGroupVersion.WithKind(kindContainerizedWorkload) {
return nil
}
r := &WorkloadHealthCondition{
@@ -127,8 +126,8 @@ func CheckContainerziedWorkloadHealth(ctx context.Context, c client.Client, ref
TargetWorkload: ref,
}
cwObj := corev1alpha2.ContainerizedWorkload{}
cwObj.SetGroupVersionKind(corev1alpha2.SchemeGroupVersion.WithKind(kindContainerizedWorkload))
cwObj := v1alpha2.ContainerizedWorkload{}
cwObj.SetGroupVersionKind(v1alpha2.SchemeGroupVersion.WithKind(kindContainerizedWorkload))
if err := c.Get(ctx, types.NamespacedName{Namespace: namespace, Name: ref.Name}, &cwObj); err != nil {
r.HealthStatus = StatusUnhealthy
r.Diagnosis = errors.Wrap(err, errHealthCheck).Error()
@@ -25,7 +25,6 @@ import (
"github.com/crossplane/crossplane-runtime/pkg/test"
"github.com/oam-dev/kubevela/apis/core.oam.dev/v1alpha2"
corev1alpha2 "github.com/oam-dev/kubevela/apis/core.oam.dev/v1alpha2"
"github.com/oam-dev/kubevela/pkg/oam/mock"
"github.com/oam-dev/kubevela/pkg/oam/util"
@@ -59,7 +58,7 @@ var _ = Describe("HealthScope Controller Reconcile Test", func() {
WithChecker(MockHealthyChecker),
)
hs := v1alpha2.HealthScope{Spec: corev1alpha2.HealthScopeSpec{WorkloadReferences: []v1alpha1.TypedReference{
hs := v1alpha2.HealthScope{Spec: v1alpha2.HealthScopeSpec{WorkloadReferences: []v1alpha1.TypedReference{
// add one wlRef to trigger mockChecker
{
APIVersion: "mock",
@@ -155,14 +154,14 @@ var _ = Describe("Test GetScopeHealthStatus", func() {
hs := v1alpha2.HealthScope{}
var cwRef, deployRef, svcRef v1alpha1.TypedReference
cwRef.SetGroupVersionKind(corev1alpha2.SchemeGroupVersion.WithKind(kindContainerizedWorkload))
cwRef.SetGroupVersionKind(v1alpha2.SchemeGroupVersion.WithKind(kindContainerizedWorkload))
cwRef.Name = "cw"
deployRef.SetGroupVersionKind(appsv1.SchemeGroupVersion.WithKind(kindDeployment))
deployRef.Name = "deploy"
svcRef.SetGroupVersionKind(appsv1.SchemeGroupVersion.WithKind(kindService))
cw := corev1alpha2.ContainerizedWorkload{}
cw.SetGroupVersionKind(corev1alpha2.SchemeGroupVersion.WithKind(kindContainerizedWorkload))
cw := v1alpha2.ContainerizedWorkload{}
cw.SetGroupVersionKind(v1alpha2.SchemeGroupVersion.WithKind(kindContainerizedWorkload))
cw.Status.Resources = []v1alpha1.TypedReference{deployRef, svcRef}
hDeploy := appsv1.Deployment{
@@ -210,7 +209,7 @@ var _ = Describe("Test GetScopeHealthStatus", func() {
caseName: "2 supportted workloads(cw,deploy)",
hsWorkloadRefs: []v1alpha1.TypedReference{cwRef, deployRef},
mockGetFn: func(ctx context.Context, key types.NamespacedName, obj runtime.Object) error {
if o, ok := obj.(*corev1alpha2.ContainerizedWorkload); ok {
if o, ok := obj.(*v1alpha2.ContainerizedWorkload); ok {
*o = cw
}
if o, ok := obj.(*appsv1.Deployment); ok {
@@ -253,7 +252,7 @@ var _ = Describe("Test GetScopeHealthStatus", func() {
hsWorkloadRefs: []v1alpha1.TypedReference{cwRef, deployRef},
mockGetFn: func(ctx context.Context, key types.NamespacedName, obj runtime.Object) error {
switch o := obj.(type) {
case *corev1alpha2.ContainerizedWorkload:
case *v1alpha2.ContainerizedWorkload:
*o = cw
case *appsv1.Deployment:
*o = hDeploy
@@ -279,7 +278,7 @@ var _ = Describe("Test GetScopeHealthStatus", func() {
hsWorkloadRefs: []v1alpha1.TypedReference{cwRef, uhGeneralRef},
mockGetFn: func(ctx context.Context, key types.NamespacedName, obj runtime.Object) error {
switch o := obj.(type) {
case *corev1alpha2.ContainerizedWorkload:
case *v1alpha2.ContainerizedWorkload:
*o = cw
case *appsv1.Deployment:
*o = hDeploy
@@ -34,7 +34,6 @@ import (
"github.com/oam-dev/kubevela/pkg/controller/common"
"github.com/oam-dev/kubevela/pkg/oam/discoverymapper"
"github.com/oam-dev/kubevela/pkg/oam/util"
oamutil "github.com/oam-dev/kubevela/pkg/oam/util"
)
// nolint:golint
@@ -88,13 +87,13 @@ func (r *Reconciler) Reconcile(req ctrl.Request) (ctrl.Result, error) {
}
// Fetch the instance to which the trait refers to
workload, err := oamutil.FetchWorkload(ctx, r, log, &scaler)
workload, err := util.FetchWorkload(ctx, r, log, &scaler)
if err != nil {
log.Error(err, "Error while fetching the workload", "workload reference",
scaler.GetWorkloadReference())
r.record.Event(&scaler, event.Warning(common.ErrLocatingWorkload, err))
return oamutil.ReconcileWaitResult,
oamutil.PatchCondition(ctx, r, &scaler,
return util.ReconcileWaitResult,
util.PatchCondition(ctx, r, &scaler,
cpv1alpha1.ReconcileError(errors.Wrap(err, common.ErrLocatingWorkload)))
}
@@ -50,7 +50,7 @@ func TestAPIs(t *testing.T) {
}
var _ = BeforeSuite(func(done Done) {
logf.SetLogger(zap.LoggerTo(GinkgoWriter, true))
logf.SetLogger(zap.New(zap.UseDevMode(true), zap.WriteTo(GinkgoWriter)))
By("bootstrapping test environment")
testEnv = &envtest.Environment{
@@ -50,7 +50,7 @@ func TestAPIs(t *testing.T) {
}
var _ = BeforeSuite(func(done Done) {
logf.SetLogger(zap.LoggerTo(GinkgoWriter, true))
logf.SetLogger(zap.New(zap.UseDevMode(true), zap.WriteTo(GinkgoWriter)))
By("bootstrapping test environment")
testEnv = &envtest.Environment{
@@ -29,7 +29,6 @@ import (
"github.com/oam-dev/kubevela/pkg/controller/common"
"github.com/oam-dev/kubevela/pkg/controller/standard.oam.dev/v1alpha1/routes/ingress"
cpv1alpha1 "github.com/crossplane/crossplane-runtime/apis/core/v1alpha1"
runtimev1alpha1 "github.com/crossplane/crossplane-runtime/apis/core/v1alpha1"
"github.com/crossplane/crossplane-runtime/pkg/event"
"github.com/go-logr/logr"
@@ -98,13 +97,13 @@ func (r *Reconciler) Reconcile(req ctrl.Request) (ctrl.Result, error) {
r.record.Event(eventObj, event.Warning(common.ErrLocatingWorkload, err))
return oamutil.ReconcileWaitResult,
oamutil.PatchCondition(ctx, r, &routeTrait,
cpv1alpha1.ReconcileError(errors.Wrap(err, common.ErrLocatingWorkload)))
runtimev1alpha1.ReconcileError(errors.Wrap(err, common.ErrLocatingWorkload)))
}
var svc *runtimev1alpha1.TypedReference
if NeedDiscovery(&routeTrait) {
if svc, err = r.discoveryAndFillBackend(ctx, mLog, eventObj, workload, &routeTrait); err != nil {
return oamutil.ReconcileWaitResult, oamutil.PatchCondition(ctx, r, &routeTrait,
cpv1alpha1.ReconcileError(err))
runtimev1alpha1.ReconcileError(err))
}
}
@@ -125,7 +124,7 @@ func (r *Reconciler) Reconcile(req ctrl.Request) (ctrl.Result, error) {
r.record.Event(eventObj, event.Warning(errApplyNginxIngress, err))
return oamutil.ReconcileWaitResult,
oamutil.PatchCondition(ctx, r, &routeTrait,
cpv1alpha1.ReconcileError(errors.Wrap(err, errApplyNginxIngress)))
runtimev1alpha1.ReconcileError(errors.Wrap(err, errApplyNginxIngress)))
}
r.record.Event(eventObj, event.Normal("nginx ingress patched",
fmt.Sprintf("successfully server side patched a route trait `%s`", routeTrait.Name)))
+4 -4
View File
@@ -9,16 +9,16 @@ import (
var _ discoverymapper.DiscoveryMapper = &DiscoveryMapper{}
// nolint
// GetMapper is func type for mock convenience
type GetMapper func() (meta.RESTMapper, error)
// nolint
// Refresh is func type for mock convenience
type Refresh func() (meta.RESTMapper, error)
// nolint
// RESTMapping is func type for mock convenience
type RESTMapping func(gk schema.GroupKind, versions ...string) (*meta.RESTMapping, error)
// nolint
// KindsFor is func type for mock convenience
type KindsFor func(input schema.GroupVersionResource) ([]schema.GroupVersionKind, error)
// NewMockDiscoveryMapper for unit test only
+4 -6
View File
@@ -85,11 +85,10 @@ func (matcher ErrorMatcher) Match(actual interface{}) (success bool, err error)
}
// FailureMessage builds an error message.
//nolint:errorlint
// TODO(roywang) use errors.As() instead of type assertion on error
func (matcher ErrorMatcher) FailureMessage(actual interface{}) (message string) {
actualError, actualOK := actual.(error)
expectedError, expectedOK := matcher.ExpectedError.(error)
expectedError := matcher.ExpectedError
expectedOK := expectedError != nil
if actualOK && expectedOK {
return format.MessageWithDiff(actualError.Error(), "to equal", expectedError.Error())
@@ -107,11 +106,10 @@ func (matcher ErrorMatcher) FailureMessage(actual interface{}) (message string)
}
// NegatedFailureMessage builds an error message.
//nolint:errorlint
// TODO(roywang) use errors.As() instead of type assertion on error
func (matcher ErrorMatcher) NegatedFailureMessage(actual interface{}) (message string) {
actualError, actualOK := actual.(error)
expectedError, expectedOK := matcher.ExpectedError.(error)
expectedError := matcher.ExpectedError
expectedOK := expectedError != nil
if actualOK && expectedOK {
return format.MessageWithDiff(actualError.Error(), "not to equal", expectedError.Error())
+2 -3
View File
@@ -13,7 +13,6 @@ import (
"k8s.io/apimachinery/pkg/runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/oam-dev/kubevela/apis/core.oam.dev/v1alpha2"
corev1alpha2 "github.com/oam-dev/kubevela/apis/core.oam.dev/v1alpha2"
"github.com/oam-dev/kubevela/apis/types"
util2 "github.com/oam-dev/kubevela/pkg/commands/util"
@@ -25,7 +24,7 @@ import (
"github.com/oam-dev/kubevela/pkg/utils/system"
)
// nolint
// DescriptionUndefined indicates the description is not defined
const DescriptionUndefined = "description not defined"
// GetCapabilitiesFromCluster will get capability from K8s cluster
@@ -108,7 +107,7 @@ func GetTraitsFromCluster(ctx context.Context, namespace string, c types.Args, s
}
// validateCapabilities validates whether helm charts are successful installed, GVK are successfully retrieved.
func validateCapabilities(tmp types.Capability, dm discoverymapper.DiscoveryMapper, definitionName string, reference v1alpha2.DefinitionReference) (types.Capability, error) {
func validateCapabilities(tmp types.Capability, dm discoverymapper.DiscoveryMapper, definitionName string, reference corev1alpha2.DefinitionReference) (types.Capability, error) {
var err error
if tmp.Install != nil {
tmp.Source = &types.Source{ChartName: tmp.Install.Helm.Name}
+1 -1
View File
@@ -51,7 +51,7 @@ func TestAPIs(t *testing.T) {
}
var _ = BeforeSuite(func(done Done) {
logf.SetLogger(zap.LoggerTo(GinkgoWriter, true))
logf.SetLogger(zap.New(zap.UseDevMode(true), zap.WriteTo(GinkgoWriter)))
ctx := context.Background()
By("bootstrapping test environment")
useExistCluster := false
+1 -2
View File
@@ -11,7 +11,6 @@ import (
"github.com/oam-dev/kubevela/pkg/server/util"
"github.com/oam-dev/kubevela/pkg/serverlib"
"github.com/oam-dev/kubevela/pkg/utils/env"
env2 "github.com/oam-dev/kubevela/pkg/utils/env"
)
// UpdateApps is placeholder for updating applications
@@ -97,7 +96,7 @@ func (s *APIServer) CreateApplication(c *gin.Context) {
util.HandleError(c, util.InvalidArgument, "the application creation request body is invalid")
return
}
env, err := env2.GetEnvByName(c.Param("envName"))
env, err := env.GetEnvByName(c.Param("envName"))
if err != nil {
util.HandleError(c, util.StatusInternalServerError, err.Error())
return
+2 -2
View File
@@ -58,8 +58,8 @@ func ConstructError(ec Code, a ...interface{}) error {
case a == nil && c > 0 ||
a != nil && (c != len(a) || a[0] == nil):
{
ctrl.Log.Error(fmt.Errorf("Args '%v' do not match placeholders in the msg '%s'", a, ec.Message()),
"Invalid error message argument")
ctrl.Log.Error(fmt.Errorf("args '%v' do not match placeholders in the msg '%s'", a, ec.Message()),
"invalid error message argument")
}
case len(a) == 0 || a[0] == nil:
{
+5 -6
View File
@@ -20,7 +20,6 @@ import (
"k8s.io/client-go/rest"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/oam-dev/kubevela/apis/core.oam.dev/v1alpha2"
corev1alpha2 "github.com/oam-dev/kubevela/apis/core.oam.dev/v1alpha2"
"github.com/oam-dev/kubevela/apis/types"
"github.com/oam-dev/kubevela/pkg/appfile"
@@ -54,7 +53,7 @@ type AppfileOptions struct {
// BuildResult is the export struct from AppFile yaml or AppFile object
type BuildResult struct {
appFile *api.AppFile
application *v1alpha2.Application
application *corev1alpha2.Application
scopes []oam.Object
}
@@ -461,13 +460,13 @@ func (o *AppfileOptions) saveToAppDir(f *api.AppFile) error {
// - for create, it displays app status along with information of url, metrics, ssh, logging.
// - for update, it rolls out a canary deployment and prints its information. User can verify the canary deployment.
// This will wait for user approval. If approved, it continues upgrading the whole; otherwise, it would rollback.
func (o *AppfileOptions) ApplyApp(app *v1alpha2.Application, scopes []oam.Object) error {
func (o *AppfileOptions) ApplyApp(app *corev1alpha2.Application, scopes []oam.Object) error {
key := apitypes.NamespacedName{
Namespace: app.Namespace,
Name: app.Name,
}
o.IO.Infof("Checking if app has been deployed...\n")
var tmpApp v1alpha2.Application
var tmpApp corev1alpha2.Application
err := o.Kubecli.Get(context.TODO(), key, &tmpApp)
switch {
case apierrors.IsNotFound(err):
@@ -484,7 +483,7 @@ func (o *AppfileOptions) ApplyApp(app *v1alpha2.Application, scopes []oam.Object
return nil
}
func (o *AppfileOptions) apply(app *v1alpha2.Application, scopes []oam.Object) error {
func (o *AppfileOptions) apply(app *corev1alpha2.Application, scopes []oam.Object) error {
if err := appfile.Run(context.TODO(), o.Kubecli, app, scopes); err != nil {
return err
}
@@ -492,7 +491,7 @@ func (o *AppfileOptions) apply(app *v1alpha2.Application, scopes []oam.Object) e
}
// Info shows the status of each service in the Appfile
func (o *AppfileOptions) Info(app *v1alpha2.Application) string {
func (o *AppfileOptions) Info(app *corev1alpha2.Application) string {
appName := app.Name
var appUpMessage = "✅ App has been deployed 🚀🚀🚀\n" +
fmt.Sprintf(" Port forward: vela port-forward %s\n", appName) +
+3
View File
@@ -213,6 +213,9 @@ func TestGetParameterFromOpenAPISchema(t *testing.T) {
t.Run(name, func(t *testing.T) {
rawFile := filepath.Join(tc.fileDir, tc.fileName)
raw, err := ioutil.ReadFile(rawFile)
if err != nil {
t.Errorf("%s\ngetParameterFromOpenAPISchema(...): raw file %s could not be read: %s", tc.reason, rawFile, err)
}
got, err := getParameterFromOpenAPISchema(raw)
if (err == nil && tc.want != nil) || (err != nil && tc.want == nil) {
t.Errorf("%s\ngetParameterFromOpenAPISchema(...): -want %s, +got %s", tc.reason, tc.want, err)
+1 -2
View File
@@ -14,7 +14,6 @@ import (
"github.com/oam-dev/kubevela/pkg/appfile"
"github.com/oam-dev/kubevela/pkg/appfile/api"
"github.com/oam-dev/kubevela/pkg/commands/util"
cmdutil "github.com/oam-dev/kubevela/pkg/commands/util"
"github.com/oam-dev/kubevela/pkg/plugins"
)
@@ -134,7 +133,7 @@ func BaseComplete(envName string, workloadName string, appName string, flagSet *
}
// BaseRun will check if it's a stating operation before run
func BaseRun(staging bool, app *api.Application, kubeClient client.Client, env *types.EnvMeta, io cmdutil.IOStreams) (string, error) {
func BaseRun(staging bool, app *api.Application, kubeClient client.Client, env *types.EnvMeta, io util.IOStreams) (string, error) {
if staging {
return "Staging saved", nil
}
-1
View File
@@ -22,7 +22,6 @@ import (
"sigs.k8s.io/controller-runtime/pkg/log/zap"
)
var mgrclose chan struct{}
var testEnv *envtest.Environment
var cfg *rest.Config
var rawClient client.Client
@@ -58,7 +58,7 @@ func TestAPIs(t *testing.T) {
}
var _ = BeforeSuite(func(done Done) {
logf.SetLogger(zap.LoggerTo(GinkgoWriter, true))
logf.SetLogger(zap.New(zap.UseDevMode(true), zap.WriteTo(GinkgoWriter)))
By("bootstrapping test environment")
testEnv = &envtest.Environment{
@@ -23,7 +23,7 @@ import (
)
const (
errFmtWorkloadNameNotEmpty = "versioning-enabled component's workload name MUST NOT be assigned, expect workload name %q to be empty."
errFmtWorkloadNameNotEmpty = "versioning-enabled component's workload name MUST NOT be assigned, expect workload name %q to be empty"
errFmtRevisionName = "componentName %q and revisionName %q are mutually exclusive, you can only specify one of them"
+8
View File
@@ -0,0 +1,8 @@
# This is config file for staticcheck.
# If you need to add ignored checks, pls also add explaination in comments.
checks = ["all", "-ST1000", "-ST1003", "-ST1016"]
# ST1000 - Incorrect or missing package comment (non-default)
# ST1003 Poorly chosen identifier (non-default)
# ST1016 Use consistent method receiver names (non-default)
+5 -6
View File
@@ -12,7 +12,6 @@ import (
"github.com/ghodss/yaml"
appsv1 "k8s.io/api/apps/v1"
v1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
@@ -496,10 +495,10 @@ var _ = Describe("Component revision", func() {
namespace := "default"
componentName := "revision-component"
appConfigName := "revision-app"
workload := v1.Deployment{
workload := appsv1.Deployment{
TypeMeta: metav1.TypeMeta{APIVersion: "apps/v1", Kind: "Deployment"},
ObjectMeta: metav1.ObjectMeta{Namespace: namespace},
Spec: v1.DeploymentSpec{
Spec: appsv1.DeploymentSpec{
Selector: &metav1.LabelSelector{
MatchLabels: map[string]string{
"app": "nginx",
@@ -579,7 +578,7 @@ var _ = Describe("Component revision", func() {
Expect(k8sClient.Create(ctx, &appConfig)).Should(Succeed())
By("check workload")
var deploy v1.Deployment
var deploy appsv1.Deployment
Eventually(
func() error {
return k8sClient.Get(ctx, workloadObjKey, &deploy)
@@ -594,11 +593,11 @@ var _ = Describe("Component revision", func() {
By("check current workload exists")
time.Sleep(3 * time.Second)
var currentDeploy v1.Deployment
var currentDeploy appsv1.Deployment
Expect(k8sClient.Get(ctx, workloadObjKey, &currentDeploy)).Should(BeNil())
By("check version 1 workload doesn't exist")
var v1Deploy v1.Deployment
var v1Deploy appsv1.Deployment
workloadObjKey := client.ObjectKey{Name: componentName + "-v1", Namespace: namespace}
Expect(k8sClient.Get(ctx, workloadObjKey, &v1Deploy)).Should(SatisfyAny(&util.NotFoundMatcher{}))
})