directives.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. var directives []Directive
  34. parseComment := func(com bzl.Comment) {
  35. match := directiveRe.FindStringSubmatch(com.Token)
  36. if match == nil {
  37. return
  38. }
  39. key, value := match[1], match[2]
  40. directives = append(directives, Directive{key, value})
  41. }
  42. for _, s := range f.Stmt {
  43. coms := s.Comment()
  44. for _, com := range coms.Before {
  45. parseComment(com)
  46. }
  47. for _, com := range coms.After {
  48. parseComment(com)
  49. }
  50. }
  51. return directives
  52. }
  53. var directiveRe = regexp.MustCompile(`^#\s*gazelle:(\w+)\s*(.*?)\s*$`)