Created
August 25, 2023 22:27
-
-
Save negz/1570d976ff3a408de5c4c57daef62606 to your computer and use it in GitHub Desktop.
Inline Crossplane error constants
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"flag" | |
"fmt" | |
"io/fs" | |
"log" | |
"os" | |
"path/filepath" | |
"regexp" | |
"strings" | |
) | |
var re = regexp.MustCompile(`(err[a-zA-Z]+) += (".+")`) | |
type errConst struct { | |
name []byte | |
value []byte | |
} | |
func main() { | |
dir := flag.String("dir", "", "Dir on which to operate") | |
flag.Parse() | |
log.Printf("Processing %q", *dir) | |
consts := map[string][]errConst{} | |
if err := filepath.WalkDir(*dir, func(path string, d fs.DirEntry, err error) error { | |
if err != nil { | |
return err | |
} | |
if !d.Type().IsRegular() || !strings.HasSuffix(d.Name(), ".go") { | |
return nil | |
} | |
log.Printf("Finding error constants in %q...", d.Name()) | |
b, err := os.ReadFile(path) | |
if err != nil { | |
return err | |
} | |
p := filepath.Dir(path) | |
if _, ok := consts[p]; !ok { | |
consts[p] = make([]errConst, 0) | |
} | |
matches := re.FindAllSubmatch(b, -1) | |
for _, m := range matches { | |
consts[p] = append(consts[p], errConst{name: m[1], value: m[2]}) | |
} | |
return nil | |
}); err != nil { | |
log.Fatal(err) | |
} | |
for p, cs := range consts { | |
if len(cs) == 0 { | |
log.Printf("No error constants found in directory %q", p) | |
continue | |
} | |
for _, c := range cs { | |
log.Printf("Found error constant: %s = %s", c.name, c.value) | |
} | |
ds, err := os.ReadDir(p) | |
if err != nil { | |
log.Fatal(err) | |
} | |
for _, d := range ds { | |
if !d.Type().IsRegular() || !strings.HasSuffix(d.Name(), ".go") { | |
continue | |
} | |
log.Printf("Found candidate file %q", d.Name()) | |
b, err := os.ReadFile(filepath.Join(p, d.Name())) | |
if err != nil { | |
log.Fatal(err) | |
} | |
for _, c := range cs { | |
o := []byte(fmt.Sprintf(", %s)", c.name)) | |
n := []byte(fmt.Sprintf(", %s)", c.value)) | |
b = bytes.ReplaceAll(b, o, n) | |
} | |
if err := os.WriteFile(filepath.Join(p, d.Name()), b, 0600); err != nil { | |
log.Fatal(err) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment