github.com/osrg/gobgp/v3@v3.30.0/pkg/packet/bgp/internal/generate.go (about) 1 //go:build ignore 2 // +build ignore 3 4 package main 5 6 import ( 7 "bytes" 8 "fmt" 9 "os" 10 "regexp" 11 ) 12 13 const ( 14 srBehaviourSourceFile = "../../../api/attribute.pb.go" 15 srBehaviourTargetFile = "srbehavior.go" 16 ) 17 18 func main() { 19 if len(os.Args) != 2 { 20 panic("expected single argument: type to generate") 21 } 22 23 switch os.Args[1] { 24 case "SRBehavior": 25 generateSRBehaviour() 26 default: 27 panic("unexpected type: " + os.Args[1]) 28 } 29 } 30 31 func generateSRBehaviour() { 32 content, err := os.ReadFile(srBehaviourSourceFile) 33 if err != nil { 34 doPanic("failed to read file %s: %w", srBehaviourSourceFile, err) 35 } 36 37 re := regexp.MustCompile(`(?ms)type SRv6Behavior int32\s+(const \(.*?\)\n)`) 38 39 match := re.FindSubmatch(content) 40 if match == nil { 41 doPanic("couldn't find SRv6Behavior constants") 42 } 43 44 constants := bytes.ReplaceAll( 45 bytes.ReplaceAll(match[1], []byte("SRv6Behavior_"), nil), 46 []byte("SRv6"), 47 []byte("SR"), 48 ) 49 50 buf := bytes.NewBuffer([]byte("// Generated code; DO NOT EDIT.\n\npackage bgp\n\n")) 51 buf.Write(constants) 52 53 if err := os.WriteFile(srBehaviourTargetFile, buf.Bytes(), 0o664); err != nil { 54 doPanic("failed to write file %s: %w") 55 } 56 } 57 func doPanic(message string, args ...interface{}) { 58 panic(fmt.Errorf(message+"\n", args...)) 59 }