Skip to content

Commit

Permalink
chore: linter fixes.
Browse files Browse the repository at this point in the history
Fix the code base after updating the Golang linter configuration.

Signed-off-by: José Guilherme Vanz <[email protected]>
  • Loading branch information
jvanz committed Jul 16, 2024
1 parent 43982c5 commit 7e56907
Show file tree
Hide file tree
Showing 31 changed files with 232 additions and 194 deletions.
30 changes: 15 additions & 15 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,11 +1,25 @@
ROOT_DIR:=$(shell dirname $(realpath $(firstword $(MAKEFILE_LIST))))
BIN_DIR := $(abspath $(ROOT_DIR)/bin)


GOLANGCI_LINT_VER := v1.59.1
GOLANGCI_LINT_BIN := golangci-lint
GOLANGCI_LINT := $(BIN_DIR)/$(GOLANGCI_LINT_BIN)

# Run go fmt against code
fmt:
go fmt ./...

# Run go vet against code
vet:
go vet ./...

deps:
go get github.com/golangci/golangci-lint/cmd/golangci-lint
go install github.com/vektra/mockery/[email protected]

generate-mocks:
mockery

golangci-lint: $(GOLANGCI_LINT) ## Install a local copy of golang ci-lint.
$(GOLANGCI_LINT): ## Install golangci-lint.
GOBIN=$(BIN_DIR) go install github.com/golangci/golangci-lint/cmd/golangci-lint@$(GOLANGCI_LINT_VER)
Expand All @@ -23,17 +37,3 @@ lint-fix: $(GOLANGCI_LINT)
test: fmt vet
go test ./... -coverprofile cover.out

# Run go fmt against code
fmt:
go fmt ./...

# Run go vet against code
vet:
go vet ./...

deps:
go get github.com/golangci/golangci-lint/cmd/golangci-lint
go install github.com/vektra/mockery/[email protected]

generate-mocks:
mockery
2 changes: 1 addition & 1 deletion constants/constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package constants

const (
// ProtocolVersion is the version of the protocol used by the
// Kubewarden waPC host and guest to exchange information
// Kubewarden waPC host and guest to exchange information.
ProtocolVersion = "v1"
// These two media types are manifests media types that the
// oci-distribution accepts when fetching images manifests. But they
Expand Down
30 changes: 17 additions & 13 deletions kubewarden.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,24 +13,24 @@ import (
"github.com/kubewarden/policy-sdk-go/protocol"
)

// Message is the optional string used to build validation responses
// Message is the optional string used to build validation responses.
type Message string

// Code is the optional error code associated with validation responses
// Code is the optional error code associated with validation responses.
type Code uint16

const (
// NoMessage can be used when building a response that doesn't have any
// message to be shown to the user
// message to be shown to the user.
NoMessage Message = ""

// NoCode can be used when building a response that doesn't have any
// error code to be shown to the user
// error code to be shown to the user.
NoCode Code = 0
)

// AcceptRequest can be used inside of the `validate` function to accept the
// incoming request
// incoming request.
func AcceptRequest() ([]byte, error) {
response := protocol.ValidationResponse{
Accepted: true,
Expand All @@ -42,7 +42,7 @@ func AcceptRequest() ([]byte, error) {
// RejectRequest can be used inside of the `validate` function to reject the
// incoming request
// * `message`: optional message to show to the user
// * `code`: optional error code to show to the user
// * `code`: optional error code to show to the user.
func RejectRequest(message Message, code Code) ([]byte, error) {
response := protocol.ValidationResponse{
Accepted: false,
Expand All @@ -60,7 +60,7 @@ func RejectRequest(message Message, code Code) ([]byte, error) {
}

// Accept the request and mutate the final object to match the
// one provided via the `newObject` param
// one provided via the `newObject` param.
func MutateRequest(newObject interface{}) ([]byte, error) {
response := protocol.ValidationResponse{
Accepted: true,
Expand All @@ -73,7 +73,9 @@ func MutateRequest(newObject interface{}) ([]byte, error) {
// Update the pod spec from the resource defined in the original object and
// create an acceptance response.
// * `validation_request` - the original admission request
// * `pod_spec` - new PodSpec to be set in the response
// * `pod_spec` - new PodSpec to be set in the response.
//
//nolint:funlen // Splitting this function would not make it more readable.
func MutatePodSpecFromRequest(validationRequest protocol.ValidationRequest, podSepc corev1.PodSpec) ([]byte, error) {
switch validationRequest.Request.Kind.Kind {
case "Deployment":
Expand Down Expand Up @@ -133,12 +135,13 @@ func MutatePodSpecFromRequest(validationRequest protocol.ValidationRequest, podS
pod.Spec = &podSepc
return MutateRequest(pod)
default:
return RejectRequest("Object should be one of these kinds: Deployment, ReplicaSet, StatefulSet, DaemonSet, ReplicationController, Job, CronJob, Pod", NoCode)
return RejectRequest("Object should be one of these kinds: Deployment, "+
"ReplicaSet, StatefulSet, DaemonSet, ReplicationController, Job, CronJob, Pod", NoCode)
}
}

// AcceptSettings can be used inside of the `validate_settings` function to
// mark the user provided settings as valid
// mark the user provided settings as valid.
func AcceptSettings() ([]byte, error) {
response := protocol.SettingsValidationResponse{
Valid: true,
Expand All @@ -148,7 +151,7 @@ func AcceptSettings() ([]byte, error) {

// RejectSettings can be used inside of the `validate_settings` function to
// mark the user provided settings as invalid
// * `message`: optional message to show to the user
// * `message`: optional message to show to the user.
func RejectSettings(message Message) ([]byte, error) {
response := protocol.SettingsValidationResponse{
Valid: false,
Expand All @@ -168,7 +171,7 @@ func RejectSettings(message Message) ([]byte, error) {
// DaemonSet, ReplicationController, Job, CronJob, Pod It returns an error if
// the object is not one of those. If it is a supported object it returns the
// PodSpec if present, otherwise returns an empty PodSpec.
// * `object`: the request to validate
// * `object`: the request to validate.
func ExtractPodSpecFromObject(object protocol.ValidationRequest) (corev1.PodSpec, error) {
switch object.Request.Kind.Kind {
case "Deployment":
Expand Down Expand Up @@ -220,6 +223,7 @@ func ExtractPodSpecFromObject(object protocol.ValidationRequest) (corev1.PodSpec
}
return *pod.Spec, nil
default:
return corev1.PodSpec{}, errors.New("object should be one of these kinds: Deployment, ReplicaSet, StatefulSet, DaemonSet, ReplicationController, Job, CronJob, Pod")
return corev1.PodSpec{}, errors.New("object should be one of these kinds: " +
"Deployment, ReplicaSet, StatefulSet, DaemonSet, ReplicationController, Job, CronJob, Pod")
}
}
10 changes: 5 additions & 5 deletions kubewarden_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package sdk

import (
"encoding/json"
"fmt"
"errors"
"testing"

appsv1 "github.com/kubewarden/k8s-objects/api/apps/v1"
Expand Down Expand Up @@ -49,11 +49,11 @@ func CheckIfAutomountServiceAccountTokenIsTrue(rawResponse []byte, mutatedObject
}

if !response.Accepted {
return fmt.Errorf("Response not accepted")
return errors.New("Response not accepted")
}

if response.MutatedObject == nil {
return fmt.Errorf("Request not mutated")
return errors.New("Request not mutated")
}

return nil
Expand Down Expand Up @@ -198,7 +198,7 @@ func TestMutatePodSpecFromRequest(t *testing.T) {
t.Fatalf("Error: %v", err)
}

if err := CheckIfAutomountServiceAccountTokenIsTrue(rawResponse, testCase.mutatedObject); err != nil {
if err = CheckIfAutomountServiceAccountTokenIsTrue(rawResponse, testCase.mutatedObject); err != nil {
t.Fatalf("Error: %v", err)
}

Expand Down Expand Up @@ -258,7 +258,7 @@ func TestMutatePodSpecFromRequestWithInvalidResourceType(t *testing.T) {
}

response := protocol.ValidationResponse{}
if err := json.Unmarshal(rawResponse, &response); err != nil {
if err = json.Unmarshal(rawResponse, &response); err != nil {
t.Fatalf("Error: %v", err)
}

Expand Down
7 changes: 4 additions & 3 deletions log_writer_native.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@ import (
"fmt"
)

func (k *KubewardenLogWriter) Write(p []byte) (n int, err error) {
n, err = k.buffer.Write(p)
func (k *KubewardenLogWriter) Write(p []byte) (int, error) {
n, err := k.buffer.Write(p)
line, _ := k.buffer.ReadBytes('\n')
//nolint:forbidigo // this is a debug print
fmt.Printf("NATIVE: |%s|\n", string(line))
return
return n, err
}
13 changes: 7 additions & 6 deletions pkg/capabilities/crypto/crypto.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,17 @@ package crypto

import (
"encoding/json"
"errors"
"fmt"

cap "github.com/kubewarden/policy-sdk-go/pkg/capabilities"
"github.com/kubewarden/policy-sdk-go/pkg/capabilities"
)

type CryptoHost struct {
cap.Host
capabilities.Host
}

// The encoding of the certificate
// The encoding of the certificate.
type CertificateEncoding int

const (
Expand All @@ -26,7 +27,7 @@ func (e CertificateEncoding) MarshalJSON() ([]byte, error) {
return json.Marshal("Pem")
}

return nil, fmt.Errorf("invalid certificate encoding")
return nil, errors.New("invalid certificate encoding")
}

// Verify_cert verifies cert's trust against the passed cert_chain, and
Expand All @@ -37,7 +38,7 @@ func (e CertificateEncoding) MarshalJSON() ([]byte, error) {
// (intermediates first, root last). If empty, certificate is assumed trusted.
// - not_after: string in RFC 3339 time format, to check expiration against.
// If None, certificate is assumed never expired.
func VerifyCert(h *cap.Host, cert Certificate, certChain []Certificate, notAfter string) (*CertificateVerificationResponse, error) {
func VerifyCert(h *capabilities.Host, cert Certificate, certChain []Certificate, notAfter string) (*CertificateVerificationResponse, error) {
requestObj := CertificateVerificationRequest{
Cert: cert,
CertChain: certChain,
Expand All @@ -56,7 +57,7 @@ func VerifyCert(h *cap.Host, cert Certificate, certChain []Certificate, notAfter
}

responseObj := CertificateVerificationResponse{}
if err := json.Unmarshal(responsePayload, &responseObj); err != nil {
if err = json.Unmarshal(responsePayload, &responseObj); err != nil {
return &CertificateVerificationResponse{}, fmt.Errorf("cannot unmarshall response object: %w", err)
}

Expand Down
8 changes: 4 additions & 4 deletions pkg/capabilities/crypto/crypto_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"encoding/json"
"testing"

cap "github.com/kubewarden/policy-sdk-go/pkg/capabilities"
"github.com/kubewarden/policy-sdk-go/pkg/capabilities"

"github.com/kubewarden/policy-sdk-go/pkg/capabilities/mocks"
)
Expand All @@ -23,7 +23,7 @@ func TestV1IsCertificateTrusted(t *testing.T) {
Encoding: Pem,
Data: []rune("certificate2"),
}}
not_after := "2021-10-01T00:00:00Z"
notAfter := "2021-10-01T00:00:00Z"

verificationResponse := CertificateVerificationResponse{
Trusted: true,
Expand All @@ -42,11 +42,11 @@ func TestV1IsCertificateTrusted(t *testing.T) {
Return(verificationPayload, nil).
Times(1)

host := &cap.Host{
host := &capabilities.Host{
Client: mockWapcClient,
}

res, err := VerifyCert(host, cert, chain, not_after)
res, err := VerifyCert(host, cert, chain, notAfter)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/capabilities/crypto/types.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package crypto

// A x509 certificate
// A x509 certificate.
type Certificate struct {
// Which encoding is used by the certificate
Encoding CertificateEncoding `json:"encoding"`
Expand Down
12 changes: 6 additions & 6 deletions pkg/capabilities/kubernetes/kubernetes.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ import (
"encoding/json"
"fmt"

cap "github.com/kubewarden/policy-sdk-go/pkg/capabilities"
"github.com/kubewarden/policy-sdk-go/pkg/capabilities"
)

// ListResourcesByNamespace gets all the Kubernetes resources defined inside of
// the given namespace
// Note: cannot be used for cluster-wide resources
func ListResourcesByNamespace(h *cap.Host, req ListResourcesByNamespaceRequest) ([]byte, error) {
// Note: cannot be used for cluster-wide resources.
func ListResourcesByNamespace(h *capabilities.Host, req ListResourcesByNamespaceRequest) ([]byte, error) {
payload, err := json.Marshal(req)
if err != nil {
return []byte{}, fmt.Errorf("cannot serialize request object: %w", err)
Expand All @@ -26,8 +26,8 @@ func ListResourcesByNamespace(h *cap.Host, req ListResourcesByNamespaceRequest)
}

// ListResources gets all the Kubernetes resources defined inside of the cluster.
// Note: this has be used for cluster-wide resources
func ListResources(h *cap.Host, req ListAllResourcesRequest) ([]byte, error) {
// Note: this has be used for cluster-wide resources.
func ListResources(h *capabilities.Host, req ListAllResourcesRequest) ([]byte, error) {
payload, err := json.Marshal(req)
if err != nil {
return []byte{}, fmt.Errorf("cannot serialize request object: %w", err)
Expand All @@ -43,7 +43,7 @@ func ListResources(h *cap.Host, req ListAllResourcesRequest) ([]byte, error) {
}

// GetResource gets a specific Kubernetes resource.
func GetResource(h *cap.Host, req GetResourceRequest) ([]byte, error) {
func GetResource(h *capabilities.Host, req GetResourceRequest) ([]byte, error) {
payload, err := json.Marshal(req)
if err != nil {
return []byte{}, fmt.Errorf("cannot serialize request object: %w", err)
Expand Down
8 changes: 4 additions & 4 deletions pkg/capabilities/kubernetes/kubernetes_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package kubernetes
import (
"testing"

cap "github.com/kubewarden/policy-sdk-go/pkg/capabilities"
"github.com/kubewarden/policy-sdk-go/pkg/capabilities"

"github.com/kubewarden/policy-sdk-go/pkg/capabilities/mocks"
)
Expand All @@ -19,7 +19,7 @@ func TestKubernetesListResourcesByNamespace(t *testing.T) {
Return([]byte{}, nil).
Times(1)

host := &cap.Host{
host := &capabilities.Host{
Client: mockWapcClient,
}

Expand Down Expand Up @@ -51,7 +51,7 @@ func TestKubernetesListResources(t *testing.T) {
Return([]byte{}, nil).
Times(1)

host := &cap.Host{
host := &capabilities.Host{
Client: mockWapcClient,
}

Expand Down Expand Up @@ -82,7 +82,7 @@ func TestKubernetesGetResource(t *testing.T) {
Return([]byte{}, nil).
Times(1)

host := &cap.Host{
host := &capabilities.Host{
Client: mockWapcClient,
}
namespace := "default"
Expand Down
6 changes: 3 additions & 3 deletions pkg/capabilities/kubernetes/types.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package kubernetes

// Set of parameters used by the `list_resources_by_namespace` function
// Set of parameters used by the `list_resources_by_namespace` function.
type ListResourcesByNamespaceRequest struct {
// apiVersion of the resource (v1 for core group, groupName/groupVersions for other).
APIVersion string `json:"api_version"`
Expand All @@ -16,7 +16,7 @@ type ListResourcesByNamespaceRequest struct {
FieldSelector *string `json:"field_selector,omitempty"`
}

// Set of parameters used by the `list_all_resources` function
// Set of parameters used by the `list_all_resources` function.
type ListAllResourcesRequest struct {
// apiVersion of the resource (v1 for core group, groupName/groupVersions for other).
APIVersion string `json:"api_version"`
Expand All @@ -30,7 +30,7 @@ type ListAllResourcesRequest struct {
FieldSelector *string `json:"field_selector,omitempty"`
}

// Set of parameters used by the `get_resource` function
// Set of parameters used by the `get_resource` function.
type GetResourceRequest struct {
APIVersion string `json:"api_version"`
// Singular PascalCase name of the resource
Expand Down
Loading

0 comments on commit 7e56907

Please sign in to comment.