Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable gofmt and gofumpt linter #740

Merged
merged 2 commits into from
Oct 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,11 @@ linters:
# - goconst - TODO(ben): Consider moving consts into separate package
- gocritic
- godot
- gofmt
- gofumpt


# TODO(ben): Enable those linters step by step and fix existing issues.
# - godox
# - gofmt
# - gofumpt
# - goheader
# - goimports
# - gomoddirectives
Expand Down
2 changes: 1 addition & 1 deletion src/k8s/cmd/k8s/hooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ func hookInitializeFormatter(env cmdutil.ExecutionEnvironment, format *string) f
func hookCheckLXD() func(*cobra.Command, []string) {
return func(cmd *cobra.Command, args []string) {
// pathsOwnershipCheck paths to validate root is the owner
var pathsOwnershipCheck = []string{"/sys", "/proc", "/dev/kmsg"}
pathsOwnershipCheck := []string{"/sys", "/proc", "/dev/kmsg"}
inLXD, err := cmdutil.InLXDContainer()
if err != nil {
cmd.PrintErrf("Failed to check if running inside LXD container: %s", err.Error())
Expand Down
12 changes: 5 additions & 7 deletions src/k8s/cmd/k8s/k8s.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,11 @@ func addCommands(root *cobra.Command, group *cobra.Group, commands ...*cobra.Com
}

func NewRootCmd(env cmdutil.ExecutionEnvironment) *cobra.Command {
var (
opts struct {
logDebug bool
logVerbose bool
stateDir string
}
)
var opts struct {
logDebug bool
logVerbose bool
stateDir string
}
cmd := &cobra.Command{
Use: "k8s",
Short: "Canonical Kubernetes CLI",
Expand Down
2 changes: 1 addition & 1 deletion src/k8s/cmd/k8s/k8s_bootstrap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ var testCases = []testCase{
func mustAddConfigToTestDir(t *testing.T, configPath string, data string) {
t.Helper()
// Create the cluster bootstrap config file
err := os.WriteFile(configPath, []byte(data), 0644)
err := os.WriteFile(configPath, []byte(data), 0o644)
if err != nil {
t.Fatal(err)
}
Expand Down
2 changes: 1 addition & 1 deletion src/k8s/cmd/k8s/k8s_x_capi.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ func newXCAPICmd(env cmdutil.ExecutionEnvironment) *cobra.Command {
return
}

if err := os.WriteFile(env.Snap.NodeTokenFile(), []byte(token), 0600); err != nil {
if err := os.WriteFile(env.Snap.NodeTokenFile(), []byte(token), 0o600); err != nil {
cmd.PrintErrf("Error: Failed to write the node token to file.\n\nThe error was: %v\n", err)
env.Exit(1)
return
Expand Down
3 changes: 1 addition & 2 deletions src/k8s/cmd/k8sd/k8sd_cluster_recover.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,6 @@ func logDebugf(format string, args ...interface{}) {
msg := fmt.Sprintf(format, args...)
log.L().Info(msg)
}

}

func newClusterRecoverCmd(env cmdutil.ExecutionEnvironment) *cobra.Command {
Expand Down Expand Up @@ -294,7 +293,7 @@ func ensureK8sDqliteMembersStopped(ctx context.Context) error {
}(ctx, dial, member.Address)
}

for _, _ = range members {
for range members {
addr, ok := <-c
if !ok {
return fmt.Errorf("channel closed unexpectedly")
Expand Down
5 changes: 5 additions & 0 deletions src/k8s/pkg/client/k8sd/mock/mock.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,14 +56,17 @@ func (m *Mock) BootstrapCluster(_ context.Context, request apiv1.BootstrapCluste
m.BootstrapClusterCalledWith = request
return m.BootstrapClusterResponse, m.BootstrapClusterErr
}

func (m *Mock) GetJoinToken(_ context.Context, request apiv1.GetJoinTokenRequest) (apiv1.GetJoinTokenResponse, error) {
m.GetJoinTokenCalledWith = request
return m.GetJoinTokenResponse, m.GetJoinTokenErr
}

func (m *Mock) JoinCluster(_ context.Context, request apiv1.JoinClusterRequest) error {
m.JoinClusterCalledWith = request
return m.JoinClusterErr
}

func (m *Mock) RemoveNode(_ context.Context, request apiv1.RemoveNodeRequest) error {
m.RemoveNodeCalledWith = request
return m.RemoveNodeErr
Expand All @@ -72,6 +75,7 @@ func (m *Mock) RemoveNode(_ context.Context, request apiv1.RemoveNodeRequest) er
func (m *Mock) NodeStatus(_ context.Context) (apiv1.NodeStatusResponse, bool, error) {
return m.NodeStatusResponse, m.NodeStatusInitialized, m.NodeStatusErr
}

func (m *Mock) ClusterStatus(_ context.Context, waitReady bool) (apiv1.ClusterStatusResponse, error) {
return m.ClusterStatusResponse, m.ClusterStatusErr
}
Expand All @@ -87,6 +91,7 @@ func (m *Mock) RefreshCertificatesRun(_ context.Context, request apiv1.RefreshCe
func (m *Mock) GetClusterConfig(_ context.Context) (apiv1.GetClusterConfigResponse, error) {
return m.GetClusterConfigResponse, m.GetClusterConfigErr
}

func (m *Mock) SetClusterConfig(_ context.Context, request apiv1.SetClusterConfigRequest) error {
m.SetClusterConfigCalledWith = request
return m.SetClusterConfigErr
Expand Down
1 change: 0 additions & 1 deletion src/k8s/pkg/client/kubernetes/configmap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,6 @@ func TestWatchConfigMap(t *testing.T) {
case <-time.After(time.Second):
t.Fatal("Timed out waiting for watch to complete")
}

})
}
}
Expand Down
1 change: 0 additions & 1 deletion src/k8s/pkg/client/kubernetes/status.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ func (c *Client) CheckKubernetesEndpoint(ctx context.Context) error {
// HasReadyNodes returns true if there is at least one Ready node in the cluster, false otherwise.
func (c *Client) HasReadyNodes(ctx context.Context) (bool, error) {
nodes, err := c.CoreV1().Nodes().List(ctx, metav1.ListOptions{})

if err != nil {
return false, fmt.Errorf("failed to list nodes: %w", err)
}
Expand Down
2 changes: 1 addition & 1 deletion src/k8s/pkg/docgen/json_struct.go
100755 → 100644
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ func MarkdownFromJsonStructToFile(i any, outFilePath string, projectDir string)
return err
}

err = os.WriteFile(outFilePath, []byte(content), 0644)
err = os.WriteFile(outFilePath, []byte(content), 0o644)
if err != nil {
return fmt.Errorf("failed to write markdown documentation to %s: %w", outFilePath, err)
}
Expand Down
6 changes: 0 additions & 6 deletions src/k8s/pkg/k8sd/api/certificates_refresh.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ func (e *Endpoints) postRefreshCertsPlan(s state.State, r *http.Request) respons
return response.SyncResponse(true, apiv1.RefreshCertificatesPlanResponse{
Seed: seed,
})

}

func (e *Endpoints) postRefreshCertsRun(s state.State, r *http.Request) response.Response {
Expand Down Expand Up @@ -187,7 +186,6 @@ func refreshCertsRunControlPlane(s state.State, r *http.Request, snap snap.Snap)
f.Flush()
return nil
})

}

// refreshCertsRunWorker refreshes the certificates for a worker node.
Expand Down Expand Up @@ -299,9 +297,7 @@ func refreshCertsRunWorker(s state.State, r *http.Request, snap snap.Snap) respo
}

return nil

})

}

if err := g.Wait(); err != nil {
Expand Down Expand Up @@ -388,7 +384,6 @@ func refreshCertsRunWorker(s state.State, r *http.Request, snap snap.Snap) respo
f.Flush()
return nil
})

}

// isCertificateSigningRequestApprovedAndIssued checks if the certificate
Expand All @@ -399,7 +394,6 @@ func isCertificateSigningRequestApprovedAndIssued(csr *certv1.CertificateSigning
for _, condition := range csr.Status.Conditions {
if condition.Type == certv1.CertificateApproved && condition.Status == corev1.ConditionTrue {
return len(csr.Status.Certificate) > 0, nil

}
if condition.Type == certv1.CertificateDenied && condition.Status == corev1.ConditionTrue {
return false, fmt.Errorf("CSR %s was denied: %s", csr.Name, condition.Reason)
Expand Down
1 change: 0 additions & 1 deletion src/k8s/pkg/k8sd/api/impl/k8sd.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,5 +59,4 @@ func GetLocalNodeStatus(ctx context.Context, s state.State, snap snap.Snap) (api
Address: s.Address().Hostname(),
ClusterRole: clusterRole,
}, nil

}
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ import (
)

func reconcileAutoApprove(ctx context.Context, log log.Logger, csr *certv1.CertificateSigningRequest,
priv *rsa.PrivateKey, client client.Client) (ctrl.Result, error) {
priv *rsa.PrivateKey, client client.Client,
) (ctrl.Result, error) {
var result certv1.RequestConditionType

if err := validateCSR(csr, priv); err != nil {
Expand Down
10 changes: 4 additions & 6 deletions src/k8s/pkg/k8sd/database/capi_auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,10 @@ import (
"github.com/canonical/microcluster/v3/cluster"
)

var (
clusterAPIConfigsStmts = map[string]int{
"insert-capi-token": MustPrepareStatement("cluster-configs", "insert-capi-token.sql"),
"select-capi-token": MustPrepareStatement("cluster-configs", "select-capi-token.sql"),
}
)
var clusterAPIConfigsStmts = map[string]int{
"insert-capi-token": MustPrepareStatement("cluster-configs", "insert-capi-token.sql"),
"select-capi-token": MustPrepareStatement("cluster-configs", "select-capi-token.sql"),
}

// SetClusterAPIToken stores the ClusterAPI token in the cluster config.
func SetClusterAPIToken(ctx context.Context, tx *sql.Tx, token string) error {
Expand Down
10 changes: 4 additions & 6 deletions src/k8s/pkg/k8sd/database/cluster_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,10 @@ import (
"github.com/canonical/microcluster/v3/cluster"
)

var (
clusterConfigsStmts = map[string]int{
"insert-v1alpha2": MustPrepareStatement("cluster-configs", "insert-v1alpha2.sql"),
"select-v1alpha2": MustPrepareStatement("cluster-configs", "select-v1alpha2.sql"),
}
)
var clusterConfigsStmts = map[string]int{
"insert-v1alpha2": MustPrepareStatement("cluster-configs", "insert-v1alpha2.sql"),
"select-v1alpha2": MustPrepareStatement("cluster-configs", "select-v1alpha2.sql"),
}

// SetClusterConfig updates the cluster configuration with any non-empty values that are set.
// SetClusterConfig will attempt to merge the existing and new configs, and return an error if any protected fields have changed.
Expand Down
2 changes: 0 additions & 2 deletions src/k8s/pkg/k8sd/database/feature_status_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@ func TestFeatureStatus(t *testing.T) {
ss, err := database.GetFeatureStatuses(ctx, tx)
g.Expect(err).To(Not(HaveOccurred()))
g.Expect(ss).To(BeEmpty())

})

t.Run("SettingNewStatus", func(t *testing.T) {
Expand All @@ -70,7 +69,6 @@ func TestFeatureStatus(t *testing.T) {
g.Expect(ss[features.DNS].Message).To(Equal(dnsStatus.Message))
g.Expect(ss[features.DNS].Version).To(Equal(dnsStatus.Version))
g.Expect(ss[features.DNS].UpdatedAt).To(Equal(dnsStatus.UpdatedAt))

})
t.Run("UpdatingStatus", func(t *testing.T) {
g := NewWithT(t)
Expand Down
16 changes: 7 additions & 9 deletions src/k8s/pkg/k8sd/database/kubernetes_auth_tokens.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,13 @@ import (
"github.com/canonical/microcluster/v3/cluster"
)

var (
k8sdTokensStmts = map[string]int{
"insert-token": MustPrepareStatement("kubernetes-auth-tokens", "insert-token.sql"),
"select-by-token": MustPrepareStatement("kubernetes-auth-tokens", "select-by-token.sql"),
"select-by-username": MustPrepareStatement("kubernetes-auth-tokens", "select-by-username.sql"),
"delete-by-token": MustPrepareStatement("kubernetes-auth-tokens", "delete-by-token.sql"),
"delete-by-username": MustPrepareStatement("kubernetes-auth-tokens", "delete-by-username.sql"),
}
)
var k8sdTokensStmts = map[string]int{
"insert-token": MustPrepareStatement("kubernetes-auth-tokens", "insert-token.sql"),
"select-by-token": MustPrepareStatement("kubernetes-auth-tokens", "select-by-token.sql"),
"select-by-username": MustPrepareStatement("kubernetes-auth-tokens", "select-by-username.sql"),
"delete-by-token": MustPrepareStatement("kubernetes-auth-tokens", "delete-by-token.sql"),
"delete-by-username": MustPrepareStatement("kubernetes-auth-tokens", "delete-by-username.sql"),
}

func groupsToString(inGroups []string) (string, error) {
groupMap := make(map[string]struct{}, len(inGroups))
Expand Down
6 changes: 2 additions & 4 deletions src/k8s/pkg/k8sd/database/util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,8 @@ const (
microclusterDatabaseShutdownTimeout = 3 * time.Second
)

var (
// nextIdx is used to pick different listen ports for each microcluster instance.
nextIdx int
)
// nextIdx is used to pick different listen ports for each microcluster instance.
var nextIdx int

// DB is an interface for the internal microcluster DB type.
type DB interface {
Expand Down
12 changes: 5 additions & 7 deletions src/k8s/pkg/k8sd/database/worker.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,11 @@ import (
"github.com/canonical/microcluster/v3/cluster"
)

var (
workerStmts = map[string]int{
"insert-token": MustPrepareStatement("worker-tokens", "insert.sql"),
"select-token": MustPrepareStatement("worker-tokens", "select.sql"),
"delete-token": MustPrepareStatement("worker-tokens", "delete-by-token.sql"),
}
)
var workerStmts = map[string]int{
"insert-token": MustPrepareStatement("worker-tokens", "insert.sql"),
"select-token": MustPrepareStatement("worker-tokens", "select.sql"),
"delete-token": MustPrepareStatement("worker-tokens", "delete-by-token.sql"),
}

// CheckWorkerNodeToken returns true if the specified token can be used to join the specified node on the cluster.
// CheckWorkerNodeToken will return true if the token is empty or if the token is associated with the specified node
Expand Down
2 changes: 0 additions & 2 deletions src/k8s/pkg/k8sd/features/cilium/gateway_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,6 @@ func TestGatewayEnabled(t *testing.T) {
g.Expect(status.Version).To(Equal(cilium.CiliumAgentImageTag))
g.Expect(status.Message).To(Equal(cilium.EnabledMsg))
})

}

func TestGatewayDisabled(t *testing.T) {
Expand Down Expand Up @@ -200,7 +199,6 @@ func TestGatewayDisabled(t *testing.T) {
g.Expect(helmCiliumArgs.Chart).To(Equal(cilium.ChartCilium))
g.Expect(helmCiliumArgs.State).To(Equal(helm.StateDeleted))
g.Expect(helmCiliumArgs.Values["gatewayAPI"].(map[string]any)["enabled"]).To(BeFalse())

})

t.Run("RolloutFail", func(t *testing.T) {
Expand Down
3 changes: 0 additions & 3 deletions src/k8s/pkg/k8sd/features/cilium/network_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,6 @@ func TestNetworkMountPath(t *testing.T) {
g.Expect(status.Message).To(Equal(fmt.Sprintf(networkDeployFailedMsgTmpl, err)))
g.Expect(status.Version).To(Equal(CiliumAgentImageTag))
g.Expect(helmM.ApplyCalledWith).To(BeEmpty())

})
}
}
Expand Down Expand Up @@ -265,7 +264,6 @@ func TestNetworkMountPropagationType(t *testing.T) {

g.Expect(status.Version).To(Equal(CiliumAgentImageTag))
g.Expect(helmM.ApplyCalledWith).To(BeEmpty())

})

t.Run("MountPropagationPrivateOnLXDError", func(t *testing.T) {
Expand Down Expand Up @@ -375,7 +373,6 @@ func TestNetworkMountPropagationType(t *testing.T) {
}

func validateNetworkValues(g Gomega, values map[string]any, network types.Network, snap snap.Snap) {

ipv4CIDR, ipv6CIDR, err := utils.SplitCIDRStrings(network.GetPodCIDR())
g.Expect(err).ToNot(HaveOccurred())

Expand Down
1 change: 0 additions & 1 deletion src/k8s/pkg/k8sd/features/cilium/status_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,6 @@ func TestCheckNetwork(t *testing.T) {
err := cilium.CheckNetwork(context.Background(), snapM)

g.Expect(err).To(HaveOccurred())

})

t.Run("allPodsPresent", func(t *testing.T) {
Expand Down
8 changes: 4 additions & 4 deletions src/k8s/pkg/k8sd/features/contour/gateway_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ func TestGatewayDisabled(t *testing.T) {
g.Expect(status.Enabled).To(BeFalse())
g.Expect(status.Version).To(Equal(contour.ContourGatewayProvisionerContourImageTag))
g.Expect(status.Message).To(Equal(fmt.Sprintf(contour.GatewayDeleteFailedMsgTmpl, err)))

})

t.Run("Success", func(t *testing.T) {
Expand All @@ -68,7 +67,6 @@ func TestGatewayDisabled(t *testing.T) {
g.Expect(status.Version).To(Equal(contour.ContourGatewayProvisionerContourImageTag))
g.Expect(status.Message).To(Equal(contour.DisabledMsg))
g.Expect(helmM.ApplyCalledWith).To(HaveLen(1))

})
}

Expand Down Expand Up @@ -124,7 +122,8 @@ func TestGatewayEnabled(t *testing.T) {
{Name: "tlscertificatedelegations"},
{Name: "httpproxies"},
},
}}
},
}
snapM := &snapmock.Snap{
Mock: snapmock.Mock{
HelmClient: helmM,
Expand Down Expand Up @@ -182,7 +181,8 @@ func TestGatewayEnabled(t *testing.T) {
{
GroupVersion: "projectcontour.io/v1",
APIResources: []v1.APIResource{},
}}
},
}
snapM := &snapmock.Snap{
Mock: snapmock.Mock{
HelmClient: helmM,
Expand Down
Loading
Loading