chore(golangci-lint): updating to latest version and code alignement

This commit is contained in:
Dario Tranchitella
2023-03-02 14:10:14 +01:00
parent da78423f42
commit 89348c9499
32 changed files with 47 additions and 70 deletions

View File

@@ -24,9 +24,9 @@ jobs:
- name: Run golangci-lint
uses: golangci/golangci-lint-action@v2.3.0
with:
version: v1.45.2
version: v1.51.2
only-new-issues: false
args: --timeout 2m --config .golangci.yml
args: --timeout 5m --config .golangci.yml
diff:
name: diff
runs-on: ubuntu-18.04

View File

@@ -39,9 +39,16 @@ linters:
- testpackage
- varnamelen
- wrapcheck
- exhaustruct
- varcheck
- structcheck
- nosnakecase
- deadcode
- ifshort
- nonamedreturns
service:
golangci-lint-version: 1.45.2
golangci-lint-version: 1.51.2
run:
skip-files:

View File

@@ -240,7 +240,7 @@ goimports:
GOLANGCI_LINT = $(shell pwd)/bin/golangci-lint
golangci-lint: ## Download golangci-lint locally if necessary.
$(call go-install-tool,$(GOLANGCI_LINT),github.com/golangci/golangci-lint/cmd/golangci-lint@v1.45.2)
$(call go-install-tool,$(GOLANGCI_LINT),github.com/golangci/golangci-lint/cmd/golangci-lint@v1.51.2)
# Linting code as PR is expecting
.PHONY: golint
@@ -250,7 +250,7 @@ golint: golangci-lint
# Running e2e tests in a KinD instance
.PHONY: e2e
e2e/%: ginkgo
$(MAKE) e2e-build/$* && $(MAKE) e2e-exec || $(MAKE) e2e-destroy
$(MAKE) e2e-build/$* && $(MAKE) e2e-exec && $(MAKE) e2e-destroy
e2e-build/%:
kind create cluster --wait=60s --name capsule --image=kindest/node:$*

View File

@@ -133,7 +133,7 @@ func (in *Tenant) convertV1Alpha1OwnerToV1Beta1() capsulev1beta1.OwnerListSpec {
return owners
}
// nolint:gocognit,gocyclo,cyclop,maintidx
//nolint:gocognit,gocyclo,cyclop,maintidx
func (in *Tenant) ConvertTo(dstRaw conversion.Hub) error {
dst, ok := dstRaw.(*capsulev1beta1.Tenant)
if !ok {
@@ -365,7 +365,7 @@ func (in *Tenant) ConvertTo(dstRaw conversion.Hub) error {
return nil
}
// nolint:gocognit,gocyclo,cyclop
//nolint:gocognit,gocyclo,cyclop
func (in *Tenant) convertV1Beta1OwnerToV1Alpha1(src *capsulev1beta1.Tenant) {
ownersAnnotations := map[string][]string{
ownerGroupsAnnotation: nil,

View File

@@ -19,7 +19,7 @@ import (
"github.com/clastix/capsule/pkg/api"
)
// nolint:maintidx
//nolint:maintidx
func generateTenantsSpecs() (Tenant, capsulev1beta1.Tenant) {
var namespaceQuota int32 = 5

View File

@@ -75,9 +75,7 @@ func init() {
func (in *Tenant) GetNamespaces() (res []string) {
res = make([]string, 0, len(in.Status.Namespaces))
for _, ns := range in.Status.Namespaces {
res = append(res, ns)
}
res = append(res, in.Status.Namespaces...)
return
}

View File

@@ -76,9 +76,7 @@ type Tenant struct {
func (in *Tenant) GetNamespaces() (res []string) {
res = make([]string, 0, len(in.Status.Namespaces))
for _, ns := range in.Status.Namespaces {
res = append(res, ns)
}
res = append(res, in.Status.Namespaces...)
return
}

View File

@@ -121,7 +121,7 @@ func (r *Global) reconcileNormal(ctx context.Context, tntResource *capsulev1beta
}
if tntResource.Status.ProcessedItems == nil {
tntResource.Status.ProcessedItems = make([]capsulev1beta2.ObjectReferenceStatus, 0, 0)
tntResource.Status.ProcessedItems = make([]capsulev1beta2.ObjectReferenceStatus, 0)
}
// Retrieving the list of the Tenants up to the selector provided by the GlobalTenantResource resource.

View File

@@ -85,7 +85,7 @@ func (r *Namespaced) reconcileNormal(ctx context.Context, tntResource *capsulev1
// Adding the default value for the status
if tntResource.Status.ProcessedItems == nil {
tntResource.Status.ProcessedItems = make([]capsulev1beta2.ObjectReferenceStatus, 0, 0)
tntResource.Status.ProcessedItems = make([]capsulev1beta2.ObjectReferenceStatus, 0)
}
// Retrieving the parent of the Tenant Resource:

View File

@@ -135,7 +135,7 @@ func (r *Processor) HandleSection(ctx context.Context, tnt capsulev1beta2.Tenant
for _, ns := range namespaces.Items {
for nsIndex, item := range spec.NamespacedItems {
keysAndValues := []interface{}{"index", nsIndex, "namespace", item.Namespace}
keysAndValues := []any{"index", nsIndex, "namespace", item.Namespace}
// A TenantResource is created by a TenantOwner, and potentially, they could point to a resource in a non-owned
// Namespace: this must be blocked by checking it this is the case.
if !allowCrossNamespaceSelection && !tntNamespaces.Has(item.Namespace) {
@@ -174,7 +174,7 @@ func (r *Processor) HandleSection(ctx context.Context, tnt capsulev1beta2.Tenant
multiErr.Go(func() error {
kv := keysAndValues
kv = append(kv, []interface{}{"resource", fmt.Sprintf("%s/%s", obj.GetNamespace(), obj.GetNamespace())})
kv = append(kv, "resource", fmt.Sprintf("%s/%s", obj.GetNamespace(), obj.GetNamespace()))
if opErr := r.createOrUpdate(ctx, &obj, objLabels, objAnnotations); opErr != nil {
log.Error(opErr, "unable to sync namespacedItems", kv...)

View File

@@ -17,9 +17,8 @@ import (
"github.com/clastix/capsule/pkg/utils"
)
// nolint:dupl
// Ensuring all the LimitRange are applied to each Namespace handled by the Tenant.
func (r *Manager) syncLimitRanges(ctx context.Context, tenant *capsulev1beta2.Tenant) error {
func (r *Manager) syncLimitRanges(ctx context.Context, tenant *capsulev1beta2.Tenant) error { //nolint:dupl
// getting requested LimitRange keys
keys := make([]string, 0, len(tenant.Spec.LimitRanges.Items))

View File

@@ -42,7 +42,7 @@ func (r *Manager) syncNamespaces(ctx context.Context, tenant *capsulev1beta2.Ten
return
}
// nolint:gocognit
//nolint:gocognit
func (r *Manager) syncNamespaceMetadata(ctx context.Context, namespace string, tnt *capsulev1beta2.Tenant) (err error) {
var res controllerutil.OperationResult

View File

@@ -17,9 +17,8 @@ import (
"github.com/clastix/capsule/pkg/utils"
)
// nolint:dupl
// Ensuring all the NetworkPolicies are applied to each Namespace handled by the Tenant.
func (r *Manager) syncNetworkPolicies(ctx context.Context, tenant *capsulev1beta2.Tenant) error {
func (r *Manager) syncNetworkPolicies(ctx context.Context, tenant *capsulev1beta2.Tenant) error { //nolint:dupl
// getting requested NetworkPolicy keys
keys := make([]string, 0, len(tenant.Spec.NetworkPolicies.Items))

View File

@@ -36,8 +36,7 @@ import (
// the mutateFn along with the CreateOrUpdate to don't perform the update since resources are identical.
//
// In case of Namespace-scoped Resource Budget, we're just replicating the resources across all registered Namespaces.
// nolint:gocognit
func (r *Manager) syncResourceQuotas(ctx context.Context, tenant *capsulev1beta2.Tenant) (err error) {
func (r *Manager) syncResourceQuotas(ctx context.Context, tenant *capsulev1beta2.Tenant) (err error) { //nolint:gocognit
// getting ResourceQuota labels for the mutateFn
var tenantLabel, typeLabel string
@@ -48,7 +47,7 @@ func (r *Manager) syncResourceQuotas(ctx context.Context, tenant *capsulev1beta2
if typeLabel, err = utils.GetTypeLabel(&corev1.ResourceQuota{}); err != nil {
return err
}
// nolint:nestif
//nolint:nestif
if tenant.Spec.ResourceQuota.Scope == api.ResourceQuotaScopeTenant {
group := new(errgroup.Group)

View File

@@ -25,7 +25,7 @@ func (r *Manager) syncCustomResourceQuotaUsages(ctx context.Context, tenant *cap
group string
version string
}
// nolint:prealloc
//nolint:prealloc
var resourceList []resource
for k := range tenant.GetAnnotations() {

View File

@@ -96,7 +96,7 @@ func newDelegatingClient(cache cache.Cache, config *rest.Config, options client.
return delegatingClient, nil
}
// nolint:maintidx,cyclop
//nolint:maintidx,cyclop
func main() {
var enableLeaderElection, version bool

View File

@@ -144,7 +144,7 @@ func NewCertificateAuthorityFromBytes(certBytes, keyBytes []byte) (*CapsuleCA, e
}, nil
}
// nolint:nakedret
//nolint:nakedret
func (c *CapsuleCA) GenerateCertificate(opts CertificateOptions) (certificatePem *bytes.Buffer, certificateKey *bytes.Buffer, err error) {
var certPrivKey *rsa.PrivateKey
certPrivKey, err = rsa.GenerateKey(rand.Reader, 4096)

View File

@@ -46,7 +46,7 @@ func NewCapsuleConfiguration(ctx context.Context, client client.Client, name str
func (c *capsuleConfiguration) ProtectedNamespaceRegexp() (*regexp.Regexp, error) {
expr := c.retrievalFn().Spec.ProtectedNamespaceRegexpString
if len(expr) == 0 {
return nil, nil // nolint:nilnil
return nil, nil //nolint:nilnil
}
r, err := regexp.Compile(expr)

View File

@@ -22,7 +22,7 @@ type HostnamePath struct {
Obj metav1.Object
}
// nolint:forcetypeassert
//nolint:forcetypeassert
func (s HostnamePath) Object() client.Object {
return s.Obj.(client.Object)
}

View File

@@ -21,7 +21,7 @@ func (o NamespacesReference) Field() string {
return ".status.namespaces"
}
// nolint:forcetypeassert
//nolint:forcetypeassert
func (o NamespacesReference) Func() client.IndexerFunc {
return func(object client.Object) []string {
return object.(api.Tenant).GetNamespaces()

View File

@@ -15,9 +15,7 @@ type userGroupList []string
func NewUserGroupList(groups []string) UserGroupList {
list := make(userGroupList, len(groups))
for k, v := range groups {
list[k] = v
}
copy(list, groups)
sort.SliceStable(list, func(i, j int) bool {
return list[i] < list[j]

View File

@@ -88,7 +88,7 @@ func (i ingressClassNotValidError) Error() string {
return utils.DefaultAllowedValuesErrorMessage(i.spec, err)
}
// nolint:predeclared
//nolint:predeclared
func appendHostnameError(spec api.AllowedListSpec) (append string) {
if len(spec.Exact) > 0 {
append = fmt.Sprintf(", specify one of the following (%s)", strings.Join(spec.Exact, ", "))

View File

@@ -63,7 +63,7 @@ func (n NetworkingV1) Namespace() string {
return n.GetNamespace()
}
// nolint:dupl
//nolint:dupl
func (n NetworkingV1) HostnamePathsPairs() (pairs map[string]sets.String) {
pairs = make(map[string]sets.String)
@@ -129,7 +129,7 @@ func (n NetworkingV1Beta1) Namespace() string {
return n.GetNamespace()
}
// nolint:dupl
//nolint:dupl
func (n NetworkingV1Beta1) HostnamePathsPairs() (pairs map[string]sets.String) {
pairs = make(map[string]sets.String)
@@ -193,7 +193,7 @@ func (e Extension) Namespace() string {
return e.GetNamespace()
}
// nolint:dupl
//nolint:dupl
func (e Extension) HostnamePathsPairs() (pairs map[string]sets.String) {
pairs = make(map[string]sets.String)

View File

@@ -26,13 +26,13 @@ func TenantFromIngress(ctx context.Context, c client.Client, ingress Ingress) (*
}
if len(tenantList.Items) == 0 {
return nil, nil // nolint:nilnil
return nil, nil //nolint:nilnil
}
return &tenantList.Items[0], nil
}
// nolint:nakedret
//nolint:nakedret
func FromRequest(req admission.Request, decoder *admission.Decoder) (ingress Ingress, err error) {
switch req.Kind.Group {
case "networking.k8s.io":

View File

@@ -84,7 +84,7 @@ func (r *collision) validate(ctx context.Context, client client.Client, req admi
return &response
}
// nolint:gocognit,gocyclo,cyclop
//nolint:gocognit,gocyclo,cyclop
func (r *collision) validateCollision(ctx context.Context, clt client.Client, ing Ingress, scope api.HostnameCollisionScope) error {
for hostname, paths := range ing.HostnamePathsPairs() {
for path := range paths {
@@ -100,7 +100,7 @@ func (r *collision) validateCollision(ctx context.Context, clt client.Client, in
}
namespaces := sets.NewString()
// nolint:exhaustive
//nolint:exhaustive
switch scope {
case api.HostnameCollisionScopeCluster:
tenantList := &capsulev1beta2.TenantList{}

View File

@@ -10,7 +10,7 @@ import (
capsuleapi "github.com/clastix/capsule/pkg/api"
)
// nolint:predeclared
//nolint:predeclared
func appendForbiddenError(spec *capsuleapi.ForbiddenListSpec) (append string) {
append += "Forbidden are "
if len(spec.Exact) > 0 {

View File

@@ -125,7 +125,7 @@ func (r *userMetadataHandler) OnUpdate(client client.Client, decoder *admission.
}
if v != oldNs.GetAnnotations()["scheduler.alpha.kubernetes.io/node-selector"] {
response := admission.Denied("the the node-selector annotation is enforced, cannot be updated")
response := admission.Denied("the node-selector annotation is enforced, cannot be updated")
recorder.Eventf(tnt, corev1.EventTypeWarning, "ForbiddenNodeSelectorUpdate", string(response.Result.Reason))

View File

@@ -50,7 +50,7 @@ func (r *handler) generic(ctx context.Context, req admission.Request, client cli
return tnt, nil
}
return nil, nil // nolint:nilnil
return nil, nil //nolint:nilnil
}
//nolint:dupl

View File

@@ -10,7 +10,7 @@ import (
capsulev1beta2 "github.com/clastix/capsule/pkg/api"
)
// nolint:predeclared
//nolint:predeclared
func appendForbiddenError(spec *capsulev1beta2.ForbiddenListSpec) (append string) {
append += "Forbidden are "
if len(spec.Exact) > 0 {

View File

@@ -86,7 +86,7 @@ func (h *containerRegistryHandler) VerifyContainerRegistry(recorder record.Event
reg := NewRegistry(container.Image)
if len(reg.Registry()) == 0 {
recorder.Eventf(&tnt, corev1.EventTypeWarning, "MissingFQCI", "Pod %s/%s is not using using a fully qualified container image, cannot enforce registry the current Tenant", req.Namespace, req.Name, reg.Registry())
recorder.Eventf(&tnt, corev1.EventTypeWarning, "MissingFQCI", "Pod %s/%s is not using a fully qualified container image, cannot enforce registry the current Tenant", req.Namespace, req.Name, reg.Registry())
response := admission.Denied(NewContainerRegistryForbidden(container.Image, *tnt.Spec.ContainerRegistries).Error())

View File

@@ -8,9 +8,6 @@ import (
"net/http"
corev1 "k8s.io/api/core/v1"
schedulingv1 "k8s.io/api/scheduling/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/tools/record"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
@@ -25,24 +22,6 @@ func PriorityClass() capsulewebhook.Handler {
return &priorityClass{}
}
func (h *priorityClass) class(ctx context.Context, c client.Client, name string) (client.Object, error) {
if len(name) == 0 {
return nil, nil
}
obj := &schedulingv1.PriorityClass{}
if err := c.Get(ctx, types.NamespacedName{Name: name}, obj); err != nil {
if errors.IsNotFound(err) {
return nil, nil
}
return nil, err
}
return obj, nil
}
func (h *priorityClass) OnCreate(c client.Client, decoder *admission.Decoder, recorder record.EventRecorder) capsulewebhook.Func {
return func(ctx context.Context, req admission.Request) *admission.Response {
pod := &corev1.Pod{}

View File

@@ -24,7 +24,7 @@ func IsCapsuleUser(ctx context.Context, req admission.Request, clt client.Client
if groupList.Find("system:serviceaccounts:kube-system") {
return false
}
// nolint:nestif
//nolint:nestif
if sets.NewString(req.UserInfo.Groups...).Has("system:serviceaccounts") {
parts := strings.Split(req.UserInfo.Username, ":")