config.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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
  13. import (
  14. "flag"
  15. "fmt"
  16. "go/build"
  17. "path/filepath"
  18. "strings"
  19. "github.com/bazelbuild/bazel-gazelle/internal/rule"
  20. "github.com/bazelbuild/bazel-gazelle/internal/wspace"
  21. )
  22. // Config holds information about how Gazelle should run. This is based on
  23. // command line arguments, directives, other hints in build files.
  24. //
  25. // A Config applies to a single directory. A Config is created for the
  26. // repository root directory, then copied and modified for each subdirectory.
  27. //
  28. // Config itself contains only general information. Most configuration
  29. // information is language-specific and is stored in Exts. This information
  30. // is modified by extensions that implement Configurer.
  31. type Config struct {
  32. // RepoRoot is the absolute, canonical path to the root directory of the
  33. // repository with all symlinks resolved.
  34. RepoRoot string
  35. // RepoName is the name of the repository.
  36. RepoName string
  37. // ReadBuildFilesDir is the absolute path to a directory where
  38. // build files should be read from instead of RepoRoot.
  39. ReadBuildFilesDir string
  40. // WriteBuildFilesDir is the absolute path to a directory where
  41. // build files should be written to instead of RepoRoot.
  42. WriteBuildFilesDir string
  43. // ValidBuildFileNames is a list of base names that are considered valid
  44. // build files. Some repositories may have files named "BUILD" that are not
  45. // used by Bazel and should be ignored. Must contain at least one string.
  46. ValidBuildFileNames []string
  47. // ShouldFix determines whether Gazelle attempts to remove and replace
  48. // usage of deprecated rules.
  49. ShouldFix bool
  50. // Exts is a set of configurable extensions. Generally, each language
  51. // has its own set of extensions, but other modules may provide their own
  52. // extensions as well. Values in here may be populated by command line
  53. // arguments, directives in build files, or other mechanisms.
  54. Exts map[string]interface{}
  55. }
  56. func New() *Config {
  57. return &Config{
  58. ValidBuildFileNames: DefaultValidBuildFileNames,
  59. Exts: make(map[string]interface{}),
  60. }
  61. }
  62. // Clone creates a copy of the configuration for use in a subdirectory.
  63. // Note that the Exts map is copied, but its contents are not.
  64. // Configurer.Configure should do this, if needed.
  65. func (c *Config) Clone() *Config {
  66. cc := *c
  67. cc.Exts = make(map[string]interface{})
  68. for k, v := range c.Exts {
  69. cc.Exts[k] = v
  70. }
  71. return &cc
  72. }
  73. var DefaultValidBuildFileNames = []string{"BUILD.bazel", "BUILD"}
  74. func (c *Config) IsValidBuildFileName(name string) bool {
  75. for _, n := range c.ValidBuildFileNames {
  76. if name == n {
  77. return true
  78. }
  79. }
  80. return false
  81. }
  82. func (c *Config) DefaultBuildFileName() string {
  83. return c.ValidBuildFileNames[0]
  84. }
  85. // Configurer is the interface for language or library-specific configuration
  86. // extensions. Most (ideally all) modifications to Config should happen
  87. // via this interface.
  88. type Configurer interface {
  89. // RegisterFlags registers command-line flags used by the extension. This
  90. // method is called once with the root configuration when Gazelle
  91. // starts. RegisterFlags may set an initial values in Config.Exts. When flags
  92. // are set, they should modify these values.
  93. RegisterFlags(fs *flag.FlagSet, cmd string, c *Config)
  94. // CheckFlags validates the configuration after command line flags are parsed.
  95. // This is called once with the root configuration when Gazelle starts.
  96. // CheckFlags may set default values in flags or make implied changes.
  97. CheckFlags(fs *flag.FlagSet, c *Config) error
  98. // KnownDirectives returns a list of directive keys that this Configurer can
  99. // interpret. Gazelle prints errors for directives that are not recoginized by
  100. // any Configurer.
  101. KnownDirectives() []string
  102. // Configure modifies the configuration using directives and other information
  103. // extracted from a build file. Configure is called in each directory.
  104. //
  105. // c is the configuration for the current directory. It starts out as a copy
  106. // of the configuration for the parent directory.
  107. //
  108. // rel is the slash-separated relative path from the repository root to
  109. // the current directory. It is "" for the root directory itself.
  110. //
  111. // f is the build file for the current directory or nil if there is no
  112. // existing build file.
  113. Configure(c *Config, rel string, f *rule.File)
  114. }
  115. // CommonConfigurer handles language-agnostic command-line flags and directives,
  116. // i.e., those that apply to Config itself and not to Config.Exts.
  117. type CommonConfigurer struct {
  118. repoRoot, buildFileNames, readBuildFilesDir, writeBuildFilesDir string
  119. }
  120. func (cc *CommonConfigurer) RegisterFlags(fs *flag.FlagSet, cmd string, c *Config) {
  121. fs.StringVar(&cc.repoRoot, "repo_root", "", "path to a directory which corresponds to go_prefix, otherwise gazelle searches for it.")
  122. 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.")
  123. fs.StringVar(&cc.readBuildFilesDir, "experimental_read_build_files_dir", "", "path to a directory where build files should be read from (instead of -repo_root)")
  124. fs.StringVar(&cc.writeBuildFilesDir, "experimental_write_build_files_dir", "", "path to a directory where build files should be written to (instead of -repo_root)")
  125. }
  126. func (cc *CommonConfigurer) CheckFlags(fs *flag.FlagSet, c *Config) error {
  127. var err error
  128. if cc.repoRoot == "" {
  129. cc.repoRoot, err = wspace.Find(".")
  130. if err != nil {
  131. return fmt.Errorf("-repo_root not specified, and WORKSPACE cannot be found: %v", err)
  132. }
  133. }
  134. c.RepoRoot, err = filepath.Abs(cc.repoRoot)
  135. if err != nil {
  136. return fmt.Errorf("%s: failed to find absolute path of repo root: %v", cc.repoRoot, err)
  137. }
  138. c.RepoRoot, err = filepath.EvalSymlinks(c.RepoRoot)
  139. if err != nil {
  140. return fmt.Errorf("%s: failed to resolve symlinks: %v", cc.repoRoot, err)
  141. }
  142. c.ValidBuildFileNames = strings.Split(cc.buildFileNames, ",")
  143. if cc.readBuildFilesDir != "" {
  144. c.ReadBuildFilesDir, err = filepath.Abs(cc.readBuildFilesDir)
  145. if err != nil {
  146. return fmt.Errorf("%s: failed to find absolute path of -read_build_files_dir: %v", cc.readBuildFilesDir, err)
  147. }
  148. }
  149. if cc.writeBuildFilesDir != "" {
  150. c.WriteBuildFilesDir, err = filepath.Abs(cc.writeBuildFilesDir)
  151. if err != nil {
  152. return fmt.Errorf("%s: failed to find absolute path of -write_build_files_dir: %v", cc.writeBuildFilesDir, err)
  153. }
  154. }
  155. return nil
  156. }
  157. func (cc *CommonConfigurer) KnownDirectives() []string {
  158. return []string{"build_file_name"}
  159. }
  160. func (cc *CommonConfigurer) Configure(c *Config, rel string, f *rule.File) {
  161. if f == nil {
  162. return
  163. }
  164. for _, d := range f.Directives {
  165. if d.Key == "build_file_name" {
  166. c.ValidBuildFileNames = strings.Split(d.Value, ",")
  167. }
  168. }
  169. }
  170. // CheckPrefix checks that a string may be used as a prefix. We forbid local
  171. // (relative) imports and those beginning with "/". We allow the empty string,
  172. // but generated rules must not have an empty importpath.
  173. func CheckPrefix(prefix string) error {
  174. if strings.HasPrefix(prefix, "/") || build.IsLocalImport(prefix) {
  175. return fmt.Errorf("invalid prefix: %q", prefix)
  176. }
  177. return nil
  178. }
  179. // DependencyMode determines how imports of packages outside of the prefix
  180. // are resolved.
  181. type DependencyMode int
  182. const (
  183. // ExternalMode indicates imports should be resolved to external dependencies
  184. // (declared in WORKSPACE).
  185. ExternalMode DependencyMode = iota
  186. // VendorMode indicates imports should be resolved to libraries in the
  187. // vendor directory.
  188. VendorMode
  189. )
  190. // DependencyModeFromString converts a string from the command line
  191. // to a DependencyMode. Valid strings are "external", "vendor". An error will
  192. // be returned for an invalid string.
  193. func DependencyModeFromString(s string) (DependencyMode, error) {
  194. switch s {
  195. case "external":
  196. return ExternalMode, nil
  197. case "vendored":
  198. return VendorMode, nil
  199. default:
  200. return 0, fmt.Errorf("unrecognized dependency mode: %q", s)
  201. }
  202. }
  203. // ProtoMode determines how proto rules are generated.
  204. type ProtoMode int
  205. const (
  206. // DefaultProtoMode generates proto_library and new grpc_proto_library rules.
  207. // .pb.go files are excluded when there is a .proto file with a similar name.
  208. DefaultProtoMode ProtoMode = iota
  209. // DisableProtoMode ignores .proto files. .pb.go files are treated
  210. // as normal sources.
  211. DisableProtoMode
  212. // LegacyProtoMode generates filegroups for .proto files if .pb.go files
  213. // are present in the same directory.
  214. LegacyProtoMode
  215. )
  216. func ProtoModeFromString(s string) (ProtoMode, error) {
  217. switch s {
  218. case "default":
  219. return DefaultProtoMode, nil
  220. case "disable":
  221. return DisableProtoMode, nil
  222. case "legacy":
  223. return LegacyProtoMode, nil
  224. default:
  225. return 0, fmt.Errorf("unrecognized proto mode: %q", s)
  226. }
  227. }