glob/cmd/globdraw/main.go

117 lines
2.3 KiB
Go
Raw Normal View History

2016-01-22 19:16:46 +03:00
package main
import (
2019-02-10 21:25:05 +03:00
"bufio"
2016-01-22 19:16:46 +03:00
"flag"
"fmt"
"os"
2019-02-10 21:25:05 +03:00
"os/exec"
2016-01-22 19:16:46 +03:00
"strings"
2016-02-02 22:03:37 +03:00
"unicode/utf8"
2018-02-16 17:36:02 +03:00
"github.com/gobwas/glob"
"github.com/gobwas/glob/match"
2016-01-22 19:16:46 +03:00
)
func main() {
2019-02-10 21:25:05 +03:00
var (
pattern = flag.String("p", "", "pattern to draw")
sep = flag.String("s", "", "comma separated list of separators characters")
filepath = flag.String("file", "", "path for patterns file")
auto = flag.Bool("auto", false, "autoopen result")
offset = flag.Int("offset", 0, "patterns to skip")
)
2016-01-22 19:16:46 +03:00
flag.Parse()
2019-02-10 21:25:05 +03:00
var patterns []string
if *pattern != "" {
patterns = append(patterns, *pattern)
}
if *filepath != "" {
file, err := os.Open(*filepath)
if err != nil {
fmt.Printf("could not open file: %v\n", err)
os.Exit(1)
}
s := bufio.NewScanner(file)
for s.Scan() {
fmt.Println(*offset)
if *offset > 0 {
*offset--
fmt.Println("skipped")
continue
}
patterns = append(patterns, s.Text())
}
file.Close()
}
if len(patterns) == 0 {
return
2016-01-22 19:16:46 +03:00
}
2016-02-02 22:03:37 +03:00
var separators []rune
2016-02-24 20:23:24 +03:00
if len(*sep) > 0 {
for _, c := range strings.Split(*sep, ",") {
2019-02-10 21:25:05 +03:00
r, w := utf8.DecodeRuneInString(c)
if len(c) > w {
2019-03-12 22:15:41 +03:00
fmt.Printf("only single charactered separators are allowed: %+q\n", c)
2016-02-24 20:23:24 +03:00
os.Exit(1)
}
2019-02-10 21:25:05 +03:00
separators = append(separators, r)
2016-02-02 22:03:37 +03:00
}
}
2019-02-10 21:25:05 +03:00
br := bufio.NewReader(os.Stdin)
for _, p := range patterns {
g, err := glob.Compile(p, separators...)
if err != nil {
fmt.Printf("could not compile pattern %+q: %v\n", p, err)
os.Exit(1)
}
s := match.Graphviz(p, g.(match.Matcher))
if *auto {
fmt.Fprintf(os.Stdout, "pattern: %+q: ", p)
if err := open(s); err != nil {
fmt.Printf("could not open graphviz: %v", err)
os.Exit(1)
}
if !next(br) {
return
}
} else {
fmt.Fprintln(os.Stdout, s)
}
}
}
func open(s string) error {
file, err := os.Create("glob.graphviz.png")
2016-01-22 19:16:46 +03:00
if err != nil {
2019-02-10 21:25:05 +03:00
return err
}
defer file.Close()
cmd := exec.Command("dot", "-Tpng")
cmd.Stdin = strings.NewReader(s)
cmd.Stdout = file
if err := cmd.Run(); err != nil {
return err
}
if err := file.Sync(); err != nil {
return err
2016-01-22 19:16:46 +03:00
}
2019-02-10 21:25:05 +03:00
cmd = exec.Command("open", file.Name())
return cmd.Run()
}
2016-01-22 19:16:46 +03:00
2019-02-10 21:25:05 +03:00
func next(in *bufio.Reader) bool {
fmt.Fprint(os.Stdout, "cancel? [Y/n]: ")
p, err := in.ReadBytes('\n')
if err != nil {
return false
}
if p[0] == 'Y' {
return false
}
return true
2016-01-22 19:16:46 +03:00
}