Merge pull request #13 from asalkeld/more-verifing

add some of the quicker linters to "make test"
This commit is contained in:
Jim Minter 2019-11-29 19:00:35 -06:00 коммит произвёл GitHub
Родитель 71a0349193 b5727806ba
Коммит 56064d8eec
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
80 изменённых файлов: 54910 добавлений и 36912 удалений

6
.github/workflows/pull_request-test.yaml поставляемый
Просмотреть файл

@ -21,9 +21,5 @@ jobs:
- name: Test
run: |
set -x
go generate ./...
go build ./...
go test ./...
make test
[[ -z "$(git status -s)" ]]

63
Gopkg.lock сгенерированный
Просмотреть файл

@ -104,7 +104,7 @@
version = "v1.0.1"
[[projects]]
digest = "1:aeb79a5ad8ad5447e400c371d8e36b0e6fd798709f9a3865773daa488b1e7fce"
digest = "1:ecd589b54bb09f628d948e21d6fc88508b37472ee673a7fac6c712f3c2515304"
name = "github.com/aws/aws-sdk-go"
packages = [
"aws",
@ -150,8 +150,8 @@
"service/sts/stsiface",
]
pruneopts = "UT"
revision = "da1bcf347b8a39f8222e2799f772112761b6f25c"
version = "v1.25.42"
revision = "44514743a8152d5959d045f906997c7152f46d14"
version = "v1.25.43"
[[projects]]
digest = "1:5f9ab5eeb3788ba8945f9acb2755fba44c3bfefdc95fae477bf6cdc790cab525"
@ -344,7 +344,7 @@
[[projects]]
branch = "master"
digest = "1:7d1e36a62463ecf5953892815b31003e782915c40f3e1e826f931e95345a00b1"
digest = "1:5ac4f65a967ff85b05d5994cb74a982d8b55147c2ae19919279354ab72120943"
name = "github.com/gophercloud/gophercloud"
packages = [
".",
@ -366,18 +366,18 @@
"pagination",
]
pruneopts = "UT"
revision = "20f58269748c805c35479c4e81572ad415193d0e"
revision = "794fbdbba08a7d1b848500304c708c980a6a272f"
[[projects]]
branch = "master"
digest = "1:509f2420155510595031f1ce65c0dda45dcd3b0d9774e010be954c1a353631e4"
digest = "1:1dce060674ee5fde4194ccdecf5185def64df934413358b34455f8a1e6582a98"
name = "github.com/gophercloud/utils"
packages = [
"env",
"openstack/clientconfig",
]
pruneopts = "UT"
revision = "ab7861aa695c70efc7fbc14b1522f7338dcc13cc"
revision = "463e26ffa30d81795505c9773498d3566d4212d8"
[[projects]]
digest = "1:cbec35fe4d5a4fba369a656a8cd65e244ea2c743007d8f6c1ccb132acf9d1296"
@ -559,7 +559,7 @@
[[projects]]
branch = "release-4.3"
digest = "1:cc83292f9535eafa6f0cd1f1e48b63ef18a029b3d24f0ed9fc39b894d70cb8f1"
digest = "1:81a504705a6902d4c00034a6e7fcfa0e628be45ee64b50bc933eb4cdf39242aa"
name = "github.com/openshift/api"
packages = [
"config/v1",
@ -567,7 +567,7 @@
"operator/v1alpha1",
]
pruneopts = "UT"
revision = "371e06d3a8a73b95b67bf6d0b7fb6259c67a5e62"
revision = "63a261ad3171fad9dd29618e9f630765f446a2f8"
[[projects]]
branch = "release-4.3"
@ -591,20 +591,18 @@
"version",
]
pruneopts = "UT"
revision = "475436e11a888af301dcff6b1a9a77d186f9ee69"
revision = "abd3b8284a59c18104220883b1edd16adf8795f4"
[[projects]]
branch = "release-4.3"
digest = "1:e8de4916b8d3f71ab1486b9304ad73804dfe383be7c3ed51f4d1c32584fae071"
digest = "1:ff4eea18a972166c1f93b2c1be7d3468f362379b95d516a29b2b8fc08efda207"
name = "github.com/openshift/cluster-api"
packages = [
"pkg/apis/cluster/common",
"pkg/apis/cluster/v1alpha1",
"pkg/apis/machine/common",
"pkg/apis/machine/v1beta1",
"pkg/client/clientset_generated/clientset",
"pkg/client/clientset_generated/clientset/scheme",
"pkg/client/clientset_generated/clientset/typed/cluster/v1alpha1",
"pkg/client/clientset_generated/clientset/typed/machine/v1beta1",
]
pruneopts = "UT"
@ -619,7 +617,7 @@
"pkg/apis/gcpprovider/v1beta1",
]
pruneopts = "UT"
revision = "537d68ec0751a812755779f31d28155cc2afc454"
revision = "2fe1cf06b7761acb220a57c941b00ea2f9f0cead"
[[projects]]
branch = "master"
@ -722,6 +720,17 @@
revision = "ba832225ce2943ea12ae4e2f0a399dd4cf151e90"
source = "https://github.com/jim-minter/installer"
[[projects]]
branch = "master"
digest = "1:13d16a17027b231e9afec1cd21159aeb617c901ff1376979fbf4002da74e7cf0"
name = "github.com/openshift/machine-api-operator"
packages = [
"pkg/apis/machine",
"pkg/apis/machine/v1beta1",
]
pruneopts = "UT"
revision = "986b771e661d787083ea5f0b6fd81fdc13fc2830"
[[projects]]
branch = "release-4.3"
digest = "1:984213011d5efba011f598ddb50f39e1207d1bb04cc354c9877b4fecf1ab1c09"
@ -862,11 +871,11 @@
"ssh/terminal",
]
pruneopts = "UT"
revision = "ac88ee75c92c889b97e05591e9a39b6480c538b3"
revision = "b544559bb6d1b5c62fba4af5e843ff542174f079"
[[projects]]
branch = "master"
digest = "1:ecff0c65c627299ff316258a094c11f8e0582e3484563d6fe8eadfbf72abc137"
digest = "1:676f320d34ccfa88bfa6d04bdf388ed7062af175355c805ef57ccda1a3f13432"
name = "golang.org/x/net"
packages = [
"context",
@ -879,7 +888,7 @@
"trace",
]
pruneopts = "UT"
revision = "ffdde105785063a81acd95bdf89ea53f6e0aac2d"
revision = "ef20fe5d793301b553005db740f730d87993f778"
[[projects]]
branch = "master"
@ -897,7 +906,7 @@
[[projects]]
branch = "master"
digest = "1:efd5367142eb275f599abcbc7fc7008ea3f01ce0305cd63d587743f6954603b8"
digest = "1:73eaec097280ac58e7dcf99d8a03f1d9e64139870340f6c711804a090afa33f1"
name = "golang.org/x/sys"
packages = [
"cpu",
@ -905,7 +914,7 @@
"windows",
]
pruneopts = "UT"
revision = "8a8471f7e56d296bf6a05aa09520b111beb1937a"
revision = "6d18c012aee9febd81bbf9806760c8c4480e870d"
[[projects]]
digest = "1:1e7fe301d41aead2026c0ade066adcf5e60af7d355cd0f826193852190350d82"
@ -947,9 +956,10 @@
[[projects]]
branch = "master"
digest = "1:d5486f0dafe554a9bb667ef234a935c42a1e77353b9cbc4656cd4f955292efe5"
digest = "1:45ba63c018e89d2061c1e8f1cc670b3f600c0fcc2acf4453399d6a776c734632"
name = "golang.org/x/tools"
packages = [
"cmd/goimports",
"go/ast/astutil",
"go/gcexportdata",
"go/internal/gcimporter",
@ -958,11 +968,13 @@
"go/types/typeutil",
"internal/fastwalk",
"internal/gopathwalk",
"internal/imports",
"internal/module",
"internal/semver",
"internal/span",
]
pruneopts = "UT"
revision = "b0650ceb63d94ec56d3a00dbdd5e37d944dbeabf"
revision = "ecd32218bd7f33fd31c1abbfb74283690bedd093"
[[projects]]
digest = "1:f3661f6218166acf60f5d551b44a537f7ecb8686be02ece061c5950cbfc9ba17"
@ -1285,14 +1297,14 @@
[[projects]]
branch = "master"
digest = "1:37e429b6dcc782044182abc8169aa9e89e81ecdb48ceeee8394116029957c048"
digest = "1:0dceea2a5cccdbea88f5da68ea2cbd7e4ac827e34734f41f2f81283010d77751"
name = "sigs.k8s.io/cluster-api-provider-aws"
packages = [
"pkg/apis",
"pkg/apis/awsproviderconfig/v1beta1",
]
pruneopts = "UT"
revision = "87c20ae1e62a8e954843fa8a0e493b66caccc6c7"
revision = "987ca1c365a091232e9bc4db32c2fc6d04486219"
source = "https://github.com/openshift/cluster-api-provider-aws.git"
[[projects]]
@ -1305,7 +1317,7 @@
"pkg/apis/azureprovider/v1beta1",
]
pruneopts = "UT"
revision = "cbe6bdd8baecc773445fa76480869ce95340ba38"
revision = "a46da8ea986b1bba33511f3c1ed4ce03b2b4b142"
source = "https://github.com/openshift/cluster-api-provider-azure"
[[projects]]
@ -1364,7 +1376,7 @@
"github.com/openshift/api/config/v1",
"github.com/openshift/client-go/config/clientset/versioned",
"github.com/openshift/cluster-api/pkg/apis/machine/v1beta1",
"github.com/openshift/cluster-api/pkg/client/clientset_generated/clientset",
"github.com/openshift/cluster-api/pkg/client/clientset_generated/clientset/typed/machine/v1beta1",
"github.com/openshift/installer/data",
"github.com/openshift/installer/pkg/asset",
"github.com/openshift/installer/pkg/asset/cluster",
@ -1392,6 +1404,7 @@
"github.com/sirupsen/logrus",
"github.com/ugorji/go/codec",
"golang.org/x/crypto/ssh",
"golang.org/x/tools/cmd/goimports",
"golang.org/x/tools/go/ast/astutil",
"golang.org/x/tools/go/packages",
"k8s.io/apimachinery/pkg/apis/meta/v1",

Просмотреть файл

@ -1,4 +1,12 @@
required = ["github.com/jim-minter/go-cosmosdb/cmd/gencosmosdb", "github.com/alvaroloes/enumer"]
required = [
"github.com/alvaroloes/enumer",
"github.com/jim-minter/go-cosmosdb/cmd/gencosmosdb",
"golang.org/x/tools/cmd/goimports"
]
[[constraint]]
name = "github.com/alvaroloes/enumer"
version = "1.1.2"
[[override]]
name = "github.com/Azure/azure-sdk-for-go"
@ -57,14 +65,6 @@ required = ["github.com/jim-minter/go-cosmosdb/cmd/gencosmosdb", "github.com/alv
branch = "release-4.3"
source = "https://github.com/openshift/cluster-api-provider-azure"
[[constraint]]
name = "github.com/jim-minter/go-cosmosdb"
branch = "master"
[[constraint]]
name = "github.com/alvaroloes/enumer"
version = "1.1.2"
[prune]
go-tests = true
unused-packages = true

Просмотреть файл

@ -4,14 +4,21 @@ rp:
clean:
rm -f rp
generate:
go generate ./...
image:
go get github.com/openshift/imagebuilder/cmd/imagebuilder
imagebuilder -f Dockerfile -t rp:latest .
test: generate
test:
go generate ./...
go build ./...
gofmt -s -w cmd hack pkg
go run ./vendor/golang.org/x/tools/cmd/goimports -w -local=github.com/jim-minter/rp cmd hack pkg
go run ./hack/validate-imports/validate-imports.go cmd hack pkg
@[ -z "$$(ls pkg/util/*.go 2>/dev/null)" ] || (echo error: go files are not allowed in pkg/util, use a subpackage; exit 1)
@[ -z "$$(find -name "*:*")" ] || (echo error: filenames with colons are not allowed on Windows, please rename; exit 1)
go vet ./...
go test ./...
.PHONY: clean generate image rp test
.PHONY: rp clean image test

Просмотреть файл

@ -7,6 +7,7 @@ import (
"os/signal"
"syscall"
uuid "github.com/satori/go.uuid"
"github.com/sirupsen/logrus"
_ "github.com/jim-minter/rp/pkg/api/v20191231preview"
@ -14,7 +15,6 @@ import (
"github.com/jim-minter/rp/pkg/database"
"github.com/jim-minter/rp/pkg/env"
"github.com/jim-minter/rp/pkg/frontend"
uuid "github.com/satori/go.uuid"
)
var (

Просмотреть файл

@ -0,0 +1,140 @@
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"os"
"path/filepath"
"sort"
"strings"
)
const local = "github.com/jim-minter/rp"
type importSpecs []*ast.ImportSpec
func (is importSpecs) Len() int { return len(is) }
func (is importSpecs) Less(i, j int) bool { return is[i].Path.Value < is[j].Path.Value }
func (is importSpecs) Swap(i, j int) { is[i], is[j] = is[j], is[i] }
var _ sort.Interface = importSpecs{}
type importType int
// at most one import group of each type may exist in a validated source file,
// specifically in the order declared below
const (
importStd importType = 1 << iota // go standard library
importDot // "." imports (ginkgo and gomega)
importOther // non-local imports
importLocal // local imports
)
func typeForImport(imp *ast.ImportSpec) importType {
path := strings.Trim(imp.Path.Value, `"`)
switch {
case imp.Name != nil && imp.Name.Name == ".":
return importDot
case strings.HasPrefix(path, local+"/"):
return importLocal
case strings.ContainsRune(path, '.'):
return importOther
default:
return importStd
}
}
func validateImport(imp *ast.ImportSpec) (errs []error) {
path := strings.Trim(imp.Path.Value, `"`)
switch typeForImport(imp) {
case importDot:
switch path {
case "github.com/onsi/ginkgo",
"github.com/onsi/gomega",
"github.com/onsi/gomega/gstruct":
default:
errs = append(errs, fmt.Errorf("invalid . import %s", imp.Path.Value))
}
}
return
}
func check(path string) (errs []error) {
var fset token.FileSet
f, err := parser.ParseFile(&fset, path, nil, parser.ImportsOnly)
if err != nil {
return []error{err}
}
var groups [][]*ast.ImportSpec
for i, imp := range f.Imports {
// if there's more than one line between this and the previous import,
// break open a new import group
if i == 0 || fset.Position(f.Imports[i].Pos()).Line-fset.Position(f.Imports[i-1].Pos()).Line > 1 {
groups = append(groups, []*ast.ImportSpec{})
}
groups[len(groups)-1] = append(groups[len(groups)-1], imp)
}
// seenTypes holds a bitmask of the importTypes seen up to this point, so
// that we can detect duplicate groups. We can also detect misordered
// groups, because when we set a bit (say 0b0100), we actually set all the
// trailing bits (0b0111) as sentinels
var seenTypes importType
for groupnum, group := range groups {
if !sort.IsSorted(importSpecs(group)) {
errs = append(errs, fmt.Errorf("group %d: imports are not sorted", groupnum+1))
}
groupImportType := typeForImport(group[0])
if (seenTypes & groupImportType) != 0 { // check if single bit is already set...
errs = append(errs, fmt.Errorf("group %d: duplicate group or invalid group ordering", groupnum+1))
}
seenTypes |= groupImportType<<1 - 1 // ...but set all trailing bits
for _, imp := range group {
errs = append(errs, validateImport(imp)...)
}
for _, imp := range group {
if typeForImport(imp) != groupImportType {
errs = append(errs, fmt.Errorf("group %d: mixed import type", groupnum+1))
break
}
}
}
return
}
func main() {
var rv int
for _, path := range os.Args[1:] {
if err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() && strings.HasSuffix(path, ".go") {
for _, err := range check(path) {
fmt.Printf("%s: %v\n", path, err)
rv = 1
}
}
return nil
}); err != nil {
panic(err)
}
}
os.Exit(rv)
}

Просмотреть файл

@ -521,7 +521,7 @@ func (i *Installer) installResources(ctx context.Context, doc *api.OpenShiftClus
Identity: &compute.VirtualMachineIdentity{
Type: compute.ResourceIdentityTypeUserAssigned,
UserAssignedIdentities: map[string]*compute.VirtualMachineIdentityUserAssignedIdentitiesValue{
"[resourceId('Microsoft.ManagedIdentity/userAssignedIdentities', '" + doc.OpenShiftCluster.Properties.InfraID + "-identity')]": &compute.VirtualMachineIdentityUserAssignedIdentitiesValue{},
"[resourceId('Microsoft.ManagedIdentity/userAssignedIdentities', '" + doc.OpenShiftCluster.Properties.InfraID + "-identity')]": {},
},
},
Name: to.StringPtr(doc.OpenShiftCluster.Properties.InfraID + "-bootstrap"),
@ -581,7 +581,7 @@ func (i *Installer) installResources(ctx context.Context, doc *api.OpenShiftClus
Identity: &compute.VirtualMachineIdentity{
Type: compute.ResourceIdentityTypeUserAssigned,
UserAssignedIdentities: map[string]*compute.VirtualMachineIdentityUserAssignedIdentitiesValue{
"[resourceId('Microsoft.ManagedIdentity/userAssignedIdentities', '" + doc.OpenShiftCluster.Properties.InfraID + "-identity')]": &compute.VirtualMachineIdentityUserAssignedIdentitiesValue{},
"[resourceId('Microsoft.ManagedIdentity/userAssignedIdentities', '" + doc.OpenShiftCluster.Properties.InfraID + "-identity')]": {},
},
},
Zones: &[]string{

6
vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go сгенерированный поставляемый
Просмотреть файл

@ -3983,13 +3983,18 @@ var awsPartition = partition{
Protocols: []string{"https"},
},
Endpoints: endpoints{
"ap-east-1": endpoint{},
"ap-northeast-1": endpoint{},
"ap-northeast-2": endpoint{},
"ap-south-1": endpoint{},
"ap-southeast-1": endpoint{},
"ap-southeast-2": endpoint{},
"ca-central-1": endpoint{},
"eu-central-1": endpoint{},
"eu-north-1": endpoint{},
"eu-west-1": endpoint{},
"eu-west-2": endpoint{},
"eu-west-3": endpoint{},
"us-east-1": endpoint{},
"us-east-1-fips": endpoint{
Hostname: "translate-fips.us-east-1.amazonaws.com",
@ -4004,6 +4009,7 @@ var awsPartition = partition{
Region: "us-east-2",
},
},
"us-west-1": endpoint{},
"us-west-2": endpoint{},
"us-west-2-fips": endpoint{
Hostname: "translate-fips.us-west-2.amazonaws.com",

2
vendor/github.com/aws/aws-sdk-go/aws/version.go сгенерированный поставляемый
Просмотреть файл

@ -5,4 +5,4 @@ package aws
const SDKName = "aws-sdk-go"
// SDKVersion is the version of this SDK
const SDKVersion = "1.25.42"
const SDKVersion = "1.25.43"

1032
vendor/github.com/aws/aws-sdk-go/service/resourcegroupstaggingapi/api.go сгенерированный поставляемый

Разница между файлами не показана из-за своего большого размера Загрузить разницу

32
vendor/github.com/aws/aws-sdk-go/service/resourcegroupstaggingapi/doc.go сгенерированный поставляемый
Просмотреть файл

@ -16,16 +16,16 @@
// You can use the resource groups tagging API operations to complete the following
// tasks:
//
// * Tag and untag supported resources located in the specified region for
// the AWS account
// * Tag and untag supported resources located in the specified Region for
// the AWS account.
//
// * Use tag-based filters to search for resources located in the specified
// region for the AWS account
// Region for the AWS account.
//
// * List all existing tag keys in the specified region for the AWS account
// * List all existing tag keys in the specified Region for the AWS account.
//
// * List all existing values for the specified key in the specified region
// for the AWS account
// * List all existing values for the specified key in the specified Region
// for the AWS account.
//
// To use resource groups tagging API operations, you must add the following
// permissions to your IAM policy:
@ -53,7 +53,7 @@
//
// * API Gateway
//
// * AWS AppStream
// * Amazon AppStream
//
// * AWS AppSync
//
@ -105,7 +105,7 @@
//
// * AWS Database Migration Service
//
// * AWS Datasync
// * AWS DataSync
//
// * AWS Direct Connect
//
@ -141,10 +141,12 @@
//
// * Amazon FSx
//
// * Amazon Glacier
// * Amazon S3 Glacier
//
// * AWS Glue
//
// * Amazon GuardDuty
//
// * Amazon Inspector
//
// * AWS IoT Analytics
@ -155,6 +157,8 @@
//
// * AWS IoT Device Management
//
// * AWS IoT Events
//
// * AWS IoT Greengrass
//
// * AWS Key Management Service
@ -179,6 +183,10 @@
//
// * AWS OpsWorks
//
// * AWS Organizations
//
// * Amazon Quantum Ledger Database (QLDB)
//
// * Amazon RDS
//
// * Amazon Redshift
@ -199,18 +207,20 @@
//
// * AWS Secrets Manager
//
// * AWS Security Hub
//
// * AWS Service Catalog
//
// * Amazon Simple Notification Service (SNS)
//
// * Amazon Simple Queue Service (SQS)
//
// * AWS Simple System Manager (SSM)
//
// * AWS Step Functions
//
// * AWS Storage Gateway
//
// * AWS Systems Manager
//
// * AWS Transfer for SFTP
//
// * Amazon VPC

43
vendor/github.com/aws/aws-sdk-go/service/resourcegroupstaggingapi/errors.go сгенерированный поставляемый
Просмотреть файл

@ -4,6 +4,33 @@ package resourcegroupstaggingapi
const (
// ErrCodeConcurrentModificationException for service response error code
// "ConcurrentModificationException".
//
// The target of the operation is currently being modified by a different request.
// Try again later.
ErrCodeConcurrentModificationException = "ConcurrentModificationException"
// ErrCodeConstraintViolationException for service response error code
// "ConstraintViolationException".
//
// The request was denied because performing this operation violates a constraint.
//
// Some of the reasons in the following list might not apply to this specific
// operation.
//
// * You must meet the prerequisites for using tag policies. For information,
// see Prerequisites and Permissions for Using Tag Policies (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_tag-policies-prereqs.html)
// in the AWS Organizations User Guide.
//
// * You must enable the tag policies service principal (tagpolicies.tag.amazonaws.com)
// to integrate with AWS Organizations For information, see EnableAWSServiceAccess
// (http://docs.aws.amazon.com/organizations/latest/APIReference/API_EnableAWSServiceAccess.html).
//
// * You must have a tag policy attached to the organization root, an OU,
// or an account.
ErrCodeConstraintViolationException = "ConstraintViolationException"
// ErrCodeInternalServiceException for service response error code
// "InternalServiceException".
//
@ -14,8 +41,20 @@ const (
// ErrCodeInvalidParameterException for service response error code
// "InvalidParameterException".
//
// A parameter is missing or a malformed string or invalid or out-of-range value
// was supplied for the request parameter.
// This error indicates one of the following:
//
// * A parameter is missing.
//
// * A malformed string was supplied for the request parameter.
//
// * An out-of-range value was supplied for the request parameter.
//
// * The target ID is invalid, unsupported, or doesn't exist.
//
// * You can't access the Amazon S3 bucket for report storage. For more information,
// see Additional Requirements for Organization-wide Tag Compliance Reports
// (http://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_tag-policies-prereqs.html#bucket-policies-org-report)
// in the AWS Organizations User Guide.
ErrCodeInvalidParameterException = "InvalidParameterException"
// ErrCodePaginationTokenExpiredException for service response error code

2
vendor/github.com/gophercloud/gophercloud/CHANGELOG.md сгенерированный поставляемый
Просмотреть файл

@ -11,6 +11,8 @@ IMPROVEMENTS
* Added `networking/v2/extensions/fwaas_v2/rules.Delete` [GH-1771](https://github.com/gophercloud/gophercloud/pull/1771).
* Added `loadbalancer/v2/providers.List` [GH-1765](https://github.com/gophercloud/gophercloud/pull/1765).
* Added `networking/v2/extensions/fwaas_v2/rules.Get` [GH-1772](https://github.com/gophercloud/gophercloud/pull/1772).
* Added `networking/v2/extensions/fwaas_v2/rules.Update` [GH-1776](https://github.com/gophercloud/gophercloud/pull/1776).
* Added `networking/v2/extensions/fwaas_v2/rules.List` [GH-1783](https://github.com/gophercloud/gophercloud/pull/1783).
## 0.6.0 (October 17, 2019)

62
vendor/github.com/gophercloud/utils/openstack/clientconfig/results.go сгенерированный поставляемый
Просмотреть файл

@ -16,112 +16,112 @@ type Clouds struct {
// Cloud represents an entry in a clouds.yaml/public-clouds.yaml/secure.yaml file.
type Cloud struct {
Cloud string `yaml:"cloud" json:"cloud"`
Profile string `yaml:"profile" json:"profile"`
AuthInfo *AuthInfo `yaml:"auth" json:"auth"`
AuthType AuthType `yaml:"auth_type" json:"auth_type"`
RegionName string `yaml:"region_name" json:"region_name"`
Regions []interface{} `yaml:"regions" json:"regions"`
Cloud string `yaml:"cloud,omitempty" json:"cloud,omitempty"`
Profile string `yaml:"profile,omitempty" json:"profile,omitempty"`
AuthInfo *AuthInfo `yaml:"auth,omitempty" json:"auth,omitempty"`
AuthType AuthType `yaml:"auth_type,omitempty" json:"auth_type,omitempty"`
RegionName string `yaml:"region_name,omitempty" json:"region_name,omitempty"`
Regions []interface{} `yaml:"regions,omitempty" json:"regions,omitempty"`
// EndpointType and Interface both specify whether to use the public, internal,
// or admin interface of a service. They should be considered synonymous, but
// EndpointType will take precedence when both are specified.
EndpointType string `yaml:"endpoint_type" json:"endpoint_type"`
Interface string `yaml:"interface" json:"interface"`
EndpointType string `yaml:"endpoint_type,omitempty" json:"endpoint_type,omitempty"`
Interface string `yaml:"interface,omitempty" json:"interface,omitempty"`
// API Version overrides.
IdentityAPIVersion string `yaml:"identity_api_version" json:"identity_api_version"`
VolumeAPIVersion string `yaml:"volume_api_version" json:"volume_api_version"`
IdentityAPIVersion string `yaml:"identity_api_version,omitempty" json:"identity_api_version,omitempty"`
VolumeAPIVersion string `yaml:"volume_api_version,omitempty" json:"volume_api_version,omitempty"`
// Verify whether or not SSL API requests should be verified.
Verify *bool `yaml:"verify" json:"verify"`
Verify *bool `yaml:"verify,omitempty" json:"verify,omitempty"`
// CACertFile a path to a CA Cert bundle that can be used as part of
// verifying SSL API requests.
CACertFile string `yaml:"cacert" json:"cacert"`
CACertFile string `yaml:"cacert,omitempty" json:"cacert,omitempty"`
// ClientCertFile a path to a client certificate to use as part of the SSL
// transaction.
ClientCertFile string `yaml:"cert" json:"cert"`
ClientCertFile string `yaml:"cert,omitempty" json:"cert,omitempty"`
// ClientKeyFile a path to a client key to use as part of the SSL
// transaction.
ClientKeyFile string `yaml:"key" json:"key"`
ClientKeyFile string `yaml:"key,omitempty" json:"key,omitempty"`
}
// AuthInfo represents the auth section of a cloud entry or
// auth options entered explicitly in ClientOpts.
type AuthInfo struct {
// AuthURL is the keystone/identity endpoint URL.
AuthURL string `yaml:"auth_url" json:"auth_url"`
AuthURL string `yaml:"auth_url,omitempty" json:"auth_url,omitempty"`
// Token is a pre-generated authentication token.
Token string `yaml:"token" json:"token"`
Token string `yaml:"token,omitempty" json:"token,omitempty"`
// Username is the username of the user.
Username string `yaml:"username" json:"username"`
Username string `yaml:"username,omitempty" json:"username,omitempty"`
// UserID is the unique ID of a user.
UserID string `yaml:"user_id" json:"user_id"`
UserID string `yaml:"user_id,omitempty" json:"user_id,omitempty"`
// Password is the password of the user.
Password string `yaml:"password" json:"password"`
Password string `yaml:"password,omitempty" json:"password,omitempty"`
// Application Credential ID to login with.
ApplicationCredentialID string `yaml:"application_credential_id" json:"application_credential_id"`
ApplicationCredentialID string `yaml:"application_credential_id,omitempty" json:"application_credential_id,omitempty"`
// Application Credential name to login with.
ApplicationCredentialName string `yaml:"application_credential_name" json:"application_credential_name"`
ApplicationCredentialName string `yaml:"application_credential_name,omitempty" json:"application_credential_name,omitempty"`
// Application Credential secret to login with.
ApplicationCredentialSecret string `yaml:"application_credential_secret" json:"application_credential_secret"`
ApplicationCredentialSecret string `yaml:"application_credential_secret,omitempty" json:"application_credential_secret,omitempty"`
// ProjectName is the common/human-readable name of a project.
// Users can be scoped to a project.
// ProjectName on its own is not enough to ensure a unique scope. It must
// also be combined with either a ProjectDomainName or ProjectDomainID.
// ProjectName cannot be combined with ProjectID in a scope.
ProjectName string `yaml:"project_name" json:"project_name"`
ProjectName string `yaml:"project_name,omitempty" json:"project_name,omitempty"`
// ProjectID is the unique ID of a project.
// It can be used to scope a user to a specific project.
ProjectID string `yaml:"project_id" json:"project_id"`
ProjectID string `yaml:"project_id,omitempty" json:"project_id,omitempty"`
// UserDomainName is the name of the domain where a user resides.
// It is used to identify the source domain of a user.
UserDomainName string `yaml:"user_domain_name" json:"user_domain_name"`
UserDomainName string `yaml:"user_domain_name,omitempty" json:"user_domain_name,omitempty"`
// UserDomainID is the unique ID of the domain where a user resides.
// It is used to identify the source domain of a user.
UserDomainID string `yaml:"user_domain_id" json:"user_domain_id"`
UserDomainID string `yaml:"user_domain_id,omitempty" json:"user_domain_id,omitempty"`
// ProjectDomainName is the name of the domain where a project resides.
// It is used to identify the source domain of a project.
// ProjectDomainName can be used in addition to a ProjectName when scoping
// a user to a specific project.
ProjectDomainName string `yaml:"project_domain_name" json:"project_domain_name"`
ProjectDomainName string `yaml:"project_domain_name,omitempty" json:"project_domain_name,omitempty"`
// ProjectDomainID is the name of the domain where a project resides.
// It is used to identify the source domain of a project.
// ProjectDomainID can be used in addition to a ProjectName when scoping
// a user to a specific project.
ProjectDomainID string `yaml:"project_domain_id" json:"project_domain_id"`
ProjectDomainID string `yaml:"project_domain_id,omitempty" json:"project_domain_id,omitempty"`
// DomainName is the name of a domain which can be used to identify the
// source domain of either a user or a project.
// If UserDomainName and ProjectDomainName are not specified, then DomainName
// is used as a default choice.
// It can also be used be used to specify a domain-only scope.
DomainName string `yaml:"domain_name" json:"domain_name"`
DomainName string `yaml:"domain_name,omitempty" json:"domain_name,omitempty"`
// DomainID is the unique ID of a domain which can be used to identify the
// source domain of eitehr a user or a project.
// If UserDomainID and ProjectDomainID are not specified, then DomainID is
// used as a default choice.
// It can also be used be used to specify a domain-only scope.
DomainID string `yaml:"domain_id" json:"domain_id"`
DomainID string `yaml:"domain_id,omitempty" json:"domain_id,omitempty"`
// DefaultDomain is the domain ID to fall back on if no other domain has
// been specified and a domain is required for scope.
DefaultDomain string `yaml:"default_domain" json:"default_domain"`
DefaultDomain string `yaml:"default_domain,omitempty" json:"default_domain,omitempty"`
}

Просмотреть файл

@ -30,6 +30,8 @@ spec:
metadata:
type: object
spec:
description: spec is the specification of the desired behavior of the Kubernetes
API Server
properties:
failedRevisionLimit:
description: failedRevisionLimit is the number of failed static pod
@ -84,6 +86,8 @@ spec:
x-kubernetes-preserve-unknown-fields: true
type: object
status:
description: status is the most recently observed status of the Kubernetes
API Server
properties:
conditions:
description: conditions is a list of conditions and their status

Просмотреть файл

@ -32,6 +32,8 @@ spec:
metadata:
type: object
spec:
description: spec is the specification of the desired behavior of the Kubernetes
Controller Manager
properties:
failedRevisionLimit:
description: failedRevisionLimit is the number of failed static pod
@ -86,6 +88,8 @@ spec:
x-kubernetes-preserve-unknown-fields: true
type: object
status:
description: status is the most recently observed status of the Kubernetes
Controller Manager
properties:
conditions:
description: conditions is a list of conditions and their status

Просмотреть файл

@ -32,6 +32,8 @@ spec:
metadata:
type: object
spec:
description: spec is the specification of the desired behavior of the Kubernetes
Scheduler
properties:
failedRevisionLimit:
description: failedRevisionLimit is the number of failed static pod
@ -86,6 +88,8 @@ spec:
x-kubernetes-preserve-unknown-fields: true
type: object
status:
description: status is the most recently observed status of the Kubernetes
Scheduler
properties:
conditions:
description: conditions is a list of conditions and their status

3
vendor/github.com/openshift/api/operator/v1/types_kubeapiserver.go сгенерированный поставляемый
Просмотреть файл

@ -13,9 +13,12 @@ type KubeAPIServer struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata"`
// spec is the specification of the desired behavior of the Kubernetes API Server
// +kubebuilder:validation:Required
// +required
Spec KubeAPIServerSpec `json:"spec"`
// status is the most recently observed status of the Kubernetes API Server
// +optional
Status KubeAPIServerStatus `json:"status"`
}

3
vendor/github.com/openshift/api/operator/v1/types_kubecontrollermanager.go сгенерированный поставляемый
Просмотреть файл

@ -13,9 +13,12 @@ type KubeControllerManager struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata"`
// spec is the specification of the desired behavior of the Kubernetes Controller Manager
// +kubebuilder:validation:Required
// +required
Spec KubeControllerManagerSpec `json:"spec"`
// status is the most recently observed status of the Kubernetes Controller Manager
// +optional
Status KubeControllerManagerStatus `json:"status"`
}

3
vendor/github.com/openshift/api/operator/v1/types_scheduler.go сгенерированный поставляемый
Просмотреть файл

@ -13,9 +13,12 @@ type KubeScheduler struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata"`
// spec is the specification of the desired behavior of the Kubernetes Scheduler
// +kubebuilder:validation:Required
// +required
Spec KubeSchedulerSpec `json:"spec"`
// status is the most recently observed status of the Kubernetes Scheduler
// +optional
Status KubeSchedulerStatus `json:"status"`
}

12
vendor/github.com/openshift/api/operator/v1/zz_generated.swagger_doc_generated.go сгенерированный поставляемый
Просмотреть файл

@ -345,7 +345,9 @@ func (PrivateStrategy) SwaggerDoc() map[string]string {
}
var map_KubeAPIServer = map[string]string{
"": "KubeAPIServer provides information to configure an operator to manage kube-apiserver.",
"": "KubeAPIServer provides information to configure an operator to manage kube-apiserver.",
"spec": "spec is the specification of the desired behavior of the Kubernetes API Server",
"status": "status is the most recently observed status of the Kubernetes API Server",
}
func (KubeAPIServer) SwaggerDoc() map[string]string {
@ -362,7 +364,9 @@ func (KubeAPIServerList) SwaggerDoc() map[string]string {
}
var map_KubeControllerManager = map[string]string{
"": "KubeControllerManager provides information to configure an operator to manage kube-controller-manager.",
"": "KubeControllerManager provides information to configure an operator to manage kube-controller-manager.",
"spec": "spec is the specification of the desired behavior of the Kubernetes Controller Manager",
"status": "status is the most recently observed status of the Kubernetes Controller Manager",
}
func (KubeControllerManager) SwaggerDoc() map[string]string {
@ -635,7 +639,9 @@ func (OpenShiftControllerManagerList) SwaggerDoc() map[string]string {
}
var map_KubeScheduler = map[string]string{
"": "KubeScheduler provides information to configure an operator to manage scheduler.",
"": "KubeScheduler provides information to configure an operator to manage scheduler.",
"spec": "spec is the specification of the desired behavior of the Kubernetes Scheduler",
"status": "status is the most recently observed status of the Kubernetes Scheduler",
}
func (KubeScheduler) SwaggerDoc() map[string]string {

111
vendor/github.com/openshift/cluster-api/pkg/client/clientset_generated/clientset/clientset.go сгенерированный поставляемый
Просмотреть файл

@ -1,111 +0,0 @@
/*
Copyright 2018 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.
*/
// Code generated by main. DO NOT EDIT.
package clientset
import (
"fmt"
clusterv1alpha1 "github.com/openshift/cluster-api/pkg/client/clientset_generated/clientset/typed/cluster/v1alpha1"
machinev1beta1 "github.com/openshift/cluster-api/pkg/client/clientset_generated/clientset/typed/machine/v1beta1"
discovery "k8s.io/client-go/discovery"
rest "k8s.io/client-go/rest"
flowcontrol "k8s.io/client-go/util/flowcontrol"
)
type Interface interface {
Discovery() discovery.DiscoveryInterface
ClusterV1alpha1() clusterv1alpha1.ClusterV1alpha1Interface
MachineV1beta1() machinev1beta1.MachineV1beta1Interface
}
// Clientset contains the clients for groups. Each group has exactly one
// version included in a Clientset.
type Clientset struct {
*discovery.DiscoveryClient
clusterV1alpha1 *clusterv1alpha1.ClusterV1alpha1Client
machineV1beta1 *machinev1beta1.MachineV1beta1Client
}
// ClusterV1alpha1 retrieves the ClusterV1alpha1Client
func (c *Clientset) ClusterV1alpha1() clusterv1alpha1.ClusterV1alpha1Interface {
return c.clusterV1alpha1
}
// MachineV1beta1 retrieves the MachineV1beta1Client
func (c *Clientset) MachineV1beta1() machinev1beta1.MachineV1beta1Interface {
return c.machineV1beta1
}
// Discovery retrieves the DiscoveryClient
func (c *Clientset) Discovery() discovery.DiscoveryInterface {
if c == nil {
return nil
}
return c.DiscoveryClient
}
// NewForConfig creates a new Clientset for the given config.
// If config's RateLimiter is not set and QPS and Burst are acceptable,
// NewForConfig will generate a rate-limiter in configShallowCopy.
func NewForConfig(c *rest.Config) (*Clientset, error) {
configShallowCopy := *c
if configShallowCopy.RateLimiter == nil && configShallowCopy.QPS > 0 {
if configShallowCopy.Burst <= 0 {
return nil, fmt.Errorf("Burst is required to be greater than 0 when RateLimiter is not set and QPS is set to greater than 0")
}
configShallowCopy.RateLimiter = flowcontrol.NewTokenBucketRateLimiter(configShallowCopy.QPS, configShallowCopy.Burst)
}
var cs Clientset
var err error
cs.clusterV1alpha1, err = clusterv1alpha1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.machineV1beta1, err = machinev1beta1.NewForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
cs.DiscoveryClient, err = discovery.NewDiscoveryClientForConfig(&configShallowCopy)
if err != nil {
return nil, err
}
return &cs, nil
}
// NewForConfigOrDie creates a new Clientset for the given config and
// panics if there is an error in the config.
func NewForConfigOrDie(c *rest.Config) *Clientset {
var cs Clientset
cs.clusterV1alpha1 = clusterv1alpha1.NewForConfigOrDie(c)
cs.machineV1beta1 = machinev1beta1.NewForConfigOrDie(c)
cs.DiscoveryClient = discovery.NewDiscoveryClientForConfigOrDie(c)
return &cs
}
// New creates a new Clientset for the given RESTClient.
func New(c rest.Interface) *Clientset {
var cs Clientset
cs.clusterV1alpha1 = clusterv1alpha1.New(c)
cs.machineV1beta1 = machinev1beta1.New(c)
cs.DiscoveryClient = discovery.NewDiscoveryClient(c)
return &cs
}

20
vendor/github.com/openshift/cluster-api/pkg/client/clientset_generated/clientset/doc.go сгенерированный поставляемый
Просмотреть файл

@ -1,20 +0,0 @@
/*
Copyright 2018 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.
*/
// Code generated by main. DO NOT EDIT.
// This package has the automatically generated clientset.
package clientset

Просмотреть файл

@ -1,191 +0,0 @@
/*
Copyright 2018 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.
*/
// Code generated by main. DO NOT EDIT.
package v1alpha1
import (
"time"
v1alpha1 "github.com/openshift/cluster-api/pkg/apis/cluster/v1alpha1"
scheme "github.com/openshift/cluster-api/pkg/client/clientset_generated/clientset/scheme"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
types "k8s.io/apimachinery/pkg/types"
watch "k8s.io/apimachinery/pkg/watch"
rest "k8s.io/client-go/rest"
)
// ClustersGetter has a method to return a ClusterInterface.
// A group's client should implement this interface.
type ClustersGetter interface {
Clusters(namespace string) ClusterInterface
}
// ClusterInterface has methods to work with Cluster resources.
type ClusterInterface interface {
Create(*v1alpha1.Cluster) (*v1alpha1.Cluster, error)
Update(*v1alpha1.Cluster) (*v1alpha1.Cluster, error)
UpdateStatus(*v1alpha1.Cluster) (*v1alpha1.Cluster, error)
Delete(name string, options *v1.DeleteOptions) error
DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error
Get(name string, options v1.GetOptions) (*v1alpha1.Cluster, error)
List(opts v1.ListOptions) (*v1alpha1.ClusterList, error)
Watch(opts v1.ListOptions) (watch.Interface, error)
Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.Cluster, err error)
ClusterExpansion
}
// clusters implements ClusterInterface
type clusters struct {
client rest.Interface
ns string
}
// newClusters returns a Clusters
func newClusters(c *ClusterV1alpha1Client, namespace string) *clusters {
return &clusters{
client: c.RESTClient(),
ns: namespace,
}
}
// Get takes name of the cluster, and returns the corresponding cluster object, and an error if there is any.
func (c *clusters) Get(name string, options v1.GetOptions) (result *v1alpha1.Cluster, err error) {
result = &v1alpha1.Cluster{}
err = c.client.Get().
Namespace(c.ns).
Resource("clusters").
Name(name).
VersionedParams(&options, scheme.ParameterCodec).
Do().
Into(result)
return
}
// List takes label and field selectors, and returns the list of Clusters that match those selectors.
func (c *clusters) List(opts v1.ListOptions) (result *v1alpha1.ClusterList, err error) {
var timeout time.Duration
if opts.TimeoutSeconds != nil {
timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
}
result = &v1alpha1.ClusterList{}
err = c.client.Get().
Namespace(c.ns).
Resource("clusters").
VersionedParams(&opts, scheme.ParameterCodec).
Timeout(timeout).
Do().
Into(result)
return
}
// Watch returns a watch.Interface that watches the requested clusters.
func (c *clusters) Watch(opts v1.ListOptions) (watch.Interface, error) {
var timeout time.Duration
if opts.TimeoutSeconds != nil {
timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
}
opts.Watch = true
return c.client.Get().
Namespace(c.ns).
Resource("clusters").
VersionedParams(&opts, scheme.ParameterCodec).
Timeout(timeout).
Watch()
}
// Create takes the representation of a cluster and creates it. Returns the server's representation of the cluster, and an error, if there is any.
func (c *clusters) Create(cluster *v1alpha1.Cluster) (result *v1alpha1.Cluster, err error) {
result = &v1alpha1.Cluster{}
err = c.client.Post().
Namespace(c.ns).
Resource("clusters").
Body(cluster).
Do().
Into(result)
return
}
// Update takes the representation of a cluster and updates it. Returns the server's representation of the cluster, and an error, if there is any.
func (c *clusters) Update(cluster *v1alpha1.Cluster) (result *v1alpha1.Cluster, err error) {
result = &v1alpha1.Cluster{}
err = c.client.Put().
Namespace(c.ns).
Resource("clusters").
Name(cluster.Name).
Body(cluster).
Do().
Into(result)
return
}
// UpdateStatus was generated because the type contains a Status member.
// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().
func (c *clusters) UpdateStatus(cluster *v1alpha1.Cluster) (result *v1alpha1.Cluster, err error) {
result = &v1alpha1.Cluster{}
err = c.client.Put().
Namespace(c.ns).
Resource("clusters").
Name(cluster.Name).
SubResource("status").
Body(cluster).
Do().
Into(result)
return
}
// Delete takes name of the cluster and deletes it. Returns an error if one occurs.
func (c *clusters) Delete(name string, options *v1.DeleteOptions) error {
return c.client.Delete().
Namespace(c.ns).
Resource("clusters").
Name(name).
Body(options).
Do().
Error()
}
// DeleteCollection deletes a collection of objects.
func (c *clusters) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error {
var timeout time.Duration
if listOptions.TimeoutSeconds != nil {
timeout = time.Duration(*listOptions.TimeoutSeconds) * time.Second
}
return c.client.Delete().
Namespace(c.ns).
Resource("clusters").
VersionedParams(&listOptions, scheme.ParameterCodec).
Timeout(timeout).
Body(options).
Do().
Error()
}
// Patch applies the patch and returns the patched cluster.
func (c *clusters) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.Cluster, err error) {
result = &v1alpha1.Cluster{}
err = c.client.Patch(pt).
Namespace(c.ns).
Resource("clusters").
SubResource(subresources...).
Name(name).
Body(data).
Do().
Into(result)
return
}

Просмотреть файл

@ -1,89 +0,0 @@
/*
Copyright 2018 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.
*/
// Code generated by main. DO NOT EDIT.
package v1alpha1
import (
v1alpha1 "github.com/openshift/cluster-api/pkg/apis/cluster/v1alpha1"
"github.com/openshift/cluster-api/pkg/client/clientset_generated/clientset/scheme"
rest "k8s.io/client-go/rest"
)
type ClusterV1alpha1Interface interface {
RESTClient() rest.Interface
ClustersGetter
}
// ClusterV1alpha1Client is used to interact with features provided by the cluster.k8s.io group.
type ClusterV1alpha1Client struct {
restClient rest.Interface
}
func (c *ClusterV1alpha1Client) Clusters(namespace string) ClusterInterface {
return newClusters(c, namespace)
}
// NewForConfig creates a new ClusterV1alpha1Client for the given config.
func NewForConfig(c *rest.Config) (*ClusterV1alpha1Client, error) {
config := *c
if err := setConfigDefaults(&config); err != nil {
return nil, err
}
client, err := rest.RESTClientFor(&config)
if err != nil {
return nil, err
}
return &ClusterV1alpha1Client{client}, nil
}
// NewForConfigOrDie creates a new ClusterV1alpha1Client for the given config and
// panics if there is an error in the config.
func NewForConfigOrDie(c *rest.Config) *ClusterV1alpha1Client {
client, err := NewForConfig(c)
if err != nil {
panic(err)
}
return client
}
// New creates a new ClusterV1alpha1Client for the given RESTClient.
func New(c rest.Interface) *ClusterV1alpha1Client {
return &ClusterV1alpha1Client{c}
}
func setConfigDefaults(config *rest.Config) error {
gv := v1alpha1.SchemeGroupVersion
config.GroupVersion = &gv
config.APIPath = "/apis"
config.NegotiatedSerializer = scheme.Codecs.WithoutConversion()
if config.UserAgent == "" {
config.UserAgent = rest.DefaultKubernetesUserAgent()
}
return nil
}
// RESTClient returns a RESTClient that is used to communicate
// with API server by this client implementation.
func (c *ClusterV1alpha1Client) RESTClient() rest.Interface {
if c == nil {
return nil
}
return c.restClient
}

Просмотреть файл

@ -1,20 +0,0 @@
/*
Copyright 2018 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.
*/
// Code generated by main. DO NOT EDIT.
// This package has the automatically generated typed clients.
package v1alpha1

201
vendor/github.com/openshift/machine-api-operator/LICENSE сгенерированный поставляемый Normal file
Просмотреть файл

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.

3
vendor/github.com/openshift/machine-api-operator/pkg/apis/machine/register.go сгенерированный поставляемый Normal file
Просмотреть файл

@ -0,0 +1,3 @@
package healthchecking
const GroupName = "machine.openshift.io"

Просмотреть файл

@ -14,8 +14,21 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by main. DO NOT EDIT.
package v1beta1
package v1alpha1
import (
"k8s.io/apimachinery/pkg/runtime"
)
type ClusterExpansion interface{}
// ProviderSpec defines the configuration to use during node creation.
type ProviderSpec struct {
// No more than one of the following may be specified.
// Value is an inlined, serialized representation of the resource
// configuration. It is recommended that providers maintain their own
// versioned API types that should be serialized/deserialized from this
// field, akin to component config.
// +optional
Value *runtime.RawExtension `json:"value,omitempty"`
}

121
vendor/github.com/openshift/machine-api-operator/pkg/apis/machine/v1beta1/consts.go сгенерированный поставляемый Normal file
Просмотреть файл

@ -0,0 +1,121 @@
/*
Copyright 2018 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 v1beta1
// Constants aren't automatically generated for unversioned packages.
// Instead share the same constant for all versioned packages
type MachineStatusError string
const (
// Represents that the combination of configuration in the MachineSpec
// is not supported by this cluster. This is not a transient error, but
// indicates a state that must be fixed before progress can be made.
//
// Example: the ProviderSpec specifies an instance type that doesn't exist,
InvalidConfigurationMachineError MachineStatusError = "InvalidConfiguration"
// This indicates that the MachineSpec has been updated in a way that
// is not supported for reconciliation on this cluster. The spec may be
// completely valid from a configuration standpoint, but the controller
// does not support changing the real world state to match the new
// spec.
//
// Example: the responsible controller is not capable of changing the
// container runtime from docker to rkt.
UnsupportedChangeMachineError MachineStatusError = "UnsupportedChange"
// This generally refers to exceeding one's quota in a cloud provider,
// or running out of physical machines in an on-premise environment.
InsufficientResourcesMachineError MachineStatusError = "InsufficientResources"
// There was an error while trying to create a Node to match this
// Machine. This may indicate a transient problem that will be fixed
// automatically with time, such as a service outage, or a terminal
// error during creation that doesn't match a more specific
// MachineStatusError value.
//
// Example: timeout trying to connect to GCE.
CreateMachineError MachineStatusError = "CreateError"
// There was an error while trying to update a Node that this
// Machine represents. This may indicate a transient problem that will be
// fixed automatically with time, such as a service outage,
//
// Example: error updating load balancers
UpdateMachineError MachineStatusError = "UpdateError"
// An error was encountered while trying to delete the Node that this
// Machine represents. This could be a transient or terminal error, but
// will only be observable if the provider's Machine controller has
// added a finalizer to the object to more gracefully handle deletions.
//
// Example: cannot resolve EC2 IP address.
DeleteMachineError MachineStatusError = "DeleteError"
// This error indicates that the machine did not join the cluster
// as a new node within the expected timeframe after instance
// creation at the provider succeeded
//
// Example use case: A controller that deletes Machines which do
// not result in a Node joining the cluster within a given timeout
// and that are managed by a MachineSet
JoinClusterTimeoutMachineError = "JoinClusterTimeoutError"
)
type ClusterStatusError string
const (
// InvalidConfigurationClusterError indicates that the cluster
// configuration is invalid.
InvalidConfigurationClusterError ClusterStatusError = "InvalidConfiguration"
// UnsupportedChangeClusterError indicates that the cluster
// spec has been updated in an unsupported way. That cannot be
// reconciled.
UnsupportedChangeClusterError ClusterStatusError = "UnsupportedChange"
// CreateClusterError indicates that an error was encountered
// when trying to create the cluster.
CreateClusterError ClusterStatusError = "CreateError"
// UpdateClusterError indicates that an error was encountered
// when trying to update the cluster.
UpdateClusterError ClusterStatusError = "UpdateError"
// DeleteClusterError indicates that an error was encountered
// when trying to delete the cluster.
DeleteClusterError ClusterStatusError = "DeleteError"
)
type MachineSetStatusError string
const (
// Represents that the combination of configuration in the MachineTemplateSpec
// is not supported by this cluster. This is not a transient error, but
// indicates a state that must be fixed before progress can be made.
//
// Example: the ProviderSpec specifies an instance type that doesn't exist.
InvalidConfigurationMachineSetError MachineSetStatusError = "InvalidConfiguration"
)
type MachineDeploymentStrategyType string
const (
// Replace the old MachineSet by new one using rolling update
// i.e. gradually scale down the old MachineSet and scale up the new one.
RollingUpdateMachineDeploymentStrategyType MachineDeploymentStrategyType = "RollingUpdate"
)

4
vendor/github.com/openshift/machine-api-operator/pkg/apis/machine/v1beta1/doc.go сгенерированный поставляемый Normal file
Просмотреть файл

@ -0,0 +1,4 @@
// Package v1alpha1 contains API Schema definitions for the healthchecking v1beta1 API group
// +k8s:deepcopy-gen=package,register
// +groupName=machine.openshift.io
package v1beta1

219
vendor/github.com/openshift/machine-api-operator/pkg/apis/machine/v1beta1/machine_types.go сгенерированный поставляемый Normal file
Просмотреть файл

@ -0,0 +1,219 @@
/*
Copyright 2018 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 v1beta1
import (
"fmt"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/validation/field"
)
const (
// MachineFinalizer is set on PrepareForCreate callback.
MachineFinalizer = "machine.machine.openshift.io"
// MachineClusterLabelName is the label set on machines linked to a cluster.
MachineClusterLabelName = "cluster.k8s.io/cluster-name"
// MachineClusterIDLabel is the label that a machine must have to identify the
// cluster to which it belongs.
MachineClusterIDLabel = "machine.openshift.io/cluster-api-cluster"
)
// +genclient
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
/// [Machine]
// Machine is the Schema for the machines API
// +k8s:openapi-gen=true
// +kubebuilder:subresource:status
// +kubebuilder:printcolumn:name="Phase",type="string",JSONPath=".status.phase",description="Phase of machine"
// +kubebuilder:printcolumn:name="Type",type="string",JSONPath=".metadata.labels['machine\\.openshift\\.io/instance-type']",description="Type of instance"
// +kubebuilder:printcolumn:name="Region",type="string",JSONPath=".metadata.labels['machine\\.openshift\\.io/region']",description="Region associated with machine"
// +kubebuilder:printcolumn:name="Zone",type="string",JSONPath=".metadata.labels['machine\\.openshift\\.io/zone']",description="Zone associated with machine"
// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp",description="Machine age"
// +kubebuilder:printcolumn:name="Node",type="string",JSONPath=".status.nodeRef.name",description="Node associated with machine",priority=1
// +kubebuilder:printcolumn:name="ProviderID",type="string",JSONPath=".spec.providerID",description="Provider ID of machine created in cloud provider",priority=1
// +kubebuilder:printcolumn:name="State",type="string",JSONPath=".metadata.annotations['machine\\.openshift\\.io/instance-state']",description="State of instance",priority=1
type Machine struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec MachineSpec `json:"spec,omitempty"`
Status MachineStatus `json:"status,omitempty"`
}
/// [Machine]
/// [MachineSpec]
// MachineSpec defines the desired state of Machine
type MachineSpec struct {
// ObjectMeta will autopopulate the Node created. Use this to
// indicate what labels, annotations, name prefix, etc., should be used
// when creating the Node.
// +optional
metav1.ObjectMeta `json:"metadata,omitempty"`
// The list of the taints to be applied to the corresponding Node in additive
// manner. This list will not overwrite any other taints added to the Node on
// an ongoing basis by other entities. These taints should be actively reconciled
// e.g. if you ask the machine controller to apply a taint and then manually remove
// the taint the machine controller will put it back) but not have the machine controller
// remove any taints
// +optional
Taints []corev1.Taint `json:"taints,omitempty"`
// ProviderSpec details Provider-specific configuration to use during node creation.
// +optional
ProviderSpec ProviderSpec `json:"providerSpec"`
// ProviderID is the identification ID of the machine provided by the provider.
// This field must match the provider ID as seen on the node object corresponding to this machine.
// This field is required by higher level consumers of cluster-api. Example use case is cluster autoscaler
// with cluster-api as provider. Clean-up logic in the autoscaler compares machines to nodes to find out
// machines at provider which could not get registered as Kubernetes nodes. With cluster-api as a
// generic out-of-tree provider for autoscaler, this field is required by autoscaler to be
// able to have a provider view of the list of machines. Another list of nodes is queried from the k8s apiserver
// and then a comparison is done to find out unregistered machines and are marked for delete.
// This field will be set by the actuators and consumed by higher level entities like autoscaler that will
// be interfacing with cluster-api as generic provider.
// +optional
ProviderID *string `json:"providerID,omitempty"`
}
/// [MachineSpec]
/// [MachineStatus]
// MachineStatus defines the observed state of Machine
type MachineStatus struct {
// NodeRef will point to the corresponding Node if it exists.
// +optional
NodeRef *corev1.ObjectReference `json:"nodeRef,omitempty"`
// LastUpdated identifies when this status was last observed.
// +optional
LastUpdated *metav1.Time `json:"lastUpdated,omitempty"`
// ErrorReason will be set in the event that there is a terminal problem
// reconciling the Machine and will contain a succinct value suitable
// for machine interpretation.
//
// This field should not be set for transitive errors that a controller
// faces that are expected to be fixed automatically over
// time (like service outages), but instead indicate that something is
// fundamentally wrong with the Machine's spec or the configuration of
// the controller, and that manual intervention is required. Examples
// of terminal errors would be invalid combinations of settings in the
// spec, values that are unsupported by the controller, or the
// responsible controller itself being critically misconfigured.
//
// Any transient errors that occur during the reconciliation of Machines
// can be added as events to the Machine object and/or logged in the
// controller's output.
// +optional
ErrorReason *MachineStatusError `json:"errorReason,omitempty"`
// ErrorMessage will be set in the event that there is a terminal problem
// reconciling the Machine and will contain a more verbose string suitable
// for logging and human consumption.
//
// This field should not be set for transitive errors that a controller
// faces that are expected to be fixed automatically over
// time (like service outages), but instead indicate that something is
// fundamentally wrong with the Machine's spec or the configuration of
// the controller, and that manual intervention is required. Examples
// of terminal errors would be invalid combinations of settings in the
// spec, values that are unsupported by the controller, or the
// responsible controller itself being critically misconfigured.
//
// Any transient errors that occur during the reconciliation of Machines
// can be added as events to the Machine object and/or logged in the
// controller's output.
// +optional
ErrorMessage *string `json:"errorMessage,omitempty"`
// ProviderStatus details a Provider-specific status.
// It is recommended that providers maintain their
// own versioned API types that should be
// serialized/deserialized from this field.
// +optional
ProviderStatus *runtime.RawExtension `json:"providerStatus,omitempty"`
// Addresses is a list of addresses assigned to the machine. Queried from cloud provider, if available.
// +optional
Addresses []corev1.NodeAddress `json:"addresses,omitempty"`
// LastOperation describes the last-operation performed by the machine-controller.
// This API should be useful as a history in terms of the latest operation performed on the
// specific machine. It should also convey the state of the latest-operation for example if
// it is still on-going, failed or completed successfully.
// +optional
LastOperation *LastOperation `json:"lastOperation,omitempty"`
// Phase represents the current phase of machine actuation.
// E.g. Pending, Running, Terminating, Failed etc.
// +optional
Phase *string `json:"phase,omitempty"`
}
// LastOperation represents the detail of the last performed operation on the MachineObject.
type LastOperation struct {
// Description is the human-readable description of the last operation.
Description *string `json:"description,omitempty"`
// LastUpdated is the timestamp at which LastOperation API was last-updated.
LastUpdated *metav1.Time `json:"lastUpdated,omitempty"`
// State is the current status of the last performed operation.
// E.g. Processing, Failed, Successful etc
State *string `json:"state,omitempty"`
// Type is the type of operation which was last performed.
// E.g. Create, Delete, Update etc
Type *string `json:"type,omitempty"`
}
/// [MachineVersionInfo]
func (m *Machine) Validate() field.ErrorList {
errors := field.ErrorList{}
// validate spec.labels
fldPath := field.NewPath("spec")
if m.Labels[MachineClusterIDLabel] == "" {
errors = append(errors, field.Invalid(fldPath.Child("labels"), m.Labels, fmt.Sprintf("missing %v label.", MachineClusterIDLabel)))
}
// validate provider config is set
if m.Spec.ProviderSpec.Value == nil {
errors = append(errors, field.Invalid(fldPath.Child("spec").Child("providerspec"), m.Spec.ProviderSpec, "value field must be set"))
}
return errors
}
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// MachineList contains a list of Machine
type MachineList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []Machine `json:"items"`
}

89
vendor/github.com/openshift/machine-api-operator/pkg/apis/machine/v1beta1/machinehealthcheck_types.go сгенерированный поставляемый Normal file
Просмотреть файл

@ -0,0 +1,89 @@
package v1beta1
import (
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
)
// RemediationStrategyType contains remediation strategy type
type RemediationStrategyType string
// +genclient
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// MachineHealthCheck is the Schema for the machinehealthchecks API
// +kubebuilder:subresource:status
// +kubebuilder:resource:shortName=mhc;mhcs
// +k8s:openapi-gen=true
type MachineHealthCheck struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
// Specification of machine health check policy
Spec MachineHealthCheckSpec `json:"spec,omitempty"`
// Most recently observed status of MachineHealthCheck resource
Status MachineHealthCheckStatus `json:"status,omitempty"`
}
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// MachineHealthCheckList contains a list of MachineHealthCheck
type MachineHealthCheckList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []MachineHealthCheck `json:"items"`
}
// MachineHealthCheckSpec defines the desired state of MachineHealthCheck
type MachineHealthCheckSpec struct {
// Label selector to match machines whose health will be exercised
Selector metav1.LabelSelector `json:"selector"`
// UnhealthyConditions contains a list of the conditions that determine
// whether a node is considered unhealthy. The conditions are combined in a
// logical OR, i.e. if any of the conditions is met, the node is unhealthy.
//
// +kubebuilder:validation:MinItems=1
UnhealthyConditions []UnhealthyCondition `json:"unhealthyConditions"`
// Any farther remediation is only allowed if at most "MaxUnhealthy" machines selected by
// "selector" are not healthy.
// +optional
MaxUnhealthy *intstr.IntOrString `json:"maxUnhealthy,omitempty"`
}
// UnhealthyCondition represents a Node condition type and value with a timeout
// specified as a duration. When the named condition has been in the given
// status for at least the timeout value, a node is considered unhealthy.
type UnhealthyCondition struct {
// +kubebuilder:validation:Type=string
// +kubebuilder:validation:MinLength=1
Type corev1.NodeConditionType `json:"type"`
// +kubebuilder:validation:Type=string
// +kubebuilder:validation:MinLength=1
Status corev1.ConditionStatus `json:"status"`
// It would be preferable for timeout to be a metav1.Duration, but there's
// no good way to validate the format here. Invalid input would cause
// problems with marshaling, so it's better to just make it a string and
// handle the conversion in the controller.
//
// Intentional blank line to keep this out of the OpenAPI description...
// +kubebuilder:validation:MinLength=1
Timeout string `json:"timeout"`
}
// MachineHealthCheckStatus defines the observed state of MachineHealthCheck
type MachineHealthCheckStatus struct {
// total number of machines counted by this machine health check
// +kubebuilder:validation:Minimum=0
ExpectedMachines int `json:"expectedMachines"`
// total number of machines counted by this machine health check
// +kubebuilder:validation:Minimum=0
CurrentHealthy int `json:"currentHealthy" protobuf:"varint,4,opt,name=currentHealthy"`
}

222
vendor/github.com/openshift/machine-api-operator/pkg/apis/machine/v1beta1/machineset_types.go сгенерированный поставляемый Normal file
Просмотреть файл

@ -0,0 +1,222 @@
/*
Copyright 2018 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 v1beta1
import (
"log"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
metav1validation "k8s.io/apimachinery/pkg/apis/meta/v1/validation"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/util/validation/field"
)
// +genclient
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
/// [MachineSet]
// MachineSet ensures that a specified number of machines replicas are running at any given time.
// +k8s:openapi-gen=true
// +kubebuilder:subresource:status
// +kubebuilder:subresource:scale:specpath=.spec.replicas,statuspath=.status.replicas,selectorpath=.status.labelSelector
// +kubebuilder:printcolumn:name="Desired",type="integer",JSONPath=".spec.replicas",description="Desired Replicas"
// +kubebuilder:printcolumn:name="Current",type="integer",JSONPath=".status.replicas",description="Current Replicas"
// +kubebuilder:printcolumn:name="Ready",type="integer",JSONPath=".status.readyReplicas",description="Ready Replicas"
// +kubebuilder:printcolumn:name="Available",type="string",JSONPath=".status.availableReplicas",description="Observed number of available replicas"
// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp",description="Machineset age"
type MachineSet struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec MachineSetSpec `json:"spec,omitempty"`
Status MachineSetStatus `json:"status,omitempty"`
}
/// [MachineSet]
/// [MachineSetSpec]
// MachineSetSpec defines the desired state of MachineSet
type MachineSetSpec struct {
// Replicas is the number of desired replicas.
// This is a pointer to distinguish between explicit zero and unspecified.
// Defaults to 1.
// +optional
Replicas *int32 `json:"replicas,omitempty"`
// MinReadySeconds is the minimum number of seconds for which a newly created machine should be ready.
// Defaults to 0 (machine will be considered available as soon as it is ready)
// +optional
MinReadySeconds int32 `json:"minReadySeconds,omitempty"`
// DeletePolicy defines the policy used to identify nodes to delete when downscaling.
// Defaults to "Random". Valid values are "Random, "Newest", "Oldest"
// +kubebuilder:validation:Enum=Random;Newest;Oldest
DeletePolicy string `json:"deletePolicy,omitempty"`
// Selector is a label query over machines that should match the replica count.
// Label keys and values that must match in order to be controlled by this MachineSet.
// It must match the machine template's labels.
// More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors
Selector metav1.LabelSelector `json:"selector"`
// Template is the object that describes the machine that will be created if
// insufficient replicas are detected.
// +optional
Template MachineTemplateSpec `json:"template,omitempty"`
}
// MachineSetDeletePolicy defines how priority is assigned to nodes to delete when
// downscaling a MachineSet. Defaults to "Random".
type MachineSetDeletePolicy string
const (
// RandomMachineSetDeletePolicy prioritizes both Machines that have the annotation
// "cluster.k8s.io/delete-machine=yes" and Machines that are unhealthy
// (Status.ErrorReason or Status.ErrorMessage are set to a non-empty value).
// Finally, it picks Machines at random to delete.
RandomMachineSetDeletePolicy MachineSetDeletePolicy = "Random"
// NewestMachineSetDeletePolicy prioritizes both Machines that have the annotation
// "cluster.k8s.io/delete-machine=yes" and Machines that are unhealthy
// (Status.ErrorReason or Status.ErrorMessage are set to a non-empty value).
// It then prioritizes the newest Machines for deletion based on the Machine's CreationTimestamp.
NewestMachineSetDeletePolicy MachineSetDeletePolicy = "Newest"
// OldestMachineSetDeletePolicy prioritizes both Machines that have the annotation
// "cluster.k8s.io/delete-machine=yes" and Machines that are unhealthy
// (Status.ErrorReason or Status.ErrorMessage are set to a non-empty value).
// It then prioritizes the oldest Machines for deletion based on the Machine's CreationTimestamp.
OldestMachineSetDeletePolicy MachineSetDeletePolicy = "Oldest"
)
/// [MachineSetSpec] // doxygen marker
/// [MachineTemplateSpec] // doxygen marker
// MachineTemplateSpec describes the data needed to create a Machine from a template
type MachineTemplateSpec struct {
// Standard object's metadata.
// More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
// +optional
metav1.ObjectMeta `json:"metadata,omitempty"`
// Specification of the desired behavior of the machine.
// More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status
// +optional
Spec MachineSpec `json:"spec,omitempty"`
}
/// [MachineTemplateSpec]
/// [MachineSetStatus]
// MachineSetStatus defines the observed state of MachineSet
type MachineSetStatus struct {
// Replicas is the most recently observed number of replicas.
Replicas int32 `json:"replicas"`
// The number of replicas that have labels matching the labels of the machine template of the MachineSet.
// +optional
FullyLabeledReplicas int32 `json:"fullyLabeledReplicas,omitempty"`
// The number of ready replicas for this MachineSet. A machine is considered ready when the node has been created and is "Ready".
// +optional
ReadyReplicas int32 `json:"readyReplicas,omitempty"`
// The number of available replicas (ready for at least minReadySeconds) for this MachineSet.
// +optional
AvailableReplicas int32 `json:"availableReplicas,omitempty"`
// ObservedGeneration reflects the generation of the most recently observed MachineSet.
// +optional
ObservedGeneration int64 `json:"observedGeneration,omitempty"`
// In the event that there is a terminal problem reconciling the
// replicas, both ErrorReason and ErrorMessage will be set. ErrorReason
// will be populated with a succinct value suitable for machine
// interpretation, while ErrorMessage will contain a more verbose
// string suitable for logging and human consumption.
//
// These fields should not be set for transitive errors that a
// controller faces that are expected to be fixed automatically over
// time (like service outages), but instead indicate that something is
// fundamentally wrong with the MachineTemplate's spec or the configuration of
// the machine controller, and that manual intervention is required. Examples
// of terminal errors would be invalid combinations of settings in the
// spec, values that are unsupported by the machine controller, or the
// responsible machine controller itself being critically misconfigured.
//
// Any transient errors that occur during the reconciliation of Machines
// can be added as events to the MachineSet object and/or logged in the
// controller's output.
// +optional
ErrorReason *MachineSetStatusError `json:"errorReason,omitempty"`
// +optional
ErrorMessage *string `json:"errorMessage,omitempty"`
}
/// [MachineSetStatus]
func (m *MachineSet) Validate() field.ErrorList {
errors := field.ErrorList{}
// validate spec.selector and spec.template.labels
fldPath := field.NewPath("spec")
errors = append(errors, metav1validation.ValidateLabelSelector(&m.Spec.Selector, fldPath.Child("selector"))...)
if len(m.Spec.Selector.MatchLabels)+len(m.Spec.Selector.MatchExpressions) == 0 {
errors = append(errors, field.Invalid(fldPath.Child("selector"), m.Spec.Selector, "empty selector is not valid for MachineSet."))
}
selector, err := metav1.LabelSelectorAsSelector(&m.Spec.Selector)
if err != nil {
errors = append(errors, field.Invalid(fldPath.Child("selector"), m.Spec.Selector, "invalid label selector."))
} else {
labels := labels.Set(m.Spec.Template.Labels)
if !selector.Matches(labels) {
errors = append(errors, field.Invalid(fldPath.Child("template", "metadata", "labels"), m.Spec.Template.Labels, "`selector` does not match template `labels`"))
}
}
return errors
}
// DefaultingFunction sets default MachineSet field values
func (m *MachineSet) Default() {
log.Printf("Defaulting fields for MachineSet %s\n", m.Name)
if m.Spec.Replicas == nil {
m.Spec.Replicas = new(int32)
*m.Spec.Replicas = 1
}
if len(m.Namespace) == 0 {
m.Namespace = metav1.NamespaceDefault
}
if m.Spec.DeletePolicy == "" {
randomPolicy := string(RandomMachineSetDeletePolicy)
log.Printf("Defaulting to %s\n", randomPolicy)
m.Spec.DeletePolicy = randomPolicy
}
}
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// MachineSetList contains a list of MachineSet
type MachineSetList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []MachineSet `json:"items"`
}

46
vendor/github.com/openshift/machine-api-operator/pkg/apis/machine/v1beta1/register.go сгенерированный поставляемый Normal file
Просмотреть файл

@ -0,0 +1,46 @@
// NOTE: Boilerplate only. Ignore this file.
// Package v1alpha1 contains API Schema definitions for the healthchecking v1beta1 API group
// +k8s:deepcopy-gen=package,register
// +groupName=machine.openshift.io
package v1beta1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
healthchecking "github.com/openshift/machine-api-operator/pkg/apis/machine"
)
// SchemeGroupVersion is group version used to register these objects
var SchemeGroupVersion = schema.GroupVersion{Group: healthchecking.GroupName, Version: "v1beta1"}
// Kind takes an unqualified kind and returns back a Group qualified GroupKind
func Kind(kind string) schema.GroupKind {
return SchemeGroupVersion.WithKind(kind).GroupKind()
}
// Resource takes an unqualified resource and returns a Group qualified GroupResource
func Resource(resource string) schema.GroupResource {
return SchemeGroupVersion.WithResource(resource).GroupResource()
}
var (
SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes)
AddToScheme = SchemeBuilder.AddToScheme
)
// Adds the list of known types to Scheme.
func addKnownTypes(scheme *runtime.Scheme) error {
scheme.AddKnownTypes(SchemeGroupVersion,
&MachineHealthCheck{},
&MachineHealthCheckList{},
&Machine{},
&MachineList{},
&MachineSet{},
&MachineSetList{},
)
metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
return nil
}

477
vendor/github.com/openshift/machine-api-operator/pkg/apis/machine/v1beta1/zz_generated.deepcopy.go сгенерированный поставляемый Normal file
Просмотреть файл

@ -0,0 +1,477 @@
// +build !ignore_autogenerated
/*
* 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.
*
* Copyright 2019 Red Hat, Inc.
*
*/
// Code generated by deepcopy-gen. DO NOT EDIT.
package v1beta1
import (
v1 "k8s.io/api/core/v1"
runtime "k8s.io/apimachinery/pkg/runtime"
intstr "k8s.io/apimachinery/pkg/util/intstr"
)
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *LastOperation) DeepCopyInto(out *LastOperation) {
*out = *in
if in.Description != nil {
in, out := &in.Description, &out.Description
*out = new(string)
**out = **in
}
if in.LastUpdated != nil {
in, out := &in.LastUpdated, &out.LastUpdated
*out = (*in).DeepCopy()
}
if in.State != nil {
in, out := &in.State, &out.State
*out = new(string)
**out = **in
}
if in.Type != nil {
in, out := &in.Type, &out.Type
*out = new(string)
**out = **in
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LastOperation.
func (in *LastOperation) DeepCopy() *LastOperation {
if in == nil {
return nil
}
out := new(LastOperation)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *Machine) DeepCopyInto(out *Machine) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
in.Spec.DeepCopyInto(&out.Spec)
in.Status.DeepCopyInto(&out.Status)
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Machine.
func (in *Machine) DeepCopy() *Machine {
if in == nil {
return nil
}
out := new(Machine)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *Machine) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *MachineHealthCheck) DeepCopyInto(out *MachineHealthCheck) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
in.Spec.DeepCopyInto(&out.Spec)
out.Status = in.Status
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineHealthCheck.
func (in *MachineHealthCheck) DeepCopy() *MachineHealthCheck {
if in == nil {
return nil
}
out := new(MachineHealthCheck)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *MachineHealthCheck) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *MachineHealthCheckList) DeepCopyInto(out *MachineHealthCheckList) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ListMeta.DeepCopyInto(&out.ListMeta)
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]MachineHealthCheck, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineHealthCheckList.
func (in *MachineHealthCheckList) DeepCopy() *MachineHealthCheckList {
if in == nil {
return nil
}
out := new(MachineHealthCheckList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *MachineHealthCheckList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *MachineHealthCheckSpec) DeepCopyInto(out *MachineHealthCheckSpec) {
*out = *in
in.Selector.DeepCopyInto(&out.Selector)
if in.UnhealthyConditions != nil {
in, out := &in.UnhealthyConditions, &out.UnhealthyConditions
*out = make([]UnhealthyCondition, len(*in))
copy(*out, *in)
}
if in.MaxUnhealthy != nil {
in, out := &in.MaxUnhealthy, &out.MaxUnhealthy
*out = new(intstr.IntOrString)
**out = **in
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineHealthCheckSpec.
func (in *MachineHealthCheckSpec) DeepCopy() *MachineHealthCheckSpec {
if in == nil {
return nil
}
out := new(MachineHealthCheckSpec)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *MachineHealthCheckStatus) DeepCopyInto(out *MachineHealthCheckStatus) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineHealthCheckStatus.
func (in *MachineHealthCheckStatus) DeepCopy() *MachineHealthCheckStatus {
if in == nil {
return nil
}
out := new(MachineHealthCheckStatus)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *MachineList) DeepCopyInto(out *MachineList) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ListMeta.DeepCopyInto(&out.ListMeta)
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]Machine, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineList.
func (in *MachineList) DeepCopy() *MachineList {
if in == nil {
return nil
}
out := new(MachineList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *MachineList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *MachineSet) DeepCopyInto(out *MachineSet) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
in.Spec.DeepCopyInto(&out.Spec)
in.Status.DeepCopyInto(&out.Status)
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineSet.
func (in *MachineSet) DeepCopy() *MachineSet {
if in == nil {
return nil
}
out := new(MachineSet)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *MachineSet) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *MachineSetList) DeepCopyInto(out *MachineSetList) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ListMeta.DeepCopyInto(&out.ListMeta)
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]MachineSet, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineSetList.
func (in *MachineSetList) DeepCopy() *MachineSetList {
if in == nil {
return nil
}
out := new(MachineSetList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *MachineSetList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *MachineSetSpec) DeepCopyInto(out *MachineSetSpec) {
*out = *in
if in.Replicas != nil {
in, out := &in.Replicas, &out.Replicas
*out = new(int32)
**out = **in
}
in.Selector.DeepCopyInto(&out.Selector)
in.Template.DeepCopyInto(&out.Template)
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineSetSpec.
func (in *MachineSetSpec) DeepCopy() *MachineSetSpec {
if in == nil {
return nil
}
out := new(MachineSetSpec)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *MachineSetStatus) DeepCopyInto(out *MachineSetStatus) {
*out = *in
if in.ErrorReason != nil {
in, out := &in.ErrorReason, &out.ErrorReason
*out = new(MachineSetStatusError)
**out = **in
}
if in.ErrorMessage != nil {
in, out := &in.ErrorMessage, &out.ErrorMessage
*out = new(string)
**out = **in
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineSetStatus.
func (in *MachineSetStatus) DeepCopy() *MachineSetStatus {
if in == nil {
return nil
}
out := new(MachineSetStatus)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *MachineSpec) DeepCopyInto(out *MachineSpec) {
*out = *in
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
if in.Taints != nil {
in, out := &in.Taints, &out.Taints
*out = make([]v1.Taint, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
in.ProviderSpec.DeepCopyInto(&out.ProviderSpec)
if in.ProviderID != nil {
in, out := &in.ProviderID, &out.ProviderID
*out = new(string)
**out = **in
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineSpec.
func (in *MachineSpec) DeepCopy() *MachineSpec {
if in == nil {
return nil
}
out := new(MachineSpec)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *MachineStatus) DeepCopyInto(out *MachineStatus) {
*out = *in
if in.NodeRef != nil {
in, out := &in.NodeRef, &out.NodeRef
*out = new(v1.ObjectReference)
**out = **in
}
if in.LastUpdated != nil {
in, out := &in.LastUpdated, &out.LastUpdated
*out = (*in).DeepCopy()
}
if in.ErrorReason != nil {
in, out := &in.ErrorReason, &out.ErrorReason
*out = new(MachineStatusError)
**out = **in
}
if in.ErrorMessage != nil {
in, out := &in.ErrorMessage, &out.ErrorMessage
*out = new(string)
**out = **in
}
if in.ProviderStatus != nil {
in, out := &in.ProviderStatus, &out.ProviderStatus
*out = new(runtime.RawExtension)
(*in).DeepCopyInto(*out)
}
if in.Addresses != nil {
in, out := &in.Addresses, &out.Addresses
*out = make([]v1.NodeAddress, len(*in))
copy(*out, *in)
}
if in.LastOperation != nil {
in, out := &in.LastOperation, &out.LastOperation
*out = new(LastOperation)
(*in).DeepCopyInto(*out)
}
if in.Phase != nil {
in, out := &in.Phase, &out.Phase
*out = new(string)
**out = **in
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineStatus.
func (in *MachineStatus) DeepCopy() *MachineStatus {
if in == nil {
return nil
}
out := new(MachineStatus)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *MachineTemplateSpec) DeepCopyInto(out *MachineTemplateSpec) {
*out = *in
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
in.Spec.DeepCopyInto(&out.Spec)
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MachineTemplateSpec.
func (in *MachineTemplateSpec) DeepCopy() *MachineTemplateSpec {
if in == nil {
return nil
}
out := new(MachineTemplateSpec)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ProviderSpec) DeepCopyInto(out *ProviderSpec) {
*out = *in
if in.Value != nil {
in, out := &in.Value, &out.Value
*out = new(runtime.RawExtension)
(*in).DeepCopyInto(*out)
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProviderSpec.
func (in *ProviderSpec) DeepCopy() *ProviderSpec {
if in == nil {
return nil
}
out := new(ProviderSpec)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *UnhealthyCondition) DeepCopyInto(out *UnhealthyCondition) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new UnhealthyCondition.
func (in *UnhealthyCondition) DeepCopy() *UnhealthyCondition {
if in == nil {
return nil
}
out := new(UnhealthyCondition)
in.DeepCopyInto(out)
return out
}

16
vendor/golang.org/x/net/http2/transport.go сгенерированный поставляемый
Просмотреть файл

@ -227,6 +227,7 @@ type ClientConn struct {
br *bufio.Reader
fr *Framer
lastActive time.Time
lastIdle time.Time // time last idle
// Settings from peer: (also guarded by mu)
maxFrameSize uint32
maxConcurrentStreams uint32
@ -736,7 +737,8 @@ func (cc *ClientConn) idleStateLocked() (st clientConnIdleState) {
}
st.canTakeNewRequest = cc.goAway == nil && !cc.closed && !cc.closing && maxConcurrentOkay &&
int64(cc.nextStreamID)+2*int64(cc.pendingRequests) < math.MaxInt32
int64(cc.nextStreamID)+2*int64(cc.pendingRequests) < math.MaxInt32 &&
!cc.tooIdleLocked()
st.freshConn = cc.nextStreamID == 1 && st.canTakeNewRequest
return
}
@ -746,6 +748,16 @@ func (cc *ClientConn) canTakeNewRequestLocked() bool {
return st.canTakeNewRequest
}
// tooIdleLocked reports whether this connection has been been sitting idle
// for too much wall time.
func (cc *ClientConn) tooIdleLocked() bool {
// The Round(0) strips the monontonic clock reading so the
// times are compared based on their wall time. We don't want
// to reuse a connection that's been sitting idle during
// VM/laptop suspend if monotonic time was also frozen.
return cc.idleTimeout != 0 && !cc.lastIdle.IsZero() && time.Since(cc.lastIdle.Round(0)) > cc.idleTimeout
}
// onIdleTimeout is called from a time.AfterFunc goroutine. It will
// only be called when we're idle, but because we're coming from a new
// goroutine, there could be a new request coming in at the same time,
@ -1150,6 +1162,7 @@ func (cc *ClientConn) awaitOpenSlotForRequest(req *http.Request) error {
}
return errClientConnUnusable
}
cc.lastIdle = time.Time{}
if int64(len(cc.streams))+1 <= int64(cc.maxConcurrentStreams) {
if waitingForConn != nil {
close(waitingForConn)
@ -1638,6 +1651,7 @@ func (cc *ClientConn) streamByID(id uint32, andRemove bool) *clientStream {
delete(cc.streams, id)
if len(cc.streams) == 0 && cc.idleTimer != nil {
cc.idleTimer.Reset(cc.idleTimeout)
cc.lastIdle = time.Now()
}
close(cs.done)
// Wake up checkResetOrDone via clientStream.awaitFlowControl and

5
vendor/golang.org/x/sys/unix/mkerrors.sh сгенерированный поставляемый
Просмотреть файл

@ -197,6 +197,7 @@ struct ltchars {
#include <linux/fanotify.h>
#include <linux/filter.h>
#include <linux/fs.h>
#include <linux/fscrypt.h>
#include <linux/genetlink.h>
#include <linux/hdreg.h>
#include <linux/icmpv6.h>
@ -496,7 +497,9 @@ ccflags="$@"
$2 ~ /^CAN_/ ||
$2 ~ /^CAP_/ ||
$2 ~ /^ALG_/ ||
$2 ~ /^FS_(POLICY_FLAGS|KEY_DESC|ENCRYPTION_MODE|[A-Z0-9_]+_KEY_SIZE|IOC_(GET|SET)_ENCRYPTION)/ ||
$2 ~ /^FS_(POLICY_FLAGS|KEY_DESC|ENCRYPTION_MODE|[A-Z0-9_]+_KEY_SIZE)/ ||
$2 ~ /^FS_IOC_.*ENCRYPTION/ ||
$2 ~ /^FSCRYPT_/ ||
$2 ~ /^GRND_/ ||
$2 ~ /^RND/ ||
$2 ~ /^KEY_(SPEC|REQKEY_DEFL)_/ ||

5586
vendor/golang.org/x/sys/unix/zerrors_linux_386.go сгенерированный поставляемый

Разница между файлами не показана из-за своего большого размера Загрузить разницу

5586
vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go сгенерированный поставляемый

Разница между файлами не показана из-за своего большого размера Загрузить разницу

5598
vendor/golang.org/x/sys/unix/zerrors_linux_arm.go сгенерированный поставляемый

Разница между файлами не показана из-за своего большого размера Загрузить разницу

5572
vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go сгенерированный поставляемый

Разница между файлами не показана из-за своего большого размера Загрузить разницу

5590
vendor/golang.org/x/sys/unix/zerrors_linux_mips.go сгенерированный поставляемый

Разница между файлами не показана из-за своего большого размера Загрузить разницу

5590
vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go сгенерированный поставляемый

Разница между файлами не показана из-за своего большого размера Загрузить разницу

5590
vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go сгенерированный поставляемый

Разница между файлами не показана из-за своего большого размера Загрузить разницу

5590
vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go сгенерированный поставляемый

Разница между файлами не показана из-за своего большого размера Загрузить разницу

5708
vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go сгенерированный поставляемый

Разница между файлами не показана из-за своего большого размера Загрузить разницу

5708
vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go сгенерированный поставляемый

Разница между файлами не показана из-за своего большого размера Загрузить разницу

5560
vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go сгенерированный поставляемый

Разница между файлами не показана из-за своего большого размера Загрузить разницу

5706
vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go сгенерированный поставляемый

Разница между файлами не показана из-за своего большого размера Загрузить разницу

5686
vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go сгенерированный поставляемый

Разница между файлами не показана из-за своего большого размера Загрузить разницу

49
vendor/golang.org/x/sys/unix/ztypes_linux_386.go сгенерированный поставляемый
Просмотреть файл

@ -179,6 +179,55 @@ type FscryptKey struct {
Size uint32
}
type FscryptPolicyV1 struct {
Version uint8
Contents_encryption_mode uint8
Filenames_encryption_mode uint8
Flags uint8
Master_key_descriptor [8]uint8
}
type FscryptPolicyV2 struct {
Version uint8
Contents_encryption_mode uint8
Filenames_encryption_mode uint8
Flags uint8
_ [4]uint8
Master_key_identifier [16]uint8
}
type FscryptGetPolicyExArg struct {
Size uint64
Policy [24]byte
}
type FscryptKeySpecifier struct {
Type uint32
_ uint32
U [32]byte
}
type FscryptAddKeyArg struct {
Key_spec FscryptKeySpecifier
Raw_size uint32
_ [9]uint32
}
type FscryptRemoveKeyArg struct {
Key_spec FscryptKeySpecifier
Removal_status_flags uint32
_ [5]uint32
}
type FscryptGetKeyStatusArg struct {
Key_spec FscryptKeySpecifier
_ [6]uint32
Status uint32
Status_flags uint32
User_count uint32
_ [13]uint32
}
type KeyctlDHParams struct {
Private int32
Prime int32

49
vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go сгенерированный поставляемый
Просмотреть файл

@ -179,6 +179,55 @@ type FscryptKey struct {
Size uint32
}
type FscryptPolicyV1 struct {
Version uint8
Contents_encryption_mode uint8
Filenames_encryption_mode uint8
Flags uint8
Master_key_descriptor [8]uint8
}
type FscryptPolicyV2 struct {
Version uint8
Contents_encryption_mode uint8
Filenames_encryption_mode uint8
Flags uint8
_ [4]uint8
Master_key_identifier [16]uint8
}
type FscryptGetPolicyExArg struct {
Size uint64
Policy [24]byte
}
type FscryptKeySpecifier struct {
Type uint32
_ uint32
U [32]byte
}
type FscryptAddKeyArg struct {
Key_spec FscryptKeySpecifier
Raw_size uint32
_ [9]uint32
}
type FscryptRemoveKeyArg struct {
Key_spec FscryptKeySpecifier
Removal_status_flags uint32
_ [5]uint32
}
type FscryptGetKeyStatusArg struct {
Key_spec FscryptKeySpecifier
_ [6]uint32
Status uint32
Status_flags uint32
User_count uint32
_ [13]uint32
}
type KeyctlDHParams struct {
Private int32
Prime int32

49
vendor/golang.org/x/sys/unix/ztypes_linux_arm.go сгенерированный поставляемый
Просмотреть файл

@ -183,6 +183,55 @@ type FscryptKey struct {
Size uint32
}
type FscryptPolicyV1 struct {
Version uint8
Contents_encryption_mode uint8
Filenames_encryption_mode uint8
Flags uint8
Master_key_descriptor [8]uint8
}
type FscryptPolicyV2 struct {
Version uint8
Contents_encryption_mode uint8
Filenames_encryption_mode uint8
Flags uint8
_ [4]uint8
Master_key_identifier [16]uint8
}
type FscryptGetPolicyExArg struct {
Size uint64
Policy [24]byte
}
type FscryptKeySpecifier struct {
Type uint32
_ uint32
U [32]byte
}
type FscryptAddKeyArg struct {
Key_spec FscryptKeySpecifier
Raw_size uint32
_ [9]uint32
}
type FscryptRemoveKeyArg struct {
Key_spec FscryptKeySpecifier
Removal_status_flags uint32
_ [5]uint32
}
type FscryptGetKeyStatusArg struct {
Key_spec FscryptKeySpecifier
_ [6]uint32
Status uint32
Status_flags uint32
User_count uint32
_ [13]uint32
}
type KeyctlDHParams struct {
Private int32
Prime int32

49
vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go сгенерированный поставляемый
Просмотреть файл

@ -180,6 +180,55 @@ type FscryptKey struct {
Size uint32
}
type FscryptPolicyV1 struct {
Version uint8
Contents_encryption_mode uint8
Filenames_encryption_mode uint8
Flags uint8
Master_key_descriptor [8]uint8
}
type FscryptPolicyV2 struct {
Version uint8
Contents_encryption_mode uint8
Filenames_encryption_mode uint8
Flags uint8
_ [4]uint8
Master_key_identifier [16]uint8
}
type FscryptGetPolicyExArg struct {
Size uint64
Policy [24]byte
}
type FscryptKeySpecifier struct {
Type uint32
_ uint32
U [32]byte
}
type FscryptAddKeyArg struct {
Key_spec FscryptKeySpecifier
Raw_size uint32
_ [9]uint32
}
type FscryptRemoveKeyArg struct {
Key_spec FscryptKeySpecifier
Removal_status_flags uint32
_ [5]uint32
}
type FscryptGetKeyStatusArg struct {
Key_spec FscryptKeySpecifier
_ [6]uint32
Status uint32
Status_flags uint32
User_count uint32
_ [13]uint32
}
type KeyctlDHParams struct {
Private int32
Prime int32

49
vendor/golang.org/x/sys/unix/ztypes_linux_mips.go сгенерированный поставляемый
Просмотреть файл

@ -182,6 +182,55 @@ type FscryptKey struct {
Size uint32
}
type FscryptPolicyV1 struct {
Version uint8
Contents_encryption_mode uint8
Filenames_encryption_mode uint8
Flags uint8
Master_key_descriptor [8]uint8
}
type FscryptPolicyV2 struct {
Version uint8
Contents_encryption_mode uint8
Filenames_encryption_mode uint8
Flags uint8
_ [4]uint8
Master_key_identifier [16]uint8
}
type FscryptGetPolicyExArg struct {
Size uint64
Policy [24]byte
}
type FscryptKeySpecifier struct {
Type uint32
_ uint32
U [32]byte
}
type FscryptAddKeyArg struct {
Key_spec FscryptKeySpecifier
Raw_size uint32
_ [9]uint32
}
type FscryptRemoveKeyArg struct {
Key_spec FscryptKeySpecifier
Removal_status_flags uint32
_ [5]uint32
}
type FscryptGetKeyStatusArg struct {
Key_spec FscryptKeySpecifier
_ [6]uint32
Status uint32
Status_flags uint32
User_count uint32
_ [13]uint32
}
type KeyctlDHParams struct {
Private int32
Prime int32

49
vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go сгенерированный поставляемый
Просмотреть файл

@ -180,6 +180,55 @@ type FscryptKey struct {
Size uint32
}
type FscryptPolicyV1 struct {
Version uint8
Contents_encryption_mode uint8
Filenames_encryption_mode uint8
Flags uint8
Master_key_descriptor [8]uint8
}
type FscryptPolicyV2 struct {
Version uint8
Contents_encryption_mode uint8
Filenames_encryption_mode uint8
Flags uint8
_ [4]uint8
Master_key_identifier [16]uint8
}
type FscryptGetPolicyExArg struct {
Size uint64
Policy [24]byte
}
type FscryptKeySpecifier struct {
Type uint32
_ uint32
U [32]byte
}
type FscryptAddKeyArg struct {
Key_spec FscryptKeySpecifier
Raw_size uint32
_ [9]uint32
}
type FscryptRemoveKeyArg struct {
Key_spec FscryptKeySpecifier
Removal_status_flags uint32
_ [5]uint32
}
type FscryptGetKeyStatusArg struct {
Key_spec FscryptKeySpecifier
_ [6]uint32
Status uint32
Status_flags uint32
User_count uint32
_ [13]uint32
}
type KeyctlDHParams struct {
Private int32
Prime int32

49
vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go сгенерированный поставляемый
Просмотреть файл

@ -180,6 +180,55 @@ type FscryptKey struct {
Size uint32
}
type FscryptPolicyV1 struct {
Version uint8
Contents_encryption_mode uint8
Filenames_encryption_mode uint8
Flags uint8
Master_key_descriptor [8]uint8
}
type FscryptPolicyV2 struct {
Version uint8
Contents_encryption_mode uint8
Filenames_encryption_mode uint8
Flags uint8
_ [4]uint8
Master_key_identifier [16]uint8
}
type FscryptGetPolicyExArg struct {
Size uint64
Policy [24]byte
}
type FscryptKeySpecifier struct {
Type uint32
_ uint32
U [32]byte
}
type FscryptAddKeyArg struct {
Key_spec FscryptKeySpecifier
Raw_size uint32
_ [9]uint32
}
type FscryptRemoveKeyArg struct {
Key_spec FscryptKeySpecifier
Removal_status_flags uint32
_ [5]uint32
}
type FscryptGetKeyStatusArg struct {
Key_spec FscryptKeySpecifier
_ [6]uint32
Status uint32
Status_flags uint32
User_count uint32
_ [13]uint32
}
type KeyctlDHParams struct {
Private int32
Prime int32

49
vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go сгенерированный поставляемый
Просмотреть файл

@ -182,6 +182,55 @@ type FscryptKey struct {
Size uint32
}
type FscryptPolicyV1 struct {
Version uint8
Contents_encryption_mode uint8
Filenames_encryption_mode uint8
Flags uint8
Master_key_descriptor [8]uint8
}
type FscryptPolicyV2 struct {
Version uint8
Contents_encryption_mode uint8
Filenames_encryption_mode uint8
Flags uint8
_ [4]uint8
Master_key_identifier [16]uint8
}
type FscryptGetPolicyExArg struct {
Size uint64
Policy [24]byte
}
type FscryptKeySpecifier struct {
Type uint32
_ uint32
U [32]byte
}
type FscryptAddKeyArg struct {
Key_spec FscryptKeySpecifier
Raw_size uint32
_ [9]uint32
}
type FscryptRemoveKeyArg struct {
Key_spec FscryptKeySpecifier
Removal_status_flags uint32
_ [5]uint32
}
type FscryptGetKeyStatusArg struct {
Key_spec FscryptKeySpecifier
_ [6]uint32
Status uint32
Status_flags uint32
User_count uint32
_ [13]uint32
}
type KeyctlDHParams struct {
Private int32
Prime int32

49
vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go сгенерированный поставляемый
Просмотреть файл

@ -181,6 +181,55 @@ type FscryptKey struct {
Size uint32
}
type FscryptPolicyV1 struct {
Version uint8
Contents_encryption_mode uint8
Filenames_encryption_mode uint8
Flags uint8
Master_key_descriptor [8]uint8
}
type FscryptPolicyV2 struct {
Version uint8
Contents_encryption_mode uint8
Filenames_encryption_mode uint8
Flags uint8
_ [4]uint8
Master_key_identifier [16]uint8
}
type FscryptGetPolicyExArg struct {
Size uint64
Policy [24]byte
}
type FscryptKeySpecifier struct {
Type uint32
_ uint32
U [32]byte
}
type FscryptAddKeyArg struct {
Key_spec FscryptKeySpecifier
Raw_size uint32
_ [9]uint32
}
type FscryptRemoveKeyArg struct {
Key_spec FscryptKeySpecifier
Removal_status_flags uint32
_ [5]uint32
}
type FscryptGetKeyStatusArg struct {
Key_spec FscryptKeySpecifier
_ [6]uint32
Status uint32
Status_flags uint32
User_count uint32
_ [13]uint32
}
type KeyctlDHParams struct {
Private int32
Prime int32

49
vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go сгенерированный поставляемый
Просмотреть файл

@ -181,6 +181,55 @@ type FscryptKey struct {
Size uint32
}
type FscryptPolicyV1 struct {
Version uint8
Contents_encryption_mode uint8
Filenames_encryption_mode uint8
Flags uint8
Master_key_descriptor [8]uint8
}
type FscryptPolicyV2 struct {
Version uint8
Contents_encryption_mode uint8
Filenames_encryption_mode uint8
Flags uint8
_ [4]uint8
Master_key_identifier [16]uint8
}
type FscryptGetPolicyExArg struct {
Size uint64
Policy [24]byte
}
type FscryptKeySpecifier struct {
Type uint32
_ uint32
U [32]byte
}
type FscryptAddKeyArg struct {
Key_spec FscryptKeySpecifier
Raw_size uint32
_ [9]uint32
}
type FscryptRemoveKeyArg struct {
Key_spec FscryptKeySpecifier
Removal_status_flags uint32
_ [5]uint32
}
type FscryptGetKeyStatusArg struct {
Key_spec FscryptKeySpecifier
_ [6]uint32
Status uint32
Status_flags uint32
User_count uint32
_ [13]uint32
}
type KeyctlDHParams struct {
Private int32
Prime int32

49
vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go сгенерированный поставляемый
Просмотреть файл

@ -180,6 +180,55 @@ type FscryptKey struct {
Size uint32
}
type FscryptPolicyV1 struct {
Version uint8
Contents_encryption_mode uint8
Filenames_encryption_mode uint8
Flags uint8
Master_key_descriptor [8]uint8
}
type FscryptPolicyV2 struct {
Version uint8
Contents_encryption_mode uint8
Filenames_encryption_mode uint8
Flags uint8
_ [4]uint8
Master_key_identifier [16]uint8
}
type FscryptGetPolicyExArg struct {
Size uint64
Policy [24]byte
}
type FscryptKeySpecifier struct {
Type uint32
_ uint32
U [32]byte
}
type FscryptAddKeyArg struct {
Key_spec FscryptKeySpecifier
Raw_size uint32
_ [9]uint32
}
type FscryptRemoveKeyArg struct {
Key_spec FscryptKeySpecifier
Removal_status_flags uint32
_ [5]uint32
}
type FscryptGetKeyStatusArg struct {
Key_spec FscryptKeySpecifier
_ [6]uint32
Status uint32
Status_flags uint32
User_count uint32
_ [13]uint32
}
type KeyctlDHParams struct {
Private int32
Prime int32

49
vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go сгенерированный поставляемый
Просмотреть файл

@ -179,6 +179,55 @@ type FscryptKey struct {
Size uint32
}
type FscryptPolicyV1 struct {
Version uint8
Contents_encryption_mode uint8
Filenames_encryption_mode uint8
Flags uint8
Master_key_descriptor [8]uint8
}
type FscryptPolicyV2 struct {
Version uint8
Contents_encryption_mode uint8
Filenames_encryption_mode uint8
Flags uint8
_ [4]uint8
Master_key_identifier [16]uint8
}
type FscryptGetPolicyExArg struct {
Size uint64
Policy [24]byte
}
type FscryptKeySpecifier struct {
Type uint32
_ uint32
U [32]byte
}
type FscryptAddKeyArg struct {
Key_spec FscryptKeySpecifier
Raw_size uint32
_ [9]uint32
}
type FscryptRemoveKeyArg struct {
Key_spec FscryptKeySpecifier
Removal_status_flags uint32
_ [5]uint32
}
type FscryptGetKeyStatusArg struct {
Key_spec FscryptKeySpecifier
_ [6]uint32
Status uint32
Status_flags uint32
User_count uint32
_ [13]uint32
}
type KeyctlDHParams struct {
Private int32
Prime int32

49
vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go сгенерированный поставляемый
Просмотреть файл

@ -183,6 +183,55 @@ type FscryptKey struct {
Size uint32
}
type FscryptPolicyV1 struct {
Version uint8
Contents_encryption_mode uint8
Filenames_encryption_mode uint8
Flags uint8
Master_key_descriptor [8]uint8
}
type FscryptPolicyV2 struct {
Version uint8
Contents_encryption_mode uint8
Filenames_encryption_mode uint8
Flags uint8
_ [4]uint8
Master_key_identifier [16]uint8
}
type FscryptGetPolicyExArg struct {
Size uint64
Policy [24]byte
}
type FscryptKeySpecifier struct {
Type uint32
_ uint32
U [32]byte
}
type FscryptAddKeyArg struct {
Key_spec FscryptKeySpecifier
Raw_size uint32
_ [9]uint32
}
type FscryptRemoveKeyArg struct {
Key_spec FscryptKeySpecifier
Removal_status_flags uint32
_ [5]uint32
}
type FscryptGetKeyStatusArg struct {
Key_spec FscryptKeySpecifier
_ [6]uint32
Status uint32
Status_flags uint32
User_count uint32
_ [13]uint32
}
type KeyctlDHParams struct {
Private int32
Prime int32

22
vendor/golang.org/x/sys/windows/syscall_windows.go сгенерированный поставляемый
Просмотреть файл

@ -701,6 +701,8 @@ const socket_error = uintptr(^uint32(0))
//sys WSACleanup() (err error) [failretval==socket_error] = ws2_32.WSACleanup
//sys WSAIoctl(s Handle, iocc uint32, inbuf *byte, cbif uint32, outbuf *byte, cbob uint32, cbbr *uint32, overlapped *Overlapped, completionRoutine uintptr) (err error) [failretval==socket_error] = ws2_32.WSAIoctl
//sys socket(af int32, typ int32, protocol int32) (handle Handle, err error) [failretval==InvalidHandle] = ws2_32.socket
//sys sendto(s Handle, buf []byte, flags int, to unsafe.Pointer, tolen int32) (err error) [failretval==socket_error] = ws2_32.sendto
//sys recvfrom(s Handle, buf []byte, flags int, from *RawSockaddrAny, fromlen *int) (n int, err error) [failretval==-1] = ws2_32.recvfrom
//sys Setsockopt(s Handle, level int32, optname int32, optval *byte, optlen int32) (err error) [failretval==socket_error] = ws2_32.setsockopt
//sys Getsockopt(s Handle, level int32, optname int32, optval *byte, optlen *int32) (err error) [failretval==socket_error] = ws2_32.getsockopt
//sys bind(s Handle, name unsafe.Pointer, namelen int32) (err error) [failretval==socket_error] = ws2_32.bind
@ -1129,10 +1131,26 @@ func NsecToTimespec(nsec int64) (ts Timespec) {
// TODO(brainman): fix all needed for net
func Accept(fd Handle) (nfd Handle, sa Sockaddr, err error) { return 0, nil, syscall.EWINDOWS }
func Recvfrom(fd Handle, p []byte, flags int) (n int, from Sockaddr, err error) {
return 0, nil, syscall.EWINDOWS
var rsa RawSockaddrAny
l := int(unsafe.Sizeof(rsa))
n, err = recvfrom(fd, p, flags, &rsa, &l)
if err != nil {
return
}
from, err = rsa.Sockaddr()
return
}
func Sendto(fd Handle, p []byte, flags int, to Sockaddr) (err error) { return syscall.EWINDOWS }
func Sendto(fd Handle, p []byte, flags int, to Sockaddr) (err error) {
ptr, l, err := to.sockaddr()
if err != nil {
return err
}
return sendto(fd, p, flags, ptr, l)
}
func SetsockoptTimeval(fd Handle, level, opt int, tv *Timeval) (err error) { return syscall.EWINDOWS }
// The Linger struct is wrong but we only noticed after Go 1.

35
vendor/golang.org/x/sys/windows/zsyscall_windows.go сгенерированный поставляемый
Просмотреть файл

@ -257,6 +257,8 @@ var (
procWSACleanup = modws2_32.NewProc("WSACleanup")
procWSAIoctl = modws2_32.NewProc("WSAIoctl")
procsocket = modws2_32.NewProc("socket")
procsendto = modws2_32.NewProc("sendto")
procrecvfrom = modws2_32.NewProc("recvfrom")
procsetsockopt = modws2_32.NewProc("setsockopt")
procgetsockopt = modws2_32.NewProc("getsockopt")
procbind = modws2_32.NewProc("bind")
@ -2873,6 +2875,39 @@ func socket(af int32, typ int32, protocol int32) (handle Handle, err error) {
return
}
func sendto(s Handle, buf []byte, flags int, to unsafe.Pointer, tolen int32) (err error) {
var _p0 *byte
if len(buf) > 0 {
_p0 = &buf[0]
}
r1, _, e1 := syscall.Syscall6(procsendto.Addr(), 6, uintptr(s), uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(tolen))
if r1 == socket_error {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func recvfrom(s Handle, buf []byte, flags int, from *RawSockaddrAny, fromlen *int) (n int, err error) {
var _p0 *byte
if len(buf) > 0 {
_p0 = &buf[0]
}
r0, _, e1 := syscall.Syscall6(procrecvfrom.Addr(), 6, uintptr(s), uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen)))
n = int(r0)
if n == -1 {
if e1 != 0 {
err = errnoErr(e1)
} else {
err = syscall.EINVAL
}
}
return
}
func Setsockopt(s Handle, level int32, optname int32, optval *byte, optlen int32) (err error) {
r1, _, e1 := syscall.Syscall6(procsetsockopt.Addr(), 5, uintptr(s), uintptr(level), uintptr(optname), uintptr(unsafe.Pointer(optval)), uintptr(optlen), 0)
if r1 == socket_error {

43
vendor/golang.org/x/tools/cmd/goimports/doc.go сгенерированный поставляемый Normal file
Просмотреть файл

@ -0,0 +1,43 @@
/*
Command goimports updates your Go import lines,
adding missing ones and removing unreferenced ones.
$ go get golang.org/x/tools/cmd/goimports
In addition to fixing imports, goimports also formats
your code in the same style as gofmt so it can be used
as a replacement for your editor's gofmt-on-save hook.
For emacs, make sure you have the latest go-mode.el:
https://github.com/dominikh/go-mode.el
Then in your .emacs file:
(setq gofmt-command "goimports")
(add-hook 'before-save-hook 'gofmt-before-save)
For vim, set "gofmt_command" to "goimports":
https://golang.org/change/39c724dd7f252
https://golang.org/wiki/IDEsAndTextEditorPlugins
etc
For GoSublime, follow the steps described here:
http://michaelwhatcott.com/gosublime-goimports/
For other editors, you probably know what to do.
To exclude directories in your $GOPATH from being scanned for Go
files, goimports respects a configuration file at
$GOPATH/src/.goimportsignore which may contain blank lines, comment
lines (beginning with '#'), or lines naming a directory relative to
the configuration file to ignore when scanning. No globbing or regex
patterns are allowed. Use the "-v" verbose flag to verify it's
working and see what goimports is doing.
File bugs or feature requests at:
https://golang.org/issues/new?title=x/tools/cmd/goimports:+
Happy hacking!
*/
package main // import "golang.org/x/tools/cmd/goimports"

377
vendor/golang.org/x/tools/cmd/goimports/goimports.go сгенерированный поставляемый Normal file
Просмотреть файл

@ -0,0 +1,377 @@
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bufio"
"bytes"
"errors"
"flag"
"fmt"
"go/build"
"go/scanner"
"io"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
"runtime"
"runtime/pprof"
"strings"
"golang.org/x/tools/internal/imports"
)
var (
// main operation modes
list = flag.Bool("l", false, "list files whose formatting differs from goimport's")
write = flag.Bool("w", false, "write result to (source) file instead of stdout")
doDiff = flag.Bool("d", false, "display diffs instead of rewriting files")
srcdir = flag.String("srcdir", "", "choose imports as if source code is from `dir`. When operating on a single file, dir may instead be the complete file name.")
verbose bool // verbose logging
cpuProfile = flag.String("cpuprofile", "", "CPU profile output")
memProfile = flag.String("memprofile", "", "memory profile output")
memProfileRate = flag.Int("memrate", 0, "if > 0, sets runtime.MemProfileRate")
options = &imports.Options{
TabWidth: 8,
TabIndent: true,
Comments: true,
Fragment: true,
// This environment, and its caches, will be reused for the whole run.
Env: &imports.ProcessEnv{
GOPATH: build.Default.GOPATH,
GOROOT: build.Default.GOROOT,
},
}
exitCode = 0
)
func init() {
flag.BoolVar(&options.AllErrors, "e", false, "report all errors (not just the first 10 on different lines)")
flag.StringVar(&options.Env.LocalPrefix, "local", "", "put imports beginning with this string after 3rd-party packages; comma-separated list")
flag.BoolVar(&options.FormatOnly, "format-only", false, "if true, don't fix imports and only format. In this mode, goimports is effectively gofmt, with the addition that imports are grouped into sections.")
}
func report(err error) {
scanner.PrintError(os.Stderr, err)
exitCode = 2
}
func usage() {
fmt.Fprintf(os.Stderr, "usage: goimports [flags] [path ...]\n")
flag.PrintDefaults()
os.Exit(2)
}
func isGoFile(f os.FileInfo) bool {
// ignore non-Go files
name := f.Name()
return !f.IsDir() && !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".go")
}
// argumentType is which mode goimports was invoked as.
type argumentType int
const (
// fromStdin means the user is piping their source into goimports.
fromStdin argumentType = iota
// singleArg is the common case from editors, when goimports is run on
// a single file.
singleArg
// multipleArg is when the user ran "goimports file1.go file2.go"
// or ran goimports on a directory tree.
multipleArg
)
func processFile(filename string, in io.Reader, out io.Writer, argType argumentType) error {
opt := options
if argType == fromStdin {
nopt := *options
nopt.Fragment = true
opt = &nopt
}
if in == nil {
f, err := os.Open(filename)
if err != nil {
return err
}
defer f.Close()
in = f
}
src, err := ioutil.ReadAll(in)
if err != nil {
return err
}
target := filename
if *srcdir != "" {
// Determine whether the provided -srcdirc is a directory or file
// and then use it to override the target.
//
// See https://github.com/dominikh/go-mode.el/issues/146
if isFile(*srcdir) {
if argType == multipleArg {
return errors.New("-srcdir value can't be a file when passing multiple arguments or when walking directories")
}
target = *srcdir
} else if argType == singleArg && strings.HasSuffix(*srcdir, ".go") && !isDir(*srcdir) {
// For a file which doesn't exist on disk yet, but might shortly.
// e.g. user in editor opens $DIR/newfile.go and newfile.go doesn't yet exist on disk.
// The goimports on-save hook writes the buffer to a temp file
// first and runs goimports before the actual save to newfile.go.
// The editor's buffer is named "newfile.go" so that is passed to goimports as:
// goimports -srcdir=/gopath/src/pkg/newfile.go /tmp/gofmtXXXXXXXX.go
// and then the editor reloads the result from the tmp file and writes
// it to newfile.go.
target = *srcdir
} else {
// Pretend that file is from *srcdir in order to decide
// visible imports correctly.
target = filepath.Join(*srcdir, filepath.Base(filename))
}
}
res, err := imports.Process(target, src, opt)
if err != nil {
return err
}
if !bytes.Equal(src, res) {
// formatting has changed
if *list {
fmt.Fprintln(out, filename)
}
if *write {
if argType == fromStdin {
// filename is "<standard input>"
return errors.New("can't use -w on stdin")
}
err = ioutil.WriteFile(filename, res, 0)
if err != nil {
return err
}
}
if *doDiff {
if argType == fromStdin {
filename = "stdin.go" // because <standard input>.orig looks silly
}
data, err := diff(src, res, filename)
if err != nil {
return fmt.Errorf("computing diff: %s", err)
}
fmt.Printf("diff -u %s %s\n", filepath.ToSlash(filename+".orig"), filepath.ToSlash(filename))
out.Write(data)
}
}
if !*list && !*write && !*doDiff {
_, err = out.Write(res)
}
return err
}
func visitFile(path string, f os.FileInfo, err error) error {
if err == nil && isGoFile(f) {
err = processFile(path, nil, os.Stdout, multipleArg)
}
if err != nil {
report(err)
}
return nil
}
func walkDir(path string) {
filepath.Walk(path, visitFile)
}
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
// call gofmtMain in a separate function
// so that it can use defer and have them
// run before the exit.
gofmtMain()
os.Exit(exitCode)
}
// parseFlags parses command line flags and returns the paths to process.
// It's a var so that custom implementations can replace it in other files.
var parseFlags = func() []string {
flag.BoolVar(&verbose, "v", false, "verbose logging")
flag.Parse()
return flag.Args()
}
func bufferedFileWriter(dest string) (w io.Writer, close func()) {
f, err := os.Create(dest)
if err != nil {
log.Fatal(err)
}
bw := bufio.NewWriter(f)
return bw, func() {
if err := bw.Flush(); err != nil {
log.Fatalf("error flushing %v: %v", dest, err)
}
if err := f.Close(); err != nil {
log.Fatal(err)
}
}
}
func gofmtMain() {
flag.Usage = usage
paths := parseFlags()
if *cpuProfile != "" {
bw, flush := bufferedFileWriter(*cpuProfile)
pprof.StartCPUProfile(bw)
defer flush()
defer pprof.StopCPUProfile()
}
// doTrace is a conditionally compiled wrapper around runtime/trace. It is
// used to allow goimports to compile under gccgo, which does not support
// runtime/trace. See https://golang.org/issue/15544.
defer doTrace()()
if *memProfileRate > 0 {
runtime.MemProfileRate = *memProfileRate
bw, flush := bufferedFileWriter(*memProfile)
defer func() {
runtime.GC() // materialize all statistics
if err := pprof.WriteHeapProfile(bw); err != nil {
log.Fatal(err)
}
flush()
}()
}
if verbose {
log.SetFlags(log.LstdFlags | log.Lmicroseconds)
options.Env.Debug = true
}
if options.TabWidth < 0 {
fmt.Fprintf(os.Stderr, "negative tabwidth %d\n", options.TabWidth)
exitCode = 2
return
}
if len(paths) == 0 {
if err := processFile("<standard input>", os.Stdin, os.Stdout, fromStdin); err != nil {
report(err)
}
return
}
argType := singleArg
if len(paths) > 1 {
argType = multipleArg
}
for _, path := range paths {
switch dir, err := os.Stat(path); {
case err != nil:
report(err)
case dir.IsDir():
walkDir(path)
default:
if err := processFile(path, nil, os.Stdout, argType); err != nil {
report(err)
}
}
}
}
func writeTempFile(dir, prefix string, data []byte) (string, error) {
file, err := ioutil.TempFile(dir, prefix)
if err != nil {
return "", err
}
_, err = file.Write(data)
if err1 := file.Close(); err == nil {
err = err1
}
if err != nil {
os.Remove(file.Name())
return "", err
}
return file.Name(), nil
}
func diff(b1, b2 []byte, filename string) (data []byte, err error) {
f1, err := writeTempFile("", "gofmt", b1)
if err != nil {
return
}
defer os.Remove(f1)
f2, err := writeTempFile("", "gofmt", b2)
if err != nil {
return
}
defer os.Remove(f2)
cmd := "diff"
if runtime.GOOS == "plan9" {
cmd = "/bin/ape/diff"
}
data, err = exec.Command(cmd, "-u", f1, f2).CombinedOutput()
if len(data) > 0 {
// diff exits with a non-zero status when the files don't match.
// Ignore that failure as long as we get output.
return replaceTempFilename(data, filename)
}
return
}
// replaceTempFilename replaces temporary filenames in diff with actual one.
//
// --- /tmp/gofmt316145376 2017-02-03 19:13:00.280468375 -0500
// +++ /tmp/gofmt617882815 2017-02-03 19:13:00.280468375 -0500
// ...
// ->
// --- path/to/file.go.orig 2017-02-03 19:13:00.280468375 -0500
// +++ path/to/file.go 2017-02-03 19:13:00.280468375 -0500
// ...
func replaceTempFilename(diff []byte, filename string) ([]byte, error) {
bs := bytes.SplitN(diff, []byte{'\n'}, 3)
if len(bs) < 3 {
return nil, fmt.Errorf("got unexpected diff for %s", filename)
}
// Preserve timestamps.
var t0, t1 []byte
if i := bytes.LastIndexByte(bs[0], '\t'); i != -1 {
t0 = bs[0][i:]
}
if i := bytes.LastIndexByte(bs[1], '\t'); i != -1 {
t1 = bs[1][i:]
}
// Always print filepath with slash separator.
f := filepath.ToSlash(filename)
bs[0] = []byte(fmt.Sprintf("--- %s%s", f+".orig", t0))
bs[1] = []byte(fmt.Sprintf("+++ %s%s", f, t1))
return bytes.Join(bs, []byte{'\n'}), nil
}
// isFile reports whether name is a file.
func isFile(name string) bool {
fi, err := os.Stat(name)
return err == nil && fi.Mode().IsRegular()
}
// isDir reports whether name is a directory.
func isDir(name string) bool {
fi, err := os.Stat(name)
return err == nil && fi.IsDir()
}

26
vendor/golang.org/x/tools/cmd/goimports/goimports_gc.go сгенерированный поставляемый Normal file
Просмотреть файл

@ -0,0 +1,26 @@
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build gc
package main
import (
"flag"
"runtime/trace"
)
var traceProfile = flag.String("trace", "", "trace profile output")
func doTrace() func() {
if *traceProfile != "" {
bw, flush := bufferedFileWriter(*traceProfile)
trace.Start(bw)
return func() {
flush()
trace.Stop()
}
}
return func() {}
}

11
vendor/golang.org/x/tools/cmd/goimports/goimports_not_gc.go сгенерированный поставляемый Normal file
Просмотреть файл

@ -0,0 +1,11 @@
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build !gc
package main
func doTrace() func() {
return func() {}
}

1581
vendor/golang.org/x/tools/internal/imports/fix.go сгенерированный поставляемый Normal file

Разница между файлами не показана из-за своего большого размера Загрузить разницу

397
vendor/golang.org/x/tools/internal/imports/imports.go сгенерированный поставляемый Normal file
Просмотреть файл

@ -0,0 +1,397 @@
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:generate go run mkstdlib.go
// Package imports implements a Go pretty-printer (like package "go/format")
// that also adds or removes import statements as necessary.
package imports
import (
"bufio"
"bytes"
"fmt"
"go/ast"
"go/build"
"go/format"
"go/parser"
"go/printer"
"go/token"
"io"
"io/ioutil"
"log"
"regexp"
"strconv"
"strings"
"golang.org/x/tools/go/ast/astutil"
)
// Options is golang.org/x/tools/imports.Options with extra internal-only options.
type Options struct {
Env *ProcessEnv // The environment to use. Note: this contains the cached module and filesystem state.
Fragment bool // Accept fragment of a source file (no package statement)
AllErrors bool // Report all errors (not just the first 10 on different lines)
Comments bool // Print comments (true if nil *Options provided)
TabIndent bool // Use tabs for indent (true if nil *Options provided)
TabWidth int // Tab width (8 if nil *Options provided)
FormatOnly bool // Disable the insertion and deletion of imports
}
// Process implements golang.org/x/tools/imports.Process with explicit context in env.
func Process(filename string, src []byte, opt *Options) (formatted []byte, err error) {
src, opt, err = initialize(filename, src, opt)
if err != nil {
return nil, err
}
fileSet := token.NewFileSet()
file, adjust, err := parse(fileSet, filename, src, opt)
if err != nil {
return nil, err
}
if !opt.FormatOnly {
if err := fixImports(fileSet, file, filename, opt.Env); err != nil {
return nil, err
}
}
return formatFile(fileSet, file, src, adjust, opt)
}
// FixImports returns a list of fixes to the imports that, when applied,
// will leave the imports in the same state as Process.
//
// Note that filename's directory influences which imports can be chosen,
// so it is important that filename be accurate.
func FixImports(filename string, src []byte, opt *Options) (fixes []*ImportFix, err error) {
src, opt, err = initialize(filename, src, opt)
if err != nil {
return nil, err
}
fileSet := token.NewFileSet()
file, _, err := parse(fileSet, filename, src, opt)
if err != nil {
return nil, err
}
return getFixes(fileSet, file, filename, opt.Env)
}
// ApplyFix will apply all of the fixes to the file and format it.
func ApplyFixes(fixes []*ImportFix, filename string, src []byte, opt *Options) (formatted []byte, err error) {
src, opt, err = initialize(filename, src, opt)
if err != nil {
return nil, err
}
fileSet := token.NewFileSet()
file, adjust, err := parse(fileSet, filename, src, opt)
if err != nil {
return nil, err
}
// Apply the fixes to the file.
apply(fileSet, file, fixes)
return formatFile(fileSet, file, src, adjust, opt)
}
// GetAllCandidates gets all of the standard library candidate packages to import in
// sorted order on import path.
func GetAllCandidates(filename string, opt *Options) (pkgs []ImportFix, err error) {
_, opt, err = initialize(filename, nil, opt)
if err != nil {
return nil, err
}
return getAllCandidates(filename, opt.Env)
}
// GetPackageExports returns all known packages with name pkg and their exports.
func GetPackageExports(pkg, filename string, opt *Options) (exports []PackageExport, err error) {
_, opt, err = initialize(filename, nil, opt)
if err != nil {
return nil, err
}
return getPackageExports(pkg, filename, opt.Env)
}
// initialize sets the values for opt and src.
// If they are provided, they are not changed. Otherwise opt is set to the
// default values and src is read from the file system.
func initialize(filename string, src []byte, opt *Options) ([]byte, *Options, error) {
// Use defaults if opt is nil.
if opt == nil {
opt = &Options{Comments: true, TabIndent: true, TabWidth: 8}
}
// Set the env if the user has not provided it.
if opt.Env == nil {
opt.Env = &ProcessEnv{
GOPATH: build.Default.GOPATH,
GOROOT: build.Default.GOROOT,
}
}
// Set the logger if the user has not provided it.
if opt.Env.Logf == nil {
opt.Env.Logf = log.Printf
}
if src == nil {
b, err := ioutil.ReadFile(filename)
if err != nil {
return nil, nil, err
}
src = b
}
return src, opt, nil
}
func formatFile(fileSet *token.FileSet, file *ast.File, src []byte, adjust func(orig []byte, src []byte) []byte, opt *Options) ([]byte, error) {
mergeImports(opt.Env, fileSet, file)
sortImports(opt.Env, fileSet, file)
imps := astutil.Imports(fileSet, file)
var spacesBefore []string // import paths we need spaces before
for _, impSection := range imps {
// Within each block of contiguous imports, see if any
// import lines are in different group numbers. If so,
// we'll need to put a space between them so it's
// compatible with gofmt.
lastGroup := -1
for _, importSpec := range impSection {
importPath, _ := strconv.Unquote(importSpec.Path.Value)
groupNum := importGroup(opt.Env, importPath)
if groupNum != lastGroup && lastGroup != -1 {
spacesBefore = append(spacesBefore, importPath)
}
lastGroup = groupNum
}
}
printerMode := printer.UseSpaces
if opt.TabIndent {
printerMode |= printer.TabIndent
}
printConfig := &printer.Config{Mode: printerMode, Tabwidth: opt.TabWidth}
var buf bytes.Buffer
err := printConfig.Fprint(&buf, fileSet, file)
if err != nil {
return nil, err
}
out := buf.Bytes()
if adjust != nil {
out = adjust(src, out)
}
if len(spacesBefore) > 0 {
out, err = addImportSpaces(bytes.NewReader(out), spacesBefore)
if err != nil {
return nil, err
}
}
out, err = format.Source(out)
if err != nil {
return nil, err
}
return out, nil
}
// parse parses src, which was read from filename,
// as a Go source file or statement list.
func parse(fset *token.FileSet, filename string, src []byte, opt *Options) (*ast.File, func(orig, src []byte) []byte, error) {
parserMode := parser.Mode(0)
if opt.Comments {
parserMode |= parser.ParseComments
}
if opt.AllErrors {
parserMode |= parser.AllErrors
}
// Try as whole source file.
file, err := parser.ParseFile(fset, filename, src, parserMode)
if err == nil {
return file, nil, nil
}
// If the error is that the source file didn't begin with a
// package line and we accept fragmented input, fall through to
// try as a source fragment. Stop and return on any other error.
if !opt.Fragment || !strings.Contains(err.Error(), "expected 'package'") {
return nil, nil, err
}
// If this is a declaration list, make it a source file
// by inserting a package clause.
// Insert using a ;, not a newline, so that parse errors are on
// the correct line.
const prefix = "package main;"
psrc := append([]byte(prefix), src...)
file, err = parser.ParseFile(fset, filename, psrc, parserMode)
if err == nil {
// Gofmt will turn the ; into a \n.
// Do that ourselves now and update the file contents,
// so that positions and line numbers are correct going forward.
psrc[len(prefix)-1] = '\n'
fset.File(file.Package).SetLinesForContent(psrc)
// If a main function exists, we will assume this is a main
// package and leave the file.
if containsMainFunc(file) {
return file, nil, nil
}
adjust := func(orig, src []byte) []byte {
// Remove the package clause.
src = src[len(prefix):]
return matchSpace(orig, src)
}
return file, adjust, nil
}
// If the error is that the source file didn't begin with a
// declaration, fall through to try as a statement list.
// Stop and return on any other error.
if !strings.Contains(err.Error(), "expected declaration") {
return nil, nil, err
}
// If this is a statement list, make it a source file
// by inserting a package clause and turning the list
// into a function body. This handles expressions too.
// Insert using a ;, not a newline, so that the line numbers
// in fsrc match the ones in src.
fsrc := append(append([]byte("package p; func _() {"), src...), '}')
file, err = parser.ParseFile(fset, filename, fsrc, parserMode)
if err == nil {
adjust := func(orig, src []byte) []byte {
// Remove the wrapping.
// Gofmt has turned the ; into a \n\n.
src = src[len("package p\n\nfunc _() {"):]
src = src[:len(src)-len("}\n")]
// Gofmt has also indented the function body one level.
// Remove that indent.
src = bytes.Replace(src, []byte("\n\t"), []byte("\n"), -1)
return matchSpace(orig, src)
}
return file, adjust, nil
}
// Failed, and out of options.
return nil, nil, err
}
// containsMainFunc checks if a file contains a function declaration with the
// function signature 'func main()'
func containsMainFunc(file *ast.File) bool {
for _, decl := range file.Decls {
if f, ok := decl.(*ast.FuncDecl); ok {
if f.Name.Name != "main" {
continue
}
if len(f.Type.Params.List) != 0 {
continue
}
if f.Type.Results != nil && len(f.Type.Results.List) != 0 {
continue
}
return true
}
}
return false
}
func cutSpace(b []byte) (before, middle, after []byte) {
i := 0
for i < len(b) && (b[i] == ' ' || b[i] == '\t' || b[i] == '\n') {
i++
}
j := len(b)
for j > 0 && (b[j-1] == ' ' || b[j-1] == '\t' || b[j-1] == '\n') {
j--
}
if i <= j {
return b[:i], b[i:j], b[j:]
}
return nil, nil, b[j:]
}
// matchSpace reformats src to use the same space context as orig.
// 1) If orig begins with blank lines, matchSpace inserts them at the beginning of src.
// 2) matchSpace copies the indentation of the first non-blank line in orig
// to every non-blank line in src.
// 3) matchSpace copies the trailing space from orig and uses it in place
// of src's trailing space.
func matchSpace(orig []byte, src []byte) []byte {
before, _, after := cutSpace(orig)
i := bytes.LastIndex(before, []byte{'\n'})
before, indent := before[:i+1], before[i+1:]
_, src, _ = cutSpace(src)
var b bytes.Buffer
b.Write(before)
for len(src) > 0 {
line := src
if i := bytes.IndexByte(line, '\n'); i >= 0 {
line, src = line[:i+1], line[i+1:]
} else {
src = nil
}
if len(line) > 0 && line[0] != '\n' { // not blank
b.Write(indent)
}
b.Write(line)
}
b.Write(after)
return b.Bytes()
}
var impLine = regexp.MustCompile(`^\s+(?:[\w\.]+\s+)?"(.+)"`)
func addImportSpaces(r io.Reader, breaks []string) ([]byte, error) {
var out bytes.Buffer
in := bufio.NewReader(r)
inImports := false
done := false
for {
s, err := in.ReadString('\n')
if err == io.EOF {
break
} else if err != nil {
return nil, err
}
if !inImports && !done && strings.HasPrefix(s, "import") {
inImports = true
}
if inImports && (strings.HasPrefix(s, "var") ||
strings.HasPrefix(s, "func") ||
strings.HasPrefix(s, "const") ||
strings.HasPrefix(s, "type")) {
done = true
inImports = false
}
if inImports && len(breaks) > 0 {
if m := impLine.FindStringSubmatch(s); m != nil {
if m[1] == breaks[0] {
out.WriteByte('\n')
breaks = breaks[1:]
}
}
}
fmt.Fprint(&out, s)
}
return out.Bytes(), nil
}

173
vendor/golang.org/x/tools/internal/imports/mkindex.go сгенерированный поставляемый Normal file
Просмотреть файл

@ -0,0 +1,173 @@
// +build ignore
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Command mkindex creates the file "pkgindex.go" containing an index of the Go
// standard library. The file is intended to be built as part of the imports
// package, so that the package may be used in environments where a GOROOT is
// not available (such as App Engine).
package imports
import (
"bytes"
"fmt"
"go/ast"
"go/build"
"go/format"
"go/parser"
"go/token"
"io/ioutil"
"log"
"os"
"path"
"path/filepath"
"strings"
)
var (
pkgIndex = make(map[string][]pkg)
exports = make(map[string]map[string]bool)
)
func main() {
// Don't use GOPATH.
ctx := build.Default
ctx.GOPATH = ""
// Populate pkgIndex global from GOROOT.
for _, path := range ctx.SrcDirs() {
f, err := os.Open(path)
if err != nil {
log.Print(err)
continue
}
children, err := f.Readdir(-1)
f.Close()
if err != nil {
log.Print(err)
continue
}
for _, child := range children {
if child.IsDir() {
loadPkg(path, child.Name())
}
}
}
// Populate exports global.
for _, ps := range pkgIndex {
for _, p := range ps {
e := loadExports(p.dir)
if e != nil {
exports[p.dir] = e
}
}
}
// Construct source file.
var buf bytes.Buffer
fmt.Fprint(&buf, pkgIndexHead)
fmt.Fprintf(&buf, "var pkgIndexMaster = %#v\n", pkgIndex)
fmt.Fprintf(&buf, "var exportsMaster = %#v\n", exports)
src := buf.Bytes()
// Replace main.pkg type name with pkg.
src = bytes.Replace(src, []byte("main.pkg"), []byte("pkg"), -1)
// Replace actual GOROOT with "/go".
src = bytes.Replace(src, []byte(ctx.GOROOT), []byte("/go"), -1)
// Add some line wrapping.
src = bytes.Replace(src, []byte("}, "), []byte("},\n"), -1)
src = bytes.Replace(src, []byte("true, "), []byte("true,\n"), -1)
var err error
src, err = format.Source(src)
if err != nil {
log.Fatal(err)
}
// Write out source file.
err = ioutil.WriteFile("pkgindex.go", src, 0644)
if err != nil {
log.Fatal(err)
}
}
const pkgIndexHead = `package imports
func init() {
pkgIndexOnce.Do(func() {
pkgIndex.m = pkgIndexMaster
})
loadExports = func(dir string) map[string]bool {
return exportsMaster[dir]
}
}
`
type pkg struct {
importpath string // full pkg import path, e.g. "net/http"
dir string // absolute file path to pkg directory e.g. "/usr/lib/go/src/fmt"
}
var fset = token.NewFileSet()
func loadPkg(root, importpath string) {
shortName := path.Base(importpath)
if shortName == "testdata" {
return
}
dir := filepath.Join(root, importpath)
pkgIndex[shortName] = append(pkgIndex[shortName], pkg{
importpath: importpath,
dir: dir,
})
pkgDir, err := os.Open(dir)
if err != nil {
return
}
children, err := pkgDir.Readdir(-1)
pkgDir.Close()
if err != nil {
return
}
for _, child := range children {
name := child.Name()
if name == "" {
continue
}
if c := name[0]; c == '.' || ('0' <= c && c <= '9') {
continue
}
if child.IsDir() {
loadPkg(root, filepath.Join(importpath, name))
}
}
}
func loadExports(dir string) map[string]bool {
exports := make(map[string]bool)
buildPkg, err := build.ImportDir(dir, 0)
if err != nil {
if strings.Contains(err.Error(), "no buildable Go source files in") {
return nil
}
log.Printf("could not import %q: %v", dir, err)
return nil
}
for _, file := range buildPkg.GoFiles {
f, err := parser.ParseFile(fset, filepath.Join(dir, file), nil, 0)
if err != nil {
log.Printf("could not parse %q: %v", file, err)
continue
}
for name := range f.Scope.Objects {
if ast.IsExported(name) {
exports[name] = true
}
}
}
return exports
}

128
vendor/golang.org/x/tools/internal/imports/mkstdlib.go сгенерированный поставляемый Normal file
Просмотреть файл

@ -0,0 +1,128 @@
// +build ignore
// mkstdlib generates the zstdlib.go file, containing the Go standard
// library API symbols. It's baked into the binary to avoid scanning
// GOPATH in the common case.
package main
import (
"bufio"
"bytes"
"fmt"
"go/format"
"io"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"sort"
)
func mustOpen(name string) io.Reader {
f, err := os.Open(name)
if err != nil {
log.Fatal(err)
}
return f
}
func api(base string) string {
return filepath.Join(runtime.GOROOT(), "api", base)
}
var sym = regexp.MustCompile(`^pkg (\S+).*?, (?:var|func|type|const) ([A-Z]\w*)`)
var unsafeSyms = map[string]bool{"Alignof": true, "ArbitraryType": true, "Offsetof": true, "Pointer": true, "Sizeof": true}
func main() {
var buf bytes.Buffer
outf := func(format string, args ...interface{}) {
fmt.Fprintf(&buf, format, args...)
}
outf("// Code generated by mkstdlib.go. DO NOT EDIT.\n\n")
outf("package imports\n")
outf("var stdlib = map[string][]string{\n")
f := io.MultiReader(
mustOpen(api("go1.txt")),
mustOpen(api("go1.1.txt")),
mustOpen(api("go1.2.txt")),
mustOpen(api("go1.3.txt")),
mustOpen(api("go1.4.txt")),
mustOpen(api("go1.5.txt")),
mustOpen(api("go1.6.txt")),
mustOpen(api("go1.7.txt")),
mustOpen(api("go1.8.txt")),
mustOpen(api("go1.9.txt")),
mustOpen(api("go1.10.txt")),
mustOpen(api("go1.11.txt")),
mustOpen(api("go1.12.txt")),
mustOpen(api("go1.13.txt")),
// The API of the syscall/js package needs to be computed explicitly,
// because it's not included in the GOROOT/api/go1.*.txt files at this time.
syscallJSAPI(),
)
sc := bufio.NewScanner(f)
pkgs := map[string]map[string]bool{
"unsafe": unsafeSyms,
}
paths := []string{"unsafe"}
for sc.Scan() {
l := sc.Text()
if m := sym.FindStringSubmatch(l); m != nil {
path, sym := m[1], m[2]
if _, ok := pkgs[path]; !ok {
pkgs[path] = map[string]bool{}
paths = append(paths, path)
}
pkgs[path][sym] = true
}
}
if err := sc.Err(); err != nil {
log.Fatal(err)
}
sort.Strings(paths)
for _, path := range paths {
outf("\t%q: []string{\n", path)
pkg := pkgs[path]
var syms []string
for sym := range pkg {
syms = append(syms, sym)
}
sort.Strings(syms)
for _, sym := range syms {
outf("\t\t%q,\n", sym)
}
outf("},\n")
}
outf("}\n")
fmtbuf, err := format.Source(buf.Bytes())
if err != nil {
log.Fatal(err)
}
err = ioutil.WriteFile("zstdlib.go", fmtbuf, 0666)
if err != nil {
log.Fatal(err)
}
}
// syscallJSAPI returns the API of the syscall/js package.
// It's computed from the contents of $(go env GOROOT)/src/syscall/js.
func syscallJSAPI() io.Reader {
var exeSuffix string
if runtime.GOOS == "windows" {
exeSuffix = ".exe"
}
cmd := exec.Command("go"+exeSuffix, "run", "cmd/api", "-contexts", "js-wasm", "syscall/js")
out, err := cmd.Output()
if err != nil {
log.Fatalln(err)
}
return bytes.NewReader(out)
}

643
vendor/golang.org/x/tools/internal/imports/mod.go сгенерированный поставляемый Normal file
Просмотреть файл

@ -0,0 +1,643 @@
package imports
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"golang.org/x/tools/internal/gopathwalk"
"golang.org/x/tools/internal/module"
"golang.org/x/tools/internal/semver"
)
// ModuleResolver implements resolver for modules using the go command as little
// as feasible.
type ModuleResolver struct {
env *ProcessEnv
moduleCacheDir string
dummyVendorMod *ModuleJSON // If vendoring is enabled, the pseudo-module that represents the /vendor directory.
Initialized bool
Main *ModuleJSON
ModsByModPath []*ModuleJSON // All modules, ordered by # of path components in module Path...
ModsByDir []*ModuleJSON // ...or Dir.
// moduleCacheCache stores information about the module cache.
moduleCacheCache *dirInfoCache
otherCache *dirInfoCache
}
type ModuleJSON struct {
Path string // module path
Replace *ModuleJSON // replaced by this module
Main bool // is this the main module?
Dir string // directory holding files for this module, if any
GoMod string // path to go.mod file for this module, if any
GoVersion string // go version used in module
}
func (r *ModuleResolver) init() error {
if r.Initialized {
return nil
}
mainMod, vendorEnabled, err := vendorEnabled(r.env)
if err != nil {
return err
}
if mainMod != nil && vendorEnabled {
// Vendor mode is on, so all the non-Main modules are irrelevant,
// and we need to search /vendor for everything.
r.Main = mainMod
r.dummyVendorMod = &ModuleJSON{
Path: "",
Dir: filepath.Join(mainMod.Dir, "vendor"),
}
r.ModsByModPath = []*ModuleJSON{mainMod, r.dummyVendorMod}
r.ModsByDir = []*ModuleJSON{mainMod, r.dummyVendorMod}
} else {
// Vendor mode is off, so run go list -m ... to find everything.
r.initAllMods()
}
r.moduleCacheDir = filepath.Join(filepath.SplitList(r.env.GOPATH)[0], "/pkg/mod")
sort.Slice(r.ModsByModPath, func(i, j int) bool {
count := func(x int) int {
return strings.Count(r.ModsByModPath[x].Path, "/")
}
return count(j) < count(i) // descending order
})
sort.Slice(r.ModsByDir, func(i, j int) bool {
count := func(x int) int {
return strings.Count(r.ModsByDir[x].Dir, "/")
}
return count(j) < count(i) // descending order
})
if r.moduleCacheCache == nil {
r.moduleCacheCache = &dirInfoCache{
dirs: map[string]*directoryPackageInfo{},
}
}
if r.otherCache == nil {
r.otherCache = &dirInfoCache{
dirs: map[string]*directoryPackageInfo{},
}
}
r.Initialized = true
return nil
}
func (r *ModuleResolver) initAllMods() error {
stdout, err := r.env.invokeGo("list", "-m", "-json", "...")
if err != nil {
return err
}
for dec := json.NewDecoder(stdout); dec.More(); {
mod := &ModuleJSON{}
if err := dec.Decode(mod); err != nil {
return err
}
if mod.Dir == "" {
if r.env.Debug {
r.env.Logf("module %v has not been downloaded and will be ignored", mod.Path)
}
// Can't do anything with a module that's not downloaded.
continue
}
r.ModsByModPath = append(r.ModsByModPath, mod)
r.ModsByDir = append(r.ModsByDir, mod)
if mod.Main {
r.Main = mod
}
}
return nil
}
func (r *ModuleResolver) ClearForNewScan() {
r.otherCache = &dirInfoCache{
dirs: map[string]*directoryPackageInfo{},
}
}
func (r *ModuleResolver) ClearForNewMod() {
env := r.env
*r = ModuleResolver{
env: env,
}
r.init()
}
// findPackage returns the module and directory that contains the package at
// the given import path, or returns nil, "" if no module is in scope.
func (r *ModuleResolver) findPackage(importPath string) (*ModuleJSON, string) {
// This can't find packages in the stdlib, but that's harmless for all
// the existing code paths.
for _, m := range r.ModsByModPath {
if !strings.HasPrefix(importPath, m.Path) {
continue
}
pathInModule := importPath[len(m.Path):]
pkgDir := filepath.Join(m.Dir, pathInModule)
if r.dirIsNestedModule(pkgDir, m) {
continue
}
if info, ok := r.cacheLoad(pkgDir); ok {
if loaded, err := info.reachedStatus(nameLoaded); loaded {
if err != nil {
continue // No package in this dir.
}
return m, pkgDir
}
if scanned, err := info.reachedStatus(directoryScanned); scanned && err != nil {
continue // Dir is unreadable, etc.
}
// This is slightly wrong: a directory doesn't have to have an
// importable package to count as a package for package-to-module
// resolution. package main or _test files should count but
// don't.
// TODO(heschi): fix this.
if _, err := r.cachePackageName(info); err == nil {
return m, pkgDir
}
}
// Not cached. Read the filesystem.
pkgFiles, err := ioutil.ReadDir(pkgDir)
if err != nil {
continue
}
// A module only contains a package if it has buildable go
// files in that directory. If not, it could be provided by an
// outer module. See #29736.
for _, fi := range pkgFiles {
if ok, _ := r.env.buildContext().MatchFile(pkgDir, fi.Name()); ok {
return m, pkgDir
}
}
}
return nil, ""
}
func (r *ModuleResolver) cacheLoad(dir string) (directoryPackageInfo, bool) {
if info, ok := r.moduleCacheCache.Load(dir); ok {
return info, ok
}
return r.otherCache.Load(dir)
}
func (r *ModuleResolver) cacheStore(info directoryPackageInfo) {
if info.rootType == gopathwalk.RootModuleCache {
r.moduleCacheCache.Store(info.dir, info)
} else {
r.otherCache.Store(info.dir, info)
}
}
func (r *ModuleResolver) cacheKeys() []string {
return append(r.moduleCacheCache.Keys(), r.otherCache.Keys()...)
}
// cachePackageName caches the package name for a dir already in the cache.
func (r *ModuleResolver) cachePackageName(info directoryPackageInfo) (directoryPackageInfo, error) {
if info.rootType == gopathwalk.RootModuleCache {
return r.moduleCacheCache.CachePackageName(info)
}
return r.otherCache.CachePackageName(info)
}
func (r *ModuleResolver) cacheExports(ctx context.Context, env *ProcessEnv, info directoryPackageInfo) (string, []string, error) {
if info.rootType == gopathwalk.RootModuleCache {
return r.moduleCacheCache.CacheExports(ctx, env, info)
}
return r.otherCache.CacheExports(ctx, env, info)
}
// findModuleByDir returns the module that contains dir, or nil if no such
// module is in scope.
func (r *ModuleResolver) findModuleByDir(dir string) *ModuleJSON {
// This is quite tricky and may not be correct. dir could be:
// - a package in the main module.
// - a replace target underneath the main module's directory.
// - a nested module in the above.
// - a replace target somewhere totally random.
// - a nested module in the above.
// - in the mod cache.
// - in /vendor/ in -mod=vendor mode.
// - nested module? Dunno.
// Rumor has it that replace targets cannot contain other replace targets.
for _, m := range r.ModsByDir {
if !strings.HasPrefix(dir, m.Dir) {
continue
}
if r.dirIsNestedModule(dir, m) {
continue
}
return m
}
return nil
}
// dirIsNestedModule reports if dir is contained in a nested module underneath
// mod, not actually in mod.
func (r *ModuleResolver) dirIsNestedModule(dir string, mod *ModuleJSON) bool {
if !strings.HasPrefix(dir, mod.Dir) {
return false
}
if r.dirInModuleCache(dir) {
// Nested modules in the module cache are pruned,
// so it cannot be a nested module.
return false
}
if mod != nil && mod == r.dummyVendorMod {
// The /vendor pseudomodule is flattened and doesn't actually count.
return false
}
modDir, _ := r.modInfo(dir)
if modDir == "" {
return false
}
return modDir != mod.Dir
}
func (r *ModuleResolver) modInfo(dir string) (modDir string, modName string) {
readModName := func(modFile string) string {
modBytes, err := ioutil.ReadFile(modFile)
if err != nil {
return ""
}
return modulePath(modBytes)
}
if r.dirInModuleCache(dir) {
matches := modCacheRegexp.FindStringSubmatch(dir)
index := strings.Index(dir, matches[1]+"@"+matches[2])
modDir := filepath.Join(dir[:index], matches[1]+"@"+matches[2])
return modDir, readModName(filepath.Join(modDir, "go.mod"))
}
for {
if info, ok := r.cacheLoad(dir); ok {
return info.moduleDir, info.moduleName
}
f := filepath.Join(dir, "go.mod")
info, err := os.Stat(f)
if err == nil && !info.IsDir() {
return dir, readModName(f)
}
d := filepath.Dir(dir)
if len(d) >= len(dir) {
return "", "" // reached top of file system, no go.mod
}
dir = d
}
}
func (r *ModuleResolver) dirInModuleCache(dir string) bool {
if r.moduleCacheDir == "" {
return false
}
return strings.HasPrefix(dir, r.moduleCacheDir)
}
func (r *ModuleResolver) loadPackageNames(importPaths []string, srcDir string) (map[string]string, error) {
if err := r.init(); err != nil {
return nil, err
}
names := map[string]string{}
for _, path := range importPaths {
_, packageDir := r.findPackage(path)
if packageDir == "" {
continue
}
name, err := packageDirToName(packageDir)
if err != nil {
continue
}
names[path] = name
}
return names, nil
}
func (r *ModuleResolver) scan(_ references, loadNames bool, exclude []gopathwalk.RootType) ([]*pkg, error) {
if err := r.init(); err != nil {
return nil, err
}
// Walk GOROOT, GOPATH/pkg/mod, and the main module.
roots := []gopathwalk.Root{
{filepath.Join(r.env.GOROOT, "/src"), gopathwalk.RootGOROOT},
}
if r.Main != nil {
roots = append(roots, gopathwalk.Root{r.Main.Dir, gopathwalk.RootCurrentModule})
}
if r.dummyVendorMod != nil {
roots = append(roots, gopathwalk.Root{r.dummyVendorMod.Dir, gopathwalk.RootOther})
} else {
roots = append(roots, gopathwalk.Root{r.moduleCacheDir, gopathwalk.RootModuleCache})
// Walk replace targets, just in case they're not in any of the above.
for _, mod := range r.ModsByModPath {
if mod.Replace != nil {
roots = append(roots, gopathwalk.Root{mod.Dir, gopathwalk.RootOther})
}
}
}
roots = filterRoots(roots, exclude)
var result []*pkg
var mu sync.Mutex
// We assume cached directories have not changed. We can skip them and their
// children.
skip := func(root gopathwalk.Root, dir string) bool {
mu.Lock()
defer mu.Unlock()
info, ok := r.cacheLoad(dir)
if !ok {
return false
}
// This directory can be skipped as long as we have already scanned it.
// Packages with errors will continue to have errors, so there is no need
// to rescan them.
packageScanned, _ := info.reachedStatus(directoryScanned)
return packageScanned
}
// Add anything new to the cache. We'll process everything in it below.
add := func(root gopathwalk.Root, dir string) {
mu.Lock()
defer mu.Unlock()
r.cacheStore(r.scanDirForPackage(root, dir))
}
gopathwalk.WalkSkip(roots, add, skip, gopathwalk.Options{Debug: r.env.Debug, ModulesEnabled: true})
// Everything we already had, and everything new, is now in the cache.
for _, dir := range r.cacheKeys() {
info, ok := r.cacheLoad(dir)
if !ok {
continue
}
// Skip this directory if we were not able to get the package information successfully.
if scanned, err := info.reachedStatus(directoryScanned); !scanned || err != nil {
continue
}
// If we want package names, make sure the cache has them.
if loadNames {
var err error
if info, err = r.cachePackageName(info); err != nil {
continue
}
}
res, err := r.canonicalize(info)
if err != nil {
continue
}
result = append(result, res)
}
return result, nil
}
// canonicalize gets the result of canonicalizing the packages using the results
// of initializing the resolver from 'go list -m'.
func (r *ModuleResolver) canonicalize(info directoryPackageInfo) (*pkg, error) {
// Packages in GOROOT are already canonical, regardless of the std/cmd modules.
if info.rootType == gopathwalk.RootGOROOT {
return &pkg{
importPathShort: info.nonCanonicalImportPath,
dir: info.dir,
packageName: path.Base(info.nonCanonicalImportPath),
relevance: 0,
}, nil
}
importPath := info.nonCanonicalImportPath
relevance := 2
// Check if the directory is underneath a module that's in scope.
if mod := r.findModuleByDir(info.dir); mod != nil {
relevance = 1
// It is. If dir is the target of a replace directive,
// our guessed import path is wrong. Use the real one.
if mod.Dir == info.dir {
importPath = mod.Path
} else {
dirInMod := info.dir[len(mod.Dir)+len("/"):]
importPath = path.Join(mod.Path, filepath.ToSlash(dirInMod))
}
} else if info.needsReplace {
return nil, fmt.Errorf("package in %q is not valid without a replace statement", info.dir)
}
res := &pkg{
importPathShort: importPath,
dir: info.dir,
packageName: info.packageName, // may not be populated if the caller didn't ask for it
relevance: relevance,
}
// We may have discovered a package that has a different version
// in scope already. Canonicalize to that one if possible.
if _, canonicalDir := r.findPackage(importPath); canonicalDir != "" {
res.dir = canonicalDir
}
return res, nil
}
func (r *ModuleResolver) loadExports(ctx context.Context, pkg *pkg) (string, []string, error) {
if err := r.init(); err != nil {
return "", nil, err
}
if info, ok := r.cacheLoad(pkg.dir); ok {
return r.cacheExports(ctx, r.env, info)
}
return loadExportsFromFiles(ctx, r.env, pkg.dir)
}
func (r *ModuleResolver) scanDirForPackage(root gopathwalk.Root, dir string) directoryPackageInfo {
subdir := ""
if dir != root.Path {
subdir = dir[len(root.Path)+len("/"):]
}
importPath := filepath.ToSlash(subdir)
if strings.HasPrefix(importPath, "vendor/") {
// Only enter vendor directories if they're explicitly requested as a root.
return directoryPackageInfo{
status: directoryScanned,
err: fmt.Errorf("unwanted vendor directory"),
}
}
switch root.Type {
case gopathwalk.RootCurrentModule:
importPath = path.Join(r.Main.Path, filepath.ToSlash(subdir))
case gopathwalk.RootModuleCache:
matches := modCacheRegexp.FindStringSubmatch(subdir)
if len(matches) == 0 {
return directoryPackageInfo{
status: directoryScanned,
err: fmt.Errorf("invalid module cache path: %v", subdir),
}
}
modPath, err := module.DecodePath(filepath.ToSlash(matches[1]))
if err != nil {
if r.env.Debug {
r.env.Logf("decoding module cache path %q: %v", subdir, err)
}
return directoryPackageInfo{
status: directoryScanned,
err: fmt.Errorf("decoding module cache path %q: %v", subdir, err),
}
}
importPath = path.Join(modPath, filepath.ToSlash(matches[3]))
}
modDir, modName := r.modInfo(dir)
result := directoryPackageInfo{
status: directoryScanned,
dir: dir,
rootType: root.Type,
nonCanonicalImportPath: importPath,
needsReplace: false,
moduleDir: modDir,
moduleName: modName,
}
if root.Type == gopathwalk.RootGOROOT {
// stdlib packages are always in scope, despite the confusing go.mod
return result
}
// Check that this package is not obviously impossible to import.
if !strings.HasPrefix(importPath, modName) {
// The module's declared path does not match
// its expected path. It probably needs a
// replace directive we don't have.
result.needsReplace = true
}
return result
}
// modCacheRegexp splits a path in a module cache into module, module version, and package.
var modCacheRegexp = regexp.MustCompile(`(.*)@([^/\\]*)(.*)`)
var (
slashSlash = []byte("//")
moduleStr = []byte("module")
)
// modulePath returns the module path from the gomod file text.
// If it cannot find a module path, it returns an empty string.
// It is tolerant of unrelated problems in the go.mod file.
//
// Copied from cmd/go/internal/modfile.
func modulePath(mod []byte) string {
for len(mod) > 0 {
line := mod
mod = nil
if i := bytes.IndexByte(line, '\n'); i >= 0 {
line, mod = line[:i], line[i+1:]
}
if i := bytes.Index(line, slashSlash); i >= 0 {
line = line[:i]
}
line = bytes.TrimSpace(line)
if !bytes.HasPrefix(line, moduleStr) {
continue
}
line = line[len(moduleStr):]
n := len(line)
line = bytes.TrimSpace(line)
if len(line) == n || len(line) == 0 {
continue
}
if line[0] == '"' || line[0] == '`' {
p, err := strconv.Unquote(string(line))
if err != nil {
return "" // malformed quoted string or multiline module path
}
return p
}
return string(line)
}
return "" // missing module path
}
var modFlagRegexp = regexp.MustCompile(`-mod[ =](\w+)`)
// vendorEnabled indicates if vendoring is enabled.
// Inspired by setDefaultBuildMod in modload/init.go
func vendorEnabled(env *ProcessEnv) (*ModuleJSON, bool, error) {
mainMod, go114, err := getMainModuleAnd114(env)
if err != nil {
return nil, false, err
}
matches := modFlagRegexp.FindStringSubmatch(env.GOFLAGS)
var modFlag string
if len(matches) != 0 {
modFlag = matches[1]
}
if modFlag != "" {
// Don't override an explicit '-mod=' argument.
return mainMod, modFlag == "vendor", nil
}
if mainMod == nil || !go114 {
return mainMod, false, nil
}
// Check 1.14's automatic vendor mode.
if fi, err := os.Stat(filepath.Join(mainMod.Dir, "vendor")); err == nil && fi.IsDir() {
if mainMod.GoVersion != "" && semver.Compare("v"+mainMod.GoVersion, "v1.14") >= 0 {
// The Go version is at least 1.14, and a vendor directory exists.
// Set -mod=vendor by default.
return mainMod, true, nil
}
}
return mainMod, false, nil
}
// getMainModuleAnd114 gets the main module's information and whether the
// go command in use is 1.14+. This is the information needed to figure out
// if vendoring should be enabled.
func getMainModuleAnd114(env *ProcessEnv) (*ModuleJSON, bool, error) {
const format = `{{.Path}}
{{.Dir}}
{{.GoMod}}
{{.GoVersion}}
{{range context.ReleaseTags}}{{if eq . "go1.14"}}{{.}}{{end}}{{end}}
`
stdout, err := env.invokeGo("list", "-m", "-f", format)
if err != nil {
return nil, false, nil
}
lines := strings.Split(stdout.String(), "\n")
if len(lines) < 5 {
return nil, false, fmt.Errorf("unexpected stdout: %q", stdout)
}
mod := &ModuleJSON{
Path: lines[0],
Dir: lines[1],
GoMod: lines[2],
GoVersion: lines[3],
Main: true,
}
return mod, lines[4] == "go1.14", nil
}

165
vendor/golang.org/x/tools/internal/imports/mod_cache.go сгенерированный поставляемый Normal file
Просмотреть файл

@ -0,0 +1,165 @@
package imports
import (
"context"
"fmt"
"sync"
"golang.org/x/tools/internal/gopathwalk"
)
// To find packages to import, the resolver needs to know about all of the
// the packages that could be imported. This includes packages that are
// already in modules that are in (1) the current module, (2) replace targets,
// and (3) packages in the module cache. Packages in (1) and (2) may change over
// time, as the client may edit the current module and locally replaced modules.
// The module cache (which includes all of the packages in (3)) can only
// ever be added to.
//
// The resolver can thus save state about packages in the module cache
// and guarantee that this will not change over time. To obtain information
// about new modules added to the module cache, the module cache should be
// rescanned.
//
// It is OK to serve information about modules that have been deleted,
// as they do still exist.
// TODO(suzmue): can we share information with the caller about
// what module needs to be downloaded to import this package?
type directoryPackageStatus int
const (
_ directoryPackageStatus = iota
directoryScanned
nameLoaded
exportsLoaded
)
type directoryPackageInfo struct {
// status indicates the extent to which this struct has been filled in.
status directoryPackageStatus
// err is non-nil when there was an error trying to reach status.
err error
// Set when status >= directoryScanned.
// dir is the absolute directory of this package.
dir string
rootType gopathwalk.RootType
// nonCanonicalImportPath is the package's expected import path. It may
// not actually be importable at that path.
nonCanonicalImportPath string
// needsReplace is true if the nonCanonicalImportPath does not match the
// module's declared path, making it impossible to import without a
// replace directive.
needsReplace bool
// Module-related information.
moduleDir string // The directory that is the module root of this dir.
moduleName string // The module name that contains this dir.
// Set when status >= nameLoaded.
packageName string // the package name, as declared in the source.
// Set when status >= exportsLoaded.
exports []string
}
// reachedStatus returns true when info has a status at least target and any error associated with
// an attempt to reach target.
func (info *directoryPackageInfo) reachedStatus(target directoryPackageStatus) (bool, error) {
if info.err == nil {
return info.status >= target, nil
}
if info.status == target {
return true, info.err
}
return true, nil
}
// dirInfoCache is a concurrency safe map for storing information about
// directories that may contain packages.
//
// The information in this cache is built incrementally. Entries are initialized in scan.
// No new keys should be added in any other functions, as all directories containing
// packages are identified in scan.
//
// Other functions, including loadExports and findPackage, may update entries in this cache
// as they discover new things about the directory.
//
// The information in the cache is not expected to change for the cache's
// lifetime, so there is no protection against competing writes. Users should
// take care not to hold the cache across changes to the underlying files.
//
// TODO(suzmue): consider other concurrency strategies and data structures (RWLocks, sync.Map, etc)
type dirInfoCache struct {
mu sync.Mutex
// dirs stores information about packages in directories, keyed by absolute path.
dirs map[string]*directoryPackageInfo
}
// Store stores the package info for dir.
func (d *dirInfoCache) Store(dir string, info directoryPackageInfo) {
d.mu.Lock()
defer d.mu.Unlock()
stored := info // defensive copy
d.dirs[dir] = &stored
}
// Load returns a copy of the directoryPackageInfo for absolute directory dir.
func (d *dirInfoCache) Load(dir string) (directoryPackageInfo, bool) {
d.mu.Lock()
defer d.mu.Unlock()
info, ok := d.dirs[dir]
if !ok {
return directoryPackageInfo{}, false
}
return *info, true
}
// Keys returns the keys currently present in d.
func (d *dirInfoCache) Keys() (keys []string) {
d.mu.Lock()
defer d.mu.Unlock()
for key := range d.dirs {
keys = append(keys, key)
}
return keys
}
func (d *dirInfoCache) CachePackageName(info directoryPackageInfo) (directoryPackageInfo, error) {
if loaded, err := info.reachedStatus(nameLoaded); loaded {
return info, err
}
if scanned, err := info.reachedStatus(directoryScanned); !scanned || err != nil {
return info, fmt.Errorf("cannot read package name, scan error: %v", err)
}
info.packageName, info.err = packageDirToName(info.dir)
info.status = nameLoaded
d.Store(info.dir, info)
return info, info.err
}
func (d *dirInfoCache) CacheExports(ctx context.Context, env *ProcessEnv, info directoryPackageInfo) (string, []string, error) {
if reached, _ := info.reachedStatus(exportsLoaded); reached {
return info.packageName, info.exports, info.err
}
if reached, err := info.reachedStatus(nameLoaded); reached && err != nil {
return "", nil, err
}
info.packageName, info.exports, info.err = loadExportsFromFiles(ctx, env, info.dir)
if info.err == context.Canceled {
return info.packageName, info.exports, info.err
}
// The cache structure wants things to proceed linearly. We can skip a
// step here, but only if we succeed.
if info.status == nameLoaded || info.err == nil {
info.status = exportsLoaded
} else {
info.status = nameLoaded
}
d.Store(info.dir, info)
return info.packageName, info.exports, info.err
}

280
vendor/golang.org/x/tools/internal/imports/sortimports.go сгенерированный поставляемый Normal file
Просмотреть файл

@ -0,0 +1,280 @@
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Hacked up copy of go/ast/import.go
package imports
import (
"go/ast"
"go/token"
"sort"
"strconv"
)
// sortImports sorts runs of consecutive import lines in import blocks in f.
// It also removes duplicate imports when it is possible to do so without data loss.
func sortImports(env *ProcessEnv, fset *token.FileSet, f *ast.File) {
for i, d := range f.Decls {
d, ok := d.(*ast.GenDecl)
if !ok || d.Tok != token.IMPORT {
// Not an import declaration, so we're done.
// Imports are always first.
break
}
if len(d.Specs) == 0 {
// Empty import block, remove it.
f.Decls = append(f.Decls[:i], f.Decls[i+1:]...)
}
if !d.Lparen.IsValid() {
// Not a block: sorted by default.
continue
}
// Identify and sort runs of specs on successive lines.
i := 0
specs := d.Specs[:0]
for j, s := range d.Specs {
if j > i && fset.Position(s.Pos()).Line > 1+fset.Position(d.Specs[j-1].End()).Line {
// j begins a new run. End this one.
specs = append(specs, sortSpecs(env, fset, f, d.Specs[i:j])...)
i = j
}
}
specs = append(specs, sortSpecs(env, fset, f, d.Specs[i:])...)
d.Specs = specs
// Deduping can leave a blank line before the rparen; clean that up.
if len(d.Specs) > 0 {
lastSpec := d.Specs[len(d.Specs)-1]
lastLine := fset.Position(lastSpec.Pos()).Line
if rParenLine := fset.Position(d.Rparen).Line; rParenLine > lastLine+1 {
fset.File(d.Rparen).MergeLine(rParenLine - 1)
}
}
}
}
// mergeImports merges all the import declarations into the first one.
// Taken from golang.org/x/tools/ast/astutil.
func mergeImports(env *ProcessEnv, fset *token.FileSet, f *ast.File) {
if len(f.Decls) <= 1 {
return
}
// Merge all the import declarations into the first one.
var first *ast.GenDecl
for i := 0; i < len(f.Decls); i++ {
decl := f.Decls[i]
gen, ok := decl.(*ast.GenDecl)
if !ok || gen.Tok != token.IMPORT || declImports(gen, "C") {
continue
}
if first == nil {
first = gen
continue // Don't touch the first one.
}
// We now know there is more than one package in this import
// declaration. Ensure that it ends up parenthesized.
first.Lparen = first.Pos()
// Move the imports of the other import declaration to the first one.
for _, spec := range gen.Specs {
spec.(*ast.ImportSpec).Path.ValuePos = first.Pos()
first.Specs = append(first.Specs, spec)
}
f.Decls = append(f.Decls[:i], f.Decls[i+1:]...)
i--
}
}
// declImports reports whether gen contains an import of path.
// Taken from golang.org/x/tools/ast/astutil.
func declImports(gen *ast.GenDecl, path string) bool {
if gen.Tok != token.IMPORT {
return false
}
for _, spec := range gen.Specs {
impspec := spec.(*ast.ImportSpec)
if importPath(impspec) == path {
return true
}
}
return false
}
func importPath(s ast.Spec) string {
t, err := strconv.Unquote(s.(*ast.ImportSpec).Path.Value)
if err == nil {
return t
}
return ""
}
func importName(s ast.Spec) string {
n := s.(*ast.ImportSpec).Name
if n == nil {
return ""
}
return n.Name
}
func importComment(s ast.Spec) string {
c := s.(*ast.ImportSpec).Comment
if c == nil {
return ""
}
return c.Text()
}
// collapse indicates whether prev may be removed, leaving only next.
func collapse(prev, next ast.Spec) bool {
if importPath(next) != importPath(prev) || importName(next) != importName(prev) {
return false
}
return prev.(*ast.ImportSpec).Comment == nil
}
type posSpan struct {
Start token.Pos
End token.Pos
}
func sortSpecs(env *ProcessEnv, fset *token.FileSet, f *ast.File, specs []ast.Spec) []ast.Spec {
// Can't short-circuit here even if specs are already sorted,
// since they might yet need deduplication.
// A lone import, however, may be safely ignored.
if len(specs) <= 1 {
return specs
}
// Record positions for specs.
pos := make([]posSpan, len(specs))
for i, s := range specs {
pos[i] = posSpan{s.Pos(), s.End()}
}
// Identify comments in this range.
// Any comment from pos[0].Start to the final line counts.
lastLine := fset.Position(pos[len(pos)-1].End).Line
cstart := len(f.Comments)
cend := len(f.Comments)
for i, g := range f.Comments {
if g.Pos() < pos[0].Start {
continue
}
if i < cstart {
cstart = i
}
if fset.Position(g.End()).Line > lastLine {
cend = i
break
}
}
comments := f.Comments[cstart:cend]
// Assign each comment to the import spec preceding it.
importComment := map[*ast.ImportSpec][]*ast.CommentGroup{}
specIndex := 0
for _, g := range comments {
for specIndex+1 < len(specs) && pos[specIndex+1].Start <= g.Pos() {
specIndex++
}
s := specs[specIndex].(*ast.ImportSpec)
importComment[s] = append(importComment[s], g)
}
// Sort the import specs by import path.
// Remove duplicates, when possible without data loss.
// Reassign the import paths to have the same position sequence.
// Reassign each comment to abut the end of its spec.
// Sort the comments by new position.
sort.Sort(byImportSpec{env, specs})
// Dedup. Thanks to our sorting, we can just consider
// adjacent pairs of imports.
deduped := specs[:0]
for i, s := range specs {
if i == len(specs)-1 || !collapse(s, specs[i+1]) {
deduped = append(deduped, s)
} else {
p := s.Pos()
fset.File(p).MergeLine(fset.Position(p).Line)
}
}
specs = deduped
// Fix up comment positions
for i, s := range specs {
s := s.(*ast.ImportSpec)
if s.Name != nil {
s.Name.NamePos = pos[i].Start
}
s.Path.ValuePos = pos[i].Start
s.EndPos = pos[i].End
nextSpecPos := pos[i].End
for _, g := range importComment[s] {
for _, c := range g.List {
c.Slash = pos[i].End
nextSpecPos = c.End()
}
}
if i < len(specs)-1 {
pos[i+1].Start = nextSpecPos
pos[i+1].End = nextSpecPos
}
}
sort.Sort(byCommentPos(comments))
// Fixup comments can insert blank lines, because import specs are on different lines.
// We remove those blank lines here by merging import spec to the first import spec line.
firstSpecLine := fset.Position(specs[0].Pos()).Line
for _, s := range specs[1:] {
p := s.Pos()
line := fset.File(p).Line(p)
for previousLine := line - 1; previousLine >= firstSpecLine; {
fset.File(p).MergeLine(previousLine)
previousLine--
}
}
return specs
}
type byImportSpec struct {
env *ProcessEnv
specs []ast.Spec // slice of *ast.ImportSpec
}
func (x byImportSpec) Len() int { return len(x.specs) }
func (x byImportSpec) Swap(i, j int) { x.specs[i], x.specs[j] = x.specs[j], x.specs[i] }
func (x byImportSpec) Less(i, j int) bool {
ipath := importPath(x.specs[i])
jpath := importPath(x.specs[j])
igroup := importGroup(x.env, ipath)
jgroup := importGroup(x.env, jpath)
if igroup != jgroup {
return igroup < jgroup
}
if ipath != jpath {
return ipath < jpath
}
iname := importName(x.specs[i])
jname := importName(x.specs[j])
if iname != jname {
return iname < jname
}
return importComment(x.specs[i]) < importComment(x.specs[j])
}
type byCommentPos []*ast.CommentGroup
func (x byCommentPos) Len() int { return len(x) }
func (x byCommentPos) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
func (x byCommentPos) Less(i, j int) bool { return x[i].Pos() < x[j].Pos() }

10377
vendor/golang.org/x/tools/internal/imports/zstdlib.go сгенерированный поставляемый Normal file

Разница между файлами не показана из-за своего большого размера Загрузить разницу

540
vendor/golang.org/x/tools/internal/module/module.go сгенерированный поставляемый Normal file
Просмотреть файл

@ -0,0 +1,540 @@
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package module defines the module.Version type
// along with support code.
package module
// IMPORTANT NOTE
//
// This file essentially defines the set of valid import paths for the go command.
// There are many subtle considerations, including Unicode ambiguity,
// security, network, and file system representations.
//
// This file also defines the set of valid module path and version combinations,
// another topic with many subtle considerations.
//
// Changes to the semantics in this file require approval from rsc.
import (
"fmt"
"sort"
"strings"
"unicode"
"unicode/utf8"
"golang.org/x/tools/internal/semver"
)
// A Version is defined by a module path and version pair.
type Version struct {
Path string
// Version is usually a semantic version in canonical form.
// There are two exceptions to this general rule.
// First, the top-level target of a build has no specific version
// and uses Version = "".
// Second, during MVS calculations the version "none" is used
// to represent the decision to take no version of a given module.
Version string `json:",omitempty"`
}
// Check checks that a given module path, version pair is valid.
// In addition to the path being a valid module path
// and the version being a valid semantic version,
// the two must correspond.
// For example, the path "yaml/v2" only corresponds to
// semantic versions beginning with "v2.".
func Check(path, version string) error {
if err := CheckPath(path); err != nil {
return err
}
if !semver.IsValid(version) {
return fmt.Errorf("malformed semantic version %v", version)
}
_, pathMajor, _ := SplitPathVersion(path)
if !MatchPathMajor(version, pathMajor) {
if pathMajor == "" {
pathMajor = "v0 or v1"
}
if pathMajor[0] == '.' { // .v1
pathMajor = pathMajor[1:]
}
return fmt.Errorf("mismatched module path %v and version %v (want %v)", path, version, pathMajor)
}
return nil
}
// firstPathOK reports whether r can appear in the first element of a module path.
// The first element of the path must be an LDH domain name, at least for now.
// To avoid case ambiguity, the domain name must be entirely lower case.
func firstPathOK(r rune) bool {
return r == '-' || r == '.' ||
'0' <= r && r <= '9' ||
'a' <= r && r <= 'z'
}
// pathOK reports whether r can appear in an import path element.
// Paths can be ASCII letters, ASCII digits, and limited ASCII punctuation: + - . _ and ~.
// This matches what "go get" has historically recognized in import paths.
// TODO(rsc): We would like to allow Unicode letters, but that requires additional
// care in the safe encoding (see note below).
func pathOK(r rune) bool {
if r < utf8.RuneSelf {
return r == '+' || r == '-' || r == '.' || r == '_' || r == '~' ||
'0' <= r && r <= '9' ||
'A' <= r && r <= 'Z' ||
'a' <= r && r <= 'z'
}
return false
}
// fileNameOK reports whether r can appear in a file name.
// For now we allow all Unicode letters but otherwise limit to pathOK plus a few more punctuation characters.
// If we expand the set of allowed characters here, we have to
// work harder at detecting potential case-folding and normalization collisions.
// See note about "safe encoding" below.
func fileNameOK(r rune) bool {
if r < utf8.RuneSelf {
// Entire set of ASCII punctuation, from which we remove characters:
// ! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ \ ] ^ _ ` { | } ~
// We disallow some shell special characters: " ' * < > ? ` |
// (Note that some of those are disallowed by the Windows file system as well.)
// We also disallow path separators / : and \ (fileNameOK is only called on path element characters).
// We allow spaces (U+0020) in file names.
const allowed = "!#$%&()+,-.=@[]^_{}~ "
if '0' <= r && r <= '9' || 'A' <= r && r <= 'Z' || 'a' <= r && r <= 'z' {
return true
}
for i := 0; i < len(allowed); i++ {
if rune(allowed[i]) == r {
return true
}
}
return false
}
// It may be OK to add more ASCII punctuation here, but only carefully.
// For example Windows disallows < > \, and macOS disallows :, so we must not allow those.
return unicode.IsLetter(r)
}
// CheckPath checks that a module path is valid.
func CheckPath(path string) error {
if err := checkPath(path, false); err != nil {
return fmt.Errorf("malformed module path %q: %v", path, err)
}
i := strings.Index(path, "/")
if i < 0 {
i = len(path)
}
if i == 0 {
return fmt.Errorf("malformed module path %q: leading slash", path)
}
if !strings.Contains(path[:i], ".") {
return fmt.Errorf("malformed module path %q: missing dot in first path element", path)
}
if path[0] == '-' {
return fmt.Errorf("malformed module path %q: leading dash in first path element", path)
}
for _, r := range path[:i] {
if !firstPathOK(r) {
return fmt.Errorf("malformed module path %q: invalid char %q in first path element", path, r)
}
}
if _, _, ok := SplitPathVersion(path); !ok {
return fmt.Errorf("malformed module path %q: invalid version", path)
}
return nil
}
// CheckImportPath checks that an import path is valid.
func CheckImportPath(path string) error {
if err := checkPath(path, false); err != nil {
return fmt.Errorf("malformed import path %q: %v", path, err)
}
return nil
}
// checkPath checks that a general path is valid.
// It returns an error describing why but not mentioning path.
// Because these checks apply to both module paths and import paths,
// the caller is expected to add the "malformed ___ path %q: " prefix.
// fileName indicates whether the final element of the path is a file name
// (as opposed to a directory name).
func checkPath(path string, fileName bool) error {
if !utf8.ValidString(path) {
return fmt.Errorf("invalid UTF-8")
}
if path == "" {
return fmt.Errorf("empty string")
}
if strings.Contains(path, "..") {
return fmt.Errorf("double dot")
}
if strings.Contains(path, "//") {
return fmt.Errorf("double slash")
}
if path[len(path)-1] == '/' {
return fmt.Errorf("trailing slash")
}
elemStart := 0
for i, r := range path {
if r == '/' {
if err := checkElem(path[elemStart:i], fileName); err != nil {
return err
}
elemStart = i + 1
}
}
if err := checkElem(path[elemStart:], fileName); err != nil {
return err
}
return nil
}
// checkElem checks whether an individual path element is valid.
// fileName indicates whether the element is a file name (not a directory name).
func checkElem(elem string, fileName bool) error {
if elem == "" {
return fmt.Errorf("empty path element")
}
if strings.Count(elem, ".") == len(elem) {
return fmt.Errorf("invalid path element %q", elem)
}
if elem[0] == '.' && !fileName {
return fmt.Errorf("leading dot in path element")
}
if elem[len(elem)-1] == '.' {
return fmt.Errorf("trailing dot in path element")
}
charOK := pathOK
if fileName {
charOK = fileNameOK
}
for _, r := range elem {
if !charOK(r) {
return fmt.Errorf("invalid char %q", r)
}
}
// Windows disallows a bunch of path elements, sadly.
// See https://docs.microsoft.com/en-us/windows/desktop/fileio/naming-a-file
short := elem
if i := strings.Index(short, "."); i >= 0 {
short = short[:i]
}
for _, bad := range badWindowsNames {
if strings.EqualFold(bad, short) {
return fmt.Errorf("disallowed path element %q", elem)
}
}
return nil
}
// CheckFilePath checks whether a slash-separated file path is valid.
func CheckFilePath(path string) error {
if err := checkPath(path, true); err != nil {
return fmt.Errorf("malformed file path %q: %v", path, err)
}
return nil
}
// badWindowsNames are the reserved file path elements on Windows.
// See https://docs.microsoft.com/en-us/windows/desktop/fileio/naming-a-file
var badWindowsNames = []string{
"CON",
"PRN",
"AUX",
"NUL",
"COM1",
"COM2",
"COM3",
"COM4",
"COM5",
"COM6",
"COM7",
"COM8",
"COM9",
"LPT1",
"LPT2",
"LPT3",
"LPT4",
"LPT5",
"LPT6",
"LPT7",
"LPT8",
"LPT9",
}
// SplitPathVersion returns prefix and major version such that prefix+pathMajor == path
// and version is either empty or "/vN" for N >= 2.
// As a special case, gopkg.in paths are recognized directly;
// they require ".vN" instead of "/vN", and for all N, not just N >= 2.
func SplitPathVersion(path string) (prefix, pathMajor string, ok bool) {
if strings.HasPrefix(path, "gopkg.in/") {
return splitGopkgIn(path)
}
i := len(path)
dot := false
for i > 0 && ('0' <= path[i-1] && path[i-1] <= '9' || path[i-1] == '.') {
if path[i-1] == '.' {
dot = true
}
i--
}
if i <= 1 || i == len(path) || path[i-1] != 'v' || path[i-2] != '/' {
return path, "", true
}
prefix, pathMajor = path[:i-2], path[i-2:]
if dot || len(pathMajor) <= 2 || pathMajor[2] == '0' || pathMajor == "/v1" {
return path, "", false
}
return prefix, pathMajor, true
}
// splitGopkgIn is like SplitPathVersion but only for gopkg.in paths.
func splitGopkgIn(path string) (prefix, pathMajor string, ok bool) {
if !strings.HasPrefix(path, "gopkg.in/") {
return path, "", false
}
i := len(path)
if strings.HasSuffix(path, "-unstable") {
i -= len("-unstable")
}
for i > 0 && ('0' <= path[i-1] && path[i-1] <= '9') {
i--
}
if i <= 1 || path[i-1] != 'v' || path[i-2] != '.' {
// All gopkg.in paths must end in vN for some N.
return path, "", false
}
prefix, pathMajor = path[:i-2], path[i-2:]
if len(pathMajor) <= 2 || pathMajor[2] == '0' && pathMajor != ".v0" {
return path, "", false
}
return prefix, pathMajor, true
}
// MatchPathMajor reports whether the semantic version v
// matches the path major version pathMajor.
func MatchPathMajor(v, pathMajor string) bool {
if strings.HasPrefix(pathMajor, ".v") && strings.HasSuffix(pathMajor, "-unstable") {
pathMajor = strings.TrimSuffix(pathMajor, "-unstable")
}
if strings.HasPrefix(v, "v0.0.0-") && pathMajor == ".v1" {
// Allow old bug in pseudo-versions that generated v0.0.0- pseudoversion for gopkg .v1.
// For example, gopkg.in/yaml.v2@v2.2.1's go.mod requires gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405.
return true
}
m := semver.Major(v)
if pathMajor == "" {
return m == "v0" || m == "v1" || semver.Build(v) == "+incompatible"
}
return (pathMajor[0] == '/' || pathMajor[0] == '.') && m == pathMajor[1:]
}
// CanonicalVersion returns the canonical form of the version string v.
// It is the same as semver.Canonical(v) except that it preserves the special build suffix "+incompatible".
func CanonicalVersion(v string) string {
cv := semver.Canonical(v)
if semver.Build(v) == "+incompatible" {
cv += "+incompatible"
}
return cv
}
// Sort sorts the list by Path, breaking ties by comparing Versions.
func Sort(list []Version) {
sort.Slice(list, func(i, j int) bool {
mi := list[i]
mj := list[j]
if mi.Path != mj.Path {
return mi.Path < mj.Path
}
// To help go.sum formatting, allow version/file.
// Compare semver prefix by semver rules,
// file by string order.
vi := mi.Version
vj := mj.Version
var fi, fj string
if k := strings.Index(vi, "/"); k >= 0 {
vi, fi = vi[:k], vi[k:]
}
if k := strings.Index(vj, "/"); k >= 0 {
vj, fj = vj[:k], vj[k:]
}
if vi != vj {
return semver.Compare(vi, vj) < 0
}
return fi < fj
})
}
// Safe encodings
//
// Module paths appear as substrings of file system paths
// (in the download cache) and of web server URLs in the proxy protocol.
// In general we cannot rely on file systems to be case-sensitive,
// nor can we rely on web servers, since they read from file systems.
// That is, we cannot rely on the file system to keep rsc.io/QUOTE
// and rsc.io/quote separate. Windows and macOS don't.
// Instead, we must never require two different casings of a file path.
// Because we want the download cache to match the proxy protocol,
// and because we want the proxy protocol to be possible to serve
// from a tree of static files (which might be stored on a case-insensitive
// file system), the proxy protocol must never require two different casings
// of a URL path either.
//
// One possibility would be to make the safe encoding be the lowercase
// hexadecimal encoding of the actual path bytes. This would avoid ever
// needing different casings of a file path, but it would be fairly illegible
// to most programmers when those paths appeared in the file system
// (including in file paths in compiler errors and stack traces)
// in web server logs, and so on. Instead, we want a safe encoding that
// leaves most paths unaltered.
//
// The safe encoding is this:
// replace every uppercase letter with an exclamation mark
// followed by the letter's lowercase equivalent.
//
// For example,
// github.com/Azure/azure-sdk-for-go -> github.com/!azure/azure-sdk-for-go.
// github.com/GoogleCloudPlatform/cloudsql-proxy -> github.com/!google!cloud!platform/cloudsql-proxy
// github.com/Sirupsen/logrus -> github.com/!sirupsen/logrus.
//
// Import paths that avoid upper-case letters are left unchanged.
// Note that because import paths are ASCII-only and avoid various
// problematic punctuation (like : < and >), the safe encoding is also ASCII-only
// and avoids the same problematic punctuation.
//
// Import paths have never allowed exclamation marks, so there is no
// need to define how to encode a literal !.
//
// Although paths are disallowed from using Unicode (see pathOK above),
// the eventual plan is to allow Unicode letters as well, to assume that
// file systems and URLs are Unicode-safe (storing UTF-8), and apply
// the !-for-uppercase convention. Note however that not all runes that
// are different but case-fold equivalent are an upper/lower pair.
// For example, U+004B ('K'), U+006B ('k'), and U+212A ('' for Kelvin)
// are considered to case-fold to each other. When we do add Unicode
// letters, we must not assume that upper/lower are the only case-equivalent pairs.
// Perhaps the Kelvin symbol would be disallowed entirely, for example.
// Or perhaps it would encode as "!!k", or perhaps as "(212A)".
//
// Also, it would be nice to allow Unicode marks as well as letters,
// but marks include combining marks, and then we must deal not
// only with case folding but also normalization: both U+00E9 ('é')
// and U+0065 U+0301 ('e' followed by combining acute accent)
// look the same on the page and are treated by some file systems
// as the same path. If we do allow Unicode marks in paths, there
// must be some kind of normalization to allow only one canonical
// encoding of any character used in an import path.
// EncodePath returns the safe encoding of the given module path.
// It fails if the module path is invalid.
func EncodePath(path string) (encoding string, err error) {
if err := CheckPath(path); err != nil {
return "", err
}
return encodeString(path)
}
// EncodeVersion returns the safe encoding of the given module version.
// Versions are allowed to be in non-semver form but must be valid file names
// and not contain exclamation marks.
func EncodeVersion(v string) (encoding string, err error) {
if err := checkElem(v, true); err != nil || strings.Contains(v, "!") {
return "", fmt.Errorf("disallowed version string %q", v)
}
return encodeString(v)
}
func encodeString(s string) (encoding string, err error) {
haveUpper := false
for _, r := range s {
if r == '!' || r >= utf8.RuneSelf {
// This should be disallowed by CheckPath, but diagnose anyway.
// The correctness of the encoding loop below depends on it.
return "", fmt.Errorf("internal error: inconsistency in EncodePath")
}
if 'A' <= r && r <= 'Z' {
haveUpper = true
}
}
if !haveUpper {
return s, nil
}
var buf []byte
for _, r := range s {
if 'A' <= r && r <= 'Z' {
buf = append(buf, '!', byte(r+'a'-'A'))
} else {
buf = append(buf, byte(r))
}
}
return string(buf), nil
}
// DecodePath returns the module path of the given safe encoding.
// It fails if the encoding is invalid or encodes an invalid path.
func DecodePath(encoding string) (path string, err error) {
path, ok := decodeString(encoding)
if !ok {
return "", fmt.Errorf("invalid module path encoding %q", encoding)
}
if err := CheckPath(path); err != nil {
return "", fmt.Errorf("invalid module path encoding %q: %v", encoding, err)
}
return path, nil
}
// DecodeVersion returns the version string for the given safe encoding.
// It fails if the encoding is invalid or encodes an invalid version.
// Versions are allowed to be in non-semver form but must be valid file names
// and not contain exclamation marks.
func DecodeVersion(encoding string) (v string, err error) {
v, ok := decodeString(encoding)
if !ok {
return "", fmt.Errorf("invalid version encoding %q", encoding)
}
if err := checkElem(v, true); err != nil {
return "", fmt.Errorf("disallowed version string %q", v)
}
return v, nil
}
func decodeString(encoding string) (string, bool) {
var buf []byte
bang := false
for _, r := range encoding {
if r >= utf8.RuneSelf {
return "", false
}
if bang {
bang = false
if r < 'a' || 'z' < r {
return "", false
}
buf = append(buf, byte(r+'A'-'a'))
continue
}
if r == '!' {
bang = true
continue
}
if 'A' <= r && r <= 'Z' {
return "", false
}
buf = append(buf, byte(r))
}
if bang {
return "", false
}
return string(buf), true
}

2
vendor/sigs.k8s.io/cluster-api-provider-aws/pkg/apis/awsproviderconfig/v1beta1/register.go сгенерированный поставляемый
Просмотреть файл

@ -28,7 +28,7 @@ import (
"bytes"
"fmt"
machinev1 "github.com/openshift/cluster-api/pkg/apis/machine/v1beta1"
machinev1 "github.com/openshift/machine-api-operator/pkg/apis/machine/v1beta1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/runtime/serializer"