Skip to content

enable all go-critic #1856

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

Merged
merged 1 commit into from
Jun 7, 2025
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
7 changes: 7 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,13 @@ linters:
gocritic:
disabled-checks:
- captLocal
- commentedOutCode
- deferInLoop
- hexLiteral
- hugeParam
- tooManyResultsChecker
- unnamedResult
enable-all: true
gomodguard:
blocked:
modules:
Expand Down
2 changes: 1 addition & 1 deletion cpu/cpu_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ func finishCPUInfo(ctx context.Context, c *InfoStat) {
var err error
var value float64

if len(c.CoreID) == 0 {
if c.CoreID == "" {
lines, err = common.ReadLines(sysCPUPath(ctx, c.CPU, "topology/core_id"))
if err == nil {
c.CoreID = lines[0]
Expand Down
2 changes: 1 addition & 1 deletion cpu/cpu_plan9_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ var timesTests = []struct {
func TestTimesPlan9(t *testing.T) {
for _, tt := range timesTests {
t.Run(tt.mockedRootFS, func(t *testing.T) {
t.Setenv("HOST_ROOT", filepath.Join("testdata/plan9", tt.mockedRootFS))
t.Setenv("HOST_ROOT", filepath.Join("testdata", "plan9", tt.mockedRootFS))
stats, err := Times(false)
common.SkipIfNotImplementedErr(t, err)
require.NoError(t, err)
Expand Down
6 changes: 3 additions & 3 deletions cpu/cpu_solaris.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,16 +140,16 @@ func InfoWithContext(ctx context.Context) ([]InfoStat, error) {
}

result := make([]InfoStat, 0, len(flags))
for _, proc := range procs {
procWithFlags := proc
for i := range procs {
procWithFlags := procs[i]
procWithFlags.Flags = flags
result = append(result, procWithFlags)
}

return result, nil
}

var flagsMatch = regexp.MustCompile(`[\w\.]+`)
var flagsMatch = regexp.MustCompile(`[\w.]+`)

func parseISAInfo(cmdOutput string) ([]string, error) {
words := flagsMatch.FindAllString(cmdOutput, -1)
Expand Down
3 changes: 1 addition & 2 deletions cpu/cpu_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
package cpu

import (
"fmt"
"os"
"runtime"
"testing"
Expand Down Expand Up @@ -80,7 +79,7 @@ func TestTimeStat_String(t *testing.T) {
Idle: 300.1,
}
e := `{"cpu":"cpu0","user":100.1,"system":200.1,"idle":300.1,"nice":0.0,"iowait":0.0,"irq":0.0,"softirq":0.0,"steal":0.0,"guest":0.0,"guestNice":0.0}`
assert.JSONEqf(t, e, fmt.Sprintf("%v", v), "CPUTimesStat string is invalid: %v", v)
assert.JSONEqf(t, e, v.String(), "CPUTimesStat string is invalid: %v", v)
}

func TestInfo(t *testing.T) {
Expand Down
9 changes: 6 additions & 3 deletions disk/disk_darwin.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ func PartitionsWithContext(_ context.Context, _ bool) ([]PartitionStat, error) {
// to prevent accessing uninitialized entries.
// https://github.com/shirou/gopsutil/issues/1390
fs = fs[:count]
for _, stat := range fs {
for i := range fs {
stat := &fs[i]
opts := []string{"rw"}
if stat.Flags&unix.MNT_RDONLY != 0 {
opts = []string{"ro"}
Expand Down Expand Up @@ -131,8 +132,10 @@ func SerialNumberWithContext(ctx context.Context, _ string) (string, error) {

// Extract all serial numbers into a single string
var serialNumbers []string
for _, spnvmeData := range data.SPNVMeDataType {
for _, item := range spnvmeData.Items {
for i := range data.SPNVMeDataType {
spnvmeData := &data.SPNVMeDataType[i]
for j := range spnvmeData.Items {
item := &spnvmeData.Items[j]
serialNumbers = append(serialNumbers, item.DeviceSerial)
}
}
Expand Down
6 changes: 4 additions & 2 deletions disk/disk_freebsd.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ func PartitionsWithContext(_ context.Context, _ bool) ([]PartitionStat, error) {
return ret, err
}

for _, stat := range fs {
for i := range fs {
stat := &fs[i]
opts := []string{"rw"}
if stat.Flags&unix.MNT_RDONLY != 0 {
opts = []string{"ro"}
Expand Down Expand Up @@ -182,7 +183,8 @@ func SerialNumberWithContext(ctx context.Context, name string) (string, error) {
break
}
}
if err = s.Err(); err != nil {
err = s.Err()
if err != nil {
return "", err
}
return serial, nil
Expand Down
2 changes: 1 addition & 1 deletion disk/disk_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -486,7 +486,7 @@ func IOCountersWithContext(ctx context.Context, names ...string) (map[string]IOC
return ret, nil
}

func udevData(ctx context.Context, major uint32, minor uint32, name string) (string, error) {
func udevData(ctx context.Context, major, minor uint32, name string) (string, error) {
udevDataPath := common.HostRunWithContext(ctx, fmt.Sprintf("udev/data/b%d:%d", major, minor))
if f, err := os.Open(udevDataPath); err == nil {
defer f.Close()
Expand Down
3 changes: 2 additions & 1 deletion disk/disk_netbsd.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,8 @@ func PartitionsWithContext(_ context.Context, _ bool) ([]PartitionStat, error) {
return ret, err
}

for _, stat := range buf {
for i := range buf {
stat := &buf[i]
opts := []string{"rw"}
if stat.Flag&MNT_RDONLY != 0 {
opts = []string{"rw"}
Expand Down
3 changes: 2 additions & 1 deletion disk/disk_openbsd.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ func PartitionsWithContext(_ context.Context, _ bool) ([]PartitionStat, error) {
return ret, err
}

for _, stat := range fs {
for i := range fs {
stat := &fs[i]
opts := []string{"rw"}
if stat.F_flags&unix.MNT_RDONLY != 0 {
opts = []string{"rw"}
Expand Down
7 changes: 3 additions & 4 deletions disk/disk_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
package disk

import (
"fmt"
"runtime"
"sync"
"testing"
Expand Down Expand Up @@ -81,7 +80,7 @@ func TestUsageStat_String(t *testing.T) {
Fstype: "ext4",
}
e := `{"path":"/","fstype":"ext4","total":1000,"free":2000,"used":3000,"usedPercent":50.1,"inodesTotal":4000,"inodesUsed":5000,"inodesFree":6000,"inodesUsedPercent":49.1}`
assert.JSONEqf(t, e, fmt.Sprintf("%v", v), "DiskUsageStat string is invalid: %v", v)
assert.JSONEqf(t, e, v.String(), "DiskUsageStat string is invalid: %v", v)
}

func TestPartitionStat_String(t *testing.T) {
Expand All @@ -92,7 +91,7 @@ func TestPartitionStat_String(t *testing.T) {
Opts: []string{"ro"},
}
e := `{"device":"sd01","mountpoint":"/","fstype":"ext4","opts":["ro"]}`
assert.JSONEqf(t, e, fmt.Sprintf("%v", v), "DiskUsageStat string is invalid: %v", v)
assert.JSONEqf(t, e, v.String(), "DiskUsageStat string is invalid: %v", v)
}

func TestIOCountersStat_String(t *testing.T) {
Expand All @@ -105,5 +104,5 @@ func TestIOCountersStat_String(t *testing.T) {
SerialNumber: "SERIAL",
}
e := `{"readCount":100,"mergedReadCount":0,"writeCount":200,"mergedWriteCount":0,"readBytes":300,"writeBytes":400,"readTime":0,"writeTime":0,"iopsInProgress":0,"ioTime":0,"weightedIO":0,"name":"sd01","serialNumber":"SERIAL","label":""}`
assert.JSONEqf(t, e, fmt.Sprintf("%v", v), "DiskUsageStat string is invalid: %v", v)
assert.JSONEqf(t, e, v.String(), "DiskUsageStat string is invalid: %v", v)
}
61 changes: 31 additions & 30 deletions disk/disk_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -192,40 +192,41 @@ func IOCountersWithContext(_ context.Context, names ...string) (map[string]IOCou
return drivemap, err
}
for _, v := range lpBuffer[:lpBufferLen] {
if 'A' <= v && v <= 'Z' {
path := string(rune(v)) + ":"
typepath, _ := windows.UTF16PtrFromString(path)
typeret := windows.GetDriveType(typepath)
if typeret != windows.DRIVE_FIXED {
if 'A' > v || v > 'Z' {
continue
}
path := string(rune(v)) + ":"
typepath, _ := windows.UTF16PtrFromString(path)
typeret := windows.GetDriveType(typepath)
if typeret != windows.DRIVE_FIXED {
continue
}
szDevice := `\\.\` + path
const IOCTL_DISK_PERFORMANCE = 0x70020
h, err := windows.CreateFile(syscall.StringToUTF16Ptr(szDevice), 0, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, 0, 0)
if err != nil {
if errors.Is(err, windows.ERROR_FILE_NOT_FOUND) {
continue
}
szDevice := `\\.\` + path
const IOCTL_DISK_PERFORMANCE = 0x70020
h, err := windows.CreateFile(syscall.StringToUTF16Ptr(szDevice), 0, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, 0, 0)
if err != nil {
if errors.Is(err, windows.ERROR_FILE_NOT_FOUND) {
continue
}
return drivemap, err
}
defer windows.CloseHandle(h)
return drivemap, err
}
defer windows.CloseHandle(h)

var diskPerformanceSize uint32
err = windows.DeviceIoControl(h, IOCTL_DISK_PERFORMANCE, nil, 0, (*byte)(unsafe.Pointer(&diskPerformance)), uint32(unsafe.Sizeof(diskPerformance)), &diskPerformanceSize, nil)
if err != nil {
return drivemap, err
}
var diskPerformanceSize uint32
err = windows.DeviceIoControl(h, IOCTL_DISK_PERFORMANCE, nil, 0, (*byte)(unsafe.Pointer(&diskPerformance)), uint32(unsafe.Sizeof(diskPerformance)), &diskPerformanceSize, nil)
if err != nil {
return drivemap, err
}

if len(names) == 0 || common.StringsHas(names, path) {
drivemap[path] = IOCountersStat{
ReadBytes: uint64(diskPerformance.BytesRead),
WriteBytes: uint64(diskPerformance.BytesWritten),
ReadCount: uint64(diskPerformance.ReadCount),
WriteCount: uint64(diskPerformance.WriteCount),
ReadTime: uint64(diskPerformance.ReadTime / 10000 / 1000), // convert to ms: https://github.com/giampaolo/psutil/issues/1012
WriteTime: uint64(diskPerformance.WriteTime / 10000 / 1000),
Name: path,
}
if len(names) == 0 || common.StringsHas(names, path) {
drivemap[path] = IOCountersStat{
ReadBytes: uint64(diskPerformance.BytesRead),
WriteBytes: uint64(diskPerformance.BytesWritten),
ReadCount: uint64(diskPerformance.ReadCount),
WriteCount: uint64(diskPerformance.WriteCount),
ReadTime: uint64(diskPerformance.ReadTime / 10000 / 1000), // convert to ms: https://github.com/giampaolo/psutil/issues/1012
WriteTime: uint64(diskPerformance.WriteTime / 10000 / 1000),
Name: path,
}
}
}
Expand Down
16 changes: 8 additions & 8 deletions docker/docker_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,26 +87,26 @@ func GetDockerIDListWithContext(ctx context.Context) ([]string, error) {
// containerID is same as docker id if you use docker.
// If you use container via systemd.slice, you could use
// containerID = docker-<container id>.scope and base=/sys/fs/cgroup/cpuacct/system.slice/
func CgroupCPU(containerID string, base string) (*CgroupCPUStat, error) {
func CgroupCPU(containerID, base string) (*CgroupCPUStat, error) {
return CgroupCPUWithContext(context.Background(), containerID, base)
}

// CgroupCPUUsage returns specified cgroup id CPU usage.
// containerID is same as docker id if you use docker.
// If you use container via systemd.slice, you could use
// containerID = docker-<container id>.scope and base=/sys/fs/cgroup/cpuacct/system.slice/
func CgroupCPUUsage(containerID string, base string) (float64, error) {
func CgroupCPUUsage(containerID, base string) (float64, error) {
return CgroupCPUUsageWithContext(context.Background(), containerID, base)
}

func CgroupCPUWithContext(ctx context.Context, containerID string, base string) (*CgroupCPUStat, error) {
func CgroupCPUWithContext(ctx context.Context, containerID, base string) (*CgroupCPUStat, error) {
statfile := getCgroupFilePath(ctx, containerID, base, "cpuacct", "cpuacct.stat")
lines, err := common.ReadLines(statfile)
if err != nil {
return nil, err
}
// empty containerID means all cgroup
if len(containerID) == 0 {
if containerID == "" {
containerID = "all"
}

Expand Down Expand Up @@ -166,15 +166,15 @@ func CgroupCPUDockerUsageWithContext(ctx context.Context, containerID string) (f
return CgroupCPUUsageWithContext(ctx, containerID, common.HostSysWithContext(ctx, "fs/cgroup/cpuacct/docker"))
}

func CgroupMem(containerID string, base string) (*CgroupMemStat, error) {
func CgroupMem(containerID, base string) (*CgroupMemStat, error) {
return CgroupMemWithContext(context.Background(), containerID, base)
}

func CgroupMemWithContext(ctx context.Context, containerID string, base string) (*CgroupMemStat, error) {
func CgroupMemWithContext(ctx context.Context, containerID, base string) (*CgroupMemStat, error) {
statfile := getCgroupFilePath(ctx, containerID, base, "memory", "memory.stat")

// empty containerID means all cgroup
if len(containerID) == 0 {
if containerID == "" {
containerID = "all"
}
lines, err := common.ReadLines(statfile)
Expand Down Expand Up @@ -276,7 +276,7 @@ func CgroupMemDockerWithContext(ctx context.Context, containerID string) (*Cgrou

// getCgroupFilePath constructs file path to get targeted stats file.
func getCgroupFilePath(ctx context.Context, containerID, base, target, file string) string {
if len(base) == 0 {
if base == "" {
base = common.HostSysWithContext(ctx, fmt.Sprintf("fs/cgroup/%s/docker", target))
}
statfile := path.Join(base, containerID, file)
Expand Down
8 changes: 4 additions & 4 deletions docker/docker_notlinux.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,11 @@ func GetDockerIDListWithContext(_ context.Context) ([]string, error) {
// containerID is same as docker id if you use docker.
// If you use container via systemd.slice, you could use
// containerID = docker-<container id>.scope and base=/sys/fs/cgroup/cpuacct/system.slice/
func CgroupCPU(containerID string, base string) (*CgroupCPUStat, error) {
func CgroupCPU(containerID, base string) (*CgroupCPUStat, error) {
return CgroupCPUWithContext(context.Background(), containerID, base)
}

func CgroupCPUWithContext(_ context.Context, _ string, _ string) (*CgroupCPUStat, error) {
func CgroupCPUWithContext(_ context.Context, _, _ string) (*CgroupCPUStat, error) {
return nil, ErrCgroupNotAvailable
}

Expand All @@ -49,11 +49,11 @@ func CgroupCPUDockerWithContext(ctx context.Context, containerID string) (*Cgrou
return CgroupCPUWithContext(ctx, containerID, common.HostSysWithContext(ctx, "fs/cgroup/cpuacct/docker"))
}

func CgroupMem(containerID string, base string) (*CgroupMemStat, error) {
func CgroupMem(containerID, base string) (*CgroupMemStat, error) {
return CgroupMemWithContext(context.Background(), containerID, base)
}

func CgroupMemWithContext(_ context.Context, _ string, _ string) (*CgroupMemStat, error) {
func CgroupMemWithContext(_ context.Context, _, _ string) (*CgroupMemStat, error) {
return nil, ErrCgroupNotAvailable
}

Expand Down
2 changes: 1 addition & 1 deletion host/host_aix.go
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ func UsersWithContext(ctx context.Context) ([]UserStat, error) {
}

// Much of this function could be static. However, to be future proofed, I've made it call the OS for the information in all instances.
func PlatformInformationWithContext(ctx context.Context) (platform string, family string, version string, err error) {
func PlatformInformationWithContext(ctx context.Context) (platform, family, version string, err error) {
// Set the platform (which should always, and only be, "AIX") from `uname -s`
out, err := invoke.CommandWithContext(ctx, "uname", "-s")
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion host/host_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ func getlsbStruct(ctx context.Context) (*lsbStruct, error) {
return ret, nil
}

func PlatformInformationWithContext(ctx context.Context) (platform string, family string, version string, err error) {
func PlatformInformationWithContext(ctx context.Context) (platform, family, version string, err error) {
lsb, err := getlsbStruct(ctx)
if err != nil {
lsb = &lsbStruct{}
Expand Down
2 changes: 1 addition & 1 deletion host/host_solaris.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ func numProcs(_ context.Context) (uint64, error) {
return uint64(len(dirs)), nil
}

var kstatMatch = regexp.MustCompile(`([^\s]+)[\s]+([^\s]*)`)
var kstatMatch = regexp.MustCompile(`(\S+)\s+(\S*)`)

func BootTimeWithContext(ctx context.Context) (uint64, error) {
out, err := invoke.CommandWithContext(ctx, "kstat", "-p", "unix:0:system_misc:boot_time")
Expand Down
5 changes: 2 additions & 3 deletions host/host_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
package host

import (
"fmt"
"os"
"sync"
"testing"
Expand Down Expand Up @@ -86,7 +85,7 @@ func TestInfoStat_String(t *testing.T) {
KernelArch: "x86_64",
}
e := `{"hostname":"test","uptime":3000,"bootTime":1447040000,"procs":100,"os":"linux","platform":"ubuntu","platformFamily":"","platformVersion":"","kernelVersion":"","kernelArch":"x86_64","virtualizationSystem":"","virtualizationRole":"","hostId":"edfd25ff-3c9c-b1a4-e660-bd826495ad35"}`
assert.JSONEqf(t, e, fmt.Sprintf("%v", v), "HostInfoStat string is invalid:\ngot %v\nwant %v", v, e)
assert.JSONEqf(t, e, v.String(), "HostInfoStat string is invalid:\ngot %v\nwant %v", v, e)
}

func TestUserStat_String(t *testing.T) {
Expand All @@ -97,7 +96,7 @@ func TestUserStat_String(t *testing.T) {
Started: 100,
}
e := `{"user":"user","terminal":"term","host":"host","started":100}`
assert.JSONEqf(t, e, fmt.Sprintf("%v", v), "UserStat string is invalid: %v", v)
assert.JSONEqf(t, e, v.String(), "UserStat string is invalid: %v", v)
}

func TestGuid(t *testing.T) {
Expand Down
2 changes: 1 addition & 1 deletion host/host_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ func BootTimeWithContext(_ context.Context) (uint64, error) {
return t, nil
}

func PlatformInformationWithContext(_ context.Context) (platform string, family string, version string, err error) {
func PlatformInformationWithContext(_ context.Context) (platform, family, version string, err error) {
platform, family, _, displayVersion, err := platformInformation()
if err != nil {
return "", "", "", err
Expand Down
Loading