Skip to content

Commit

Permalink
chores: fix CI lint complains and add simple tests on the way
Browse files Browse the repository at this point in the history
  • Loading branch information
aybabtme committed Oct 25, 2024
1 parent 4545307 commit f51f213
Show file tree
Hide file tree
Showing 13 changed files with 169 additions and 74 deletions.
11 changes: 0 additions & 11 deletions cmd/humanlog/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,11 @@ package main
import (
"context"
"fmt"
"log"
"log/slog"
"net/http"
"os"

"connectrpc.com/connect"
"github.com/fatih/color"
"github.com/humanlogio/api/go/svc/auth/v1/authv1connect"
userpb "github.com/humanlogio/api/go/svc/user/v1"
"github.com/humanlogio/api/go/svc/user/v1/userv1connect"
Expand Down Expand Up @@ -112,12 +110,3 @@ func authCmd(
},
}
}

func promptToLogin() {
log.Print(
color.YellowString("You are not logged in."),
)
log.Print(
color.YellowString("Run `%s` to log in.", color.New(color.Bold).Sprint("humanlog auth login")),
)
}
21 changes: 0 additions & 21 deletions cmd/humanlog/helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,8 @@ import (
"log"
"log/slog"
"net/http"
"net/http/httputil"
"os"
"runtime"
"strings"
"time"

"connectrpc.com/connect"
Expand Down Expand Up @@ -353,22 +351,3 @@ func printFact(key string, fact any) {
color.CyanString(fmt.Sprintf("%v", fact)),
)
}

type debugLogger struct {
rt http.RoundTripper
}

func (dl *debugLogger) RoundTrip(req *http.Request) (*http.Response, error) {
var rt string
if b, err := httputil.DumpRequestOut(req, true); err == nil {
rt += strings.Repeat("->", 20) + "\n" + string(b) + "\n"
}
res, err := dl.rt.RoundTrip(req)
if err != nil {
rt += strings.Repeat("<=", 20) + "\n" + strings.Repeat("\terror", 5) + "\n" + err.Error() + "\n"
} else if b, err := httputil.DumpResponse(res, true); err == nil {
rt += strings.Repeat("<=", 20) + "\n" + string(b) + "\n"
}
log.Print(rt)
return res, err
}
8 changes: 6 additions & 2 deletions cmd/humanlog/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,9 @@ var (

func fatalf(c *cli.Context, format string, args ...interface{}) {
log.Printf(format, args...)
cli.ShowAppHelp(c)
if err := cli.ShowAppHelp(c); err != nil {
panic(err)
}
os.Exit(1)
}

Expand Down Expand Up @@ -473,7 +475,9 @@ func newApp() *cli.App {

if err := beeep.Alert("humanlog has problems!", msg, ""); err != nil {
logerror("couldn't send desktop notification: %v", err)
beeep.Beep(3000, 1)
if err := beeep.Beep(3000, 1); err != nil {
logerror("can't even beeep :'( -> %w", err)
}
os.Exit(1)
}
}
Expand Down
5 changes: 0 additions & 5 deletions cmd/humanlog/versions.go
Original file line number Diff line number Diff line change
Expand Up @@ -172,11 +172,6 @@ func versionCmd(
}
}

type checkForUpdateReq struct {
arch string
os string
current *types.Version
}
type checkForUpdateRes struct {
pb *types.Version
sem semver.Version
Expand Down
5 changes: 3 additions & 2 deletions internal/pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,8 @@ type Features struct {
}

func (cfg Config) populateEmpty(other *Config) *Config {
out := *(&cfg)
cpcfg := cfg
out := &cpcfg
if out.Skip == nil && out.Keep == nil {
// skip and keep are mutually exclusive, so these are
// either both set by default, or not at all
Expand Down Expand Up @@ -165,7 +166,7 @@ func (cfg Config) populateEmpty(other *Config) *Config {
if out.ExperimentalFeatures == nil && other.ExperimentalFeatures != nil {
out.ExperimentalFeatures = other.ExperimentalFeatures
}
return &out
return out
}

type TextPalette struct {
Expand Down
68 changes: 68 additions & 0 deletions internal/pkg/config/config_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package config

import (
"encoding/json"
"testing"

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

func TestConfig_populateEmpty(t *testing.T) {

tests := []struct {
name string
input Config
other *Config
want *Config
}{
{
input: Config{},
other: &Config{
Skip: ptr([]string{"hello"}),
},
want: &Config{
Skip: ptr([]string{"hello"}),
},
},
{
input: Config{
Skip: ptr([]string{"hello"}),
},
other: &Config{},
want: &Config{
Skip: ptr([]string{"hello"}),
},
},
{
input: Config{
Skip: ptr([]string{"hello"}),
},
other: &Config{
Skip: ptr([]string{"world"}),
},
want: &Config{
Skip: ptr([]string{"hello"}),
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
originput, err := json.Marshal(tt.input)
require.NoError(t, err)

origother, err := json.Marshal(tt.other)
require.NoError(t, err)

got := tt.input.populateEmpty(tt.other)
require.Equal(t, tt.want, got)

afterinput, err := json.Marshal(tt.input)
require.NoError(t, err)
require.Equal(t, originput, afterinput, "input shouldn't be changed")

afterother, err := json.Marshal(tt.other)
require.NoError(t, err)
require.Equal(t, origother, afterother, "other shouldn't be changed")
})
}
}
13 changes: 0 additions & 13 deletions logfmt_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package humanlog

import (
"bytes"
"strconv"
"time"

"github.com/go-logfmt/logfmt"
Expand Down Expand Up @@ -100,15 +99,3 @@ func (h *LogfmtHandler) UnmarshalLogfmt(data []byte) bool {
}
return dec.Err() == nil
}

func (h *LogfmtHandler) setLevel(val []byte) { h.Level = string(val) }
func (h *LogfmtHandler) setMessage(val []byte) { h.Message = string(val) }
func (h *LogfmtHandler) setTime(val []byte) (parsed bool) {
valStr := string(val)
if valFloat, err := strconv.ParseFloat(valStr, 64); err == nil {
h.Time, parsed = tryParseTime(valFloat)
} else {
h.Time, parsed = tryParseTime(string(val))
}
return
}
78 changes: 78 additions & 0 deletions pkg/retry/retry_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package retry

import (
"context"
"math/rand"
"testing"
"time"

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

func TestRetrySuccess(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
now := time.Date(2024, time.October, 25, 13, 40, 37, 0, time.UTC)
start := now
r := rand.New(rand.NewSource(now.UnixNano()))
tch := make(chan time.Time, 10)
tch <- now

called := 0
err := Do(ctx,
func(ctx context.Context) (bool, error) {
called++
return false, nil
},
UseRand(r),
useSleepFn(func(d time.Duration) <-chan time.Time {
t.Logf("sleeping for %v", d)
now = now.Add(d)
go func() {
select {
case tch <- now:
case <-ctx.Done():
panic("so sloooow")
}
}()
return tch
}),
)
require.NoError(t, err)
require.Equal(t, 1, called)
require.Equal(t, start, now)
}

func TestRetryFailOnce(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
now := time.Date(2024, time.October, 25, 13, 40, 37, 0, time.UTC)
start := now
r := rand.New(rand.NewSource(now.UnixNano()))
tch := make(chan time.Time, 1)
tch <- now

called := 0
err := Do(ctx,
func(ctx context.Context) (bool, error) {
called++
return called != 2, nil
},
UseRand(r),
useSleepFn(func(d time.Duration) <-chan time.Time {
t.Logf("sleeping for %v", d)
now = now.Add(d)
go func() {
select {
case tch <- now:
case <-ctx.Done():
panic("so sloooow")
}
}()
return tch
}),
)
require.NoError(t, err)
require.Equal(t, 2, called)
require.Equal(t, start.Add(61015267), now)
}
4 changes: 2 additions & 2 deletions pkg/sink/logsvcsink/bidistream_sink.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,8 +130,8 @@ func (snk *ConnectBidiStreamSink) connectAndHandleBuffer(
return nil, resumeSessionID, fmt.Errorf("waiting for ingestion stream session ID: %w", err)
}
defer func() {
stream.CloseRequest()
stream.CloseResponse()
_ = stream.CloseRequest()
_ = stream.CloseResponse()
}()

ll.DebugContext(ctx, "ready to send logs")
Expand Down
2 changes: 1 addition & 1 deletion pkg/tui/components/modal/mode_selector.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ type State int
var _ tea.Model = (*Modal)(nil)

func NewModal(baseStyle lipgloss.Style, modes []*Mode, exitModeKey key.Binding) *Modal {
modeStyle := baseStyle.Copy().
modeStyle := baseStyle.
Align(lipgloss.Center).
Bold(true).
Background(lipgloss.Color("#b8bb26"))
Expand Down
10 changes: 2 additions & 8 deletions pkg/tui/querier.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,6 @@ import (
"google.golang.org/protobuf/types/known/timestamppb"
)

var axisStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("3")) // yellow

var labelStyle = lipgloss.NewStyle().
Foreground(lipgloss.Color("6")) // cyan

type QuerierModel struct {
appStyle lipgloss.Style
ctx context.Context
Expand Down Expand Up @@ -247,12 +241,12 @@ func sendQueryCmd(
msg := res.Msg()

for _, leg := range msg.Events {
enc.Encode(map[string]int64{
_ = enc.Encode(map[string]int64{
"machine": leg.MachineId,
"session": leg.SessionId,
})
for _, ev := range leg.Logs {
enc.Encode(ev)
_ = enc.Encode(ev)
}
}
sendMsg(&AppendLogsMsg{
Expand Down
14 changes: 7 additions & 7 deletions time_parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,24 +46,24 @@ func parseTimeFloat64(value float64) time.Time {
func tryParseTime(value interface{}) (time.Time, bool) {
var t time.Time
var err error
switch value.(type) {
switch v := value.(type) {
case string:
for _, layout := range TimeFormats {
t, err = time.Parse(layout, value.(string))
t, err = time.Parse(layout, v)
if err == nil {
return t, true
}
}
case float32:
return parseTimeFloat64(float64(value.(float32))), true
return parseTimeFloat64(float64(v)), true
case float64:
return parseTimeFloat64(value.(float64)), true
return parseTimeFloat64(v), true
case int:
return parseTimeFloat64(float64(value.(int))), true
return parseTimeFloat64(float64(v)), true
case int32:
return parseTimeFloat64(float64(value.(int32))), true
return parseTimeFloat64(float64(v)), true
case int64:
return parseTimeFloat64(float64(value.(int64))), true
return parseTimeFloat64(float64(v)), true
}
return t, false
}
4 changes: 2 additions & 2 deletions zap_development_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,13 @@ import (
// 5. a JSON object containing the structured k/v pairs
// 6. optional context lines - but since they are on a separate line the main
// scanner loop will never capture them
var zapDevLogsPrefixRe = regexp.MustCompile("^(?P<timestamp>\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}-\\d{4})\\s+(?P<level>\\w{4,5})\\s+(?P<location>\\S+)\\s+(?P<message>[^{]+?)\\s+(?P<jsonbody>{.+})$")
var zapDevLogsPrefixRe = regexp.MustCompile(`^(?P<timestamp>\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}-\d{4})\s+(?P<level>\w{4,5})\s+(?P<location>\S+)\s+(?P<message>[^{]+?)\s+(?P<jsonbody>{.+})$`)

// Zap Development Logs when run in Docker-Compose are nearly identical to before
// Fields are tab separated instead of whitespace
// Timestamp is now in ...
// Everything else remains the same
var zapDevDCLogsPrefixRe = regexp.MustCompile("^(?P<timestamp>\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z)\t(?P<level>\\w{4,5})\t(?P<location>\\S+)\t(?P<message>[^{]+?)\t(?P<jsonbody>{.+})$")
var zapDevDCLogsPrefixRe = regexp.MustCompile(`^(?P<timestamp>\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z)\t(?P<level>\w{4,5})\t(?P<location>\S+)\t(?P<message>[^{]+?)\t(?P<jsonbody>{.+})$`)

// This is not obviously an RFC-compliant format and is not a constant in the
// time package which is worrisome but this pattern does work.
Expand Down

0 comments on commit f51f213

Please sign in to comment.