Initial commit

This commit is contained in:
Donny
2019-04-22 20:46:32 +08:00
commit 49ab8aadd1
25441 changed files with 4055000 additions and 0 deletions

41
vendor/github.com/hawkingrei/kazel/BUILD.bazel generated vendored Normal file
View File

@@ -0,0 +1,41 @@
load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_binary")
go_library(
name = "go_default_library",
srcs = [
"config.go",
"diff.go",
"fileinfo.go",
"generator.go",
"kazel.go",
"proto.go",
"sourcerer.go",
],
importmap = "go-common/vendor/github.com/hawkingrei/kazel",
importpath = "github.com/hawkingrei/kazel",
visibility = ["//visibility:private"],
deps = [
"//vendor/github.com/bazelbuild/buildtools/build:go_default_library",
"//vendor/github.com/golang/glog:go_default_library",
],
)
go_binary(
name = "kazel",
embed = [":go_default_library"],
visibility = ["//visibility:public"],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

90
vendor/github.com/hawkingrei/kazel/README.rst generated vendored Normal file
View File

@@ -0,0 +1,90 @@
kazel - a BUILD file generator for go and bazel
===============================================
Requirements:
#############
* Your project must be somewhat compatible with go tool because
kazel uses go tool to parse your import tree.
* You must have a **GOPATH** and **GOROOT** setup and your project must
be in the correct location in your **GOPATH**.
* Your ``./vendor`` directory may not contain ``BUILD`` files.
Usage:
######
1. Get kazel by running ``go get k8s.io/repo-infra/kazel``.
2. Create a ``.kazelcfg.json`` in the root of the repository. For the
kazel repository, the ``.kazelcfg.json`` would look like:
.. code-block:: json
{
"GoPrefix": "k8s.io/repo-infra",
"SrcDirs": [
"./kazel"
],
"SkippedPaths": [
".*foobar(baz)?.*$"
]
}
3. Run kazel:
.. code-block:: bash
$ kazel -root=$GOPATH/src/k8s.io/repo-infra
Defaults:
#########
* **SrcDirs** in ``.kazelcfg.json`` defaults to ``["./"]``
* ``-root`` option defaults to the current working directory
Automanagement:
###############
kazel reconciles rules that have the "**automanaged**" tag. If
you no longer want kazel to manage a rule, you can remove the
**automanaged** tag and kazel will no longer manage that rule.
kazel only manages srcs, deps, and library attributes of a
rule after initial creation so you can add and managed other
attributes like data and copts and kazel will respect your
changes.
kazel automatically formats all ``BUILD`` files in your repository
except for those matching **SkippedPaths**.
Adding "sources" rules:
#######################
If you set "**AddSourcesRules**": ``true`` in your ``.kazelcfg.json``,
kazel will create "**package-srcs**" and "**all-srcs**" rules in every
package.
The "**package-srcs**" rule is a glob matching all files in the
package recursively, but not any files owned by packages in
subdirectories.
The "**all-srcs**" rule includes both the "**package-srcs**" rule and
the "**all-srcs**" rules of all subpackages; i.e. **//:all-srcs** will
include all files in your repository.
The "**package-srcs**" rule defaults to private visibility,
since it is safer to depend on the "**all-srcs**" rule: if a
subpackage is added, the "**package-srcs**" rule will no longer
include those files.
You can remove the "**automanaged**" tag from the "**package-srcs**"
rule if you need to modify the glob (such as adding excludes).
It's recommended that you leave the "**all-srcs**" rule
automanaged.
Validating BUILD files in CI:
#############################
If you run kazel with ``--validate``, it will not update any ``BUILD`` files, but it
will exit nonzero if any ``BUILD`` files are out-of-date. You can add ``--print-diff``
to print out the changes needed.

61
vendor/github.com/hawkingrei/kazel/config.go generated vendored Normal file
View File

@@ -0,0 +1,61 @@
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"encoding/json"
"io/ioutil"
)
// Cfg defines the configuration options for kazel.
type Cfg struct {
GoPrefix string
// evaluated recursively, defaults to ["."]
SrcDirs []string
// regexps that match packages to skip
SkippedPaths []string
// whether to add "pkg-srcs" and "all-srcs" filegroups
// note that this operates on the entire tree (not just SrcsDirs) but skips anything matching SkippedPaths
AddSourcesRules bool
// whether to have multiple build files in vendor/ or just one.
VendorMultipleBuildFiles bool
// whether to manage kubernetes' pkg/generated/openapi.
K8sOpenAPIGen bool
// Whether to manage the upstream Go rules provided by bazelbuild/rules_go.
// If using gazelle, set this to false (or omit).
ManageGoRules bool
}
// ReadCfg reads and unmarshals the specified json file into a Cfg struct.
func ReadCfg(cfgPath string) (*Cfg, error) {
b, err := ioutil.ReadFile(cfgPath)
if err != nil {
return nil, err
}
var cfg Cfg
if err := json.Unmarshal(b, &cfg); err != nil {
return nil, err
}
defaultCfg(&cfg)
return &cfg, nil
}
func defaultCfg(c *Cfg) {
if len(c.SrcDirs) == 0 {
c.SrcDirs = []string{"."}
}
}

60
vendor/github.com/hawkingrei/kazel/diff.go generated vendored Normal file
View File

@@ -0,0 +1,60 @@
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"io/ioutil"
"os"
"os/exec"
)
// Diff prints the unified diff of the two provided byte slices
// using the unix diff command.
func Diff(left, right []byte) error {
lf, err := ioutil.TempFile("/tmp", "actual-file-")
if err != nil {
return err
}
defer lf.Close()
defer os.Remove(lf.Name())
rf, err := ioutil.TempFile("/tmp", "expected-file-")
if err != nil {
return err
}
defer rf.Close()
defer os.Remove(rf.Name())
_, err = lf.Write(left)
if err != nil {
return err
}
lf.Close()
_, err = rf.Write(right)
if err != nil {
return err
}
rf.Close()
cmd := exec.Command("/usr/bin/diff", "-u", lf.Name(), rf.Name())
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Run()
return nil
}

71
vendor/github.com/hawkingrei/kazel/fileinfo.go generated vendored Normal file
View File

@@ -0,0 +1,71 @@
package main
type fileInfo struct {
path, rel, name, ext string
// packageName is the Go package name of a .go file, without the
// "_test" suffix if it was present. It is empty for non-Go files.
packageName string
// importPath is the canonical import path for this file's package.
// This may be read from a package comment (in Go) or a go_package
// option (in proto). This field is empty for files that don't specify
// an import path.
importPath string
// category is the type of file, based on extension.
category extCategory
// isTest is true if the file stem (the part before the extension)
// ends with "_test.go". This is never true for non-Go files.
isTest bool
// isXTest is true for test Go files whose declared package name ends
// with "_test".
isXTest bool
// imports is a list of packages imported by a file. It does not include
// "C" or anything from the standard library.
imports []string
// isCgo is true for .go files that import "C".
isCgo bool
// goos and goarch contain the OS and architecture suffixes in the filename,
// if they were present.
goos, goarch string
// tags is a list of build tag lines. Each entry is the trimmed text of
// a line after a "+build" prefix.
tags []tagLine
// copts and clinkopts contain flags that are part of CFLAGS, CPPFLAGS,
// CXXFLAGS, and LDFLAGS directives in cgo comments.
copts, clinkopts []taggedOpts
// hasServices indicates whether a .proto file has service definitions.
hasServices bool
}
// tagLine represents the space-separated disjunction of build tag groups
// in a line comment.
type tagLine []tagGroup
// tagGroup represents a comma-separated conjuction of build tags.
type tagGroup []string
// extCategory indicates how a file should be treated, based on extension.
type extCategory int
// taggedOpts a list of compile or link options which should only be applied
// if the given set of build tags are satisfied. These options have already
// been tokenized using the same algorithm that "go build" uses, then joined
// with OptSeparator.
type taggedOpts struct {
tags tagLine
opts string
}
func fileNameInfo(dir, rel, name string) fileInfo {
return fileInfo{}
}

128
vendor/github.com/hawkingrei/kazel/generator.go generated vendored Normal file
View File

@@ -0,0 +1,128 @@
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strings"
)
const (
openAPIGenTag = "// +k8s:openapi-gen"
staging = "staging/src/"
)
// walkGenerated updates the rule for kubernetes' OpenAPI generated file.
// This involves reading all go files in the source tree and looking for the
// "+k8s:openapi-gen" tag. If present, then that package must be supplied to
// the genrule.
func (v *Vendorer) walkGenerated() error {
if !v.cfg.K8sOpenAPIGen {
return nil
}
v.managedAttrs = append(v.managedAttrs, "openapi_targets", "vendor_targets")
paths, err := v.findOpenAPI(".")
if err != nil {
return err
}
return v.addGeneratedOpenAPIRule(paths)
}
// findOpenAPI searches for all packages under root that request OpenAPI. It
// returns the go import paths. It does not follow symlinks.
func (v *Vendorer) findOpenAPI(root string) ([]string, error) {
for _, r := range v.skippedPaths {
if r.MatchString(root) {
return nil, nil
}
}
finfos, err := ioutil.ReadDir(root)
if err != nil {
return nil, err
}
var res []string
var includeMe bool
for _, finfo := range finfos {
path := filepath.Join(root, finfo.Name())
if finfo.IsDir() && (finfo.Mode()&os.ModeSymlink == 0) {
children, err := v.findOpenAPI(path)
if err != nil {
return nil, err
}
res = append(res, children...)
} else if strings.HasSuffix(path, ".go") && !strings.HasSuffix(path, "_test.go") {
b, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
if bytes.Contains(b, []byte(openAPIGenTag)) {
includeMe = true
}
}
}
if includeMe {
pkg, err := v.ctx.ImportDir(filepath.Join(v.root, root), 0)
if err != nil {
return nil, err
}
res = append(res, pkg.ImportPath)
}
return res, nil
}
// addGeneratedOpenAPIRule updates the pkg/generated/openapi go_default_library
// rule with the automanaged openapi_targets and vendor_targets.
func (v *Vendorer) addGeneratedOpenAPIRule(paths []string) error {
var openAPITargets []string
var vendorTargets []string
baseImport := v.cfg.GoPrefix + "/"
for _, p := range paths {
if !strings.HasPrefix(p, baseImport) {
return fmt.Errorf("openapi-gen path outside of %s: %s", v.cfg.GoPrefix, p)
}
np := p[len(baseImport):]
if strings.HasPrefix(np, staging) {
vendorTargets = append(vendorTargets, np[len(staging):])
} else {
openAPITargets = append(openAPITargets, np)
}
}
sort.Strings(openAPITargets)
sort.Strings(vendorTargets)
pkgPath := filepath.Join("pkg", "generated", "openapi")
// If we haven't walked this package yet, walk it so there is a go_library rule to modify
if len(v.newRules[pkgPath]) == 0 {
if err := v.updateSinglePkg(pkgPath); err != nil {
return err
}
}
for _, r := range v.newRules[pkgPath] {
if r.Name() == "go_default_library" {
r.SetAttr("openapi_targets", asExpr(openAPITargets))
r.SetAttr("vendor_targets", asExpr(vendorTargets))
break
}
}
return nil
}

6
vendor/github.com/hawkingrei/kazel/go.mod generated vendored Normal file
View File

@@ -0,0 +1,6 @@
module github.com/hawkingrei/kazel
require (
github.com/bazelbuild/buildtools v0.0.0-20180226164855-80c7f0d45d7e
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b
)

4
vendor/github.com/hawkingrei/kazel/go.sum generated vendored Normal file
View File

@@ -0,0 +1,4 @@
github.com/bazelbuild/buildtools v0.0.0-20180226164855-80c7f0d45d7e h1:VuTBHPJNCQ88Okm9ld5SyLCvU50soWJYQYjQFdcDxew=
github.com/bazelbuild/buildtools v0.0.0-20180226164855-80c7f0d45d7e/go.mod h1:5JP0TXzWDHXv8qvxRC4InIazwdyDseBDbzESUMKk1yU=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=

1126
vendor/github.com/hawkingrei/kazel/kazel.go generated vendored Normal file

File diff suppressed because it is too large Load Diff

159
vendor/github.com/hawkingrei/kazel/proto.go generated vendored Normal file
View File

@@ -0,0 +1,159 @@
package main
import (
"bytes"
"io/ioutil"
"log"
"path"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"unicode"
)
type ProtoInfo struct {
src []string
importPath string
packageName string
imports []string
isGogo bool
hasServices bool
}
var protoRe = buildProtoRegexp()
const (
importSubexpIndex = 1
packageSubexpIndex = 2
goPackageSubexpIndex = 3
serviceSubexpIndex = 4
goCommonTimeIndex = 5
)
func protoFileInfo(goPrefix, basepath string, protosrc []string) ProtoInfo {
//info := fileNameInfo(dir, rel, name)
var info ProtoInfo
info.src = protosrc
for _, srcpath := range info.src {
content, err := ioutil.ReadFile(filepath.Join(basepath, srcpath))
if err != nil {
log.Printf("%s: error reading proto file: %v", srcpath, err)
return info
}
for _, match := range protoRe.FindAllSubmatch(content, -1) {
switch {
case match[importSubexpIndex] != nil:
imp := unquoteProtoString(match[importSubexpIndex])
info.imports = append(info.imports, imp)
case match[packageSubexpIndex] != nil:
pkg := string(match[packageSubexpIndex])
if info.packageName == "" {
info.packageName = strings.Replace(pkg, ".", "_", -1)
}
case match[goPackageSubexpIndex] != nil:
gopkg := unquoteProtoString(match[goPackageSubexpIndex])
// If there's no / in the package option, then it's just a
// simple package name, not a full import path.
if strings.LastIndexByte(gopkg, '/') == -1 {
info.packageName = gopkg
} else {
if i := strings.LastIndexByte(gopkg, ';'); i != -1 {
info.importPath = gopkg[:i]
info.packageName = gopkg[i+1:]
} else {
info.importPath = gopkg
info.packageName = path.Base(gopkg)
}
}
case match[serviceSubexpIndex] != nil:
info.hasServices = true
default:
// Comment matched. Nothing to extract.
}
}
rtime := regexp.MustCompile("go-common/library/time.Time")
if rtime.FindAllSubmatchIndex(content, -1) != nil {
info.imports = append(info.imports, "//library/time:go_default_library")
}
sort.Strings(info.imports)
if info.packageName == "" {
stem := strings.TrimSuffix(filepath.Base(srcpath), ".proto")
fs := strings.FieldsFunc(stem, func(r rune) bool {
return !(unicode.IsLetter(r) || unicode.IsNumber(r) || r == '_')
})
info.packageName = strings.Join(fs, "_")
}
}
if len(info.imports) > 1 {
info.imports = unique(info.imports)
}
for _, v := range info.imports {
if strings.Contains(v, "gogo") {
info.isGogo = true
}
}
info.importPath = filepath.Join(goPrefix, basepath)
return info
}
// Based on https://developers.google.com/protocol-buffers/docs/reference/proto3-spec
func buildProtoRegexp() *regexp.Regexp {
hexEscape := `\\[xX][0-9a-fA-f]{2}`
octEscape := `\\[0-7]{3}`
charEscape := `\\[abfnrtv'"\\]`
charValue := strings.Join([]string{hexEscape, octEscape, charEscape, "[^\x00\\'\\\"\\\\]"}, "|")
strLit := `'(?:` + charValue + `|")*'|"(?:` + charValue + `|')*"`
ident := `[A-Za-z][A-Za-z0-9_]*`
fullIdent := ident + `(?:\.` + ident + `)*`
importStmt := `\bimport\s*(?:public|weak)?\s*(?P<import>` + strLit + `)\s*;`
packageStmt := `\bpackage\s*(?P<package>` + fullIdent + `)\s*;`
goPackageStmt := `\boption\s*go_package\s*=\s*(?P<go_package>` + strLit + `)\s*;`
serviceStmt := `(?P<service>service)`
comment := `//[^\n]*`
protoReSrc := strings.Join([]string{importStmt, packageStmt, goPackageStmt, serviceStmt, comment}, "|")
return regexp.MustCompile(protoReSrc)
}
func unquoteProtoString(q []byte) string {
// Adjust quotes so that Unquote is happy. We need a double quoted string
// without unescaped double quote characters inside.
noQuotes := bytes.Split(q[1:len(q)-1], []byte{'"'})
if len(noQuotes) != 1 {
for i := 0; i < len(noQuotes)-1; i++ {
if len(noQuotes[i]) == 0 || noQuotes[i][len(noQuotes[i])-1] != '\\' {
noQuotes[i] = append(noQuotes[i], '\\')
}
}
q = append([]byte{'"'}, bytes.Join(noQuotes, []byte{'"'})...)
q = append(q, '"')
}
if q[0] == '\'' {
q[0] = '"'
q[len(q)-1] = '"'
}
s, err := strconv.Unquote(string(q))
if err != nil {
log.Panicf("unquoting string literal %s from proto: %v", q, err)
}
return s
}
func unique(intSlice []string) []string {
keys := make(map[string]interface{})
list := []string{}
for _, entry := range intSlice {
if _, value := keys[entry]; !value {
keys[entry] = nil
list = append(list, entry)
}
}
return list
}

109
vendor/github.com/hawkingrei/kazel/sourcerer.go generated vendored Normal file
View File

@@ -0,0 +1,109 @@
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"fmt"
"io/ioutil"
"path/filepath"
bzl "github.com/bazelbuild/buildtools/build"
)
const (
pkgSrcsTarget = "package-srcs"
allSrcsTarget = "all-srcs"
)
// walkSource walks the source tree recursively from pkgPath, adding
// any BUILD files to v.newRules to be formatted.
//
// If AddSourcesRules is enabled in the kazel config, then we additionally add
// package-sources and recursive all-srcs filegroups rules to every BUILD file.
//
// Returns the list of children all-srcs targets that should be added to the
// all-srcs rule of the enclosing package.
func (v *Vendorer) walkSource(pkgPath string) ([]string, error) {
// clean pkgPath since we access v.newRules directly
pkgPath = filepath.Clean(pkgPath)
for _, r := range v.skippedPaths {
if r.MatchString(pkgPath) {
return nil, nil
}
}
files, err := ioutil.ReadDir(pkgPath)
if err != nil {
return nil, err
}
// Find any children packages we need to include in an all-srcs rule.
var children []string
for _, f := range files {
if f.IsDir() {
c, err := v.walkSource(filepath.Join(pkgPath, f.Name()))
if err != nil {
return nil, err
}
children = append(children, c...)
}
}
// This path is a package either if we've added rules or if a BUILD file already exists.
_, hasRules := v.newRules[pkgPath]
isPkg := hasRules
if !isPkg {
isPkg, _ = findBuildFile(pkgPath)
}
if !isPkg {
// This directory isn't a package (doesn't contain a BUILD file),
// but there might be subdirectories that are packages,
// so pass that up to our parent.
return children, nil
}
// Enforce formatting the BUILD file, even if we're not adding srcs rules
if !hasRules {
v.addRules(pkgPath, nil)
}
if !v.cfg.AddSourcesRules {
return nil, nil
}
pkgSrcsExpr := &bzl.LiteralExpr{Token: `glob(["**"])`}
if pkgPath == "." {
pkgSrcsExpr = &bzl.LiteralExpr{Token: `glob(["**"], exclude=["bazel-*/**", ".git/**", ".idea/**"])`}
}
v.addRules(pkgPath, []*bzl.Rule{
newRule(RuleTypeFileGroup,
func(_ ruleType) string { return pkgSrcsTarget },
map[string]bzl.Expr{
"srcs": pkgSrcsExpr,
"visibility": asExpr([]string{"//visibility:private"}),
}),
newRule(RuleTypeFileGroup,
func(_ ruleType) string { return allSrcsTarget },
map[string]bzl.Expr{
"srcs": asExpr(append(children, fmt.Sprintf(":%s", pkgSrcsTarget))),
// TODO: should this be more restricted?
"visibility": asExpr([]string{"//visibility:public"}),
}),
})
return []string{fmt.Sprintf("//%s:%s", pkgPath, allSrcsTarget)}, nil
}