Skip to content

Commit c05e8c9

Browse files
authored
Extracts tilde-in-home check and tests it (#45)
* Extract user home directory detection to a function * Extracts tilde-in-path substitution and tests it
1 parent 93b7c8f commit c05e8c9

2 files changed

Lines changed: 67 additions & 7 deletions

File tree

main.go

Lines changed: 35 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -52,19 +52,47 @@ func ReadConfigfile(configfile string) *types.Conf {
5252
return &t
5353
}
5454

55+
func GetUserHome() (string, error) {
56+
usr, err := user.Current()
57+
58+
if err != nil {
59+
return "", err
60+
}
61+
62+
return usr.HomeDir, nil
63+
}
64+
65+
func SubstituteHomeForTildeInPath(path string) string {
66+
if !strings.HasPrefix(path, "~") {
67+
return path
68+
} else {
69+
if path == "~" {
70+
userHome, err := GetUserHome()
71+
if err != nil {
72+
log.Fatal().Str("stage", "local ~ substitution").Str("path", path).Msg(err.Error())
73+
} else {
74+
return userHome
75+
}
76+
} else if strings.HasPrefix(path, "~/") {
77+
userHome, err := GetUserHome()
78+
if err != nil {
79+
log.Fatal().Str("stage", "local ~/ substitution").Str("path", path).Msg(err.Error())
80+
} else {
81+
return filepath.Join(userHome, path[2:])
82+
}
83+
}
84+
}
85+
// in any other strange case
86+
return path
87+
}
88+
5589
func Backup(repos []types.Repo, conf *types.Conf) {
5690
checkedpath := false
5791
for _, r := range repos {
5892
log.Info().Str("stage", "backup").Msgf("starting backup for %s", r.Url)
5993
for i, d := range conf.Destination.Local {
6094
if !checkedpath {
61-
usr, _ := user.Current()
62-
dir := usr.HomeDir
63-
if d.Path == "~" {
64-
d.Path = dir
65-
} else if strings.HasPrefix(d.Path, "~/") {
66-
d.Path = filepath.Join(dir, d.Path[2:])
67-
}
95+
d.Path = SubstituteHomeForTildeInPath(d.Path)
6896
path, err := filepath.Abs(d.Path)
6997
if err != nil {
7098
log.Fatal().Str("stage", "locally").Str("path", d.Path).Msg(err.Error())

main_test.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package main
2+
3+
import (
4+
"strings"
5+
"testing"
6+
)
7+
8+
func TestTildeReplacement_NoAction(t *testing.T) {
9+
path := "/boop"
10+
if SubstituteHomeForTildeInPath(path) != path {
11+
t.Error("Altered path when no alteration was expected")
12+
}
13+
}
14+
15+
func TestTildeReplacement_TildeOnly(t *testing.T) {
16+
path := "~"
17+
if SubstituteHomeForTildeInPath(path) == path {
18+
t.Error("Path unaltered when alteration was expected")
19+
}
20+
}
21+
22+
func TestTildeReplacement_TildeDir(t *testing.T) {
23+
path := "~/boop"
24+
actual := SubstituteHomeForTildeInPath(path)
25+
if strings.HasPrefix(actual, "~") {
26+
t.Error("Altered path still contains ~")
27+
}
28+
29+
if !strings.HasSuffix(actual, "boop") {
30+
t.Error("Altered path does not end with directory to be retained")
31+
}
32+
}

0 commit comments

Comments
 (0)