Add homedir to context

This commit is contained in:
David Dworken 2022-09-21 20:19:11 -07:00
parent 569e2f3e61
commit 8002c5e942
2 changed files with 17 additions and 12 deletions

View File

@ -108,6 +108,11 @@ func MakeContext() *context.Context {
panic(fmt.Errorf("failed to open local DB: %v", err))
}
ctx = context.WithValue(ctx, hishtoryContextKey("db"), db)
homedir, err := os.UserHomeDir()
if err != nil {
panic(fmt.Errorf("failed to get homedir: %v", err))
}
ctx = context.WithValue(ctx, hishtoryContextKey("homedir"), homedir)
return &ctx
}
@ -127,6 +132,14 @@ func GetDb(ctx *context.Context) *gorm.DB {
panic(fmt.Errorf("failed to find db in ctx"))
}
func GetHome(ctx *context.Context) string {
v := (*ctx).Value(hishtoryContextKey("homedir"))
if v != nil {
return v.(string)
}
panic(fmt.Errorf("failed to find homedir in ctx"))
}
type ClientConfig struct {
// The user secret that is used to derive encryption keys for syncing history entries
UserSecret string `json:"user_secret"`
@ -200,5 +213,3 @@ func InitConfig() error {
}
return err
}
// TODO: make homedir part of the context

View File

@ -54,15 +54,12 @@ var Version string = "Unknown"
// 256KB ought to be enough for any reasonable cmd
var maxSupportedLineLengthForImport = 256_000
func getCwd() (string, string, error) {
func getCwd(ctx *context.Context) (string, string, error) {
cwd, err := os.Getwd()
if err != nil {
return "", "", fmt.Errorf("failed to get cwd for last command: %v", err)
}
homedir, err := os.UserHomeDir()
if err != nil {
return "", "", fmt.Errorf("failed to get user's home directory: %v", err)
}
homedir := hctx.GetHome(ctx)
if cwd == homedir {
return "~/", homedir, nil
}
@ -96,7 +93,7 @@ func BuildHistoryEntry(ctx *context.Context, args []string) (*data.HistoryEntry,
entry.LocalUsername = user.Username
// cwd and homedir
cwd, homedir, err := getCwd()
cwd, homedir, err := getCwd(ctx)
if err != nil {
return nil, fmt.Errorf("failed to build history entry: %v", err)
}
@ -382,10 +379,7 @@ func ImportHistory(ctx *context.Context) (int, error) {
// Don't run an import if we already have run one. This avoids importing the same entry multiple times.
return 0, nil
}
homedir, err := os.UserHomeDir()
if err != nil {
return 0, fmt.Errorf("failed to get user's home directory: %v", err)
}
homedir := hctx.GetHome(ctx)
historyEntries, err := parseBashHistory(homedir)
if err != nil {
return 0, fmt.Errorf("failed to parse bash history: %v", err)