Skip to content

Commit

Permalink
refactor: adjust osx
Browse files Browse the repository at this point in the history
Signed-off-by: thxCode <[email protected]>
  • Loading branch information
thxCode committed Aug 5, 2024
1 parent 49e15ae commit 3d12f93
Showing 1 changed file with 22 additions and 29 deletions.
51 changes: 22 additions & 29 deletions util/osx/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,33 @@ import (
"strings"
)

// Open is similar to os.Open but supports ~ as the home directory.
func Open(path string) (*os.File, error) {
p := filepath.Clean(path)
if strings.HasPrefix(p, "~"+string(filepath.Separator)) {
// InlineTilde replaces the leading ~ with the home directory.
func InlineTilde(path string) string {
if path == "" {
return path
}
if strings.HasPrefix(path, "~"+string(filepath.Separator)) {
hd, err := os.UserHomeDir()
if err != nil {
return nil, err
if err == nil {
path = filepath.Join(hd, path[2:])
}
p = filepath.Join(hd, p[2:])
}
return path
}

// Open is similar to os.Open but supports ~ as the home directory.
func Open(path string) (*os.File, error) {
p := filepath.Clean(path)
p = InlineTilde(p)
return os.Open(p)
}

// Exists checks if the given path exists.
func Exists(path string, checks ...func(os.FileInfo) bool) bool {
stat, err := os.Lstat(path)
p := filepath.Clean(path)
p = InlineTilde(p)

stat, err := os.Lstat(p)
if err != nil {
return false
}
Expand Down Expand Up @@ -87,13 +98,7 @@ func Close(c io.Closer) {
// and also supports the parent directory creation.
func WriteFile(name string, data []byte, perm os.FileMode) error {
p := filepath.Clean(name)
if strings.HasPrefix(p, "~"+string(filepath.Separator)) {
hd, err := os.UserHomeDir()
if err != nil {
return err
}
p = filepath.Join(hd, p[2:])
}
p = InlineTilde(p)

if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
return err
Expand All @@ -106,13 +111,7 @@ func WriteFile(name string, data []byte, perm os.FileMode) error {
// and also supports the parent directory creation.
func CreateFile(name string, perm os.FileMode) (*os.File, error) {
p := filepath.Clean(name)
if strings.HasPrefix(p, "~"+string(filepath.Separator)) {
hd, err := os.UserHomeDir()
if err != nil {
return nil, err
}
p = filepath.Join(hd, p[2:])
}
p = InlineTilde(p)

if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
return nil, err
Expand All @@ -125,13 +124,7 @@ func CreateFile(name string, perm os.FileMode) (*os.File, error) {
// and also supports the parent directory creation.
func OpenFile(name string, flag int, perm os.FileMode) (*os.File, error) {
p := filepath.Clean(name)
if strings.HasPrefix(p, "~"+string(filepath.Separator)) {
hd, err := os.UserHomeDir()
if err != nil {
return nil, err
}
p = filepath.Join(hd, p[2:])
}
p = InlineTilde(p)

if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
return nil, err
Expand Down

0 comments on commit 3d12f93

Please sign in to comment.