github.com/bazelbuild/bazel-gazelle@v0.36.1-0.20240520142334-61b277ba6fed/rule/directives.go (about) 1 /* Copyright 2017 The Bazel Authors. All rights reserved. 2 3 Licensed under the Apache License, Version 2.0 (the "License"); 4 you may not use this file except in compliance with the License. 5 You may obtain a copy of the License at 6 7 http://www.apache.org/licenses/LICENSE-2.0 8 9 Unless required by applicable law or agreed to in writing, software 10 distributed under the License is distributed on an "AS IS" BASIS, 11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 See the License for the specific language governing permissions and 13 limitations under the License. 14 */ 15 16 package rule 17 18 import ( 19 "regexp" 20 21 bzl "github.com/bazelbuild/buildtools/build" 22 ) 23 24 // Directive is a key-value pair extracted from a top-level comment in 25 // a build file. Directives have the following format: 26 // 27 // # gazelle:key value 28 // 29 // Keys may not contain spaces. Values may be empty and may contain spaces, 30 // but surrounding space is trimmed. 31 type Directive struct { 32 Key, Value string 33 } 34 35 // TODO(jayconrod): annotation directives will apply to an individual rule. 36 // They must appear in the block of comments above that rule. 37 38 // ParseDirectives scans f for Gazelle directives. The full list of directives 39 // is returned. Errors are reported for unrecognized directives and directives 40 // out of place (after the first statement). 41 func ParseDirectives(f *bzl.File) []Directive { 42 return parseDirectives(f.Stmt) 43 } 44 45 // ParseDirectivesFromMacro scans a macro body for Gazelle directives. The 46 // full list of directives is returned. Errors are reported for unrecognized 47 // directives and directives out of place (after the first statement). 48 func ParseDirectivesFromMacro(f *bzl.DefStmt) []Directive { 49 return parseDirectives(f.Body) 50 } 51 52 func parseDirectives(stmt []bzl.Expr) []Directive { 53 var directives []Directive 54 parseComment := func(com bzl.Comment) { 55 match := directiveRe.FindStringSubmatch(com.Token) 56 if match == nil { 57 return 58 } 59 key, value := match[1], match[2] 60 directives = append(directives, Directive{key, value}) 61 } 62 63 for _, s := range stmt { 64 coms := s.Comment() 65 for _, com := range coms.Before { 66 parseComment(com) 67 } 68 for _, com := range coms.After { 69 parseComment(com) 70 } 71 } 72 return directives 73 } 74 75 var directiveRe = regexp.MustCompile(`^#\s*gazelle:(\w+)\s*(.*?)\s*$`)