From 99546577c6094ddc9e407065ccaab06810537917 Mon Sep 17 00:00:00 2001 From: Martin Polden Date: Fri, 30 Jul 2021 12:42:51 +0200 Subject: config: Expand user in PostCommand path --- queue/config.go | 32 +++++++++++++++++++++++--------- queue/config_test.go | 25 +++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 9 deletions(-) diff --git a/queue/config.go b/queue/config.go index f8b4469..f774438 100644 --- a/queue/config.go +++ b/queue/config.go @@ -99,15 +99,32 @@ func parseTemplate(tmpl string) (*template.Template, error) { return t, nil } +func expandUser(path string) string { + tilde := strings.Index(path, "~") + end := strings.IndexRune(path, os.PathSeparator) + if tilde != 0 { + return path + } + if end == -1 { + end = len(path) + } + home := os.Getenv("HOME") + if end > 1 { + home = filepath.Join(filepath.Dir(home), path[1:end]) + } + return filepath.Join(home, path[end:]) +} + func command(cmd string) (*exec.Cmd, error) { if cmd == "" { return nil, nil } argv := strings.Split(cmd, " ") - if _, err := exec.LookPath(argv[0]); err != nil { + program := expandUser(argv[0]) + if _, err := exec.LookPath(program); err != nil { return nil, err } - return exec.Command(argv[0], argv[1:]...), nil + return exec.Command(program, argv[1:]...), nil } func (c *Config) load() error { @@ -225,16 +242,13 @@ func readConfig(r io.Reader) (Config, error) { return cfg, nil } -func ReadConfig(name string) (Config, error) { - if name == "~/.lftpqrc" { - home := os.Getenv("HOME") - name = filepath.Join(home, ".lftpqrc") - } +func ReadConfig(path string) (Config, error) { + path = expandUser(path) var r io.Reader - if name == "-" { + if path == "-" { r = bufio.NewReader(os.Stdin) } else { - f, err := os.Open(name) + f, err := os.Open(path) if err != nil { return Config{}, err } diff --git a/queue/config_test.go b/queue/config_test.go index 1592bb1..7cf57a2 100644 --- a/queue/config_test.go +++ b/queue/config_test.go @@ -1,6 +1,7 @@ package queue import ( + "os" "reflect" "strings" "testing" @@ -173,3 +174,27 @@ func TestSetLocalDir(t *testing.T) { } } } + +func TestExpandUser(t *testing.T) { + home := "/home/foo" + os.Setenv("HOME", home) + var tests = []struct { + in string + out string + }{ + {"", ""}, + {"/d", "/d"}, + {"~", home}, + {"~/", home}, + {"~bar", "/home/bar"}, + {"~bar/baz", "/home/bar/baz"}, + {"~/bar", home + "/bar"}, + {"/foo/~/bar", "/foo/~/bar"}, + } + for i, tt := range tests { + out := expandUser(tt.in) + if out != tt.out { + t.Errorf("#%d: expandUser(%q) = %q, want %q", i, tt.in, out, tt.out) + } + } +} -- cgit v1.2.3