// Copyright 2016 bee authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package main import ( "bytes" "go/ast" "os" "path" "strings" "text/template" "unicode" ) type Policy struct { Method string Path string Policies []string } var ( policyList = make(map[string]map[string]*Policy) //controllername -> method -> policy policyPathList = make(map[string]map[string]*Policy) //path -> method -> policy ) func controllerFindPolicies(comments *ast.CommentGroup, controllerName, pkgpath string) { if comments == nil || comments.List == nil { return } for _, c := range comments.List { t := strings.TrimSpace(strings.TrimLeft(c.Text, "//")) if strings.HasPrefix(t, "@policy") { policy := Policy{ Method: "*", } policyFields := strings.FieldsFunc(t[len("@policy"):], func(c rune) bool { return !unicode.IsLetter(c) && !unicode.IsNumber(c) && c != '_' }) for _, val := range policyFields { policy.Policies = append(policy.Policies, val) } policyMethods := policyList[pkgpath+controllerName] if policyMethods == nil { policyMethods = make(map[string]*Policy) policyList[pkgpath+controllerName] = policyMethods } if pm := policyMethods[policy.Method]; pm != nil { for _, curPolicy := range policy.Policies { pm.Policies = append(pm.Policies, curPolicy) } } else { policyMethods[policy.Method] = &policy } } } } func generatePolicies(curpath string) { fn := template.FuncMap{ "join": strings.Join, } tmpl, err := template.New("policy template").Funcs(fn).Parse(policyTpl) if err != nil { panic("Can't parse policy template: " + err.Error()) } var buf bytes.Buffer err = tmpl.Execute(&buf, policyPathList) if err != nil { panic("Can't execute policy template: " + err.Error()) } policyFile, err := os.Create(path.Join(curpath, "policies", "policies_autogen.go")) if err != nil { panic(err) } defer policyFile.Close() _, err = policyFile.Write(buf.Bytes()) if err != nil { panic(err) } } var policyTpl = `// This file was auto-generated by bee tools, do not change it! package policies import "github.com/astaxie/beego" func init() { {{ range $path, $policyList := . }}{{ range $, $policy := $policyList }} beego.Policy("{{$path}}{{$policy.Path}}", "{{$policy.Method}}", {{ join $policy.Policies ", " }}) {{ end }}{{ end }} } `