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"
2023-11-11 12:51:15 +03:00
//"github.com/omnipunk/tk/pathx"
2023-03-30 10:13:49 +03:00
"path/filepath"
2023-11-11 12:51:15 +03:00
"github.com/omnipunk/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())
}
}