config.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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 config provides extensible configuration for Gazelle libraries.
  13. //
  14. // Packages may define Configurers which add support for new command-line
  15. // options and directive comments in build files. Note that the
  16. // language.Language interface embeds Configurer, so each language extension
  17. // has the opportunity
  18. //
  19. // When Gazelle walks the directory trees in a repository, it calls the
  20. // Configure method of each Configurer to produce a Config object.
  21. // Config objects are passed as arguments to most functions in Gazelle, so
  22. // this mechanism may be used to control many aspects of Gazelle's behavior.
  23. package config
  24. import (
  25. "flag"
  26. "fmt"
  27. "log"
  28. "path/filepath"
  29. "strings"
  30. "github.com/bazelbuild/bazel-gazelle/internal/wspace"
  31. "github.com/bazelbuild/bazel-gazelle/rule"
  32. )
  33. // Config holds information about how Gazelle should run. This is based on
  34. // command line arguments, directives, other hints in build files.
  35. //
  36. // A Config applies to a single directory. A Config is created for the
  37. // repository root directory, then copied and modified for each subdirectory.
  38. //
  39. // Config itself contains only general information. Most configuration
  40. // information is language-specific and is stored in Exts. This information
  41. // is modified by extensions that implement Configurer.
  42. type Config struct {
  43. // RepoRoot is the absolute, canonical path to the root directory of the
  44. // repository with all symlinks resolved.
  45. RepoRoot string
  46. // RepoName is the name of the repository.
  47. RepoName string
  48. // ReadBuildFilesDir is the absolute path to a directory where
  49. // build files should be read from instead of RepoRoot.
  50. ReadBuildFilesDir string
  51. // WriteBuildFilesDir is the absolute path to a directory where
  52. // build files should be written to instead of RepoRoot.
  53. WriteBuildFilesDir string
  54. // ValidBuildFileNames is a list of base names that are considered valid
  55. // build files. Some repositories may have files named "BUILD" that are not
  56. // used by Bazel and should be ignored. Must contain at least one string.
  57. ValidBuildFileNames []string
  58. // ShouldFix determines whether Gazelle attempts to remove and replace
  59. // usage of deprecated rules.
  60. ShouldFix bool
  61. // IndexLibraries determines whether Gazelle should build an index of
  62. // libraries in the workspace for dependency resolution
  63. IndexLibraries bool
  64. // KindMap maps from a kind name to its replacement. It provides a way for
  65. // users to customize the kind of rules created by Gazelle, via
  66. // # gazelle:map_kind.
  67. KindMap map[string]MappedKind
  68. // Repos is a list of repository rules declared in the main WORKSPACE file
  69. // or in macros called by the main WORKSPACE file. This may affect rule
  70. // generation and dependency resolution.
  71. Repos []*rule.Rule
  72. // Exts is a set of configurable extensions. Generally, each language
  73. // has its own set of extensions, but other modules may provide their own
  74. // extensions as well. Values in here may be populated by command line
  75. // arguments, directives in build files, or other mechanisms.
  76. Exts map[string]interface{}
  77. }
  78. // MappedKind describes a replacement to use for a built-in kind.
  79. type MappedKind struct {
  80. FromKind, KindName, KindLoad string
  81. }
  82. func New() *Config {
  83. return &Config{
  84. ValidBuildFileNames: DefaultValidBuildFileNames,
  85. Exts: make(map[string]interface{}),
  86. }
  87. }
  88. // Clone creates a copy of the configuration for use in a subdirectory.
  89. // Note that the Exts map is copied, but its contents are not.
  90. // Configurer.Configure should do this, if needed.
  91. func (c *Config) Clone() *Config {
  92. cc := *c
  93. cc.Exts = make(map[string]interface{})
  94. for k, v := range c.Exts {
  95. cc.Exts[k] = v
  96. }
  97. cc.KindMap = make(map[string]MappedKind)
  98. for k, v := range c.KindMap {
  99. cc.KindMap[k] = v
  100. }
  101. return &cc
  102. }
  103. var DefaultValidBuildFileNames = []string{"BUILD.bazel", "BUILD"}
  104. // IsValidBuildFileName returns true if a file with the given base name
  105. // should be treated as a build file.
  106. func (c *Config) IsValidBuildFileName(name string) bool {
  107. for _, n := range c.ValidBuildFileNames {
  108. if name == n {
  109. return true
  110. }
  111. }
  112. return false
  113. }
  114. // DefaultBuildFileName returns the base name used to create new build files.
  115. func (c *Config) DefaultBuildFileName() string {
  116. return c.ValidBuildFileNames[0]
  117. }
  118. // Configurer is the interface for language or library-specific configuration
  119. // extensions. Most (ideally all) modifications to Config should happen
  120. // via this interface.
  121. type Configurer interface {
  122. // RegisterFlags registers command-line flags used by the extension. This
  123. // method is called once with the root configuration when Gazelle
  124. // starts. RegisterFlags may set an initial values in Config.Exts. When flags
  125. // are set, they should modify these values.
  126. RegisterFlags(fs *flag.FlagSet, cmd string, c *Config)
  127. // CheckFlags validates the configuration after command line flags are parsed.
  128. // This is called once with the root configuration when Gazelle starts.
  129. // CheckFlags may set default values in flags or make implied changes.
  130. CheckFlags(fs *flag.FlagSet, c *Config) error
  131. // KnownDirectives returns a list of directive keys that this Configurer can
  132. // interpret. Gazelle prints errors for directives that are not recoginized by
  133. // any Configurer.
  134. KnownDirectives() []string
  135. // Configure modifies the configuration using directives and other information
  136. // extracted from a build file. Configure is called in each directory.
  137. //
  138. // c is the configuration for the current directory. It starts out as a copy
  139. // of the configuration for the parent directory.
  140. //
  141. // rel is the slash-separated relative path from the repository root to
  142. // the current directory. It is "" for the root directory itself.
  143. //
  144. // f is the build file for the current directory or nil if there is no
  145. // existing build file.
  146. Configure(c *Config, rel string, f *rule.File)
  147. }
  148. // CommonConfigurer handles language-agnostic command-line flags and directives,
  149. // i.e., those that apply to Config itself and not to Config.Exts.
  150. type CommonConfigurer struct {
  151. repoRoot, buildFileNames, readBuildFilesDir, writeBuildFilesDir string
  152. indexLibraries bool
  153. }
  154. func (cc *CommonConfigurer) RegisterFlags(fs *flag.FlagSet, cmd string, c *Config) {
  155. fs.StringVar(&cc.repoRoot, "repo_root", "", "path to a directory which corresponds to go_prefix, otherwise gazelle searches for it.")
  156. fs.StringVar(&cc.buildFileNames, "build_file_name", strings.Join(DefaultValidBuildFileNames, ","), "comma-separated list of valid build file names.\nThe first element of the list is the name of output build files to generate.")
  157. fs.BoolVar(&cc.indexLibraries, "index", true, "when true, gazelle will build an index of libraries in the workspace for dependency resolution")
  158. fs.StringVar(&cc.readBuildFilesDir, "experimental_read_build_files_dir", "", "path to a directory where build files should be read from (instead of -repo_root)")
  159. fs.StringVar(&cc.writeBuildFilesDir, "experimental_write_build_files_dir", "", "path to a directory where build files should be written to (instead of -repo_root)")
  160. }
  161. func (cc *CommonConfigurer) CheckFlags(fs *flag.FlagSet, c *Config) error {
  162. var err error
  163. if cc.repoRoot == "" {
  164. cc.repoRoot, err = wspace.Find(".")
  165. if err != nil {
  166. return fmt.Errorf("-repo_root not specified, and WORKSPACE cannot be found: %v", err)
  167. }
  168. }
  169. c.RepoRoot, err = filepath.Abs(cc.repoRoot)
  170. if err != nil {
  171. return fmt.Errorf("%s: failed to find absolute path of repo root: %v", cc.repoRoot, err)
  172. }
  173. c.RepoRoot, err = filepath.EvalSymlinks(c.RepoRoot)
  174. if err != nil {
  175. return fmt.Errorf("%s: failed to resolve symlinks: %v", cc.repoRoot, err)
  176. }
  177. c.ValidBuildFileNames = strings.Split(cc.buildFileNames, ",")
  178. if cc.readBuildFilesDir != "" {
  179. c.ReadBuildFilesDir, err = filepath.Abs(cc.readBuildFilesDir)
  180. if err != nil {
  181. return fmt.Errorf("%s: failed to find absolute path of -read_build_files_dir: %v", cc.readBuildFilesDir, err)
  182. }
  183. }
  184. if cc.writeBuildFilesDir != "" {
  185. c.WriteBuildFilesDir, err = filepath.Abs(cc.writeBuildFilesDir)
  186. if err != nil {
  187. return fmt.Errorf("%s: failed to find absolute path of -write_build_files_dir: %v", cc.writeBuildFilesDir, err)
  188. }
  189. }
  190. c.IndexLibraries = cc.indexLibraries
  191. return nil
  192. }
  193. func (cc *CommonConfigurer) KnownDirectives() []string {
  194. return []string{"build_file_name", "map_kind"}
  195. }
  196. func (cc *CommonConfigurer) Configure(c *Config, rel string, f *rule.File) {
  197. if f == nil {
  198. return
  199. }
  200. for _, d := range f.Directives {
  201. switch d.Key {
  202. case "build_file_name":
  203. c.ValidBuildFileNames = strings.Split(d.Value, ",")
  204. case "map_kind":
  205. vals := strings.Fields(d.Value)
  206. if len(vals) != 3 {
  207. log.Printf("expected three arguments (gazelle:map_kind from_kind to_kind load_file), got %v", vals)
  208. continue
  209. }
  210. if c.KindMap == nil {
  211. c.KindMap = make(map[string]MappedKind)
  212. }
  213. c.KindMap[vals[0]] = MappedKind{
  214. FromKind: vals[0],
  215. KindName: vals[1],
  216. KindLoad: vals[2],
  217. }
  218. }
  219. }
  220. }