Skip to content

Commit

Permalink
Merge pull request #1537 from kubernetes-sigs/goconst
Browse files Browse the repository at this point in the history
Enable and fix `goconst` linter
  • Loading branch information
k8s-ci-robot committed Jul 31, 2024
2 parents accffba + b6c89f9 commit 32c9832
Show file tree
Hide file tree
Showing 19 changed files with 81 additions and 65 deletions.
2 changes: 1 addition & 1 deletion .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ linters:
- gocheckcompilerdirectives
- gochecksumtype
- gocognit
- goconst
- gocritic
- gocyclo
- godot
Expand Down Expand Up @@ -99,7 +100,6 @@ linters:
# - funlen
# - gochecknoglobals
# - gochecknoinits
# - goconst
# - gosec
# - ireturn
# - lll
Expand Down
16 changes: 9 additions & 7 deletions cmd/crictl/container.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ import (
internalapi "k8s.io/cri-api/pkg/apis"
pb "k8s.io/cri-api/pkg/apis/runtime/v1"
"k8s.io/kubelet/pkg/types"

"sigs.k8s.io/cri-tools/pkg/framework"
)

type containerByCreated []*pb.Container
Expand Down Expand Up @@ -580,7 +582,7 @@ var listContainersCommand = &cli.Command{
Name: "output",
Aliases: []string{"o"},
Usage: "Output format, One of: json|yaml|table",
Value: "table",
Value: outputTypeTable,
},
&cli.BoolFlag{
Name: "all",
Expand Down Expand Up @@ -889,7 +891,7 @@ func UpdateContainerResources(client internalapi.RuntimeService, id string, opts
request := &pb.UpdateContainerResourcesRequest{
ContainerId: id,
}
if goruntime.GOOS != "windows" {
if goruntime.GOOS != framework.OSWindows {
request.Linux = &pb.LinuxContainerResources{
CpuPeriod: opts.CPUPeriod,
CpuQuota: opts.CPUQuota,
Expand Down Expand Up @@ -1010,7 +1012,7 @@ func marshalContainerStatus(cs *pb.ContainerStatus) (string, error) {
func containerStatus(client internalapi.RuntimeService, ids []string, output, tmplStr string, quiet bool) error {
verbose := !(quiet)
if output == "" { // default to json output
output = "json"
output = outputTypeJSON
}
if len(ids) == 0 {
return errors.New("ID cannot be empty")
Expand All @@ -1036,7 +1038,7 @@ func containerStatus(client internalapi.RuntimeService, ids []string, output, tm
return fmt.Errorf("marshal container status: %w", err)
}

if output == "table" {
if output == outputTypeTable {
outputContainerStatusTable(r, verbose)
} else {
statuses = append(statuses, statusData{json: statusJSON, info: r.Info})
Expand Down Expand Up @@ -1138,11 +1140,11 @@ func ListContainers(runtimeClient internalapi.RuntimeService, imageClient intern
r = getContainersList(r, opts)

switch opts.output {
case "json":
case outputTypeJSON:
return outputProtobufObjAsJSON(&pb.ListContainersResponse{Containers: r})
case "yaml":
case outputTypeYAML:
return outputProtobufObjAsYAML(&pb.ListContainersResponse{Containers: r})
case "table":
case outputTypeTable:
// continue; output will be generated after the switch block ends.
default:
return fmt.Errorf("unsupported output format %q", opts.output)
Expand Down
4 changes: 2 additions & 2 deletions cmd/crictl/container_stats.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,9 +164,9 @@ func (d containerStatsDisplayer) displayStats(ctx context.Context, client intern
return err
}
switch d.opts.output {
case "json":
case outputTypeJSON:
return outputProtobufObjAsJSON(r)
case "yaml":
case outputTypeYAML:
return outputProtobufObjAsYAML(r)
}
oldStats := make(map[string]*pb.ContainerStats)
Expand Down
6 changes: 3 additions & 3 deletions cmd/crictl/events.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ var eventsCommand = &cli.Command{
&cli.StringFlag{
Name: "output",
Aliases: []string{"o"},
Value: "json",
Value: outputTypeJSON,
Usage: "Output format, One of: json|yaml|go-template",
},
&cli.StringFlag{
Expand All @@ -51,11 +51,11 @@ var eventsCommand = &cli.Command{
}

switch format := c.String("output"); format {
case "json", "yaml":
case outputTypeJSON, outputTypeYAML:
if c.String("template") != "" {
return fmt.Errorf("template can't be used with %q format", format)
}
case "go-template":
case outputTypeGoTemplate:
if err := validateTemplate(c.String(("template"))); err != nil {
return fmt.Errorf("failed to parse go-template: %w", err)
}
Expand Down
12 changes: 6 additions & 6 deletions cmd/crictl/image.go
Original file line number Diff line number Diff line change
Expand Up @@ -210,9 +210,9 @@ var listImageCommand = &cli.Command{
}

switch c.String("output") {
case "json":
case outputTypeJSON:
return outputProtobufObjAsJSON(r)
case "yaml":
case outputTypeYAML:
return outputProtobufObjAsYAML(r)
}

Expand Down Expand Up @@ -320,7 +320,7 @@ var imageStatusCommand = &cli.Command{
verbose := !(c.Bool("quiet"))
output := c.String("output")
if output == "" { // default to json output
output = "json"
output = outputTypeJSON
}
tmplStr := c.String("template")

Expand All @@ -342,7 +342,7 @@ var imageStatusCommand = &cli.Command{
return fmt.Errorf("marshal status to JSON for %q: %w", id, err)
}

if output == "table" {
if output == outputTypeTable {
outputImageStatusTable(r, verbose)
} else {
statuses = append(statuses, statusData{json: statusJSON, info: r.Info})
Expand Down Expand Up @@ -528,7 +528,7 @@ var imageFsInfoCommand = &cli.Command{

output := c.String("output")
if output == "" { // default to json output
output = "json"
output = outputTypeJSON
}
tmplStr := c.String("template")

Expand All @@ -541,7 +541,7 @@ var imageFsInfoCommand = &cli.Command{
return fmt.Errorf("marshal filesystem info to json: %w", err)
}

if output == "table" {
if output == outputTypeTable {
ouputImageFsInfoTable(r)
} else {
return outputStatusData([]statusData{{json: status}}, output, tmplStr)
Expand Down
2 changes: 1 addition & 1 deletion cmd/crictl/info.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ var runtimeStatusCommand = &cli.Command{
&cli.StringFlag{
Name: "output",
Aliases: []string{"o"},
Value: "json",
Value: outputTypeJSON,
Usage: "Output format, One of: json|yaml|go-template",
},
&cli.BoolFlag{
Expand Down
3 changes: 2 additions & 1 deletion cmd/crictl/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import (
"k8s.io/klog/v2"

"sigs.k8s.io/cri-tools/pkg/common"
"sigs.k8s.io/cri-tools/pkg/framework"
"sigs.k8s.io/cri-tools/pkg/tracing"
"sigs.k8s.io/cri-tools/pkg/version"
)
Expand Down Expand Up @@ -165,7 +166,7 @@ func getTimeout(timeDuration time.Duration) time.Duration {
return timeDuration
}

if runtime.GOOS == "windows" {
if runtime.GOOS == framework.OSWindows {
return defaultTimeoutWindows
}

Expand Down
6 changes: 3 additions & 3 deletions cmd/crictl/pod_metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ var podMetricsCommand = &cli.Command{
}

switch opts.output {
case "json", "yaml", "":
case outputTypeJSON, outputTypeYAML, "":
default:
return cli.ShowSubcommandHelp(c)
}
Expand Down Expand Up @@ -103,9 +103,9 @@ func (p *podMetricsDisplayer) displayPodMetrics(

response := &pb.ListPodSandboxMetricsResponse{PodMetrics: metrics}
switch p.opts.output {
case "json", "":
case outputTypeJSON, "":
return outputProtobufObjAsJSON(response)
case "yaml":
case outputTypeYAML:
return outputProtobufObjAsYAML(response)
}
return nil
Expand Down
4 changes: 2 additions & 2 deletions cmd/crictl/pod_stats.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,9 +158,9 @@ func (d *podStatsDisplayer) displayPodStats(

response := &pb.ListPodSandboxStatsResponse{Stats: stats}
switch d.opts.output {
case "json":
case outputTypeJSON:
return outputProtobufObjAsJSON(response)
case "yaml":
case outputTypeYAML:
return outputProtobufObjAsYAML(response)
}

Expand Down
12 changes: 6 additions & 6 deletions cmd/crictl/sandbox.go
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,7 @@ var listPodCommand = &cli.Command{
Name: "output",
Aliases: []string{"o"},
Usage: "Output format, One of: json|yaml|table",
Value: "table",
Value: outputTypeTable,
},
&cli.BoolFlag{
Name: "latest",
Expand Down Expand Up @@ -406,7 +406,7 @@ func marshalPodSandboxStatus(ps *pb.PodSandboxStatus) (string, error) {
func podSandboxStatus(client internalapi.RuntimeService, ids []string, output string, quiet bool, tmplStr string) error {
verbose := !(quiet)
if output == "" { // default to json output
output = "json"
output = outputTypeJSON
}
if len(ids) == 0 {
return errors.New("ID cannot be empty")
Expand All @@ -433,7 +433,7 @@ func podSandboxStatus(client internalapi.RuntimeService, ids []string, output st
return fmt.Errorf("marshal pod sandbox status: %w", err)
}

if output == "table" {
if output == outputTypeTable {
outputPodSandboxStatusTable(r, verbose)
} else {
statuses = append(statuses, statusData{json: statusJSON, info: r.Info})
Expand Down Expand Up @@ -523,11 +523,11 @@ func ListPodSandboxes(client internalapi.RuntimeService, opts *listOptions) erro
r = getSandboxesList(r, opts)

switch opts.output {
case "json":
case outputTypeJSON:
return outputProtobufObjAsJSON(&pb.ListPodSandboxResponse{Items: r})
case "yaml":
case outputTypeYAML:
return outputProtobufObjAsYAML(&pb.ListPodSandboxResponse{Items: r})
case "table":
case outputTypeTable:
// continue; output will be generated after the switch block ends.
default:
return fmt.Errorf("unsupported output format %q", opts.output)
Expand Down
8 changes: 4 additions & 4 deletions cmd/crictl/templates.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,10 @@ func builtinTmplFuncs() template.FuncMap {
l := cases.Lower(language.Und)
u := cases.Upper(language.Und)
return template.FuncMap{
"json": jsonBuiltinTmplFunc,
"title": t.String,
"lower": l.String,
"upper": u.String,
outputTypeJSON: jsonBuiltinTmplFunc,
"title": t.String,
"lower": l.String,
"upper": u.String,
}
}

Expand Down
19 changes: 12 additions & 7 deletions cmd/crictl/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@ import (
const (
// truncatedImageIDLen is the truncated length of imageID.
truncatedIDLen = 13

outputTypeJSON = "json"
outputTypeYAML = "yaml"
outputTypeTable = "table"
outputTypeGoTemplate = "go-template"
)

var (
Expand Down Expand Up @@ -348,19 +353,19 @@ func outputStatusData(statuses []statusData, format, tmplStr string) (err error)
}

switch format {
case "yaml":
case outputTypeYAML:
yamlInfo, err := yaml.JSONToYAML(jsonResult)
if err != nil {
return fmt.Errorf("JSON result to YAML: %w", err)
}
fmt.Println(string(yamlInfo))
case "json":
case outputTypeJSON:
var output bytes.Buffer
if err := json.Indent(&output, jsonResult, "", " "); err != nil {
return fmt.Errorf("indent JSON result: %w", err)
}
fmt.Println(output.String())
case "go-template":
case outputTypeGoTemplate:
output, err := tmplExecuteRawJSON(tmplStr, string(jsonResult))
if err != nil {
return fmt.Errorf("execute template: %w", err)
Expand All @@ -375,17 +380,17 @@ func outputStatusData(statuses []statusData, format, tmplStr string) (err error)

func outputEvent(event protoiface.MessageV1, format, tmplStr string) error {
switch format {
case "yaml":
case outputTypeYAML:
err := outputProtobufObjAsYAML(event)
if err != nil {
return err
}
case "json":
case outputTypeJSON:
err := outputProtobufObjAsJSON(event)
if err != nil {
return err
}
case "go-template":
case outputTypeGoTemplate:
jsonEvent, err := protobufObjectToJSON(event)
if err != nil {
return err
Expand Down Expand Up @@ -440,7 +445,7 @@ func marshalMapInOrder(m map[string]interface{}, t interface{}) (string, error)

// jsonFieldFromTag gets json field name from field tag.
func jsonFieldFromTag(tag reflect.StructTag) string {
field := strings.Split(tag.Get("json"), ",")[0]
field := strings.Split(tag.Get(outputTypeJSON), ",")[0]
for _, f := range strings.Split(tag.Get("protobuf"), ",") {
if !strings.HasPrefix(f, "json=") {
continue
Expand Down
10 changes: 5 additions & 5 deletions cmd/crictl/util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,39 +117,39 @@ func TestOutputStatusData(t *testing.T) {
status: statusResponse,
handlers: handlerResponse,
info: map[string]string{"key1": `{"foo": "bar"}`, "key2": `{"bar": "baz"}`},
format: "yaml",
format: outputTypeYAML,
tmplStr: "",
expectedOut: "key1:\n foo: bar\nkey2:\n bar: baz\nruntimeHandlers:\n- features:\n recursive_read_only_mounts: true\n name: runc\n- features:\n recursive_read_only_mounts: true\n user_namespaces: true\n name: crun\nstatus:\n conditions:\n - message: no network config found in C:\\Program Files\n reason: NetworkPluginNotReady\n status: false\n type: NetworkReady",
},
{
name: "YAML format with empty status response",
status: emptyResponse,
handlers: handlerResponse,
format: "yaml",
format: outputTypeYAML,
tmplStr: "",
expectedOut: "runtimeHandlers:\n- features:\n recursive_read_only_mounts: true\n name: runc\n- features:\n recursive_read_only_mounts: true\n user_namespaces: true\n name: crun",
},
{
name: "YAML format with empty handlers response",
status: statusResponse,
handlers: emptyResponse,
format: "yaml",
format: outputTypeYAML,
tmplStr: "",
expectedOut: "status:\n conditions:\n - message: no network config found in C:\\Program Files\n reason: NetworkPluginNotReady\n status: false\n type: NetworkReady",
},
{
name: "JSON format",
status: statusResponse,
handlers: handlerResponse,
format: "json",
format: outputTypeJSON,
tmplStr: "",
expectedOut: "{\n \"runtimeHandlers\": [\n {\n \"features\": {\n \"recursive_read_only_mounts\": true\n },\n \"name\": \"runc\"\n },\n {\n \"features\": {\n \"recursive_read_only_mounts\": true,\n \"user_namespaces\": true\n },\n \"name\": \"crun\"\n }\n ],\n \"status\": {\n \"conditions\": [\n {\n \"message\": \"no network config found in C:\\\\Program Files\",\n \"reason\": \"NetworkPluginNotReady\",\n \"status\": false,\n \"type\": \"NetworkReady\"\n }\n ]\n }\n}",
},
{
name: "Go template format",
status: statusResponse,
handlers: handlerResponse,
format: "go-template",
format: outputTypeGoTemplate,
tmplStr: `NetworkReady: {{ (index .status.conditions 0).status }}`,
expectedOut: "NetworkReady: false",
},
Expand Down
Loading

0 comments on commit 32c9832

Please sign in to comment.