2024-08-06 02:09:00 -04:00
|
|
|
// Package dirs provides functions to sanitize directory and file names.
|
2024-06-19 18:55:01 -04:00
|
|
|
package dirs
|
|
|
|
|
|
|
|
import (
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2024-08-06 02:09:00 -04:00
|
|
|
const (
|
|
|
|
sep = string(os.PathSeparator)
|
|
|
|
space = " "
|
|
|
|
spacep = "%20"
|
|
|
|
newline = "\n"
|
|
|
|
newlinep = "%0A"
|
|
|
|
)
|
2024-07-15 20:10:38 -04:00
|
|
|
|
2024-07-15 21:46:39 -04:00
|
|
|
var (
|
2024-07-31 03:13:48 -04:00
|
|
|
home = os.Getenv("HOME")
|
|
|
|
pwd, _ = os.Getwd()
|
2024-07-15 21:46:39 -04:00
|
|
|
)
|
|
|
|
|
2024-07-27 19:30:28 -04:00
|
|
|
// UnExpand returns dir after expanding some directory shortcuts
|
2024-06-19 18:55:01 -04:00
|
|
|
//
|
2024-07-30 14:43:54 -04:00
|
|
|
// $HOME -> ~
|
2024-07-27 19:30:28 -04:00
|
|
|
//
|
2024-07-30 14:43:54 -04:00
|
|
|
// $PWD -> .
|
2024-07-27 19:30:28 -04:00
|
|
|
//
|
2024-07-30 14:43:54 -04:00
|
|
|
// workdir -> /
|
2024-07-15 20:10:38 -04:00
|
|
|
func UnExpand(dir, workdir string) (outdir string) {
|
|
|
|
if dir != "" {
|
|
|
|
outdir = cleanDir(dir, pwd)
|
|
|
|
}
|
2024-06-19 19:35:40 -04:00
|
|
|
|
2024-07-15 20:10:38 -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)
|
2024-06-19 18:55:01 -04:00
|
|
|
|
2024-08-06 02:09:00 -04:00
|
|
|
outdir = PercentDecode(outdir)
|
2024-06-28 13:45:44 -04:00
|
|
|
|
2024-06-30 23:01:36 -04:00
|
|
|
if outdir == "" {
|
|
|
|
outdir = "/"
|
|
|
|
}
|
|
|
|
|
2024-06-19 18:55:01 -04:00
|
|
|
return
|
|
|
|
}
|
2024-06-28 13:45:44 -04:00
|
|
|
|
2024-08-06 02:09:00 -04:00
|
|
|
func PercentDecode(input string) (output string) {
|
|
|
|
output = strings.ReplaceAll(input, spacep, space)
|
|
|
|
output = strings.ReplaceAll(output, newlinep, newline)
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
func PercentEncode(input string) (output string) {
|
|
|
|
output = strings.ReplaceAll(input, space, spacep)
|
|
|
|
output = strings.ReplaceAll(output, newline, newlinep)
|
|
|
|
|
|
|
|
return
|
2024-07-28 21:07:07 -04:00
|
|
|
}
|
|
|
|
|
2024-07-15 20:10:38 -04:00
|
|
|
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
|
|
|
|
}
|