diff --git a/.github/workflows/trivy.yaml b/.github/workflows/trivy.yaml index 5f37a43c7..8c69889fa 100644 --- a/.github/workflows/trivy.yaml +++ b/.github/workflows/trivy.yaml @@ -23,7 +23,6 @@ jobs: make docker build -t test/csi-snapshotter:latest -f ./cmd/csi-snapshotter/Dockerfile --output=type=docker --label revision=latest . docker build -t test/snapshot-controller:latest -f ./cmd/snapshot-controller/Dockerfile --output=type=docker --label revision=latest . - docker build -t test/snapshot-validation-webhook:latest -f ./cmd/snapshot-validation-webhook/Dockerfile --output=type=docker --label revision=latest . - name: Run Trivy vulnerability scanner on csi-snapshotter image uses: aquasecurity/trivy-action@master @@ -48,15 +47,3 @@ jobs: ignore-unfixed: true vuln-type: 'os,library' severity: 'CRITICAL,HIGH,MEDIUM,LOW,UNKNOWN' - - - name: Run Trivy vulnerability scanner on snapshot-validation-webhook image - uses: aquasecurity/trivy-action@master - env: - TRIVY_DB_REPOSITORY: "public.ecr.aws/aquasecurity/trivy-db:2" - with: - image-ref: 'test/snapshot-validation-webhook:latest' - format: 'table' - exit-code: '1' - ignore-unfixed: true - vuln-type: 'os,library' - severity: 'CRITICAL,HIGH,MEDIUM,LOW,UNKNOWN' diff --git a/Makefile b/Makefile index ab0a3ae77..ec3520a51 100644 --- a/Makefile +++ b/Makefile @@ -12,9 +12,9 @@ # See the License for the specific language governing permissions and # limitations under the License. -.PHONY: all snapshot-controller csi-snapshotter snapshot-validation-webhook clean test +.PHONY: all snapshot-controller csi-snapshotter clean test -CMDS=snapshot-controller csi-snapshotter snapshot-validation-webhook +CMDS=snapshot-controller csi-snapshotter all: build include release-tools/build.make diff --git a/README.md b/README.md index f79903734..7305872b5 100644 --- a/README.md +++ b/README.md @@ -6,9 +6,6 @@ The volume snapshot feature supports CSI v1.0 and higher. It was introduced as a The volume group snapshot feature supports CSI v1.10.0 and higher, and have been introduced in [Kubernetes 1.27 as an alpha feature](https://kubernetes.io/blog/2023/05/08/kubernetes-1-27-volume-group-snapshot-alpha/). -> :warning: **WARNING**: There is a new validating webhook server which provides tightened validation on snapshot objects. This SHOULD be installed by all users of this feature. More details [below](#validating-webhook). - - ## Overview With the promotion of Volume Snapshot to GA, the feature is enabled by default on standard Kubernetes deployments and cannot be turned off. @@ -29,9 +26,9 @@ This information reflects the head of this branch. | [CSI Spec v1.0.0](https://github.com/container-storage-interface/spec/releases/tag/v1.0.0) | [CSI Spec v1.5.0](https://github.com/container-storage-interface/spec/releases/tag/v1.5.0) | k8s.gcr.io/sig-storage/snapshot-controller | 1.20 | 1.20 | | [CSI Spec v1.0.0](https://github.com/container-storage-interface/spec/releases/tag/v1.0.0) | [CSI Spec v1.5.0](https://github.com/container-storage-interface/spec/releases/tag/v1.5.0) | k8s.gcr.io/sig-storage/snapshot-validation-webhook | 1.20 | 1.20 | -Note: snapshot-controller, snapshot-validation-webhook, csi-snapshotter v4.1 requires v1 snapshot CRDs to be installed, but it serves both v1 and v1beta1 snapshot objects. Storage version is changed from v1beta1 to v1 in 4.1.0 so v1beta1 is deprecated and will be removed in a future release. +Note: snapshot-controller, csi-snapshotter v4.1 requires v1 snapshot CRDs to be installed, but it serves both v1 and v1beta1 snapshot objects. Storage version is changed from v1beta1 to v1 in 4.1.0 so v1beta1 is deprecated and will be removed in a future release. -Note: when the volume group snapshot feature is enabled, snapshot-controller, snapshot-validation-webhook, csi-snapshotter require the v1alpha1 volumegroupsnapshot CRDs to be installed. +Note: when the volume group snapshot feature is enabled, snapshot-controller, csi-snapshotter require the v1alpha1 volumegroupsnapshot CRDs to be installed. ## Feature Status @@ -59,7 +56,6 @@ Volume Snapshot feature contains the following components: * [Kubernetes Volume Snapshot and Volume Group Snapshot CRDs](https://github.com/kubernetes-csi/external-snapshotter/tree/master/client/config/crd) * [Volume snapshot and volume group snapshot controller](https://github.com/kubernetes-csi/external-snapshotter/tree/master/pkg/common-controller) -* [Snapshot and volume group snapshot validation webhook](https://github.com/kubernetes-csi/external-snapshotter/tree/master/pkg/validation-webhook) * CSI Driver along with [CSI Snapshotter sidecar](https://github.com/kubernetes-csi/external-snapshotter/tree/master/pkg/sidecar-controller) The Volume Snapshot feature depends on a volume snapshot controller and the volume snapshot CRDs. Both the controller and the CRDs are independent of any CSI driver. The CSI Snapshotter sidecar must run once per CSI driver. The single snapshot controller deployment works for all CSI drivers in a cluster. With leader election configured, the CSI sidecars and snapshot controller elect one leader per deployment. If deployed with two or more pods and leader election is enabled, the non-leader containers will attempt to get the lease. If the leader container dies, a non-leader will take over. @@ -68,8 +64,6 @@ Therefore, it is strongly recommended that Kubernetes distributors bundle and de If your Kubernetes distribution does not bundle the snapshot controller, you may manually install these components by executing the following steps. Note that the snapshot controller YAML files in the git repository deploy into the default namespace for system testing purposes. For general use, update the snapshot controller YAMLs with an appropriate namespace prior to installing. For example, on a Vanilla Kubernetes cluster update the namespace from 'default' to 'kube-system' prior to issuing the kubectl create command. -There is a new validating webhook server which provides tightened validation on snapshot objects. The cluster admin or Kubernetes distribution admin should install the webhook alongside the snapshot controllers and CRDs. More details [below](#validating-webhook). - Install Snapshot and Volume Group Snapshot CRDs: * kubectl kustomize client/config/crd | kubectl create -f - * https://github.com/kubernetes-csi/external-snapshotter/tree/master/client/config/crd @@ -86,44 +80,6 @@ Install CSI Driver: * kubectl kustomize deploy/kubernetes/csi-snapshotter | kubectl create -f - * https://github.com/kubernetes-csi/external-snapshotter/tree/master/deploy/kubernetes/csi-snapshotter -### Validating Webhook - -The snapshot validating webhook is an HTTP callback which responds to [admission requests](https://kubernetes.io/docs/reference/access-authn-authz/extensible-admission-controllers/). It is part of a larger [plan](https://github.com/kubernetes/enhancements/tree/master/keps/sig-storage/1900-volume-snapshot-validation-webhook) to tighten validation for volume snapshot objects. This webhook introduces the [ratcheting validation](https://github.com/kubernetes/enhancements/tree/master/keps/sig-storage/1900-volume-snapshot-validation-webhook#backwards-compatibility) mechanism targeting the tighter validation. The cluster admin or Kubernetes distribution admin should install the webhook alongside the snapshot controllers and CRDs. - -Along with the validation webhook, the volume snapshot controller will start [labeling](https://github.com/kubernetes/enhancements/tree/master/keps/sig-storage/1900-volume-snapshot-validation-webhook#automatic-labelling-of-invalid-objects) invalid snapshot objects which already existed. This is to enable quick identification of invalid snapshot objects in the system by running: -``` -kubectl get volumesnapshots --selector=snapshot.storage.kubernetes.io/invalid-snapshot-resource: "" -kubectl get volumesnapshotcontents --selector=snapshot.storage.kubernetes.io/invalid-snapshot-content-resource: "" -``` - -Users should run this to identify, remove any invalid objects, and correct their workflows before upgrading to v1. Once the API has been switched to the v1 type, those invalid objects will not be deletable from the system. - -If there are no existing invalid v1beta1 objects, after upgrading to v1, the webhook and schema validation will prevent the user from creating new invalid v1 and v1beta1 objects. - -If there are existing invalid v1beta1 objects, the user should make sure that the snapshot controller is upgraded to v3.0.0 or higher (v3.0.3 is the latest recommended v3.0.x release) and install the corresponding validation webhook before upgrading to v1 so that those invalid objects will be labeled and can be identified easily and removed before upgrading to v1. - -If there are existing invalid v1beta1 objects, and the user didn't upgrade to the snapshot controller 3.0.0 or higher and install the corresponding validation webhook before upgrading to v1, those existing invalid v1beta1 objects will not be labeled by the snapshot controller. - -So the recommendation is that before upgrading to v1 CRDs and upgrading snapshot controller and validation webhook to v4.0, the user should upgrade to the snapshot controller 3.0.0 and higher (v3.0.3 is the latest recommended version for 3.0.x) and install the corresponding validation webhook so that all existing invalid objects will be labeled and can be easily identified and deleted. - -> :warning: **WARNING**: Cluster admins choosing not to install the webhook server and participate in the phased release process can cause future problems when upgrading from `v1beta1` to `v1` volumesnapshot API, if there are currently persisted objects which fail the new stricter validation. Potential impacts include being unable to delete invalid snapshot objects. - -Read more about how to install the example webhook [here](deploy/kubernetes/webhook-example/README.md). - -#### Validating Webhook Command Line Options - -* `--tls-cert-file`: File containing the x509 Certificate for HTTPS. (CA cert, if any, concatenated after server cert). Required. - -* `--tls-private-key-file`: File containing the x509 private key matching --tls-cert-file. Required. - -* `--port`: Secure port that the webhook listens on (default 443) - -* `--kubeconfig `: Path to Kubernetes client configuration that the webhook uses to connect to Kubernetes API server. When omitted, default token provided by Kubernetes will be used. This option is useful only when the snapshot controller does not run as a Kubernetes pod, e.g. for debugging. - -* `--prevent-volume-mode-conversion`: Boolean that prevents an unauthorised user from modifying the volume mode when creating a PVC from an existing VolumeSnapshot. Was present as an alpha feature in `v6.0.0`; Having graduated to beta, defaults to true. - -#### Validating Webhook Validations - ##### Volume Snapshot * Spec.VolumeSnapshotClassName must not be an empty string or nil on creation @@ -280,8 +236,6 @@ If you have already deployed v1alpha1 snapshot APIs and external-snapshotter sid ### Upgrade from v1beta1 to v1 -Validation webhook should be installed before upgrading to v1. Potential impacts of not installing the validation webhook before upgrading to v1 include being unable to delete invalid snapshot objects. See the section on Validation Webhook for details. - * When upgrading to 4.0, change from v1beta1 to v1 is backward compatible because both v1 and v1beta1 are served while the stored API version is still v1beta1. Future releases will switch the stored version to v1 and gradually remove v1beta1 support. * When upgrading from 3.x to 4.1, change from v1beta1 to v1 is no longer backward compatible because stored API version is changed to v1 although both v1 and v1beta1 are still served. v1beta1 is deprecated in 4.1. * v1beta1 support will be removed in a future release. It is recommended for users to switch to v1 as soon as possible. Any previously created invalid v1beta1 objects have to be deleted before upgrading to version 4.1. diff --git a/cmd/snapshot-validation-webhook/Dockerfile b/cmd/snapshot-validation-webhook/Dockerfile deleted file mode 100644 index 68cf7548f..000000000 --- a/cmd/snapshot-validation-webhook/Dockerfile +++ /dev/null @@ -1,7 +0,0 @@ -FROM gcr.io/distroless/static:latest -LABEL maintainers="Kubernetes Authors" -LABEL description="Snapshot Validation Webhook" -ARG binary=./bin/snapshot-validation-webhook - -COPY ${binary} snapshot-validation-webhook -ENTRYPOINT ["/snapshot-validation-webhook"] diff --git a/cmd/snapshot-validation-webhook/main.go b/cmd/snapshot-validation-webhook/main.go deleted file mode 100644 index 9d7a9c148..000000000 --- a/cmd/snapshot-validation-webhook/main.go +++ /dev/null @@ -1,33 +0,0 @@ -/* -Copyright 2020 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package main - -import ( - "flag" - - webhook "github.com/kubernetes-csi/external-snapshotter/v8/pkg/validation-webhook" - "k8s.io/klog/v2" -) - -func main() { - rootCmd := webhook.CmdWebhook - - loggingFlags := &flag.FlagSet{} - klog.InitFlags(loggingFlags) - rootCmd.PersistentFlags().AddGoFlagSet(loggingFlags) - rootCmd.Execute() -} diff --git a/deploy/kubernetes/webhook-example/README.md b/deploy/kubernetes/webhook-example/README.md deleted file mode 100644 index 4c0a66f69..000000000 --- a/deploy/kubernetes/webhook-example/README.md +++ /dev/null @@ -1,71 +0,0 @@ -# Validating Webhook - -The snapshot validating webhook is an HTTP callback which responds to [admission requests](https://kubernetes.io/docs/reference/access-authn-authz/extensible-admission-controllers/). It is part of a larger [plan](https://github.com/kubernetes/enhancements/tree/master/keps/sig-storage/1900-volume-snapshot-validation-webhook#proposal) to tighten validation for volume snapshot objects. This webhook introduces the [ratcheting validation](https://github.com/kubernetes/enhancements/tree/master/keps/sig-storage/1900-volume-snapshot-validation-webhook#backwards-compatibility) mechanism targeting the tighter validation. The cluster admin or Kubernetes distribution admin should install the webhook alongside the snapshot controllers and CRDs. - -## How to build the webhook - -Build the binary - -```bash -make -``` - -Build the docker image - -```bash -docker build -t snapshot-validation-webhook:latest -f ./cmd/snapshot-validation-webhook/Dockerfile . -``` - -## How to deploy the webhook - -The webhook server is provided as an image which can be built from this repository. It can be deployed anywhere, as long as the api server is able to reach it over HTTPS. It is recommended to deploy the webhook server in the cluster as snapshotting is latency sensitive. A `ValidatingWebhookConfiguration` object is needed to configure the api server to contact the webhook server. Please see the [documentation](https://kubernetes.io/docs/reference/access-authn-authz/extensible-admission-controllers/) for more details. The webhook server code is adapted from the [webhook server](https://github.com/kubernetes/kubernetes/tree/v1.18.6/test/images/agnhost/webhook) used in the kubernetes/kubernetes end to end testing code. - -### Example in-cluster deployment using Kubernetes Secrets - -Please note this is not considered to be a production ready method to deploy the certificates and is only provided for demo purposes. This is only one of many ways to deploy the certificates, it is your responsibility to ensure the security of your cluster. TLS certificates and private keys should be handled with care and you may not want to keep them in plain Kubernetes secrets. - -This method was heavily adapted from [banzai cloud](https://banzaicloud.com/blog/k8s-admission-webhooks/). - -#### Method - -These commands should be run from the top level directory. - -1. Run the `create-cert.sh` script. Note using the default namespace will allow anyone with access to that namespace to read your secret. It is recommended to change the namespace in all the files and the commands given below. - - - ```bash - # This script will create a TLS certificate signed by the [cluster](https://kubernetes.io/docs/tasks/tls/managing-tls-in-a-cluster/). It will place the public and private key into a secret on the cluster. - ./deploy/kubernetes/webhook-example/create-cert.sh --service snapshot-validation-service --secret snapshot-validation-secret --namespace default # Make sure to use a different namespace - ``` - -2. Patch the `ValidatingWebhookConfiguration` file from the template, filling in the CA bundle field. - - ```bash - cat ./deploy/kubernetes/webhook-example/admission-configuration-template | ./deploy/kubernetes/webhook-example/patch-ca-bundle.sh > ./deploy/kubernetes/webhook-example/admission-configuration.yaml - ``` - -3. Change the namespace in the generated `admission-configuration.yaml` file. Change the namespace in the service and deployment in the `webhook.yaml` file. - -4. Create the deployment, service, RBAC, and admission configuration objects on the cluster. - - ```bash - kubectl apply -f ./deploy/kubernetes/webhook-example - ``` - -Once all the pods from the deployment are up and running, you should be ready to go. - -#### Verify the webhook works - -Try to create an invalid snapshot object, the snapshot creation should fail. - -```bash -kubectl create -f ./examples/kubernetes/invalid-snapshot-v1.yaml -``` - -### Other methods to deploy the webhook server - -Look into [cert-manager](https://cert-manager.io/) to handle the certificates, and this kube-builder [tutorial](https://book.kubebuilder.io/cronjob-tutorial/cert-manager.html) on how to deploy a webhook. - -#### Important - -Please see the deployment [yaml](./webhook.yaml) for the arguments expected by the webhook server. The snapshot validation webhook is served at the path `/volumesnapshot`. diff --git a/deploy/kubernetes/webhook-example/admission-configuration-template b/deploy/kubernetes/webhook-example/admission-configuration-template deleted file mode 100644 index 3d8ccc63c..000000000 --- a/deploy/kubernetes/webhook-example/admission-configuration-template +++ /dev/null @@ -1,45 +0,0 @@ -apiVersion: admissionregistration.k8s.io/v1 -kind: ValidatingWebhookConfiguration -metadata: - name: "validation-webhook.snapshot.storage.k8s.io" -webhooks: -- name: "validation-webhook.snapshot.storage.k8s.io" - rules: - - apiGroups: ["snapshot.storage.k8s.io"] - apiVersions: ["v1"] - operations: ["CREATE", "UPDATE"] - resources: ["volumesnapshotclasses"] - scope: "*" - clientConfig: - service: - namespace: "default" - name: "snapshot-validation-service" - path: "/volumesnapshot" - caBundle: ${CA_BUNDLE} - admissionReviewVersions: ["v1"] - sideEffects: None - failurePolicy: Ignore # We recommend switching to Fail only after successful installation of the webhook server and webhook. - timeoutSeconds: 2 # This will affect the latency and performance. Finetune this value based on your application's tolerance. ---- -apiVersion: admissionregistration.k8s.io/v1 -kind: ValidatingWebhookConfiguration -metadata: - name: "validation-webhook.groupsnapshot.storage.k8s.io" -webhooks: -- name: "validation-webhook.groupsnapshot.storage.k8s.io" - rules: - - apiGroups: ["groupsnapshot.storage.k8s.io"] - apiVersions: ["v1alpha1"] - operations: ["CREATE", "UPDATE"] - resources: ["volumegroupsnapshotclasses"] - scope: "*" - clientConfig: - service: - namespace: "default" - name: "snapshot-validation-service" - path: "/volumegroupsnapshot" - caBundle: ${CA_BUNDLE} - admissionReviewVersions: ["v1"] - sideEffects: None - failurePolicy: Ignore # We recommend switching to Fail only after successful installation of the webhook server and webhook. - timeoutSeconds: 2 # This will affect the latency and performance. Finetune this value based on your application's tolerance. diff --git a/deploy/kubernetes/webhook-example/create-cert.sh b/deploy/kubernetes/webhook-example/create-cert.sh deleted file mode 100755 index 4cafaf1f4..000000000 --- a/deploy/kubernetes/webhook-example/create-cert.sh +++ /dev/null @@ -1,127 +0,0 @@ -#!/bin/bash -# File originally from https://github.com/banzaicloud/admission-webhook-example/blob/blog/deployment/webhook-create-signed-cert.sh - -set -e - -usage() { - cat <> ${tmpdir}/csr.conf -[req] -req_extensions = v3_req -distinguished_name = req_distinguished_name -[req_distinguished_name] -[ v3_req ] -basicConstraints = CA:FALSE -keyUsage = nonRepudiation, digitalSignature, keyEncipherment -extendedKeyUsage = serverAuth -subjectAltName = @alt_names -[alt_names] -DNS.1 = ${service} -DNS.2 = ${service}.${namespace} -DNS.3 = ${service}.${namespace}.svc -EOF - -openssl genrsa -out ${tmpdir}/server-key.pem 2048 -openssl req -new -key ${tmpdir}/server-key.pem -subj "/CN=system:node:${service}.${namespace}.svc;/O=system:nodes" -out ${tmpdir}/server.csr -config ${tmpdir}/csr.conf - -# clean-up any previously created CSR for our service. Ignore errors if not present. -kubectl delete csr ${csrName} 2>/dev/null || true - -# create server cert/key CSR and send to k8s API -cat <&2 - exit 1 -fi -echo ${serverCert} | openssl base64 -d -A -out ${tmpdir}/server-cert.pem - - -# create the secret with CA cert and server cert/key -kubectl create secret tls ${secret} \ - --key=${tmpdir}/server-key.pem \ - --cert=${tmpdir}/server-cert.pem \ - --dry-run=client -o yaml | - kubectl -n ${namespace} apply -f - diff --git a/deploy/kubernetes/webhook-example/patch-ca-bundle.sh b/deploy/kubernetes/webhook-example/patch-ca-bundle.sh deleted file mode 100755 index 723af5cec..000000000 --- a/deploy/kubernetes/webhook-example/patch-ca-bundle.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/bash -# File originally from https://github.com/banzaicloud/admission-webhook-example/blob/blog/deployment/webhook-patch-ca-bundle.sh - -ROOT=$(cd $(dirname $0)/../../; pwd) - -set -o errexit -set -o nounset -set -o pipefail - -export CA_BUNDLE=$(kubectl config view --raw -o json | jq -r '.clusters[0].cluster."certificate-authority-data"' | tr -d '"') - -if command -v envsubst >/dev/null 2>&1; then - envsubst -else - sed -e "s|\${CA_BUNDLE}|${CA_BUNDLE}|g" -fi diff --git a/deploy/kubernetes/webhook-example/rbac-snapshot-webhook.yaml b/deploy/kubernetes/webhook-example/rbac-snapshot-webhook.yaml deleted file mode 100644 index a26369f23..000000000 --- a/deploy/kubernetes/webhook-example/rbac-snapshot-webhook.yaml +++ /dev/null @@ -1,38 +0,0 @@ -# RBAC file for the snapshot webhook. -# -# The snapshot webhook implements the validation and admission for CSI snapshot functionality. -# It should be installed as part of the base Kubernetes distribution in an appropriate -# namespace for components implementing base system functionality. For installing with -# Vanilla Kubernetes, kube-system makes sense for the namespace. - ---- -apiVersion: v1 -kind: ServiceAccount -metadata: - name: snapshot-webhook - namespace: default # NOTE: change the namespace ---- -kind: ClusterRole -apiVersion: rbac.authorization.k8s.io/v1 -metadata: - name: snapshot-webhook-runner -rules: - - apiGroups: ["snapshot.storage.k8s.io"] - resources: ["volumesnapshotclasses"] - verbs: ["get", "list", "watch"] - - apiGroups: ["groupsnapshot.storage.k8s.io"] - resources: ["volumegroupsnapshotclasses"] - verbs: ["get", "list", "watch"] ---- -kind: ClusterRoleBinding -apiVersion: rbac.authorization.k8s.io/v1 -metadata: - name: snapshot-webhook-role -subjects: - - kind: ServiceAccount - name: snapshot-webhook - namespace: default # NOTE: change the namespace -roleRef: - kind: ClusterRole - name: snapshot-webhook-runner - apiGroup: rbac.authorization.k8s.io diff --git a/deploy/kubernetes/webhook-example/webhook.yaml b/deploy/kubernetes/webhook-example/webhook.yaml deleted file mode 100644 index 2550efb76..000000000 --- a/deploy/kubernetes/webhook-example/webhook.yaml +++ /dev/null @@ -1,51 +0,0 @@ ---- -apiVersion: apps/v1 -kind: Deployment -metadata: - name: snapshot-validation-deployment - namespace: default # NOTE: change the namespace - labels: - app.kubernetes.io/name: snapshot-validation -spec: - replicas: 3 - selector: - matchLabels: - app.kubernetes.io/name: snapshot-validation - template: - metadata: - labels: - app.kubernetes.io/name: snapshot-validation - spec: - serviceAccountName: snapshot-webhook - containers: - - name: snapshot-validation - image: registry.k8s.io/sig-storage/snapshot-validation-webhook:v8.0.1 # change the image if you wish to use your own custom validation server image - imagePullPolicy: IfNotPresent - args: - - '--tls-cert-file=/etc/snapshot-validation-webhook/certs/tls.crt' - - '--tls-private-key-file=/etc/snapshot-validation-webhook/certs/tls.key' - # uncomment the following line to enable webhook for VolumeGroupSnapshot, VolumeGroupSnapshotContent and VolumeGroupSnapshotClass. - # - '--enable-volume-group-snapshot-webhook' - ports: - - containerPort: 443 # change the port as needed - volumeMounts: - - name: snapshot-validation-webhook-certs - mountPath: /etc/snapshot-validation-webhook/certs - readOnly: true - volumes: - - name: snapshot-validation-webhook-certs - secret: - secretName: snapshot-validation-secret ---- -apiVersion: v1 -kind: Service -metadata: - name: snapshot-validation-service - namespace: default # NOTE: change the namespace -spec: - selector: - app.kubernetes.io/name: snapshot-validation - ports: - - protocol: TCP - port: 443 # Change if needed - targetPort: 443 # Change if the webserver image expects a different port diff --git a/go.mod b/go.mod index a4880cf13..7dd05e1d9 100644 --- a/go.mod +++ b/go.mod @@ -6,16 +6,14 @@ require ( // TODO: update version once it is officially released github.com/container-storage-interface/spec v1.10.1-0.20241022120259-f6b6d53db606 github.com/evanphx/json-patch v5.9.0+incompatible - github.com/fsnotify/fsnotify v1.8.0 github.com/golang/mock v1.6.0 - github.com/google/gofuzz v1.2.0 + github.com/google/gofuzz v1.2.0 // indirect github.com/kubernetes-csi/csi-lib-utils v0.19.0 github.com/kubernetes-csi/csi-test/v5 v5.3.1 github.com/kubernetes-csi/external-snapshotter/client/v8 v8.0.0 github.com/prometheus/client_golang v1.20.5 github.com/prometheus/client_model v0.6.1 github.com/prometheus/common v0.60.1 - github.com/spf13/cobra v1.8.1 google.golang.org/grpc v1.67.1 google.golang.org/protobuf v1.35.1 k8s.io/api v0.31.0 @@ -45,7 +43,6 @@ require ( github.com/google/go-cmp v0.6.0 // indirect github.com/google/uuid v1.6.0 // indirect github.com/imdario/mergo v0.3.13 // indirect - github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/josharian/intern v1.0.0 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/compress v1.17.11 // indirect diff --git a/go.sum b/go.sum index 41cd2f3fe..38aee3c8d 100644 --- a/go.sum +++ b/go.sum @@ -6,7 +6,6 @@ github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UF github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/container-storage-interface/spec v1.10.1-0.20241022120259-f6b6d53db606 h1:PtXpku0GhORJLv9g2RRenXXdmJB+dklYJXSeJePxPmo= github.com/container-storage-interface/spec v1.10.1-0.20241022120259-f6b6d53db606/go.mod h1:DtUvaQszPml1YJfIK7c00mlv6/g4wNMLanLgiUbKFRI= -github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= @@ -15,8 +14,6 @@ github.com/emicklei/go-restful/v3 v3.12.1 h1:PJMDIM/ak7btuL8Ex0iYET9hxM3CI2sjZtz github.com/emicklei/go-restful/v3 v3.12.1/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= github.com/evanphx/json-patch v5.9.0+incompatible h1:fBXyNpNMuTTDdquAq/uisOr2lShz4oaXpDTX2bLe7ls= github.com/evanphx/json-patch v5.9.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= -github.com/fsnotify/fsnotify v1.8.0 h1:dAwr6QBTBZIkG8roQaJjGof0pp0EeF+tNV7YBP3F/8M= -github.com/fsnotify/fsnotify v1.8.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= github.com/fxamacker/cbor/v2 v2.7.0 h1:iM5WgngdRBanHcxugY4JySA0nk1wZorNOpTgCMedv5E= github.com/fxamacker/cbor/v2 v2.7.0/go.mod h1:pxXPTn3joSm21Gbwsv0w9OSA2y1HFR9qXEeXQVeNoDQ= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= @@ -55,8 +52,6 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/imdario/mergo v0.3.13 h1:lFzP57bqS/wsqKssCGmtLAb8A0wKjLGrve2q3PPVcBk= github.com/imdario/mergo v0.3.13/go.mod h1:4lJ1jqUDcsbIECGy0RUJAXNIhg+6ocWgb1ALK2O4oXg= -github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= -github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= @@ -103,9 +98,6 @@ github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0leargg github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk= github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= -github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM= -github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= diff --git a/pkg/validation-webhook/certwatcher.go b/pkg/validation-webhook/certwatcher.go deleted file mode 100644 index 6ea928317..000000000 --- a/pkg/validation-webhook/certwatcher.go +++ /dev/null @@ -1,164 +0,0 @@ -/* -Copyright 2020 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 webhook - -import ( - "context" - "crypto/tls" - "sync" - - "github.com/fsnotify/fsnotify" - "k8s.io/klog/v2" -) - -// This file originated from github.com/kubernetes-sigs/controller-runtime/pkg/webhook/internal/certwatcher. -// We cannot import this package as it's an internal one. In addition, we cannot yet easily integrate -// with controller-runtime/pkg/webhook directly, as it would require extensive rework: -// https://github.com/kubernetes-csi/external-snapshotter/issues/422 - -// CertWatcher watches certificate and key files for changes. When either file -// changes, it reads and parses both and calls an optional callback with the new -// certificate. -type CertWatcher struct { - sync.Mutex - - currentCert *tls.Certificate - watcher *fsnotify.Watcher - - certPath string - keyPath string -} - -// NewCertWatcher returns a new CertWatcher watching the given certificate and key. -func NewCertWatcher(certPath, keyPath string) (*CertWatcher, error) { - var err error - - cw := &CertWatcher{ - certPath: certPath, - keyPath: keyPath, - } - - // Initial read of certificate and key. - if err := cw.ReadCertificate(); err != nil { - return nil, err - } - - cw.watcher, err = fsnotify.NewWatcher() - if err != nil { - return nil, err - } - - return cw, nil -} - -// GetCertificate fetches the currently loaded certificate, which may be nil. -func (cw *CertWatcher) GetCertificate(_ *tls.ClientHelloInfo) (*tls.Certificate, error) { - cw.Lock() - defer cw.Unlock() - return cw.currentCert, nil -} - -// Start starts the watch on the certificate and key files. -func (cw *CertWatcher) Start(ctx context.Context) error { - files := []string{cw.certPath, cw.keyPath} - - for _, f := range files { - if err := cw.watcher.Add(f); err != nil { - return err - } - } - - go cw.Watch() - - // Block until the context is done. - <-ctx.Done() - - return cw.watcher.Close() -} - -// Watch reads events from the watcher's channel and reacts to changes. -func (cw *CertWatcher) Watch() { - for { - select { - case event, ok := <-cw.watcher.Events: - // Channel is closed. - if !ok { - return - } - - cw.handleEvent(event) - - case err, ok := <-cw.watcher.Errors: - // Channel is closed. - if !ok { - return - } - - klog.Error(err, "certificate watch error") - } - } -} - -// ReadCertificate reads the certificate and key files from disk, parses them, -// and updates the current certificate on the watcher. If a callback is set, it -// is invoked with the new certificate. -func (cw *CertWatcher) ReadCertificate() error { - cert, err := tls.LoadX509KeyPair(cw.certPath, cw.keyPath) - if err != nil { - return err - } - - cw.Lock() - cw.currentCert = &cert - cw.Unlock() - - klog.Info("Updated current TLS certificate") - - return nil -} - -func (cw *CertWatcher) handleEvent(event fsnotify.Event) { - // Only care about events which may modify the contents of the file. - if !(isWrite(event) || isRemove(event) || isCreate(event)) { - return - } - - klog.V(1).Info("certificate event", "event", event) - - // If the file was removed, re-add the watch. - if isRemove(event) { - if err := cw.watcher.Add(event.Name); err != nil { - klog.Error(err, "error re-watching file") - } - } - - if err := cw.ReadCertificate(); err != nil { - klog.Error(err, "error re-reading certificate") - } -} - -func isWrite(event fsnotify.Event) bool { - return event.Op&fsnotify.Write == fsnotify.Write -} - -func isCreate(event fsnotify.Event) bool { - return event.Op&fsnotify.Create == fsnotify.Create -} - -func isRemove(event fsnotify.Event) bool { - return event.Op&fsnotify.Remove == fsnotify.Remove -} diff --git a/pkg/validation-webhook/config.go b/pkg/validation-webhook/config.go deleted file mode 100644 index 59add5b2b..000000000 --- a/pkg/validation-webhook/config.go +++ /dev/null @@ -1,41 +0,0 @@ -/* -Copyright 2020 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 webhook - -import ( - "crypto/tls" - - "k8s.io/klog/v2" -) - -// Config contains the server (the webhook) cert and key. -type Config struct { - CertFile string - KeyFile string -} - -func configTLS(config Config) *tls.Config { - sCert, err := tls.LoadX509KeyPair(config.CertFile, config.KeyFile) - if err != nil { - klog.Fatal(err) - } - return &tls.Config{ - Certificates: []tls.Certificate{sCert}, - // TODO: uses mutual tls after we agree on what cert the apiserver should use. - // ClientAuth: tls.RequireAndVerifyClientCert, - } -} diff --git a/pkg/validation-webhook/convert.go b/pkg/validation-webhook/convert.go deleted file mode 100644 index cca0b8024..000000000 --- a/pkg/validation-webhook/convert.go +++ /dev/null @@ -1,105 +0,0 @@ -/* -Copyright 2020 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 webhook - -import ( - v1 "k8s.io/api/admission/v1" - "k8s.io/api/admission/v1beta1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -func convertAdmissionRequestToV1(r *v1beta1.AdmissionRequest) *v1.AdmissionRequest { - return &v1.AdmissionRequest{ - Kind: r.Kind, - Namespace: r.Namespace, - Name: r.Name, - Object: r.Object, - Resource: r.Resource, - Operation: v1.Operation(r.Operation), - UID: r.UID, - DryRun: r.DryRun, - OldObject: r.OldObject, - Options: r.Options, - RequestKind: r.RequestKind, - RequestResource: r.RequestResource, - RequestSubResource: r.RequestSubResource, - SubResource: r.SubResource, - UserInfo: r.UserInfo, - } -} - -func convertAdmissionRequestToV1beta1(r *v1.AdmissionRequest) *v1beta1.AdmissionRequest { - return &v1beta1.AdmissionRequest{ - Kind: r.Kind, - Namespace: r.Namespace, - Name: r.Name, - Object: r.Object, - Resource: r.Resource, - Operation: v1beta1.Operation(r.Operation), - UID: r.UID, - DryRun: r.DryRun, - OldObject: r.OldObject, - Options: r.Options, - RequestKind: r.RequestKind, - RequestResource: r.RequestResource, - RequestSubResource: r.RequestSubResource, - SubResource: r.SubResource, - UserInfo: r.UserInfo, - } -} - -func convertAdmissionResponseToV1(r *v1beta1.AdmissionResponse) *v1.AdmissionResponse { - var pt *v1.PatchType - if r.PatchType != nil { - t := v1.PatchType(*r.PatchType) - pt = &t - } - return &v1.AdmissionResponse{ - UID: r.UID, - Allowed: r.Allowed, - AuditAnnotations: r.AuditAnnotations, - Patch: r.Patch, - PatchType: pt, - Result: r.Result, - Warnings: r.Warnings, - } -} - -func convertAdmissionResponseToV1beta1(r *v1.AdmissionResponse) *v1beta1.AdmissionResponse { - var pt *v1beta1.PatchType - if r.PatchType != nil { - t := v1beta1.PatchType(*r.PatchType) - pt = &t - } - return &v1beta1.AdmissionResponse{ - UID: r.UID, - Allowed: r.Allowed, - AuditAnnotations: r.AuditAnnotations, - Patch: r.Patch, - PatchType: pt, - Result: r.Result, - Warnings: r.Warnings, - } -} - -func toV1AdmissionResponse(err error) *v1.AdmissionResponse { - return &v1.AdmissionResponse{ - Result: &metav1.Status{ - Message: err.Error(), - }, - } -} diff --git a/pkg/validation-webhook/convert_test.go b/pkg/validation-webhook/convert_test.go deleted file mode 100644 index f411cbf83..000000000 --- a/pkg/validation-webhook/convert_test.go +++ /dev/null @@ -1,63 +0,0 @@ -/* -Copyright 2020 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 webhook - -import ( - "fmt" - "math/rand" - "reflect" - "testing" - - fuzz "github.com/google/gofuzz" - - v1 "k8s.io/api/admission/v1" - "k8s.io/api/admission/v1beta1" - "k8s.io/apimachinery/pkg/api/apitesting/fuzzer" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/serializer" - "k8s.io/apimachinery/pkg/util/diff" -) - -func TestConvertAdmissionRequestToV1(t *testing.T) { - f := fuzzer.FuzzerFor(AdmissionfuzzerFuncs, rand.NewSource(rand.Int63()), serializer.NewCodecFactory(runtime.NewScheme())) - for i := 0; i < 100; i++ { - t.Run(fmt.Sprintf("Run %d/100", i), func(t *testing.T) { - orig := &v1beta1.AdmissionRequest{} - f.Fuzz(orig) - converted := convertAdmissionRequestToV1(orig) - rt := convertAdmissionRequestToV1beta1(converted) - if !reflect.DeepEqual(orig, rt) { - t.Errorf("expected all request fields to be in converted object but found unaccounted for differences, diff:\n%s", diff.ObjectReflectDiff(orig, converted)) - } - }) - } -} - -func TestConvertAdmissionResponseToV1beta1(t *testing.T) { - f := fuzz.New() - for i := 0; i < 100; i++ { - t.Run(fmt.Sprintf("Run %d/100", i), func(t *testing.T) { - orig := &v1.AdmissionResponse{} - f.Fuzz(orig) - converted := convertAdmissionResponseToV1beta1(orig) - rt := convertAdmissionResponseToV1(converted) - if !reflect.DeepEqual(orig, rt) { - t.Errorf("expected all fields to be in converted object but found unaccounted for differences, diff:\n%s", diff.ObjectReflectDiff(orig, converted)) - } - }) - } -} diff --git a/pkg/validation-webhook/fuzzer.go b/pkg/validation-webhook/fuzzer.go deleted file mode 100644 index 7e5222cf4..000000000 --- a/pkg/validation-webhook/fuzzer.go +++ /dev/null @@ -1,43 +0,0 @@ -/* -Copyright 2017 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// NOTE: This file is copied from -// https://github.com/kubernetes/kubernetes/blob/v1.29.0-alpha.0/pkg/apis/admission/fuzzer/fuzzer.go -// so that external-snapshotter no longer needs to depend on k8s.io/kubernetes - -package webhook - -import ( - fuzz "github.com/google/gofuzz" - - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime" - runtimeserializer "k8s.io/apimachinery/pkg/runtime/serializer" -) - -// Funcs returns the fuzzer functions for the admission api group. -var AdmissionfuzzerFuncs = func(codecs runtimeserializer.CodecFactory) []interface{} { - return []interface{}{ - func(s *runtime.RawExtension, c fuzz.Continue) { - u := &unstructured.Unstructured{Object: map[string]interface{}{ - "apiVersion": "unknown.group/unknown", - "kind": "Something", - "somekey": "somevalue", - }} - s.Object = u - }, - } -} diff --git a/pkg/validation-webhook/groupsnapshot.go b/pkg/validation-webhook/groupsnapshot.go deleted file mode 100644 index 844164e4d..000000000 --- a/pkg/validation-webhook/groupsnapshot.go +++ /dev/null @@ -1,124 +0,0 @@ -/* -Copyright 2023 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 webhook - -import ( - "fmt" - - volumegroupsnapshotv1alpha1 "github.com/kubernetes-csi/external-snapshotter/client/v8/apis/volumegroupsnapshot/v1alpha1" - groupsnapshotlisters "github.com/kubernetes-csi/external-snapshotter/client/v8/listers/volumegroupsnapshot/v1alpha1" - "github.com/kubernetes-csi/external-snapshotter/v8/pkg/utils" - v1 "k8s.io/api/admission/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/klog/v2" -) - -var ( - // GroupSnapshotClassV1Apha1GVR is GroupVersionResource for v1alpha1 VolumeGroupSnapshotClasses - GroupSnapshotClassV1Apha1GVR = metav1.GroupVersionResource{Group: volumegroupsnapshotv1alpha1.GroupName, Version: "v1alpha1", Resource: "volumegroupsnapshotclasses"} -) - -type GroupSnapshotAdmitter interface { - Admit(v1.AdmissionReview) *v1.AdmissionResponse -} - -type groupSnapshotAdmitter struct { - lister groupsnapshotlisters.VolumeGroupSnapshotClassLister -} - -func NewGroupSnapshotAdmitter(lister groupsnapshotlisters.VolumeGroupSnapshotClassLister) GroupSnapshotAdmitter { - return &groupSnapshotAdmitter{ - lister: lister, - } -} - -// Add a label {"added-label": "yes"} to the object -func (a groupSnapshotAdmitter) Admit(ar v1.AdmissionReview) *v1.AdmissionResponse { - klog.V(2).Info("admitting volumegroupsnapshotclasses") - - reviewResponse := &v1.AdmissionResponse{ - Allowed: true, - Result: &metav1.Status{}, - } - - // Admit requests other than Update and Create - if !(ar.Request.Operation == v1.Update || ar.Request.Operation == v1.Create) { - return reviewResponse - } - - raw := ar.Request.Object.Raw - oldRaw := ar.Request.OldObject.Raw - - deserializer := codecs.UniversalDeserializer() - switch ar.Request.Resource { - case GroupSnapshotClassV1Apha1GVR: - groupSnapClass := &volumegroupsnapshotv1alpha1.VolumeGroupSnapshotClass{} - if _, _, err := deserializer.Decode(raw, nil, groupSnapClass); err != nil { - klog.Error(err) - return toV1AdmissionResponse(err) - } - oldGroupSnapClass := &volumegroupsnapshotv1alpha1.VolumeGroupSnapshotClass{} - if _, _, err := deserializer.Decode(oldRaw, nil, oldGroupSnapClass); err != nil { - klog.Error(err) - return toV1AdmissionResponse(err) - } - return decideGroupSnapshotClassV1Alpha1(groupSnapClass, oldGroupSnapClass, a.lister) - default: - err := fmt.Errorf("expect resource to be %s, but found %v", - GroupSnapshotClassV1Apha1GVR, ar.Request.Resource) - klog.Error(err) - return toV1AdmissionResponse(err) - } -} - -func decideGroupSnapshotClassV1Alpha1(groupSnapClass, oldGroupSnapClass *volumegroupsnapshotv1alpha1.VolumeGroupSnapshotClass, lister groupsnapshotlisters.VolumeGroupSnapshotClassLister) *v1.AdmissionResponse { - reviewResponse := &v1.AdmissionResponse{ - Allowed: true, - Result: &metav1.Status{}, - } - - // Only Validate when a new group snapshot class is being set as a default. - if groupSnapClass.Annotations[utils.IsDefaultGroupSnapshotClassAnnotation] != "true" { - return reviewResponse - } - - // If the old group snapshot class has this, then we can assume that it was validated if driver is the same. - if oldGroupSnapClass.Annotations[utils.IsDefaultGroupSnapshotClassAnnotation] == "true" && oldGroupSnapClass.Driver == groupSnapClass.Driver { - return reviewResponse - } - - ret, err := lister.List(labels.Everything()) - if err != nil { - reviewResponse.Allowed = false - reviewResponse.Result.Message = err.Error() - return reviewResponse - } - - for _, groupSnapshotClass := range ret { - if groupSnapshotClass.Annotations[utils.IsDefaultGroupSnapshotClassAnnotation] != "true" { - continue - } - if groupSnapshotClass.Driver == groupSnapClass.Driver { - reviewResponse.Allowed = false - reviewResponse.Result.Message = fmt.Sprintf("default group snapshot class: %v already exists for driver: %v", groupSnapshotClass.Name, groupSnapClass.Driver) - return reviewResponse - } - } - - return reviewResponse -} diff --git a/pkg/validation-webhook/groupsnapshot_test.go b/pkg/validation-webhook/groupsnapshot_test.go deleted file mode 100644 index 17fda56ba..000000000 --- a/pkg/validation-webhook/groupsnapshot_test.go +++ /dev/null @@ -1,315 +0,0 @@ -/* -Copyright 2023 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 webhook - -import ( - "encoding/json" - "testing" - - volumegroupsnapshotv1alpha1 "github.com/kubernetes-csi/external-snapshotter/client/v8/apis/volumegroupsnapshot/v1alpha1" - groupsnapshotlisters "github.com/kubernetes-csi/external-snapshotter/client/v8/listers/volumegroupsnapshot/v1alpha1" - "github.com/kubernetes-csi/external-snapshotter/v8/pkg/utils" - v1 "k8s.io/api/admission/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/apimachinery/pkg/runtime" -) - -type fakeGroupSnapshotLister struct { - values []*volumegroupsnapshotv1alpha1.VolumeGroupSnapshotClass -} - -func (f *fakeGroupSnapshotLister) List(selector labels.Selector) (ret []*volumegroupsnapshotv1alpha1.VolumeGroupSnapshotClass, err error) { - return f.values, nil -} - -func (f *fakeGroupSnapshotLister) Get(name string) (*volumegroupsnapshotv1alpha1.VolumeGroupSnapshotClass, error) { - for _, v := range f.values { - if v.Name == name { - return v, nil - } - } - return nil, nil -} - -func TestAdmitVolumeGroupSnapshotClassV1Alpha1(t *testing.T) { - testCases := []struct { - name string - groupSnapClass *volumegroupsnapshotv1alpha1.VolumeGroupSnapshotClass - oldGroupSnapClass *volumegroupsnapshotv1alpha1.VolumeGroupSnapshotClass - shouldAdmit bool - msg string - operation v1.Operation - lister groupsnapshotlisters.VolumeGroupSnapshotClassLister - }{ - { - name: "new default for group snapshot class with no existing group snapshot classes", - groupSnapClass: &volumegroupsnapshotv1alpha1.VolumeGroupSnapshotClass{ - TypeMeta: metav1.TypeMeta{}, - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{ - utils.IsDefaultGroupSnapshotClassAnnotation: "true", - }, - }, - Driver: "test.csi.io", - }, - oldGroupSnapClass: nil, - shouldAdmit: true, - msg: "", - operation: v1.Create, - lister: &fakeGroupSnapshotLister{values: []*volumegroupsnapshotv1alpha1.VolumeGroupSnapshotClass{}}, - }, - { - name: "new default for group snapshot class for with existing default group snapshot class with different drivers", - groupSnapClass: &volumegroupsnapshotv1alpha1.VolumeGroupSnapshotClass{ - TypeMeta: metav1.TypeMeta{}, - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{ - utils.IsDefaultGroupSnapshotClassAnnotation: "true", - }, - }, - Driver: "test.csi.io", - }, - oldGroupSnapClass: &volumegroupsnapshotv1alpha1.VolumeGroupSnapshotClass{}, - shouldAdmit: true, - msg: "", - operation: v1.Create, - lister: &fakeGroupSnapshotLister{values: []*volumegroupsnapshotv1alpha1.VolumeGroupSnapshotClass{ - { - TypeMeta: metav1.TypeMeta{}, - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{ - utils.IsDefaultGroupSnapshotClassAnnotation: "true", - }, - }, - Driver: "existing.test.csi.io", - }, - }}, - }, - { - name: "new default for group snapshot class with existing default group snapshot class same driver", - groupSnapClass: &volumegroupsnapshotv1alpha1.VolumeGroupSnapshotClass{ - TypeMeta: metav1.TypeMeta{}, - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{ - utils.IsDefaultGroupSnapshotClassAnnotation: "true", - }, - }, - Driver: "test.csi.io", - }, - oldGroupSnapClass: &volumegroupsnapshotv1alpha1.VolumeGroupSnapshotClass{}, - shouldAdmit: false, - msg: "default group snapshot class: driver-a already exists for driver: test.csi.io", - operation: v1.Create, - lister: &fakeGroupSnapshotLister{values: []*volumegroupsnapshotv1alpha1.VolumeGroupSnapshotClass{ - { - TypeMeta: metav1.TypeMeta{}, - ObjectMeta: metav1.ObjectMeta{ - Name: "driver-a", - Annotations: map[string]string{ - utils.IsDefaultGroupSnapshotClassAnnotation: "true", - }, - }, - Driver: "test.csi.io", - }, - }}, - }, - { - name: "default for group snapshot class with existing default group snapshot class same driver update", - groupSnapClass: &volumegroupsnapshotv1alpha1.VolumeGroupSnapshotClass{ - TypeMeta: metav1.TypeMeta{}, - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{ - utils.IsDefaultGroupSnapshotClassAnnotation: "true", - }, - }, - Driver: "test.csi.io", - }, - oldGroupSnapClass: &volumegroupsnapshotv1alpha1.VolumeGroupSnapshotClass{ - TypeMeta: metav1.TypeMeta{}, - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{ - utils.IsDefaultGroupSnapshotClassAnnotation: "true", - }, - }, - Driver: "test.csi.io", - }, - shouldAdmit: true, - msg: "", - operation: v1.Update, - lister: &fakeGroupSnapshotLister{values: []*volumegroupsnapshotv1alpha1.VolumeGroupSnapshotClass{ - { - TypeMeta: metav1.TypeMeta{}, - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{ - utils.IsDefaultGroupSnapshotClassAnnotation: "true", - }, - }, - Driver: "test.csi.io", - }, - }}, - }, - { - name: "new group snapshot for group snapshot class with existing default group snapshot class same driver", - groupSnapClass: &volumegroupsnapshotv1alpha1.VolumeGroupSnapshotClass{ - TypeMeta: metav1.TypeMeta{}, - ObjectMeta: metav1.ObjectMeta{}, - Driver: "test.csi.io", - }, - oldGroupSnapClass: &volumegroupsnapshotv1alpha1.VolumeGroupSnapshotClass{}, - shouldAdmit: true, - msg: "", - operation: v1.Create, - lister: &fakeGroupSnapshotLister{values: []*volumegroupsnapshotv1alpha1.VolumeGroupSnapshotClass{ - { - TypeMeta: metav1.TypeMeta{}, - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{ - utils.IsDefaultGroupSnapshotClassAnnotation: "true", - }, - }, - Driver: "test.csi.io", - }, - }}, - }, - { - name: "new group snapshot for group snapshot class with existing group snapshot default classes", - groupSnapClass: &volumegroupsnapshotv1alpha1.VolumeGroupSnapshotClass{ - TypeMeta: metav1.TypeMeta{}, - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{ - utils.IsDefaultGroupSnapshotClassAnnotation: "true", - }, - }, - Driver: "test.csi.io", - }, - oldGroupSnapClass: &volumegroupsnapshotv1alpha1.VolumeGroupSnapshotClass{}, - shouldAdmit: false, - msg: "default group snapshot class: driver-is-default already exists for driver: test.csi.io", - operation: v1.Create, - lister: &fakeGroupSnapshotLister{[]*volumegroupsnapshotv1alpha1.VolumeGroupSnapshotClass{ - { - TypeMeta: metav1.TypeMeta{}, - ObjectMeta: metav1.ObjectMeta{ - Name: "driver-is-default", - Annotations: map[string]string{ - utils.IsDefaultGroupSnapshotClassAnnotation: "true", - }, - }, - Driver: "test.csi.io", - }, - { - TypeMeta: metav1.TypeMeta{}, - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{ - utils.IsDefaultGroupSnapshotClassAnnotation: "true", - }, - }, - Driver: "test.csi.io", - }, - }}, - }, - { - name: "update group snapshot class to new driver with existing default group snapshot classes", - groupSnapClass: &volumegroupsnapshotv1alpha1.VolumeGroupSnapshotClass{ - TypeMeta: metav1.TypeMeta{}, - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{ - utils.IsDefaultGroupSnapshotClassAnnotation: "true", - }, - }, - Driver: "driver.test.csi.io", - }, - oldGroupSnapClass: &volumegroupsnapshotv1alpha1.VolumeGroupSnapshotClass{ - TypeMeta: metav1.TypeMeta{}, - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{ - utils.IsDefaultGroupSnapshotClassAnnotation: "true", - }, - }, - Driver: "test.csi.io", - }, - shouldAdmit: false, - msg: "default group snapshot class: driver-test-default already exists for driver: driver.test.csi.io", - operation: v1.Update, - lister: &fakeGroupSnapshotLister{values: []*volumegroupsnapshotv1alpha1.VolumeGroupSnapshotClass{ - { - TypeMeta: metav1.TypeMeta{}, - ObjectMeta: metav1.ObjectMeta{ - Name: "driver-is-default", - Annotations: map[string]string{ - utils.IsDefaultGroupSnapshotClassAnnotation: "true", - }, - }, - Driver: "test.csi.io", - }, - { - TypeMeta: metav1.TypeMeta{}, - ObjectMeta: metav1.ObjectMeta{ - Name: "driver-test-default", - Annotations: map[string]string{ - utils.IsDefaultGroupSnapshotClassAnnotation: "true", - }, - }, - Driver: "driver.test.csi.io", - }, - }}, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - groupSnapContent := tc.groupSnapClass - raw, err := json.Marshal(groupSnapContent) - if err != nil { - t.Fatal(err) - } - oldGroupSnapClass := tc.oldGroupSnapClass - oldRaw, err := json.Marshal(oldGroupSnapClass) - if err != nil { - t.Fatal(err) - } - review := v1.AdmissionReview{ - Request: &v1.AdmissionRequest{ - Object: runtime.RawExtension{ - Raw: raw, - }, - OldObject: runtime.RawExtension{ - Raw: oldRaw, - }, - Resource: GroupSnapshotClassV1Apha1GVR, - Operation: tc.operation, - }, - } - sa := NewGroupSnapshotAdmitter(tc.lister) - response := sa.Admit(review) - - shouldAdmit := response.Allowed - msg := response.Result.Message - - expectedResponse := tc.shouldAdmit - expectedMsg := tc.msg - - if shouldAdmit != expectedResponse { - t.Errorf("expected \"%v\" to equal \"%v\"", shouldAdmit, expectedResponse) - } - if msg != expectedMsg { - t.Errorf("expected \"%v\" to equal \"%v\"", msg, expectedMsg) - } - }) - } -} diff --git a/pkg/validation-webhook/scheme.go b/pkg/validation-webhook/scheme.go deleted file mode 100644 index abff42d03..000000000 --- a/pkg/validation-webhook/scheme.go +++ /dev/null @@ -1,47 +0,0 @@ -/* -Copyright 2020 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 webhook - -import ( - snapshot "github.com/kubernetes-csi/external-snapshotter/client/v8/clientset/versioned/scheme" - admissionv1 "k8s.io/api/admission/v1" - admissionv1beta1 "k8s.io/api/admission/v1beta1" - admissionregistrationv1 "k8s.io/api/admissionregistration/v1" - admissionregistrationv1beta1 "k8s.io/api/admissionregistration/v1beta1" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/serializer" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" -) - -var ( - scheme = runtime.NewScheme() - codecs = serializer.NewCodecFactory(scheme) -) - -func init() { - addToScheme(scheme) -} - -func addToScheme(scheme *runtime.Scheme) { - utilruntime.Must(corev1.AddToScheme(scheme)) - utilruntime.Must(admissionv1beta1.AddToScheme(scheme)) - utilruntime.Must(admissionregistrationv1beta1.AddToScheme(scheme)) - utilruntime.Must(admissionv1.AddToScheme(scheme)) - utilruntime.Must(admissionregistrationv1.AddToScheme(scheme)) - utilruntime.Must(snapshot.AddToScheme(scheme)) -} diff --git a/pkg/validation-webhook/snapshot.go b/pkg/validation-webhook/snapshot.go deleted file mode 100644 index 0a432bc9a..000000000 --- a/pkg/validation-webhook/snapshot.go +++ /dev/null @@ -1,131 +0,0 @@ -/* -Copyright 2020 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 webhook - -import ( - "fmt" - - volumesnapshotv1 "github.com/kubernetes-csi/external-snapshotter/client/v8/apis/volumesnapshot/v1" - storagelisters "github.com/kubernetes-csi/external-snapshotter/client/v8/listers/volumesnapshot/v1" - "github.com/kubernetes-csi/external-snapshotter/v8/pkg/utils" - v1 "k8s.io/api/admission/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/klog/v2" -) - -var ( - // SnapshotContentV1GVR is GroupVersionResource for v1 VolumeSnapshotContents - SnapshotClassV1GVR = metav1.GroupVersionResource{Group: volumesnapshotv1.GroupName, Version: "v1", Resource: "volumesnapshotclasses"} -) - -type SnapshotAdmitter interface { - Admit(v1.AdmissionReview) *v1.AdmissionResponse -} - -type admitter struct { - lister storagelisters.VolumeSnapshotClassLister -} - -func NewSnapshotAdmitter(lister storagelisters.VolumeSnapshotClassLister) SnapshotAdmitter { - return &admitter{ - lister: lister, - } -} - -// Add a label {"added-label": "yes"} to the object -func (a admitter) Admit(ar v1.AdmissionReview) *v1.AdmissionResponse { - klog.V(2).Info("admitting volumesnapshotclasses") - - reviewResponse := &v1.AdmissionResponse{ - Allowed: true, - Result: &metav1.Status{}, - } - - // Admit requests other than Update and Create - if !(ar.Request.Operation == v1.Update || ar.Request.Operation == v1.Create) { - return reviewResponse - } - - raw := ar.Request.Object.Raw - oldRaw := ar.Request.OldObject.Raw - - deserializer := codecs.UniversalDeserializer() - switch ar.Request.Resource { - case SnapshotClassV1GVR: - snapClass := &volumesnapshotv1.VolumeSnapshotClass{} - if _, _, err := deserializer.Decode(raw, nil, snapClass); err != nil { - klog.Error(err) - return toV1AdmissionResponse(err) - } - oldSnapClass := &volumesnapshotv1.VolumeSnapshotClass{} - if _, _, err := deserializer.Decode(oldRaw, nil, oldSnapClass); err != nil { - klog.Error(err) - return toV1AdmissionResponse(err) - } - return decideSnapshotClassV1(snapClass, oldSnapClass, a.lister) - default: - err := fmt.Errorf("expect resource to be %s, but found %v", - SnapshotClassV1GVR, ar.Request.Resource) - klog.Error(err) - return toV1AdmissionResponse(err) - } -} - -func decideSnapshotClassV1(snapClass, oldSnapClass *volumesnapshotv1.VolumeSnapshotClass, lister storagelisters.VolumeSnapshotClassLister) *v1.AdmissionResponse { - reviewResponse := &v1.AdmissionResponse{ - Allowed: true, - Result: &metav1.Status{}, - } - - // Only Validate when a new snapClass is being set as a default. - if snapClass.Annotations[utils.IsDefaultSnapshotClassAnnotation] != "true" { - return reviewResponse - } - - // If Old snapshot class has this, then we can assume that it was validated if driver is the same. - if oldSnapClass.Annotations[utils.IsDefaultSnapshotClassAnnotation] == "true" && oldSnapClass.Driver == snapClass.Driver { - return reviewResponse - } - - ret, err := lister.List(labels.Everything()) - if err != nil { - reviewResponse.Allowed = false - reviewResponse.Result.Message = err.Error() - return reviewResponse - } - - for _, snapshotClass := range ret { - if snapshotClass.Annotations[utils.IsDefaultSnapshotClassAnnotation] != "true" { - continue - } - if snapshotClass.Driver == snapClass.Driver { - reviewResponse.Allowed = false - reviewResponse.Result.Message = fmt.Sprintf("default snapshot class: %v already exists for driver: %v", snapshotClass.Name, snapClass.Driver) - return reviewResponse - } - } - - return reviewResponse -} - -func strPtrDereference(s *string) string { - if s == nil { - return "" - } - return *s -} diff --git a/pkg/validation-webhook/snapshot_test.go b/pkg/validation-webhook/snapshot_test.go deleted file mode 100644 index 39e7f23d8..000000000 --- a/pkg/validation-webhook/snapshot_test.go +++ /dev/null @@ -1,315 +0,0 @@ -/* -Copyright 2020 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 webhook - -import ( - "encoding/json" - "testing" - - volumesnapshotv1 "github.com/kubernetes-csi/external-snapshotter/client/v8/apis/volumesnapshot/v1" - storagelisters "github.com/kubernetes-csi/external-snapshotter/client/v8/listers/volumesnapshot/v1" - "github.com/kubernetes-csi/external-snapshotter/v8/pkg/utils" - v1 "k8s.io/api/admission/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/apimachinery/pkg/runtime" -) - -type fakeSnapshotLister struct { - values []*volumesnapshotv1.VolumeSnapshotClass -} - -func (f *fakeSnapshotLister) List(selector labels.Selector) (ret []*volumesnapshotv1.VolumeSnapshotClass, err error) { - return f.values, nil -} - -func (f *fakeSnapshotLister) Get(name string) (*volumesnapshotv1.VolumeSnapshotClass, error) { - for _, v := range f.values { - if v.Name == name { - return v, nil - } - } - return nil, nil -} - -func TestAdmitVolumeSnapshotClassV1(t *testing.T) { - testCases := []struct { - name string - volumeSnapshotClass *volumesnapshotv1.VolumeSnapshotClass - oldVolumeSnapshotClass *volumesnapshotv1.VolumeSnapshotClass - shouldAdmit bool - msg string - operation v1.Operation - lister storagelisters.VolumeSnapshotClassLister - }{ - { - name: "new default for class with no existing classes", - volumeSnapshotClass: &volumesnapshotv1.VolumeSnapshotClass{ - TypeMeta: metav1.TypeMeta{}, - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{ - utils.IsDefaultSnapshotClassAnnotation: "true", - }, - }, - Driver: "test.csi.io", - }, - oldVolumeSnapshotClass: &volumesnapshotv1.VolumeSnapshotClass{}, - shouldAdmit: true, - msg: "", - operation: v1.Create, - lister: &fakeSnapshotLister{values: []*volumesnapshotv1.VolumeSnapshotClass{}}, - }, - { - name: "new default for class for with existing default class different drivers", - volumeSnapshotClass: &volumesnapshotv1.VolumeSnapshotClass{ - TypeMeta: metav1.TypeMeta{}, - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{ - utils.IsDefaultSnapshotClassAnnotation: "true", - }, - }, - Driver: "test.csi.io", - }, - oldVolumeSnapshotClass: &volumesnapshotv1.VolumeSnapshotClass{}, - shouldAdmit: true, - msg: "", - operation: v1.Create, - lister: &fakeSnapshotLister{values: []*volumesnapshotv1.VolumeSnapshotClass{ - { - TypeMeta: metav1.TypeMeta{}, - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{ - utils.IsDefaultSnapshotClassAnnotation: "true", - }, - }, - Driver: "existing.test.csi.io", - }, - }}, - }, - { - name: "new default for class with existing default class same driver", - volumeSnapshotClass: &volumesnapshotv1.VolumeSnapshotClass{ - TypeMeta: metav1.TypeMeta{}, - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{ - utils.IsDefaultSnapshotClassAnnotation: "true", - }, - }, - Driver: "test.csi.io", - }, - oldVolumeSnapshotClass: &volumesnapshotv1.VolumeSnapshotClass{}, - shouldAdmit: false, - msg: "default snapshot class: driver-a already exists for driver: test.csi.io", - operation: v1.Create, - lister: &fakeSnapshotLister{values: []*volumesnapshotv1.VolumeSnapshotClass{ - { - TypeMeta: metav1.TypeMeta{}, - ObjectMeta: metav1.ObjectMeta{ - Name: "driver-a", - Annotations: map[string]string{ - utils.IsDefaultSnapshotClassAnnotation: "true", - }, - }, - Driver: "test.csi.io", - }, - }}, - }, - { - name: "default for class with existing default class same driver update", - volumeSnapshotClass: &volumesnapshotv1.VolumeSnapshotClass{ - TypeMeta: metav1.TypeMeta{}, - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{ - utils.IsDefaultSnapshotClassAnnotation: "true", - }, - }, - Driver: "test.csi.io", - }, - oldVolumeSnapshotClass: &volumesnapshotv1.VolumeSnapshotClass{ - TypeMeta: metav1.TypeMeta{}, - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{ - utils.IsDefaultSnapshotClassAnnotation: "true", - }, - }, - Driver: "test.csi.io", - }, - shouldAdmit: true, - msg: "", - operation: v1.Update, - lister: &fakeSnapshotLister{values: []*volumesnapshotv1.VolumeSnapshotClass{ - { - TypeMeta: metav1.TypeMeta{}, - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{ - utils.IsDefaultSnapshotClassAnnotation: "true", - }, - }, - Driver: "test.csi.io", - }, - }}, - }, - { - name: "new snapshot for class with existing default class same driver", - volumeSnapshotClass: &volumesnapshotv1.VolumeSnapshotClass{ - TypeMeta: metav1.TypeMeta{}, - ObjectMeta: metav1.ObjectMeta{}, - Driver: "test.csi.io", - }, - oldVolumeSnapshotClass: &volumesnapshotv1.VolumeSnapshotClass{}, - shouldAdmit: true, - msg: "", - operation: v1.Create, - lister: &fakeSnapshotLister{values: []*volumesnapshotv1.VolumeSnapshotClass{ - { - TypeMeta: metav1.TypeMeta{}, - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{ - utils.IsDefaultSnapshotClassAnnotation: "true", - }, - }, - Driver: "test.csi.io", - }, - }}, - }, - { - name: "new snapshot for class with existing default classes", - volumeSnapshotClass: &volumesnapshotv1.VolumeSnapshotClass{ - TypeMeta: metav1.TypeMeta{}, - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{ - utils.IsDefaultSnapshotClassAnnotation: "true", - }, - }, - Driver: "test.csi.io", - }, - oldVolumeSnapshotClass: &volumesnapshotv1.VolumeSnapshotClass{}, - shouldAdmit: false, - msg: "default snapshot class: driver-is-default already exists for driver: test.csi.io", - operation: v1.Create, - lister: &fakeSnapshotLister{values: []*volumesnapshotv1.VolumeSnapshotClass{ - { - TypeMeta: metav1.TypeMeta{}, - ObjectMeta: metav1.ObjectMeta{ - Name: "driver-is-default", - Annotations: map[string]string{ - utils.IsDefaultSnapshotClassAnnotation: "true", - }, - }, - Driver: "test.csi.io", - }, - { - TypeMeta: metav1.TypeMeta{}, - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{ - utils.IsDefaultSnapshotClassAnnotation: "true", - }, - }, - Driver: "test.csi.io", - }, - }}, - }, - { - name: "update snapshot class to new driver with existing default classes", - volumeSnapshotClass: &volumesnapshotv1.VolumeSnapshotClass{ - TypeMeta: metav1.TypeMeta{}, - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{ - utils.IsDefaultSnapshotClassAnnotation: "true", - }, - }, - Driver: "driver.test.csi.io", - }, - oldVolumeSnapshotClass: &volumesnapshotv1.VolumeSnapshotClass{ - TypeMeta: metav1.TypeMeta{}, - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{ - utils.IsDefaultSnapshotClassAnnotation: "true", - }, - }, - Driver: "test.csi.io", - }, - shouldAdmit: false, - msg: "default snapshot class: driver-test-default already exists for driver: driver.test.csi.io", - operation: v1.Update, - lister: &fakeSnapshotLister{values: []*volumesnapshotv1.VolumeSnapshotClass{ - { - TypeMeta: metav1.TypeMeta{}, - ObjectMeta: metav1.ObjectMeta{ - Name: "driver-is-default", - Annotations: map[string]string{ - utils.IsDefaultSnapshotClassAnnotation: "true", - }, - }, - Driver: "test.csi.io", - }, - { - TypeMeta: metav1.TypeMeta{}, - ObjectMeta: metav1.ObjectMeta{ - Name: "driver-test-default", - Annotations: map[string]string{ - utils.IsDefaultSnapshotClassAnnotation: "true", - }, - }, - Driver: "driver.test.csi.io", - }, - }}, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - snapshotContent := tc.volumeSnapshotClass - raw, err := json.Marshal(snapshotContent) - if err != nil { - t.Fatal(err) - } - oldSnapshotClass := tc.oldVolumeSnapshotClass - oldRaw, err := json.Marshal(oldSnapshotClass) - if err != nil { - t.Fatal(err) - } - review := v1.AdmissionReview{ - Request: &v1.AdmissionRequest{ - Object: runtime.RawExtension{ - Raw: raw, - }, - OldObject: runtime.RawExtension{ - Raw: oldRaw, - }, - Resource: SnapshotClassV1GVR, - Operation: tc.operation, - }, - } - sa := NewSnapshotAdmitter(tc.lister) - response := sa.Admit(review) - - shouldAdmit := response.Allowed - msg := response.Result.Message - - expectedResponse := tc.shouldAdmit - expectedMsg := tc.msg - - if shouldAdmit != expectedResponse { - t.Errorf("expected \"%v\" to equal \"%v\"", shouldAdmit, expectedResponse) - } - if msg != expectedMsg { - t.Errorf("expected \"%v\" to equal \"%v\"", msg, expectedMsg) - } - }) - } -} diff --git a/pkg/validation-webhook/webhook.go b/pkg/validation-webhook/webhook.go deleted file mode 100644 index 190fbb6aa..000000000 --- a/pkg/validation-webhook/webhook.go +++ /dev/null @@ -1,297 +0,0 @@ -/* -Copyright 2020 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 webhook - -import ( - "context" - "crypto/tls" - "encoding/json" - "fmt" - "io" - "net/http" - "os" - - clientset "github.com/kubernetes-csi/external-snapshotter/client/v8/clientset/versioned" - groupsnapshotlisters "github.com/kubernetes-csi/external-snapshotter/client/v8/listers/volumegroupsnapshot/v1alpha1" - snapshotlisters "github.com/kubernetes-csi/external-snapshotter/client/v8/listers/volumesnapshot/v1" - "github.com/spf13/cobra" - - informers "github.com/kubernetes-csi/external-snapshotter/client/v8/informers/externalversions" - v1 "k8s.io/api/admission/v1" - "k8s.io/api/admission/v1beta1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/client-go/rest" - "k8s.io/client-go/tools/clientcmd" - "k8s.io/klog/v2" -) - -var ( - certFile string - keyFile string - kubeconfigFile string - port int - preventVolumeModeConversion bool - enableVolumeGroupSnapshotWebhook bool -) - -// CmdWebhook is used by Cobra. -var CmdWebhook = &cobra.Command{ - Use: "validation-webhook", - Short: "Starts a HTTPS server, uses ValidatingAdmissionWebhook to perform ratcheting validation on VolumeSnapshot and VolumeSnapshotContent", - Long: `Starts a HTTPS server, uses ValidatingAdmissionWebhook to perform ratcheting validation on VolumeSnapshot and VolumeSnapshotContent. -After deploying it to Kubernetes cluster, the Administrator needs to create a ValidatingWebhookConfiguration -in the Kubernetes cluster to register remote webhook admission controllers. Phase one of https://github.com/kubernetes/enhancements/blob/master/keps/sig-storage/177-volume-snapshot/tighten-validation-webhook-crd.md`, - Args: cobra.MaximumNArgs(0), - Run: main, -} - -func init() { - CmdWebhook.Flags().StringVar(&certFile, "tls-cert-file", "", - "File containing the x509 Certificate for HTTPS. (CA cert, if any, concatenated after server cert). Required.") - CmdWebhook.Flags().StringVar(&keyFile, "tls-private-key-file", "", - "File containing the x509 private key matching --tls-cert-file. Required.") - CmdWebhook.Flags().IntVar(&port, "port", 443, - "Secure port that the webhook listens on") - CmdWebhook.MarkFlagRequired("tls-cert-file") - CmdWebhook.MarkFlagRequired("tls-private-key-file") - // Add optional flag for kubeconfig - CmdWebhook.Flags().StringVar(&kubeconfigFile, "kubeconfig", "", "kubeconfig file to use for volumesnapshotclasses") - CmdWebhook.Flags().BoolVar(&preventVolumeModeConversion, "prevent-volume-mode-conversion", - true, "Prevents an unauthorised user from modifying the volume mode when creating a PVC from an existing VolumeSnapshot.") - CmdWebhook.Flags().BoolVar(&enableVolumeGroupSnapshotWebhook, "enable-volume-group-snapshot-webhook", - false, "Enables webhook for VolumeGroupSnapshotClass.") -} - -// admitv1beta1Func handles a v1beta1 admission -type admitv1beta1Func func(v1beta1.AdmissionReview) *v1beta1.AdmissionResponse - -// admitv1beta1Func handles a v1 admission -type admitv1Func func(v1.AdmissionReview) *v1.AdmissionResponse - -// admitHandler is a handler, for both validators and mutators, that supports multiple admission review versions -type admitHandler struct { - SnapshotAdmitter -} - -func newDelegateToV1AdmitHandler(sa SnapshotAdmitter) admitHandler { - return admitHandler{ - SnapshotAdmitter: sa, - } -} - -func delegateV1beta1AdmitToV1(f admitv1Func) admitv1beta1Func { - return func(review v1beta1.AdmissionReview) *v1beta1.AdmissionResponse { - in := v1.AdmissionReview{Request: convertAdmissionRequestToV1(review.Request)} - out := f(in) - return convertAdmissionResponseToV1beta1(out) - } -} - -// serve handles the http portion of a request prior to handing to an admit -// function -func serve(w http.ResponseWriter, r *http.Request, admit admitHandler) { - var body []byte - if r.Body == nil { - msg := "Expected request body to be non-empty" - klog.Error(msg) - http.Error(w, msg, http.StatusBadRequest) - } - - data, err := io.ReadAll(r.Body) - if err != nil { - msg := fmt.Sprintf("Request could not be decoded: %v", err) - klog.Error(msg) - http.Error(w, msg, http.StatusBadRequest) - } - body = data - - // verify the content type is accurate - contentType := r.Header.Get("Content-Type") - if contentType != "application/json" { - msg := fmt.Sprintf("contentType=%s, expect application/json", contentType) - klog.Errorf(msg) - http.Error(w, msg, http.StatusBadRequest) - return - } - - klog.V(2).Info(fmt.Sprintf("handling request: %s", body)) - - deserializer := codecs.UniversalDeserializer() - obj, gvk, err := deserializer.Decode(body, nil, nil) - if err != nil { - msg := fmt.Sprintf("Request could not be decoded: %v", err) - klog.Error(msg) - http.Error(w, msg, http.StatusBadRequest) - return - } - - var responseObj runtime.Object - switch *gvk { - case v1beta1.SchemeGroupVersion.WithKind("AdmissionReview"): - requestedAdmissionReview, ok := obj.(*v1beta1.AdmissionReview) - if !ok { - msg := fmt.Sprintf("Expected v1beta1.AdmissionReview but got: %T", obj) - klog.Errorf(msg) - http.Error(w, msg, http.StatusBadRequest) - return - } - responseAdmissionReview := &v1beta1.AdmissionReview{} - responseAdmissionReview.SetGroupVersionKind(*gvk) - responseAdmissionReview.Response = delegateV1beta1AdmitToV1(admit.Admit)(*requestedAdmissionReview) - responseAdmissionReview.Response.UID = requestedAdmissionReview.Request.UID - responseObj = responseAdmissionReview - case v1.SchemeGroupVersion.WithKind("AdmissionReview"): - requestedAdmissionReview, ok := obj.(*v1.AdmissionReview) - if !ok { - msg := fmt.Sprintf("Expected v1.AdmissionReview but got: %T", obj) - klog.Errorf(msg) - http.Error(w, msg, http.StatusBadRequest) - return - } - responseAdmissionReview := &v1.AdmissionReview{} - responseAdmissionReview.SetGroupVersionKind(*gvk) - responseAdmissionReview.Response = admit.Admit(*requestedAdmissionReview) - responseAdmissionReview.Response.UID = requestedAdmissionReview.Request.UID - responseObj = responseAdmissionReview - default: - msg := fmt.Sprintf("Unsupported group version kind: %v", gvk) - klog.Error(msg) - http.Error(w, msg, http.StatusBadRequest) - return - } - - klog.V(2).Info(fmt.Sprintf("sending response: %v", responseObj)) - respBytes, err := json.Marshal(responseObj) - if err != nil { - klog.Error(err) - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - w.Header().Set("Content-Type", "application/json") - if _, err := w.Write(respBytes); err != nil { - klog.Error(err) - } -} - -type serveSnapshotWebhook struct { - lister snapshotlisters.VolumeSnapshotClassLister -} - -func (s serveSnapshotWebhook) ServeHTTP(w http.ResponseWriter, r *http.Request) { - serve(w, r, newDelegateToV1AdmitHandler(NewSnapshotAdmitter(s.lister))) -} - -type serveGroupSnapshotWebhook struct { - lister groupsnapshotlisters.VolumeGroupSnapshotClassLister -} - -func (s serveGroupSnapshotWebhook) ServeHTTP(w http.ResponseWriter, r *http.Request) { - serve(w, r, newDelegateToV1AdmitHandler(NewGroupSnapshotAdmitter(s.lister))) -} - -func startServer( - ctx context.Context, - tlsConfig *tls.Config, - cw *CertWatcher, - vscLister snapshotlisters.VolumeSnapshotClassLister, - vgscLister groupsnapshotlisters.VolumeGroupSnapshotClassLister, -) error { - go func() { - klog.Info("Starting certificate watcher") - if err := cw.Start(ctx); err != nil { - klog.Errorf("certificate watcher error: %v", err) - } - }() - // Pipe through the informer at some point here. - snapshotWebhook := serveSnapshotWebhook{ - lister: vscLister, - } - - fmt.Println("Starting webhook server") - mux := http.NewServeMux() - mux.Handle("/volumesnapshot", snapshotWebhook) - - if enableVolumeGroupSnapshotWebhook { - groupSnapshotWebhook := serveGroupSnapshotWebhook{ - lister: vgscLister, - } - mux.Handle("/volumegroupsnapshot", groupSnapshotWebhook) - } - - mux.HandleFunc("/readyz", func(w http.ResponseWriter, req *http.Request) { w.Write([]byte("ok")) }) - srv := &http.Server{ - Handler: mux, - TLSConfig: tlsConfig, - } - - // listener is always closed by srv.Serve - listener, err := tls.Listen("tcp", fmt.Sprintf(":%d", port), tlsConfig) - if err != nil { - return err - } - - return srv.Serve(listener) -} - -func main(cmd *cobra.Command, args []string) { - // Create new cert watcher - ctx, cancel := context.WithCancel(cmd.Context()) - defer cancel() // stops certwatcher - cw, err := NewCertWatcher(certFile, keyFile) - if err != nil { - klog.Fatalf("failed to initialize new cert watcher: %v", err) - } - tlsConfig := &tls.Config{ - GetCertificate: cw.GetCertificate, - } - - // Create an indexer. - // Create the client config. Use kubeconfig if given, otherwise assume in-cluster. - config, err := buildConfig(kubeconfigFile) - if err != nil { - klog.Error(err.Error()) - os.Exit(1) - } - snapClient, err := clientset.NewForConfig(config) - if err != nil { - klog.Errorf("Error building snapshot clientset: %s", err.Error()) - os.Exit(1) - } - - factory := informers.NewSharedInformerFactory(snapClient, 0) - snapshotLister := factory.Snapshot().V1().VolumeSnapshotClasses().Lister() - var groupSnapshotLister groupsnapshotlisters.VolumeGroupSnapshotClassLister - if enableVolumeGroupSnapshotWebhook { - groupSnapshotLister = factory.Groupsnapshot().V1alpha1().VolumeGroupSnapshotClasses().Lister() - } - - // Start the informers - factory.Start(ctx.Done()) - // wait for the caches to sync - factory.WaitForCacheSync(ctx.Done()) - - if err := startServer(ctx, tlsConfig, cw, snapshotLister, groupSnapshotLister); err != nil { - klog.Fatalf("server stopped: %v", err) - } -} - -func buildConfig(kubeconfig string) (*rest.Config, error) { - if kubeconfig != "" { - return clientcmd.BuildConfigFromFlags("", kubeconfig) - } - return rest.InClusterConfig() -} diff --git a/pkg/validation-webhook/webhook_test.go b/pkg/validation-webhook/webhook_test.go deleted file mode 100644 index daba532c7..000000000 --- a/pkg/validation-webhook/webhook_test.go +++ /dev/null @@ -1,180 +0,0 @@ -package webhook - -import ( - "context" - "crypto/rand" - "crypto/rsa" - "crypto/tls" - "crypto/x509" - "crypto/x509/pkix" - "encoding/pem" - "fmt" - "math/big" - "net" - "os" - "testing" - "time" -) - -func TestWebhookCertReload(t *testing.T) { - // Initialize test space - tmpDir := os.TempDir() + "/webhook-cert-tests" - certFile = tmpDir + "/tls.crt" - keyFile = tmpDir + "/tls.key" - port = 30443 - err := os.Mkdir(tmpDir, 0o777) - if err != nil && err != os.ErrExist { - t.Errorf("unexpected error occurred while creating tmp dir: %v", err) - } - defer func() { - err := os.RemoveAll(tmpDir) - if err != nil { - t.Errorf("unexpected error occurred while deleting certs: %v", err) - } - }() - err = generateTestCertKeyPair(t, certFile, keyFile) - if err != nil { - t.Errorf("unexpected error occurred while generating test certs: %v", err) - } - - // Start test server - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - cw, err := NewCertWatcher(certFile, keyFile) - if err != nil { - t.Errorf("failed to initialize new cert watcher: %v", err) - } - tlsConfig := &tls.Config{ - GetCertificate: cw.GetCertificate, - } - go func() { - err := startServer(ctx, - tlsConfig, - cw, - &fakeSnapshotLister{}, - &fakeGroupSnapshotLister{}) - if err != nil { - panic(err) - } - }() - time.Sleep(250 * time.Millisecond) // Give some time for watcher to start - - // TC: Original cert should not change with no file changes - originalCert, err := tlsConfig.GetCertificate(nil) - if err != nil { - t.Errorf("unexpected error occurred while getting cert: %v", err) - } - originalCertStr := string(originalCert.Certificate[0]) - originalKey := originalCert.PrivateKey.(*rsa.PrivateKey) - - newCert, err := tlsConfig.GetCertificate(nil) // get certificate again - if err != nil { - t.Errorf("unexpected error occurred while getting newcert: %v", err) - } - if string(newCert.Certificate[0]) != originalCertStr { - t.Error("new cert was updated when it should not have been") - } - newKey := newCert.PrivateKey.(*rsa.PrivateKey) - if !newKey.Equal(originalKey) { - t.Error("new key was updated when it should not have been") - } - - // TC: Certificate should consistently change with a file change - for i := 0; i < 5; i++ { - // Generate new key/cert - err = generateTestCertKeyPair(t, certFile, keyFile) - if err != nil { - t.Errorf("unexpected error occurred while generating test certs: %v", err) - } - - // Wait for certwatcher to update - time.Sleep(250 * time.Millisecond) - newCert, err = tlsConfig.GetCertificate(nil) - if err != nil { - t.Errorf("unexpected error occurred while getting newcert: %v", err) - } - if string(newCert.Certificate[0]) == originalCertStr { - t.Errorf("new cert was not updated") - } - - newKey = newCert.PrivateKey.(*rsa.PrivateKey) - if newKey.Equal(originalKey) { - t.Error("new key was not updated") - } - - originalCertStr = string(newCert.Certificate[0]) - originalKey = newKey - } -} - -// generateTestCertKeyPair generates a new random test key/crt and writes it to tmpDir -// based on https://golang.org/src/crypto/tls/generate_cert.go -func generateTestCertKeyPair(t *testing.T, certPath, keyPath string) error { - notBefore := time.Now() - serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) - serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) - if err != nil { - return fmt.Errorf("Failed to generate serial number: %v", err) - } - - var priv interface{} - priv, err = rsa.GenerateKey(rand.Reader, 4096) - if err != nil { - return fmt.Errorf("Failed to generate key: %v", err) - } - keyUsage := x509.KeyUsageDigitalSignature - if _, isRSA := priv.(*rsa.PrivateKey); isRSA { - keyUsage |= x509.KeyUsageKeyEncipherment - } - randomOrganizationStr := time.Now().String() - template := x509.Certificate{ - SerialNumber: serialNumber, - Subject: pkix.Name{ - Organization: []string{randomOrganizationStr}, - }, - NotBefore: notBefore, - NotAfter: time.Now().Add(1 * time.Hour), - - KeyUsage: keyUsage, - ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, - BasicConstraintsValid: true, - IPAddresses: []net.IP{net.ParseIP("127.0.0.1")}, - DNSNames: []string{"127.0.0.1"}, - } - - rk := priv.(*rsa.PrivateKey) - derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &rk.PublicKey, priv) - if err != nil { - return fmt.Errorf("Failed to create certificate: %v", err) - } - - certOut, err := os.Create(certPath) - if err != nil { - return fmt.Errorf("Failed to open tls.crt for writing: %v", err) - } - if err := pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil { - return fmt.Errorf("Failed to write data to tls.crt: %v", err) - } - if err := certOut.Close(); err != nil { - return fmt.Errorf("Error closing tls.crt: %v", err) - } - fmt.Printf("wrote new cert: %s\n", certPath) - - keyOut, err := os.OpenFile(keyPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600) - if err != nil { - return fmt.Errorf("Failed to open tls.key for writing: %v", err) - } - privBytes, err := x509.MarshalPKCS8PrivateKey(priv) - if err != nil { - return fmt.Errorf("Unable to marshal private key: %v", err) - } - if err := pem.Encode(keyOut, &pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}); err != nil { - return fmt.Errorf("Failed to write data to tls.key: %v", err) - } - if err := keyOut.Close(); err != nil { - return fmt.Errorf("Error closing tls.key: %v", err) - } - fmt.Printf("wrote new key: %s\n", keyPath) - - return nil -} diff --git a/vendor/github.com/fsnotify/fsnotify/.cirrus.yml b/vendor/github.com/fsnotify/fsnotify/.cirrus.yml deleted file mode 100644 index f4e7dbf37..000000000 --- a/vendor/github.com/fsnotify/fsnotify/.cirrus.yml +++ /dev/null @@ -1,14 +0,0 @@ -freebsd_task: - name: 'FreeBSD' - freebsd_instance: - image_family: freebsd-14-1 - install_script: - - pkg update -f - - pkg install -y go - test_script: - # run tests as user "cirrus" instead of root - - pw useradd cirrus -m - - chown -R cirrus:cirrus . - - FSNOTIFY_BUFFER=4096 sudo --preserve-env=FSNOTIFY_BUFFER -u cirrus go test -parallel 1 -race ./... - - sudo --preserve-env=FSNOTIFY_BUFFER -u cirrus go test -parallel 1 -race ./... - - FSNOTIFY_DEBUG=1 sudo --preserve-env=FSNOTIFY_BUFFER -u cirrus go test -parallel 1 -race -v ./... diff --git a/vendor/github.com/fsnotify/fsnotify/.gitignore b/vendor/github.com/fsnotify/fsnotify/.gitignore deleted file mode 100644 index daea9dd6d..000000000 --- a/vendor/github.com/fsnotify/fsnotify/.gitignore +++ /dev/null @@ -1,10 +0,0 @@ -# go test -c output -*.test -*.test.exe - -# Output of go build ./cmd/fsnotify -/fsnotify -/fsnotify.exe - -/test/kqueue -/test/a.out diff --git a/vendor/github.com/fsnotify/fsnotify/.mailmap b/vendor/github.com/fsnotify/fsnotify/.mailmap deleted file mode 100644 index a04f2907f..000000000 --- a/vendor/github.com/fsnotify/fsnotify/.mailmap +++ /dev/null @@ -1,2 +0,0 @@ -Chris Howey -Nathan Youngman <4566+nathany@users.noreply.github.com> diff --git a/vendor/github.com/fsnotify/fsnotify/CHANGELOG.md b/vendor/github.com/fsnotify/fsnotify/CHANGELOG.md deleted file mode 100644 index fa854785d..000000000 --- a/vendor/github.com/fsnotify/fsnotify/CHANGELOG.md +++ /dev/null @@ -1,569 +0,0 @@ -# Changelog - -1.8.0 2023-10-31 ----------------- - -### Additions - -- all: add `FSNOTIFY_DEBUG` to print debug logs to stderr ([#619]) - -### Changes and fixes - -- windows: fix behaviour of `WatchList()` to be consistent with other platforms ([#610]) - -- kqueue: ignore events with Ident=0 ([#590]) - -- kqueue: set O_CLOEXEC to prevent passing file descriptors to children ([#617]) - -- kqueue: emit events as "/path/dir/file" instead of "path/link/file" when watching a symlink ([#625]) - -- inotify: don't send event for IN_DELETE_SELF when also watching the parent ([#620]) - -- inotify: fix panic when calling Remove() in a goroutine ([#650]) - -- fen: allow watching subdirectories of watched directories ([#621]) - -[#590]: https://github.com/fsnotify/fsnotify/pull/590 -[#610]: https://github.com/fsnotify/fsnotify/pull/610 -[#617]: https://github.com/fsnotify/fsnotify/pull/617 -[#619]: https://github.com/fsnotify/fsnotify/pull/619 -[#620]: https://github.com/fsnotify/fsnotify/pull/620 -[#621]: https://github.com/fsnotify/fsnotify/pull/621 -[#625]: https://github.com/fsnotify/fsnotify/pull/625 -[#650]: https://github.com/fsnotify/fsnotify/pull/650 - -1.7.0 - 2023-10-22 ------------------- -This version of fsnotify needs Go 1.17. - -### Additions - -- illumos: add FEN backend to support illumos and Solaris. ([#371]) - -- all: add `NewBufferedWatcher()` to use a buffered channel, which can be useful - in cases where you can't control the kernel buffer and receive a large number - of events in bursts. ([#550], [#572]) - -- all: add `AddWith()`, which is identical to `Add()` but allows passing - options. ([#521]) - -- windows: allow setting the ReadDirectoryChangesW() buffer size with - `fsnotify.WithBufferSize()`; the default of 64K is the highest value that - works on all platforms and is enough for most purposes, but in some cases a - highest buffer is needed. ([#521]) - -### Changes and fixes - -- inotify: remove watcher if a watched path is renamed ([#518]) - - After a rename the reported name wasn't updated, or even an empty string. - Inotify doesn't provide any good facilities to update it, so just remove the - watcher. This is already how it worked on kqueue and FEN. - - On Windows this does work, and remains working. - -- windows: don't listen for file attribute changes ([#520]) - - File attribute changes are sent as `FILE_ACTION_MODIFIED` by the Windows API, - with no way to see if they're a file write or attribute change, so would show - up as a fsnotify.Write event. This is never useful, and could result in many - spurious Write events. - -- windows: return `ErrEventOverflow` if the buffer is full ([#525]) - - Before it would merely return "short read", making it hard to detect this - error. - -- kqueue: make sure events for all files are delivered properly when removing a - watched directory ([#526]) - - Previously they would get sent with `""` (empty string) or `"."` as the path - name. - -- kqueue: don't emit spurious Create events for symbolic links ([#524]) - - The link would get resolved but kqueue would "forget" it already saw the link - itself, resulting on a Create for every Write event for the directory. - -- all: return `ErrClosed` on `Add()` when the watcher is closed ([#516]) - -- other: add `Watcher.Errors` and `Watcher.Events` to the no-op `Watcher` in - `backend_other.go`, making it easier to use on unsupported platforms such as - WASM, AIX, etc. ([#528]) - -- other: use the `backend_other.go` no-op if the `appengine` build tag is set; - Google AppEngine forbids usage of the unsafe package so the inotify backend - won't compile there. - -[#371]: https://github.com/fsnotify/fsnotify/pull/371 -[#516]: https://github.com/fsnotify/fsnotify/pull/516 -[#518]: https://github.com/fsnotify/fsnotify/pull/518 -[#520]: https://github.com/fsnotify/fsnotify/pull/520 -[#521]: https://github.com/fsnotify/fsnotify/pull/521 -[#524]: https://github.com/fsnotify/fsnotify/pull/524 -[#525]: https://github.com/fsnotify/fsnotify/pull/525 -[#526]: https://github.com/fsnotify/fsnotify/pull/526 -[#528]: https://github.com/fsnotify/fsnotify/pull/528 -[#537]: https://github.com/fsnotify/fsnotify/pull/537 -[#550]: https://github.com/fsnotify/fsnotify/pull/550 -[#572]: https://github.com/fsnotify/fsnotify/pull/572 - -1.6.0 - 2022-10-13 ------------------- -This version of fsnotify needs Go 1.16 (this was already the case since 1.5.1, -but not documented). It also increases the minimum Linux version to 2.6.32. - -### Additions - -- all: add `Event.Has()` and `Op.Has()` ([#477]) - - This makes checking events a lot easier; for example: - - if event.Op&Write == Write && !(event.Op&Remove == Remove) { - } - - Becomes: - - if event.Has(Write) && !event.Has(Remove) { - } - -- all: add cmd/fsnotify ([#463]) - - A command-line utility for testing and some examples. - -### Changes and fixes - -- inotify: don't ignore events for files that don't exist ([#260], [#470]) - - Previously the inotify watcher would call `os.Lstat()` to check if a file - still exists before emitting events. - - This was inconsistent with other platforms and resulted in inconsistent event - reporting (e.g. when a file is quickly removed and re-created), and generally - a source of confusion. It was added in 2013 to fix a memory leak that no - longer exists. - -- all: return `ErrNonExistentWatch` when `Remove()` is called on a path that's - not watched ([#460]) - -- inotify: replace epoll() with non-blocking inotify ([#434]) - - Non-blocking inotify was not generally available at the time this library was - written in 2014, but now it is. As a result, the minimum Linux version is - bumped from 2.6.27 to 2.6.32. This hugely simplifies the code and is faster. - -- kqueue: don't check for events every 100ms ([#480]) - - The watcher would wake up every 100ms, even when there was nothing to do. Now - it waits until there is something to do. - -- macos: retry opening files on EINTR ([#475]) - -- kqueue: skip unreadable files ([#479]) - - kqueue requires a file descriptor for every file in a directory; this would - fail if a file was unreadable by the current user. Now these files are simply - skipped. - -- windows: fix renaming a watched directory if the parent is also watched ([#370]) - -- windows: increase buffer size from 4K to 64K ([#485]) - -- windows: close file handle on Remove() ([#288]) - -- kqueue: put pathname in the error if watching a file fails ([#471]) - -- inotify, windows: calling Close() more than once could race ([#465]) - -- kqueue: improve Close() performance ([#233]) - -- all: various documentation additions and clarifications. - -[#233]: https://github.com/fsnotify/fsnotify/pull/233 -[#260]: https://github.com/fsnotify/fsnotify/pull/260 -[#288]: https://github.com/fsnotify/fsnotify/pull/288 -[#370]: https://github.com/fsnotify/fsnotify/pull/370 -[#434]: https://github.com/fsnotify/fsnotify/pull/434 -[#460]: https://github.com/fsnotify/fsnotify/pull/460 -[#463]: https://github.com/fsnotify/fsnotify/pull/463 -[#465]: https://github.com/fsnotify/fsnotify/pull/465 -[#470]: https://github.com/fsnotify/fsnotify/pull/470 -[#471]: https://github.com/fsnotify/fsnotify/pull/471 -[#475]: https://github.com/fsnotify/fsnotify/pull/475 -[#477]: https://github.com/fsnotify/fsnotify/pull/477 -[#479]: https://github.com/fsnotify/fsnotify/pull/479 -[#480]: https://github.com/fsnotify/fsnotify/pull/480 -[#485]: https://github.com/fsnotify/fsnotify/pull/485 - -## [1.5.4] - 2022-04-25 - -* Windows: add missing defer to `Watcher.WatchList` [#447](https://github.com/fsnotify/fsnotify/pull/447) -* go.mod: use latest x/sys [#444](https://github.com/fsnotify/fsnotify/pull/444) -* Fix compilation for OpenBSD [#443](https://github.com/fsnotify/fsnotify/pull/443) - -## [1.5.3] - 2022-04-22 - -* This version is retracted. An incorrect branch is published accidentally [#445](https://github.com/fsnotify/fsnotify/issues/445) - -## [1.5.2] - 2022-04-21 - -* Add a feature to return the directories and files that are being monitored [#374](https://github.com/fsnotify/fsnotify/pull/374) -* Fix potential crash on windows if `raw.FileNameLength` exceeds `syscall.MAX_PATH` [#361](https://github.com/fsnotify/fsnotify/pull/361) -* Allow build on unsupported GOOS [#424](https://github.com/fsnotify/fsnotify/pull/424) -* Don't set `poller.fd` twice in `newFdPoller` [#406](https://github.com/fsnotify/fsnotify/pull/406) -* fix go vet warnings: call to `(*T).Fatalf` from a non-test goroutine [#416](https://github.com/fsnotify/fsnotify/pull/416) - -## [1.5.1] - 2021-08-24 - -* Revert Add AddRaw to not follow symlinks [#394](https://github.com/fsnotify/fsnotify/pull/394) - -## [1.5.0] - 2021-08-20 - -* Go: Increase minimum required version to Go 1.12 [#381](https://github.com/fsnotify/fsnotify/pull/381) -* Feature: Add AddRaw method which does not follow symlinks when adding a watch [#289](https://github.com/fsnotify/fsnotify/pull/298) -* Windows: Follow symlinks by default like on all other systems [#289](https://github.com/fsnotify/fsnotify/pull/289) -* CI: Use GitHub Actions for CI and cover go 1.12-1.17 - [#378](https://github.com/fsnotify/fsnotify/pull/378) - [#381](https://github.com/fsnotify/fsnotify/pull/381) - [#385](https://github.com/fsnotify/fsnotify/pull/385) -* Go 1.14+: Fix unsafe pointer conversion [#325](https://github.com/fsnotify/fsnotify/pull/325) - -## [1.4.9] - 2020-03-11 - -* Move example usage to the readme #329. This may resolve #328. - -## [1.4.8] - 2020-03-10 - -* CI: test more go versions (@nathany 1d13583d846ea9d66dcabbfefbfb9d8e6fb05216) -* Tests: Queued inotify events could have been read by the test before max_queued_events was hit (@matthias-stone #265) -* Tests: t.Fatalf -> t.Errorf in go routines (@gdey #266) -* CI: Less verbosity (@nathany #267) -* Tests: Darwin: Exchangedata is deprecated on 10.13 (@nathany #267) -* Tests: Check if channels are closed in the example (@alexeykazakov #244) -* CI: Only run golint on latest version of go and fix issues (@cpuguy83 #284) -* CI: Add windows to travis matrix (@cpuguy83 #284) -* Docs: Remover appveyor badge (@nathany 11844c0959f6fff69ba325d097fce35bd85a8e93) -* Linux: create epoll and pipe fds with close-on-exec (@JohannesEbke #219) -* Linux: open files with close-on-exec (@linxiulei #273) -* Docs: Plan to support fanotify (@nathany ab058b44498e8b7566a799372a39d150d9ea0119 ) -* Project: Add go.mod (@nathany #309) -* Project: Revise editor config (@nathany #309) -* Project: Update copyright for 2019 (@nathany #309) -* CI: Drop go1.8 from CI matrix (@nathany #309) -* Docs: Updating the FAQ section for supportability with NFS & FUSE filesystems (@Pratik32 4bf2d1fec78374803a39307bfb8d340688f4f28e ) - -## [1.4.7] - 2018-01-09 - -* BSD/macOS: Fix possible deadlock on closing the watcher on kqueue (thanks @nhooyr and @glycerine) -* Tests: Fix missing verb on format string (thanks @rchiossi) -* Linux: Fix deadlock in Remove (thanks @aarondl) -* Linux: Watch.Add improvements (avoid race, fix consistency, reduce garbage) (thanks @twpayne) -* Docs: Moved FAQ into the README (thanks @vahe) -* Linux: Properly handle inotify's IN_Q_OVERFLOW event (thanks @zeldovich) -* Docs: replace references to OS X with macOS - -## [1.4.2] - 2016-10-10 - -* Linux: use InotifyInit1 with IN_CLOEXEC to stop leaking a file descriptor to a child process when using fork/exec [#178](https://github.com/fsnotify/fsnotify/pull/178) (thanks @pattyshack) - -## [1.4.1] - 2016-10-04 - -* Fix flaky inotify stress test on Linux [#177](https://github.com/fsnotify/fsnotify/pull/177) (thanks @pattyshack) - -## [1.4.0] - 2016-10-01 - -* add a String() method to Event.Op [#165](https://github.com/fsnotify/fsnotify/pull/165) (thanks @oozie) - -## [1.3.1] - 2016-06-28 - -* Windows: fix for double backslash when watching the root of a drive [#151](https://github.com/fsnotify/fsnotify/issues/151) (thanks @brunoqc) - -## [1.3.0] - 2016-04-19 - -* Support linux/arm64 by [patching](https://go-review.googlesource.com/#/c/21971/) x/sys/unix and switching to to it from syscall (thanks @suihkulokki) [#135](https://github.com/fsnotify/fsnotify/pull/135) - -## [1.2.10] - 2016-03-02 - -* Fix golint errors in windows.go [#121](https://github.com/fsnotify/fsnotify/pull/121) (thanks @tiffanyfj) - -## [1.2.9] - 2016-01-13 - -kqueue: Fix logic for CREATE after REMOVE [#111](https://github.com/fsnotify/fsnotify/pull/111) (thanks @bep) - -## [1.2.8] - 2015-12-17 - -* kqueue: fix race condition in Close [#105](https://github.com/fsnotify/fsnotify/pull/105) (thanks @djui for reporting the issue and @ppknap for writing a failing test) -* inotify: fix race in test -* enable race detection for continuous integration (Linux, Mac, Windows) - -## [1.2.5] - 2015-10-17 - -* inotify: use epoll_create1 for arm64 support (requires Linux 2.6.27 or later) [#100](https://github.com/fsnotify/fsnotify/pull/100) (thanks @suihkulokki) -* inotify: fix path leaks [#73](https://github.com/fsnotify/fsnotify/pull/73) (thanks @chamaken) -* kqueue: watch for rename events on subdirectories [#83](https://github.com/fsnotify/fsnotify/pull/83) (thanks @guotie) -* kqueue: avoid infinite loops from symlinks cycles [#101](https://github.com/fsnotify/fsnotify/pull/101) (thanks @illicitonion) - -## [1.2.1] - 2015-10-14 - -* kqueue: don't watch named pipes [#98](https://github.com/fsnotify/fsnotify/pull/98) (thanks @evanphx) - -## [1.2.0] - 2015-02-08 - -* inotify: use epoll to wake up readEvents [#66](https://github.com/fsnotify/fsnotify/pull/66) (thanks @PieterD) -* inotify: closing watcher should now always shut down goroutine [#63](https://github.com/fsnotify/fsnotify/pull/63) (thanks @PieterD) -* kqueue: close kqueue after removing watches, fixes [#59](https://github.com/fsnotify/fsnotify/issues/59) - -## [1.1.1] - 2015-02-05 - -* inotify: Retry read on EINTR [#61](https://github.com/fsnotify/fsnotify/issues/61) (thanks @PieterD) - -## [1.1.0] - 2014-12-12 - -* kqueue: rework internals [#43](https://github.com/fsnotify/fsnotify/pull/43) - * add low-level functions - * only need to store flags on directories - * less mutexes [#13](https://github.com/fsnotify/fsnotify/issues/13) - * done can be an unbuffered channel - * remove calls to os.NewSyscallError -* More efficient string concatenation for Event.String() [#52](https://github.com/fsnotify/fsnotify/pull/52) (thanks @mdlayher) -* kqueue: fix regression in rework causing subdirectories to be watched [#48](https://github.com/fsnotify/fsnotify/issues/48) -* kqueue: cleanup internal watch before sending remove event [#51](https://github.com/fsnotify/fsnotify/issues/51) - -## [1.0.4] - 2014-09-07 - -* kqueue: add dragonfly to the build tags. -* Rename source code files, rearrange code so exported APIs are at the top. -* Add done channel to example code. [#37](https://github.com/fsnotify/fsnotify/pull/37) (thanks @chenyukang) - -## [1.0.3] - 2014-08-19 - -* [Fix] Windows MOVED_TO now translates to Create like on BSD and Linux. [#36](https://github.com/fsnotify/fsnotify/issues/36) - -## [1.0.2] - 2014-08-17 - -* [Fix] Missing create events on macOS. [#14](https://github.com/fsnotify/fsnotify/issues/14) (thanks @zhsso) -* [Fix] Make ./path and path equivalent. (thanks @zhsso) - -## [1.0.0] - 2014-08-15 - -* [API] Remove AddWatch on Windows, use Add. -* Improve documentation for exported identifiers. [#30](https://github.com/fsnotify/fsnotify/issues/30) -* Minor updates based on feedback from golint. - -## dev / 2014-07-09 - -* Moved to [github.com/fsnotify/fsnotify](https://github.com/fsnotify/fsnotify). -* Use os.NewSyscallError instead of returning errno (thanks @hariharan-uno) - -## dev / 2014-07-04 - -* kqueue: fix incorrect mutex used in Close() -* Update example to demonstrate usage of Op. - -## dev / 2014-06-28 - -* [API] Don't set the Write Op for attribute notifications [#4](https://github.com/fsnotify/fsnotify/issues/4) -* Fix for String() method on Event (thanks Alex Brainman) -* Don't build on Plan 9 or Solaris (thanks @4ad) - -## dev / 2014-06-21 - -* Events channel of type Event rather than *Event. -* [internal] use syscall constants directly for inotify and kqueue. -* [internal] kqueue: rename events to kevents and fileEvent to event. - -## dev / 2014-06-19 - -* Go 1.3+ required on Windows (uses syscall.ERROR_MORE_DATA internally). -* [internal] remove cookie from Event struct (unused). -* [internal] Event struct has the same definition across every OS. -* [internal] remove internal watch and removeWatch methods. - -## dev / 2014-06-12 - -* [API] Renamed Watch() to Add() and RemoveWatch() to Remove(). -* [API] Pluralized channel names: Events and Errors. -* [API] Renamed FileEvent struct to Event. -* [API] Op constants replace methods like IsCreate(). - -## dev / 2014-06-12 - -* Fix data race on kevent buffer (thanks @tilaks) [#98](https://github.com/howeyc/fsnotify/pull/98) - -## dev / 2014-05-23 - -* [API] Remove current implementation of WatchFlags. - * current implementation doesn't take advantage of OS for efficiency - * provides little benefit over filtering events as they are received, but has extra bookkeeping and mutexes - * no tests for the current implementation - * not fully implemented on Windows [#93](https://github.com/howeyc/fsnotify/issues/93#issuecomment-39285195) - -## [0.9.3] - 2014-12-31 - -* kqueue: cleanup internal watch before sending remove event [#51](https://github.com/fsnotify/fsnotify/issues/51) - -## [0.9.2] - 2014-08-17 - -* [Backport] Fix missing create events on macOS. [#14](https://github.com/fsnotify/fsnotify/issues/14) (thanks @zhsso) - -## [0.9.1] - 2014-06-12 - -* Fix data race on kevent buffer (thanks @tilaks) [#98](https://github.com/howeyc/fsnotify/pull/98) - -## [0.9.0] - 2014-01-17 - -* IsAttrib() for events that only concern a file's metadata [#79][] (thanks @abustany) -* [Fix] kqueue: fix deadlock [#77][] (thanks @cespare) -* [NOTICE] Development has moved to `code.google.com/p/go.exp/fsnotify` in preparation for inclusion in the Go standard library. - -## [0.8.12] - 2013-11-13 - -* [API] Remove FD_SET and friends from Linux adapter - -## [0.8.11] - 2013-11-02 - -* [Doc] Add Changelog [#72][] (thanks @nathany) -* [Doc] Spotlight and double modify events on macOS [#62][] (reported by @paulhammond) - -## [0.8.10] - 2013-10-19 - -* [Fix] kqueue: remove file watches when parent directory is removed [#71][] (reported by @mdwhatcott) -* [Fix] kqueue: race between Close and readEvents [#70][] (reported by @bernerdschaefer) -* [Doc] specify OS-specific limits in README (thanks @debrando) - -## [0.8.9] - 2013-09-08 - -* [Doc] Contributing (thanks @nathany) -* [Doc] update package path in example code [#63][] (thanks @paulhammond) -* [Doc] GoCI badge in README (Linux only) [#60][] -* [Doc] Cross-platform testing with Vagrant [#59][] (thanks @nathany) - -## [0.8.8] - 2013-06-17 - -* [Fix] Windows: handle `ERROR_MORE_DATA` on Windows [#49][] (thanks @jbowtie) - -## [0.8.7] - 2013-06-03 - -* [API] Make syscall flags internal -* [Fix] inotify: ignore event changes -* [Fix] race in symlink test [#45][] (reported by @srid) -* [Fix] tests on Windows -* lower case error messages - -## [0.8.6] - 2013-05-23 - -* kqueue: Use EVT_ONLY flag on Darwin -* [Doc] Update README with full example - -## [0.8.5] - 2013-05-09 - -* [Fix] inotify: allow monitoring of "broken" symlinks (thanks @tsg) - -## [0.8.4] - 2013-04-07 - -* [Fix] kqueue: watch all file events [#40][] (thanks @ChrisBuchholz) - -## [0.8.3] - 2013-03-13 - -* [Fix] inoitfy/kqueue memory leak [#36][] (reported by @nbkolchin) -* [Fix] kqueue: use fsnFlags for watching a directory [#33][] (reported by @nbkolchin) - -## [0.8.2] - 2013-02-07 - -* [Doc] add Authors -* [Fix] fix data races for map access [#29][] (thanks @fsouza) - -## [0.8.1] - 2013-01-09 - -* [Fix] Windows path separators -* [Doc] BSD License - -## [0.8.0] - 2012-11-09 - -* kqueue: directory watching improvements (thanks @vmirage) -* inotify: add `IN_MOVED_TO` [#25][] (requested by @cpisto) -* [Fix] kqueue: deleting watched directory [#24][] (reported by @jakerr) - -## [0.7.4] - 2012-10-09 - -* [Fix] inotify: fixes from https://codereview.appspot.com/5418045/ (ugorji) -* [Fix] kqueue: preserve watch flags when watching for delete [#21][] (reported by @robfig) -* [Fix] kqueue: watch the directory even if it isn't a new watch (thanks @robfig) -* [Fix] kqueue: modify after recreation of file - -## [0.7.3] - 2012-09-27 - -* [Fix] kqueue: watch with an existing folder inside the watched folder (thanks @vmirage) -* [Fix] kqueue: no longer get duplicate CREATE events - -## [0.7.2] - 2012-09-01 - -* kqueue: events for created directories - -## [0.7.1] - 2012-07-14 - -* [Fix] for renaming files - -## [0.7.0] - 2012-07-02 - -* [Feature] FSNotify flags -* [Fix] inotify: Added file name back to event path - -## [0.6.0] - 2012-06-06 - -* kqueue: watch files after directory created (thanks @tmc) - -## [0.5.1] - 2012-05-22 - -* [Fix] inotify: remove all watches before Close() - -## [0.5.0] - 2012-05-03 - -* [API] kqueue: return errors during watch instead of sending over channel -* kqueue: match symlink behavior on Linux -* inotify: add `DELETE_SELF` (requested by @taralx) -* [Fix] kqueue: handle EINTR (reported by @robfig) -* [Doc] Godoc example [#1][] (thanks @davecheney) - -## [0.4.0] - 2012-03-30 - -* Go 1 released: build with go tool -* [Feature] Windows support using winfsnotify -* Windows does not have attribute change notifications -* Roll attribute notifications into IsModify - -## [0.3.0] - 2012-02-19 - -* kqueue: add files when watch directory - -## [0.2.0] - 2011-12-30 - -* update to latest Go weekly code - -## [0.1.0] - 2011-10-19 - -* kqueue: add watch on file creation to match inotify -* kqueue: create file event -* inotify: ignore `IN_IGNORED` events -* event String() -* linux: common FileEvent functions -* initial commit - -[#79]: https://github.com/howeyc/fsnotify/pull/79 -[#77]: https://github.com/howeyc/fsnotify/pull/77 -[#72]: https://github.com/howeyc/fsnotify/issues/72 -[#71]: https://github.com/howeyc/fsnotify/issues/71 -[#70]: https://github.com/howeyc/fsnotify/issues/70 -[#63]: https://github.com/howeyc/fsnotify/issues/63 -[#62]: https://github.com/howeyc/fsnotify/issues/62 -[#60]: https://github.com/howeyc/fsnotify/issues/60 -[#59]: https://github.com/howeyc/fsnotify/issues/59 -[#49]: https://github.com/howeyc/fsnotify/issues/49 -[#45]: https://github.com/howeyc/fsnotify/issues/45 -[#40]: https://github.com/howeyc/fsnotify/issues/40 -[#36]: https://github.com/howeyc/fsnotify/issues/36 -[#33]: https://github.com/howeyc/fsnotify/issues/33 -[#29]: https://github.com/howeyc/fsnotify/issues/29 -[#25]: https://github.com/howeyc/fsnotify/issues/25 -[#24]: https://github.com/howeyc/fsnotify/issues/24 -[#21]: https://github.com/howeyc/fsnotify/issues/21 diff --git a/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md b/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md deleted file mode 100644 index e4ac2a2ff..000000000 --- a/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md +++ /dev/null @@ -1,144 +0,0 @@ -Thank you for your interest in contributing to fsnotify! We try to review and -merge PRs in a reasonable timeframe, but please be aware that: - -- To avoid "wasted" work, please discuss changes on the issue tracker first. You - can just send PRs, but they may end up being rejected for one reason or the - other. - -- fsnotify is a cross-platform library, and changes must work reasonably well on - all supported platforms. - -- Changes will need to be compatible; old code should still compile, and the - runtime behaviour can't change in ways that are likely to lead to problems for - users. - -Testing -------- -Just `go test ./...` runs all the tests; the CI runs this on all supported -platforms. Testing different platforms locally can be done with something like -[goon] or [Vagrant], but this isn't super-easy to set up at the moment. - -Use the `-short` flag to make the "stress test" run faster. - -Writing new tests ------------------ -Scripts in the testdata directory allow creating test cases in a "shell-like" -syntax. The basic format is: - - script - - Output: - desired output - -For example: - - # Create a new empty file with some data. - watch / - echo data >/file - - Output: - create /file - write /file - -Just create a new file to add a new test; select which tests to run with -`-run TestScript/[path]`. - -script ------- -The script is a "shell-like" script: - - cmd arg arg - -Comments are supported with `#`: - - # Comment - cmd arg arg # Comment - -All operations are done in a temp directory; a path like "/foo" is rewritten to -"/tmp/TestFoo/foo". - -Arguments can be quoted with `"` or `'`; there are no escapes and they're -functionally identical right now, but this may change in the future, so best to -assume shell-like rules. - - touch "/file with spaces" - -End-of-line escapes with `\` are not supported. - -### Supported commands - - watch path [ops] # Watch the path, reporting events for it. Nothing is - # watched by default. Optionally a list of ops can be - # given, as with AddWith(path, WithOps(...)). - unwatch path # Stop watching the path. - watchlist n # Assert watchlist length. - - stop # Stop running the script; for debugging. - debug [yes/no] # Enable/disable FSNOTIFY_DEBUG (tests are run in - parallel by default, so -parallel=1 is probably a good - idea). - - touch path - mkdir [-p] dir - ln -s target link # Only ln -s supported. - mkfifo path - mknod dev path - mv src dst - rm [-r] path - chmod mode path # Octal only - sleep time-in-ms - - cat path # Read path (does nothing with the data; just reads it). - echo str >>path # Append "str" to "path". - echo str >path # Truncate "path" and write "str". - - require reason # Skip the test if "reason" is true; "skip" and - skip reason # "require" behave identical; it supports both for - # readability. Possible reasons are: - # - # always Always skip this test. - # symlink Symlinks are supported (requires admin - # permissions on Windows). - # mkfifo Platform doesn't support FIFO named sockets. - # mknod Platform doesn't support device nodes. - - -output ------- -After `Output:` the desired output is given; this is indented by convention, but -that's not required. - -The format of that is: - - # Comment - event path # Comment - - system: - event path - system2: - event path - -Every event is one line, and any whitespace between the event and path are -ignored. The path can optionally be surrounded in ". Anything after a "#" is -ignored. - -Platform-specific tests can be added after GOOS; for example: - - watch / - touch /file - - Output: - # Tested if nothing else matches - create /file - - # Windows-specific test. - windows: - write /file - -You can specify multiple platforms with a comma (e.g. "windows, linux:"). -"kqueue" is a shortcut for all kqueue systems (BSD, macOS). - - -[goon]: https://github.com/arp242/goon -[Vagrant]: https://www.vagrantup.com/ -[integration_test.go]: /integration_test.go diff --git a/vendor/github.com/fsnotify/fsnotify/LICENSE b/vendor/github.com/fsnotify/fsnotify/LICENSE deleted file mode 100644 index fb03ade75..000000000 --- a/vendor/github.com/fsnotify/fsnotify/LICENSE +++ /dev/null @@ -1,25 +0,0 @@ -Copyright © 2012 The Go Authors. All rights reserved. -Copyright © fsnotify Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright notice, this - list of conditions and the following disclaimer in the documentation and/or - other materials provided with the distribution. -* Neither the name of Google Inc. nor the names of its contributors may be used - to endorse or promote products derived from this software without specific - prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/fsnotify/fsnotify/README.md b/vendor/github.com/fsnotify/fsnotify/README.md deleted file mode 100644 index e480733d1..000000000 --- a/vendor/github.com/fsnotify/fsnotify/README.md +++ /dev/null @@ -1,184 +0,0 @@ -fsnotify is a Go library to provide cross-platform filesystem notifications on -Windows, Linux, macOS, BSD, and illumos. - -Go 1.17 or newer is required; the full documentation is at -https://pkg.go.dev/github.com/fsnotify/fsnotify - ---- - -Platform support: - -| Backend | OS | Status | -| :-------------------- | :--------- | :------------------------------------------------------------------------ | -| inotify | Linux | Supported | -| kqueue | BSD, macOS | Supported | -| ReadDirectoryChangesW | Windows | Supported | -| FEN | illumos | Supported | -| fanotify | Linux 5.9+ | [Not yet](https://github.com/fsnotify/fsnotify/issues/114) | -| AHAFS | AIX | [aix branch]; experimental due to lack of maintainer and test environment | -| FSEvents | macOS | [Needs support in x/sys/unix][fsevents] | -| USN Journals | Windows | [Needs support in x/sys/windows][usn] | -| Polling | *All* | [Not yet](https://github.com/fsnotify/fsnotify/issues/9) | - -Linux and illumos should include Android and Solaris, but these are currently -untested. - -[fsevents]: https://github.com/fsnotify/fsnotify/issues/11#issuecomment-1279133120 -[usn]: https://github.com/fsnotify/fsnotify/issues/53#issuecomment-1279829847 -[aix branch]: https://github.com/fsnotify/fsnotify/issues/353#issuecomment-1284590129 - -Usage ------ -A basic example: - -```go -package main - -import ( - "log" - - "github.com/fsnotify/fsnotify" -) - -func main() { - // Create new watcher. - watcher, err := fsnotify.NewWatcher() - if err != nil { - log.Fatal(err) - } - defer watcher.Close() - - // Start listening for events. - go func() { - for { - select { - case event, ok := <-watcher.Events: - if !ok { - return - } - log.Println("event:", event) - if event.Has(fsnotify.Write) { - log.Println("modified file:", event.Name) - } - case err, ok := <-watcher.Errors: - if !ok { - return - } - log.Println("error:", err) - } - } - }() - - // Add a path. - err = watcher.Add("/tmp") - if err != nil { - log.Fatal(err) - } - - // Block main goroutine forever. - <-make(chan struct{}) -} -``` - -Some more examples can be found in [cmd/fsnotify](cmd/fsnotify), which can be -run with: - - % go run ./cmd/fsnotify - -Further detailed documentation can be found in godoc: -https://pkg.go.dev/github.com/fsnotify/fsnotify - -FAQ ---- -### Will a file still be watched when it's moved to another directory? -No, not unless you are watching the location it was moved to. - -### Are subdirectories watched? -No, you must add watches for any directory you want to watch (a recursive -watcher is on the roadmap: [#18]). - -[#18]: https://github.com/fsnotify/fsnotify/issues/18 - -### Do I have to watch the Error and Event channels in a goroutine? -Yes. You can read both channels in the same goroutine using `select` (you don't -need a separate goroutine for both channels; see the example). - -### Why don't notifications work with NFS, SMB, FUSE, /proc, or /sys? -fsnotify requires support from underlying OS to work. The current NFS and SMB -protocols does not provide network level support for file notifications, and -neither do the /proc and /sys virtual filesystems. - -This could be fixed with a polling watcher ([#9]), but it's not yet implemented. - -[#9]: https://github.com/fsnotify/fsnotify/issues/9 - -### Why do I get many Chmod events? -Some programs may generate a lot of attribute changes; for example Spotlight on -macOS, anti-virus programs, backup applications, and some others are known to do -this. As a rule, it's typically best to ignore Chmod events. They're often not -useful, and tend to cause problems. - -Spotlight indexing on macOS can result in multiple events (see [#15]). A -temporary workaround is to add your folder(s) to the *Spotlight Privacy -settings* until we have a native FSEvents implementation (see [#11]). - -[#11]: https://github.com/fsnotify/fsnotify/issues/11 -[#15]: https://github.com/fsnotify/fsnotify/issues/15 - -### Watching a file doesn't work well -Watching individual files (rather than directories) is generally not recommended -as many programs (especially editors) update files atomically: it will write to -a temporary file which is then moved to to destination, overwriting the original -(or some variant thereof). The watcher on the original file is now lost, as that -no longer exists. - -The upshot of this is that a power failure or crash won't leave a half-written -file. - -Watch the parent directory and use `Event.Name` to filter out files you're not -interested in. There is an example of this in `cmd/fsnotify/file.go`. - -Platform-specific notes ------------------------ -### Linux -When a file is removed a REMOVE event won't be emitted until all file -descriptors are closed; it will emit a CHMOD instead: - - fp := os.Open("file") - os.Remove("file") // CHMOD - fp.Close() // REMOVE - -This is the event that inotify sends, so not much can be changed about this. - -The `fs.inotify.max_user_watches` sysctl variable specifies the upper limit for -the number of watches per user, and `fs.inotify.max_user_instances` specifies -the maximum number of inotify instances per user. Every Watcher you create is an -"instance", and every path you add is a "watch". - -These are also exposed in `/proc` as `/proc/sys/fs/inotify/max_user_watches` and -`/proc/sys/fs/inotify/max_user_instances` - -To increase them you can use `sysctl` or write the value to proc file: - - # The default values on Linux 5.18 - sysctl fs.inotify.max_user_watches=124983 - sysctl fs.inotify.max_user_instances=128 - -To make the changes persist on reboot edit `/etc/sysctl.conf` or -`/usr/lib/sysctl.d/50-default.conf` (details differ per Linux distro; check your -distro's documentation): - - fs.inotify.max_user_watches=124983 - fs.inotify.max_user_instances=128 - -Reaching the limit will result in a "no space left on device" or "too many open -files" error. - -### kqueue (macOS, all BSD systems) -kqueue requires opening a file descriptor for every file that's being watched; -so if you're watching a directory with five files then that's six file -descriptors. You will run in to your system's "max open files" limit faster on -these platforms. - -The sysctl variables `kern.maxfiles` and `kern.maxfilesperproc` can be used to -control the maximum number of open files. diff --git a/vendor/github.com/fsnotify/fsnotify/backend_fen.go b/vendor/github.com/fsnotify/fsnotify/backend_fen.go deleted file mode 100644 index c349c326c..000000000 --- a/vendor/github.com/fsnotify/fsnotify/backend_fen.go +++ /dev/null @@ -1,484 +0,0 @@ -//go:build solaris - -// FEN backend for illumos (supported) and Solaris (untested, but should work). -// -// See port_create(3c) etc. for docs. https://www.illumos.org/man/3C/port_create - -package fsnotify - -import ( - "errors" - "fmt" - "os" - "path/filepath" - "sync" - "time" - - "github.com/fsnotify/fsnotify/internal" - "golang.org/x/sys/unix" -) - -type fen struct { - Events chan Event - Errors chan error - - mu sync.Mutex - port *unix.EventPort - done chan struct{} // Channel for sending a "quit message" to the reader goroutine - dirs map[string]Op // Explicitly watched directories - watches map[string]Op // Explicitly watched non-directories -} - -func newBackend(ev chan Event, errs chan error) (backend, error) { - return newBufferedBackend(0, ev, errs) -} - -func newBufferedBackend(sz uint, ev chan Event, errs chan error) (backend, error) { - w := &fen{ - Events: ev, - Errors: errs, - dirs: make(map[string]Op), - watches: make(map[string]Op), - done: make(chan struct{}), - } - - var err error - w.port, err = unix.NewEventPort() - if err != nil { - return nil, fmt.Errorf("fsnotify.NewWatcher: %w", err) - } - - go w.readEvents() - return w, nil -} - -// sendEvent attempts to send an event to the user, returning true if the event -// was put in the channel successfully and false if the watcher has been closed. -func (w *fen) sendEvent(name string, op Op) (sent bool) { - select { - case <-w.done: - return false - case w.Events <- Event{Name: name, Op: op}: - return true - } -} - -// sendError attempts to send an error to the user, returning true if the error -// was put in the channel successfully and false if the watcher has been closed. -func (w *fen) sendError(err error) (sent bool) { - if err == nil { - return true - } - select { - case <-w.done: - return false - case w.Errors <- err: - return true - } -} - -func (w *fen) isClosed() bool { - select { - case <-w.done: - return true - default: - return false - } -} - -func (w *fen) Close() error { - // Take the lock used by associateFile to prevent lingering events from - // being processed after the close - w.mu.Lock() - defer w.mu.Unlock() - if w.isClosed() { - return nil - } - close(w.done) - return w.port.Close() -} - -func (w *fen) Add(name string) error { return w.AddWith(name) } - -func (w *fen) AddWith(name string, opts ...addOpt) error { - if w.isClosed() { - return ErrClosed - } - if debug { - fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s AddWith(%q)\n", - time.Now().Format("15:04:05.000000000"), name) - } - - with := getOptions(opts...) - if !w.xSupports(with.op) { - return fmt.Errorf("%w: %s", xErrUnsupported, with.op) - } - - // Currently we resolve symlinks that were explicitly requested to be - // watched. Otherwise we would use LStat here. - stat, err := os.Stat(name) - if err != nil { - return err - } - - // Associate all files in the directory. - if stat.IsDir() { - err := w.handleDirectory(name, stat, true, w.associateFile) - if err != nil { - return err - } - - w.mu.Lock() - w.dirs[name] = with.op - w.mu.Unlock() - return nil - } - - err = w.associateFile(name, stat, true) - if err != nil { - return err - } - - w.mu.Lock() - w.watches[name] = with.op - w.mu.Unlock() - return nil -} - -func (w *fen) Remove(name string) error { - if w.isClosed() { - return nil - } - if !w.port.PathIsWatched(name) { - return fmt.Errorf("%w: %s", ErrNonExistentWatch, name) - } - if debug { - fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s Remove(%q)\n", - time.Now().Format("15:04:05.000000000"), name) - } - - // The user has expressed an intent. Immediately remove this name from - // whichever watch list it might be in. If it's not in there the delete - // doesn't cause harm. - w.mu.Lock() - delete(w.watches, name) - delete(w.dirs, name) - w.mu.Unlock() - - stat, err := os.Stat(name) - if err != nil { - return err - } - - // Remove associations for every file in the directory. - if stat.IsDir() { - err := w.handleDirectory(name, stat, false, w.dissociateFile) - if err != nil { - return err - } - return nil - } - - err = w.port.DissociatePath(name) - if err != nil { - return err - } - - return nil -} - -// readEvents contains the main loop that runs in a goroutine watching for events. -func (w *fen) readEvents() { - // If this function returns, the watcher has been closed and we can close - // these channels - defer func() { - close(w.Errors) - close(w.Events) - }() - - pevents := make([]unix.PortEvent, 8) - for { - count, err := w.port.Get(pevents, 1, nil) - if err != nil && err != unix.ETIME { - // Interrupted system call (count should be 0) ignore and continue - if errors.Is(err, unix.EINTR) && count == 0 { - continue - } - // Get failed because we called w.Close() - if errors.Is(err, unix.EBADF) && w.isClosed() { - return - } - // There was an error not caused by calling w.Close() - if !w.sendError(err) { - return - } - } - - p := pevents[:count] - for _, pevent := range p { - if pevent.Source != unix.PORT_SOURCE_FILE { - // Event from unexpected source received; should never happen. - if !w.sendError(errors.New("Event from unexpected source received")) { - return - } - continue - } - - if debug { - internal.Debug(pevent.Path, pevent.Events) - } - - err = w.handleEvent(&pevent) - if !w.sendError(err) { - return - } - } - } -} - -func (w *fen) handleDirectory(path string, stat os.FileInfo, follow bool, handler func(string, os.FileInfo, bool) error) error { - files, err := os.ReadDir(path) - if err != nil { - return err - } - - // Handle all children of the directory. - for _, entry := range files { - finfo, err := entry.Info() - if err != nil { - return err - } - err = handler(filepath.Join(path, finfo.Name()), finfo, false) - if err != nil { - return err - } - } - - // And finally handle the directory itself. - return handler(path, stat, follow) -} - -// handleEvent might need to emit more than one fsnotify event if the events -// bitmap matches more than one event type (e.g. the file was both modified and -// had the attributes changed between when the association was created and the -// when event was returned) -func (w *fen) handleEvent(event *unix.PortEvent) error { - var ( - events = event.Events - path = event.Path - fmode = event.Cookie.(os.FileMode) - reRegister = true - ) - - w.mu.Lock() - _, watchedDir := w.dirs[path] - _, watchedPath := w.watches[path] - w.mu.Unlock() - isWatched := watchedDir || watchedPath - - if events&unix.FILE_DELETE != 0 { - if !w.sendEvent(path, Remove) { - return nil - } - reRegister = false - } - if events&unix.FILE_RENAME_FROM != 0 { - if !w.sendEvent(path, Rename) { - return nil - } - // Don't keep watching the new file name - reRegister = false - } - if events&unix.FILE_RENAME_TO != 0 { - // We don't report a Rename event for this case, because Rename events - // are interpreted as referring to the _old_ name of the file, and in - // this case the event would refer to the new name of the file. This - // type of rename event is not supported by fsnotify. - - // inotify reports a Remove event in this case, so we simulate this - // here. - if !w.sendEvent(path, Remove) { - return nil - } - // Don't keep watching the file that was removed - reRegister = false - } - - // The file is gone, nothing left to do. - if !reRegister { - if watchedDir { - w.mu.Lock() - delete(w.dirs, path) - w.mu.Unlock() - } - if watchedPath { - w.mu.Lock() - delete(w.watches, path) - w.mu.Unlock() - } - return nil - } - - // If we didn't get a deletion the file still exists and we're going to have - // to watch it again. Let's Stat it now so that we can compare permissions - // and have what we need to continue watching the file - - stat, err := os.Lstat(path) - if err != nil { - // This is unexpected, but we should still emit an event. This happens - // most often on "rm -r" of a subdirectory inside a watched directory We - // get a modify event of something happening inside, but by the time we - // get here, the sudirectory is already gone. Clearly we were watching - // this path but now it is gone. Let's tell the user that it was - // removed. - if !w.sendEvent(path, Remove) { - return nil - } - // Suppress extra write events on removed directories; they are not - // informative and can be confusing. - return nil - } - - // resolve symlinks that were explicitly watched as we would have at Add() - // time. this helps suppress spurious Chmod events on watched symlinks - if isWatched { - stat, err = os.Stat(path) - if err != nil { - // The symlink still exists, but the target is gone. Report the - // Remove similar to above. - if !w.sendEvent(path, Remove) { - return nil - } - // Don't return the error - } - } - - if events&unix.FILE_MODIFIED != 0 { - if fmode.IsDir() && watchedDir { - if err := w.updateDirectory(path); err != nil { - return err - } - } else { - if !w.sendEvent(path, Write) { - return nil - } - } - } - if events&unix.FILE_ATTRIB != 0 && stat != nil { - // Only send Chmod if perms changed - if stat.Mode().Perm() != fmode.Perm() { - if !w.sendEvent(path, Chmod) { - return nil - } - } - } - - if stat != nil { - // If we get here, it means we've hit an event above that requires us to - // continue watching the file or directory - return w.associateFile(path, stat, isWatched) - } - return nil -} - -func (w *fen) updateDirectory(path string) error { - // The directory was modified, so we must find unwatched entities and watch - // them. If something was removed from the directory, nothing will happen, - // as everything else should still be watched. - files, err := os.ReadDir(path) - if err != nil { - return err - } - - for _, entry := range files { - path := filepath.Join(path, entry.Name()) - if w.port.PathIsWatched(path) { - continue - } - - finfo, err := entry.Info() - if err != nil { - return err - } - err = w.associateFile(path, finfo, false) - if !w.sendError(err) { - return nil - } - if !w.sendEvent(path, Create) { - return nil - } - } - return nil -} - -func (w *fen) associateFile(path string, stat os.FileInfo, follow bool) error { - if w.isClosed() { - return ErrClosed - } - // This is primarily protecting the call to AssociatePath but it is - // important and intentional that the call to PathIsWatched is also - // protected by this mutex. Without this mutex, AssociatePath has been seen - // to error out that the path is already associated. - w.mu.Lock() - defer w.mu.Unlock() - - if w.port.PathIsWatched(path) { - // Remove the old association in favor of this one If we get ENOENT, - // then while the x/sys/unix wrapper still thought that this path was - // associated, the underlying event port did not. This call will have - // cleared up that discrepancy. The most likely cause is that the event - // has fired but we haven't processed it yet. - err := w.port.DissociatePath(path) - if err != nil && !errors.Is(err, unix.ENOENT) { - return err - } - } - - var events int - if !follow { - // Watch symlinks themselves rather than their targets unless this entry - // is explicitly watched. - events |= unix.FILE_NOFOLLOW - } - if true { // TODO: implement withOps() - events |= unix.FILE_MODIFIED - } - if true { - events |= unix.FILE_ATTRIB - } - return w.port.AssociatePath(path, stat, events, stat.Mode()) -} - -func (w *fen) dissociateFile(path string, stat os.FileInfo, unused bool) error { - if !w.port.PathIsWatched(path) { - return nil - } - return w.port.DissociatePath(path) -} - -func (w *fen) WatchList() []string { - if w.isClosed() { - return nil - } - - w.mu.Lock() - defer w.mu.Unlock() - - entries := make([]string, 0, len(w.watches)+len(w.dirs)) - for pathname := range w.dirs { - entries = append(entries, pathname) - } - for pathname := range w.watches { - entries = append(entries, pathname) - } - - return entries -} - -func (w *fen) xSupports(op Op) bool { - if op.Has(xUnportableOpen) || op.Has(xUnportableRead) || - op.Has(xUnportableCloseWrite) || op.Has(xUnportableCloseRead) { - return false - } - return true -} diff --git a/vendor/github.com/fsnotify/fsnotify/backend_inotify.go b/vendor/github.com/fsnotify/fsnotify/backend_inotify.go deleted file mode 100644 index 36c311694..000000000 --- a/vendor/github.com/fsnotify/fsnotify/backend_inotify.go +++ /dev/null @@ -1,658 +0,0 @@ -//go:build linux && !appengine - -package fsnotify - -import ( - "errors" - "fmt" - "io" - "io/fs" - "os" - "path/filepath" - "strings" - "sync" - "time" - "unsafe" - - "github.com/fsnotify/fsnotify/internal" - "golang.org/x/sys/unix" -) - -type inotify struct { - Events chan Event - Errors chan error - - // Store fd here as os.File.Read() will no longer return on close after - // calling Fd(). See: https://github.com/golang/go/issues/26439 - fd int - inotifyFile *os.File - watches *watches - done chan struct{} // Channel for sending a "quit message" to the reader goroutine - doneMu sync.Mutex - doneResp chan struct{} // Channel to respond to Close - - // Store rename cookies in an array, with the index wrapping to 0. Almost - // all of the time what we get is a MOVED_FROM to set the cookie and the - // next event inotify sends will be MOVED_TO to read it. However, this is - // not guaranteed – as described in inotify(7) – and we may get other events - // between the two MOVED_* events (including other MOVED_* ones). - // - // A second issue is that moving a file outside the watched directory will - // trigger a MOVED_FROM to set the cookie, but we never see the MOVED_TO to - // read and delete it. So just storing it in a map would slowly leak memory. - // - // Doing it like this gives us a simple fast LRU-cache that won't allocate. - // Ten items should be more than enough for our purpose, and a loop over - // such a short array is faster than a map access anyway (not that it hugely - // matters since we're talking about hundreds of ns at the most, but still). - cookies [10]koekje - cookieIndex uint8 - cookiesMu sync.Mutex -} - -type ( - watches struct { - mu sync.RWMutex - wd map[uint32]*watch // wd → watch - path map[string]uint32 // pathname → wd - } - watch struct { - wd uint32 // Watch descriptor (as returned by the inotify_add_watch() syscall) - flags uint32 // inotify flags of this watch (see inotify(7) for the list of valid flags) - path string // Watch path. - recurse bool // Recursion with ./...? - } - koekje struct { - cookie uint32 - path string - } -) - -func newWatches() *watches { - return &watches{ - wd: make(map[uint32]*watch), - path: make(map[string]uint32), - } -} - -func (w *watches) len() int { - w.mu.RLock() - defer w.mu.RUnlock() - return len(w.wd) -} - -func (w *watches) add(ww *watch) { - w.mu.Lock() - defer w.mu.Unlock() - w.wd[ww.wd] = ww - w.path[ww.path] = ww.wd -} - -func (w *watches) remove(wd uint32) { - w.mu.Lock() - defer w.mu.Unlock() - watch := w.wd[wd] // Could have had Remove() called. See #616. - if watch == nil { - return - } - delete(w.path, watch.path) - delete(w.wd, wd) -} - -func (w *watches) removePath(path string) ([]uint32, error) { - w.mu.Lock() - defer w.mu.Unlock() - - path, recurse := recursivePath(path) - wd, ok := w.path[path] - if !ok { - return nil, fmt.Errorf("%w: %s", ErrNonExistentWatch, path) - } - - watch := w.wd[wd] - if recurse && !watch.recurse { - return nil, fmt.Errorf("can't use /... with non-recursive watch %q", path) - } - - delete(w.path, path) - delete(w.wd, wd) - if !watch.recurse { - return []uint32{wd}, nil - } - - wds := make([]uint32, 0, 8) - wds = append(wds, wd) - for p, rwd := range w.path { - if filepath.HasPrefix(p, path) { - delete(w.path, p) - delete(w.wd, rwd) - wds = append(wds, rwd) - } - } - return wds, nil -} - -func (w *watches) byPath(path string) *watch { - w.mu.RLock() - defer w.mu.RUnlock() - return w.wd[w.path[path]] -} - -func (w *watches) byWd(wd uint32) *watch { - w.mu.RLock() - defer w.mu.RUnlock() - return w.wd[wd] -} - -func (w *watches) updatePath(path string, f func(*watch) (*watch, error)) error { - w.mu.Lock() - defer w.mu.Unlock() - - var existing *watch - wd, ok := w.path[path] - if ok { - existing = w.wd[wd] - } - - upd, err := f(existing) - if err != nil { - return err - } - if upd != nil { - w.wd[upd.wd] = upd - w.path[upd.path] = upd.wd - - if upd.wd != wd { - delete(w.wd, wd) - } - } - - return nil -} - -func newBackend(ev chan Event, errs chan error) (backend, error) { - return newBufferedBackend(0, ev, errs) -} - -func newBufferedBackend(sz uint, ev chan Event, errs chan error) (backend, error) { - // Need to set nonblocking mode for SetDeadline to work, otherwise blocking - // I/O operations won't terminate on close. - fd, errno := unix.InotifyInit1(unix.IN_CLOEXEC | unix.IN_NONBLOCK) - if fd == -1 { - return nil, errno - } - - w := &inotify{ - Events: ev, - Errors: errs, - fd: fd, - inotifyFile: os.NewFile(uintptr(fd), ""), - watches: newWatches(), - done: make(chan struct{}), - doneResp: make(chan struct{}), - } - - go w.readEvents() - return w, nil -} - -// Returns true if the event was sent, or false if watcher is closed. -func (w *inotify) sendEvent(e Event) bool { - select { - case <-w.done: - return false - case w.Events <- e: - return true - } -} - -// Returns true if the error was sent, or false if watcher is closed. -func (w *inotify) sendError(err error) bool { - if err == nil { - return true - } - select { - case <-w.done: - return false - case w.Errors <- err: - return true - } -} - -func (w *inotify) isClosed() bool { - select { - case <-w.done: - return true - default: - return false - } -} - -func (w *inotify) Close() error { - w.doneMu.Lock() - if w.isClosed() { - w.doneMu.Unlock() - return nil - } - close(w.done) - w.doneMu.Unlock() - - // Causes any blocking reads to return with an error, provided the file - // still supports deadline operations. - err := w.inotifyFile.Close() - if err != nil { - return err - } - - // Wait for goroutine to close - <-w.doneResp - - return nil -} - -func (w *inotify) Add(name string) error { return w.AddWith(name) } - -func (w *inotify) AddWith(path string, opts ...addOpt) error { - if w.isClosed() { - return ErrClosed - } - if debug { - fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s AddWith(%q)\n", - time.Now().Format("15:04:05.000000000"), path) - } - - with := getOptions(opts...) - if !w.xSupports(with.op) { - return fmt.Errorf("%w: %s", xErrUnsupported, with.op) - } - - path, recurse := recursivePath(path) - if recurse { - return filepath.WalkDir(path, func(root string, d fs.DirEntry, err error) error { - if err != nil { - return err - } - if !d.IsDir() { - if root == path { - return fmt.Errorf("fsnotify: not a directory: %q", path) - } - return nil - } - - // Send a Create event when adding new directory from a recursive - // watch; this is for "mkdir -p one/two/three". Usually all those - // directories will be created before we can set up watchers on the - // subdirectories, so only "one" would be sent as a Create event and - // not "one/two" and "one/two/three" (inotifywait -r has the same - // problem). - if with.sendCreate && root != path { - w.sendEvent(Event{Name: root, Op: Create}) - } - - return w.add(root, with, true) - }) - } - - return w.add(path, with, false) -} - -func (w *inotify) add(path string, with withOpts, recurse bool) error { - var flags uint32 - if with.noFollow { - flags |= unix.IN_DONT_FOLLOW - } - if with.op.Has(Create) { - flags |= unix.IN_CREATE - } - if with.op.Has(Write) { - flags |= unix.IN_MODIFY - } - if with.op.Has(Remove) { - flags |= unix.IN_DELETE | unix.IN_DELETE_SELF - } - if with.op.Has(Rename) { - flags |= unix.IN_MOVED_TO | unix.IN_MOVED_FROM | unix.IN_MOVE_SELF - } - if with.op.Has(Chmod) { - flags |= unix.IN_ATTRIB - } - if with.op.Has(xUnportableOpen) { - flags |= unix.IN_OPEN - } - if with.op.Has(xUnportableRead) { - flags |= unix.IN_ACCESS - } - if with.op.Has(xUnportableCloseWrite) { - flags |= unix.IN_CLOSE_WRITE - } - if with.op.Has(xUnportableCloseRead) { - flags |= unix.IN_CLOSE_NOWRITE - } - return w.register(path, flags, recurse) -} - -func (w *inotify) register(path string, flags uint32, recurse bool) error { - return w.watches.updatePath(path, func(existing *watch) (*watch, error) { - if existing != nil { - flags |= existing.flags | unix.IN_MASK_ADD - } - - wd, err := unix.InotifyAddWatch(w.fd, path, flags) - if wd == -1 { - return nil, err - } - - if existing == nil { - return &watch{ - wd: uint32(wd), - path: path, - flags: flags, - recurse: recurse, - }, nil - } - - existing.wd = uint32(wd) - existing.flags = flags - return existing, nil - }) -} - -func (w *inotify) Remove(name string) error { - if w.isClosed() { - return nil - } - if debug { - fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s Remove(%q)\n", - time.Now().Format("15:04:05.000000000"), name) - } - return w.remove(filepath.Clean(name)) -} - -func (w *inotify) remove(name string) error { - wds, err := w.watches.removePath(name) - if err != nil { - return err - } - - for _, wd := range wds { - _, err := unix.InotifyRmWatch(w.fd, wd) - if err != nil { - // TODO: Perhaps it's not helpful to return an error here in every - // case; the only two possible errors are: - // - // EBADF, which happens when w.fd is not a valid file descriptor of - // any kind. - // - // EINVAL, which is when fd is not an inotify descriptor or wd is - // not a valid watch descriptor. Watch descriptors are invalidated - // when they are removed explicitly or implicitly; explicitly by - // inotify_rm_watch, implicitly when the file they are watching is - // deleted. - return err - } - } - return nil -} - -func (w *inotify) WatchList() []string { - if w.isClosed() { - return nil - } - - entries := make([]string, 0, w.watches.len()) - w.watches.mu.RLock() - for pathname := range w.watches.path { - entries = append(entries, pathname) - } - w.watches.mu.RUnlock() - - return entries -} - -// readEvents reads from the inotify file descriptor, converts the -// received events into Event objects and sends them via the Events channel -func (w *inotify) readEvents() { - defer func() { - close(w.doneResp) - close(w.Errors) - close(w.Events) - }() - - var ( - buf [unix.SizeofInotifyEvent * 4096]byte // Buffer for a maximum of 4096 raw events - errno error // Syscall errno - ) - for { - // See if we have been closed. - if w.isClosed() { - return - } - - n, err := w.inotifyFile.Read(buf[:]) - switch { - case errors.Unwrap(err) == os.ErrClosed: - return - case err != nil: - if !w.sendError(err) { - return - } - continue - } - - if n < unix.SizeofInotifyEvent { - var err error - if n == 0 { - err = io.EOF // If EOF is received. This should really never happen. - } else if n < 0 { - err = errno // If an error occurred while reading. - } else { - err = errors.New("notify: short read in readEvents()") // Read was too short. - } - if !w.sendError(err) { - return - } - continue - } - - // We don't know how many events we just read into the buffer - // While the offset points to at least one whole event... - var offset uint32 - for offset <= uint32(n-unix.SizeofInotifyEvent) { - var ( - // Point "raw" to the event in the buffer - raw = (*unix.InotifyEvent)(unsafe.Pointer(&buf[offset])) - mask = uint32(raw.Mask) - nameLen = uint32(raw.Len) - // Move to the next event in the buffer - next = func() { offset += unix.SizeofInotifyEvent + nameLen } - ) - - if mask&unix.IN_Q_OVERFLOW != 0 { - if !w.sendError(ErrEventOverflow) { - return - } - } - - /// If the event happened to the watched directory or the watched - /// file, the kernel doesn't append the filename to the event, but - /// we would like to always fill the the "Name" field with a valid - /// filename. We retrieve the path of the watch from the "paths" - /// map. - watch := w.watches.byWd(uint32(raw.Wd)) - /// Can be nil if Remove() was called in another goroutine for this - /// path inbetween reading the events from the kernel and reading - /// the internal state. Not much we can do about it, so just skip. - /// See #616. - if watch == nil { - next() - continue - } - - name := watch.path - if nameLen > 0 { - /// Point "bytes" at the first byte of the filename - bytes := (*[unix.PathMax]byte)(unsafe.Pointer(&buf[offset+unix.SizeofInotifyEvent]))[:nameLen:nameLen] - /// The filename is padded with NULL bytes. TrimRight() gets rid of those. - name += "/" + strings.TrimRight(string(bytes[0:nameLen]), "\000") - } - - if debug { - internal.Debug(name, raw.Mask, raw.Cookie) - } - - if mask&unix.IN_IGNORED != 0 { //&& event.Op != 0 - next() - continue - } - - // inotify will automatically remove the watch on deletes; just need - // to clean our state here. - if mask&unix.IN_DELETE_SELF == unix.IN_DELETE_SELF { - w.watches.remove(watch.wd) - } - - // We can't really update the state when a watched path is moved; - // only IN_MOVE_SELF is sent and not IN_MOVED_{FROM,TO}. So remove - // the watch. - if mask&unix.IN_MOVE_SELF == unix.IN_MOVE_SELF { - if watch.recurse { - next() // Do nothing - continue - } - - err := w.remove(watch.path) - if err != nil && !errors.Is(err, ErrNonExistentWatch) { - if !w.sendError(err) { - return - } - } - } - - /// Skip if we're watching both this path and the parent; the parent - /// will already send a delete so no need to do it twice. - if mask&unix.IN_DELETE_SELF != 0 { - if _, ok := w.watches.path[filepath.Dir(watch.path)]; ok { - next() - continue - } - } - - ev := w.newEvent(name, mask, raw.Cookie) - // Need to update watch path for recurse. - if watch.recurse { - isDir := mask&unix.IN_ISDIR == unix.IN_ISDIR - /// New directory created: set up watch on it. - if isDir && ev.Has(Create) { - err := w.register(ev.Name, watch.flags, true) - if !w.sendError(err) { - return - } - - // This was a directory rename, so we need to update all - // the children. - // - // TODO: this is of course pretty slow; we should use a - // better data structure for storing all of this, e.g. store - // children in the watch. I have some code for this in my - // kqueue refactor we can use in the future. For now I'm - // okay with this as it's not publicly available. - // Correctness first, performance second. - if ev.renamedFrom != "" { - w.watches.mu.Lock() - for k, ww := range w.watches.wd { - if k == watch.wd || ww.path == ev.Name { - continue - } - if strings.HasPrefix(ww.path, ev.renamedFrom) { - ww.path = strings.Replace(ww.path, ev.renamedFrom, ev.Name, 1) - w.watches.wd[k] = ww - } - } - w.watches.mu.Unlock() - } - } - } - - /// Send the events that are not ignored on the events channel - if !w.sendEvent(ev) { - return - } - next() - } - } -} - -func (w *inotify) isRecursive(path string) bool { - ww := w.watches.byPath(path) - if ww == nil { // path could be a file, so also check the Dir. - ww = w.watches.byPath(filepath.Dir(path)) - } - return ww != nil && ww.recurse -} - -func (w *inotify) newEvent(name string, mask, cookie uint32) Event { - e := Event{Name: name} - if mask&unix.IN_CREATE == unix.IN_CREATE || mask&unix.IN_MOVED_TO == unix.IN_MOVED_TO { - e.Op |= Create - } - if mask&unix.IN_DELETE_SELF == unix.IN_DELETE_SELF || mask&unix.IN_DELETE == unix.IN_DELETE { - e.Op |= Remove - } - if mask&unix.IN_MODIFY == unix.IN_MODIFY { - e.Op |= Write - } - if mask&unix.IN_OPEN == unix.IN_OPEN { - e.Op |= xUnportableOpen - } - if mask&unix.IN_ACCESS == unix.IN_ACCESS { - e.Op |= xUnportableRead - } - if mask&unix.IN_CLOSE_WRITE == unix.IN_CLOSE_WRITE { - e.Op |= xUnportableCloseWrite - } - if mask&unix.IN_CLOSE_NOWRITE == unix.IN_CLOSE_NOWRITE { - e.Op |= xUnportableCloseRead - } - if mask&unix.IN_MOVE_SELF == unix.IN_MOVE_SELF || mask&unix.IN_MOVED_FROM == unix.IN_MOVED_FROM { - e.Op |= Rename - } - if mask&unix.IN_ATTRIB == unix.IN_ATTRIB { - e.Op |= Chmod - } - - if cookie != 0 { - if mask&unix.IN_MOVED_FROM == unix.IN_MOVED_FROM { - w.cookiesMu.Lock() - w.cookies[w.cookieIndex] = koekje{cookie: cookie, path: e.Name} - w.cookieIndex++ - if w.cookieIndex > 9 { - w.cookieIndex = 0 - } - w.cookiesMu.Unlock() - } else if mask&unix.IN_MOVED_TO == unix.IN_MOVED_TO { - w.cookiesMu.Lock() - var prev string - for _, c := range w.cookies { - if c.cookie == cookie { - prev = c.path - break - } - } - w.cookiesMu.Unlock() - e.renamedFrom = prev - } - } - return e -} - -func (w *inotify) xSupports(op Op) bool { - return true // Supports everything. -} - -func (w *inotify) state() { - w.watches.mu.Lock() - defer w.watches.mu.Unlock() - for wd, ww := range w.watches.wd { - fmt.Fprintf(os.Stderr, "%4d: recurse=%t %q\n", wd, ww.recurse, ww.path) - } -} diff --git a/vendor/github.com/fsnotify/fsnotify/backend_kqueue.go b/vendor/github.com/fsnotify/fsnotify/backend_kqueue.go deleted file mode 100644 index d8de5ab76..000000000 --- a/vendor/github.com/fsnotify/fsnotify/backend_kqueue.go +++ /dev/null @@ -1,733 +0,0 @@ -//go:build freebsd || openbsd || netbsd || dragonfly || darwin - -package fsnotify - -import ( - "errors" - "fmt" - "os" - "path/filepath" - "runtime" - "sync" - "time" - - "github.com/fsnotify/fsnotify/internal" - "golang.org/x/sys/unix" -) - -type kqueue struct { - Events chan Event - Errors chan error - - kq int // File descriptor (as returned by the kqueue() syscall). - closepipe [2]int // Pipe used for closing kq. - watches *watches - done chan struct{} - doneMu sync.Mutex -} - -type ( - watches struct { - mu sync.RWMutex - wd map[int]watch // wd → watch - path map[string]int // pathname → wd - byDir map[string]map[int]struct{} // dirname(path) → wd - seen map[string]struct{} // Keep track of if we know this file exists. - byUser map[string]struct{} // Watches added with Watcher.Add() - } - watch struct { - wd int - name string - linkName string // In case of links; name is the target, and this is the link. - isDir bool - dirFlags uint32 - } -) - -func newWatches() *watches { - return &watches{ - wd: make(map[int]watch), - path: make(map[string]int), - byDir: make(map[string]map[int]struct{}), - seen: make(map[string]struct{}), - byUser: make(map[string]struct{}), - } -} - -func (w *watches) listPaths(userOnly bool) []string { - w.mu.RLock() - defer w.mu.RUnlock() - - if userOnly { - l := make([]string, 0, len(w.byUser)) - for p := range w.byUser { - l = append(l, p) - } - return l - } - - l := make([]string, 0, len(w.path)) - for p := range w.path { - l = append(l, p) - } - return l -} - -func (w *watches) watchesInDir(path string) []string { - w.mu.RLock() - defer w.mu.RUnlock() - - l := make([]string, 0, 4) - for fd := range w.byDir[path] { - info := w.wd[fd] - if _, ok := w.byUser[info.name]; !ok { - l = append(l, info.name) - } - } - return l -} - -// Mark path as added by the user. -func (w *watches) addUserWatch(path string) { - w.mu.Lock() - defer w.mu.Unlock() - w.byUser[path] = struct{}{} -} - -func (w *watches) addLink(path string, fd int) { - w.mu.Lock() - defer w.mu.Unlock() - - w.path[path] = fd - w.seen[path] = struct{}{} -} - -func (w *watches) add(path, linkPath string, fd int, isDir bool) { - w.mu.Lock() - defer w.mu.Unlock() - - w.path[path] = fd - w.wd[fd] = watch{wd: fd, name: path, linkName: linkPath, isDir: isDir} - - parent := filepath.Dir(path) - byDir, ok := w.byDir[parent] - if !ok { - byDir = make(map[int]struct{}, 1) - w.byDir[parent] = byDir - } - byDir[fd] = struct{}{} -} - -func (w *watches) byWd(fd int) (watch, bool) { - w.mu.RLock() - defer w.mu.RUnlock() - info, ok := w.wd[fd] - return info, ok -} - -func (w *watches) byPath(path string) (watch, bool) { - w.mu.RLock() - defer w.mu.RUnlock() - info, ok := w.wd[w.path[path]] - return info, ok -} - -func (w *watches) updateDirFlags(path string, flags uint32) { - w.mu.Lock() - defer w.mu.Unlock() - - fd := w.path[path] - info := w.wd[fd] - info.dirFlags = flags - w.wd[fd] = info -} - -func (w *watches) remove(fd int, path string) bool { - w.mu.Lock() - defer w.mu.Unlock() - - isDir := w.wd[fd].isDir - delete(w.path, path) - delete(w.byUser, path) - - parent := filepath.Dir(path) - delete(w.byDir[parent], fd) - - if len(w.byDir[parent]) == 0 { - delete(w.byDir, parent) - } - - delete(w.wd, fd) - delete(w.seen, path) - return isDir -} - -func (w *watches) markSeen(path string, exists bool) { - w.mu.Lock() - defer w.mu.Unlock() - if exists { - w.seen[path] = struct{}{} - } else { - delete(w.seen, path) - } -} - -func (w *watches) seenBefore(path string) bool { - w.mu.RLock() - defer w.mu.RUnlock() - _, ok := w.seen[path] - return ok -} - -func newBackend(ev chan Event, errs chan error) (backend, error) { - return newBufferedBackend(0, ev, errs) -} - -func newBufferedBackend(sz uint, ev chan Event, errs chan error) (backend, error) { - kq, closepipe, err := newKqueue() - if err != nil { - return nil, err - } - - w := &kqueue{ - Events: ev, - Errors: errs, - kq: kq, - closepipe: closepipe, - done: make(chan struct{}), - watches: newWatches(), - } - - go w.readEvents() - return w, nil -} - -// newKqueue creates a new kernel event queue and returns a descriptor. -// -// This registers a new event on closepipe, which will trigger an event when -// it's closed. This way we can use kevent() without timeout/polling; without -// the closepipe, it would block forever and we wouldn't be able to stop it at -// all. -func newKqueue() (kq int, closepipe [2]int, err error) { - kq, err = unix.Kqueue() - if kq == -1 { - return kq, closepipe, err - } - - // Register the close pipe. - err = unix.Pipe(closepipe[:]) - if err != nil { - unix.Close(kq) - return kq, closepipe, err - } - unix.CloseOnExec(closepipe[0]) - unix.CloseOnExec(closepipe[1]) - - // Register changes to listen on the closepipe. - changes := make([]unix.Kevent_t, 1) - // SetKevent converts int to the platform-specific types. - unix.SetKevent(&changes[0], closepipe[0], unix.EVFILT_READ, - unix.EV_ADD|unix.EV_ENABLE|unix.EV_ONESHOT) - - ok, err := unix.Kevent(kq, changes, nil, nil) - if ok == -1 { - unix.Close(kq) - unix.Close(closepipe[0]) - unix.Close(closepipe[1]) - return kq, closepipe, err - } - return kq, closepipe, nil -} - -// Returns true if the event was sent, or false if watcher is closed. -func (w *kqueue) sendEvent(e Event) bool { - select { - case <-w.done: - return false - case w.Events <- e: - return true - } -} - -// Returns true if the error was sent, or false if watcher is closed. -func (w *kqueue) sendError(err error) bool { - if err == nil { - return true - } - select { - case <-w.done: - return false - case w.Errors <- err: - return true - } -} - -func (w *kqueue) isClosed() bool { - select { - case <-w.done: - return true - default: - return false - } -} - -func (w *kqueue) Close() error { - w.doneMu.Lock() - if w.isClosed() { - w.doneMu.Unlock() - return nil - } - close(w.done) - w.doneMu.Unlock() - - pathsToRemove := w.watches.listPaths(false) - for _, name := range pathsToRemove { - w.Remove(name) - } - - // Send "quit" message to the reader goroutine. - unix.Close(w.closepipe[1]) - return nil -} - -func (w *kqueue) Add(name string) error { return w.AddWith(name) } - -func (w *kqueue) AddWith(name string, opts ...addOpt) error { - if debug { - fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s AddWith(%q)\n", - time.Now().Format("15:04:05.000000000"), name) - } - - with := getOptions(opts...) - if !w.xSupports(with.op) { - return fmt.Errorf("%w: %s", xErrUnsupported, with.op) - } - - _, err := w.addWatch(name, noteAllEvents) - if err != nil { - return err - } - w.watches.addUserWatch(name) - return nil -} - -func (w *kqueue) Remove(name string) error { - if debug { - fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s Remove(%q)\n", - time.Now().Format("15:04:05.000000000"), name) - } - return w.remove(name, true) -} - -func (w *kqueue) remove(name string, unwatchFiles bool) error { - if w.isClosed() { - return nil - } - - name = filepath.Clean(name) - info, ok := w.watches.byPath(name) - if !ok { - return fmt.Errorf("%w: %s", ErrNonExistentWatch, name) - } - - err := w.register([]int{info.wd}, unix.EV_DELETE, 0) - if err != nil { - return err - } - - unix.Close(info.wd) - - isDir := w.watches.remove(info.wd, name) - - // Find all watched paths that are in this directory that are not external. - if unwatchFiles && isDir { - pathsToRemove := w.watches.watchesInDir(name) - for _, name := range pathsToRemove { - // Since these are internal, not much sense in propagating error to - // the user, as that will just confuse them with an error about a - // path they did not explicitly watch themselves. - w.Remove(name) - } - } - return nil -} - -func (w *kqueue) WatchList() []string { - if w.isClosed() { - return nil - } - return w.watches.listPaths(true) -} - -// Watch all events (except NOTE_EXTEND, NOTE_LINK, NOTE_REVOKE) -const noteAllEvents = unix.NOTE_DELETE | unix.NOTE_WRITE | unix.NOTE_ATTRIB | unix.NOTE_RENAME - -// addWatch adds name to the watched file set; the flags are interpreted as -// described in kevent(2). -// -// Returns the real path to the file which was added, with symlinks resolved. -func (w *kqueue) addWatch(name string, flags uint32) (string, error) { - if w.isClosed() { - return "", ErrClosed - } - - name = filepath.Clean(name) - - info, alreadyWatching := w.watches.byPath(name) - if !alreadyWatching { - fi, err := os.Lstat(name) - if err != nil { - return "", err - } - - // Don't watch sockets or named pipes. - if (fi.Mode()&os.ModeSocket == os.ModeSocket) || (fi.Mode()&os.ModeNamedPipe == os.ModeNamedPipe) { - return "", nil - } - - // Follow symlinks. - if fi.Mode()&os.ModeSymlink == os.ModeSymlink { - link, err := os.Readlink(name) - if err != nil { - // Return nil because Linux can add unresolvable symlinks to the - // watch list without problems, so maintain consistency with - // that. There will be no file events for broken symlinks. - // TODO: more specific check; returns os.PathError; ENOENT? - return "", nil - } - - _, alreadyWatching = w.watches.byPath(link) - if alreadyWatching { - // Add to watches so we don't get spurious Create events later - // on when we diff the directories. - w.watches.addLink(name, 0) - return link, nil - } - - info.linkName = name - name = link - fi, err = os.Lstat(name) - if err != nil { - return "", nil - } - } - - // Retry on EINTR; open() can return EINTR in practice on macOS. - // See #354, and Go issues 11180 and 39237. - for { - info.wd, err = unix.Open(name, openMode, 0) - if err == nil { - break - } - if errors.Is(err, unix.EINTR) { - continue - } - - return "", err - } - - info.isDir = fi.IsDir() - } - - err := w.register([]int{info.wd}, unix.EV_ADD|unix.EV_CLEAR|unix.EV_ENABLE, flags) - if err != nil { - unix.Close(info.wd) - return "", err - } - - if !alreadyWatching { - w.watches.add(name, info.linkName, info.wd, info.isDir) - } - - // Watch the directory if it has not been watched before, or if it was - // watched before, but perhaps only a NOTE_DELETE (watchDirectoryFiles) - if info.isDir { - watchDir := (flags&unix.NOTE_WRITE) == unix.NOTE_WRITE && - (!alreadyWatching || (info.dirFlags&unix.NOTE_WRITE) != unix.NOTE_WRITE) - w.watches.updateDirFlags(name, flags) - - if watchDir { - if err := w.watchDirectoryFiles(name); err != nil { - return "", err - } - } - } - return name, nil -} - -// readEvents reads from kqueue and converts the received kevents into -// Event values that it sends down the Events channel. -func (w *kqueue) readEvents() { - defer func() { - close(w.Events) - close(w.Errors) - _ = unix.Close(w.kq) - unix.Close(w.closepipe[0]) - }() - - eventBuffer := make([]unix.Kevent_t, 10) - for { - kevents, err := w.read(eventBuffer) - // EINTR is okay, the syscall was interrupted before timeout expired. - if err != nil && err != unix.EINTR { - if !w.sendError(fmt.Errorf("fsnotify.readEvents: %w", err)) { - return - } - } - - for _, kevent := range kevents { - var ( - wd = int(kevent.Ident) - mask = uint32(kevent.Fflags) - ) - - // Shut down the loop when the pipe is closed, but only after all - // other events have been processed. - if wd == w.closepipe[0] { - return - } - - path, ok := w.watches.byWd(wd) - if debug { - internal.Debug(path.name, &kevent) - } - - // On macOS it seems that sometimes an event with Ident=0 is - // delivered, and no other flags/information beyond that, even - // though we never saw such a file descriptor. For example in - // TestWatchSymlink/277 (usually at the end, but sometimes sooner): - // - // fmt.Printf("READ: %2d %#v\n", kevent.Ident, kevent) - // unix.Kevent_t{Ident:0x2a, Filter:-4, Flags:0x25, Fflags:0x2, Data:0, Udata:(*uint8)(nil)} - // unix.Kevent_t{Ident:0x0, Filter:-4, Flags:0x25, Fflags:0x2, Data:0, Udata:(*uint8)(nil)} - // - // The first is a normal event, the second with Ident 0. No error - // flag, no data, no ... nothing. - // - // I read a bit through bsd/kern_event.c from the xnu source, but I - // don't really see an obvious location where this is triggered – - // this doesn't seem intentional, but idk... - // - // Technically fd 0 is a valid descriptor, so only skip it if - // there's no path, and if we're on macOS. - if !ok && kevent.Ident == 0 && runtime.GOOS == "darwin" { - continue - } - - event := w.newEvent(path.name, path.linkName, mask) - - if event.Has(Rename) || event.Has(Remove) { - w.remove(event.Name, false) - w.watches.markSeen(event.Name, false) - } - - if path.isDir && event.Has(Write) && !event.Has(Remove) { - w.dirChange(event.Name) - } else if !w.sendEvent(event) { - return - } - - if event.Has(Remove) { - // Look for a file that may have overwritten this; for example, - // mv f1 f2 will delete f2, then create f2. - if path.isDir { - fileDir := filepath.Clean(event.Name) - _, found := w.watches.byPath(fileDir) - if found { - // TODO: this branch is never triggered in any test. - // Added in d6220df (2012). - // isDir check added in 8611c35 (2016): https://github.com/fsnotify/fsnotify/pull/111 - // - // I don't really get how this can be triggered either. - // And it wasn't triggered in the patch that added it, - // either. - // - // Original also had a comment: - // make sure the directory exists before we watch for - // changes. When we do a recursive watch and perform - // rm -rf, the parent directory might have gone - // missing, ignore the missing directory and let the - // upcoming delete event remove the watch from the - // parent directory. - err := w.dirChange(fileDir) - if !w.sendError(err) { - return - } - } - } else { - path := filepath.Clean(event.Name) - if fi, err := os.Lstat(path); err == nil { - err := w.sendCreateIfNew(path, fi) - if !w.sendError(err) { - return - } - } - } - } - } - } -} - -// newEvent returns an platform-independent Event based on kqueue Fflags. -func (w *kqueue) newEvent(name, linkName string, mask uint32) Event { - e := Event{Name: name} - if linkName != "" { - // If the user watched "/path/link" then emit events as "/path/link" - // rather than "/path/target". - e.Name = linkName - } - - if mask&unix.NOTE_DELETE == unix.NOTE_DELETE { - e.Op |= Remove - } - if mask&unix.NOTE_WRITE == unix.NOTE_WRITE { - e.Op |= Write - } - if mask&unix.NOTE_RENAME == unix.NOTE_RENAME { - e.Op |= Rename - } - if mask&unix.NOTE_ATTRIB == unix.NOTE_ATTRIB { - e.Op |= Chmod - } - // No point sending a write and delete event at the same time: if it's gone, - // then it's gone. - if e.Op.Has(Write) && e.Op.Has(Remove) { - e.Op &^= Write - } - return e -} - -// watchDirectoryFiles to mimic inotify when adding a watch on a directory -func (w *kqueue) watchDirectoryFiles(dirPath string) error { - files, err := os.ReadDir(dirPath) - if err != nil { - return err - } - - for _, f := range files { - path := filepath.Join(dirPath, f.Name()) - - fi, err := f.Info() - if err != nil { - return fmt.Errorf("%q: %w", path, err) - } - - cleanPath, err := w.internalWatch(path, fi) - if err != nil { - // No permission to read the file; that's not a problem: just skip. - // But do add it to w.fileExists to prevent it from being picked up - // as a "new" file later (it still shows up in the directory - // listing). - switch { - case errors.Is(err, unix.EACCES) || errors.Is(err, unix.EPERM): - cleanPath = filepath.Clean(path) - default: - return fmt.Errorf("%q: %w", path, err) - } - } - - w.watches.markSeen(cleanPath, true) - } - - return nil -} - -// Search the directory for new files and send an event for them. -// -// This functionality is to have the BSD watcher match the inotify, which sends -// a create event for files created in a watched directory. -func (w *kqueue) dirChange(dir string) error { - files, err := os.ReadDir(dir) - if err != nil { - // Directory no longer exists: we can ignore this safely. kqueue will - // still give us the correct events. - if errors.Is(err, os.ErrNotExist) { - return nil - } - return fmt.Errorf("fsnotify.dirChange: %w", err) - } - - for _, f := range files { - fi, err := f.Info() - if err != nil { - return fmt.Errorf("fsnotify.dirChange: %w", err) - } - - err = w.sendCreateIfNew(filepath.Join(dir, fi.Name()), fi) - if err != nil { - // Don't need to send an error if this file isn't readable. - if errors.Is(err, unix.EACCES) || errors.Is(err, unix.EPERM) { - return nil - } - return fmt.Errorf("fsnotify.dirChange: %w", err) - } - } - return nil -} - -// Send a create event if the file isn't already being tracked, and start -// watching this file. -func (w *kqueue) sendCreateIfNew(path string, fi os.FileInfo) error { - if !w.watches.seenBefore(path) { - if !w.sendEvent(Event{Name: path, Op: Create}) { - return nil - } - } - - // Like watchDirectoryFiles, but without doing another ReadDir. - path, err := w.internalWatch(path, fi) - if err != nil { - return err - } - w.watches.markSeen(path, true) - return nil -} - -func (w *kqueue) internalWatch(name string, fi os.FileInfo) (string, error) { - if fi.IsDir() { - // mimic Linux providing delete events for subdirectories, but preserve - // the flags used if currently watching subdirectory - info, _ := w.watches.byPath(name) - return w.addWatch(name, info.dirFlags|unix.NOTE_DELETE|unix.NOTE_RENAME) - } - - // watch file to mimic Linux inotify - return w.addWatch(name, noteAllEvents) -} - -// Register events with the queue. -func (w *kqueue) register(fds []int, flags int, fflags uint32) error { - changes := make([]unix.Kevent_t, len(fds)) - for i, fd := range fds { - // SetKevent converts int to the platform-specific types. - unix.SetKevent(&changes[i], fd, unix.EVFILT_VNODE, flags) - changes[i].Fflags = fflags - } - - // Register the events. - success, err := unix.Kevent(w.kq, changes, nil, nil) - if success == -1 { - return err - } - return nil -} - -// read retrieves pending events, or waits until an event occurs. -func (w *kqueue) read(events []unix.Kevent_t) ([]unix.Kevent_t, error) { - n, err := unix.Kevent(w.kq, nil, events, nil) - if err != nil { - return nil, err - } - return events[0:n], nil -} - -func (w *kqueue) xSupports(op Op) bool { - if runtime.GOOS == "freebsd" { - //return true // Supports everything. - } - if op.Has(xUnportableOpen) || op.Has(xUnportableRead) || - op.Has(xUnportableCloseWrite) || op.Has(xUnportableCloseRead) { - return false - } - return true -} diff --git a/vendor/github.com/fsnotify/fsnotify/backend_other.go b/vendor/github.com/fsnotify/fsnotify/backend_other.go deleted file mode 100644 index 5eb5dbc66..000000000 --- a/vendor/github.com/fsnotify/fsnotify/backend_other.go +++ /dev/null @@ -1,23 +0,0 @@ -//go:build appengine || (!darwin && !dragonfly && !freebsd && !openbsd && !linux && !netbsd && !solaris && !windows) - -package fsnotify - -import "errors" - -type other struct { - Events chan Event - Errors chan error -} - -func newBackend(ev chan Event, errs chan error) (backend, error) { - return nil, errors.New("fsnotify not supported on the current platform") -} -func newBufferedBackend(sz uint, ev chan Event, errs chan error) (backend, error) { - return newBackend(ev, errs) -} -func (w *other) Close() error { return nil } -func (w *other) WatchList() []string { return nil } -func (w *other) Add(name string) error { return nil } -func (w *other) AddWith(name string, opts ...addOpt) error { return nil } -func (w *other) Remove(name string) error { return nil } -func (w *other) xSupports(op Op) bool { return false } diff --git a/vendor/github.com/fsnotify/fsnotify/backend_windows.go b/vendor/github.com/fsnotify/fsnotify/backend_windows.go deleted file mode 100644 index c54a63083..000000000 --- a/vendor/github.com/fsnotify/fsnotify/backend_windows.go +++ /dev/null @@ -1,682 +0,0 @@ -//go:build windows - -// Windows backend based on ReadDirectoryChangesW() -// -// https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-readdirectorychangesw - -package fsnotify - -import ( - "errors" - "fmt" - "os" - "path/filepath" - "reflect" - "runtime" - "strings" - "sync" - "time" - "unsafe" - - "github.com/fsnotify/fsnotify/internal" - "golang.org/x/sys/windows" -) - -type readDirChangesW struct { - Events chan Event - Errors chan error - - port windows.Handle // Handle to completion port - input chan *input // Inputs to the reader are sent on this channel - quit chan chan<- error - - mu sync.Mutex // Protects access to watches, closed - watches watchMap // Map of watches (key: i-number) - closed bool // Set to true when Close() is first called -} - -func newBackend(ev chan Event, errs chan error) (backend, error) { - return newBufferedBackend(50, ev, errs) -} - -func newBufferedBackend(sz uint, ev chan Event, errs chan error) (backend, error) { - port, err := windows.CreateIoCompletionPort(windows.InvalidHandle, 0, 0, 0) - if err != nil { - return nil, os.NewSyscallError("CreateIoCompletionPort", err) - } - w := &readDirChangesW{ - Events: ev, - Errors: errs, - port: port, - watches: make(watchMap), - input: make(chan *input, 1), - quit: make(chan chan<- error, 1), - } - go w.readEvents() - return w, nil -} - -func (w *readDirChangesW) isClosed() bool { - w.mu.Lock() - defer w.mu.Unlock() - return w.closed -} - -func (w *readDirChangesW) sendEvent(name, renamedFrom string, mask uint64) bool { - if mask == 0 { - return false - } - - event := w.newEvent(name, uint32(mask)) - event.renamedFrom = renamedFrom - select { - case ch := <-w.quit: - w.quit <- ch - case w.Events <- event: - } - return true -} - -// Returns true if the error was sent, or false if watcher is closed. -func (w *readDirChangesW) sendError(err error) bool { - if err == nil { - return true - } - select { - case w.Errors <- err: - return true - case <-w.quit: - return false - } -} - -func (w *readDirChangesW) Close() error { - if w.isClosed() { - return nil - } - - w.mu.Lock() - w.closed = true - w.mu.Unlock() - - // Send "quit" message to the reader goroutine - ch := make(chan error) - w.quit <- ch - if err := w.wakeupReader(); err != nil { - return err - } - return <-ch -} - -func (w *readDirChangesW) Add(name string) error { return w.AddWith(name) } - -func (w *readDirChangesW) AddWith(name string, opts ...addOpt) error { - if w.isClosed() { - return ErrClosed - } - if debug { - fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s AddWith(%q)\n", - time.Now().Format("15:04:05.000000000"), filepath.ToSlash(name)) - } - - with := getOptions(opts...) - if !w.xSupports(with.op) { - return fmt.Errorf("%w: %s", xErrUnsupported, with.op) - } - if with.bufsize < 4096 { - return fmt.Errorf("fsnotify.WithBufferSize: buffer size cannot be smaller than 4096 bytes") - } - - in := &input{ - op: opAddWatch, - path: filepath.Clean(name), - flags: sysFSALLEVENTS, - reply: make(chan error), - bufsize: with.bufsize, - } - w.input <- in - if err := w.wakeupReader(); err != nil { - return err - } - return <-in.reply -} - -func (w *readDirChangesW) Remove(name string) error { - if w.isClosed() { - return nil - } - if debug { - fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s Remove(%q)\n", - time.Now().Format("15:04:05.000000000"), filepath.ToSlash(name)) - } - - in := &input{ - op: opRemoveWatch, - path: filepath.Clean(name), - reply: make(chan error), - } - w.input <- in - if err := w.wakeupReader(); err != nil { - return err - } - return <-in.reply -} - -func (w *readDirChangesW) WatchList() []string { - if w.isClosed() { - return nil - } - - w.mu.Lock() - defer w.mu.Unlock() - - entries := make([]string, 0, len(w.watches)) - for _, entry := range w.watches { - for _, watchEntry := range entry { - for name := range watchEntry.names { - entries = append(entries, filepath.Join(watchEntry.path, name)) - } - // the directory itself is being watched - if watchEntry.mask != 0 { - entries = append(entries, watchEntry.path) - } - } - } - - return entries -} - -// These options are from the old golang.org/x/exp/winfsnotify, where you could -// add various options to the watch. This has long since been removed. -// -// The "sys" in the name is misleading as they're not part of any "system". -// -// This should all be removed at some point, and just use windows.FILE_NOTIFY_* -const ( - sysFSALLEVENTS = 0xfff - sysFSCREATE = 0x100 - sysFSDELETE = 0x200 - sysFSDELETESELF = 0x400 - sysFSMODIFY = 0x2 - sysFSMOVE = 0xc0 - sysFSMOVEDFROM = 0x40 - sysFSMOVEDTO = 0x80 - sysFSMOVESELF = 0x800 - sysFSIGNORED = 0x8000 -) - -func (w *readDirChangesW) newEvent(name string, mask uint32) Event { - e := Event{Name: name} - if mask&sysFSCREATE == sysFSCREATE || mask&sysFSMOVEDTO == sysFSMOVEDTO { - e.Op |= Create - } - if mask&sysFSDELETE == sysFSDELETE || mask&sysFSDELETESELF == sysFSDELETESELF { - e.Op |= Remove - } - if mask&sysFSMODIFY == sysFSMODIFY { - e.Op |= Write - } - if mask&sysFSMOVE == sysFSMOVE || mask&sysFSMOVESELF == sysFSMOVESELF || mask&sysFSMOVEDFROM == sysFSMOVEDFROM { - e.Op |= Rename - } - return e -} - -const ( - opAddWatch = iota - opRemoveWatch -) - -const ( - provisional uint64 = 1 << (32 + iota) -) - -type input struct { - op int - path string - flags uint32 - bufsize int - reply chan error -} - -type inode struct { - handle windows.Handle - volume uint32 - index uint64 -} - -type watch struct { - ov windows.Overlapped - ino *inode // i-number - recurse bool // Recursive watch? - path string // Directory path - mask uint64 // Directory itself is being watched with these notify flags - names map[string]uint64 // Map of names being watched and their notify flags - rename string // Remembers the old name while renaming a file - buf []byte // buffer, allocated later -} - -type ( - indexMap map[uint64]*watch - watchMap map[uint32]indexMap -) - -func (w *readDirChangesW) wakeupReader() error { - err := windows.PostQueuedCompletionStatus(w.port, 0, 0, nil) - if err != nil { - return os.NewSyscallError("PostQueuedCompletionStatus", err) - } - return nil -} - -func (w *readDirChangesW) getDir(pathname string) (dir string, err error) { - attr, err := windows.GetFileAttributes(windows.StringToUTF16Ptr(pathname)) - if err != nil { - return "", os.NewSyscallError("GetFileAttributes", err) - } - if attr&windows.FILE_ATTRIBUTE_DIRECTORY != 0 { - dir = pathname - } else { - dir, _ = filepath.Split(pathname) - dir = filepath.Clean(dir) - } - return -} - -func (w *readDirChangesW) getIno(path string) (ino *inode, err error) { - h, err := windows.CreateFile(windows.StringToUTF16Ptr(path), - windows.FILE_LIST_DIRECTORY, - windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE, - nil, windows.OPEN_EXISTING, - windows.FILE_FLAG_BACKUP_SEMANTICS|windows.FILE_FLAG_OVERLAPPED, 0) - if err != nil { - return nil, os.NewSyscallError("CreateFile", err) - } - - var fi windows.ByHandleFileInformation - err = windows.GetFileInformationByHandle(h, &fi) - if err != nil { - windows.CloseHandle(h) - return nil, os.NewSyscallError("GetFileInformationByHandle", err) - } - ino = &inode{ - handle: h, - volume: fi.VolumeSerialNumber, - index: uint64(fi.FileIndexHigh)<<32 | uint64(fi.FileIndexLow), - } - return ino, nil -} - -// Must run within the I/O thread. -func (m watchMap) get(ino *inode) *watch { - if i := m[ino.volume]; i != nil { - return i[ino.index] - } - return nil -} - -// Must run within the I/O thread. -func (m watchMap) set(ino *inode, watch *watch) { - i := m[ino.volume] - if i == nil { - i = make(indexMap) - m[ino.volume] = i - } - i[ino.index] = watch -} - -// Must run within the I/O thread. -func (w *readDirChangesW) addWatch(pathname string, flags uint64, bufsize int) error { - pathname, recurse := recursivePath(pathname) - - dir, err := w.getDir(pathname) - if err != nil { - return err - } - - ino, err := w.getIno(dir) - if err != nil { - return err - } - w.mu.Lock() - watchEntry := w.watches.get(ino) - w.mu.Unlock() - if watchEntry == nil { - _, err := windows.CreateIoCompletionPort(ino.handle, w.port, 0, 0) - if err != nil { - windows.CloseHandle(ino.handle) - return os.NewSyscallError("CreateIoCompletionPort", err) - } - watchEntry = &watch{ - ino: ino, - path: dir, - names: make(map[string]uint64), - recurse: recurse, - buf: make([]byte, bufsize), - } - w.mu.Lock() - w.watches.set(ino, watchEntry) - w.mu.Unlock() - flags |= provisional - } else { - windows.CloseHandle(ino.handle) - } - if pathname == dir { - watchEntry.mask |= flags - } else { - watchEntry.names[filepath.Base(pathname)] |= flags - } - - err = w.startRead(watchEntry) - if err != nil { - return err - } - - if pathname == dir { - watchEntry.mask &= ^provisional - } else { - watchEntry.names[filepath.Base(pathname)] &= ^provisional - } - return nil -} - -// Must run within the I/O thread. -func (w *readDirChangesW) remWatch(pathname string) error { - pathname, recurse := recursivePath(pathname) - - dir, err := w.getDir(pathname) - if err != nil { - return err - } - ino, err := w.getIno(dir) - if err != nil { - return err - } - - w.mu.Lock() - watch := w.watches.get(ino) - w.mu.Unlock() - - if recurse && !watch.recurse { - return fmt.Errorf("can't use \\... with non-recursive watch %q", pathname) - } - - err = windows.CloseHandle(ino.handle) - if err != nil { - w.sendError(os.NewSyscallError("CloseHandle", err)) - } - if watch == nil { - return fmt.Errorf("%w: %s", ErrNonExistentWatch, pathname) - } - if pathname == dir { - w.sendEvent(watch.path, "", watch.mask&sysFSIGNORED) - watch.mask = 0 - } else { - name := filepath.Base(pathname) - w.sendEvent(filepath.Join(watch.path, name), "", watch.names[name]&sysFSIGNORED) - delete(watch.names, name) - } - - return w.startRead(watch) -} - -// Must run within the I/O thread. -func (w *readDirChangesW) deleteWatch(watch *watch) { - for name, mask := range watch.names { - if mask&provisional == 0 { - w.sendEvent(filepath.Join(watch.path, name), "", mask&sysFSIGNORED) - } - delete(watch.names, name) - } - if watch.mask != 0 { - if watch.mask&provisional == 0 { - w.sendEvent(watch.path, "", watch.mask&sysFSIGNORED) - } - watch.mask = 0 - } -} - -// Must run within the I/O thread. -func (w *readDirChangesW) startRead(watch *watch) error { - err := windows.CancelIo(watch.ino.handle) - if err != nil { - w.sendError(os.NewSyscallError("CancelIo", err)) - w.deleteWatch(watch) - } - mask := w.toWindowsFlags(watch.mask) - for _, m := range watch.names { - mask |= w.toWindowsFlags(m) - } - if mask == 0 { - err := windows.CloseHandle(watch.ino.handle) - if err != nil { - w.sendError(os.NewSyscallError("CloseHandle", err)) - } - w.mu.Lock() - delete(w.watches[watch.ino.volume], watch.ino.index) - w.mu.Unlock() - return nil - } - - // We need to pass the array, rather than the slice. - hdr := (*reflect.SliceHeader)(unsafe.Pointer(&watch.buf)) - rdErr := windows.ReadDirectoryChanges(watch.ino.handle, - (*byte)(unsafe.Pointer(hdr.Data)), uint32(hdr.Len), - watch.recurse, mask, nil, &watch.ov, 0) - if rdErr != nil { - err := os.NewSyscallError("ReadDirectoryChanges", rdErr) - if rdErr == windows.ERROR_ACCESS_DENIED && watch.mask&provisional == 0 { - // Watched directory was probably removed - w.sendEvent(watch.path, "", watch.mask&sysFSDELETESELF) - err = nil - } - w.deleteWatch(watch) - w.startRead(watch) - return err - } - return nil -} - -// readEvents reads from the I/O completion port, converts the -// received events into Event objects and sends them via the Events channel. -// Entry point to the I/O thread. -func (w *readDirChangesW) readEvents() { - var ( - n uint32 - key uintptr - ov *windows.Overlapped - ) - runtime.LockOSThread() - - for { - // This error is handled after the watch == nil check below. - qErr := windows.GetQueuedCompletionStatus(w.port, &n, &key, &ov, windows.INFINITE) - - watch := (*watch)(unsafe.Pointer(ov)) - if watch == nil { - select { - case ch := <-w.quit: - w.mu.Lock() - var indexes []indexMap - for _, index := range w.watches { - indexes = append(indexes, index) - } - w.mu.Unlock() - for _, index := range indexes { - for _, watch := range index { - w.deleteWatch(watch) - w.startRead(watch) - } - } - - err := windows.CloseHandle(w.port) - if err != nil { - err = os.NewSyscallError("CloseHandle", err) - } - close(w.Events) - close(w.Errors) - ch <- err - return - case in := <-w.input: - switch in.op { - case opAddWatch: - in.reply <- w.addWatch(in.path, uint64(in.flags), in.bufsize) - case opRemoveWatch: - in.reply <- w.remWatch(in.path) - } - default: - } - continue - } - - switch qErr { - case nil: - // No error - case windows.ERROR_MORE_DATA: - if watch == nil { - w.sendError(errors.New("ERROR_MORE_DATA has unexpectedly null lpOverlapped buffer")) - } else { - // The i/o succeeded but the buffer is full. - // In theory we should be building up a full packet. - // In practice we can get away with just carrying on. - n = uint32(unsafe.Sizeof(watch.buf)) - } - case windows.ERROR_ACCESS_DENIED: - // Watched directory was probably removed - w.sendEvent(watch.path, "", watch.mask&sysFSDELETESELF) - w.deleteWatch(watch) - w.startRead(watch) - continue - case windows.ERROR_OPERATION_ABORTED: - // CancelIo was called on this handle - continue - default: - w.sendError(os.NewSyscallError("GetQueuedCompletionPort", qErr)) - continue - } - - var offset uint32 - for { - if n == 0 { - w.sendError(ErrEventOverflow) - break - } - - // Point "raw" to the event in the buffer - raw := (*windows.FileNotifyInformation)(unsafe.Pointer(&watch.buf[offset])) - - // Create a buf that is the size of the path name - size := int(raw.FileNameLength / 2) - var buf []uint16 - // TODO: Use unsafe.Slice in Go 1.17; https://stackoverflow.com/questions/51187973 - sh := (*reflect.SliceHeader)(unsafe.Pointer(&buf)) - sh.Data = uintptr(unsafe.Pointer(&raw.FileName)) - sh.Len = size - sh.Cap = size - name := windows.UTF16ToString(buf) - fullname := filepath.Join(watch.path, name) - - if debug { - internal.Debug(fullname, raw.Action) - } - - var mask uint64 - switch raw.Action { - case windows.FILE_ACTION_REMOVED: - mask = sysFSDELETESELF - case windows.FILE_ACTION_MODIFIED: - mask = sysFSMODIFY - case windows.FILE_ACTION_RENAMED_OLD_NAME: - watch.rename = name - case windows.FILE_ACTION_RENAMED_NEW_NAME: - // Update saved path of all sub-watches. - old := filepath.Join(watch.path, watch.rename) - w.mu.Lock() - for _, watchMap := range w.watches { - for _, ww := range watchMap { - if strings.HasPrefix(ww.path, old) { - ww.path = filepath.Join(fullname, strings.TrimPrefix(ww.path, old)) - } - } - } - w.mu.Unlock() - - if watch.names[watch.rename] != 0 { - watch.names[name] |= watch.names[watch.rename] - delete(watch.names, watch.rename) - mask = sysFSMOVESELF - } - } - - if raw.Action != windows.FILE_ACTION_RENAMED_NEW_NAME { - w.sendEvent(fullname, "", watch.names[name]&mask) - } - if raw.Action == windows.FILE_ACTION_REMOVED { - w.sendEvent(fullname, "", watch.names[name]&sysFSIGNORED) - delete(watch.names, name) - } - - if watch.rename != "" && raw.Action == windows.FILE_ACTION_RENAMED_NEW_NAME { - w.sendEvent(fullname, filepath.Join(watch.path, watch.rename), watch.mask&w.toFSnotifyFlags(raw.Action)) - } else { - w.sendEvent(fullname, "", watch.mask&w.toFSnotifyFlags(raw.Action)) - } - - if raw.Action == windows.FILE_ACTION_RENAMED_NEW_NAME { - w.sendEvent(filepath.Join(watch.path, watch.rename), "", watch.names[name]&mask) - } - - // Move to the next event in the buffer - if raw.NextEntryOffset == 0 { - break - } - offset += raw.NextEntryOffset - - // Error! - if offset >= n { - //lint:ignore ST1005 Windows should be capitalized - w.sendError(errors.New("Windows system assumed buffer larger than it is, events have likely been missed")) - break - } - } - - if err := w.startRead(watch); err != nil { - w.sendError(err) - } - } -} - -func (w *readDirChangesW) toWindowsFlags(mask uint64) uint32 { - var m uint32 - if mask&sysFSMODIFY != 0 { - m |= windows.FILE_NOTIFY_CHANGE_LAST_WRITE - } - if mask&(sysFSMOVE|sysFSCREATE|sysFSDELETE) != 0 { - m |= windows.FILE_NOTIFY_CHANGE_FILE_NAME | windows.FILE_NOTIFY_CHANGE_DIR_NAME - } - return m -} - -func (w *readDirChangesW) toFSnotifyFlags(action uint32) uint64 { - switch action { - case windows.FILE_ACTION_ADDED: - return sysFSCREATE - case windows.FILE_ACTION_REMOVED: - return sysFSDELETE - case windows.FILE_ACTION_MODIFIED: - return sysFSMODIFY - case windows.FILE_ACTION_RENAMED_OLD_NAME: - return sysFSMOVEDFROM - case windows.FILE_ACTION_RENAMED_NEW_NAME: - return sysFSMOVEDTO - } - return 0 -} - -func (w *readDirChangesW) xSupports(op Op) bool { - if op.Has(xUnportableOpen) || op.Has(xUnportableRead) || - op.Has(xUnportableCloseWrite) || op.Has(xUnportableCloseRead) { - return false - } - return true -} diff --git a/vendor/github.com/fsnotify/fsnotify/fsnotify.go b/vendor/github.com/fsnotify/fsnotify/fsnotify.go deleted file mode 100644 index 0760efe91..000000000 --- a/vendor/github.com/fsnotify/fsnotify/fsnotify.go +++ /dev/null @@ -1,494 +0,0 @@ -// Package fsnotify provides a cross-platform interface for file system -// notifications. -// -// Currently supported systems: -// -// - Linux via inotify -// - BSD, macOS via kqueue -// - Windows via ReadDirectoryChangesW -// - illumos via FEN -// -// # FSNOTIFY_DEBUG -// -// Set the FSNOTIFY_DEBUG environment variable to "1" to print debug messages to -// stderr. This can be useful to track down some problems, especially in cases -// where fsnotify is used as an indirect dependency. -// -// Every event will be printed as soon as there's something useful to print, -// with as little processing from fsnotify. -// -// Example output: -// -// FSNOTIFY_DEBUG: 11:34:23.633087586 256:IN_CREATE → "/tmp/file-1" -// FSNOTIFY_DEBUG: 11:34:23.633202319 4:IN_ATTRIB → "/tmp/file-1" -// FSNOTIFY_DEBUG: 11:34:28.989728764 512:IN_DELETE → "/tmp/file-1" -package fsnotify - -import ( - "errors" - "fmt" - "os" - "path/filepath" - "strings" -) - -// Watcher watches a set of paths, delivering events on a channel. -// -// A watcher should not be copied (e.g. pass it by pointer, rather than by -// value). -// -// # Linux notes -// -// When a file is removed a Remove event won't be emitted until all file -// descriptors are closed, and deletes will always emit a Chmod. For example: -// -// fp := os.Open("file") -// os.Remove("file") // Triggers Chmod -// fp.Close() // Triggers Remove -// -// This is the event that inotify sends, so not much can be changed about this. -// -// The fs.inotify.max_user_watches sysctl variable specifies the upper limit -// for the number of watches per user, and fs.inotify.max_user_instances -// specifies the maximum number of inotify instances per user. Every Watcher you -// create is an "instance", and every path you add is a "watch". -// -// These are also exposed in /proc as /proc/sys/fs/inotify/max_user_watches and -// /proc/sys/fs/inotify/max_user_instances -// -// To increase them you can use sysctl or write the value to the /proc file: -// -// # Default values on Linux 5.18 -// sysctl fs.inotify.max_user_watches=124983 -// sysctl fs.inotify.max_user_instances=128 -// -// To make the changes persist on reboot edit /etc/sysctl.conf or -// /usr/lib/sysctl.d/50-default.conf (details differ per Linux distro; check -// your distro's documentation): -// -// fs.inotify.max_user_watches=124983 -// fs.inotify.max_user_instances=128 -// -// Reaching the limit will result in a "no space left on device" or "too many open -// files" error. -// -// # kqueue notes (macOS, BSD) -// -// kqueue requires opening a file descriptor for every file that's being watched; -// so if you're watching a directory with five files then that's six file -// descriptors. You will run in to your system's "max open files" limit faster on -// these platforms. -// -// The sysctl variables kern.maxfiles and kern.maxfilesperproc can be used to -// control the maximum number of open files, as well as /etc/login.conf on BSD -// systems. -// -// # Windows notes -// -// Paths can be added as "C:\\path\\to\\dir", but forward slashes -// ("C:/path/to/dir") will also work. -// -// When a watched directory is removed it will always send an event for the -// directory itself, but may not send events for all files in that directory. -// Sometimes it will send events for all files, sometimes it will send no -// events, and often only for some files. -// -// The default ReadDirectoryChangesW() buffer size is 64K, which is the largest -// value that is guaranteed to work with SMB filesystems. If you have many -// events in quick succession this may not be enough, and you will have to use -// [WithBufferSize] to increase the value. -type Watcher struct { - b backend - - // Events sends the filesystem change events. - // - // fsnotify can send the following events; a "path" here can refer to a - // file, directory, symbolic link, or special file like a FIFO. - // - // fsnotify.Create A new path was created; this may be followed by one - // or more Write events if data also gets written to a - // file. - // - // fsnotify.Remove A path was removed. - // - // fsnotify.Rename A path was renamed. A rename is always sent with the - // old path as Event.Name, and a Create event will be - // sent with the new name. Renames are only sent for - // paths that are currently watched; e.g. moving an - // unmonitored file into a monitored directory will - // show up as just a Create. Similarly, renaming a file - // to outside a monitored directory will show up as - // only a Rename. - // - // fsnotify.Write A file or named pipe was written to. A Truncate will - // also trigger a Write. A single "write action" - // initiated by the user may show up as one or multiple - // writes, depending on when the system syncs things to - // disk. For example when compiling a large Go program - // you may get hundreds of Write events, and you may - // want to wait until you've stopped receiving them - // (see the dedup example in cmd/fsnotify). - // - // Some systems may send Write event for directories - // when the directory content changes. - // - // fsnotify.Chmod Attributes were changed. On Linux this is also sent - // when a file is removed (or more accurately, when a - // link to an inode is removed). On kqueue it's sent - // when a file is truncated. On Windows it's never - // sent. - Events chan Event - - // Errors sends any errors. - Errors chan error -} - -// Event represents a file system notification. -type Event struct { - // Path to the file or directory. - // - // Paths are relative to the input; for example with Add("dir") the Name - // will be set to "dir/file" if you create that file, but if you use - // Add("/path/to/dir") it will be "/path/to/dir/file". - Name string - - // File operation that triggered the event. - // - // This is a bitmask and some systems may send multiple operations at once. - // Use the Event.Has() method instead of comparing with ==. - Op Op - - // Create events will have this set to the old path if it's a rename. This - // only works when both the source and destination are watched. It's not - // reliable when watching individual files, only directories. - // - // For example "mv /tmp/file /tmp/rename" will emit: - // - // Event{Op: Rename, Name: "/tmp/file"} - // Event{Op: Create, Name: "/tmp/rename", RenamedFrom: "/tmp/file"} - renamedFrom string -} - -// Op describes a set of file operations. -type Op uint32 - -// The operations fsnotify can trigger; see the documentation on [Watcher] for a -// full description, and check them with [Event.Has]. -const ( - // A new pathname was created. - Create Op = 1 << iota - - // The pathname was written to; this does *not* mean the write has finished, - // and a write can be followed by more writes. - Write - - // The path was removed; any watches on it will be removed. Some "remove" - // operations may trigger a Rename if the file is actually moved (for - // example "remove to trash" is often a rename). - Remove - - // The path was renamed to something else; any watches on it will be - // removed. - Rename - - // File attributes were changed. - // - // It's generally not recommended to take action on this event, as it may - // get triggered very frequently by some software. For example, Spotlight - // indexing on macOS, anti-virus software, backup software, etc. - Chmod - - // File descriptor was opened. - // - // Only works on Linux and FreeBSD. - xUnportableOpen - - // File was read from. - // - // Only works on Linux and FreeBSD. - xUnportableRead - - // File opened for writing was closed. - // - // Only works on Linux and FreeBSD. - // - // The advantage of using this over Write is that it's more reliable than - // waiting for Write events to stop. It's also faster (if you're not - // listening to Write events): copying a file of a few GB can easily - // generate tens of thousands of Write events in a short span of time. - xUnportableCloseWrite - - // File opened for reading was closed. - // - // Only works on Linux and FreeBSD. - xUnportableCloseRead -) - -var ( - // ErrNonExistentWatch is used when Remove() is called on a path that's not - // added. - ErrNonExistentWatch = errors.New("fsnotify: can't remove non-existent watch") - - // ErrClosed is used when trying to operate on a closed Watcher. - ErrClosed = errors.New("fsnotify: watcher already closed") - - // ErrEventOverflow is reported from the Errors channel when there are too - // many events: - // - // - inotify: inotify returns IN_Q_OVERFLOW – because there are too - // many queued events (the fs.inotify.max_queued_events - // sysctl can be used to increase this). - // - windows: The buffer size is too small; WithBufferSize() can be used to increase it. - // - kqueue, fen: Not used. - ErrEventOverflow = errors.New("fsnotify: queue or buffer overflow") - - // ErrUnsupported is returned by AddWith() when WithOps() specified an - // Unportable event that's not supported on this platform. - xErrUnsupported = errors.New("fsnotify: not supported with this backend") -) - -// NewWatcher creates a new Watcher. -func NewWatcher() (*Watcher, error) { - ev, errs := make(chan Event), make(chan error) - b, err := newBackend(ev, errs) - if err != nil { - return nil, err - } - return &Watcher{b: b, Events: ev, Errors: errs}, nil -} - -// NewBufferedWatcher creates a new Watcher with a buffered Watcher.Events -// channel. -// -// The main use case for this is situations with a very large number of events -// where the kernel buffer size can't be increased (e.g. due to lack of -// permissions). An unbuffered Watcher will perform better for almost all use -// cases, and whenever possible you will be better off increasing the kernel -// buffers instead of adding a large userspace buffer. -func NewBufferedWatcher(sz uint) (*Watcher, error) { - ev, errs := make(chan Event), make(chan error) - b, err := newBufferedBackend(sz, ev, errs) - if err != nil { - return nil, err - } - return &Watcher{b: b, Events: ev, Errors: errs}, nil -} - -// Add starts monitoring the path for changes. -// -// A path can only be watched once; watching it more than once is a no-op and will -// not return an error. Paths that do not yet exist on the filesystem cannot be -// watched. -// -// A watch will be automatically removed if the watched path is deleted or -// renamed. The exception is the Windows backend, which doesn't remove the -// watcher on renames. -// -// Notifications on network filesystems (NFS, SMB, FUSE, etc.) or special -// filesystems (/proc, /sys, etc.) generally don't work. -// -// Returns [ErrClosed] if [Watcher.Close] was called. -// -// See [Watcher.AddWith] for a version that allows adding options. -// -// # Watching directories -// -// All files in a directory are monitored, including new files that are created -// after the watcher is started. Subdirectories are not watched (i.e. it's -// non-recursive). -// -// # Watching files -// -// Watching individual files (rather than directories) is generally not -// recommended as many programs (especially editors) update files atomically: it -// will write to a temporary file which is then moved to destination, -// overwriting the original (or some variant thereof). The watcher on the -// original file is now lost, as that no longer exists. -// -// The upshot of this is that a power failure or crash won't leave a -// half-written file. -// -// Watch the parent directory and use Event.Name to filter out files you're not -// interested in. There is an example of this in cmd/fsnotify/file.go. -func (w *Watcher) Add(path string) error { return w.b.Add(path) } - -// AddWith is like [Watcher.Add], but allows adding options. When using Add() -// the defaults described below are used. -// -// Possible options are: -// -// - [WithBufferSize] sets the buffer size for the Windows backend; no-op on -// other platforms. The default is 64K (65536 bytes). -func (w *Watcher) AddWith(path string, opts ...addOpt) error { return w.b.AddWith(path, opts...) } - -// Remove stops monitoring the path for changes. -// -// Directories are always removed non-recursively. For example, if you added -// /tmp/dir and /tmp/dir/subdir then you will need to remove both. -// -// Removing a path that has not yet been added returns [ErrNonExistentWatch]. -// -// Returns nil if [Watcher.Close] was called. -func (w *Watcher) Remove(path string) error { return w.b.Remove(path) } - -// Close removes all watches and closes the Events channel. -func (w *Watcher) Close() error { return w.b.Close() } - -// WatchList returns all paths explicitly added with [Watcher.Add] (and are not -// yet removed). -// -// Returns nil if [Watcher.Close] was called. -func (w *Watcher) WatchList() []string { return w.b.WatchList() } - -// Supports reports if all the listed operations are supported by this platform. -// -// Create, Write, Remove, Rename, and Chmod are always supported. It can only -// return false for an Op starting with Unportable. -func (w *Watcher) xSupports(op Op) bool { return w.b.xSupports(op) } - -func (o Op) String() string { - var b strings.Builder - if o.Has(Create) { - b.WriteString("|CREATE") - } - if o.Has(Remove) { - b.WriteString("|REMOVE") - } - if o.Has(Write) { - b.WriteString("|WRITE") - } - if o.Has(xUnportableOpen) { - b.WriteString("|OPEN") - } - if o.Has(xUnportableRead) { - b.WriteString("|READ") - } - if o.Has(xUnportableCloseWrite) { - b.WriteString("|CLOSE_WRITE") - } - if o.Has(xUnportableCloseRead) { - b.WriteString("|CLOSE_READ") - } - if o.Has(Rename) { - b.WriteString("|RENAME") - } - if o.Has(Chmod) { - b.WriteString("|CHMOD") - } - if b.Len() == 0 { - return "[no events]" - } - return b.String()[1:] -} - -// Has reports if this operation has the given operation. -func (o Op) Has(h Op) bool { return o&h != 0 } - -// Has reports if this event has the given operation. -func (e Event) Has(op Op) bool { return e.Op.Has(op) } - -// String returns a string representation of the event with their path. -func (e Event) String() string { - if e.renamedFrom != "" { - return fmt.Sprintf("%-13s %q ← %q", e.Op.String(), e.Name, e.renamedFrom) - } - return fmt.Sprintf("%-13s %q", e.Op.String(), e.Name) -} - -type ( - backend interface { - Add(string) error - AddWith(string, ...addOpt) error - Remove(string) error - WatchList() []string - Close() error - xSupports(Op) bool - } - addOpt func(opt *withOpts) - withOpts struct { - bufsize int - op Op - noFollow bool - sendCreate bool - } -) - -var debug = func() bool { - // Check for exactly "1" (rather than mere existence) so we can add - // options/flags in the future. I don't know if we ever want that, but it's - // nice to leave the option open. - return os.Getenv("FSNOTIFY_DEBUG") == "1" -}() - -var defaultOpts = withOpts{ - bufsize: 65536, // 64K - op: Create | Write | Remove | Rename | Chmod, -} - -func getOptions(opts ...addOpt) withOpts { - with := defaultOpts - for _, o := range opts { - if o != nil { - o(&with) - } - } - return with -} - -// WithBufferSize sets the [ReadDirectoryChangesW] buffer size. -// -// This only has effect on Windows systems, and is a no-op for other backends. -// -// The default value is 64K (65536 bytes) which is the highest value that works -// on all filesystems and should be enough for most applications, but if you -// have a large burst of events it may not be enough. You can increase it if -// you're hitting "queue or buffer overflow" errors ([ErrEventOverflow]). -// -// [ReadDirectoryChangesW]: https://learn.microsoft.com/en-gb/windows/win32/api/winbase/nf-winbase-readdirectorychangesw -func WithBufferSize(bytes int) addOpt { - return func(opt *withOpts) { opt.bufsize = bytes } -} - -// WithOps sets which operations to listen for. The default is [Create], -// [Write], [Remove], [Rename], and [Chmod]. -// -// Excluding operations you're not interested in can save quite a bit of CPU -// time; in some use cases there may be hundreds of thousands of useless Write -// or Chmod operations per second. -// -// This can also be used to add unportable operations not supported by all -// platforms; unportable operations all start with "Unportable": -// [UnportableOpen], [UnportableRead], [UnportableCloseWrite], and -// [UnportableCloseRead]. -// -// AddWith returns an error when using an unportable operation that's not -// supported. Use [Watcher.Support] to check for support. -func withOps(op Op) addOpt { - return func(opt *withOpts) { opt.op = op } -} - -// WithNoFollow disables following symlinks, so the symlinks themselves are -// watched. -func withNoFollow() addOpt { - return func(opt *withOpts) { opt.noFollow = true } -} - -// "Internal" option for recursive watches on inotify. -func withCreate() addOpt { - return func(opt *withOpts) { opt.sendCreate = true } -} - -var enableRecurse = false - -// Check if this path is recursive (ends with "/..." or "\..."), and return the -// path with the /... stripped. -func recursivePath(path string) (string, bool) { - path = filepath.Clean(path) - if !enableRecurse { // Only enabled in tests for now. - return path, false - } - if filepath.Base(path) == "..." { - return filepath.Dir(path), true - } - return path, false -} diff --git a/vendor/github.com/fsnotify/fsnotify/internal/darwin.go b/vendor/github.com/fsnotify/fsnotify/internal/darwin.go deleted file mode 100644 index b0eab1009..000000000 --- a/vendor/github.com/fsnotify/fsnotify/internal/darwin.go +++ /dev/null @@ -1,39 +0,0 @@ -//go:build darwin - -package internal - -import ( - "syscall" - - "golang.org/x/sys/unix" -) - -var ( - SyscallEACCES = syscall.EACCES - UnixEACCES = unix.EACCES -) - -var maxfiles uint64 - -// Go 1.19 will do this automatically: https://go-review.googlesource.com/c/go/+/393354/ -func SetRlimit() { - var l syscall.Rlimit - err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &l) - if err == nil && l.Cur != l.Max { - l.Cur = l.Max - syscall.Setrlimit(syscall.RLIMIT_NOFILE, &l) - } - maxfiles = l.Cur - - if n, err := syscall.SysctlUint32("kern.maxfiles"); err == nil && uint64(n) < maxfiles { - maxfiles = uint64(n) - } - - if n, err := syscall.SysctlUint32("kern.maxfilesperproc"); err == nil && uint64(n) < maxfiles { - maxfiles = uint64(n) - } -} - -func Maxfiles() uint64 { return maxfiles } -func Mkfifo(path string, mode uint32) error { return unix.Mkfifo(path, mode) } -func Mknod(path string, mode uint32, dev int) error { return unix.Mknod(path, mode, dev) } diff --git a/vendor/github.com/fsnotify/fsnotify/internal/debug_darwin.go b/vendor/github.com/fsnotify/fsnotify/internal/debug_darwin.go deleted file mode 100644 index 928319fb0..000000000 --- a/vendor/github.com/fsnotify/fsnotify/internal/debug_darwin.go +++ /dev/null @@ -1,57 +0,0 @@ -package internal - -import "golang.org/x/sys/unix" - -var names = []struct { - n string - m uint32 -}{ - {"NOTE_ABSOLUTE", unix.NOTE_ABSOLUTE}, - {"NOTE_ATTRIB", unix.NOTE_ATTRIB}, - {"NOTE_BACKGROUND", unix.NOTE_BACKGROUND}, - {"NOTE_CHILD", unix.NOTE_CHILD}, - {"NOTE_CRITICAL", unix.NOTE_CRITICAL}, - {"NOTE_DELETE", unix.NOTE_DELETE}, - {"NOTE_EXEC", unix.NOTE_EXEC}, - {"NOTE_EXIT", unix.NOTE_EXIT}, - {"NOTE_EXITSTATUS", unix.NOTE_EXITSTATUS}, - {"NOTE_EXIT_CSERROR", unix.NOTE_EXIT_CSERROR}, - {"NOTE_EXIT_DECRYPTFAIL", unix.NOTE_EXIT_DECRYPTFAIL}, - {"NOTE_EXIT_DETAIL", unix.NOTE_EXIT_DETAIL}, - {"NOTE_EXIT_DETAIL_MASK", unix.NOTE_EXIT_DETAIL_MASK}, - {"NOTE_EXIT_MEMORY", unix.NOTE_EXIT_MEMORY}, - {"NOTE_EXIT_REPARENTED", unix.NOTE_EXIT_REPARENTED}, - {"NOTE_EXTEND", unix.NOTE_EXTEND}, - {"NOTE_FFAND", unix.NOTE_FFAND}, - {"NOTE_FFCOPY", unix.NOTE_FFCOPY}, - {"NOTE_FFCTRLMASK", unix.NOTE_FFCTRLMASK}, - {"NOTE_FFLAGSMASK", unix.NOTE_FFLAGSMASK}, - {"NOTE_FFNOP", unix.NOTE_FFNOP}, - {"NOTE_FFOR", unix.NOTE_FFOR}, - {"NOTE_FORK", unix.NOTE_FORK}, - {"NOTE_FUNLOCK", unix.NOTE_FUNLOCK}, - {"NOTE_LEEWAY", unix.NOTE_LEEWAY}, - {"NOTE_LINK", unix.NOTE_LINK}, - {"NOTE_LOWAT", unix.NOTE_LOWAT}, - {"NOTE_MACHTIME", unix.NOTE_MACHTIME}, - {"NOTE_MACH_CONTINUOUS_TIME", unix.NOTE_MACH_CONTINUOUS_TIME}, - {"NOTE_NONE", unix.NOTE_NONE}, - {"NOTE_NSECONDS", unix.NOTE_NSECONDS}, - {"NOTE_OOB", unix.NOTE_OOB}, - //{"NOTE_PCTRLMASK", unix.NOTE_PCTRLMASK}, -0x100000 (?!) - {"NOTE_PDATAMASK", unix.NOTE_PDATAMASK}, - {"NOTE_REAP", unix.NOTE_REAP}, - {"NOTE_RENAME", unix.NOTE_RENAME}, - {"NOTE_REVOKE", unix.NOTE_REVOKE}, - {"NOTE_SECONDS", unix.NOTE_SECONDS}, - {"NOTE_SIGNAL", unix.NOTE_SIGNAL}, - {"NOTE_TRACK", unix.NOTE_TRACK}, - {"NOTE_TRACKERR", unix.NOTE_TRACKERR}, - {"NOTE_TRIGGER", unix.NOTE_TRIGGER}, - {"NOTE_USECONDS", unix.NOTE_USECONDS}, - {"NOTE_VM_ERROR", unix.NOTE_VM_ERROR}, - {"NOTE_VM_PRESSURE", unix.NOTE_VM_PRESSURE}, - {"NOTE_VM_PRESSURE_SUDDEN_TERMINATE", unix.NOTE_VM_PRESSURE_SUDDEN_TERMINATE}, - {"NOTE_VM_PRESSURE_TERMINATE", unix.NOTE_VM_PRESSURE_TERMINATE}, - {"NOTE_WRITE", unix.NOTE_WRITE}, -} diff --git a/vendor/github.com/fsnotify/fsnotify/internal/debug_dragonfly.go b/vendor/github.com/fsnotify/fsnotify/internal/debug_dragonfly.go deleted file mode 100644 index 3186b0c34..000000000 --- a/vendor/github.com/fsnotify/fsnotify/internal/debug_dragonfly.go +++ /dev/null @@ -1,33 +0,0 @@ -package internal - -import "golang.org/x/sys/unix" - -var names = []struct { - n string - m uint32 -}{ - {"NOTE_ATTRIB", unix.NOTE_ATTRIB}, - {"NOTE_CHILD", unix.NOTE_CHILD}, - {"NOTE_DELETE", unix.NOTE_DELETE}, - {"NOTE_EXEC", unix.NOTE_EXEC}, - {"NOTE_EXIT", unix.NOTE_EXIT}, - {"NOTE_EXTEND", unix.NOTE_EXTEND}, - {"NOTE_FFAND", unix.NOTE_FFAND}, - {"NOTE_FFCOPY", unix.NOTE_FFCOPY}, - {"NOTE_FFCTRLMASK", unix.NOTE_FFCTRLMASK}, - {"NOTE_FFLAGSMASK", unix.NOTE_FFLAGSMASK}, - {"NOTE_FFNOP", unix.NOTE_FFNOP}, - {"NOTE_FFOR", unix.NOTE_FFOR}, - {"NOTE_FORK", unix.NOTE_FORK}, - {"NOTE_LINK", unix.NOTE_LINK}, - {"NOTE_LOWAT", unix.NOTE_LOWAT}, - {"NOTE_OOB", unix.NOTE_OOB}, - {"NOTE_PCTRLMASK", unix.NOTE_PCTRLMASK}, - {"NOTE_PDATAMASK", unix.NOTE_PDATAMASK}, - {"NOTE_RENAME", unix.NOTE_RENAME}, - {"NOTE_REVOKE", unix.NOTE_REVOKE}, - {"NOTE_TRACK", unix.NOTE_TRACK}, - {"NOTE_TRACKERR", unix.NOTE_TRACKERR}, - {"NOTE_TRIGGER", unix.NOTE_TRIGGER}, - {"NOTE_WRITE", unix.NOTE_WRITE}, -} diff --git a/vendor/github.com/fsnotify/fsnotify/internal/debug_freebsd.go b/vendor/github.com/fsnotify/fsnotify/internal/debug_freebsd.go deleted file mode 100644 index f69fdb930..000000000 --- a/vendor/github.com/fsnotify/fsnotify/internal/debug_freebsd.go +++ /dev/null @@ -1,42 +0,0 @@ -package internal - -import "golang.org/x/sys/unix" - -var names = []struct { - n string - m uint32 -}{ - {"NOTE_ABSTIME", unix.NOTE_ABSTIME}, - {"NOTE_ATTRIB", unix.NOTE_ATTRIB}, - {"NOTE_CHILD", unix.NOTE_CHILD}, - {"NOTE_CLOSE", unix.NOTE_CLOSE}, - {"NOTE_CLOSE_WRITE", unix.NOTE_CLOSE_WRITE}, - {"NOTE_DELETE", unix.NOTE_DELETE}, - {"NOTE_EXEC", unix.NOTE_EXEC}, - {"NOTE_EXIT", unix.NOTE_EXIT}, - {"NOTE_EXTEND", unix.NOTE_EXTEND}, - {"NOTE_FFAND", unix.NOTE_FFAND}, - {"NOTE_FFCOPY", unix.NOTE_FFCOPY}, - {"NOTE_FFCTRLMASK", unix.NOTE_FFCTRLMASK}, - {"NOTE_FFLAGSMASK", unix.NOTE_FFLAGSMASK}, - {"NOTE_FFNOP", unix.NOTE_FFNOP}, - {"NOTE_FFOR", unix.NOTE_FFOR}, - {"NOTE_FILE_POLL", unix.NOTE_FILE_POLL}, - {"NOTE_FORK", unix.NOTE_FORK}, - {"NOTE_LINK", unix.NOTE_LINK}, - {"NOTE_LOWAT", unix.NOTE_LOWAT}, - {"NOTE_MSECONDS", unix.NOTE_MSECONDS}, - {"NOTE_NSECONDS", unix.NOTE_NSECONDS}, - {"NOTE_OPEN", unix.NOTE_OPEN}, - {"NOTE_PCTRLMASK", unix.NOTE_PCTRLMASK}, - {"NOTE_PDATAMASK", unix.NOTE_PDATAMASK}, - {"NOTE_READ", unix.NOTE_READ}, - {"NOTE_RENAME", unix.NOTE_RENAME}, - {"NOTE_REVOKE", unix.NOTE_REVOKE}, - {"NOTE_SECONDS", unix.NOTE_SECONDS}, - {"NOTE_TRACK", unix.NOTE_TRACK}, - {"NOTE_TRACKERR", unix.NOTE_TRACKERR}, - {"NOTE_TRIGGER", unix.NOTE_TRIGGER}, - {"NOTE_USECONDS", unix.NOTE_USECONDS}, - {"NOTE_WRITE", unix.NOTE_WRITE}, -} diff --git a/vendor/github.com/fsnotify/fsnotify/internal/debug_kqueue.go b/vendor/github.com/fsnotify/fsnotify/internal/debug_kqueue.go deleted file mode 100644 index 607e683bd..000000000 --- a/vendor/github.com/fsnotify/fsnotify/internal/debug_kqueue.go +++ /dev/null @@ -1,32 +0,0 @@ -//go:build freebsd || openbsd || netbsd || dragonfly || darwin - -package internal - -import ( - "fmt" - "os" - "strings" - "time" - - "golang.org/x/sys/unix" -) - -func Debug(name string, kevent *unix.Kevent_t) { - mask := uint32(kevent.Fflags) - - var ( - l []string - unknown = mask - ) - for _, n := range names { - if mask&n.m == n.m { - l = append(l, n.n) - unknown ^= n.m - } - } - if unknown > 0 { - l = append(l, fmt.Sprintf("0x%x", unknown)) - } - fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s %10d:%-60s → %q\n", - time.Now().Format("15:04:05.000000000"), mask, strings.Join(l, " | "), name) -} diff --git a/vendor/github.com/fsnotify/fsnotify/internal/debug_linux.go b/vendor/github.com/fsnotify/fsnotify/internal/debug_linux.go deleted file mode 100644 index 35c734be4..000000000 --- a/vendor/github.com/fsnotify/fsnotify/internal/debug_linux.go +++ /dev/null @@ -1,56 +0,0 @@ -package internal - -import ( - "fmt" - "os" - "strings" - "time" - - "golang.org/x/sys/unix" -) - -func Debug(name string, mask, cookie uint32) { - names := []struct { - n string - m uint32 - }{ - {"IN_ACCESS", unix.IN_ACCESS}, - {"IN_ATTRIB", unix.IN_ATTRIB}, - {"IN_CLOSE", unix.IN_CLOSE}, - {"IN_CLOSE_NOWRITE", unix.IN_CLOSE_NOWRITE}, - {"IN_CLOSE_WRITE", unix.IN_CLOSE_WRITE}, - {"IN_CREATE", unix.IN_CREATE}, - {"IN_DELETE", unix.IN_DELETE}, - {"IN_DELETE_SELF", unix.IN_DELETE_SELF}, - {"IN_IGNORED", unix.IN_IGNORED}, - {"IN_ISDIR", unix.IN_ISDIR}, - {"IN_MODIFY", unix.IN_MODIFY}, - {"IN_MOVE", unix.IN_MOVE}, - {"IN_MOVED_FROM", unix.IN_MOVED_FROM}, - {"IN_MOVED_TO", unix.IN_MOVED_TO}, - {"IN_MOVE_SELF", unix.IN_MOVE_SELF}, - {"IN_OPEN", unix.IN_OPEN}, - {"IN_Q_OVERFLOW", unix.IN_Q_OVERFLOW}, - {"IN_UNMOUNT", unix.IN_UNMOUNT}, - } - - var ( - l []string - unknown = mask - ) - for _, n := range names { - if mask&n.m == n.m { - l = append(l, n.n) - unknown ^= n.m - } - } - if unknown > 0 { - l = append(l, fmt.Sprintf("0x%x", unknown)) - } - var c string - if cookie > 0 { - c = fmt.Sprintf("(cookie: %d) ", cookie) - } - fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s %-30s → %s%q\n", - time.Now().Format("15:04:05.000000000"), strings.Join(l, "|"), c, name) -} diff --git a/vendor/github.com/fsnotify/fsnotify/internal/debug_netbsd.go b/vendor/github.com/fsnotify/fsnotify/internal/debug_netbsd.go deleted file mode 100644 index e5b3b6f69..000000000 --- a/vendor/github.com/fsnotify/fsnotify/internal/debug_netbsd.go +++ /dev/null @@ -1,25 +0,0 @@ -package internal - -import "golang.org/x/sys/unix" - -var names = []struct { - n string - m uint32 -}{ - {"NOTE_ATTRIB", unix.NOTE_ATTRIB}, - {"NOTE_CHILD", unix.NOTE_CHILD}, - {"NOTE_DELETE", unix.NOTE_DELETE}, - {"NOTE_EXEC", unix.NOTE_EXEC}, - {"NOTE_EXIT", unix.NOTE_EXIT}, - {"NOTE_EXTEND", unix.NOTE_EXTEND}, - {"NOTE_FORK", unix.NOTE_FORK}, - {"NOTE_LINK", unix.NOTE_LINK}, - {"NOTE_LOWAT", unix.NOTE_LOWAT}, - {"NOTE_PCTRLMASK", unix.NOTE_PCTRLMASK}, - {"NOTE_PDATAMASK", unix.NOTE_PDATAMASK}, - {"NOTE_RENAME", unix.NOTE_RENAME}, - {"NOTE_REVOKE", unix.NOTE_REVOKE}, - {"NOTE_TRACK", unix.NOTE_TRACK}, - {"NOTE_TRACKERR", unix.NOTE_TRACKERR}, - {"NOTE_WRITE", unix.NOTE_WRITE}, -} diff --git a/vendor/github.com/fsnotify/fsnotify/internal/debug_openbsd.go b/vendor/github.com/fsnotify/fsnotify/internal/debug_openbsd.go deleted file mode 100644 index 1dd455bc5..000000000 --- a/vendor/github.com/fsnotify/fsnotify/internal/debug_openbsd.go +++ /dev/null @@ -1,28 +0,0 @@ -package internal - -import "golang.org/x/sys/unix" - -var names = []struct { - n string - m uint32 -}{ - {"NOTE_ATTRIB", unix.NOTE_ATTRIB}, - // {"NOTE_CHANGE", unix.NOTE_CHANGE}, // Not on 386? - {"NOTE_CHILD", unix.NOTE_CHILD}, - {"NOTE_DELETE", unix.NOTE_DELETE}, - {"NOTE_EOF", unix.NOTE_EOF}, - {"NOTE_EXEC", unix.NOTE_EXEC}, - {"NOTE_EXIT", unix.NOTE_EXIT}, - {"NOTE_EXTEND", unix.NOTE_EXTEND}, - {"NOTE_FORK", unix.NOTE_FORK}, - {"NOTE_LINK", unix.NOTE_LINK}, - {"NOTE_LOWAT", unix.NOTE_LOWAT}, - {"NOTE_PCTRLMASK", unix.NOTE_PCTRLMASK}, - {"NOTE_PDATAMASK", unix.NOTE_PDATAMASK}, - {"NOTE_RENAME", unix.NOTE_RENAME}, - {"NOTE_REVOKE", unix.NOTE_REVOKE}, - {"NOTE_TRACK", unix.NOTE_TRACK}, - {"NOTE_TRACKERR", unix.NOTE_TRACKERR}, - {"NOTE_TRUNCATE", unix.NOTE_TRUNCATE}, - {"NOTE_WRITE", unix.NOTE_WRITE}, -} diff --git a/vendor/github.com/fsnotify/fsnotify/internal/debug_solaris.go b/vendor/github.com/fsnotify/fsnotify/internal/debug_solaris.go deleted file mode 100644 index f1b2e73bd..000000000 --- a/vendor/github.com/fsnotify/fsnotify/internal/debug_solaris.go +++ /dev/null @@ -1,45 +0,0 @@ -package internal - -import ( - "fmt" - "os" - "strings" - "time" - - "golang.org/x/sys/unix" -) - -func Debug(name string, mask int32) { - names := []struct { - n string - m int32 - }{ - {"FILE_ACCESS", unix.FILE_ACCESS}, - {"FILE_MODIFIED", unix.FILE_MODIFIED}, - {"FILE_ATTRIB", unix.FILE_ATTRIB}, - {"FILE_TRUNC", unix.FILE_TRUNC}, - {"FILE_NOFOLLOW", unix.FILE_NOFOLLOW}, - {"FILE_DELETE", unix.FILE_DELETE}, - {"FILE_RENAME_TO", unix.FILE_RENAME_TO}, - {"FILE_RENAME_FROM", unix.FILE_RENAME_FROM}, - {"UNMOUNTED", unix.UNMOUNTED}, - {"MOUNTEDOVER", unix.MOUNTEDOVER}, - {"FILE_EXCEPTION", unix.FILE_EXCEPTION}, - } - - var ( - l []string - unknown = mask - ) - for _, n := range names { - if mask&n.m == n.m { - l = append(l, n.n) - unknown ^= n.m - } - } - if unknown > 0 { - l = append(l, fmt.Sprintf("0x%x", unknown)) - } - fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s %10d:%-30s → %q\n", - time.Now().Format("15:04:05.000000000"), mask, strings.Join(l, " | "), name) -} diff --git a/vendor/github.com/fsnotify/fsnotify/internal/debug_windows.go b/vendor/github.com/fsnotify/fsnotify/internal/debug_windows.go deleted file mode 100644 index 52bf4ce53..000000000 --- a/vendor/github.com/fsnotify/fsnotify/internal/debug_windows.go +++ /dev/null @@ -1,40 +0,0 @@ -package internal - -import ( - "fmt" - "os" - "path/filepath" - "strings" - "time" - - "golang.org/x/sys/windows" -) - -func Debug(name string, mask uint32) { - names := []struct { - n string - m uint32 - }{ - {"FILE_ACTION_ADDED", windows.FILE_ACTION_ADDED}, - {"FILE_ACTION_REMOVED", windows.FILE_ACTION_REMOVED}, - {"FILE_ACTION_MODIFIED", windows.FILE_ACTION_MODIFIED}, - {"FILE_ACTION_RENAMED_OLD_NAME", windows.FILE_ACTION_RENAMED_OLD_NAME}, - {"FILE_ACTION_RENAMED_NEW_NAME", windows.FILE_ACTION_RENAMED_NEW_NAME}, - } - - var ( - l []string - unknown = mask - ) - for _, n := range names { - if mask&n.m == n.m { - l = append(l, n.n) - unknown ^= n.m - } - } - if unknown > 0 { - l = append(l, fmt.Sprintf("0x%x", unknown)) - } - fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s %-65s → %q\n", - time.Now().Format("15:04:05.000000000"), strings.Join(l, " | "), filepath.ToSlash(name)) -} diff --git a/vendor/github.com/fsnotify/fsnotify/internal/freebsd.go b/vendor/github.com/fsnotify/fsnotify/internal/freebsd.go deleted file mode 100644 index 547df1df8..000000000 --- a/vendor/github.com/fsnotify/fsnotify/internal/freebsd.go +++ /dev/null @@ -1,31 +0,0 @@ -//go:build freebsd - -package internal - -import ( - "syscall" - - "golang.org/x/sys/unix" -) - -var ( - SyscallEACCES = syscall.EACCES - UnixEACCES = unix.EACCES -) - -var maxfiles uint64 - -func SetRlimit() { - // Go 1.19 will do this automatically: https://go-review.googlesource.com/c/go/+/393354/ - var l syscall.Rlimit - err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &l) - if err == nil && l.Cur != l.Max { - l.Cur = l.Max - syscall.Setrlimit(syscall.RLIMIT_NOFILE, &l) - } - maxfiles = uint64(l.Cur) -} - -func Maxfiles() uint64 { return maxfiles } -func Mkfifo(path string, mode uint32) error { return unix.Mkfifo(path, mode) } -func Mknod(path string, mode uint32, dev int) error { return unix.Mknod(path, mode, uint64(dev)) } diff --git a/vendor/github.com/fsnotify/fsnotify/internal/internal.go b/vendor/github.com/fsnotify/fsnotify/internal/internal.go deleted file mode 100644 index 7daa45e19..000000000 --- a/vendor/github.com/fsnotify/fsnotify/internal/internal.go +++ /dev/null @@ -1,2 +0,0 @@ -// Package internal contains some helpers. -package internal diff --git a/vendor/github.com/fsnotify/fsnotify/internal/unix.go b/vendor/github.com/fsnotify/fsnotify/internal/unix.go deleted file mode 100644 index 30976ce97..000000000 --- a/vendor/github.com/fsnotify/fsnotify/internal/unix.go +++ /dev/null @@ -1,31 +0,0 @@ -//go:build !windows && !darwin && !freebsd - -package internal - -import ( - "syscall" - - "golang.org/x/sys/unix" -) - -var ( - SyscallEACCES = syscall.EACCES - UnixEACCES = unix.EACCES -) - -var maxfiles uint64 - -func SetRlimit() { - // Go 1.19 will do this automatically: https://go-review.googlesource.com/c/go/+/393354/ - var l syscall.Rlimit - err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &l) - if err == nil && l.Cur != l.Max { - l.Cur = l.Max - syscall.Setrlimit(syscall.RLIMIT_NOFILE, &l) - } - maxfiles = uint64(l.Cur) -} - -func Maxfiles() uint64 { return maxfiles } -func Mkfifo(path string, mode uint32) error { return unix.Mkfifo(path, mode) } -func Mknod(path string, mode uint32, dev int) error { return unix.Mknod(path, mode, dev) } diff --git a/vendor/github.com/fsnotify/fsnotify/internal/unix2.go b/vendor/github.com/fsnotify/fsnotify/internal/unix2.go deleted file mode 100644 index 37dfeddc2..000000000 --- a/vendor/github.com/fsnotify/fsnotify/internal/unix2.go +++ /dev/null @@ -1,7 +0,0 @@ -//go:build !windows - -package internal - -func HasPrivilegesForSymlink() bool { - return true -} diff --git a/vendor/github.com/fsnotify/fsnotify/internal/windows.go b/vendor/github.com/fsnotify/fsnotify/internal/windows.go deleted file mode 100644 index a72c64954..000000000 --- a/vendor/github.com/fsnotify/fsnotify/internal/windows.go +++ /dev/null @@ -1,41 +0,0 @@ -//go:build windows - -package internal - -import ( - "errors" - - "golang.org/x/sys/windows" -) - -// Just a dummy. -var ( - SyscallEACCES = errors.New("dummy") - UnixEACCES = errors.New("dummy") -) - -func SetRlimit() {} -func Maxfiles() uint64 { return 1<<64 - 1 } -func Mkfifo(path string, mode uint32) error { return errors.New("no FIFOs on Windows") } -func Mknod(path string, mode uint32, dev int) error { return errors.New("no device nodes on Windows") } - -func HasPrivilegesForSymlink() bool { - var sid *windows.SID - err := windows.AllocateAndInitializeSid( - &windows.SECURITY_NT_AUTHORITY, - 2, - windows.SECURITY_BUILTIN_DOMAIN_RID, - windows.DOMAIN_ALIAS_RID_ADMINS, - 0, 0, 0, 0, 0, 0, - &sid) - if err != nil { - return false - } - defer windows.FreeSid(sid) - token := windows.Token(0) - member, err := token.IsMember(sid) - if err != nil { - return false - } - return member || token.IsElevated() -} diff --git a/vendor/github.com/fsnotify/fsnotify/system_bsd.go b/vendor/github.com/fsnotify/fsnotify/system_bsd.go deleted file mode 100644 index f65e8fe3e..000000000 --- a/vendor/github.com/fsnotify/fsnotify/system_bsd.go +++ /dev/null @@ -1,7 +0,0 @@ -//go:build freebsd || openbsd || netbsd || dragonfly - -package fsnotify - -import "golang.org/x/sys/unix" - -const openMode = unix.O_NONBLOCK | unix.O_RDONLY | unix.O_CLOEXEC diff --git a/vendor/github.com/fsnotify/fsnotify/system_darwin.go b/vendor/github.com/fsnotify/fsnotify/system_darwin.go deleted file mode 100644 index a29fc7aab..000000000 --- a/vendor/github.com/fsnotify/fsnotify/system_darwin.go +++ /dev/null @@ -1,8 +0,0 @@ -//go:build darwin - -package fsnotify - -import "golang.org/x/sys/unix" - -// note: this constant is not defined on BSD -const openMode = unix.O_EVTONLY | unix.O_CLOEXEC diff --git a/vendor/github.com/inconshreveable/mousetrap/LICENSE b/vendor/github.com/inconshreveable/mousetrap/LICENSE deleted file mode 100644 index 5f920e973..000000000 --- a/vendor/github.com/inconshreveable/mousetrap/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - 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 2022 Alan Shreve (@inconshreveable) - - 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. diff --git a/vendor/github.com/inconshreveable/mousetrap/README.md b/vendor/github.com/inconshreveable/mousetrap/README.md deleted file mode 100644 index 7a950d177..000000000 --- a/vendor/github.com/inconshreveable/mousetrap/README.md +++ /dev/null @@ -1,23 +0,0 @@ -# mousetrap - -mousetrap is a tiny library that answers a single question. - -On a Windows machine, was the process invoked by someone double clicking on -the executable file while browsing in explorer? - -### Motivation - -Windows developers unfamiliar with command line tools will often "double-click" -the executable for a tool. Because most CLI tools print the help and then exit -when invoked without arguments, this is often very frustrating for those users. - -mousetrap provides a way to detect these invocations so that you can provide -more helpful behavior and instructions on how to run the CLI tool. To see what -this looks like, both from an organizational and a technical perspective, see -https://inconshreveable.com/09-09-2014/sweat-the-small-stuff/ - -### The interface - -The library exposes a single interface: - - func StartedByExplorer() (bool) diff --git a/vendor/github.com/inconshreveable/mousetrap/trap_others.go b/vendor/github.com/inconshreveable/mousetrap/trap_others.go deleted file mode 100644 index 06a91f086..000000000 --- a/vendor/github.com/inconshreveable/mousetrap/trap_others.go +++ /dev/null @@ -1,16 +0,0 @@ -//go:build !windows -// +build !windows - -package mousetrap - -// StartedByExplorer returns true if the program was invoked by the user -// double-clicking on the executable from explorer.exe -// -// It is conservative and returns false if any of the internal calls fail. -// It does not guarantee that the program was run from a terminal. It only can tell you -// whether it was launched from explorer.exe -// -// On non-Windows platforms, it always returns false. -func StartedByExplorer() bool { - return false -} diff --git a/vendor/github.com/inconshreveable/mousetrap/trap_windows.go b/vendor/github.com/inconshreveable/mousetrap/trap_windows.go deleted file mode 100644 index 0c5688021..000000000 --- a/vendor/github.com/inconshreveable/mousetrap/trap_windows.go +++ /dev/null @@ -1,42 +0,0 @@ -package mousetrap - -import ( - "syscall" - "unsafe" -) - -func getProcessEntry(pid int) (*syscall.ProcessEntry32, error) { - snapshot, err := syscall.CreateToolhelp32Snapshot(syscall.TH32CS_SNAPPROCESS, 0) - if err != nil { - return nil, err - } - defer syscall.CloseHandle(snapshot) - var procEntry syscall.ProcessEntry32 - procEntry.Size = uint32(unsafe.Sizeof(procEntry)) - if err = syscall.Process32First(snapshot, &procEntry); err != nil { - return nil, err - } - for { - if procEntry.ProcessID == uint32(pid) { - return &procEntry, nil - } - err = syscall.Process32Next(snapshot, &procEntry) - if err != nil { - return nil, err - } - } -} - -// StartedByExplorer returns true if the program was invoked by the user double-clicking -// on the executable from explorer.exe -// -// It is conservative and returns false if any of the internal calls fail. -// It does not guarantee that the program was run from a terminal. It only can tell you -// whether it was launched from explorer.exe -func StartedByExplorer() bool { - pe, err := getProcessEntry(syscall.Getppid()) - if err != nil { - return false - } - return "explorer.exe" == syscall.UTF16ToString(pe.ExeFile[:]) -} diff --git a/vendor/github.com/spf13/cobra/.gitignore b/vendor/github.com/spf13/cobra/.gitignore deleted file mode 100644 index c7b459e4d..000000000 --- a/vendor/github.com/spf13/cobra/.gitignore +++ /dev/null @@ -1,39 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -# Vim files https://github.com/github/gitignore/blob/master/Global/Vim.gitignore -# swap -[._]*.s[a-w][a-z] -[._]s[a-w][a-z] -# session -Session.vim -# temporary -.netrwhist -*~ -# auto-generated tag files -tags - -*.exe -cobra.test -bin - -.idea/ -*.iml diff --git a/vendor/github.com/spf13/cobra/.golangci.yml b/vendor/github.com/spf13/cobra/.golangci.yml deleted file mode 100644 index 2c8f4808c..000000000 --- a/vendor/github.com/spf13/cobra/.golangci.yml +++ /dev/null @@ -1,57 +0,0 @@ -# Copyright 2013-2023 The Cobra 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. - -run: - deadline: 5m - -linters: - disable-all: true - enable: - #- bodyclose - # - deadcode ! deprecated since v1.49.0; replaced by 'unused' - #- depguard - #- dogsled - #- dupl - - errcheck - #- exhaustive - #- funlen - #- gochecknoinits - - goconst - - gocritic - #- gocyclo - - gofmt - - goimports - #- gomnd - #- goprintffuncname - - gosec - - gosimple - - govet - - ineffassign - #- lll - - misspell - #- nakedret - #- noctx - - nolintlint - #- rowserrcheck - #- scopelint - - staticcheck - #- structcheck ! deprecated since v1.49.0; replaced by 'unused' - - stylecheck - #- typecheck - - unconvert - #- unparam - - unused - # - varcheck ! deprecated since v1.49.0; replaced by 'unused' - #- whitespace - fast: false diff --git a/vendor/github.com/spf13/cobra/.mailmap b/vendor/github.com/spf13/cobra/.mailmap deleted file mode 100644 index 94ec53068..000000000 --- a/vendor/github.com/spf13/cobra/.mailmap +++ /dev/null @@ -1,3 +0,0 @@ -Steve Francia -Bjørn Erik Pedersen -Fabiano Franz diff --git a/vendor/github.com/spf13/cobra/CONDUCT.md b/vendor/github.com/spf13/cobra/CONDUCT.md deleted file mode 100644 index 9d16f88fd..000000000 --- a/vendor/github.com/spf13/cobra/CONDUCT.md +++ /dev/null @@ -1,37 +0,0 @@ -## Cobra User Contract - -### Versioning -Cobra will follow a steady release cadence. Non breaking changes will be released as minor versions quarterly. Patch bug releases are at the discretion of the maintainers. Users can expect security patch fixes to be released within relatively short order of a CVE becoming known. For more information on security patch fixes see the CVE section below. Releases will follow [Semantic Versioning](https://semver.org/). Users tracking the Master branch should expect unpredictable breaking changes as the project continues to move forward. For stability, it is highly recommended to use a release. - -### Backward Compatibility -We will maintain two major releases in a moving window. The N-1 release will only receive bug fixes and security updates and will be dropped once N+1 is released. - -### Deprecation -Deprecation of Go versions or dependent packages will only occur in major releases. To reduce the change of this taking users by surprise, any large deprecation will be preceded by an announcement in the [#cobra slack channel](https://gophers.slack.com/archives/CD3LP1199) and an Issue on Github. - -### CVE -Maintainers will make every effort to release security patches in the case of a medium to high severity CVE directly impacting the library. The speed in which these patches reach a release is up to the discretion of the maintainers. A low severity CVE may be a lower priority than a high severity one. - -### Communication -Cobra maintainers will use GitHub issues and the [#cobra slack channel](https://gophers.slack.com/archives/CD3LP1199) as the primary means of communication with the community. This is to foster open communication with all users and contributors. - -### Breaking Changes -Breaking changes are generally allowed in the master branch, as this is the branch used to develop the next release of Cobra. - -There may be times, however, when master is closed for breaking changes. This is likely to happen as we near the release of a new version. - -Breaking changes are not allowed in release branches, as these represent minor versions that have already been released. These version have consumers who expect the APIs, behaviors, etc, to remain stable during the lifetime of the patch stream for the minor release. - -Examples of breaking changes include: -- Removing or renaming exported constant, variable, type, or function. -- Updating the version of critical libraries such as `spf13/pflag`, `spf13/viper` etc... - - Some version updates may be acceptable for picking up bug fixes, but maintainers must exercise caution when reviewing. - -There may, at times, need to be exceptions where breaking changes are allowed in release branches. These are at the discretion of the project's maintainers, and must be carefully considered before merging. - -### CI Testing -Maintainers will ensure the Cobra test suite utilizes the current supported versions of Golang. - -### Disclaimer -Changes to this document and the contents therein are at the discretion of the maintainers. -None of the contents of this document are legally binding in any way to the maintainers or the users. diff --git a/vendor/github.com/spf13/cobra/CONTRIBUTING.md b/vendor/github.com/spf13/cobra/CONTRIBUTING.md deleted file mode 100644 index 6f356e6a8..000000000 --- a/vendor/github.com/spf13/cobra/CONTRIBUTING.md +++ /dev/null @@ -1,50 +0,0 @@ -# Contributing to Cobra - -Thank you so much for contributing to Cobra. We appreciate your time and help. -Here are some guidelines to help you get started. - -## Code of Conduct - -Be kind and respectful to the members of the community. Take time to educate -others who are seeking help. Harassment of any kind will not be tolerated. - -## Questions - -If you have questions regarding Cobra, feel free to ask it in the community -[#cobra Slack channel][cobra-slack] - -## Filing a bug or feature - -1. Before filing an issue, please check the existing issues to see if a - similar one was already opened. If there is one already opened, feel free - to comment on it. -1. If you believe you've found a bug, please provide detailed steps of - reproduction, the version of Cobra and anything else you believe will be - useful to help troubleshoot it (e.g. OS environment, environment variables, - etc...). Also state the current behavior vs. the expected behavior. -1. If you'd like to see a feature or an enhancement please open an issue with - a clear title and description of what the feature is and why it would be - beneficial to the project and its users. - -## Submitting changes - -1. CLA: Upon submitting a Pull Request (PR), contributors will be prompted to - sign a CLA. Please sign the CLA :slightly_smiling_face: -1. Tests: If you are submitting code, please ensure you have adequate tests - for the feature. Tests can be run via `go test ./...` or `make test`. -1. Since this is golang project, ensure the new code is properly formatted to - ensure code consistency. Run `make all`. - -### Quick steps to contribute - -1. Fork the project. -1. Download your fork to your PC (`git clone https://github.com/your_username/cobra && cd cobra`) -1. Create your feature branch (`git checkout -b my-new-feature`) -1. Make changes and run tests (`make test`) -1. Add them to staging (`git add .`) -1. Commit your changes (`git commit -m 'Add some feature'`) -1. Push to the branch (`git push origin my-new-feature`) -1. Create new pull request - - -[cobra-slack]: https://gophers.slack.com/archives/CD3LP1199 diff --git a/vendor/github.com/spf13/cobra/LICENSE.txt b/vendor/github.com/spf13/cobra/LICENSE.txt deleted file mode 100644 index 298f0e266..000000000 --- a/vendor/github.com/spf13/cobra/LICENSE.txt +++ /dev/null @@ -1,174 +0,0 @@ - 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. diff --git a/vendor/github.com/spf13/cobra/MAINTAINERS b/vendor/github.com/spf13/cobra/MAINTAINERS deleted file mode 100644 index 4c5ac3dd9..000000000 --- a/vendor/github.com/spf13/cobra/MAINTAINERS +++ /dev/null @@ -1,13 +0,0 @@ -maintainers: -- spf13 -- johnSchnake -- jpmcb -- marckhouzam -inactive: -- anthonyfok -- bep -- bogem -- broady -- eparis -- jharshman -- wfernandes diff --git a/vendor/github.com/spf13/cobra/Makefile b/vendor/github.com/spf13/cobra/Makefile deleted file mode 100644 index 0da8d7aa0..000000000 --- a/vendor/github.com/spf13/cobra/Makefile +++ /dev/null @@ -1,35 +0,0 @@ -BIN="./bin" -SRC=$(shell find . -name "*.go") - -ifeq (, $(shell which golangci-lint)) -$(warning "could not find golangci-lint in $(PATH), run: curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh") -endif - -.PHONY: fmt lint test install_deps clean - -default: all - -all: fmt test - -fmt: - $(info ******************** checking formatting ********************) - @test -z $(shell gofmt -l $(SRC)) || (gofmt -d $(SRC); exit 1) - -lint: - $(info ******************** running lint tools ********************) - golangci-lint run -v - -test: install_deps - $(info ******************** running tests ********************) - go test -v ./... - -richtest: install_deps - $(info ******************** running tests with kyoh86/richgo ********************) - richgo test -v ./... - -install_deps: - $(info ******************** downloading dependencies ********************) - go get -v ./... - -clean: - rm -rf $(BIN) diff --git a/vendor/github.com/spf13/cobra/README.md b/vendor/github.com/spf13/cobra/README.md deleted file mode 100644 index 6444f4b7f..000000000 --- a/vendor/github.com/spf13/cobra/README.md +++ /dev/null @@ -1,112 +0,0 @@ -![cobra logo](assets/CobraMain.png) - -Cobra is a library for creating powerful modern CLI applications. - -Cobra is used in many Go projects such as [Kubernetes](https://kubernetes.io/), -[Hugo](https://gohugo.io), and [GitHub CLI](https://github.com/cli/cli) to -name a few. [This list](site/content/projects_using_cobra.md) contains a more extensive list of projects using Cobra. - -[![](https://img.shields.io/github/actions/workflow/status/spf13/cobra/test.yml?branch=main&longCache=true&label=Test&logo=github%20actions&logoColor=fff)](https://github.com/spf13/cobra/actions?query=workflow%3ATest) -[![Go Reference](https://pkg.go.dev/badge/github.com/spf13/cobra.svg)](https://pkg.go.dev/github.com/spf13/cobra) -[![Go Report Card](https://goreportcard.com/badge/github.com/spf13/cobra)](https://goreportcard.com/report/github.com/spf13/cobra) -[![Slack](https://img.shields.io/badge/Slack-cobra-brightgreen)](https://gophers.slack.com/archives/CD3LP1199) - -# Overview - -Cobra is a library providing a simple interface to create powerful modern CLI -interfaces similar to git & go tools. - -Cobra provides: -* Easy subcommand-based CLIs: `app server`, `app fetch`, etc. -* Fully POSIX-compliant flags (including short & long versions) -* Nested subcommands -* Global, local and cascading flags -* Intelligent suggestions (`app srver`... did you mean `app server`?) -* Automatic help generation for commands and flags -* Grouping help for subcommands -* Automatic help flag recognition of `-h`, `--help`, etc. -* Automatically generated shell autocomplete for your application (bash, zsh, fish, powershell) -* Automatically generated man pages for your application -* Command aliases so you can change things without breaking them -* The flexibility to define your own help, usage, etc. -* Optional seamless integration with [viper](https://github.com/spf13/viper) for 12-factor apps - -# Concepts - -Cobra is built on a structure of commands, arguments & flags. - -**Commands** represent actions, **Args** are things and **Flags** are modifiers for those actions. - -The best applications read like sentences when used, and as a result, users -intuitively know how to interact with them. - -The pattern to follow is -`APPNAME VERB NOUN --ADJECTIVE` - or -`APPNAME COMMAND ARG --FLAG`. - -A few good real world examples may better illustrate this point. - -In the following example, 'server' is a command, and 'port' is a flag: - - hugo server --port=1313 - -In this command we are telling Git to clone the url bare. - - git clone URL --bare - -## Commands - -Command is the central point of the application. Each interaction that -the application supports will be contained in a Command. A command can -have children commands and optionally run an action. - -In the example above, 'server' is the command. - -[More about cobra.Command](https://pkg.go.dev/github.com/spf13/cobra#Command) - -## Flags - -A flag is a way to modify the behavior of a command. Cobra supports -fully POSIX-compliant flags as well as the Go [flag package](https://golang.org/pkg/flag/). -A Cobra command can define flags that persist through to children commands -and flags that are only available to that command. - -In the example above, 'port' is the flag. - -Flag functionality is provided by the [pflag -library](https://github.com/spf13/pflag), a fork of the flag standard library -which maintains the same interface while adding POSIX compliance. - -# Installing -Using Cobra is easy. First, use `go get` to install the latest version -of the library. - -``` -go get -u github.com/spf13/cobra@latest -``` - -Next, include Cobra in your application: - -```go -import "github.com/spf13/cobra" -``` - -# Usage -`cobra-cli` is a command line program to generate cobra applications and command files. -It will bootstrap your application scaffolding to rapidly -develop a Cobra-based application. It is the easiest way to incorporate Cobra into your application. - -It can be installed by running: - -``` -go install github.com/spf13/cobra-cli@latest -``` - -For complete details on using the Cobra-CLI generator, please read [The Cobra Generator README](https://github.com/spf13/cobra-cli/blob/main/README.md) - -For complete details on using the Cobra library, please read the [The Cobra User Guide](site/content/user_guide.md). - -# License - -Cobra is released under the Apache 2.0 license. See [LICENSE.txt](LICENSE.txt) diff --git a/vendor/github.com/spf13/cobra/active_help.go b/vendor/github.com/spf13/cobra/active_help.go deleted file mode 100644 index 25c30e3cc..000000000 --- a/vendor/github.com/spf13/cobra/active_help.go +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2013-2023 The Cobra 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 cobra - -import ( - "fmt" - "os" -) - -const ( - activeHelpMarker = "_activeHelp_ " - // The below values should not be changed: programs will be using them explicitly - // in their user documentation, and users will be using them explicitly. - activeHelpEnvVarSuffix = "ACTIVE_HELP" - activeHelpGlobalEnvVar = configEnvVarGlobalPrefix + "_" + activeHelpEnvVarSuffix - activeHelpGlobalDisable = "0" -) - -// AppendActiveHelp adds the specified string to the specified array to be used as ActiveHelp. -// Such strings will be processed by the completion script and will be shown as ActiveHelp -// to the user. -// The array parameter should be the array that will contain the completions. -// This function can be called multiple times before and/or after completions are added to -// the array. Each time this function is called with the same array, the new -// ActiveHelp line will be shown below the previous ones when completion is triggered. -func AppendActiveHelp(compArray []string, activeHelpStr string) []string { - return append(compArray, fmt.Sprintf("%s%s", activeHelpMarker, activeHelpStr)) -} - -// GetActiveHelpConfig returns the value of the ActiveHelp environment variable -// _ACTIVE_HELP where is the name of the root command in upper -// case, with all non-ASCII-alphanumeric characters replaced by `_`. -// It will always return "0" if the global environment variable COBRA_ACTIVE_HELP -// is set to "0". -func GetActiveHelpConfig(cmd *Command) string { - activeHelpCfg := os.Getenv(activeHelpGlobalEnvVar) - if activeHelpCfg != activeHelpGlobalDisable { - activeHelpCfg = os.Getenv(activeHelpEnvVar(cmd.Root().Name())) - } - return activeHelpCfg -} - -// activeHelpEnvVar returns the name of the program-specific ActiveHelp environment -// variable. It has the format _ACTIVE_HELP where is the name of the -// root command in upper case, with all non-ASCII-alphanumeric characters replaced by `_`. -func activeHelpEnvVar(name string) string { - return configEnvVar(name, activeHelpEnvVarSuffix) -} diff --git a/vendor/github.com/spf13/cobra/args.go b/vendor/github.com/spf13/cobra/args.go deleted file mode 100644 index ed1e70cea..000000000 --- a/vendor/github.com/spf13/cobra/args.go +++ /dev/null @@ -1,131 +0,0 @@ -// Copyright 2013-2023 The Cobra 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 cobra - -import ( - "fmt" - "strings" -) - -type PositionalArgs func(cmd *Command, args []string) error - -// legacyArgs validation has the following behaviour: -// - root commands with no subcommands can take arbitrary arguments -// - root commands with subcommands will do subcommand validity checking -// - subcommands will always accept arbitrary arguments -func legacyArgs(cmd *Command, args []string) error { - // no subcommand, always take args - if !cmd.HasSubCommands() { - return nil - } - - // root command with subcommands, do subcommand checking. - if !cmd.HasParent() && len(args) > 0 { - return fmt.Errorf("unknown command %q for %q%s", args[0], cmd.CommandPath(), cmd.findSuggestions(args[0])) - } - return nil -} - -// NoArgs returns an error if any args are included. -func NoArgs(cmd *Command, args []string) error { - if len(args) > 0 { - return fmt.Errorf("unknown command %q for %q", args[0], cmd.CommandPath()) - } - return nil -} - -// OnlyValidArgs returns an error if there are any positional args that are not in -// the `ValidArgs` field of `Command` -func OnlyValidArgs(cmd *Command, args []string) error { - if len(cmd.ValidArgs) > 0 { - // Remove any description that may be included in ValidArgs. - // A description is following a tab character. - validArgs := make([]string, 0, len(cmd.ValidArgs)) - for _, v := range cmd.ValidArgs { - validArgs = append(validArgs, strings.SplitN(v, "\t", 2)[0]) - } - for _, v := range args { - if !stringInSlice(v, validArgs) { - return fmt.Errorf("invalid argument %q for %q%s", v, cmd.CommandPath(), cmd.findSuggestions(args[0])) - } - } - } - return nil -} - -// ArbitraryArgs never returns an error. -func ArbitraryArgs(cmd *Command, args []string) error { - return nil -} - -// MinimumNArgs returns an error if there is not at least N args. -func MinimumNArgs(n int) PositionalArgs { - return func(cmd *Command, args []string) error { - if len(args) < n { - return fmt.Errorf("requires at least %d arg(s), only received %d", n, len(args)) - } - return nil - } -} - -// MaximumNArgs returns an error if there are more than N args. -func MaximumNArgs(n int) PositionalArgs { - return func(cmd *Command, args []string) error { - if len(args) > n { - return fmt.Errorf("accepts at most %d arg(s), received %d", n, len(args)) - } - return nil - } -} - -// ExactArgs returns an error if there are not exactly n args. -func ExactArgs(n int) PositionalArgs { - return func(cmd *Command, args []string) error { - if len(args) != n { - return fmt.Errorf("accepts %d arg(s), received %d", n, len(args)) - } - return nil - } -} - -// RangeArgs returns an error if the number of args is not within the expected range. -func RangeArgs(min int, max int) PositionalArgs { - return func(cmd *Command, args []string) error { - if len(args) < min || len(args) > max { - return fmt.Errorf("accepts between %d and %d arg(s), received %d", min, max, len(args)) - } - return nil - } -} - -// MatchAll allows combining several PositionalArgs to work in concert. -func MatchAll(pargs ...PositionalArgs) PositionalArgs { - return func(cmd *Command, args []string) error { - for _, parg := range pargs { - if err := parg(cmd, args); err != nil { - return err - } - } - return nil - } -} - -// ExactValidArgs returns an error if there are not exactly N positional args OR -// there are any positional args that are not in the `ValidArgs` field of `Command` -// -// Deprecated: use MatchAll(ExactArgs(n), OnlyValidArgs) instead -func ExactValidArgs(n int) PositionalArgs { - return MatchAll(ExactArgs(n), OnlyValidArgs) -} diff --git a/vendor/github.com/spf13/cobra/bash_completions.go b/vendor/github.com/spf13/cobra/bash_completions.go deleted file mode 100644 index f4d198cbc..000000000 --- a/vendor/github.com/spf13/cobra/bash_completions.go +++ /dev/null @@ -1,709 +0,0 @@ -// Copyright 2013-2023 The Cobra 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 cobra - -import ( - "bytes" - "fmt" - "io" - "os" - "sort" - "strings" - - "github.com/spf13/pflag" -) - -// Annotations for Bash completion. -const ( - BashCompFilenameExt = "cobra_annotation_bash_completion_filename_extensions" - BashCompCustom = "cobra_annotation_bash_completion_custom" - BashCompOneRequiredFlag = "cobra_annotation_bash_completion_one_required_flag" - BashCompSubdirsInDir = "cobra_annotation_bash_completion_subdirs_in_dir" -) - -func writePreamble(buf io.StringWriter, name string) { - WriteStringAndCheck(buf, fmt.Sprintf("# bash completion for %-36s -*- shell-script -*-\n", name)) - WriteStringAndCheck(buf, fmt.Sprintf(` -__%[1]s_debug() -{ - if [[ -n ${BASH_COMP_DEBUG_FILE:-} ]]; then - echo "$*" >> "${BASH_COMP_DEBUG_FILE}" - fi -} - -# Homebrew on Macs have version 1.3 of bash-completion which doesn't include -# _init_completion. This is a very minimal version of that function. -__%[1]s_init_completion() -{ - COMPREPLY=() - _get_comp_words_by_ref "$@" cur prev words cword -} - -__%[1]s_index_of_word() -{ - local w word=$1 - shift - index=0 - for w in "$@"; do - [[ $w = "$word" ]] && return - index=$((index+1)) - done - index=-1 -} - -__%[1]s_contains_word() -{ - local w word=$1; shift - for w in "$@"; do - [[ $w = "$word" ]] && return - done - return 1 -} - -__%[1]s_handle_go_custom_completion() -{ - __%[1]s_debug "${FUNCNAME[0]}: cur is ${cur}, words[*] is ${words[*]}, #words[@] is ${#words[@]}" - - local shellCompDirectiveError=%[3]d - local shellCompDirectiveNoSpace=%[4]d - local shellCompDirectiveNoFileComp=%[5]d - local shellCompDirectiveFilterFileExt=%[6]d - local shellCompDirectiveFilterDirs=%[7]d - - local out requestComp lastParam lastChar comp directive args - - # Prepare the command to request completions for the program. - # Calling ${words[0]} instead of directly %[1]s allows handling aliases - args=("${words[@]:1}") - # Disable ActiveHelp which is not supported for bash completion v1 - requestComp="%[8]s=0 ${words[0]} %[2]s ${args[*]}" - - lastParam=${words[$((${#words[@]}-1))]} - lastChar=${lastParam:$((${#lastParam}-1)):1} - __%[1]s_debug "${FUNCNAME[0]}: lastParam ${lastParam}, lastChar ${lastChar}" - - if [ -z "${cur}" ] && [ "${lastChar}" != "=" ]; then - # If the last parameter is complete (there is a space following it) - # We add an extra empty parameter so we can indicate this to the go method. - __%[1]s_debug "${FUNCNAME[0]}: Adding extra empty parameter" - requestComp="${requestComp} \"\"" - fi - - __%[1]s_debug "${FUNCNAME[0]}: calling ${requestComp}" - # Use eval to handle any environment variables and such - out=$(eval "${requestComp}" 2>/dev/null) - - # Extract the directive integer at the very end of the output following a colon (:) - directive=${out##*:} - # Remove the directive - out=${out%%:*} - if [ "${directive}" = "${out}" ]; then - # There is not directive specified - directive=0 - fi - __%[1]s_debug "${FUNCNAME[0]}: the completion directive is: ${directive}" - __%[1]s_debug "${FUNCNAME[0]}: the completions are: ${out}" - - if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then - # Error code. No completion. - __%[1]s_debug "${FUNCNAME[0]}: received error from custom completion go code" - return - else - if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then - if [[ $(type -t compopt) = "builtin" ]]; then - __%[1]s_debug "${FUNCNAME[0]}: activating no space" - compopt -o nospace - fi - fi - if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then - if [[ $(type -t compopt) = "builtin" ]]; then - __%[1]s_debug "${FUNCNAME[0]}: activating no file completion" - compopt +o default - fi - fi - fi - - if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then - # File extension filtering - local fullFilter filter filteringCmd - # Do not use quotes around the $out variable or else newline - # characters will be kept. - for filter in ${out}; do - fullFilter+="$filter|" - done - - filteringCmd="_filedir $fullFilter" - __%[1]s_debug "File filtering command: $filteringCmd" - $filteringCmd - elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then - # File completion for directories only - local subdir - # Use printf to strip any trailing newline - subdir=$(printf "%%s" "${out}") - if [ -n "$subdir" ]; then - __%[1]s_debug "Listing directories in $subdir" - __%[1]s_handle_subdirs_in_dir_flag "$subdir" - else - __%[1]s_debug "Listing directories in ." - _filedir -d - fi - else - while IFS='' read -r comp; do - COMPREPLY+=("$comp") - done < <(compgen -W "${out}" -- "$cur") - fi -} - -__%[1]s_handle_reply() -{ - __%[1]s_debug "${FUNCNAME[0]}" - local comp - case $cur in - -*) - if [[ $(type -t compopt) = "builtin" ]]; then - compopt -o nospace - fi - local allflags - if [ ${#must_have_one_flag[@]} -ne 0 ]; then - allflags=("${must_have_one_flag[@]}") - else - allflags=("${flags[*]} ${two_word_flags[*]}") - fi - while IFS='' read -r comp; do - COMPREPLY+=("$comp") - done < <(compgen -W "${allflags[*]}" -- "$cur") - if [[ $(type -t compopt) = "builtin" ]]; then - [[ "${COMPREPLY[0]}" == *= ]] || compopt +o nospace - fi - - # complete after --flag=abc - if [[ $cur == *=* ]]; then - if [[ $(type -t compopt) = "builtin" ]]; then - compopt +o nospace - fi - - local index flag - flag="${cur%%=*}" - __%[1]s_index_of_word "${flag}" "${flags_with_completion[@]}" - COMPREPLY=() - if [[ ${index} -ge 0 ]]; then - PREFIX="" - cur="${cur#*=}" - ${flags_completion[${index}]} - if [ -n "${ZSH_VERSION:-}" ]; then - # zsh completion needs --flag= prefix - eval "COMPREPLY=( \"\${COMPREPLY[@]/#/${flag}=}\" )" - fi - fi - fi - - if [[ -z "${flag_parsing_disabled}" ]]; then - # If flag parsing is enabled, we have completed the flags and can return. - # If flag parsing is disabled, we may not know all (or any) of the flags, so we fallthrough - # to possibly call handle_go_custom_completion. - return 0; - fi - ;; - esac - - # check if we are handling a flag with special work handling - local index - __%[1]s_index_of_word "${prev}" "${flags_with_completion[@]}" - if [[ ${index} -ge 0 ]]; then - ${flags_completion[${index}]} - return - fi - - # we are parsing a flag and don't have a special handler, no completion - if [[ ${cur} != "${words[cword]}" ]]; then - return - fi - - local completions - completions=("${commands[@]}") - if [[ ${#must_have_one_noun[@]} -ne 0 ]]; then - completions+=("${must_have_one_noun[@]}") - elif [[ -n "${has_completion_function}" ]]; then - # if a go completion function is provided, defer to that function - __%[1]s_handle_go_custom_completion - fi - if [[ ${#must_have_one_flag[@]} -ne 0 ]]; then - completions+=("${must_have_one_flag[@]}") - fi - while IFS='' read -r comp; do - COMPREPLY+=("$comp") - done < <(compgen -W "${completions[*]}" -- "$cur") - - if [[ ${#COMPREPLY[@]} -eq 0 && ${#noun_aliases[@]} -gt 0 && ${#must_have_one_noun[@]} -ne 0 ]]; then - while IFS='' read -r comp; do - COMPREPLY+=("$comp") - done < <(compgen -W "${noun_aliases[*]}" -- "$cur") - fi - - if [[ ${#COMPREPLY[@]} -eq 0 ]]; then - if declare -F __%[1]s_custom_func >/dev/null; then - # try command name qualified custom func - __%[1]s_custom_func - else - # otherwise fall back to unqualified for compatibility - declare -F __custom_func >/dev/null && __custom_func - fi - fi - - # available in bash-completion >= 2, not always present on macOS - if declare -F __ltrim_colon_completions >/dev/null; then - __ltrim_colon_completions "$cur" - fi - - # If there is only 1 completion and it is a flag with an = it will be completed - # but we don't want a space after the = - if [[ "${#COMPREPLY[@]}" -eq "1" ]] && [[ $(type -t compopt) = "builtin" ]] && [[ "${COMPREPLY[0]}" == --*= ]]; then - compopt -o nospace - fi -} - -# The arguments should be in the form "ext1|ext2|extn" -__%[1]s_handle_filename_extension_flag() -{ - local ext="$1" - _filedir "@(${ext})" -} - -__%[1]s_handle_subdirs_in_dir_flag() -{ - local dir="$1" - pushd "${dir}" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return -} - -__%[1]s_handle_flag() -{ - __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" - - # if a command required a flag, and we found it, unset must_have_one_flag() - local flagname=${words[c]} - local flagvalue="" - # if the word contained an = - if [[ ${words[c]} == *"="* ]]; then - flagvalue=${flagname#*=} # take in as flagvalue after the = - flagname=${flagname%%=*} # strip everything after the = - flagname="${flagname}=" # but put the = back - fi - __%[1]s_debug "${FUNCNAME[0]}: looking for ${flagname}" - if __%[1]s_contains_word "${flagname}" "${must_have_one_flag[@]}"; then - must_have_one_flag=() - fi - - # if you set a flag which only applies to this command, don't show subcommands - if __%[1]s_contains_word "${flagname}" "${local_nonpersistent_flags[@]}"; then - commands=() - fi - - # keep flag value with flagname as flaghash - # flaghash variable is an associative array which is only supported in bash > 3. - if [[ -z "${BASH_VERSION:-}" || "${BASH_VERSINFO[0]:-}" -gt 3 ]]; then - if [ -n "${flagvalue}" ] ; then - flaghash[${flagname}]=${flagvalue} - elif [ -n "${words[ $((c+1)) ]}" ] ; then - flaghash[${flagname}]=${words[ $((c+1)) ]} - else - flaghash[${flagname}]="true" # pad "true" for bool flag - fi - fi - - # skip the argument to a two word flag - if [[ ${words[c]} != *"="* ]] && __%[1]s_contains_word "${words[c]}" "${two_word_flags[@]}"; then - __%[1]s_debug "${FUNCNAME[0]}: found a flag ${words[c]}, skip the next argument" - c=$((c+1)) - # if we are looking for a flags value, don't show commands - if [[ $c -eq $cword ]]; then - commands=() - fi - fi - - c=$((c+1)) - -} - -__%[1]s_handle_noun() -{ - __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" - - if __%[1]s_contains_word "${words[c]}" "${must_have_one_noun[@]}"; then - must_have_one_noun=() - elif __%[1]s_contains_word "${words[c]}" "${noun_aliases[@]}"; then - must_have_one_noun=() - fi - - nouns+=("${words[c]}") - c=$((c+1)) -} - -__%[1]s_handle_command() -{ - __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" - - local next_command - if [[ -n ${last_command} ]]; then - next_command="_${last_command}_${words[c]//:/__}" - else - if [[ $c -eq 0 ]]; then - next_command="_%[1]s_root_command" - else - next_command="_${words[c]//:/__}" - fi - fi - c=$((c+1)) - __%[1]s_debug "${FUNCNAME[0]}: looking for ${next_command}" - declare -F "$next_command" >/dev/null && $next_command -} - -__%[1]s_handle_word() -{ - if [[ $c -ge $cword ]]; then - __%[1]s_handle_reply - return - fi - __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" - if [[ "${words[c]}" == -* ]]; then - __%[1]s_handle_flag - elif __%[1]s_contains_word "${words[c]}" "${commands[@]}"; then - __%[1]s_handle_command - elif [[ $c -eq 0 ]]; then - __%[1]s_handle_command - elif __%[1]s_contains_word "${words[c]}" "${command_aliases[@]}"; then - # aliashash variable is an associative array which is only supported in bash > 3. - if [[ -z "${BASH_VERSION:-}" || "${BASH_VERSINFO[0]:-}" -gt 3 ]]; then - words[c]=${aliashash[${words[c]}]} - __%[1]s_handle_command - else - __%[1]s_handle_noun - fi - else - __%[1]s_handle_noun - fi - __%[1]s_handle_word -} - -`, name, ShellCompNoDescRequestCmd, - ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, - ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, activeHelpEnvVar(name))) -} - -func writePostscript(buf io.StringWriter, name string) { - name = strings.ReplaceAll(name, ":", "__") - WriteStringAndCheck(buf, fmt.Sprintf("__start_%s()\n", name)) - WriteStringAndCheck(buf, fmt.Sprintf(`{ - local cur prev words cword split - declare -A flaghash 2>/dev/null || : - declare -A aliashash 2>/dev/null || : - if declare -F _init_completion >/dev/null 2>&1; then - _init_completion -s || return - else - __%[1]s_init_completion -n "=" || return - fi - - local c=0 - local flag_parsing_disabled= - local flags=() - local two_word_flags=() - local local_nonpersistent_flags=() - local flags_with_completion=() - local flags_completion=() - local commands=("%[1]s") - local command_aliases=() - local must_have_one_flag=() - local must_have_one_noun=() - local has_completion_function="" - local last_command="" - local nouns=() - local noun_aliases=() - - __%[1]s_handle_word -} - -`, name)) - WriteStringAndCheck(buf, fmt.Sprintf(`if [[ $(type -t compopt) = "builtin" ]]; then - complete -o default -F __start_%s %s -else - complete -o default -o nospace -F __start_%s %s -fi - -`, name, name, name, name)) - WriteStringAndCheck(buf, "# ex: ts=4 sw=4 et filetype=sh\n") -} - -func writeCommands(buf io.StringWriter, cmd *Command) { - WriteStringAndCheck(buf, " commands=()\n") - for _, c := range cmd.Commands() { - if !c.IsAvailableCommand() && c != cmd.helpCommand { - continue - } - WriteStringAndCheck(buf, fmt.Sprintf(" commands+=(%q)\n", c.Name())) - writeCmdAliases(buf, c) - } - WriteStringAndCheck(buf, "\n") -} - -func writeFlagHandler(buf io.StringWriter, name string, annotations map[string][]string, cmd *Command) { - for key, value := range annotations { - switch key { - case BashCompFilenameExt: - WriteStringAndCheck(buf, fmt.Sprintf(" flags_with_completion+=(%q)\n", name)) - - var ext string - if len(value) > 0 { - ext = fmt.Sprintf("__%s_handle_filename_extension_flag ", cmd.Root().Name()) + strings.Join(value, "|") - } else { - ext = "_filedir" - } - WriteStringAndCheck(buf, fmt.Sprintf(" flags_completion+=(%q)\n", ext)) - case BashCompCustom: - WriteStringAndCheck(buf, fmt.Sprintf(" flags_with_completion+=(%q)\n", name)) - - if len(value) > 0 { - handlers := strings.Join(value, "; ") - WriteStringAndCheck(buf, fmt.Sprintf(" flags_completion+=(%q)\n", handlers)) - } else { - WriteStringAndCheck(buf, " flags_completion+=(:)\n") - } - case BashCompSubdirsInDir: - WriteStringAndCheck(buf, fmt.Sprintf(" flags_with_completion+=(%q)\n", name)) - - var ext string - if len(value) == 1 { - ext = fmt.Sprintf("__%s_handle_subdirs_in_dir_flag ", cmd.Root().Name()) + value[0] - } else { - ext = "_filedir -d" - } - WriteStringAndCheck(buf, fmt.Sprintf(" flags_completion+=(%q)\n", ext)) - } - } -} - -const cbn = "\")\n" - -func writeShortFlag(buf io.StringWriter, flag *pflag.Flag, cmd *Command) { - name := flag.Shorthand - format := " " - if len(flag.NoOptDefVal) == 0 { - format += "two_word_" - } - format += "flags+=(\"-%s" + cbn - WriteStringAndCheck(buf, fmt.Sprintf(format, name)) - writeFlagHandler(buf, "-"+name, flag.Annotations, cmd) -} - -func writeFlag(buf io.StringWriter, flag *pflag.Flag, cmd *Command) { - name := flag.Name - format := " flags+=(\"--%s" - if len(flag.NoOptDefVal) == 0 { - format += "=" - } - format += cbn - WriteStringAndCheck(buf, fmt.Sprintf(format, name)) - if len(flag.NoOptDefVal) == 0 { - format = " two_word_flags+=(\"--%s" + cbn - WriteStringAndCheck(buf, fmt.Sprintf(format, name)) - } - writeFlagHandler(buf, "--"+name, flag.Annotations, cmd) -} - -func writeLocalNonPersistentFlag(buf io.StringWriter, flag *pflag.Flag) { - name := flag.Name - format := " local_nonpersistent_flags+=(\"--%[1]s" + cbn - if len(flag.NoOptDefVal) == 0 { - format += " local_nonpersistent_flags+=(\"--%[1]s=" + cbn - } - WriteStringAndCheck(buf, fmt.Sprintf(format, name)) - if len(flag.Shorthand) > 0 { - WriteStringAndCheck(buf, fmt.Sprintf(" local_nonpersistent_flags+=(\"-%s\")\n", flag.Shorthand)) - } -} - -// prepareCustomAnnotationsForFlags setup annotations for go completions for registered flags -func prepareCustomAnnotationsForFlags(cmd *Command) { - flagCompletionMutex.RLock() - defer flagCompletionMutex.RUnlock() - for flag := range flagCompletionFunctions { - // Make sure the completion script calls the __*_go_custom_completion function for - // every registered flag. We need to do this here (and not when the flag was registered - // for completion) so that we can know the root command name for the prefix - // of ___go_custom_completion - if flag.Annotations == nil { - flag.Annotations = map[string][]string{} - } - flag.Annotations[BashCompCustom] = []string{fmt.Sprintf("__%[1]s_handle_go_custom_completion", cmd.Root().Name())} - } -} - -func writeFlags(buf io.StringWriter, cmd *Command) { - prepareCustomAnnotationsForFlags(cmd) - WriteStringAndCheck(buf, ` flags=() - two_word_flags=() - local_nonpersistent_flags=() - flags_with_completion=() - flags_completion=() - -`) - - if cmd.DisableFlagParsing { - WriteStringAndCheck(buf, " flag_parsing_disabled=1\n") - } - - localNonPersistentFlags := cmd.LocalNonPersistentFlags() - cmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) { - if nonCompletableFlag(flag) { - return - } - writeFlag(buf, flag, cmd) - if len(flag.Shorthand) > 0 { - writeShortFlag(buf, flag, cmd) - } - // localNonPersistentFlags are used to stop the completion of subcommands when one is set - // if TraverseChildren is true we should allow to complete subcommands - if localNonPersistentFlags.Lookup(flag.Name) != nil && !cmd.Root().TraverseChildren { - writeLocalNonPersistentFlag(buf, flag) - } - }) - cmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) { - if nonCompletableFlag(flag) { - return - } - writeFlag(buf, flag, cmd) - if len(flag.Shorthand) > 0 { - writeShortFlag(buf, flag, cmd) - } - }) - - WriteStringAndCheck(buf, "\n") -} - -func writeRequiredFlag(buf io.StringWriter, cmd *Command) { - WriteStringAndCheck(buf, " must_have_one_flag=()\n") - flags := cmd.NonInheritedFlags() - flags.VisitAll(func(flag *pflag.Flag) { - if nonCompletableFlag(flag) { - return - } - if _, ok := flag.Annotations[BashCompOneRequiredFlag]; ok { - format := " must_have_one_flag+=(\"--%s" - if flag.Value.Type() != "bool" { - format += "=" - } - format += cbn - WriteStringAndCheck(buf, fmt.Sprintf(format, flag.Name)) - - if len(flag.Shorthand) > 0 { - WriteStringAndCheck(buf, fmt.Sprintf(" must_have_one_flag+=(\"-%s"+cbn, flag.Shorthand)) - } - } - }) -} - -func writeRequiredNouns(buf io.StringWriter, cmd *Command) { - WriteStringAndCheck(buf, " must_have_one_noun=()\n") - sort.Strings(cmd.ValidArgs) - for _, value := range cmd.ValidArgs { - // Remove any description that may be included following a tab character. - // Descriptions are not supported by bash completion. - value = strings.SplitN(value, "\t", 2)[0] - WriteStringAndCheck(buf, fmt.Sprintf(" must_have_one_noun+=(%q)\n", value)) - } - if cmd.ValidArgsFunction != nil { - WriteStringAndCheck(buf, " has_completion_function=1\n") - } -} - -func writeCmdAliases(buf io.StringWriter, cmd *Command) { - if len(cmd.Aliases) == 0 { - return - } - - sort.Strings(cmd.Aliases) - - WriteStringAndCheck(buf, fmt.Sprint(` if [[ -z "${BASH_VERSION:-}" || "${BASH_VERSINFO[0]:-}" -gt 3 ]]; then`, "\n")) - for _, value := range cmd.Aliases { - WriteStringAndCheck(buf, fmt.Sprintf(" command_aliases+=(%q)\n", value)) - WriteStringAndCheck(buf, fmt.Sprintf(" aliashash[%q]=%q\n", value, cmd.Name())) - } - WriteStringAndCheck(buf, ` fi`) - WriteStringAndCheck(buf, "\n") -} -func writeArgAliases(buf io.StringWriter, cmd *Command) { - WriteStringAndCheck(buf, " noun_aliases=()\n") - sort.Strings(cmd.ArgAliases) - for _, value := range cmd.ArgAliases { - WriteStringAndCheck(buf, fmt.Sprintf(" noun_aliases+=(%q)\n", value)) - } -} - -func gen(buf io.StringWriter, cmd *Command) { - for _, c := range cmd.Commands() { - if !c.IsAvailableCommand() && c != cmd.helpCommand { - continue - } - gen(buf, c) - } - commandName := cmd.CommandPath() - commandName = strings.ReplaceAll(commandName, " ", "_") - commandName = strings.ReplaceAll(commandName, ":", "__") - - if cmd.Root() == cmd { - WriteStringAndCheck(buf, fmt.Sprintf("_%s_root_command()\n{\n", commandName)) - } else { - WriteStringAndCheck(buf, fmt.Sprintf("_%s()\n{\n", commandName)) - } - - WriteStringAndCheck(buf, fmt.Sprintf(" last_command=%q\n", commandName)) - WriteStringAndCheck(buf, "\n") - WriteStringAndCheck(buf, " command_aliases=()\n") - WriteStringAndCheck(buf, "\n") - - writeCommands(buf, cmd) - writeFlags(buf, cmd) - writeRequiredFlag(buf, cmd) - writeRequiredNouns(buf, cmd) - writeArgAliases(buf, cmd) - WriteStringAndCheck(buf, "}\n\n") -} - -// GenBashCompletion generates bash completion file and writes to the passed writer. -func (c *Command) GenBashCompletion(w io.Writer) error { - buf := new(bytes.Buffer) - writePreamble(buf, c.Name()) - if len(c.BashCompletionFunction) > 0 { - buf.WriteString(c.BashCompletionFunction + "\n") - } - gen(buf, c) - writePostscript(buf, c.Name()) - - _, err := buf.WriteTo(w) - return err -} - -func nonCompletableFlag(flag *pflag.Flag) bool { - return flag.Hidden || len(flag.Deprecated) > 0 -} - -// GenBashCompletionFile generates bash completion file. -func (c *Command) GenBashCompletionFile(filename string) error { - outFile, err := os.Create(filename) - if err != nil { - return err - } - defer outFile.Close() - - return c.GenBashCompletion(outFile) -} diff --git a/vendor/github.com/spf13/cobra/bash_completionsV2.go b/vendor/github.com/spf13/cobra/bash_completionsV2.go deleted file mode 100644 index 1cce5c329..000000000 --- a/vendor/github.com/spf13/cobra/bash_completionsV2.go +++ /dev/null @@ -1,396 +0,0 @@ -// Copyright 2013-2023 The Cobra 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 cobra - -import ( - "bytes" - "fmt" - "io" - "os" -) - -func (c *Command) genBashCompletion(w io.Writer, includeDesc bool) error { - buf := new(bytes.Buffer) - genBashComp(buf, c.Name(), includeDesc) - _, err := buf.WriteTo(w) - return err -} - -func genBashComp(buf io.StringWriter, name string, includeDesc bool) { - compCmd := ShellCompRequestCmd - if !includeDesc { - compCmd = ShellCompNoDescRequestCmd - } - - WriteStringAndCheck(buf, fmt.Sprintf(`# bash completion V2 for %-36[1]s -*- shell-script -*- - -__%[1]s_debug() -{ - if [[ -n ${BASH_COMP_DEBUG_FILE-} ]]; then - echo "$*" >> "${BASH_COMP_DEBUG_FILE}" - fi -} - -# Macs have bash3 for which the bash-completion package doesn't include -# _init_completion. This is a minimal version of that function. -__%[1]s_init_completion() -{ - COMPREPLY=() - _get_comp_words_by_ref "$@" cur prev words cword -} - -# This function calls the %[1]s program to obtain the completion -# results and the directive. It fills the 'out' and 'directive' vars. -__%[1]s_get_completion_results() { - local requestComp lastParam lastChar args - - # Prepare the command to request completions for the program. - # Calling ${words[0]} instead of directly %[1]s allows handling aliases - args=("${words[@]:1}") - requestComp="${words[0]} %[2]s ${args[*]}" - - lastParam=${words[$((${#words[@]}-1))]} - lastChar=${lastParam:$((${#lastParam}-1)):1} - __%[1]s_debug "lastParam ${lastParam}, lastChar ${lastChar}" - - if [[ -z ${cur} && ${lastChar} != = ]]; then - # If the last parameter is complete (there is a space following it) - # We add an extra empty parameter so we can indicate this to the go method. - __%[1]s_debug "Adding extra empty parameter" - requestComp="${requestComp} ''" - fi - - # When completing a flag with an = (e.g., %[1]s -n=) - # bash focuses on the part after the =, so we need to remove - # the flag part from $cur - if [[ ${cur} == -*=* ]]; then - cur="${cur#*=}" - fi - - __%[1]s_debug "Calling ${requestComp}" - # Use eval to handle any environment variables and such - out=$(eval "${requestComp}" 2>/dev/null) - - # Extract the directive integer at the very end of the output following a colon (:) - directive=${out##*:} - # Remove the directive - out=${out%%:*} - if [[ ${directive} == "${out}" ]]; then - # There is not directive specified - directive=0 - fi - __%[1]s_debug "The completion directive is: ${directive}" - __%[1]s_debug "The completions are: ${out}" -} - -__%[1]s_process_completion_results() { - local shellCompDirectiveError=%[3]d - local shellCompDirectiveNoSpace=%[4]d - local shellCompDirectiveNoFileComp=%[5]d - local shellCompDirectiveFilterFileExt=%[6]d - local shellCompDirectiveFilterDirs=%[7]d - local shellCompDirectiveKeepOrder=%[8]d - - if (((directive & shellCompDirectiveError) != 0)); then - # Error code. No completion. - __%[1]s_debug "Received error from custom completion go code" - return - else - if (((directive & shellCompDirectiveNoSpace) != 0)); then - if [[ $(type -t compopt) == builtin ]]; then - __%[1]s_debug "Activating no space" - compopt -o nospace - else - __%[1]s_debug "No space directive not supported in this version of bash" - fi - fi - if (((directive & shellCompDirectiveKeepOrder) != 0)); then - if [[ $(type -t compopt) == builtin ]]; then - # no sort isn't supported for bash less than < 4.4 - if [[ ${BASH_VERSINFO[0]} -lt 4 || ( ${BASH_VERSINFO[0]} -eq 4 && ${BASH_VERSINFO[1]} -lt 4 ) ]]; then - __%[1]s_debug "No sort directive not supported in this version of bash" - else - __%[1]s_debug "Activating keep order" - compopt -o nosort - fi - else - __%[1]s_debug "No sort directive not supported in this version of bash" - fi - fi - if (((directive & shellCompDirectiveNoFileComp) != 0)); then - if [[ $(type -t compopt) == builtin ]]; then - __%[1]s_debug "Activating no file completion" - compopt +o default - else - __%[1]s_debug "No file completion directive not supported in this version of bash" - fi - fi - fi - - # Separate activeHelp from normal completions - local completions=() - local activeHelp=() - __%[1]s_extract_activeHelp - - if (((directive & shellCompDirectiveFilterFileExt) != 0)); then - # File extension filtering - local fullFilter filter filteringCmd - - # Do not use quotes around the $completions variable or else newline - # characters will be kept. - for filter in ${completions[*]}; do - fullFilter+="$filter|" - done - - filteringCmd="_filedir $fullFilter" - __%[1]s_debug "File filtering command: $filteringCmd" - $filteringCmd - elif (((directive & shellCompDirectiveFilterDirs) != 0)); then - # File completion for directories only - - local subdir - subdir=${completions[0]} - if [[ -n $subdir ]]; then - __%[1]s_debug "Listing directories in $subdir" - pushd "$subdir" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return - else - __%[1]s_debug "Listing directories in ." - _filedir -d - fi - else - __%[1]s_handle_completion_types - fi - - __%[1]s_handle_special_char "$cur" : - __%[1]s_handle_special_char "$cur" = - - # Print the activeHelp statements before we finish - if ((${#activeHelp[*]} != 0)); then - printf "\n"; - printf "%%s\n" "${activeHelp[@]}" - printf "\n" - - # The prompt format is only available from bash 4.4. - # We test if it is available before using it. - if (x=${PS1@P}) 2> /dev/null; then - printf "%%s" "${PS1@P}${COMP_LINE[@]}" - else - # Can't print the prompt. Just print the - # text the user had typed, it is workable enough. - printf "%%s" "${COMP_LINE[@]}" - fi - fi -} - -# Separate activeHelp lines from real completions. -# Fills the $activeHelp and $completions arrays. -__%[1]s_extract_activeHelp() { - local activeHelpMarker="%[9]s" - local endIndex=${#activeHelpMarker} - - while IFS='' read -r comp; do - if [[ ${comp:0:endIndex} == $activeHelpMarker ]]; then - comp=${comp:endIndex} - __%[1]s_debug "ActiveHelp found: $comp" - if [[ -n $comp ]]; then - activeHelp+=("$comp") - fi - else - # Not an activeHelp line but a normal completion - completions+=("$comp") - fi - done <<<"${out}" -} - -__%[1]s_handle_completion_types() { - __%[1]s_debug "__%[1]s_handle_completion_types: COMP_TYPE is $COMP_TYPE" - - case $COMP_TYPE in - 37|42) - # Type: menu-complete/menu-complete-backward and insert-completions - # If the user requested inserting one completion at a time, or all - # completions at once on the command-line we must remove the descriptions. - # https://github.com/spf13/cobra/issues/1508 - local tab=$'\t' comp - while IFS='' read -r comp; do - [[ -z $comp ]] && continue - # Strip any description - comp=${comp%%%%$tab*} - # Only consider the completions that match - if [[ $comp == "$cur"* ]]; then - COMPREPLY+=("$comp") - fi - done < <(printf "%%s\n" "${completions[@]}") - ;; - - *) - # Type: complete (normal completion) - __%[1]s_handle_standard_completion_case - ;; - esac -} - -__%[1]s_handle_standard_completion_case() { - local tab=$'\t' comp - - # Short circuit to optimize if we don't have descriptions - if [[ "${completions[*]}" != *$tab* ]]; then - IFS=$'\n' read -ra COMPREPLY -d '' < <(compgen -W "${completions[*]}" -- "$cur") - return 0 - fi - - local longest=0 - local compline - # Look for the longest completion so that we can format things nicely - while IFS='' read -r compline; do - [[ -z $compline ]] && continue - # Strip any description before checking the length - comp=${compline%%%%$tab*} - # Only consider the completions that match - [[ $comp == "$cur"* ]] || continue - COMPREPLY+=("$compline") - if ((${#comp}>longest)); then - longest=${#comp} - fi - done < <(printf "%%s\n" "${completions[@]}") - - # If there is a single completion left, remove the description text - if ((${#COMPREPLY[*]} == 1)); then - __%[1]s_debug "COMPREPLY[0]: ${COMPREPLY[0]}" - comp="${COMPREPLY[0]%%%%$tab*}" - __%[1]s_debug "Removed description from single completion, which is now: ${comp}" - COMPREPLY[0]=$comp - else # Format the descriptions - __%[1]s_format_comp_descriptions $longest - fi -} - -__%[1]s_handle_special_char() -{ - local comp="$1" - local char=$2 - if [[ "$comp" == *${char}* && "$COMP_WORDBREAKS" == *${char}* ]]; then - local word=${comp%%"${comp##*${char}}"} - local idx=${#COMPREPLY[*]} - while ((--idx >= 0)); do - COMPREPLY[idx]=${COMPREPLY[idx]#"$word"} - done - fi -} - -__%[1]s_format_comp_descriptions() -{ - local tab=$'\t' - local comp desc maxdesclength - local longest=$1 - - local i ci - for ci in ${!COMPREPLY[*]}; do - comp=${COMPREPLY[ci]} - # Properly format the description string which follows a tab character if there is one - if [[ "$comp" == *$tab* ]]; then - __%[1]s_debug "Original comp: $comp" - desc=${comp#*$tab} - comp=${comp%%%%$tab*} - - # $COLUMNS stores the current shell width. - # Remove an extra 4 because we add 2 spaces and 2 parentheses. - maxdesclength=$(( COLUMNS - longest - 4 )) - - # Make sure we can fit a description of at least 8 characters - # if we are to align the descriptions. - if ((maxdesclength > 8)); then - # Add the proper number of spaces to align the descriptions - for ((i = ${#comp} ; i < longest ; i++)); do - comp+=" " - done - else - # Don't pad the descriptions so we can fit more text after the completion - maxdesclength=$(( COLUMNS - ${#comp} - 4 )) - fi - - # If there is enough space for any description text, - # truncate the descriptions that are too long for the shell width - if ((maxdesclength > 0)); then - if ((${#desc} > maxdesclength)); then - desc=${desc:0:$(( maxdesclength - 1 ))} - desc+="…" - fi - comp+=" ($desc)" - fi - COMPREPLY[ci]=$comp - __%[1]s_debug "Final comp: $comp" - fi - done -} - -__start_%[1]s() -{ - local cur prev words cword split - - COMPREPLY=() - - # Call _init_completion from the bash-completion package - # to prepare the arguments properly - if declare -F _init_completion >/dev/null 2>&1; then - _init_completion -n =: || return - else - __%[1]s_init_completion -n =: || return - fi - - __%[1]s_debug - __%[1]s_debug "========= starting completion logic ==========" - __%[1]s_debug "cur is ${cur}, words[*] is ${words[*]}, #words[@] is ${#words[@]}, cword is $cword" - - # The user could have moved the cursor backwards on the command-line. - # We need to trigger completion from the $cword location, so we need - # to truncate the command-line ($words) up to the $cword location. - words=("${words[@]:0:$cword+1}") - __%[1]s_debug "Truncated words[*]: ${words[*]}," - - local out directive - __%[1]s_get_completion_results - __%[1]s_process_completion_results -} - -if [[ $(type -t compopt) = "builtin" ]]; then - complete -o default -F __start_%[1]s %[1]s -else - complete -o default -o nospace -F __start_%[1]s %[1]s -fi - -# ex: ts=4 sw=4 et filetype=sh -`, name, compCmd, - ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, - ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder, - activeHelpMarker)) -} - -// GenBashCompletionFileV2 generates Bash completion version 2. -func (c *Command) GenBashCompletionFileV2(filename string, includeDesc bool) error { - outFile, err := os.Create(filename) - if err != nil { - return err - } - defer outFile.Close() - - return c.GenBashCompletionV2(outFile, includeDesc) -} - -// GenBashCompletionV2 generates Bash completion file version 2 -// and writes it to the passed writer. -func (c *Command) GenBashCompletionV2(w io.Writer, includeDesc bool) error { - return c.genBashCompletion(w, includeDesc) -} diff --git a/vendor/github.com/spf13/cobra/cobra.go b/vendor/github.com/spf13/cobra/cobra.go deleted file mode 100644 index e0b0947b0..000000000 --- a/vendor/github.com/spf13/cobra/cobra.go +++ /dev/null @@ -1,242 +0,0 @@ -// Copyright 2013-2023 The Cobra 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. - -// Commands similar to git, go tools and other modern CLI tools -// inspired by go, go-Commander, gh and subcommand - -package cobra - -import ( - "fmt" - "io" - "os" - "reflect" - "strconv" - "strings" - "text/template" - "time" - "unicode" -) - -var templateFuncs = template.FuncMap{ - "trim": strings.TrimSpace, - "trimRightSpace": trimRightSpace, - "trimTrailingWhitespaces": trimRightSpace, - "appendIfNotPresent": appendIfNotPresent, - "rpad": rpad, - "gt": Gt, - "eq": Eq, -} - -var initializers []func() -var finalizers []func() - -const ( - defaultPrefixMatching = false - defaultCommandSorting = true - defaultCaseInsensitive = false - defaultTraverseRunHooks = false -) - -// EnablePrefixMatching allows setting automatic prefix matching. Automatic prefix matching can be a dangerous thing -// to automatically enable in CLI tools. -// Set this to true to enable it. -var EnablePrefixMatching = defaultPrefixMatching - -// EnableCommandSorting controls sorting of the slice of commands, which is turned on by default. -// To disable sorting, set it to false. -var EnableCommandSorting = defaultCommandSorting - -// EnableCaseInsensitive allows case-insensitive commands names. (case sensitive by default) -var EnableCaseInsensitive = defaultCaseInsensitive - -// EnableTraverseRunHooks executes persistent pre-run and post-run hooks from all parents. -// By default this is disabled, which means only the first run hook to be found is executed. -var EnableTraverseRunHooks = defaultTraverseRunHooks - -// MousetrapHelpText enables an information splash screen on Windows -// if the CLI is started from explorer.exe. -// To disable the mousetrap, just set this variable to blank string (""). -// Works only on Microsoft Windows. -var MousetrapHelpText = `This is a command line tool. - -You need to open cmd.exe and run it from there. -` - -// MousetrapDisplayDuration controls how long the MousetrapHelpText message is displayed on Windows -// if the CLI is started from explorer.exe. Set to 0 to wait for the return key to be pressed. -// To disable the mousetrap, just set MousetrapHelpText to blank string (""). -// Works only on Microsoft Windows. -var MousetrapDisplayDuration = 5 * time.Second - -// AddTemplateFunc adds a template function that's available to Usage and Help -// template generation. -func AddTemplateFunc(name string, tmplFunc interface{}) { - templateFuncs[name] = tmplFunc -} - -// AddTemplateFuncs adds multiple template functions that are available to Usage and -// Help template generation. -func AddTemplateFuncs(tmplFuncs template.FuncMap) { - for k, v := range tmplFuncs { - templateFuncs[k] = v - } -} - -// OnInitialize sets the passed functions to be run when each command's -// Execute method is called. -func OnInitialize(y ...func()) { - initializers = append(initializers, y...) -} - -// OnFinalize sets the passed functions to be run when each command's -// Execute method is terminated. -func OnFinalize(y ...func()) { - finalizers = append(finalizers, y...) -} - -// FIXME Gt is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra. - -// Gt takes two types and checks whether the first type is greater than the second. In case of types Arrays, Chans, -// Maps and Slices, Gt will compare their lengths. Ints are compared directly while strings are first parsed as -// ints and then compared. -func Gt(a interface{}, b interface{}) bool { - var left, right int64 - av := reflect.ValueOf(a) - - switch av.Kind() { - case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice: - left = int64(av.Len()) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - left = av.Int() - case reflect.String: - left, _ = strconv.ParseInt(av.String(), 10, 64) - } - - bv := reflect.ValueOf(b) - - switch bv.Kind() { - case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice: - right = int64(bv.Len()) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - right = bv.Int() - case reflect.String: - right, _ = strconv.ParseInt(bv.String(), 10, 64) - } - - return left > right -} - -// FIXME Eq is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra. - -// Eq takes two types and checks whether they are equal. Supported types are int and string. Unsupported types will panic. -func Eq(a interface{}, b interface{}) bool { - av := reflect.ValueOf(a) - bv := reflect.ValueOf(b) - - switch av.Kind() { - case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice: - panic("Eq called on unsupported type") - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return av.Int() == bv.Int() - case reflect.String: - return av.String() == bv.String() - } - return false -} - -func trimRightSpace(s string) string { - return strings.TrimRightFunc(s, unicode.IsSpace) -} - -// FIXME appendIfNotPresent is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra. - -// appendIfNotPresent will append stringToAppend to the end of s, but only if it's not yet present in s. -func appendIfNotPresent(s, stringToAppend string) string { - if strings.Contains(s, stringToAppend) { - return s - } - return s + " " + stringToAppend -} - -// rpad adds padding to the right of a string. -func rpad(s string, padding int) string { - formattedString := fmt.Sprintf("%%-%ds", padding) - return fmt.Sprintf(formattedString, s) -} - -// tmpl executes the given template text on data, writing the result to w. -func tmpl(w io.Writer, text string, data interface{}) error { - t := template.New("top") - t.Funcs(templateFuncs) - template.Must(t.Parse(text)) - return t.Execute(w, data) -} - -// ld compares two strings and returns the levenshtein distance between them. -func ld(s, t string, ignoreCase bool) int { - if ignoreCase { - s = strings.ToLower(s) - t = strings.ToLower(t) - } - d := make([][]int, len(s)+1) - for i := range d { - d[i] = make([]int, len(t)+1) - d[i][0] = i - } - for j := range d[0] { - d[0][j] = j - } - for j := 1; j <= len(t); j++ { - for i := 1; i <= len(s); i++ { - if s[i-1] == t[j-1] { - d[i][j] = d[i-1][j-1] - } else { - min := d[i-1][j] - if d[i][j-1] < min { - min = d[i][j-1] - } - if d[i-1][j-1] < min { - min = d[i-1][j-1] - } - d[i][j] = min + 1 - } - } - - } - return d[len(s)][len(t)] -} - -func stringInSlice(a string, list []string) bool { - for _, b := range list { - if b == a { - return true - } - } - return false -} - -// CheckErr prints the msg with the prefix 'Error:' and exits with error code 1. If the msg is nil, it does nothing. -func CheckErr(msg interface{}) { - if msg != nil { - fmt.Fprintln(os.Stderr, "Error:", msg) - os.Exit(1) - } -} - -// WriteStringAndCheck writes a string into a buffer, and checks if the error is not nil. -func WriteStringAndCheck(b io.StringWriter, s string) { - _, err := b.WriteString(s) - CheckErr(err) -} diff --git a/vendor/github.com/spf13/cobra/command.go b/vendor/github.com/spf13/cobra/command.go deleted file mode 100644 index 54748fc67..000000000 --- a/vendor/github.com/spf13/cobra/command.go +++ /dev/null @@ -1,1896 +0,0 @@ -// Copyright 2013-2023 The Cobra 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 cobra is a commander providing a simple interface to create powerful modern CLI interfaces. -// In addition to providing an interface, Cobra simultaneously provides a controller to organize your application code. -package cobra - -import ( - "bytes" - "context" - "errors" - "fmt" - "io" - "os" - "path/filepath" - "sort" - "strings" - - flag "github.com/spf13/pflag" -) - -const ( - FlagSetByCobraAnnotation = "cobra_annotation_flag_set_by_cobra" - CommandDisplayNameAnnotation = "cobra_annotation_command_display_name" -) - -// FParseErrWhitelist configures Flag parse errors to be ignored -type FParseErrWhitelist flag.ParseErrorsWhitelist - -// Group Structure to manage groups for commands -type Group struct { - ID string - Title string -} - -// Command is just that, a command for your application. -// E.g. 'go run ...' - 'run' is the command. Cobra requires -// you to define the usage and description as part of your command -// definition to ensure usability. -type Command struct { - // Use is the one-line usage message. - // Recommended syntax is as follows: - // [ ] identifies an optional argument. Arguments that are not enclosed in brackets are required. - // ... indicates that you can specify multiple values for the previous argument. - // | indicates mutually exclusive information. You can use the argument to the left of the separator or the - // argument to the right of the separator. You cannot use both arguments in a single use of the command. - // { } delimits a set of mutually exclusive arguments when one of the arguments is required. If the arguments are - // optional, they are enclosed in brackets ([ ]). - // Example: add [-F file | -D dir]... [-f format] profile - Use string - - // Aliases is an array of aliases that can be used instead of the first word in Use. - Aliases []string - - // SuggestFor is an array of command names for which this command will be suggested - - // similar to aliases but only suggests. - SuggestFor []string - - // Short is the short description shown in the 'help' output. - Short string - - // The group id under which this subcommand is grouped in the 'help' output of its parent. - GroupID string - - // Long is the long message shown in the 'help ' output. - Long string - - // Example is examples of how to use the command. - Example string - - // ValidArgs is list of all valid non-flag arguments that are accepted in shell completions - ValidArgs []string - // ValidArgsFunction is an optional function that provides valid non-flag arguments for shell completion. - // It is a dynamic version of using ValidArgs. - // Only one of ValidArgs and ValidArgsFunction can be used for a command. - ValidArgsFunction func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) - - // Expected arguments - Args PositionalArgs - - // ArgAliases is List of aliases for ValidArgs. - // These are not suggested to the user in the shell completion, - // but accepted if entered manually. - ArgAliases []string - - // BashCompletionFunction is custom bash functions used by the legacy bash autocompletion generator. - // For portability with other shells, it is recommended to instead use ValidArgsFunction - BashCompletionFunction string - - // Deprecated defines, if this command is deprecated and should print this string when used. - Deprecated string - - // Annotations are key/value pairs that can be used by applications to identify or - // group commands or set special options. - Annotations map[string]string - - // Version defines the version for this command. If this value is non-empty and the command does not - // define a "version" flag, a "version" boolean flag will be added to the command and, if specified, - // will print content of the "Version" variable. A shorthand "v" flag will also be added if the - // command does not define one. - Version string - - // The *Run functions are executed in the following order: - // * PersistentPreRun() - // * PreRun() - // * Run() - // * PostRun() - // * PersistentPostRun() - // All functions get the same args, the arguments after the command name. - // The *PreRun and *PostRun functions will only be executed if the Run function of the current - // command has been declared. - // - // PersistentPreRun: children of this command will inherit and execute. - PersistentPreRun func(cmd *Command, args []string) - // PersistentPreRunE: PersistentPreRun but returns an error. - PersistentPreRunE func(cmd *Command, args []string) error - // PreRun: children of this command will not inherit. - PreRun func(cmd *Command, args []string) - // PreRunE: PreRun but returns an error. - PreRunE func(cmd *Command, args []string) error - // Run: Typically the actual work function. Most commands will only implement this. - Run func(cmd *Command, args []string) - // RunE: Run but returns an error. - RunE func(cmd *Command, args []string) error - // PostRun: run after the Run command. - PostRun func(cmd *Command, args []string) - // PostRunE: PostRun but returns an error. - PostRunE func(cmd *Command, args []string) error - // PersistentPostRun: children of this command will inherit and execute after PostRun. - PersistentPostRun func(cmd *Command, args []string) - // PersistentPostRunE: PersistentPostRun but returns an error. - PersistentPostRunE func(cmd *Command, args []string) error - - // groups for subcommands - commandgroups []*Group - - // args is actual args parsed from flags. - args []string - // flagErrorBuf contains all error messages from pflag. - flagErrorBuf *bytes.Buffer - // flags is full set of flags. - flags *flag.FlagSet - // pflags contains persistent flags. - pflags *flag.FlagSet - // lflags contains local flags. - // This field does not represent internal state, it's used as a cache to optimise LocalFlags function call - lflags *flag.FlagSet - // iflags contains inherited flags. - // This field does not represent internal state, it's used as a cache to optimise InheritedFlags function call - iflags *flag.FlagSet - // parentsPflags is all persistent flags of cmd's parents. - parentsPflags *flag.FlagSet - // globNormFunc is the global normalization function - // that we can use on every pflag set and children commands - globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName - - // usageFunc is usage func defined by user. - usageFunc func(*Command) error - // usageTemplate is usage template defined by user. - usageTemplate string - // flagErrorFunc is func defined by user and it's called when the parsing of - // flags returns an error. - flagErrorFunc func(*Command, error) error - // helpTemplate is help template defined by user. - helpTemplate string - // helpFunc is help func defined by user. - helpFunc func(*Command, []string) - // helpCommand is command with usage 'help'. If it's not defined by user, - // cobra uses default help command. - helpCommand *Command - // helpCommandGroupID is the group id for the helpCommand - helpCommandGroupID string - - // completionCommandGroupID is the group id for the completion command - completionCommandGroupID string - - // versionTemplate is the version template defined by user. - versionTemplate string - - // errPrefix is the error message prefix defined by user. - errPrefix string - - // inReader is a reader defined by the user that replaces stdin - inReader io.Reader - // outWriter is a writer defined by the user that replaces stdout - outWriter io.Writer - // errWriter is a writer defined by the user that replaces stderr - errWriter io.Writer - - // FParseErrWhitelist flag parse errors to be ignored - FParseErrWhitelist FParseErrWhitelist - - // CompletionOptions is a set of options to control the handling of shell completion - CompletionOptions CompletionOptions - - // commandsAreSorted defines, if command slice are sorted or not. - commandsAreSorted bool - // commandCalledAs is the name or alias value used to call this command. - commandCalledAs struct { - name string - called bool - } - - ctx context.Context - - // commands is the list of commands supported by this program. - commands []*Command - // parent is a parent command for this command. - parent *Command - // Max lengths of commands' string lengths for use in padding. - commandsMaxUseLen int - commandsMaxCommandPathLen int - commandsMaxNameLen int - - // TraverseChildren parses flags on all parents before executing child command. - TraverseChildren bool - - // Hidden defines, if this command is hidden and should NOT show up in the list of available commands. - Hidden bool - - // SilenceErrors is an option to quiet errors down stream. - SilenceErrors bool - - // SilenceUsage is an option to silence usage when an error occurs. - SilenceUsage bool - - // DisableFlagParsing disables the flag parsing. - // If this is true all flags will be passed to the command as arguments. - DisableFlagParsing bool - - // DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...") - // will be printed by generating docs for this command. - DisableAutoGenTag bool - - // DisableFlagsInUseLine will disable the addition of [flags] to the usage - // line of a command when printing help or generating docs - DisableFlagsInUseLine bool - - // DisableSuggestions disables the suggestions based on Levenshtein distance - // that go along with 'unknown command' messages. - DisableSuggestions bool - - // SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions. - // Must be > 0. - SuggestionsMinimumDistance int -} - -// Context returns underlying command context. If command was executed -// with ExecuteContext or the context was set with SetContext, the -// previously set context will be returned. Otherwise, nil is returned. -// -// Notice that a call to Execute and ExecuteC will replace a nil context of -// a command with a context.Background, so a background context will be -// returned by Context after one of these functions has been called. -func (c *Command) Context() context.Context { - return c.ctx -} - -// SetContext sets context for the command. This context will be overwritten by -// Command.ExecuteContext or Command.ExecuteContextC. -func (c *Command) SetContext(ctx context.Context) { - c.ctx = ctx -} - -// SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden -// particularly useful when testing. -func (c *Command) SetArgs(a []string) { - c.args = a -} - -// SetOutput sets the destination for usage and error messages. -// If output is nil, os.Stderr is used. -// Deprecated: Use SetOut and/or SetErr instead -func (c *Command) SetOutput(output io.Writer) { - c.outWriter = output - c.errWriter = output -} - -// SetOut sets the destination for usage messages. -// If newOut is nil, os.Stdout is used. -func (c *Command) SetOut(newOut io.Writer) { - c.outWriter = newOut -} - -// SetErr sets the destination for error messages. -// If newErr is nil, os.Stderr is used. -func (c *Command) SetErr(newErr io.Writer) { - c.errWriter = newErr -} - -// SetIn sets the source for input data -// If newIn is nil, os.Stdin is used. -func (c *Command) SetIn(newIn io.Reader) { - c.inReader = newIn -} - -// SetUsageFunc sets usage function. Usage can be defined by application. -func (c *Command) SetUsageFunc(f func(*Command) error) { - c.usageFunc = f -} - -// SetUsageTemplate sets usage template. Can be defined by Application. -func (c *Command) SetUsageTemplate(s string) { - c.usageTemplate = s -} - -// SetFlagErrorFunc sets a function to generate an error when flag parsing -// fails. -func (c *Command) SetFlagErrorFunc(f func(*Command, error) error) { - c.flagErrorFunc = f -} - -// SetHelpFunc sets help function. Can be defined by Application. -func (c *Command) SetHelpFunc(f func(*Command, []string)) { - c.helpFunc = f -} - -// SetHelpCommand sets help command. -func (c *Command) SetHelpCommand(cmd *Command) { - c.helpCommand = cmd -} - -// SetHelpCommandGroupID sets the group id of the help command. -func (c *Command) SetHelpCommandGroupID(groupID string) { - if c.helpCommand != nil { - c.helpCommand.GroupID = groupID - } - // helpCommandGroupID is used if no helpCommand is defined by the user - c.helpCommandGroupID = groupID -} - -// SetCompletionCommandGroupID sets the group id of the completion command. -func (c *Command) SetCompletionCommandGroupID(groupID string) { - // completionCommandGroupID is used if no completion command is defined by the user - c.Root().completionCommandGroupID = groupID -} - -// SetHelpTemplate sets help template to be used. Application can use it to set custom template. -func (c *Command) SetHelpTemplate(s string) { - c.helpTemplate = s -} - -// SetVersionTemplate sets version template to be used. Application can use it to set custom template. -func (c *Command) SetVersionTemplate(s string) { - c.versionTemplate = s -} - -// SetErrPrefix sets error message prefix to be used. Application can use it to set custom prefix. -func (c *Command) SetErrPrefix(s string) { - c.errPrefix = s -} - -// SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands. -// The user should not have a cyclic dependency on commands. -func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) { - c.Flags().SetNormalizeFunc(n) - c.PersistentFlags().SetNormalizeFunc(n) - c.globNormFunc = n - - for _, command := range c.commands { - command.SetGlobalNormalizationFunc(n) - } -} - -// OutOrStdout returns output to stdout. -func (c *Command) OutOrStdout() io.Writer { - return c.getOut(os.Stdout) -} - -// OutOrStderr returns output to stderr -func (c *Command) OutOrStderr() io.Writer { - return c.getOut(os.Stderr) -} - -// ErrOrStderr returns output to stderr -func (c *Command) ErrOrStderr() io.Writer { - return c.getErr(os.Stderr) -} - -// InOrStdin returns input to stdin -func (c *Command) InOrStdin() io.Reader { - return c.getIn(os.Stdin) -} - -func (c *Command) getOut(def io.Writer) io.Writer { - if c.outWriter != nil { - return c.outWriter - } - if c.HasParent() { - return c.parent.getOut(def) - } - return def -} - -func (c *Command) getErr(def io.Writer) io.Writer { - if c.errWriter != nil { - return c.errWriter - } - if c.HasParent() { - return c.parent.getErr(def) - } - return def -} - -func (c *Command) getIn(def io.Reader) io.Reader { - if c.inReader != nil { - return c.inReader - } - if c.HasParent() { - return c.parent.getIn(def) - } - return def -} - -// UsageFunc returns either the function set by SetUsageFunc for this command -// or a parent, or it returns a default usage function. -func (c *Command) UsageFunc() (f func(*Command) error) { - if c.usageFunc != nil { - return c.usageFunc - } - if c.HasParent() { - return c.Parent().UsageFunc() - } - return func(c *Command) error { - c.mergePersistentFlags() - err := tmpl(c.OutOrStderr(), c.UsageTemplate(), c) - if err != nil { - c.PrintErrln(err) - } - return err - } -} - -// Usage puts out the usage for the command. -// Used when a user provides invalid input. -// Can be defined by user by overriding UsageFunc. -func (c *Command) Usage() error { - return c.UsageFunc()(c) -} - -// HelpFunc returns either the function set by SetHelpFunc for this command -// or a parent, or it returns a function with default help behavior. -func (c *Command) HelpFunc() func(*Command, []string) { - if c.helpFunc != nil { - return c.helpFunc - } - if c.HasParent() { - return c.Parent().HelpFunc() - } - return func(c *Command, a []string) { - c.mergePersistentFlags() - // The help should be sent to stdout - // See https://github.com/spf13/cobra/issues/1002 - err := tmpl(c.OutOrStdout(), c.HelpTemplate(), c) - if err != nil { - c.PrintErrln(err) - } - } -} - -// Help puts out the help for the command. -// Used when a user calls help [command]. -// Can be defined by user by overriding HelpFunc. -func (c *Command) Help() error { - c.HelpFunc()(c, []string{}) - return nil -} - -// UsageString returns usage string. -func (c *Command) UsageString() string { - // Storing normal writers - tmpOutput := c.outWriter - tmpErr := c.errWriter - - bb := new(bytes.Buffer) - c.outWriter = bb - c.errWriter = bb - - CheckErr(c.Usage()) - - // Setting things back to normal - c.outWriter = tmpOutput - c.errWriter = tmpErr - - return bb.String() -} - -// FlagErrorFunc returns either the function set by SetFlagErrorFunc for this -// command or a parent, or it returns a function which returns the original -// error. -func (c *Command) FlagErrorFunc() (f func(*Command, error) error) { - if c.flagErrorFunc != nil { - return c.flagErrorFunc - } - - if c.HasParent() { - return c.parent.FlagErrorFunc() - } - return func(c *Command, err error) error { - return err - } -} - -var minUsagePadding = 25 - -// UsagePadding return padding for the usage. -func (c *Command) UsagePadding() int { - if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen { - return minUsagePadding - } - return c.parent.commandsMaxUseLen -} - -var minCommandPathPadding = 11 - -// CommandPathPadding return padding for the command path. -func (c *Command) CommandPathPadding() int { - if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen { - return minCommandPathPadding - } - return c.parent.commandsMaxCommandPathLen -} - -var minNamePadding = 11 - -// NamePadding returns padding for the name. -func (c *Command) NamePadding() int { - if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen { - return minNamePadding - } - return c.parent.commandsMaxNameLen -} - -// UsageTemplate returns usage template for the command. -func (c *Command) UsageTemplate() string { - if c.usageTemplate != "" { - return c.usageTemplate - } - - if c.HasParent() { - return c.parent.UsageTemplate() - } - return `Usage:{{if .Runnable}} - {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}} - {{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}} - -Aliases: - {{.NameAndAliases}}{{end}}{{if .HasExample}} - -Examples: -{{.Example}}{{end}}{{if .HasAvailableSubCommands}}{{$cmds := .Commands}}{{if eq (len .Groups) 0}} - -Available Commands:{{range $cmds}}{{if (or .IsAvailableCommand (eq .Name "help"))}} - {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{else}}{{range $group := .Groups}} - -{{.Title}}{{range $cmds}}{{if (and (eq .GroupID $group.ID) (or .IsAvailableCommand (eq .Name "help")))}} - {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if not .AllChildCommandsHaveGroup}} - -Additional Commands:{{range $cmds}}{{if (and (eq .GroupID "") (or .IsAvailableCommand (eq .Name "help")))}} - {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}} - -Flags: -{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}} - -Global Flags: -{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}} - -Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}} - {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}} - -Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}} -` -} - -// HelpTemplate return help template for the command. -func (c *Command) HelpTemplate() string { - if c.helpTemplate != "" { - return c.helpTemplate - } - - if c.HasParent() { - return c.parent.HelpTemplate() - } - return `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}} - -{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}` -} - -// VersionTemplate return version template for the command. -func (c *Command) VersionTemplate() string { - if c.versionTemplate != "" { - return c.versionTemplate - } - - if c.HasParent() { - return c.parent.VersionTemplate() - } - return `{{with .Name}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}} -` -} - -// ErrPrefix return error message prefix for the command -func (c *Command) ErrPrefix() string { - if c.errPrefix != "" { - return c.errPrefix - } - - if c.HasParent() { - return c.parent.ErrPrefix() - } - return "Error:" -} - -func hasNoOptDefVal(name string, fs *flag.FlagSet) bool { - flag := fs.Lookup(name) - if flag == nil { - return false - } - return flag.NoOptDefVal != "" -} - -func shortHasNoOptDefVal(name string, fs *flag.FlagSet) bool { - if len(name) == 0 { - return false - } - - flag := fs.ShorthandLookup(name[:1]) - if flag == nil { - return false - } - return flag.NoOptDefVal != "" -} - -func stripFlags(args []string, c *Command) []string { - if len(args) == 0 { - return args - } - c.mergePersistentFlags() - - commands := []string{} - flags := c.Flags() - -Loop: - for len(args) > 0 { - s := args[0] - args = args[1:] - switch { - case s == "--": - // "--" terminates the flags - break Loop - case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags): - // If '--flag arg' then - // delete arg from args. - fallthrough // (do the same as below) - case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags): - // If '-f arg' then - // delete 'arg' from args or break the loop if len(args) <= 1. - if len(args) <= 1 { - break Loop - } else { - args = args[1:] - continue - } - case s != "" && !strings.HasPrefix(s, "-"): - commands = append(commands, s) - } - } - - return commands -} - -// argsMinusFirstX removes only the first x from args. Otherwise, commands that look like -// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]). -// Special care needs to be taken not to remove a flag value. -func (c *Command) argsMinusFirstX(args []string, x string) []string { - if len(args) == 0 { - return args - } - c.mergePersistentFlags() - flags := c.Flags() - -Loop: - for pos := 0; pos < len(args); pos++ { - s := args[pos] - switch { - case s == "--": - // -- means we have reached the end of the parseable args. Break out of the loop now. - break Loop - case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags): - fallthrough - case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags): - // This is a flag without a default value, and an equal sign is not used. Increment pos in order to skip - // over the next arg, because that is the value of this flag. - pos++ - continue - case !strings.HasPrefix(s, "-"): - // This is not a flag or a flag value. Check to see if it matches what we're looking for, and if so, - // return the args, excluding the one at this position. - if s == x { - ret := make([]string, 0, len(args)-1) - ret = append(ret, args[:pos]...) - ret = append(ret, args[pos+1:]...) - return ret - } - } - } - return args -} - -func isFlagArg(arg string) bool { - return ((len(arg) >= 3 && arg[0:2] == "--") || - (len(arg) >= 2 && arg[0] == '-' && arg[1] != '-')) -} - -// Find the target command given the args and command tree -// Meant to be run on the highest node. Only searches down. -func (c *Command) Find(args []string) (*Command, []string, error) { - var innerfind func(*Command, []string) (*Command, []string) - - innerfind = func(c *Command, innerArgs []string) (*Command, []string) { - argsWOflags := stripFlags(innerArgs, c) - if len(argsWOflags) == 0 { - return c, innerArgs - } - nextSubCmd := argsWOflags[0] - - cmd := c.findNext(nextSubCmd) - if cmd != nil { - return innerfind(cmd, c.argsMinusFirstX(innerArgs, nextSubCmd)) - } - return c, innerArgs - } - - commandFound, a := innerfind(c, args) - if commandFound.Args == nil { - return commandFound, a, legacyArgs(commandFound, stripFlags(a, commandFound)) - } - return commandFound, a, nil -} - -func (c *Command) findSuggestions(arg string) string { - if c.DisableSuggestions { - return "" - } - if c.SuggestionsMinimumDistance <= 0 { - c.SuggestionsMinimumDistance = 2 - } - var sb strings.Builder - if suggestions := c.SuggestionsFor(arg); len(suggestions) > 0 { - sb.WriteString("\n\nDid you mean this?\n") - for _, s := range suggestions { - _, _ = fmt.Fprintf(&sb, "\t%v\n", s) - } - } - return sb.String() -} - -func (c *Command) findNext(next string) *Command { - matches := make([]*Command, 0) - for _, cmd := range c.commands { - if commandNameMatches(cmd.Name(), next) || cmd.HasAlias(next) { - cmd.commandCalledAs.name = next - return cmd - } - if EnablePrefixMatching && cmd.hasNameOrAliasPrefix(next) { - matches = append(matches, cmd) - } - } - - if len(matches) == 1 { - // Temporarily disable gosec G602, which produces a false positive. - // See https://github.com/securego/gosec/issues/1005. - return matches[0] // #nosec G602 - } - - return nil -} - -// Traverse the command tree to find the command, and parse args for -// each parent. -func (c *Command) Traverse(args []string) (*Command, []string, error) { - flags := []string{} - inFlag := false - - for i, arg := range args { - switch { - // A long flag with a space separated value - case strings.HasPrefix(arg, "--") && !strings.Contains(arg, "="): - // TODO: this isn't quite right, we should really check ahead for 'true' or 'false' - inFlag = !hasNoOptDefVal(arg[2:], c.Flags()) - flags = append(flags, arg) - continue - // A short flag with a space separated value - case strings.HasPrefix(arg, "-") && !strings.Contains(arg, "=") && len(arg) == 2 && !shortHasNoOptDefVal(arg[1:], c.Flags()): - inFlag = true - flags = append(flags, arg) - continue - // The value for a flag - case inFlag: - inFlag = false - flags = append(flags, arg) - continue - // A flag without a value, or with an `=` separated value - case isFlagArg(arg): - flags = append(flags, arg) - continue - } - - cmd := c.findNext(arg) - if cmd == nil { - return c, args, nil - } - - if err := c.ParseFlags(flags); err != nil { - return nil, args, err - } - return cmd.Traverse(args[i+1:]) - } - return c, args, nil -} - -// SuggestionsFor provides suggestions for the typedName. -func (c *Command) SuggestionsFor(typedName string) []string { - suggestions := []string{} - for _, cmd := range c.commands { - if cmd.IsAvailableCommand() { - levenshteinDistance := ld(typedName, cmd.Name(), true) - suggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance - suggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName)) - if suggestByLevenshtein || suggestByPrefix { - suggestions = append(suggestions, cmd.Name()) - } - for _, explicitSuggestion := range cmd.SuggestFor { - if strings.EqualFold(typedName, explicitSuggestion) { - suggestions = append(suggestions, cmd.Name()) - } - } - } - } - return suggestions -} - -// VisitParents visits all parents of the command and invokes fn on each parent. -func (c *Command) VisitParents(fn func(*Command)) { - if c.HasParent() { - fn(c.Parent()) - c.Parent().VisitParents(fn) - } -} - -// Root finds root command. -func (c *Command) Root() *Command { - if c.HasParent() { - return c.Parent().Root() - } - return c -} - -// ArgsLenAtDash will return the length of c.Flags().Args at the moment -// when a -- was found during args parsing. -func (c *Command) ArgsLenAtDash() int { - return c.Flags().ArgsLenAtDash() -} - -func (c *Command) execute(a []string) (err error) { - if c == nil { - return fmt.Errorf("called Execute() on a nil Command") - } - - if len(c.Deprecated) > 0 { - c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated) - } - - // initialize help and version flag at the last point possible to allow for user - // overriding - c.InitDefaultHelpFlag() - c.InitDefaultVersionFlag() - - err = c.ParseFlags(a) - if err != nil { - return c.FlagErrorFunc()(c, err) - } - - // If help is called, regardless of other flags, return we want help. - // Also say we need help if the command isn't runnable. - helpVal, err := c.Flags().GetBool("help") - if err != nil { - // should be impossible to get here as we always declare a help - // flag in InitDefaultHelpFlag() - c.Println("\"help\" flag declared as non-bool. Please correct your code") - return err - } - - if helpVal { - return flag.ErrHelp - } - - // for back-compat, only add version flag behavior if version is defined - if c.Version != "" { - versionVal, err := c.Flags().GetBool("version") - if err != nil { - c.Println("\"version\" flag declared as non-bool. Please correct your code") - return err - } - if versionVal { - err := tmpl(c.OutOrStdout(), c.VersionTemplate(), c) - if err != nil { - c.Println(err) - } - return err - } - } - - if !c.Runnable() { - return flag.ErrHelp - } - - c.preRun() - - defer c.postRun() - - argWoFlags := c.Flags().Args() - if c.DisableFlagParsing { - argWoFlags = a - } - - if err := c.ValidateArgs(argWoFlags); err != nil { - return err - } - - parents := make([]*Command, 0, 5) - for p := c; p != nil; p = p.Parent() { - if EnableTraverseRunHooks { - // When EnableTraverseRunHooks is set: - // - Execute all persistent pre-runs from the root parent till this command. - // - Execute all persistent post-runs from this command till the root parent. - parents = append([]*Command{p}, parents...) - } else { - // Otherwise, execute only the first found persistent hook. - parents = append(parents, p) - } - } - for _, p := range parents { - if p.PersistentPreRunE != nil { - if err := p.PersistentPreRunE(c, argWoFlags); err != nil { - return err - } - if !EnableTraverseRunHooks { - break - } - } else if p.PersistentPreRun != nil { - p.PersistentPreRun(c, argWoFlags) - if !EnableTraverseRunHooks { - break - } - } - } - if c.PreRunE != nil { - if err := c.PreRunE(c, argWoFlags); err != nil { - return err - } - } else if c.PreRun != nil { - c.PreRun(c, argWoFlags) - } - - if err := c.ValidateRequiredFlags(); err != nil { - return err - } - if err := c.ValidateFlagGroups(); err != nil { - return err - } - - if c.RunE != nil { - if err := c.RunE(c, argWoFlags); err != nil { - return err - } - } else { - c.Run(c, argWoFlags) - } - if c.PostRunE != nil { - if err := c.PostRunE(c, argWoFlags); err != nil { - return err - } - } else if c.PostRun != nil { - c.PostRun(c, argWoFlags) - } - for p := c; p != nil; p = p.Parent() { - if p.PersistentPostRunE != nil { - if err := p.PersistentPostRunE(c, argWoFlags); err != nil { - return err - } - if !EnableTraverseRunHooks { - break - } - } else if p.PersistentPostRun != nil { - p.PersistentPostRun(c, argWoFlags) - if !EnableTraverseRunHooks { - break - } - } - } - - return nil -} - -func (c *Command) preRun() { - for _, x := range initializers { - x() - } -} - -func (c *Command) postRun() { - for _, x := range finalizers { - x() - } -} - -// ExecuteContext is the same as Execute(), but sets the ctx on the command. -// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs -// functions. -func (c *Command) ExecuteContext(ctx context.Context) error { - c.ctx = ctx - return c.Execute() -} - -// Execute uses the args (os.Args[1:] by default) -// and run through the command tree finding appropriate matches -// for commands and then corresponding flags. -func (c *Command) Execute() error { - _, err := c.ExecuteC() - return err -} - -// ExecuteContextC is the same as ExecuteC(), but sets the ctx on the command. -// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs -// functions. -func (c *Command) ExecuteContextC(ctx context.Context) (*Command, error) { - c.ctx = ctx - return c.ExecuteC() -} - -// ExecuteC executes the command. -func (c *Command) ExecuteC() (cmd *Command, err error) { - if c.ctx == nil { - c.ctx = context.Background() - } - - // Regardless of what command execute is called on, run on Root only - if c.HasParent() { - return c.Root().ExecuteC() - } - - // windows hook - if preExecHookFn != nil { - preExecHookFn(c) - } - - // initialize help at the last point to allow for user overriding - c.InitDefaultHelpCmd() - // initialize completion at the last point to allow for user overriding - c.InitDefaultCompletionCmd() - - // Now that all commands have been created, let's make sure all groups - // are properly created also - c.checkCommandGroups() - - args := c.args - - // Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155 - if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" { - args = os.Args[1:] - } - - // initialize the hidden command to be used for shell completion - c.initCompleteCmd(args) - - var flags []string - if c.TraverseChildren { - cmd, flags, err = c.Traverse(args) - } else { - cmd, flags, err = c.Find(args) - } - if err != nil { - // If found parse to a subcommand and then failed, talk about the subcommand - if cmd != nil { - c = cmd - } - if !c.SilenceErrors { - c.PrintErrln(c.ErrPrefix(), err.Error()) - c.PrintErrf("Run '%v --help' for usage.\n", c.CommandPath()) - } - return c, err - } - - cmd.commandCalledAs.called = true - if cmd.commandCalledAs.name == "" { - cmd.commandCalledAs.name = cmd.Name() - } - - // We have to pass global context to children command - // if context is present on the parent command. - if cmd.ctx == nil { - cmd.ctx = c.ctx - } - - err = cmd.execute(flags) - if err != nil { - // Always show help if requested, even if SilenceErrors is in - // effect - if errors.Is(err, flag.ErrHelp) { - cmd.HelpFunc()(cmd, args) - return cmd, nil - } - - // If root command has SilenceErrors flagged, - // all subcommands should respect it - if !cmd.SilenceErrors && !c.SilenceErrors { - c.PrintErrln(cmd.ErrPrefix(), err.Error()) - } - - // If root command has SilenceUsage flagged, - // all subcommands should respect it - if !cmd.SilenceUsage && !c.SilenceUsage { - c.Println(cmd.UsageString()) - } - } - return cmd, err -} - -func (c *Command) ValidateArgs(args []string) error { - if c.Args == nil { - return ArbitraryArgs(c, args) - } - return c.Args(c, args) -} - -// ValidateRequiredFlags validates all required flags are present and returns an error otherwise -func (c *Command) ValidateRequiredFlags() error { - if c.DisableFlagParsing { - return nil - } - - flags := c.Flags() - missingFlagNames := []string{} - flags.VisitAll(func(pflag *flag.Flag) { - requiredAnnotation, found := pflag.Annotations[BashCompOneRequiredFlag] - if !found { - return - } - if (requiredAnnotation[0] == "true") && !pflag.Changed { - missingFlagNames = append(missingFlagNames, pflag.Name) - } - }) - - if len(missingFlagNames) > 0 { - return fmt.Errorf(`required flag(s) "%s" not set`, strings.Join(missingFlagNames, `", "`)) - } - return nil -} - -// checkCommandGroups checks if a command has been added to a group that does not exists. -// If so, we panic because it indicates a coding error that should be corrected. -func (c *Command) checkCommandGroups() { - for _, sub := range c.commands { - // if Group is not defined let the developer know right away - if sub.GroupID != "" && !c.ContainsGroup(sub.GroupID) { - panic(fmt.Sprintf("group id '%s' is not defined for subcommand '%s'", sub.GroupID, sub.CommandPath())) - } - - sub.checkCommandGroups() - } -} - -// InitDefaultHelpFlag adds default help flag to c. -// It is called automatically by executing the c or by calling help and usage. -// If c already has help flag, it will do nothing. -func (c *Command) InitDefaultHelpFlag() { - c.mergePersistentFlags() - if c.Flags().Lookup("help") == nil { - usage := "help for " - name := c.displayName() - if name == "" { - usage += "this command" - } else { - usage += name - } - c.Flags().BoolP("help", "h", false, usage) - _ = c.Flags().SetAnnotation("help", FlagSetByCobraAnnotation, []string{"true"}) - } -} - -// InitDefaultVersionFlag adds default version flag to c. -// It is called automatically by executing the c. -// If c already has a version flag, it will do nothing. -// If c.Version is empty, it will do nothing. -func (c *Command) InitDefaultVersionFlag() { - if c.Version == "" { - return - } - - c.mergePersistentFlags() - if c.Flags().Lookup("version") == nil { - usage := "version for " - if c.Name() == "" { - usage += "this command" - } else { - usage += c.Name() - } - if c.Flags().ShorthandLookup("v") == nil { - c.Flags().BoolP("version", "v", false, usage) - } else { - c.Flags().Bool("version", false, usage) - } - _ = c.Flags().SetAnnotation("version", FlagSetByCobraAnnotation, []string{"true"}) - } -} - -// InitDefaultHelpCmd adds default help command to c. -// It is called automatically by executing the c or by calling help and usage. -// If c already has help command or c has no subcommands, it will do nothing. -func (c *Command) InitDefaultHelpCmd() { - if !c.HasSubCommands() { - return - } - - if c.helpCommand == nil { - c.helpCommand = &Command{ - Use: "help [command]", - Short: "Help about any command", - Long: `Help provides help for any command in the application. -Simply type ` + c.displayName() + ` help [path to command] for full details.`, - ValidArgsFunction: func(c *Command, args []string, toComplete string) ([]string, ShellCompDirective) { - var completions []string - cmd, _, e := c.Root().Find(args) - if e != nil { - return nil, ShellCompDirectiveNoFileComp - } - if cmd == nil { - // Root help command. - cmd = c.Root() - } - for _, subCmd := range cmd.Commands() { - if subCmd.IsAvailableCommand() || subCmd == cmd.helpCommand { - if strings.HasPrefix(subCmd.Name(), toComplete) { - completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short)) - } - } - } - return completions, ShellCompDirectiveNoFileComp - }, - Run: func(c *Command, args []string) { - cmd, _, e := c.Root().Find(args) - if cmd == nil || e != nil { - c.Printf("Unknown help topic %#q\n", args) - CheckErr(c.Root().Usage()) - } else { - cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown - cmd.InitDefaultVersionFlag() // make possible 'version' flag to be shown - CheckErr(cmd.Help()) - } - }, - GroupID: c.helpCommandGroupID, - } - } - c.RemoveCommand(c.helpCommand) - c.AddCommand(c.helpCommand) -} - -// ResetCommands delete parent, subcommand and help command from c. -func (c *Command) ResetCommands() { - c.parent = nil - c.commands = nil - c.helpCommand = nil - c.parentsPflags = nil -} - -// Sorts commands by their names. -type commandSorterByName []*Command - -func (c commandSorterByName) Len() int { return len(c) } -func (c commandSorterByName) Swap(i, j int) { c[i], c[j] = c[j], c[i] } -func (c commandSorterByName) Less(i, j int) bool { return c[i].Name() < c[j].Name() } - -// Commands returns a sorted slice of child commands. -func (c *Command) Commands() []*Command { - // do not sort commands if it already sorted or sorting was disabled - if EnableCommandSorting && !c.commandsAreSorted { - sort.Sort(commandSorterByName(c.commands)) - c.commandsAreSorted = true - } - return c.commands -} - -// AddCommand adds one or more commands to this parent command. -func (c *Command) AddCommand(cmds ...*Command) { - for i, x := range cmds { - if cmds[i] == c { - panic("Command can't be a child of itself") - } - cmds[i].parent = c - // update max lengths - usageLen := len(x.Use) - if usageLen > c.commandsMaxUseLen { - c.commandsMaxUseLen = usageLen - } - commandPathLen := len(x.CommandPath()) - if commandPathLen > c.commandsMaxCommandPathLen { - c.commandsMaxCommandPathLen = commandPathLen - } - nameLen := len(x.Name()) - if nameLen > c.commandsMaxNameLen { - c.commandsMaxNameLen = nameLen - } - // If global normalization function exists, update all children - if c.globNormFunc != nil { - x.SetGlobalNormalizationFunc(c.globNormFunc) - } - c.commands = append(c.commands, x) - c.commandsAreSorted = false - } -} - -// Groups returns a slice of child command groups. -func (c *Command) Groups() []*Group { - return c.commandgroups -} - -// AllChildCommandsHaveGroup returns if all subcommands are assigned to a group -func (c *Command) AllChildCommandsHaveGroup() bool { - for _, sub := range c.commands { - if (sub.IsAvailableCommand() || sub == c.helpCommand) && sub.GroupID == "" { - return false - } - } - return true -} - -// ContainsGroup return if groupID exists in the list of command groups. -func (c *Command) ContainsGroup(groupID string) bool { - for _, x := range c.commandgroups { - if x.ID == groupID { - return true - } - } - return false -} - -// AddGroup adds one or more command groups to this parent command. -func (c *Command) AddGroup(groups ...*Group) { - c.commandgroups = append(c.commandgroups, groups...) -} - -// RemoveCommand removes one or more commands from a parent command. -func (c *Command) RemoveCommand(cmds ...*Command) { - commands := []*Command{} -main: - for _, command := range c.commands { - for _, cmd := range cmds { - if command == cmd { - command.parent = nil - continue main - } - } - commands = append(commands, command) - } - c.commands = commands - // recompute all lengths - c.commandsMaxUseLen = 0 - c.commandsMaxCommandPathLen = 0 - c.commandsMaxNameLen = 0 - for _, command := range c.commands { - usageLen := len(command.Use) - if usageLen > c.commandsMaxUseLen { - c.commandsMaxUseLen = usageLen - } - commandPathLen := len(command.CommandPath()) - if commandPathLen > c.commandsMaxCommandPathLen { - c.commandsMaxCommandPathLen = commandPathLen - } - nameLen := len(command.Name()) - if nameLen > c.commandsMaxNameLen { - c.commandsMaxNameLen = nameLen - } - } -} - -// Print is a convenience method to Print to the defined output, fallback to Stderr if not set. -func (c *Command) Print(i ...interface{}) { - fmt.Fprint(c.OutOrStderr(), i...) -} - -// Println is a convenience method to Println to the defined output, fallback to Stderr if not set. -func (c *Command) Println(i ...interface{}) { - c.Print(fmt.Sprintln(i...)) -} - -// Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set. -func (c *Command) Printf(format string, i ...interface{}) { - c.Print(fmt.Sprintf(format, i...)) -} - -// PrintErr is a convenience method to Print to the defined Err output, fallback to Stderr if not set. -func (c *Command) PrintErr(i ...interface{}) { - fmt.Fprint(c.ErrOrStderr(), i...) -} - -// PrintErrln is a convenience method to Println to the defined Err output, fallback to Stderr if not set. -func (c *Command) PrintErrln(i ...interface{}) { - c.PrintErr(fmt.Sprintln(i...)) -} - -// PrintErrf is a convenience method to Printf to the defined Err output, fallback to Stderr if not set. -func (c *Command) PrintErrf(format string, i ...interface{}) { - c.PrintErr(fmt.Sprintf(format, i...)) -} - -// CommandPath returns the full path to this command. -func (c *Command) CommandPath() string { - if c.HasParent() { - return c.Parent().CommandPath() + " " + c.Name() - } - return c.displayName() -} - -func (c *Command) displayName() string { - if displayName, ok := c.Annotations[CommandDisplayNameAnnotation]; ok { - return displayName - } - return c.Name() -} - -// UseLine puts out the full usage for a given command (including parents). -func (c *Command) UseLine() string { - var useline string - use := strings.Replace(c.Use, c.Name(), c.displayName(), 1) - if c.HasParent() { - useline = c.parent.CommandPath() + " " + use - } else { - useline = use - } - if c.DisableFlagsInUseLine { - return useline - } - if c.HasAvailableFlags() && !strings.Contains(useline, "[flags]") { - useline += " [flags]" - } - return useline -} - -// DebugFlags used to determine which flags have been assigned to which commands -// and which persist. -func (c *Command) DebugFlags() { - c.Println("DebugFlags called on", c.Name()) - var debugflags func(*Command) - - debugflags = func(x *Command) { - if x.HasFlags() || x.HasPersistentFlags() { - c.Println(x.Name()) - } - if x.HasFlags() { - x.flags.VisitAll(func(f *flag.Flag) { - if x.HasPersistentFlags() && x.persistentFlag(f.Name) != nil { - c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]") - } else { - c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]") - } - }) - } - if x.HasPersistentFlags() { - x.pflags.VisitAll(func(f *flag.Flag) { - if x.HasFlags() { - if x.flags.Lookup(f.Name) == nil { - c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]") - } - } else { - c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]") - } - }) - } - c.Println(x.flagErrorBuf) - if x.HasSubCommands() { - for _, y := range x.commands { - debugflags(y) - } - } - } - - debugflags(c) -} - -// Name returns the command's name: the first word in the use line. -func (c *Command) Name() string { - name := c.Use - i := strings.Index(name, " ") - if i >= 0 { - name = name[:i] - } - return name -} - -// HasAlias determines if a given string is an alias of the command. -func (c *Command) HasAlias(s string) bool { - for _, a := range c.Aliases { - if commandNameMatches(a, s) { - return true - } - } - return false -} - -// CalledAs returns the command name or alias that was used to invoke -// this command or an empty string if the command has not been called. -func (c *Command) CalledAs() string { - if c.commandCalledAs.called { - return c.commandCalledAs.name - } - return "" -} - -// hasNameOrAliasPrefix returns true if the Name or any of aliases start -// with prefix -func (c *Command) hasNameOrAliasPrefix(prefix string) bool { - if strings.HasPrefix(c.Name(), prefix) { - c.commandCalledAs.name = c.Name() - return true - } - for _, alias := range c.Aliases { - if strings.HasPrefix(alias, prefix) { - c.commandCalledAs.name = alias - return true - } - } - return false -} - -// NameAndAliases returns a list of the command name and all aliases -func (c *Command) NameAndAliases() string { - return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ") -} - -// HasExample determines if the command has example. -func (c *Command) HasExample() bool { - return len(c.Example) > 0 -} - -// Runnable determines if the command is itself runnable. -func (c *Command) Runnable() bool { - return c.Run != nil || c.RunE != nil -} - -// HasSubCommands determines if the command has children commands. -func (c *Command) HasSubCommands() bool { - return len(c.commands) > 0 -} - -// IsAvailableCommand determines if a command is available as a non-help command -// (this includes all non deprecated/hidden commands). -func (c *Command) IsAvailableCommand() bool { - if len(c.Deprecated) != 0 || c.Hidden { - return false - } - - if c.HasParent() && c.Parent().helpCommand == c { - return false - } - - if c.Runnable() || c.HasAvailableSubCommands() { - return true - } - - return false -} - -// IsAdditionalHelpTopicCommand determines if a command is an additional -// help topic command; additional help topic command is determined by the -// fact that it is NOT runnable/hidden/deprecated, and has no sub commands that -// are runnable/hidden/deprecated. -// Concrete example: https://github.com/spf13/cobra/issues/393#issuecomment-282741924. -func (c *Command) IsAdditionalHelpTopicCommand() bool { - // if a command is runnable, deprecated, or hidden it is not a 'help' command - if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden { - return false - } - - // if any non-help sub commands are found, the command is not a 'help' command - for _, sub := range c.commands { - if !sub.IsAdditionalHelpTopicCommand() { - return false - } - } - - // the command either has no sub commands, or no non-help sub commands - return true -} - -// HasHelpSubCommands determines if a command has any available 'help' sub commands -// that need to be shown in the usage/help default template under 'additional help -// topics'. -func (c *Command) HasHelpSubCommands() bool { - // return true on the first found available 'help' sub command - for _, sub := range c.commands { - if sub.IsAdditionalHelpTopicCommand() { - return true - } - } - - // the command either has no sub commands, or no available 'help' sub commands - return false -} - -// HasAvailableSubCommands determines if a command has available sub commands that -// need to be shown in the usage/help default template under 'available commands'. -func (c *Command) HasAvailableSubCommands() bool { - // return true on the first found available (non deprecated/help/hidden) - // sub command - for _, sub := range c.commands { - if sub.IsAvailableCommand() { - return true - } - } - - // the command either has no sub commands, or no available (non deprecated/help/hidden) - // sub commands - return false -} - -// HasParent determines if the command is a child command. -func (c *Command) HasParent() bool { - return c.parent != nil -} - -// GlobalNormalizationFunc returns the global normalization function or nil if it doesn't exist. -func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName { - return c.globNormFunc -} - -// Flags returns the complete FlagSet that applies -// to this command (local and persistent declared here and by all parents). -func (c *Command) Flags() *flag.FlagSet { - if c.flags == nil { - c.flags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError) - if c.flagErrorBuf == nil { - c.flagErrorBuf = new(bytes.Buffer) - } - c.flags.SetOutput(c.flagErrorBuf) - } - - return c.flags -} - -// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands. -// This function does not modify the flags of the current command, it's purpose is to return the current state. -func (c *Command) LocalNonPersistentFlags() *flag.FlagSet { - persistentFlags := c.PersistentFlags() - - out := flag.NewFlagSet(c.displayName(), flag.ContinueOnError) - c.LocalFlags().VisitAll(func(f *flag.Flag) { - if persistentFlags.Lookup(f.Name) == nil { - out.AddFlag(f) - } - }) - return out -} - -// LocalFlags returns the local FlagSet specifically set in the current command. -// This function does not modify the flags of the current command, it's purpose is to return the current state. -func (c *Command) LocalFlags() *flag.FlagSet { - c.mergePersistentFlags() - - if c.lflags == nil { - c.lflags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError) - if c.flagErrorBuf == nil { - c.flagErrorBuf = new(bytes.Buffer) - } - c.lflags.SetOutput(c.flagErrorBuf) - } - c.lflags.SortFlags = c.Flags().SortFlags - if c.globNormFunc != nil { - c.lflags.SetNormalizeFunc(c.globNormFunc) - } - - addToLocal := func(f *flag.Flag) { - // Add the flag if it is not a parent PFlag, or it shadows a parent PFlag - if c.lflags.Lookup(f.Name) == nil && f != c.parentsPflags.Lookup(f.Name) { - c.lflags.AddFlag(f) - } - } - c.Flags().VisitAll(addToLocal) - c.PersistentFlags().VisitAll(addToLocal) - return c.lflags -} - -// InheritedFlags returns all flags which were inherited from parent commands. -// This function does not modify the flags of the current command, it's purpose is to return the current state. -func (c *Command) InheritedFlags() *flag.FlagSet { - c.mergePersistentFlags() - - if c.iflags == nil { - c.iflags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError) - if c.flagErrorBuf == nil { - c.flagErrorBuf = new(bytes.Buffer) - } - c.iflags.SetOutput(c.flagErrorBuf) - } - - local := c.LocalFlags() - if c.globNormFunc != nil { - c.iflags.SetNormalizeFunc(c.globNormFunc) - } - - c.parentsPflags.VisitAll(func(f *flag.Flag) { - if c.iflags.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil { - c.iflags.AddFlag(f) - } - }) - return c.iflags -} - -// NonInheritedFlags returns all flags which were not inherited from parent commands. -// This function does not modify the flags of the current command, it's purpose is to return the current state. -func (c *Command) NonInheritedFlags() *flag.FlagSet { - return c.LocalFlags() -} - -// PersistentFlags returns the persistent FlagSet specifically set in the current command. -func (c *Command) PersistentFlags() *flag.FlagSet { - if c.pflags == nil { - c.pflags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError) - if c.flagErrorBuf == nil { - c.flagErrorBuf = new(bytes.Buffer) - } - c.pflags.SetOutput(c.flagErrorBuf) - } - return c.pflags -} - -// ResetFlags deletes all flags from command. -func (c *Command) ResetFlags() { - c.flagErrorBuf = new(bytes.Buffer) - c.flagErrorBuf.Reset() - c.flags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError) - c.flags.SetOutput(c.flagErrorBuf) - c.pflags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError) - c.pflags.SetOutput(c.flagErrorBuf) - - c.lflags = nil - c.iflags = nil - c.parentsPflags = nil -} - -// HasFlags checks if the command contains any flags (local plus persistent from the entire structure). -func (c *Command) HasFlags() bool { - return c.Flags().HasFlags() -} - -// HasPersistentFlags checks if the command contains persistent flags. -func (c *Command) HasPersistentFlags() bool { - return c.PersistentFlags().HasFlags() -} - -// HasLocalFlags checks if the command has flags specifically declared locally. -func (c *Command) HasLocalFlags() bool { - return c.LocalFlags().HasFlags() -} - -// HasInheritedFlags checks if the command has flags inherited from its parent command. -func (c *Command) HasInheritedFlags() bool { - return c.InheritedFlags().HasFlags() -} - -// HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire -// structure) which are not hidden or deprecated. -func (c *Command) HasAvailableFlags() bool { - return c.Flags().HasAvailableFlags() -} - -// HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated. -func (c *Command) HasAvailablePersistentFlags() bool { - return c.PersistentFlags().HasAvailableFlags() -} - -// HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden -// or deprecated. -func (c *Command) HasAvailableLocalFlags() bool { - return c.LocalFlags().HasAvailableFlags() -} - -// HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which are -// not hidden or deprecated. -func (c *Command) HasAvailableInheritedFlags() bool { - return c.InheritedFlags().HasAvailableFlags() -} - -// Flag climbs up the command tree looking for matching flag. -func (c *Command) Flag(name string) (flag *flag.Flag) { - flag = c.Flags().Lookup(name) - - if flag == nil { - flag = c.persistentFlag(name) - } - - return -} - -// Recursively find matching persistent flag. -func (c *Command) persistentFlag(name string) (flag *flag.Flag) { - if c.HasPersistentFlags() { - flag = c.PersistentFlags().Lookup(name) - } - - if flag == nil { - c.updateParentsPflags() - flag = c.parentsPflags.Lookup(name) - } - return -} - -// ParseFlags parses persistent flag tree and local flags. -func (c *Command) ParseFlags(args []string) error { - if c.DisableFlagParsing { - return nil - } - - if c.flagErrorBuf == nil { - c.flagErrorBuf = new(bytes.Buffer) - } - beforeErrorBufLen := c.flagErrorBuf.Len() - c.mergePersistentFlags() - - // do it here after merging all flags and just before parse - c.Flags().ParseErrorsWhitelist = flag.ParseErrorsWhitelist(c.FParseErrWhitelist) - - err := c.Flags().Parse(args) - // Print warnings if they occurred (e.g. deprecated flag messages). - if c.flagErrorBuf.Len()-beforeErrorBufLen > 0 && err == nil { - c.Print(c.flagErrorBuf.String()) - } - - return err -} - -// Parent returns a commands parent command. -func (c *Command) Parent() *Command { - return c.parent -} - -// mergePersistentFlags merges c.PersistentFlags() to c.Flags() -// and adds missing persistent flags of all parents. -func (c *Command) mergePersistentFlags() { - c.updateParentsPflags() - c.Flags().AddFlagSet(c.PersistentFlags()) - c.Flags().AddFlagSet(c.parentsPflags) -} - -// updateParentsPflags updates c.parentsPflags by adding -// new persistent flags of all parents. -// If c.parentsPflags == nil, it makes new. -func (c *Command) updateParentsPflags() { - if c.parentsPflags == nil { - c.parentsPflags = flag.NewFlagSet(c.displayName(), flag.ContinueOnError) - c.parentsPflags.SetOutput(c.flagErrorBuf) - c.parentsPflags.SortFlags = false - } - - if c.globNormFunc != nil { - c.parentsPflags.SetNormalizeFunc(c.globNormFunc) - } - - c.Root().PersistentFlags().AddFlagSet(flag.CommandLine) - - c.VisitParents(func(parent *Command) { - c.parentsPflags.AddFlagSet(parent.PersistentFlags()) - }) -} - -// commandNameMatches checks if two command names are equal -// taking into account case sensitivity according to -// EnableCaseInsensitive global configuration. -func commandNameMatches(s string, t string) bool { - if EnableCaseInsensitive { - return strings.EqualFold(s, t) - } - - return s == t -} diff --git a/vendor/github.com/spf13/cobra/command_notwin.go b/vendor/github.com/spf13/cobra/command_notwin.go deleted file mode 100644 index 307f0c127..000000000 --- a/vendor/github.com/spf13/cobra/command_notwin.go +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2013-2023 The Cobra 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. - -//go:build !windows -// +build !windows - -package cobra - -var preExecHookFn func(*Command) diff --git a/vendor/github.com/spf13/cobra/command_win.go b/vendor/github.com/spf13/cobra/command_win.go deleted file mode 100644 index adbef395c..000000000 --- a/vendor/github.com/spf13/cobra/command_win.go +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2013-2023 The Cobra 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. - -//go:build windows -// +build windows - -package cobra - -import ( - "fmt" - "os" - "time" - - "github.com/inconshreveable/mousetrap" -) - -var preExecHookFn = preExecHook - -func preExecHook(c *Command) { - if MousetrapHelpText != "" && mousetrap.StartedByExplorer() { - c.Print(MousetrapHelpText) - if MousetrapDisplayDuration > 0 { - time.Sleep(MousetrapDisplayDuration) - } else { - c.Println("Press return to continue...") - fmt.Scanln() - } - os.Exit(1) - } -} diff --git a/vendor/github.com/spf13/cobra/completions.go b/vendor/github.com/spf13/cobra/completions.go deleted file mode 100644 index c0c08b057..000000000 --- a/vendor/github.com/spf13/cobra/completions.go +++ /dev/null @@ -1,939 +0,0 @@ -// Copyright 2013-2023 The Cobra 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 cobra - -import ( - "fmt" - "os" - "regexp" - "strconv" - "strings" - "sync" - - "github.com/spf13/pflag" -) - -const ( - // ShellCompRequestCmd is the name of the hidden command that is used to request - // completion results from the program. It is used by the shell completion scripts. - ShellCompRequestCmd = "__complete" - // ShellCompNoDescRequestCmd is the name of the hidden command that is used to request - // completion results without their description. It is used by the shell completion scripts. - ShellCompNoDescRequestCmd = "__completeNoDesc" -) - -// Global map of flag completion functions. Make sure to use flagCompletionMutex before you try to read and write from it. -var flagCompletionFunctions = map[*pflag.Flag]func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective){} - -// lock for reading and writing from flagCompletionFunctions -var flagCompletionMutex = &sync.RWMutex{} - -// ShellCompDirective is a bit map representing the different behaviors the shell -// can be instructed to have once completions have been provided. -type ShellCompDirective int - -type flagCompError struct { - subCommand string - flagName string -} - -func (e *flagCompError) Error() string { - return "Subcommand '" + e.subCommand + "' does not support flag '" + e.flagName + "'" -} - -const ( - // ShellCompDirectiveError indicates an error occurred and completions should be ignored. - ShellCompDirectiveError ShellCompDirective = 1 << iota - - // ShellCompDirectiveNoSpace indicates that the shell should not add a space - // after the completion even if there is a single completion provided. - ShellCompDirectiveNoSpace - - // ShellCompDirectiveNoFileComp indicates that the shell should not provide - // file completion even when no completion is provided. - ShellCompDirectiveNoFileComp - - // ShellCompDirectiveFilterFileExt indicates that the provided completions - // should be used as file extension filters. - // For flags, using Command.MarkFlagFilename() and Command.MarkPersistentFlagFilename() - // is a shortcut to using this directive explicitly. The BashCompFilenameExt - // annotation can also be used to obtain the same behavior for flags. - ShellCompDirectiveFilterFileExt - - // ShellCompDirectiveFilterDirs indicates that only directory names should - // be provided in file completion. To request directory names within another - // directory, the returned completions should specify the directory within - // which to search. The BashCompSubdirsInDir annotation can be used to - // obtain the same behavior but only for flags. - ShellCompDirectiveFilterDirs - - // ShellCompDirectiveKeepOrder indicates that the shell should preserve the order - // in which the completions are provided - ShellCompDirectiveKeepOrder - - // =========================================================================== - - // All directives using iota should be above this one. - // For internal use. - shellCompDirectiveMaxValue - - // ShellCompDirectiveDefault indicates to let the shell perform its default - // behavior after completions have been provided. - // This one must be last to avoid messing up the iota count. - ShellCompDirectiveDefault ShellCompDirective = 0 -) - -const ( - // Constants for the completion command - compCmdName = "completion" - compCmdNoDescFlagName = "no-descriptions" - compCmdNoDescFlagDesc = "disable completion descriptions" - compCmdNoDescFlagDefault = false -) - -// CompletionOptions are the options to control shell completion -type CompletionOptions struct { - // DisableDefaultCmd prevents Cobra from creating a default 'completion' command - DisableDefaultCmd bool - // DisableNoDescFlag prevents Cobra from creating the '--no-descriptions' flag - // for shells that support completion descriptions - DisableNoDescFlag bool - // DisableDescriptions turns off all completion descriptions for shells - // that support them - DisableDescriptions bool - // HiddenDefaultCmd makes the default 'completion' command hidden - HiddenDefaultCmd bool -} - -// NoFileCompletions can be used to disable file completion for commands that should -// not trigger file completions. -func NoFileCompletions(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) { - return nil, ShellCompDirectiveNoFileComp -} - -// FixedCompletions can be used to create a completion function which always -// returns the same results. -func FixedCompletions(choices []string, directive ShellCompDirective) func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) { - return func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) { - return choices, directive - } -} - -// RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag. -func (c *Command) RegisterFlagCompletionFunc(flagName string, f func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)) error { - flag := c.Flag(flagName) - if flag == nil { - return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' does not exist", flagName) - } - flagCompletionMutex.Lock() - defer flagCompletionMutex.Unlock() - - if _, exists := flagCompletionFunctions[flag]; exists { - return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' already registered", flagName) - } - flagCompletionFunctions[flag] = f - return nil -} - -// GetFlagCompletionFunc returns the completion function for the given flag of the command, if available. -func (c *Command) GetFlagCompletionFunc(flagName string) (func(*Command, []string, string) ([]string, ShellCompDirective), bool) { - flag := c.Flag(flagName) - if flag == nil { - return nil, false - } - - flagCompletionMutex.RLock() - defer flagCompletionMutex.RUnlock() - - completionFunc, exists := flagCompletionFunctions[flag] - return completionFunc, exists -} - -// Returns a string listing the different directive enabled in the specified parameter -func (d ShellCompDirective) string() string { - var directives []string - if d&ShellCompDirectiveError != 0 { - directives = append(directives, "ShellCompDirectiveError") - } - if d&ShellCompDirectiveNoSpace != 0 { - directives = append(directives, "ShellCompDirectiveNoSpace") - } - if d&ShellCompDirectiveNoFileComp != 0 { - directives = append(directives, "ShellCompDirectiveNoFileComp") - } - if d&ShellCompDirectiveFilterFileExt != 0 { - directives = append(directives, "ShellCompDirectiveFilterFileExt") - } - if d&ShellCompDirectiveFilterDirs != 0 { - directives = append(directives, "ShellCompDirectiveFilterDirs") - } - if d&ShellCompDirectiveKeepOrder != 0 { - directives = append(directives, "ShellCompDirectiveKeepOrder") - } - if len(directives) == 0 { - directives = append(directives, "ShellCompDirectiveDefault") - } - - if d >= shellCompDirectiveMaxValue { - return fmt.Sprintf("ERROR: unexpected ShellCompDirective value: %d", d) - } - return strings.Join(directives, ", ") -} - -// initCompleteCmd adds a special hidden command that can be used to request custom completions. -func (c *Command) initCompleteCmd(args []string) { - completeCmd := &Command{ - Use: fmt.Sprintf("%s [command-line]", ShellCompRequestCmd), - Aliases: []string{ShellCompNoDescRequestCmd}, - DisableFlagsInUseLine: true, - Hidden: true, - DisableFlagParsing: true, - Args: MinimumNArgs(1), - Short: "Request shell completion choices for the specified command-line", - Long: fmt.Sprintf("%[2]s is a special command that is used by the shell completion logic\n%[1]s", - "to request completion choices for the specified command-line.", ShellCompRequestCmd), - Run: func(cmd *Command, args []string) { - finalCmd, completions, directive, err := cmd.getCompletions(args) - if err != nil { - CompErrorln(err.Error()) - // Keep going for multiple reasons: - // 1- There could be some valid completions even though there was an error - // 2- Even without completions, we need to print the directive - } - - noDescriptions := cmd.CalledAs() == ShellCompNoDescRequestCmd - if !noDescriptions { - if doDescriptions, err := strconv.ParseBool(getEnvConfig(cmd, configEnvVarSuffixDescriptions)); err == nil { - noDescriptions = !doDescriptions - } - } - noActiveHelp := GetActiveHelpConfig(finalCmd) == activeHelpGlobalDisable - out := finalCmd.OutOrStdout() - for _, comp := range completions { - if noActiveHelp && strings.HasPrefix(comp, activeHelpMarker) { - // Remove all activeHelp entries if it's disabled. - continue - } - if noDescriptions { - // Remove any description that may be included following a tab character. - comp = strings.SplitN(comp, "\t", 2)[0] - } - - // Make sure we only write the first line to the output. - // This is needed if a description contains a linebreak. - // Otherwise the shell scripts will interpret the other lines as new flags - // and could therefore provide a wrong completion. - comp = strings.SplitN(comp, "\n", 2)[0] - - // Finally trim the completion. This is especially important to get rid - // of a trailing tab when there are no description following it. - // For example, a sub-command without a description should not be completed - // with a tab at the end (or else zsh will show a -- following it - // although there is no description). - comp = strings.TrimSpace(comp) - - // Print each possible completion to the output for the completion script to consume. - fmt.Fprintln(out, comp) - } - - // As the last printout, print the completion directive for the completion script to parse. - // The directive integer must be that last character following a single colon (:). - // The completion script expects : - fmt.Fprintf(out, ":%d\n", directive) - - // Print some helpful info to stderr for the user to understand. - // Output from stderr must be ignored by the completion script. - fmt.Fprintf(finalCmd.ErrOrStderr(), "Completion ended with directive: %s\n", directive.string()) - }, - } - c.AddCommand(completeCmd) - subCmd, _, err := c.Find(args) - if err != nil || subCmd.Name() != ShellCompRequestCmd { - // Only create this special command if it is actually being called. - // This reduces possible side-effects of creating such a command; - // for example, having this command would cause problems to a - // cobra program that only consists of the root command, since this - // command would cause the root command to suddenly have a subcommand. - c.RemoveCommand(completeCmd) - } -} - -func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDirective, error) { - // The last argument, which is not completely typed by the user, - // should not be part of the list of arguments - toComplete := args[len(args)-1] - trimmedArgs := args[:len(args)-1] - - var finalCmd *Command - var finalArgs []string - var err error - // Find the real command for which completion must be performed - // check if we need to traverse here to parse local flags on parent commands - if c.Root().TraverseChildren { - finalCmd, finalArgs, err = c.Root().Traverse(trimmedArgs) - } else { - // For Root commands that don't specify any value for their Args fields, when we call - // Find(), if those Root commands don't have any sub-commands, they will accept arguments. - // However, because we have added the __complete sub-command in the current code path, the - // call to Find() -> legacyArgs() will return an error if there are any arguments. - // To avoid this, we first remove the __complete command to get back to having no sub-commands. - rootCmd := c.Root() - if len(rootCmd.Commands()) == 1 { - rootCmd.RemoveCommand(c) - } - - finalCmd, finalArgs, err = rootCmd.Find(trimmedArgs) - } - if err != nil { - // Unable to find the real command. E.g., someInvalidCmd - return c, []string{}, ShellCompDirectiveDefault, fmt.Errorf("unable to find a command for arguments: %v", trimmedArgs) - } - finalCmd.ctx = c.ctx - - // These flags are normally added when `execute()` is called on `finalCmd`, - // however, when doing completion, we don't call `finalCmd.execute()`. - // Let's add the --help and --version flag ourselves but only if the finalCmd - // has not disabled flag parsing; if flag parsing is disabled, it is up to the - // finalCmd itself to handle the completion of *all* flags. - if !finalCmd.DisableFlagParsing { - finalCmd.InitDefaultHelpFlag() - finalCmd.InitDefaultVersionFlag() - } - - // Check if we are doing flag value completion before parsing the flags. - // This is important because if we are completing a flag value, we need to also - // remove the flag name argument from the list of finalArgs or else the parsing - // could fail due to an invalid value (incomplete) for the flag. - flag, finalArgs, toComplete, flagErr := checkIfFlagCompletion(finalCmd, finalArgs, toComplete) - - // Check if interspersed is false or -- was set on a previous arg. - // This works by counting the arguments. Normally -- is not counted as arg but - // if -- was already set or interspersed is false and there is already one arg then - // the extra added -- is counted as arg. - flagCompletion := true - _ = finalCmd.ParseFlags(append(finalArgs, "--")) - newArgCount := finalCmd.Flags().NArg() - - // Parse the flags early so we can check if required flags are set - if err = finalCmd.ParseFlags(finalArgs); err != nil { - return finalCmd, []string{}, ShellCompDirectiveDefault, fmt.Errorf("Error while parsing flags from args %v: %s", finalArgs, err.Error()) - } - - realArgCount := finalCmd.Flags().NArg() - if newArgCount > realArgCount { - // don't do flag completion (see above) - flagCompletion = false - } - // Error while attempting to parse flags - if flagErr != nil { - // If error type is flagCompError and we don't want flagCompletion we should ignore the error - if _, ok := flagErr.(*flagCompError); !(ok && !flagCompletion) { - return finalCmd, []string{}, ShellCompDirectiveDefault, flagErr - } - } - - // Look for the --help or --version flags. If they are present, - // there should be no further completions. - if helpOrVersionFlagPresent(finalCmd) { - return finalCmd, []string{}, ShellCompDirectiveNoFileComp, nil - } - - // We only remove the flags from the arguments if DisableFlagParsing is not set. - // This is important for commands which have requested to do their own flag completion. - if !finalCmd.DisableFlagParsing { - finalArgs = finalCmd.Flags().Args() - } - - if flag != nil && flagCompletion { - // Check if we are completing a flag value subject to annotations - if validExts, present := flag.Annotations[BashCompFilenameExt]; present { - if len(validExts) != 0 { - // File completion filtered by extensions - return finalCmd, validExts, ShellCompDirectiveFilterFileExt, nil - } - - // The annotation requests simple file completion. There is no reason to do - // that since it is the default behavior anyway. Let's ignore this annotation - // in case the program also registered a completion function for this flag. - // Even though it is a mistake on the program's side, let's be nice when we can. - } - - if subDir, present := flag.Annotations[BashCompSubdirsInDir]; present { - if len(subDir) == 1 { - // Directory completion from within a directory - return finalCmd, subDir, ShellCompDirectiveFilterDirs, nil - } - // Directory completion - return finalCmd, []string{}, ShellCompDirectiveFilterDirs, nil - } - } - - var completions []string - var directive ShellCompDirective - - // Enforce flag groups before doing flag completions - finalCmd.enforceFlagGroupsForCompletion() - - // Note that we want to perform flagname completion even if finalCmd.DisableFlagParsing==true; - // doing this allows for completion of persistent flag names even for commands that disable flag parsing. - // - // When doing completion of a flag name, as soon as an argument starts with - // a '-' we know it is a flag. We cannot use isFlagArg() here as it requires - // the flag name to be complete - if flag == nil && len(toComplete) > 0 && toComplete[0] == '-' && !strings.Contains(toComplete, "=") && flagCompletion { - // First check for required flags - completions = completeRequireFlags(finalCmd, toComplete) - - // If we have not found any required flags, only then can we show regular flags - if len(completions) == 0 { - doCompleteFlags := func(flag *pflag.Flag) { - if !flag.Changed || - strings.Contains(flag.Value.Type(), "Slice") || - strings.Contains(flag.Value.Type(), "Array") { - // If the flag is not already present, or if it can be specified multiple times (Array or Slice) - // we suggest it as a completion - completions = append(completions, getFlagNameCompletions(flag, toComplete)...) - } - } - - // We cannot use finalCmd.Flags() because we may not have called ParsedFlags() for commands - // that have set DisableFlagParsing; it is ParseFlags() that merges the inherited and - // non-inherited flags. - finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) { - doCompleteFlags(flag) - }) - // Try to complete non-inherited flags even if DisableFlagParsing==true. - // This allows programs to tell Cobra about flags for completion even - // if the actual parsing of flags is not done by Cobra. - // For instance, Helm uses this to provide flag name completion for - // some of its plugins. - finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) { - doCompleteFlags(flag) - }) - } - - directive = ShellCompDirectiveNoFileComp - if len(completions) == 1 && strings.HasSuffix(completions[0], "=") { - // If there is a single completion, the shell usually adds a space - // after the completion. We don't want that if the flag ends with an = - directive = ShellCompDirectiveNoSpace - } - - if !finalCmd.DisableFlagParsing { - // If DisableFlagParsing==false, we have completed the flags as known by Cobra; - // we can return what we found. - // If DisableFlagParsing==true, Cobra may not be aware of all flags, so we - // let the logic continue to see if ValidArgsFunction needs to be called. - return finalCmd, completions, directive, nil - } - } else { - directive = ShellCompDirectiveDefault - if flag == nil { - foundLocalNonPersistentFlag := false - // If TraverseChildren is true on the root command we don't check for - // local flags because we can use a local flag on a parent command - if !finalCmd.Root().TraverseChildren { - // Check if there are any local, non-persistent flags on the command-line - localNonPersistentFlags := finalCmd.LocalNonPersistentFlags() - finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) { - if localNonPersistentFlags.Lookup(flag.Name) != nil && flag.Changed { - foundLocalNonPersistentFlag = true - } - }) - } - - // Complete subcommand names, including the help command - if len(finalArgs) == 0 && !foundLocalNonPersistentFlag { - // We only complete sub-commands if: - // - there are no arguments on the command-line and - // - there are no local, non-persistent flags on the command-line or TraverseChildren is true - for _, subCmd := range finalCmd.Commands() { - if subCmd.IsAvailableCommand() || subCmd == finalCmd.helpCommand { - if strings.HasPrefix(subCmd.Name(), toComplete) { - completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short)) - } - directive = ShellCompDirectiveNoFileComp - } - } - } - - // Complete required flags even without the '-' prefix - completions = append(completions, completeRequireFlags(finalCmd, toComplete)...) - - // Always complete ValidArgs, even if we are completing a subcommand name. - // This is for commands that have both subcommands and ValidArgs. - if len(finalCmd.ValidArgs) > 0 { - if len(finalArgs) == 0 { - // ValidArgs are only for the first argument - for _, validArg := range finalCmd.ValidArgs { - if strings.HasPrefix(validArg, toComplete) { - completions = append(completions, validArg) - } - } - directive = ShellCompDirectiveNoFileComp - - // If no completions were found within commands or ValidArgs, - // see if there are any ArgAliases that should be completed. - if len(completions) == 0 { - for _, argAlias := range finalCmd.ArgAliases { - if strings.HasPrefix(argAlias, toComplete) { - completions = append(completions, argAlias) - } - } - } - } - - // If there are ValidArgs specified (even if they don't match), we stop completion. - // Only one of ValidArgs or ValidArgsFunction can be used for a single command. - return finalCmd, completions, directive, nil - } - - // Let the logic continue so as to add any ValidArgsFunction completions, - // even if we already found sub-commands. - // This is for commands that have subcommands but also specify a ValidArgsFunction. - } - } - - // Find the completion function for the flag or command - var completionFn func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) - if flag != nil && flagCompletion { - flagCompletionMutex.RLock() - completionFn = flagCompletionFunctions[flag] - flagCompletionMutex.RUnlock() - } else { - completionFn = finalCmd.ValidArgsFunction - } - if completionFn != nil { - // Go custom completion defined for this flag or command. - // Call the registered completion function to get the completions. - var comps []string - comps, directive = completionFn(finalCmd, finalArgs, toComplete) - completions = append(completions, comps...) - } - - return finalCmd, completions, directive, nil -} - -func helpOrVersionFlagPresent(cmd *Command) bool { - if versionFlag := cmd.Flags().Lookup("version"); versionFlag != nil && - len(versionFlag.Annotations[FlagSetByCobraAnnotation]) > 0 && versionFlag.Changed { - return true - } - if helpFlag := cmd.Flags().Lookup("help"); helpFlag != nil && - len(helpFlag.Annotations[FlagSetByCobraAnnotation]) > 0 && helpFlag.Changed { - return true - } - return false -} - -func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []string { - if nonCompletableFlag(flag) { - return []string{} - } - - var completions []string - flagName := "--" + flag.Name - if strings.HasPrefix(flagName, toComplete) { - // Flag without the = - completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage)) - - // Why suggest both long forms: --flag and --flag= ? - // This forces the user to *always* have to type either an = or a space after the flag name. - // Let's be nice and avoid making users have to do that. - // Since boolean flags and shortname flags don't show the = form, let's go that route and never show it. - // The = form will still work, we just won't suggest it. - // This also makes the list of suggested flags shorter as we avoid all the = forms. - // - // if len(flag.NoOptDefVal) == 0 { - // // Flag requires a value, so it can be suffixed with = - // flagName += "=" - // completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage)) - // } - } - - flagName = "-" + flag.Shorthand - if len(flag.Shorthand) > 0 && strings.HasPrefix(flagName, toComplete) { - completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage)) - } - - return completions -} - -func completeRequireFlags(finalCmd *Command, toComplete string) []string { - var completions []string - - doCompleteRequiredFlags := func(flag *pflag.Flag) { - if _, present := flag.Annotations[BashCompOneRequiredFlag]; present { - if !flag.Changed { - // If the flag is not already present, we suggest it as a completion - completions = append(completions, getFlagNameCompletions(flag, toComplete)...) - } - } - } - - // We cannot use finalCmd.Flags() because we may not have called ParsedFlags() for commands - // that have set DisableFlagParsing; it is ParseFlags() that merges the inherited and - // non-inherited flags. - finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) { - doCompleteRequiredFlags(flag) - }) - finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) { - doCompleteRequiredFlags(flag) - }) - - return completions -} - -func checkIfFlagCompletion(finalCmd *Command, args []string, lastArg string) (*pflag.Flag, []string, string, error) { - if finalCmd.DisableFlagParsing { - // We only do flag completion if we are allowed to parse flags - // This is important for commands which have requested to do their own flag completion. - return nil, args, lastArg, nil - } - - var flagName string - trimmedArgs := args - flagWithEqual := false - orgLastArg := lastArg - - // When doing completion of a flag name, as soon as an argument starts with - // a '-' we know it is a flag. We cannot use isFlagArg() here as that function - // requires the flag name to be complete - if len(lastArg) > 0 && lastArg[0] == '-' { - if index := strings.Index(lastArg, "="); index >= 0 { - // Flag with an = - if strings.HasPrefix(lastArg[:index], "--") { - // Flag has full name - flagName = lastArg[2:index] - } else { - // Flag is shorthand - // We have to get the last shorthand flag name - // e.g. `-asd` => d to provide the correct completion - // https://github.com/spf13/cobra/issues/1257 - flagName = lastArg[index-1 : index] - } - lastArg = lastArg[index+1:] - flagWithEqual = true - } else { - // Normal flag completion - return nil, args, lastArg, nil - } - } - - if len(flagName) == 0 { - if len(args) > 0 { - prevArg := args[len(args)-1] - if isFlagArg(prevArg) { - // Only consider the case where the flag does not contain an =. - // If the flag contains an = it means it has already been fully processed, - // so we don't need to deal with it here. - if index := strings.Index(prevArg, "="); index < 0 { - if strings.HasPrefix(prevArg, "--") { - // Flag has full name - flagName = prevArg[2:] - } else { - // Flag is shorthand - // We have to get the last shorthand flag name - // e.g. `-asd` => d to provide the correct completion - // https://github.com/spf13/cobra/issues/1257 - flagName = prevArg[len(prevArg)-1:] - } - // Remove the uncompleted flag or else there could be an error created - // for an invalid value for that flag - trimmedArgs = args[:len(args)-1] - } - } - } - } - - if len(flagName) == 0 { - // Not doing flag completion - return nil, trimmedArgs, lastArg, nil - } - - flag := findFlag(finalCmd, flagName) - if flag == nil { - // Flag not supported by this command, the interspersed option might be set so return the original args - return nil, args, orgLastArg, &flagCompError{subCommand: finalCmd.Name(), flagName: flagName} - } - - if !flagWithEqual { - if len(flag.NoOptDefVal) != 0 { - // We had assumed dealing with a two-word flag but the flag is a boolean flag. - // In that case, there is no value following it, so we are not really doing flag completion. - // Reset everything to do noun completion. - trimmedArgs = args - flag = nil - } - } - - return flag, trimmedArgs, lastArg, nil -} - -// InitDefaultCompletionCmd adds a default 'completion' command to c. -// This function will do nothing if any of the following is true: -// 1- the feature has been explicitly disabled by the program, -// 2- c has no subcommands (to avoid creating one), -// 3- c already has a 'completion' command provided by the program. -func (c *Command) InitDefaultCompletionCmd() { - if c.CompletionOptions.DisableDefaultCmd || !c.HasSubCommands() { - return - } - - for _, cmd := range c.commands { - if cmd.Name() == compCmdName || cmd.HasAlias(compCmdName) { - // A completion command is already available - return - } - } - - haveNoDescFlag := !c.CompletionOptions.DisableNoDescFlag && !c.CompletionOptions.DisableDescriptions - - completionCmd := &Command{ - Use: compCmdName, - Short: "Generate the autocompletion script for the specified shell", - Long: fmt.Sprintf(`Generate the autocompletion script for %[1]s for the specified shell. -See each sub-command's help for details on how to use the generated script. -`, c.Root().Name()), - Args: NoArgs, - ValidArgsFunction: NoFileCompletions, - Hidden: c.CompletionOptions.HiddenDefaultCmd, - GroupID: c.completionCommandGroupID, - } - c.AddCommand(completionCmd) - - out := c.OutOrStdout() - noDesc := c.CompletionOptions.DisableDescriptions - shortDesc := "Generate the autocompletion script for %s" - bash := &Command{ - Use: "bash", - Short: fmt.Sprintf(shortDesc, "bash"), - Long: fmt.Sprintf(`Generate the autocompletion script for the bash shell. - -This script depends on the 'bash-completion' package. -If it is not installed already, you can install it via your OS's package manager. - -To load completions in your current shell session: - - source <(%[1]s completion bash) - -To load completions for every new session, execute once: - -#### Linux: - - %[1]s completion bash > /etc/bash_completion.d/%[1]s - -#### macOS: - - %[1]s completion bash > $(brew --prefix)/etc/bash_completion.d/%[1]s - -You will need to start a new shell for this setup to take effect. -`, c.Root().Name()), - Args: NoArgs, - DisableFlagsInUseLine: true, - ValidArgsFunction: NoFileCompletions, - RunE: func(cmd *Command, args []string) error { - return cmd.Root().GenBashCompletionV2(out, !noDesc) - }, - } - if haveNoDescFlag { - bash.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc) - } - - zsh := &Command{ - Use: "zsh", - Short: fmt.Sprintf(shortDesc, "zsh"), - Long: fmt.Sprintf(`Generate the autocompletion script for the zsh shell. - -If shell completion is not already enabled in your environment you will need -to enable it. You can execute the following once: - - echo "autoload -U compinit; compinit" >> ~/.zshrc - -To load completions in your current shell session: - - source <(%[1]s completion zsh) - -To load completions for every new session, execute once: - -#### Linux: - - %[1]s completion zsh > "${fpath[1]}/_%[1]s" - -#### macOS: - - %[1]s completion zsh > $(brew --prefix)/share/zsh/site-functions/_%[1]s - -You will need to start a new shell for this setup to take effect. -`, c.Root().Name()), - Args: NoArgs, - ValidArgsFunction: NoFileCompletions, - RunE: func(cmd *Command, args []string) error { - if noDesc { - return cmd.Root().GenZshCompletionNoDesc(out) - } - return cmd.Root().GenZshCompletion(out) - }, - } - if haveNoDescFlag { - zsh.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc) - } - - fish := &Command{ - Use: "fish", - Short: fmt.Sprintf(shortDesc, "fish"), - Long: fmt.Sprintf(`Generate the autocompletion script for the fish shell. - -To load completions in your current shell session: - - %[1]s completion fish | source - -To load completions for every new session, execute once: - - %[1]s completion fish > ~/.config/fish/completions/%[1]s.fish - -You will need to start a new shell for this setup to take effect. -`, c.Root().Name()), - Args: NoArgs, - ValidArgsFunction: NoFileCompletions, - RunE: func(cmd *Command, args []string) error { - return cmd.Root().GenFishCompletion(out, !noDesc) - }, - } - if haveNoDescFlag { - fish.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc) - } - - powershell := &Command{ - Use: "powershell", - Short: fmt.Sprintf(shortDesc, "powershell"), - Long: fmt.Sprintf(`Generate the autocompletion script for powershell. - -To load completions in your current shell session: - - %[1]s completion powershell | Out-String | Invoke-Expression - -To load completions for every new session, add the output of the above command -to your powershell profile. -`, c.Root().Name()), - Args: NoArgs, - ValidArgsFunction: NoFileCompletions, - RunE: func(cmd *Command, args []string) error { - if noDesc { - return cmd.Root().GenPowerShellCompletion(out) - } - return cmd.Root().GenPowerShellCompletionWithDesc(out) - - }, - } - if haveNoDescFlag { - powershell.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc) - } - - completionCmd.AddCommand(bash, zsh, fish, powershell) -} - -func findFlag(cmd *Command, name string) *pflag.Flag { - flagSet := cmd.Flags() - if len(name) == 1 { - // First convert the short flag into a long flag - // as the cmd.Flag() search only accepts long flags - if short := flagSet.ShorthandLookup(name); short != nil { - name = short.Name - } else { - set := cmd.InheritedFlags() - if short = set.ShorthandLookup(name); short != nil { - name = short.Name - } else { - return nil - } - } - } - return cmd.Flag(name) -} - -// CompDebug prints the specified string to the same file as where the -// completion script prints its logs. -// Note that completion printouts should never be on stdout as they would -// be wrongly interpreted as actual completion choices by the completion script. -func CompDebug(msg string, printToStdErr bool) { - msg = fmt.Sprintf("[Debug] %s", msg) - - // Such logs are only printed when the user has set the environment - // variable BASH_COMP_DEBUG_FILE to the path of some file to be used. - if path := os.Getenv("BASH_COMP_DEBUG_FILE"); path != "" { - f, err := os.OpenFile(path, - os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) - if err == nil { - defer f.Close() - WriteStringAndCheck(f, msg) - } - } - - if printToStdErr { - // Must print to stderr for this not to be read by the completion script. - fmt.Fprint(os.Stderr, msg) - } -} - -// CompDebugln prints the specified string with a newline at the end -// to the same file as where the completion script prints its logs. -// Such logs are only printed when the user has set the environment -// variable BASH_COMP_DEBUG_FILE to the path of some file to be used. -func CompDebugln(msg string, printToStdErr bool) { - CompDebug(fmt.Sprintf("%s\n", msg), printToStdErr) -} - -// CompError prints the specified completion message to stderr. -func CompError(msg string) { - msg = fmt.Sprintf("[Error] %s", msg) - CompDebug(msg, true) -} - -// CompErrorln prints the specified completion message to stderr with a newline at the end. -func CompErrorln(msg string) { - CompError(fmt.Sprintf("%s\n", msg)) -} - -// These values should not be changed: users will be using them explicitly. -const ( - configEnvVarGlobalPrefix = "COBRA" - configEnvVarSuffixDescriptions = "COMPLETION_DESCRIPTIONS" -) - -var configEnvVarPrefixSubstRegexp = regexp.MustCompile(`[^A-Z0-9_]`) - -// configEnvVar returns the name of the program-specific configuration environment -// variable. It has the format _ where is the name of the -// root command in upper case, with all non-ASCII-alphanumeric characters replaced by `_`. -func configEnvVar(name, suffix string) string { - // This format should not be changed: users will be using it explicitly. - v := strings.ToUpper(fmt.Sprintf("%s_%s", name, suffix)) - v = configEnvVarPrefixSubstRegexp.ReplaceAllString(v, "_") - return v -} - -// getEnvConfig returns the value of the configuration environment variable -// _ where is the name of the root command in upper -// case, with all non-ASCII-alphanumeric characters replaced by `_`. -// If the value is empty or not set, the value of the environment variable -// COBRA_ is returned instead. -func getEnvConfig(cmd *Command, suffix string) string { - v := os.Getenv(configEnvVar(cmd.Root().Name(), suffix)) - if v == "" { - v = os.Getenv(configEnvVar(configEnvVarGlobalPrefix, suffix)) - } - return v -} diff --git a/vendor/github.com/spf13/cobra/fish_completions.go b/vendor/github.com/spf13/cobra/fish_completions.go deleted file mode 100644 index 12d61b691..000000000 --- a/vendor/github.com/spf13/cobra/fish_completions.go +++ /dev/null @@ -1,292 +0,0 @@ -// Copyright 2013-2023 The Cobra 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 cobra - -import ( - "bytes" - "fmt" - "io" - "os" - "strings" -) - -func genFishComp(buf io.StringWriter, name string, includeDesc bool) { - // Variables should not contain a '-' or ':' character - nameForVar := name - nameForVar = strings.ReplaceAll(nameForVar, "-", "_") - nameForVar = strings.ReplaceAll(nameForVar, ":", "_") - - compCmd := ShellCompRequestCmd - if !includeDesc { - compCmd = ShellCompNoDescRequestCmd - } - WriteStringAndCheck(buf, fmt.Sprintf("# fish completion for %-36s -*- shell-script -*-\n", name)) - WriteStringAndCheck(buf, fmt.Sprintf(` -function __%[1]s_debug - set -l file "$BASH_COMP_DEBUG_FILE" - if test -n "$file" - echo "$argv" >> $file - end -end - -function __%[1]s_perform_completion - __%[1]s_debug "Starting __%[1]s_perform_completion" - - # Extract all args except the last one - set -l args (commandline -opc) - # Extract the last arg and escape it in case it is a space - set -l lastArg (string escape -- (commandline -ct)) - - __%[1]s_debug "args: $args" - __%[1]s_debug "last arg: $lastArg" - - # Disable ActiveHelp which is not supported for fish shell - set -l requestComp "%[10]s=0 $args[1] %[3]s $args[2..-1] $lastArg" - - __%[1]s_debug "Calling $requestComp" - set -l results (eval $requestComp 2> /dev/null) - - # Some programs may output extra empty lines after the directive. - # Let's ignore them or else it will break completion. - # Ref: https://github.com/spf13/cobra/issues/1279 - for line in $results[-1..1] - if test (string trim -- $line) = "" - # Found an empty line, remove it - set results $results[1..-2] - else - # Found non-empty line, we have our proper output - break - end - end - - set -l comps $results[1..-2] - set -l directiveLine $results[-1] - - # For Fish, when completing a flag with an = (e.g., -n=) - # completions must be prefixed with the flag - set -l flagPrefix (string match -r -- '-.*=' "$lastArg") - - __%[1]s_debug "Comps: $comps" - __%[1]s_debug "DirectiveLine: $directiveLine" - __%[1]s_debug "flagPrefix: $flagPrefix" - - for comp in $comps - printf "%%s%%s\n" "$flagPrefix" "$comp" - end - - printf "%%s\n" "$directiveLine" -end - -# this function limits calls to __%[1]s_perform_completion, by caching the result behind $__%[1]s_perform_completion_once_result -function __%[1]s_perform_completion_once - __%[1]s_debug "Starting __%[1]s_perform_completion_once" - - if test -n "$__%[1]s_perform_completion_once_result" - __%[1]s_debug "Seems like a valid result already exists, skipping __%[1]s_perform_completion" - return 0 - end - - set --global __%[1]s_perform_completion_once_result (__%[1]s_perform_completion) - if test -z "$__%[1]s_perform_completion_once_result" - __%[1]s_debug "No completions, probably due to a failure" - return 1 - end - - __%[1]s_debug "Performed completions and set __%[1]s_perform_completion_once_result" - return 0 -end - -# this function is used to clear the $__%[1]s_perform_completion_once_result variable after completions are run -function __%[1]s_clear_perform_completion_once_result - __%[1]s_debug "" - __%[1]s_debug "========= clearing previously set __%[1]s_perform_completion_once_result variable ==========" - set --erase __%[1]s_perform_completion_once_result - __%[1]s_debug "Successfully erased the variable __%[1]s_perform_completion_once_result" -end - -function __%[1]s_requires_order_preservation - __%[1]s_debug "" - __%[1]s_debug "========= checking if order preservation is required ==========" - - __%[1]s_perform_completion_once - if test -z "$__%[1]s_perform_completion_once_result" - __%[1]s_debug "Error determining if order preservation is required" - return 1 - end - - set -l directive (string sub --start 2 $__%[1]s_perform_completion_once_result[-1]) - __%[1]s_debug "Directive is: $directive" - - set -l shellCompDirectiveKeepOrder %[9]d - set -l keeporder (math (math --scale 0 $directive / $shellCompDirectiveKeepOrder) %% 2) - __%[1]s_debug "Keeporder is: $keeporder" - - if test $keeporder -ne 0 - __%[1]s_debug "This does require order preservation" - return 0 - end - - __%[1]s_debug "This doesn't require order preservation" - return 1 -end - - -# This function does two things: -# - Obtain the completions and store them in the global __%[1]s_comp_results -# - Return false if file completion should be performed -function __%[1]s_prepare_completions - __%[1]s_debug "" - __%[1]s_debug "========= starting completion logic ==========" - - # Start fresh - set --erase __%[1]s_comp_results - - __%[1]s_perform_completion_once - __%[1]s_debug "Completion results: $__%[1]s_perform_completion_once_result" - - if test -z "$__%[1]s_perform_completion_once_result" - __%[1]s_debug "No completion, probably due to a failure" - # Might as well do file completion, in case it helps - return 1 - end - - set -l directive (string sub --start 2 $__%[1]s_perform_completion_once_result[-1]) - set --global __%[1]s_comp_results $__%[1]s_perform_completion_once_result[1..-2] - - __%[1]s_debug "Completions are: $__%[1]s_comp_results" - __%[1]s_debug "Directive is: $directive" - - set -l shellCompDirectiveError %[4]d - set -l shellCompDirectiveNoSpace %[5]d - set -l shellCompDirectiveNoFileComp %[6]d - set -l shellCompDirectiveFilterFileExt %[7]d - set -l shellCompDirectiveFilterDirs %[8]d - - if test -z "$directive" - set directive 0 - end - - set -l compErr (math (math --scale 0 $directive / $shellCompDirectiveError) %% 2) - if test $compErr -eq 1 - __%[1]s_debug "Received error directive: aborting." - # Might as well do file completion, in case it helps - return 1 - end - - set -l filefilter (math (math --scale 0 $directive / $shellCompDirectiveFilterFileExt) %% 2) - set -l dirfilter (math (math --scale 0 $directive / $shellCompDirectiveFilterDirs) %% 2) - if test $filefilter -eq 1; or test $dirfilter -eq 1 - __%[1]s_debug "File extension filtering or directory filtering not supported" - # Do full file completion instead - return 1 - end - - set -l nospace (math (math --scale 0 $directive / $shellCompDirectiveNoSpace) %% 2) - set -l nofiles (math (math --scale 0 $directive / $shellCompDirectiveNoFileComp) %% 2) - - __%[1]s_debug "nospace: $nospace, nofiles: $nofiles" - - # If we want to prevent a space, or if file completion is NOT disabled, - # we need to count the number of valid completions. - # To do so, we will filter on prefix as the completions we have received - # may not already be filtered so as to allow fish to match on different - # criteria than the prefix. - if test $nospace -ne 0; or test $nofiles -eq 0 - set -l prefix (commandline -t | string escape --style=regex) - __%[1]s_debug "prefix: $prefix" - - set -l completions (string match -r -- "^$prefix.*" $__%[1]s_comp_results) - set --global __%[1]s_comp_results $completions - __%[1]s_debug "Filtered completions are: $__%[1]s_comp_results" - - # Important not to quote the variable for count to work - set -l numComps (count $__%[1]s_comp_results) - __%[1]s_debug "numComps: $numComps" - - if test $numComps -eq 1; and test $nospace -ne 0 - # We must first split on \t to get rid of the descriptions to be - # able to check what the actual completion will be. - # We don't need descriptions anyway since there is only a single - # real completion which the shell will expand immediately. - set -l split (string split --max 1 \t $__%[1]s_comp_results[1]) - - # Fish won't add a space if the completion ends with any - # of the following characters: @=/:., - set -l lastChar (string sub -s -1 -- $split) - if not string match -r -q "[@=/:.,]" -- "$lastChar" - # In other cases, to support the "nospace" directive we trick the shell - # by outputting an extra, longer completion. - __%[1]s_debug "Adding second completion to perform nospace directive" - set --global __%[1]s_comp_results $split[1] $split[1]. - __%[1]s_debug "Completions are now: $__%[1]s_comp_results" - end - end - - if test $numComps -eq 0; and test $nofiles -eq 0 - # To be consistent with bash and zsh, we only trigger file - # completion when there are no other completions - __%[1]s_debug "Requesting file completion" - return 1 - end - end - - return 0 -end - -# Since Fish completions are only loaded once the user triggers them, we trigger them ourselves -# so we can properly delete any completions provided by another script. -# Only do this if the program can be found, or else fish may print some errors; besides, -# the existing completions will only be loaded if the program can be found. -if type -q "%[2]s" - # The space after the program name is essential to trigger completion for the program - # and not completion of the program name itself. - # Also, we use '> /dev/null 2>&1' since '&>' is not supported in older versions of fish. - complete --do-complete "%[2]s " > /dev/null 2>&1 -end - -# Remove any pre-existing completions for the program since we will be handling all of them. -complete -c %[2]s -e - -# this will get called after the two calls below and clear the $__%[1]s_perform_completion_once_result global -complete -c %[2]s -n '__%[1]s_clear_perform_completion_once_result' -# The call to __%[1]s_prepare_completions will setup __%[1]s_comp_results -# which provides the program's completion choices. -# If this doesn't require order preservation, we don't use the -k flag -complete -c %[2]s -n 'not __%[1]s_requires_order_preservation && __%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results' -# otherwise we use the -k flag -complete -k -c %[2]s -n '__%[1]s_requires_order_preservation && __%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results' -`, nameForVar, name, compCmd, - ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, - ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder, activeHelpEnvVar(name))) -} - -// GenFishCompletion generates fish completion file and writes to the passed writer. -func (c *Command) GenFishCompletion(w io.Writer, includeDesc bool) error { - buf := new(bytes.Buffer) - genFishComp(buf, c.Name(), includeDesc) - _, err := buf.WriteTo(w) - return err -} - -// GenFishCompletionFile generates fish completion file. -func (c *Command) GenFishCompletionFile(filename string, includeDesc bool) error { - outFile, err := os.Create(filename) - if err != nil { - return err - } - defer outFile.Close() - - return c.GenFishCompletion(outFile, includeDesc) -} diff --git a/vendor/github.com/spf13/cobra/flag_groups.go b/vendor/github.com/spf13/cobra/flag_groups.go deleted file mode 100644 index 560612fd3..000000000 --- a/vendor/github.com/spf13/cobra/flag_groups.go +++ /dev/null @@ -1,290 +0,0 @@ -// Copyright 2013-2023 The Cobra 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 cobra - -import ( - "fmt" - "sort" - "strings" - - flag "github.com/spf13/pflag" -) - -const ( - requiredAsGroupAnnotation = "cobra_annotation_required_if_others_set" - oneRequiredAnnotation = "cobra_annotation_one_required" - mutuallyExclusiveAnnotation = "cobra_annotation_mutually_exclusive" -) - -// MarkFlagsRequiredTogether marks the given flags with annotations so that Cobra errors -// if the command is invoked with a subset (but not all) of the given flags. -func (c *Command) MarkFlagsRequiredTogether(flagNames ...string) { - c.mergePersistentFlags() - for _, v := range flagNames { - f := c.Flags().Lookup(v) - if f == nil { - panic(fmt.Sprintf("Failed to find flag %q and mark it as being required in a flag group", v)) - } - if err := c.Flags().SetAnnotation(v, requiredAsGroupAnnotation, append(f.Annotations[requiredAsGroupAnnotation], strings.Join(flagNames, " "))); err != nil { - // Only errs if the flag isn't found. - panic(err) - } - } -} - -// MarkFlagsOneRequired marks the given flags with annotations so that Cobra errors -// if the command is invoked without at least one flag from the given set of flags. -func (c *Command) MarkFlagsOneRequired(flagNames ...string) { - c.mergePersistentFlags() - for _, v := range flagNames { - f := c.Flags().Lookup(v) - if f == nil { - panic(fmt.Sprintf("Failed to find flag %q and mark it as being in a one-required flag group", v)) - } - if err := c.Flags().SetAnnotation(v, oneRequiredAnnotation, append(f.Annotations[oneRequiredAnnotation], strings.Join(flagNames, " "))); err != nil { - // Only errs if the flag isn't found. - panic(err) - } - } -} - -// MarkFlagsMutuallyExclusive marks the given flags with annotations so that Cobra errors -// if the command is invoked with more than one flag from the given set of flags. -func (c *Command) MarkFlagsMutuallyExclusive(flagNames ...string) { - c.mergePersistentFlags() - for _, v := range flagNames { - f := c.Flags().Lookup(v) - if f == nil { - panic(fmt.Sprintf("Failed to find flag %q and mark it as being in a mutually exclusive flag group", v)) - } - // Each time this is called is a single new entry; this allows it to be a member of multiple groups if needed. - if err := c.Flags().SetAnnotation(v, mutuallyExclusiveAnnotation, append(f.Annotations[mutuallyExclusiveAnnotation], strings.Join(flagNames, " "))); err != nil { - panic(err) - } - } -} - -// ValidateFlagGroups validates the mutuallyExclusive/oneRequired/requiredAsGroup logic and returns the -// first error encountered. -func (c *Command) ValidateFlagGroups() error { - if c.DisableFlagParsing { - return nil - } - - flags := c.Flags() - - // groupStatus format is the list of flags as a unique ID, - // then a map of each flag name and whether it is set or not. - groupStatus := map[string]map[string]bool{} - oneRequiredGroupStatus := map[string]map[string]bool{} - mutuallyExclusiveGroupStatus := map[string]map[string]bool{} - flags.VisitAll(func(pflag *flag.Flag) { - processFlagForGroupAnnotation(flags, pflag, requiredAsGroupAnnotation, groupStatus) - processFlagForGroupAnnotation(flags, pflag, oneRequiredAnnotation, oneRequiredGroupStatus) - processFlagForGroupAnnotation(flags, pflag, mutuallyExclusiveAnnotation, mutuallyExclusiveGroupStatus) - }) - - if err := validateRequiredFlagGroups(groupStatus); err != nil { - return err - } - if err := validateOneRequiredFlagGroups(oneRequiredGroupStatus); err != nil { - return err - } - if err := validateExclusiveFlagGroups(mutuallyExclusiveGroupStatus); err != nil { - return err - } - return nil -} - -func hasAllFlags(fs *flag.FlagSet, flagnames ...string) bool { - for _, fname := range flagnames { - f := fs.Lookup(fname) - if f == nil { - return false - } - } - return true -} - -func processFlagForGroupAnnotation(flags *flag.FlagSet, pflag *flag.Flag, annotation string, groupStatus map[string]map[string]bool) { - groupInfo, found := pflag.Annotations[annotation] - if found { - for _, group := range groupInfo { - if groupStatus[group] == nil { - flagnames := strings.Split(group, " ") - - // Only consider this flag group at all if all the flags are defined. - if !hasAllFlags(flags, flagnames...) { - continue - } - - groupStatus[group] = make(map[string]bool, len(flagnames)) - for _, name := range flagnames { - groupStatus[group][name] = false - } - } - - groupStatus[group][pflag.Name] = pflag.Changed - } - } -} - -func validateRequiredFlagGroups(data map[string]map[string]bool) error { - keys := sortedKeys(data) - for _, flagList := range keys { - flagnameAndStatus := data[flagList] - - unset := []string{} - for flagname, isSet := range flagnameAndStatus { - if !isSet { - unset = append(unset, flagname) - } - } - if len(unset) == len(flagnameAndStatus) || len(unset) == 0 { - continue - } - - // Sort values, so they can be tested/scripted against consistently. - sort.Strings(unset) - return fmt.Errorf("if any flags in the group [%v] are set they must all be set; missing %v", flagList, unset) - } - - return nil -} - -func validateOneRequiredFlagGroups(data map[string]map[string]bool) error { - keys := sortedKeys(data) - for _, flagList := range keys { - flagnameAndStatus := data[flagList] - var set []string - for flagname, isSet := range flagnameAndStatus { - if isSet { - set = append(set, flagname) - } - } - if len(set) >= 1 { - continue - } - - // Sort values, so they can be tested/scripted against consistently. - sort.Strings(set) - return fmt.Errorf("at least one of the flags in the group [%v] is required", flagList) - } - return nil -} - -func validateExclusiveFlagGroups(data map[string]map[string]bool) error { - keys := sortedKeys(data) - for _, flagList := range keys { - flagnameAndStatus := data[flagList] - var set []string - for flagname, isSet := range flagnameAndStatus { - if isSet { - set = append(set, flagname) - } - } - if len(set) == 0 || len(set) == 1 { - continue - } - - // Sort values, so they can be tested/scripted against consistently. - sort.Strings(set) - return fmt.Errorf("if any flags in the group [%v] are set none of the others can be; %v were all set", flagList, set) - } - return nil -} - -func sortedKeys(m map[string]map[string]bool) []string { - keys := make([]string, len(m)) - i := 0 - for k := range m { - keys[i] = k - i++ - } - sort.Strings(keys) - return keys -} - -// enforceFlagGroupsForCompletion will do the following: -// - when a flag in a group is present, other flags in the group will be marked required -// - when none of the flags in a one-required group are present, all flags in the group will be marked required -// - when a flag in a mutually exclusive group is present, other flags in the group will be marked as hidden -// This allows the standard completion logic to behave appropriately for flag groups -func (c *Command) enforceFlagGroupsForCompletion() { - if c.DisableFlagParsing { - return - } - - flags := c.Flags() - groupStatus := map[string]map[string]bool{} - oneRequiredGroupStatus := map[string]map[string]bool{} - mutuallyExclusiveGroupStatus := map[string]map[string]bool{} - c.Flags().VisitAll(func(pflag *flag.Flag) { - processFlagForGroupAnnotation(flags, pflag, requiredAsGroupAnnotation, groupStatus) - processFlagForGroupAnnotation(flags, pflag, oneRequiredAnnotation, oneRequiredGroupStatus) - processFlagForGroupAnnotation(flags, pflag, mutuallyExclusiveAnnotation, mutuallyExclusiveGroupStatus) - }) - - // If a flag that is part of a group is present, we make all the other flags - // of that group required so that the shell completion suggests them automatically - for flagList, flagnameAndStatus := range groupStatus { - for _, isSet := range flagnameAndStatus { - if isSet { - // One of the flags of the group is set, mark the other ones as required - for _, fName := range strings.Split(flagList, " ") { - _ = c.MarkFlagRequired(fName) - } - } - } - } - - // If none of the flags of a one-required group are present, we make all the flags - // of that group required so that the shell completion suggests them automatically - for flagList, flagnameAndStatus := range oneRequiredGroupStatus { - isSet := false - - for _, isSet = range flagnameAndStatus { - if isSet { - break - } - } - - // None of the flags of the group are set, mark all flags in the group - // as required - if !isSet { - for _, fName := range strings.Split(flagList, " ") { - _ = c.MarkFlagRequired(fName) - } - } - } - - // If a flag that is mutually exclusive to others is present, we hide the other - // flags of that group so the shell completion does not suggest them - for flagList, flagnameAndStatus := range mutuallyExclusiveGroupStatus { - for flagName, isSet := range flagnameAndStatus { - if isSet { - // One of the flags of the mutually exclusive group is set, mark the other ones as hidden - // Don't mark the flag that is already set as hidden because it may be an - // array or slice flag and therefore must continue being suggested - for _, fName := range strings.Split(flagList, " ") { - if fName != flagName { - flag := c.Flags().Lookup(fName) - flag.Hidden = true - } - } - } - } - } -} diff --git a/vendor/github.com/spf13/cobra/powershell_completions.go b/vendor/github.com/spf13/cobra/powershell_completions.go deleted file mode 100644 index a830b7bca..000000000 --- a/vendor/github.com/spf13/cobra/powershell_completions.go +++ /dev/null @@ -1,325 +0,0 @@ -// Copyright 2013-2023 The Cobra 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. - -// The generated scripts require PowerShell v5.0+ (which comes Windows 10, but -// can be downloaded separately for windows 7 or 8.1). - -package cobra - -import ( - "bytes" - "fmt" - "io" - "os" - "strings" -) - -func genPowerShellComp(buf io.StringWriter, name string, includeDesc bool) { - // Variables should not contain a '-' or ':' character - nameForVar := name - nameForVar = strings.ReplaceAll(nameForVar, "-", "_") - nameForVar = strings.ReplaceAll(nameForVar, ":", "_") - - compCmd := ShellCompRequestCmd - if !includeDesc { - compCmd = ShellCompNoDescRequestCmd - } - WriteStringAndCheck(buf, fmt.Sprintf(`# powershell completion for %-36[1]s -*- shell-script -*- - -function __%[1]s_debug { - if ($env:BASH_COMP_DEBUG_FILE) { - "$args" | Out-File -Append -FilePath "$env:BASH_COMP_DEBUG_FILE" - } -} - -filter __%[1]s_escapeStringWithSpecialChars { -`+" $_ -replace '\\s|#|@|\\$|;|,|''|\\{|\\}|\\(|\\)|\"|`|\\||<|>|&','`$&'"+` -} - -[scriptblock]${__%[2]sCompleterBlock} = { - param( - $WordToComplete, - $CommandAst, - $CursorPosition - ) - - # Get the current command line and convert into a string - $Command = $CommandAst.CommandElements - $Command = "$Command" - - __%[1]s_debug "" - __%[1]s_debug "========= starting completion logic ==========" - __%[1]s_debug "WordToComplete: $WordToComplete Command: $Command CursorPosition: $CursorPosition" - - # The user could have moved the cursor backwards on the command-line. - # We need to trigger completion from the $CursorPosition location, so we need - # to truncate the command-line ($Command) up to the $CursorPosition location. - # Make sure the $Command is longer then the $CursorPosition before we truncate. - # This happens because the $Command does not include the last space. - if ($Command.Length -gt $CursorPosition) { - $Command=$Command.Substring(0,$CursorPosition) - } - __%[1]s_debug "Truncated command: $Command" - - $ShellCompDirectiveError=%[4]d - $ShellCompDirectiveNoSpace=%[5]d - $ShellCompDirectiveNoFileComp=%[6]d - $ShellCompDirectiveFilterFileExt=%[7]d - $ShellCompDirectiveFilterDirs=%[8]d - $ShellCompDirectiveKeepOrder=%[9]d - - # Prepare the command to request completions for the program. - # Split the command at the first space to separate the program and arguments. - $Program,$Arguments = $Command.Split(" ",2) - - $RequestComp="$Program %[3]s $Arguments" - __%[1]s_debug "RequestComp: $RequestComp" - - # we cannot use $WordToComplete because it - # has the wrong values if the cursor was moved - # so use the last argument - if ($WordToComplete -ne "" ) { - $WordToComplete = $Arguments.Split(" ")[-1] - } - __%[1]s_debug "New WordToComplete: $WordToComplete" - - - # Check for flag with equal sign - $IsEqualFlag = ($WordToComplete -Like "--*=*" ) - if ( $IsEqualFlag ) { - __%[1]s_debug "Completing equal sign flag" - # Remove the flag part - $Flag,$WordToComplete = $WordToComplete.Split("=",2) - } - - if ( $WordToComplete -eq "" -And ( -Not $IsEqualFlag )) { - # If the last parameter is complete (there is a space following it) - # We add an extra empty parameter so we can indicate this to the go method. - __%[1]s_debug "Adding extra empty parameter" - # PowerShell 7.2+ changed the way how the arguments are passed to executables, - # so for pre-7.2 or when Legacy argument passing is enabled we need to use -`+" # `\"`\" to pass an empty argument, a \"\" or '' does not work!!!"+` - if ($PSVersionTable.PsVersion -lt [version]'7.2.0' -or - ($PSVersionTable.PsVersion -lt [version]'7.3.0' -and -not [ExperimentalFeature]::IsEnabled("PSNativeCommandArgumentPassing")) -or - (($PSVersionTable.PsVersion -ge [version]'7.3.0' -or [ExperimentalFeature]::IsEnabled("PSNativeCommandArgumentPassing")) -and - $PSNativeCommandArgumentPassing -eq 'Legacy')) { -`+" $RequestComp=\"$RequestComp\" + ' `\"`\"'"+` - } else { - $RequestComp="$RequestComp" + ' ""' - } - } - - __%[1]s_debug "Calling $RequestComp" - # First disable ActiveHelp which is not supported for Powershell - ${env:%[10]s}=0 - - #call the command store the output in $out and redirect stderr and stdout to null - # $Out is an array contains each line per element - Invoke-Expression -OutVariable out "$RequestComp" 2>&1 | Out-Null - - # get directive from last line - [int]$Directive = $Out[-1].TrimStart(':') - if ($Directive -eq "") { - # There is no directive specified - $Directive = 0 - } - __%[1]s_debug "The completion directive is: $Directive" - - # remove directive (last element) from out - $Out = $Out | Where-Object { $_ -ne $Out[-1] } - __%[1]s_debug "The completions are: $Out" - - if (($Directive -band $ShellCompDirectiveError) -ne 0 ) { - # Error code. No completion. - __%[1]s_debug "Received error from custom completion go code" - return - } - - $Longest = 0 - [Array]$Values = $Out | ForEach-Object { - #Split the output in name and description -`+" $Name, $Description = $_.Split(\"`t\",2)"+` - __%[1]s_debug "Name: $Name Description: $Description" - - # Look for the longest completion so that we can format things nicely - if ($Longest -lt $Name.Length) { - $Longest = $Name.Length - } - - # Set the description to a one space string if there is none set. - # This is needed because the CompletionResult does not accept an empty string as argument - if (-Not $Description) { - $Description = " " - } - @{Name="$Name";Description="$Description"} - } - - - $Space = " " - if (($Directive -band $ShellCompDirectiveNoSpace) -ne 0 ) { - # remove the space here - __%[1]s_debug "ShellCompDirectiveNoSpace is called" - $Space = "" - } - - if ((($Directive -band $ShellCompDirectiveFilterFileExt) -ne 0 ) -or - (($Directive -band $ShellCompDirectiveFilterDirs) -ne 0 )) { - __%[1]s_debug "ShellCompDirectiveFilterFileExt ShellCompDirectiveFilterDirs are not supported" - - # return here to prevent the completion of the extensions - return - } - - $Values = $Values | Where-Object { - # filter the result - $_.Name -like "$WordToComplete*" - - # Join the flag back if we have an equal sign flag - if ( $IsEqualFlag ) { - __%[1]s_debug "Join the equal sign flag back to the completion value" - $_.Name = $Flag + "=" + $_.Name - } - } - - # we sort the values in ascending order by name if keep order isn't passed - if (($Directive -band $ShellCompDirectiveKeepOrder) -eq 0 ) { - $Values = $Values | Sort-Object -Property Name - } - - if (($Directive -band $ShellCompDirectiveNoFileComp) -ne 0 ) { - __%[1]s_debug "ShellCompDirectiveNoFileComp is called" - - if ($Values.Length -eq 0) { - # Just print an empty string here so the - # shell does not start to complete paths. - # We cannot use CompletionResult here because - # it does not accept an empty string as argument. - "" - return - } - } - - # Get the current mode - $Mode = (Get-PSReadLineKeyHandler | Where-Object {$_.Key -eq "Tab" }).Function - __%[1]s_debug "Mode: $Mode" - - $Values | ForEach-Object { - - # store temporary because switch will overwrite $_ - $comp = $_ - - # PowerShell supports three different completion modes - # - TabCompleteNext (default windows style - on each key press the next option is displayed) - # - Complete (works like bash) - # - MenuComplete (works like zsh) - # You set the mode with Set-PSReadLineKeyHandler -Key Tab -Function - - # CompletionResult Arguments: - # 1) CompletionText text to be used as the auto completion result - # 2) ListItemText text to be displayed in the suggestion list - # 3) ResultType type of completion result - # 4) ToolTip text for the tooltip with details about the object - - switch ($Mode) { - - # bash like - "Complete" { - - if ($Values.Length -eq 1) { - __%[1]s_debug "Only one completion left" - - # insert space after value - [System.Management.Automation.CompletionResult]::new($($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space, "$($comp.Name)", 'ParameterValue', "$($comp.Description)") - - } else { - # Add the proper number of spaces to align the descriptions - while($comp.Name.Length -lt $Longest) { - $comp.Name = $comp.Name + " " - } - - # Check for empty description and only add parentheses if needed - if ($($comp.Description) -eq " " ) { - $Description = "" - } else { - $Description = " ($($comp.Description))" - } - - [System.Management.Automation.CompletionResult]::new("$($comp.Name)$Description", "$($comp.Name)$Description", 'ParameterValue', "$($comp.Description)") - } - } - - # zsh like - "MenuComplete" { - # insert space after value - # MenuComplete will automatically show the ToolTip of - # the highlighted value at the bottom of the suggestions. - [System.Management.Automation.CompletionResult]::new($($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space, "$($comp.Name)", 'ParameterValue', "$($comp.Description)") - } - - # TabCompleteNext and in case we get something unknown - Default { - # Like MenuComplete but we don't want to add a space here because - # the user need to press space anyway to get the completion. - # Description will not be shown because that's not possible with TabCompleteNext - [System.Management.Automation.CompletionResult]::new($($comp.Name | __%[1]s_escapeStringWithSpecialChars), "$($comp.Name)", 'ParameterValue', "$($comp.Description)") - } - } - - } -} - -Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock ${__%[2]sCompleterBlock} -`, name, nameForVar, compCmd, - ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, - ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder, activeHelpEnvVar(name))) -} - -func (c *Command) genPowerShellCompletion(w io.Writer, includeDesc bool) error { - buf := new(bytes.Buffer) - genPowerShellComp(buf, c.Name(), includeDesc) - _, err := buf.WriteTo(w) - return err -} - -func (c *Command) genPowerShellCompletionFile(filename string, includeDesc bool) error { - outFile, err := os.Create(filename) - if err != nil { - return err - } - defer outFile.Close() - - return c.genPowerShellCompletion(outFile, includeDesc) -} - -// GenPowerShellCompletionFile generates powershell completion file without descriptions. -func (c *Command) GenPowerShellCompletionFile(filename string) error { - return c.genPowerShellCompletionFile(filename, false) -} - -// GenPowerShellCompletion generates powershell completion file without descriptions -// and writes it to the passed writer. -func (c *Command) GenPowerShellCompletion(w io.Writer) error { - return c.genPowerShellCompletion(w, false) -} - -// GenPowerShellCompletionFileWithDesc generates powershell completion file with descriptions. -func (c *Command) GenPowerShellCompletionFileWithDesc(filename string) error { - return c.genPowerShellCompletionFile(filename, true) -} - -// GenPowerShellCompletionWithDesc generates powershell completion file with descriptions -// and writes it to the passed writer. -func (c *Command) GenPowerShellCompletionWithDesc(w io.Writer) error { - return c.genPowerShellCompletion(w, true) -} diff --git a/vendor/github.com/spf13/cobra/shell_completions.go b/vendor/github.com/spf13/cobra/shell_completions.go deleted file mode 100644 index b035742d3..000000000 --- a/vendor/github.com/spf13/cobra/shell_completions.go +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright 2013-2023 The Cobra 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 cobra - -import ( - "github.com/spf13/pflag" -) - -// MarkFlagRequired instructs the various shell completion implementations to -// prioritize the named flag when performing completion, -// and causes your command to report an error if invoked without the flag. -func (c *Command) MarkFlagRequired(name string) error { - return MarkFlagRequired(c.Flags(), name) -} - -// MarkPersistentFlagRequired instructs the various shell completion implementations to -// prioritize the named persistent flag when performing completion, -// and causes your command to report an error if invoked without the flag. -func (c *Command) MarkPersistentFlagRequired(name string) error { - return MarkFlagRequired(c.PersistentFlags(), name) -} - -// MarkFlagRequired instructs the various shell completion implementations to -// prioritize the named flag when performing completion, -// and causes your command to report an error if invoked without the flag. -func MarkFlagRequired(flags *pflag.FlagSet, name string) error { - return flags.SetAnnotation(name, BashCompOneRequiredFlag, []string{"true"}) -} - -// MarkFlagFilename instructs the various shell completion implementations to -// limit completions for the named flag to the specified file extensions. -func (c *Command) MarkFlagFilename(name string, extensions ...string) error { - return MarkFlagFilename(c.Flags(), name, extensions...) -} - -// MarkFlagCustom adds the BashCompCustom annotation to the named flag, if it exists. -// The bash completion script will call the bash function f for the flag. -// -// This will only work for bash completion. -// It is recommended to instead use c.RegisterFlagCompletionFunc(...) which allows -// to register a Go function which will work across all shells. -func (c *Command) MarkFlagCustom(name string, f string) error { - return MarkFlagCustom(c.Flags(), name, f) -} - -// MarkPersistentFlagFilename instructs the various shell completion -// implementations to limit completions for the named persistent flag to the -// specified file extensions. -func (c *Command) MarkPersistentFlagFilename(name string, extensions ...string) error { - return MarkFlagFilename(c.PersistentFlags(), name, extensions...) -} - -// MarkFlagFilename instructs the various shell completion implementations to -// limit completions for the named flag to the specified file extensions. -func MarkFlagFilename(flags *pflag.FlagSet, name string, extensions ...string) error { - return flags.SetAnnotation(name, BashCompFilenameExt, extensions) -} - -// MarkFlagCustom adds the BashCompCustom annotation to the named flag, if it exists. -// The bash completion script will call the bash function f for the flag. -// -// This will only work for bash completion. -// It is recommended to instead use c.RegisterFlagCompletionFunc(...) which allows -// to register a Go function which will work across all shells. -func MarkFlagCustom(flags *pflag.FlagSet, name string, f string) error { - return flags.SetAnnotation(name, BashCompCustom, []string{f}) -} - -// MarkFlagDirname instructs the various shell completion implementations to -// limit completions for the named flag to directory names. -func (c *Command) MarkFlagDirname(name string) error { - return MarkFlagDirname(c.Flags(), name) -} - -// MarkPersistentFlagDirname instructs the various shell completion -// implementations to limit completions for the named persistent flag to -// directory names. -func (c *Command) MarkPersistentFlagDirname(name string) error { - return MarkFlagDirname(c.PersistentFlags(), name) -} - -// MarkFlagDirname instructs the various shell completion implementations to -// limit completions for the named flag to directory names. -func MarkFlagDirname(flags *pflag.FlagSet, name string) error { - return flags.SetAnnotation(name, BashCompSubdirsInDir, []string{}) -} diff --git a/vendor/github.com/spf13/cobra/zsh_completions.go b/vendor/github.com/spf13/cobra/zsh_completions.go deleted file mode 100644 index 1856e4c7f..000000000 --- a/vendor/github.com/spf13/cobra/zsh_completions.go +++ /dev/null @@ -1,308 +0,0 @@ -// Copyright 2013-2023 The Cobra 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 cobra - -import ( - "bytes" - "fmt" - "io" - "os" -) - -// GenZshCompletionFile generates zsh completion file including descriptions. -func (c *Command) GenZshCompletionFile(filename string) error { - return c.genZshCompletionFile(filename, true) -} - -// GenZshCompletion generates zsh completion file including descriptions -// and writes it to the passed writer. -func (c *Command) GenZshCompletion(w io.Writer) error { - return c.genZshCompletion(w, true) -} - -// GenZshCompletionFileNoDesc generates zsh completion file without descriptions. -func (c *Command) GenZshCompletionFileNoDesc(filename string) error { - return c.genZshCompletionFile(filename, false) -} - -// GenZshCompletionNoDesc generates zsh completion file without descriptions -// and writes it to the passed writer. -func (c *Command) GenZshCompletionNoDesc(w io.Writer) error { - return c.genZshCompletion(w, false) -} - -// MarkZshCompPositionalArgumentFile only worked for zsh and its behavior was -// not consistent with Bash completion. It has therefore been disabled. -// Instead, when no other completion is specified, file completion is done by -// default for every argument. One can disable file completion on a per-argument -// basis by using ValidArgsFunction and ShellCompDirectiveNoFileComp. -// To achieve file extension filtering, one can use ValidArgsFunction and -// ShellCompDirectiveFilterFileExt. -// -// Deprecated -func (c *Command) MarkZshCompPositionalArgumentFile(argPosition int, patterns ...string) error { - return nil -} - -// MarkZshCompPositionalArgumentWords only worked for zsh. It has therefore -// been disabled. -// To achieve the same behavior across all shells, one can use -// ValidArgs (for the first argument only) or ValidArgsFunction for -// any argument (can include the first one also). -// -// Deprecated -func (c *Command) MarkZshCompPositionalArgumentWords(argPosition int, words ...string) error { - return nil -} - -func (c *Command) genZshCompletionFile(filename string, includeDesc bool) error { - outFile, err := os.Create(filename) - if err != nil { - return err - } - defer outFile.Close() - - return c.genZshCompletion(outFile, includeDesc) -} - -func (c *Command) genZshCompletion(w io.Writer, includeDesc bool) error { - buf := new(bytes.Buffer) - genZshComp(buf, c.Name(), includeDesc) - _, err := buf.WriteTo(w) - return err -} - -func genZshComp(buf io.StringWriter, name string, includeDesc bool) { - compCmd := ShellCompRequestCmd - if !includeDesc { - compCmd = ShellCompNoDescRequestCmd - } - WriteStringAndCheck(buf, fmt.Sprintf(`#compdef %[1]s -compdef _%[1]s %[1]s - -# zsh completion for %-36[1]s -*- shell-script -*- - -__%[1]s_debug() -{ - local file="$BASH_COMP_DEBUG_FILE" - if [[ -n ${file} ]]; then - echo "$*" >> "${file}" - fi -} - -_%[1]s() -{ - local shellCompDirectiveError=%[3]d - local shellCompDirectiveNoSpace=%[4]d - local shellCompDirectiveNoFileComp=%[5]d - local shellCompDirectiveFilterFileExt=%[6]d - local shellCompDirectiveFilterDirs=%[7]d - local shellCompDirectiveKeepOrder=%[8]d - - local lastParam lastChar flagPrefix requestComp out directive comp lastComp noSpace keepOrder - local -a completions - - __%[1]s_debug "\n========= starting completion logic ==========" - __%[1]s_debug "CURRENT: ${CURRENT}, words[*]: ${words[*]}" - - # The user could have moved the cursor backwards on the command-line. - # We need to trigger completion from the $CURRENT location, so we need - # to truncate the command-line ($words) up to the $CURRENT location. - # (We cannot use $CURSOR as its value does not work when a command is an alias.) - words=("${=words[1,CURRENT]}") - __%[1]s_debug "Truncated words[*]: ${words[*]}," - - lastParam=${words[-1]} - lastChar=${lastParam[-1]} - __%[1]s_debug "lastParam: ${lastParam}, lastChar: ${lastChar}" - - # For zsh, when completing a flag with an = (e.g., %[1]s -n=) - # completions must be prefixed with the flag - setopt local_options BASH_REMATCH - if [[ "${lastParam}" =~ '-.*=' ]]; then - # We are dealing with a flag with an = - flagPrefix="-P ${BASH_REMATCH}" - fi - - # Prepare the command to obtain completions - requestComp="${words[1]} %[2]s ${words[2,-1]}" - if [ "${lastChar}" = "" ]; then - # If the last parameter is complete (there is a space following it) - # We add an extra empty parameter so we can indicate this to the go completion code. - __%[1]s_debug "Adding extra empty parameter" - requestComp="${requestComp} \"\"" - fi - - __%[1]s_debug "About to call: eval ${requestComp}" - - # Use eval to handle any environment variables and such - out=$(eval ${requestComp} 2>/dev/null) - __%[1]s_debug "completion output: ${out}" - - # Extract the directive integer following a : from the last line - local lastLine - while IFS='\n' read -r line; do - lastLine=${line} - done < <(printf "%%s\n" "${out[@]}") - __%[1]s_debug "last line: ${lastLine}" - - if [ "${lastLine[1]}" = : ]; then - directive=${lastLine[2,-1]} - # Remove the directive including the : and the newline - local suffix - (( suffix=${#lastLine}+2)) - out=${out[1,-$suffix]} - else - # There is no directive specified. Leave $out as is. - __%[1]s_debug "No directive found. Setting do default" - directive=0 - fi - - __%[1]s_debug "directive: ${directive}" - __%[1]s_debug "completions: ${out}" - __%[1]s_debug "flagPrefix: ${flagPrefix}" - - if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then - __%[1]s_debug "Completion received error. Ignoring completions." - return - fi - - local activeHelpMarker="%[9]s" - local endIndex=${#activeHelpMarker} - local startIndex=$((${#activeHelpMarker}+1)) - local hasActiveHelp=0 - while IFS='\n' read -r comp; do - # Check if this is an activeHelp statement (i.e., prefixed with $activeHelpMarker) - if [ "${comp[1,$endIndex]}" = "$activeHelpMarker" ];then - __%[1]s_debug "ActiveHelp found: $comp" - comp="${comp[$startIndex,-1]}" - if [ -n "$comp" ]; then - compadd -x "${comp}" - __%[1]s_debug "ActiveHelp will need delimiter" - hasActiveHelp=1 - fi - - continue - fi - - if [ -n "$comp" ]; then - # If requested, completions are returned with a description. - # The description is preceded by a TAB character. - # For zsh's _describe, we need to use a : instead of a TAB. - # We first need to escape any : as part of the completion itself. - comp=${comp//:/\\:} - - local tab="$(printf '\t')" - comp=${comp//$tab/:} - - __%[1]s_debug "Adding completion: ${comp}" - completions+=${comp} - lastComp=$comp - fi - done < <(printf "%%s\n" "${out[@]}") - - # Add a delimiter after the activeHelp statements, but only if: - # - there are completions following the activeHelp statements, or - # - file completion will be performed (so there will be choices after the activeHelp) - if [ $hasActiveHelp -eq 1 ]; then - if [ ${#completions} -ne 0 ] || [ $((directive & shellCompDirectiveNoFileComp)) -eq 0 ]; then - __%[1]s_debug "Adding activeHelp delimiter" - compadd -x "--" - hasActiveHelp=0 - fi - fi - - if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then - __%[1]s_debug "Activating nospace." - noSpace="-S ''" - fi - - if [ $((directive & shellCompDirectiveKeepOrder)) -ne 0 ]; then - __%[1]s_debug "Activating keep order." - keepOrder="-V" - fi - - if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then - # File extension filtering - local filteringCmd - filteringCmd='_files' - for filter in ${completions[@]}; do - if [ ${filter[1]} != '*' ]; then - # zsh requires a glob pattern to do file filtering - filter="\*.$filter" - fi - filteringCmd+=" -g $filter" - done - filteringCmd+=" ${flagPrefix}" - - __%[1]s_debug "File filtering command: $filteringCmd" - _arguments '*:filename:'"$filteringCmd" - elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then - # File completion for directories only - local subdir - subdir="${completions[1]}" - if [ -n "$subdir" ]; then - __%[1]s_debug "Listing directories in $subdir" - pushd "${subdir}" >/dev/null 2>&1 - else - __%[1]s_debug "Listing directories in ." - fi - - local result - _arguments '*:dirname:_files -/'" ${flagPrefix}" - result=$? - if [ -n "$subdir" ]; then - popd >/dev/null 2>&1 - fi - return $result - else - __%[1]s_debug "Calling _describe" - if eval _describe $keepOrder "completions" completions $flagPrefix $noSpace; then - __%[1]s_debug "_describe found some completions" - - # Return the success of having called _describe - return 0 - else - __%[1]s_debug "_describe did not find completions." - __%[1]s_debug "Checking if we should do file completion." - if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then - __%[1]s_debug "deactivating file completion" - - # We must return an error code here to let zsh know that there were no - # completions found by _describe; this is what will trigger other - # matching algorithms to attempt to find completions. - # For example zsh can match letters in the middle of words. - return 1 - else - # Perform file completion - __%[1]s_debug "Activating file completion" - - # We must return the result of this command, so it must be the - # last command, or else we must store its result to return it. - _arguments '*:filename:_files'" ${flagPrefix}" - fi - fi - fi -} - -# don't run the completion function when being source-ed or eval-ed -if [ "$funcstack[1]" = "_%[1]s" ]; then - _%[1]s -fi -`, name, compCmd, - ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, - ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder, - activeHelpMarker)) -} diff --git a/vendor/k8s.io/api/admission/v1/doc.go b/vendor/k8s.io/api/admission/v1/doc.go deleted file mode 100644 index e7df9f629..000000000 --- a/vendor/k8s.io/api/admission/v1/doc.go +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright 2019 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. -*/ - -// +k8s:deepcopy-gen=package -// +k8s:protobuf-gen=package -// +k8s:openapi-gen=false -// +k8s:prerelease-lifecycle-gen=true -// +groupName=admission.k8s.io - -package v1 // import "k8s.io/api/admission/v1" diff --git a/vendor/k8s.io/api/admission/v1/generated.pb.go b/vendor/k8s.io/api/admission/v1/generated.pb.go deleted file mode 100644 index f5c417919..000000000 --- a/vendor/k8s.io/api/admission/v1/generated.pb.go +++ /dev/null @@ -1,1782 +0,0 @@ -/* -Copyright 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 protoc-gen-gogo. DO NOT EDIT. -// source: k8s.io/api/admission/v1/generated.proto - -package v1 - -import ( - fmt "fmt" - - io "io" - - proto "github.com/gogo/protobuf/proto" - github_com_gogo_protobuf_sortkeys "github.com/gogo/protobuf/sortkeys" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - math "math" - math_bits "math/bits" - reflect "reflect" - strings "strings" - - k8s_io_apimachinery_pkg_types "k8s.io/apimachinery/pkg/types" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -func (m *AdmissionRequest) Reset() { *m = AdmissionRequest{} } -func (*AdmissionRequest) ProtoMessage() {} -func (*AdmissionRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_7b47d27831186ccf, []int{0} -} -func (m *AdmissionRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *AdmissionRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil -} -func (m *AdmissionRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_AdmissionRequest.Merge(m, src) -} -func (m *AdmissionRequest) XXX_Size() int { - return m.Size() -} -func (m *AdmissionRequest) XXX_DiscardUnknown() { - xxx_messageInfo_AdmissionRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_AdmissionRequest proto.InternalMessageInfo - -func (m *AdmissionResponse) Reset() { *m = AdmissionResponse{} } -func (*AdmissionResponse) ProtoMessage() {} -func (*AdmissionResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_7b47d27831186ccf, []int{1} -} -func (m *AdmissionResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *AdmissionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil -} -func (m *AdmissionResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_AdmissionResponse.Merge(m, src) -} -func (m *AdmissionResponse) XXX_Size() int { - return m.Size() -} -func (m *AdmissionResponse) XXX_DiscardUnknown() { - xxx_messageInfo_AdmissionResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_AdmissionResponse proto.InternalMessageInfo - -func (m *AdmissionReview) Reset() { *m = AdmissionReview{} } -func (*AdmissionReview) ProtoMessage() {} -func (*AdmissionReview) Descriptor() ([]byte, []int) { - return fileDescriptor_7b47d27831186ccf, []int{2} -} -func (m *AdmissionReview) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *AdmissionReview) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil -} -func (m *AdmissionReview) XXX_Merge(src proto.Message) { - xxx_messageInfo_AdmissionReview.Merge(m, src) -} -func (m *AdmissionReview) XXX_Size() int { - return m.Size() -} -func (m *AdmissionReview) XXX_DiscardUnknown() { - xxx_messageInfo_AdmissionReview.DiscardUnknown(m) -} - -var xxx_messageInfo_AdmissionReview proto.InternalMessageInfo - -func init() { - proto.RegisterType((*AdmissionRequest)(nil), "k8s.io.api.admission.v1.AdmissionRequest") - proto.RegisterType((*AdmissionResponse)(nil), "k8s.io.api.admission.v1.AdmissionResponse") - proto.RegisterMapType((map[string]string)(nil), "k8s.io.api.admission.v1.AdmissionResponse.AuditAnnotationsEntry") - proto.RegisterType((*AdmissionReview)(nil), "k8s.io.api.admission.v1.AdmissionReview") -} - -func init() { - proto.RegisterFile("k8s.io/api/admission/v1/generated.proto", fileDescriptor_7b47d27831186ccf) -} - -var fileDescriptor_7b47d27831186ccf = []byte{ - // 907 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x56, 0x4f, 0x6f, 0x1b, 0x45, - 0x14, 0xf7, 0xd6, 0x8e, 0xed, 0x1d, 0x87, 0xda, 0x9d, 0x82, 0xba, 0xf2, 0x61, 0x6d, 0x72, 0x00, - 0x17, 0xb5, 0xbb, 0x24, 0x82, 0x2a, 0xaa, 0x40, 0x22, 0x4b, 0x2a, 0x14, 0x90, 0x9a, 0x68, 0xda, - 0x40, 0xc5, 0x01, 0x69, 0x62, 0x4f, 0xed, 0xc1, 0xf6, 0xcc, 0xb2, 0x33, 0xeb, 0xe0, 0x1b, 0x27, - 0xce, 0x7c, 0x03, 0x8e, 0x7c, 0x06, 0xbe, 0x41, 0x8e, 0x3d, 0xf6, 0x64, 0x11, 0xf3, 0x2d, 0x72, - 0x42, 0x33, 0x3b, 0xfb, 0xa7, 0x89, 0x2d, 0x42, 0xc3, 0x29, 0xfb, 0xfe, 0xfc, 0x7e, 0xef, 0xe5, - 0xf7, 0xf6, 0xbd, 0x35, 0xf8, 0x70, 0xbc, 0x2b, 0x3c, 0xca, 0x7d, 0x1c, 0x52, 0x1f, 0x0f, 0xa6, - 0x54, 0x08, 0xca, 0x99, 0x3f, 0xdb, 0xf6, 0x87, 0x84, 0x91, 0x08, 0x4b, 0x32, 0xf0, 0xc2, 0x88, - 0x4b, 0x0e, 0xef, 0x25, 0x89, 0x1e, 0x0e, 0xa9, 0x97, 0x25, 0x7a, 0xb3, 0xed, 0xf6, 0xc3, 0x21, - 0x95, 0xa3, 0xf8, 0xc4, 0xeb, 0xf3, 0xa9, 0x3f, 0xe4, 0x43, 0xee, 0xeb, 0xfc, 0x93, 0xf8, 0xa5, - 0xb6, 0xb4, 0xa1, 0x9f, 0x12, 0x9e, 0xf6, 0x83, 0x62, 0xc1, 0x58, 0x8e, 0x08, 0x93, 0xb4, 0x8f, - 0xe5, 0xea, 0xaa, 0xed, 0x4f, 0xf2, 0xec, 0x29, 0xee, 0x8f, 0x28, 0x23, 0xd1, 0xdc, 0x0f, 0xc7, - 0x43, 0xe5, 0x10, 0xfe, 0x94, 0x48, 0xbc, 0x0a, 0xe5, 0xaf, 0x43, 0x45, 0x31, 0x93, 0x74, 0x4a, - 0xae, 0x00, 0x1e, 0xfd, 0x1b, 0x40, 0xf4, 0x47, 0x64, 0x8a, 0x2f, 0xe3, 0xb6, 0x7e, 0xb7, 0x41, - 0x6b, 0x2f, 0x15, 0x03, 0x91, 0x9f, 0x62, 0x22, 0x24, 0x0c, 0x40, 0x39, 0xa6, 0x03, 0xc7, 0xea, - 0x5a, 0x3d, 0x3b, 0xf8, 0xf8, 0x6c, 0xd1, 0x29, 0x2d, 0x17, 0x9d, 0xf2, 0xf1, 0xc1, 0xfe, 0xc5, - 0xa2, 0xf3, 0xfe, 0xba, 0x42, 0x72, 0x1e, 0x12, 0xe1, 0x1d, 0x1f, 0xec, 0x23, 0x05, 0x86, 0x2f, - 0x40, 0x65, 0x4c, 0xd9, 0xc0, 0xb9, 0xd5, 0xb5, 0x7a, 0x8d, 0x9d, 0x47, 0x5e, 0x2e, 0x7e, 0x06, - 0xf3, 0xc2, 0xf1, 0x50, 0x39, 0x84, 0xa7, 0x64, 0xf0, 0x66, 0xdb, 0xde, 0x57, 0x11, 0x8f, 0xc3, - 0x6f, 0x49, 0xa4, 0x9a, 0xf9, 0x86, 0xb2, 0x41, 0xb0, 0x69, 0x8a, 0x57, 0x94, 0x85, 0x34, 0x23, - 0x1c, 0x81, 0x7a, 0x44, 0x04, 0x8f, 0xa3, 0x3e, 0x71, 0xca, 0x9a, 0xfd, 0xf1, 0x7f, 0x67, 0x47, - 0x86, 0x21, 0x68, 0x99, 0x0a, 0xf5, 0xd4, 0x83, 0x32, 0x76, 0xf8, 0x29, 0x68, 0x88, 0xf8, 0x24, - 0x0d, 0x38, 0x15, 0xad, 0xc7, 0x5d, 0x03, 0x68, 0x3c, 0xcb, 0x43, 0xa8, 0x98, 0x07, 0x29, 0x68, - 0x44, 0x89, 0x92, 0xaa, 0x6b, 0xe7, 0x9d, 0x1b, 0x29, 0xd0, 0x54, 0xa5, 0x50, 0x4e, 0x87, 0x8a, - 0xdc, 0x70, 0x0e, 0x9a, 0xc6, 0xcc, 0xba, 0xbc, 0x7d, 0x63, 0x49, 0xee, 0x2e, 0x17, 0x9d, 0x26, - 0x7a, 0x93, 0x16, 0x5d, 0xae, 0x03, 0xbf, 0x06, 0xd0, 0xb8, 0x0a, 0x42, 0x38, 0x4d, 0xad, 0x51, - 0xdb, 0x68, 0x04, 0xd1, 0x95, 0x0c, 0xb4, 0x02, 0x05, 0xbb, 0xa0, 0xc2, 0xf0, 0x94, 0x38, 0x1b, - 0x1a, 0x9d, 0x0d, 0xfd, 0x29, 0x9e, 0x12, 0xa4, 0x23, 0xd0, 0x07, 0xb6, 0xfa, 0x2b, 0x42, 0xdc, - 0x27, 0x4e, 0x55, 0xa7, 0xdd, 0x31, 0x69, 0xf6, 0xd3, 0x34, 0x80, 0xf2, 0x1c, 0xf8, 0x19, 0xb0, - 0x79, 0xa8, 0x5e, 0x75, 0xca, 0x99, 0x53, 0xd3, 0x00, 0x37, 0x05, 0x1c, 0xa6, 0x81, 0x8b, 0xa2, - 0x81, 0x72, 0x00, 0x7c, 0x0e, 0xea, 0xb1, 0x20, 0xd1, 0x01, 0x7b, 0xc9, 0x9d, 0xba, 0x16, 0xf4, - 0x03, 0xaf, 0x78, 0x3e, 0xde, 0x58, 0x7b, 0x25, 0xe4, 0xb1, 0xc9, 0xce, 0xdf, 0xa7, 0xd4, 0x83, - 0x32, 0x26, 0x78, 0x0c, 0xaa, 0xfc, 0xe4, 0x47, 0xd2, 0x97, 0x8e, 0xad, 0x39, 0x1f, 0xae, 0x1d, - 0x92, 0xd9, 0x5a, 0x0f, 0xe1, 0xd3, 0x27, 0x3f, 0x4b, 0xc2, 0xd4, 0x7c, 0x82, 0xdb, 0x86, 0xba, - 0x7a, 0xa8, 0x49, 0x90, 0x21, 0x83, 0x3f, 0x00, 0x9b, 0x4f, 0x06, 0x89, 0xd3, 0x01, 0x6f, 0xc3, - 0x9c, 0x49, 0x79, 0x98, 0xf2, 0xa0, 0x9c, 0x12, 0x6e, 0x81, 0xea, 0x20, 0x9a, 0xa3, 0x98, 0x39, - 0x8d, 0xae, 0xd5, 0xab, 0x07, 0x40, 0xf5, 0xb0, 0xaf, 0x3d, 0xc8, 0x44, 0xe0, 0x0b, 0x50, 0xe3, - 0xa1, 0x12, 0x43, 0x38, 0x9b, 0x6f, 0xd3, 0x41, 0xd3, 0x74, 0x50, 0x3b, 0x4c, 0x58, 0x50, 0x4a, - 0xb7, 0xf5, 0x47, 0x05, 0xdc, 0x29, 0x5c, 0x28, 0x11, 0x72, 0x26, 0xc8, 0xff, 0x72, 0xa2, 0xee, - 0x83, 0x1a, 0x9e, 0x4c, 0xf8, 0x29, 0x49, 0xae, 0x54, 0x3d, 0x6f, 0x62, 0x2f, 0x71, 0xa3, 0x34, - 0x0e, 0x8f, 0x40, 0x55, 0x48, 0x2c, 0x63, 0x61, 0x2e, 0xce, 0x83, 0xeb, 0xad, 0xd7, 0x33, 0x8d, - 0x49, 0x04, 0x43, 0x44, 0xc4, 0x13, 0x89, 0x0c, 0x0f, 0xec, 0x80, 0x8d, 0x10, 0xcb, 0xfe, 0x48, - 0x5f, 0x95, 0xcd, 0xc0, 0x5e, 0x2e, 0x3a, 0x1b, 0x47, 0xca, 0x81, 0x12, 0x3f, 0xdc, 0x05, 0xb6, - 0x7e, 0x78, 0x3e, 0x0f, 0xd3, 0xc5, 0x68, 0xab, 0x11, 0x1d, 0xa5, 0xce, 0x8b, 0xa2, 0x81, 0xf2, - 0x64, 0xf8, 0xab, 0x05, 0x5a, 0x38, 0x1e, 0x50, 0xb9, 0xc7, 0x18, 0x97, 0x38, 0x99, 0x4a, 0xb5, - 0x5b, 0xee, 0x35, 0x76, 0xbe, 0xf0, 0xd6, 0x7c, 0x04, 0xbd, 0x2b, 0x12, 0x7b, 0x7b, 0x97, 0x28, - 0x9e, 0x30, 0x19, 0xcd, 0x03, 0xc7, 0x68, 0xd4, 0xba, 0x1c, 0x46, 0x57, 0x6a, 0xc2, 0x1e, 0xa8, - 0x9f, 0xe2, 0x88, 0x51, 0x36, 0x14, 0x4e, 0xad, 0x5b, 0x56, 0xab, 0xad, 0x36, 0xe3, 0x3b, 0xe3, - 0x43, 0x59, 0xb4, 0xfd, 0x25, 0x78, 0x6f, 0x65, 0x39, 0xd8, 0x02, 0xe5, 0x31, 0x99, 0x27, 0x73, - 0x46, 0xea, 0x11, 0xbe, 0x0b, 0x36, 0x66, 0x78, 0x12, 0x13, 0x3d, 0x33, 0x1b, 0x25, 0xc6, 0xe3, - 0x5b, 0xbb, 0xd6, 0xd6, 0x9f, 0x16, 0x68, 0x16, 0xfe, 0x8d, 0x19, 0x25, 0xa7, 0xf0, 0x08, 0xd4, - 0xcc, 0xbd, 0xd1, 0x1c, 0x8d, 0x9d, 0xfb, 0xd7, 0x51, 0x40, 0x03, 0x82, 0x86, 0x7a, 0x15, 0xd2, - 0x3b, 0x98, 0xd2, 0xa8, 0xd3, 0x10, 0x19, 0x89, 0xcc, 0xc7, 0xed, 0xa3, 0xeb, 0x8b, 0x9a, 0x08, - 0x90, 0x5a, 0x28, 0x63, 0x0a, 0x3e, 0x3f, 0x3b, 0x77, 0x4b, 0xaf, 0xce, 0xdd, 0xd2, 0xeb, 0x73, - 0xb7, 0xf4, 0xcb, 0xd2, 0xb5, 0xce, 0x96, 0xae, 0xf5, 0x6a, 0xe9, 0x5a, 0xaf, 0x97, 0xae, 0xf5, - 0xd7, 0xd2, 0xb5, 0x7e, 0xfb, 0xdb, 0x2d, 0x7d, 0x7f, 0x6f, 0xcd, 0x6f, 0x9d, 0x7f, 0x02, 0x00, - 0x00, 0xff, 0xff, 0x5c, 0x49, 0x23, 0x22, 0x05, 0x09, 0x00, 0x00, -} - -func (m *AdmissionRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *AdmissionRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AdmissionRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - i -= len(m.RequestSubResource) - copy(dAtA[i:], m.RequestSubResource) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.RequestSubResource))) - i-- - dAtA[i] = 0x7a - if m.RequestResource != nil { - { - size, err := m.RequestResource.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x72 - } - if m.RequestKind != nil { - { - size, err := m.RequestKind.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x6a - } - { - size, err := m.Options.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x62 - if m.DryRun != nil { - i-- - if *m.DryRun { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x58 - } - { - size, err := m.OldObject.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x52 - { - size, err := m.Object.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x4a - { - size, err := m.UserInfo.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x42 - i -= len(m.Operation) - copy(dAtA[i:], m.Operation) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.Operation))) - i-- - dAtA[i] = 0x3a - i -= len(m.Namespace) - copy(dAtA[i:], m.Namespace) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.Namespace))) - i-- - dAtA[i] = 0x32 - i -= len(m.Name) - copy(dAtA[i:], m.Name) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.Name))) - i-- - dAtA[i] = 0x2a - i -= len(m.SubResource) - copy(dAtA[i:], m.SubResource) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.SubResource))) - i-- - dAtA[i] = 0x22 - { - size, err := m.Resource.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.Kind.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - i -= len(m.UID) - copy(dAtA[i:], m.UID) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.UID))) - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *AdmissionResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *AdmissionResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AdmissionResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Warnings) > 0 { - for iNdEx := len(m.Warnings) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.Warnings[iNdEx]) - copy(dAtA[i:], m.Warnings[iNdEx]) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.Warnings[iNdEx]))) - i-- - dAtA[i] = 0x3a - } - } - if len(m.AuditAnnotations) > 0 { - keysForAuditAnnotations := make([]string, 0, len(m.AuditAnnotations)) - for k := range m.AuditAnnotations { - keysForAuditAnnotations = append(keysForAuditAnnotations, string(k)) - } - github_com_gogo_protobuf_sortkeys.Strings(keysForAuditAnnotations) - for iNdEx := len(keysForAuditAnnotations) - 1; iNdEx >= 0; iNdEx-- { - v := m.AuditAnnotations[string(keysForAuditAnnotations[iNdEx])] - baseI := i - i -= len(v) - copy(dAtA[i:], v) - i = encodeVarintGenerated(dAtA, i, uint64(len(v))) - i-- - dAtA[i] = 0x12 - i -= len(keysForAuditAnnotations[iNdEx]) - copy(dAtA[i:], keysForAuditAnnotations[iNdEx]) - i = encodeVarintGenerated(dAtA, i, uint64(len(keysForAuditAnnotations[iNdEx]))) - i-- - dAtA[i] = 0xa - i = encodeVarintGenerated(dAtA, i, uint64(baseI-i)) - i-- - dAtA[i] = 0x32 - } - } - if m.PatchType != nil { - i -= len(*m.PatchType) - copy(dAtA[i:], *m.PatchType) - i = encodeVarintGenerated(dAtA, i, uint64(len(*m.PatchType))) - i-- - dAtA[i] = 0x2a - } - if m.Patch != nil { - i -= len(m.Patch) - copy(dAtA[i:], m.Patch) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.Patch))) - i-- - dAtA[i] = 0x22 - } - if m.Result != nil { - { - size, err := m.Result.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - i-- - if m.Allowed { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x10 - i -= len(m.UID) - copy(dAtA[i:], m.UID) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.UID))) - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *AdmissionReview) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *AdmissionReview) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AdmissionReview) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Response != nil { - { - size, err := m.Response.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if m.Request != nil { - { - size, err := m.Request.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int { - offset -= sovGenerated(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *AdmissionRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.UID) - n += 1 + l + sovGenerated(uint64(l)) - l = m.Kind.Size() - n += 1 + l + sovGenerated(uint64(l)) - l = m.Resource.Size() - n += 1 + l + sovGenerated(uint64(l)) - l = len(m.SubResource) - n += 1 + l + sovGenerated(uint64(l)) - l = len(m.Name) - n += 1 + l + sovGenerated(uint64(l)) - l = len(m.Namespace) - n += 1 + l + sovGenerated(uint64(l)) - l = len(m.Operation) - n += 1 + l + sovGenerated(uint64(l)) - l = m.UserInfo.Size() - n += 1 + l + sovGenerated(uint64(l)) - l = m.Object.Size() - n += 1 + l + sovGenerated(uint64(l)) - l = m.OldObject.Size() - n += 1 + l + sovGenerated(uint64(l)) - if m.DryRun != nil { - n += 2 - } - l = m.Options.Size() - n += 1 + l + sovGenerated(uint64(l)) - if m.RequestKind != nil { - l = m.RequestKind.Size() - n += 1 + l + sovGenerated(uint64(l)) - } - if m.RequestResource != nil { - l = m.RequestResource.Size() - n += 1 + l + sovGenerated(uint64(l)) - } - l = len(m.RequestSubResource) - n += 1 + l + sovGenerated(uint64(l)) - return n -} - -func (m *AdmissionResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.UID) - n += 1 + l + sovGenerated(uint64(l)) - n += 2 - if m.Result != nil { - l = m.Result.Size() - n += 1 + l + sovGenerated(uint64(l)) - } - if m.Patch != nil { - l = len(m.Patch) - n += 1 + l + sovGenerated(uint64(l)) - } - if m.PatchType != nil { - l = len(*m.PatchType) - n += 1 + l + sovGenerated(uint64(l)) - } - if len(m.AuditAnnotations) > 0 { - for k, v := range m.AuditAnnotations { - _ = k - _ = v - mapEntrySize := 1 + len(k) + sovGenerated(uint64(len(k))) + 1 + len(v) + sovGenerated(uint64(len(v))) - n += mapEntrySize + 1 + sovGenerated(uint64(mapEntrySize)) - } - } - if len(m.Warnings) > 0 { - for _, s := range m.Warnings { - l = len(s) - n += 1 + l + sovGenerated(uint64(l)) - } - } - return n -} - -func (m *AdmissionReview) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Request != nil { - l = m.Request.Size() - n += 1 + l + sovGenerated(uint64(l)) - } - if m.Response != nil { - l = m.Response.Size() - n += 1 + l + sovGenerated(uint64(l)) - } - return n -} - -func sovGenerated(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozGenerated(x uint64) (n int) { - return sovGenerated(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (this *AdmissionRequest) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&AdmissionRequest{`, - `UID:` + fmt.Sprintf("%v", this.UID) + `,`, - `Kind:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Kind), "GroupVersionKind", "v1.GroupVersionKind", 1), `&`, ``, 1) + `,`, - `Resource:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Resource), "GroupVersionResource", "v1.GroupVersionResource", 1), `&`, ``, 1) + `,`, - `SubResource:` + fmt.Sprintf("%v", this.SubResource) + `,`, - `Name:` + fmt.Sprintf("%v", this.Name) + `,`, - `Namespace:` + fmt.Sprintf("%v", this.Namespace) + `,`, - `Operation:` + fmt.Sprintf("%v", this.Operation) + `,`, - `UserInfo:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.UserInfo), "UserInfo", "v11.UserInfo", 1), `&`, ``, 1) + `,`, - `Object:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Object), "RawExtension", "runtime.RawExtension", 1), `&`, ``, 1) + `,`, - `OldObject:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.OldObject), "RawExtension", "runtime.RawExtension", 1), `&`, ``, 1) + `,`, - `DryRun:` + valueToStringGenerated(this.DryRun) + `,`, - `Options:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Options), "RawExtension", "runtime.RawExtension", 1), `&`, ``, 1) + `,`, - `RequestKind:` + strings.Replace(fmt.Sprintf("%v", this.RequestKind), "GroupVersionKind", "v1.GroupVersionKind", 1) + `,`, - `RequestResource:` + strings.Replace(fmt.Sprintf("%v", this.RequestResource), "GroupVersionResource", "v1.GroupVersionResource", 1) + `,`, - `RequestSubResource:` + fmt.Sprintf("%v", this.RequestSubResource) + `,`, - `}`, - }, "") - return s -} -func (this *AdmissionResponse) String() string { - if this == nil { - return "nil" - } - keysForAuditAnnotations := make([]string, 0, len(this.AuditAnnotations)) - for k := range this.AuditAnnotations { - keysForAuditAnnotations = append(keysForAuditAnnotations, k) - } - github_com_gogo_protobuf_sortkeys.Strings(keysForAuditAnnotations) - mapStringForAuditAnnotations := "map[string]string{" - for _, k := range keysForAuditAnnotations { - mapStringForAuditAnnotations += fmt.Sprintf("%v: %v,", k, this.AuditAnnotations[k]) - } - mapStringForAuditAnnotations += "}" - s := strings.Join([]string{`&AdmissionResponse{`, - `UID:` + fmt.Sprintf("%v", this.UID) + `,`, - `Allowed:` + fmt.Sprintf("%v", this.Allowed) + `,`, - `Result:` + strings.Replace(fmt.Sprintf("%v", this.Result), "Status", "v1.Status", 1) + `,`, - `Patch:` + valueToStringGenerated(this.Patch) + `,`, - `PatchType:` + valueToStringGenerated(this.PatchType) + `,`, - `AuditAnnotations:` + mapStringForAuditAnnotations + `,`, - `Warnings:` + fmt.Sprintf("%v", this.Warnings) + `,`, - `}`, - }, "") - return s -} -func (this *AdmissionReview) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&AdmissionReview{`, - `Request:` + strings.Replace(this.Request.String(), "AdmissionRequest", "AdmissionRequest", 1) + `,`, - `Response:` + strings.Replace(this.Response.String(), "AdmissionResponse", "AdmissionResponse", 1) + `,`, - `}`, - }, "") - return s -} -func valueToStringGenerated(v interface{}) string { - rv := reflect.ValueOf(v) - if rv.IsNil() { - return "nil" - } - pv := reflect.Indirect(rv).Interface() - return fmt.Sprintf("*%v", pv) -} -func (m *AdmissionRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: AdmissionRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AdmissionRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field UID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.UID = k8s_io_apimachinery_pkg_types.UID(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Kind", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Kind.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Resource", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Resource.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SubResource", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SubResource = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Name = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Namespace", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Namespace = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Operation", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Operation = Operation(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field UserInfo", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.UserInfo.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 9: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Object", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Object.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 10: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field OldObject", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.OldObject.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 11: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field DryRun", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - b := bool(v != 0) - m.DryRun = &b - case 12: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Options", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Options.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 13: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RequestKind", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.RequestKind == nil { - m.RequestKind = &v1.GroupVersionKind{} - } - if err := m.RequestKind.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 14: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RequestResource", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.RequestResource == nil { - m.RequestResource = &v1.GroupVersionResource{} - } - if err := m.RequestResource.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 15: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RequestSubResource", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RequestSubResource = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenerated(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenerated - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *AdmissionResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: AdmissionResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AdmissionResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field UID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.UID = k8s_io_apimachinery_pkg_types.UID(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Allowed", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Allowed = bool(v != 0) - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Result", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Result == nil { - m.Result = &v1.Status{} - } - if err := m.Result.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Patch", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Patch = append(m.Patch[:0], dAtA[iNdEx:postIndex]...) - if m.Patch == nil { - m.Patch = []byte{} - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PatchType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - s := PatchType(dAtA[iNdEx:postIndex]) - m.PatchType = &s - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AuditAnnotations", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.AuditAnnotations == nil { - m.AuditAnnotations = make(map[string]string) - } - var mapkey string - var mapvalue string - for iNdEx < postIndex { - entryPreIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - if fieldNum == 1 { - var stringLenmapkey uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLenmapkey |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLenmapkey := int(stringLenmapkey) - if intStringLenmapkey < 0 { - return ErrInvalidLengthGenerated - } - postStringIndexmapkey := iNdEx + intStringLenmapkey - if postStringIndexmapkey < 0 { - return ErrInvalidLengthGenerated - } - if postStringIndexmapkey > l { - return io.ErrUnexpectedEOF - } - mapkey = string(dAtA[iNdEx:postStringIndexmapkey]) - iNdEx = postStringIndexmapkey - } else if fieldNum == 2 { - var stringLenmapvalue uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLenmapvalue |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLenmapvalue := int(stringLenmapvalue) - if intStringLenmapvalue < 0 { - return ErrInvalidLengthGenerated - } - postStringIndexmapvalue := iNdEx + intStringLenmapvalue - if postStringIndexmapvalue < 0 { - return ErrInvalidLengthGenerated - } - if postStringIndexmapvalue > l { - return io.ErrUnexpectedEOF - } - mapvalue = string(dAtA[iNdEx:postStringIndexmapvalue]) - iNdEx = postStringIndexmapvalue - } else { - iNdEx = entryPreIndex - skippy, err := skipGenerated(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenerated - } - if (iNdEx + skippy) > postIndex { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - m.AuditAnnotations[mapkey] = mapvalue - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Warnings", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Warnings = append(m.Warnings, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenerated(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenerated - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *AdmissionReview) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: AdmissionReview: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AdmissionReview: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Request", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Request == nil { - m.Request = &AdmissionRequest{} - } - if err := m.Request.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Response", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Response == nil { - m.Response = &AdmissionResponse{} - } - if err := m.Response.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenerated(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenerated - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipGenerated(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenerated - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenerated - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenerated - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthGenerated - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupGenerated - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthGenerated - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthGenerated = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowGenerated = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupGenerated = fmt.Errorf("proto: unexpected end of group") -) diff --git a/vendor/k8s.io/api/admission/v1/generated.proto b/vendor/k8s.io/api/admission/v1/generated.proto deleted file mode 100644 index 9648aa58f..000000000 --- a/vendor/k8s.io/api/admission/v1/generated.proto +++ /dev/null @@ -1,167 +0,0 @@ -/* -Copyright 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. -*/ - - -// This file was autogenerated by go-to-protobuf. Do not edit it manually! - -syntax = "proto2"; - -package k8s.io.api.admission.v1; - -import "k8s.io/api/authentication/v1/generated.proto"; -import "k8s.io/apimachinery/pkg/apis/meta/v1/generated.proto"; -import "k8s.io/apimachinery/pkg/runtime/generated.proto"; -import "k8s.io/apimachinery/pkg/runtime/schema/generated.proto"; - -// Package-wide variables from generator "generated". -option go_package = "k8s.io/api/admission/v1"; - -// AdmissionRequest describes the admission.Attributes for the admission request. -message AdmissionRequest { - // UID is an identifier for the individual request/response. It allows us to distinguish instances of requests which are - // otherwise identical (parallel requests, requests when earlier requests did not modify etc) - // The UID is meant to track the round trip (request/response) between the KAS and the WebHook, not the user request. - // It is suitable for correlating log entries between the webhook and apiserver, for either auditing or debugging. - optional string uid = 1; - - // Kind is the fully-qualified type of object being submitted (for example, v1.Pod or autoscaling.v1.Scale) - optional .k8s.io.apimachinery.pkg.apis.meta.v1.GroupVersionKind kind = 2; - - // Resource is the fully-qualified resource being requested (for example, v1.pods) - optional .k8s.io.apimachinery.pkg.apis.meta.v1.GroupVersionResource resource = 3; - - // SubResource is the subresource being requested, if any (for example, "status" or "scale") - // +optional - optional string subResource = 4; - - // RequestKind is the fully-qualified type of the original API request (for example, v1.Pod or autoscaling.v1.Scale). - // If this is specified and differs from the value in "kind", an equivalent match and conversion was performed. - // - // For example, if deployments can be modified via apps/v1 and apps/v1beta1, and a webhook registered a rule of - // `apiGroups:["apps"], apiVersions:["v1"], resources: ["deployments"]` and `matchPolicy: Equivalent`, - // an API request to apps/v1beta1 deployments would be converted and sent to the webhook - // with `kind: {group:"apps", version:"v1", kind:"Deployment"}` (matching the rule the webhook registered for), - // and `requestKind: {group:"apps", version:"v1beta1", kind:"Deployment"}` (indicating the kind of the original API request). - // - // See documentation for the "matchPolicy" field in the webhook configuration type for more details. - // +optional - optional .k8s.io.apimachinery.pkg.apis.meta.v1.GroupVersionKind requestKind = 13; - - // RequestResource is the fully-qualified resource of the original API request (for example, v1.pods). - // If this is specified and differs from the value in "resource", an equivalent match and conversion was performed. - // - // For example, if deployments can be modified via apps/v1 and apps/v1beta1, and a webhook registered a rule of - // `apiGroups:["apps"], apiVersions:["v1"], resources: ["deployments"]` and `matchPolicy: Equivalent`, - // an API request to apps/v1beta1 deployments would be converted and sent to the webhook - // with `resource: {group:"apps", version:"v1", resource:"deployments"}` (matching the resource the webhook registered for), - // and `requestResource: {group:"apps", version:"v1beta1", resource:"deployments"}` (indicating the resource of the original API request). - // - // See documentation for the "matchPolicy" field in the webhook configuration type. - // +optional - optional .k8s.io.apimachinery.pkg.apis.meta.v1.GroupVersionResource requestResource = 14; - - // RequestSubResource is the name of the subresource of the original API request, if any (for example, "status" or "scale") - // If this is specified and differs from the value in "subResource", an equivalent match and conversion was performed. - // See documentation for the "matchPolicy" field in the webhook configuration type. - // +optional - optional string requestSubResource = 15; - - // Name is the name of the object as presented in the request. On a CREATE operation, the client may omit name and - // rely on the server to generate the name. If that is the case, this field will contain an empty string. - // +optional - optional string name = 5; - - // Namespace is the namespace associated with the request (if any). - // +optional - optional string namespace = 6; - - // Operation is the operation being performed. This may be different than the operation - // requested. e.g. a patch can result in either a CREATE or UPDATE Operation. - optional string operation = 7; - - // UserInfo is information about the requesting user - optional .k8s.io.api.authentication.v1.UserInfo userInfo = 8; - - // Object is the object from the incoming request. - // +optional - optional .k8s.io.apimachinery.pkg.runtime.RawExtension object = 9; - - // OldObject is the existing object. Only populated for DELETE and UPDATE requests. - // +optional - optional .k8s.io.apimachinery.pkg.runtime.RawExtension oldObject = 10; - - // DryRun indicates that modifications will definitely not be persisted for this request. - // Defaults to false. - // +optional - optional bool dryRun = 11; - - // Options is the operation option structure of the operation being performed. - // e.g. `meta.k8s.io/v1.DeleteOptions` or `meta.k8s.io/v1.CreateOptions`. This may be - // different than the options the caller provided. e.g. for a patch request the performed - // Operation might be a CREATE, in which case the Options will a - // `meta.k8s.io/v1.CreateOptions` even though the caller provided `meta.k8s.io/v1.PatchOptions`. - // +optional - optional .k8s.io.apimachinery.pkg.runtime.RawExtension options = 12; -} - -// AdmissionResponse describes an admission response. -message AdmissionResponse { - // UID is an identifier for the individual request/response. - // This must be copied over from the corresponding AdmissionRequest. - optional string uid = 1; - - // Allowed indicates whether or not the admission request was permitted. - optional bool allowed = 2; - - // Result contains extra details into why an admission request was denied. - // This field IS NOT consulted in any way if "Allowed" is "true". - // +optional - optional .k8s.io.apimachinery.pkg.apis.meta.v1.Status status = 3; - - // The patch body. Currently we only support "JSONPatch" which implements RFC 6902. - // +optional - optional bytes patch = 4; - - // The type of Patch. Currently we only allow "JSONPatch". - // +optional - optional string patchType = 5; - - // AuditAnnotations is an unstructured key value map set by remote admission controller (e.g. error=image-blacklisted). - // MutatingAdmissionWebhook and ValidatingAdmissionWebhook admission controller will prefix the keys with - // admission webhook name (e.g. imagepolicy.example.com/error=image-blacklisted). AuditAnnotations will be provided by - // the admission webhook to add additional context to the audit log for this request. - // +optional - map auditAnnotations = 6; - - // warnings is a list of warning messages to return to the requesting API client. - // Warning messages describe a problem the client making the API request should correct or be aware of. - // Limit warnings to 120 characters if possible. - // Warnings over 256 characters and large numbers of warnings may be truncated. - // +optional - repeated string warnings = 7; -} - -// AdmissionReview describes an admission review request/response. -message AdmissionReview { - // Request describes the attributes for the admission request. - // +optional - optional AdmissionRequest request = 1; - - // Response describes the attributes for the admission response. - // +optional - optional AdmissionResponse response = 2; -} - diff --git a/vendor/k8s.io/api/admission/v1/register.go b/vendor/k8s.io/api/admission/v1/register.go deleted file mode 100644 index 79000535c..000000000 --- a/vendor/k8s.io/api/admission/v1/register.go +++ /dev/null @@ -1,53 +0,0 @@ -/* -Copyright 2019 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 v1 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -// GroupName is the group name for this API. -const GroupName = "admission.k8s.io" - -// SchemeGroupVersion is group version used to register these objects -var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: "v1"} - -// Resource takes an unqualified resource and returns a Group qualified GroupResource -func Resource(resource string) schema.GroupResource { - return SchemeGroupVersion.WithResource(resource).GroupResource() -} - -// TODO: move SchemeBuilder with zz_generated.deepcopy.go to k8s.io/api. -// localSchemeBuilder and AddToScheme will stay in k8s.io/kubernetes. -var ( - // SchemeBuilder points to a list of functions added to Scheme. - SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) - localSchemeBuilder = &SchemeBuilder - // AddToScheme is a common registration function for mapping packaged scoped group & version keys to a scheme. - AddToScheme = localSchemeBuilder.AddToScheme -) - -// Adds the list of known types to the given scheme. -func addKnownTypes(scheme *runtime.Scheme) error { - scheme.AddKnownTypes(SchemeGroupVersion, - &AdmissionReview{}, - ) - metav1.AddToGroupVersion(scheme, SchemeGroupVersion) - return nil -} diff --git a/vendor/k8s.io/api/admission/v1/types.go b/vendor/k8s.io/api/admission/v1/types.go deleted file mode 100644 index 2def92da5..000000000 --- a/vendor/k8s.io/api/admission/v1/types.go +++ /dev/null @@ -1,170 +0,0 @@ -/* -Copyright 2019 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 v1 - -import ( - authenticationv1 "k8s.io/api/authentication/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/types" -) - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +k8s:prerelease-lifecycle-gen:introduced=1.19 - -// AdmissionReview describes an admission review request/response. -type AdmissionReview struct { - metav1.TypeMeta `json:",inline"` - // Request describes the attributes for the admission request. - // +optional - Request *AdmissionRequest `json:"request,omitempty" protobuf:"bytes,1,opt,name=request"` - // Response describes the attributes for the admission response. - // +optional - Response *AdmissionResponse `json:"response,omitempty" protobuf:"bytes,2,opt,name=response"` -} - -// AdmissionRequest describes the admission.Attributes for the admission request. -type AdmissionRequest struct { - // UID is an identifier for the individual request/response. It allows us to distinguish instances of requests which are - // otherwise identical (parallel requests, requests when earlier requests did not modify etc) - // The UID is meant to track the round trip (request/response) between the KAS and the WebHook, not the user request. - // It is suitable for correlating log entries between the webhook and apiserver, for either auditing or debugging. - UID types.UID `json:"uid" protobuf:"bytes,1,opt,name=uid"` - // Kind is the fully-qualified type of object being submitted (for example, v1.Pod or autoscaling.v1.Scale) - Kind metav1.GroupVersionKind `json:"kind" protobuf:"bytes,2,opt,name=kind"` - // Resource is the fully-qualified resource being requested (for example, v1.pods) - Resource metav1.GroupVersionResource `json:"resource" protobuf:"bytes,3,opt,name=resource"` - // SubResource is the subresource being requested, if any (for example, "status" or "scale") - // +optional - SubResource string `json:"subResource,omitempty" protobuf:"bytes,4,opt,name=subResource"` - - // RequestKind is the fully-qualified type of the original API request (for example, v1.Pod or autoscaling.v1.Scale). - // If this is specified and differs from the value in "kind", an equivalent match and conversion was performed. - // - // For example, if deployments can be modified via apps/v1 and apps/v1beta1, and a webhook registered a rule of - // `apiGroups:["apps"], apiVersions:["v1"], resources: ["deployments"]` and `matchPolicy: Equivalent`, - // an API request to apps/v1beta1 deployments would be converted and sent to the webhook - // with `kind: {group:"apps", version:"v1", kind:"Deployment"}` (matching the rule the webhook registered for), - // and `requestKind: {group:"apps", version:"v1beta1", kind:"Deployment"}` (indicating the kind of the original API request). - // - // See documentation for the "matchPolicy" field in the webhook configuration type for more details. - // +optional - RequestKind *metav1.GroupVersionKind `json:"requestKind,omitempty" protobuf:"bytes,13,opt,name=requestKind"` - // RequestResource is the fully-qualified resource of the original API request (for example, v1.pods). - // If this is specified and differs from the value in "resource", an equivalent match and conversion was performed. - // - // For example, if deployments can be modified via apps/v1 and apps/v1beta1, and a webhook registered a rule of - // `apiGroups:["apps"], apiVersions:["v1"], resources: ["deployments"]` and `matchPolicy: Equivalent`, - // an API request to apps/v1beta1 deployments would be converted and sent to the webhook - // with `resource: {group:"apps", version:"v1", resource:"deployments"}` (matching the resource the webhook registered for), - // and `requestResource: {group:"apps", version:"v1beta1", resource:"deployments"}` (indicating the resource of the original API request). - // - // See documentation for the "matchPolicy" field in the webhook configuration type. - // +optional - RequestResource *metav1.GroupVersionResource `json:"requestResource,omitempty" protobuf:"bytes,14,opt,name=requestResource"` - // RequestSubResource is the name of the subresource of the original API request, if any (for example, "status" or "scale") - // If this is specified and differs from the value in "subResource", an equivalent match and conversion was performed. - // See documentation for the "matchPolicy" field in the webhook configuration type. - // +optional - RequestSubResource string `json:"requestSubResource,omitempty" protobuf:"bytes,15,opt,name=requestSubResource"` - - // Name is the name of the object as presented in the request. On a CREATE operation, the client may omit name and - // rely on the server to generate the name. If that is the case, this field will contain an empty string. - // +optional - Name string `json:"name,omitempty" protobuf:"bytes,5,opt,name=name"` - // Namespace is the namespace associated with the request (if any). - // +optional - Namespace string `json:"namespace,omitempty" protobuf:"bytes,6,opt,name=namespace"` - // Operation is the operation being performed. This may be different than the operation - // requested. e.g. a patch can result in either a CREATE or UPDATE Operation. - Operation Operation `json:"operation" protobuf:"bytes,7,opt,name=operation"` - // UserInfo is information about the requesting user - UserInfo authenticationv1.UserInfo `json:"userInfo" protobuf:"bytes,8,opt,name=userInfo"` - // Object is the object from the incoming request. - // +optional - Object runtime.RawExtension `json:"object,omitempty" protobuf:"bytes,9,opt,name=object"` - // OldObject is the existing object. Only populated for DELETE and UPDATE requests. - // +optional - OldObject runtime.RawExtension `json:"oldObject,omitempty" protobuf:"bytes,10,opt,name=oldObject"` - // DryRun indicates that modifications will definitely not be persisted for this request. - // Defaults to false. - // +optional - DryRun *bool `json:"dryRun,omitempty" protobuf:"varint,11,opt,name=dryRun"` - // Options is the operation option structure of the operation being performed. - // e.g. `meta.k8s.io/v1.DeleteOptions` or `meta.k8s.io/v1.CreateOptions`. This may be - // different than the options the caller provided. e.g. for a patch request the performed - // Operation might be a CREATE, in which case the Options will a - // `meta.k8s.io/v1.CreateOptions` even though the caller provided `meta.k8s.io/v1.PatchOptions`. - // +optional - Options runtime.RawExtension `json:"options,omitempty" protobuf:"bytes,12,opt,name=options"` -} - -// AdmissionResponse describes an admission response. -type AdmissionResponse struct { - // UID is an identifier for the individual request/response. - // This must be copied over from the corresponding AdmissionRequest. - UID types.UID `json:"uid" protobuf:"bytes,1,opt,name=uid"` - - // Allowed indicates whether or not the admission request was permitted. - Allowed bool `json:"allowed" protobuf:"varint,2,opt,name=allowed"` - - // Result contains extra details into why an admission request was denied. - // This field IS NOT consulted in any way if "Allowed" is "true". - // +optional - Result *metav1.Status `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` - - // The patch body. Currently we only support "JSONPatch" which implements RFC 6902. - // +optional - Patch []byte `json:"patch,omitempty" protobuf:"bytes,4,opt,name=patch"` - - // The type of Patch. Currently we only allow "JSONPatch". - // +optional - PatchType *PatchType `json:"patchType,omitempty" protobuf:"bytes,5,opt,name=patchType"` - - // AuditAnnotations is an unstructured key value map set by remote admission controller (e.g. error=image-blacklisted). - // MutatingAdmissionWebhook and ValidatingAdmissionWebhook admission controller will prefix the keys with - // admission webhook name (e.g. imagepolicy.example.com/error=image-blacklisted). AuditAnnotations will be provided by - // the admission webhook to add additional context to the audit log for this request. - // +optional - AuditAnnotations map[string]string `json:"auditAnnotations,omitempty" protobuf:"bytes,6,opt,name=auditAnnotations"` - - // warnings is a list of warning messages to return to the requesting API client. - // Warning messages describe a problem the client making the API request should correct or be aware of. - // Limit warnings to 120 characters if possible. - // Warnings over 256 characters and large numbers of warnings may be truncated. - // +optional - Warnings []string `json:"warnings,omitempty" protobuf:"bytes,7,rep,name=warnings"` -} - -// PatchType is the type of patch being used to represent the mutated object -type PatchType string - -// PatchType constants. -const ( - PatchTypeJSONPatch PatchType = "JSONPatch" -) - -// Operation is the type of resource operation being checked for admission control -type Operation string - -// Operation constants -const ( - Create Operation = "CREATE" - Update Operation = "UPDATE" - Delete Operation = "DELETE" - Connect Operation = "CONNECT" -) diff --git a/vendor/k8s.io/api/admission/v1/types_swagger_doc_generated.go b/vendor/k8s.io/api/admission/v1/types_swagger_doc_generated.go deleted file mode 100644 index 1395a7e10..000000000 --- a/vendor/k8s.io/api/admission/v1/types_swagger_doc_generated.go +++ /dev/null @@ -1,78 +0,0 @@ -/* -Copyright 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 v1 - -// This file contains a collection of methods that can be used from go-restful to -// generate Swagger API documentation for its models. Please read this PR for more -// information on the implementation: https://github.com/emicklei/go-restful/pull/215 -// -// TODOs are ignored from the parser (e.g. TODO(andronat):... || TODO:...) if and only if -// they are on one line! For multiple line or blocks that you want to ignore use ---. -// Any context after a --- is ignored. -// -// Those methods can be generated by using hack/update-codegen.sh - -// AUTO-GENERATED FUNCTIONS START HERE. DO NOT EDIT. -var map_AdmissionRequest = map[string]string{ - "": "AdmissionRequest describes the admission.Attributes for the admission request.", - "uid": "UID is an identifier for the individual request/response. It allows us to distinguish instances of requests which are otherwise identical (parallel requests, requests when earlier requests did not modify etc) The UID is meant to track the round trip (request/response) between the KAS and the WebHook, not the user request. It is suitable for correlating log entries between the webhook and apiserver, for either auditing or debugging.", - "kind": "Kind is the fully-qualified type of object being submitted (for example, v1.Pod or autoscaling.v1.Scale)", - "resource": "Resource is the fully-qualified resource being requested (for example, v1.pods)", - "subResource": "SubResource is the subresource being requested, if any (for example, \"status\" or \"scale\")", - "requestKind": "RequestKind is the fully-qualified type of the original API request (for example, v1.Pod or autoscaling.v1.Scale). If this is specified and differs from the value in \"kind\", an equivalent match and conversion was performed.\n\nFor example, if deployments can be modified via apps/v1 and apps/v1beta1, and a webhook registered a rule of `apiGroups:[\"apps\"], apiVersions:[\"v1\"], resources: [\"deployments\"]` and `matchPolicy: Equivalent`, an API request to apps/v1beta1 deployments would be converted and sent to the webhook with `kind: {group:\"apps\", version:\"v1\", kind:\"Deployment\"}` (matching the rule the webhook registered for), and `requestKind: {group:\"apps\", version:\"v1beta1\", kind:\"Deployment\"}` (indicating the kind of the original API request).\n\nSee documentation for the \"matchPolicy\" field in the webhook configuration type for more details.", - "requestResource": "RequestResource is the fully-qualified resource of the original API request (for example, v1.pods). If this is specified and differs from the value in \"resource\", an equivalent match and conversion was performed.\n\nFor example, if deployments can be modified via apps/v1 and apps/v1beta1, and a webhook registered a rule of `apiGroups:[\"apps\"], apiVersions:[\"v1\"], resources: [\"deployments\"]` and `matchPolicy: Equivalent`, an API request to apps/v1beta1 deployments would be converted and sent to the webhook with `resource: {group:\"apps\", version:\"v1\", resource:\"deployments\"}` (matching the resource the webhook registered for), and `requestResource: {group:\"apps\", version:\"v1beta1\", resource:\"deployments\"}` (indicating the resource of the original API request).\n\nSee documentation for the \"matchPolicy\" field in the webhook configuration type.", - "requestSubResource": "RequestSubResource is the name of the subresource of the original API request, if any (for example, \"status\" or \"scale\") If this is specified and differs from the value in \"subResource\", an equivalent match and conversion was performed. See documentation for the \"matchPolicy\" field in the webhook configuration type.", - "name": "Name is the name of the object as presented in the request. On a CREATE operation, the client may omit name and rely on the server to generate the name. If that is the case, this field will contain an empty string.", - "namespace": "Namespace is the namespace associated with the request (if any).", - "operation": "Operation is the operation being performed. This may be different than the operation requested. e.g. a patch can result in either a CREATE or UPDATE Operation.", - "userInfo": "UserInfo is information about the requesting user", - "object": "Object is the object from the incoming request.", - "oldObject": "OldObject is the existing object. Only populated for DELETE and UPDATE requests.", - "dryRun": "DryRun indicates that modifications will definitely not be persisted for this request. Defaults to false.", - "options": "Options is the operation option structure of the operation being performed. e.g. `meta.k8s.io/v1.DeleteOptions` or `meta.k8s.io/v1.CreateOptions`. This may be different than the options the caller provided. e.g. for a patch request the performed Operation might be a CREATE, in which case the Options will a `meta.k8s.io/v1.CreateOptions` even though the caller provided `meta.k8s.io/v1.PatchOptions`.", -} - -func (AdmissionRequest) SwaggerDoc() map[string]string { - return map_AdmissionRequest -} - -var map_AdmissionResponse = map[string]string{ - "": "AdmissionResponse describes an admission response.", - "uid": "UID is an identifier for the individual request/response. This must be copied over from the corresponding AdmissionRequest.", - "allowed": "Allowed indicates whether or not the admission request was permitted.", - "status": "Result contains extra details into why an admission request was denied. This field IS NOT consulted in any way if \"Allowed\" is \"true\".", - "patch": "The patch body. Currently we only support \"JSONPatch\" which implements RFC 6902.", - "patchType": "The type of Patch. Currently we only allow \"JSONPatch\".", - "auditAnnotations": "AuditAnnotations is an unstructured key value map set by remote admission controller (e.g. error=image-blacklisted). MutatingAdmissionWebhook and ValidatingAdmissionWebhook admission controller will prefix the keys with admission webhook name (e.g. imagepolicy.example.com/error=image-blacklisted). AuditAnnotations will be provided by the admission webhook to add additional context to the audit log for this request.", - "warnings": "warnings is a list of warning messages to return to the requesting API client. Warning messages describe a problem the client making the API request should correct or be aware of. Limit warnings to 120 characters if possible. Warnings over 256 characters and large numbers of warnings may be truncated.", -} - -func (AdmissionResponse) SwaggerDoc() map[string]string { - return map_AdmissionResponse -} - -var map_AdmissionReview = map[string]string{ - "": "AdmissionReview describes an admission review request/response.", - "request": "Request describes the attributes for the admission request.", - "response": "Response describes the attributes for the admission response.", -} - -func (AdmissionReview) SwaggerDoc() map[string]string { - return map_AdmissionReview -} - -// AUTO-GENERATED FUNCTIONS END HERE diff --git a/vendor/k8s.io/api/admission/v1/zz_generated.deepcopy.go b/vendor/k8s.io/api/admission/v1/zz_generated.deepcopy.go deleted file mode 100644 index d35688285..000000000 --- a/vendor/k8s.io/api/admission/v1/zz_generated.deepcopy.go +++ /dev/null @@ -1,142 +0,0 @@ -//go:build !ignore_autogenerated -// +build !ignore_autogenerated - -/* -Copyright 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 deepcopy-gen. DO NOT EDIT. - -package v1 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" -) - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *AdmissionRequest) DeepCopyInto(out *AdmissionRequest) { - *out = *in - out.Kind = in.Kind - out.Resource = in.Resource - if in.RequestKind != nil { - in, out := &in.RequestKind, &out.RequestKind - *out = new(metav1.GroupVersionKind) - **out = **in - } - if in.RequestResource != nil { - in, out := &in.RequestResource, &out.RequestResource - *out = new(metav1.GroupVersionResource) - **out = **in - } - in.UserInfo.DeepCopyInto(&out.UserInfo) - in.Object.DeepCopyInto(&out.Object) - in.OldObject.DeepCopyInto(&out.OldObject) - if in.DryRun != nil { - in, out := &in.DryRun, &out.DryRun - *out = new(bool) - **out = **in - } - in.Options.DeepCopyInto(&out.Options) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AdmissionRequest. -func (in *AdmissionRequest) DeepCopy() *AdmissionRequest { - if in == nil { - return nil - } - out := new(AdmissionRequest) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *AdmissionResponse) DeepCopyInto(out *AdmissionResponse) { - *out = *in - if in.Result != nil { - in, out := &in.Result, &out.Result - *out = new(metav1.Status) - (*in).DeepCopyInto(*out) - } - if in.Patch != nil { - in, out := &in.Patch, &out.Patch - *out = make([]byte, len(*in)) - copy(*out, *in) - } - if in.PatchType != nil { - in, out := &in.PatchType, &out.PatchType - *out = new(PatchType) - **out = **in - } - if in.AuditAnnotations != nil { - in, out := &in.AuditAnnotations, &out.AuditAnnotations - *out = make(map[string]string, len(*in)) - for key, val := range *in { - (*out)[key] = val - } - } - if in.Warnings != nil { - in, out := &in.Warnings, &out.Warnings - *out = make([]string, len(*in)) - copy(*out, *in) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AdmissionResponse. -func (in *AdmissionResponse) DeepCopy() *AdmissionResponse { - if in == nil { - return nil - } - out := new(AdmissionResponse) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *AdmissionReview) DeepCopyInto(out *AdmissionReview) { - *out = *in - out.TypeMeta = in.TypeMeta - if in.Request != nil { - in, out := &in.Request, &out.Request - *out = new(AdmissionRequest) - (*in).DeepCopyInto(*out) - } - if in.Response != nil { - in, out := &in.Response, &out.Response - *out = new(AdmissionResponse) - (*in).DeepCopyInto(*out) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AdmissionReview. -func (in *AdmissionReview) DeepCopy() *AdmissionReview { - if in == nil { - return nil - } - out := new(AdmissionReview) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *AdmissionReview) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} diff --git a/vendor/k8s.io/api/admission/v1/zz_generated.prerelease-lifecycle.go b/vendor/k8s.io/api/admission/v1/zz_generated.prerelease-lifecycle.go deleted file mode 100644 index ac81d993c..000000000 --- a/vendor/k8s.io/api/admission/v1/zz_generated.prerelease-lifecycle.go +++ /dev/null @@ -1,28 +0,0 @@ -//go:build !ignore_autogenerated -// +build !ignore_autogenerated - -/* -Copyright 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 prerelease-lifecycle-gen. DO NOT EDIT. - -package v1 - -// APILifecycleIntroduced is an autogenerated function, returning the release in which the API struct was introduced as int versions of major and minor for comparison. -// It is controlled by "k8s:prerelease-lifecycle-gen:introduced" tags in types.go. -func (in *AdmissionReview) APILifecycleIntroduced() (major, minor int) { - return 1, 19 -} diff --git a/vendor/k8s.io/api/admission/v1beta1/doc.go b/vendor/k8s.io/api/admission/v1beta1/doc.go deleted file mode 100644 index a5669022a..000000000 --- a/vendor/k8s.io/api/admission/v1beta1/doc.go +++ /dev/null @@ -1,24 +0,0 @@ -/* -Copyright 2017 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// +k8s:deepcopy-gen=package -// +k8s:protobuf-gen=package -// +k8s:openapi-gen=false -// +k8s:prerelease-lifecycle-gen=true - -// +groupName=admission.k8s.io - -package v1beta1 // import "k8s.io/api/admission/v1beta1" diff --git a/vendor/k8s.io/api/admission/v1beta1/generated.pb.go b/vendor/k8s.io/api/admission/v1beta1/generated.pb.go deleted file mode 100644 index 22147cbe9..000000000 --- a/vendor/k8s.io/api/admission/v1beta1/generated.pb.go +++ /dev/null @@ -1,1782 +0,0 @@ -/* -Copyright 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 protoc-gen-gogo. DO NOT EDIT. -// source: k8s.io/api/admission/v1beta1/generated.proto - -package v1beta1 - -import ( - fmt "fmt" - - io "io" - - proto "github.com/gogo/protobuf/proto" - github_com_gogo_protobuf_sortkeys "github.com/gogo/protobuf/sortkeys" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - math "math" - math_bits "math/bits" - reflect "reflect" - strings "strings" - - k8s_io_apimachinery_pkg_types "k8s.io/apimachinery/pkg/types" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package - -func (m *AdmissionRequest) Reset() { *m = AdmissionRequest{} } -func (*AdmissionRequest) ProtoMessage() {} -func (*AdmissionRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_d8f147b43c61e73e, []int{0} -} -func (m *AdmissionRequest) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *AdmissionRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil -} -func (m *AdmissionRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_AdmissionRequest.Merge(m, src) -} -func (m *AdmissionRequest) XXX_Size() int { - return m.Size() -} -func (m *AdmissionRequest) XXX_DiscardUnknown() { - xxx_messageInfo_AdmissionRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_AdmissionRequest proto.InternalMessageInfo - -func (m *AdmissionResponse) Reset() { *m = AdmissionResponse{} } -func (*AdmissionResponse) ProtoMessage() {} -func (*AdmissionResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_d8f147b43c61e73e, []int{1} -} -func (m *AdmissionResponse) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *AdmissionResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil -} -func (m *AdmissionResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_AdmissionResponse.Merge(m, src) -} -func (m *AdmissionResponse) XXX_Size() int { - return m.Size() -} -func (m *AdmissionResponse) XXX_DiscardUnknown() { - xxx_messageInfo_AdmissionResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_AdmissionResponse proto.InternalMessageInfo - -func (m *AdmissionReview) Reset() { *m = AdmissionReview{} } -func (*AdmissionReview) ProtoMessage() {} -func (*AdmissionReview) Descriptor() ([]byte, []int) { - return fileDescriptor_d8f147b43c61e73e, []int{2} -} -func (m *AdmissionReview) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *AdmissionReview) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - b = b[:cap(b)] - n, err := m.MarshalToSizedBuffer(b) - if err != nil { - return nil, err - } - return b[:n], nil -} -func (m *AdmissionReview) XXX_Merge(src proto.Message) { - xxx_messageInfo_AdmissionReview.Merge(m, src) -} -func (m *AdmissionReview) XXX_Size() int { - return m.Size() -} -func (m *AdmissionReview) XXX_DiscardUnknown() { - xxx_messageInfo_AdmissionReview.DiscardUnknown(m) -} - -var xxx_messageInfo_AdmissionReview proto.InternalMessageInfo - -func init() { - proto.RegisterType((*AdmissionRequest)(nil), "k8s.io.api.admission.v1beta1.AdmissionRequest") - proto.RegisterType((*AdmissionResponse)(nil), "k8s.io.api.admission.v1beta1.AdmissionResponse") - proto.RegisterMapType((map[string]string)(nil), "k8s.io.api.admission.v1beta1.AdmissionResponse.AuditAnnotationsEntry") - proto.RegisterType((*AdmissionReview)(nil), "k8s.io.api.admission.v1beta1.AdmissionReview") -} - -func init() { - proto.RegisterFile("k8s.io/api/admission/v1beta1/generated.proto", fileDescriptor_d8f147b43c61e73e) -} - -var fileDescriptor_d8f147b43c61e73e = []byte{ - // 911 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x56, 0x4f, 0x6f, 0x1b, 0x45, - 0x14, 0xf7, 0xd6, 0x8e, 0xed, 0x1d, 0x87, 0xda, 0x9d, 0x82, 0xb4, 0xb2, 0xaa, 0xb5, 0xc9, 0x01, - 0x19, 0xa9, 0x9d, 0x25, 0x11, 0x54, 0x51, 0xc5, 0x25, 0x4b, 0x22, 0x14, 0x90, 0x9a, 0x68, 0x5a, - 0x43, 0xe1, 0x80, 0x34, 0xb6, 0xa7, 0xf6, 0x60, 0x7b, 0x66, 0xd9, 0x99, 0x4d, 0xf0, 0x8d, 0x3b, - 0x17, 0xbe, 0x01, 0x5f, 0x80, 0x6f, 0xc1, 0x25, 0xc7, 0x1e, 0x7b, 0xb2, 0x88, 0xf9, 0x16, 0x39, - 0xa1, 0x99, 0x9d, 0xf5, 0x3a, 0x4e, 0x52, 0xfa, 0xef, 0x94, 0x7d, 0x7f, 0x7e, 0xbf, 0xf7, 0xf2, - 0x7b, 0xfb, 0xde, 0x1a, 0xdc, 0x1f, 0xef, 0x4a, 0xc4, 0x44, 0x40, 0x22, 0x16, 0x90, 0xc1, 0x94, - 0x49, 0xc9, 0x04, 0x0f, 0x4e, 0xb6, 0x7b, 0x54, 0x91, 0xed, 0x60, 0x48, 0x39, 0x8d, 0x89, 0xa2, - 0x03, 0x14, 0xc5, 0x42, 0x09, 0x78, 0x2f, 0xcd, 0x46, 0x24, 0x62, 0x68, 0x99, 0x8d, 0x6c, 0x76, - 0xf3, 0xc1, 0x90, 0xa9, 0x51, 0xd2, 0x43, 0x7d, 0x31, 0x0d, 0x86, 0x62, 0x28, 0x02, 0x03, 0xea, - 0x25, 0xcf, 0x8d, 0x65, 0x0c, 0xf3, 0x94, 0x92, 0x35, 0x2f, 0x95, 0x4e, 0xd4, 0x88, 0x72, 0xc5, - 0xfa, 0x44, 0xa5, 0xf5, 0xd7, 0x4b, 0x37, 0x3f, 0xcf, 0xb3, 0xa7, 0xa4, 0x3f, 0x62, 0x9c, 0xc6, - 0xb3, 0x20, 0x1a, 0x0f, 0xb5, 0x43, 0x06, 0x53, 0xaa, 0xc8, 0x75, 0xa8, 0xe0, 0x26, 0x54, 0x9c, - 0x70, 0xc5, 0xa6, 0xf4, 0x0a, 0xe0, 0xe1, 0xff, 0x01, 0x64, 0x7f, 0x44, 0xa7, 0x64, 0x1d, 0xb7, - 0xf5, 0xa7, 0x0b, 0x1a, 0x7b, 0x99, 0x22, 0x98, 0xfe, 0x92, 0x50, 0xa9, 0x60, 0x08, 0x8a, 0x09, - 0x1b, 0x78, 0x4e, 0xdb, 0xe9, 0xb8, 0xe1, 0x67, 0x67, 0xf3, 0x56, 0x61, 0x31, 0x6f, 0x15, 0xbb, - 0x87, 0xfb, 0x17, 0xf3, 0xd6, 0xc7, 0x37, 0x15, 0x52, 0xb3, 0x88, 0x4a, 0xd4, 0x3d, 0xdc, 0xc7, - 0x1a, 0x0c, 0x9f, 0x81, 0xd2, 0x98, 0xf1, 0x81, 0x77, 0xab, 0xed, 0x74, 0x6a, 0x3b, 0x0f, 0x51, - 0x3e, 0x81, 0x25, 0x0c, 0x45, 0xe3, 0xa1, 0x76, 0x48, 0xa4, 0x65, 0x40, 0x27, 0xdb, 0xe8, 0xeb, - 0x58, 0x24, 0xd1, 0x77, 0x34, 0xd6, 0xcd, 0x7c, 0xcb, 0xf8, 0x20, 0xdc, 0xb4, 0xc5, 0x4b, 0xda, - 0xc2, 0x86, 0x11, 0x8e, 0x40, 0x35, 0xa6, 0x52, 0x24, 0x71, 0x9f, 0x7a, 0x45, 0xc3, 0xfe, 0xe8, - 0xcd, 0xd9, 0xb1, 0x65, 0x08, 0x1b, 0xb6, 0x42, 0x35, 0xf3, 0xe0, 0x25, 0x3b, 0xfc, 0x02, 0xd4, - 0x64, 0xd2, 0xcb, 0x02, 0x5e, 0xc9, 0xe8, 0x71, 0xd7, 0x02, 0x6a, 0x4f, 0xf2, 0x10, 0x5e, 0xcd, - 0x83, 0x0c, 0xd4, 0xe2, 0x54, 0x49, 0xdd, 0xb5, 0xf7, 0xc1, 0x3b, 0x29, 0x50, 0xd7, 0xa5, 0x70, - 0x4e, 0x87, 0x57, 0xb9, 0xe1, 0x0c, 0xd4, 0xad, 0xb9, 0xec, 0xf2, 0xf6, 0x3b, 0x4b, 0x72, 0x77, - 0x31, 0x6f, 0xd5, 0xf1, 0x65, 0x5a, 0xbc, 0x5e, 0x07, 0x7e, 0x03, 0xa0, 0x75, 0xad, 0x08, 0xe1, - 0xd5, 0x8d, 0x46, 0x4d, 0xab, 0x11, 0xc4, 0x57, 0x32, 0xf0, 0x35, 0x28, 0xd8, 0x06, 0x25, 0x4e, - 0xa6, 0xd4, 0xdb, 0x30, 0xe8, 0xe5, 0xd0, 0x1f, 0x93, 0x29, 0xc5, 0x26, 0x02, 0x03, 0xe0, 0xea, - 0xbf, 0x32, 0x22, 0x7d, 0xea, 0x95, 0x4d, 0xda, 0x1d, 0x9b, 0xe6, 0x3e, 0xce, 0x02, 0x38, 0xcf, - 0x81, 0x5f, 0x02, 0x57, 0x44, 0xfa, 0x55, 0x67, 0x82, 0x7b, 0x15, 0x03, 0xf0, 0x33, 0xc0, 0x51, - 0x16, 0xb8, 0x58, 0x35, 0x70, 0x0e, 0x80, 0x4f, 0x41, 0x35, 0x91, 0x34, 0x3e, 0xe4, 0xcf, 0x85, - 0x57, 0x35, 0x82, 0x7e, 0x82, 0x56, 0x6f, 0xc8, 0xa5, 0xb5, 0xd7, 0x42, 0x76, 0x6d, 0x76, 0xfe, - 0x3e, 0x65, 0x1e, 0xbc, 0x64, 0x82, 0x5d, 0x50, 0x16, 0xbd, 0x9f, 0x69, 0x5f, 0x79, 0xae, 0xe1, - 0x7c, 0x70, 0xe3, 0x90, 0xec, 0xd6, 0x22, 0x4c, 0x4e, 0x0f, 0x7e, 0x55, 0x94, 0xeb, 0xf9, 0x84, - 0xb7, 0x2d, 0x75, 0xf9, 0xc8, 0x90, 0x60, 0x4b, 0x06, 0x7f, 0x02, 0xae, 0x98, 0x0c, 0x52, 0xa7, - 0x07, 0xde, 0x86, 0x79, 0x29, 0xe5, 0x51, 0xc6, 0x83, 0x73, 0x4a, 0xb8, 0x05, 0xca, 0x83, 0x78, - 0x86, 0x13, 0xee, 0xd5, 0xda, 0x4e, 0xa7, 0x1a, 0x02, 0xdd, 0xc3, 0xbe, 0xf1, 0x60, 0x1b, 0x81, - 0xcf, 0x40, 0x45, 0x44, 0x5a, 0x0c, 0xe9, 0x6d, 0xbe, 0x4d, 0x07, 0x75, 0xdb, 0x41, 0xe5, 0x28, - 0x65, 0xc1, 0x19, 0xdd, 0xd6, 0x5f, 0x25, 0x70, 0x67, 0xe5, 0x42, 0xc9, 0x48, 0x70, 0x49, 0xdf, - 0xcb, 0x89, 0xfa, 0x14, 0x54, 0xc8, 0x64, 0x22, 0x4e, 0x69, 0x7a, 0xa5, 0xaa, 0x79, 0x13, 0x7b, - 0xa9, 0x1b, 0x67, 0x71, 0x78, 0x0c, 0xca, 0x52, 0x11, 0x95, 0x48, 0x7b, 0x71, 0xee, 0xbf, 0xde, - 0x7a, 0x3d, 0x31, 0x98, 0x54, 0x30, 0x4c, 0x65, 0x32, 0x51, 0xd8, 0xf2, 0xc0, 0x16, 0xd8, 0x88, - 0x88, 0xea, 0x8f, 0xcc, 0x55, 0xd9, 0x0c, 0xdd, 0xc5, 0xbc, 0xb5, 0x71, 0xac, 0x1d, 0x38, 0xf5, - 0xc3, 0x5d, 0xe0, 0x9a, 0x87, 0xa7, 0xb3, 0x28, 0x5b, 0x8c, 0xa6, 0x1e, 0xd1, 0x71, 0xe6, 0xbc, - 0x58, 0x35, 0x70, 0x9e, 0x0c, 0x7f, 0x77, 0x40, 0x83, 0x24, 0x03, 0xa6, 0xf6, 0x38, 0x17, 0x8a, - 0xa4, 0x53, 0x29, 0xb7, 0x8b, 0x9d, 0xda, 0xce, 0x01, 0x7a, 0xd5, 0x97, 0x10, 0x5d, 0xd1, 0x19, - 0xed, 0xad, 0xf1, 0x1c, 0x70, 0x15, 0xcf, 0x42, 0xcf, 0x0a, 0xd5, 0x58, 0x0f, 0xe3, 0x2b, 0x85, - 0x61, 0x07, 0x54, 0x4f, 0x49, 0xcc, 0x19, 0x1f, 0x4a, 0xaf, 0xd2, 0x2e, 0xea, 0xfd, 0xd6, 0xeb, - 0xf1, 0xbd, 0xf5, 0xe1, 0x65, 0xb4, 0xf9, 0x15, 0xf8, 0xe8, 0xda, 0x72, 0xb0, 0x01, 0x8a, 0x63, - 0x3a, 0x4b, 0x87, 0x8d, 0xf5, 0x23, 0xfc, 0x10, 0x6c, 0x9c, 0x90, 0x49, 0x42, 0xcd, 0xe0, 0x5c, - 0x9c, 0x1a, 0x8f, 0x6e, 0xed, 0x3a, 0x5b, 0x7f, 0x3b, 0xa0, 0xbe, 0xf2, 0x6f, 0x9c, 0x30, 0x7a, - 0x0a, 0xbb, 0xa0, 0x62, 0x8f, 0x8e, 0xe1, 0xa8, 0xed, 0xa0, 0xd7, 0x96, 0xc1, 0xa0, 0xc2, 0x9a, - 0x7e, 0x29, 0xb2, 0x8b, 0x98, 0x71, 0xc1, 0x1f, 0xcc, 0x87, 0xc8, 0xe8, 0x64, 0x3f, 0x73, 0xc1, - 0x1b, 0xca, 0x9b, 0x4a, 0x91, 0x59, 0x78, 0x49, 0x17, 0x86, 0x67, 0xe7, 0x7e, 0xe1, 0xc5, 0xb9, - 0x5f, 0x78, 0x79, 0xee, 0x17, 0x7e, 0x5b, 0xf8, 0xce, 0xd9, 0xc2, 0x77, 0x5e, 0x2c, 0x7c, 0xe7, - 0xe5, 0xc2, 0x77, 0xfe, 0x59, 0xf8, 0xce, 0x1f, 0xff, 0xfa, 0x85, 0x1f, 0xef, 0xbd, 0xea, 0x47, - 0xd0, 0x7f, 0x01, 0x00, 0x00, 0xff, 0xff, 0x90, 0x6e, 0x31, 0x41, 0x23, 0x09, 0x00, 0x00, -} - -func (m *AdmissionRequest) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *AdmissionRequest) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AdmissionRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - i -= len(m.RequestSubResource) - copy(dAtA[i:], m.RequestSubResource) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.RequestSubResource))) - i-- - dAtA[i] = 0x7a - if m.RequestResource != nil { - { - size, err := m.RequestResource.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x72 - } - if m.RequestKind != nil { - { - size, err := m.RequestKind.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x6a - } - { - size, err := m.Options.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x62 - if m.DryRun != nil { - i-- - if *m.DryRun { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x58 - } - { - size, err := m.OldObject.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x52 - { - size, err := m.Object.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x4a - { - size, err := m.UserInfo.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x42 - i -= len(m.Operation) - copy(dAtA[i:], m.Operation) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.Operation))) - i-- - dAtA[i] = 0x3a - i -= len(m.Namespace) - copy(dAtA[i:], m.Namespace) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.Namespace))) - i-- - dAtA[i] = 0x32 - i -= len(m.Name) - copy(dAtA[i:], m.Name) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.Name))) - i-- - dAtA[i] = 0x2a - i -= len(m.SubResource) - copy(dAtA[i:], m.SubResource) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.SubResource))) - i-- - dAtA[i] = 0x22 - { - size, err := m.Resource.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - { - size, err := m.Kind.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - i -= len(m.UID) - copy(dAtA[i:], m.UID) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.UID))) - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *AdmissionResponse) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *AdmissionResponse) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AdmissionResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if len(m.Warnings) > 0 { - for iNdEx := len(m.Warnings) - 1; iNdEx >= 0; iNdEx-- { - i -= len(m.Warnings[iNdEx]) - copy(dAtA[i:], m.Warnings[iNdEx]) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.Warnings[iNdEx]))) - i-- - dAtA[i] = 0x3a - } - } - if len(m.AuditAnnotations) > 0 { - keysForAuditAnnotations := make([]string, 0, len(m.AuditAnnotations)) - for k := range m.AuditAnnotations { - keysForAuditAnnotations = append(keysForAuditAnnotations, string(k)) - } - github_com_gogo_protobuf_sortkeys.Strings(keysForAuditAnnotations) - for iNdEx := len(keysForAuditAnnotations) - 1; iNdEx >= 0; iNdEx-- { - v := m.AuditAnnotations[string(keysForAuditAnnotations[iNdEx])] - baseI := i - i -= len(v) - copy(dAtA[i:], v) - i = encodeVarintGenerated(dAtA, i, uint64(len(v))) - i-- - dAtA[i] = 0x12 - i -= len(keysForAuditAnnotations[iNdEx]) - copy(dAtA[i:], keysForAuditAnnotations[iNdEx]) - i = encodeVarintGenerated(dAtA, i, uint64(len(keysForAuditAnnotations[iNdEx]))) - i-- - dAtA[i] = 0xa - i = encodeVarintGenerated(dAtA, i, uint64(baseI-i)) - i-- - dAtA[i] = 0x32 - } - } - if m.PatchType != nil { - i -= len(*m.PatchType) - copy(dAtA[i:], *m.PatchType) - i = encodeVarintGenerated(dAtA, i, uint64(len(*m.PatchType))) - i-- - dAtA[i] = 0x2a - } - if m.Patch != nil { - i -= len(m.Patch) - copy(dAtA[i:], m.Patch) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.Patch))) - i-- - dAtA[i] = 0x22 - } - if m.Result != nil { - { - size, err := m.Result.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1a - } - i-- - if m.Allowed { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i-- - dAtA[i] = 0x10 - i -= len(m.UID) - copy(dAtA[i:], m.UID) - i = encodeVarintGenerated(dAtA, i, uint64(len(m.UID))) - i-- - dAtA[i] = 0xa - return len(dAtA) - i, nil -} - -func (m *AdmissionReview) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalToSizedBuffer(dAtA[:size]) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *AdmissionReview) MarshalTo(dAtA []byte) (int, error) { - size := m.Size() - return m.MarshalToSizedBuffer(dAtA[:size]) -} - -func (m *AdmissionReview) MarshalToSizedBuffer(dAtA []byte) (int, error) { - i := len(dAtA) - _ = i - var l int - _ = l - if m.Response != nil { - { - size, err := m.Response.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x12 - } - if m.Request != nil { - { - size, err := m.Request.MarshalToSizedBuffer(dAtA[:i]) - if err != nil { - return 0, err - } - i -= size - i = encodeVarintGenerated(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0xa - } - return len(dAtA) - i, nil -} - -func encodeVarintGenerated(dAtA []byte, offset int, v uint64) int { - offset -= sovGenerated(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return base -} -func (m *AdmissionRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.UID) - n += 1 + l + sovGenerated(uint64(l)) - l = m.Kind.Size() - n += 1 + l + sovGenerated(uint64(l)) - l = m.Resource.Size() - n += 1 + l + sovGenerated(uint64(l)) - l = len(m.SubResource) - n += 1 + l + sovGenerated(uint64(l)) - l = len(m.Name) - n += 1 + l + sovGenerated(uint64(l)) - l = len(m.Namespace) - n += 1 + l + sovGenerated(uint64(l)) - l = len(m.Operation) - n += 1 + l + sovGenerated(uint64(l)) - l = m.UserInfo.Size() - n += 1 + l + sovGenerated(uint64(l)) - l = m.Object.Size() - n += 1 + l + sovGenerated(uint64(l)) - l = m.OldObject.Size() - n += 1 + l + sovGenerated(uint64(l)) - if m.DryRun != nil { - n += 2 - } - l = m.Options.Size() - n += 1 + l + sovGenerated(uint64(l)) - if m.RequestKind != nil { - l = m.RequestKind.Size() - n += 1 + l + sovGenerated(uint64(l)) - } - if m.RequestResource != nil { - l = m.RequestResource.Size() - n += 1 + l + sovGenerated(uint64(l)) - } - l = len(m.RequestSubResource) - n += 1 + l + sovGenerated(uint64(l)) - return n -} - -func (m *AdmissionResponse) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.UID) - n += 1 + l + sovGenerated(uint64(l)) - n += 2 - if m.Result != nil { - l = m.Result.Size() - n += 1 + l + sovGenerated(uint64(l)) - } - if m.Patch != nil { - l = len(m.Patch) - n += 1 + l + sovGenerated(uint64(l)) - } - if m.PatchType != nil { - l = len(*m.PatchType) - n += 1 + l + sovGenerated(uint64(l)) - } - if len(m.AuditAnnotations) > 0 { - for k, v := range m.AuditAnnotations { - _ = k - _ = v - mapEntrySize := 1 + len(k) + sovGenerated(uint64(len(k))) + 1 + len(v) + sovGenerated(uint64(len(v))) - n += mapEntrySize + 1 + sovGenerated(uint64(mapEntrySize)) - } - } - if len(m.Warnings) > 0 { - for _, s := range m.Warnings { - l = len(s) - n += 1 + l + sovGenerated(uint64(l)) - } - } - return n -} - -func (m *AdmissionReview) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Request != nil { - l = m.Request.Size() - n += 1 + l + sovGenerated(uint64(l)) - } - if m.Response != nil { - l = m.Response.Size() - n += 1 + l + sovGenerated(uint64(l)) - } - return n -} - -func sovGenerated(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozGenerated(x uint64) (n int) { - return sovGenerated(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (this *AdmissionRequest) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&AdmissionRequest{`, - `UID:` + fmt.Sprintf("%v", this.UID) + `,`, - `Kind:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Kind), "GroupVersionKind", "v1.GroupVersionKind", 1), `&`, ``, 1) + `,`, - `Resource:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Resource), "GroupVersionResource", "v1.GroupVersionResource", 1), `&`, ``, 1) + `,`, - `SubResource:` + fmt.Sprintf("%v", this.SubResource) + `,`, - `Name:` + fmt.Sprintf("%v", this.Name) + `,`, - `Namespace:` + fmt.Sprintf("%v", this.Namespace) + `,`, - `Operation:` + fmt.Sprintf("%v", this.Operation) + `,`, - `UserInfo:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.UserInfo), "UserInfo", "v11.UserInfo", 1), `&`, ``, 1) + `,`, - `Object:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Object), "RawExtension", "runtime.RawExtension", 1), `&`, ``, 1) + `,`, - `OldObject:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.OldObject), "RawExtension", "runtime.RawExtension", 1), `&`, ``, 1) + `,`, - `DryRun:` + valueToStringGenerated(this.DryRun) + `,`, - `Options:` + strings.Replace(strings.Replace(fmt.Sprintf("%v", this.Options), "RawExtension", "runtime.RawExtension", 1), `&`, ``, 1) + `,`, - `RequestKind:` + strings.Replace(fmt.Sprintf("%v", this.RequestKind), "GroupVersionKind", "v1.GroupVersionKind", 1) + `,`, - `RequestResource:` + strings.Replace(fmt.Sprintf("%v", this.RequestResource), "GroupVersionResource", "v1.GroupVersionResource", 1) + `,`, - `RequestSubResource:` + fmt.Sprintf("%v", this.RequestSubResource) + `,`, - `}`, - }, "") - return s -} -func (this *AdmissionResponse) String() string { - if this == nil { - return "nil" - } - keysForAuditAnnotations := make([]string, 0, len(this.AuditAnnotations)) - for k := range this.AuditAnnotations { - keysForAuditAnnotations = append(keysForAuditAnnotations, k) - } - github_com_gogo_protobuf_sortkeys.Strings(keysForAuditAnnotations) - mapStringForAuditAnnotations := "map[string]string{" - for _, k := range keysForAuditAnnotations { - mapStringForAuditAnnotations += fmt.Sprintf("%v: %v,", k, this.AuditAnnotations[k]) - } - mapStringForAuditAnnotations += "}" - s := strings.Join([]string{`&AdmissionResponse{`, - `UID:` + fmt.Sprintf("%v", this.UID) + `,`, - `Allowed:` + fmt.Sprintf("%v", this.Allowed) + `,`, - `Result:` + strings.Replace(fmt.Sprintf("%v", this.Result), "Status", "v1.Status", 1) + `,`, - `Patch:` + valueToStringGenerated(this.Patch) + `,`, - `PatchType:` + valueToStringGenerated(this.PatchType) + `,`, - `AuditAnnotations:` + mapStringForAuditAnnotations + `,`, - `Warnings:` + fmt.Sprintf("%v", this.Warnings) + `,`, - `}`, - }, "") - return s -} -func (this *AdmissionReview) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&AdmissionReview{`, - `Request:` + strings.Replace(this.Request.String(), "AdmissionRequest", "AdmissionRequest", 1) + `,`, - `Response:` + strings.Replace(this.Response.String(), "AdmissionResponse", "AdmissionResponse", 1) + `,`, - `}`, - }, "") - return s -} -func valueToStringGenerated(v interface{}) string { - rv := reflect.ValueOf(v) - if rv.IsNil() { - return "nil" - } - pv := reflect.Indirect(rv).Interface() - return fmt.Sprintf("*%v", pv) -} -func (m *AdmissionRequest) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: AdmissionRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AdmissionRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field UID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.UID = k8s_io_apimachinery_pkg_types.UID(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Kind", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Kind.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Resource", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Resource.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SubResource", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SubResource = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Name = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Namespace", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Namespace = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Operation", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Operation = Operation(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field UserInfo", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.UserInfo.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 9: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Object", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Object.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 10: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field OldObject", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.OldObject.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 11: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field DryRun", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - b := bool(v != 0) - m.DryRun = &b - case 12: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Options", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.Options.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 13: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RequestKind", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.RequestKind == nil { - m.RequestKind = &v1.GroupVersionKind{} - } - if err := m.RequestKind.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 14: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RequestResource", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.RequestResource == nil { - m.RequestResource = &v1.GroupVersionResource{} - } - if err := m.RequestResource.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 15: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RequestSubResource", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RequestSubResource = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenerated(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenerated - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *AdmissionResponse) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: AdmissionResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AdmissionResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field UID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.UID = k8s_io_apimachinery_pkg_types.UID(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Allowed", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.Allowed = bool(v != 0) - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Result", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Result == nil { - m.Result = &v1.Status{} - } - if err := m.Result.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Patch", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - byteLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + byteLen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Patch = append(m.Patch[:0], dAtA[iNdEx:postIndex]...) - if m.Patch == nil { - m.Patch = []byte{} - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PatchType", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - s := PatchType(dAtA[iNdEx:postIndex]) - m.PatchType = &s - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AuditAnnotations", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.AuditAnnotations == nil { - m.AuditAnnotations = make(map[string]string) - } - var mapkey string - var mapvalue string - for iNdEx < postIndex { - entryPreIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - if fieldNum == 1 { - var stringLenmapkey uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLenmapkey |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLenmapkey := int(stringLenmapkey) - if intStringLenmapkey < 0 { - return ErrInvalidLengthGenerated - } - postStringIndexmapkey := iNdEx + intStringLenmapkey - if postStringIndexmapkey < 0 { - return ErrInvalidLengthGenerated - } - if postStringIndexmapkey > l { - return io.ErrUnexpectedEOF - } - mapkey = string(dAtA[iNdEx:postStringIndexmapkey]) - iNdEx = postStringIndexmapkey - } else if fieldNum == 2 { - var stringLenmapvalue uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLenmapvalue |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLenmapvalue := int(stringLenmapvalue) - if intStringLenmapvalue < 0 { - return ErrInvalidLengthGenerated - } - postStringIndexmapvalue := iNdEx + intStringLenmapvalue - if postStringIndexmapvalue < 0 { - return ErrInvalidLengthGenerated - } - if postStringIndexmapvalue > l { - return io.ErrUnexpectedEOF - } - mapvalue = string(dAtA[iNdEx:postStringIndexmapvalue]) - iNdEx = postStringIndexmapvalue - } else { - iNdEx = entryPreIndex - skippy, err := skipGenerated(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenerated - } - if (iNdEx + skippy) > postIndex { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - m.AuditAnnotations[mapkey] = mapvalue - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Warnings", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Warnings = append(m.Warnings, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenerated(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenerated - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *AdmissionReview) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: AdmissionReview: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: AdmissionReview: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Request", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Request == nil { - m.Request = &AdmissionRequest{} - } - if err := m.Request.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Response", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowGenerated - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthGenerated - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthGenerated - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Response == nil { - m.Response = &AdmissionResponse{} - } - if err := m.Response.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipGenerated(dAtA[iNdEx:]) - if err != nil { - return err - } - if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthGenerated - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipGenerated(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - depth := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenerated - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenerated - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - case 1: - iNdEx += 8 - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowGenerated - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthGenerated - } - iNdEx += length - case 3: - depth++ - case 4: - if depth == 0 { - return 0, ErrUnexpectedEndOfGroupGenerated - } - depth-- - case 5: - iNdEx += 4 - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - if iNdEx < 0 { - return 0, ErrInvalidLengthGenerated - } - if depth == 0 { - return iNdEx, nil - } - } - return 0, io.ErrUnexpectedEOF -} - -var ( - ErrInvalidLengthGenerated = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowGenerated = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupGenerated = fmt.Errorf("proto: unexpected end of group") -) diff --git a/vendor/k8s.io/api/admission/v1beta1/generated.proto b/vendor/k8s.io/api/admission/v1beta1/generated.proto deleted file mode 100644 index d27c05b72..000000000 --- a/vendor/k8s.io/api/admission/v1beta1/generated.proto +++ /dev/null @@ -1,167 +0,0 @@ -/* -Copyright 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. -*/ - - -// This file was autogenerated by go-to-protobuf. Do not edit it manually! - -syntax = "proto2"; - -package k8s.io.api.admission.v1beta1; - -import "k8s.io/api/authentication/v1/generated.proto"; -import "k8s.io/apimachinery/pkg/apis/meta/v1/generated.proto"; -import "k8s.io/apimachinery/pkg/runtime/generated.proto"; -import "k8s.io/apimachinery/pkg/runtime/schema/generated.proto"; - -// Package-wide variables from generator "generated". -option go_package = "k8s.io/api/admission/v1beta1"; - -// AdmissionRequest describes the admission.Attributes for the admission request. -message AdmissionRequest { - // UID is an identifier for the individual request/response. It allows us to distinguish instances of requests which are - // otherwise identical (parallel requests, requests when earlier requests did not modify etc) - // The UID is meant to track the round trip (request/response) between the KAS and the WebHook, not the user request. - // It is suitable for correlating log entries between the webhook and apiserver, for either auditing or debugging. - optional string uid = 1; - - // Kind is the fully-qualified type of object being submitted (for example, v1.Pod or autoscaling.v1.Scale) - optional .k8s.io.apimachinery.pkg.apis.meta.v1.GroupVersionKind kind = 2; - - // Resource is the fully-qualified resource being requested (for example, v1.pods) - optional .k8s.io.apimachinery.pkg.apis.meta.v1.GroupVersionResource resource = 3; - - // SubResource is the subresource being requested, if any (for example, "status" or "scale") - // +optional - optional string subResource = 4; - - // RequestKind is the fully-qualified type of the original API request (for example, v1.Pod or autoscaling.v1.Scale). - // If this is specified and differs from the value in "kind", an equivalent match and conversion was performed. - // - // For example, if deployments can be modified via apps/v1 and apps/v1beta1, and a webhook registered a rule of - // `apiGroups:["apps"], apiVersions:["v1"], resources: ["deployments"]` and `matchPolicy: Equivalent`, - // an API request to apps/v1beta1 deployments would be converted and sent to the webhook - // with `kind: {group:"apps", version:"v1", kind:"Deployment"}` (matching the rule the webhook registered for), - // and `requestKind: {group:"apps", version:"v1beta1", kind:"Deployment"}` (indicating the kind of the original API request). - // - // See documentation for the "matchPolicy" field in the webhook configuration type for more details. - // +optional - optional .k8s.io.apimachinery.pkg.apis.meta.v1.GroupVersionKind requestKind = 13; - - // RequestResource is the fully-qualified resource of the original API request (for example, v1.pods). - // If this is specified and differs from the value in "resource", an equivalent match and conversion was performed. - // - // For example, if deployments can be modified via apps/v1 and apps/v1beta1, and a webhook registered a rule of - // `apiGroups:["apps"], apiVersions:["v1"], resources: ["deployments"]` and `matchPolicy: Equivalent`, - // an API request to apps/v1beta1 deployments would be converted and sent to the webhook - // with `resource: {group:"apps", version:"v1", resource:"deployments"}` (matching the resource the webhook registered for), - // and `requestResource: {group:"apps", version:"v1beta1", resource:"deployments"}` (indicating the resource of the original API request). - // - // See documentation for the "matchPolicy" field in the webhook configuration type. - // +optional - optional .k8s.io.apimachinery.pkg.apis.meta.v1.GroupVersionResource requestResource = 14; - - // RequestSubResource is the name of the subresource of the original API request, if any (for example, "status" or "scale") - // If this is specified and differs from the value in "subResource", an equivalent match and conversion was performed. - // See documentation for the "matchPolicy" field in the webhook configuration type. - // +optional - optional string requestSubResource = 15; - - // Name is the name of the object as presented in the request. On a CREATE operation, the client may omit name and - // rely on the server to generate the name. If that is the case, this field will contain an empty string. - // +optional - optional string name = 5; - - // Namespace is the namespace associated with the request (if any). - // +optional - optional string namespace = 6; - - // Operation is the operation being performed. This may be different than the operation - // requested. e.g. a patch can result in either a CREATE or UPDATE Operation. - optional string operation = 7; - - // UserInfo is information about the requesting user - optional .k8s.io.api.authentication.v1.UserInfo userInfo = 8; - - // Object is the object from the incoming request. - // +optional - optional .k8s.io.apimachinery.pkg.runtime.RawExtension object = 9; - - // OldObject is the existing object. Only populated for DELETE and UPDATE requests. - // +optional - optional .k8s.io.apimachinery.pkg.runtime.RawExtension oldObject = 10; - - // DryRun indicates that modifications will definitely not be persisted for this request. - // Defaults to false. - // +optional - optional bool dryRun = 11; - - // Options is the operation option structure of the operation being performed. - // e.g. `meta.k8s.io/v1.DeleteOptions` or `meta.k8s.io/v1.CreateOptions`. This may be - // different than the options the caller provided. e.g. for a patch request the performed - // Operation might be a CREATE, in which case the Options will a - // `meta.k8s.io/v1.CreateOptions` even though the caller provided `meta.k8s.io/v1.PatchOptions`. - // +optional - optional .k8s.io.apimachinery.pkg.runtime.RawExtension options = 12; -} - -// AdmissionResponse describes an admission response. -message AdmissionResponse { - // UID is an identifier for the individual request/response. - // This should be copied over from the corresponding AdmissionRequest. - optional string uid = 1; - - // Allowed indicates whether or not the admission request was permitted. - optional bool allowed = 2; - - // Result contains extra details into why an admission request was denied. - // This field IS NOT consulted in any way if "Allowed" is "true". - // +optional - optional .k8s.io.apimachinery.pkg.apis.meta.v1.Status status = 3; - - // The patch body. Currently we only support "JSONPatch" which implements RFC 6902. - // +optional - optional bytes patch = 4; - - // The type of Patch. Currently we only allow "JSONPatch". - // +optional - optional string patchType = 5; - - // AuditAnnotations is an unstructured key value map set by remote admission controller (e.g. error=image-blacklisted). - // MutatingAdmissionWebhook and ValidatingAdmissionWebhook admission controller will prefix the keys with - // admission webhook name (e.g. imagepolicy.example.com/error=image-blacklisted). AuditAnnotations will be provided by - // the admission webhook to add additional context to the audit log for this request. - // +optional - map auditAnnotations = 6; - - // warnings is a list of warning messages to return to the requesting API client. - // Warning messages describe a problem the client making the API request should correct or be aware of. - // Limit warnings to 120 characters if possible. - // Warnings over 256 characters and large numbers of warnings may be truncated. - // +optional - repeated string warnings = 7; -} - -// AdmissionReview describes an admission review request/response. -message AdmissionReview { - // Request describes the attributes for the admission request. - // +optional - optional AdmissionRequest request = 1; - - // Response describes the attributes for the admission response. - // +optional - optional AdmissionResponse response = 2; -} - diff --git a/vendor/k8s.io/api/admission/v1beta1/register.go b/vendor/k8s.io/api/admission/v1beta1/register.go deleted file mode 100644 index 1c53e755d..000000000 --- a/vendor/k8s.io/api/admission/v1beta1/register.go +++ /dev/null @@ -1,53 +0,0 @@ -/* -Copyright 2017 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1beta1 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -// GroupName is the group name for this API. -const GroupName = "admission.k8s.io" - -// SchemeGroupVersion is group version used to register these objects -var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: "v1beta1"} - -// Resource takes an unqualified resource and returns a Group qualified GroupResource -func Resource(resource string) schema.GroupResource { - return SchemeGroupVersion.WithResource(resource).GroupResource() -} - -// TODO: move SchemeBuilder with zz_generated.deepcopy.go to k8s.io/api. -// localSchemeBuilder and AddToScheme will stay in k8s.io/kubernetes. -var ( - // SchemeBuilder points to a list of functions added to Scheme. - SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) - localSchemeBuilder = &SchemeBuilder - // AddToScheme is a common registration function for mapping packaged scoped group & version keys to a scheme. - AddToScheme = localSchemeBuilder.AddToScheme -) - -// Adds the list of known types to the given scheme. -func addKnownTypes(scheme *runtime.Scheme) error { - scheme.AddKnownTypes(SchemeGroupVersion, - &AdmissionReview{}, - ) - metav1.AddToGroupVersion(scheme, SchemeGroupVersion) - return nil -} diff --git a/vendor/k8s.io/api/admission/v1beta1/types.go b/vendor/k8s.io/api/admission/v1beta1/types.go deleted file mode 100644 index 00c619d99..000000000 --- a/vendor/k8s.io/api/admission/v1beta1/types.go +++ /dev/null @@ -1,174 +0,0 @@ -/* -Copyright 2017 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1beta1 - -import ( - authenticationv1 "k8s.io/api/authentication/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/types" -) - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +k8s:prerelease-lifecycle-gen:introduced=1.9 -// +k8s:prerelease-lifecycle-gen:deprecated=1.19 -// This API is never server served. It is used for outbound requests from apiservers. This will ensure it never gets served accidentally -// and having the generator against this group will protect future APIs which may be served. -// +k8s:prerelease-lifecycle-gen:replacement=admission.k8s.io,v1,AdmissionReview - -// AdmissionReview describes an admission review request/response. -type AdmissionReview struct { - metav1.TypeMeta `json:",inline"` - // Request describes the attributes for the admission request. - // +optional - Request *AdmissionRequest `json:"request,omitempty" protobuf:"bytes,1,opt,name=request"` - // Response describes the attributes for the admission response. - // +optional - Response *AdmissionResponse `json:"response,omitempty" protobuf:"bytes,2,opt,name=response"` -} - -// AdmissionRequest describes the admission.Attributes for the admission request. -type AdmissionRequest struct { - // UID is an identifier for the individual request/response. It allows us to distinguish instances of requests which are - // otherwise identical (parallel requests, requests when earlier requests did not modify etc) - // The UID is meant to track the round trip (request/response) between the KAS and the WebHook, not the user request. - // It is suitable for correlating log entries between the webhook and apiserver, for either auditing or debugging. - UID types.UID `json:"uid" protobuf:"bytes,1,opt,name=uid"` - // Kind is the fully-qualified type of object being submitted (for example, v1.Pod or autoscaling.v1.Scale) - Kind metav1.GroupVersionKind `json:"kind" protobuf:"bytes,2,opt,name=kind"` - // Resource is the fully-qualified resource being requested (for example, v1.pods) - Resource metav1.GroupVersionResource `json:"resource" protobuf:"bytes,3,opt,name=resource"` - // SubResource is the subresource being requested, if any (for example, "status" or "scale") - // +optional - SubResource string `json:"subResource,omitempty" protobuf:"bytes,4,opt,name=subResource"` - - // RequestKind is the fully-qualified type of the original API request (for example, v1.Pod or autoscaling.v1.Scale). - // If this is specified and differs from the value in "kind", an equivalent match and conversion was performed. - // - // For example, if deployments can be modified via apps/v1 and apps/v1beta1, and a webhook registered a rule of - // `apiGroups:["apps"], apiVersions:["v1"], resources: ["deployments"]` and `matchPolicy: Equivalent`, - // an API request to apps/v1beta1 deployments would be converted and sent to the webhook - // with `kind: {group:"apps", version:"v1", kind:"Deployment"}` (matching the rule the webhook registered for), - // and `requestKind: {group:"apps", version:"v1beta1", kind:"Deployment"}` (indicating the kind of the original API request). - // - // See documentation for the "matchPolicy" field in the webhook configuration type for more details. - // +optional - RequestKind *metav1.GroupVersionKind `json:"requestKind,omitempty" protobuf:"bytes,13,opt,name=requestKind"` - // RequestResource is the fully-qualified resource of the original API request (for example, v1.pods). - // If this is specified and differs from the value in "resource", an equivalent match and conversion was performed. - // - // For example, if deployments can be modified via apps/v1 and apps/v1beta1, and a webhook registered a rule of - // `apiGroups:["apps"], apiVersions:["v1"], resources: ["deployments"]` and `matchPolicy: Equivalent`, - // an API request to apps/v1beta1 deployments would be converted and sent to the webhook - // with `resource: {group:"apps", version:"v1", resource:"deployments"}` (matching the resource the webhook registered for), - // and `requestResource: {group:"apps", version:"v1beta1", resource:"deployments"}` (indicating the resource of the original API request). - // - // See documentation for the "matchPolicy" field in the webhook configuration type. - // +optional - RequestResource *metav1.GroupVersionResource `json:"requestResource,omitempty" protobuf:"bytes,14,opt,name=requestResource"` - // RequestSubResource is the name of the subresource of the original API request, if any (for example, "status" or "scale") - // If this is specified and differs from the value in "subResource", an equivalent match and conversion was performed. - // See documentation for the "matchPolicy" field in the webhook configuration type. - // +optional - RequestSubResource string `json:"requestSubResource,omitempty" protobuf:"bytes,15,opt,name=requestSubResource"` - - // Name is the name of the object as presented in the request. On a CREATE operation, the client may omit name and - // rely on the server to generate the name. If that is the case, this field will contain an empty string. - // +optional - Name string `json:"name,omitempty" protobuf:"bytes,5,opt,name=name"` - // Namespace is the namespace associated with the request (if any). - // +optional - Namespace string `json:"namespace,omitempty" protobuf:"bytes,6,opt,name=namespace"` - // Operation is the operation being performed. This may be different than the operation - // requested. e.g. a patch can result in either a CREATE or UPDATE Operation. - Operation Operation `json:"operation" protobuf:"bytes,7,opt,name=operation"` - // UserInfo is information about the requesting user - UserInfo authenticationv1.UserInfo `json:"userInfo" protobuf:"bytes,8,opt,name=userInfo"` - // Object is the object from the incoming request. - // +optional - Object runtime.RawExtension `json:"object,omitempty" protobuf:"bytes,9,opt,name=object"` - // OldObject is the existing object. Only populated for DELETE and UPDATE requests. - // +optional - OldObject runtime.RawExtension `json:"oldObject,omitempty" protobuf:"bytes,10,opt,name=oldObject"` - // DryRun indicates that modifications will definitely not be persisted for this request. - // Defaults to false. - // +optional - DryRun *bool `json:"dryRun,omitempty" protobuf:"varint,11,opt,name=dryRun"` - // Options is the operation option structure of the operation being performed. - // e.g. `meta.k8s.io/v1.DeleteOptions` or `meta.k8s.io/v1.CreateOptions`. This may be - // different than the options the caller provided. e.g. for a patch request the performed - // Operation might be a CREATE, in which case the Options will a - // `meta.k8s.io/v1.CreateOptions` even though the caller provided `meta.k8s.io/v1.PatchOptions`. - // +optional - Options runtime.RawExtension `json:"options,omitempty" protobuf:"bytes,12,opt,name=options"` -} - -// AdmissionResponse describes an admission response. -type AdmissionResponse struct { - // UID is an identifier for the individual request/response. - // This should be copied over from the corresponding AdmissionRequest. - UID types.UID `json:"uid" protobuf:"bytes,1,opt,name=uid"` - - // Allowed indicates whether or not the admission request was permitted. - Allowed bool `json:"allowed" protobuf:"varint,2,opt,name=allowed"` - - // Result contains extra details into why an admission request was denied. - // This field IS NOT consulted in any way if "Allowed" is "true". - // +optional - Result *metav1.Status `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` - - // The patch body. Currently we only support "JSONPatch" which implements RFC 6902. - // +optional - Patch []byte `json:"patch,omitempty" protobuf:"bytes,4,opt,name=patch"` - - // The type of Patch. Currently we only allow "JSONPatch". - // +optional - PatchType *PatchType `json:"patchType,omitempty" protobuf:"bytes,5,opt,name=patchType"` - - // AuditAnnotations is an unstructured key value map set by remote admission controller (e.g. error=image-blacklisted). - // MutatingAdmissionWebhook and ValidatingAdmissionWebhook admission controller will prefix the keys with - // admission webhook name (e.g. imagepolicy.example.com/error=image-blacklisted). AuditAnnotations will be provided by - // the admission webhook to add additional context to the audit log for this request. - // +optional - AuditAnnotations map[string]string `json:"auditAnnotations,omitempty" protobuf:"bytes,6,opt,name=auditAnnotations"` - - // warnings is a list of warning messages to return to the requesting API client. - // Warning messages describe a problem the client making the API request should correct or be aware of. - // Limit warnings to 120 characters if possible. - // Warnings over 256 characters and large numbers of warnings may be truncated. - // +optional - Warnings []string `json:"warnings,omitempty" protobuf:"bytes,7,rep,name=warnings"` -} - -// PatchType is the type of patch being used to represent the mutated object -type PatchType string - -// PatchType constants. -const ( - PatchTypeJSONPatch PatchType = "JSONPatch" -) - -// Operation is the type of resource operation being checked for admission control -type Operation string - -// Operation constants -const ( - Create Operation = "CREATE" - Update Operation = "UPDATE" - Delete Operation = "DELETE" - Connect Operation = "CONNECT" -) diff --git a/vendor/k8s.io/api/admission/v1beta1/types_swagger_doc_generated.go b/vendor/k8s.io/api/admission/v1beta1/types_swagger_doc_generated.go deleted file mode 100644 index 82598ed57..000000000 --- a/vendor/k8s.io/api/admission/v1beta1/types_swagger_doc_generated.go +++ /dev/null @@ -1,78 +0,0 @@ -/* -Copyright 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 - -// This file contains a collection of methods that can be used from go-restful to -// generate Swagger API documentation for its models. Please read this PR for more -// information on the implementation: https://github.com/emicklei/go-restful/pull/215 -// -// TODOs are ignored from the parser (e.g. TODO(andronat):... || TODO:...) if and only if -// they are on one line! For multiple line or blocks that you want to ignore use ---. -// Any context after a --- is ignored. -// -// Those methods can be generated by using hack/update-codegen.sh - -// AUTO-GENERATED FUNCTIONS START HERE. DO NOT EDIT. -var map_AdmissionRequest = map[string]string{ - "": "AdmissionRequest describes the admission.Attributes for the admission request.", - "uid": "UID is an identifier for the individual request/response. It allows us to distinguish instances of requests which are otherwise identical (parallel requests, requests when earlier requests did not modify etc) The UID is meant to track the round trip (request/response) between the KAS and the WebHook, not the user request. It is suitable for correlating log entries between the webhook and apiserver, for either auditing or debugging.", - "kind": "Kind is the fully-qualified type of object being submitted (for example, v1.Pod or autoscaling.v1.Scale)", - "resource": "Resource is the fully-qualified resource being requested (for example, v1.pods)", - "subResource": "SubResource is the subresource being requested, if any (for example, \"status\" or \"scale\")", - "requestKind": "RequestKind is the fully-qualified type of the original API request (for example, v1.Pod or autoscaling.v1.Scale). If this is specified and differs from the value in \"kind\", an equivalent match and conversion was performed.\n\nFor example, if deployments can be modified via apps/v1 and apps/v1beta1, and a webhook registered a rule of `apiGroups:[\"apps\"], apiVersions:[\"v1\"], resources: [\"deployments\"]` and `matchPolicy: Equivalent`, an API request to apps/v1beta1 deployments would be converted and sent to the webhook with `kind: {group:\"apps\", version:\"v1\", kind:\"Deployment\"}` (matching the rule the webhook registered for), and `requestKind: {group:\"apps\", version:\"v1beta1\", kind:\"Deployment\"}` (indicating the kind of the original API request).\n\nSee documentation for the \"matchPolicy\" field in the webhook configuration type for more details.", - "requestResource": "RequestResource is the fully-qualified resource of the original API request (for example, v1.pods). If this is specified and differs from the value in \"resource\", an equivalent match and conversion was performed.\n\nFor example, if deployments can be modified via apps/v1 and apps/v1beta1, and a webhook registered a rule of `apiGroups:[\"apps\"], apiVersions:[\"v1\"], resources: [\"deployments\"]` and `matchPolicy: Equivalent`, an API request to apps/v1beta1 deployments would be converted and sent to the webhook with `resource: {group:\"apps\", version:\"v1\", resource:\"deployments\"}` (matching the resource the webhook registered for), and `requestResource: {group:\"apps\", version:\"v1beta1\", resource:\"deployments\"}` (indicating the resource of the original API request).\n\nSee documentation for the \"matchPolicy\" field in the webhook configuration type.", - "requestSubResource": "RequestSubResource is the name of the subresource of the original API request, if any (for example, \"status\" or \"scale\") If this is specified and differs from the value in \"subResource\", an equivalent match and conversion was performed. See documentation for the \"matchPolicy\" field in the webhook configuration type.", - "name": "Name is the name of the object as presented in the request. On a CREATE operation, the client may omit name and rely on the server to generate the name. If that is the case, this field will contain an empty string.", - "namespace": "Namespace is the namespace associated with the request (if any).", - "operation": "Operation is the operation being performed. This may be different than the operation requested. e.g. a patch can result in either a CREATE or UPDATE Operation.", - "userInfo": "UserInfo is information about the requesting user", - "object": "Object is the object from the incoming request.", - "oldObject": "OldObject is the existing object. Only populated for DELETE and UPDATE requests.", - "dryRun": "DryRun indicates that modifications will definitely not be persisted for this request. Defaults to false.", - "options": "Options is the operation option structure of the operation being performed. e.g. `meta.k8s.io/v1.DeleteOptions` or `meta.k8s.io/v1.CreateOptions`. This may be different than the options the caller provided. e.g. for a patch request the performed Operation might be a CREATE, in which case the Options will a `meta.k8s.io/v1.CreateOptions` even though the caller provided `meta.k8s.io/v1.PatchOptions`.", -} - -func (AdmissionRequest) SwaggerDoc() map[string]string { - return map_AdmissionRequest -} - -var map_AdmissionResponse = map[string]string{ - "": "AdmissionResponse describes an admission response.", - "uid": "UID is an identifier for the individual request/response. This should be copied over from the corresponding AdmissionRequest.", - "allowed": "Allowed indicates whether or not the admission request was permitted.", - "status": "Result contains extra details into why an admission request was denied. This field IS NOT consulted in any way if \"Allowed\" is \"true\".", - "patch": "The patch body. Currently we only support \"JSONPatch\" which implements RFC 6902.", - "patchType": "The type of Patch. Currently we only allow \"JSONPatch\".", - "auditAnnotations": "AuditAnnotations is an unstructured key value map set by remote admission controller (e.g. error=image-blacklisted). MutatingAdmissionWebhook and ValidatingAdmissionWebhook admission controller will prefix the keys with admission webhook name (e.g. imagepolicy.example.com/error=image-blacklisted). AuditAnnotations will be provided by the admission webhook to add additional context to the audit log for this request.", - "warnings": "warnings is a list of warning messages to return to the requesting API client. Warning messages describe a problem the client making the API request should correct or be aware of. Limit warnings to 120 characters if possible. Warnings over 256 characters and large numbers of warnings may be truncated.", -} - -func (AdmissionResponse) SwaggerDoc() map[string]string { - return map_AdmissionResponse -} - -var map_AdmissionReview = map[string]string{ - "": "AdmissionReview describes an admission review request/response.", - "request": "Request describes the attributes for the admission request.", - "response": "Response describes the attributes for the admission response.", -} - -func (AdmissionReview) SwaggerDoc() map[string]string { - return map_AdmissionReview -} - -// AUTO-GENERATED FUNCTIONS END HERE diff --git a/vendor/k8s.io/api/admission/v1beta1/zz_generated.deepcopy.go b/vendor/k8s.io/api/admission/v1beta1/zz_generated.deepcopy.go deleted file mode 100644 index 8234b322f..000000000 --- a/vendor/k8s.io/api/admission/v1beta1/zz_generated.deepcopy.go +++ /dev/null @@ -1,142 +0,0 @@ -//go:build !ignore_autogenerated -// +build !ignore_autogenerated - -/* -Copyright 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 deepcopy-gen. DO NOT EDIT. - -package v1beta1 - -import ( - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - runtime "k8s.io/apimachinery/pkg/runtime" -) - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *AdmissionRequest) DeepCopyInto(out *AdmissionRequest) { - *out = *in - out.Kind = in.Kind - out.Resource = in.Resource - if in.RequestKind != nil { - in, out := &in.RequestKind, &out.RequestKind - *out = new(v1.GroupVersionKind) - **out = **in - } - if in.RequestResource != nil { - in, out := &in.RequestResource, &out.RequestResource - *out = new(v1.GroupVersionResource) - **out = **in - } - in.UserInfo.DeepCopyInto(&out.UserInfo) - in.Object.DeepCopyInto(&out.Object) - in.OldObject.DeepCopyInto(&out.OldObject) - if in.DryRun != nil { - in, out := &in.DryRun, &out.DryRun - *out = new(bool) - **out = **in - } - in.Options.DeepCopyInto(&out.Options) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AdmissionRequest. -func (in *AdmissionRequest) DeepCopy() *AdmissionRequest { - if in == nil { - return nil - } - out := new(AdmissionRequest) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *AdmissionResponse) DeepCopyInto(out *AdmissionResponse) { - *out = *in - if in.Result != nil { - in, out := &in.Result, &out.Result - *out = new(v1.Status) - (*in).DeepCopyInto(*out) - } - if in.Patch != nil { - in, out := &in.Patch, &out.Patch - *out = make([]byte, len(*in)) - copy(*out, *in) - } - if in.PatchType != nil { - in, out := &in.PatchType, &out.PatchType - *out = new(PatchType) - **out = **in - } - if in.AuditAnnotations != nil { - in, out := &in.AuditAnnotations, &out.AuditAnnotations - *out = make(map[string]string, len(*in)) - for key, val := range *in { - (*out)[key] = val - } - } - if in.Warnings != nil { - in, out := &in.Warnings, &out.Warnings - *out = make([]string, len(*in)) - copy(*out, *in) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AdmissionResponse. -func (in *AdmissionResponse) DeepCopy() *AdmissionResponse { - if in == nil { - return nil - } - out := new(AdmissionResponse) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *AdmissionReview) DeepCopyInto(out *AdmissionReview) { - *out = *in - out.TypeMeta = in.TypeMeta - if in.Request != nil { - in, out := &in.Request, &out.Request - *out = new(AdmissionRequest) - (*in).DeepCopyInto(*out) - } - if in.Response != nil { - in, out := &in.Response, &out.Response - *out = new(AdmissionResponse) - (*in).DeepCopyInto(*out) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AdmissionReview. -func (in *AdmissionReview) DeepCopy() *AdmissionReview { - if in == nil { - return nil - } - out := new(AdmissionReview) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *AdmissionReview) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} diff --git a/vendor/k8s.io/api/admission/v1beta1/zz_generated.prerelease-lifecycle.go b/vendor/k8s.io/api/admission/v1beta1/zz_generated.prerelease-lifecycle.go deleted file mode 100644 index f96e8a443..000000000 --- a/vendor/k8s.io/api/admission/v1beta1/zz_generated.prerelease-lifecycle.go +++ /dev/null @@ -1,50 +0,0 @@ -//go:build !ignore_autogenerated -// +build !ignore_autogenerated - -/* -Copyright 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 prerelease-lifecycle-gen. DO NOT EDIT. - -package v1beta1 - -import ( - schema "k8s.io/apimachinery/pkg/runtime/schema" -) - -// APILifecycleIntroduced is an autogenerated function, returning the release in which the API struct was introduced as int versions of major and minor for comparison. -// It is controlled by "k8s:prerelease-lifecycle-gen:introduced" tags in types.go. -func (in *AdmissionReview) APILifecycleIntroduced() (major, minor int) { - return 1, 9 -} - -// APILifecycleDeprecated is an autogenerated function, returning the release in which the API struct was or will be deprecated as int versions of major and minor for comparison. -// It is controlled by "k8s:prerelease-lifecycle-gen:deprecated" tags in types.go or "k8s:prerelease-lifecycle-gen:introduced" plus three minor. -func (in *AdmissionReview) APILifecycleDeprecated() (major, minor int) { - return 1, 19 -} - -// APILifecycleReplacement is an autogenerated function, returning the group, version, and kind that should be used instead of this deprecated type. -// It is controlled by "k8s:prerelease-lifecycle-gen:replacement=,," tags in types.go. -func (in *AdmissionReview) APILifecycleReplacement() schema.GroupVersionKind { - return schema.GroupVersionKind{Group: "admission.k8s.io", Version: "v1", Kind: "AdmissionReview"} -} - -// APILifecycleRemoved is an autogenerated function, returning the release in which the API is no longer served as int versions of major and minor for comparison. -// It is controlled by "k8s:prerelease-lifecycle-gen:removed" tags in types.go or "k8s:prerelease-lifecycle-gen:deprecated" plus three minor. -func (in *AdmissionReview) APILifecycleRemoved() (major, minor int) { - return 1, 22 -} diff --git a/vendor/k8s.io/apimachinery/pkg/api/apitesting/fuzzer/fuzzer.go b/vendor/k8s.io/apimachinery/pkg/api/apitesting/fuzzer/fuzzer.go deleted file mode 100644 index f528e9f92..000000000 --- a/vendor/k8s.io/apimachinery/pkg/api/apitesting/fuzzer/fuzzer.go +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright 2017 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package fuzzer - -import ( - "math/rand" - - "github.com/google/gofuzz" - - runtimeserializer "k8s.io/apimachinery/pkg/runtime/serializer" -) - -// FuzzerFuncs returns a list of func(*SomeType, c fuzz.Continue) functions. -type FuzzerFuncs func(codecs runtimeserializer.CodecFactory) []interface{} - -// FuzzerFor can randomly populate api objects that are destined for version. -func FuzzerFor(funcs FuzzerFuncs, src rand.Source, codecs runtimeserializer.CodecFactory) *fuzz.Fuzzer { - f := fuzz.New().NilChance(.5).NumElements(0, 1) - if src != nil { - f.RandSource(src) - } - f.Funcs(funcs(codecs)...) - return f -} - -// MergeFuzzerFuncs will merge the given funcLists, overriding early funcs with later ones if there first -// argument has the same type. -func MergeFuzzerFuncs(funcs ...FuzzerFuncs) FuzzerFuncs { - return FuzzerFuncs(func(codecs runtimeserializer.CodecFactory) []interface{} { - result := []interface{}{} - for _, f := range funcs { - if f != nil { - result = append(result, f(codecs)...) - } - } - return result - }) -} diff --git a/vendor/k8s.io/apimachinery/pkg/api/apitesting/fuzzer/valuefuzz.go b/vendor/k8s.io/apimachinery/pkg/api/apitesting/fuzzer/valuefuzz.go deleted file mode 100644 index facff57bb..000000000 --- a/vendor/k8s.io/apimachinery/pkg/api/apitesting/fuzzer/valuefuzz.go +++ /dev/null @@ -1,86 +0,0 @@ -/* -Copyright 2017 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package fuzzer - -import ( - "reflect" -) - -// ValueFuzz recursively changes all basic type values in an object. Any kind of references will not -// be touch, i.e. the addresses of slices, maps, pointers will stay unchanged. -func ValueFuzz(obj interface{}) { - valueFuzz(reflect.ValueOf(obj)) -} - -func valueFuzz(obj reflect.Value) { - switch obj.Kind() { - case reflect.Array: - for i := 0; i < obj.Len(); i++ { - valueFuzz(obj.Index(i)) - } - case reflect.Slice: - if obj.IsNil() { - // TODO: set non-nil value - } else { - for i := 0; i < obj.Len(); i++ { - valueFuzz(obj.Index(i)) - } - } - case reflect.Interface, reflect.Pointer: - if obj.IsNil() { - // TODO: set non-nil value - } else { - valueFuzz(obj.Elem()) - } - case reflect.Struct: - for i, n := 0, obj.NumField(); i < n; i++ { - valueFuzz(obj.Field(i)) - } - case reflect.Map: - if obj.IsNil() { - // TODO: set non-nil value - } else { - for _, k := range obj.MapKeys() { - // map values are not addressable. We need a copy. - v := obj.MapIndex(k) - copy := reflect.New(v.Type()) - copy.Elem().Set(v) - valueFuzz(copy.Elem()) - obj.SetMapIndex(k, copy.Elem()) - } - // TODO: set some new value - } - case reflect.Func: // ignore, we don't have function types in our API - default: - if !obj.CanSet() { - return - } - switch obj.Kind() { - case reflect.String: - obj.SetString(obj.String() + "x") - case reflect.Bool: - obj.SetBool(!obj.Bool()) - case reflect.Float32, reflect.Float64: - obj.SetFloat(obj.Float()*2.0 + 1.0) - case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: - obj.SetInt(obj.Int() + 1) - case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: - obj.SetUint(obj.Uint() + 1) - default: - } - } -} diff --git a/vendor/modules.txt b/vendor/modules.txt index aed2a1603..50324b7ee 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -20,10 +20,6 @@ github.com/emicklei/go-restful/v3/log # github.com/evanphx/json-patch v5.9.0+incompatible ## explicit github.com/evanphx/json-patch -# github.com/fsnotify/fsnotify v1.8.0 -## explicit; go 1.17 -github.com/fsnotify/fsnotify -github.com/fsnotify/fsnotify/internal # github.com/fxamacker/cbor/v2 v2.7.0 ## explicit; go 1.17 github.com/fxamacker/cbor/v2 @@ -88,9 +84,6 @@ github.com/google/uuid # github.com/imdario/mergo v0.3.13 ## explicit; go 1.13 github.com/imdario/mergo -# github.com/inconshreveable/mousetrap v1.1.0 -## explicit; go 1.18 -github.com/inconshreveable/mousetrap # github.com/josharian/intern v1.0.0 ## explicit; go 1.5 github.com/josharian/intern @@ -172,9 +165,6 @@ github.com/prometheus/common/model github.com/prometheus/procfs github.com/prometheus/procfs/internal/fs github.com/prometheus/procfs/internal/util -# github.com/spf13/cobra v1.8.1 -## explicit; go 1.15 -github.com/spf13/cobra # github.com/spf13/pflag v1.0.5 ## explicit; go 1.12 github.com/spf13/pflag @@ -353,8 +343,6 @@ gopkg.in/yaml.v2 gopkg.in/yaml.v3 # k8s.io/api v0.31.0 => k8s.io/api v0.31.0 ## explicit; go 1.22.0 -k8s.io/api/admission/v1 -k8s.io/api/admission/v1beta1 k8s.io/api/admissionregistration/v1 k8s.io/api/admissionregistration/v1alpha1 k8s.io/api/admissionregistration/v1beta1 @@ -413,7 +401,6 @@ k8s.io/api/storage/v1beta1 k8s.io/api/storagemigration/v1alpha1 # k8s.io/apimachinery v0.31.0 => k8s.io/apimachinery v0.31.0 ## explicit; go 1.22.0 -k8s.io/apimachinery/pkg/api/apitesting/fuzzer k8s.io/apimachinery/pkg/api/equality k8s.io/apimachinery/pkg/api/errors k8s.io/apimachinery/pkg/api/meta