From d0089e641e4721acf02de3c82d2198cb8b04d243 Mon Sep 17 00:00:00 2001 From: Cory LaNou Date: Fri, 13 Sep 2024 15:11:10 -0500 Subject: [PATCH] replace tildas with users home directory when executing commands --- cmd.go | 12 +++++++++++- cmd_test.go | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++ home.go | 23 +++++++++++++++++++++++ 3 files changed, 87 insertions(+), 1 deletion(-) create mode 100644 home.go diff --git a/cmd.go b/cmd.go index 05d56ce..30d3143 100644 --- a/cmd.go +++ b/cmd.go @@ -104,7 +104,17 @@ func (c *Cmd) Execute(ctx context.Context, doc *Document) error { cmd.Dir = dir } - res, err := cmd.Run(ctx, c.Args...) + // Check the args for the ~ character and replace it with the home directory + // Make a copy of those args as we only want to change them when we pass it to the clam.Cmd + args := make([]string, len(c.Args)) + copy(args, c.Args) + for i, arg := range args { + if strings.HasPrefix(arg, "~") { + args[i] = filepath.Join(homeDirectory(), arg[1:]) + } + } + + res, err := cmd.Run(ctx, args...) if err != nil { switch c.ExpectedExit { case -1: diff --git a/cmd_test.go b/cmd_test.go index b078dd3..650a25f 100644 --- a/cmd_test.go +++ b/cmd_test.go @@ -3,6 +3,8 @@ package hype import ( "context" "errors" + "os" + "path/filepath" "strings" "testing" "time" @@ -186,3 +188,54 @@ func Test_Cmd_MarshalJSON(t *testing.T) { testJSON(t, "cmd", c) } +func Test_Cmd_HomeDirectory(t *testing.T) { + t.Parallel() + r := require.New(t) + + homeDir, err := os.UserHomeDir() + r.NoError(err) + + // Create a directory in the user's home directory with a random temporary name + dir := filepath.Join(homeDir, "tmp_test_dir") + t.Log("created dir:", dir) + err = os.MkdirAll(dir, 0755) + r.NoError(err) + t.Cleanup(func() { + os.RemoveAll(dir) + }) + + // Add three files to the directory: a.txt, b.txt, and c.txt + files := []string{"a.txt", "b.txt", "c.txt"} + for _, file := range files { + filePath := filepath.Join(dir, file) + _, err := os.Create(filePath) + r.NoError(err) + } + + c := &Cmd{ + Element: NewEl("cmd", nil), + Args: []string{"ls", "~/tmp_test_dir"}, + } + r.NoError(c.Set("exec", "ls ~/tmp_test_dir")) + r.NoError(c.Set("hide-cmd", "")) + + ctx := context.Background() + doc := &Document{ + Parser: NewParser(nil), + } + + doc.Nodes = append(doc.Nodes, c) + err = doc.Execute(ctx) + r.NoError(err) + + r.NotNil(c.Result()) + + act := c.String() + act = strings.TrimSpace(act) + + exp := `
a.txt
+b.txt
+c.txt
` + + r.Equal(exp, act) +} diff --git a/home.go b/home.go new file mode 100644 index 0000000..d5afbee --- /dev/null +++ b/home.go @@ -0,0 +1,23 @@ +package hype + +import ( + "log" + "os" +) + +// homeDirectory retursn the home directory of the current user +// it only runs once +var homeDir string + +func homeDirectory() string { + if homeDir != "" { + return homeDir + } + + hd, err := os.UserHomeDir() + if err != nil { + log.Fatal(err) + } + homeDir = hd + return homeDir +}