bb/tool/paths/main.go

77 lines
1.3 KiB
Go
Raw Normal View History

package paths
import (
"bufio"
"errors"
"fmt"
"log"
"os"
2023-02-17 16:07:42 +03:00
"path"
"strings"
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"
)
var (
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
}
handler func(string) string
r bool
fromReal bool
ec bool
2023-02-17 16:07:42 +03:00
noPartErr = errors.New("no such part")
)
func handlePath(p string) {
if fromReal {
2023-03-30 10:13:49 +03:00
p = filepath.ToSlash(p)
}
2023-02-17 16:07:42 +03:00
if handler != nil {
p = handler(p)
}
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 {
toPrint = p
}
if ec {
toPrint = strings.ReplaceAll(toPrint, "\\", "\\\\")
2023-02-17 16:07:42 +03:00
}
fmt.Println(toPrint)
}
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")
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
for _, p := range args {
handlePath(p)
}
rd := bufio.NewScanner(os.Stdin)
for rd.Scan() {
handlePath(rd.Text())
}
}