Skip to content

Commit c2516c4

Browse files
committed
Add tilde expansion to file locators
Signed-off-by: Jan Dubois <[email protected]>
1 parent f3afdb6 commit c2516c4

File tree

3 files changed

+23
-4
lines changed

3 files changed

+23
-4
lines changed

pkg/limatmpl/abs.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ import (
1111
"path/filepath"
1212
"runtime"
1313
"strings"
14+
15+
"github.com/lima-vm/lima/v2/pkg/localpathutil"
1416
)
1517

1618
// UseAbsLocators will replace all relative template locators with absolute ones, so this template
@@ -105,6 +107,13 @@ func absPath(locator, basePath string) (string, error) {
105107
if err == nil && len(u.Scheme) > 1 {
106108
return locator, nil
107109
}
110+
// Don't expand relative path to absolute unless we know it needs tilde expansion.
111+
if locator == "~" || strings.HasPrefix(locator, "~/") {
112+
locator, err = localpathutil.Expand(locator)
113+
if err != nil {
114+
return "", err
115+
}
116+
}
108117
// Check for rooted locator; filepath.IsAbs() returns false on Windows when the volume name is missing
109118
volumeLen := len(filepath.VolumeName(locator))
110119
if locator[volumeLen] != '/' && locator[volumeLen] != filepath.Separator {

pkg/limatmpl/abs_test.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
package limatmpl
55

66
import (
7+
"os"
78
"path/filepath"
89
"runtime"
910
"strings"
@@ -205,6 +206,15 @@ func TestAbsPath(t *testing.T) {
205206
assert.Equal(t, actual, filepath.Clean(volume+"/foo"))
206207
})
207208

209+
t.Run("If the locator starts with ~/, then it will be expanded to an absolute path", func(t *testing.T) {
210+
actual, err := absPath("~/foo", volume+"/root")
211+
assert.NilError(t, err)
212+
homeDir, err := os.UserHomeDir()
213+
assert.NilError(t, err)
214+
// homeDir already includes the volume
215+
assert.Equal(t, actual, filepath.Join(homeDir, "foo"))
216+
})
217+
208218
t.Run("", func(t *testing.T) {
209219
actual, err := absPath("template://foo", volume+"/root")
210220
assert.NilError(t, err)

pkg/localpathutil/localpathutil.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,13 @@ func Expand(orig string) (string, error) {
2020
if s == "" {
2121
return "", errors.New("empty path")
2222
}
23-
homeDir, err := os.UserHomeDir()
24-
if err != nil {
25-
return "", err
26-
}
2723

2824
if strings.HasPrefix(s, "~") {
2925
if s == "~" || strings.HasPrefix(s, "~/") {
26+
homeDir, err := os.UserHomeDir()
27+
if err != nil {
28+
return "", err
29+
}
3030
s = strings.Replace(s, "~", homeDir, 1)
3131
} else {
3232
// Paths like "~foo/bar" are unsupported.

0 commit comments

Comments
 (0)