gt/internal/dirs/dirs.go

61 lines
1 KiB
Go
Raw Normal View History

// Package dirs provides functions sanitize directory names.
package dirs
import (
"os"
"path/filepath"
"strings"
)
const sep = string(os.PathSeparator)
var (
2024-07-31 03:13:48 -04:00
home = os.Getenv("HOME")
pwd, _ = os.Getwd()
)
2024-07-27 19:30:28 -04:00
// UnExpand returns dir after expanding some directory shortcuts
//
// $HOME -> ~
2024-07-27 19:30:28 -04:00
//
// $PWD -> .
2024-07-27 19:30:28 -04:00
//
// workdir -> /
func UnExpand(dir, workdir string) (outdir string) {
if dir != "" {
outdir = cleanDir(dir, pwd)
}
2024-06-19 19:35:40 -04:00
if workdir != "" {
workdir = cleanDir(workdir, pwd)
outdir = strings.Replace(outdir, workdir, "", 1)
} else if home != pwd && pwd != "" {
2024-06-20 01:21:35 -04:00
outdir = strings.Replace(outdir, pwd, ".", 1)
2024-06-19 19:35:40 -04:00
}
outdir = strings.Replace(outdir, home, "~", 1)
outdir = UnEscape(outdir)
if outdir == "" {
outdir = "/"
}
return
}
2024-07-28 21:07:07 -04:00
func UnEscape(input string) string {
return strings.ReplaceAll(input, "%20", " ")
}
func cleanDir(dir, pwd string) (out string) {
if strings.HasPrefix(dir, ".") {
out = filepath.Clean(dir)
} else if !strings.HasPrefix(dir, sep) {
out = filepath.Join(pwd, dir)
} else {
out = dir
}
return
}