Skip to content

Commit

Permalink
Enable staticcheck and resolve found issues.
Browse files Browse the repository at this point in the history
Signed-off-by: Xun Jiang <blackpiglet@gmail.com>
  • Loading branch information
Xun Jiang committed Apr 25, 2023
1 parent 1fd28e8 commit cb0ada1
Show file tree
Hide file tree
Showing 24 changed files with 51 additions and 45 deletions.
4 changes: 0 additions & 4 deletions .github/workflows/pr-ci-check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,3 @@ jobs:
token: ${{ secrets.CODECOV_TOKEN }}
files: coverage.out
verbose: true
- name: Run staticcheck
uses: dominikh/staticcheck-action@v1.3.0
with:
version: "2022.1.3"
1 change: 1 addition & 0 deletions changelogs/unreleased/6183-blackpiglet
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Enable staticcheck and resolve found issues
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ require (
golang.org/x/net v0.7.0
golang.org/x/oauth2 v0.0.0-20220608161450-d0670ef3b1eb
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c
golang.org/x/text v0.7.0
google.golang.org/api v0.74.0
google.golang.org/grpc v1.45.0
google.golang.org/protobuf v1.28.0
Expand Down Expand Up @@ -135,7 +136,6 @@ require (
golang.org/x/exp v0.0.0-20210916165020-5cb4fee858ee // indirect
golang.org/x/sys v0.5.0 // indirect
golang.org/x/term v0.5.0 // indirect
golang.org/x/text v0.7.0 // indirect
golang.org/x/time v0.0.0-20220609170525-579cf78fd858 // indirect
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
gomodules.xyz/jsonpatch/v2 v2.2.0 // indirect
Expand Down
15 changes: 15 additions & 0 deletions golangci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ run:
# on Windows.
skip-dirs:
- test/e2e/*
- pkg/plugin/generated/*
# - autogenerated_by_my_lib

# default is true. Enables skipping of directories:
Expand Down Expand Up @@ -249,6 +250,8 @@ linters-settings:
rowserrcheck:
packages:
- github.com/jmoiron/sqlx
staticcheck:

testpackage:
# regexp pattern to skip files
skip-regexp: (export|internal)_test\.go
Expand Down Expand Up @@ -297,6 +300,7 @@ linters:
- goimports
- gosec
- misspell
- staticcheck
- typecheck
- unparam
- unused
Expand All @@ -306,6 +310,17 @@ linters:


issues:
exclude-rules:
- linters:
- staticcheck
text: "github.com/golang/protobuf/proto" # grpc-go still uses github.com/golang/protobuf/proto.
- linters:
- staticcheck
text: "github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2019-06-01/storage" # Kopia still depends on this.
- linters:
- staticcheck
text: "DefaultVolumesToRestic" # No need to report deprecate for DefaultVolumesToRestic.

# The list of ids of default excludes to include or disable. By default it's empty.
include:
- EXC0002 # disable excluding of issues about comments from golint
Expand Down
6 changes: 2 additions & 4 deletions pkg/backup/backup.go
Original file line number Diff line number Diff line change
Expand Up @@ -346,7 +346,6 @@ func (kb *kubernetesBackupper) BackupWithResolvers(log logrus.FieldLogger,
}()

backedUpGroupResources := map[schema.GroupResource]bool{}
totalItems := len(items)

for i, item := range items {
log.WithFields(map[string]interface{}{
Expand Down Expand Up @@ -381,7 +380,7 @@ func (kb *kubernetesBackupper) BackupWithResolvers(log logrus.FieldLogger,

// updated total is computed as "how many items we've backed up so far, plus
// how many items we know of that are remaining"
totalItems = len(backupRequest.BackedUpItems) + (len(items) - (i + 1))
totalItems := len(backupRequest.BackedUpItems) + (len(items) - (i + 1))

// send a progress update
update <- progressUpdate{
Expand Down Expand Up @@ -587,7 +586,6 @@ func (kb *kubernetesBackupper) FinalizeBackup(log logrus.FieldLogger,
}
updateFiles := make(map[string]FileForArchive)
backedUpGroupResources := map[schema.GroupResource]bool{}
totalItems := len(items)

for i, item := range items {
log.WithFields(map[string]interface{}{
Expand Down Expand Up @@ -626,7 +624,7 @@ func (kb *kubernetesBackupper) FinalizeBackup(log logrus.FieldLogger,

// updated total is computed as "how many items we've backed up so far, plus
// how many items we know of that are remaining"
totalItems = len(backupRequest.BackedUpItems) + (len(items) - (i + 1))
totalItems := len(backupRequest.BackedUpItems) + (len(items) - (i + 1))

log.WithFields(map[string]interface{}{
"progress": "",
Expand Down
1 change: 0 additions & 1 deletion pkg/backup/backup_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,6 @@ func TestBackedUpItemsMatchesTarballContents(t *testing.T) {
if item.namespace != "" {
fileWithVersion = fileWithVersion + "/v1-preferredversion/" + "namespaces/" + item.namespace
} else {
file = file + "/cluster"
fileWithVersion = fileWithVersion + "/v1-preferredversion" + "/cluster"
}
fileWithVersion = fileWithVersion + "/" + item.name + ".json"
Expand Down
4 changes: 4 additions & 0 deletions pkg/backup/item_collector.go
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,10 @@ func (r *itemCollector) getResourceItems(log logrus.FieldLogger, gv schema.Group
},
).Infof("Getting item")
resourceClient, err := r.dynamicFactory.ClientForGroupVersionResource(gv, resource, resourceID.Namespace)
if err != nil {
log.WithError(errors.WithStack(err)).Error("Error getting client for resource")
continue
}
unstructured, err := resourceClient.Get(resourceID.Name, metav1.GetOptions{})
if err != nil {
log.WithError(errors.WithStack(err)).Error("Error getting item")
Expand Down
4 changes: 2 additions & 2 deletions pkg/cmd/cli/backup/create_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,10 +105,10 @@ func TestCreateOptions_BuildBackupFromSchedule(t *testing.T) {
}

func TestCreateOptions_OrderedResources(t *testing.T) {
orderedResources, err := ParseOrderedResources("pods= ns1/p1; ns1/p2; persistentvolumeclaims=ns2/pvc1, ns2/pvc2")
_, err := ParseOrderedResources("pods= ns1/p1; ns1/p2; persistentvolumeclaims=ns2/pvc1, ns2/pvc2")
assert.NotNil(t, err)

orderedResources, err = ParseOrderedResources("pods= ns1/p1,ns1/p2 ; persistentvolumeclaims=ns2/pvc1,ns2/pvc2")
orderedResources, err := ParseOrderedResources("pods= ns1/p1,ns1/p2 ; persistentvolumeclaims=ns2/pvc1,ns2/pvc2")
assert.NoError(t, err)

expectedResources := map[string]string{
Expand Down
7 changes: 4 additions & 3 deletions pkg/cmd/cli/select_option.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,10 @@ package cli

import (
"errors"
"strings"

"github.com/spf13/pflag"
"golang.org/x/text/cases"
"golang.org/x/text/language"

"github.com/vmware-tanzu/velero/pkg/cmd/util/flag"
)
Expand Down Expand Up @@ -64,6 +65,6 @@ func (o *SelectOptions) Validate() error {

// BindFlags binds options for this command to flags.
func (o *SelectOptions) BindFlags(flags *pflag.FlagSet) {
flags.BoolVar(&o.All, "all", o.All, strings.Title(o.CMD)+" all "+o.SingularTypeName+"s")
flags.VarP(&o.Selector, "selector", "l", strings.Title(o.CMD)+" all "+o.SingularTypeName+"s matching this label selector.")
flags.BoolVar(&o.All, "all", o.All, cases.Title(language.Und).String(o.CMD)+" all "+o.SingularTypeName+"s")
flags.VarP(&o.Selector, "selector", "l", cases.Title(language.Und).String(o.CMD)+" all "+o.SingularTypeName+"s matching this label selector.")
}
2 changes: 1 addition & 1 deletion pkg/cmd/cli/version/version_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ func TestPrintVersion(t *testing.T) {
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
var (
kbClient = fake.NewFakeClientWithScheme(scheme.Scheme)
kbClient = fake.NewClientBuilder().WithScheme(scheme.Scheme).Build()
serverStatusGetter = new(mockServerStatusGetter)
buf = new(bytes.Buffer)
)
Expand Down
4 changes: 4 additions & 0 deletions pkg/cmd/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,10 @@ func newServer(f client.Factory, config serverConfig, logger *logrus.Logger) (*s
}

credentialSecretStore, err := credentials.NewNamespacedSecretStore(mgr.GetClient(), f.Namespace())
if err != nil {
cancelFunc()
return nil, err
}

s := &server{
namespace: f.Namespace(),
Expand Down
4 changes: 0 additions & 4 deletions pkg/cmd/util/output/output.go
Original file line number Diff line number Diff line change
Expand Up @@ -219,10 +219,6 @@ func printTable(cmd *cobra.Command, obj runtime.Object) (bool, error) {
return false, errors.Errorf("type %T is not supported", obj)
}

if table == nil {
return false, errors.Errorf("error generating table for type %T", obj)
}

// 2. print table
tablePrinter, err := NewPrinter(cmd)
if err != nil {
Expand Down
13 changes: 0 additions & 13 deletions pkg/controller/backup_sync_controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ import (
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/validation"
core "k8s.io/client-go/testing"
testclocks "k8s.io/utils/clock/testing"

ctrl "sigs.k8s.io/controller-runtime"
Expand Down Expand Up @@ -669,22 +668,10 @@ var _ = Describe("Backup Sync Reconciler", func() {
logger: velerotest.NewLogger(),
}

expectedDeleteActions := make([]core.Action, 0)

for _, backup := range test.k8sBackups {
// add test backup to client
err := client.Create(context.TODO(), backup, &ctrlClient.CreateOptions{})
Expect(err).ShouldNot(HaveOccurred())

// if we expect this backup to be deleted, set up the expected DeleteAction
if test.expectedDeletes.Has(backup.Name) {
actionDelete := core.NewDeleteAction(
velerov1api.SchemeGroupVersion.WithResource("backups"),
test.namespace,
backup.Name,
)
expectedDeleteActions = append(expectedDeleteActions, actionDelete)
}
}

bslName := "default"
Expand Down
4 changes: 3 additions & 1 deletion pkg/controller/pod_volume_backup_controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ var _ = Describe("PodVolumeBackup Reconciler", func() {
func(test request) {
ctx := context.Background()

fakeClient := fake.NewFakeClientWithScheme(scheme.Scheme)
fakeClient := fake.NewClientBuilder().WithScheme(scheme.Scheme).Build()
err = fakeClient.Create(ctx, test.pvb)
Expect(err).To(BeNil())

Expand All @@ -139,6 +139,8 @@ var _ = Describe("PodVolumeBackup Reconciler", func() {
fakeFS,
)

Expect(err).To(BeNil())

// Setup reconciler
Expect(velerov1api.AddToScheme(scheme.Scheme)).To(Succeed())
r := PodVolumeBackupReconciler{
Expand Down
1 change: 1 addition & 0 deletions pkg/controller/restore_operations_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,7 @@ func (r *restoreOperationsReconciler) updateRestoreAndOperationsJSON(
completionChanges bool) error {
if len(operations.ErrsSinceUpdate) > 0 {
// FIXME: download/upload results
r.logger.WithField("restore", restore.Name).Infof("Restore has %d errors", len(operations.ErrsSinceUpdate))
}
removeIfComplete := true
defer func() {
Expand Down
4 changes: 2 additions & 2 deletions pkg/persistence/object_store_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -412,7 +412,7 @@ func TestGetBackupVolumeSnapshots(t *testing.T) {

// volumesnapshots file containing invalid data should error
harness.objectStore.PutObject(harness.bucket, "backups/test-backup/test-backup-volumesnapshots.json.gz", newStringReadSeeker("foo"))
res, err = harness.GetBackupVolumeSnapshots("test-backup")
_, err = harness.GetBackupVolumeSnapshots("test-backup")
assert.NotNil(t, err)

// volumesnapshots file containing gzipped json data should return correctly
Expand Down Expand Up @@ -454,7 +454,7 @@ func TestGetBackupItemOperations(t *testing.T) {

// itemoperations file containing invalid data should error
harness.objectStore.PutObject(harness.bucket, "backups/test-backup/test-backup-itemoperations.json.gz", newStringReadSeeker("foo"))
res, err = harness.GetBackupItemOperations("test-backup")
_, err = harness.GetBackupItemOperations("test-backup")
assert.NotNil(t, err)

// itemoperations file containing gzipped json data should return correctly
Expand Down
1 change: 1 addition & 0 deletions pkg/plugin/framework/common/server_errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ limitations under the License.
package common

import (
//lint:ignore SA1019 grpc-go still depends on github.com/golang/protobuf/proto
goproto "github.com/golang/protobuf/proto"
"github.com/pkg/errors"
"google.golang.org/grpc/codes"
Expand Down
2 changes: 1 addition & 1 deletion pkg/podvolume/backupper.go
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ func (b *backupper) BackupPodVolumes(backup *velerov1api.Backup, pod *corev1api.
}

volumeBackup := newPodVolumeBackup(backup, pod, volume, repo.Spec.ResticIdentifier, b.uploaderType, pvc)
if volumeBackup, err = b.veleroClient.VeleroV1().PodVolumeBackups(volumeBackup.Namespace).Create(context.TODO(), volumeBackup, metav1.CreateOptions{}); err != nil {
if _, err = b.veleroClient.VeleroV1().PodVolumeBackups(volumeBackup.Namespace).Create(context.TODO(), volumeBackup, metav1.CreateOptions{}); err != nil {
errs = append(errs, err)
continue
}
Expand Down
1 change: 0 additions & 1 deletion pkg/staticcheck.conf

This file was deleted.

5 changes: 4 additions & 1 deletion pkg/test/discovery_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ package test
import (
"strings"

"golang.org/x/text/cases"
"golang.org/x/text/language"

metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/discovery"
discoveryfake "k8s.io/client-go/discovery/fake"
Expand Down Expand Up @@ -73,7 +76,7 @@ func (c *DiscoveryClient) WithAPIResource(resource *APIResource) *DiscoveryClien
Namespaced: resource.Namespaced,
Group: resource.Group,
Version: resource.Version,
Kind: strings.Title(strings.TrimSuffix(resource.Name, "s")),
Kind: cases.Title(language.Und).String(strings.TrimSuffix(resource.Name, "s")),
Verbs: metav1.Verbs([]string{"list", "create", "get", "delete"}),
ShortNames: []string{resource.ShortName},
})
Expand Down
2 changes: 1 addition & 1 deletion pkg/test/fake_controller_runtime_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,5 +48,5 @@ func NewFakeControllerRuntimeClient(t *testing.T, initObjs ...runtime.Object) cl
require.NoError(t, err)
err = snapshotv1api.AddToScheme(scheme)
require.NoError(t, err)
return k8sfake.NewFakeClientWithScheme(scheme, initObjs...)
return k8sfake.NewClientBuilder().WithScheme(scheme).WithRuntimeObjects(initObjs...).Build()
}
4 changes: 2 additions & 2 deletions pkg/uploader/provider/kopia_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ import (
func TestRunBackup(t *testing.T) {
var kp kopiaProvider
kp.log = logrus.New()
updater := FakeBackupProgressUpdater{PodVolumeBackup: &velerov1api.PodVolumeBackup{}, Log: kp.log, Ctx: context.Background(), Cli: fake.NewFakeClientWithScheme(scheme.Scheme)}
updater := FakeBackupProgressUpdater{PodVolumeBackup: &velerov1api.PodVolumeBackup{}, Log: kp.log, Ctx: context.Background(), Cli: fake.NewClientBuilder().WithScheme(scheme.Scheme).Build()}
testCases := []struct {
name string
hookBackupFunc func(ctx context.Context, fsUploader *snapshotfs.Uploader, repoWriter repo.RepositoryWriter, sourcePath, parentSnapshot string, log logrus.FieldLogger) (*uploader.SnapshotInfo, bool, error)
Expand Down Expand Up @@ -81,7 +81,7 @@ func TestRunBackup(t *testing.T) {
func TestRunRestore(t *testing.T) {
var kp kopiaProvider
kp.log = logrus.New()
updater := FakeRestoreProgressUpdater{PodVolumeRestore: &velerov1api.PodVolumeRestore{}, Log: kp.log, Ctx: context.Background(), Cli: fake.NewFakeClientWithScheme(scheme.Scheme)}
updater := FakeRestoreProgressUpdater{PodVolumeRestore: &velerov1api.PodVolumeRestore{}, Log: kp.log, Ctx: context.Background(), Cli: fake.NewClientBuilder().WithScheme(scheme.Scheme).Build()}

testCases := []struct {
name string
Expand Down
4 changes: 2 additions & 2 deletions pkg/uploader/provider/restic_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ import (
func TestResticRunBackup(t *testing.T) {
var rp resticProvider
rp.log = logrus.New()
updater := FakeBackupProgressUpdater{PodVolumeBackup: &velerov1api.PodVolumeBackup{}, Log: rp.log, Ctx: context.Background(), Cli: fake.NewFakeClientWithScheme(scheme.Scheme)}
updater := FakeBackupProgressUpdater{PodVolumeBackup: &velerov1api.PodVolumeBackup{}, Log: rp.log, Ctx: context.Background(), Cli: fake.NewClientBuilder().WithScheme(scheme.Scheme).Build()}
testCases := []struct {
name string
hookBackupFunc func(repoIdentifier string, passwordFile string, path string, tags map[string]string) *restic.Command
Expand Down Expand Up @@ -74,7 +74,7 @@ func TestResticRunBackup(t *testing.T) {
func TestResticRunRestore(t *testing.T) {
var rp resticProvider
rp.log = logrus.New()
updater := FakeBackupProgressUpdater{PodVolumeBackup: &velerov1api.PodVolumeBackup{}, Log: rp.log, Ctx: context.Background(), Cli: fake.NewFakeClientWithScheme(scheme.Scheme)}
updater := FakeBackupProgressUpdater{PodVolumeBackup: &velerov1api.PodVolumeBackup{}, Log: rp.log, Ctx: context.Background(), Cli: fake.NewClientBuilder().WithScheme(scheme.Scheme).Build()}
ResticRestoreCMDFunc = func(repoIdentifier, passwordFile, snapshotID, target string) *restic.Command {
return &restic.Command{Args: []string{""}}
}
Expand Down
1 change: 0 additions & 1 deletion test/staticcheck.conf

This file was deleted.

0 comments on commit cb0ada1

Please sign in to comment.