config.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /* Copyright 2018 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 walk
  13. import (
  14. "flag"
  15. "path"
  16. "github.com/bazelbuild/bazel-gazelle/config"
  17. gzflag "github.com/bazelbuild/bazel-gazelle/flag"
  18. "github.com/bazelbuild/bazel-gazelle/rule"
  19. )
  20. // TODO(#472): store location information to validate each exclude. They
  21. // may be set in one directory and used in another. Excludes work on
  22. // declared generated files, so we can't just stat.
  23. type walkConfig struct {
  24. excludes []string
  25. ignore bool
  26. follow []string
  27. }
  28. const walkName = "_walk"
  29. func getWalkConfig(c *config.Config) *walkConfig {
  30. return c.Exts[walkName].(*walkConfig)
  31. }
  32. func (wc *walkConfig) isExcluded(rel, base string) bool {
  33. if base == ".git" {
  34. return true
  35. }
  36. f := path.Join(rel, base)
  37. for _, x := range wc.excludes {
  38. if f == x {
  39. return true
  40. }
  41. }
  42. return false
  43. }
  44. type Configurer struct{}
  45. func (_ *Configurer) RegisterFlags(fs *flag.FlagSet, cmd string, c *config.Config) {
  46. wc := &walkConfig{}
  47. c.Exts[walkName] = wc
  48. fs.Var(&gzflag.MultiFlag{Values: &wc.excludes}, "exclude", "Path to file or directory that should be ignored (may be repeated)")
  49. }
  50. func (_ *Configurer) CheckFlags(fs *flag.FlagSet, c *config.Config) error { return nil }
  51. func (_ *Configurer) KnownDirectives() []string {
  52. return []string{"exclude", "follow", "ignore"}
  53. }
  54. func (_ *Configurer) Configure(c *config.Config, rel string, f *rule.File) {
  55. wc := getWalkConfig(c)
  56. wcCopy := &walkConfig{}
  57. *wcCopy = *wc
  58. wcCopy.ignore = false
  59. if f != nil {
  60. for _, d := range f.Directives {
  61. switch d.Key {
  62. case "exclude":
  63. wcCopy.excludes = append(wcCopy.excludes, path.Join(rel, d.Value))
  64. case "follow":
  65. wcCopy.follow = append(wcCopy.follow, path.Join(rel, d.Value))
  66. case "ignore":
  67. wcCopy.ignore = true
  68. }
  69. }
  70. }
  71. c.Exts[walkName] = wcCopy
  72. }