github.com/wolfd/bazel-gazelle@v0.14.0/internal/walk/config.go (about)

     1  /* Copyright 2018 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 walk
    17  
    18  import (
    19  	"flag"
    20  	"path"
    21  	"strings"
    22  
    23  	"github.com/bazelbuild/bazel-gazelle/internal/config"
    24  	"github.com/bazelbuild/bazel-gazelle/internal/rule"
    25  )
    26  
    27  type walkConfig struct {
    28  	excludes []string
    29  	ignore   bool
    30  }
    31  
    32  const walkName = "_walk"
    33  
    34  func getWalkConfig(c *config.Config) walkConfig {
    35  	return c.Exts[walkName].(walkConfig)
    36  }
    37  
    38  func (wc *walkConfig) isExcluded(base string) bool {
    39  	for _, x := range wc.excludes {
    40  		if base == x {
    41  			return true
    42  		}
    43  	}
    44  	return false
    45  }
    46  
    47  type walkConfigurer struct{}
    48  
    49  func (_ *walkConfigurer) RegisterFlags(fs *flag.FlagSet, cmd string, c *config.Config) {}
    50  
    51  func (_ *walkConfigurer) CheckFlags(fs *flag.FlagSet, c *config.Config) error { return nil }
    52  
    53  func (_ *walkConfigurer) KnownDirectives() []string {
    54  	return []string{"exclude", "ignore"}
    55  }
    56  
    57  func (_ *walkConfigurer) Configure(c *config.Config, rel string, f *rule.File) {
    58  	var wc walkConfig
    59  	if raw, ok := c.Exts[walkName]; ok {
    60  		wc = raw.(walkConfig)
    61  		wc.ignore = false
    62  		if rel != "" {
    63  			prefix := path.Base(rel) + "/"
    64  			excludes := make([]string, 0, len(wc.excludes))
    65  			for _, x := range wc.excludes {
    66  				if strings.HasPrefix(x, prefix) {
    67  					excludes = append(excludes, x[len(prefix):])
    68  				}
    69  			}
    70  			wc.excludes = excludes
    71  		}
    72  	}
    73  
    74  	if f != nil {
    75  		for _, d := range f.Directives {
    76  			switch d.Key {
    77  			case "exclude":
    78  				wc.excludes = append(wc.excludes, d.Value)
    79  			case "ignore":
    80  				wc.ignore = true
    81  			}
    82  		}
    83  	}
    84  
    85  	c.Exts[walkName] = wc
    86  }