run "make fmt" (#233)

This commit is contained in:
Pavel Griaznov
2024-08-11 19:19:41 +00:00
committed by GitHub
parent 54cb4ea318
commit 8da11eb3fa
42 changed files with 151 additions and 97 deletions

View File

@ -1,6 +1,10 @@
help: ## Show this help. help: ## Show this help.
@fgrep -h "##" $(MAKEFILE_LIST) | fgrep -v fgrep | sed -e 's/\\$$//' | sed -e 's/##//' @fgrep -h "##" $(MAKEFILE_LIST) | fgrep -v fgrep | sed -e 's/\\$$//' | sed -e 's/##//'
fmt:
gofumpt -l -w -extra .
gci write --custom-order -s standard -s 'Prefix(github.com/ddworken/hishtory)' -s default .
local-install: ## Build and install hishtory locally from the current directory local-install: ## Build and install hishtory locally from the current directory
go build; ./hishtory install go build; ./hishtory install
@ -9,7 +13,7 @@ forcetest: ## Force running all tests without a test cache
make test make test
test: ## Run all tests test: ## Run all tests
TZ='America/Los_Angeles' HISHTORY_TEST=1 HISHTORY_SKIP_INIT_IMPORT=1 gotestsum --packages ./... --rerun-fails=10 --rerun-fails-max-failures=30 --format testname --jsonfile /tmp/testrun.json --post-run-command "go run client/posttest/main.go export" -- -p 1 -timeout 90m TZ='America/Los_Angeles' HISHTORY_TEST=1 HISHTORY_SKIP_INIT_IMPORT=1 gotestsum --packages ./... --rerun-fails=10 --rerun-fails-max-failures=30 --format testname --jsonfile /tmp/testrun.json --post-run-command "go run client/posttest/main.go export" -- -p 1 -timeout 90m
ftest: ## Run a specific test specified via `make ftest FILTER=TestParam/testTui/color` ftest: ## Run a specific test specified via `make ftest FILTER=TestParam/testTui/color`
go clean -testcache go clean -testcache
@ -23,26 +27,26 @@ release: ## [ddworken only] Release the latest version on Github
expr `cat VERSION` + 1 > VERSION expr `cat VERSION` + 1 > VERSION
git add VERSION git add VERSION
git commit -m "Release v0.`cat VERSION`" --no-verify git commit -m "Release v0.`cat VERSION`" --no-verify
git push git push
gh release create v0.`cat VERSION` --generate-notes gh release create v0.`cat VERSION` --generate-notes
git push && git push --tags git push && git push --tags
build-static: ## [ddworken only] Build the server for hishtory.dev build-static: ## [ddworken only] Build the server for hishtory.dev
ssh server "cd ~/code/hishtory/; git pull; docker build --build-arg GOARCH=amd64 --tag gcr.io/dworken-k8s/hishtory-static --file backend/web/caddy/Dockerfile ." ssh server "cd ~/code/hishtory/; git pull; docker build --build-arg GOARCH=amd64 --tag gcr.io/dworken-k8s/hishtory-static --file backend/web/caddy/Dockerfile ."
build-api: ## [ddworken only] Build the API for api.hishtory.dev build-api: ## [ddworken only] Build the API for api.hishtory.dev
rm hishtory server || true rm hishtory server || true
docker build --build-arg GOARCH=amd64 --tag gcr.io/dworken-k8s/hishtory-api --file backend/server/Dockerfile . docker build --build-arg GOARCH=amd64 --tag gcr.io/dworken-k8s/hishtory-api --file backend/server/Dockerfile .
deploy-static: ## [ddworken only] Build and deploy the server for hishtory.dev deploy-static: ## [ddworken only] Build and deploy the server for hishtory.dev
deploy-static: build-static deploy-static: build-static
ssh server "docker push gcr.io/dworken-k8s/hishtory-static" ssh server "docker push gcr.io/dworken-k8s/hishtory-static"
ssh monoserver "cd ~/infra/ && docker compose pull hishtory-static && docker compose rm -svf hishtory-static && docker compose up -d hishtory-static" ssh monoserver "cd ~/infra/ && docker compose pull hishtory-static && docker compose rm -svf hishtory-static && docker compose up -d hishtory-static"
deploy-api: ## [ddworken only] Build and deploy the API server for api.hishtory.dev deploy-api: ## [ddworken only] Build and deploy the API server for api.hishtory.dev
deploy-api: build-api deploy-api: build-api
docker push gcr.io/dworken-k8s/hishtory-api docker push gcr.io/dworken-k8s/hishtory-api
ssh monoserver "cd ~/infra/ && docker compose pull hishtory-api && docker compose up -d --no-deps hishtory-api" ssh monoserver "cd ~/infra/ && docker compose pull hishtory-api && docker compose up -d --no-deps hishtory-api"
deploy: ## [ddworken only] Build and deploy all backend services deploy: ## [ddworken only] Build and deploy all backend services
deploy: release deploy-static deploy-api deploy: release deploy-static deploy-api

View File

@ -8,6 +8,7 @@ import (
"time" "time"
"github.com/ddworken/hishtory/shared" "github.com/ddworken/hishtory/shared"
"github.com/jackc/pgx/v4/stdlib" "github.com/jackc/pgx/v4/stdlib"
_ "github.com/lib/pq" _ "github.com/lib/pq"
sqltrace "gopkg.in/DataDog/dd-trace-go.v1/contrib/database/sql" sqltrace "gopkg.in/DataDog/dd-trace-go.v1/contrib/database/sql"

View File

@ -5,6 +5,7 @@ import (
"fmt" "fmt"
"github.com/ddworken/hishtory/shared" "github.com/ddworken/hishtory/shared"
"gorm.io/gorm" "gorm.io/gorm"
) )

View File

@ -65,7 +65,7 @@ func (db *DB) UpdateUsageDataForNumEntriesHandled(ctx context.Context, userId, d
return nil return nil
} }
func (db *DB) UpdateUsageDataClientVersion(ctx context.Context, userID, deviceID string, version string) error { func (db *DB) UpdateUsageDataClientVersion(ctx context.Context, userID, deviceID, version string) error {
tx := db.DB.WithContext(ctx).Exec("UPDATE usage_data SET version = ? WHERE user_id = ? AND device_id = ?", version, userID, deviceID) tx := db.DB.WithContext(ctx).Exec("UPDATE usage_data SET version = ? WHERE user_id = ? AND device_id = ?", version, userID, deviceID)
if tx.Error != nil { if tx.Error != nil {

View File

@ -5,6 +5,7 @@ import (
"testing" "testing"
"github.com/ddworken/hishtory/shared/testutils" "github.com/ddworken/hishtory/shared/testutils"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )

View File

@ -12,6 +12,7 @@ import (
"github.com/ddworken/hishtory/backend/server/internal/database" "github.com/ddworken/hishtory/backend/server/internal/database"
"github.com/ddworken/hishtory/shared" "github.com/ddworken/hishtory/shared"
"github.com/ddworken/hishtory/shared/ai" "github.com/ddworken/hishtory/shared/ai"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer" "gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer"
) )
@ -195,7 +196,6 @@ func (s *Server) apiGetPendingDumpRequestsHandler(w http.ResponseWriter, r *http
func (s *Server) apiDownloadHandler(w http.ResponseWriter, r *http.Request) { func (s *Server) apiDownloadHandler(w http.ResponseWriter, r *http.Request) {
err := json.NewEncoder(w).Encode(s.updateInfo) err := json.NewEncoder(w).Encode(s.updateInfo)
if err != nil { if err != nil {
panic(fmt.Errorf("failed to JSON marshall the update info: %w", err)) panic(fmt.Errorf("failed to JSON marshall the update info: %w", err))
} }

View File

@ -14,15 +14,15 @@ import (
"time" "time"
"github.com/ddworken/hishtory/backend/server/internal/database" "github.com/ddworken/hishtory/backend/server/internal/database"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gorm.io/gorm"
"github.com/ddworken/hishtory/client/data" "github.com/ddworken/hishtory/client/data"
"github.com/ddworken/hishtory/shared" "github.com/ddworken/hishtory/shared"
"github.com/ddworken/hishtory/shared/testutils" "github.com/ddworken/hishtory/shared/testutils"
"github.com/go-test/deep" "github.com/go-test/deep"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gorm.io/gorm"
) )
var DB *database.DB var DB *database.DB

View File

@ -9,9 +9,10 @@ import (
"strings" "strings"
"time" "time"
"github.com/DataDog/datadog-go/statsd"
"github.com/ddworken/hishtory/backend/server/internal/database" "github.com/ddworken/hishtory/backend/server/internal/database"
"github.com/ddworken/hishtory/shared" "github.com/ddworken/hishtory/shared"
"github.com/DataDog/datadog-go/statsd"
httptrace "gopkg.in/DataDog/dd-trace-go.v1/contrib/net/http" httptrace "gopkg.in/DataDog/dd-trace-go.v1/contrib/net/http"
) )
@ -27,8 +28,10 @@ type Server struct {
updateInfo shared.UpdateInfo updateInfo shared.UpdateInfo
} }
type CronFn func(ctx context.Context, db *database.DB, stats *statsd.Client) error type (
type Option func(*Server) CronFn func(ctx context.Context, db *database.DB, stats *statsd.Client) error
Option func(*Server)
)
func WithStatsd(statsd *statsd.Client) Option { func WithStatsd(statsd *statsd.Client) Option {
return func(s *Server) { return func(s *Server) {
@ -154,7 +157,7 @@ func (s *Server) handleNonCriticalError(err error) {
} }
} }
func (s *Server) updateUsageData(ctx context.Context, version string, remoteAddr string, userId, deviceId string, numEntriesHandled int, isQuery bool) error { func (s *Server) updateUsageData(ctx context.Context, version, remoteAddr, userId, deviceId string, numEntriesHandled int, isQuery bool) error {
if !s.trackUsageData { if !s.trackUsageData {
return nil return nil
} }

View File

@ -7,10 +7,11 @@ import (
"os" "os"
"time" "time"
"github.com/DataDog/datadog-go/statsd"
"github.com/ddworken/hishtory/backend/server/internal/database" "github.com/ddworken/hishtory/backend/server/internal/database"
"github.com/ddworken/hishtory/backend/server/internal/release" "github.com/ddworken/hishtory/backend/server/internal/release"
"github.com/ddworken/hishtory/backend/server/internal/server" "github.com/ddworken/hishtory/backend/server/internal/server"
"github.com/DataDog/datadog-go/statsd"
_ "github.com/lib/pq" _ "github.com/lib/pq"
"gorm.io/gorm" "gorm.io/gorm"
"gorm.io/gorm/logger" "gorm.io/gorm/logger"
@ -21,10 +22,8 @@ const (
StatsdSocket = "unix:///var/run/datadog/dsd.socket" StatsdSocket = "unix:///var/run/datadog/dsd.socket"
) )
var ( // Filled in via ldflags with the latest released version as of the server getting built
// Filled in via ldflags with the latest released version as of the server getting built var ReleaseVersion string
ReleaseVersion string
)
func isTestEnvironment() bool { func isTestEnvironment() bool {
return os.Getenv("HISHTORY_TEST") != "" return os.Getenv("HISHTORY_TEST") != ""
@ -104,8 +103,10 @@ func OpenDB() (*database.DB, error) {
return db, nil return db, nil
} }
var LAST_USER_STATS_RUN = time.Unix(0, 0) var (
var LAST_DEEP_CLEAN = time.Unix(0, 0) LAST_USER_STATS_RUN = time.Unix(0, 0)
LAST_DEEP_CLEAN = time.Unix(0, 0)
)
func cron(ctx context.Context, db *database.DB, stats *statsd.Client) error { func cron(ctx context.Context, db *database.DB, stats *statsd.Client) error {
// Determine the latest released version of hishtory to serve via the /api/v1/download // Determine the latest released version of hishtory to serve via the /api/v1/download

View File

@ -16,10 +16,6 @@ import (
"testing" "testing"
"time" "time"
"github.com/google/go-cmp/cmp"
"github.com/google/uuid"
"gorm.io/gorm"
"github.com/ddworken/hishtory/client/cmd" "github.com/ddworken/hishtory/client/cmd"
"github.com/ddworken/hishtory/client/data" "github.com/ddworken/hishtory/client/data"
"github.com/ddworken/hishtory/client/hctx" "github.com/ddworken/hishtory/client/hctx"
@ -27,7 +23,11 @@ import (
"github.com/ddworken/hishtory/shared" "github.com/ddworken/hishtory/shared"
"github.com/ddworken/hishtory/shared/ai" "github.com/ddworken/hishtory/shared/ai"
"github.com/ddworken/hishtory/shared/testutils" "github.com/ddworken/hishtory/shared/testutils"
"github.com/google/go-cmp/cmp"
"github.com/google/uuid"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"gorm.io/gorm"
) )
func skipSlowTests() bool { func skipSlowTests() bool {
@ -1244,7 +1244,7 @@ func TestStripBashTimePrefix(t *testing.T) {
homedir, err := os.UserHomeDir() homedir, err := os.UserHomeDir()
require.NoError(t, err) require.NoError(t, err)
f, err := os.OpenFile(path.Join(homedir, data.GetHishtoryPath(), "config.sh"), f, err := os.OpenFile(path.Join(homedir, data.GetHishtoryPath(), "config.sh"),
os.O_APPEND|os.O_WRONLY, 0644) os.O_APPEND|os.O_WRONLY, 0o644)
require.NoError(t, err) require.NoError(t, err)
defer f.Close() defer f.Close()
_, err = f.WriteString("\nexport HISTTIMEFORMAT='%F %T '\n") _, err = f.WriteString("\nexport HISTTIMEFORMAT='%F %T '\n")
@ -1263,7 +1263,7 @@ func TestStripBashTimePrefix(t *testing.T) {
homedir, err = os.UserHomeDir() homedir, err = os.UserHomeDir()
require.NoError(t, err) require.NoError(t, err)
f, err = os.OpenFile(path.Join(homedir, data.GetHishtoryPath(), "config.sh"), f, err = os.OpenFile(path.Join(homedir, data.GetHishtoryPath(), "config.sh"),
os.O_APPEND|os.O_WRONLY, 0644) os.O_APPEND|os.O_WRONLY, 0o644)
require.NoError(t, err) require.NoError(t, err)
defer f.Close() defer f.Close()
_, err = f.WriteString("\nexport HISTTIMEFORMAT='[%c] '\n") _, err = f.WriteString("\nexport HISTTIMEFORMAT='[%c] '\n")
@ -2995,7 +2995,7 @@ func testMultipleUsers(t *testing.T, tester shellTester) {
func createSyntheticImportEntries(t testing.TB, numSyntheticEntries int) { func createSyntheticImportEntries(t testing.TB, numSyntheticEntries int) {
homedir, err := os.UserHomeDir() homedir, err := os.UserHomeDir()
require.NoError(t, err) require.NoError(t, err)
f, err := os.OpenFile(path.Join(homedir, ".bash_history"), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) f, err := os.OpenFile(path.Join(homedir, ".bash_history"), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
require.NoError(t, err) require.NoError(t, err)
defer f.Close() defer f.Close()
for i := 1; i <= numSyntheticEntries; i++ { for i := 1; i <= numSyntheticEntries; i++ {

View File

@ -7,6 +7,7 @@ import (
"github.com/ddworken/hishtory/client/hctx" "github.com/ddworken/hishtory/client/hctx"
"github.com/ddworken/hishtory/client/lib" "github.com/ddworken/hishtory/client/lib"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )

View File

@ -6,6 +6,7 @@ import (
"github.com/ddworken/hishtory/client/hctx" "github.com/ddworken/hishtory/client/hctx"
"github.com/ddworken/hishtory/client/lib" "github.com/ddworken/hishtory/client/lib"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@ -57,6 +58,7 @@ var deleteCustomColumnsCmd = &cobra.Command{
lib.CheckFatalError(hctx.SetConfig(config)) lib.CheckFatalError(hctx.SetConfig(config))
}, },
} }
var deleteDisplayedColumnCommand = &cobra.Command{ var deleteDisplayedColumnCommand = &cobra.Command{
Use: "displayed-columns", Use: "displayed-columns",
Aliases: []string{"displayed-column"}, Aliases: []string{"displayed-column"},

View File

@ -7,6 +7,7 @@ import (
"github.com/ddworken/hishtory/client/hctx" "github.com/ddworken/hishtory/client/hctx"
"github.com/ddworken/hishtory/client/lib" "github.com/ddworken/hishtory/client/lib"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@ -41,6 +42,7 @@ var getHighlightMatchesCmd = &cobra.Command{
fmt.Println(config.HighlightMatches) fmt.Println(config.HighlightMatches)
}, },
} }
var getDefaultFilterCmd = &cobra.Command{ var getDefaultFilterCmd = &cobra.Command{
Use: "default-filter", Use: "default-filter",
Short: "The default filter that is applied to all search queries", Short: "The default filter that is applied to all search queries",

View File

@ -6,6 +6,7 @@ import (
"github.com/ddworken/hishtory/client/hctx" "github.com/ddworken/hishtory/client/hctx"
"github.com/ddworken/hishtory/client/lib" "github.com/ddworken/hishtory/client/lib"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )

View File

@ -8,6 +8,7 @@ import (
"github.com/ddworken/hishtory/client/hctx" "github.com/ddworken/hishtory/client/hctx"
"github.com/ddworken/hishtory/client/lib" "github.com/ddworken/hishtory/client/lib"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@ -102,6 +103,7 @@ var setEnableAiCompletionCmd = &cobra.Command{
lib.CheckFatalError(hctx.SetConfig(config)) lib.CheckFatalError(hctx.SetConfig(config))
}, },
} }
var setPresavingCmd = &cobra.Command{ var setPresavingCmd = &cobra.Command{
Use: "presaving", Use: "presaving",
Short: "Enable 'presaving' of shell entries that never finish running", Short: "Enable 'presaving' of shell entries that never finish running",

View File

@ -5,6 +5,7 @@ import (
"github.com/ddworken/hishtory/client/hctx" "github.com/ddworken/hishtory/client/hctx"
"github.com/ddworken/hishtory/client/lib" "github.com/ddworken/hishtory/client/lib"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )

View File

@ -5,6 +5,7 @@ import (
"github.com/ddworken/hishtory/client/hctx" "github.com/ddworken/hishtory/client/hctx"
"github.com/ddworken/hishtory/client/lib" "github.com/ddworken/hishtory/client/lib"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )

View File

@ -19,15 +19,18 @@ import (
"github.com/ddworken/hishtory/client/hctx" "github.com/ddworken/hishtory/client/hctx"
"github.com/ddworken/hishtory/client/lib" "github.com/ddworken/hishtory/client/lib"
"github.com/ddworken/hishtory/shared" "github.com/ddworken/hishtory/shared"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"gorm.io/gorm" "gorm.io/gorm"
) )
var offlineInit *bool var (
var forceInit *bool offlineInit *bool
var offlineInstall *bool forceInit *bool
var skipConfigModification *bool offlineInstall *bool
skipConfigModification *bool
)
var installCmd = &cobra.Command{ var installCmd = &cobra.Command{
Use: "install", Use: "install",
@ -581,7 +584,7 @@ func stripLines(filePath, lines string) error {
ret += "\n" ret += "\n"
} }
} }
return os.WriteFile(filePath, []byte(ret), 0644) return os.WriteFile(filePath, []byte(ret), 0o644)
} }
func setup(userSecret string, isOffline bool) error { func setup(userSecret string, isOffline bool) error {

View File

@ -8,6 +8,7 @@ import (
"github.com/ddworken/hishtory/client/data" "github.com/ddworken/hishtory/client/data"
"github.com/ddworken/hishtory/client/hctx" "github.com/ddworken/hishtory/client/hctx"
"github.com/ddworken/hishtory/shared/testutils" "github.com/ddworken/hishtory/shared/testutils"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )

View File

@ -11,6 +11,7 @@ import (
"github.com/ddworken/hishtory/client/hctx" "github.com/ddworken/hishtory/client/hctx"
"github.com/ddworken/hishtory/client/lib" "github.com/ddworken/hishtory/client/lib"
"github.com/ddworken/hishtory/client/tui" "github.com/ddworken/hishtory/client/tui"
"github.com/fatih/color" "github.com/fatih/color"
"github.com/muesli/termenv" "github.com/muesli/termenv"
"github.com/rodaine/table" "github.com/rodaine/table"
@ -171,7 +172,7 @@ func DisplayResults(ctx context.Context, results []*data.HistoryEntry, numResult
numRows := 0 numRows := 0
var seenCommands = make(map[string]bool) seenCommands := make(map[string]bool)
for _, entry := range results { for _, entry := range results {
if config.FilterDuplicateCommands && entry != nil { if config.FilterDuplicateCommands && entry != nil {

View File

@ -12,6 +12,7 @@ import (
"github.com/ddworken/hishtory/client/hctx" "github.com/ddworken/hishtory/client/hctx"
"github.com/ddworken/hishtory/client/lib" "github.com/ddworken/hishtory/client/lib"
"github.com/ddworken/hishtory/shared" "github.com/ddworken/hishtory/shared"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )

View File

@ -3,6 +3,7 @@ package cmd
import ( import (
"github.com/ddworken/hishtory/client/hctx" "github.com/ddworken/hishtory/client/hctx"
"github.com/ddworken/hishtory/client/lib" "github.com/ddworken/hishtory/client/lib"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )

View File

@ -7,6 +7,7 @@ import (
"os" "os"
"github.com/ddworken/hishtory/client/lib" "github.com/ddworken/hishtory/client/lib"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )

View File

@ -19,6 +19,7 @@ import (
"github.com/ddworken/hishtory/client/hctx" "github.com/ddworken/hishtory/client/hctx"
"github.com/ddworken/hishtory/client/lib" "github.com/ddworken/hishtory/client/lib"
"github.com/ddworken/hishtory/shared" "github.com/ddworken/hishtory/shared"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"gorm.io/gorm" "gorm.io/gorm"
@ -441,7 +442,6 @@ func extractCommandFromArg(ctx context.Context, shell, arg string, isPresave boo
} else { } else {
return "", fmt.Errorf("tried to save a hishtory entry from an unsupported shell=%#v", shell) return "", fmt.Errorf("tried to save a hishtory entry from an unsupported shell=%#v", shell)
} }
} }
func trimTrailingWhitespace(s string) string { func trimTrailingWhitespace(s string) string {
@ -582,7 +582,6 @@ func parseCrossPlatformTime(data string) time.Time {
} else { } else {
return time.Unix(startTime, 0).UTC() return time.Unix(startTime, 0).UTC()
} }
} }
func getLastCommand(history string) (string, error) { func getLastCommand(history string) (string, error) {

View File

@ -9,6 +9,7 @@ import (
"github.com/ddworken/hishtory/client/hctx" "github.com/ddworken/hishtory/client/hctx"
"github.com/ddworken/hishtory/shared/testutils" "github.com/ddworken/hishtory/shared/testutils"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
@ -167,6 +168,7 @@ func TestBuildRegexFromTimeFormat(t *testing.T) {
} }
} }
} }
func TestGetLastCommand(t *testing.T) { func TestGetLastCommand(t *testing.T) {
testcases := []struct { testcases := []struct {
input, expectedOutput string input, expectedOutput string

View File

@ -6,6 +6,7 @@ import (
"github.com/ddworken/hishtory/client/data" "github.com/ddworken/hishtory/client/data"
"github.com/ddworken/hishtory/client/hctx" "github.com/ddworken/hishtory/client/hctx"
"github.com/ddworken/hishtory/client/lib" "github.com/ddworken/hishtory/client/lib"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )

View File

@ -7,6 +7,7 @@ import (
"github.com/ddworken/hishtory/client/data" "github.com/ddworken/hishtory/client/data"
"github.com/ddworken/hishtory/client/hctx" "github.com/ddworken/hishtory/client/hctx"
"github.com/ddworken/hishtory/client/lib" "github.com/ddworken/hishtory/client/lib"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )

View File

@ -18,6 +18,7 @@ import (
"github.com/ddworken/hishtory/client/hctx" "github.com/ddworken/hishtory/client/hctx"
"github.com/ddworken/hishtory/client/lib" "github.com/ddworken/hishtory/client/lib"
"github.com/ddworken/hishtory/shared" "github.com/ddworken/hishtory/shared"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )

View File

@ -8,12 +8,15 @@ import (
"github.com/ddworken/hishtory/client/hctx" "github.com/ddworken/hishtory/client/hctx"
"github.com/ddworken/hishtory/client/lib" "github.com/ddworken/hishtory/client/lib"
"github.com/ddworken/hishtory/client/webui" "github.com/ddworken/hishtory/client/webui"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
var disableAuth *bool var (
var forceCreds *string disableAuth *bool
var port *int forceCreds *string
port *int
)
var webUiCmd = &cobra.Command{ var webUiCmd = &cobra.Command{
Use: "start-web-ui", Use: "start-web-ui",

View File

@ -57,5 +57,4 @@ func TestCustomColumnSerialization(t *testing.T) {
if val != "[{\"name\":\"name1\",\"value\":\"val1\"},{\"name\":\"name2\",\"value\":\"val2\"}]" { if val != "[{\"name\":\"name1\",\"value\":\"val1\"},{\"name\":\"name2\",\"value\":\"val2\"}]" {
t.Fatalf("unexpected val for empty CustomColumns: %#v", val) t.Fatalf("unexpected val for empty CustomColumns: %#v", val)
} }
} }

View File

@ -8,6 +8,7 @@ import (
"testing" "testing"
"github.com/ddworken/hishtory/shared/testutils" "github.com/ddworken/hishtory/shared/testutils"
"github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
@ -18,8 +19,10 @@ type operation struct {
redactQuery string redactQuery string
} }
var tmp int = 0 var (
var runCounter *int = &tmp tmp int = 0
runCounter *int = &tmp
)
func fuzzTest(t *testing.T, tester shellTester, input string) { func fuzzTest(t *testing.T, tester shellTester, input string) {
testutils.TestLog(t, fmt.Sprintf("Starting fuzz test for input=%#v", input)) testutils.TestLog(t, fmt.Sprintf("Starting fuzz test for input=%#v", input))

View File

@ -13,14 +13,14 @@ import (
"github.com/ddworken/hishtory/client/data" "github.com/ddworken/hishtory/client/data"
"github.com/ddworken/hishtory/client/tui/keybindings" "github.com/ddworken/hishtory/client/tui/keybindings"
"github.com/ddworken/hishtory/shared" "github.com/ddworken/hishtory/shared"
// Needed to use sqlite without CGO
"github.com/glebarez/sqlite"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"gopkg.in/natefinch/lumberjack.v2" "gopkg.in/natefinch/lumberjack.v2"
"gorm.io/gorm" "gorm.io/gorm"
"gorm.io/gorm/logger" "gorm.io/gorm/logger"
// Needed to use sqlite without CGO
"github.com/glebarez/sqlite"
) )
var ( var (

View File

@ -5,6 +5,7 @@ import (
"bytes" "bytes"
"context" "context"
"database/sql" "database/sql"
_ "embed" // for embedding config.sh
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
@ -21,18 +22,15 @@ import (
"strings" "strings"
"time" "time"
_ "embed" // for embedding config.sh "github.com/ddworken/hishtory/client/data"
"github.com/ddworken/hishtory/client/hctx"
"golang.org/x/exp/slices" "github.com/ddworken/hishtory/shared"
"gorm.io/gorm"
"github.com/araddon/dateparse" "github.com/araddon/dateparse"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/schollz/progressbar/v3" "github.com/schollz/progressbar/v3"
"golang.org/x/exp/slices"
"github.com/ddworken/hishtory/client/data" "gorm.io/gorm"
"github.com/ddworken/hishtory/client/hctx"
"github.com/ddworken/hishtory/shared"
) )
//go:embed config.sh //go:embed config.sh
@ -44,8 +42,10 @@ var ConfigZshContents string
//go:embed config.fish //go:embed config.fish
var ConfigFishContents string var ConfigFishContents string
var Version string = "Unknown" var (
var GitCommit string = "Unknown" Version string = "Unknown"
GitCommit string = "Unknown"
)
// 512KB ought to be enough for any reasonable cmd // 512KB ought to be enough for any reasonable cmd
// Funnily enough, 256KB actually wasn't enough. See https://github.com/ddworken/hishtory/issues/93 // Funnily enough, 256KB actually wasn't enough. See https://github.com/ddworken/hishtory/issues/93
@ -728,7 +728,7 @@ func parseTimeGenerously(input string) (time.Time, error) {
} }
// A wrapper around tx.Where(...) that filters out nil-values // A wrapper around tx.Where(...) that filters out nil-values
func where(tx *gorm.DB, s string, v1 any, v2 any) *gorm.DB { func where(tx *gorm.DB, s string, v1, v2 any) *gorm.DB {
if v1 == nil && v2 == nil { if v1 == nil && v2 == nil {
return tx.Where(s) return tx.Where(s)
} }
@ -787,7 +787,7 @@ func Search(ctx context.Context, db *gorm.DB, query string, limit int) ([]*data.
const SEARCH_RETRY_COUNT = 3 const SEARCH_RETRY_COUNT = 3
func retryingSearch(ctx context.Context, db *gorm.DB, query string, limit int, currentRetryNum int) ([]*data.HistoryEntry, error) { func retryingSearch(ctx context.Context, db *gorm.DB, query string, limit, currentRetryNum int) ([]*data.HistoryEntry, error) {
if ctx == nil && query != "" { if ctx == nil && query != "" {
return nil, fmt.Errorf("lib.Search called with a nil context and a non-empty query (this should never happen)") return nil, fmt.Errorf("lib.Search called with a nil context and a non-empty query (this should never happen)")
} }
@ -982,7 +982,7 @@ func heuristicIgnoreUnclosedQuote(isCurrentlyInQuotedString bool, quoteType rune
return true return true
} }
func containsUnescaped(query string, token string) bool { func containsUnescaped(query, token string) bool {
runeQuery := []rune(query) runeQuery := []rune(query)
for i := 0; i < len(runeQuery); i++ { for i := 0; i < len(runeQuery); i++ {
if runeQuery[i] == '\\' && i+1 < len(runeQuery) { if runeQuery[i] == '\\' && i+1 < len(runeQuery) {

View File

@ -10,6 +10,7 @@ import (
"github.com/ddworken/hishtory/client/hctx" "github.com/ddworken/hishtory/client/hctx"
"github.com/ddworken/hishtory/shared" "github.com/ddworken/hishtory/shared"
"github.com/ddworken/hishtory/shared/testutils" "github.com/ddworken/hishtory/shared/testutils"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
@ -142,6 +143,7 @@ func TestChunks(t *testing.T) {
} }
} }
} }
func TestZshWeirdness(t *testing.T) { func TestZshWeirdness(t *testing.T) {
testcases := []struct { testcases := []struct {
input string input string

View File

@ -13,6 +13,7 @@ import (
"github.com/ddworken/hishtory/client/hctx" "github.com/ddworken/hishtory/client/hctx"
"github.com/ddworken/hishtory/shared" "github.com/ddworken/hishtory/shared"
"github.com/slsa-framework/slsa-verifier/options" "github.com/slsa-framework/slsa-verifier/options"
"github.com/slsa-framework/slsa-verifier/verifiers" "github.com/slsa-framework/slsa-verifier/verifiers"
) )

View File

@ -20,8 +20,10 @@ var GLOBAL_STATSD *statsd.Client = nil
var NUM_TEST_RETRIES map[string]int var NUM_TEST_RETRIES map[string]int
var UNUSED_GOLDENS []string = []string{"testCustomColumns-query-isAction=false", "testCustomColumns-tquery-bash", var UNUSED_GOLDENS []string = []string{
"testCustomColumns-tquery-zsh"} "testCustomColumns-query-isAction=false", "testCustomColumns-tquery-bash",
"testCustomColumns-tquery-zsh",
}
func main() { func main() {
if os.Args[1] == "export" { if os.Args[1] == "export" {
@ -90,7 +92,6 @@ func checkGoldensUsed() {
} }
} }
fmt.Println("Validated that all goldens in testdata/ were referenced!") fmt.Println("Validated that all goldens in testdata/ were referenced!")
} }
func exportMetrics() { func exportMetrics() {

View File

@ -469,7 +469,7 @@ func (m *Model) FromValues(value, separator string) {
} }
func (m Model) headersView() string { func (m Model) headersView() string {
var s = make([]string, 0, len(m.cols)) s := make([]string, 0, len(m.cols))
for _, col := range m.cols { for _, col := range m.cols {
style := lipgloss.NewStyle().Width(col.Width).MaxWidth(col.Width).Inline(true) style := lipgloss.NewStyle().Width(col.Width).MaxWidth(col.Width).Inline(true)
renderedCell := style.Render(runewidth.Truncate(col.Title, col.Width, "…")) renderedCell := style.Render(runewidth.Truncate(col.Title, col.Width, "…"))
@ -491,7 +491,7 @@ func (m *Model) columnNeedsScrolling(columnIdxToCheck int) bool {
func (m *Model) renderRow(rowID int) string { func (m *Model) renderRow(rowID int) string {
isRowSelected := rowID == m.cursor isRowSelected := rowID == m.cursor
var s = make([]string, 0, len(m.cols)) s := make([]string, 0, len(m.cols))
for i, value := range m.rows[rowID] { for i, value := range m.rows[rowID] {
style := lipgloss.NewStyle().Width(m.cols[i].Width).MaxWidth(m.cols[i].Width).Inline(true) style := lipgloss.NewStyle().Width(m.cols[i].Width).MaxWidth(m.cols[i].Width).Inline(true)

View File

@ -21,6 +21,7 @@ import (
"github.com/ddworken/hishtory/client/lib" "github.com/ddworken/hishtory/client/lib"
"github.com/ddworken/hishtory/shared" "github.com/ddworken/hishtory/shared"
"github.com/ddworken/hishtory/shared/testutils" "github.com/ddworken/hishtory/shared/testutils"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )

View File

@ -2,6 +2,7 @@ package tui
import ( import (
"context" "context"
_ "embed" // for embedding config.sh
"fmt" "fmt"
"os" "os"
"path/filepath" "path/filepath"
@ -10,14 +11,6 @@ import (
"strings" "strings"
"time" "time"
_ "embed" // for embedding config.sh
"github.com/charmbracelet/bubbles/help"
"github.com/charmbracelet/bubbles/key"
"github.com/charmbracelet/bubbles/spinner"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/ddworken/hishtory/client/ai" "github.com/ddworken/hishtory/client/ai"
"github.com/ddworken/hishtory/client/data" "github.com/ddworken/hishtory/client/data"
"github.com/ddworken/hishtory/client/hctx" "github.com/ddworken/hishtory/client/hctx"
@ -25,23 +18,36 @@ import (
"github.com/ddworken/hishtory/client/table" "github.com/ddworken/hishtory/client/table"
"github.com/ddworken/hishtory/client/tui/keybindings" "github.com/ddworken/hishtory/client/tui/keybindings"
"github.com/ddworken/hishtory/shared" "github.com/ddworken/hishtory/shared"
"github.com/charmbracelet/bubbles/help"
"github.com/charmbracelet/bubbles/key"
"github.com/charmbracelet/bubbles/spinner"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/muesli/termenv" "github.com/muesli/termenv"
"golang.org/x/term" "golang.org/x/term"
) )
const TABLE_HEIGHT = 20 const (
const PADDED_NUM_ENTRIES = TABLE_HEIGHT * 5 TABLE_HEIGHT = 20
PADDED_NUM_ENTRIES = TABLE_HEIGHT * 5
)
var CURRENT_QUERY_FOR_HIGHLIGHTING string = "" var (
var SELECTED_COMMAND string = "" CURRENT_QUERY_FOR_HIGHLIGHTING string = ""
SELECTED_COMMAND string = ""
)
// Globally shared monotonically increasing IDs used to prevent race conditions in handling async queries. // Globally shared monotonically increasing IDs used to prevent race conditions in handling async queries.
// If the user types 'l' and then 's', two queries will be dispatched: One for 'l' and one for 'ls'. These // If the user types 'l' and then 's', two queries will be dispatched: One for 'l' and one for 'ls'. These
// counters are used to ensure that we don't process the query results for 'ls' and then promptly overwrite // counters are used to ensure that we don't process the query results for 'ls' and then promptly overwrite
// them with the results for 'l'. // them with the results for 'l'.
var LAST_DISPATCHED_QUERY_ID = 0 var (
var LAST_DISPATCHED_QUERY_TIMESTAMP time.Time LAST_DISPATCHED_QUERY_ID = 0
var LAST_PROCESSED_QUERY_ID = -1 LAST_DISPATCHED_QUERY_TIMESTAMP time.Time
LAST_PROCESSED_QUERY_ID = -1
)
type SelectStatus int64 type SelectStatus int64
@ -96,11 +102,14 @@ type model struct {
shellName string shellName string
} }
type doneDownloadingMsg struct{} type (
type offlineMsg struct{} doneDownloadingMsg struct{}
type bannerMsg struct { offlineMsg struct{}
banner string bannerMsg struct {
} banner string
}
)
type asyncQueryFinishedMsg struct { type asyncQueryFinishedMsg struct {
// The query ID finished running. Used to ensure that we only process this message if it is the latest query to finish. // The query ID finished running. Used to ensure that we only process this message if it is the latest query to finish.
queryId int queryId int
@ -499,7 +508,7 @@ func getRows(ctx context.Context, columnNames []string, shellName, defaultFilter
} }
var rows []table.Row var rows []table.Row
var filteredData []*data.HistoryEntry var filteredData []*data.HistoryEntry
var seenCommands = make(map[string]bool) seenCommands := make(map[string]bool)
for i := 0; i < numEntries; i++ { for i := 0; i < numEntries; i++ {
if i < len(searchResults) { if i < len(searchResults) {
@ -633,6 +642,7 @@ func max(a, b int) int {
} }
return b return b
} }
func min(a, b int) int { func min(a, b int) int {
if a < b { if a < b {
return a return a

View File

@ -5,15 +5,15 @@ import (
"crypto/subtle" "crypto/subtle"
"embed" "embed"
"fmt" "fmt"
"html/template"
"net" "net"
"net/http" "net/http"
"net/url" "net/url"
"html/template"
"github.com/ddworken/hishtory/client/data" "github.com/ddworken/hishtory/client/data"
"github.com/ddworken/hishtory/client/hctx" "github.com/ddworken/hishtory/client/hctx"
"github.com/ddworken/hishtory/client/lib" "github.com/ddworken/hishtory/client/lib"
"github.com/google/uuid" "github.com/google/uuid"
) )
@ -92,7 +92,6 @@ func webuiHandler(w http.ResponseWriter, r *http.Request) {
func getTemplates() *template.Template { func getTemplates() *template.Template {
return template.Must(template.ParseFS(templateFiles, "templates/*")) return template.Must(template.ParseFS(templateFiles, "templates/*"))
} }
func buildTableRows(ctx context.Context, entries []*data.HistoryEntry) ([][]string, error) { func buildTableRows(ctx context.Context, entries []*data.HistoryEntry) ([][]string, error) {

View File

@ -10,6 +10,7 @@ import (
"strconv" "strconv"
"github.com/ddworken/hishtory/client/hctx" "github.com/ddworken/hishtory/client/hctx"
"golang.org/x/exp/slices" "golang.org/x/exp/slices"
) )

View File

@ -16,6 +16,7 @@ import (
"time" "time"
"github.com/ddworken/hishtory/client/data" "github.com/ddworken/hishtory/client/data"
"github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
@ -154,7 +155,7 @@ setopt SHARE_HISTORY
if strings.Contains(string(dat), zshrcHistConfig) { if strings.Contains(string(dat), zshrcHistConfig) {
return return
} }
f, err := os.OpenFile(path.Join(homedir, ".zshrc"), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) f, err := os.OpenFile(path.Join(homedir, ".zshrc"), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
checkError(err) checkError(err)
defer f.Close() defer f.Close()
_, err = f.WriteString(zshrcHistConfig) _, err = f.WriteString(zshrcHistConfig)
@ -290,7 +291,7 @@ func RunTestServer() func() {
panic(fmt.Sprintf("server experienced an error\n\n\nstderr=\n%s\n\n\nstdout=%s", stderr.String(), stdout.String())) panic(fmt.Sprintf("server experienced an error\n\n\nstderr=\n%s\n\n\nstdout=%s", stderr.String(), stdout.String()))
} }
// Persist test server logs for debugging // Persist test server logs for debugging
f, err := os.OpenFile("/tmp/hishtory-server.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) f, err := os.OpenFile("/tmp/hishtory-server.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
checkError(err) checkError(err)
defer f.Close() defer f.Close()
_, err = f.Write([]byte(stdout.String() + "\n")) _, err = f.Write([]byte(stdout.String() + "\n"))
@ -332,7 +333,7 @@ func IsGithubAction() bool {
} }
func TestLog(t testing.TB, line string) { func TestLog(t testing.TB, line string) {
f, err := os.OpenFile("/tmp/test.log", os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644) f, err := os.OpenFile("/tmp/test.log", os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0o644)
if err != nil { if err != nil {
require.NoError(t, err) require.NoError(t, err)
} }
@ -351,7 +352,7 @@ func persistLog() {
if err != nil { if err != nil {
return return
} }
f, err := os.OpenFile("/tmp/hishtory.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) f, err := os.OpenFile("/tmp/hishtory.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
checkError(err) checkError(err)
defer f.Close() defer f.Close()
_, err = f.Write(log) _, err = f.Write(log)
@ -362,7 +363,7 @@ func persistLog() {
func recordUsingGolden(t testing.TB, goldenName string) { func recordUsingGolden(t testing.TB, goldenName string) {
f, err := os.OpenFile("/tmp/goldens-used.txt", f, err := os.OpenFile("/tmp/goldens-used.txt",
os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
if err != nil { if err != nil {
t.Fatalf("failed to open file to record using golden: %v", err) t.Fatalf("failed to open file to record using golden: %v", err)
} }
@ -389,12 +390,12 @@ func CompareGoldens(t testing.TB, out, goldenName string) {
if err := os.Mkdir("/tmp/test-goldens", os.ModePerm); err != nil && !os.IsExist(err) { if err := os.Mkdir("/tmp/test-goldens", os.ModePerm); err != nil && !os.IsExist(err) {
log.Fatal(err) log.Fatal(err)
} }
require.NoError(t, os.WriteFile(path.Join("/tmp/test-goldens", goldenName), []byte(out), 0644)) require.NoError(t, os.WriteFile(path.Join("/tmp/test-goldens", goldenName), []byte(out), 0o644))
if os.Getenv("HISHTORY_UPDATE_GOLDENS") == "" { if os.Getenv("HISHTORY_UPDATE_GOLDENS") == "" {
_, filename, line, _ := runtime.Caller(1) _, filename, line, _ := runtime.Caller(1)
t.Fatalf("hishtory golden mismatch for %s at %s:%d (-expected +got):\n%s\nactual=\n%s", goldenName, filename, line, diff, out) t.Fatalf("hishtory golden mismatch for %s at %s:%d (-expected +got):\n%s\nactual=\n%s", goldenName, filename, line, diff, out)
} else { } else {
require.NoError(t, os.WriteFile(goldenPath, []byte(out), 0644)) require.NoError(t, os.WriteFile(goldenPath, []byte(out), 0o644))
} }
} }
} }