github.com/treeverse/lakefs@v1.24.1-0.20240520134607-95648127bfb0/pkg/permissions/codegen/main.go (about) 1 //go:build generate 2 3 package main 4 5 import ( 6 "fmt" 7 "go/ast" 8 "go/importer" 9 "go/parser" 10 "go/token" 11 "go/types" 12 "log" 13 "os" 14 ) 15 16 func main() { 17 inFile := os.Args[1] 18 outFile := os.Args[2] 19 20 out, err := os.Create(outFile) 21 if err != nil { 22 log.Fatalln(err) 23 } 24 25 constantValues := []string{} 26 ConstantsOf(inFile, func(v string) { 27 constantValues = append(constantValues, v) 28 }) 29 30 fmt.Fprintln(out, `// Code generated by extract_actions. DO NOT EDIT. 31 // 32 package permissions 33 34 var Actions = []string{`) 35 for _, c := range constantValues { 36 fmt.Fprintf(out, "\t%s,\n", c) 37 } 38 fmt.Fprintln(out, "}") 39 } 40 41 func ConstantsOf(file string, value func(string)) { 42 fset := token.NewFileSet() 43 f, err := parser.ParseFile(fset, file, nil, 0) 44 if err != nil { 45 log.Fatalln(err) 46 } 47 48 // Obtain type information. 49 conf := types.Config{Importer: importer.Default()} 50 info := &types.Info{ 51 Defs: make(map[*ast.Ident]types.Object), 52 } 53 _, err = conf.Check("p", fset, []*ast.File{f}, info) 54 if err != nil { 55 log.Fatal(err) 56 } 57 58 for _, d := range f.Decls { 59 genDecl, ok := d.(*ast.GenDecl) 60 if !ok { 61 continue 62 } 63 for _, s := range genDecl.Specs { 64 v, ok := s.(*ast.ValueSpec) 65 if !ok { 66 continue 67 } 68 for _, name := range v.Names { 69 c, ok := info.ObjectOf(name).(*types.Const) 70 if ok { 71 value(c.Val().ExactString()) 72 } 73 } 74 } 75 } 76 }