Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 15 additions & 20 deletions internal/home/home.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,38 +6,33 @@ import (
"os"
"path/filepath"
"strings"
"sync"
)

// Dir returns the users home directory, or if it fails, tries to create a new
// temporary directory and use that instead.
var Dir = sync.OnceValue(func() string {
home, err := os.UserHomeDir()
if err == nil {
slog.Debug("user home directory", "home", home)
return home
}
tmp, err := os.MkdirTemp("crush", "")
if err != nil {
slog.Error("could not find the user home directory")
return ""
var homedir, homedirErr = os.UserHomeDir()

func init() {
if homedirErr != nil {
slog.Error("failed to get user home directory", "error", homedirErr)
}
slog.Warn("could not find the user home directory, using a temporary one", "home", tmp)
return tmp
})
}

// Dir returns the user home directory.
func Dir() string {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could probably keep the OnceValue though

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. Otherwise, this is a solid one, @andreynering.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@caarlos0 I want to remove OnceValue because it hold a sync.Mutex inside and it locks reads.

If we want to cache it, then I think we can just compute on func init() and hold on a global unexported variable.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Made changes. Take a look again.

return homedir
}

// Short replaces the actual home path from [Dir] with `~`.
func Short(p string) string {
if !strings.HasPrefix(p, Dir()) || Dir() == "" {
if homedir == "" || !strings.HasPrefix(p, homedir) {
return p
}
return filepath.Join("~", strings.TrimPrefix(p, Dir()))
return filepath.Join("~", strings.TrimPrefix(p, homedir))
}

// Long replaces the `~` with actual home path from [Dir].
func Long(p string) string {
if !strings.HasPrefix(p, "~") || Dir() == "" {
if homedir == "" || !strings.HasPrefix(p, "~") {
return p
}
return strings.Replace(p, "~", Dir(), 1)
return strings.Replace(p, "~", homedir, 1)
}
Loading