Skip to content

Commit fcb8f1c

Browse files
committed
Expand ~ in configuration
Fixes #60
1 parent 73abe27 commit fcb8f1c

File tree

2 files changed

+46
-1
lines changed

2 files changed

+46
-1
lines changed

config.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66

77
"github.com/BurntSushi/toml"
88
"github.com/jessevdk/go-flags"
9+
"github.com/zyedidia/eget/home"
910
)
1011

1112
type ConfigGlobal struct {
@@ -150,7 +151,7 @@ func InitializeConfig() (*Config, error) {
150151
}
151152

152153
if !config.Meta.MetaData.IsDefined(name, "target") {
153-
repo.Target = config.Global.Target
154+
repo.Target, err = home.Expand(config.Global.Target)
154155
}
155156

156157
if !config.Meta.MetaData.IsDefined(name, "upgrade_only") {

home/home.go

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package home
2+
3+
import (
4+
"fmt"
5+
"os/user"
6+
"path/filepath"
7+
"strings"
8+
)
9+
10+
func Home() (string, error) {
11+
userData, err := user.Current()
12+
if err != nil {
13+
return "", fmt.Errorf("find homedir: %w", err)
14+
}
15+
return userData.HomeDir, err
16+
}
17+
18+
// Expand takes a path as input and replaces ~ at the start of the path with the user's
19+
// home directory. Does nothing if the path does not start with '~'.
20+
func Expand(path string) (string, error) {
21+
if !strings.HasPrefix(path, "~") {
22+
return path, nil
23+
}
24+
25+
var userData *user.User
26+
var err error
27+
28+
homeString := strings.Split(filepath.ToSlash(path), "/")[0]
29+
if homeString == "~" {
30+
userData, err = user.Current()
31+
if err != nil {
32+
return "", fmt.Errorf("expand tilde: %w", err)
33+
}
34+
} else {
35+
userData, err = user.Lookup(homeString[1:])
36+
if err != nil {
37+
return "", fmt.Errorf("expand tilde: %w", err)
38+
}
39+
}
40+
41+
home := userData.HomeDir
42+
43+
return strings.Replace(path, homeString, home, 1), nil
44+
}

0 commit comments

Comments
 (0)