directives.go 2.2 KB

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