Skip to content

Commit

Permalink
chore: Resolve linter issues for ineffassign, nilerr, gosimple... (in…
Browse files Browse the repository at this point in the history
  • Loading branch information
zak-pawel authored Oct 12, 2022
1 parent beba64e commit 08c1ce9
Show file tree
Hide file tree
Showing 12 changed files with 95 additions and 120 deletions.
7 changes: 3 additions & 4 deletions agent/tick_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,9 @@ func TestAlignedTicker(t *testing.T) {

clk.Add(10 * time.Second)
for !clk.Now().After(until) {
select {
case tm := <-ticker.Elapsed():
actual = append(actual, tm.UTC())
}
tm := <-ticker.Elapsed()
actual = append(actual, tm.UTC())

clk.Add(10 * time.Second)
}

Expand Down
17 changes: 10 additions & 7 deletions internal/content_coding.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ type AutoDecoder struct {
identity *IdentityDecoder
}

func (a *AutoDecoder) SetEnconding(encoding string) {
func (a *AutoDecoder) SetEncoding(encoding string) {
a.encoding = encoding
}

Expand Down Expand Up @@ -199,7 +199,7 @@ func (*IdentityEncoder) Encode(data []byte) ([]byte, error) {

// ContentDecoder removes a wrapper encoding from byte buffers.
type ContentDecoder interface {
SetEnconding(string)
SetEncoding(string)
Decode([]byte) ([]byte, error)
}

Expand All @@ -216,13 +216,16 @@ func NewGzipDecoder() (*GzipDecoder, error) {
}, nil
}

func (*GzipDecoder) SetEnconding(string) {}
func (*GzipDecoder) SetEncoding(string) {}

func (d *GzipDecoder) Decode(data []byte) ([]byte, error) {
d.reader.Reset(bytes.NewBuffer(data))
err := d.reader.Reset(bytes.NewBuffer(data))
if err != nil {
return nil, err
}
d.buf.Reset()

_, err := d.buf.ReadFrom(d.reader)
_, err = d.buf.ReadFrom(d.reader)
if err != nil && err != io.EOF {
return nil, err
}
Expand All @@ -243,7 +246,7 @@ func NewZlibDecoder() (*ZlibDecoder, error) {
}, nil
}

func (*ZlibDecoder) SetEnconding(string) {}
func (*ZlibDecoder) SetEncoding(string) {}

func (d *ZlibDecoder) Decode(data []byte) ([]byte, error) {
d.buf.Reset()
Expand Down Expand Up @@ -271,7 +274,7 @@ func NewIdentityDecoder() *IdentityDecoder {
return &IdentityDecoder{}
}

func (*IdentityDecoder) SetEnconding(string) {}
func (*IdentityDecoder) SetEncoding(string) {}

func (*IdentityDecoder) Decode(data []byte) ([]byte, error) {
return data, nil
Expand Down
37 changes: 9 additions & 28 deletions internal/internal.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,45 +70,26 @@ func ProductToken() string {
}

// ReadLines reads contents from a file and splits them by new lines.
// A convenience wrapper to ReadLinesOffsetN(filename, 0, -1).
func ReadLines(filename string) ([]string, error) {
return ReadLinesOffsetN(filename, 0, -1)
}

// ReadLines 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
// n < 0: whole file
func ReadLinesOffsetN(filename string, offset uint, n int) ([]string, error) {
f, err := os.Open(filename)
if err != nil {
return []string{""}, err
}
defer f.Close()

var ret []string

r := bufio.NewReader(f)
for i := 0; i < n+int(offset) || n < 0; i++ {
line, err := r.ReadString('\n')
if err != nil {
break
}
if i < int(offset) {
continue
}
ret = append(ret, strings.Trim(line, "\n"))
scanner := bufio.NewScanner(f)
for scanner.Scan() {
ret = append(ret, scanner.Text())
}

return ret, nil
}

// RandomString returns a random string of alpha-numeric characters
// RandomString returns a random string of alphanumeric characters
func RandomString(n int) string {
var bytes = make([]byte, n)
rand.Read(bytes)
rand.Read(bytes) //nolint:revive // from math/rand/rand.go: "It always returns len(p) and a nil error."
for i, b := range bytes {
bytes[i] = alphanum[b%byte(len(alphanum))]
}
Expand Down Expand Up @@ -249,7 +230,7 @@ func CompressWithGzip(data io.Reader) (io.ReadCloser, error) {
// The format can be one of "unix", "unix_ms", "unix_us", "unix_ns", or a Go
// time layout suitable for time.Parse.
//
// When using the "unix" format, a optional fractional component is allowed.
// When using the "unix" format, an optional fractional component is allowed.
// Specific unix time precisions cannot have a fractional component.
//
// Unix times may be an int64, float64, or string. When using a Go format
Expand Down Expand Up @@ -344,17 +325,17 @@ func timeFromFraction(f *big.Rat, factor int64) time.Time {

// sanitizeTimestamp removes thousand separators and uses dot as
// decimal separator. Returns also a boolean indicating success.
func sanitizeTimestamp(timestamp string, decimalSeparartor []string) string {
func sanitizeTimestamp(timestamp string, decimalSeparator []string) string {
// Remove thousand-separators that are not used for decimal separation
sanitized := timestamp
for _, s := range []string{" ", ",", "."} {
if !choice.Contains(s, decimalSeparartor) {
if !choice.Contains(s, decimalSeparator) {
sanitized = strings.ReplaceAll(sanitized, s, "")
}
}

// Replace decimal separators by dot to have a standard, parsable format
for _, s := range decimalSeparartor {
for _, s := range decimalSeparator {
// Make sure we replace only the first occurrence of any separator.
if strings.Contains(sanitized, s) {
return strings.Replace(sanitized, s, ".", 1)
Expand Down
50 changes: 25 additions & 25 deletions internal/internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import (
"testing"
"time"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

Expand Down Expand Up @@ -61,9 +60,9 @@ func TestRunTimeout(t *testing.T) {
err := RunTimeout(cmd, time.Millisecond*20)
elapsed := time.Since(start)

assert.Equal(t, ErrTimeout, err)
require.Equal(t, ErrTimeout, err)
// Verify that command gets killed in 20ms, with some breathing room
assert.True(t, elapsed < time.Millisecond*75)
require.True(t, elapsed < time.Millisecond*75)
}

// Verifies behavior of a command that doesn't get killed.
Expand All @@ -83,7 +82,7 @@ func TestRunTimeoutFastExit(t *testing.T) {

require.NoError(t, err)
// Verify that command gets killed in 20ms, with some breathing room
assert.True(t, elapsed < time.Millisecond*75)
require.True(t, elapsed < time.Millisecond*75)

// Verify "process already finished" log doesn't occur.
time.Sleep(time.Millisecond * 75)
Expand All @@ -101,9 +100,9 @@ func TestCombinedOutputTimeout(t *testing.T) {
_, err := CombinedOutputTimeout(cmd, time.Millisecond*20)
elapsed := time.Since(start)

assert.Equal(t, ErrTimeout, err)
require.Equal(t, ErrTimeout, err)
// Verify that command gets killed in 20ms, with some breathing room
assert.True(t, elapsed < time.Millisecond*75)
require.True(t, elapsed < time.Millisecond*75)
}

func TestCombinedOutput(t *testing.T) {
Expand All @@ -113,8 +112,8 @@ func TestCombinedOutput(t *testing.T) {
cmd := exec.Command(echobin, "foo")
out, err := CombinedOutputTimeout(cmd, time.Second)

assert.NoError(t, err)
assert.Equal(t, "foo\n", string(out))
require.NoError(t, err)
require.Equal(t, "foo\n", string(out))
}

// test that CombinedOutputTimeout and exec.Cmd.CombinedOutput return
Expand All @@ -125,12 +124,13 @@ func TestCombinedOutputError(t *testing.T) {
}
cmd := exec.Command(shell, "-c", "false")
expected, err := cmd.CombinedOutput()
require.Error(t, err)

cmd2 := exec.Command(shell, "-c", "false")
actual, err := CombinedOutputTimeout(cmd2, time.Second)

assert.Error(t, err)
assert.Equal(t, expected, actual)
require.Error(t, err)
require.Equal(t, expected, actual)
}

func TestRunError(t *testing.T) {
Expand All @@ -140,7 +140,7 @@ func TestRunError(t *testing.T) {
cmd := exec.Command(shell, "-c", "false")
err := RunTimeout(cmd, time.Second)

assert.Error(t, err)
require.Error(t, err)
}

func TestRandomSleep(t *testing.T) {
Expand All @@ -150,13 +150,13 @@ func TestRandomSleep(t *testing.T) {
s := time.Now()
RandomSleep(time.Duration(0), make(chan struct{}))
elapsed := time.Since(s)
assert.True(t, elapsed < time.Millisecond)
require.True(t, elapsed < time.Millisecond)

// test that max sleep is respected
s = time.Now()
RandomSleep(time.Millisecond*50, make(chan struct{}))
elapsed = time.Since(s)
assert.True(t, elapsed < time.Millisecond*100)
require.True(t, elapsed < time.Millisecond*100)

// test that shutdown is respected
s = time.Now()
Expand All @@ -167,24 +167,24 @@ func TestRandomSleep(t *testing.T) {
}()
RandomSleep(time.Second, shutdown)
elapsed = time.Since(s)
assert.True(t, elapsed < time.Millisecond*150)
require.True(t, elapsed < time.Millisecond*150)
}

func TestCompressWithGzip(t *testing.T) {
testData := "the quick brown fox jumps over the lazy dog"
inputBuffer := bytes.NewBuffer([]byte(testData))

outputBuffer, err := CompressWithGzip(inputBuffer)
assert.NoError(t, err)
require.NoError(t, err)

gzipReader, err := gzip.NewReader(outputBuffer)
assert.NoError(t, err)
require.NoError(t, err)
defer gzipReader.Close()

output, err := io.ReadAll(gzipReader)
assert.NoError(t, err)
require.NoError(t, err)

assert.Equal(t, testData, string(output))
require.Equal(t, testData, string(output))
}

type mockReader struct {
Expand All @@ -200,23 +200,23 @@ func TestCompressWithGzipEarlyClose(t *testing.T) {
mr := &mockReader{}

rc, err := CompressWithGzip(mr)
assert.NoError(t, err)
require.NoError(t, err)

n, err := io.CopyN(io.Discard, rc, 10000)
assert.NoError(t, err)
assert.Equal(t, int64(10000), n)
require.NoError(t, err)
require.Equal(t, int64(10000), n)

r1 := mr.readN
err = rc.Close()
assert.NoError(t, err)
require.NoError(t, err)

n, err = io.CopyN(io.Discard, rc, 10000)
assert.Error(t, io.EOF, err)
assert.Equal(t, int64(0), n)
require.Error(t, io.EOF, err)
require.Equal(t, int64(0), n)

r2 := mr.readN
// no more read to the source after closing
assert.Equal(t, r1, r2)
require.Equal(t, r1, r2)
}

func TestAlignDuration(t *testing.T) {
Expand Down
4 changes: 2 additions & 2 deletions internal/process/process_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ func TestRestartingRebindsPipes(t *testing.T) {
time.Sleep(1 * time.Millisecond)
}

syscall.Kill(p.Pid(), syscall.SIGKILL)
require.NoError(t, syscall.Kill(p.Pid(), syscall.SIGKILL))

for atomic.LoadInt64(&linesRead) < 2 {
time.Sleep(1 * time.Millisecond)
Expand Down Expand Up @@ -74,7 +74,7 @@ func TestMain(m *testing.M) {
// cleanly.
func externalProcess() {
wait := make(chan int)
fmt.Fprintln(os.Stdout, "started")
_, _ = fmt.Fprintln(os.Stdout, "started")
<-wait
os.Exit(2)
}
11 changes: 5 additions & 6 deletions internal/syslog/framing.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,12 @@ func (f Framing) String() string {
}

// UnmarshalTOML implements ability to unmarshal framing from TOML files.
func (f *Framing) UnmarshalTOML(data []byte) (err error) {
func (f *Framing) UnmarshalTOML(data []byte) error {
return f.UnmarshalText(data)
}

// UnmarshalText implements encoding.TextUnmarshaler
func (f *Framing) UnmarshalText(data []byte) (err error) {
func (f *Framing) UnmarshalText(data []byte) error {
s := string(data)
switch strings.ToUpper(s) {
case `OCTET-COUNTING`:
Expand All @@ -40,21 +40,20 @@ func (f *Framing) UnmarshalText(data []byte) (err error) {
fallthrough
case `'OCTET-COUNTING'`:
*f = OctetCounting
return

return nil
case `NON-TRANSPARENT`:
fallthrough
case `"NON-TRANSPARENT"`:
fallthrough
case `'NON-TRANSPARENT'`:
*f = NonTransparent
return
return nil
}
*f = -1
return fmt.Errorf("unknown framing")
}

// MarshalText implements encoding.TextMarshaler
// MarshalText implements encoding.TextMarshaller
func (f Framing) MarshalText() ([]byte, error) {
s := f.String()
if s != "" {
Expand Down
4 changes: 3 additions & 1 deletion internal/templating/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ type Engine struct {

// Apply extracts the template fields from the given line and returns the measurement
// name, tags and field name
func (e *Engine) Apply(line string) (string, map[string]string, string, error) {
//
//nolint:revive //function-result-limit conditionally 4 return results allowed
func (e *Engine) Apply(line string) (measurementName string, tags map[string]string, field string, err error) {
return e.matcher.match(line).Apply(line, e.joiner)
}

Expand Down
Loading

0 comments on commit 08c1ce9

Please sign in to comment.