| 1 | /* |
| 2 | Copyright The containerd Authors. |
| 3 | |
| 4 | Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | you may not use this file except in compliance with the License. |
| 6 | You may obtain a copy of the License at |
| 7 | |
| 8 | http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | |
| 10 | Unless required by applicable law or agreed to in writing, software |
| 11 | distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | See the License for the specific language governing permissions and |
| 14 | limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | package main |
| 18 | |
| 19 | import ( |
| 20 | "bytes" |
| 21 | "errors" |
| 22 | "flag" |
| 23 | "fmt" |
| 24 | "io/ioutil" |
| 25 | "log" |
| 26 | "os" |
| 27 | "os/exec" |
| 28 | "path" |
| 29 | "path/filepath" |
| 30 | "strconv" |
| 31 | "strings" |
| 32 | "syscall" |
| 33 | |
| 34 | "github.com/golang/protobuf/protoc-gen-go/descriptor" |
| 35 | ) |
| 36 | |
| 37 | // defines several variables for parameterizing the protoc command. We can pull |
| 38 | // this out into a toml files in cases where we to vary this per package. |
| 39 | var ( |
| 40 | configPath string |
| 41 | dryRun bool |
| 42 | quiet bool |
| 43 | ) |
| 44 | |
| 45 | func init() { |
| 46 | flag.StringVar(&configPath, "f", "Protobuild.toml", "override default config location") |
| 47 | flag.BoolVar(&dryRun, "dryrun", false, "prints commands without running") |
| 48 | flag.BoolVar(&quiet, "quiet", false, "suppress verbose output") |
| 49 | } |
| 50 | |
| 51 | func parseVersion(s string) (int, error) { |
| 52 | if s == "unstable" { |
| 53 | return 0, nil |
| 54 | } |
| 55 | |
| 56 | v, err := strconv.Atoi(s) |
| 57 | if err != nil { |
| 58 | return 0, fmt.Errorf("unknown file version %q: %w", s, err) |
| 59 | } |
| 60 | |
| 61 | if v < 1 || v > 2 { |
| 62 | return 0, fmt.Errorf(`unknown file version %q; valid versions are "unstable", "1" and "2"`, s) |
| 63 | } |
| 64 | return v, nil |
| 65 | } |
| 66 | |
| 67 | func importPath(base, target string) (string, error) { |
| 68 | rel, err := filepath.Rel(base, target) |
| 69 | if err != nil { |
| 70 | return "", err |
| 71 | } |
| 72 | return filepath.ToSlash(rel), nil |
| 73 | } |
| 74 | |
| 75 | func main() { |
| 76 | flag.Parse() |
| 77 | |
| 78 | c, err := readConfig(configPath) |
| 79 | if err != nil { |
| 80 | log.Fatalln(err) |
| 81 | } |
| 82 | |
| 83 | version, err := parseVersion(c.Version) |
| 84 | if err != nil { |
| 85 | log.Fatalln(err) |
| 86 | } |
| 87 | |
| 88 | pkgInfos, err := goPkgInfo(flag.Args()...) |
| 89 | if err != nil { |
| 90 | log.Fatalln(err) |
| 91 | } |
| 92 | |
| 93 | gopath, err := gopathSrc() |
| 94 | if err != nil { |
| 95 | log.Fatalln(err) |
| 96 | } |
| 97 | |
| 98 | gopathCurrent, err := gopathCurrent() |
| 99 | if err != nil { |
| 100 | log.Fatalln(err) |
| 101 | } |
| 102 | |
| 103 | // For some reason, the golang protobuf generator makes the god awful |
| 104 | // decision to output the files relative to the gopath root. It doesn't do |
| 105 | // this only in the case where you give it ".". |
| 106 | outputDir := filepath.Join(gopathCurrent, "src") |
| 107 | |
| 108 | // Index overrides by target import path |
| 109 | overrides := map[string]struct { |
| 110 | Prefixes []string |
| 111 | Generator string |
| 112 | Generators []string |
| 113 | Parameters map[string]map[string]string |
| 114 | Plugins *[]string |
| 115 | }{} |
| 116 | for _, override := range c.Overrides { |
| 117 | for _, prefix := range override.Prefixes { |
| 118 | overrides[prefix] = override |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | // Create include paths used to find the descriptor proto. As a special case |
| 123 | // we search the vendor directory relative to the current working directory. |
| 124 | // This handles the case where a user has vendored their descriptor proto. |
| 125 | var descriptorIncludes []string |
| 126 | descriptorIncludes = append(descriptorIncludes, c.Includes.Before...) |
| 127 | for _, vendorPath := range c.Includes.Vendored { |
| 128 | descriptorIncludes = append(descriptorIncludes, |
| 129 | filepath.Join("vendor", vendorPath)) |
| 130 | } |
| 131 | descriptorIncludes = append(descriptorIncludes, c.Includes.Packages...) |
| 132 | descriptorIncludes = append(descriptorIncludes, c.Includes.After...) |
| 133 | descProto, includeDir, err := descriptorProto(descriptorIncludes) |
| 134 | if err != nil { |
| 135 | log.Fatalln(err) |
| 136 | } |
| 137 | |
| 138 | // Aggregate descriptors for each descriptor prefix. |
| 139 | descriptorSets := map[string]*descriptorSet{} |
| 140 | for _, stable := range c.Descriptors { |
| 141 | descriptorSets[stable.Prefix] = newDescriptorSet(stable.IgnoreFiles, descProto, includeDir) |
| 142 | } |
| 143 | |
| 144 | shouldGenerateDescriptors := func(p string) bool { |
| 145 | for prefix := range descriptorSets { |
| 146 | if strings.HasPrefix(p, prefix) { |
| 147 | return true |
| 148 | } |
| 149 | } |
| 150 | |
| 151 | return false |
| 152 | } |
| 153 | |
| 154 | var descriptors []*descriptor.FileDescriptorSet |
| 155 | for _, pkg := range pkgInfos { |
| 156 | var includes []string |
| 157 | includes = append(includes, c.Includes.Before...) |
| 158 | |
| 159 | vendor, err := closestVendorDir(pkg.Dir) |
| 160 | if err != nil { |
| 161 | if err != errVendorNotFound { |
| 162 | log.Fatalln(err) |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | if vendor != "" { |
| 167 | // TODO(stevvooe): The use of the closest vendor directory is a |
| 168 | // little naive. We should probably resolve all possible vendor |
| 169 | // directories or at least match Go's behavior. |
| 170 | |
| 171 | // we also special case the inclusion of gogoproto in the vendor dir. |
| 172 | // We could parameterize this better if we find it to be a common case. |
| 173 | var vendoredIncludesResolved []string |
| 174 | for _, vendoredInclude := range c.Includes.Vendored { |
| 175 | vendoredIncludesResolved = append(vendoredIncludesResolved, |
| 176 | filepath.Join(vendor, vendoredInclude)) |
| 177 | } |
| 178 | |
| 179 | // Also do this for pkg includes. |
| 180 | for _, pkgInclude := range c.Includes.Packages { |
| 181 | vendoredIncludesResolved = append(vendoredIncludesResolved, |
| 182 | filepath.Join(vendor, pkgInclude)) |
| 183 | } |
| 184 | |
| 185 | includes = append(includes, vendoredIncludesResolved...) |
| 186 | includes = append(includes, vendor) |
| 187 | } else if len(c.Includes.Vendored) > 0 { |
| 188 | log.Println("ignoring vendored includes: vendor directory not found") |
| 189 | } |
| 190 | |
| 191 | // handle packages that we want to have as an include root from any of |
| 192 | // the gopaths. |
| 193 | for _, pkg := range c.Includes.Packages { |
| 194 | includes = append(includes, gopathJoin(gopath, pkg)) |
| 195 | } |
| 196 | |
| 197 | includes = append(includes, gopath) |
| 198 | includes = append(includes, c.Includes.After...) |
| 199 | |
| 200 | protoc := protocCmd{ |
| 201 | Generators: generators(c.Generators, outputDir), |
| 202 | Files: pkg.ProtoFiles, |
| 203 | OutputDir: outputDir, |
| 204 | Includes: includes, |
| 205 | Version: version, |
| 206 | Names: c.Generators, |
| 207 | Plugins: c.Plugins, |
| 208 | ImportPath: pkg.GoImportPath, |
| 209 | PackageMap: c.Packages, |
| 210 | } |
| 211 | |
| 212 | importDirPath, err := importPath(outputDir, pkg.Dir) |
| 213 | if err != nil { |
| 214 | log.Fatalln(err) |
| 215 | } |
| 216 | |
| 217 | parameters := map[string]map[string]string{} |
| 218 | for proto, pkg := range c.Packages { |
| 219 | parameters["go"] = mergeMap(parameters["go"], map[string]string{ |
| 220 | fmt.Sprintf("M%s", proto): pkg, |
| 221 | }) |
| 222 | } |
| 223 | |
| 224 | for k, v := range c.Parameters { |
| 225 | parameters[k] = mergeMap(parameters[k], v) |
| 226 | } |
| 227 | if override, ok := overrides[importDirPath]; ok { |
| 228 | // selectively apply the overrides to the protoc structure. |
| 229 | if len(override.Generators) > 0 { |
| 230 | protoc.Names = override.Generators |
| 231 | protoc.Generators = generators(override.Generators, outputDir) |
| 232 | } |
| 233 | |
| 234 | if override.Plugins != nil { |
| 235 | protoc.Plugins = *override.Plugins |
| 236 | } |
| 237 | |
| 238 | for k, v := range override.Parameters { |
| 239 | parameters[k] = mergeMap(parameters[k], v) |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | // Set parameters per generator |
| 244 | for i := range protoc.Generators { |
| 245 | protoc.Generators[i].Parameters = parameters[protoc.Generators[i].Name] |
| 246 | } |
| 247 | |
| 248 | var ( |
| 249 | genDescriptors = shouldGenerateDescriptors(importDirPath) |
| 250 | dfp *os.File // tempfile for descriptors |
| 251 | ) |
| 252 | |
| 253 | if genDescriptors { |
| 254 | dfp, err = ioutil.TempFile("", "descriptors.pb-") |
| 255 | if err != nil { |
| 256 | log.Fatalln(err) |
| 257 | } |
| 258 | protoc.Descriptors = dfp.Name() |
| 259 | } |
| 260 | |
| 261 | arg, err := protoc.mkcmd() |
| 262 | if err != nil { |
| 263 | log.Fatalln(err) |
| 264 | } |
| 265 | |
| 266 | if !quiet { |
| 267 | fmt.Println(arg) |
| 268 | } |
| 269 | |
| 270 | if dryRun { |
| 271 | continue |
| 272 | } |
| 273 | |
| 274 | if err := protoc.run(); err != nil { |
| 275 | if quiet { |
| 276 | log.Println(arg) |
| 277 | } |
| 278 | if err, ok := err.(*exec.ExitError); ok { |
| 279 | if status, ok := err.Sys().(syscall.WaitStatus); ok { |
| 280 | os.Exit(status.ExitStatus()) // proxy protoc exit status |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | log.Fatalln(err) |
| 285 | } |
| 286 | |
| 287 | if genDescriptors { |
| 288 | desc, err := readDesc(protoc.Descriptors) |
| 289 | if err != nil { |
| 290 | log.Fatalln(err) |
| 291 | } |
| 292 | |
| 293 | for path, set := range descriptorSets { |
| 294 | if strings.HasPrefix(importDirPath, path) { |
| 295 | set.add(desc.File...) |
| 296 | } |
| 297 | } |
| 298 | descriptors = append(descriptors, desc) |
| 299 | |
| 300 | // clean up descriptors file |
| 301 | if err := os.Remove(dfp.Name()); err != nil { |
| 302 | log.Fatalln(err) |
| 303 | } |
| 304 | |
| 305 | if err := dfp.Close(); err != nil { |
| 306 | log.Fatalln(err) |
| 307 | } |
| 308 | } |
| 309 | } |
| 310 | |
| 311 | for _, descriptorConfig := range c.Descriptors { |
| 312 | fp, err := os.OpenFile(descriptorConfig.Target, os.O_TRUNC|os.O_WRONLY|os.O_CREATE, 0777) |
| 313 | if err != nil { |
| 314 | log.Fatalln(err) |
| 315 | } |
| 316 | defer fp.Sync() |
| 317 | defer fp.Close() |
| 318 | |
| 319 | set := descriptorSets[descriptorConfig.Prefix] |
| 320 | if len(set.merged.File) == 0 { |
| 321 | continue // just skip if there is nothing. |
| 322 | } |
| 323 | |
| 324 | if err := set.marshalTo(fp); err != nil { |
| 325 | log.Fatalln(err) |
| 326 | } |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | func generators(names []string, outDir string) []generator { |
| 331 | g := make([]generator, len(names)) |
| 332 | for i, name := range names { |
| 333 | g[i].Name = name |
| 334 | g[i].OutputDir = outDir |
| 335 | } |
| 336 | return g |
| 337 | } |
| 338 | |
| 339 | type protoGoPkgInfo struct { |
| 340 | Dir string |
| 341 | GoImportPath string |
| 342 | ProtoFiles []string |
| 343 | } |
| 344 | |
| 345 | // goPkgInfo hunts down packages with proto files. |
| 346 | func goPkgInfo(golistpath ...string) ([]protoGoPkgInfo, error) { |
| 347 | args := []string{ |
| 348 | "list", "-e", "-f", "{{.ImportPath}} {{.Dir}}"} |
| 349 | args = append(args, golistpath...) |
| 350 | cmd := exec.Command("go", args...) |
| 351 | |
| 352 | p, err := cmd.Output() |
| 353 | if err != nil { |
| 354 | return nil, err |
| 355 | } |
| 356 | |
| 357 | var pkgInfos []protoGoPkgInfo |
| 358 | lines := bytes.Split(p, []byte("\n")) |
| 359 | for _, line := range lines { |
| 360 | if len(line) == 0 { |
| 361 | continue |
| 362 | } |
| 363 | parts := bytes.Fields(line) |
| 364 | if len(parts) != 2 { |
| 365 | return nil, fmt.Errorf("bad output from command: %s", p) |
| 366 | } |
| 367 | |
| 368 | pkgInfo := protoGoPkgInfo{ |
| 369 | Dir: string(parts[1]), |
| 370 | GoImportPath: string(parts[0]), |
| 371 | } |
| 372 | |
| 373 | protoFiles, err := filepath.Glob(filepath.Join(pkgInfo.Dir, "*.proto")) |
| 374 | if err != nil { |
| 375 | return nil, err |
| 376 | } |
| 377 | if len(protoFiles) == 0 { |
| 378 | continue // not a proto directory, skip |
| 379 | } |
| 380 | |
| 381 | pkgInfo.ProtoFiles = protoFiles |
| 382 | pkgInfos = append(pkgInfos, pkgInfo) |
| 383 | } |
| 384 | |
| 385 | return pkgInfos, nil |
| 386 | } |
| 387 | |
| 388 | func gopaths() ([]string, error) { |
| 389 | cmd := exec.Command("go", "env", "GOPATH") |
| 390 | out, err := cmd.Output() |
| 391 | if err != nil { |
| 392 | return nil, err |
| 393 | } |
| 394 | |
| 395 | gp := strings.TrimSpace(string(out)) |
| 396 | |
| 397 | if gp == "" { |
| 398 | return nil, errors.New("go env GOPATH is empty") |
| 399 | } |
| 400 | |
| 401 | return strings.Split(gp, string(filepath.ListSeparator)), nil |
| 402 | } |
| 403 | |
| 404 | // gopathSrc modifies GOPATH elements from env to include the src directory. |
| 405 | func gopathSrc() (string, error) { |
| 406 | gps, err := gopaths() |
| 407 | if err != nil { |
| 408 | return "", err |
| 409 | } |
| 410 | if len(gps) == 0 { |
| 411 | return "", fmt.Errorf("must be run from a gopath") |
| 412 | } |
| 413 | var elements []string |
| 414 | for _, element := range gps { |
| 415 | elements = append(elements, filepath.Join(element, "src")) |
| 416 | } |
| 417 | |
| 418 | return strings.Join(elements, string(filepath.ListSeparator)), nil |
| 419 | } |
| 420 | |
| 421 | // gopathCurrent provides the top-level gopath for the current generation. |
| 422 | func gopathCurrent() (string, error) { |
| 423 | gps, err := gopaths() |
| 424 | if err != nil { |
| 425 | return "", err |
| 426 | } |
| 427 | if len(gps) == 0 { |
| 428 | return "", fmt.Errorf("must be run from a gopath") |
| 429 | } |
| 430 | |
| 431 | return gps[0], nil |
| 432 | } |
| 433 | |
| 434 | // gopathJoin combines the element with each path item and then recombines the set. |
| 435 | func gopathJoin(gopath, element string) string { |
| 436 | gps := strings.Split(gopath, string(filepath.ListSeparator)) |
| 437 | var elements []string |
| 438 | for _, p := range gps { |
| 439 | elements = append(elements, filepath.Join(p, element)) |
| 440 | } |
| 441 | |
| 442 | return strings.Join(elements, string(filepath.ListSeparator)) |
| 443 | } |
| 444 | |
| 445 | // descriptorProto returns the full path to google/protobuf/descriptor.proto |
| 446 | // which might be different depending on whether it was installed. The argument |
| 447 | // is the list of paths to check. |
| 448 | func descriptorProto(paths []string) (string, string, error) { |
| 449 | const descProto = "google/protobuf/descriptor.proto" |
| 450 | |
| 451 | for _, dir := range paths { |
| 452 | file := path.Join(dir, descProto) |
| 453 | if _, err := os.Stat(file); err == nil { |
| 454 | return file, dir, err |
| 455 | } |
| 456 | } |
| 457 | |
| 458 | return "", "", fmt.Errorf("File %q not found (looked in: %v)", descProto, paths) |
| 459 | } |
| 460 | |
| 461 | var errVendorNotFound = fmt.Errorf("no vendor dir found") |
| 462 | |
| 463 | // closestVendorDir walks up from dir until it finds the vendor directory. |
| 464 | func closestVendorDir(dir string) (string, error) { |
| 465 | dir = filepath.Clean(dir) |
| 466 | for dir != filepath.Join(filepath.VolumeName(dir), string(filepath.Separator)) { |
| 467 | vendor := filepath.Join(dir, "vendor") |
| 468 | fi, err := os.Stat(vendor) |
| 469 | if err != nil { |
| 470 | if os.IsNotExist(err) { |
| 471 | // up we go! |
| 472 | dir = filepath.Dir(dir) |
| 473 | continue |
| 474 | } |
| 475 | return "", err |
| 476 | } |
| 477 | |
| 478 | if !fi.IsDir() { |
| 479 | // up we go! |
| 480 | dir = filepath.Dir(dir) |
| 481 | continue |
| 482 | } |
| 483 | |
| 484 | return vendor, nil |
| 485 | } |
| 486 | |
| 487 | return "", errVendorNotFound |
| 488 | } |
| 489 | |
| 490 | func mergeMap(m1, m2 map[string]string) map[string]string { |
| 491 | if m1 == nil { |
| 492 | m1 = map[string]string{} |
| 493 | } |
| 494 | |
| 495 | for k, v := range m2 { |
| 496 | m1[k] = v |
| 497 | } |
| 498 | |
| 499 | return m1 |
| 500 | } |