chore: enable gocritic linter

pull/1813/head
Matthieu MOREL 7 days ago
parent 62da883e11
commit 384adb89af

@ -8,6 +8,7 @@ linters:
- durationcheck
- errorlint
- gci
- gocritic
- gofmt
- gofumpt
- goimports
@ -38,6 +39,9 @@ linters-settings:
- standard
- default
- prefix(github.com/shirou)
gocritic:
disabled-checks:
- captLocal
gomodguard:
blocked:
modules:

@ -105,14 +105,15 @@ func InfoWithContext(ctx context.Context) ([]InfoStat, error) {
ret := InfoStat{}
for _, line := range strings.Split(string(out), "\n") {
if strings.HasPrefix(line, "Number Of Processors:") {
switch {
case strings.HasPrefix(line, "Number Of Processors:"):
p := strings.Fields(line)
if len(p) > 3 {
if t, err := strconv.ParseUint(p[3], 10, 64); err == nil {
ret.Cores = int32(t)
}
}
} else if strings.HasPrefix(line, "Processor Clock Speed:") {
case strings.HasPrefix(line, "Processor Clock Speed:"):
p := strings.Fields(line)
if len(p) > 4 {
if t, err := strconv.ParseFloat(p[3], 64); err == nil {
@ -128,13 +129,12 @@ func InfoWithContext(ctx context.Context) ([]InfoStat, error) {
}
}
}
break
} else if strings.HasPrefix(line, "System Model:") {
case strings.HasPrefix(line, "System Model:"):
p := strings.Split(string(line), ":")
if p != nil {
ret.VendorID = strings.TrimSpace(p[1])
}
} else if strings.HasPrefix(line, "Processor Type:") {
case strings.HasPrefix(line, "Processor Type:"):
p := strings.Split(string(line), ":")
if p != nil {
c := strings.Split(string(p[1]), "_")

@ -157,7 +157,7 @@ func finishCPUInfo(ctx context.Context, c *InfoStat) {
}
c.Mhz = value / 1000.0 // value is in kHz
if c.Mhz > 9999 {
c.Mhz = c.Mhz / 1000.0 // value in Hz
c.Mhz /= 1000.0 // value in Hz
}
}

@ -81,7 +81,7 @@ func TimesWithContext(ctx context.Context, percpu bool) ([]TimesStat, error) {
if err != nil {
return nil, fmt.Errorf("cannot parse iowait: %w", err)
}
//not sure how this translates, don't report, add to kernel, something else?
// not sure how this translates, don't report, add to kernel, something else?
/*case "swap":
swap[cpuNumber], err = strconv.ParseFloat(fields[4], 64)
if err != nil {

@ -34,7 +34,7 @@ func SerialNumberWithContext(ctx context.Context, name string) (string, error) {
ret := ""
// Kind of inefficient, but it works
lines := strings.Split(string(out[:]), "\n")
lines := strings.Split(string(out), "\n")
for line := 1; line < len(lines); line++ {
v := strings.TrimSpace(lines[line])
if strings.HasPrefix(v, "Serial Number...............") {

@ -98,7 +98,7 @@ func UsageWithContext(ctx context.Context, path string) (*UsageStat, error) {
return &UsageStat{}, common.ErrNotImplementedError
}
hf := strings.Fields(strings.Replace(lines[0], "Mounted on", "Path", -1)) // headers
hf := strings.Fields(strings.ReplaceAll(lines[0], "Mounted on", "Path")) // headers
for line := 1; line < len(lines); line++ {
fs := strings.Fields(lines[line]) // values
for i, header := range hf {
@ -137,7 +137,7 @@ func UsageWithContext(ctx context.Context, path string) (*UsageStat, error) {
return nil, err
}
case `%Used`:
val, err := strconv.ParseInt(strings.Replace(fs[i], "%", "", -1), 10, 32)
val, err := strconv.ParseInt(strings.ReplaceAll(fs[i], "%", ""), 10, 32)
if err != nil {
return nil, err
}
@ -153,7 +153,7 @@ func UsageWithContext(ctx context.Context, path string) (*UsageStat, error) {
return nil, err
}
case `%Iused`:
val, err := strconv.ParseInt(strings.Replace(fs[i], "%", "", -1), 10, 32)
val, err := strconv.ParseInt(strings.ReplaceAll(fs[i], "%", ""), 10, 32)
if err != nil {
return nil, err
}
@ -178,7 +178,7 @@ func GetMountFSTypeWithContext(ctx context.Context, mp string) (string, error) {
}
// Kind of inefficient, but it works
lines := strings.Split(string(out[:]), "\n")
lines := strings.Split(string(out), "\n")
for line := 1; line < len(lines); line++ {
fields := strings.Fields(lines[line])
if strings.TrimSpace(fields[0]) == mp {

@ -24,7 +24,7 @@ func HostIDWithContext(ctx context.Context) (string, error) {
}
// The command always returns an extra newline, so we make use of Split() to get only the first line
return strings.Split(string(out[:]), "\n")[0], nil
return strings.Split(string(out), "\n")[0], nil
}
func numProcs(_ context.Context) (uint64, error) {
@ -41,7 +41,7 @@ func BootTimeWithContext(ctx context.Context) (btime uint64, err error) {
return 0, errors.New("uptime was not set, so cannot calculate boot time from it")
}
ut = ut * 60
ut *= 60
return timeSince(ut), nil
}
@ -59,7 +59,7 @@ func UptimeWithContext(ctx context.Context) (uint64, error) {
return 0, err
}
return parseUptime(string(out[:])), nil
return parseUptime(string(out)), nil
}
func parseUptime(uptime string) uint64 {
@ -166,17 +166,17 @@ func PlatformInformationWithContext(ctx context.Context) (platform string, famil
if err != nil {
return "", "", "", err
}
platform = strings.TrimRight(string(out[:]), "\n")
platform = strings.TrimRight(string(out), "\n")
// Set the family
family = strings.TrimRight(string(out[:]), "\n")
family = strings.TrimRight(string(out), "\n")
// Set the version
out, err = invoke.CommandWithContext(ctx, "oslevel")
if err != nil {
return "", "", "", err
}
version = strings.TrimRight(string(out[:]), "\n")
version = strings.TrimRight(string(out), "\n")
return platform, family, version, nil
}
@ -186,7 +186,7 @@ func KernelVersionWithContext(ctx context.Context) (version string, err error) {
if err != nil {
return "", err
}
version = strings.TrimRight(string(out[:]), "\n")
version = strings.TrimRight(string(out), "\n")
return version, nil
}
@ -196,7 +196,7 @@ func KernelArch() (arch string, err error) {
if err != nil {
return "", err
}
arch = strings.TrimRight(string(out[:]), "\n")
arch = strings.TrimRight(string(out), "\n")
return arch, nil
}

@ -176,45 +176,47 @@ func PlatformInformationWithContext(ctx context.Context) (platform string, famil
lsb = &lsbStruct{}
}
if common.PathExistsWithContents(common.HostEtcWithContext(ctx, "oracle-release")) {
switch {
case common.PathExistsWithContents(common.HostEtcWithContext(ctx, "oracle-release")):
platform = "oracle"
contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "oracle-release"))
if err == nil {
version = getRedhatishVersion(contents)
}
} else if common.PathExistsWithContents(common.HostEtcWithContext(ctx, "enterprise-release")) {
case common.PathExistsWithContents(common.HostEtcWithContext(ctx, "enterprise-release")):
platform = "oracle"
contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "enterprise-release"))
if err == nil {
version = getRedhatishVersion(contents)
}
} else if common.PathExistsWithContents(common.HostEtcWithContext(ctx, "slackware-version")) {
case common.PathExistsWithContents(common.HostEtcWithContext(ctx, "slackware-version")):
platform = "slackware"
contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "slackware-version"))
if err == nil {
version = getSlackwareVersion(contents)
}
} else if common.PathExistsWithContents(common.HostEtcWithContext(ctx, "debian_version")) {
if lsb.ID == "Ubuntu" {
case common.PathExistsWithContents(common.HostEtcWithContext(ctx, "debian_version")):
switch {
case lsb.ID == "Ubuntu":
platform = "ubuntu"
version = lsb.Release
} else if lsb.ID == "LinuxMint" {
case lsb.ID == "LinuxMint":
platform = "linuxmint"
version = lsb.Release
} else if lsb.ID == "Kylin" {
case lsb.ID == "Kylin":
platform = "Kylin"
version = lsb.Release
} else if lsb.ID == `"Cumulus Linux"` {
case lsb.ID == `"Cumulus Linux"`:
platform = "cumuluslinux"
version = lsb.Release
} else if lsb.ID == "uos" {
case lsb.ID == "uos":
platform = "uos"
version = lsb.Release
} else if lsb.ID == "Deepin" {
case lsb.ID == "Deepin":
platform = "Deepin"
version = lsb.Release
} else {
default:
if common.PathExistsWithContents("/usr/bin/raspi-config") {
platform = "raspbian"
} else {
@ -225,65 +227,65 @@ func PlatformInformationWithContext(ctx context.Context) (platform string, famil
version = contents[0]
}
}
} else if common.PathExistsWithContents(common.HostEtcWithContext(ctx, "neokylin-release")) {
case common.PathExistsWithContents(common.HostEtcWithContext(ctx, "neokylin-release")):
contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "neokylin-release"))
if err == nil {
version = getRedhatishVersion(contents)
platform = getRedhatishPlatform(contents)
}
} else if common.PathExistsWithContents(common.HostEtcWithContext(ctx, "redhat-release")) {
case common.PathExistsWithContents(common.HostEtcWithContext(ctx, "redhat-release")):
contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "redhat-release"))
if err == nil {
version = getRedhatishVersion(contents)
platform = getRedhatishPlatform(contents)
}
} else if common.PathExistsWithContents(common.HostEtcWithContext(ctx, "system-release")) {
case common.PathExistsWithContents(common.HostEtcWithContext(ctx, "system-release")):
contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "system-release"))
if err == nil {
version = getRedhatishVersion(contents)
platform = getRedhatishPlatform(contents)
}
} else if common.PathExistsWithContents(common.HostEtcWithContext(ctx, "gentoo-release")) {
case common.PathExistsWithContents(common.HostEtcWithContext(ctx, "gentoo-release")):
platform = "gentoo"
contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "gentoo-release"))
if err == nil {
version = getRedhatishVersion(contents)
}
} else if common.PathExistsWithContents(common.HostEtcWithContext(ctx, "SuSE-release")) {
case common.PathExistsWithContents(common.HostEtcWithContext(ctx, "SuSE-release")):
contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "SuSE-release"))
if err == nil {
version = getSuseVersion(contents)
platform = getSusePlatform(contents)
}
// TODO: slackware detecion
} else if common.PathExistsWithContents(common.HostEtcWithContext(ctx, "arch-release")) {
case common.PathExistsWithContents(common.HostEtcWithContext(ctx, "arch-release")):
platform = "arch"
version = lsb.Release
} else if common.PathExistsWithContents(common.HostEtcWithContext(ctx, "alpine-release")) {
case common.PathExistsWithContents(common.HostEtcWithContext(ctx, "alpine-release")):
platform = "alpine"
contents, err := common.ReadLines(common.HostEtcWithContext(ctx, "alpine-release"))
if err == nil && len(contents) > 0 && contents[0] != "" {
version = contents[0]
}
} else if common.PathExistsWithContents(common.HostEtcWithContext(ctx, "os-release")) {
case common.PathExistsWithContents(common.HostEtcWithContext(ctx, "os-release")):
p, v, err := common.GetOSReleaseWithContext(ctx)
if err == nil {
platform = p
version = v
}
} else if lsb.ID == "RedHat" {
case lsb.ID == "RedHat":
platform = "redhat"
version = lsb.Release
} else if lsb.ID == "Amazon" {
case lsb.ID == "Amazon":
platform = "amazon"
version = lsb.Release
} else if lsb.ID == "ScientificSL" {
case lsb.ID == "ScientificSL":
platform = "scientific"
version = lsb.Release
} else if lsb.ID == "XenServer" {
case lsb.ID == "XenServer":
platform = "xenserver"
version = lsb.Release
} else if lsb.ID != "" {
case lsb.ID != "":
platform = strings.ToLower(lsb.ID)
version = lsb.Release
}

@ -174,14 +174,14 @@ func platformInformation() (platform, family, version, displayVersion string, er
if err != nil {
return //nolint:nakedret //FIXME
}
platform = windows.UTF16ToString(regBuf[:])
platform = windows.UTF16ToString(regBuf)
if strings.Contains(platform, "Windows 10") { // check build number to determine whether it's actually Windows 11
err = windows.RegQueryValueEx(h, windows.StringToUTF16Ptr(`CurrentBuildNumber`), nil, &valType, nil, &bufLen)
if err == nil {
regBuf = make([]uint16, bufLen/2+1)
err = windows.RegQueryValueEx(h, windows.StringToUTF16Ptr(`CurrentBuildNumber`), nil, &valType, (*byte)(unsafe.Pointer(&regBuf[0])), &bufLen)
if err == nil {
buildNumberStr := windows.UTF16ToString(regBuf[:])
buildNumberStr := windows.UTF16ToString(regBuf)
if buildNumber, err := strconv.ParseInt(buildNumberStr, 10, 32); err == nil && buildNumber >= 22000 {
platform = strings.Replace(platform, "Windows 10", "Windows 11", 1)
}
@ -196,7 +196,7 @@ func platformInformation() (platform, family, version, displayVersion string, er
regBuf = make([]uint16, bufLen/2+1)
err = windows.RegQueryValueEx(h, windows.StringToUTF16Ptr(`CSDVersion`), nil, &valType, (*byte)(unsafe.Pointer(&regBuf[0])), &bufLen)
if err == nil {
platform += " " + windows.UTF16ToString(regBuf[:])
platform += " " + windows.UTF16ToString(regBuf)
}
}
@ -213,7 +213,7 @@ func platformInformation() (platform, family, version, displayVersion string, er
if err == nil {
regBuf := make([]uint16, bufLen/2+1)
err = windows.RegQueryValueEx(h, windows.StringToUTF16Ptr(`DisplayVersion`), nil, &valType, (*byte)(unsafe.Pointer(&regBuf[0])), &bufLen)
displayVersion = windows.UTF16ToString(regBuf[:])
displayVersion = windows.UTF16ToString(regBuf)
}
// PlatformFamily

@ -196,19 +196,20 @@ func VirtualizationWithContext(ctx context.Context) (string, string, error) {
if PathExists(filename) {
contents, err := ReadLines(filename)
if err == nil {
if StringsContains(contents, "kvm") {
switch {
case StringsContains(contents, "kvm"):
system = "kvm"
role = "host"
} else if StringsContains(contents, "hv_util") {
case StringsContains(contents, "hv_util"):
system = "hyperv"
role = "guest"
} else if StringsContains(contents, "vboxdrv") {
case StringsContains(contents, "vboxdrv"):
system = "vbox"
role = "host"
} else if StringsContains(contents, "vboxguest") {
case StringsContains(contents, "vboxguest"):
system = "vbox"
role = "guest"
} else if StringsContains(contents, "vmware") {
case StringsContains(contents, "vmware"):
system = "vmware"
role = "guest"
}
@ -273,16 +274,17 @@ func VirtualizationWithContext(ctx context.Context) (string, string, error) {
if PathExists(filepath.Join(filename, "self", "cgroup")) {
contents, err := ReadLines(filepath.Join(filename, "self", "cgroup"))
if err == nil {
if StringsContains(contents, "lxc") {
switch {
case StringsContains(contents, "lxc"):
system = "lxc"
role = "guest"
} else if StringsContains(contents, "docker") {
case StringsContains(contents, "docker"):
system = "docker"
role = "guest"
} else if StringsContains(contents, "machine-rkt") {
case StringsContains(contents, "machine-rkt"):
system = "rkt"
role = "guest"
} else if PathExists("/usr/bin/lxc-version") {
case PathExists("/usr/bin/lxc-version"):
system = "lxc"
role = "host"
}

@ -233,7 +233,7 @@ func ConvertDOSPath(p string) string {
ret, _, _ := procQueryDosDeviceW.Call(uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(szDeviceName))),
uintptr(unsafe.Pointer(&szTarget[0])),
uintptr(len(szTarget)))
if ret != 0 && windows.UTF16ToString(szTarget[:]) == rawDrive {
if ret != 0 && windows.UTF16ToString(szTarget) == rawDrive {
return filepath.Join(szDeviceName, p[len(rawDrive):])
}
}

@ -139,7 +139,8 @@ func SwapMemoryWithContext(ctx context.Context) (*SwapMemoryStat, error) {
// first, try to parse with version 2
xsw := (*xswdev)(unsafe.Pointer(&buf[0]))
if xsw.Version == XSWDEV_VERSION11 {
switch {
case xsw.Version == XSWDEV_VERSION11:
// this is version 1, so try to parse again
xsw := (*xswdev11)(unsafe.Pointer(&buf[0]))
if xsw.Version != XSWDEV_VERSION11 {
@ -147,9 +148,9 @@ func SwapMemoryWithContext(ctx context.Context) (*SwapMemoryStat, error) {
}
s.Total += uint64(xsw.NBlks)
s.Used += uint64(xsw.Used)
} else if xsw.Version != XSWDEV_VERSION {
case xsw.Version != XSWDEV_VERSION:
return nil, errors.New("xswdev version mismatch")
} else {
default:
s.Total += uint64(xsw.NBlks)
s.Used += uint64(xsw.Used)
}

@ -50,7 +50,7 @@ func fillFromMeminfoWithContext(ctx context.Context) (*VirtualMemoryStat, *ExVir
}
key := strings.TrimSpace(fields[0])
value := strings.TrimSpace(fields[1])
value = strings.Replace(value, " kB", "", -1)
value = strings.ReplaceAll(value, " kB", "")
switch key {
case "MemTotal":

@ -193,7 +193,8 @@ func parseNetstatA(output string, kind string) ([]ConnectionStat, error) {
continue
}
if strings.HasPrefix(fields[0], "f1") {
switch {
case strings.HasPrefix(fields[0], "f1"):
// Unix lines
if len(fields) < 2 {
// every unix connections have two lines
@ -207,7 +208,7 @@ func parseNetstatA(output string, kind string) ([]ConnectionStat, error) {
ret = append(ret, c)
} else if strings.HasPrefix(fields[0], "tcp") || strings.HasPrefix(fields[0], "udp") {
case strings.HasPrefix(fields[0], "tcp") || strings.HasPrefix(fields[0], "udp"):
// Inet lines
if !hasCorrectInetProto(kind, fields[0]) {
continue
@ -225,7 +226,7 @@ func parseNetstatA(output string, kind string) ([]ConnectionStat, error) {
}
ret = append(ret, c)
} else {
default:
// Header lines
continue
}

@ -269,13 +269,11 @@ func (p *Process) PercentWithContext(ctx context.Context, interval time.Duration
if err != nil {
return 0, err
}
} else {
if p.lastCPUTimes == nil {
// invoked first time
p.lastCPUTimes = cpuTimes
p.lastCPUTime = now
return 0, nil
}
} else if p.lastCPUTimes == nil {
// invoked first time
p.lastCPUTimes = cpuTimes
p.lastCPUTime = now
return 0, nil
}
numcpu := runtime.NumCPU()

@ -240,11 +240,12 @@ func (p *Process) getKProc() (*unix.KinfoProc, error) {
// If passed arg pid is 0, get information from all process.
func callPsWithContext(ctx context.Context, arg string, pid int32, threadOption bool, nameOption bool) ([][]string, error) {
var cmd []string
if pid == 0 { // will get from all processes.
switch {
case pid == 0: // will get from all processes.
cmd = []string{"-ax", "-o", arg}
} else if threadOption {
case threadOption:
cmd = []string{"-x", "-o", arg, "-M", "-p", strconv.Itoa(int(pid))}
} else {
default:
cmd = []string{"-x", "-o", arg, "-p", strconv.Itoa(int(pid))}
}
if nameOption {
@ -394,7 +395,7 @@ func (p *Process) cmdlineSlice() ([]string, error) {
// are the arguments. Everything else in the slice is then the environment
// of the process.
for _, arg := range args[1:] {
argStr = string(arg[:])
argStr = string(arg)
if len(argStr) > 0 {
if nargs > 0 {
argSlice = append(argSlice, argStr)

@ -71,7 +71,7 @@ func getTerminalMap() (map[uint64]string, error) {
return nil, err
}
rdev := uint64(stat.Rdev)
ret[rdev] = strings.Replace(name, "/dev", "", -1)
ret[rdev] = strings.ReplaceAll(name, "/dev", "")
}
return ret, nil
}

@ -357,14 +357,14 @@ func (p *Process) ExeWithContext(ctx context.Context) (string, error) {
if ret == 0 {
return "", err
}
return windows.UTF16ToString(buf[:]), nil
return windows.UTF16ToString(buf), nil
}
// XP fallback
ret, _, err := procGetProcessImageFileNameW.Call(uintptr(c), uintptr(unsafe.Pointer(&buf[0])), uintptr(size))
if ret == 0 {
return "", err
}
return common.ConvertDOSPath(windows.UTF16ToString(buf[:])), nil
return common.ConvertDOSPath(windows.UTF16ToString(buf)), nil
}
func (p *Process) CmdlineWithContext(_ context.Context) (string, error) {

@ -79,25 +79,23 @@ func readProcessMemory(h syscall.Handle, is32BitProcess bool, address uint64, si
if int(ret) >= 0 && read > 0 {
return buffer[:read]
}
} else {
// reading a 64-bit process from a 32-bit one
if common.ProcNtWow64ReadVirtualMemory64.Find() == nil { // avoid panic
var read uint64
} else if common.ProcNtWow64ReadVirtualMemory64.Find() == nil { // avoid panic
var read uint64
buffer := make([]byte, size)
buffer := make([]byte, size)
ret, _, _ := common.ProcNtWow64ReadVirtualMemory64.Call(
uintptr(h),
uintptr(address&0xFFFFFFFF), // the call expects a 64-bit value
uintptr(address>>32),
uintptr(unsafe.Pointer(&buffer[0])),
uintptr(size), // the call expects a 64-bit value
uintptr(0), // but size is 32-bit so pass zero as the high dword
uintptr(unsafe.Pointer(&read)),
)
if int(ret) >= 0 && read > 0 {
return buffer[:uint(read)]
}
ret, _, _ := common.ProcNtWow64ReadVirtualMemory64.Call(
uintptr(h),
uintptr(address&0xFFFFFFFF), // the call expects a 64-bit value
uintptr(address>>32),
uintptr(unsafe.Pointer(&buffer[0])),
uintptr(size), // the call expects a 64-bit value
uintptr(0), // but size is 32-bit so pass zero as the high dword
uintptr(unsafe.Pointer(&read)),
)
if int(ret) >= 0 && read > 0 {
return buffer[:uint(read)]
}
}

Loading…
Cancel
Save