home.go

 1package home
 2
 3import (
 4	"log/slog"
 5	"os"
 6	"path/filepath"
 7	"strings"
 8	"sync"
 9)
10
11// Dir returns the users home directory, or if it fails, tries to create a new
12// temporary directory and use that instead.
13var Dir = sync.OnceValue(func() string {
14	home, err := os.UserHomeDir()
15	if err == nil {
16		slog.Debug("user home directory", "home", home)
17		return home
18	}
19	tmp, err := os.MkdirTemp("crush", "")
20	if err != nil {
21		slog.Error("could not find the user home directory")
22		return ""
23	}
24	slog.Warn("could not find the user home directory, using a temporary one", "home", tmp)
25	return tmp
26})
27
28// Short replaces the actual home path from [Dir] with `~`.
29func Short(p string) string {
30	if !strings.HasPrefix(p, Dir()) || Dir() == "" {
31		return p
32	}
33	return filepath.Join("~", strings.TrimPrefix(p, Dir()))
34}
35
36// Long replaces the `~` with actual home path from [Dir].
37func Long(p string) string {
38	if !strings.HasPrefix(p, "~") || Dir() == "" {
39		return p
40	}
41	return strings.Replace(p, "~", Dir(), 1)
42}