Skip to content

Commit

Permalink
xmain: Add AbsPath and HumanPath
Browse files Browse the repository at this point in the history
  • Loading branch information
nhooyr committed Mar 5, 2023
1 parent 9eb7128 commit 3c9bf85
Showing 1 changed file with 21 additions and 2 deletions.
23 changes: 21 additions & 2 deletions xmain/xmain.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
"time"

Expand Down Expand Up @@ -181,8 +182,26 @@ func (ms *State) WritePath(fp string, p []byte) error {
return os.WriteFile(fp, p, 0644)
}

func (ms *State) RelPath(fp string) string {
rel, err := filepath.Rel(ms.PWD, fp)
// AbsPath joins the PWD with fp to give the absolute path to fp.
func (ms *State) AbsPath(fp string) string {
if filepath.IsAbs(fp) {
return fp
}
return filepath.Join(ms.PWD, fp)
}

// HumanPath makes absolute path fp more suitable for human consumption
// by replacing $HOME in fp with ~ and making it relative to the current PWD.
func (ms *State) HumanPath(fp string) string {
if strings.HasPrefix(fp, os.Getenv("HOME")) {
fp = filepath.Join("~", strings.TrimPrefix(fp, os.Getenv("HOME")))
}
pwd := ms.PWD
if strings.HasPrefix(pwd, os.Getenv("HOME")) {
pwd = filepath.Join("~", strings.TrimPrefix(pwd, os.Getenv("HOME")))
}

rel, err := filepath.Rel(pwd, fp)
if err != nil {
return fp
}
Expand Down

0 comments on commit 3c9bf85

Please sign in to comment.