diff --git a/.golangci.yaml b/.golangci.yaml index 69833088dd..ab45d0ceb9 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -16,7 +16,7 @@ linters: - gocritic #- gocyclo #- godot - #- gofumpt + - gofumpt #- gosec - gosimple - govet diff --git a/cmd/gitops-server/cmd/cmd.go b/cmd/gitops-server/cmd/cmd.go index 8dd64efa24..12e2a3fa47 100644 --- a/cmd/gitops-server/cmd/cmd.go +++ b/cmd/gitops-server/cmd/cmd.go @@ -151,7 +151,6 @@ func runCmd(cmd *cobra.Command, args []string) error { mux.Handle("/health/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, err := w.Write([]byte("ok")) - if err != nil { log.Error(err, "error writing health check") } diff --git a/cmd/gitops/check/oidcconfig/cmd.go b/cmd/gitops/check/oidcconfig/cmd.go index 488187f6ad..cd3bef9a59 100644 --- a/cmd/gitops/check/oidcconfig/cmd.go +++ b/cmd/gitops/check/oidcconfig/cmd.go @@ -95,7 +95,6 @@ gitops check oidc-config --skip-secret --client-id=CID --client-secret=SEC --iss ClaimUsername: claimUsernameFlag, ClaimGroups: claimGroupsFlag, }, log, kubeClient) - if err != nil { return fmt.Errorf("failed getting claims: %w", err) } diff --git a/cmd/gitops/get/bcrypt/cmd.go b/cmd/gitops/get/bcrypt/cmd.go index 7adb500c4f..a2290af4d1 100644 --- a/cmd/gitops/get/bcrypt/cmd.go +++ b/cmd/gitops/get/bcrypt/cmd.go @@ -32,7 +32,6 @@ func hashCommandRunE() func(*cobra.Command, []string) error { return func(cmd *cobra.Command, args []string) error { file := os.Stdin stats, err := file.Stat() - if err != nil { return err } @@ -41,7 +40,6 @@ func hashCommandRunE() func(*cobra.Command, []string) error { if (stats.Mode() & os.ModeCharDevice) == 0 { p, err = io.ReadAll(os.Stdin) - if err != nil { return err } @@ -58,7 +56,6 @@ func hashCommandRunE() func(*cobra.Command, []string) error { } secret, err := bcrypt.GenerateFromPassword(p, bcrypt.DefaultCost) - if err != nil { return err } diff --git a/cmd/gitops/root/cmd.go b/cmd/gitops/root/cmd.go index 8204af055e..8ab785a8df 100644 --- a/cmd/gitops/root/cmd.go +++ b/cmd/gitops/root/cmd.go @@ -46,7 +46,7 @@ func init() { } func RootCmd() *cobra.Command { - var rootCmd = &cobra.Command{ + rootCmd := &cobra.Command{ Use: "gitops", SilenceUsage: true, SilenceErrors: true, diff --git a/cmd/gitops/version/cmd.go b/cmd/gitops/version/cmd.go index 78034ca487..242ad84275 100644 --- a/cmd/gitops/version/cmd.go +++ b/cmd/gitops/version/cmd.go @@ -7,10 +7,12 @@ import ( ) // Version is the current wego version -var Version = "v0.0.0" -var GitCommit = "" -var Branch = "" -var BuildTime = "" +var ( + Version = "v0.0.0" + GitCommit = "" + Branch = "" + BuildTime = "" +) var Cmd = &cobra.Command{ Use: "version", diff --git a/core/clustersmngr/client.go b/core/clustersmngr/client.go index f352db5e35..96644b0f1c 100644 --- a/core/clustersmngr/client.go +++ b/core/clustersmngr/client.go @@ -177,7 +177,7 @@ func (c *clustersClient) ClusteredList(ctx context.Context, clist ClusteredObjec wg.Add(1) - go func(clusterName string, nsName string, c client.Client, optsWithNamespace ...client.ListOption) { + go func(clusterName, nsName string, c client.Client, optsWithNamespace ...client.ListOption) { defer wg.Done() list := clist.NewList() diff --git a/core/clustersmngr/client_test.go b/core/clustersmngr/client_test.go index 282ba6268b..54ab91f2f1 100644 --- a/core/clustersmngr/client_test.go +++ b/core/clustersmngr/client_test.go @@ -138,7 +138,7 @@ func TestClientClusteredListPagination(t *testing.T) { clusterName := "mycluster" - createKust := func(name string, nsName string) { + createKust := func(name, nsName string) { kust := &kustomizev1.Kustomization{ ObjectMeta: metav1.ObjectMeta{ Name: name, diff --git a/core/clustersmngr/cluster/cluster.go b/core/clustersmngr/cluster/cluster.go index bf423a287e..297ad849d3 100644 --- a/core/clustersmngr/cluster/cluster.go +++ b/core/clustersmngr/cluster/cluster.go @@ -88,7 +88,6 @@ func getEnvDuration(key string, defaultDuration time.Duration) time.Duration { } d, err := time.ParseDuration(val) - // on error return the default duration if err != nil { return defaultDuration diff --git a/core/clustersmngr/cluster/suite_test.go b/core/clustersmngr/cluster/suite_test.go index 59996f08a9..047d51e594 100644 --- a/core/clustersmngr/cluster/suite_test.go +++ b/core/clustersmngr/cluster/suite_test.go @@ -15,7 +15,6 @@ func TestMain(m *testing.M) { "../../manifests/crds", "../../tools/testcrds", }) - if err != nil { panic(err) } diff --git a/core/clustersmngr/factory.go b/core/clustersmngr/factory.go index 9779652bf6..5943649889 100644 --- a/core/clustersmngr/factory.go +++ b/core/clustersmngr/factory.go @@ -34,9 +34,7 @@ const ( usersClientResolution = 30 * time.Second ) -var ( - usersClientsTTL = getEnvDuration("WEAVE_GITOPS_USERS_CLIENTS_TTL", 30*time.Minute) -) +var usersClientsTTL = getEnvDuration("WEAVE_GITOPS_USERS_CLIENTS_TTL", 30*time.Minute) func getEnvDuration(key string, defaultDuration time.Duration) time.Duration { val := os.Getenv(key) @@ -45,7 +43,6 @@ func getEnvDuration(key string, defaultDuration time.Duration) time.Duration { } d, err := time.ParseDuration(val) - // on error return the default duration if err != nil { return defaultDuration diff --git a/core/clustersmngr/suite_test.go b/core/clustersmngr/suite_test.go index c33a536c30..1045a21e9d 100644 --- a/core/clustersmngr/suite_test.go +++ b/core/clustersmngr/suite_test.go @@ -19,7 +19,6 @@ func TestMain(m *testing.M) { "../../manifests/crds", "../../tools/testcrds", }) - if err != nil { panic(err) } diff --git a/core/fluxsync/fluxsync.go b/core/fluxsync/fluxsync.go index 6fc6a5330d..3195982743 100644 --- a/core/fluxsync/fluxsync.go +++ b/core/fluxsync/fluxsync.go @@ -14,8 +14,10 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" ) -var k8sPollInterval = 2 * time.Second -var k8sTimeout = 1 * time.Minute +var ( + k8sPollInterval = 2 * time.Second + k8sTimeout = 1 * time.Minute +) // RequestReconciliation sets the annotations of an object so that the flux controller(s) will force a reconciliation. // Take straight from the flux CLI source: diff --git a/core/nsaccess/nsaccess_test.go b/core/nsaccess/nsaccess_test.go index 90c5c83b2c..3a4d04f210 100644 --- a/core/nsaccess/nsaccess_test.go +++ b/core/nsaccess/nsaccess_test.go @@ -429,7 +429,8 @@ func createRole(t *testing.T, cl client.Client, key types.NamespacedName, rules binding := &rbacv1.RoleBinding{ ObjectMeta: metav1.ObjectMeta{ - Name: "test-role-binding", Namespace: key.Namespace}, + Name: "test-role-binding", Namespace: key.Namespace, + }, Subjects: []rbacv1.Subject{ { Kind: "User", diff --git a/core/server/fluxruntime.go b/core/server/fluxruntime.go index 94d47b68cd..0fb6a6a7f1 100644 --- a/core/server/fluxruntime.go +++ b/core/server/fluxruntime.go @@ -420,7 +420,6 @@ ItemsLoop: tenant := GetTenant(obj.GetNamespace(), msg.ClusterName, clusterUserNamespaces) obj, err := coretypes.K8sObjectToProto(&obj, msg.ClusterName, tenant, nil, "") - if err != nil { respErrors = *multierror.Append(fmt.Errorf("error converting objects: %w", err), respErrors.Errors...) continue diff --git a/core/server/fluxruntime_test.go b/core/server/fluxruntime_test.go index a2813d9c8a..0783512272 100644 --- a/core/server/fluxruntime_test.go +++ b/core/server/fluxruntime_test.go @@ -563,7 +563,8 @@ func TestListRuntimeCrds(t *testing.T) { }, Spec: apiextensions.CustomResourceDefinitionSpec{ Group: "group", Names: apiextensions.CustomResourceDefinitionNames{Plural: "policies", Kind: "kind"}, - Versions: []apiextensions.CustomResourceDefinitionVersion{}}}, + Versions: []apiextensions.CustomResourceDefinitionVersion{}, + }}, }, func(res *pb.ListRuntimeCrdsResponse) { g.Expect(res.Crds).To(HaveLen(2)) diff --git a/core/server/helm_release.go b/core/server/helm_release.go index 83aeea51c6..cb01b895b8 100644 --- a/core/server/helm_release.go +++ b/core/server/helm_release.go @@ -18,7 +18,6 @@ func getHelmReleaseInventory(ctx context.Context, helmRelease helmv2.HelmRelease } objects, err := getHelmReleaseObjects(ctx, k8sClient, &helmRelease) - if err != nil { return nil, err } diff --git a/core/server/inventory.go b/core/server/inventory.go index 7fa6d075cd..8f0a0d2897 100644 --- a/core/server/inventory.go +++ b/core/server/inventory.go @@ -180,7 +180,7 @@ func getHelmReleaseObjects(ctx context.Context, k8sClient client.Client, helmRel return nil, err } - var magicGzip = []byte{0x1f, 0x8b, 0x08} + magicGzip := []byte{0x1f, 0x8b, 0x08} if bytes.Equal(byteData[0:3], magicGzip) { r, err := gzip.NewReader(bytes.NewReader(byteData)) if err != nil { diff --git a/core/server/objects.go b/core/server/objects.go index cf3c202880..f846c0b453 100644 --- a/core/server/objects.go +++ b/core/server/objects.go @@ -202,7 +202,6 @@ func (cs *coreServer) sessionObjectsCreated(ctx context.Context, clusterName, ob Kind: automationKind, ClusterName: clusterName, }) - if err != nil { return false, err } @@ -213,7 +212,6 @@ func (cs *coreServer) sessionObjectsCreated(ctx context.Context, clusterName, ob Kind: "Bucket", ClusterName: clusterName, }) - if err != nil { return false, err } @@ -268,7 +266,6 @@ func (cs *coreServer) GetObject(ctx context.Context, msg *pb.GetObjectRequest) ( tenant := GetTenant(obj.GetNamespace(), msg.ClusterName, clusterUserNamespaces) res, err := types.K8sObjectToProto(obj, msg.ClusterName, tenant, inventory, "") - if err != nil { return nil, fmt.Errorf("converting object to proto: %w", err) } diff --git a/core/server/policy_violations.go b/core/server/policy_violations.go index d83053de96..bebda912d2 100644 --- a/core/server/policy_violations.go +++ b/core/server/policy_violations.go @@ -60,8 +60,8 @@ func (cs *coreServer) ListPolicyValidations(ctx context.Context, m *pb.ListPolic } labelSelector, err := k8sLabels.ValidatedSelectorFromSet(map[string]string{ - "pac.weave.works/type": validationType}) - + "pac.weave.works/type": validationType, + }) if err != nil { return nil, fmt.Errorf("error building selector for events query: %v", err) } @@ -134,8 +134,8 @@ func (cs *coreServer) GetPolicyValidation(ctx context.Context, m *pb.GetPolicyVa selector, err := k8sLabels.ValidatedSelectorFromSet(map[string]string{ "pac.weave.works/type": validationType, - "pac.weave.works/id": m.ValidationId}) - + "pac.weave.works/id": m.ValidationId, + }) if err != nil { return nil, fmt.Errorf("error building selector for events query: %v", err) } diff --git a/core/server/primarykinds_test.go b/core/server/primarykinds_test.go index 9f8b2397ed..8393ab6822 100644 --- a/core/server/primarykinds_test.go +++ b/core/server/primarykinds_test.go @@ -16,7 +16,6 @@ func TestVersionRank(t *testing.T) { gvk2 schema.GroupVersionKind expected int }{ - {schema.GroupVersionKind{Version: "v1"}, schema.GroupVersionKind{Version: "v1alpha1"}, 1}, {schema.GroupVersionKind{Version: "v1"}, schema.GroupVersionKind{Version: "v1beta1"}, 1}, {schema.GroupVersionKind{Version: "v1"}, schema.GroupVersionKind{Version: "v1beta2"}, 1}, @@ -70,7 +69,8 @@ func TestGetPrimaryKinds(t *testing.T) { {Group: "core", Version: "v2", Kind: "Pod"}: reflect.TypeOf(PodV2{}), {Group: "core", Version: "v1alpha1", Kind: "Node"}: reflect.TypeOf(NodeV1a1{}), {Group: "core", Version: "v1beta2", Kind: "Node"}: reflect.TypeOf(NodeV1b2{}), - {Group: "core", Version: "v1beta1", Kind: "Node"}: reflect.TypeOf(NodeV1b1{})}, + {Group: "core", Version: "v1beta1", Kind: "Node"}: reflect.TypeOf(NodeV1b1{}), + }, } primaryKinds, err := getPrimaryKinds(scheme) diff --git a/core/server/suite_test.go b/core/server/suite_test.go index 53152a7b56..38056a0adb 100644 --- a/core/server/suite_test.go +++ b/core/server/suite_test.go @@ -32,8 +32,10 @@ import ( "github.com/weaveworks/weave-gitops/pkg/testutils" ) -var k8sEnv *testutils.K8sTestEnv -var nsChecker nsaccessfakes.FakeChecker +var ( + k8sEnv *testutils.K8sTestEnv + nsChecker nsaccessfakes.FakeChecker +) func TestMain(m *testing.M) { var err error @@ -41,7 +43,6 @@ func TestMain(m *testing.M) { "../../manifests/crds", "../../tools/testcrds", }) - if err != nil { fmt.Fprintf(os.Stderr, "Failed to start test environment: %v\n", err) os.Exit(1) diff --git a/core/server/suspend.go b/core/server/suspend.go index 8b9f0d74a0..aacf360ea4 100644 --- a/core/server/suspend.go +++ b/core/server/suspend.go @@ -12,8 +12,10 @@ import ( "github.com/weaveworks/weave-gitops/pkg/server/auth" ) -const SuspendedByAnnotation = "metadata.weave.works/suspended-by" -const SuspendedCommentAnnotation = "metadata.weave.works/suspended-comment" +const ( + SuspendedByAnnotation = "metadata.weave.works/suspended-by" + SuspendedCommentAnnotation = "metadata.weave.works/suspended-comment" +) func (cs *coreServer) ToggleSuspendResource(ctx context.Context, msg *pb.ToggleSuspendResourceRequest) (*pb.ToggleSuspendResourceResponse, error) { principal := auth.Principal(ctx) diff --git a/core/server/suspend_test.go b/core/server/suspend_test.go index 52bc8968d0..5b44c66ed1 100644 --- a/core/server/suspend_test.go +++ b/core/server/suspend_test.go @@ -144,16 +144,17 @@ func TestSuspend_Suspend(t *testing.T) { md := metadata.Pairs(MetadataUserKey, "anne", MetadataGroupsKey, "system:masters") outgoingCtx := metadata.NewOutgoingContext(ctx, md) _, err = c.ToggleSuspendResource(outgoingCtx, &api.ToggleSuspendResourceRequest{ - Objects: []*api.ObjectRef{{ Kind: sourcev1.GitRepositoryKind, Name: "fakeName", Namespace: "fakeNamespace", ClusterName: "Default", - }, {Kind: sourcev1.GitRepositoryKind, + }, { + Kind: sourcev1.GitRepositoryKind, Name: "fakeName2", Namespace: "fakeNamespace2", - ClusterName: "Default2"}}, + ClusterName: "Default2", + }}, Suspend: true, }) diff --git a/core/server/sync_test.go b/core/server/sync_test.go index 72fe1fe2ae..1e6e22b7fd 100644 --- a/core/server/sync_test.go +++ b/core/server/sync_test.go @@ -75,16 +75,20 @@ func TestSync(t *testing.T) { }{{ name: "helm release no source", msg: &pb.SyncFluxObjectRequest{ - Objects: []*pb.ObjectRef{{ClusterName: "Default", - Kind: helmv2.HelmReleaseKind}}, + Objects: []*pb.ObjectRef{{ + ClusterName: "Default", + Kind: helmv2.HelmReleaseKind, + }}, WithSource: false, }, reconcilable: fluxsync.HelmReleaseAdapter{HelmRelease: hr}, }, { name: "helm release with source", msg: &pb.SyncFluxObjectRequest{ - Objects: []*pb.ObjectRef{{ClusterName: "Default", - Kind: helmv2.HelmReleaseKind}}, + Objects: []*pb.ObjectRef{{ + ClusterName: "Default", + Kind: helmv2.HelmReleaseKind, + }}, WithSource: true, }, reconcilable: fluxsync.HelmReleaseAdapter{HelmRelease: hr}, @@ -92,16 +96,20 @@ func TestSync(t *testing.T) { }, { name: "kustomization no source", msg: &pb.SyncFluxObjectRequest{ - Objects: []*pb.ObjectRef{{ClusterName: "Default", - Kind: kustomizev1.KustomizationKind}}, + Objects: []*pb.ObjectRef{{ + ClusterName: "Default", + Kind: kustomizev1.KustomizationKind, + }}, WithSource: false, }, reconcilable: fluxsync.KustomizationAdapter{Kustomization: kust}, }, { name: "kustomization with source", msg: &pb.SyncFluxObjectRequest{ - Objects: []*pb.ObjectRef{{ClusterName: "Default", - Kind: kustomizev1.KustomizationKind}}, + Objects: []*pb.ObjectRef{{ + ClusterName: "Default", + Kind: kustomizev1.KustomizationKind, + }}, WithSource: true, }, reconcilable: fluxsync.KustomizationAdapter{Kustomization: kust}, @@ -109,65 +117,83 @@ func TestSync(t *testing.T) { }, { name: "gitrepository", msg: &pb.SyncFluxObjectRequest{ - Objects: []*pb.ObjectRef{{ClusterName: "Default", - Kind: sourcev1.GitRepositoryKind}}, + Objects: []*pb.ObjectRef{{ + ClusterName: "Default", + Kind: sourcev1.GitRepositoryKind, + }}, WithSource: false, }, reconcilable: fluxsync.GitRepositoryAdapter{GitRepository: gitRepo}, }, { name: "bucket", msg: &pb.SyncFluxObjectRequest{ - Objects: []*pb.ObjectRef{{ClusterName: "Default", - Kind: sourcev1.BucketKind}}, + Objects: []*pb.ObjectRef{{ + ClusterName: "Default", + Kind: sourcev1.BucketKind, + }}, WithSource: false, }, reconcilable: fluxsync.BucketAdapter{Bucket: bucket}, }, { name: "helmchart", msg: &pb.SyncFluxObjectRequest{ - Objects: []*pb.ObjectRef{{ClusterName: "Default", - Kind: sourcev1.HelmChartKind}}, + Objects: []*pb.ObjectRef{{ + ClusterName: "Default", + Kind: sourcev1.HelmChartKind, + }}, WithSource: false, }, reconcilable: fluxsync.HelmChartAdapter{HelmChart: chart}, }, { name: "helmrepository", msg: &pb.SyncFluxObjectRequest{ - Objects: []*pb.ObjectRef{{ClusterName: "Default", - Kind: sourcev1.HelmRepositoryKind}}, + Objects: []*pb.ObjectRef{{ + ClusterName: "Default", + Kind: sourcev1.HelmRepositoryKind, + }}, WithSource: false, }, reconcilable: fluxsync.HelmRepositoryAdapter{HelmRepository: helmRepo}, }, { name: "ocirepository", msg: &pb.SyncFluxObjectRequest{ - Objects: []*pb.ObjectRef{{ClusterName: "Default", - Kind: sourcev1b2.OCIRepositoryKind}}, + Objects: []*pb.ObjectRef{{ + ClusterName: "Default", + Kind: sourcev1b2.OCIRepositoryKind, + }}, WithSource: false, }, reconcilable: fluxsync.OCIRepositoryAdapter{OCIRepository: ociRepo}, }, { name: "image repository", msg: &pb.SyncFluxObjectRequest{ - Objects: []*pb.ObjectRef{{ClusterName: "Default", - Kind: reflectorv1.ImageRepositoryKind}}, + Objects: []*pb.ObjectRef{{ + ClusterName: "Default", + Kind: reflectorv1.ImageRepositoryKind, + }}, WithSource: false, }, reconcilable: fluxsync.ImageRepositoryAdapter{ImageRepository: ir}, }, { name: "image update automation", msg: &pb.SyncFluxObjectRequest{ - Objects: []*pb.ObjectRef{{ClusterName: "Default", - Kind: imgautomationv1.ImageUpdateAutomationKind}}, + Objects: []*pb.ObjectRef{{ + ClusterName: "Default", + Kind: imgautomationv1.ImageUpdateAutomationKind, + }}, WithSource: false, }, reconcilable: fluxsync.ImageUpdateAutomationAdapter{ImageUpdateAutomation: iua}, }, { name: "multiple objects", msg: &pb.SyncFluxObjectRequest{ - Objects: []*pb.ObjectRef{{ClusterName: "Default", - Kind: helmv2.HelmReleaseKind}, {ClusterName: "Default", - Kind: helmv2.HelmReleaseKind}}, + Objects: []*pb.ObjectRef{{ + ClusterName: "Default", + Kind: helmv2.HelmReleaseKind, + }, { + ClusterName: "Default", + Kind: helmv2.HelmReleaseKind, + }}, WithSource: true, }, reconcilable: fluxsync.HelmReleaseAdapter{HelmRelease: hr}, diff --git a/pkg/analytics/analytics.go b/pkg/analytics/analytics.go index c9bfaacee2..ce5696197f 100644 --- a/pkg/analytics/analytics.go +++ b/pkg/analytics/analytics.go @@ -37,9 +37,11 @@ type analyticsRequestBody struct { Properties *eventProperties `json:"properties"` } -const tierKey = "tier" -const versionKey = "version" -const appKey = "app" +const ( + tierKey = "tier" + versionKey = "version" + appKey = "app" +) type eventProperties map[string]interface{} diff --git a/pkg/analytics/analytics_test.go b/pkg/analytics/analytics_test.go index 26b0f6f252..dadd1d035d 100644 --- a/pkg/analytics/analytics_test.go +++ b/pkg/analytics/analytics_test.go @@ -8,15 +8,15 @@ import ( var _ = Describe("getCommandPath", func() { It("gets command path from command", func() { - var rootCmd = &cobra.Command{ + rootCmd := &cobra.Command{ Use: "root", } - var parentCmd = &cobra.Command{ + parentCmd := &cobra.Command{ Use: "parent", } - var cmd = &cobra.Command{ + cmd := &cobra.Command{ Use: "cmd", } @@ -27,7 +27,6 @@ var _ = Describe("getCommandPath", func() { commandPath := getCommandPath(cmd) Expect(commandPath).To(Equal("parent cmd")) - }) }) diff --git a/pkg/fluxexec/bootstrap_bitbucket_test.go b/pkg/fluxexec/bootstrap_bitbucket_test.go index 3121fbc821..7d5dec4da9 100644 --- a/pkg/fluxexec/bootstrap_bitbucket_test.go +++ b/pkg/fluxexec/bootstrap_bitbucket_test.go @@ -44,7 +44,5 @@ var _ = Describe("bootstrapBitBucketServerCmd", func() { "--group", "group1,group2", })) }) - }) - }) diff --git a/pkg/fluxexec/bootstrap_gitlab_test.go b/pkg/fluxexec/bootstrap_gitlab_test.go index 791af75886..e31f167b76 100644 --- a/pkg/fluxexec/bootstrap_gitlab_test.go +++ b/pkg/fluxexec/bootstrap_gitlab_test.go @@ -31,6 +31,5 @@ var _ = Describe("bootstrapGitLabCmd", func() { "--secret-name", "weave-gitops-system", })) }) - }) }) diff --git a/pkg/fluxexec/install_test.go b/pkg/fluxexec/install_test.go index 66b15eb3c6..a70dafacfe 100644 --- a/pkg/fluxexec/install_test.go +++ b/pkg/fluxexec/install_test.go @@ -51,6 +51,5 @@ var _ = Describe("installCmd", func() { "image-reflector-controller,image-automation-controller", })) }) - }) }) diff --git a/pkg/fluxinstall/installer_test.go b/pkg/fluxinstall/installer_test.go index f7924e177d..b126b74f62 100644 --- a/pkg/fluxinstall/installer_test.go +++ b/pkg/fluxinstall/installer_test.go @@ -46,5 +46,4 @@ var _ = Describe("Install Flux CLI", func() { Expect(err).To(BeNil()) }) }) - }) diff --git a/pkg/fluxinstall/product.go b/pkg/fluxinstall/product.go index b8326e076f..5e57cefca6 100644 --- a/pkg/fluxinstall/product.go +++ b/pkg/fluxinstall/product.go @@ -63,7 +63,6 @@ func (p *Product) Install(ctx context.Context) (string, error) { binaryURL := fmt.Sprintf("https://github.com/fluxcd/flux2/releases/download/v%s/flux_%s_%s_%s.%s", p.Version, p.Version, runtime.GOOS, runtime.GOARCH, extension) client := p.cli resp, err := client.Get(binaryURL) - if err != nil { return "", err } @@ -123,7 +122,6 @@ func (p *Product) verifyChecksum(filename, sum string) error { checkSumURL := fmt.Sprintf("https://github.com/fluxcd/flux2/releases/download/v%s/flux_%s_checksums.txt", p.Version, p.Version) client := p.cli resp, err := client.Get(checkSumURL) - if err != nil { return err } diff --git a/pkg/fluxinstall/product_test.go b/pkg/fluxinstall/product_test.go index 54bc077bcf..b0507bbca4 100644 --- a/pkg/fluxinstall/product_test.go +++ b/pkg/fluxinstall/product_test.go @@ -81,14 +81,12 @@ func addToArchive(tw *tar.Writer, filename string, data []byte) error { return nil } -type MockProductHTTPClient struct { -} +type MockProductHTTPClient struct{} func (m *MockProductHTTPClient) Get(url string) (resp *http.Response, err error) { - var archivePattern = regexp.MustCompile(`https://github\.com/fluxcd/flux2/releases/download/v0.32.0/flux_0.32.0_(linux|darwin)_(amd64|arm64).tar.gz`) + archivePattern := regexp.MustCompile(`https://github\.com/fluxcd/flux2/releases/download/v0.32.0/flux_0.32.0_(linux|darwin)_(amd64|arm64).tar.gz`) if archivePattern.MatchString(url) { body, err := createMockFluxArchive([]byte("flux")) - if err != nil { return nil, err } @@ -111,7 +109,6 @@ func (m *MockProductHTTPClient) Get(url string) (resp *http.Response, err error) } var _ = Describe("Product", func() { - var product *Product It("should verify checksum of flux product", func() { @@ -127,5 +124,4 @@ var _ = Describe("Product", func() { Expect(err).To(BeNil()) }) }) - }) diff --git a/pkg/git/gogit.go b/pkg/git/gogit.go index 98503f7cae..0bd709fcd2 100644 --- a/pkg/git/gogit.go +++ b/pkg/git/gogit.go @@ -53,7 +53,6 @@ func New(auth transport.AuthMethod, wrapper wrapper.Git) Git { func (g *GoGit) Open(path string) (*gogit.Repository, error) { g.path = path repo, err := g.git.PlainOpen(path) - if err != nil { return nil, err } @@ -144,7 +143,6 @@ func (g *GoGit) clone(ctx context.Context, path, url, branch string, depth int) Depth: depth, Tags: gogit.NoTags, }) - if err != nil { return nil, err } diff --git a/pkg/git/gogit_test.go b/pkg/git/gogit_test.go index 65b5c92dc1..87d0ecedcd 100644 --- a/pkg/git/gogit_test.go +++ b/pkg/git/gogit_test.go @@ -102,7 +102,6 @@ var _ = Describe("ValidateAccess", func() { }) It("should not fail on an empty repo", func() { - fakeGit.PlainCloneContextReturns(nil, transport.ErrEmptyRemoteRepository) err := fakeGitClient.ValidateAccess(context.Background(), "https://github.com/githubtraining/hellogitworld", "master") @@ -111,7 +110,6 @@ var _ = Describe("ValidateAccess", func() { }) It("should fail with custom error", func() { - customError := errors.New("my-custom-error") fakeGit.PlainCloneContextReturns(nil, customError) @@ -122,7 +120,6 @@ var _ = Describe("ValidateAccess", func() { }) It("should fail to create temporary directory", func() { - tempDirName := "-*/3486rw7f" os.Setenv("TMPDIR", tempDirName) @@ -444,7 +441,6 @@ var _ = Describe("Remove", func() { var _ = Describe("Checkout", func() { It("succeeds", func() { - _, err = gitClient.Clone(context.Background(), dir, "https://github.com/github/gitignore", "main") Expect(err).ShouldNot(HaveOccurred()) @@ -461,7 +457,8 @@ var _ = Describe("Checkout", func() { Author: git.Author{ Name: "test", Email: "test@test.com", - }}, + }, + }, func(s string) bool { return true }) diff --git a/pkg/gitproviders/dryrun_test.go b/pkg/gitproviders/dryrun_test.go index bf8443c4f9..698ba494a7 100644 --- a/pkg/gitproviders/dryrun_test.go +++ b/pkg/gitproviders/dryrun_test.go @@ -17,7 +17,7 @@ var ( ) var _ = Describe("DryRun", func() { - var _ = BeforeEach(func() { + _ = BeforeEach(func() { orgProvider := orgGitProvider{ domain: "github.com", provider: &fakegitprovider.Client{ diff --git a/pkg/gitproviders/factory_test.go b/pkg/gitproviders/factory_test.go index c0abd35bee..a9b66fcd6f 100644 --- a/pkg/gitproviders/factory_test.go +++ b/pkg/gitproviders/factory_test.go @@ -18,7 +18,6 @@ var _ = DescribeTable("buildGitProvider", func(input Config, expected expectedGi Expect(c.ProviderID()).To(Equal(gitprovider.ProviderID(expected.clientProviderID)), "ProviderID") Expect(c.SupportedDomain()).To(Equal(expected.clientDomain), "SupportedDomain") Expect(h).To(Equal(expected.hostname), "hostname") - }, Entry("github.com", Config{Provider: "github", Hostname: "github.com", Token: "abc"}, expectedGitProvider{ clientDomain: "github.com", diff --git a/pkg/gitproviders/provider_org_test.go b/pkg/gitproviders/provider_org_test.go index a5ca9c574c..11776de6a0 100644 --- a/pkg/gitproviders/provider_org_test.go +++ b/pkg/gitproviders/provider_org_test.go @@ -29,7 +29,7 @@ var _ = Describe("Org Provider", func() { repoURL RepoURL ) - var _ = BeforeEach(func() { + _ = BeforeEach(func() { commitClient = &fakegitprovider.CommitClient{} branchesClient = &fakegitprovider.BranchClient{} pullRequestsClient = &fakegitprovider.PullRequestClient{} diff --git a/pkg/gitproviders/provider_user_test.go b/pkg/gitproviders/provider_user_test.go index ed85e908ce..7be300d837 100644 --- a/pkg/gitproviders/provider_user_test.go +++ b/pkg/gitproviders/provider_user_test.go @@ -28,7 +28,7 @@ var _ = Describe("User Provider", func() { repoURL RepoURL ) - var _ = BeforeEach(func() { + _ = BeforeEach(func() { commitClient = &fakegitprovider.CommitClient{} branchesClient = &fakegitprovider.BranchClient{} pullRequestsClient = &fakegitprovider.PullRequestClient{} diff --git a/pkg/health/health.go b/pkg/health/health.go index b94636111c..1aeff3b73b 100644 --- a/pkg/health/health.go +++ b/pkg/health/health.go @@ -180,14 +180,15 @@ func checkStatefulSet(obj unstructured.Unstructured) (HealthStatus, error) { return HealthStatus{Status: HealthStatusProgressing, Message: "waiting for ready replicas"}, nil } - //ref: https://github.com/kubernetes/kubernetes/blob/5232ad4a00ec93942d0b2c6359ee6cd1201b46bc/pkg/kubectl/rollout_status.go#L137 + // ref: https://github.com/kubernetes/kubernetes/blob/5232ad4a00ec93942d0b2c6359ee6cd1201b46bc/pkg/kubectl/rollout_status.go#L137 if sts.Spec.UpdateStrategy.Type == appsv1.RollingUpdateStatefulSetStrategyType && sts.Spec.UpdateStrategy.RollingUpdate != nil { if sts.Spec.Replicas != nil && sts.Spec.UpdateStrategy.RollingUpdate.Partition != nil { if sts.Status.UpdatedReplicas < (*sts.Spec.Replicas - *sts.Spec.UpdateStrategy.RollingUpdate.Partition) { return HealthStatus{ Status: HealthStatusProgressing, Message: fmt.Sprintf("Waiting for partitioned roll out to finish: %d out of %d new pods have been updated...\n", - sts.Status.UpdatedReplicas, (*sts.Spec.Replicas - *sts.Spec.UpdateStrategy.RollingUpdate.Partition))}, nil + sts.Status.UpdatedReplicas, (*sts.Spec.Replicas - *sts.Spec.UpdateStrategy.RollingUpdate.Partition)), + }, nil } } diff --git a/pkg/kube/kubehttp.go b/pkg/kube/kubehttp.go index 52e929ea55..11106e2498 100644 --- a/pkg/kube/kubehttp.go +++ b/pkg/kube/kubehttp.go @@ -56,17 +56,17 @@ func CreateScheme() (*apiruntime.Scheme, error) { return scheme, nil } -const WeGOCRDName = "apps.wego.weave.works" -const FluxNamespace = "flux-system" +const ( + WeGOCRDName = "apps.wego.weave.works" + FluxNamespace = "flux-system" +) const ( WegoConfigMapName = "weave-gitops-config" ) -var ( - // ErrWegoConfigNotFound indicates weave gitops config could not be found - ErrWegoConfigNotFound = errors.New("wego config not found") -) +// ErrWegoConfigNotFound indicates weave gitops config could not be found +var ErrWegoConfigNotFound = errors.New("wego config not found") // InClusterConfig defines a function for checking if this code is executing in kubernetes. // This can be overriden if needed. diff --git a/pkg/kube/kubehttp_test.go b/pkg/kube/kubehttp_test.go index ef6aec93ff..3d2304b47e 100644 --- a/pkg/kube/kubehttp_test.go +++ b/pkg/kube/kubehttp_test.go @@ -16,9 +16,7 @@ import ( ) var _ = Describe("KubeHTTP", func() { - var ( - namespace *corev1.Namespace - ) + var namespace *corev1.Namespace BeforeEach(func() { namespace = &corev1.Namespace{} diff --git a/pkg/logger/s3_log_writer.go b/pkg/logger/s3_log_writer.go index 616cb3f050..4447d9087d 100644 --- a/pkg/logger/s3_log_writer.go +++ b/pkg/logger/s3_log_writer.go @@ -20,9 +20,11 @@ type S3LogWriter struct { log0 Logger } -const SessionLogBucketName = "gitops-run-logs" -const PodLogBucketName = "pod-logs" -const SessionLogSource = "gitops-run-client" +const ( + SessionLogBucketName = "gitops-run-logs" + PodLogBucketName = "pod-logs" + SessionLogSource = "gitops-run-client" +) func (l *S3LogWriter) L() logr.Logger { return l.log0.L() @@ -78,7 +80,6 @@ func (l *S3LogWriter) putLog(msg string) { // This funny pattern 20060102-150405.00000 is the layout needed by time.Format fmt.Sprintf("%s/%s.txt", l.id, now.Format("20060102-150405.00000")), strings.NewReader(logMsg), int64(len(logMsg)), minio.PutObjectOptions{}) - if err != nil { l.log0.Failuref("failed to put log to s3: %v", err) } diff --git a/pkg/run/get_kube_client_test.go b/pkg/run/get_kube_client_test.go index 22d1010f2a..885a972a9a 100644 --- a/pkg/run/get_kube_client_test.go +++ b/pkg/run/get_kube_client_test.go @@ -9,7 +9,6 @@ import ( ) var _ = Describe("GetKubeClient", func() { - It("returns kube client", func() { kubeConfigArgs := GetKubeConfigArgs() diff --git a/pkg/run/install/install_dashboard.go b/pkg/run/install/install_dashboard.go index 491a558108..f1d0a3ed8c 100644 --- a/pkg/run/install/install_dashboard.go +++ b/pkg/run/install/install_dashboard.go @@ -104,7 +104,6 @@ func CreateDashboardObjects(log logger.Logger, name, namespace, username, passwo helmRepository := makeHelmRepository(name, namespace) helmRelease, err := makeHelmRelease(log, name, namespace, username, passwordHash, chartVersion, dashboardImage, valuesFromFiles) - if err != nil { log.Failuref("Creating HelmRelease failed") return nil, err @@ -445,12 +444,11 @@ func parseImageRepository(input string) (repository, image, tag string, err erro func makeValues(username, passwordHash, dashboardImage string, valuesFromFiles map[string]interface{}) ([]byte, error) { valuesMap := make(map[string]interface{}) if username != "" && passwordHash != "" { - valuesMap["adminUser"] = - map[string]interface{}{ - "create": true, - "username": username, - "passwordHash": passwordHash, - } + valuesMap["adminUser"] = map[string]interface{}{ + "create": true, + "username": username, + "passwordHash": passwordHash, + } } gitopsConfig, err := config.GetConfig(false) diff --git a/pkg/run/install/install_flux_test.go b/pkg/run/install/install_flux_test.go index 8c1372e300..53ec4f63d9 100644 --- a/pkg/run/install/install_flux_test.go +++ b/pkg/run/install/install_flux_test.go @@ -117,5 +117,4 @@ var _ = Describe("GetFluxVersion", func() { Eventually(kubeClient.Delete(ctx, fluxNs)).ProbeEvery(1 * time.Second).Should(Succeed()) }) - }) diff --git a/pkg/run/paths.go b/pkg/run/paths.go index f6dfde24fc..2513e227a9 100644 --- a/pkg/run/paths.go +++ b/pkg/run/paths.go @@ -71,7 +71,6 @@ func findGitRepoDir() (string, error) { func GetRelativePathToRootDir(rootDir, path string) (string, error) { absGitDir, err := filepath.Abs(rootDir) - if err != nil { // not in a git repo return "", err } diff --git a/pkg/runner/runner_test.go b/pkg/runner/runner_test.go index 5a1ac32cc4..5ac8dfa315 100644 --- a/pkg/runner/runner_test.go +++ b/pkg/runner/runner_test.go @@ -9,9 +9,7 @@ import ( "github.com/weaveworks/weave-gitops/pkg/runner" ) -var ( - cliRunner runner.Runner -) +var cliRunner runner.Runner var _ = BeforeEach(func() { cliRunner = &runner.CLIRunner{} diff --git a/pkg/server/auth/auth_method_type_test.go b/pkg/server/auth/auth_method_type_test.go index 640b7318a9..d12aaa488c 100644 --- a/pkg/server/auth/auth_method_type_test.go +++ b/pkg/server/auth/auth_method_type_test.go @@ -16,7 +16,6 @@ func TestInvariant(t *testing.T) { authstring := method.String() parsedMethod, err := auth.ParseAuthMethod(authstring) - if err != nil { t.Fatalf("Auth methods should parse without error, got %s", err) } diff --git a/pkg/server/handler.go b/pkg/server/handler.go index 57d905f433..cbe0bd596f 100644 --- a/pkg/server/handler.go +++ b/pkg/server/handler.go @@ -13,11 +13,9 @@ import ( "github.com/weaveworks/weave-gitops/pkg/server/middleware" ) -var ( - PublicRoutes = []string{ - "/v1/featureflags", - } -) +var PublicRoutes = []string{ + "/v1/featureflags", +} type Config struct { CoreServerConfig core.CoreServerConfig diff --git a/pkg/server/middleware/middleware.go b/pkg/server/middleware/middleware.go index a06302deb5..7f8e4a9d6e 100644 --- a/pkg/server/middleware/middleware.go +++ b/pkg/server/middleware/middleware.go @@ -25,9 +25,11 @@ func (r *statusRecorder) WriteHeader(status int) { r.ResponseWriter.WriteHeader(status) } -var RequestOkText = "request success" -var RequestErrorText = "request error" -var ServerErrorText = "server error" +var ( + RequestOkText = "request success" + RequestErrorText = "request error" + ServerErrorText = "server error" +) // WithGrpcErrorLogging logs errors returned from server RPC handlers. // Our errors happen in gRPC land, so we cannot introspect into the content of diff --git a/pkg/server/server.go b/pkg/server/server.go index 967992aa87..0152204f41 100644 --- a/pkg/server/server.go +++ b/pkg/server/server.go @@ -1,4 +1,6 @@ package server -const DefaultHost = "0.0.0.0" -const DefaultPort = "9001" +const ( + DefaultHost = "0.0.0.0" + DefaultPort = "9001" +) diff --git a/pkg/services/auth/github.go b/pkg/services/auth/github.go index 155d2745f1..a18592d001 100644 --- a/pkg/services/auth/github.go +++ b/pkg/services/auth/github.go @@ -112,11 +112,15 @@ func doGithubCodeRequest(client *http.Client, scope string) (*GithubDeviceCodeRe return d, nil } -var ErrAuthPending = errors.New("auth pending") -var ErrSlowDown = errors.New("slow down") +var ( + ErrAuthPending = errors.New("auth pending") + ErrSlowDown = errors.New("slow down") +) -const accessTokenURL = "https://github.com/login/oauth/access_token?%s" -const githubRequiredGrantType = "urn:ietf:params:oauth:grant-type:device_code" +const ( + accessTokenURL = "https://github.com/login/oauth/access_token?%s" + githubRequiredGrantType = "urn:ietf:params:oauth:grant-type:device_code" +) // It appears we need `repo` scope, which is VERY permissive. // We need to be able to push a deploy key and merge commits. No other scopes matched. diff --git a/pkg/services/auth/gitlab.go b/pkg/services/auth/gitlab.go index 760e152586..ce7c4c015d 100644 --- a/pkg/services/auth/gitlab.go +++ b/pkg/services/auth/gitlab.go @@ -112,7 +112,6 @@ func parseTokenResponseBody(body io.ReadCloser) (internal.GitlabTokenResponse, e var tokenResponse internal.GitlabTokenResponse err := json.NewDecoder(body).Decode(&tokenResponse) - if err != nil { return internal.GitlabTokenResponse{}, err } diff --git a/pkg/services/auth/jwt.go b/pkg/services/auth/jwt.go index 18336643b8..f2b46065f4 100644 --- a/pkg/services/auth/jwt.go +++ b/pkg/services/auth/jwt.go @@ -78,7 +78,6 @@ func (i *internalJWTClient) VerifyJWT(accessToken string) (*Claims, error) { return []byte(i.secretKey), nil }, ) - if err != nil { return nil, fmt.Errorf("%w: %w", ErrUnauthorizedToken, err) } diff --git a/pkg/services/auth/types/token_test.go b/pkg/services/auth/types/token_test.go index fd1b24f739..86799567c7 100644 --- a/pkg/services/auth/types/token_test.go +++ b/pkg/services/auth/types/token_test.go @@ -10,7 +10,6 @@ import ( ) var _ = Describe("TokenResponseState", func() { - var token *TokenResponseState var tokenResponse internal.GitlabTokenResponse @@ -39,6 +38,5 @@ var _ = Describe("TokenResponseState", func() { Expect(token.ExpiresIn).To(Equal(time.Duration(seconds) * time.Second)) Expect(token.RefreshToken).To(Equal(refreshToken)) Expect(token.CreatedAt).To(Equal(createdAt)) - }) }) diff --git a/pkg/services/crd/suite_test.go b/pkg/services/crd/suite_test.go index 347cdef802..cdceff22bb 100644 --- a/pkg/services/crd/suite_test.go +++ b/pkg/services/crd/suite_test.go @@ -32,7 +32,6 @@ func TestMain(m *testing.M) { "../../../manifests/crds", "../../../tools/testcrds", }) - if err != nil { panic(err) } diff --git a/pkg/sourceignore/sourceignore.go b/pkg/sourceignore/sourceignore.go index a03f7029d7..d12d7980d9 100644 --- a/pkg/sourceignore/sourceignore.go +++ b/pkg/sourceignore/sourceignore.go @@ -22,10 +22,8 @@ const ( ExcludeExtra = "**/.goreleaser.yml,**/.goreleaser.brew.yml,**/.sops.yaml,**/.flux.yaml,**/.golangci.yaml" ) -var ( - // ErrIgnoreFileExists is returned when the ignore file already exists when attempting to create it - ErrIgnoreFileExists = fmt.Errorf("%s file already exists", IgnoreFilename) -) +// ErrIgnoreFileExists is returned when the ignore file already exists when attempting to create it +var ErrIgnoreFileExists = fmt.Errorf("%s file already exists", IgnoreFilename) // IgnoreFilter ignores certain files based on a list of patterns and domain. type IgnoreFilter func(p string, fi os.FileInfo) bool diff --git a/pkg/testutils/testutils.go b/pkg/testutils/testutils.go index 6de8c36c77..d189d30d59 100644 --- a/pkg/testutils/testutils.go +++ b/pkg/testutils/testutils.go @@ -71,7 +71,6 @@ func StartK8sTestEnvironment(crdPaths []string) (*K8sTestEnv, error) { var err error cfg, err := testEnv.Start() - if err != nil { return nil, fmt.Errorf("could not start testEnv: %w", err) } diff --git a/pkg/utils/string_test.go b/pkg/utils/string_test.go index 287e9b75d4..291069152b 100644 --- a/pkg/utils/string_test.go +++ b/pkg/utils/string_test.go @@ -6,7 +6,6 @@ import ( ) var _ = Describe("Generate random string", func() { - It("does not return the same value on each call", func() { value1, _ := GenerateRandomString(10, 20) value2, _ := GenerateRandomString(10, 20) @@ -36,5 +35,4 @@ var _ = Describe("Generate random string", func() { Expect(err).To(BeNil()) Expect(len(value)).To(BeNumerically("<", 12)) }) - }) diff --git a/pkg/validate/validate.go b/pkg/validate/validate.go index 8717131d1f..626106cca7 100644 --- a/pkg/validate/validate.go +++ b/pkg/validate/validate.go @@ -41,7 +41,6 @@ func Validate(log logger.Logger, targetDir, rootDir, kubernetesVersion, fluxVers cli := cleanhttp.DefaultClient() url := fmt.Sprintf("https://github.com/fluxcd/flux2/releases/download/%s/crd-schemas.tar.gz", fluxVersion) response, err := cli.Get(url) - if err != nil { return err } @@ -108,7 +107,6 @@ func Validate(log logger.Logger, targetDir, rootDir, kubernetesVersion, fluxVers return nil }) - if err != nil { return err } @@ -143,7 +141,6 @@ func Validate(log logger.Logger, targetDir, rootDir, kubernetesVersion, fluxVers Strict: true, IgnoreMissingSchemas: true, }) - if err != nil { return err } diff --git a/pkg/version/version.go b/pkg/version/version.go index 19a3824b84..29045f8301 100644 --- a/pkg/version/version.go +++ b/pkg/version/version.go @@ -1,8 +1,6 @@ package version -var ( - // The constants below are to be set by flags passed to `go build`. - // Examples: -X version.FluxVersion=xxxxx +// The constants below are to be set by flags passed to `go build`. +// Examples: -X version.FluxVersion=xxxxx - FluxVersion = "latest" -) +var FluxVersion = "latest"