on main help sign in
refactor: simplify `home.Dir()` (#1353)
c658994Andrey Nering
internal/home/home.go+15−20
@@ -6,38 +6,33 @@ import (
6 "os"
6 "os"
7 "path/filepath"
7 "path/filepath"
8 "strings"
8 "strings"
9− "sync"
10)
9)
11
10
12−// Dir returns the users home directory, or if it fails, tries to create a new
11+var homedir, homedirErr = os.UserHomeDir()
13−// temporary directory and use that instead.
12+
14−var Dir = sync.OnceValue(func() string {
13+func init() {
15− home, err := os.UserHomeDir()
16− if err == nil {
17− slog.Debug("user home directory", "home", home)
18− return home
19− }
20− tmp, err := os.MkdirTemp("crush", "")
21− if err != nil {
14+ if homedirErr != nil {
22− slog.Error("could not find the user home directory")
15+ slog.Error("failed to get user home directory", "error", homedirErr)
23− return ""
24 }
16 }
17+}
18+
25− slog.Warn("could not find the user home directory, using a temporary one", "home", tmp)
19+// Dir returns the user home directory.
20+func Dir() string {
26− return tmp
21+ return homedir
27−})
22+}
28
23
29// Short replaces the actual home path from [Dir] with `~`.
24// Short replaces the actual home path from [Dir] with `~`.
30func Short(p string) string {
25func Short(p string) string {
31− if !strings.HasPrefix(p, Dir()) || Dir() == "" {
26+ if homedir == "" || !strings.HasPrefix(p, homedir) {
32 return p
27 return p
33 }
28 }
34− return filepath.Join("~", strings.TrimPrefix(p, Dir()))
29+ return filepath.Join("~", strings.TrimPrefix(p, homedir))
35}
30}
36
31
37// Long replaces the `~` with actual home path from [Dir].
32// Long replaces the `~` with actual home path from [Dir].
38func Long(p string) string {
33func Long(p string) string {
39− if !strings.HasPrefix(p, "~") || Dir() == "" {
34+ if homedir == "" || !strings.HasPrefix(p, "~") {
40 return p
35 return p
41 }
36 }
42− return strings.Replace(p, "~", Dir(), 1)
37+ return strings.Replace(p, "~", homedir, 1)
43}
38}