Merge pull request #1121 from scop/lint

Lint fixes
pull/1146/head
shirou 4 years ago committed by GitHub
commit fd4fbd9c79
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -253,7 +253,7 @@ func Write(w io.Writer, order ByteOrder, data interface{}) error {
b[0] = *v b[0] = *v
case uint8: case uint8:
bs = b[:1] bs = b[:1]
b[0] = byte(v) b[0] = v
case []uint8: case []uint8:
bs = v bs = v
case *int16: case *int16:

@ -94,7 +94,7 @@ func (i FakeInvoke) CommandWithContext(ctx context.Context, name string, arg ...
var ErrNotImplementedError = errors.New("not implemented yet") 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) { func ReadFile(filename string) (string, error) {
content, err := ioutil.ReadFile(filename) content, err := ioutil.ReadFile(filename)
@ -111,7 +111,7 @@ func ReadLines(filename string) ([]string, error) {
return ReadLinesOffsetN(filename, 0, -1) 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 offset tells at which line number to start.
// The count determines the number of lines to read (starting from offset): // The count determines the number of lines to read (starting from offset):
// n >= 0: at most n lines // n >= 0: at most n lines
@ -165,7 +165,7 @@ func UintToString(orig []uint8) string {
size = i size = i
break break
} }
ret[i] = byte(o) ret[i] = o
} }
if size == -1 { if size == -1 {
size = len(orig) size = len(orig)
@ -224,31 +224,31 @@ func ReadInts(filename string) ([]int64, error) {
return ret, nil return ret, nil
} }
// Parse Hex to uint32 without error // HexToUint32 parses Hex to uint32 without error.
func HexToUint32(hex string) uint32 { func HexToUint32(hex string) uint32 {
vv, _ := strconv.ParseUint(hex, 16, 32) vv, _ := strconv.ParseUint(hex, 16, 32)
return uint32(vv) return uint32(vv)
} }
// Parse to int32 without error // mustParseInt32 parses to int32 without error.
func mustParseInt32(val string) int32 { func mustParseInt32(val string) int32 {
vv, _ := strconv.ParseInt(val, 10, 32) vv, _ := strconv.ParseInt(val, 10, 32)
return int32(vv) return int32(vv)
} }
// Parse to uint64 without error // mustParseUint64 parses to uint64 without error.
func mustParseUint64(val string) uint64 { func mustParseUint64(val string) uint64 {
vv, _ := strconv.ParseInt(val, 10, 64) vv, _ := strconv.ParseInt(val, 10, 64)
return uint64(vv) return uint64(vv)
} }
// Parse to Float64 without error // mustParseFloat64 parses to Float64 without error.
func mustParseFloat64(val string) float64 { func mustParseFloat64(val string) float64 {
vv, _ := strconv.ParseFloat(val, 64) vv, _ := strconv.ParseFloat(val, 64)
return vv 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 { func StringsHas(target []string, src string) bool {
for _, t := range target { for _, t := range target {
if strings.TrimSpace(t) == src { if strings.TrimSpace(t) == src {
@ -258,7 +258,7 @@ func StringsHas(target []string, src string) bool {
return false 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 { func StringsContains(target []string, src string) bool {
for _, t := range target { for _, t := range target {
if strings.Contains(t, src) { if strings.Contains(t, src) {

@ -26,8 +26,8 @@ func DoSysctrl(mib string) ([]string, error) {
return []string{}, err return []string{}, err
} }
v := strings.Replace(string(out), "{ ", "", 1) v := strings.Replace(string(out), "{ ", "", 1)
v = strings.Replace(string(v), " }", "", 1) v = strings.Replace(v, " }", "", 1)
values := strings.Fields(string(v)) values := strings.Fields(v)
return values, nil return values, nil
} }
@ -55,7 +55,6 @@ func NumProcs() (uint64, error) {
} }
func BootTimeWithContext(ctx context.Context) (uint64, error) { func BootTimeWithContext(ctx context.Context) (uint64, error) {
system, role, err := Virtualization() system, role, err := Virtualization()
if err != nil { if err != nil {
return 0, err return 0, err
@ -76,6 +75,18 @@ func BootTimeWithContext(ctx context.Context) (uint64, error) {
return 0, err 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" { if statFile == "stat" {
for _, line := range lines { for _, line := range lines {
if strings.HasPrefix(line, "btime") { if strings.HasPrefix(line, "btime") {
@ -91,17 +102,6 @@ func BootTimeWithContext(ctx context.Context) (uint64, error) {
return t, nil 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") return 0, fmt.Errorf("could not find btime")
@ -111,7 +111,7 @@ func Virtualization() (string, string, error) {
return VirtualizationWithContext(context.Background()) return VirtualizationWithContext(context.Background())
} }
// required variables for concurrency safe virtualization caching // required variables for concurrency safe virtualization caching.
var ( var (
cachedVirtMap map[string]string cachedVirtMap map[string]string
cachedVirtMutex sync.RWMutex cachedVirtMutex sync.RWMutex
@ -137,28 +137,27 @@ func VirtualizationWithContext(ctx context.Context) (string, string, error) {
if PathExists(filepath.Join(filename, "capabilities")) { if PathExists(filepath.Join(filename, "capabilities")) {
contents, err := ReadLines(filepath.Join(filename, "capabilities")) contents, err := ReadLines(filepath.Join(filename, "capabilities"))
if err == nil { if err == nil && StringsContains(contents, "control_d") {
if StringsContains(contents, "control_d") {
role = "host" role = "host"
} }
} }
} }
}
filename = HostProc("modules") filename = HostProc("modules")
if PathExists(filename) { if PathExists(filename) {
contents, err := ReadLines(filename) contents, err := ReadLines(filename)
if err == nil { if err == nil {
if StringsContains(contents, "kvm") { switch {
case StringsContains(contents, "kvm"):
system = "kvm" system = "kvm"
role = "host" role = "host"
} else if StringsContains(contents, "vboxdrv") { case StringsContains(contents, "vboxdrv"):
system = "vbox" system = "vbox"
role = "host" role = "host"
} else if StringsContains(contents, "vboxguest") { case StringsContains(contents, "vboxguest"):
system = "vbox" system = "vbox"
role = "guest" role = "guest"
} else if StringsContains(contents, "vmware") { case StringsContains(contents, "vmware"):
system = "vmware" system = "vmware"
role = "guest" role = "guest"
} }
@ -201,7 +200,6 @@ func VirtualizationWithContext(ctx context.Context) (string, string, error) {
if PathExists(filepath.Join(filename, "self", "status")) { if PathExists(filepath.Join(filename, "self", "status")) {
contents, err := ReadLines(filepath.Join(filename, "self", "status")) contents, err := ReadLines(filepath.Join(filename, "self", "status"))
if err == nil { if err == nil {
if StringsContains(contents, "s_context:") || if StringsContains(contents, "s_context:") ||
StringsContains(contents, "VxID:") { StringsContains(contents, "VxID:") {
system = "linux-vserver" system = "linux-vserver"
@ -224,16 +222,17 @@ func VirtualizationWithContext(ctx context.Context) (string, string, error) {
if PathExists(filepath.Join(filename, "self", "cgroup")) { if PathExists(filepath.Join(filename, "self", "cgroup")) {
contents, err := ReadLines(filepath.Join(filename, "self", "cgroup")) contents, err := ReadLines(filepath.Join(filename, "self", "cgroup"))
if err == nil { if err == nil {
if StringsContains(contents, "lxc") { switch {
case StringsContains(contents, "lxc"):
system = "lxc" system = "lxc"
role = "guest" role = "guest"
} else if StringsContains(contents, "docker") { case StringsContains(contents, "docker"):
system = "docker" system = "docker"
role = "guest" role = "guest"
} else if StringsContains(contents, "machine-rkt") { case StringsContains(contents, "machine-rkt"):
system = "rkt" system = "rkt"
role = "guest" role = "guest"
} else if PathExists("/usr/bin/lxc-version") { case PathExists("/usr/bin/lxc-version"):
system = "lxc" system = "lxc"
role = "host" role = "host"
} }
@ -281,7 +280,7 @@ func GetOSRelease() (platform string, version string, err error) {
return platform, version, nil return platform, version, nil
} }
// Remove quotes of the source string // trimQuotes removes quotes in the source string.
func trimQuotes(s string) string { func trimQuotes(s string) string {
if len(s) >= 2 { if len(s) >= 2 {
if s[0] == '"' && s[len(s)-1] == '"' { if s[0] == '"' && s[len(s)-1] == '"' {

@ -32,8 +32,7 @@ func TestReadLinesOffsetN(t *testing.T) {
func TestIntToString(t *testing.T) { func TestIntToString(t *testing.T) {
src := []int8{65, 66, 67} src := []int8{65, 66, 67}
dst := IntToString(src) if dst := IntToString(src); dst != "ABC" {
if dst != "ABC" {
t.Error("could not convert") t.Error("could not convert")
} }
} }
@ -58,8 +57,7 @@ func TestHexToUint32(t *testing.T) {
} }
func TestMustParseInt32(t *testing.T) { func TestMustParseInt32(t *testing.T) {
ret := mustParseInt32("11111") if ret := mustParseInt32("11111"); ret != int32(11111) {
if ret != int32(11111) {
t.Error("could not parse") t.Error("could not parse")
} }
} }
@ -102,8 +100,7 @@ func TestHostEtc(t *testing.T) {
if runtime.GOOS == "windows" { if runtime.GOOS == "windows" {
t.Skip("windows doesn't have etc") t.Skip("windows doesn't have etc")
} }
p := HostEtc("mtab") if p := HostEtc("mtab"); p != "/etc/mtab" {
if p != "/etc/mtab" {
t.Errorf("invalid HostEtc, %s", p) t.Errorf("invalid HostEtc, %s", p)
} }
} }

@ -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) { 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") pgrep, err := exec.LookPath("pgrep")
if err != nil { if err != nil {
return []int32{}, err return []int32{}, err

@ -2,6 +2,7 @@ package common_test
import ( import (
"context" "context"
"errors"
"testing" "testing"
"time" "time"
@ -13,7 +14,7 @@ func TestSleep(test *testing.T) {
var t = func(name string, ctx context.Context, expected error) { var t = func(name string, ctx context.Context, expected error) {
test.Run(name, func(test *testing.T) { test.Run(name, func(test *testing.T) {
var err = common.Sleep(ctx, dt) var err = common.Sleep(ctx, dt)
if err != expected { if !errors.Is(err, expected) {
test.Errorf("expected %v, got %v", expected, err) test.Errorf("expected %v, got %v", expected, err)
} }
}) })

@ -26,16 +26,15 @@ func AvgWithContext(ctx context.Context) (*AvgStat, error) {
func sysinfoAvgWithContext(ctx context.Context) (*AvgStat, error) { func sysinfoAvgWithContext(ctx context.Context) (*AvgStat, error) {
var info syscall.Sysinfo_t var info syscall.Sysinfo_t
err := syscall.Sysinfo(&info) if err := syscall.Sysinfo(&info); err != nil {
if err != nil {
return nil, err return nil, err
} }
const si_load_shift = 16 const siLoadShift = 16
return &AvgStat{ return &AvgStat{
Load1: float64(info.Loads[0]) / float64(1<<si_load_shift), Load1: float64(info.Loads[0]) / float64(1<<siLoadShift),
Load5: float64(info.Loads[1]) / float64(1<<si_load_shift), Load5: float64(info.Loads[1]) / float64(1<<siLoadShift),
Load15: float64(info.Loads[2]) / float64(1<<si_load_shift), Load15: float64(info.Loads[2]) / float64(1<<siLoadShift),
}, nil }, nil
} }
@ -103,7 +102,6 @@ func MiscWithContext(ctx context.Context) (*MiscStat, error) {
default: default:
continue continue
} }
} }
procsTotal, err := getProcsTotal() procsTotal, err := getProcsTotal()

@ -1,6 +1,7 @@
package load package load
import ( import (
"errors"
"fmt" "fmt"
"testing" "testing"
@ -8,7 +9,7 @@ import (
) )
func skipIfNotImplementedErr(t testing.TB, err error) { func skipIfNotImplementedErr(t testing.TB, err error) {
if err == common.ErrNotImplementedError { if errors.Is(err, common.ErrNotImplementedError) {
t.Skip("not implemented") t.Skip("not implemented")
} }
} }
@ -70,7 +71,6 @@ func TestMiscStatString(t *testing.T) {
} }
func BenchmarkLoad(b *testing.B) { func BenchmarkLoad(b *testing.B) {
loadAvg := func(t testing.TB) { loadAvg := func(t testing.TB) {
v, err := Avg() v, err := Avg()
skipIfNotImplementedErr(t, err) skipIfNotImplementedErr(t, err)

Loading…
Cancel
Save