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 ae08a69
Showing 1 changed file with 26 additions and 2 deletions.
28 changes: 26 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,31 @@ 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 fp == "-" || 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 fp == "-" {
return fp
}
fp = ms.AbsPath(fp)

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 ae08a69

Please sign in to comment.