2023-02-16 14:57:39 +03:00
|
|
|
package paths
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
2023-03-08 22:26:23 +03:00
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"log"
|
2023-02-16 14:57:39 +03:00
|
|
|
"os"
|
2023-02-17 16:07:42 +03:00
|
|
|
"path"
|
2023-03-10 16:13:55 +03:00
|
|
|
"strings"
|
2023-03-08 22:26:23 +03:00
|
|
|
|
2024-05-15 21:07:35 +03:00
|
|
|
//"surdeus.su/core/tk/pathx"
|
2023-03-30 10:13:49 +03:00
|
|
|
"path/filepath"
|
2024-05-15 21:07:35 +03:00
|
|
|
"surdeus.su/core/cli/mtool"
|
2023-02-16 14:57:39 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
2023-03-08 22:26:23 +03:00
|
|
|
part string
|
|
|
|
handlers = map[string]func(string) string{
|
2023-06-28 14:20:42 +03:00
|
|
|
"b": path.Base,
|
|
|
|
"e": path.Ext,
|
|
|
|
"d": path.Dir,
|
|
|
|
"a": func(v string) string { return v },
|
2023-02-17 16:07:42 +03:00
|
|
|
}
|
2023-03-08 22:26:23 +03:00
|
|
|
handler func(string) string
|
|
|
|
r bool
|
2023-03-10 16:13:55 +03:00
|
|
|
fromReal bool
|
|
|
|
ec bool
|
2023-02-17 16:07:42 +03:00
|
|
|
noPartErr = errors.New("no such part")
|
2023-02-16 14:57:39 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
func handlePath(p string) {
|
2023-03-10 16:13:55 +03:00
|
|
|
if fromReal {
|
2023-03-30 10:13:49 +03:00
|
|
|
p = filepath.ToSlash(p)
|
2023-03-10 16:13:55 +03:00
|
|
|
}
|
2023-02-17 16:07:42 +03:00
|
|
|
if handler != nil {
|
|
|
|
p = handler(p)
|
|
|
|
}
|
|
|
|
|
2023-03-10 16:13:55 +03:00
|
|
|
var toPrint string
|
2023-02-17 16:07:42 +03:00
|
|
|
if r {
|
2023-03-30 10:13:49 +03:00
|
|
|
toPrint = filepath.FromSlash(p)
|
2023-02-17 16:07:42 +03:00
|
|
|
} else {
|
2023-03-10 16:13:55 +03:00
|
|
|
toPrint = p
|
|
|
|
}
|
|
|
|
|
|
|
|
if ec {
|
|
|
|
toPrint = strings.ReplaceAll(toPrint, "\\", "\\\\")
|
2023-02-17 16:07:42 +03:00
|
|
|
}
|
2023-03-10 16:13:55 +03:00
|
|
|
|
|
|
|
fmt.Println(toPrint)
|
2023-02-16 14:57:39 +03:00
|
|
|
}
|
|
|
|
|
2023-03-24 19:47:31 +03:00
|
|
|
func Run(flags *mtool.Flags) {
|
2023-02-17 16:07:42 +03:00
|
|
|
flags.StringVar(&part, "p", "all", "part of path you want to print")
|
|
|
|
flags.BoolVar(&r, "r", false, "print real OS dependent paths")
|
2023-03-10 16:13:55 +03:00
|
|
|
flags.BoolVar(&fromReal, "fr", false, "take input paths as real ones")
|
|
|
|
flags.BoolVar(&ec, "ec", false, "escape characters (mostly for '\\' char in Git bash")
|
2023-02-17 16:07:42 +03:00
|
|
|
|
2023-06-28 14:20:42 +03:00
|
|
|
args := flags.Parse()
|
2023-03-24 19:47:31 +03:00
|
|
|
|
2023-02-17 16:07:42 +03:00
|
|
|
lhandler, ok := handlers[part]
|
|
|
|
if !ok {
|
|
|
|
log.Fatal(noPartErr)
|
|
|
|
}
|
|
|
|
handler = lhandler
|
2023-02-16 14:57:39 +03:00
|
|
|
|
|
|
|
for _, p := range args {
|
|
|
|
handlePath(p)
|
|
|
|
}
|
|
|
|
|
|
|
|
rd := bufio.NewScanner(os.Stdin)
|
|
|
|
for rd.Scan() {
|
|
|
|
handlePath(rd.Text())
|
|
|
|
}
|
|
|
|
}
|