github.com/wolfd/bazel-gazelle@v0.14.0/internal/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  	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  
    52  	for _, s := range f.Stmt {
    53  		coms := s.Comment()
    54  		for _, com := range coms.Before {
    55  			parseComment(com)
    56  		}
    57  		for _, com := range coms.After {
    58  			parseComment(com)
    59  		}
    60  	}
    61  	return directives
    62  }
    63  
    64  var directiveRe = regexp.MustCompile(`^#\s*gazelle:(\w+)\s*(.*?)\s*$`)