diff --git a/.golangci.yml b/.golangci.yml index 7b516a98ea..90bc437aba 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -12,6 +12,8 @@ linters: - whitespace - gocognit - unparam + - gocyclo + - gocritic run: timeout: 10m # golangci-lint run's timeout. @@ -29,3 +31,7 @@ issues: - text: "`ctx` is unused" # Context might not be in use in places, but for consistency, we pass it. linters: - unparam + +linters-settings: + gocyclo: + min-complexity: 20 diff --git a/cmd/kanctl/main.go b/cmd/kanctl/main.go index d594b48d4a..81aef8fbeb 100644 --- a/cmd/kanctl/main.go +++ b/cmd/kanctl/main.go @@ -21,7 +21,7 @@ import ( func init() { // We silence all non-fatal log messages. - //logrus.SetLevel(logrus.ErrorLevel) + // logrus.SetLevel(logrus.ErrorLevel) } func main() { diff --git a/pkg/blockstorage/awsefs/awsefs.go b/pkg/blockstorage/awsefs/awsefs.go index c7af278296..f62d301a90 100644 --- a/pkg/blockstorage/awsefs/awsefs.go +++ b/pkg/blockstorage/awsefs/awsefs.go @@ -565,7 +565,7 @@ func (e *Efs) SnapshotsListWLimit(ctx context.Context, tags map[string]string, l req := &backup.ListRecoveryPointsByBackupVaultInput{} req.SetBackupVaultName(e.backupVaultName) req.SetMaxResults(limit) - resp, err := e.ListRecoveryPointsByBackupVaultWithContext(ctx, req) //backup API + resp, err := e.ListRecoveryPointsByBackupVaultWithContext(ctx, req) // backup API if err != nil { return nil, errors.Wrap(err, "Failed to list recovery points by vault") } diff --git a/pkg/blockstorage/azure/azuredisk.go b/pkg/blockstorage/azure/azuredisk.go index cbe190a727..c74a52cbbd 100644 --- a/pkg/blockstorage/azure/azuredisk.go +++ b/pkg/blockstorage/azure/azuredisk.go @@ -199,47 +199,20 @@ func (s *AdStorage) SnapshotCopyWithArgs(ctx context.Context, from blockstorage. blob := container.GetBlobReference(blobName) defer deleteBlob(blob, blobName) - var copyOptions *storage.CopyOptions - if t, ok := ctx.Deadline(); ok { - time := time.Until(t).Seconds() - if time <= 0 { - return nil, errors.New("Context deadline exceeded, cannot copy snapshot") - } - copyOptions = &storage.CopyOptions{ - Timeout: uint(time), - } + copyOptions, err := getCopyOptions(ctx) + if err != nil { + return nil, err } err = blob.Copy(*accessURI.AccessSAS, copyOptions) if err != nil { return nil, errors.Wrapf(err, "Failed to copy disk to blob") } - blobURI := blob.GetURL() - snapId, err := uuid.NewV1() if err != nil { return nil, errors.Wrap(err, "Failed to create UUID") } snapName := fmt.Sprintf(snapshotNameFmt, snapId.String()) - var tags = make(map[string]string) - for _, tag := range from.Volume.Tags { - if _, found := tags[tag.Key]; !found { - tags[tag.Key] = tag.Value - } - } - tags = blockstorage.SanitizeTags(ktags.GetTags(tags)) - - createSnap := azcompute.Snapshot{ - Name: azto.StringPtr(snapName), - Location: azto.StringPtr(to.Region), - Tags: *azto.StringMapPtr(tags), - SnapshotProperties: &azcompute.SnapshotProperties{ - CreationData: &azcompute.CreationData{ - CreateOption: azcompute.Import, - StorageAccountID: azto.StringPtr(storageAccountID), - SourceURI: azto.StringPtr(blobURI), - }, - }, - } + createSnap := getSnapshotObject(blob, from, to, snapName, storageAccountID) migrateResourceGroup := s.azCli.ResourceGroup if val, ok := args[blockstorage.AzureMigrateResourceGroup]; ok && val != "" { @@ -266,14 +239,60 @@ func (s *AdStorage) SnapshotCopyWithArgs(ctx context.Context, from blockstorage. return snap, nil } +func getCopyOptions(ctx context.Context) (*storage.CopyOptions, error) { + var copyOptions *storage.CopyOptions + if t, ok := ctx.Deadline(); ok { + time := time.Until(t).Seconds() + if time <= 0 { + return nil, errors.New("Context deadline exceeded, cannot copy snapshot") + } + copyOptions = &storage.CopyOptions{ + Timeout: uint(time), + } + } + return copyOptions, nil +} + +func getSnapshotObject( + blob *storage.Blob, + from, + to blockstorage.Snapshot, + snapName, + storageAccountID string, +) azcompute.Snapshot { + blobURI := blob.GetURL() + + var tags = make(map[string]string) + for _, tag := range from.Volume.Tags { + if _, found := tags[tag.Key]; !found { + tags[tag.Key] = tag.Value + } + } + tags = blockstorage.SanitizeTags(ktags.GetTags(tags)) + + createSnap := azcompute.Snapshot{ + Name: azto.StringPtr(snapName), + Location: azto.StringPtr(to.Region), + Tags: *azto.StringMapPtr(tags), + SnapshotProperties: &azcompute.SnapshotProperties{ + CreationData: &azcompute.CreationData{ + CreateOption: azcompute.Import, + StorageAccountID: azto.StringPtr(storageAccountID), + SourceURI: azto.StringPtr(blobURI), + }, + }, + } + return createSnap +} + func isMigrateStorageAccountorKey(migrateStorageAccount, migrateStorageKey string) bool { return migrateStorageAccount == "" || migrateStorageKey == "" } -func (s *AdStorage) revokeAccess(ctx context.Context, rg, name, ID string) { +func (s *AdStorage) revokeAccess(ctx context.Context, rg, name, id string) { _, err := s.azCli.SnapshotsClient.RevokeAccess(ctx, rg, name) if err != nil { - log.Print("Failed to revoke access from snapshot", field.M{"snapshot": ID}) + log.Print("Failed to revoke access from snapshot", field.M{"snapshot": id}) } } @@ -554,7 +573,7 @@ func (s *AdStorage) VolumeCreateFromSnapshot(ctx context.Context, snapshot block } func (s *AdStorage) getRegionAndZoneID(ctx context.Context, sourceRegion, volAz string) (string, string, error) { - //check if current node region is zoned or not + // check if current node region is zoned or not kubeCli, err := kube.NewClient() if err != nil { return "", "", err diff --git a/pkg/blockstorage/tags/tags.go b/pkg/blockstorage/tags/tags.go index b482124e4f..c27a2d4b29 100644 --- a/pkg/blockstorage/tags/tags.go +++ b/pkg/blockstorage/tags/tags.go @@ -103,14 +103,14 @@ func IsSubset(set map[string]string, subset map[string]string) bool { return true } -// Union returns union of A and B as a new map. -// B's values have priority if a key from A and B collides. -func Union(A map[string]string, B map[string]string) map[string]string { +// Union returns union of first and second as a new map. +// second's values have priority if a key from first and second collides. +func Union(first map[string]string, second map[string]string) map[string]string { result := make(map[string]string) - for k, v := range A { + for k, v := range first { result[k] = v } - for k, v := range B { + for k, v := range second { result[k] = v } return result diff --git a/pkg/blockstorage/vmware/vmware.go b/pkg/blockstorage/vmware/vmware.go index ceeea73867..51013a7d24 100644 --- a/pkg/blockstorage/vmware/vmware.go +++ b/pkg/blockstorage/vmware/vmware.go @@ -811,11 +811,12 @@ func (ge govmomiError) ExtractMessages() []string { case govmomitask.Error: foundHandledErrorType = true default: - if soap.IsSoapFault(err) { + switch { + case soap.IsSoapFault(err): foundHandledErrorType = true - } else if soap.IsVimFault(err) { + case soap.IsVimFault(err): foundHandledErrorType = true - } else { + default: err = errors.Unwrap(err) } } diff --git a/pkg/blockstorage/zone/zone_test.go b/pkg/blockstorage/zone/zone_test.go index f74c289d05..4e69b5a2b5 100644 --- a/pkg/blockstorage/zone/zone_test.go +++ b/pkg/blockstorage/zone/zone_test.go @@ -23,7 +23,7 @@ import ( "github.com/kanisterio/kanister/pkg/kube" . "gopkg.in/check.v1" - "k8s.io/api/core/v1" + v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/kubernetes/fake" @@ -543,14 +543,14 @@ func (s ZoneSuite) TestFromSourceRegionZone(c *C) { outZones []string outErr error }{ - { //success case + { // success case inRegion: "us-west-2", inZones: []string{"us-west-2a"}, inCli: cli, outZones: []string{"us-west-2a"}, outErr: nil, }, - { //success case gce multi region + { // success case gce multi region inRegion: "us-west1", inZones: []string{"us-west1-a"}, inCli: cligce, diff --git a/pkg/blueprint/validate/validate.go b/pkg/blueprint/validate/validate.go index 4a40a98988..44a496e426 100644 --- a/pkg/blueprint/validate/validate.go +++ b/pkg/blueprint/validate/validate.go @@ -73,9 +73,10 @@ func Do(bp *crv1alpha1.Blueprint, funcVersion string) error { func validatePhaseNames(bp *crv1alpha1.Blueprint) error { phasesCount := make(map[string]int) for _, action := range bp.Actions { - allPhases := action.Phases + allPhases := []crv1alpha1.BlueprintPhase{} + allPhases = append(allPhases, action.Phases...) if action.DeferPhase != nil { - allPhases = append(action.Phases, *action.DeferPhase) + allPhases = append(allPhases, *action.DeferPhase) } for _, phase := range allPhases { diff --git a/pkg/controller/controller.go b/pkg/controller/controller.go index e06dc34c7f..31e35662b0 100644 --- a/pkg/controller/controller.go +++ b/pkg/controller/controller.go @@ -246,11 +246,12 @@ func (c *Controller) onUpdateActionSet(oldAS, newAS *crv1alpha1.ActionSet) error return err } if newAS.Status == nil || newAS.Status.State != crv1alpha1.StateRunning { - if newAS.Status == nil { + switch { + case newAS.Status == nil: log.WithContext(ctx).Print("Updated ActionSet", field.M{"Status": "nil"}) - } else if newAS.Status.State == crv1alpha1.StateComplete { + case newAS.Status.State == crv1alpha1.StateComplete: c.logAndSuccessEvent(ctx, fmt.Sprintf("Updated ActionSet '%s' Status->%s", newAS.Name, newAS.Status.State), "Update Complete", newAS) - } else { + default: log.WithContext(ctx).Print("Updated ActionSet", field.M{"Status": newAS.Status.State}) } return nil diff --git a/pkg/controller/controller_test.go b/pkg/controller/controller_test.go index 1a25b65446..33efabfb7b 100644 --- a/pkg/controller/controller_test.go +++ b/pkg/controller/controller_test.go @@ -703,7 +703,7 @@ func (s *ControllerSuite) TestRuntimeObjEventLogs(c *C) { msg := "Unit testing event logs" reason := "Test Logs" - //Create nil ActionSet + // Create nil ActionSet var nilAs = (*crv1alpha1.ActionSet)(nil) // Create Blueprint @@ -711,7 +711,7 @@ func (s *ControllerSuite) TestRuntimeObjEventLogs(c *C) { bp, err = s.crCli.Blueprints(s.namespace).Create(ctx, bp, metav1.CreateOptions{}) c.Assert(err, IsNil) - //Test the logAndErrorEvent function + // Test the logAndErrorEvent function ctx = field.Context(ctx, consts.ActionsetNameKey, as.GetName()) config, err := kube.LoadConfig() c.Assert(err, IsNil) @@ -725,19 +725,19 @@ func (s *ControllerSuite) TestRuntimeObjEventLogs(c *C) { c.Assert(len(events.Items) > 0, Equals, true) c.Assert(events.Items[0].Message, Equals, msg) - //Testing nil ActionSet error event logging + // Testing nil ActionSet error event logging events, err = s.cli.CoreV1().Events(as.Namespace).Search(scheme.Scheme, nilAs) c.Assert(err, NotNil) c.Assert(len(events.Items), Equals, 0) - //Testing Blueprint error event logging + // Testing Blueprint error event logging events, err = s.cli.CoreV1().Events(bp.Namespace).Search(scheme.Scheme, bp) c.Assert(err, IsNil) c.Assert(events, NotNil) c.Assert(len(events.Items) > 0, Equals, true) c.Assert(events.Items[0].Message, Equals, msg) - //Testing empty Blueprint + // Testing empty Blueprint testbp := &crv1alpha1.Blueprint{} ctlr.logAndErrorEvent(ctx, msg, reason, errors.New("Testing Event Logs"), testbp) events, err = s.cli.CoreV1().Events(bp.Namespace).Search(scheme.Scheme, testbp) diff --git a/pkg/controllers/repositoryserver/repositoryserver_controller_test.go b/pkg/controllers/repositoryserver/repositoryserver_controller_test.go index a9ce5aa3e9..3040b8e9de 100644 --- a/pkg/controllers/repositoryserver/repositoryserver_controller_test.go +++ b/pkg/controllers/repositoryserver/repositoryserver_controller_test.go @@ -233,7 +233,7 @@ func (s *RepoServerControllerSuite) TestRepositoryServerImmutability(c *C) { repoServerCRCreated, err := s.crCli.RepositoryServers(s.repoServerControllerNamespace).Create(ctx, &repoServerCR, metav1.CreateOptions{}) c.Assert(err, IsNil) - //Update the repository server CR's Immutable field. + // Update the repository server CR's Immutable field. patch := []patchStringValue{{ Op: "replace", Path: "/spec/repository/rootPath", @@ -265,7 +265,7 @@ func (s *RepoServerControllerSuite) TestRepositoryServerStatusIsServerReady(c *C err = s.waitForRepoServerInfoUpdateInCR(repoServerCRCreated.Name) c.Assert(err, IsNil) - //Get repository server CR with the updated server information + // Get repository server CR with the updated server information repoServerCRCreated, err = s.crCli.RepositoryServers(s.repoServerControllerNamespace).Get(ctx, repoServerCRCreated.Name, metav1.GetOptions{}) c.Assert(err, IsNil) @@ -312,7 +312,7 @@ func (s *RepoServerControllerSuite) TestCreationOfOwnedResources(c *C) { err = s.waitForRepoServerInfoUpdateInCR(repoServerCRCreated.Name) c.Assert(err, IsNil) - //Get repository server CR with the updated server information + // Get repository server CR with the updated server information repoServerCRCreated, err = s.crCli.RepositoryServers(s.repoServerControllerNamespace).Get(ctx, repoServerCRCreated.Name, metav1.GetOptions{}) c.Assert(err, IsNil) @@ -434,7 +434,7 @@ func (s *RepoServerControllerSuite) TestFilestoreLocationVolumeMountOnRepoServer err = s.waitForRepoServerInfoUpdateInCR(repoServerCRCreated.Name) c.Assert(err, IsNil) - //Get repository server CR with the updated server information + // Get repository server CR with the updated server information repoServerCRCreated, err = s.crCli.RepositoryServers(s.repoServerControllerNamespace).Get(ctx, repoServerCRCreated.Name, metav1.GetOptions{}) c.Assert(err, IsNil) diff --git a/pkg/datamover/profile_test.go b/pkg/datamover/profile_test.go index ef1537d780..1f8af86363 100644 --- a/pkg/datamover/profile_test.go +++ b/pkg/datamover/profile_test.go @@ -64,7 +64,7 @@ func (ps *ProfileSuite) TestLocationOperationsForProfileDataMover(c *C) { err = locationDelete(ps.ctx, p, path) c.Assert(err, IsNil) - //test deleting dir with multiple artifacts + // test deleting dir with multiple artifacts source = bytes.NewBufferString(testContent) err = locationPush(ps.ctx, p, path, source) c.Assert(err, IsNil) diff --git a/pkg/filter/filter.go b/pkg/filter/filter.go index 1d8547ba21..ae161213d7 100644 --- a/pkg/filter/filter.go +++ b/pkg/filter/filter.go @@ -145,7 +145,7 @@ type ResourceRequirement struct { // DeepCopyInto provides explicit deep copy implementation to avoid func (r ResourceRequirement) DeepCopyInto(out *ResourceRequirement) { r.LocalObjectReference.DeepCopyInto(&out.LocalObjectReference) - (*out).ResourceTypeRequirement = r.ResourceTypeRequirement + out.ResourceTypeRequirement = r.ResourceTypeRequirement r.LabelSelector.DeepCopyInto(&out.LabelSelector) } diff --git a/pkg/function/export_rds_snapshot_location.go b/pkg/function/export_rds_snapshot_location.go index 3828fe7fb8..aac1417d92 100644 --- a/pkg/function/export_rds_snapshot_location.go +++ b/pkg/function/export_rds_snapshot_location.go @@ -286,8 +286,7 @@ func prepareCommand( return nil, "", err } - switch dbEngine { - case PostgrSQLEngine: + if dbEngine == PostgrSQLEngine { switch action { case BackupAction: // For backup operation, if database arg is not set, we take backup of all databases diff --git a/pkg/kanctl/actionset.go b/pkg/kanctl/actionset.go index c35a028eb3..39b8da6f2a 100644 --- a/pkg/kanctl/actionset.go +++ b/pkg/kanctl/actionset.go @@ -88,9 +88,7 @@ func newActionSetCmd() *cobra.Command { Use: "actionset", Short: "Create a new ActionSet or override a ActionSet", Args: cobra.ExactArgs(0), - RunE: func(c *cobra.Command, args []string) error { - return initializeAndPerform(c, args) - }, + RunE: initializeAndPerform, } cmd.Flags().StringP(sourceFlagName, "f", "", "specify name of the action set") @@ -558,7 +556,7 @@ func parseGenericObjectReference(s string) (crv1alpha1.ObjectReference, error) { }, nil } -func parseObjectsFromSelector(selector, kind, sns string, cli kubernetes.Interface, osCli osversioned.Interface, parsed map[string]bool) ([]crv1alpha1.ObjectReference, error) { +func parseObjectsFromSelector(selector, kind, sns string, cli kubernetes.Interface, osCli osversioned.Interface, parsed map[string]bool) ([]crv1alpha1.ObjectReference, error) { //nolint:gocyclo ctx := context.Background() var objects []crv1alpha1.ObjectReference appendObj := func(kind, namespace, name string) { diff --git a/pkg/kanctl/profile.go b/pkg/kanctl/profile.go index c7866a5857..2938712bb6 100644 --- a/pkg/kanctl/profile.go +++ b/pkg/kanctl/profile.go @@ -95,9 +95,7 @@ func newS3CompliantProfileCmd() *cobra.Command { Use: "s3compliant", Short: "Create new S3 compliant profile", Args: cobra.ExactArgs(0), - RunE: func(cmd *cobra.Command, args []string) error { - return createNewProfile(cmd, args) - }, + RunE: createNewProfile, } cmd.Flags().StringP(awsAccessKeyFlag, "a", "", "access key of the s3 compliant bucket") @@ -114,9 +112,7 @@ func newGCPProfileCmd() *cobra.Command { Use: "gcp", Short: "Create new gcp profile", Args: cobra.ExactArgs(0), - RunE: func(cmd *cobra.Command, args []string) error { - return createNewProfile(cmd, args) - }, + RunE: createNewProfile, } cmd.Flags().StringP(gcpProjectIDFlag, "a", "", "Project ID of the google application") @@ -132,9 +128,7 @@ func newAzureProfileCmd() *cobra.Command { Use: "azure", Short: "Create new azure profile", Args: cobra.ExactArgs(0), - RunE: func(cmd *cobra.Command, args []string) error { - return createNewProfile(cmd, args) - }, + RunE: createNewProfile, } cmd.Flags().StringP(AzureStorageAccountFlag, "a", "", "Storage account name of the azure storage") @@ -263,7 +257,7 @@ func constructProfile(lP *locationParams, secret *v1.Secret) *v1alpha1.Profile { }, }, } - case lP.locationType == v1alpha1.LocationTypeGCS: //GCP + case lP.locationType == v1alpha1.LocationTypeGCS: // GCP creds = v1alpha1.Credential{ Type: v1alpha1.CredentialTypeKeyPair, KeyPair: &v1alpha1.KeyPair{ @@ -490,7 +484,7 @@ func getServiceKey(ctx context.Context, filename string) (string, error) { if err != nil { return "", err } - //Parse the service key + // Parse the service key _, err = google.CredentialsFromJSON(ctx, b, compute.ComputeScope) if err != nil { return "", err diff --git a/pkg/kanctl/repositoryserver.go b/pkg/kanctl/repositoryserver.go index 52c660b9f7..a3ac978649 100644 --- a/pkg/kanctl/repositoryserver.go +++ b/pkg/kanctl/repositoryserver.go @@ -64,9 +64,7 @@ func newRepositoryServerCommand() *cobra.Command { Use: "repository-server", Short: "Create a new RepositoryServer", Args: cobra.ExactArgs(0), - RunE: func(cmd *cobra.Command, args []string) error { - return createNewRepositoryServer(cmd, args) - }, + RunE: createNewRepositoryServer, } cmd.PersistentFlags().StringP(tlsSecretFlag, "t", "", "name of the tls secret needed for secure kopia client and kopia repository server communication") diff --git a/pkg/kanctl/validate.go b/pkg/kanctl/validate.go index c3de036df8..b643c7ce03 100644 --- a/pkg/kanctl/validate.go +++ b/pkg/kanctl/validate.go @@ -42,9 +42,7 @@ func newValidateCommand() *cobra.Command { Use: "validate ", Short: "Validate custom Kanister resources", Args: cobra.ExactArgs(1), - RunE: func(cmd *cobra.Command, args []string) error { - return performValidation(cmd, args) - }, + RunE: performValidation, } cmd.Flags().String(nameFlag, "", "specify the K8s name of the custom resource to validate") cmd.Flags().StringP(filenameFlag, "f", "", "yaml or json file of the custom resource to validate") diff --git a/pkg/kando/output.go b/pkg/kando/output.go index e00838da58..13f372163c 100644 --- a/pkg/kando/output.go +++ b/pkg/kando/output.go @@ -25,13 +25,9 @@ func newOutputCommand() *cobra.Command { cmd := &cobra.Command{ Use: "output ", Short: "Create phase output with given key:value", - Args: func(c *cobra.Command, args []string) error { - return validateArguments(c, args) - }, + Args: validateArguments, // TODO: Example invocations - RunE: func(c *cobra.Command, args []string) error { - return runOutputCommand(c, args) - }, + RunE: runOutputCommand, } return cmd } diff --git a/pkg/kando/stream_push.go b/pkg/kando/stream_push.go index 8ec041239d..8497b34439 100644 --- a/pkg/kando/stream_push.go +++ b/pkg/kando/stream_push.go @@ -34,9 +34,7 @@ func newStreamPushCommand() *cobra.Command { Use: "push ", Short: "Push the output of a stream source to object storage", Args: cobra.ExactArgs(1), - RunE: func(c *cobra.Command, args []string) error { - return runStreamPush(c, args) - }, + RunE: runStreamPush, } cmd.Flags().StringP(streamPushDirPathFlagName, "d", "", "Specify a root directory path for the data stream (required)") cmd.Flags().StringP(streamPushFilePathFlagName, "f", "", "Specify a file name or path for the data stream (required)") diff --git a/pkg/kube/pod.go b/pkg/kube/pod.go index 8f7b089d1e..0ad6e06102 100644 --- a/pkg/kube/pod.go +++ b/pkg/kube/pod.go @@ -152,6 +152,10 @@ func GetPodObjectFromPodOptions(ctx context.Context, cli kubernetes.Interface, o return patchedSpecs.Containers[i].Name == ContainerNameFromPodOptsOrDefault(opts) }) + return createPodSpec(opts, patchedSpecs, ns), nil +} + +func createPodSpec(opts *PodOptions, patchedSpecs v1.PodSpec, ns string) *v1.Pod { pod := &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ GenerateName: opts.GenerateName, @@ -196,8 +200,7 @@ func GetPodObjectFromPodOptions(ctx context.Context, cli kubernetes.Interface, o } pod.Namespace = ns - - return pod, nil + return pod } // ContainerNameFromPodOptsOrDefault returns the container name if it's set in @@ -408,8 +411,7 @@ func WaitForPodCompletion(ctx context.Context, cli kubernetes.Interface, namespa return true, err } containerForLogs = p.Spec.Containers[0].Name - switch p.Status.Phase { - case v1.PodFailed: + if p.Status.Phase == v1.PodFailed { return false, errors.Errorf("Pod %s failed. Pod status: %s", name, p.Status.String()) } return p.Status.Phase == v1.PodSucceeded, nil diff --git a/pkg/kube/volume/volume.go b/pkg/kube/volume/volume.go index be76c32739..08dc56fdd8 100644 --- a/pkg/kube/volume/volume.go +++ b/pkg/kube/volume/volume.go @@ -320,6 +320,9 @@ func labelSelector(labels map[string]string) string { // zoneToRegion removes -latter or just last latter from provided zone. func zoneToRegion(zone string) string { - r, _ := regexp.Compile("-?[a-z]$") + // TODO: gocritic rule below suggests to use regexp.MustCompile but it + // panics if regex cannot be compiled. We should add proper test before + // enabling this below so that no change to this regex results in a panic + r, _ := regexp.Compile("-?[a-z]$") //nolint:gocritic return r.ReplaceAllString(zone, "") } diff --git a/pkg/log/log_test.go b/pkg/log/log_test.go index 0f0eee14be..dfbff9f6a6 100644 --- a/pkg/log/log_test.go +++ b/pkg/log/log_test.go @@ -174,14 +174,14 @@ func (s *LogSuite) TestLogLevel(c *C) { log.SetOutput(&output) ctx := field.Context(context.Background(), "key", "value") var entry map[string]interface{} - //Check if debug level log is printed when log level is info + // Check if debug level log is printed when log level is info Debug().WithContext(ctx).Print("Testing debug level") err := json.Unmarshal(output.Bytes(), &entry) c.Assert(err, NotNil) c.Assert(output.String(), HasLen, 0) - //Check if debug level log is printed when log level is debug + // Check if debug level log is printed when log level is debug os.Setenv(LevelEnvName, "debug") defer func() { os.Unsetenv(LevelEnvName) diff --git a/pkg/objectstore/directory.go b/pkg/objectstore/directory.go index dc6ae0b360..e1d28f5674 100644 --- a/pkg/objectstore/directory.go +++ b/pkg/objectstore/directory.go @@ -298,7 +298,7 @@ func (d *directory) absPathName(name string) string { func sanitizeTags(tags map[string]string) map[string]interface{} { cTags := make(map[string]interface{}) for key, val := range tags { - cKey := strings.Replace(key, "/", "-", -1) + cKey := strings.ReplaceAll(key, "/", "-") cTags[cKey] = val } return cTags diff --git a/pkg/objectstore/objectstore_test.go b/pkg/objectstore/objectstore_test.go index a03a03f6ea..af44ae732c 100644 --- a/pkg/objectstore/objectstore_test.go +++ b/pkg/objectstore/objectstore_test.go @@ -421,7 +421,7 @@ func (s *ObjectStoreProviderSuite) createBucketName(c *C) string { } // GCS bucket names cannot contain '.' (except for recognized top-level domains) - bucketName = strings.Replace(bucketName, ".", "-", -1) + bucketName = strings.ReplaceAll(bucketName, ".", "-") return bucketName } diff --git a/pkg/progress/action.go b/pkg/progress/action.go index 3cea9fcb41..9a0ac8d31a 100644 --- a/pkg/progress/action.go +++ b/pkg/progress/action.go @@ -186,7 +186,7 @@ func SetActionSetPercentCompleted(actionSet *crv1alpha1.ActionSet) error { totalPhases++ } } - actionProgress = actionProgress / totalPhases + actionProgress /= totalPhases // Update LastTransitionTime only if there is a change in action PercentCompleted if strconv.Itoa(actionProgress) == actionSet.Status.Progress.PercentCompleted {