Skip to content

Commit

Permalink
Merge pull request shirou#1121 from scop/lint
Browse files Browse the repository at this point in the history
Lint fixes
  • Loading branch information
shirou authored Oct 7, 2021
2 parents 5bdd02c + a21240a commit fd4fbd9
Show file tree
Hide file tree
Showing 8 changed files with 52 additions and 58 deletions.
2 changes: 1 addition & 1 deletion internal/common/binary.go
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ func Write(w io.Writer, order ByteOrder, data interface{}) error {
b[0] = *v
case uint8:
bs = b[:1]
b[0] = byte(v)
b[0] = v
case []uint8:
bs = v
case *int16:
Expand Down
20 changes: 10 additions & 10 deletions internal/common/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ func (i FakeInvoke) CommandWithContext(ctx context.Context, name string, arg ...

var ErrNotImplementedError = errors.New("not implemented yet")

// ReadFile reads contents from a file
// ReadFile reads contents from a file.
func ReadFile(filename string) (string, error) {
content, err := ioutil.ReadFile(filename)

Expand All @@ -111,7 +111,7 @@ func ReadLines(filename string) ([]string, error) {
return ReadLinesOffsetN(filename, 0, -1)
}

// ReadLines reads contents from file and splits them by new line.
// ReadLinesOffsetN reads contents from file and splits them by new line.
// The offset tells at which line number to start.
// The count determines the number of lines to read (starting from offset):
// n >= 0: at most n lines
Expand Down Expand Up @@ -165,7 +165,7 @@ func UintToString(orig []uint8) string {
size = i
break
}
ret[i] = byte(o)
ret[i] = o
}
if size == -1 {
size = len(orig)
Expand Down Expand Up @@ -224,31 +224,31 @@ func ReadInts(filename string) ([]int64, error) {
return ret, nil
}

// Parse Hex to uint32 without error
// HexToUint32 parses Hex to uint32 without error.
func HexToUint32(hex string) uint32 {
vv, _ := strconv.ParseUint(hex, 16, 32)
return uint32(vv)
}

// Parse to int32 without error
// mustParseInt32 parses to int32 without error.
func mustParseInt32(val string) int32 {
vv, _ := strconv.ParseInt(val, 10, 32)
return int32(vv)
}

// Parse to uint64 without error
// mustParseUint64 parses to uint64 without error.
func mustParseUint64(val string) uint64 {
vv, _ := strconv.ParseInt(val, 10, 64)
return uint64(vv)
}

// Parse to Float64 without error
// mustParseFloat64 parses to Float64 without error.
func mustParseFloat64(val string) float64 {
vv, _ := strconv.ParseFloat(val, 64)
return vv
}

// StringsHas checks the target string slice contains src or not
// StringsHas checks the target string slice contains src or not.
func StringsHas(target []string, src string) bool {
for _, t := range target {
if strings.TrimSpace(t) == src {
Expand All @@ -258,7 +258,7 @@ func StringsHas(target []string, src string) bool {
return false
}

// StringsContains checks the src in any string of the target string slice
// StringsContains checks the src in any string of the target string slice.
func StringsContains(target []string, src string) bool {
for _, t := range target {
if strings.Contains(t, src) {
Expand Down Expand Up @@ -308,7 +308,7 @@ func PathExists(filename string) bool {
return false
}

//GetEnv retrieves the environment variable key. If it does not exist it returns the default.
// GetEnv retrieves the environment variable key. If it does not exist it returns the default.
func GetEnv(key string, dfault string, combineWith ...string) string {
value := os.Getenv(key)
if value == "" {
Expand Down
57 changes: 28 additions & 29 deletions internal/common/common_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ func DoSysctrl(mib string) ([]string, error) {
return []string{}, err
}
v := strings.Replace(string(out), "{ ", "", 1)
v = strings.Replace(string(v), " }", "", 1)
values := strings.Fields(string(v))
v = strings.Replace(v, " }", "", 1)
values := strings.Fields(v)

return values, nil
}
Expand Down Expand Up @@ -55,7 +55,6 @@ func NumProcs() (uint64, error) {
}

func BootTimeWithContext(ctx context.Context) (uint64, error) {

system, role, err := Virtualization()
if err != nil {
return 0, err
Expand All @@ -76,6 +75,18 @@ func BootTimeWithContext(ctx context.Context) (uint64, error) {
return 0, err
}

if statFile == "uptime" {
if len(lines) != 1 {
return 0, fmt.Errorf("wrong uptime format")
}
f := strings.Fields(lines[0])
b, err := strconv.ParseFloat(f[0], 64)
if err != nil {
return 0, err
}
t := uint64(time.Now().Unix()) - uint64(b)
return t, nil
}
if statFile == "stat" {
for _, line := range lines {
if strings.HasPrefix(line, "btime") {
Expand All @@ -91,17 +102,6 @@ func BootTimeWithContext(ctx context.Context) (uint64, error) {
return t, nil
}
}
} else if statFile == "uptime" {
if len(lines) != 1 {
return 0, fmt.Errorf("wrong uptime format")
}
f := strings.Fields(lines[0])
b, err := strconv.ParseFloat(f[0], 64)
if err != nil {
return 0, err
}
t := uint64(time.Now().Unix()) - uint64(b)
return t, nil
}

return 0, fmt.Errorf("could not find btime")
Expand All @@ -111,7 +111,7 @@ func Virtualization() (string, string, error) {
return VirtualizationWithContext(context.Background())
}

// required variables for concurrency safe virtualization caching
// required variables for concurrency safe virtualization caching.
var (
cachedVirtMap map[string]string
cachedVirtMutex sync.RWMutex
Expand All @@ -137,10 +137,8 @@ func VirtualizationWithContext(ctx context.Context) (string, string, error) {

if PathExists(filepath.Join(filename, "capabilities")) {
contents, err := ReadLines(filepath.Join(filename, "capabilities"))
if err == nil {
if StringsContains(contents, "control_d") {
role = "host"
}
if err == nil && StringsContains(contents, "control_d") {
role = "host"
}
}
}
Expand All @@ -149,16 +147,17 @@ 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, "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"
}
Expand Down Expand Up @@ -201,7 +200,6 @@ func VirtualizationWithContext(ctx context.Context) (string, string, error) {
if PathExists(filepath.Join(filename, "self", "status")) {
contents, err := ReadLines(filepath.Join(filename, "self", "status"))
if err == nil {

if StringsContains(contents, "s_context:") ||
StringsContains(contents, "VxID:") {
system = "linux-vserver"
Expand All @@ -224,16 +222,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"
}
Expand Down Expand Up @@ -281,7 +280,7 @@ func GetOSRelease() (platform string, version string, err error) {
return platform, version, nil
}

// Remove quotes of the source string
// trimQuotes removes quotes in the source string.
func trimQuotes(s string) string {
if len(s) >= 2 {
if s[0] == '"' && s[len(s)-1] == '"' {
Expand Down
9 changes: 3 additions & 6 deletions internal/common/common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,7 @@ func TestReadLinesOffsetN(t *testing.T) {

func TestIntToString(t *testing.T) {
src := []int8{65, 66, 67}
dst := IntToString(src)
if dst != "ABC" {
if dst := IntToString(src); dst != "ABC" {
t.Error("could not convert")
}
}
Expand All @@ -58,8 +57,7 @@ func TestHexToUint32(t *testing.T) {
}

func TestMustParseInt32(t *testing.T) {
ret := mustParseInt32("11111")
if ret != int32(11111) {
if ret := mustParseInt32("11111"); ret != int32(11111) {
t.Error("could not parse")
}
}
Expand Down Expand Up @@ -102,8 +100,7 @@ func TestHostEtc(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("windows doesn't have etc")
}
p := HostEtc("mtab")
if p != "/etc/mtab" {
if p := HostEtc("mtab"); p != "/etc/mtab" {
t.Errorf("invalid HostEtc, %s", p)
}
}
Expand Down
3 changes: 1 addition & 2 deletions internal/common/common_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,7 @@ func CallLsofWithContext(ctx context.Context, invoke Invoker, pid int32, args ..
}

func CallPgrepWithContext(ctx context.Context, invoke Invoker, pid int32) ([]int32, error) {
var cmd []string
cmd = []string{"-P", strconv.Itoa(int(pid))}
cmd := []string{"-P", strconv.Itoa(int(pid))}
pgrep, err := exec.LookPath("pgrep")
if err != nil {
return []int32{}, err
Expand Down
3 changes: 2 additions & 1 deletion internal/common/sleep_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package common_test

import (
"context"
"errors"
"testing"
"time"

Expand All @@ -13,7 +14,7 @@ func TestSleep(test *testing.T) {
var t = func(name string, ctx context.Context, expected error) {
test.Run(name, func(test *testing.T) {
var err = common.Sleep(ctx, dt)
if err != expected {
if !errors.Is(err, expected) {
test.Errorf("expected %v, got %v", expected, err)
}
})
Expand Down
12 changes: 5 additions & 7 deletions load/load_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,15 @@ func AvgWithContext(ctx context.Context) (*AvgStat, error) {

func sysinfoAvgWithContext(ctx context.Context) (*AvgStat, error) {
var info syscall.Sysinfo_t
err := syscall.Sysinfo(&info)
if err != nil {
if err := syscall.Sysinfo(&info); err != nil {
return nil, err
}

const si_load_shift = 16
const siLoadShift = 16
return &AvgStat{
Load1: float64(info.Loads[0]) / float64(1<<si_load_shift),
Load5: float64(info.Loads[1]) / float64(1<<si_load_shift),
Load15: float64(info.Loads[2]) / float64(1<<si_load_shift),
Load1: float64(info.Loads[0]) / float64(1<<siLoadShift),
Load5: float64(info.Loads[1]) / float64(1<<siLoadShift),
Load15: float64(info.Loads[2]) / float64(1<<siLoadShift),
}, nil
}

Expand Down Expand Up @@ -103,7 +102,6 @@ func MiscWithContext(ctx context.Context) (*MiscStat, error) {
default:
continue
}

}

procsTotal, err := getProcsTotal()
Expand Down
4 changes: 2 additions & 2 deletions load/load_test.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
package load

import (
"errors"
"fmt"
"testing"

"github.com/shirou/gopsutil/internal/common"
)

func skipIfNotImplementedErr(t testing.TB, err error) {
if err == common.ErrNotImplementedError {
if errors.Is(err, common.ErrNotImplementedError) {
t.Skip("not implemented")
}
}
Expand Down Expand Up @@ -70,7 +71,6 @@ func TestMiscStatString(t *testing.T) {
}

func BenchmarkLoad(b *testing.B) {

loadAvg := func(t testing.TB) {
v, err := Avg()
skipIfNotImplementedErr(t, err)
Expand Down

0 comments on commit fd4fbd9

Please sign in to comment.