From d7eec191b9b48a52fbca9b6a90357da0e36680ba Mon Sep 17 00:00:00 2001 From: Mitchell Riedstra Date: Wed, 28 Dec 2022 18:18:39 -0500 Subject: Add a couple of tiny little go utilities --- go/cmd/chardump/main.go | 41 +++++++++++++++++++++++++++++++++++++ go/cmd/fixpths/main.go | 54 +++++++++++++++++++++++++++++++++++++++++++++++++ go/go.mod | 3 +++ 3 files changed, 98 insertions(+) create mode 100644 go/cmd/chardump/main.go create mode 100644 go/cmd/fixpths/main.go create mode 100644 go/go.mod (limited to 'go') diff --git a/go/cmd/chardump/main.go b/go/cmd/chardump/main.go new file mode 100644 index 0000000..c275205 --- /dev/null +++ b/go/cmd/chardump/main.go @@ -0,0 +1,41 @@ +package main + +import ( + "bytes" + "fmt" + "io" + "log" + "os" + "strconv" +) + +var Logger = log.New(os.Stderr, "", 0) + +func dumpString(w io.Writer, s string) { + n := 0 + for _, char := range s { // I don't care about the byte number, just chars... + // https://go.dev/ref/spec#Rune_literals + fmt.Fprintf(w, + "Number: %-4d Char: %-6s Unicode: %U Hex Bytes: %+v\n", + n, + strconv.QuoteRune(char), + char, + []byte(string(char))) + n++ + } +} + +func main() { + buf := &bytes.Buffer{} + + n, err := io.Copy(buf, os.Stdin) + if err != io.EOF && err != nil { + Logger.Fatalf("Failed to read stdin: %s\n", err) + } + + Logger.Println("------------------------") + Logger.Printf("Read in %d bytes\n", n) + Logger.Println("------------------------") + + dumpString(os.Stdout, buf.String()) +} diff --git a/go/cmd/fixpths/main.go b/go/cmd/fixpths/main.go new file mode 100644 index 0000000..6730276 --- /dev/null +++ b/go/cmd/fixpths/main.go @@ -0,0 +1,54 @@ +package main + +import ( + "flag" + "fmt" + "io/fs" + "log" + "os" + "path/filepath" + "regexp" +) + +func main() { + fl := flag.NewFlagSet("fixpths", flag.ExitOnError) + pth := fl.String("p", "", "Path to scan and fix windows incompatible chars on") + rename := fl.Bool("rename", false, "Whether or not to actually rename the files to work on windows") + fl.Parse(os.Args[1:]) + + if *pth == "" { + fmt.Println("need a path") + os.Exit(2) + } + + invalidChars := regexp.MustCompile(`(<|>|:|\||"|\\|\*|\?)`) + + err := filepath.WalkDir(*pth, func(path string, d fs.DirEntry, err error) error { + if d.IsDir() { + return nil + } + + if invalidChars.MatchString(path) { + if !*rename { + fmt.Printf("%s\n", + invalidChars.ReplaceAllString(path, "\033[1;31m${1}\033[0m")) + } + + if *rename { + npath := invalidChars.ReplaceAllString(path, "_") + err := os.Rename(path, npath) + fmt.Printf("%s->%s\n", path, npath) + if err != nil { + log.Println(err) + } + } + } + + return nil + }) + + if err != nil { + log.Println(err) + } + +} diff --git a/go/go.mod b/go/go.mod new file mode 100644 index 0000000..55a923a --- /dev/null +++ b/go/go.mod @@ -0,0 +1,3 @@ +module riedstra.dev/mitch/dotfiles/go + +go 1.19 -- cgit v1.2.3