repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/provider.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/provider.go
/* Copyright 2019 Red Hat Inc. 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 ( "os" "strconv" libcnd "github.com/kubev2v/forklift/pkg/lib/condition" core "k8s.io/api/core/v1" meta "k8s.io/apimachinery/pkg/apis/meta/v1" ) type ProviderType string // Provider types. const ( Undefined ProviderType = "" // OpenShift OpenShift ProviderType = "openshift" // vSphere VSphere ProviderType = "vsphere" // oVirt OVirt ProviderType = "ovirt" // OpenStack OpenStack ProviderType = "openstack" // OVA Ova ProviderType = "ova" ) var ProviderTypes = []ProviderType{ OpenShift, VSphere, OVirt, OpenStack, Ova, } func (t ProviderType) String() string { return string(t) } // Secret fields. const ( Insecure = "insecureSkipVerify" Token = "token" ) // Provider settings. const ( VDDK = "vddkInitImage" SDK = "sdkEndpoint" VCenter = "vcenter" ESXI = "esxi" UseVddkAioOptimization = "useVddkAioOptimization" VddkConfig = "vddkConfig" ESXiCloneMethod = "esxiCloneMethod" ) // ESXi clone method values. const ( ESXiCloneMethodVIB = "vib" ESXiCloneMethodSSH = "ssh" ) const OvaProviderFinalizer = "forklift/ova-provider" // Defines the desired state of Provider. type ProviderSpec struct { // Provider type. Type *ProviderType `json:"type"` // The provider URL. // Empty may be used for the `host` provider. URL string `json:"url,omitempty"` // References a secret containing credentials and // other confidential information. Secret core.ObjectReference `json:"secret" ref:"Secret"` // Provider settings. Settings map[string]string `json:"settings,omitempty"` } // ProviderStatus defines the observed state of Provider type ProviderStatus struct { // Current life cycle phase of the provider. // +optional Phase string `json:"phase,omitempty"` // Conditions. libcnd.Conditions `json:",inline"` // The most recent generation observed by the controller. // +optional ObservedGeneration int64 `json:"observedGeneration,omitempty"` // Fingerprint. // +optional Fingerprint string `json:"fingerprint,omitempty"` // Provider service reference // +optional Service *core.ObjectReference `json:"service,omitempty"` } // +genclient // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // +k8s:openapi-gen=true // +kubebuilder:subresource:status // +kubebuilder:printcolumn:name="TYPE",type="string",JSONPath=".spec.type" // +kubebuilder:printcolumn:name="STATUS",type="string",JSONPath=".status.phase" // +kubebuilder:printcolumn:name="READY",type=string,JSONPath=".status.conditions[?(@.type=='Ready')].status" // +kubebuilder:printcolumn:name="CONNECTED",type=string,JSONPath=".status.conditions[?(@.type=='ConnectionTestSucceeded')].status" // +kubebuilder:printcolumn:name="INVENTORY",type=string,JSONPath=".status.conditions[?(@.type=='InventoryCreated')].status" // +kubebuilder:printcolumn:name="URL",type="string",JSONPath=".spec.url" // +kubebuilder:printcolumn:name="AGE",type="date",JSONPath=".metadata.creationTimestamp" type Provider struct { meta.TypeMeta `json:",inline"` meta.ObjectMeta `json:"metadata,omitempty"` Spec ProviderSpec `json:"spec,omitempty"` Status ProviderStatus `json:"status,omitempty"` } // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object type ProviderList struct { meta.TypeMeta `json:",inline"` meta.ListMeta `json:"metadata,omitempty"` Items []Provider `json:"items"` } func init() { SchemeBuilder.Register(&Provider{}, &ProviderList{}) } // The provider type. func (p *Provider) Type() ProviderType { if p.Spec.Type != nil { return *p.Spec.Type } return Undefined } func (p *Provider) SupportsPreserveStaticIps() bool { return p.Type() == VSphere } // This provider is the `host` cluster. func (p *Provider) IsHost() bool { return p.Type() == OpenShift && p.Spec.URL == "" } // This provider is a `host` provider but it is not within the main forklift // namespace (e.g. generally 'konveyor-forklift' or 'openshift-mtv'). All other // 'host' providers are namespace-scoped and should use limited credentials func (p *Provider) IsRestrictedHost() bool { return p.IsHost() && p.GetNamespace() != os.Getenv("POD_NAMESPACE") } // Current generation has been reconciled. func (p *Provider) HasReconciled() bool { return p.Generation == p.Status.ObservedGeneration } // This provider requires VM guest conversion. func (p *Provider) RequiresConversion() bool { return p.Type() == VSphere || p.Type() == Ova } // This provider support the vddk aio parameters. func (p *Provider) UseVddkAioOptimization() bool { useVddkAioOptimization := p.Spec.Settings[UseVddkAioOptimization] if useVddkAioOptimization == "" { return false } parseBool, err := strconv.ParseBool(useVddkAioOptimization) if err != nil { return false } return parseBool }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/doc.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/doc.go
/* Copyright 2019 Red Hat Inc. 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 v1alpha1 contains API Schema definitions for the migration v1alpha1 API group // +k8s:openapi-gen=true // +k8s:deepcopy-gen=package,register // +k8s:conversion-gen=github.com/kubev2v/forklift/pkg/apis // +k8s:defaulter-gen=TypeMeta // +groupName=forklift.konveyor.io package v1beta1 import libcnd "github.com/kubev2v/forklift/pkg/lib/condition" // GlanceSource represents an image of which the source is Glance, to be used in storage mapping const GlanceSource = "glance" // Conditions const ( ConditionExecuting = "Executing" ConditionRunning = "Running" ConditionPending = "Pending" ConditionCanceled = "Canceled" ConditionSucceeded = "Succeeded" ConditionFailed = "Failed" ConditionBlocked = "Blocked" ConditionDeleted = "Deleted" ) // Condition categories const ( CategoryRequired = libcnd.Required CategoryAdvisory = libcnd.Advisory CategoryCritical = libcnd.Critical CategoryError = libcnd.Error CategoryWarn = libcnd.Warn ) // VM Phases: // // Common phases. const ( PhaseStarted = "Started" PhasePreHook = "PreHook" PhasePostHook = "PostHook" PhaseCompleted = "Completed" ) // Warm and cold phases. const ( PhaseAddCheckpoint = "AddCheckpoint" PhaseAddFinalCheckpoint = "AddFinalCheckpoint" PhaseAllocateDisks = "AllocateDisks" PhaseConvertGuest = "ConvertGuest" PhaseConvertOpenstackSnapshot = "ConvertOpenstackSnapshot" PhaseCopyDisks = "CopyDisks" PhaseCopyDisksVirtV2V = "CopyDisksVirtV2V" PhaseCopyingPaused = "CopyingPaused" PhaseCreateDataVolumes = "CreateDataVolumes" PhaseCreateFinalSnapshot = "CreateFinalSnapshot" PhaseCreateGuestConversionPod = "CreateGuestConversionPod" PhaseCreateInitialSnapshot = "CreateInitialSnapshot" PhaseCreateSnapshot = "CreateSnapshot" PhaseCreateVM = "CreateVM" PhaseFinalize = "Finalize" PhasePreflightInspection = "PreflightInspection" PhasePowerOffSource = "PowerOffSource" PhaseRemoveFinalSnapshot = "RemoveFinalSnapshot" PhaseRemovePenultimateSnapshot = "RemovePenultimateSnapshot" PhaseRemovePreviousSnapshot = "RemovePreviousSnapshot" PhaseStoreInitialSnapshotDeltas = "StoreInitialSnapshotDeltas" PhaseStorePowerState = "StorePowerState" PhaseStoreSnapshotDeltas = "StoreSnapshotDeltas" PhaseWaitForDataVolumesStatus = "WaitForDataVolumesStatus" PhaseWaitForFinalDataVolumesStatus = "WaitForFinalDataVolumesStatus" PhaseWaitForFinalSnapshot = "WaitForFinalSnapshot" PhaseWaitForFinalSnapshotRemoval = "WaitForFinalSnapshotRemoval" PhaseWaitForInitialSnapshot = "WaitForInitialSnapshot" PhaseWaitForPenultimateSnapshotRemoval = "WaitForPenultimateSnapshotRemoval" PhaseWaitForPowerOff = "WaitForPowerOff" PhaseWaitForPreviousSnapshotRemoval = "WaitForPreviousSnapshotRemoval" PhaseWaitForSnapshot = "WaitForSnapshot" ) // Step/task phases. const ( StepStarted = "Started" StepPending = "Pending" StepRunning = "Running" StepCompleted = "Completed" ) // Annotations. const ( AnnDiskSource = "forklift.konveyor.io/disk-source" AnnSource = "forklift.konveyor.io/source" )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/mapping.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/mapping.go
/* Copyright 2019 Red Hat Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package v1beta1 import ( "fmt" "github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/provider" "github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/ref" libcnd "github.com/kubev2v/forklift/pkg/lib/condition" core "k8s.io/api/core/v1" meta "k8s.io/apimachinery/pkg/apis/meta/v1" ) // Mapped network destination. type DestinationNetwork struct { // Type of network to use for the destination. // Valid values: // - pod: Use the Kubernetes pod network // - multus: Use a Multus additional network // - ignored: Network is excluded from mapping // +kubebuilder:validation:Enum=pod;multus;ignored Type string `json:"type"` // The namespace (multus only). Namespace string `json:"namespace,omitempty"` // The name. Name string `json:"name,omitempty"` } // Mapped network. type NetworkPair struct { // Source network. Source ref.Ref `json:"source"` // Destination network. Destination DestinationNetwork `json:"destination"` } // OffloadPlugin is a storage plugin that acts on the storage allocation and copying // phase of the migration. There can be more than one available but currently only // one will be supported type OffloadPlugin struct { VSphereXcopyPluginConfig *VSphereXcopyPluginConfig `json:"vsphereXcopyConfig"` } // StorageVendorProduct is an identifier of the product used for XCOPY. // NOTE - Update the kubebuilder:validation line for every change to this enum type StorageVendorProduct string const ( StorageVendorProductFlashSystem StorageVendorProduct = "flashsystem" StorageVendorProductVantara StorageVendorProduct = "vantara" StorageVendorProductOntap StorageVendorProduct = "ontap" StorageVendorProductPrimera3Par StorageVendorProduct = "primera3par" StorageVendorProductPureFlashArray StorageVendorProduct = "pureFlashArray" StorageVendorProductPowerFlex StorageVendorProduct = "powerflex" StorageVendorProductPowerMax StorageVendorProduct = "powermax" StorageVendorProductPowerStore StorageVendorProduct = "powerstore" StorageVendorProductInfinibox StorageVendorProduct = "infinibox" ) func StorageVendorProducts() []StorageVendorProduct { return []StorageVendorProduct{ StorageVendorProductFlashSystem, StorageVendorProductVantara, StorageVendorProductOntap, StorageVendorProductPrimera3Par, StorageVendorProductPureFlashArray, StorageVendorProductPowerFlex, StorageVendorProductPowerMax, StorageVendorProductPowerStore, StorageVendorProductInfinibox, } } // VSphereXcopyPluginConfig works with the Vsphere Xcopy Volume Populator // to offload the copy to Vsphere and the storage array. type VSphereXcopyPluginConfig struct { // SecretRef is the name of the secret with the storage credentials for the plugin. // The secret should reside in the same namespace where the source provider is. SecretRef string `json:"secretRef"` // StorageVendorProduct the string identifier of the storage vendor product // +kubebuilder:validation:Enum=flashsystem;vantara;ontap;primera3par;pureFlashArray;powerflex;powermax;powerstore;infinibox StorageVendorProduct StorageVendorProduct `json:"storageVendorProduct"` } // Mapped storage. type StoragePair struct { // Source storage. Source ref.Ref `json:"source"` // Destination storage. Destination DestinationStorage `json:"destination"` // Offload Plugin OffloadPlugin *OffloadPlugin `json:"offloadPlugin,omitempty"` } // Mapped storage destination. type DestinationStorage struct { // A storage class. StorageClass string `json:"storageClass"` // Volume mode. // +kubebuilder:validation:Enum=Filesystem;Block VolumeMode core.PersistentVolumeMode `json:"volumeMode,omitempty"` // Access mode. // +kubebuilder:validation:Enum=ReadWriteOnce;ReadWriteMany;ReadOnlyMany AccessMode core.PersistentVolumeAccessMode `json:"accessMode,omitempty"` } // Network map spec. type NetworkMapSpec struct { // Provider Provider provider.Pair `json:"provider"` // Map. Map []NetworkPair `json:"map"` } // Storage map spec. type StorageMapSpec struct { // Provider Provider provider.Pair `json:"provider"` // Map. Map []StoragePair `json:"map"` } // MapStatus defines the observed state of Maps. type MapStatus struct { // Conditions. libcnd.Conditions `json:",inline"` // References. ref.Refs `json:",inline"` // The most recent generation observed by the controller. // +optional ObservedGeneration int64 `json:"observedGeneration,omitempty"` } // +genclient // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // +k8s:openapi-gen=true // +kubebuilder:subresource:status // +kubebuilder:printcolumn:name="READY",type=string,JSONPath=".status.conditions[?(@.type=='Ready')].status" // +kubebuilder:printcolumn:name="AGE",type="date",JSONPath=".metadata.creationTimestamp" type NetworkMap struct { meta.TypeMeta `json:",inline"` meta.ObjectMeta `json:"metadata,omitempty"` Spec NetworkMapSpec `json:"spec,omitempty"` Status MapStatus `json:"status,omitempty"` // Referenced resources populated // during validation. Referenced `json:"-"` } // Find network map for source ID. func (r *NetworkMap) FindNetwork(networkID string) (pair NetworkPair, found bool) { for _, pair = range r.Spec.Map { if pair.Source.ID == networkID { found = true break } } return } // Find network map for source type. func (r *NetworkMap) FindNetworkByType(networkType string) (pair NetworkPair, found bool) { for _, pair = range r.Spec.Map { if pair.Source.Type == networkType { found = true break } } return } // Find network map for source name and namespace. func (r *NetworkMap) FindNetworkByNameAndNamespace(namespace, name string) (pair NetworkPair, found bool) { for _, pair = range r.Spec.Map { if pair.Source.Namespace != "" { if pair.Source.Namespace == namespace && pair.Source.Name == name { found = true break } } else if pair.Source.Name == fmt.Sprintf("%s/%s", namespace, name) { found = true break } } return } // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object type NetworkMapList struct { meta.TypeMeta `json:",inline"` meta.ListMeta `json:"metadata,omitempty"` Items []NetworkMap `json:"items"` } // +genclient // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // +k8s:openapi-gen=true // +kubebuilder:subresource:status // +kubebuilder:printcolumn:name="READY",type=string,JSONPath=".status.conditions[?(@.type=='Ready')].status" // +kubebuilder:printcolumn:name="AGE",type="date",JSONPath=".metadata.creationTimestamp" type StorageMap struct { meta.TypeMeta `json:",inline"` meta.ObjectMeta `json:"metadata,omitempty"` Spec StorageMapSpec `json:"spec,omitempty"` Status MapStatus `json:"status,omitempty"` // Referenced resources populated // during validation. Referenced `json:"-"` } // Find storage map for source ID. func (r *StorageMap) FindStorage(storageID string) (pair StoragePair, found bool) { for _, pair = range r.Spec.Map { if pair.Source.ID == storageID { found = true break } } return } // Find storage map for source Name. func (r *StorageMap) FindStorageByName(storageName string) (pair StoragePair, found bool) { for _, pair = range r.Spec.Map { if pair.Source.Name == storageName { found = true break } } return } // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object type StorageMapList struct { meta.TypeMeta `json:",inline"` meta.ListMeta `json:"metadata,omitempty"` Items []StorageMap `json:"items"` } func init() { SchemeBuilder.Register( &NetworkMap{}, &NetworkMapList{}, &StorageMap{}, &StorageMapList{}) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/migration.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/migration.go
/* Copyright 2019 Red Hat Inc. 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 ( "github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/plan" "github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/ref" libcnd "github.com/kubev2v/forklift/pkg/lib/condition" core "k8s.io/api/core/v1" meta "k8s.io/apimachinery/pkg/apis/meta/v1" ) // MigrationSpec defines the desired state of Migration type MigrationSpec struct { // Reference to the associated Plan. Plan core.ObjectReference `json:"plan" ref:"Plan"` // List of VMs which will have their imports canceled. Cancel []ref.Ref `json:"cancel,omitempty"` // Date and time to finalize a warm migration. // If present, this will override the value set on the Plan. Cutover *meta.Time `json:"cutover,omitempty"` } // Canceled indicates whether a VM ref is present // in the list of VM refs to be canceled. func (r *MigrationSpec) Canceled(ref ref.Ref) (found bool) { if ref.ID == "" { return } for _, vm := range r.Cancel { // the refs in the Cancel array might not have // all been resolved successfully, so skip // over any VMs that don't have an ID set. if vm.ID == "" { continue } if vm.ID == ref.ID { found = true return } } return } // MigrationStatus defines the observed state of Migration type MigrationStatus struct { plan.Timed `json:",inline"` // Conditions. libcnd.Conditions `json:",inline"` // The most recent generation observed by the controller. // +optional ObservedGeneration int64 `json:"observedGeneration,omitempty"` // VM status VMs []*plan.VMStatus `json:"vms,omitempty"` } // +genclient // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // +k8s:openapi-gen=true // +kubebuilder:subresource:status // +kubebuilder:printcolumn:name="READY",type=string,JSONPath=".status.conditions[?(@.type=='Ready')].status" // +kubebuilder:printcolumn:name="RUNNING",type=string,JSONPath=".status.conditions[?(@.type=='Running')].status" // +kubebuilder:printcolumn:name="SUCCEEDED",type=string,JSONPath=".status.conditions[?(@.type=='Succeeded')].status" // +kubebuilder:printcolumn:name="FAILED",type=string,JSONPath=".status.conditions[?(@.type=='Failed')].status" // +kubebuilder:printcolumn:name="AGE",type="date",JSONPath=".metadata.creationTimestamp" type Migration struct { meta.TypeMeta `json:",inline"` meta.ObjectMeta `json:"metadata,omitempty"` Spec MigrationSpec `json:"spec,omitempty"` Status MigrationStatus `json:"status,omitempty"` } // Match plan. func (r *Migration) Match(plan *Plan) bool { ref := r.Spec.Plan return ref.Namespace == plan.Namespace && ref.Name == plan.Name } // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object type MigrationList struct { meta.TypeMeta `json:",inline"` meta.ListMeta `json:"metadata,omitempty"` Items []Migration `json:"items"` } func init() { SchemeBuilder.Register(&Migration{}, &MigrationList{}) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/ovaserver.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/ovaserver.go
package v1beta1 import ( libcnd "github.com/kubev2v/forklift/pkg/lib/condition" v1 "k8s.io/api/core/v1" meta "k8s.io/apimachinery/pkg/apis/meta/v1" ) type OVAProviderServerSpec struct { // Reference to a Provider resource. // +kubebuilder:validation:XValidation:message="spec.provider is immutable",rule="oldSelf == null || oldSelf.name == '' || self == oldSelf" Provider v1.ObjectReference `json:"provider"` } type OVAProviderServerStatus struct { // Current life cycle phase of the OVA server. // +optional Phase string `json:"phase,omitempty"` // Reference to Service resource // +optional Service *v1.ObjectReference `json:"service,omitempty"` // Conditions. libcnd.Conditions `json:",inline"` } // +genclient // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // +k8s:openapi-gen=true // +kubebuilder:subresource:status type OVAProviderServer struct { meta.TypeMeta `json:",inline"` meta.ObjectMeta `json:"metadata,omitempty"` Spec OVAProviderServerSpec `json:"spec,omitempty"` Status OVAProviderServerStatus `json:"status,omitempty"` } // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object type OVAProviderServerList struct { meta.TypeMeta `json:",inline"` meta.ListMeta `json:"metadata,omitempty"` Items []OVAProviderServer `json:"items"` } func init() { SchemeBuilder.Register(&OVAProviderServer{}, &OVAProviderServerList{}) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/plan/vm.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/plan/vm.go
package plan import ( "fmt" "path" "github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/ref" libcnd "github.com/kubev2v/forklift/pkg/lib/condition" core "k8s.io/api/core/v1" meta "k8s.io/apimachinery/pkg/apis/meta/v1" ) // Plan hook. type HookRef struct { // Pipeline step. Step string `json:"step"` // Hook reference. Hook core.ObjectReference `json:"hook" ref:"Hook"` } // TargetPowerState defines the desired power state of the target VM after migration type TargetPowerState string const ( // Target power state constants TargetPowerStateOn TargetPowerState = "on" TargetPowerStateOff TargetPowerState = "off" TargetPowerStateAuto TargetPowerState = "auto" ) func (r *HookRef) String() string { return fmt.Sprintf( "%s @%s", path.Join(r.Hook.Namespace, r.Hook.Name), r.Step) } // A VM listed on the plan. type VM struct { ref.Ref `json:",inline"` // Enable hooks. Hooks []HookRef `json:"hooks,omitempty"` // Disk decryption LUKS keys // +optional LUKS core.ObjectReference `json:"luks" ref:"Secret"` // Attempt passphrase-less unlocking for all devices with Clevis, over the network. // Conversion pod running on target cluster will attempt to connect to a TANG server, make sure TANG // server is available on target network. // https://docs.redhat.com/en/documentation/red_hat_enterprise_linux/8/html/security_hardening/configuring-automated-unlocking-of-encrypted-volumes-using-policy-based-decryption_security-hardening // If both nbdeClevis and LUKS are configured, nbdeClevis takes precedence. // +optional NbdeClevis bool `json:"nbdeClevis,omitempty"` // Choose the primary disk the VM boots from // +optional RootDisk string `json:"rootDisk,omitempty"` // Selected InstanceType that will override the VM properties. // +optional InstanceType string `json:"instanceType,omitempty"` // PVCNameTemplate is a template for generating PVC names for VM disks. // Generated names must be valid DNS-1123 labels (lowercase alphanumerics, '-' allowed, max 63 chars). // It follows Go template syntax and has access to the following variables: // - .VmName: name of the VM in the source cluster (original source name) // - .TargetVmName: final VM name in the target cluster (may equal .VmName if no rename/normalization) // - .PlanName: name of the migration plan // - .DiskIndex: initial volume index of the disk // - .WinDriveLetter: Windows drive letter (lowercase, if applicable, e.g. "c", requires guest agent) // - .RootDiskIndex: index of the root disk // - .Shared: true if the volume is shared by multiple VMs, false otherwise // - .FileName: name of the file in the source provider (VMware only, filename includes the .vmdk suffix) // Note: // This template overrides the plan level template. // Examples: // "{{.TargetVmName}}-disk-{{.DiskIndex}}" // "{{if eq .DiskIndex .RootDiskIndex}}root{{else}}data{{end}}-{{.DiskIndex}}" // "{{if .Shared}}shared-{{end}}{{.VmName | lower}}-{{.DiskIndex}}" // See: // https://github.com/kubev2v/forklift/tree/main/pkg/templateutil for template functions. // +optional PVCNameTemplate string `json:"pvcNameTemplate,omitempty"` // VolumeNameTemplate is a template for generating volume interface names in the target virtual machine. // It follows Go template syntax and has access to the following variables: // - .PVCName: name of the PVC mounted to the VM using this volume // - .VolumeIndex: sequential index of the volume interface (0-based) // Note: // - This template will override at the plan level template // - If not specified on VM level and on Plan leverl, default naming conventions will be used // Examples: // "disk-{{.VolumeIndex}}" // "pvc-{{.PVCName}}" // +optional VolumeNameTemplate string `json:"volumeNameTemplate,omitempty"` // NetworkNameTemplate is a template for generating network interface names in the target virtual machine. // It follows Go template syntax and has access to the following variables: // - .NetworkName: If target network is multus, name of the Multus network attachment definition, empty otherwise. // - .NetworkNamespace: If target network is multus, namespace where the network attachment definition is located. // - .NetworkType: type of the network ("Multus" or "Pod") // - .NetworkIndex: sequential index of the network interface (0-based) // The template can be used to customize network interface names based on target network configuration. // Note: // - This template will override at the plan level template // - If not specified on VM level and on Plan leverl, default naming conventions will be used // Examples: // "net-{{.NetworkIndex}}" // "{{if eq .NetworkType "Pod"}}pod{{else}}multus-{{.NetworkIndex}}{{end}}" // +optional NetworkNameTemplate string `json:"networkNameTemplate,omitempty"` // TargetName specifies a custom name for the VM in the target cluster. // If not provided, the original VM name will be used and automatically adjusted to meet k8s DNS1123 requirements. // If provided, this exact name will be used instead. The migration will fail if the name is not unique or already in use. // +optional TargetName string `json:"targetName,omitempty"` // TargetPowerState specifies the desired power state of the target VM after migration. // - "on": Target VM will be powered on after migration // - "off": Target VM will be powered off after migration // - "auto" or nil (default): Target VM will match the source VM's power state // +optional // +kubebuilder:validation:Enum=on;off;auto TargetPowerState TargetPowerState `json:"targetPowerState,omitempty"` // DeleteVmOnFailMigration controls whether the target VM created by this Plan is deleted when a migration fails. // When true and the migration fails after the target VM has been created, the controller // will delete the target VM (and related target-side resources) during failed-migration cleanup // and when the Plan is deleted. When false (default), the target VM is preserved to aid // troubleshooting. The source VM is never modified. // // Note: If the Plan-level option is set to true, the VM-level option will be ignored. // // +optional DeleteVmOnFailMigration bool `json:"deleteVmOnFailMigration,omitempty"` } // Find a Hook for the specified step. func (r *VM) FindHook(step string) (ref HookRef, found bool) { for _, h := range r.Hooks { if h.Step == step { found = true ref = h break } } return } // VM Status type VMStatus struct { Timed `json:",inline"` VM `json:",inline"` // Migration pipeline. Pipeline []*Step `json:"pipeline"` // Phase Phase string `json:"phase"` // Errors Error *Error `json:"error,omitempty"` // Warm migration status Warm *Warm `json:"warm,omitempty"` // Source VM power state before migration. RestorePowerState VMPowerState `json:"restorePowerState,omitempty"` // The firmware type detected from the OVF file produced by virt-v2v. Firmware string `json:"firmware,omitempty"` // The Operating System detected by virt-v2v. OperatingSystem string `json:"operatingSystem,omitempty"` // The new name of the VM after matching DNS1123 requirements. NewName string `json:"newName,omitempty"` // Conditions. libcnd.Conditions `json:",inline"` } // Warm Migration status type Warm struct { Successes int `json:"successes"` Failures int `json:"failures"` ConsecutiveFailures int `json:"consecutiveFailures"` NextPrecopyAt *meta.Time `json:"nextPrecopyAt,omitempty"` Precopies []Precopy `json:"precopies,omitempty"` } type VMPowerState string const ( VMPowerStateOn VMPowerState = "On" VMPowerStateOff VMPowerState = "Off" VMPowerStateUnknown VMPowerState = "Unknown" ) // Precopy durations type Precopy struct { Start *meta.Time `json:"start,omitempty"` End *meta.Time `json:"end,omitempty"` Snapshot string `json:"snapshot,omitempty"` CreateTaskId string `json:"createTaskId,omitempty"` RemoveTaskId string `json:"removeTaskId,omitempty"` Deltas []DiskDelta `json:"deltas,omitempty"` } func (r *Precopy) WithDeltas(deltas map[string]string) { for disk, deltaId := range deltas { r.Deltas = append(r.Deltas, DiskDelta{Disk: disk, DeltaID: deltaId}) } } func (r *Precopy) DeltaMap() map[string]string { mapping := make(map[string]string) for _, d := range r.Deltas { mapping[d.Disk] = d.DeltaID } return mapping } type DiskDelta struct { Disk string `json:"disk"` DeltaID string `json:"deltaId"` } // Find a step by name. func (r *VMStatus) FindStep(name string) (step *Step, found bool) { for _, s := range r.Pipeline { if s.Name == name { found = true step = s break } } return } // Add an error. func (r *VMStatus) AddError(reason ...string) { if r.Error == nil { r.Error = &Error{Phase: r.Phase} } r.Error.Add(reason...) } // Reflect pipeline. func (r *VMStatus) ReflectPipeline() { nStarted := 0 nCompleted := 0 for _, step := range r.Pipeline { if step.MarkedStarted() { nStarted++ } if step.MarkedCompleted() { nCompleted++ } if step.Error != nil { r.AddError(step.Error.Reasons...) } } if nStarted > 0 { r.MarkStarted() } if nCompleted == len(r.Pipeline) { r.MarkCompleted() } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/plan/zz_generated.deepcopy.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/plan/zz_generated.deepcopy.go
//go:build !ignore_autogenerated /* Copyright 2019 Red Hat Inc. 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 controller-gen. DO NOT EDIT. package plan import () // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *DiskDelta) DeepCopyInto(out *DiskDelta) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DiskDelta. func (in *DiskDelta) DeepCopy() *DiskDelta { if in == nil { return nil } out := new(DiskDelta) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Error) DeepCopyInto(out *Error) { *out = *in if in.Reasons != nil { in, out := &in.Reasons, &out.Reasons *out = make([]string, len(*in)) copy(*out, *in) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Error. func (in *Error) DeepCopy() *Error { if in == nil { return nil } out := new(Error) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *HookRef) DeepCopyInto(out *HookRef) { *out = *in out.Hook = in.Hook } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HookRef. func (in *HookRef) DeepCopy() *HookRef { if in == nil { return nil } out := new(HookRef) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Map) DeepCopyInto(out *Map) { *out = *in out.Network = in.Network out.Storage = in.Storage } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Map. func (in *Map) DeepCopy() *Map { if in == nil { return nil } out := new(Map) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *MigrationStatus) DeepCopyInto(out *MigrationStatus) { *out = *in in.Timed.DeepCopyInto(&out.Timed) if in.History != nil { in, out := &in.History, &out.History *out = make([]Snapshot, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } if in.VMs != nil { in, out := &in.VMs, &out.VMs *out = make([]*VMStatus, len(*in)) for i := range *in { if (*in)[i] != nil { in, out := &(*in)[i], &(*out)[i] *out = new(VMStatus) (*in).DeepCopyInto(*out) } } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MigrationStatus. func (in *MigrationStatus) DeepCopy() *MigrationStatus { if in == nil { return nil } out := new(MigrationStatus) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Precopy) DeepCopyInto(out *Precopy) { *out = *in if in.Start != nil { in, out := &in.Start, &out.Start *out = (*in).DeepCopy() } if in.End != nil { in, out := &in.End, &out.End *out = (*in).DeepCopy() } if in.Deltas != nil { in, out := &in.Deltas, &out.Deltas *out = make([]DiskDelta, len(*in)) copy(*out, *in) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Precopy. func (in *Precopy) DeepCopy() *Precopy { if in == nil { return nil } out := new(Precopy) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Snapshot) DeepCopyInto(out *Snapshot) { *out = *in in.Conditions.DeepCopyInto(&out.Conditions) out.Provider = in.Provider out.Plan = in.Plan out.Map = in.Map out.Migration = in.Migration } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Snapshot. func (in *Snapshot) DeepCopy() *Snapshot { if in == nil { return nil } out := new(Snapshot) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SnapshotMap) DeepCopyInto(out *SnapshotMap) { *out = *in out.Network = in.Network out.Storage = in.Storage } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SnapshotMap. func (in *SnapshotMap) DeepCopy() *SnapshotMap { if in == nil { return nil } out := new(SnapshotMap) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SnapshotRef) DeepCopyInto(out *SnapshotRef) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SnapshotRef. func (in *SnapshotRef) DeepCopy() *SnapshotRef { if in == nil { return nil } out := new(SnapshotRef) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SnapshotRefPair) DeepCopyInto(out *SnapshotRefPair) { *out = *in out.Source = in.Source out.Destination = in.Destination } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SnapshotRefPair. func (in *SnapshotRefPair) DeepCopy() *SnapshotRefPair { if in == nil { return nil } out := new(SnapshotRefPair) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Step) DeepCopyInto(out *Step) { *out = *in in.Task.DeepCopyInto(&out.Task) if in.Tasks != nil { in, out := &in.Tasks, &out.Tasks *out = make([]*Task, len(*in)) for i := range *in { if (*in)[i] != nil { in, out := &(*in)[i], &(*out)[i] *out = new(Task) (*in).DeepCopyInto(*out) } } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Step. func (in *Step) DeepCopy() *Step { if in == nil { return nil } out := new(Step) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Task) DeepCopyInto(out *Task) { *out = *in in.Timed.DeepCopyInto(&out.Timed) out.Progress = in.Progress if in.Annotations != nil { in, out := &in.Annotations, &out.Annotations *out = make(map[string]string, len(*in)) for key, val := range *in { (*out)[key] = val } } if in.Error != nil { in, out := &in.Error, &out.Error *out = new(Error) (*in).DeepCopyInto(*out) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Task. func (in *Task) DeepCopy() *Task { if in == nil { return nil } out := new(Task) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Timed) DeepCopyInto(out *Timed) { *out = *in if in.Started != nil { in, out := &in.Started, &out.Started *out = (*in).DeepCopy() } if in.Completed != nil { in, out := &in.Completed, &out.Completed *out = (*in).DeepCopy() } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Timed. func (in *Timed) DeepCopy() *Timed { if in == nil { return nil } out := new(Timed) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *VM) DeepCopyInto(out *VM) { *out = *in out.Ref = in.Ref if in.Hooks != nil { in, out := &in.Hooks, &out.Hooks *out = make([]HookRef, len(*in)) copy(*out, *in) } out.LUKS = in.LUKS } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VM. func (in *VM) DeepCopy() *VM { if in == nil { return nil } out := new(VM) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *VMStatus) DeepCopyInto(out *VMStatus) { *out = *in in.Timed.DeepCopyInto(&out.Timed) in.VM.DeepCopyInto(&out.VM) if in.Pipeline != nil { in, out := &in.Pipeline, &out.Pipeline *out = make([]*Step, len(*in)) for i := range *in { if (*in)[i] != nil { in, out := &(*in)[i], &(*out)[i] *out = new(Step) (*in).DeepCopyInto(*out) } } } if in.Error != nil { in, out := &in.Error, &out.Error *out = new(Error) (*in).DeepCopyInto(*out) } if in.Warm != nil { in, out := &in.Warm, &out.Warm *out = new(Warm) (*in).DeepCopyInto(*out) } in.Conditions.DeepCopyInto(&out.Conditions) } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VMStatus. func (in *VMStatus) DeepCopy() *VMStatus { if in == nil { return nil } out := new(VMStatus) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Warm) DeepCopyInto(out *Warm) { *out = *in if in.NextPrecopyAt != nil { in, out := &in.NextPrecopyAt, &out.NextPrecopyAt *out = (*in).DeepCopy() } if in.Precopies != nil { in, out := &in.Precopies, &out.Precopies *out = make([]Precopy, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Warm. func (in *Warm) DeepCopy() *Warm { if in == nil { return nil } out := new(Warm) in.DeepCopyInto(out) return out }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/plan/snapshot.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/plan/snapshot.go
package plan import ( libcnd "github.com/kubev2v/forklift/pkg/lib/condition" meta "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" ) // Snapshot object reference. type SnapshotRef struct { Namespace string `json:"namespace"` Name string `json:"name"` UID types.UID `json:"uid"` Generation int64 `json:"generation"` } // Source and destination pair. type SnapshotRefPair struct { Source SnapshotRef `json:"source"` Destination SnapshotRef `json:"destination"` } // Mapping. type SnapshotMap struct { Network SnapshotRef `json:"network"` Storage SnapshotRef `json:"storage"` } // Snapshot type Snapshot struct { // Conditions. libcnd.Conditions `json:",inline"` // Provider Provider SnapshotRefPair `json:"provider"` // Plan Plan SnapshotRef `json:"plan"` // Map. Map SnapshotMap `json:"map"` // Migration Migration SnapshotRef `json:"migration"` } // Populate the ref using the specified (meta) object. func (r *SnapshotRef) With(object meta.Object) { r.Namespace = object.GetNamespace() r.Name = object.GetName() r.Generation = object.GetGeneration() r.UID = object.GetUID() } // Match the object and ref by UID/Generation. func (r *SnapshotRef) Match(object meta.Object) bool { return r.UID == object.GetUID() && r.Generation == object.GetGeneration() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/plan/timed.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/plan/timed.go
package plan import meta "k8s.io/apimachinery/pkg/apis/meta/v1" // Resources that record started and completed timestamps. type Timed struct { // Started timestamp. Started *meta.Time `json:"started,omitempty"` // Completed timestamp. Completed *meta.Time `json:"completed,omitempty"` } // Reset. func (r *Timed) MarkReset() { r.Started = nil r.Completed = nil } // Mark as started. func (r *Timed) MarkStarted() { if r.Started == nil { r.Started = r.now() r.Completed = nil } } // Mark as completed. func (r *Timed) MarkCompleted() { r.MarkStarted() if r.Completed == nil { r.Completed = r.now() } } // Has started. func (r *Timed) MarkedStarted() bool { return r.Started != nil } // Is migrating. func (r *Timed) Running() bool { return r.MarkedStarted() && !r.MarkedCompleted() } // Has completed. func (r *Timed) MarkedCompleted() bool { return r.Completed != nil } func (r *Timed) now() *meta.Time { now := meta.Now() return &now }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/plan/doc.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/plan/doc.go
package plan // +k8s:deepcopy-gen=package
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/plan/mapping.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/plan/mapping.go
package plan import core "k8s.io/api/core/v1" // Maps. type Map struct { // Network. Network core.ObjectReference `json:"network" ref:"NetworkMap"` // Storage. Storage core.ObjectReference `json:"storage" ref:"StorageMap"` }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/plan/migration.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/plan/migration.go
package plan import ( "github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/ref" libitr "github.com/kubev2v/forklift/pkg/lib/itinerary" "k8s.io/apimachinery/pkg/types" ) // Error. type Error struct { Phase string `json:"phase"` Reasons []string `json:"reasons"` } // Add. func (e *Error) Add(reason ...string) { find := func(reason string) (found bool) { for _, r := range e.Reasons { if r == reason { found = true break } } return } for _, r := range reason { if !find(r) { e.Reasons = append(e.Reasons, r) } } } // Migration status. type MigrationStatus struct { Timed `json:",inline,omitempty"` // History History []Snapshot `json:"history,omitempty"` // VM status VMs []*VMStatus `json:"vms,omitempty"` } // The active snapshot. // This is the last snapshot in the history. func (r *MigrationStatus) ActiveSnapshot() *Snapshot { if len(r.History) > 0 { return &r.History[len(r.History)-1] } return &Snapshot{} } // Find snapshot for migration by UID. func (r *MigrationStatus) SnapshotWithMigration(uid types.UID) (found bool, snapshot *Snapshot) { for i := range r.History { sn := &r.History[i] if sn.Migration.UID == uid { snapshot = sn found = true } } return } // Add new snapshot. func (r *MigrationStatus) NewSnapshot(snapshot Snapshot) { r.History = append(r.History, snapshot) } // Find a VM status. func (r *MigrationStatus) FindVM(ref ref.Ref) (v *VMStatus, found bool) { for _, vm := range r.VMs { if vm.ID == ref.ID { found = true v = vm return } } return } // Pipeline step. type Step struct { Task `json:",inline"` // Nested tasks. Tasks []*Task `json:"tasks,omitempty"` } // Find task by name. func (r *Step) FindTask(name string) (task *Task, found bool) { for _, task = range r.Tasks { if task.Name == name { found = true break } } return } // Reflect task progress and errors. func (r *Step) ReflectTasks() { tasksStarted := 0 tasksCompleted := 0 completed := int64(0) for _, task := range r.Tasks { if task.MarkedStarted() { tasksStarted++ } if task.MarkedCompleted() { tasksCompleted++ } completed += task.Progress.Completed if task.Error != nil { r.AddError(task.Error.Reasons...) } } r.Progress.Completed = completed if tasksStarted > 0 { r.MarkStarted() } if tasksCompleted == len(r.Tasks) { r.MarkCompleted() } } // Migration task. type Task struct { Timed `json:",inline"` // Name. Name string `json:"name"` // Name Description string `json:"description,omitempty"` // Phase Phase string `json:"phase,omitempty"` // Reason Reason string `json:"reason,omitempty"` // Progress. Progress libitr.Progress `json:"progress"` // Annotations. Annotations map[string]string `json:"annotations,omitempty"` // Error. Error *Error `json:"error,omitempty"` } // Add an error. func (r *Task) AddError(reason ...string) { if r.Error == nil { r.Error = &Error{Phase: r.Phase} } r.Error.Add(reason...) } // Return whether the task has an error. func (r *Task) HasError() bool { return r.Error != nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/provider/pair.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/provider/pair.go
package provider import core "k8s.io/api/core/v1" // Referenced Provider pair. type Pair struct { // Source. Source core.ObjectReference `json:"source" ref:"Provider"` // Destination. Destination core.ObjectReference `json:"destination" ref:"Provider"` }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/provider/zz_generated.deepcopy.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/provider/zz_generated.deepcopy.go
//go:build !ignore_autogenerated /* Copyright 2019 Red Hat Inc. 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 controller-gen. DO NOT EDIT. package provider import () // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Pair) DeepCopyInto(out *Pair) { *out = *in out.Source = in.Source out.Destination = in.Destination } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Pair. func (in *Pair) DeepCopy() *Pair { if in == nil { return nil } out := new(Pair) in.DeepCopyInto(out) return out }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/provider/doc.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/provider/doc.go
package provider // +k8s:deepcopy-gen=package
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/ref/ref.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/ref/ref.go
package ref import "fmt" // Source reference. // Either the ID or Name must be specified. type Ref struct { // The object ID. // vsphere: // The managed object ID. ID string `json:"id,omitempty"` // An object Name. // vsphere: // A qualified name. Name string `json:"name,omitempty"` // The VM Namespace // Only relevant for an openshift source. Namespace string `json:"namespace,omitempty"` // Type used to qualify the name. Type string `json:"type,omitempty"` } // Determine if the ref either the ID or Name is set. func (r Ref) NotSet() bool { return r.ID == "" && r.Name == "" && r.Type == "" } // String representation. func (r *Ref) String() (s string) { if r.Type != "" { s = fmt.Sprintf( "(%s)", r.Type) } s = fmt.Sprintf( "%s id:%s name:'%s' ", s, r.ID, r.Name) return } // Collection of Refs. type Refs struct { List []Ref `json:"references,omitempty"` } // Determine whether the list of refs contains a given ref. func (r *Refs) Find(ref Ref) (found bool) { for _, r := range r.List { if r.ID == ref.ID { found = true break } } return }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/ref/zz_generated.deepcopy.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/ref/zz_generated.deepcopy.go
//go:build !ignore_autogenerated /* Copyright 2019 Red Hat Inc. 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 controller-gen. DO NOT EDIT. package ref import () // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Ref) DeepCopyInto(out *Ref) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Ref. func (in *Ref) DeepCopy() *Ref { if in == nil { return nil } out := new(Ref) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Refs) DeepCopyInto(out *Refs) { *out = *in if in.List != nil { in, out := &in.List, &out.List *out = make([]Ref, len(*in)) copy(*out, *in) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Refs. func (in *Refs) DeepCopy() *Refs { if in == nil { return nil } out := new(Refs) in.DeepCopyInto(out) return out }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/ref/doc.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/kubev2v/forklift/pkg/apis/forklift/v1beta1/ref/doc.go
package ref // +k8s:deepcopy-gen=package
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/moby/sys/mountinfo/mounted_unix.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/moby/sys/mountinfo/mounted_unix.go
//go:build linux || freebsd || openbsd || darwin // +build linux freebsd openbsd darwin package mountinfo import ( "os" "path/filepath" "golang.org/x/sys/unix" ) func mountedByStat(path string) (bool, error) { var st unix.Stat_t if err := unix.Lstat(path, &st); err != nil { return false, &os.PathError{Op: "stat", Path: path, Err: err} } dev := st.Dev parent := filepath.Dir(path) if err := unix.Lstat(parent, &st); err != nil { return false, &os.PathError{Op: "stat", Path: parent, Err: err} } if dev != st.Dev { // Device differs from that of parent, // so definitely a mount point. return true, nil } // NB: this does not detect bind mounts on Linux. return false, nil } func normalizePath(path string) (realPath string, err error) { if realPath, err = filepath.Abs(path); err != nil { return "", err } if realPath, err = filepath.EvalSymlinks(realPath); err != nil { return "", err } if _, err := os.Stat(realPath); err != nil { return "", err } return realPath, nil } func mountedByMountinfo(path string) (bool, error) { entries, err := GetMounts(SingleEntryFilter(path)) if err != nil { return false, err } return len(entries) > 0, nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/moby/sys/mountinfo/mountinfo_bsd.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/moby/sys/mountinfo/mountinfo_bsd.go
//go:build freebsd || openbsd || darwin // +build freebsd openbsd darwin package mountinfo import "golang.org/x/sys/unix" // parseMountTable returns information about mounted filesystems func parseMountTable(filter FilterFunc) ([]*Info, error) { count, err := unix.Getfsstat(nil, unix.MNT_WAIT) if err != nil { return nil, err } entries := make([]unix.Statfs_t, count) _, err = unix.Getfsstat(entries, unix.MNT_WAIT) if err != nil { return nil, err } var out []*Info for _, entry := range entries { var skip, stop bool mountinfo := getMountinfo(&entry) if filter != nil { // filter out entries we're not interested in skip, stop = filter(mountinfo) if skip { continue } } out = append(out, mountinfo) if stop { break } } return out, nil } func mounted(path string) (bool, error) { path, err := normalizePath(path) if err != nil { return false, err } // Fast path: compare st.st_dev fields. // This should always work for FreeBSD and OpenBSD. mounted, err := mountedByStat(path) if err == nil { return mounted, nil } // Fallback to parsing mountinfo return mountedByMountinfo(path) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/moby/sys/mountinfo/mountinfo.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/moby/sys/mountinfo/mountinfo.go
package mountinfo import ( "os" ) // GetMounts retrieves a list of mounts for the current running process, // with an optional filter applied (use nil for no filter). func GetMounts(f FilterFunc) ([]*Info, error) { return parseMountTable(f) } // Mounted determines if a specified path is a mount point. In case of any // error, false (and an error) is returned. // // If a non-existent path is specified, an appropriate error is returned. // In case the caller is not interested in this particular error, it should // be handled separately using e.g. errors.Is(err, fs.ErrNotExist). func Mounted(path string) (bool, error) { // root is always mounted if path == string(os.PathSeparator) { return true, nil } return mounted(path) } // Info reveals information about a particular mounted filesystem. This // struct is populated from the content in the /proc/<pid>/mountinfo file. type Info struct { // ID is a unique identifier of the mount (may be reused after umount). ID int // Parent is the ID of the parent mount (or of self for the root // of this mount namespace's mount tree). Parent int // Major and Minor are the major and the minor components of the Dev // field of unix.Stat_t structure returned by unix.*Stat calls for // files on this filesystem. Major, Minor int // Root is the pathname of the directory in the filesystem which forms // the root of this mount. Root string // Mountpoint is the pathname of the mount point relative to the // process's root directory. Mountpoint string // Options is a comma-separated list of mount options. Options string // Optional are zero or more fields of the form "tag[:value]", // separated by a space. Currently, the possible optional fields are // "shared", "master", "propagate_from", and "unbindable". For more // information, see mount_namespaces(7) Linux man page. Optional string // FSType is the filesystem type in the form "type[.subtype]". FSType string // Source is filesystem-specific information, or "none". Source string // VFSOptions is a comma-separated list of superblock options. VFSOptions string }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/moby/sys/mountinfo/mounted_linux.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/moby/sys/mountinfo/mounted_linux.go
package mountinfo import ( "os" "path/filepath" "golang.org/x/sys/unix" ) // MountedFast is a method of detecting a mount point without reading // mountinfo from procfs. A caller can only trust the result if no error // and sure == true are returned. Otherwise, other methods (e.g. parsing // /proc/mounts) have to be used. If unsure, use Mounted instead (which // uses MountedFast, but falls back to parsing mountinfo if needed). // // If a non-existent path is specified, an appropriate error is returned. // In case the caller is not interested in this particular error, it should // be handled separately using e.g. errors.Is(err, fs.ErrNotExist). // // This function is only available on Linux. When available (since kernel // v5.6), openat2(2) syscall is used to reliably detect all mounts. Otherwise, // the implementation falls back to using stat(2), which can reliably detect // normal (but not bind) mounts. func MountedFast(path string) (mounted, sure bool, err error) { // Root is always mounted. if path == string(os.PathSeparator) { return true, true, nil } path, err = normalizePath(path) if err != nil { return false, false, err } mounted, sure, err = mountedFast(path) return } // mountedByOpenat2 is a method of detecting a mount that works for all kinds // of mounts (incl. bind mounts), but requires a recent (v5.6+) linux kernel. func mountedByOpenat2(path string) (bool, error) { dir, last := filepath.Split(path) dirfd, err := unix.Openat2(unix.AT_FDCWD, dir, &unix.OpenHow{ Flags: unix.O_PATH | unix.O_CLOEXEC, }) if err != nil { return false, &os.PathError{Op: "openat2", Path: dir, Err: err} } fd, err := unix.Openat2(dirfd, last, &unix.OpenHow{ Flags: unix.O_PATH | unix.O_CLOEXEC | unix.O_NOFOLLOW, Resolve: unix.RESOLVE_NO_XDEV, }) _ = unix.Close(dirfd) switch err { case nil: // definitely not a mount _ = unix.Close(fd) return false, nil case unix.EXDEV: // definitely a mount return true, nil } // not sure return false, &os.PathError{Op: "openat2", Path: path, Err: err} } // mountedFast is similar to MountedFast, except it expects a normalized path. func mountedFast(path string) (mounted, sure bool, err error) { // Root is always mounted. if path == string(os.PathSeparator) { return true, true, nil } // Try a fast path, using openat2() with RESOLVE_NO_XDEV. mounted, err = mountedByOpenat2(path) if err == nil { return mounted, true, nil } // Another fast path: compare st.st_dev fields. mounted, err = mountedByStat(path) // This does not work for bind mounts, so false negative // is possible, therefore only trust if return is true. if mounted && err == nil { return true, true, nil } return } func mounted(path string) (bool, error) { path, err := normalizePath(path) if err != nil { return false, err } mounted, sure, err := mountedFast(path) if sure && err == nil { return mounted, nil } // Fallback to parsing mountinfo. return mountedByMountinfo(path) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/moby/sys/mountinfo/mountinfo_unsupported.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/moby/sys/mountinfo/mountinfo_unsupported.go
//go:build !windows && !linux && !freebsd && !openbsd && !darwin // +build !windows,!linux,!freebsd,!openbsd,!darwin package mountinfo import ( "fmt" "runtime" ) var errNotImplemented = fmt.Errorf("not implemented on %s/%s", runtime.GOOS, runtime.GOARCH) func parseMountTable(_ FilterFunc) ([]*Info, error) { return nil, errNotImplemented } func mounted(path string) (bool, error) { return false, errNotImplemented }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/moby/sys/mountinfo/mountinfo_freebsdlike.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/moby/sys/mountinfo/mountinfo_freebsdlike.go
//go:build freebsd || darwin // +build freebsd darwin package mountinfo import "golang.org/x/sys/unix" func getMountinfo(entry *unix.Statfs_t) *Info { return &Info{ Mountpoint: unix.ByteSliceToString(entry.Mntonname[:]), FSType: unix.ByteSliceToString(entry.Fstypename[:]), Source: unix.ByteSliceToString(entry.Mntfromname[:]), } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/moby/sys/mountinfo/mountinfo_filters.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/moby/sys/mountinfo/mountinfo_filters.go
package mountinfo import "strings" // FilterFunc is a type defining a callback function for GetMount(), // used to filter out mountinfo entries we're not interested in, // and/or stop further processing if we found what we wanted. // // It takes a pointer to the Info struct (fully populated with all available // fields on the GOOS platform), and returns two booleans: // // skip: true if the entry should be skipped; // // stop: true if parsing should be stopped after the entry. type FilterFunc func(*Info) (skip, stop bool) // PrefixFilter discards all entries whose mount points do not start with, or // are equal to the path specified in prefix. The prefix path must be absolute, // have all symlinks resolved, and cleaned (i.e. no extra slashes or dots). // // PrefixFilter treats prefix as a path, not a partial prefix, which means that // given "/foo", "/foo/bar" and "/foobar" entries, PrefixFilter("/foo") returns // "/foo" and "/foo/bar", and discards "/foobar". func PrefixFilter(prefix string) FilterFunc { return func(m *Info) (bool, bool) { skip := !strings.HasPrefix(m.Mountpoint+"/", prefix+"/") return skip, false } } // SingleEntryFilter looks for a specific entry. func SingleEntryFilter(mp string) FilterFunc { return func(m *Info) (bool, bool) { if m.Mountpoint == mp { return false, true // don't skip, stop now } return true, false // skip, keep going } } // ParentsFilter returns all entries whose mount points // can be parents of a path specified, discarding others. // // For example, given /var/lib/docker/something, entries // like /var/lib/docker, /var and / are returned. func ParentsFilter(path string) FilterFunc { return func(m *Info) (bool, bool) { skip := !strings.HasPrefix(path, m.Mountpoint) return skip, false } } // FSTypeFilter returns all entries that match provided fstype(s). func FSTypeFilter(fstype ...string) FilterFunc { return func(m *Info) (bool, bool) { for _, t := range fstype { if m.FSType == t { return false, false // don't skip, keep going } } return true, false // skip, keep going } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/moby/sys/mountinfo/mountinfo_windows.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/moby/sys/mountinfo/mountinfo_windows.go
package mountinfo func parseMountTable(_ FilterFunc) ([]*Info, error) { // Do NOT return an error! return nil, nil } func mounted(_ string) (bool, error) { return false, nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/moby/sys/mountinfo/mountinfo_openbsd.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/moby/sys/mountinfo/mountinfo_openbsd.go
package mountinfo import "golang.org/x/sys/unix" func getMountinfo(entry *unix.Statfs_t) *Info { return &Info{ Mountpoint: unix.ByteSliceToString(entry.F_mntonname[:]), FSType: unix.ByteSliceToString(entry.F_fstypename[:]), Source: unix.ByteSliceToString(entry.F_mntfromname[:]), } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/moby/sys/mountinfo/doc.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/moby/sys/mountinfo/doc.go
// Package mountinfo provides a set of functions to retrieve information about OS mounts. // // Currently it supports Linux. For historical reasons, there is also some support for FreeBSD and OpenBSD, // and a shallow implementation for Windows, but in general this is Linux-only package, so // the rest of the document only applies to Linux, unless explicitly specified otherwise. // // In Linux, information about mounts seen by the current process is available from // /proc/self/mountinfo. Note that due to mount namespaces, different processes can // see different mounts. A per-process mountinfo table is available from /proc/<PID>/mountinfo, // where <PID> is a numerical process identifier. // // In general, /proc is not a very efficient interface, and mountinfo is not an exception. // For example, there is no way to get information about a specific mount point (i.e. it // is all-or-nothing). This package tries to hide the /proc ineffectiveness by using // parse filters while reading mountinfo. A filter can skip some entries, or stop // processing the rest of the file once the needed information is found. // // For mountinfo filters that accept path as an argument, the path must be absolute, // having all symlinks resolved, and being cleaned (i.e. no extra slashes or dots). // One way to achieve all of the above is to employ filepath.Abs followed by // filepath.EvalSymlinks (the latter calls filepath.Clean on the result so // there is no need to explicitly call filepath.Clean). // // NOTE that in many cases there is no need to consult mountinfo at all. Here are some // of the cases where mountinfo should not be parsed: // // 1. Before performing a mount. Usually, this is not needed, but if required (say to // prevent over-mounts), to check whether a directory is mounted, call os.Lstat // on it and its parent directory, and compare their st.Sys().(*syscall.Stat_t).Dev // fields -- if they differ, then the directory is the mount point. NOTE this does // not work for bind mounts. Optionally, the filesystem type can also be checked // by calling unix.Statfs and checking the Type field (i.e. filesystem type). // // 2. After performing a mount. If there is no error returned, the mount succeeded; // checking the mount table for a new mount is redundant and expensive. // // 3. Before performing an unmount. It is more efficient to do an unmount and ignore // a specific error (EINVAL) which tells the directory is not mounted. // // 4. After performing an unmount. If there is no error returned, the unmount succeeded. // // 5. To find the mount point root of a specific directory. You can perform os.Stat() // on the directory and traverse up until the Dev field of a parent directory differs. package mountinfo
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/moby/sys/mountinfo/mountinfo_linux.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/moby/sys/mountinfo/mountinfo_linux.go
package mountinfo import ( "bufio" "fmt" "io" "os" "runtime" "strconv" "strings" "sync" "golang.org/x/sys/unix" ) // GetMountsFromReader retrieves a list of mounts from the // reader provided, with an optional filter applied (use nil // for no filter). This can be useful in tests or benchmarks // that provide fake mountinfo data, or when a source other // than /proc/thread-self/mountinfo needs to be read from. // // This function is Linux-specific. func GetMountsFromReader(r io.Reader, filter FilterFunc) ([]*Info, error) { s := bufio.NewScanner(r) out := []*Info{} for s.Scan() { var err error /* See http://man7.org/linux/man-pages/man5/proc.5.html 36 35 98:0 /mnt1 /mnt2 rw,noatime master:1 - ext3 /dev/root rw,errors=continue (1)(2)(3) (4) (5) (6) (7) (8) (9) (10) (11) (1) mount ID: unique identifier of the mount (may be reused after umount) (2) parent ID: ID of parent (or of self for the top of the mount tree) (3) major:minor: value of st_dev for files on filesystem (4) root: root of the mount within the filesystem (5) mount point: mount point relative to the process's root (6) mount options: per mount options (7) optional fields: zero or more fields of the form "tag[:value]" (8) separator: marks the end of the optional fields (9) filesystem type: name of filesystem of the form "type[.subtype]" (10) mount source: filesystem specific information or "none" (11) super options: per super block options In other words, we have: * 6 mandatory fields (1)..(6) * 0 or more optional fields (7) * a separator field (8) * 3 mandatory fields (9)..(11) */ text := s.Text() fields := strings.Split(text, " ") numFields := len(fields) if numFields < 10 { // should be at least 10 fields return nil, fmt.Errorf("parsing '%s' failed: not enough fields (%d)", text, numFields) } // separator field sepIdx := numFields - 4 // In Linux <= 3.9 mounting a cifs with spaces in a share // name (like "//srv/My Docs") _may_ end up having a space // in the last field of mountinfo (like "unc=//serv/My Docs"). // Since kernel 3.10-rc1, cifs option "unc=" is ignored, // so spaces should not appear. // // Check for a separator, and work around the spaces bug for fields[sepIdx] != "-" { sepIdx-- if sepIdx == 5 { return nil, fmt.Errorf("parsing '%s' failed: missing - separator", text) } } p := &Info{} p.Mountpoint, err = unescape(fields[4]) if err != nil { return nil, fmt.Errorf("parsing '%s' failed: mount point: %w", fields[4], err) } p.FSType, err = unescape(fields[sepIdx+1]) if err != nil { return nil, fmt.Errorf("parsing '%s' failed: fstype: %w", fields[sepIdx+1], err) } p.Source, err = unescape(fields[sepIdx+2]) if err != nil { return nil, fmt.Errorf("parsing '%s' failed: source: %w", fields[sepIdx+2], err) } p.VFSOptions = fields[sepIdx+3] // ignore any numbers parsing errors, as there should not be any p.ID, _ = strconv.Atoi(fields[0]) p.Parent, _ = strconv.Atoi(fields[1]) mm := strings.SplitN(fields[2], ":", 3) if len(mm) != 2 { return nil, fmt.Errorf("parsing '%s' failed: unexpected major:minor pair %s", text, mm) } p.Major, _ = strconv.Atoi(mm[0]) p.Minor, _ = strconv.Atoi(mm[1]) p.Root, err = unescape(fields[3]) if err != nil { return nil, fmt.Errorf("parsing '%s' failed: root: %w", fields[3], err) } p.Options = fields[5] // zero or more optional fields p.Optional = strings.Join(fields[6:sepIdx], " ") // Run the filter after parsing all fields. var skip, stop bool if filter != nil { skip, stop = filter(p) if skip { continue } } out = append(out, p) if stop { break } } if err := s.Err(); err != nil { return nil, err } return out, nil } var ( haveProcThreadSelf bool haveProcThreadSelfOnce sync.Once ) func parseMountTable(filter FilterFunc) (_ []*Info, err error) { haveProcThreadSelfOnce.Do(func() { _, err := os.Stat("/proc/thread-self/mountinfo") haveProcThreadSelf = err == nil }) // We need to lock ourselves to the current OS thread in order to make sure // that the thread referenced by /proc/thread-self stays alive until we // finish parsing the file. runtime.LockOSThread() defer runtime.UnlockOSThread() var f *os.File if haveProcThreadSelf { f, err = os.Open("/proc/thread-self/mountinfo") } else { // On pre-3.17 kernels (such as CentOS 7), we don't have // /proc/thread-self/ so we need to manually construct // /proc/self/task/<tid>/ as a fallback. f, err = os.Open("/proc/self/task/" + strconv.Itoa(unix.Gettid()) + "/mountinfo") if os.IsNotExist(err) { // If /proc/self/task/... failed, it means that our active pid // namespace doesn't match the pid namespace of the /proc mount. In // this case we just have to make do with /proc/self, since there // is no other way of figuring out our tid in a parent pid // namespace on pre-3.17 kernels. f, err = os.Open("/proc/self/mountinfo") } } if err != nil { return nil, err } defer f.Close() return GetMountsFromReader(f, filter) } // PidMountInfo retrieves the list of mounts from a given process' mount // namespace. Unless there is a need to get mounts from a mount namespace // different from that of a calling process, use GetMounts. // // This function is Linux-specific. // // Deprecated: this will be removed before v1; use GetMountsFromReader with // opened /proc/<pid>/mountinfo as an argument instead. func PidMountInfo(pid int) ([]*Info, error) { f, err := os.Open(fmt.Sprintf("/proc/%d/mountinfo", pid)) if err != nil { return nil, err } defer f.Close() return GetMountsFromReader(f, nil) } // A few specific characters in mountinfo path entries (root and mountpoint) // are escaped using a backslash followed by a character's ascii code in octal. // // space -- as \040 // tab (aka \t) -- as \011 // newline (aka \n) -- as \012 // backslash (aka \\) -- as \134 // // This function converts path from mountinfo back, i.e. it unescapes the above sequences. func unescape(path string) (string, error) { // try to avoid copying if strings.IndexByte(path, '\\') == -1 { return path, nil } // The following code is UTF-8 transparent as it only looks for some // specific characters (backslash and 0..7) with values < utf8.RuneSelf, // and everything else is passed through as is. buf := make([]byte, len(path)) bufLen := 0 for i := 0; i < len(path); i++ { if path[i] != '\\' { buf[bufLen] = path[i] bufLen++ continue } s := path[i:] if len(s) < 4 { // too short return "", fmt.Errorf("bad escape sequence %q: too short", s) } c := s[1] switch c { case '0', '1', '2', '3', '4', '5', '6', '7': v := c - '0' for j := 2; j < 4; j++ { // one digit already; two more if s[j] < '0' || s[j] > '7' { return "", fmt.Errorf("bad escape sequence %q: not a digit", s[:3]) } x := s[j] - '0' v = (v << 3) | x } if v > 255 { return "", fmt.Errorf("bad escape sequence %q: out of range" + s[:3]) } buf[bufLen] = v bufLen++ i += 3 continue default: return "", fmt.Errorf("bad escape sequence %q: not a digit" + s[:3]) } } return string(buf[:bufLen]), nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/moby/sys/userns/userns_linux_fuzzer.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/moby/sys/userns/userns_linux_fuzzer.go
//go:build linux && gofuzz package userns func FuzzUIDMap(uidmap []byte) int { _ = uidMapInUserNS(string(uidmap)) return 1 }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/moby/sys/userns/userns_unsupported.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/moby/sys/userns/userns_unsupported.go
//go:build !linux package userns // inUserNS is a stub for non-Linux systems. Always returns false. func inUserNS() bool { return false }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/moby/sys/userns/userns_linux.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/moby/sys/userns/userns_linux.go
package userns import ( "bufio" "fmt" "os" "sync" ) var inUserNS = sync.OnceValue(runningInUserNS) // runningInUserNS detects whether we are currently running in a user namespace. // // This code was migrated from [libcontainer/runc] and based on an implementation // from [lcx/incus]. // // [libcontainer/runc]: https://github.com/opencontainers/runc/blob/3778ae603c706494fd1e2c2faf83b406e38d687d/libcontainer/userns/userns_linux.go#L12-L49 // [lcx/incus]: https://github.com/lxc/incus/blob/e45085dd42f826b3c8c3228e9733c0b6f998eafe/shared/util.go#L678-L700 func runningInUserNS() bool { file, err := os.Open("/proc/self/uid_map") if err != nil { // This kernel-provided file only exists if user namespaces are supported. return false } defer file.Close() buf := bufio.NewReader(file) l, _, err := buf.ReadLine() if err != nil { return false } return uidMapInUserNS(string(l)) } func uidMapInUserNS(uidMap string) bool { if uidMap == "" { // File exist but empty (the initial state when userns is created, // see user_namespaces(7)). return true } var a, b, c int64 if _, err := fmt.Sscanf(uidMap, "%d %d %d", &a, &b, &c); err != nil { // Assume we are in a regular, non user namespace. return false } // As per user_namespaces(7), /proc/self/uid_map of // the initial user namespace shows 0 0 4294967295. initNS := a == 0 && b == 0 && c == 4294967295 return !initNS }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/moby/sys/userns/userns.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/moby/sys/userns/userns.go
// Package userns provides utilities to detect whether we are currently running // in a Linux user namespace. // // This code was migrated from [libcontainer/runc], which based its implementation // on code from [lcx/incus]. // // [libcontainer/runc]: https://github.com/opencontainers/runc/blob/3778ae603c706494fd1e2c2faf83b406e38d687d/libcontainer/userns/userns_linux.go#L12-L49 // [lcx/incus]: https://github.com/lxc/incus/blob/e45085dd42f826b3c8c3228e9733c0b6f998eafe/shared/util.go#L678-L700 package userns // RunningInUserNS detects whether we are currently running in a Linux // user namespace and memoizes the result. It returns false on non-Linux // platforms. func RunningInUserNS() bool { return inUserNS() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/davecgh/go-spew/spew/config.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/davecgh/go-spew/spew/config.go
/* * Copyright (c) 2013-2016 Dave Collins <dave@davec.name> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package spew import ( "bytes" "fmt" "io" "os" ) // ConfigState houses the configuration options used by spew to format and // display values. There is a global instance, Config, that is used to control // all top-level Formatter and Dump functionality. Each ConfigState instance // provides methods equivalent to the top-level functions. // // The zero value for ConfigState provides no indentation. You would typically // want to set it to a space or a tab. // // Alternatively, you can use NewDefaultConfig to get a ConfigState instance // with default settings. See the documentation of NewDefaultConfig for default // values. type ConfigState struct { // Indent specifies the string to use for each indentation level. The // global config instance that all top-level functions use set this to a // single space by default. If you would like more indentation, you might // set this to a tab with "\t" or perhaps two spaces with " ". Indent string // MaxDepth controls the maximum number of levels to descend into nested // data structures. The default, 0, means there is no limit. // // NOTE: Circular data structures are properly detected, so it is not // necessary to set this value unless you specifically want to limit deeply // nested data structures. MaxDepth int // DisableMethods specifies whether or not error and Stringer interfaces are // invoked for types that implement them. DisableMethods bool // DisablePointerMethods specifies whether or not to check for and invoke // error and Stringer interfaces on types which only accept a pointer // receiver when the current type is not a pointer. // // NOTE: This might be an unsafe action since calling one of these methods // with a pointer receiver could technically mutate the value, however, // in practice, types which choose to satisify an error or Stringer // interface with a pointer receiver should not be mutating their state // inside these interface methods. As a result, this option relies on // access to the unsafe package, so it will not have any effect when // running in environments without access to the unsafe package such as // Google App Engine or with the "safe" build tag specified. DisablePointerMethods bool // DisablePointerAddresses specifies whether to disable the printing of // pointer addresses. This is useful when diffing data structures in tests. DisablePointerAddresses bool // DisableCapacities specifies whether to disable the printing of capacities // for arrays, slices, maps and channels. This is useful when diffing // data structures in tests. DisableCapacities bool // ContinueOnMethod specifies whether or not recursion should continue once // a custom error or Stringer interface is invoked. The default, false, // means it will print the results of invoking the custom error or Stringer // interface and return immediately instead of continuing to recurse into // the internals of the data type. // // NOTE: This flag does not have any effect if method invocation is disabled // via the DisableMethods or DisablePointerMethods options. ContinueOnMethod bool // SortKeys specifies map keys should be sorted before being printed. Use // this to have a more deterministic, diffable output. Note that only // native types (bool, int, uint, floats, uintptr and string) and types // that support the error or Stringer interfaces (if methods are // enabled) are supported, with other types sorted according to the // reflect.Value.String() output which guarantees display stability. SortKeys bool // SpewKeys specifies that, as a last resort attempt, map keys should // be spewed to strings and sorted by those strings. This is only // considered if SortKeys is true. SpewKeys bool } // Config is the active configuration of the top-level functions. // The configuration can be changed by modifying the contents of spew.Config. var Config = ConfigState{Indent: " "} // Errorf is a wrapper for fmt.Errorf that treats each argument as if it were // passed with a Formatter interface returned by c.NewFormatter. It returns // the formatted string as a value that satisfies error. See NewFormatter // for formatting details. // // This function is shorthand for the following syntax: // // fmt.Errorf(format, c.NewFormatter(a), c.NewFormatter(b)) func (c *ConfigState) Errorf(format string, a ...interface{}) (err error) { return fmt.Errorf(format, c.convertArgs(a)...) } // Fprint is a wrapper for fmt.Fprint that treats each argument as if it were // passed with a Formatter interface returned by c.NewFormatter. It returns // the number of bytes written and any write error encountered. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Fprint(w, c.NewFormatter(a), c.NewFormatter(b)) func (c *ConfigState) Fprint(w io.Writer, a ...interface{}) (n int, err error) { return fmt.Fprint(w, c.convertArgs(a)...) } // Fprintf is a wrapper for fmt.Fprintf that treats each argument as if it were // passed with a Formatter interface returned by c.NewFormatter. It returns // the number of bytes written and any write error encountered. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Fprintf(w, format, c.NewFormatter(a), c.NewFormatter(b)) func (c *ConfigState) Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { return fmt.Fprintf(w, format, c.convertArgs(a)...) } // Fprintln is a wrapper for fmt.Fprintln that treats each argument as if it // passed with a Formatter interface returned by c.NewFormatter. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Fprintln(w, c.NewFormatter(a), c.NewFormatter(b)) func (c *ConfigState) Fprintln(w io.Writer, a ...interface{}) (n int, err error) { return fmt.Fprintln(w, c.convertArgs(a)...) } // Print is a wrapper for fmt.Print that treats each argument as if it were // passed with a Formatter interface returned by c.NewFormatter. It returns // the number of bytes written and any write error encountered. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Print(c.NewFormatter(a), c.NewFormatter(b)) func (c *ConfigState) Print(a ...interface{}) (n int, err error) { return fmt.Print(c.convertArgs(a)...) } // Printf is a wrapper for fmt.Printf that treats each argument as if it were // passed with a Formatter interface returned by c.NewFormatter. It returns // the number of bytes written and any write error encountered. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Printf(format, c.NewFormatter(a), c.NewFormatter(b)) func (c *ConfigState) Printf(format string, a ...interface{}) (n int, err error) { return fmt.Printf(format, c.convertArgs(a)...) } // Println is a wrapper for fmt.Println that treats each argument as if it were // passed with a Formatter interface returned by c.NewFormatter. It returns // the number of bytes written and any write error encountered. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Println(c.NewFormatter(a), c.NewFormatter(b)) func (c *ConfigState) Println(a ...interface{}) (n int, err error) { return fmt.Println(c.convertArgs(a)...) } // Sprint is a wrapper for fmt.Sprint that treats each argument as if it were // passed with a Formatter interface returned by c.NewFormatter. It returns // the resulting string. See NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Sprint(c.NewFormatter(a), c.NewFormatter(b)) func (c *ConfigState) Sprint(a ...interface{}) string { return fmt.Sprint(c.convertArgs(a)...) } // Sprintf is a wrapper for fmt.Sprintf that treats each argument as if it were // passed with a Formatter interface returned by c.NewFormatter. It returns // the resulting string. See NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Sprintf(format, c.NewFormatter(a), c.NewFormatter(b)) func (c *ConfigState) Sprintf(format string, a ...interface{}) string { return fmt.Sprintf(format, c.convertArgs(a)...) } // Sprintln is a wrapper for fmt.Sprintln that treats each argument as if it // were passed with a Formatter interface returned by c.NewFormatter. It // returns the resulting string. See NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Sprintln(c.NewFormatter(a), c.NewFormatter(b)) func (c *ConfigState) Sprintln(a ...interface{}) string { return fmt.Sprintln(c.convertArgs(a)...) } /* NewFormatter returns a custom formatter that satisfies the fmt.Formatter interface. As a result, it integrates cleanly with standard fmt package printing functions. The formatter is useful for inline printing of smaller data types similar to the standard %v format specifier. The custom formatter only responds to the %v (most compact), %+v (adds pointer addresses), %#v (adds types), and %#+v (adds types and pointer addresses) verb combinations. Any other verbs such as %x and %q will be sent to the the standard fmt package for formatting. In addition, the custom formatter ignores the width and precision arguments (however they will still work on the format specifiers not handled by the custom formatter). Typically this function shouldn't be called directly. It is much easier to make use of the custom formatter by calling one of the convenience functions such as c.Printf, c.Println, or c.Printf. */ func (c *ConfigState) NewFormatter(v interface{}) fmt.Formatter { return newFormatter(c, v) } // Fdump formats and displays the passed arguments to io.Writer w. It formats // exactly the same as Dump. func (c *ConfigState) Fdump(w io.Writer, a ...interface{}) { fdump(c, w, a...) } /* Dump displays the passed parameters to standard out with newlines, customizable indentation, and additional debug information such as complete types and all pointer addresses used to indirect to the final value. It provides the following features over the built-in printing facilities provided by the fmt package: * Pointers are dereferenced and followed * Circular data structures are detected and handled properly * Custom Stringer/error interfaces are optionally invoked, including on unexported types * Custom types which only implement the Stringer/error interfaces via a pointer receiver are optionally invoked when passing non-pointer variables * Byte arrays and slices are dumped like the hexdump -C command which includes offsets, byte values in hex, and ASCII output The configuration options are controlled by modifying the public members of c. See ConfigState for options documentation. See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to get the formatted result as a string. */ func (c *ConfigState) Dump(a ...interface{}) { fdump(c, os.Stdout, a...) } // Sdump returns a string with the passed arguments formatted exactly the same // as Dump. func (c *ConfigState) Sdump(a ...interface{}) string { var buf bytes.Buffer fdump(c, &buf, a...) return buf.String() } // convertArgs accepts a slice of arguments and returns a slice of the same // length with each argument converted to a spew Formatter interface using // the ConfigState associated with s. func (c *ConfigState) convertArgs(args []interface{}) (formatters []interface{}) { formatters = make([]interface{}, len(args)) for index, arg := range args { formatters[index] = newFormatter(c, arg) } return formatters } // NewDefaultConfig returns a ConfigState with the following default settings. // // Indent: " " // MaxDepth: 0 // DisableMethods: false // DisablePointerMethods: false // ContinueOnMethod: false // SortKeys: false func NewDefaultConfig() *ConfigState { return &ConfigState{Indent: " "} }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/davecgh/go-spew/spew/format.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/davecgh/go-spew/spew/format.go
/* * Copyright (c) 2013-2016 Dave Collins <dave@davec.name> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package spew import ( "bytes" "fmt" "reflect" "strconv" "strings" ) // supportedFlags is a list of all the character flags supported by fmt package. const supportedFlags = "0-+# " // formatState implements the fmt.Formatter interface and contains information // about the state of a formatting operation. The NewFormatter function can // be used to get a new Formatter which can be used directly as arguments // in standard fmt package printing calls. type formatState struct { value interface{} fs fmt.State depth int pointers map[uintptr]int ignoreNextType bool cs *ConfigState } // buildDefaultFormat recreates the original format string without precision // and width information to pass in to fmt.Sprintf in the case of an // unrecognized type. Unless new types are added to the language, this // function won't ever be called. func (f *formatState) buildDefaultFormat() (format string) { buf := bytes.NewBuffer(percentBytes) for _, flag := range supportedFlags { if f.fs.Flag(int(flag)) { buf.WriteRune(flag) } } buf.WriteRune('v') format = buf.String() return format } // constructOrigFormat recreates the original format string including precision // and width information to pass along to the standard fmt package. This allows // automatic deferral of all format strings this package doesn't support. func (f *formatState) constructOrigFormat(verb rune) (format string) { buf := bytes.NewBuffer(percentBytes) for _, flag := range supportedFlags { if f.fs.Flag(int(flag)) { buf.WriteRune(flag) } } if width, ok := f.fs.Width(); ok { buf.WriteString(strconv.Itoa(width)) } if precision, ok := f.fs.Precision(); ok { buf.Write(precisionBytes) buf.WriteString(strconv.Itoa(precision)) } buf.WriteRune(verb) format = buf.String() return format } // unpackValue returns values inside of non-nil interfaces when possible and // ensures that types for values which have been unpacked from an interface // are displayed when the show types flag is also set. // This is useful for data types like structs, arrays, slices, and maps which // can contain varying types packed inside an interface. func (f *formatState) unpackValue(v reflect.Value) reflect.Value { if v.Kind() == reflect.Interface { f.ignoreNextType = false if !v.IsNil() { v = v.Elem() } } return v } // formatPtr handles formatting of pointers by indirecting them as necessary. func (f *formatState) formatPtr(v reflect.Value) { // Display nil if top level pointer is nil. showTypes := f.fs.Flag('#') if v.IsNil() && (!showTypes || f.ignoreNextType) { f.fs.Write(nilAngleBytes) return } // Remove pointers at or below the current depth from map used to detect // circular refs. for k, depth := range f.pointers { if depth >= f.depth { delete(f.pointers, k) } } // Keep list of all dereferenced pointers to possibly show later. pointerChain := make([]uintptr, 0) // Figure out how many levels of indirection there are by derferencing // pointers and unpacking interfaces down the chain while detecting circular // references. nilFound := false cycleFound := false indirects := 0 ve := v for ve.Kind() == reflect.Ptr { if ve.IsNil() { nilFound = true break } indirects++ addr := ve.Pointer() pointerChain = append(pointerChain, addr) if pd, ok := f.pointers[addr]; ok && pd < f.depth { cycleFound = true indirects-- break } f.pointers[addr] = f.depth ve = ve.Elem() if ve.Kind() == reflect.Interface { if ve.IsNil() { nilFound = true break } ve = ve.Elem() } } // Display type or indirection level depending on flags. if showTypes && !f.ignoreNextType { f.fs.Write(openParenBytes) f.fs.Write(bytes.Repeat(asteriskBytes, indirects)) f.fs.Write([]byte(ve.Type().String())) f.fs.Write(closeParenBytes) } else { if nilFound || cycleFound { indirects += strings.Count(ve.Type().String(), "*") } f.fs.Write(openAngleBytes) f.fs.Write([]byte(strings.Repeat("*", indirects))) f.fs.Write(closeAngleBytes) } // Display pointer information depending on flags. if f.fs.Flag('+') && (len(pointerChain) > 0) { f.fs.Write(openParenBytes) for i, addr := range pointerChain { if i > 0 { f.fs.Write(pointerChainBytes) } printHexPtr(f.fs, addr) } f.fs.Write(closeParenBytes) } // Display dereferenced value. switch { case nilFound: f.fs.Write(nilAngleBytes) case cycleFound: f.fs.Write(circularShortBytes) default: f.ignoreNextType = true f.format(ve) } } // format is the main workhorse for providing the Formatter interface. It // uses the passed reflect value to figure out what kind of object we are // dealing with and formats it appropriately. It is a recursive function, // however circular data structures are detected and handled properly. func (f *formatState) format(v reflect.Value) { // Handle invalid reflect values immediately. kind := v.Kind() if kind == reflect.Invalid { f.fs.Write(invalidAngleBytes) return } // Handle pointers specially. if kind == reflect.Ptr { f.formatPtr(v) return } // Print type information unless already handled elsewhere. if !f.ignoreNextType && f.fs.Flag('#') { f.fs.Write(openParenBytes) f.fs.Write([]byte(v.Type().String())) f.fs.Write(closeParenBytes) } f.ignoreNextType = false // Call Stringer/error interfaces if they exist and the handle methods // flag is enabled. if !f.cs.DisableMethods { if (kind != reflect.Invalid) && (kind != reflect.Interface) { if handled := handleMethods(f.cs, f.fs, v); handled { return } } } switch kind { case reflect.Invalid: // Do nothing. We should never get here since invalid has already // been handled above. case reflect.Bool: printBool(f.fs, v.Bool()) case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: printInt(f.fs, v.Int(), 10) case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: printUint(f.fs, v.Uint(), 10) case reflect.Float32: printFloat(f.fs, v.Float(), 32) case reflect.Float64: printFloat(f.fs, v.Float(), 64) case reflect.Complex64: printComplex(f.fs, v.Complex(), 32) case reflect.Complex128: printComplex(f.fs, v.Complex(), 64) case reflect.Slice: if v.IsNil() { f.fs.Write(nilAngleBytes) break } fallthrough case reflect.Array: f.fs.Write(openBracketBytes) f.depth++ if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { f.fs.Write(maxShortBytes) } else { numEntries := v.Len() for i := 0; i < numEntries; i++ { if i > 0 { f.fs.Write(spaceBytes) } f.ignoreNextType = true f.format(f.unpackValue(v.Index(i))) } } f.depth-- f.fs.Write(closeBracketBytes) case reflect.String: f.fs.Write([]byte(v.String())) case reflect.Interface: // The only time we should get here is for nil interfaces due to // unpackValue calls. if v.IsNil() { f.fs.Write(nilAngleBytes) } case reflect.Ptr: // Do nothing. We should never get here since pointers have already // been handled above. case reflect.Map: // nil maps should be indicated as different than empty maps if v.IsNil() { f.fs.Write(nilAngleBytes) break } f.fs.Write(openMapBytes) f.depth++ if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { f.fs.Write(maxShortBytes) } else { keys := v.MapKeys() if f.cs.SortKeys { sortValues(keys, f.cs) } for i, key := range keys { if i > 0 { f.fs.Write(spaceBytes) } f.ignoreNextType = true f.format(f.unpackValue(key)) f.fs.Write(colonBytes) f.ignoreNextType = true f.format(f.unpackValue(v.MapIndex(key))) } } f.depth-- f.fs.Write(closeMapBytes) case reflect.Struct: numFields := v.NumField() f.fs.Write(openBraceBytes) f.depth++ if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { f.fs.Write(maxShortBytes) } else { vt := v.Type() for i := 0; i < numFields; i++ { if i > 0 { f.fs.Write(spaceBytes) } vtf := vt.Field(i) if f.fs.Flag('+') || f.fs.Flag('#') { f.fs.Write([]byte(vtf.Name)) f.fs.Write(colonBytes) } f.format(f.unpackValue(v.Field(i))) } } f.depth-- f.fs.Write(closeBraceBytes) case reflect.Uintptr: printHexPtr(f.fs, uintptr(v.Uint())) case reflect.UnsafePointer, reflect.Chan, reflect.Func: printHexPtr(f.fs, v.Pointer()) // There were not any other types at the time this code was written, but // fall back to letting the default fmt package handle it if any get added. default: format := f.buildDefaultFormat() if v.CanInterface() { fmt.Fprintf(f.fs, format, v.Interface()) } else { fmt.Fprintf(f.fs, format, v.String()) } } } // Format satisfies the fmt.Formatter interface. See NewFormatter for usage // details. func (f *formatState) Format(fs fmt.State, verb rune) { f.fs = fs // Use standard formatting for verbs that are not v. if verb != 'v' { format := f.constructOrigFormat(verb) fmt.Fprintf(fs, format, f.value) return } if f.value == nil { if fs.Flag('#') { fs.Write(interfaceBytes) } fs.Write(nilAngleBytes) return } f.format(reflect.ValueOf(f.value)) } // newFormatter is a helper function to consolidate the logic from the various // public methods which take varying config states. func newFormatter(cs *ConfigState, v interface{}) fmt.Formatter { fs := &formatState{value: v, cs: cs} fs.pointers = make(map[uintptr]int) return fs } /* NewFormatter returns a custom formatter that satisfies the fmt.Formatter interface. As a result, it integrates cleanly with standard fmt package printing functions. The formatter is useful for inline printing of smaller data types similar to the standard %v format specifier. The custom formatter only responds to the %v (most compact), %+v (adds pointer addresses), %#v (adds types), or %#+v (adds types and pointer addresses) verb combinations. Any other verbs such as %x and %q will be sent to the the standard fmt package for formatting. In addition, the custom formatter ignores the width and precision arguments (however they will still work on the format specifiers not handled by the custom formatter). Typically this function shouldn't be called directly. It is much easier to make use of the custom formatter by calling one of the convenience functions such as Printf, Println, or Fprintf. */ func NewFormatter(v interface{}) fmt.Formatter { return newFormatter(&Config, v) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/davecgh/go-spew/spew/bypass.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/davecgh/go-spew/spew/bypass.go
// Copyright (c) 2015-2016 Dave Collins <dave@davec.name> // // Permission to use, copy, modify, and distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // NOTE: Due to the following build constraints, this file will only be compiled // when the code is not running on Google App Engine, compiled by GopherJS, and // "-tags safe" is not added to the go build command line. The "disableunsafe" // tag is deprecated and thus should not be used. // Go versions prior to 1.4 are disabled because they use a different layout // for interfaces which make the implementation of unsafeReflectValue more complex. // +build !js,!appengine,!safe,!disableunsafe,go1.4 package spew import ( "reflect" "unsafe" ) const ( // UnsafeDisabled is a build-time constant which specifies whether or // not access to the unsafe package is available. UnsafeDisabled = false // ptrSize is the size of a pointer on the current arch. ptrSize = unsafe.Sizeof((*byte)(nil)) ) type flag uintptr var ( // flagRO indicates whether the value field of a reflect.Value // is read-only. flagRO flag // flagAddr indicates whether the address of the reflect.Value's // value may be taken. flagAddr flag ) // flagKindMask holds the bits that make up the kind // part of the flags field. In all the supported versions, // it is in the lower 5 bits. const flagKindMask = flag(0x1f) // Different versions of Go have used different // bit layouts for the flags type. This table // records the known combinations. var okFlags = []struct { ro, addr flag }{{ // From Go 1.4 to 1.5 ro: 1 << 5, addr: 1 << 7, }, { // Up to Go tip. ro: 1<<5 | 1<<6, addr: 1 << 8, }} var flagValOffset = func() uintptr { field, ok := reflect.TypeOf(reflect.Value{}).FieldByName("flag") if !ok { panic("reflect.Value has no flag field") } return field.Offset }() // flagField returns a pointer to the flag field of a reflect.Value. func flagField(v *reflect.Value) *flag { return (*flag)(unsafe.Pointer(uintptr(unsafe.Pointer(v)) + flagValOffset)) } // unsafeReflectValue converts the passed reflect.Value into a one that bypasses // the typical safety restrictions preventing access to unaddressable and // unexported data. It works by digging the raw pointer to the underlying // value out of the protected value and generating a new unprotected (unsafe) // reflect.Value to it. // // This allows us to check for implementations of the Stringer and error // interfaces to be used for pretty printing ordinarily unaddressable and // inaccessible values such as unexported struct fields. func unsafeReflectValue(v reflect.Value) reflect.Value { if !v.IsValid() || (v.CanInterface() && v.CanAddr()) { return v } flagFieldPtr := flagField(&v) *flagFieldPtr &^= flagRO *flagFieldPtr |= flagAddr return v } // Sanity checks against future reflect package changes // to the type or semantics of the Value.flag field. func init() { field, ok := reflect.TypeOf(reflect.Value{}).FieldByName("flag") if !ok { panic("reflect.Value has no flag field") } if field.Type.Kind() != reflect.TypeOf(flag(0)).Kind() { panic("reflect.Value flag field has changed kind") } type t0 int var t struct { A t0 // t0 will have flagEmbedRO set. t0 // a will have flagStickyRO set a t0 } vA := reflect.ValueOf(t).FieldByName("A") va := reflect.ValueOf(t).FieldByName("a") vt0 := reflect.ValueOf(t).FieldByName("t0") // Infer flagRO from the difference between the flags // for the (otherwise identical) fields in t. flagPublic := *flagField(&vA) flagWithRO := *flagField(&va) | *flagField(&vt0) flagRO = flagPublic ^ flagWithRO // Infer flagAddr from the difference between a value // taken from a pointer and not. vPtrA := reflect.ValueOf(&t).Elem().FieldByName("A") flagNoPtr := *flagField(&vA) flagPtr := *flagField(&vPtrA) flagAddr = flagNoPtr ^ flagPtr // Check that the inferred flags tally with one of the known versions. for _, f := range okFlags { if flagRO == f.ro && flagAddr == f.addr { return } } panic("reflect.Value read-only flag has changed semantics") }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go
// Copyright (c) 2015-2016 Dave Collins <dave@davec.name> // // Permission to use, copy, modify, and distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // NOTE: Due to the following build constraints, this file will only be compiled // when the code is running on Google App Engine, compiled by GopherJS, or // "-tags safe" is added to the go build command line. The "disableunsafe" // tag is deprecated and thus should not be used. // +build js appengine safe disableunsafe !go1.4 package spew import "reflect" const ( // UnsafeDisabled is a build-time constant which specifies whether or // not access to the unsafe package is available. UnsafeDisabled = true ) // unsafeReflectValue typically converts the passed reflect.Value into a one // that bypasses the typical safety restrictions preventing access to // unaddressable and unexported data. However, doing this relies on access to // the unsafe package. This is a stub version which simply returns the passed // reflect.Value when the unsafe package is not available. func unsafeReflectValue(v reflect.Value) reflect.Value { return v }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/davecgh/go-spew/spew/doc.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/davecgh/go-spew/spew/doc.go
/* * Copyright (c) 2013-2016 Dave Collins <dave@davec.name> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* Package spew implements a deep pretty printer for Go data structures to aid in debugging. A quick overview of the additional features spew provides over the built-in printing facilities for Go data types are as follows: * Pointers are dereferenced and followed * Circular data structures are detected and handled properly * Custom Stringer/error interfaces are optionally invoked, including on unexported types * Custom types which only implement the Stringer/error interfaces via a pointer receiver are optionally invoked when passing non-pointer variables * Byte arrays and slices are dumped like the hexdump -C command which includes offsets, byte values in hex, and ASCII output (only when using Dump style) There are two different approaches spew allows for dumping Go data structures: * Dump style which prints with newlines, customizable indentation, and additional debug information such as types and all pointer addresses used to indirect to the final value * A custom Formatter interface that integrates cleanly with the standard fmt package and replaces %v, %+v, %#v, and %#+v to provide inline printing similar to the default %v while providing the additional functionality outlined above and passing unsupported format verbs such as %x and %q along to fmt Quick Start This section demonstrates how to quickly get started with spew. See the sections below for further details on formatting and configuration options. To dump a variable with full newlines, indentation, type, and pointer information use Dump, Fdump, or Sdump: spew.Dump(myVar1, myVar2, ...) spew.Fdump(someWriter, myVar1, myVar2, ...) str := spew.Sdump(myVar1, myVar2, ...) Alternatively, if you would prefer to use format strings with a compacted inline printing style, use the convenience wrappers Printf, Fprintf, etc with %v (most compact), %+v (adds pointer addresses), %#v (adds types), or %#+v (adds types and pointer addresses): spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2) spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) spew.Fprintf(someWriter, "myVar1: %v -- myVar2: %+v", myVar1, myVar2) spew.Fprintf(someWriter, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) Configuration Options Configuration of spew is handled by fields in the ConfigState type. For convenience, all of the top-level functions use a global state available via the spew.Config global. It is also possible to create a ConfigState instance that provides methods equivalent to the top-level functions. This allows concurrent configuration options. See the ConfigState documentation for more details. The following configuration options are available: * Indent String to use for each indentation level for Dump functions. It is a single space by default. A popular alternative is "\t". * MaxDepth Maximum number of levels to descend into nested data structures. There is no limit by default. * DisableMethods Disables invocation of error and Stringer interface methods. Method invocation is enabled by default. * DisablePointerMethods Disables invocation of error and Stringer interface methods on types which only accept pointer receivers from non-pointer variables. Pointer method invocation is enabled by default. * DisablePointerAddresses DisablePointerAddresses specifies whether to disable the printing of pointer addresses. This is useful when diffing data structures in tests. * DisableCapacities DisableCapacities specifies whether to disable the printing of capacities for arrays, slices, maps and channels. This is useful when diffing data structures in tests. * ContinueOnMethod Enables recursion into types after invoking error and Stringer interface methods. Recursion after method invocation is disabled by default. * SortKeys Specifies map keys should be sorted before being printed. Use this to have a more deterministic, diffable output. Note that only native types (bool, int, uint, floats, uintptr and string) and types which implement error or Stringer interfaces are supported with other types sorted according to the reflect.Value.String() output which guarantees display stability. Natural map order is used by default. * SpewKeys Specifies that, as a last resort attempt, map keys should be spewed to strings and sorted by those strings. This is only considered if SortKeys is true. Dump Usage Simply call spew.Dump with a list of variables you want to dump: spew.Dump(myVar1, myVar2, ...) You may also call spew.Fdump if you would prefer to output to an arbitrary io.Writer. For example, to dump to standard error: spew.Fdump(os.Stderr, myVar1, myVar2, ...) A third option is to call spew.Sdump to get the formatted output as a string: str := spew.Sdump(myVar1, myVar2, ...) Sample Dump Output See the Dump example for details on the setup of the types and variables being shown here. (main.Foo) { unexportedField: (*main.Bar)(0xf84002e210)({ flag: (main.Flag) flagTwo, data: (uintptr) <nil> }), ExportedField: (map[interface {}]interface {}) (len=1) { (string) (len=3) "one": (bool) true } } Byte (and uint8) arrays and slices are displayed uniquely like the hexdump -C command as shown. ([]uint8) (len=32 cap=32) { 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 |............... | 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 |!"#$%&'()*+,-./0| 00000020 31 32 |12| } Custom Formatter Spew provides a custom formatter that implements the fmt.Formatter interface so that it integrates cleanly with standard fmt package printing functions. The formatter is useful for inline printing of smaller data types similar to the standard %v format specifier. The custom formatter only responds to the %v (most compact), %+v (adds pointer addresses), %#v (adds types), or %#+v (adds types and pointer addresses) verb combinations. Any other verbs such as %x and %q will be sent to the the standard fmt package for formatting. In addition, the custom formatter ignores the width and precision arguments (however they will still work on the format specifiers not handled by the custom formatter). Custom Formatter Usage The simplest way to make use of the spew custom formatter is to call one of the convenience functions such as spew.Printf, spew.Println, or spew.Printf. The functions have syntax you are most likely already familiar with: spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2) spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) spew.Println(myVar, myVar2) spew.Fprintf(os.Stderr, "myVar1: %v -- myVar2: %+v", myVar1, myVar2) spew.Fprintf(os.Stderr, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) See the Index for the full list convenience functions. Sample Formatter Output Double pointer to a uint8: %v: <**>5 %+v: <**>(0xf8400420d0->0xf8400420c8)5 %#v: (**uint8)5 %#+v: (**uint8)(0xf8400420d0->0xf8400420c8)5 Pointer to circular struct with a uint8 field and a pointer to itself: %v: <*>{1 <*><shown>} %+v: <*>(0xf84003e260){ui8:1 c:<*>(0xf84003e260)<shown>} %#v: (*main.circular){ui8:(uint8)1 c:(*main.circular)<shown>} %#+v: (*main.circular)(0xf84003e260){ui8:(uint8)1 c:(*main.circular)(0xf84003e260)<shown>} See the Printf example for details on the setup of variables being shown here. Errors Since it is possible for custom Stringer/error interfaces to panic, spew detects them and handles them internally by printing the panic information inline with the output. Since spew is intended to provide deep pretty printing capabilities on structures, it intentionally does not return any errors. */ package spew
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/davecgh/go-spew/spew/dump.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/davecgh/go-spew/spew/dump.go
/* * Copyright (c) 2013-2016 Dave Collins <dave@davec.name> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package spew import ( "bytes" "encoding/hex" "fmt" "io" "os" "reflect" "regexp" "strconv" "strings" ) var ( // uint8Type is a reflect.Type representing a uint8. It is used to // convert cgo types to uint8 slices for hexdumping. uint8Type = reflect.TypeOf(uint8(0)) // cCharRE is a regular expression that matches a cgo char. // It is used to detect character arrays to hexdump them. cCharRE = regexp.MustCompile(`^.*\._Ctype_char$`) // cUnsignedCharRE is a regular expression that matches a cgo unsigned // char. It is used to detect unsigned character arrays to hexdump // them. cUnsignedCharRE = regexp.MustCompile(`^.*\._Ctype_unsignedchar$`) // cUint8tCharRE is a regular expression that matches a cgo uint8_t. // It is used to detect uint8_t arrays to hexdump them. cUint8tCharRE = regexp.MustCompile(`^.*\._Ctype_uint8_t$`) ) // dumpState contains information about the state of a dump operation. type dumpState struct { w io.Writer depth int pointers map[uintptr]int ignoreNextType bool ignoreNextIndent bool cs *ConfigState } // indent performs indentation according to the depth level and cs.Indent // option. func (d *dumpState) indent() { if d.ignoreNextIndent { d.ignoreNextIndent = false return } d.w.Write(bytes.Repeat([]byte(d.cs.Indent), d.depth)) } // unpackValue returns values inside of non-nil interfaces when possible. // This is useful for data types like structs, arrays, slices, and maps which // can contain varying types packed inside an interface. func (d *dumpState) unpackValue(v reflect.Value) reflect.Value { if v.Kind() == reflect.Interface && !v.IsNil() { v = v.Elem() } return v } // dumpPtr handles formatting of pointers by indirecting them as necessary. func (d *dumpState) dumpPtr(v reflect.Value) { // Remove pointers at or below the current depth from map used to detect // circular refs. for k, depth := range d.pointers { if depth >= d.depth { delete(d.pointers, k) } } // Keep list of all dereferenced pointers to show later. pointerChain := make([]uintptr, 0) // Figure out how many levels of indirection there are by dereferencing // pointers and unpacking interfaces down the chain while detecting circular // references. nilFound := false cycleFound := false indirects := 0 ve := v for ve.Kind() == reflect.Ptr { if ve.IsNil() { nilFound = true break } indirects++ addr := ve.Pointer() pointerChain = append(pointerChain, addr) if pd, ok := d.pointers[addr]; ok && pd < d.depth { cycleFound = true indirects-- break } d.pointers[addr] = d.depth ve = ve.Elem() if ve.Kind() == reflect.Interface { if ve.IsNil() { nilFound = true break } ve = ve.Elem() } } // Display type information. d.w.Write(openParenBytes) d.w.Write(bytes.Repeat(asteriskBytes, indirects)) d.w.Write([]byte(ve.Type().String())) d.w.Write(closeParenBytes) // Display pointer information. if !d.cs.DisablePointerAddresses && len(pointerChain) > 0 { d.w.Write(openParenBytes) for i, addr := range pointerChain { if i > 0 { d.w.Write(pointerChainBytes) } printHexPtr(d.w, addr) } d.w.Write(closeParenBytes) } // Display dereferenced value. d.w.Write(openParenBytes) switch { case nilFound: d.w.Write(nilAngleBytes) case cycleFound: d.w.Write(circularBytes) default: d.ignoreNextType = true d.dump(ve) } d.w.Write(closeParenBytes) } // dumpSlice handles formatting of arrays and slices. Byte (uint8 under // reflection) arrays and slices are dumped in hexdump -C fashion. func (d *dumpState) dumpSlice(v reflect.Value) { // Determine whether this type should be hex dumped or not. Also, // for types which should be hexdumped, try to use the underlying data // first, then fall back to trying to convert them to a uint8 slice. var buf []uint8 doConvert := false doHexDump := false numEntries := v.Len() if numEntries > 0 { vt := v.Index(0).Type() vts := vt.String() switch { // C types that need to be converted. case cCharRE.MatchString(vts): fallthrough case cUnsignedCharRE.MatchString(vts): fallthrough case cUint8tCharRE.MatchString(vts): doConvert = true // Try to use existing uint8 slices and fall back to converting // and copying if that fails. case vt.Kind() == reflect.Uint8: // We need an addressable interface to convert the type // to a byte slice. However, the reflect package won't // give us an interface on certain things like // unexported struct fields in order to enforce // visibility rules. We use unsafe, when available, to // bypass these restrictions since this package does not // mutate the values. vs := v if !vs.CanInterface() || !vs.CanAddr() { vs = unsafeReflectValue(vs) } if !UnsafeDisabled { vs = vs.Slice(0, numEntries) // Use the existing uint8 slice if it can be // type asserted. iface := vs.Interface() if slice, ok := iface.([]uint8); ok { buf = slice doHexDump = true break } } // The underlying data needs to be converted if it can't // be type asserted to a uint8 slice. doConvert = true } // Copy and convert the underlying type if needed. if doConvert && vt.ConvertibleTo(uint8Type) { // Convert and copy each element into a uint8 byte // slice. buf = make([]uint8, numEntries) for i := 0; i < numEntries; i++ { vv := v.Index(i) buf[i] = uint8(vv.Convert(uint8Type).Uint()) } doHexDump = true } } // Hexdump the entire slice as needed. if doHexDump { indent := strings.Repeat(d.cs.Indent, d.depth) str := indent + hex.Dump(buf) str = strings.Replace(str, "\n", "\n"+indent, -1) str = strings.TrimRight(str, d.cs.Indent) d.w.Write([]byte(str)) return } // Recursively call dump for each item. for i := 0; i < numEntries; i++ { d.dump(d.unpackValue(v.Index(i))) if i < (numEntries - 1) { d.w.Write(commaNewlineBytes) } else { d.w.Write(newlineBytes) } } } // dump is the main workhorse for dumping a value. It uses the passed reflect // value to figure out what kind of object we are dealing with and formats it // appropriately. It is a recursive function, however circular data structures // are detected and handled properly. func (d *dumpState) dump(v reflect.Value) { // Handle invalid reflect values immediately. kind := v.Kind() if kind == reflect.Invalid { d.w.Write(invalidAngleBytes) return } // Handle pointers specially. if kind == reflect.Ptr { d.indent() d.dumpPtr(v) return } // Print type information unless already handled elsewhere. if !d.ignoreNextType { d.indent() d.w.Write(openParenBytes) d.w.Write([]byte(v.Type().String())) d.w.Write(closeParenBytes) d.w.Write(spaceBytes) } d.ignoreNextType = false // Display length and capacity if the built-in len and cap functions // work with the value's kind and the len/cap itself is non-zero. valueLen, valueCap := 0, 0 switch v.Kind() { case reflect.Array, reflect.Slice, reflect.Chan: valueLen, valueCap = v.Len(), v.Cap() case reflect.Map, reflect.String: valueLen = v.Len() } if valueLen != 0 || !d.cs.DisableCapacities && valueCap != 0 { d.w.Write(openParenBytes) if valueLen != 0 { d.w.Write(lenEqualsBytes) printInt(d.w, int64(valueLen), 10) } if !d.cs.DisableCapacities && valueCap != 0 { if valueLen != 0 { d.w.Write(spaceBytes) } d.w.Write(capEqualsBytes) printInt(d.w, int64(valueCap), 10) } d.w.Write(closeParenBytes) d.w.Write(spaceBytes) } // Call Stringer/error interfaces if they exist and the handle methods flag // is enabled if !d.cs.DisableMethods { if (kind != reflect.Invalid) && (kind != reflect.Interface) { if handled := handleMethods(d.cs, d.w, v); handled { return } } } switch kind { case reflect.Invalid: // Do nothing. We should never get here since invalid has already // been handled above. case reflect.Bool: printBool(d.w, v.Bool()) case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: printInt(d.w, v.Int(), 10) case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: printUint(d.w, v.Uint(), 10) case reflect.Float32: printFloat(d.w, v.Float(), 32) case reflect.Float64: printFloat(d.w, v.Float(), 64) case reflect.Complex64: printComplex(d.w, v.Complex(), 32) case reflect.Complex128: printComplex(d.w, v.Complex(), 64) case reflect.Slice: if v.IsNil() { d.w.Write(nilAngleBytes) break } fallthrough case reflect.Array: d.w.Write(openBraceNewlineBytes) d.depth++ if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { d.indent() d.w.Write(maxNewlineBytes) } else { d.dumpSlice(v) } d.depth-- d.indent() d.w.Write(closeBraceBytes) case reflect.String: d.w.Write([]byte(strconv.Quote(v.String()))) case reflect.Interface: // The only time we should get here is for nil interfaces due to // unpackValue calls. if v.IsNil() { d.w.Write(nilAngleBytes) } case reflect.Ptr: // Do nothing. We should never get here since pointers have already // been handled above. case reflect.Map: // nil maps should be indicated as different than empty maps if v.IsNil() { d.w.Write(nilAngleBytes) break } d.w.Write(openBraceNewlineBytes) d.depth++ if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { d.indent() d.w.Write(maxNewlineBytes) } else { numEntries := v.Len() keys := v.MapKeys() if d.cs.SortKeys { sortValues(keys, d.cs) } for i, key := range keys { d.dump(d.unpackValue(key)) d.w.Write(colonSpaceBytes) d.ignoreNextIndent = true d.dump(d.unpackValue(v.MapIndex(key))) if i < (numEntries - 1) { d.w.Write(commaNewlineBytes) } else { d.w.Write(newlineBytes) } } } d.depth-- d.indent() d.w.Write(closeBraceBytes) case reflect.Struct: d.w.Write(openBraceNewlineBytes) d.depth++ if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { d.indent() d.w.Write(maxNewlineBytes) } else { vt := v.Type() numFields := v.NumField() for i := 0; i < numFields; i++ { d.indent() vtf := vt.Field(i) d.w.Write([]byte(vtf.Name)) d.w.Write(colonSpaceBytes) d.ignoreNextIndent = true d.dump(d.unpackValue(v.Field(i))) if i < (numFields - 1) { d.w.Write(commaNewlineBytes) } else { d.w.Write(newlineBytes) } } } d.depth-- d.indent() d.w.Write(closeBraceBytes) case reflect.Uintptr: printHexPtr(d.w, uintptr(v.Uint())) case reflect.UnsafePointer, reflect.Chan, reflect.Func: printHexPtr(d.w, v.Pointer()) // There were not any other types at the time this code was written, but // fall back to letting the default fmt package handle it in case any new // types are added. default: if v.CanInterface() { fmt.Fprintf(d.w, "%v", v.Interface()) } else { fmt.Fprintf(d.w, "%v", v.String()) } } } // fdump is a helper function to consolidate the logic from the various public // methods which take varying writers and config states. func fdump(cs *ConfigState, w io.Writer, a ...interface{}) { for _, arg := range a { if arg == nil { w.Write(interfaceBytes) w.Write(spaceBytes) w.Write(nilAngleBytes) w.Write(newlineBytes) continue } d := dumpState{w: w, cs: cs} d.pointers = make(map[uintptr]int) d.dump(reflect.ValueOf(arg)) d.w.Write(newlineBytes) } } // Fdump formats and displays the passed arguments to io.Writer w. It formats // exactly the same as Dump. func Fdump(w io.Writer, a ...interface{}) { fdump(&Config, w, a...) } // Sdump returns a string with the passed arguments formatted exactly the same // as Dump. func Sdump(a ...interface{}) string { var buf bytes.Buffer fdump(&Config, &buf, a...) return buf.String() } /* Dump displays the passed parameters to standard out with newlines, customizable indentation, and additional debug information such as complete types and all pointer addresses used to indirect to the final value. It provides the following features over the built-in printing facilities provided by the fmt package: * Pointers are dereferenced and followed * Circular data structures are detected and handled properly * Custom Stringer/error interfaces are optionally invoked, including on unexported types * Custom types which only implement the Stringer/error interfaces via a pointer receiver are optionally invoked when passing non-pointer variables * Byte arrays and slices are dumped like the hexdump -C command which includes offsets, byte values in hex, and ASCII output The configuration options are controlled by an exported package global, spew.Config. See ConfigState for options documentation. See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to get the formatted result as a string. */ func Dump(a ...interface{}) { fdump(&Config, os.Stdout, a...) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/davecgh/go-spew/spew/spew.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/davecgh/go-spew/spew/spew.go
/* * Copyright (c) 2013-2016 Dave Collins <dave@davec.name> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package spew import ( "fmt" "io" ) // Errorf is a wrapper for fmt.Errorf that treats each argument as if it were // passed with a default Formatter interface returned by NewFormatter. It // returns the formatted string as a value that satisfies error. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Errorf(format, spew.NewFormatter(a), spew.NewFormatter(b)) func Errorf(format string, a ...interface{}) (err error) { return fmt.Errorf(format, convertArgs(a)...) } // Fprint is a wrapper for fmt.Fprint that treats each argument as if it were // passed with a default Formatter interface returned by NewFormatter. It // returns the number of bytes written and any write error encountered. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Fprint(w, spew.NewFormatter(a), spew.NewFormatter(b)) func Fprint(w io.Writer, a ...interface{}) (n int, err error) { return fmt.Fprint(w, convertArgs(a)...) } // Fprintf is a wrapper for fmt.Fprintf that treats each argument as if it were // passed with a default Formatter interface returned by NewFormatter. It // returns the number of bytes written and any write error encountered. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Fprintf(w, format, spew.NewFormatter(a), spew.NewFormatter(b)) func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { return fmt.Fprintf(w, format, convertArgs(a)...) } // Fprintln is a wrapper for fmt.Fprintln that treats each argument as if it // passed with a default Formatter interface returned by NewFormatter. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Fprintln(w, spew.NewFormatter(a), spew.NewFormatter(b)) func Fprintln(w io.Writer, a ...interface{}) (n int, err error) { return fmt.Fprintln(w, convertArgs(a)...) } // Print is a wrapper for fmt.Print that treats each argument as if it were // passed with a default Formatter interface returned by NewFormatter. It // returns the number of bytes written and any write error encountered. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Print(spew.NewFormatter(a), spew.NewFormatter(b)) func Print(a ...interface{}) (n int, err error) { return fmt.Print(convertArgs(a)...) } // Printf is a wrapper for fmt.Printf that treats each argument as if it were // passed with a default Formatter interface returned by NewFormatter. It // returns the number of bytes written and any write error encountered. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Printf(format, spew.NewFormatter(a), spew.NewFormatter(b)) func Printf(format string, a ...interface{}) (n int, err error) { return fmt.Printf(format, convertArgs(a)...) } // Println is a wrapper for fmt.Println that treats each argument as if it were // passed with a default Formatter interface returned by NewFormatter. It // returns the number of bytes written and any write error encountered. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Println(spew.NewFormatter(a), spew.NewFormatter(b)) func Println(a ...interface{}) (n int, err error) { return fmt.Println(convertArgs(a)...) } // Sprint is a wrapper for fmt.Sprint that treats each argument as if it were // passed with a default Formatter interface returned by NewFormatter. It // returns the resulting string. See NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Sprint(spew.NewFormatter(a), spew.NewFormatter(b)) func Sprint(a ...interface{}) string { return fmt.Sprint(convertArgs(a)...) } // Sprintf is a wrapper for fmt.Sprintf that treats each argument as if it were // passed with a default Formatter interface returned by NewFormatter. It // returns the resulting string. See NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Sprintf(format, spew.NewFormatter(a), spew.NewFormatter(b)) func Sprintf(format string, a ...interface{}) string { return fmt.Sprintf(format, convertArgs(a)...) } // Sprintln is a wrapper for fmt.Sprintln that treats each argument as if it // were passed with a default Formatter interface returned by NewFormatter. It // returns the resulting string. See NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Sprintln(spew.NewFormatter(a), spew.NewFormatter(b)) func Sprintln(a ...interface{}) string { return fmt.Sprintln(convertArgs(a)...) } // convertArgs accepts a slice of arguments and returns a slice of the same // length with each argument converted to a default spew Formatter interface. func convertArgs(args []interface{}) (formatters []interface{}) { formatters = make([]interface{}, len(args)) for index, arg := range args { formatters[index] = NewFormatter(arg) } return formatters }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/davecgh/go-spew/spew/common.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/davecgh/go-spew/spew/common.go
/* * Copyright (c) 2013-2016 Dave Collins <dave@davec.name> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package spew import ( "bytes" "fmt" "io" "reflect" "sort" "strconv" ) // Some constants in the form of bytes to avoid string overhead. This mirrors // the technique used in the fmt package. var ( panicBytes = []byte("(PANIC=") plusBytes = []byte("+") iBytes = []byte("i") trueBytes = []byte("true") falseBytes = []byte("false") interfaceBytes = []byte("(interface {})") commaNewlineBytes = []byte(",\n") newlineBytes = []byte("\n") openBraceBytes = []byte("{") openBraceNewlineBytes = []byte("{\n") closeBraceBytes = []byte("}") asteriskBytes = []byte("*") colonBytes = []byte(":") colonSpaceBytes = []byte(": ") openParenBytes = []byte("(") closeParenBytes = []byte(")") spaceBytes = []byte(" ") pointerChainBytes = []byte("->") nilAngleBytes = []byte("<nil>") maxNewlineBytes = []byte("<max depth reached>\n") maxShortBytes = []byte("<max>") circularBytes = []byte("<already shown>") circularShortBytes = []byte("<shown>") invalidAngleBytes = []byte("<invalid>") openBracketBytes = []byte("[") closeBracketBytes = []byte("]") percentBytes = []byte("%") precisionBytes = []byte(".") openAngleBytes = []byte("<") closeAngleBytes = []byte(">") openMapBytes = []byte("map[") closeMapBytes = []byte("]") lenEqualsBytes = []byte("len=") capEqualsBytes = []byte("cap=") ) // hexDigits is used to map a decimal value to a hex digit. var hexDigits = "0123456789abcdef" // catchPanic handles any panics that might occur during the handleMethods // calls. func catchPanic(w io.Writer, v reflect.Value) { if err := recover(); err != nil { w.Write(panicBytes) fmt.Fprintf(w, "%v", err) w.Write(closeParenBytes) } } // handleMethods attempts to call the Error and String methods on the underlying // type the passed reflect.Value represents and outputes the result to Writer w. // // It handles panics in any called methods by catching and displaying the error // as the formatted value. func handleMethods(cs *ConfigState, w io.Writer, v reflect.Value) (handled bool) { // We need an interface to check if the type implements the error or // Stringer interface. However, the reflect package won't give us an // interface on certain things like unexported struct fields in order // to enforce visibility rules. We use unsafe, when it's available, // to bypass these restrictions since this package does not mutate the // values. if !v.CanInterface() { if UnsafeDisabled { return false } v = unsafeReflectValue(v) } // Choose whether or not to do error and Stringer interface lookups against // the base type or a pointer to the base type depending on settings. // Technically calling one of these methods with a pointer receiver can // mutate the value, however, types which choose to satisify an error or // Stringer interface with a pointer receiver should not be mutating their // state inside these interface methods. if !cs.DisablePointerMethods && !UnsafeDisabled && !v.CanAddr() { v = unsafeReflectValue(v) } if v.CanAddr() { v = v.Addr() } // Is it an error or Stringer? switch iface := v.Interface().(type) { case error: defer catchPanic(w, v) if cs.ContinueOnMethod { w.Write(openParenBytes) w.Write([]byte(iface.Error())) w.Write(closeParenBytes) w.Write(spaceBytes) return false } w.Write([]byte(iface.Error())) return true case fmt.Stringer: defer catchPanic(w, v) if cs.ContinueOnMethod { w.Write(openParenBytes) w.Write([]byte(iface.String())) w.Write(closeParenBytes) w.Write(spaceBytes) return false } w.Write([]byte(iface.String())) return true } return false } // printBool outputs a boolean value as true or false to Writer w. func printBool(w io.Writer, val bool) { if val { w.Write(trueBytes) } else { w.Write(falseBytes) } } // printInt outputs a signed integer value to Writer w. func printInt(w io.Writer, val int64, base int) { w.Write([]byte(strconv.FormatInt(val, base))) } // printUint outputs an unsigned integer value to Writer w. func printUint(w io.Writer, val uint64, base int) { w.Write([]byte(strconv.FormatUint(val, base))) } // printFloat outputs a floating point value using the specified precision, // which is expected to be 32 or 64bit, to Writer w. func printFloat(w io.Writer, val float64, precision int) { w.Write([]byte(strconv.FormatFloat(val, 'g', -1, precision))) } // printComplex outputs a complex value using the specified float precision // for the real and imaginary parts to Writer w. func printComplex(w io.Writer, c complex128, floatPrecision int) { r := real(c) w.Write(openParenBytes) w.Write([]byte(strconv.FormatFloat(r, 'g', -1, floatPrecision))) i := imag(c) if i >= 0 { w.Write(plusBytes) } w.Write([]byte(strconv.FormatFloat(i, 'g', -1, floatPrecision))) w.Write(iBytes) w.Write(closeParenBytes) } // printHexPtr outputs a uintptr formatted as hexadecimal with a leading '0x' // prefix to Writer w. func printHexPtr(w io.Writer, p uintptr) { // Null pointer. num := uint64(p) if num == 0 { w.Write(nilAngleBytes) return } // Max uint64 is 16 bytes in hex + 2 bytes for '0x' prefix buf := make([]byte, 18) // It's simpler to construct the hex string right to left. base := uint64(16) i := len(buf) - 1 for num >= base { buf[i] = hexDigits[num%base] num /= base i-- } buf[i] = hexDigits[num] // Add '0x' prefix. i-- buf[i] = 'x' i-- buf[i] = '0' // Strip unused leading bytes. buf = buf[i:] w.Write(buf) } // valuesSorter implements sort.Interface to allow a slice of reflect.Value // elements to be sorted. type valuesSorter struct { values []reflect.Value strings []string // either nil or same len and values cs *ConfigState } // newValuesSorter initializes a valuesSorter instance, which holds a set of // surrogate keys on which the data should be sorted. It uses flags in // ConfigState to decide if and how to populate those surrogate keys. func newValuesSorter(values []reflect.Value, cs *ConfigState) sort.Interface { vs := &valuesSorter{values: values, cs: cs} if canSortSimply(vs.values[0].Kind()) { return vs } if !cs.DisableMethods { vs.strings = make([]string, len(values)) for i := range vs.values { b := bytes.Buffer{} if !handleMethods(cs, &b, vs.values[i]) { vs.strings = nil break } vs.strings[i] = b.String() } } if vs.strings == nil && cs.SpewKeys { vs.strings = make([]string, len(values)) for i := range vs.values { vs.strings[i] = Sprintf("%#v", vs.values[i].Interface()) } } return vs } // canSortSimply tests whether a reflect.Kind is a primitive that can be sorted // directly, or whether it should be considered for sorting by surrogate keys // (if the ConfigState allows it). func canSortSimply(kind reflect.Kind) bool { // This switch parallels valueSortLess, except for the default case. switch kind { case reflect.Bool: return true case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: return true case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: return true case reflect.Float32, reflect.Float64: return true case reflect.String: return true case reflect.Uintptr: return true case reflect.Array: return true } return false } // Len returns the number of values in the slice. It is part of the // sort.Interface implementation. func (s *valuesSorter) Len() int { return len(s.values) } // Swap swaps the values at the passed indices. It is part of the // sort.Interface implementation. func (s *valuesSorter) Swap(i, j int) { s.values[i], s.values[j] = s.values[j], s.values[i] if s.strings != nil { s.strings[i], s.strings[j] = s.strings[j], s.strings[i] } } // valueSortLess returns whether the first value should sort before the second // value. It is used by valueSorter.Less as part of the sort.Interface // implementation. func valueSortLess(a, b reflect.Value) bool { switch a.Kind() { case reflect.Bool: return !a.Bool() && b.Bool() case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: return a.Int() < b.Int() case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: return a.Uint() < b.Uint() case reflect.Float32, reflect.Float64: return a.Float() < b.Float() case reflect.String: return a.String() < b.String() case reflect.Uintptr: return a.Uint() < b.Uint() case reflect.Array: // Compare the contents of both arrays. l := a.Len() for i := 0; i < l; i++ { av := a.Index(i) bv := b.Index(i) if av.Interface() == bv.Interface() { continue } return valueSortLess(av, bv) } } return a.String() < b.String() } // Less returns whether the value at index i should sort before the // value at index j. It is part of the sort.Interface implementation. func (s *valuesSorter) Less(i, j int) bool { if s.strings == nil { return valueSortLess(s.values[i], s.values[j]) } return s.strings[i] < s.strings[j] } // sortValues is a sort function that handles both native types and any type that // can be converted to error or Stringer. Other inputs are sorted according to // their Value.String() value to ensure display stability. func sortValues(values []reflect.Value, cs *ConfigState) { if len(values) == 0 { return } sort.Sort(newValuesSorter(values, cs)) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/mitchellh/copystructure/copystructure.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/mitchellh/copystructure/copystructure.go
package copystructure import ( "errors" "reflect" "sync" "github.com/mitchellh/reflectwalk" ) const tagKey = "copy" // Copy returns a deep copy of v. // // Copy is unable to copy unexported fields in a struct (lowercase field names). // Unexported fields can't be reflected by the Go runtime and therefore // copystructure can't perform any data copies. // // For structs, copy behavior can be controlled with struct tags. For example: // // struct { // Name string // Data *bytes.Buffer `copy:"shallow"` // } // // The available tag values are: // // * "ignore" - The field will be ignored, effectively resulting in it being // assigned the zero value in the copy. // // * "shallow" - The field will be be shallow copied. This means that references // values such as pointers, maps, slices, etc. will be directly assigned // versus deep copied. // func Copy(v interface{}) (interface{}, error) { return Config{}.Copy(v) } // CopierFunc is a function that knows how to deep copy a specific type. // Register these globally with the Copiers variable. type CopierFunc func(interface{}) (interface{}, error) // Copiers is a map of types that behave specially when they are copied. // If a type is found in this map while deep copying, this function // will be called to copy it instead of attempting to copy all fields. // // The key should be the type, obtained using: reflect.TypeOf(value with type). // // It is unsafe to write to this map after Copies have started. If you // are writing to this map while also copying, wrap all modifications to // this map as well as to Copy in a mutex. var Copiers map[reflect.Type]CopierFunc = make(map[reflect.Type]CopierFunc) // ShallowCopiers is a map of pointer types that behave specially // when they are copied. If a type is found in this map while deep // copying, the pointer value will be shallow copied and not walked // into. // // The key should be the type, obtained using: reflect.TypeOf(value // with type). // // It is unsafe to write to this map after Copies have started. If you // are writing to this map while also copying, wrap all modifications to // this map as well as to Copy in a mutex. var ShallowCopiers map[reflect.Type]struct{} = make(map[reflect.Type]struct{}) // Must is a helper that wraps a call to a function returning // (interface{}, error) and panics if the error is non-nil. It is intended // for use in variable initializations and should only be used when a copy // error should be a crashing case. func Must(v interface{}, err error) interface{} { if err != nil { panic("copy error: " + err.Error()) } return v } var errPointerRequired = errors.New("Copy argument must be a pointer when Lock is true") type Config struct { // Lock any types that are a sync.Locker and are not a mutex while copying. // If there is an RLocker method, use that to get the sync.Locker. Lock bool // Copiers is a map of types associated with a CopierFunc. Use the global // Copiers map if this is nil. Copiers map[reflect.Type]CopierFunc // ShallowCopiers is a map of pointer types that when they are // shallow copied no matter where they are encountered. Use the // global ShallowCopiers if this is nil. ShallowCopiers map[reflect.Type]struct{} } func (c Config) Copy(v interface{}) (interface{}, error) { if c.Lock && reflect.ValueOf(v).Kind() != reflect.Ptr { return nil, errPointerRequired } w := new(walker) if c.Lock { w.useLocks = true } if c.Copiers == nil { c.Copiers = Copiers } w.copiers = c.Copiers if c.ShallowCopiers == nil { c.ShallowCopiers = ShallowCopiers } w.shallowCopiers = c.ShallowCopiers err := reflectwalk.Walk(v, w) if err != nil { return nil, err } // Get the result. If the result is nil, then we want to turn it // into a typed nil if we can. result := w.Result if result == nil { val := reflect.ValueOf(v) result = reflect.Indirect(reflect.New(val.Type())).Interface() } return result, nil } // Return the key used to index interfaces types we've seen. Store the number // of pointers in the upper 32bits, and the depth in the lower 32bits. This is // easy to calculate, easy to match a key with our current depth, and we don't // need to deal with initializing and cleaning up nested maps or slices. func ifaceKey(pointers, depth int) uint64 { return uint64(pointers)<<32 | uint64(depth) } type walker struct { Result interface{} copiers map[reflect.Type]CopierFunc shallowCopiers map[reflect.Type]struct{} depth int ignoreDepth int vals []reflect.Value cs []reflect.Value // This stores the number of pointers we've walked over, indexed by depth. ps []int // If an interface is indirected by a pointer, we need to know the type of // interface to create when creating the new value. Store the interface // types here, indexed by both the walk depth and the number of pointers // already seen at that depth. Use ifaceKey to calculate the proper uint64 // value. ifaceTypes map[uint64]reflect.Type // any locks we've taken, indexed by depth locks []sync.Locker // take locks while walking the structure useLocks bool } func (w *walker) Enter(l reflectwalk.Location) error { w.depth++ // ensure we have enough elements to index via w.depth for w.depth >= len(w.locks) { w.locks = append(w.locks, nil) } for len(w.ps) < w.depth+1 { w.ps = append(w.ps, 0) } return nil } func (w *walker) Exit(l reflectwalk.Location) error { locker := w.locks[w.depth] w.locks[w.depth] = nil if locker != nil { defer locker.Unlock() } // clear out pointers and interfaces as we exit the stack w.ps[w.depth] = 0 for k := range w.ifaceTypes { mask := uint64(^uint32(0)) if k&mask == uint64(w.depth) { delete(w.ifaceTypes, k) } } w.depth-- if w.ignoreDepth > w.depth { w.ignoreDepth = 0 } if w.ignoring() { return nil } switch l { case reflectwalk.Array: fallthrough case reflectwalk.Map: fallthrough case reflectwalk.Slice: w.replacePointerMaybe() // Pop map off our container w.cs = w.cs[:len(w.cs)-1] case reflectwalk.MapValue: // Pop off the key and value mv := w.valPop() mk := w.valPop() m := w.cs[len(w.cs)-1] // If mv is the zero value, SetMapIndex deletes the key form the map, // or in this case never adds it. We need to create a properly typed // zero value so that this key can be set. if !mv.IsValid() { mv = reflect.Zero(m.Elem().Type().Elem()) } m.Elem().SetMapIndex(mk, mv) case reflectwalk.ArrayElem: // Pop off the value and the index and set it on the array v := w.valPop() i := w.valPop().Interface().(int) if v.IsValid() { a := w.cs[len(w.cs)-1] ae := a.Elem().Index(i) // storing array as pointer on stack - so need Elem() call if ae.CanSet() { ae.Set(v) } } case reflectwalk.SliceElem: // Pop off the value and the index and set it on the slice v := w.valPop() i := w.valPop().Interface().(int) if v.IsValid() { s := w.cs[len(w.cs)-1] se := s.Elem().Index(i) if se.CanSet() { se.Set(v) } } case reflectwalk.Struct: w.replacePointerMaybe() // Remove the struct from the container stack w.cs = w.cs[:len(w.cs)-1] case reflectwalk.StructField: // Pop off the value and the field v := w.valPop() f := w.valPop().Interface().(reflect.StructField) if v.IsValid() { s := w.cs[len(w.cs)-1] sf := reflect.Indirect(s).FieldByName(f.Name) if sf.CanSet() { sf.Set(v) } } case reflectwalk.WalkLoc: // Clear out the slices for GC w.cs = nil w.vals = nil } return nil } func (w *walker) Map(m reflect.Value) error { if w.ignoring() { return nil } w.lock(m) // Create the map. If the map itself is nil, then just make a nil map var newMap reflect.Value if m.IsNil() { newMap = reflect.New(m.Type()) } else { newMap = wrapPtr(reflect.MakeMap(m.Type())) } w.cs = append(w.cs, newMap) w.valPush(newMap) return nil } func (w *walker) MapElem(m, k, v reflect.Value) error { return nil } func (w *walker) PointerEnter(v bool) error { if v { w.ps[w.depth]++ } return nil } func (w *walker) PointerExit(v bool) error { if v { w.ps[w.depth]-- } return nil } func (w *walker) Pointer(v reflect.Value) error { if _, ok := w.shallowCopiers[v.Type()]; ok { // Shallow copy this value. Use the same logic as primitive, then // return skip. if err := w.Primitive(v); err != nil { return err } return reflectwalk.SkipEntry } return nil } func (w *walker) Interface(v reflect.Value) error { if !v.IsValid() { return nil } if w.ifaceTypes == nil { w.ifaceTypes = make(map[uint64]reflect.Type) } w.ifaceTypes[ifaceKey(w.ps[w.depth], w.depth)] = v.Type() return nil } func (w *walker) Primitive(v reflect.Value) error { if w.ignoring() { return nil } w.lock(v) // IsValid verifies the v is non-zero and CanInterface verifies // that we're allowed to read this value (unexported fields). var newV reflect.Value if v.IsValid() && v.CanInterface() { newV = reflect.New(v.Type()) newV.Elem().Set(v) } w.valPush(newV) w.replacePointerMaybe() return nil } func (w *walker) Slice(s reflect.Value) error { if w.ignoring() { return nil } w.lock(s) var newS reflect.Value if s.IsNil() { newS = reflect.New(s.Type()) } else { newS = wrapPtr(reflect.MakeSlice(s.Type(), s.Len(), s.Cap())) } w.cs = append(w.cs, newS) w.valPush(newS) return nil } func (w *walker) SliceElem(i int, elem reflect.Value) error { if w.ignoring() { return nil } // We don't write the slice here because elem might still be // arbitrarily complex. Just record the index and continue on. w.valPush(reflect.ValueOf(i)) return nil } func (w *walker) Array(a reflect.Value) error { if w.ignoring() { return nil } w.lock(a) newA := reflect.New(a.Type()) w.cs = append(w.cs, newA) w.valPush(newA) return nil } func (w *walker) ArrayElem(i int, elem reflect.Value) error { if w.ignoring() { return nil } // We don't write the array here because elem might still be // arbitrarily complex. Just record the index and continue on. w.valPush(reflect.ValueOf(i)) return nil } func (w *walker) Struct(s reflect.Value) error { if w.ignoring() { return nil } w.lock(s) var v reflect.Value if c, ok := w.copiers[s.Type()]; ok { // We have a Copier for this struct, so we use that copier to // get the copy, and we ignore anything deeper than this. w.ignoreDepth = w.depth dup, err := c(s.Interface()) if err != nil { return err } // We need to put a pointer to the value on the value stack, // so allocate a new pointer and set it. v = reflect.New(s.Type()) reflect.Indirect(v).Set(reflect.ValueOf(dup)) } else { // No copier, we copy ourselves and allow reflectwalk to guide // us deeper into the structure for copying. v = reflect.New(s.Type()) } // Push the value onto the value stack for setting the struct field, // and add the struct itself to the containers stack in case we walk // deeper so that its own fields can be modified. w.valPush(v) w.cs = append(w.cs, v) return nil } func (w *walker) StructField(f reflect.StructField, v reflect.Value) error { if w.ignoring() { return nil } // If PkgPath is non-empty, this is a private (unexported) field. // We do not set this unexported since the Go runtime doesn't allow us. if f.PkgPath != "" { return reflectwalk.SkipEntry } switch f.Tag.Get(tagKey) { case "shallow": // If we're shallow copying then assign the value directly to the // struct and skip the entry. if v.IsValid() { s := w.cs[len(w.cs)-1] sf := reflect.Indirect(s).FieldByName(f.Name) if sf.CanSet() { sf.Set(v) } } return reflectwalk.SkipEntry case "ignore": // Do nothing return reflectwalk.SkipEntry } // Push the field onto the stack, we'll handle it when we exit // the struct field in Exit... w.valPush(reflect.ValueOf(f)) return nil } // ignore causes the walker to ignore any more values until we exit this on func (w *walker) ignore() { w.ignoreDepth = w.depth } func (w *walker) ignoring() bool { return w.ignoreDepth > 0 && w.depth >= w.ignoreDepth } func (w *walker) pointerPeek() bool { return w.ps[w.depth] > 0 } func (w *walker) valPop() reflect.Value { result := w.vals[len(w.vals)-1] w.vals = w.vals[:len(w.vals)-1] // If we're out of values, that means we popped everything off. In // this case, we reset the result so the next pushed value becomes // the result. if len(w.vals) == 0 { w.Result = nil } return result } func (w *walker) valPush(v reflect.Value) { w.vals = append(w.vals, v) // If we haven't set the result yet, then this is the result since // it is the first (outermost) value we're seeing. if w.Result == nil && v.IsValid() { w.Result = v.Interface() } } func (w *walker) replacePointerMaybe() { // Determine the last pointer value. If it is NOT a pointer, then // we need to push that onto the stack. if !w.pointerPeek() { w.valPush(reflect.Indirect(w.valPop())) return } v := w.valPop() // If the expected type is a pointer to an interface of any depth, // such as *interface{}, **interface{}, etc., then we need to convert // the value "v" from *CONCRETE to *interface{} so types match for // Set. // // Example if v is type *Foo where Foo is a struct, v would become // *interface{} instead. This only happens if we have an interface expectation // at this depth. // // For more info, see GH-16 if iType, ok := w.ifaceTypes[ifaceKey(w.ps[w.depth], w.depth)]; ok && iType.Kind() == reflect.Interface { y := reflect.New(iType) // Create *interface{} y.Elem().Set(reflect.Indirect(v)) // Assign "Foo" to interface{} (dereferenced) v = y // v is now typed *interface{} (where *v = Foo) } for i := 1; i < w.ps[w.depth]; i++ { if iType, ok := w.ifaceTypes[ifaceKey(w.ps[w.depth]-i, w.depth)]; ok { iface := reflect.New(iType).Elem() iface.Set(v) v = iface } p := reflect.New(v.Type()) p.Elem().Set(v) v = p } w.valPush(v) } // if this value is a Locker, lock it and add it to the locks slice func (w *walker) lock(v reflect.Value) { if !w.useLocks { return } if !v.IsValid() || !v.CanInterface() { return } type rlocker interface { RLocker() sync.Locker } var locker sync.Locker // We can't call Interface() on a value directly, since that requires // a copy. This is OK, since the pointer to a value which is a sync.Locker // is also a sync.Locker. if v.Kind() == reflect.Ptr { switch l := v.Interface().(type) { case rlocker: // don't lock a mutex directly if _, ok := l.(*sync.RWMutex); !ok { locker = l.RLocker() } case sync.Locker: locker = l } } else if v.CanAddr() { switch l := v.Addr().Interface().(type) { case rlocker: // don't lock a mutex directly if _, ok := l.(*sync.RWMutex); !ok { locker = l.RLocker() } case sync.Locker: locker = l } } // still no callable locker if locker == nil { return } // don't lock a mutex directly switch locker.(type) { case *sync.Mutex, *sync.RWMutex: return } locker.Lock() w.locks[w.depth] = locker } // wrapPtr is a helper that takes v and always make it *v. copystructure // stores things internally as pointers until the last moment before unwrapping func wrapPtr(v reflect.Value) reflect.Value { if !v.IsValid() { return v } vPtr := reflect.New(v.Type()) vPtr.Elem().Set(v) return vPtr }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/mitchellh/copystructure/copier_time.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/mitchellh/copystructure/copier_time.go
package copystructure import ( "reflect" "time" ) func init() { Copiers[reflect.TypeOf(time.Time{})] = timeCopier } func timeCopier(v interface{}) (interface{}, error) { // Just... copy it. return v.(time.Time), nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/mitchellh/reflectwalk/location.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/mitchellh/reflectwalk/location.go
package reflectwalk //go:generate stringer -type=Location location.go type Location uint const ( None Location = iota Map MapKey MapValue Slice SliceElem Array ArrayElem Struct StructField WalkLoc )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/mitchellh/reflectwalk/reflectwalk.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/mitchellh/reflectwalk/reflectwalk.go
// reflectwalk is a package that allows you to "walk" complex structures // similar to how you may "walk" a filesystem: visiting every element one // by one and calling callback functions allowing you to handle and manipulate // those elements. package reflectwalk import ( "errors" "reflect" ) // PrimitiveWalker implementations are able to handle primitive values // within complex structures. Primitive values are numbers, strings, // booleans, funcs, chans. // // These primitive values are often members of more complex // structures (slices, maps, etc.) that are walkable by other interfaces. type PrimitiveWalker interface { Primitive(reflect.Value) error } // InterfaceWalker implementations are able to handle interface values as they // are encountered during the walk. type InterfaceWalker interface { Interface(reflect.Value) error } // MapWalker implementations are able to handle individual elements // found within a map structure. type MapWalker interface { Map(m reflect.Value) error MapElem(m, k, v reflect.Value) error } // SliceWalker implementations are able to handle slice elements found // within complex structures. type SliceWalker interface { Slice(reflect.Value) error SliceElem(int, reflect.Value) error } // ArrayWalker implementations are able to handle array elements found // within complex structures. type ArrayWalker interface { Array(reflect.Value) error ArrayElem(int, reflect.Value) error } // StructWalker is an interface that has methods that are called for // structs when a Walk is done. type StructWalker interface { Struct(reflect.Value) error StructField(reflect.StructField, reflect.Value) error } // EnterExitWalker implementations are notified before and after // they walk deeper into complex structures (into struct fields, // into slice elements, etc.) type EnterExitWalker interface { Enter(Location) error Exit(Location) error } // PointerWalker implementations are notified when the value they're // walking is a pointer or not. Pointer is called for _every_ value whether // it is a pointer or not. type PointerWalker interface { PointerEnter(bool) error PointerExit(bool) error } // PointerValueWalker implementations are notified with the value of // a particular pointer when a pointer is walked. Pointer is called // right before PointerEnter. type PointerValueWalker interface { Pointer(reflect.Value) error } // SkipEntry can be returned from walk functions to skip walking // the value of this field. This is only valid in the following functions: // // - Struct: skips all fields from being walked // - StructField: skips walking the struct value // var SkipEntry = errors.New("skip this entry") // Walk takes an arbitrary value and an interface and traverses the // value, calling callbacks on the interface if they are supported. // The interface should implement one or more of the walker interfaces // in this package, such as PrimitiveWalker, StructWalker, etc. func Walk(data, walker interface{}) (err error) { v := reflect.ValueOf(data) ew, ok := walker.(EnterExitWalker) if ok { err = ew.Enter(WalkLoc) } if err == nil { err = walk(v, walker) } if ok && err == nil { err = ew.Exit(WalkLoc) } return } func walk(v reflect.Value, w interface{}) (err error) { // Determine if we're receiving a pointer and if so notify the walker. // The logic here is convoluted but very important (tests will fail if // almost any part is changed). I will try to explain here. // // First, we check if the value is an interface, if so, we really need // to check the interface's VALUE to see whether it is a pointer. // // Check whether the value is then a pointer. If so, then set pointer // to true to notify the user. // // If we still have a pointer or an interface after the indirections, then // we unwrap another level // // At this time, we also set "v" to be the dereferenced value. This is // because once we've unwrapped the pointer we want to use that value. pointer := false pointerV := v for { if pointerV.Kind() == reflect.Interface { if iw, ok := w.(InterfaceWalker); ok { if err = iw.Interface(pointerV); err != nil { return } } pointerV = pointerV.Elem() } if pointerV.Kind() == reflect.Ptr { if pw, ok := w.(PointerValueWalker); ok { if err = pw.Pointer(pointerV); err != nil { if err == SkipEntry { // Skip the rest of this entry but clear the error return nil } return } } pointer = true v = reflect.Indirect(pointerV) } if pw, ok := w.(PointerWalker); ok { if err = pw.PointerEnter(pointer); err != nil { return } defer func(pointer bool) { if err != nil { return } err = pw.PointerExit(pointer) }(pointer) } if pointer { pointerV = v } pointer = false // If we still have a pointer or interface we have to indirect another level. switch pointerV.Kind() { case reflect.Ptr, reflect.Interface: continue } break } // We preserve the original value here because if it is an interface // type, we want to pass that directly into the walkPrimitive, so that // we can set it. originalV := v if v.Kind() == reflect.Interface { v = v.Elem() } k := v.Kind() if k >= reflect.Int && k <= reflect.Complex128 { k = reflect.Int } switch k { // Primitives case reflect.Bool, reflect.Chan, reflect.Func, reflect.Int, reflect.String, reflect.Invalid: err = walkPrimitive(originalV, w) return case reflect.Map: err = walkMap(v, w) return case reflect.Slice: err = walkSlice(v, w) return case reflect.Struct: err = walkStruct(v, w) return case reflect.Array: err = walkArray(v, w) return default: panic("unsupported type: " + k.String()) } } func walkMap(v reflect.Value, w interface{}) error { ew, ewok := w.(EnterExitWalker) if ewok { ew.Enter(Map) } if mw, ok := w.(MapWalker); ok { if err := mw.Map(v); err != nil { return err } } for _, k := range v.MapKeys() { kv := v.MapIndex(k) if mw, ok := w.(MapWalker); ok { if err := mw.MapElem(v, k, kv); err != nil { return err } } ew, ok := w.(EnterExitWalker) if ok { ew.Enter(MapKey) } if err := walk(k, w); err != nil { return err } if ok { ew.Exit(MapKey) ew.Enter(MapValue) } // get the map value again as it may have changed in the MapElem call if err := walk(v.MapIndex(k), w); err != nil { return err } if ok { ew.Exit(MapValue) } } if ewok { ew.Exit(Map) } return nil } func walkPrimitive(v reflect.Value, w interface{}) error { if pw, ok := w.(PrimitiveWalker); ok { return pw.Primitive(v) } return nil } func walkSlice(v reflect.Value, w interface{}) (err error) { ew, ok := w.(EnterExitWalker) if ok { ew.Enter(Slice) } if sw, ok := w.(SliceWalker); ok { if err := sw.Slice(v); err != nil { return err } } for i := 0; i < v.Len(); i++ { elem := v.Index(i) if sw, ok := w.(SliceWalker); ok { if err := sw.SliceElem(i, elem); err != nil { return err } } ew, ok := w.(EnterExitWalker) if ok { ew.Enter(SliceElem) } if err := walk(elem, w); err != nil { return err } if ok { ew.Exit(SliceElem) } } ew, ok = w.(EnterExitWalker) if ok { ew.Exit(Slice) } return nil } func walkArray(v reflect.Value, w interface{}) (err error) { ew, ok := w.(EnterExitWalker) if ok { ew.Enter(Array) } if aw, ok := w.(ArrayWalker); ok { if err := aw.Array(v); err != nil { return err } } for i := 0; i < v.Len(); i++ { elem := v.Index(i) if aw, ok := w.(ArrayWalker); ok { if err := aw.ArrayElem(i, elem); err != nil { return err } } ew, ok := w.(EnterExitWalker) if ok { ew.Enter(ArrayElem) } if err := walk(elem, w); err != nil { return err } if ok { ew.Exit(ArrayElem) } } ew, ok = w.(EnterExitWalker) if ok { ew.Exit(Array) } return nil } func walkStruct(v reflect.Value, w interface{}) (err error) { ew, ewok := w.(EnterExitWalker) if ewok { ew.Enter(Struct) } skip := false if sw, ok := w.(StructWalker); ok { err = sw.Struct(v) if err == SkipEntry { skip = true err = nil } if err != nil { return } } if !skip { vt := v.Type() for i := 0; i < vt.NumField(); i++ { sf := vt.Field(i) f := v.FieldByIndex([]int{i}) if sw, ok := w.(StructWalker); ok { err = sw.StructField(sf, f) // SkipEntry just pretends this field doesn't even exist if err == SkipEntry { continue } if err != nil { return } } ew, ok := w.(EnterExitWalker) if ok { ew.Enter(StructField) } err = walk(f, w) if err != nil { return } if ok { ew.Exit(StructField) } } } if ewok { ew.Exit(Struct) } return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/mitchellh/reflectwalk/location_string.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/mitchellh/reflectwalk/location_string.go
// Code generated by "stringer -type=Location location.go"; DO NOT EDIT. package reflectwalk import "fmt" const _Location_name = "NoneMapMapKeyMapValueSliceSliceElemArrayArrayElemStructStructFieldWalkLoc" var _Location_index = [...]uint8{0, 4, 7, 13, 21, 26, 35, 40, 49, 55, 66, 73} func (i Location) String() string { if i >= Location(len(_Location_index)-1) { return fmt.Sprintf("Location(%d)", i) } return _Location_name[_Location_index[i]:_Location_index[i+1]] }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/mitchellh/mapstructure/error.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/mitchellh/mapstructure/error.go
package mapstructure import ( "errors" "fmt" "sort" "strings" ) // Error implements the error interface and can represents multiple // errors that occur in the course of a single decode. type Error struct { Errors []string } func (e *Error) Error() string { points := make([]string, len(e.Errors)) for i, err := range e.Errors { points[i] = fmt.Sprintf("* %s", err) } sort.Strings(points) return fmt.Sprintf( "%d error(s) decoding:\n\n%s", len(e.Errors), strings.Join(points, "\n")) } // WrappedErrors implements the errwrap.Wrapper interface to make this // return value more useful with the errwrap and go-multierror libraries. func (e *Error) WrappedErrors() []error { if e == nil { return nil } result := make([]error, len(e.Errors)) for i, e := range e.Errors { result[i] = errors.New(e) } return result } func appendErrors(errors []string, err error) []string { switch e := err.(type) { case *Error: return append(errors, e.Errors...) default: return append(errors, e.Error()) } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/mitchellh/mapstructure/decode_hooks.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/mitchellh/mapstructure/decode_hooks.go
package mapstructure import ( "encoding" "errors" "fmt" "net" "reflect" "strconv" "strings" "time" ) // typedDecodeHook takes a raw DecodeHookFunc (an interface{}) and turns // it into the proper DecodeHookFunc type, such as DecodeHookFuncType. func typedDecodeHook(h DecodeHookFunc) DecodeHookFunc { // Create variables here so we can reference them with the reflect pkg var f1 DecodeHookFuncType var f2 DecodeHookFuncKind var f3 DecodeHookFuncValue // Fill in the variables into this interface and the rest is done // automatically using the reflect package. potential := []interface{}{f1, f2, f3} v := reflect.ValueOf(h) vt := v.Type() for _, raw := range potential { pt := reflect.ValueOf(raw).Type() if vt.ConvertibleTo(pt) { return v.Convert(pt).Interface() } } return nil } // DecodeHookExec executes the given decode hook. This should be used // since it'll naturally degrade to the older backwards compatible DecodeHookFunc // that took reflect.Kind instead of reflect.Type. func DecodeHookExec( raw DecodeHookFunc, from reflect.Value, to reflect.Value) (interface{}, error) { switch f := typedDecodeHook(raw).(type) { case DecodeHookFuncType: return f(from.Type(), to.Type(), from.Interface()) case DecodeHookFuncKind: return f(from.Kind(), to.Kind(), from.Interface()) case DecodeHookFuncValue: return f(from, to) default: return nil, errors.New("invalid decode hook signature") } } // ComposeDecodeHookFunc creates a single DecodeHookFunc that // automatically composes multiple DecodeHookFuncs. // // The composed funcs are called in order, with the result of the // previous transformation. func ComposeDecodeHookFunc(fs ...DecodeHookFunc) DecodeHookFunc { return func(f reflect.Value, t reflect.Value) (interface{}, error) { var err error data := f.Interface() newFrom := f for _, f1 := range fs { data, err = DecodeHookExec(f1, newFrom, t) if err != nil { return nil, err } newFrom = reflect.ValueOf(data) } return data, nil } } // OrComposeDecodeHookFunc executes all input hook functions until one of them returns no error. In that case its value is returned. // If all hooks return an error, OrComposeDecodeHookFunc returns an error concatenating all error messages. func OrComposeDecodeHookFunc(ff ...DecodeHookFunc) DecodeHookFunc { return func(a, b reflect.Value) (interface{}, error) { var allErrs string var out interface{} var err error for _, f := range ff { out, err = DecodeHookExec(f, a, b) if err != nil { allErrs += err.Error() + "\n" continue } return out, nil } return nil, errors.New(allErrs) } } // StringToSliceHookFunc returns a DecodeHookFunc that converts // string to []string by splitting on the given sep. func StringToSliceHookFunc(sep string) DecodeHookFunc { return func( f reflect.Kind, t reflect.Kind, data interface{}) (interface{}, error) { if f != reflect.String || t != reflect.Slice { return data, nil } raw := data.(string) if raw == "" { return []string{}, nil } return strings.Split(raw, sep), nil } } // StringToTimeDurationHookFunc returns a DecodeHookFunc that converts // strings to time.Duration. func StringToTimeDurationHookFunc() DecodeHookFunc { return func( f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { if f.Kind() != reflect.String { return data, nil } if t != reflect.TypeOf(time.Duration(5)) { return data, nil } // Convert it by parsing return time.ParseDuration(data.(string)) } } // StringToIPHookFunc returns a DecodeHookFunc that converts // strings to net.IP func StringToIPHookFunc() DecodeHookFunc { return func( f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { if f.Kind() != reflect.String { return data, nil } if t != reflect.TypeOf(net.IP{}) { return data, nil } // Convert it by parsing ip := net.ParseIP(data.(string)) if ip == nil { return net.IP{}, fmt.Errorf("failed parsing ip %v", data) } return ip, nil } } // StringToIPNetHookFunc returns a DecodeHookFunc that converts // strings to net.IPNet func StringToIPNetHookFunc() DecodeHookFunc { return func( f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { if f.Kind() != reflect.String { return data, nil } if t != reflect.TypeOf(net.IPNet{}) { return data, nil } // Convert it by parsing _, net, err := net.ParseCIDR(data.(string)) return net, err } } // StringToTimeHookFunc returns a DecodeHookFunc that converts // strings to time.Time. func StringToTimeHookFunc(layout string) DecodeHookFunc { return func( f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { if f.Kind() != reflect.String { return data, nil } if t != reflect.TypeOf(time.Time{}) { return data, nil } // Convert it by parsing return time.Parse(layout, data.(string)) } } // WeaklyTypedHook is a DecodeHookFunc which adds support for weak typing to // the decoder. // // Note that this is significantly different from the WeaklyTypedInput option // of the DecoderConfig. func WeaklyTypedHook( f reflect.Kind, t reflect.Kind, data interface{}) (interface{}, error) { dataVal := reflect.ValueOf(data) switch t { case reflect.String: switch f { case reflect.Bool: if dataVal.Bool() { return "1", nil } return "0", nil case reflect.Float32: return strconv.FormatFloat(dataVal.Float(), 'f', -1, 64), nil case reflect.Int: return strconv.FormatInt(dataVal.Int(), 10), nil case reflect.Slice: dataType := dataVal.Type() elemKind := dataType.Elem().Kind() if elemKind == reflect.Uint8 { return string(dataVal.Interface().([]uint8)), nil } case reflect.Uint: return strconv.FormatUint(dataVal.Uint(), 10), nil } } return data, nil } func RecursiveStructToMapHookFunc() DecodeHookFunc { return func(f reflect.Value, t reflect.Value) (interface{}, error) { if f.Kind() != reflect.Struct { return f.Interface(), nil } var i interface{} = struct{}{} if t.Type() != reflect.TypeOf(&i).Elem() { return f.Interface(), nil } m := make(map[string]interface{}) t.Set(reflect.ValueOf(m)) return f.Interface(), nil } } // TextUnmarshallerHookFunc returns a DecodeHookFunc that applies // strings to the UnmarshalText function, when the target type // implements the encoding.TextUnmarshaler interface func TextUnmarshallerHookFunc() DecodeHookFuncType { return func( f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { if f.Kind() != reflect.String { return data, nil } result := reflect.New(t).Interface() unmarshaller, ok := result.(encoding.TextUnmarshaler) if !ok { return data, nil } if err := unmarshaller.UnmarshalText([]byte(data.(string))); err != nil { return nil, err } return result, nil } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/github.com/mitchellh/mapstructure/mapstructure.go
cmd/vsphere-xcopy-volume-populator/vendor/github.com/mitchellh/mapstructure/mapstructure.go
// Package mapstructure exposes functionality to convert one arbitrary // Go type into another, typically to convert a map[string]interface{} // into a native Go structure. // // The Go structure can be arbitrarily complex, containing slices, // other structs, etc. and the decoder will properly decode nested // maps and so on into the proper structures in the native Go struct. // See the examples to see what the decoder is capable of. // // The simplest function to start with is Decode. // // Field Tags // // When decoding to a struct, mapstructure will use the field name by // default to perform the mapping. For example, if a struct has a field // "Username" then mapstructure will look for a key in the source value // of "username" (case insensitive). // // type User struct { // Username string // } // // You can change the behavior of mapstructure by using struct tags. // The default struct tag that mapstructure looks for is "mapstructure" // but you can customize it using DecoderConfig. // // Renaming Fields // // To rename the key that mapstructure looks for, use the "mapstructure" // tag and set a value directly. For example, to change the "username" example // above to "user": // // type User struct { // Username string `mapstructure:"user"` // } // // Embedded Structs and Squashing // // Embedded structs are treated as if they're another field with that name. // By default, the two structs below are equivalent when decoding with // mapstructure: // // type Person struct { // Name string // } // // type Friend struct { // Person // } // // type Friend struct { // Person Person // } // // This would require an input that looks like below: // // map[string]interface{}{ // "person": map[string]interface{}{"name": "alice"}, // } // // If your "person" value is NOT nested, then you can append ",squash" to // your tag value and mapstructure will treat it as if the embedded struct // were part of the struct directly. Example: // // type Friend struct { // Person `mapstructure:",squash"` // } // // Now the following input would be accepted: // // map[string]interface{}{ // "name": "alice", // } // // When decoding from a struct to a map, the squash tag squashes the struct // fields into a single map. Using the example structs from above: // // Friend{Person: Person{Name: "alice"}} // // Will be decoded into a map: // // map[string]interface{}{ // "name": "alice", // } // // DecoderConfig has a field that changes the behavior of mapstructure // to always squash embedded structs. // // Remainder Values // // If there are any unmapped keys in the source value, mapstructure by // default will silently ignore them. You can error by setting ErrorUnused // in DecoderConfig. If you're using Metadata you can also maintain a slice // of the unused keys. // // You can also use the ",remain" suffix on your tag to collect all unused // values in a map. The field with this tag MUST be a map type and should // probably be a "map[string]interface{}" or "map[interface{}]interface{}". // See example below: // // type Friend struct { // Name string // Other map[string]interface{} `mapstructure:",remain"` // } // // Given the input below, Other would be populated with the other // values that weren't used (everything but "name"): // // map[string]interface{}{ // "name": "bob", // "address": "123 Maple St.", // } // // Omit Empty Values // // When decoding from a struct to any other value, you may use the // ",omitempty" suffix on your tag to omit that value if it equates to // the zero value. The zero value of all types is specified in the Go // specification. // // For example, the zero type of a numeric type is zero ("0"). If the struct // field value is zero and a numeric type, the field is empty, and it won't // be encoded into the destination type. // // type Source struct { // Age int `mapstructure:",omitempty"` // } // // Unexported fields // // Since unexported (private) struct fields cannot be set outside the package // where they are defined, the decoder will simply skip them. // // For this output type definition: // // type Exported struct { // private string // this unexported field will be skipped // Public string // } // // Using this map as input: // // map[string]interface{}{ // "private": "I will be ignored", // "Public": "I made it through!", // } // // The following struct will be decoded: // // type Exported struct { // private: "" // field is left with an empty string (zero value) // Public: "I made it through!" // } // // Other Configuration // // mapstructure is highly configurable. See the DecoderConfig struct // for other features and options that are supported. package mapstructure import ( "encoding/json" "errors" "fmt" "reflect" "sort" "strconv" "strings" ) // DecodeHookFunc is the callback function that can be used for // data transformations. See "DecodeHook" in the DecoderConfig // struct. // // The type must be one of DecodeHookFuncType, DecodeHookFuncKind, or // DecodeHookFuncValue. // Values are a superset of Types (Values can return types), and Types are a // superset of Kinds (Types can return Kinds) and are generally a richer thing // to use, but Kinds are simpler if you only need those. // // The reason DecodeHookFunc is multi-typed is for backwards compatibility: // we started with Kinds and then realized Types were the better solution, // but have a promise to not break backwards compat so we now support // both. type DecodeHookFunc interface{} // DecodeHookFuncType is a DecodeHookFunc which has complete information about // the source and target types. type DecodeHookFuncType func(reflect.Type, reflect.Type, interface{}) (interface{}, error) // DecodeHookFuncKind is a DecodeHookFunc which knows only the Kinds of the // source and target types. type DecodeHookFuncKind func(reflect.Kind, reflect.Kind, interface{}) (interface{}, error) // DecodeHookFuncValue is a DecodeHookFunc which has complete access to both the source and target // values. type DecodeHookFuncValue func(from reflect.Value, to reflect.Value) (interface{}, error) // DecoderConfig is the configuration that is used to create a new decoder // and allows customization of various aspects of decoding. type DecoderConfig struct { // DecodeHook, if set, will be called before any decoding and any // type conversion (if WeaklyTypedInput is on). This lets you modify // the values before they're set down onto the resulting struct. The // DecodeHook is called for every map and value in the input. This means // that if a struct has embedded fields with squash tags the decode hook // is called only once with all of the input data, not once for each // embedded struct. // // If an error is returned, the entire decode will fail with that error. DecodeHook DecodeHookFunc // If ErrorUnused is true, then it is an error for there to exist // keys in the original map that were unused in the decoding process // (extra keys). ErrorUnused bool // If ErrorUnset is true, then it is an error for there to exist // fields in the result that were not set in the decoding process // (extra fields). This only applies to decoding to a struct. This // will affect all nested structs as well. ErrorUnset bool // ZeroFields, if set to true, will zero fields before writing them. // For example, a map will be emptied before decoded values are put in // it. If this is false, a map will be merged. ZeroFields bool // If WeaklyTypedInput is true, the decoder will make the following // "weak" conversions: // // - bools to string (true = "1", false = "0") // - numbers to string (base 10) // - bools to int/uint (true = 1, false = 0) // - strings to int/uint (base implied by prefix) // - int to bool (true if value != 0) // - string to bool (accepts: 1, t, T, TRUE, true, True, 0, f, F, // FALSE, false, False. Anything else is an error) // - empty array = empty map and vice versa // - negative numbers to overflowed uint values (base 10) // - slice of maps to a merged map // - single values are converted to slices if required. Each // element is weakly decoded. For example: "4" can become []int{4} // if the target type is an int slice. // WeaklyTypedInput bool // Squash will squash embedded structs. A squash tag may also be // added to an individual struct field using a tag. For example: // // type Parent struct { // Child `mapstructure:",squash"` // } Squash bool // Metadata is the struct that will contain extra metadata about // the decoding. If this is nil, then no metadata will be tracked. Metadata *Metadata // Result is a pointer to the struct that will contain the decoded // value. Result interface{} // The tag name that mapstructure reads for field names. This // defaults to "mapstructure" TagName string // IgnoreUntaggedFields ignores all struct fields without explicit // TagName, comparable to `mapstructure:"-"` as default behaviour. IgnoreUntaggedFields bool // MatchName is the function used to match the map key to the struct // field name or tag. Defaults to `strings.EqualFold`. This can be used // to implement case-sensitive tag values, support snake casing, etc. MatchName func(mapKey, fieldName string) bool } // A Decoder takes a raw interface value and turns it into structured // data, keeping track of rich error information along the way in case // anything goes wrong. Unlike the basic top-level Decode method, you can // more finely control how the Decoder behaves using the DecoderConfig // structure. The top-level Decode method is just a convenience that sets // up the most basic Decoder. type Decoder struct { config *DecoderConfig } // Metadata contains information about decoding a structure that // is tedious or difficult to get otherwise. type Metadata struct { // Keys are the keys of the structure which were successfully decoded Keys []string // Unused is a slice of keys that were found in the raw value but // weren't decoded since there was no matching field in the result interface Unused []string // Unset is a slice of field names that were found in the result interface // but weren't set in the decoding process since there was no matching value // in the input Unset []string } // Decode takes an input structure and uses reflection to translate it to // the output structure. output must be a pointer to a map or struct. func Decode(input interface{}, output interface{}) error { config := &DecoderConfig{ Metadata: nil, Result: output, } decoder, err := NewDecoder(config) if err != nil { return err } return decoder.Decode(input) } // WeakDecode is the same as Decode but is shorthand to enable // WeaklyTypedInput. See DecoderConfig for more info. func WeakDecode(input, output interface{}) error { config := &DecoderConfig{ Metadata: nil, Result: output, WeaklyTypedInput: true, } decoder, err := NewDecoder(config) if err != nil { return err } return decoder.Decode(input) } // DecodeMetadata is the same as Decode, but is shorthand to // enable metadata collection. See DecoderConfig for more info. func DecodeMetadata(input interface{}, output interface{}, metadata *Metadata) error { config := &DecoderConfig{ Metadata: metadata, Result: output, } decoder, err := NewDecoder(config) if err != nil { return err } return decoder.Decode(input) } // WeakDecodeMetadata is the same as Decode, but is shorthand to // enable both WeaklyTypedInput and metadata collection. See // DecoderConfig for more info. func WeakDecodeMetadata(input interface{}, output interface{}, metadata *Metadata) error { config := &DecoderConfig{ Metadata: metadata, Result: output, WeaklyTypedInput: true, } decoder, err := NewDecoder(config) if err != nil { return err } return decoder.Decode(input) } // NewDecoder returns a new decoder for the given configuration. Once // a decoder has been returned, the same configuration must not be used // again. func NewDecoder(config *DecoderConfig) (*Decoder, error) { val := reflect.ValueOf(config.Result) if val.Kind() != reflect.Ptr { return nil, errors.New("result must be a pointer") } val = val.Elem() if !val.CanAddr() { return nil, errors.New("result must be addressable (a pointer)") } if config.Metadata != nil { if config.Metadata.Keys == nil { config.Metadata.Keys = make([]string, 0) } if config.Metadata.Unused == nil { config.Metadata.Unused = make([]string, 0) } if config.Metadata.Unset == nil { config.Metadata.Unset = make([]string, 0) } } if config.TagName == "" { config.TagName = "mapstructure" } if config.MatchName == nil { config.MatchName = strings.EqualFold } result := &Decoder{ config: config, } return result, nil } // Decode decodes the given raw interface to the target pointer specified // by the configuration. func (d *Decoder) Decode(input interface{}) error { return d.decode("", input, reflect.ValueOf(d.config.Result).Elem()) } // Decodes an unknown data type into a specific reflection value. func (d *Decoder) decode(name string, input interface{}, outVal reflect.Value) error { var inputVal reflect.Value if input != nil { inputVal = reflect.ValueOf(input) // We need to check here if input is a typed nil. Typed nils won't // match the "input == nil" below so we check that here. if inputVal.Kind() == reflect.Ptr && inputVal.IsNil() { input = nil } } if input == nil { // If the data is nil, then we don't set anything, unless ZeroFields is set // to true. if d.config.ZeroFields { outVal.Set(reflect.Zero(outVal.Type())) if d.config.Metadata != nil && name != "" { d.config.Metadata.Keys = append(d.config.Metadata.Keys, name) } } return nil } if !inputVal.IsValid() { // If the input value is invalid, then we just set the value // to be the zero value. outVal.Set(reflect.Zero(outVal.Type())) if d.config.Metadata != nil && name != "" { d.config.Metadata.Keys = append(d.config.Metadata.Keys, name) } return nil } if d.config.DecodeHook != nil { // We have a DecodeHook, so let's pre-process the input. var err error input, err = DecodeHookExec(d.config.DecodeHook, inputVal, outVal) if err != nil { return fmt.Errorf("error decoding '%s': %s", name, err) } } var err error outputKind := getKind(outVal) addMetaKey := true switch outputKind { case reflect.Bool: err = d.decodeBool(name, input, outVal) case reflect.Interface: err = d.decodeBasic(name, input, outVal) case reflect.String: err = d.decodeString(name, input, outVal) case reflect.Int: err = d.decodeInt(name, input, outVal) case reflect.Uint: err = d.decodeUint(name, input, outVal) case reflect.Float32: err = d.decodeFloat(name, input, outVal) case reflect.Struct: err = d.decodeStruct(name, input, outVal) case reflect.Map: err = d.decodeMap(name, input, outVal) case reflect.Ptr: addMetaKey, err = d.decodePtr(name, input, outVal) case reflect.Slice: err = d.decodeSlice(name, input, outVal) case reflect.Array: err = d.decodeArray(name, input, outVal) case reflect.Func: err = d.decodeFunc(name, input, outVal) default: // If we reached this point then we weren't able to decode it return fmt.Errorf("%s: unsupported type: %s", name, outputKind) } // If we reached here, then we successfully decoded SOMETHING, so // mark the key as used if we're tracking metainput. if addMetaKey && d.config.Metadata != nil && name != "" { d.config.Metadata.Keys = append(d.config.Metadata.Keys, name) } return err } // This decodes a basic type (bool, int, string, etc.) and sets the // value to "data" of that type. func (d *Decoder) decodeBasic(name string, data interface{}, val reflect.Value) error { if val.IsValid() && val.Elem().IsValid() { elem := val.Elem() // If we can't address this element, then its not writable. Instead, // we make a copy of the value (which is a pointer and therefore // writable), decode into that, and replace the whole value. copied := false if !elem.CanAddr() { copied = true // Make *T copy := reflect.New(elem.Type()) // *T = elem copy.Elem().Set(elem) // Set elem so we decode into it elem = copy } // Decode. If we have an error then return. We also return right // away if we're not a copy because that means we decoded directly. if err := d.decode(name, data, elem); err != nil || !copied { return err } // If we're a copy, we need to set te final result val.Set(elem.Elem()) return nil } dataVal := reflect.ValueOf(data) // If the input data is a pointer, and the assigned type is the dereference // of that exact pointer, then indirect it so that we can assign it. // Example: *string to string if dataVal.Kind() == reflect.Ptr && dataVal.Type().Elem() == val.Type() { dataVal = reflect.Indirect(dataVal) } if !dataVal.IsValid() { dataVal = reflect.Zero(val.Type()) } dataValType := dataVal.Type() if !dataValType.AssignableTo(val.Type()) { return fmt.Errorf( "'%s' expected type '%s', got '%s'", name, val.Type(), dataValType) } val.Set(dataVal) return nil } func (d *Decoder) decodeString(name string, data interface{}, val reflect.Value) error { dataVal := reflect.Indirect(reflect.ValueOf(data)) dataKind := getKind(dataVal) converted := true switch { case dataKind == reflect.String: val.SetString(dataVal.String()) case dataKind == reflect.Bool && d.config.WeaklyTypedInput: if dataVal.Bool() { val.SetString("1") } else { val.SetString("0") } case dataKind == reflect.Int && d.config.WeaklyTypedInput: val.SetString(strconv.FormatInt(dataVal.Int(), 10)) case dataKind == reflect.Uint && d.config.WeaklyTypedInput: val.SetString(strconv.FormatUint(dataVal.Uint(), 10)) case dataKind == reflect.Float32 && d.config.WeaklyTypedInput: val.SetString(strconv.FormatFloat(dataVal.Float(), 'f', -1, 64)) case dataKind == reflect.Slice && d.config.WeaklyTypedInput, dataKind == reflect.Array && d.config.WeaklyTypedInput: dataType := dataVal.Type() elemKind := dataType.Elem().Kind() switch elemKind { case reflect.Uint8: var uints []uint8 if dataKind == reflect.Array { uints = make([]uint8, dataVal.Len(), dataVal.Len()) for i := range uints { uints[i] = dataVal.Index(i).Interface().(uint8) } } else { uints = dataVal.Interface().([]uint8) } val.SetString(string(uints)) default: converted = false } default: converted = false } if !converted { return fmt.Errorf( "'%s' expected type '%s', got unconvertible type '%s', value: '%v'", name, val.Type(), dataVal.Type(), data) } return nil } func (d *Decoder) decodeInt(name string, data interface{}, val reflect.Value) error { dataVal := reflect.Indirect(reflect.ValueOf(data)) dataKind := getKind(dataVal) dataType := dataVal.Type() switch { case dataKind == reflect.Int: val.SetInt(dataVal.Int()) case dataKind == reflect.Uint: val.SetInt(int64(dataVal.Uint())) case dataKind == reflect.Float32: val.SetInt(int64(dataVal.Float())) case dataKind == reflect.Bool && d.config.WeaklyTypedInput: if dataVal.Bool() { val.SetInt(1) } else { val.SetInt(0) } case dataKind == reflect.String && d.config.WeaklyTypedInput: str := dataVal.String() if str == "" { str = "0" } i, err := strconv.ParseInt(str, 0, val.Type().Bits()) if err == nil { val.SetInt(i) } else { return fmt.Errorf("cannot parse '%s' as int: %s", name, err) } case dataType.PkgPath() == "encoding/json" && dataType.Name() == "Number": jn := data.(json.Number) i, err := jn.Int64() if err != nil { return fmt.Errorf( "error decoding json.Number into %s: %s", name, err) } val.SetInt(i) default: return fmt.Errorf( "'%s' expected type '%s', got unconvertible type '%s', value: '%v'", name, val.Type(), dataVal.Type(), data) } return nil } func (d *Decoder) decodeUint(name string, data interface{}, val reflect.Value) error { dataVal := reflect.Indirect(reflect.ValueOf(data)) dataKind := getKind(dataVal) dataType := dataVal.Type() switch { case dataKind == reflect.Int: i := dataVal.Int() if i < 0 && !d.config.WeaklyTypedInput { return fmt.Errorf("cannot parse '%s', %d overflows uint", name, i) } val.SetUint(uint64(i)) case dataKind == reflect.Uint: val.SetUint(dataVal.Uint()) case dataKind == reflect.Float32: f := dataVal.Float() if f < 0 && !d.config.WeaklyTypedInput { return fmt.Errorf("cannot parse '%s', %f overflows uint", name, f) } val.SetUint(uint64(f)) case dataKind == reflect.Bool && d.config.WeaklyTypedInput: if dataVal.Bool() { val.SetUint(1) } else { val.SetUint(0) } case dataKind == reflect.String && d.config.WeaklyTypedInput: str := dataVal.String() if str == "" { str = "0" } i, err := strconv.ParseUint(str, 0, val.Type().Bits()) if err == nil { val.SetUint(i) } else { return fmt.Errorf("cannot parse '%s' as uint: %s", name, err) } case dataType.PkgPath() == "encoding/json" && dataType.Name() == "Number": jn := data.(json.Number) i, err := strconv.ParseUint(string(jn), 0, 64) if err != nil { return fmt.Errorf( "error decoding json.Number into %s: %s", name, err) } val.SetUint(i) default: return fmt.Errorf( "'%s' expected type '%s', got unconvertible type '%s', value: '%v'", name, val.Type(), dataVal.Type(), data) } return nil } func (d *Decoder) decodeBool(name string, data interface{}, val reflect.Value) error { dataVal := reflect.Indirect(reflect.ValueOf(data)) dataKind := getKind(dataVal) switch { case dataKind == reflect.Bool: val.SetBool(dataVal.Bool()) case dataKind == reflect.Int && d.config.WeaklyTypedInput: val.SetBool(dataVal.Int() != 0) case dataKind == reflect.Uint && d.config.WeaklyTypedInput: val.SetBool(dataVal.Uint() != 0) case dataKind == reflect.Float32 && d.config.WeaklyTypedInput: val.SetBool(dataVal.Float() != 0) case dataKind == reflect.String && d.config.WeaklyTypedInput: b, err := strconv.ParseBool(dataVal.String()) if err == nil { val.SetBool(b) } else if dataVal.String() == "" { val.SetBool(false) } else { return fmt.Errorf("cannot parse '%s' as bool: %s", name, err) } default: return fmt.Errorf( "'%s' expected type '%s', got unconvertible type '%s', value: '%v'", name, val.Type(), dataVal.Type(), data) } return nil } func (d *Decoder) decodeFloat(name string, data interface{}, val reflect.Value) error { dataVal := reflect.Indirect(reflect.ValueOf(data)) dataKind := getKind(dataVal) dataType := dataVal.Type() switch { case dataKind == reflect.Int: val.SetFloat(float64(dataVal.Int())) case dataKind == reflect.Uint: val.SetFloat(float64(dataVal.Uint())) case dataKind == reflect.Float32: val.SetFloat(dataVal.Float()) case dataKind == reflect.Bool && d.config.WeaklyTypedInput: if dataVal.Bool() { val.SetFloat(1) } else { val.SetFloat(0) } case dataKind == reflect.String && d.config.WeaklyTypedInput: str := dataVal.String() if str == "" { str = "0" } f, err := strconv.ParseFloat(str, val.Type().Bits()) if err == nil { val.SetFloat(f) } else { return fmt.Errorf("cannot parse '%s' as float: %s", name, err) } case dataType.PkgPath() == "encoding/json" && dataType.Name() == "Number": jn := data.(json.Number) i, err := jn.Float64() if err != nil { return fmt.Errorf( "error decoding json.Number into %s: %s", name, err) } val.SetFloat(i) default: return fmt.Errorf( "'%s' expected type '%s', got unconvertible type '%s', value: '%v'", name, val.Type(), dataVal.Type(), data) } return nil } func (d *Decoder) decodeMap(name string, data interface{}, val reflect.Value) error { valType := val.Type() valKeyType := valType.Key() valElemType := valType.Elem() // By default we overwrite keys in the current map valMap := val // If the map is nil or we're purposely zeroing fields, make a new map if valMap.IsNil() || d.config.ZeroFields { // Make a new map to hold our result mapType := reflect.MapOf(valKeyType, valElemType) valMap = reflect.MakeMap(mapType) } // Check input type and based on the input type jump to the proper func dataVal := reflect.Indirect(reflect.ValueOf(data)) switch dataVal.Kind() { case reflect.Map: return d.decodeMapFromMap(name, dataVal, val, valMap) case reflect.Struct: return d.decodeMapFromStruct(name, dataVal, val, valMap) case reflect.Array, reflect.Slice: if d.config.WeaklyTypedInput { return d.decodeMapFromSlice(name, dataVal, val, valMap) } fallthrough default: return fmt.Errorf("'%s' expected a map, got '%s'", name, dataVal.Kind()) } } func (d *Decoder) decodeMapFromSlice(name string, dataVal reflect.Value, val reflect.Value, valMap reflect.Value) error { // Special case for BC reasons (covered by tests) if dataVal.Len() == 0 { val.Set(valMap) return nil } for i := 0; i < dataVal.Len(); i++ { err := d.decode( name+"["+strconv.Itoa(i)+"]", dataVal.Index(i).Interface(), val) if err != nil { return err } } return nil } func (d *Decoder) decodeMapFromMap(name string, dataVal reflect.Value, val reflect.Value, valMap reflect.Value) error { valType := val.Type() valKeyType := valType.Key() valElemType := valType.Elem() // Accumulate errors errors := make([]string, 0) // If the input data is empty, then we just match what the input data is. if dataVal.Len() == 0 { if dataVal.IsNil() { if !val.IsNil() { val.Set(dataVal) } } else { // Set to empty allocated value val.Set(valMap) } return nil } for _, k := range dataVal.MapKeys() { fieldName := name + "[" + k.String() + "]" // First decode the key into the proper type currentKey := reflect.Indirect(reflect.New(valKeyType)) if err := d.decode(fieldName, k.Interface(), currentKey); err != nil { errors = appendErrors(errors, err) continue } // Next decode the data into the proper type v := dataVal.MapIndex(k).Interface() currentVal := reflect.Indirect(reflect.New(valElemType)) if err := d.decode(fieldName, v, currentVal); err != nil { errors = appendErrors(errors, err) continue } valMap.SetMapIndex(currentKey, currentVal) } // Set the built up map to the value val.Set(valMap) // If we had errors, return those if len(errors) > 0 { return &Error{errors} } return nil } func (d *Decoder) decodeMapFromStruct(name string, dataVal reflect.Value, val reflect.Value, valMap reflect.Value) error { typ := dataVal.Type() for i := 0; i < typ.NumField(); i++ { // Get the StructField first since this is a cheap operation. If the // field is unexported, then ignore it. f := typ.Field(i) if f.PkgPath != "" { continue } // Next get the actual value of this field and verify it is assignable // to the map value. v := dataVal.Field(i) if !v.Type().AssignableTo(valMap.Type().Elem()) { return fmt.Errorf("cannot assign type '%s' to map value field of type '%s'", v.Type(), valMap.Type().Elem()) } tagValue := f.Tag.Get(d.config.TagName) keyName := f.Name if tagValue == "" && d.config.IgnoreUntaggedFields { continue } // If Squash is set in the config, we squash the field down. squash := d.config.Squash && v.Kind() == reflect.Struct && f.Anonymous v = dereferencePtrToStructIfNeeded(v, d.config.TagName) // Determine the name of the key in the map if index := strings.Index(tagValue, ","); index != -1 { if tagValue[:index] == "-" { continue } // If "omitempty" is specified in the tag, it ignores empty values. if strings.Index(tagValue[index+1:], "omitempty") != -1 && isEmptyValue(v) { continue } // If "squash" is specified in the tag, we squash the field down. squash = squash || strings.Index(tagValue[index+1:], "squash") != -1 if squash { // When squashing, the embedded type can be a pointer to a struct. if v.Kind() == reflect.Ptr && v.Elem().Kind() == reflect.Struct { v = v.Elem() } // The final type must be a struct if v.Kind() != reflect.Struct { return fmt.Errorf("cannot squash non-struct type '%s'", v.Type()) } } if keyNameTagValue := tagValue[:index]; keyNameTagValue != "" { keyName = keyNameTagValue } } else if len(tagValue) > 0 { if tagValue == "-" { continue } keyName = tagValue } switch v.Kind() { // this is an embedded struct, so handle it differently case reflect.Struct: x := reflect.New(v.Type()) x.Elem().Set(v) vType := valMap.Type() vKeyType := vType.Key() vElemType := vType.Elem() mType := reflect.MapOf(vKeyType, vElemType) vMap := reflect.MakeMap(mType) // Creating a pointer to a map so that other methods can completely // overwrite the map if need be (looking at you decodeMapFromMap). The // indirection allows the underlying map to be settable (CanSet() == true) // where as reflect.MakeMap returns an unsettable map. addrVal := reflect.New(vMap.Type()) reflect.Indirect(addrVal).Set(vMap) err := d.decode(keyName, x.Interface(), reflect.Indirect(addrVal)) if err != nil { return err } // the underlying map may have been completely overwritten so pull // it indirectly out of the enclosing value. vMap = reflect.Indirect(addrVal) if squash { for _, k := range vMap.MapKeys() { valMap.SetMapIndex(k, vMap.MapIndex(k)) } } else { valMap.SetMapIndex(reflect.ValueOf(keyName), vMap) } default: valMap.SetMapIndex(reflect.ValueOf(keyName), v) } } if val.CanAddr() { val.Set(valMap) } return nil } func (d *Decoder) decodePtr(name string, data interface{}, val reflect.Value) (bool, error) { // If the input data is nil, then we want to just set the output // pointer to be nil as well. isNil := data == nil if !isNil { switch v := reflect.Indirect(reflect.ValueOf(data)); v.Kind() { case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: isNil = v.IsNil() } } if isNil { if !val.IsNil() && val.CanSet() { nilValue := reflect.New(val.Type()).Elem() val.Set(nilValue) } return true, nil } // Create an element of the concrete (non pointer) type and decode // into that. Then set the value of the pointer to this type. valType := val.Type() valElemType := valType.Elem() if val.CanSet() { realVal := val if realVal.IsNil() || d.config.ZeroFields { realVal = reflect.New(valElemType) } if err := d.decode(name, data, reflect.Indirect(realVal)); err != nil { return false, err } val.Set(realVal) } else { if err := d.decode(name, data, reflect.Indirect(val)); err != nil { return false, err } } return false, nil } func (d *Decoder) decodeFunc(name string, data interface{}, val reflect.Value) error { // Create an element of the concrete (non pointer) type and decode // into that. Then set the value of the pointer to this type. dataVal := reflect.Indirect(reflect.ValueOf(data)) if val.Type() != dataVal.Type() { return fmt.Errorf( "'%s' expected type '%s', got unconvertible type '%s', value: '%v'", name, val.Type(), dataVal.Type(), data) } val.Set(dataVal) return nil } func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value) error { dataVal := reflect.Indirect(reflect.ValueOf(data)) dataValKind := dataVal.Kind() valType := val.Type() valElemType := valType.Elem() sliceType := reflect.SliceOf(valElemType) // If we have a non array/slice type then we first attempt to convert. if dataValKind != reflect.Array && dataValKind != reflect.Slice { if d.config.WeaklyTypedInput { switch { // Slice and array we use the normal logic case dataValKind == reflect.Slice, dataValKind == reflect.Array: break // Empty maps turn into empty slices case dataValKind == reflect.Map: if dataVal.Len() == 0 { val.Set(reflect.MakeSlice(sliceType, 0, 0)) return nil } // Create slice of maps of other sizes return d.decodeSlice(name, []interface{}{data}, val) case dataValKind == reflect.String && valElemType.Kind() == reflect.Uint8: return d.decodeSlice(name, []byte(dataVal.String()), val) // All other types we try to convert to the slice type // and "lift" it into it. i.e. a string becomes a string slice. default:
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
true
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/validation/spec/ref.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/validation/spec/ref.go
// Copyright 2015 go-swagger maintainers // // 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 spec import ( "encoding/json" "net/http" "os" "path/filepath" "github.com/go-openapi/jsonreference" "k8s.io/kube-openapi/pkg/internal" ) // Refable is a struct for things that accept a $ref property type Refable struct { Ref Ref } // MarshalJSON marshals the ref to json func (r Refable) MarshalJSON() ([]byte, error) { return r.Ref.MarshalJSON() } // UnmarshalJSON unmarshalss the ref from json func (r *Refable) UnmarshalJSON(d []byte) error { return json.Unmarshal(d, &r.Ref) } // Ref represents a json reference that is potentially resolved type Ref struct { jsonreference.Ref } // RemoteURI gets the remote uri part of the ref func (r *Ref) RemoteURI() string { if r.String() == "" { return r.String() } u := *r.GetURL() u.Fragment = "" return u.String() } // IsValidURI returns true when the url the ref points to can be found func (r *Ref) IsValidURI(basepaths ...string) bool { if r.String() == "" { return true } v := r.RemoteURI() if v == "" { return true } if r.HasFullURL { rr, err := http.Get(v) if err != nil { return false } return rr.StatusCode/100 == 2 } if !(r.HasFileScheme || r.HasFullFilePath || r.HasURLPathOnly) { return false } // check for local file pth := v if r.HasURLPathOnly { base := "." if len(basepaths) > 0 { base = filepath.Dir(filepath.Join(basepaths...)) } p, e := filepath.Abs(filepath.ToSlash(filepath.Join(base, pth))) if e != nil { return false } pth = p } fi, err := os.Stat(filepath.ToSlash(pth)) if err != nil { return false } return !fi.IsDir() } // Inherits creates a new reference from a parent and a child // If the child cannot inherit from the parent, an error is returned func (r *Ref) Inherits(child Ref) (*Ref, error) { ref, err := r.Ref.Inherits(child.Ref) if err != nil { return nil, err } return &Ref{Ref: *ref}, nil } // NewRef creates a new instance of a ref object // returns an error when the reference uri is an invalid uri func NewRef(refURI string) (Ref, error) { ref, err := jsonreference.New(refURI) if err != nil { return Ref{}, err } return Ref{Ref: ref}, nil } // MustCreateRef creates a ref object but panics when refURI is invalid. // Use the NewRef method for a version that returns an error. func MustCreateRef(refURI string) Ref { return Ref{Ref: jsonreference.MustCreateRef(refURI)} } // MarshalJSON marshals this ref into a JSON object func (r Ref) MarshalJSON() ([]byte, error) { str := r.String() if str == "" { if r.IsRoot() { return []byte(`{"$ref":""}`), nil } return []byte("{}"), nil } v := map[string]interface{}{"$ref": str} return json.Marshal(v) } // UnmarshalJSON unmarshals this ref from a JSON object func (r *Ref) UnmarshalJSON(d []byte) error { var v map[string]interface{} if err := json.Unmarshal(d, &v); err != nil { return err } return r.fromMap(v) } func (r *Ref) fromMap(v map[string]interface{}) error { return internal.JSONRefFromMap(&r.Ref, v) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/validation/spec/items.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/validation/spec/items.go
// Copyright 2015 go-swagger maintainers // // 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 spec import ( "encoding/json" "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" ) const ( jsonRef = "$ref" ) // SimpleSchema describe swagger simple schemas for parameters and headers type SimpleSchema struct { Type string `json:"type,omitempty"` Nullable bool `json:"nullable,omitempty"` Format string `json:"format,omitempty"` Items *Items `json:"items,omitempty"` CollectionFormat string `json:"collectionFormat,omitempty"` Default interface{} `json:"default,omitempty"` Example interface{} `json:"example,omitempty"` } // Marshaling structure only, always edit along with corresponding // struct (or compilation will fail). type simpleSchemaOmitZero struct { Type string `json:"type,omitempty"` Nullable bool `json:"nullable,omitzero"` Format string `json:"format,omitempty"` Items *Items `json:"items,omitzero"` CollectionFormat string `json:"collectionFormat,omitempty"` Default interface{} `json:"default,omitempty"` Example interface{} `json:"example,omitempty"` } // CommonValidations describe common JSON-schema validations type CommonValidations struct { Maximum *float64 `json:"maximum,omitempty"` ExclusiveMaximum bool `json:"exclusiveMaximum,omitempty"` Minimum *float64 `json:"minimum,omitempty"` ExclusiveMinimum bool `json:"exclusiveMinimum,omitempty"` MaxLength *int64 `json:"maxLength,omitempty"` MinLength *int64 `json:"minLength,omitempty"` Pattern string `json:"pattern,omitempty"` MaxItems *int64 `json:"maxItems,omitempty"` MinItems *int64 `json:"minItems,omitempty"` UniqueItems bool `json:"uniqueItems,omitempty"` MultipleOf *float64 `json:"multipleOf,omitempty"` Enum []interface{} `json:"enum,omitempty"` } // Marshaling structure only, always edit along with corresponding // struct (or compilation will fail). type commonValidationsOmitZero struct { Maximum *float64 `json:"maximum,omitempty"` ExclusiveMaximum bool `json:"exclusiveMaximum,omitzero"` Minimum *float64 `json:"minimum,omitempty"` ExclusiveMinimum bool `json:"exclusiveMinimum,omitzero"` MaxLength *int64 `json:"maxLength,omitempty"` MinLength *int64 `json:"minLength,omitempty"` Pattern string `json:"pattern,omitempty"` MaxItems *int64 `json:"maxItems,omitempty"` MinItems *int64 `json:"minItems,omitempty"` UniqueItems bool `json:"uniqueItems,omitzero"` MultipleOf *float64 `json:"multipleOf,omitempty"` Enum []interface{} `json:"enum,omitempty"` } // Items a limited subset of JSON-Schema's items object. // It is used by parameter definitions that are not located in "body". // // For more information: http://goo.gl/8us55a#items-object type Items struct { Refable CommonValidations SimpleSchema VendorExtensible } // UnmarshalJSON hydrates this items instance with the data from JSON func (i *Items) UnmarshalJSON(data []byte) error { if internal.UseOptimizedJSONUnmarshaling { return jsonv2.Unmarshal(data, i) } var validations CommonValidations if err := json.Unmarshal(data, &validations); err != nil { return err } var ref Refable if err := json.Unmarshal(data, &ref); err != nil { return err } var simpleSchema SimpleSchema if err := json.Unmarshal(data, &simpleSchema); err != nil { return err } var vendorExtensible VendorExtensible if err := json.Unmarshal(data, &vendorExtensible); err != nil { return err } i.Refable = ref i.CommonValidations = validations i.SimpleSchema = simpleSchema i.VendorExtensible = vendorExtensible return nil } func (i *Items) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { var x struct { CommonValidations SimpleSchema Extensions } if err := opts.UnmarshalNext(dec, &x); err != nil { return err } if err := i.Refable.Ref.fromMap(x.Extensions); err != nil { return err } i.CommonValidations = x.CommonValidations i.SimpleSchema = x.SimpleSchema i.Extensions = internal.SanitizeExtensions(x.Extensions) return nil } // MarshalJSON converts this items object to JSON func (i Items) MarshalJSON() ([]byte, error) { if internal.UseOptimizedJSONMarshaling { return internal.DeterministicMarshal(i) } b1, err := json.Marshal(i.CommonValidations) if err != nil { return nil, err } b2, err := json.Marshal(i.SimpleSchema) if err != nil { return nil, err } b3, err := json.Marshal(i.Refable) if err != nil { return nil, err } b4, err := json.Marshal(i.VendorExtensible) if err != nil { return nil, err } return swag.ConcatJSON(b4, b3, b1, b2), nil } func (i Items) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { var x struct { CommonValidations commonValidationsOmitZero `json:",inline"` SimpleSchema simpleSchemaOmitZero `json:",inline"` Ref string `json:"$ref,omitempty"` Extensions } x.CommonValidations = commonValidationsOmitZero(i.CommonValidations) x.SimpleSchema = simpleSchemaOmitZero(i.SimpleSchema) x.Ref = i.Refable.Ref.String() x.Extensions = internal.SanitizeExtensions(i.Extensions) return opts.MarshalNext(enc, x) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/validation/spec/response.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/validation/spec/response.go
// Copyright 2015 go-swagger maintainers // // 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 spec import ( "encoding/json" "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" ) // ResponseProps properties specific to a response type ResponseProps struct { Description string `json:"description,omitempty"` Schema *Schema `json:"schema,omitempty"` Headers map[string]Header `json:"headers,omitempty"` Examples map[string]interface{} `json:"examples,omitempty"` } // Marshaling structure only, always edit along with corresponding // struct (or compilation will fail). type responsePropsOmitZero struct { Description string `json:"description,omitempty"` Schema *Schema `json:"schema,omitzero"` Headers map[string]Header `json:"headers,omitempty"` Examples map[string]interface{} `json:"examples,omitempty"` } // Response describes a single response from an API Operation. // // For more information: http://goo.gl/8us55a#responseObject type Response struct { Refable ResponseProps VendorExtensible } // UnmarshalJSON hydrates this items instance with the data from JSON func (r *Response) UnmarshalJSON(data []byte) error { if internal.UseOptimizedJSONUnmarshaling { return jsonv2.Unmarshal(data, r) } if err := json.Unmarshal(data, &r.ResponseProps); err != nil { return err } if err := json.Unmarshal(data, &r.Refable); err != nil { return err } if err := json.Unmarshal(data, &r.VendorExtensible); err != nil { return err } return nil } func (r *Response) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { var x struct { ResponseProps Extensions } if err := opts.UnmarshalNext(dec, &x); err != nil { return err } if err := r.Refable.Ref.fromMap(x.Extensions); err != nil { return err } r.Extensions = internal.SanitizeExtensions(x.Extensions) r.ResponseProps = x.ResponseProps return nil } // MarshalJSON converts this items object to JSON func (r Response) MarshalJSON() ([]byte, error) { if internal.UseOptimizedJSONMarshaling { return internal.DeterministicMarshal(r) } b1, err := json.Marshal(r.ResponseProps) if err != nil { return nil, err } b2, err := json.Marshal(r.Refable) if err != nil { return nil, err } b3, err := json.Marshal(r.VendorExtensible) if err != nil { return nil, err } return swag.ConcatJSON(b1, b2, b3), nil } func (r Response) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { var x struct { Ref string `json:"$ref,omitempty"` Extensions ResponseProps responsePropsOmitZero `json:",inline"` } x.Ref = r.Refable.Ref.String() x.Extensions = internal.SanitizeExtensions(r.Extensions) x.ResponseProps = responsePropsOmitZero(r.ResponseProps) return opts.MarshalNext(enc, x) } // NewResponse creates a new response instance func NewResponse() *Response { return new(Response) } // ResponseRef creates a response as a json reference func ResponseRef(url string) *Response { resp := NewResponse() resp.Ref = MustCreateRef(url) return resp }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/validation/spec/contact_info.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/validation/spec/contact_info.go
// Copyright 2015 go-swagger maintainers // // 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 spec // ContactInfo contact information for the exposed API. // // For more information: http://goo.gl/8us55a#contactObject type ContactInfo struct { Name string `json:"name,omitempty"` URL string `json:"url,omitempty"` Email string `json:"email,omitempty"` }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/validation/spec/path_item.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/validation/spec/path_item.go
// Copyright 2015 go-swagger maintainers // // 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 spec import ( "encoding/json" "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" ) // PathItemProps the path item specific properties type PathItemProps struct { Get *Operation `json:"get,omitempty"` Put *Operation `json:"put,omitempty"` Post *Operation `json:"post,omitempty"` Delete *Operation `json:"delete,omitempty"` Options *Operation `json:"options,omitempty"` Head *Operation `json:"head,omitempty"` Patch *Operation `json:"patch,omitempty"` Parameters []Parameter `json:"parameters,omitempty"` } // PathItem describes the operations available on a single path. // A Path Item may be empty, due to [ACL constraints](http://goo.gl/8us55a#securityFiltering). // The path itself is still exposed to the documentation viewer but they will // not know which operations and parameters are available. // // For more information: http://goo.gl/8us55a#pathItemObject type PathItem struct { Refable VendorExtensible PathItemProps } // UnmarshalJSON hydrates this items instance with the data from JSON func (p *PathItem) UnmarshalJSON(data []byte) error { if internal.UseOptimizedJSONUnmarshaling { return jsonv2.Unmarshal(data, p) } if err := json.Unmarshal(data, &p.Refable); err != nil { return err } if err := json.Unmarshal(data, &p.VendorExtensible); err != nil { return err } return json.Unmarshal(data, &p.PathItemProps) } func (p *PathItem) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { var x struct { Extensions PathItemProps } if err := opts.UnmarshalNext(dec, &x); err != nil { return err } if err := p.Refable.Ref.fromMap(x.Extensions); err != nil { return err } p.Extensions = internal.SanitizeExtensions(x.Extensions) p.PathItemProps = x.PathItemProps return nil } // MarshalJSON converts this items object to JSON func (p PathItem) MarshalJSON() ([]byte, error) { if internal.UseOptimizedJSONMarshaling { return internal.DeterministicMarshal(p) } b3, err := json.Marshal(p.Refable) if err != nil { return nil, err } b4, err := json.Marshal(p.VendorExtensible) if err != nil { return nil, err } b5, err := json.Marshal(p.PathItemProps) if err != nil { return nil, err } concated := swag.ConcatJSON(b3, b4, b5) return concated, nil } func (p PathItem) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { var x struct { Ref string `json:"$ref,omitempty"` Extensions PathItemProps } x.Ref = p.Refable.Ref.String() x.Extensions = internal.SanitizeExtensions(p.Extensions) x.PathItemProps = p.PathItemProps return opts.MarshalNext(enc, x) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/validation/spec/gnostic.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/validation/spec/gnostic.go
/* Copyright 2022 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 spec import ( "errors" "strconv" "github.com/go-openapi/jsonreference" openapi_v2 "github.com/google/gnostic-models/openapiv2" ) // Interfaces type GnosticCommonValidations interface { GetMaximum() float64 GetExclusiveMaximum() bool GetMinimum() float64 GetExclusiveMinimum() bool GetMaxLength() int64 GetMinLength() int64 GetPattern() string GetMaxItems() int64 GetMinItems() int64 GetUniqueItems() bool GetMultipleOf() float64 GetEnum() []*openapi_v2.Any } func (k *CommonValidations) FromGnostic(g GnosticCommonValidations) error { if g == nil { return nil } max := g.GetMaximum() if max != 0 { k.Maximum = &max } k.ExclusiveMaximum = g.GetExclusiveMaximum() min := g.GetMinimum() if min != 0 { k.Minimum = &min } k.ExclusiveMinimum = g.GetExclusiveMinimum() maxLen := g.GetMaxLength() if maxLen != 0 { k.MaxLength = &maxLen } minLen := g.GetMinLength() if minLen != 0 { k.MinLength = &minLen } k.Pattern = g.GetPattern() maxItems := g.GetMaxItems() if maxItems != 0 { k.MaxItems = &maxItems } minItems := g.GetMinItems() if minItems != 0 { k.MinItems = &minItems } k.UniqueItems = g.GetUniqueItems() multOf := g.GetMultipleOf() if multOf != 0 { k.MultipleOf = &multOf } enums := g.GetEnum() if enums != nil { k.Enum = make([]interface{}, len(enums)) for i, v := range enums { if v == nil { continue } var convert interface{} if err := v.ToRawInfo().Decode(&convert); err != nil { return err } else { k.Enum[i] = convert } } } return nil } type GnosticSimpleSchema interface { GetType() string GetFormat() string GetItems() *openapi_v2.PrimitivesItems GetCollectionFormat() string GetDefault() *openapi_v2.Any } func (k *SimpleSchema) FromGnostic(g GnosticSimpleSchema) error { if g == nil { return nil } k.Type = g.GetType() k.Format = g.GetFormat() k.CollectionFormat = g.GetCollectionFormat() items := g.GetItems() if items != nil { k.Items = &Items{} if err := k.Items.FromGnostic(items); err != nil { return err } } def := g.GetDefault() if def != nil { var convert interface{} if err := def.ToRawInfo().Decode(&convert); err != nil { return err } else { k.Default = convert } } return nil } func (k *Items) FromGnostic(g *openapi_v2.PrimitivesItems) error { if g == nil { return nil } if err := k.SimpleSchema.FromGnostic(g); err != nil { return err } if err := k.CommonValidations.FromGnostic(g); err != nil { return err } if err := k.VendorExtensible.FromGnostic(g.VendorExtension); err != nil { return err } return nil } func (k *VendorExtensible) FromGnostic(g []*openapi_v2.NamedAny) error { if len(g) == 0 { return nil } k.Extensions = make(Extensions, len(g)) for _, v := range g { if v == nil { continue } if v.Value == nil { k.Extensions[v.Name] = nil continue } var iface interface{} if err := v.Value.ToRawInfo().Decode(&iface); err != nil { return err } else { k.Extensions[v.Name] = iface } } return nil } func (k *Refable) FromGnostic(g string) error { return k.Ref.FromGnostic(g) } func (k *Ref) FromGnostic(g string) error { if g == "" { return nil } ref, err := jsonreference.New(g) if err != nil { return err } *k = Ref{ Ref: ref, } return nil } // Converts a gnostic v2 Document to a kube-openapi Swagger Document // // Caveats: // // - gnostic v2 documents treats zero as unspecified for numerical fields of // CommonValidations fields such as Maximum, Minimum, MaximumItems, etc. // There will always be data loss if one of the values of these fields is set to zero. // // Returns: // // - `ok`: `false` if a value was present in the gnostic document which cannot be // roundtripped into kube-openapi types. In these instances, `ok` is set to // `false` and the value is skipped. // // - `err`: an unexpected error occurred in the conversion from the gnostic type // to kube-openapi type. func (k *Swagger) FromGnostic(g *openapi_v2.Document) (ok bool, err error) { ok = true if g == nil { return true, nil } if err := k.VendorExtensible.FromGnostic(g.VendorExtension); err != nil { return false, err } if nok, err := k.SwaggerProps.FromGnostic(g); err != nil { return false, err } else if !nok { ok = false } return ok, nil } func (k *SwaggerProps) FromGnostic(g *openapi_v2.Document) (ok bool, err error) { if g == nil { return true, nil } ok = true // openapi_v2.Document does not support "ID" field, so it will not be // included k.Consumes = g.Consumes k.Produces = g.Produces k.Schemes = g.Schemes k.Swagger = g.Swagger if g.Info != nil { k.Info = &Info{} if nok, err := k.Info.FromGnostic(g.Info); err != nil { return false, err } else if !nok { ok = false } } k.Host = g.Host k.BasePath = g.BasePath if g.Paths != nil { k.Paths = &Paths{} if nok, err := k.Paths.FromGnostic(g.Paths); err != nil { return false, err } else if !nok { ok = false } } if g.Definitions != nil { k.Definitions = make(Definitions, len(g.Definitions.AdditionalProperties)) for _, v := range g.Definitions.AdditionalProperties { if v == nil { continue } converted := Schema{} if nok, err := converted.FromGnostic(v.Value); err != nil { return false, err } else if !nok { ok = false } k.Definitions[v.Name] = converted } } if g.Parameters != nil { k.Parameters = make( map[string]Parameter, len(g.Parameters.AdditionalProperties)) for _, v := range g.Parameters.AdditionalProperties { if v == nil { continue } p := Parameter{} if nok, err := p.FromGnostic(v.Value); err != nil { return false, err } else if !nok { ok = false } k.Parameters[v.Name] = p } } if g.Responses != nil { k.Responses = make( map[string]Response, len(g.Responses.AdditionalProperties)) for _, v := range g.Responses.AdditionalProperties { if v == nil { continue } p := Response{} if nok, err := p.FromGnostic(v.Value); err != nil { return false, err } else if !nok { ok = false } k.Responses[v.Name] = p } } if g.SecurityDefinitions != nil { k.SecurityDefinitions = make(SecurityDefinitions) if err := k.SecurityDefinitions.FromGnostic(g.SecurityDefinitions); err != nil { return false, err } } if g.Security != nil { k.Security = make([]map[string][]string, len(g.Security)) for i, v := range g.Security { if v == nil || v.AdditionalProperties == nil { continue } k.Security[i] = make(map[string][]string, len(v.AdditionalProperties)) converted := k.Security[i] for _, p := range v.AdditionalProperties { if p == nil { continue } if p.Value != nil { converted[p.Name] = p.Value.Value } else { converted[p.Name] = nil } } } } if g.Tags != nil { k.Tags = make([]Tag, len(g.Tags)) for i, v := range g.Tags { if v == nil { continue } else if nok, err := k.Tags[i].FromGnostic(v); err != nil { return false, err } else if !nok { ok = false } } } if g.ExternalDocs != nil { k.ExternalDocs = &ExternalDocumentation{} if nok, err := k.ExternalDocs.FromGnostic(g.ExternalDocs); err != nil { return false, err } else if !nok { ok = false } } return ok, nil } // Info func (k *Info) FromGnostic(g *openapi_v2.Info) (ok bool, err error) { ok = true if g == nil { return true, nil } if err := k.VendorExtensible.FromGnostic(g.VendorExtension); err != nil { return false, err } if nok, err := k.InfoProps.FromGnostic(g); err != nil { return false, err } else if !nok { ok = false } return ok, nil } func (k *InfoProps) FromGnostic(g *openapi_v2.Info) (ok bool, err error) { if g == nil { return true, nil } ok = true k.Description = g.Description k.Title = g.Title k.TermsOfService = g.TermsOfService if g.Contact != nil { k.Contact = &ContactInfo{} if nok, err := k.Contact.FromGnostic(g.Contact); err != nil { return false, err } else if !nok { ok = false } } if g.License != nil { k.License = &License{} if nok, err := k.License.FromGnostic(g.License); err != nil { return false, err } else if !nok { ok = false } } k.Version = g.Version return ok, nil } func (k *License) FromGnostic(g *openapi_v2.License) (ok bool, err error) { if g == nil { return true, nil } ok = true k.Name = g.Name k.URL = g.Url // License does not embed to VendorExtensible! // data loss from g.VendorExtension if len(g.VendorExtension) != 0 { ok = false } return ok, nil } func (k *ContactInfo) FromGnostic(g *openapi_v2.Contact) (ok bool, err error) { if g == nil { return true, nil } ok = true k.Name = g.Name k.URL = g.Url k.Email = g.Email // ContactInfo does not embed to VendorExtensible! // data loss from g.VendorExtension if len(g.VendorExtension) != 0 { ok = false } return ok, nil } // Paths func (k *Paths) FromGnostic(g *openapi_v2.Paths) (ok bool, err error) { if g == nil { return true, nil } ok = true if g.Path != nil { k.Paths = make(map[string]PathItem, len(g.Path)) for _, v := range g.Path { if v == nil { continue } converted := PathItem{} if nok, err := converted.FromGnostic(v.Value); err != nil { return false, err } else if !nok { ok = false } k.Paths[v.Name] = converted } } if err := k.VendorExtensible.FromGnostic(g.VendorExtension); err != nil { return false, err } return ok, nil } func (k *PathItem) FromGnostic(g *openapi_v2.PathItem) (ok bool, err error) { if g == nil { return true, nil } ok = true if nok, err := k.PathItemProps.FromGnostic(g); err != nil { return false, err } else if !nok { ok = false } if err := k.Refable.FromGnostic(g.XRef); err != nil { return false, err } if err := k.VendorExtensible.FromGnostic(g.VendorExtension); err != nil { return false, err } return ok, nil } func (k *PathItemProps) FromGnostic(g *openapi_v2.PathItem) (ok bool, err error) { if g == nil { return true, nil } ok = true if g.Get != nil { k.Get = &Operation{} if nok, err := k.Get.FromGnostic(g.Get); err != nil { return false, err } else if !nok { ok = false } } if g.Put != nil { k.Put = &Operation{} if nok, err := k.Put.FromGnostic(g.Put); err != nil { return false, err } else if !nok { ok = false } } if g.Post != nil { k.Post = &Operation{} if nok, err := k.Post.FromGnostic(g.Post); err != nil { return false, err } else if !nok { ok = false } } if g.Delete != nil { k.Delete = &Operation{} if nok, err := k.Delete.FromGnostic(g.Delete); err != nil { return false, err } else if !nok { ok = false } } if g.Options != nil { k.Options = &Operation{} if nok, err := k.Options.FromGnostic(g.Options); err != nil { return false, err } else if !nok { ok = false } } if g.Head != nil { k.Head = &Operation{} if nok, err := k.Head.FromGnostic(g.Head); err != nil { return false, err } else if !nok { ok = false } } if g.Patch != nil { k.Patch = &Operation{} if nok, err := k.Patch.FromGnostic(g.Patch); err != nil { return false, err } else if !nok { ok = false } } if g.Parameters != nil { k.Parameters = make([]Parameter, len(g.Parameters)) for i, v := range g.Parameters { if v == nil { continue } else if nok, err := k.Parameters[i].FromGnosticParametersItem(v); err != nil { return false, err } else if !nok { ok = false } } } return ok, nil } func (k *Operation) FromGnostic(g *openapi_v2.Operation) (ok bool, err error) { if g == nil { return true, nil } ok = true if err := k.VendorExtensible.FromGnostic(g.VendorExtension); err != nil { return false, err } if nok, err := k.OperationProps.FromGnostic(g); err != nil { return false, err } else if !nok { ok = false } return ok, nil } func (k *OperationProps) FromGnostic(g *openapi_v2.Operation) (ok bool, err error) { if g == nil { return true, nil } ok = true k.Description = g.Description k.Consumes = g.Consumes k.Produces = g.Produces k.Schemes = g.Schemes k.Tags = g.Tags k.Summary = g.Summary if g.ExternalDocs != nil { k.ExternalDocs = &ExternalDocumentation{} if nok, err := k.ExternalDocs.FromGnostic(g.ExternalDocs); err != nil { return false, err } else if !nok { ok = false } } k.ID = g.OperationId k.Deprecated = g.Deprecated if g.Security != nil { k.Security = make([]map[string][]string, len(g.Security)) for i, v := range g.Security { if v == nil || v.AdditionalProperties == nil { continue } k.Security[i] = make(map[string][]string, len(v.AdditionalProperties)) converted := k.Security[i] for _, p := range v.AdditionalProperties { if p == nil { continue } if p.Value != nil { converted[p.Name] = p.Value.Value } else { converted[p.Name] = nil } } } } if g.Parameters != nil { k.Parameters = make([]Parameter, len(g.Parameters)) for i, v := range g.Parameters { if v == nil { continue } else if nok, err := k.Parameters[i].FromGnosticParametersItem(v); err != nil { return false, err } else if !nok { ok = false } } } if g.Responses != nil { k.Responses = &Responses{} if nok, err := k.Responses.FromGnostic(g.Responses); err != nil { return false, err } else if !nok { ok = false } } return ok, nil } // Responses func (k *Responses) FromGnostic(g *openapi_v2.Responses) (ok bool, err error) { if g == nil { return true, nil } ok = true if err := k.VendorExtensible.FromGnostic(g.VendorExtension); err != nil { return false, err } if nok, err := k.ResponsesProps.FromGnostic(g); err != nil { return false, err } else if !nok { ok = false } return ok, nil } func (k *ResponsesProps) FromGnostic(g *openapi_v2.Responses) (ok bool, err error) { if g == nil { return true, nil } else if g.ResponseCode == nil { return ok, nil } ok = true for _, v := range g.ResponseCode { if v == nil { continue } if v.Name == "default" { k.Default = &Response{} if nok, err := k.Default.FromGnosticResponseValue(v.Value); err != nil { return false, err } else if !nok { ok = false } } else if nk, err := strconv.Atoi(v.Name); err != nil { // This should actually never fail, unless gnostic struct was // manually/purposefully tampered with at runtime. // Gnostic's ParseDocument validates that all StatusCodeResponses // keys adhere to the following regex ^([0-9]{3})$|^(default)$ ok = false } else { if k.StatusCodeResponses == nil { k.StatusCodeResponses = map[int]Response{} } res := Response{} if nok, err := res.FromGnosticResponseValue(v.Value); err != nil { return false, err } else if !nok { ok = false } k.StatusCodeResponses[nk] = res } } return ok, nil } func (k *Response) FromGnostic(g *openapi_v2.Response) (ok bool, err error) { if g == nil { return true, nil } ok = true // Refable case handled in FromGnosticResponseValue if err := k.VendorExtensible.FromGnostic(g.VendorExtension); err != nil { return false, err } if nok, err := k.ResponseProps.FromGnostic(g); err != nil { return false, err } else if !nok { ok = false } return ok, nil } func (k *Response) FromGnosticResponseValue(g *openapi_v2.ResponseValue) (ok bool, err error) { ok = true if ref := g.GetJsonReference(); ref != nil { k.Description = ref.Description if err := k.Refable.FromGnostic(ref.XRef); err != nil { return false, err } } else if nok, err := k.FromGnostic(g.GetResponse()); err != nil { return false, err } else if !nok { ok = false } return ok, nil } func (k *ResponseProps) FromGnostic(g *openapi_v2.Response) (ok bool, err error) { if g == nil { return true, nil } ok = true k.Description = g.Description if g.Schema != nil { k.Schema = &Schema{} if nok, err := k.Schema.FromGnosticSchemaItem(g.Schema); err != nil { return false, err } else if !nok { ok = false } } if g.Headers != nil { k.Headers = make(map[string]Header, len(g.Headers.AdditionalProperties)) for _, v := range g.Headers.AdditionalProperties { if v == nil { continue } converted := Header{} if err := converted.FromGnostic(v.GetValue()); err != nil { return false, err } k.Headers[v.Name] = converted } } if g.Examples != nil { k.Examples = make(map[string]interface{}, len(g.Examples.AdditionalProperties)) for _, v := range g.Examples.AdditionalProperties { if v == nil { continue } else if v.Value == nil { k.Examples[v.Name] = nil continue } var iface interface{} if err := v.Value.ToRawInfo().Decode(&iface); err != nil { return false, err } else { k.Examples[v.Name] = iface } } } return ok, nil } // Header func (k *Header) FromGnostic(g *openapi_v2.Header) (err error) { if g == nil { return nil } if err := k.CommonValidations.FromGnostic(g); err != nil { return err } if err := k.VendorExtensible.FromGnostic(g.VendorExtension); err != nil { return err } if err := k.SimpleSchema.FromGnostic(g); err != nil { return err } if err := k.HeaderProps.FromGnostic(g); err != nil { return err } return nil } func (k *HeaderProps) FromGnostic(g *openapi_v2.Header) error { if g == nil { return nil } // All other fields of openapi_v2.Header are handled by // the embeded fields, commonvalidations, etc. k.Description = g.Description return nil } // Parameters func (k *Parameter) FromGnostic(g *openapi_v2.Parameter) (ok bool, err error) { if g == nil { return true, nil } ok = true switch p := g.Oneof.(type) { case *openapi_v2.Parameter_BodyParameter: if nok, err := k.ParamProps.FromGnostic(p.BodyParameter); err != nil { return false, err } else if !nok { ok = false } if err := k.VendorExtensible.FromGnostic(p.BodyParameter.GetVendorExtension()); err != nil { return false, err } return ok, nil case *openapi_v2.Parameter_NonBodyParameter: switch nb := g.GetNonBodyParameter().Oneof.(type) { case *openapi_v2.NonBodyParameter_HeaderParameterSubSchema: if nok, err := k.ParamProps.FromGnostic(nb.HeaderParameterSubSchema); err != nil { return false, err } else if !nok { ok = false } if err := k.SimpleSchema.FromGnostic(nb.HeaderParameterSubSchema); err != nil { return false, err } if err := k.CommonValidations.FromGnostic(nb.HeaderParameterSubSchema); err != nil { return false, err } if err := k.VendorExtensible.FromGnostic(nb.HeaderParameterSubSchema.GetVendorExtension()); err != nil { return false, err } return ok, nil case *openapi_v2.NonBodyParameter_FormDataParameterSubSchema: if nok, err := k.ParamProps.FromGnostic(nb.FormDataParameterSubSchema); err != nil { return false, err } else if !nok { ok = false } if err := k.SimpleSchema.FromGnostic(nb.FormDataParameterSubSchema); err != nil { return false, err } if err := k.CommonValidations.FromGnostic(nb.FormDataParameterSubSchema); err != nil { return false, err } if err := k.VendorExtensible.FromGnostic(nb.FormDataParameterSubSchema.GetVendorExtension()); err != nil { return false, err } return ok, nil case *openapi_v2.NonBodyParameter_QueryParameterSubSchema: if nok, err := k.ParamProps.FromGnostic(nb.QueryParameterSubSchema); err != nil { return false, err } else if !nok { ok = false } if err := k.SimpleSchema.FromGnostic(nb.QueryParameterSubSchema); err != nil { return false, err } if err := k.CommonValidations.FromGnostic(nb.QueryParameterSubSchema); err != nil { return false, err } if err := k.VendorExtensible.FromGnostic(nb.QueryParameterSubSchema.GetVendorExtension()); err != nil { return false, err } return ok, nil case *openapi_v2.NonBodyParameter_PathParameterSubSchema: if nok, err := k.ParamProps.FromGnostic(nb.PathParameterSubSchema); err != nil { return false, err } else if !nok { ok = false } if err := k.SimpleSchema.FromGnostic(nb.PathParameterSubSchema); err != nil { return false, err } if err := k.CommonValidations.FromGnostic(nb.PathParameterSubSchema); err != nil { return false, err } if err := k.VendorExtensible.FromGnostic(nb.PathParameterSubSchema.GetVendorExtension()); err != nil { return false, err } return ok, nil default: return false, errors.New("unrecognized nonbody type for Parameter") } default: return false, errors.New("unrecognized type for Parameter") } } type GnosticCommonParamProps interface { GetName() string GetRequired() bool GetIn() string GetDescription() string } type GnosticCommonParamPropsBodyParameter interface { GetSchema() *openapi_v2.Schema } type GnosticCommonParamPropsFormData interface { GetAllowEmptyValue() bool } func (k *ParamProps) FromGnostic(g GnosticCommonParamProps) (ok bool, err error) { ok = true k.Description = g.GetDescription() k.In = g.GetIn() k.Name = g.GetName() k.Required = g.GetRequired() if formDataParameter, success := g.(GnosticCommonParamPropsFormData); success { k.AllowEmptyValue = formDataParameter.GetAllowEmptyValue() } if bodyParameter, success := g.(GnosticCommonParamPropsBodyParameter); success { if bodyParameter.GetSchema() != nil { k.Schema = &Schema{} if nok, err := k.Schema.FromGnostic(bodyParameter.GetSchema()); err != nil { return false, err } else if !nok { ok = false } } } return ok, nil } // PB types use a different structure than we do for "refable". For PB, there is // a wrappign oneof type that could be a ref or the type func (k *Parameter) FromGnosticParametersItem(g *openapi_v2.ParametersItem) (ok bool, err error) { if g == nil { return true, nil } ok = true if ref := g.GetJsonReference(); ref != nil { k.Description = ref.Description if err := k.Refable.FromGnostic(ref.XRef); err != nil { return false, err } } else if nok, err := k.FromGnostic(g.GetParameter()); err != nil { return false, err } else if !nok { ok = false } return ok, nil } // Schema func (k *Schema) FromGnostic(g *openapi_v2.Schema) (ok bool, err error) { if g == nil { return true, nil } ok = true if err := k.VendorExtensible.FromGnostic(g.VendorExtension); err != nil { return false, err } // SwaggerSchemaProps k.Discriminator = g.Discriminator k.ReadOnly = g.ReadOnly k.Description = g.Description if g.ExternalDocs != nil { k.ExternalDocs = &ExternalDocumentation{} if nok, err := k.ExternalDocs.FromGnostic(g.ExternalDocs); err != nil { return false, err } else if !nok { ok = false } } if g.Example != nil { if err := g.Example.ToRawInfo().Decode(&k.Example); err != nil { return false, err } } // SchemaProps if err := k.Ref.FromGnostic(g.XRef); err != nil { return false, err } k.Type = g.Type.GetValue() k.Format = g.GetFormat() k.Title = g.GetTitle() // These below fields are not available in gnostic types, so will never // be populated. This means roundtrips which make use of these // (non-official, kube-only) fields will lose information. // // Schema.ID is not available in official spec // Schema.$schema // Schema.Nullable - in openapiv3, not v2 // Schema.AnyOf - in openapiv3, not v2 // Schema.OneOf - in openapiv3, not v2 // Schema.Not - in openapiv3, not v2 // Schema.PatternProperties - in openapiv3, not v2 // Schema.Dependencies - in openapiv3, not v2 // Schema.AdditionalItems // Schema.Definitions - not part of spec // Schema.ExtraProps - gnostic parser rejects any keys it does not recognize if g.GetDefault() != nil { if err := g.GetDefault().ToRawInfo().Decode(&k.Default); err != nil { return false, err } } // These conditionals (!= 0) follow gnostic's logic for ToRawInfo // The keys in gnostic source are only included if nonzero. if g.Maximum != 0.0 { k.Maximum = &g.Maximum } if g.Minimum != 0.0 { k.Minimum = &g.Minimum } k.ExclusiveMaximum = g.ExclusiveMaximum k.ExclusiveMinimum = g.ExclusiveMinimum if g.MaxLength != 0 { k.MaxLength = &g.MaxLength } if g.MinLength != 0 { k.MinLength = &g.MinLength } k.Pattern = g.GetPattern() if g.MaxItems != 0 { k.MaxItems = &g.MaxItems } if g.MinItems != 0 { k.MinItems = &g.MinItems } k.UniqueItems = g.UniqueItems if g.MultipleOf != 0 { k.MultipleOf = &g.MultipleOf } for _, v := range g.GetEnum() { if v == nil { continue } var convert interface{} if err := v.ToRawInfo().Decode(&convert); err != nil { return false, err } k.Enum = append(k.Enum, convert) } if g.MaxProperties != 0 { k.MaxProperties = &g.MaxProperties } if g.MinProperties != 0 { k.MinProperties = &g.MinProperties } k.Required = g.Required if g.GetItems() != nil { k.Items = &SchemaOrArray{} for _, v := range g.Items.GetSchema() { if v == nil { continue } schema := Schema{} if nok, err := schema.FromGnostic(v); err != nil { return false, err } else if !nok { ok = false } k.Items.Schemas = append(k.Items.Schemas, schema) } if len(k.Items.Schemas) == 1 { k.Items.Schema = &k.Items.Schemas[0] k.Items.Schemas = nil } } for i, v := range g.GetAllOf() { if v == nil { continue } k.AllOf = append(k.AllOf, Schema{}) if nok, err := k.AllOf[i].FromGnostic(v); err != nil { return false, err } else if !nok { ok = false } } if g.Properties != nil { k.Properties = make(map[string]Schema) for _, namedSchema := range g.Properties.AdditionalProperties { if namedSchema == nil { continue } val := &Schema{} if nok, err := val.FromGnostic(namedSchema.Value); err != nil { return false, err } else if !nok { ok = false } k.Properties[namedSchema.Name] = *val } } if g.AdditionalProperties != nil { k.AdditionalProperties = &SchemaOrBool{} if g.AdditionalProperties.GetSchema() == nil { k.AdditionalProperties.Allows = g.AdditionalProperties.GetBoolean() } else { k.AdditionalProperties.Schema = &Schema{} k.AdditionalProperties.Allows = true if nok, err := k.AdditionalProperties.Schema.FromGnostic(g.AdditionalProperties.GetSchema()); err != nil { return false, err } else if !nok { ok = false } } } return ok, nil } func (k *Schema) FromGnosticSchemaItem(g *openapi_v2.SchemaItem) (ok bool, err error) { if g == nil { return true, nil } ok = true switch p := g.Oneof.(type) { case *openapi_v2.SchemaItem_FileSchema: fileSchema := p.FileSchema if err := k.VendorExtensible.FromGnostic(fileSchema.VendorExtension); err != nil { return false, err } k.Format = fileSchema.Format k.Title = fileSchema.Title k.Description = fileSchema.Description k.Required = fileSchema.Required k.Type = []string{fileSchema.Type} k.ReadOnly = fileSchema.ReadOnly if fileSchema.ExternalDocs != nil { k.ExternalDocs = &ExternalDocumentation{} if nok, err := k.ExternalDocs.FromGnostic(fileSchema.ExternalDocs); err != nil { return false, err } else if !nok { ok = false } } if fileSchema.Example != nil { if err := fileSchema.Example.ToRawInfo().Decode(&k.Example); err != nil { return false, err } } if fileSchema.Default != nil { if err := fileSchema.Default.ToRawInfo().Decode(&k.Default); err != nil { return false, err } } case *openapi_v2.SchemaItem_Schema: schema := p.Schema if nok, err := k.FromGnostic(schema); err != nil { return false, err } else if !nok { ok = false } default: return false, errors.New("unrecognized type for SchemaItem") } return ok, nil } // SecurityDefinitions func (k SecurityDefinitions) FromGnostic(g *openapi_v2.SecurityDefinitions) error { for _, v := range g.GetAdditionalProperties() { if v == nil { continue } secScheme := &SecurityScheme{} if err := secScheme.FromGnostic(v.Value); err != nil { return err } k[v.Name] = secScheme } return nil } type GnosticCommonSecurityDefinition interface { GetType() string GetDescription() string } func (k *SecuritySchemeProps) FromGnostic(g GnosticCommonSecurityDefinition) error { k.Type = g.GetType() k.Description = g.GetDescription() if hasName, success := g.(interface{ GetName() string }); success { k.Name = hasName.GetName() } if hasIn, success := g.(interface{ GetIn() string }); success { k.In = hasIn.GetIn() } if hasFlow, success := g.(interface{ GetFlow() string }); success { k.Flow = hasFlow.GetFlow() } if hasAuthURL, success := g.(interface{ GetAuthorizationUrl() string }); success { k.AuthorizationURL = hasAuthURL.GetAuthorizationUrl() } if hasTokenURL, success := g.(interface{ GetTokenUrl() string }); success { k.TokenURL = hasTokenURL.GetTokenUrl() } if hasScopes, success := g.(interface { GetScopes() *openapi_v2.Oauth2Scopes }); success { scopes := hasScopes.GetScopes() if scopes != nil { k.Scopes = make(map[string]string, len(scopes.AdditionalProperties)) for _, v := range scopes.AdditionalProperties { if v == nil { continue } k.Scopes[v.Name] = v.Value } } } return nil } func (k *SecurityScheme) FromGnostic(g *openapi_v2.SecurityDefinitionsItem) error { if g == nil { return nil } switch s := g.Oneof.(type) { case *openapi_v2.SecurityDefinitionsItem_ApiKeySecurity: if err := k.SecuritySchemeProps.FromGnostic(s.ApiKeySecurity); err != nil { return err } if err := k.VendorExtensible.FromGnostic(s.ApiKeySecurity.VendorExtension); err != nil { return err } return nil case *openapi_v2.SecurityDefinitionsItem_BasicAuthenticationSecurity: if err := k.SecuritySchemeProps.FromGnostic(s.BasicAuthenticationSecurity); err != nil { return err } if err := k.VendorExtensible.FromGnostic(s.BasicAuthenticationSecurity.VendorExtension); err != nil { return err } return nil case *openapi_v2.SecurityDefinitionsItem_Oauth2AccessCodeSecurity: if err := k.SecuritySchemeProps.FromGnostic(s.Oauth2AccessCodeSecurity); err != nil { return err } if err := k.VendorExtensible.FromGnostic(s.Oauth2AccessCodeSecurity.VendorExtension); err != nil { return err } return nil case *openapi_v2.SecurityDefinitionsItem_Oauth2ApplicationSecurity: if err := k.SecuritySchemeProps.FromGnostic(s.Oauth2ApplicationSecurity); err != nil { return err } if err := k.VendorExtensible.FromGnostic(s.Oauth2ApplicationSecurity.VendorExtension); err != nil { return err } return nil case *openapi_v2.SecurityDefinitionsItem_Oauth2ImplicitSecurity: if err := k.SecuritySchemeProps.FromGnostic(s.Oauth2ImplicitSecurity); err != nil { return err } if err := k.VendorExtensible.FromGnostic(s.Oauth2ImplicitSecurity.VendorExtension); err != nil { return err } return nil case *openapi_v2.SecurityDefinitionsItem_Oauth2PasswordSecurity: if err := k.SecuritySchemeProps.FromGnostic(s.Oauth2PasswordSecurity); err != nil { return err } if err := k.VendorExtensible.FromGnostic(s.Oauth2PasswordSecurity.VendorExtension); err != nil { return err } return nil default: return errors.New("unrecognized SecurityDefinitionsItem") } } // Tag func (k *Tag) FromGnostic(g *openapi_v2.Tag) (ok bool, err error) { if g == nil { return true, nil } ok = true if nok, err := k.TagProps.FromGnostic(g); err != nil { return false, err } else if !nok { ok = false } if err := k.VendorExtensible.FromGnostic(g.VendorExtension); err != nil { return false, err } return ok, nil } func (k *TagProps) FromGnostic(g *openapi_v2.Tag) (ok bool, err error) { if g == nil { return true, nil } ok = true k.Description = g.Description k.Name = g.Name if g.ExternalDocs != nil { k.ExternalDocs = &ExternalDocumentation{} if nok, err := k.ExternalDocs.FromGnostic(g.ExternalDocs); err != nil { return false, err } else if !nok { ok = false } } return ok, nil } // ExternalDocumentation
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
true
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/validation/spec/header.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/validation/spec/header.go
// Copyright 2015 go-swagger maintainers // // 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 spec import ( "encoding/json" "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" ) const ( jsonArray = "array" ) // HeaderProps describes a response header type HeaderProps struct { Description string `json:"description,omitempty"` } // Header describes a header for a response of the API // // For more information: http://goo.gl/8us55a#headerObject type Header struct { CommonValidations SimpleSchema VendorExtensible HeaderProps } // MarshalJSON marshal this to JSON func (h Header) MarshalJSON() ([]byte, error) { if internal.UseOptimizedJSONMarshaling { return internal.DeterministicMarshal(h) } b1, err := json.Marshal(h.CommonValidations) if err != nil { return nil, err } b2, err := json.Marshal(h.SimpleSchema) if err != nil { return nil, err } b3, err := json.Marshal(h.HeaderProps) if err != nil { return nil, err } b4, err := json.Marshal(h.VendorExtensible) if err != nil { return nil, err } return swag.ConcatJSON(b1, b2, b3, b4), nil } func (h Header) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { var x struct { CommonValidations commonValidationsOmitZero `json:",inline"` SimpleSchema simpleSchemaOmitZero `json:",inline"` Extensions HeaderProps } x.CommonValidations = commonValidationsOmitZero(h.CommonValidations) x.SimpleSchema = simpleSchemaOmitZero(h.SimpleSchema) x.Extensions = internal.SanitizeExtensions(h.Extensions) x.HeaderProps = h.HeaderProps return opts.MarshalNext(enc, x) } // UnmarshalJSON unmarshals this header from JSON func (h *Header) UnmarshalJSON(data []byte) error { if internal.UseOptimizedJSONUnmarshaling { return jsonv2.Unmarshal(data, h) } if err := json.Unmarshal(data, &h.CommonValidations); err != nil { return err } if err := json.Unmarshal(data, &h.SimpleSchema); err != nil { return err } if err := json.Unmarshal(data, &h.VendorExtensible); err != nil { return err } return json.Unmarshal(data, &h.HeaderProps) } func (h *Header) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { var x struct { CommonValidations SimpleSchema Extensions HeaderProps } if err := opts.UnmarshalNext(dec, &x); err != nil { return err } h.CommonValidations = x.CommonValidations h.SimpleSchema = x.SimpleSchema h.Extensions = internal.SanitizeExtensions(x.Extensions) h.HeaderProps = x.HeaderProps return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/validation/spec/tag.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/validation/spec/tag.go
// Copyright 2015 go-swagger maintainers // // 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 spec import ( "encoding/json" "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" ) // TagProps describe a tag entry in the top level tags section of a swagger spec type TagProps struct { Description string `json:"description,omitempty"` Name string `json:"name,omitempty"` ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"` } // Tag allows adding meta data to a single tag that is used by the // [Operation Object](http://goo.gl/8us55a#operationObject). // It is not mandatory to have a Tag Object per tag used there. // // For more information: http://goo.gl/8us55a#tagObject type Tag struct { VendorExtensible TagProps } // MarshalJSON marshal this to JSON func (t Tag) MarshalJSON() ([]byte, error) { if internal.UseOptimizedJSONMarshaling { return internal.DeterministicMarshal(t) } b1, err := json.Marshal(t.TagProps) if err != nil { return nil, err } b2, err := json.Marshal(t.VendorExtensible) if err != nil { return nil, err } return swag.ConcatJSON(b1, b2), nil } func (t Tag) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { var x struct { Extensions TagProps } x.Extensions = internal.SanitizeExtensions(t.Extensions) x.TagProps = t.TagProps return opts.MarshalNext(enc, x) } // UnmarshalJSON marshal this from JSON func (t *Tag) UnmarshalJSON(data []byte) error { if internal.UseOptimizedJSONUnmarshaling { return jsonv2.Unmarshal(data, t) } if err := json.Unmarshal(data, &t.TagProps); err != nil { return err } return json.Unmarshal(data, &t.VendorExtensible) } func (t *Tag) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { var x struct { Extensions TagProps } if err := opts.UnmarshalNext(dec, &x); err != nil { return err } t.Extensions = internal.SanitizeExtensions(x.Extensions) t.TagProps = x.TagProps return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/validation/spec/paths.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/validation/spec/paths.go
// Copyright 2015 go-swagger maintainers // // 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 spec import ( "encoding/json" "fmt" "strings" "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" ) // Paths holds the relative paths to the individual endpoints. // The path is appended to the [`basePath`](http://goo.gl/8us55a#swaggerBasePath) in order // to construct the full URL. // The Paths may be empty, due to [ACL constraints](http://goo.gl/8us55a#securityFiltering). // // For more information: http://goo.gl/8us55a#pathsObject type Paths struct { VendorExtensible Paths map[string]PathItem `json:"-"` // custom serializer to flatten this, each entry must start with "/" } // UnmarshalJSON hydrates this items instance with the data from JSON func (p *Paths) UnmarshalJSON(data []byte) error { if internal.UseOptimizedJSONUnmarshaling { return jsonv2.Unmarshal(data, p) } var res map[string]json.RawMessage if err := json.Unmarshal(data, &res); err != nil { return err } for k, v := range res { if strings.HasPrefix(strings.ToLower(k), "x-") { if p.Extensions == nil { p.Extensions = make(map[string]interface{}) } var d interface{} if err := json.Unmarshal(v, &d); err != nil { return err } p.Extensions[k] = d } if strings.HasPrefix(k, "/") { if p.Paths == nil { p.Paths = make(map[string]PathItem) } var pi PathItem if err := json.Unmarshal(v, &pi); err != nil { return err } p.Paths[k] = pi } } return nil } func (p *Paths) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { tok, err := dec.ReadToken() if err != nil { return err } var ext any var pi PathItem switch k := tok.Kind(); k { case 'n': return nil // noop case '{': for { tok, err := dec.ReadToken() if err != nil { return err } if tok.Kind() == '}' { return nil } switch k := tok.String(); { case internal.IsExtensionKey(k): ext = nil if err := opts.UnmarshalNext(dec, &ext); err != nil { return err } if p.Extensions == nil { p.Extensions = make(map[string]any) } p.Extensions[k] = ext case len(k) > 0 && k[0] == '/': pi = PathItem{} if err := opts.UnmarshalNext(dec, &pi); err != nil { return err } if p.Paths == nil { p.Paths = make(map[string]PathItem) } p.Paths[k] = pi default: _, err := dec.ReadValue() // skip value if err != nil { return err } } } default: return fmt.Errorf("unknown JSON kind: %v", k) } } // MarshalJSON converts this items object to JSON func (p Paths) MarshalJSON() ([]byte, error) { if internal.UseOptimizedJSONMarshaling { return internal.DeterministicMarshal(p) } b1, err := json.Marshal(p.VendorExtensible) if err != nil { return nil, err } pths := make(map[string]PathItem) for k, v := range p.Paths { if strings.HasPrefix(k, "/") { pths[k] = v } } b2, err := json.Marshal(pths) if err != nil { return nil, err } concated := swag.ConcatJSON(b1, b2) return concated, nil } func (p Paths) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { m := make(map[string]any, len(p.Extensions)+len(p.Paths)) for k, v := range p.Extensions { if internal.IsExtensionKey(k) { m[k] = v } } for k, v := range p.Paths { if strings.HasPrefix(k, "/") { m[k] = v } } return opts.MarshalNext(enc, m) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/validation/spec/swagger.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/validation/spec/swagger.go
// Copyright 2015 go-swagger maintainers // // 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 spec import ( "encoding/json" "fmt" "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" ) // Swagger this is the root document object for the API specification. // It combines what previously was the Resource Listing and API Declaration (version 1.2 and earlier) // together into one document. // // For more information: http://goo.gl/8us55a#swagger-object- type Swagger struct { VendorExtensible SwaggerProps } // MarshalJSON marshals this swagger structure to json func (s Swagger) MarshalJSON() ([]byte, error) { if internal.UseOptimizedJSONMarshaling { return internal.DeterministicMarshal(s) } b1, err := json.Marshal(s.SwaggerProps) if err != nil { return nil, err } b2, err := json.Marshal(s.VendorExtensible) if err != nil { return nil, err } return swag.ConcatJSON(b1, b2), nil } // MarshalJSON marshals this swagger structure to json func (s Swagger) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { var x struct { Extensions SwaggerProps } x.Extensions = internal.SanitizeExtensions(s.Extensions) x.SwaggerProps = s.SwaggerProps return opts.MarshalNext(enc, x) } // UnmarshalJSON unmarshals a swagger spec from json func (s *Swagger) UnmarshalJSON(data []byte) error { if internal.UseOptimizedJSONUnmarshaling { return jsonv2.Unmarshal(data, s) } var sw Swagger if err := json.Unmarshal(data, &sw.SwaggerProps); err != nil { return err } if err := json.Unmarshal(data, &sw.VendorExtensible); err != nil { return err } *s = sw return nil } func (s *Swagger) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { // Note: If you're willing to make breaking changes, it is possible to // optimize this and other usages of this pattern: // https://github.com/kubernetes/kube-openapi/pull/319#discussion_r983165948 var x struct { Extensions SwaggerProps } if err := opts.UnmarshalNext(dec, &x); err != nil { return err } s.Extensions = internal.SanitizeExtensions(x.Extensions) s.SwaggerProps = x.SwaggerProps return nil } // SwaggerProps captures the top-level properties of an Api specification // // NOTE: validation rules // - the scheme, when present must be from [http, https, ws, wss] // - BasePath must start with a leading "/" // - Paths is required type SwaggerProps struct { ID string `json:"id,omitempty"` Consumes []string `json:"consumes,omitempty"` Produces []string `json:"produces,omitempty"` Schemes []string `json:"schemes,omitempty"` Swagger string `json:"swagger,omitempty"` Info *Info `json:"info,omitempty"` Host string `json:"host,omitempty"` BasePath string `json:"basePath,omitempty"` Paths *Paths `json:"paths"` Definitions Definitions `json:"definitions,omitempty"` Parameters map[string]Parameter `json:"parameters,omitempty"` Responses map[string]Response `json:"responses,omitempty"` SecurityDefinitions SecurityDefinitions `json:"securityDefinitions,omitempty"` Security []map[string][]string `json:"security,omitempty"` Tags []Tag `json:"tags,omitempty"` ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"` } // Dependencies represent a dependencies property type Dependencies map[string]SchemaOrStringArray // SchemaOrBool represents a schema or boolean value, is biased towards true for the boolean property type SchemaOrBool struct { Allows bool Schema *Schema } var jsTrue = []byte("true") var jsFalse = []byte("false") // MarshalJSON convert this object to JSON func (s SchemaOrBool) MarshalJSON() ([]byte, error) { if internal.UseOptimizedJSONMarshaling { return internal.DeterministicMarshal(s) } if s.Schema != nil { return json.Marshal(s.Schema) } if s.Schema == nil && !s.Allows { return jsFalse, nil } return jsTrue, nil } // MarshalJSON convert this object to JSON func (s SchemaOrBool) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { if s.Schema != nil { return opts.MarshalNext(enc, s.Schema) } if s.Schema == nil && !s.Allows { return enc.WriteToken(jsonv2.False) } return enc.WriteToken(jsonv2.True) } // UnmarshalJSON converts this bool or schema object from a JSON structure func (s *SchemaOrBool) UnmarshalJSON(data []byte) error { if internal.UseOptimizedJSONUnmarshaling { return jsonv2.Unmarshal(data, s) } var nw SchemaOrBool if len(data) > 0 && data[0] == '{' { var sch Schema if err := json.Unmarshal(data, &sch); err != nil { return err } nw.Schema = &sch nw.Allows = true } else { json.Unmarshal(data, &nw.Allows) } *s = nw return nil } func (s *SchemaOrBool) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { switch k := dec.PeekKind(); k { case '{': err := opts.UnmarshalNext(dec, &s.Schema) if err != nil { return err } s.Allows = true return nil case 't', 'f': err := opts.UnmarshalNext(dec, &s.Allows) if err != nil { return err } return nil default: return fmt.Errorf("expected object or bool, not '%v'", k.String()) } } // SchemaOrStringArray represents a schema or a string array type SchemaOrStringArray struct { Schema *Schema Property []string } // MarshalJSON converts this schema object or array into JSON structure func (s SchemaOrStringArray) MarshalJSON() ([]byte, error) { if internal.UseOptimizedJSONMarshaling { return internal.DeterministicMarshal(s) } if len(s.Property) > 0 { return json.Marshal(s.Property) } if s.Schema != nil { return json.Marshal(s.Schema) } return []byte("null"), nil } // MarshalJSON converts this schema object or array into JSON structure func (s SchemaOrStringArray) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { if len(s.Property) > 0 { return opts.MarshalNext(enc, s.Property) } if s.Schema != nil { return opts.MarshalNext(enc, s.Schema) } return enc.WriteToken(jsonv2.Null) } // UnmarshalJSON converts this schema object or array from a JSON structure func (s *SchemaOrStringArray) UnmarshalJSON(data []byte) error { if internal.UseOptimizedJSONUnmarshaling { return jsonv2.Unmarshal(data, s) } var first byte if len(data) > 1 { first = data[0] } var nw SchemaOrStringArray if first == '{' { var sch Schema if err := json.Unmarshal(data, &sch); err != nil { return err } nw.Schema = &sch } if first == '[' { if err := json.Unmarshal(data, &nw.Property); err != nil { return err } } *s = nw return nil } func (s *SchemaOrStringArray) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { switch dec.PeekKind() { case '{': return opts.UnmarshalNext(dec, &s.Schema) case '[': return opts.UnmarshalNext(dec, &s.Property) default: _, err := dec.ReadValue() return err } } // Definitions contains the models explicitly defined in this spec // An object to hold data types that can be consumed and produced by operations. // These data types can be primitives, arrays or models. // // For more information: http://goo.gl/8us55a#definitionsObject type Definitions map[string]Schema // SecurityDefinitions a declaration of the security schemes available to be used in the specification. // This does not enforce the security schemes on the operations and only serves to provide // the relevant details for each scheme. // // For more information: http://goo.gl/8us55a#securityDefinitionsObject type SecurityDefinitions map[string]*SecurityScheme // StringOrArray represents a value that can either be a string // or an array of strings. Mainly here for serialization purposes type StringOrArray []string // Contains returns true when the value is contained in the slice func (s StringOrArray) Contains(value string) bool { for _, str := range s { if str == value { return true } } return false } // UnmarshalJSON unmarshals this string or array object from a JSON array or JSON string func (s *StringOrArray) UnmarshalJSON(data []byte) error { if internal.UseOptimizedJSONUnmarshaling { return jsonv2.Unmarshal(data, s) } var first byte if len(data) > 1 { first = data[0] } if first == '[' { var parsed []string if err := json.Unmarshal(data, &parsed); err != nil { return err } *s = StringOrArray(parsed) return nil } var single interface{} if err := json.Unmarshal(data, &single); err != nil { return err } if single == nil { return nil } switch v := single.(type) { case string: *s = StringOrArray([]string{v}) return nil default: return fmt.Errorf("only string or array is allowed, not %T", single) } } func (s *StringOrArray) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { switch k := dec.PeekKind(); k { case '[': *s = StringOrArray{} return opts.UnmarshalNext(dec, (*[]string)(s)) case '"': *s = StringOrArray{""} return opts.UnmarshalNext(dec, &(*s)[0]) case 'n': // Throw out null token _, _ = dec.ReadToken() return nil default: return fmt.Errorf("expected string or array, not '%v'", k.String()) } } // MarshalJSON converts this string or array to a JSON array or JSON string func (s StringOrArray) MarshalJSON() ([]byte, error) { if len(s) == 1 { return json.Marshal([]string(s)[0]) } return json.Marshal([]string(s)) } // SchemaOrArray represents a value that can either be a Schema // or an array of Schema. Mainly here for serialization purposes type SchemaOrArray struct { Schema *Schema Schemas []Schema } // Len returns the number of schemas in this property func (s SchemaOrArray) Len() int { if s.Schema != nil { return 1 } return len(s.Schemas) } // ContainsType returns true when one of the schemas is of the specified type func (s *SchemaOrArray) ContainsType(name string) bool { if s.Schema != nil { return s.Schema.Type != nil && s.Schema.Type.Contains(name) } return false } // MarshalJSON converts this schema object or array into JSON structure func (s SchemaOrArray) MarshalJSON() ([]byte, error) { if internal.UseOptimizedJSONMarshaling { return internal.DeterministicMarshal(s) } if s.Schemas != nil { return json.Marshal(s.Schemas) } return json.Marshal(s.Schema) } // MarshalJSON converts this schema object or array into JSON structure func (s SchemaOrArray) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { if s.Schemas != nil { return opts.MarshalNext(enc, s.Schemas) } return opts.MarshalNext(enc, s.Schema) } // UnmarshalJSON converts this schema object or array from a JSON structure func (s *SchemaOrArray) UnmarshalJSON(data []byte) error { if internal.UseOptimizedJSONUnmarshaling { return jsonv2.Unmarshal(data, s) } var nw SchemaOrArray var first byte if len(data) > 1 { first = data[0] } if first == '{' { var sch Schema if err := json.Unmarshal(data, &sch); err != nil { return err } nw.Schema = &sch } if first == '[' { if err := json.Unmarshal(data, &nw.Schemas); err != nil { return err } } *s = nw return nil } func (s *SchemaOrArray) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { switch dec.PeekKind() { case '{': return opts.UnmarshalNext(dec, &s.Schema) case '[': return opts.UnmarshalNext(dec, &s.Schemas) default: _, err := dec.ReadValue() return err } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/validation/spec/responses.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/validation/spec/responses.go
// Copyright 2015 go-swagger maintainers // // 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 spec import ( "encoding/json" "fmt" "reflect" "strconv" "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" ) // Responses is a container for the expected responses of an operation. // The container maps a HTTP response code to the expected response. // It is not expected from the documentation to necessarily cover all possible HTTP response codes, // since they may not be known in advance. However, it is expected from the documentation to cover // a successful operation response and any known errors. // // The `default` can be used a default response object for all HTTP codes that are not covered // individually by the specification. // // The `Responses Object` MUST contain at least one response code, and it SHOULD be the response // for a successful operation call. // // For more information: http://goo.gl/8us55a#responsesObject type Responses struct { VendorExtensible ResponsesProps } // UnmarshalJSON hydrates this items instance with the data from JSON func (r *Responses) UnmarshalJSON(data []byte) error { if internal.UseOptimizedJSONUnmarshaling { return jsonv2.Unmarshal(data, r) } if err := json.Unmarshal(data, &r.ResponsesProps); err != nil { return err } if err := json.Unmarshal(data, &r.VendorExtensible); err != nil { return err } if reflect.DeepEqual(ResponsesProps{}, r.ResponsesProps) { r.ResponsesProps = ResponsesProps{} } return nil } // MarshalJSON converts this items object to JSON func (r Responses) MarshalJSON() ([]byte, error) { if internal.UseOptimizedJSONMarshaling { return internal.DeterministicMarshal(r) } b1, err := json.Marshal(r.ResponsesProps) if err != nil { return nil, err } b2, err := json.Marshal(r.VendorExtensible) if err != nil { return nil, err } concated := swag.ConcatJSON(b1, b2) return concated, nil } func (r Responses) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { type ArbitraryKeys map[string]interface{} var x struct { ArbitraryKeys Default *Response `json:"default,omitempty"` } x.ArbitraryKeys = make(map[string]any, len(r.Extensions)+len(r.StatusCodeResponses)) for k, v := range r.Extensions { if internal.IsExtensionKey(k) { x.ArbitraryKeys[k] = v } } for k, v := range r.StatusCodeResponses { x.ArbitraryKeys[strconv.Itoa(k)] = v } x.Default = r.Default return opts.MarshalNext(enc, x) } // ResponsesProps describes all responses for an operation. // It tells what is the default response and maps all responses with a // HTTP status code. type ResponsesProps struct { Default *Response StatusCodeResponses map[int]Response } // MarshalJSON marshals responses as JSON func (r ResponsesProps) MarshalJSON() ([]byte, error) { toser := map[string]Response{} if r.Default != nil { toser["default"] = *r.Default } for k, v := range r.StatusCodeResponses { toser[strconv.Itoa(k)] = v } return json.Marshal(toser) } // UnmarshalJSON unmarshals responses from JSON func (r *ResponsesProps) UnmarshalJSON(data []byte) error { if internal.UseOptimizedJSONUnmarshaling { return jsonv2.Unmarshal(data, r) } var res map[string]json.RawMessage if err := json.Unmarshal(data, &res); err != nil { return err } if v, ok := res["default"]; ok { value := Response{} if err := json.Unmarshal(v, &value); err != nil { return err } r.Default = &value delete(res, "default") } for k, v := range res { // Take all integral keys if nk, err := strconv.Atoi(k); err == nil { if r.StatusCodeResponses == nil { r.StatusCodeResponses = map[int]Response{} } value := Response{} if err := json.Unmarshal(v, &value); err != nil { return err } r.StatusCodeResponses[nk] = value } } return nil } func (r *Responses) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) (err error) { tok, err := dec.ReadToken() if err != nil { return err } var ext any var resp Response switch k := tok.Kind(); k { case 'n': return nil // noop case '{': for { tok, err := dec.ReadToken() if err != nil { return err } if tok.Kind() == '}' { return nil } switch k := tok.String(); { case internal.IsExtensionKey(k): ext = nil if err := opts.UnmarshalNext(dec, &ext); err != nil { return err } if r.Extensions == nil { r.Extensions = make(map[string]any) } r.Extensions[k] = ext case k == "default": resp = Response{} if err := opts.UnmarshalNext(dec, &resp); err != nil { return err } respCopy := resp r.ResponsesProps.Default = &respCopy default: if nk, err := strconv.Atoi(k); err == nil { resp = Response{} if err := opts.UnmarshalNext(dec, &resp); err != nil { return err } if r.StatusCodeResponses == nil { r.StatusCodeResponses = map[int]Response{} } r.StatusCodeResponses[nk] = resp } } } default: return fmt.Errorf("unknown JSON kind: %v", k) } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/validation/spec/license.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/validation/spec/license.go
// Copyright 2015 go-swagger maintainers // // 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 spec // License information for the exposed API. // // For more information: http://goo.gl/8us55a#licenseObject type License struct { Name string `json:"name,omitempty"` URL string `json:"url,omitempty"` }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/validation/spec/security_scheme.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/validation/spec/security_scheme.go
// Copyright 2015 go-swagger maintainers // // 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 spec import ( "encoding/json" "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" ) // SecuritySchemeProps describes a swagger security scheme in the securityDefinitions section type SecuritySchemeProps struct { Description string `json:"description,omitempty"` Type string `json:"type"` Name string `json:"name,omitempty"` // api key In string `json:"in,omitempty"` // api key Flow string `json:"flow,omitempty"` // oauth2 AuthorizationURL string `json:"authorizationUrl,omitempty"` // oauth2 TokenURL string `json:"tokenUrl,omitempty"` // oauth2 Scopes map[string]string `json:"scopes,omitempty"` // oauth2 } // SecurityScheme allows the definition of a security scheme that can be used by the operations. // Supported schemes are basic authentication, an API key (either as a header or as a query parameter) // and OAuth2's common flows (implicit, password, application and access code). // // For more information: http://goo.gl/8us55a#securitySchemeObject type SecurityScheme struct { VendorExtensible SecuritySchemeProps } // MarshalJSON marshal this to JSON func (s SecurityScheme) MarshalJSON() ([]byte, error) { if internal.UseOptimizedJSONMarshaling { return internal.DeterministicMarshal(s) } b1, err := json.Marshal(s.SecuritySchemeProps) if err != nil { return nil, err } b2, err := json.Marshal(s.VendorExtensible) if err != nil { return nil, err } return swag.ConcatJSON(b1, b2), nil } func (s SecurityScheme) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { var x struct { Extensions SecuritySchemeProps } x.Extensions = internal.SanitizeExtensions(s.Extensions) x.SecuritySchemeProps = s.SecuritySchemeProps return opts.MarshalNext(enc, x) } // UnmarshalJSON marshal this from JSON func (s *SecurityScheme) UnmarshalJSON(data []byte) error { if err := json.Unmarshal(data, &s.SecuritySchemeProps); err != nil { return err } return json.Unmarshal(data, &s.VendorExtensible) } func (s *SecurityScheme) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { var x struct { Extensions SecuritySchemeProps } if err := opts.UnmarshalNext(dec, &x); err != nil { return err } s.Extensions = internal.SanitizeExtensions(x.Extensions) s.SecuritySchemeProps = x.SecuritySchemeProps return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/validation/spec/operation.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/validation/spec/operation.go
// Copyright 2015 go-swagger maintainers // // 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 spec import ( "encoding/json" "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" ) // OperationProps describes an operation // // NOTES: // - schemes, when present must be from [http, https, ws, wss]: see validate // - Security is handled as a special case: see MarshalJSON function type OperationProps struct { Description string `json:"description,omitempty"` Consumes []string `json:"consumes,omitempty"` Produces []string `json:"produces,omitempty"` Schemes []string `json:"schemes,omitempty"` Tags []string `json:"tags,omitempty"` Summary string `json:"summary,omitempty"` ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"` ID string `json:"operationId,omitempty"` Deprecated bool `json:"deprecated,omitempty"` Security []map[string][]string `json:"security,omitempty"` Parameters []Parameter `json:"parameters,omitempty"` Responses *Responses `json:"responses,omitempty"` } // Marshaling structure only, always edit along with corresponding // struct (or compilation will fail). type operationPropsOmitZero struct { Description string `json:"description,omitempty"` Consumes []string `json:"consumes,omitempty"` Produces []string `json:"produces,omitempty"` Schemes []string `json:"schemes,omitempty"` Tags []string `json:"tags,omitempty"` Summary string `json:"summary,omitempty"` ExternalDocs *ExternalDocumentation `json:"externalDocs,omitzero"` ID string `json:"operationId,omitempty"` Deprecated bool `json:"deprecated,omitempty,omitzero"` Security []map[string][]string `json:"security,omitempty"` Parameters []Parameter `json:"parameters,omitempty"` Responses *Responses `json:"responses,omitzero"` } // MarshalJSON takes care of serializing operation properties to JSON // // We use a custom marhaller here to handle a special cases related to // the Security field. We need to preserve zero length slice // while omitting the field when the value is nil/unset. func (op OperationProps) MarshalJSON() ([]byte, error) { type Alias OperationProps if op.Security == nil { return json.Marshal(&struct { Security []map[string][]string `json:"security,omitempty"` *Alias }{ Security: op.Security, Alias: (*Alias)(&op), }) } return json.Marshal(&struct { Security []map[string][]string `json:"security"` *Alias }{ Security: op.Security, Alias: (*Alias)(&op), }) } // Operation describes a single API operation on a path. // // For more information: http://goo.gl/8us55a#operationObject type Operation struct { VendorExtensible OperationProps } // UnmarshalJSON hydrates this items instance with the data from JSON func (o *Operation) UnmarshalJSON(data []byte) error { if internal.UseOptimizedJSONUnmarshaling { return jsonv2.Unmarshal(data, o) } if err := json.Unmarshal(data, &o.OperationProps); err != nil { return err } return json.Unmarshal(data, &o.VendorExtensible) } func (o *Operation) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { type OperationPropsNoMethods OperationProps // strip MarshalJSON method var x struct { Extensions OperationPropsNoMethods } if err := opts.UnmarshalNext(dec, &x); err != nil { return err } o.Extensions = internal.SanitizeExtensions(x.Extensions) o.OperationProps = OperationProps(x.OperationPropsNoMethods) return nil } // MarshalJSON converts this items object to JSON func (o Operation) MarshalJSON() ([]byte, error) { if internal.UseOptimizedJSONMarshaling { return internal.DeterministicMarshal(o) } b1, err := json.Marshal(o.OperationProps) if err != nil { return nil, err } b2, err := json.Marshal(o.VendorExtensible) if err != nil { return nil, err } concated := swag.ConcatJSON(b1, b2) return concated, nil } func (o Operation) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { var x struct { Extensions OperationProps operationPropsOmitZero `json:",inline"` } x.Extensions = internal.SanitizeExtensions(o.Extensions) x.OperationProps = operationPropsOmitZero(o.OperationProps) return opts.MarshalNext(enc, x) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/validation/spec/parameter.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/validation/spec/parameter.go
// Copyright 2015 go-swagger maintainers // // 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 spec import ( "encoding/json" "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" ) // ParamProps describes the specific attributes of an operation parameter // // NOTE: // - Schema is defined when "in" == "body": see validate // - AllowEmptyValue is allowed where "in" == "query" || "formData" type ParamProps struct { Description string `json:"description,omitempty"` Name string `json:"name,omitempty"` In string `json:"in,omitempty"` Required bool `json:"required,omitempty"` Schema *Schema `json:"schema,omitempty"` AllowEmptyValue bool `json:"allowEmptyValue,omitempty"` } // Marshaling structure only, always edit along with corresponding // struct (or compilation will fail). type paramPropsOmitZero struct { Description string `json:"description,omitempty"` Name string `json:"name,omitempty"` In string `json:"in,omitempty"` Required bool `json:"required,omitzero"` Schema *Schema `json:"schema,omitzero"` AllowEmptyValue bool `json:"allowEmptyValue,omitzero"` } // Parameter a unique parameter is defined by a combination of a [name](#parameterName) and [location](#parameterIn). // // There are five possible parameter types. // * Path - Used together with [Path Templating](#pathTemplating), where the parameter value is actually part // // of the operation's URL. This does not include the host or base path of the API. For example, in `/items/{itemId}`, // the path parameter is `itemId`. // // * Query - Parameters that are appended to the URL. For example, in `/items?id=###`, the query parameter is `id`. // * Header - Custom headers that are expected as part of the request. // * Body - The payload that's appended to the HTTP request. Since there can only be one payload, there can only be // // _one_ body parameter. The name of the body parameter has no effect on the parameter itself and is used for // documentation purposes only. Since Form parameters are also in the payload, body and form parameters cannot exist // together for the same operation. // // * Form - Used to describe the payload of an HTTP request when either `application/x-www-form-urlencoded` or // // `multipart/form-data` are used as the content type of the request (in Swagger's definition, // the [`consumes`](#operationConsumes) property of an operation). This is the only parameter type that can be used // to send files, thus supporting the `file` type. Since form parameters are sent in the payload, they cannot be // declared together with a body parameter for the same operation. Form parameters have a different format based on // the content-type used (for further details, consult http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4). // * `application/x-www-form-urlencoded` - Similar to the format of Query parameters but as a payload. // For example, `foo=1&bar=swagger` - both `foo` and `bar` are form parameters. This is normally used for simple // parameters that are being transferred. // * `multipart/form-data` - each parameter takes a section in the payload with an internal header. // For example, for the header `Content-Disposition: form-data; name="submit-name"` the name of the parameter is // `submit-name`. This type of form parameters is more commonly used for file transfers. // // For more information: http://goo.gl/8us55a#parameterObject type Parameter struct { Refable CommonValidations SimpleSchema VendorExtensible ParamProps } // UnmarshalJSON hydrates this items instance with the data from JSON func (p *Parameter) UnmarshalJSON(data []byte) error { if internal.UseOptimizedJSONUnmarshaling { return jsonv2.Unmarshal(data, p) } if err := json.Unmarshal(data, &p.CommonValidations); err != nil { return err } if err := json.Unmarshal(data, &p.Refable); err != nil { return err } if err := json.Unmarshal(data, &p.SimpleSchema); err != nil { return err } if err := json.Unmarshal(data, &p.VendorExtensible); err != nil { return err } return json.Unmarshal(data, &p.ParamProps) } func (p *Parameter) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { var x struct { CommonValidations SimpleSchema Extensions ParamProps } if err := opts.UnmarshalNext(dec, &x); err != nil { return err } if err := p.Refable.Ref.fromMap(x.Extensions); err != nil { return err } p.CommonValidations = x.CommonValidations p.SimpleSchema = x.SimpleSchema p.Extensions = internal.SanitizeExtensions(x.Extensions) p.ParamProps = x.ParamProps return nil } // MarshalJSON converts this items object to JSON func (p Parameter) MarshalJSON() ([]byte, error) { if internal.UseOptimizedJSONMarshaling { return internal.DeterministicMarshal(p) } b1, err := json.Marshal(p.CommonValidations) if err != nil { return nil, err } b2, err := json.Marshal(p.SimpleSchema) if err != nil { return nil, err } b3, err := json.Marshal(p.Refable) if err != nil { return nil, err } b4, err := json.Marshal(p.VendorExtensible) if err != nil { return nil, err } b5, err := json.Marshal(p.ParamProps) if err != nil { return nil, err } return swag.ConcatJSON(b3, b1, b2, b4, b5), nil } func (p Parameter) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { var x struct { CommonValidations commonValidationsOmitZero `json:",inline"` SimpleSchema simpleSchemaOmitZero `json:",inline"` ParamProps paramPropsOmitZero `json:",inline"` Ref string `json:"$ref,omitempty"` Extensions } x.CommonValidations = commonValidationsOmitZero(p.CommonValidations) x.SimpleSchema = simpleSchemaOmitZero(p.SimpleSchema) x.Extensions = internal.SanitizeExtensions(p.Extensions) x.ParamProps = paramPropsOmitZero(p.ParamProps) x.Ref = p.Refable.Ref.String() return opts.MarshalNext(enc, x) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/validation/spec/info.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/validation/spec/info.go
// Copyright 2015 go-swagger maintainers // // 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 spec import ( "encoding/json" "strings" "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" ) // Extensions vendor specific extensions type Extensions map[string]interface{} // Add adds a value to these extensions func (e Extensions) Add(key string, value interface{}) { realKey := strings.ToLower(key) e[realKey] = value } // GetString gets a string value from the extensions func (e Extensions) GetString(key string) (string, bool) { if v, ok := e[strings.ToLower(key)]; ok { str, ok := v.(string) return str, ok } return "", false } // GetBool gets a string value from the extensions func (e Extensions) GetBool(key string) (bool, bool) { if v, ok := e[strings.ToLower(key)]; ok { str, ok := v.(bool) return str, ok } return false, false } // GetStringSlice gets a string value from the extensions func (e Extensions) GetStringSlice(key string) ([]string, bool) { if v, ok := e[strings.ToLower(key)]; ok { arr, isSlice := v.([]interface{}) if !isSlice { return nil, false } var strs []string for _, iface := range arr { str, isString := iface.(string) if !isString { return nil, false } strs = append(strs, str) } return strs, ok } return nil, false } // GetObject gets the object value from the extensions. // out must be a json serializable type; the json go struct // tags of out are used to populate it. func (e Extensions) GetObject(key string, out interface{}) error { // This json serialization/deserialization could be replaced with // an approach using reflection if the optimization becomes justified. if v, ok := e[strings.ToLower(key)]; ok { b, err := json.Marshal(v) if err != nil { return err } err = json.Unmarshal(b, out) if err != nil { return err } } return nil } func (e Extensions) sanitizeWithExtra() (extra map[string]any) { for k, v := range e { if !internal.IsExtensionKey(k) { if extra == nil { extra = make(map[string]any) } extra[k] = v delete(e, k) } } return extra } // VendorExtensible composition block. type VendorExtensible struct { Extensions Extensions } // AddExtension adds an extension to this extensible object func (v *VendorExtensible) AddExtension(key string, value interface{}) { if value == nil { return } if v.Extensions == nil { v.Extensions = make(map[string]interface{}) } v.Extensions.Add(key, value) } // MarshalJSON marshals the extensions to json func (v VendorExtensible) MarshalJSON() ([]byte, error) { toser := make(map[string]interface{}) for k, v := range v.Extensions { lk := strings.ToLower(k) if strings.HasPrefix(lk, "x-") { toser[k] = v } } return json.Marshal(toser) } // UnmarshalJSON for this extensible object func (v *VendorExtensible) UnmarshalJSON(data []byte) error { var d map[string]interface{} if err := json.Unmarshal(data, &d); err != nil { return err } for k, vv := range d { lk := strings.ToLower(k) if strings.HasPrefix(lk, "x-") { if v.Extensions == nil { v.Extensions = map[string]interface{}{} } v.Extensions[k] = vv } } return nil } // InfoProps the properties for an info definition type InfoProps struct { Description string `json:"description,omitempty"` Title string `json:"title,omitempty"` TermsOfService string `json:"termsOfService,omitempty"` Contact *ContactInfo `json:"contact,omitempty"` License *License `json:"license,omitempty"` Version string `json:"version,omitempty"` } // Info object provides metadata about the API. // The metadata can be used by the clients if needed, and can be presented in the Swagger-UI for convenience. // // For more information: http://goo.gl/8us55a#infoObject type Info struct { VendorExtensible InfoProps } // MarshalJSON marshal this to JSON func (i Info) MarshalJSON() ([]byte, error) { if internal.UseOptimizedJSONMarshaling { return internal.DeterministicMarshal(i) } b1, err := json.Marshal(i.InfoProps) if err != nil { return nil, err } b2, err := json.Marshal(i.VendorExtensible) if err != nil { return nil, err } return swag.ConcatJSON(b1, b2), nil } func (i Info) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { var x struct { Extensions InfoProps } x.Extensions = i.Extensions x.InfoProps = i.InfoProps return opts.MarshalNext(enc, x) } // UnmarshalJSON marshal this from JSON func (i *Info) UnmarshalJSON(data []byte) error { if internal.UseOptimizedJSONUnmarshaling { return jsonv2.Unmarshal(data, i) } if err := json.Unmarshal(data, &i.InfoProps); err != nil { return err } return json.Unmarshal(data, &i.VendorExtensible) } func (i *Info) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { var x struct { Extensions InfoProps } if err := opts.UnmarshalNext(dec, &x); err != nil { return err } i.Extensions = internal.SanitizeExtensions(x.Extensions) i.InfoProps = x.InfoProps return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/validation/spec/schema.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/validation/spec/schema.go
// Copyright 2015 go-swagger maintainers // // 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 spec import ( "encoding/json" "fmt" "net/url" "strings" "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" ) // BooleanProperty creates a boolean property func BooleanProperty() *Schema { return &Schema{SchemaProps: SchemaProps{Type: []string{"boolean"}}} } // BoolProperty creates a boolean property func BoolProperty() *Schema { return BooleanProperty() } // StringProperty creates a string property func StringProperty() *Schema { return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}}} } // CharProperty creates a string property func CharProperty() *Schema { return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}}} } // Float64Property creates a float64/double property func Float64Property() *Schema { return &Schema{SchemaProps: SchemaProps{Type: []string{"number"}, Format: "double"}} } // Float32Property creates a float32/float property func Float32Property() *Schema { return &Schema{SchemaProps: SchemaProps{Type: []string{"number"}, Format: "float"}} } // Int8Property creates an int8 property func Int8Property() *Schema { return &Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int8"}} } // Int16Property creates an int16 property func Int16Property() *Schema { return &Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int16"}} } // Int32Property creates an int32 property func Int32Property() *Schema { return &Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int32"}} } // Int64Property creates an int64 property func Int64Property() *Schema { return &Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int64"}} } // StrFmtProperty creates a property for the named string format func StrFmtProperty(format string) *Schema { return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}, Format: format}} } // DateProperty creates a date property func DateProperty() *Schema { return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}, Format: "date"}} } // DateTimeProperty creates a date time property func DateTimeProperty() *Schema { return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}, Format: "date-time"}} } // MapProperty creates a map property func MapProperty(property *Schema) *Schema { return &Schema{SchemaProps: SchemaProps{Type: []string{"object"}, AdditionalProperties: &SchemaOrBool{Allows: true, Schema: property}}} } // RefProperty creates a ref property func RefProperty(name string) *Schema { return &Schema{SchemaProps: SchemaProps{Ref: MustCreateRef(name)}} } // RefSchema creates a ref property func RefSchema(name string) *Schema { return &Schema{SchemaProps: SchemaProps{Ref: MustCreateRef(name)}} } // ArrayProperty creates an array property func ArrayProperty(items *Schema) *Schema { if items == nil { return &Schema{SchemaProps: SchemaProps{Type: []string{"array"}}} } return &Schema{SchemaProps: SchemaProps{Items: &SchemaOrArray{Schema: items}, Type: []string{"array"}}} } // ComposedSchema creates a schema with allOf func ComposedSchema(schemas ...Schema) *Schema { s := new(Schema) s.AllOf = schemas return s } // SchemaURL represents a schema url type SchemaURL string // MarshalJSON marshal this to JSON func (r SchemaURL) MarshalJSON() ([]byte, error) { if r == "" { return []byte("{}"), nil } v := map[string]interface{}{"$schema": string(r)} return json.Marshal(v) } // UnmarshalJSON unmarshal this from JSON func (r *SchemaURL) UnmarshalJSON(data []byte) error { var v map[string]interface{} if err := json.Unmarshal(data, &v); err != nil { return err } return r.fromMap(v) } func (r *SchemaURL) fromMap(v map[string]interface{}) error { if v == nil { return nil } if vv, ok := v["$schema"]; ok { if str, ok := vv.(string); ok { u, err := url.Parse(str) if err != nil { return err } *r = SchemaURL(u.String()) } } return nil } // SchemaProps describes a JSON schema (draft 4) type SchemaProps struct { ID string `json:"id,omitempty"` Ref Ref `json:"-"` Schema SchemaURL `json:"-"` Description string `json:"description,omitempty"` Type StringOrArray `json:"type,omitempty"` Nullable bool `json:"nullable,omitempty"` Format string `json:"format,omitempty"` Title string `json:"title,omitempty"` Default interface{} `json:"default,omitempty"` Maximum *float64 `json:"maximum,omitempty"` ExclusiveMaximum bool `json:"exclusiveMaximum,omitempty"` Minimum *float64 `json:"minimum,omitempty"` ExclusiveMinimum bool `json:"exclusiveMinimum,omitempty"` MaxLength *int64 `json:"maxLength,omitempty"` MinLength *int64 `json:"minLength,omitempty"` Pattern string `json:"pattern,omitempty"` MaxItems *int64 `json:"maxItems,omitempty"` MinItems *int64 `json:"minItems,omitempty"` UniqueItems bool `json:"uniqueItems,omitempty"` MultipleOf *float64 `json:"multipleOf,omitempty"` Enum []interface{} `json:"enum,omitempty"` MaxProperties *int64 `json:"maxProperties,omitempty"` MinProperties *int64 `json:"minProperties,omitempty"` Required []string `json:"required,omitempty"` Items *SchemaOrArray `json:"items,omitempty"` AllOf []Schema `json:"allOf,omitempty"` OneOf []Schema `json:"oneOf,omitempty"` AnyOf []Schema `json:"anyOf,omitempty"` Not *Schema `json:"not,omitempty"` Properties map[string]Schema `json:"properties,omitempty"` AdditionalProperties *SchemaOrBool `json:"additionalProperties,omitempty"` PatternProperties map[string]Schema `json:"patternProperties,omitempty"` Dependencies Dependencies `json:"dependencies,omitempty"` AdditionalItems *SchemaOrBool `json:"additionalItems,omitempty"` Definitions Definitions `json:"definitions,omitempty"` } // Marshaling structure only, always edit along with corresponding // struct (or compilation will fail). type schemaPropsOmitZero struct { ID string `json:"id,omitempty"` Ref Ref `json:"-"` Schema SchemaURL `json:"-"` Description string `json:"description,omitempty"` Type StringOrArray `json:"type,omitzero"` Nullable bool `json:"nullable,omitzero"` Format string `json:"format,omitempty"` Title string `json:"title,omitempty"` Default interface{} `json:"default,omitzero"` Maximum *float64 `json:"maximum,omitempty"` ExclusiveMaximum bool `json:"exclusiveMaximum,omitzero"` Minimum *float64 `json:"minimum,omitempty"` ExclusiveMinimum bool `json:"exclusiveMinimum,omitzero"` MaxLength *int64 `json:"maxLength,omitempty"` MinLength *int64 `json:"minLength,omitempty"` Pattern string `json:"pattern,omitempty"` MaxItems *int64 `json:"maxItems,omitempty"` MinItems *int64 `json:"minItems,omitempty"` UniqueItems bool `json:"uniqueItems,omitzero"` MultipleOf *float64 `json:"multipleOf,omitempty"` Enum []interface{} `json:"enum,omitempty"` MaxProperties *int64 `json:"maxProperties,omitempty"` MinProperties *int64 `json:"minProperties,omitempty"` Required []string `json:"required,omitempty"` Items *SchemaOrArray `json:"items,omitzero"` AllOf []Schema `json:"allOf,omitempty"` OneOf []Schema `json:"oneOf,omitempty"` AnyOf []Schema `json:"anyOf,omitempty"` Not *Schema `json:"not,omitzero"` Properties map[string]Schema `json:"properties,omitempty"` AdditionalProperties *SchemaOrBool `json:"additionalProperties,omitzero"` PatternProperties map[string]Schema `json:"patternProperties,omitempty"` Dependencies Dependencies `json:"dependencies,omitempty"` AdditionalItems *SchemaOrBool `json:"additionalItems,omitzero"` Definitions Definitions `json:"definitions,omitempty"` } // SwaggerSchemaProps are additional properties supported by swagger schemas, but not JSON-schema (draft 4) type SwaggerSchemaProps struct { Discriminator string `json:"discriminator,omitempty"` ReadOnly bool `json:"readOnly,omitempty"` ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"` Example interface{} `json:"example,omitempty"` } // Marshaling structure only, always edit along with corresponding // struct (or compilation will fail). type swaggerSchemaPropsOmitZero struct { Discriminator string `json:"discriminator,omitempty"` ReadOnly bool `json:"readOnly,omitzero"` ExternalDocs *ExternalDocumentation `json:"externalDocs,omitzero"` Example interface{} `json:"example,omitempty"` } // Schema the schema object allows the definition of input and output data types. // These types can be objects, but also primitives and arrays. // This object is based on the [JSON Schema Specification Draft 4](http://json-schema.org/) // and uses a predefined subset of it. // On top of this subset, there are extensions provided by this specification to allow for more complete documentation. // // For more information: http://goo.gl/8us55a#schemaObject type Schema struct { VendorExtensible SchemaProps SwaggerSchemaProps ExtraProps map[string]interface{} `json:"-"` } // WithID sets the id for this schema, allows for chaining func (s *Schema) WithID(id string) *Schema { s.ID = id return s } // WithTitle sets the title for this schema, allows for chaining func (s *Schema) WithTitle(title string) *Schema { s.Title = title return s } // WithDescription sets the description for this schema, allows for chaining func (s *Schema) WithDescription(description string) *Schema { s.Description = description return s } // WithProperties sets the properties for this schema func (s *Schema) WithProperties(schemas map[string]Schema) *Schema { s.Properties = schemas return s } // SetProperty sets a property on this schema func (s *Schema) SetProperty(name string, schema Schema) *Schema { if s.Properties == nil { s.Properties = make(map[string]Schema) } s.Properties[name] = schema return s } // WithAllOf sets the all of property func (s *Schema) WithAllOf(schemas ...Schema) *Schema { s.AllOf = schemas return s } // WithMaxProperties sets the max number of properties an object can have func (s *Schema) WithMaxProperties(max int64) *Schema { s.MaxProperties = &max return s } // WithMinProperties sets the min number of properties an object must have func (s *Schema) WithMinProperties(min int64) *Schema { s.MinProperties = &min return s } // Typed sets the type of this schema for a single value item func (s *Schema) Typed(tpe, format string) *Schema { s.Type = []string{tpe} s.Format = format return s } // AddType adds a type with potential format to the types for this schema func (s *Schema) AddType(tpe, format string) *Schema { s.Type = append(s.Type, tpe) if format != "" { s.Format = format } return s } // AsNullable flags this schema as nullable. func (s *Schema) AsNullable() *Schema { s.Nullable = true return s } // CollectionOf a fluent builder method for an array parameter func (s *Schema) CollectionOf(items Schema) *Schema { s.Type = []string{jsonArray} s.Items = &SchemaOrArray{Schema: &items} return s } // WithDefault sets the default value on this parameter func (s *Schema) WithDefault(defaultValue interface{}) *Schema { s.Default = defaultValue return s } // WithRequired flags this parameter as required func (s *Schema) WithRequired(items ...string) *Schema { s.Required = items return s } // AddRequired adds field names to the required properties array func (s *Schema) AddRequired(items ...string) *Schema { s.Required = append(s.Required, items...) return s } // WithMaxLength sets a max length value func (s *Schema) WithMaxLength(max int64) *Schema { s.MaxLength = &max return s } // WithMinLength sets a min length value func (s *Schema) WithMinLength(min int64) *Schema { s.MinLength = &min return s } // WithPattern sets a pattern value func (s *Schema) WithPattern(pattern string) *Schema { s.Pattern = pattern return s } // WithMultipleOf sets a multiple of value func (s *Schema) WithMultipleOf(number float64) *Schema { s.MultipleOf = &number return s } // WithMaximum sets a maximum number value func (s *Schema) WithMaximum(max float64, exclusive bool) *Schema { s.Maximum = &max s.ExclusiveMaximum = exclusive return s } // WithMinimum sets a minimum number value func (s *Schema) WithMinimum(min float64, exclusive bool) *Schema { s.Minimum = &min s.ExclusiveMinimum = exclusive return s } // WithEnum sets a the enum values (replace) func (s *Schema) WithEnum(values ...interface{}) *Schema { s.Enum = append([]interface{}{}, values...) return s } // WithMaxItems sets the max items func (s *Schema) WithMaxItems(size int64) *Schema { s.MaxItems = &size return s } // WithMinItems sets the min items func (s *Schema) WithMinItems(size int64) *Schema { s.MinItems = &size return s } // UniqueValues dictates that this array can only have unique items func (s *Schema) UniqueValues() *Schema { s.UniqueItems = true return s } // AllowDuplicates this array can have duplicates func (s *Schema) AllowDuplicates() *Schema { s.UniqueItems = false return s } // AddToAllOf adds a schema to the allOf property func (s *Schema) AddToAllOf(schemas ...Schema) *Schema { s.AllOf = append(s.AllOf, schemas...) return s } // WithDiscriminator sets the name of the discriminator field func (s *Schema) WithDiscriminator(discriminator string) *Schema { s.Discriminator = discriminator return s } // AsReadOnly flags this schema as readonly func (s *Schema) AsReadOnly() *Schema { s.ReadOnly = true return s } // AsWritable flags this schema as writeable (not read-only) func (s *Schema) AsWritable() *Schema { s.ReadOnly = false return s } // WithExample sets the example for this schema func (s *Schema) WithExample(example interface{}) *Schema { s.Example = example return s } // WithExternalDocs sets/removes the external docs for/from this schema. // When you pass empty strings as params the external documents will be removed. // When you pass non-empty string as one value then those values will be used on the external docs object. // So when you pass a non-empty description, you should also pass the url and vice versa. func (s *Schema) WithExternalDocs(description, url string) *Schema { if description == "" && url == "" { s.ExternalDocs = nil return s } if s.ExternalDocs == nil { s.ExternalDocs = &ExternalDocumentation{} } s.ExternalDocs.Description = description s.ExternalDocs.URL = url return s } // MarshalJSON marshal this to JSON func (s Schema) MarshalJSON() ([]byte, error) { if internal.UseOptimizedJSONMarshaling { return internal.DeterministicMarshal(s) } b1, err := json.Marshal(s.SchemaProps) if err != nil { return nil, fmt.Errorf("schema props %v", err) } b2, err := json.Marshal(s.VendorExtensible) if err != nil { return nil, fmt.Errorf("vendor props %v", err) } b3, err := s.Ref.MarshalJSON() if err != nil { return nil, fmt.Errorf("ref prop %v", err) } b4, err := s.Schema.MarshalJSON() if err != nil { return nil, fmt.Errorf("schema prop %v", err) } b5, err := json.Marshal(s.SwaggerSchemaProps) if err != nil { return nil, fmt.Errorf("common validations %v", err) } var b6 []byte if s.ExtraProps != nil { jj, err := json.Marshal(s.ExtraProps) if err != nil { return nil, fmt.Errorf("extra props %v", err) } b6 = jj } return swag.ConcatJSON(b1, b2, b3, b4, b5, b6), nil } func (s Schema) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { type ArbitraryKeys map[string]interface{} var x struct { ArbitraryKeys SchemaProps schemaPropsOmitZero `json:",inline"` SwaggerSchemaProps swaggerSchemaPropsOmitZero `json:",inline"` Schema string `json:"$schema,omitempty"` Ref string `json:"$ref,omitempty"` } x.ArbitraryKeys = make(map[string]any, len(s.Extensions)+len(s.ExtraProps)) for k, v := range s.Extensions { if internal.IsExtensionKey(k) { x.ArbitraryKeys[k] = v } } for k, v := range s.ExtraProps { x.ArbitraryKeys[k] = v } x.SchemaProps = schemaPropsOmitZero(s.SchemaProps) x.SwaggerSchemaProps = swaggerSchemaPropsOmitZero(s.SwaggerSchemaProps) x.Ref = s.Ref.String() x.Schema = string(s.Schema) return opts.MarshalNext(enc, x) } // UnmarshalJSON marshal this from JSON func (s *Schema) UnmarshalJSON(data []byte) error { if internal.UseOptimizedJSONUnmarshaling { return jsonv2.Unmarshal(data, s) } props := struct { SchemaProps SwaggerSchemaProps }{} if err := json.Unmarshal(data, &props); err != nil { return err } sch := Schema{ SchemaProps: props.SchemaProps, SwaggerSchemaProps: props.SwaggerSchemaProps, } var d map[string]interface{} if err := json.Unmarshal(data, &d); err != nil { return err } _ = sch.Ref.fromMap(d) _ = sch.Schema.fromMap(d) delete(d, "$ref") delete(d, "$schema") for _, pn := range swag.DefaultJSONNameProvider.GetJSONNames(s) { delete(d, pn) } for k, vv := range d { lk := strings.ToLower(k) if strings.HasPrefix(lk, "x-") { if sch.Extensions == nil { sch.Extensions = map[string]interface{}{} } sch.Extensions[k] = vv continue } if sch.ExtraProps == nil { sch.ExtraProps = map[string]interface{}{} } sch.ExtraProps[k] = vv } *s = sch return nil } func (s *Schema) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { var x struct { Extensions SchemaProps SwaggerSchemaProps } if err := opts.UnmarshalNext(dec, &x); err != nil { return err } if err := x.Ref.fromMap(x.Extensions); err != nil { return err } if err := x.Schema.fromMap(x.Extensions); err != nil { return err } delete(x.Extensions, "$ref") delete(x.Extensions, "$schema") for _, pn := range swag.DefaultJSONNameProvider.GetJSONNames(s) { delete(x.Extensions, pn) } if len(x.Extensions) == 0 { x.Extensions = nil } s.ExtraProps = x.Extensions.sanitizeWithExtra() s.Extensions = internal.SanitizeExtensions(x.Extensions) s.SchemaProps = x.SchemaProps s.SwaggerSchemaProps = x.SwaggerSchemaProps return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/validation/spec/external_docs.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/validation/spec/external_docs.go
// Copyright 2015 go-swagger maintainers // // 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 spec // ExternalDocumentation allows referencing an external resource for // extended documentation. // // For more information: http://goo.gl/8us55a#externalDocumentationObject type ExternalDocumentation struct { Description string `json:"description,omitempty"` URL string `json:"url,omitempty"` }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/util/proto/document.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/util/proto/document.go
/* 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 proto import ( "fmt" "sort" "strings" openapi_v2 "github.com/google/gnostic-models/openapiv2" yaml "sigs.k8s.io/yaml/goyaml.v2" ) func newSchemaError(path *Path, format string, a ...interface{}) error { err := fmt.Sprintf(format, a...) if path.Len() == 0 { return fmt.Errorf("SchemaError: %v", err) } return fmt.Errorf("SchemaError(%v): %v", path, err) } // VendorExtensionToMap converts openapi VendorExtension to a map. func VendorExtensionToMap(e []*openapi_v2.NamedAny) map[string]interface{} { values := map[string]interface{}{} for _, na := range e { if na.GetName() == "" || na.GetValue() == nil { continue } if na.GetValue().GetYaml() == "" { continue } var value interface{} err := yaml.Unmarshal([]byte(na.GetValue().GetYaml()), &value) if err != nil { continue } values[na.GetName()] = value } return values } // Definitions is an implementation of `Models`. It looks for // models in an openapi Schema. type Definitions struct { models map[string]Schema } var _ Models = &Definitions{} // NewOpenAPIData creates a new `Models` out of the openapi document. func NewOpenAPIData(doc *openapi_v2.Document) (Models, error) { definitions := Definitions{ models: map[string]Schema{}, } // Save the list of all models first. This will allow us to // validate that we don't have any dangling reference. for _, namedSchema := range doc.GetDefinitions().GetAdditionalProperties() { definitions.models[namedSchema.GetName()] = nil } // Now, parse each model. We can validate that references exists. for _, namedSchema := range doc.GetDefinitions().GetAdditionalProperties() { path := NewPath(namedSchema.GetName()) schema, err := definitions.ParseSchema(namedSchema.GetValue(), &path) if err != nil { return nil, err } definitions.models[namedSchema.GetName()] = schema } return &definitions, nil } // We believe the schema is a reference, verify that and returns a new // Schema func (d *Definitions) parseReference(s *openapi_v2.Schema, path *Path) (Schema, error) { // TODO(wrong): a schema with a $ref can have properties. We can ignore them (would be incomplete), but we cannot return an error. if len(s.GetProperties().GetAdditionalProperties()) > 0 { return nil, newSchemaError(path, "unallowed embedded type definition") } // TODO(wrong): a schema with a $ref can have a type. We can ignore it (would be incomplete), but we cannot return an error. if len(s.GetType().GetValue()) > 0 { return nil, newSchemaError(path, "definition reference can't have a type") } // TODO(wrong): $refs outside of the definitions are completely valid. We can ignore them (would be incomplete), but we cannot return an error. if !strings.HasPrefix(s.GetXRef(), "#/definitions/") { return nil, newSchemaError(path, "unallowed reference to non-definition %q", s.GetXRef()) } reference := strings.TrimPrefix(s.GetXRef(), "#/definitions/") if _, ok := d.models[reference]; !ok { return nil, newSchemaError(path, "unknown model in reference: %q", reference) } base, err := d.parseBaseSchema(s, path) if err != nil { return nil, err } return &Ref{ BaseSchema: base, reference: reference, definitions: d, }, nil } func parseDefault(def *openapi_v2.Any) (interface{}, error) { if def == nil { return nil, nil } var i interface{} if err := yaml.Unmarshal([]byte(def.Yaml), &i); err != nil { return nil, err } return i, nil } func (d *Definitions) parseBaseSchema(s *openapi_v2.Schema, path *Path) (BaseSchema, error) { def, err := parseDefault(s.GetDefault()) if err != nil { return BaseSchema{}, err } return BaseSchema{ Description: s.GetDescription(), Default: def, Extensions: VendorExtensionToMap(s.GetVendorExtension()), Path: *path, }, nil } // We believe the schema is a map, verify and return a new schema func (d *Definitions) parseMap(s *openapi_v2.Schema, path *Path) (Schema, error) { if len(s.GetType().GetValue()) != 0 && s.GetType().GetValue()[0] != object { return nil, newSchemaError(path, "invalid object type") } var sub Schema // TODO(incomplete): this misses the boolean case as AdditionalProperties is a bool+schema sum type. if s.GetAdditionalProperties().GetSchema() == nil { base, err := d.parseBaseSchema(s, path) if err != nil { return nil, err } sub = &Arbitrary{ BaseSchema: base, } } else { var err error sub, err = d.ParseSchema(s.GetAdditionalProperties().GetSchema(), path) if err != nil { return nil, err } } base, err := d.parseBaseSchema(s, path) if err != nil { return nil, err } return &Map{ BaseSchema: base, SubType: sub, }, nil } func (d *Definitions) parsePrimitive(s *openapi_v2.Schema, path *Path) (Schema, error) { var t string if len(s.GetType().GetValue()) > 1 { return nil, newSchemaError(path, "primitive can't have more than 1 type") } if len(s.GetType().GetValue()) == 1 { t = s.GetType().GetValue()[0] } switch t { case String: // do nothing case Number: // do nothing case Integer: // do nothing case Boolean: // do nothing // TODO(wrong): this misses "null". Would skip the null case (would be incomplete), but we cannot return an error. default: return nil, newSchemaError(path, "Unknown primitive type: %q", t) } base, err := d.parseBaseSchema(s, path) if err != nil { return nil, err } return &Primitive{ BaseSchema: base, Type: t, Format: s.GetFormat(), }, nil } func (d *Definitions) parseArray(s *openapi_v2.Schema, path *Path) (Schema, error) { if len(s.GetType().GetValue()) != 1 { return nil, newSchemaError(path, "array should have exactly one type") } if s.GetType().GetValue()[0] != array { return nil, newSchemaError(path, `array should have type "array"`) } if len(s.GetItems().GetSchema()) != 1 { // TODO(wrong): Items can have multiple elements. We can ignore Items then (would be incomplete), but we cannot return an error. // TODO(wrong): "type: array" witohut any items at all is completely valid. return nil, newSchemaError(path, "array should have exactly one sub-item") } sub, err := d.ParseSchema(s.GetItems().GetSchema()[0], path) if err != nil { return nil, err } base, err := d.parseBaseSchema(s, path) if err != nil { return nil, err } return &Array{ BaseSchema: base, SubType: sub, }, nil } func (d *Definitions) parseKind(s *openapi_v2.Schema, path *Path) (Schema, error) { if len(s.GetType().GetValue()) != 0 && s.GetType().GetValue()[0] != object { return nil, newSchemaError(path, "invalid object type") } if s.GetProperties() == nil { return nil, newSchemaError(path, "object doesn't have properties") } fields := map[string]Schema{} fieldOrder := []string{} for _, namedSchema := range s.GetProperties().GetAdditionalProperties() { var err error name := namedSchema.GetName() path := path.FieldPath(name) fields[name], err = d.ParseSchema(namedSchema.GetValue(), &path) if err != nil { return nil, err } fieldOrder = append(fieldOrder, name) } base, err := d.parseBaseSchema(s, path) if err != nil { return nil, err } return &Kind{ BaseSchema: base, RequiredFields: s.GetRequired(), Fields: fields, FieldOrder: fieldOrder, }, nil } func (d *Definitions) parseArbitrary(s *openapi_v2.Schema, path *Path) (Schema, error) { base, err := d.parseBaseSchema(s, path) if err != nil { return nil, err } return &Arbitrary{ BaseSchema: base, }, nil } // ParseSchema creates a walkable Schema from an openapi schema. While // this function is public, it doesn't leak through the interface. func (d *Definitions) ParseSchema(s *openapi_v2.Schema, path *Path) (Schema, error) { if s.GetXRef() != "" { // TODO(incomplete): ignoring the rest of s is wrong. As long as there are no conflict, everything from s must be considered // Reference: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#path-item-object return d.parseReference(s, path) } objectTypes := s.GetType().GetValue() switch len(objectTypes) { case 0: // in the OpenAPI schema served by older k8s versions, object definitions created from structs did not include // the type:object property (they only included the "properties" property), so we need to handle this case // TODO: validate that we ever published empty, non-nil properties. JSON roundtripping nils them. if s.GetProperties() != nil { // TODO(wrong): when verifying a non-object later against this, it will be rejected as invalid type. // TODO(CRD validation schema publishing): we have to filter properties (empty or not) if type=object is not given return d.parseKind(s, path) } else { // Definition has no type and no properties. Treat it as an arbitrary value // TODO(incomplete): what if it has additionalProperties=false or patternProperties? // ANSWER: parseArbitrary is less strict than it has to be with patternProperties (which is ignored). So this is correct (of course not complete). return d.parseArbitrary(s, path) } case 1: t := objectTypes[0] switch t { case object: if s.GetProperties() != nil { return d.parseKind(s, path) } else { return d.parseMap(s, path) } case array: return d.parseArray(s, path) } return d.parsePrimitive(s, path) default: // the OpenAPI generator never generates (nor it ever did in the past) OpenAPI type definitions with multiple types // TODO(wrong): this is rejecting a completely valid OpenAPI spec // TODO(CRD validation schema publishing): filter these out return nil, newSchemaError(path, "definitions with multiple types aren't supported") } } // LookupModel is public through the interface of Models. It // returns a visitable schema from the given model name. func (d *Definitions) LookupModel(model string) Schema { return d.models[model] } func (d *Definitions) ListModels() []string { models := []string{} for model := range d.models { models = append(models, model) } sort.Strings(models) return models } type Ref struct { BaseSchema reference string definitions *Definitions } var _ Reference = &Ref{} func (r *Ref) Reference() string { return r.reference } func (r *Ref) SubSchema() Schema { return r.definitions.models[r.reference] } func (r *Ref) Accept(v SchemaVisitor) { v.VisitReference(r) } func (r *Ref) GetName() string { return fmt.Sprintf("Reference to %q", r.reference) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/util/proto/openapi.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/util/proto/openapi.go
/* 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 proto import ( "fmt" "sort" "strings" ) // Defines openapi types. const ( Integer = "integer" Number = "number" String = "string" Boolean = "boolean" // These types are private as they should never leak, and are // represented by actual structs. array = "array" object = "object" ) // Models interface describe a model provider. They can give you the // schema for a specific model. type Models interface { LookupModel(string) Schema ListModels() []string } // SchemaVisitor is an interface that you need to implement if you want // to "visit" an openapi schema. A dispatch on the Schema type will call // the appropriate function based on its actual type: // - Array is a list of one and only one given subtype // - Map is a map of string to one and only one given subtype // - Primitive can be string, integer, number and boolean. // - Kind is an object with specific fields mapping to specific types. // - Reference is a link to another definition. type SchemaVisitor interface { VisitArray(*Array) VisitMap(*Map) VisitPrimitive(*Primitive) VisitKind(*Kind) VisitReference(Reference) } // SchemaVisitorArbitrary is an additional visitor interface which handles // arbitrary types. For backwards compatibility, it's a separate interface // which is checked for at runtime. type SchemaVisitorArbitrary interface { SchemaVisitor VisitArbitrary(*Arbitrary) } // Schema is the base definition of an openapi type. type Schema interface { // Giving a visitor here will let you visit the actual type. Accept(SchemaVisitor) // Pretty print the name of the type. GetName() string // Describes how to access this field. GetPath() *Path // Describes the field. GetDescription() string // Default for that schema. GetDefault() interface{} // Returns type extensions. GetExtensions() map[string]interface{} } // Path helps us keep track of type paths type Path struct { parent *Path key string } func NewPath(key string) Path { return Path{key: key} } func (p *Path) Get() []string { if p == nil { return []string{} } if p.key == "" { return p.parent.Get() } return append(p.parent.Get(), p.key) } func (p *Path) Len() int { return len(p.Get()) } func (p *Path) String() string { return strings.Join(p.Get(), "") } // ArrayPath appends an array index and creates a new path func (p *Path) ArrayPath(i int) Path { return Path{ parent: p, key: fmt.Sprintf("[%d]", i), } } // FieldPath appends a field name and creates a new path func (p *Path) FieldPath(field string) Path { return Path{ parent: p, key: fmt.Sprintf(".%s", field), } } // BaseSchema holds data used by each types of schema. type BaseSchema struct { Description string Extensions map[string]interface{} Default interface{} Path Path } func (b *BaseSchema) GetDescription() string { return b.Description } func (b *BaseSchema) GetExtensions() map[string]interface{} { return b.Extensions } func (b *BaseSchema) GetDefault() interface{} { return b.Default } func (b *BaseSchema) GetPath() *Path { return &b.Path } // Array must have all its element of the same `SubType`. type Array struct { BaseSchema SubType Schema } var _ Schema = &Array{} func (a *Array) Accept(v SchemaVisitor) { v.VisitArray(a) } func (a *Array) GetName() string { return fmt.Sprintf("Array of %s", a.SubType.GetName()) } // Kind is a complex object. It can have multiple different // subtypes for each field, as defined in the `Fields` field. Mandatory // fields are listed in `RequiredFields`. The key of the object is // always of type `string`. type Kind struct { BaseSchema // Lists names of required fields. RequiredFields []string // Maps field names to types. Fields map[string]Schema // FieldOrder reports the canonical order for the fields. FieldOrder []string } var _ Schema = &Kind{} func (k *Kind) Accept(v SchemaVisitor) { v.VisitKind(k) } func (k *Kind) GetName() string { properties := []string{} for key := range k.Fields { properties = append(properties, key) } return fmt.Sprintf("Kind(%v)", properties) } // IsRequired returns true if `field` is a required field for this type. func (k *Kind) IsRequired(field string) bool { for _, f := range k.RequiredFields { if f == field { return true } } return false } // Keys returns a alphabetically sorted list of keys. func (k *Kind) Keys() []string { keys := make([]string, 0) for key := range k.Fields { keys = append(keys, key) } sort.Strings(keys) return keys } // Map is an object who values must all be of the same `SubType`. // The key of the object is always of type `string`. type Map struct { BaseSchema SubType Schema } var _ Schema = &Map{} func (m *Map) Accept(v SchemaVisitor) { v.VisitMap(m) } func (m *Map) GetName() string { return fmt.Sprintf("Map of %s", m.SubType.GetName()) } // Primitive is a literal. There can be multiple types of primitives, // and this subtype can be visited through the `subType` field. type Primitive struct { BaseSchema // Type of a primitive must be one of: integer, number, string, boolean. Type string Format string } var _ Schema = &Primitive{} func (p *Primitive) Accept(v SchemaVisitor) { v.VisitPrimitive(p) } func (p *Primitive) GetName() string { if p.Format == "" { return p.Type } return fmt.Sprintf("%s (%s)", p.Type, p.Format) } // Arbitrary is a value of any type (primitive, object or array) type Arbitrary struct { BaseSchema } var _ Schema = &Arbitrary{} func (a *Arbitrary) Accept(v SchemaVisitor) { if visitor, ok := v.(SchemaVisitorArbitrary); ok { visitor.VisitArbitrary(a) } } func (a *Arbitrary) GetName() string { return "Arbitrary value (primitive, object or array)" } // Reference implementation depends on the type of document. type Reference interface { Schema Reference() string SubSchema() Schema }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/util/proto/doc.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/util/proto/doc.go
/* 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 proto is a collection of libraries for parsing and indexing the type definitions. // The openapi spec contains the object model definitions and extensions metadata. package proto
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/util/proto/document_v3.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/util/proto/document_v3.go
/* Copyright 2022 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 proto import ( "fmt" "reflect" "strings" openapi_v3 "github.com/google/gnostic-models/openapiv3" "gopkg.in/yaml.v3" ) // Temporary parse implementation to be used until gnostic->kube-openapi conversion // is possible. func NewOpenAPIV3Data(doc *openapi_v3.Document) (Models, error) { definitions := Definitions{ models: map[string]Schema{}, } schemas := doc.GetComponents().GetSchemas() if schemas == nil { return &definitions, nil } // Save the list of all models first. This will allow us to // validate that we don't have any dangling reference. for _, namedSchema := range schemas.GetAdditionalProperties() { definitions.models[namedSchema.GetName()] = nil } // Now, parse each model. We can validate that references exists. for _, namedSchema := range schemas.GetAdditionalProperties() { path := NewPath(namedSchema.GetName()) val := namedSchema.GetValue() if val == nil { continue } if schema, err := definitions.ParseV3SchemaOrReference(namedSchema.GetValue(), &path); err != nil { return nil, err } else if schema != nil { // Schema may be nil if we hit incompleteness in the conversion, // but not a fatal error definitions.models[namedSchema.GetName()] = schema } } return &definitions, nil } func (d *Definitions) ParseV3SchemaReference(s *openapi_v3.Reference, path *Path) (Schema, error) { base := &BaseSchema{ Description: s.Description, } if !strings.HasPrefix(s.GetXRef(), "#/components/schemas") { // Only resolve references to components/schemas. We may add support // later for other in-spec paths, but otherwise treat unrecognized // refs as arbitrary/unknown values. return &Arbitrary{ BaseSchema: *base, }, nil } reference := strings.TrimPrefix(s.GetXRef(), "#/components/schemas/") if _, ok := d.models[reference]; !ok { return nil, newSchemaError(path, "unknown model in reference: %q", reference) } return &Ref{ BaseSchema: BaseSchema{ Description: s.Description, }, reference: reference, definitions: d, }, nil } func (d *Definitions) ParseV3SchemaOrReference(s *openapi_v3.SchemaOrReference, path *Path) (Schema, error) { var schema Schema var err error switch v := s.GetOneof().(type) { case *openapi_v3.SchemaOrReference_Reference: // Any references stored in #!/components/... are bound to refer // to external documents. This API does not support such a // feature. // // In the weird case that this is a reference to a schema that is // not external, we attempt to parse anyway schema, err = d.ParseV3SchemaReference(v.Reference, path) case *openapi_v3.SchemaOrReference_Schema: schema, err = d.ParseSchemaV3(v.Schema, path) default: panic("unexpected type") } return schema, err } // ParseSchema creates a walkable Schema from an openapi v3 schema. While // this function is public, it doesn't leak through the interface. func (d *Definitions) ParseSchemaV3(s *openapi_v3.Schema, path *Path) (Schema, error) { switch s.GetType() { case object: for _, extension := range s.GetSpecificationExtension() { if extension.Name == "x-kubernetes-group-version-kind" { // Objects with x-kubernetes-group-version-kind are always top // level types. return d.parseV3Kind(s, path) } } if len(s.GetProperties().GetAdditionalProperties()) > 0 { return d.parseV3Kind(s, path) } return d.parseV3Map(s, path) case array: return d.parseV3Array(s, path) case String, Number, Integer, Boolean: return d.parseV3Primitive(s, path) default: return d.parseV3Arbitrary(s, path) } } func (d *Definitions) parseV3Kind(s *openapi_v3.Schema, path *Path) (Schema, error) { if s.GetType() != object { return nil, newSchemaError(path, "invalid object type") } else if s.GetProperties() == nil { return nil, newSchemaError(path, "object doesn't have properties") } fields := map[string]Schema{} fieldOrder := []string{} for _, namedSchema := range s.GetProperties().GetAdditionalProperties() { var err error name := namedSchema.GetName() path := path.FieldPath(name) fields[name], err = d.ParseV3SchemaOrReference(namedSchema.GetValue(), &path) if err != nil { return nil, err } fieldOrder = append(fieldOrder, name) } base, err := d.parseV3BaseSchema(s, path) if err != nil { return nil, err } return &Kind{ BaseSchema: *base, RequiredFields: s.GetRequired(), Fields: fields, FieldOrder: fieldOrder, }, nil } func (d *Definitions) parseV3Arbitrary(s *openapi_v3.Schema, path *Path) (Schema, error) { base, err := d.parseV3BaseSchema(s, path) if err != nil { return nil, err } return &Arbitrary{ BaseSchema: *base, }, nil } func (d *Definitions) parseV3Primitive(s *openapi_v3.Schema, path *Path) (Schema, error) { switch s.GetType() { case String: // do nothing case Number: // do nothing case Integer: // do nothing case Boolean: // do nothing default: // Unsupported primitive type. Treat as arbitrary type return d.parseV3Arbitrary(s, path) } base, err := d.parseV3BaseSchema(s, path) if err != nil { return nil, err } return &Primitive{ BaseSchema: *base, Type: s.GetType(), Format: s.GetFormat(), }, nil } func (d *Definitions) parseV3Array(s *openapi_v3.Schema, path *Path) (Schema, error) { if s.GetType() != array { return nil, newSchemaError(path, `array should have type "array"`) } else if len(s.GetItems().GetSchemaOrReference()) != 1 { // This array can have multiple types in it (or no types at all) // This is not supported by this conversion. // Just return an arbitrary type return d.parseV3Arbitrary(s, path) } sub, err := d.ParseV3SchemaOrReference(s.GetItems().GetSchemaOrReference()[0], path) if err != nil { return nil, err } base, err := d.parseV3BaseSchema(s, path) if err != nil { return nil, err } return &Array{ BaseSchema: *base, SubType: sub, }, nil } // We believe the schema is a map, verify and return a new schema func (d *Definitions) parseV3Map(s *openapi_v3.Schema, path *Path) (Schema, error) { if s.GetType() != object { return nil, newSchemaError(path, "invalid object type") } var sub Schema switch p := s.GetAdditionalProperties().GetOneof().(type) { case *openapi_v3.AdditionalPropertiesItem_Boolean: // What does this boolean even mean? base, err := d.parseV3BaseSchema(s, path) if err != nil { return nil, err } sub = &Arbitrary{ BaseSchema: *base, } case *openapi_v3.AdditionalPropertiesItem_SchemaOrReference: if schema, err := d.ParseV3SchemaOrReference(p.SchemaOrReference, path); err != nil { return nil, err } else { sub = schema } case nil: // no subtype? sub = &Arbitrary{} default: panic("unrecognized type " + reflect.TypeOf(p).Name()) } base, err := d.parseV3BaseSchema(s, path) if err != nil { return nil, err } return &Map{ BaseSchema: *base, SubType: sub, }, nil } func parseV3Interface(def *yaml.Node) (interface{}, error) { if def == nil { return nil, nil } var i interface{} if err := def.Decode(&i); err != nil { return nil, err } return i, nil } func (d *Definitions) parseV3BaseSchema(s *openapi_v3.Schema, path *Path) (*BaseSchema, error) { if s == nil { return nil, fmt.Errorf("cannot initialize BaseSchema from nil") } def, err := parseV3Interface(s.GetDefault().ToRawInfo()) if err != nil { return nil, err } return &BaseSchema{ Description: s.GetDescription(), Default: def, Extensions: SpecificationExtensionToMap(s.GetSpecificationExtension()), Path: *path, }, nil } func SpecificationExtensionToMap(e []*openapi_v3.NamedAny) map[string]interface{} { values := map[string]interface{}{} for _, na := range e { if na.GetName() == "" || na.GetValue() == nil { continue } if na.GetValue().GetYaml() == "" { continue } var value interface{} err := yaml.Unmarshal([]byte(na.GetValue().GetYaml()), &value) if err != nil { continue } values[na.GetName()] = value } return values }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/spec3/fuzz.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/spec3/fuzz.go
package spec3 import ( "math/rand" "strings" "sigs.k8s.io/randfill" "k8s.io/kube-openapi/pkg/validation/spec" ) // refChance is the chance that a particular component will use a $ref // instead of fuzzed. Expressed as a fraction 1/n, currently there is // a 1/3 chance that a ref will be used. const refChance = 3 const alphaNumChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" func randAlphanumString() string { arr := make([]string, rand.Intn(10)+5) for i := 0; i < len(arr); i++ { arr[i] = string(alphaNumChars[rand.Intn(len(alphaNumChars))]) } return strings.Join(arr, "") } var OpenAPIV3FuzzFuncs []interface{} = []interface{}{ func(s *string, c randfill.Continue) { // All OpenAPI V3 map keys must follow the corresponding // regex. Note that this restricts the range for all other // string values as well. str := randAlphanumString() *s = str }, func(o *OpenAPI, c randfill.Continue) { c.FillNoCustom(o) o.Version = "3.0.0" for i, val := range o.SecurityRequirement { if val == nil { o.SecurityRequirement[i] = make(map[string][]string) } for k, v := range val { if v == nil { val[k] = make([]string, 0) } } } }, func(r *interface{}, c randfill.Continue) { switch c.Intn(3) { case 0: *r = nil case 1: n := c.String(0) + "x" *r = n case 2: n := c.Float64() *r = n } }, func(v **spec.Info, c randfill.Continue) { // Info is never nil *v = &spec.Info{} c.FillNoCustom(*v) (*v).Title = c.String(0) + "x" }, func(v *Paths, c randfill.Continue) { c.Fill(&v.VendorExtensible) num := c.Intn(5) if num > 0 { v.Paths = make(map[string]*Path) } for i := 0; i < num; i++ { val := Path{} c.Fill(&val) v.Paths["/"+c.String(0)] = &val } }, func(v *SecurityScheme, c randfill.Continue) { if c.Intn(refChance) == 0 { c.Fill(&v.Refable) return } switch c.Intn(4) { case 0: v.Type = "apiKey" v.Name = c.String(0) + "x" switch c.Intn(3) { case 0: v.In = "query" case 1: v.In = "header" case 2: v.In = "cookie" } case 1: v.Type = "http" case 2: v.Type = "oauth2" v.Flows = make(map[string]*OAuthFlow) flow := OAuthFlow{} flow.AuthorizationUrl = c.String(0) + "x" v.Flows["implicit"] = &flow flow.Scopes = make(map[string]string) flow.Scopes["foo"] = "bar" case 3: v.Type = "openIdConnect" v.OpenIdConnectUrl = "https://" + c.String(0) } v.Scheme = "basic" }, func(v *spec.Ref, c randfill.Continue) { switch c.Intn(7) { case 0: *v = spec.MustCreateRef("#/components/schemas/" + randAlphanumString()) case 1: *v = spec.MustCreateRef("#/components/responses/" + randAlphanumString()) case 2: *v = spec.MustCreateRef("#/components/headers/" + randAlphanumString()) case 3: *v = spec.MustCreateRef("#/components/securitySchemes/" + randAlphanumString()) case 5: *v = spec.MustCreateRef("#/components/parameters/" + randAlphanumString()) case 6: *v = spec.MustCreateRef("#/components/requestBodies/" + randAlphanumString()) } }, func(v *Parameter, c randfill.Continue) { if c.Intn(refChance) == 0 { c.Fill(&v.Refable) return } c.Fill(&v.ParameterProps) c.Fill(&v.VendorExtensible) switch c.Intn(3) { case 0: // Header param v.In = "query" case 1: v.In = "header" case 2: v.In = "cookie" } }, func(v *RequestBody, c randfill.Continue) { if c.Intn(refChance) == 0 { c.Fill(&v.Refable) return } c.Fill(&v.RequestBodyProps) c.Fill(&v.VendorExtensible) }, func(v *Header, c randfill.Continue) { if c.Intn(refChance) == 0 { c.Fill(&v.Refable) return } c.Fill(&v.HeaderProps) c.Fill(&v.VendorExtensible) }, func(v *ResponsesProps, c randfill.Continue) { c.Fill(&v.Default) n := c.Intn(5) for i := 0; i < n; i++ { r2 := Response{} c.Fill(&r2) // HTTP Status code in 100-599 Range code := c.Intn(500) + 100 v.StatusCodeResponses = make(map[int]*Response) v.StatusCodeResponses[code] = &r2 } }, func(v *Response, c randfill.Continue) { if c.Intn(refChance) == 0 { c.Fill(&v.Refable) return } c.Fill(&v.ResponseProps) c.Fill(&v.VendorExtensible) }, func(v *Operation, c randfill.Continue) { c.FillNoCustom(v) // Do not fuzz null values into the array. for i, val := range v.SecurityRequirement { if val == nil { v.SecurityRequirement[i] = make(map[string][]string) } for k, v := range val { if v == nil { val[k] = make([]string, 0) } } } }, func(v *spec.Extensions, c randfill.Continue) { numChildren := c.Intn(5) for i := 0; i < numChildren; i++ { if *v == nil { *v = spec.Extensions{} } (*v)["x-"+c.String(0)] = c.String(0) } }, func(v *spec.ExternalDocumentation, c randfill.Continue) { c.Fill(&v.Description) v.URL = "https://" + randAlphanumString() }, func(v *spec.SchemaURL, c randfill.Continue) { *v = spec.SchemaURL("https://" + randAlphanumString()) }, func(v *spec.SchemaOrBool, c randfill.Continue) { *v = spec.SchemaOrBool{} if c.Bool() { v.Allows = c.Bool() } else { v.Schema = &spec.Schema{} v.Allows = true c.Fill(&v.Schema) } }, func(v *spec.SchemaOrArray, c randfill.Continue) { *v = spec.SchemaOrArray{} if c.Bool() { schema := spec.Schema{} c.Fill(&schema) v.Schema = &schema } else { v.Schemas = []spec.Schema{} numChildren := c.Intn(5) for i := 0; i < numChildren; i++ { schema := spec.Schema{} c.Fill(&schema) v.Schemas = append(v.Schemas, schema) } } }, func(v *spec.SchemaOrStringArray, c randfill.Continue) { if c.Bool() { *v = spec.SchemaOrStringArray{} if c.Bool() { c.Fill(&v.Property) } else { c.Fill(&v.Schema) } } }, func(v *spec.Schema, c randfill.Continue) { if c.Intn(refChance) == 0 { c.Fill(&v.Ref) return } if c.Bool() { // file schema c.Fill(&v.Default) c.Fill(&v.Description) c.Fill(&v.Example) c.Fill(&v.ExternalDocs) c.Fill(&v.Format) c.Fill(&v.ReadOnly) c.Fill(&v.Required) c.Fill(&v.Title) v.Type = spec.StringOrArray{"file"} } else { // normal schema c.Fill(&v.SchemaProps) c.Fill(&v.SwaggerSchemaProps) c.Fill(&v.VendorExtensible) c.Fill(&v.ExtraProps) } }, }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/spec3/request_body.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/spec3/request_body.go
/* Copyright 2021 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 spec3 import ( "encoding/json" "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" "k8s.io/kube-openapi/pkg/validation/spec" ) // RequestBody describes a single request body, more at https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#requestBodyObject // // Note that this struct is actually a thin wrapper around RequestBodyProps to make it referable and extensible type RequestBody struct { spec.Refable RequestBodyProps spec.VendorExtensible } // MarshalJSON is a custom marshal function that knows how to encode RequestBody as JSON func (r *RequestBody) MarshalJSON() ([]byte, error) { if internal.UseOptimizedJSONMarshalingV3 { return internal.DeterministicMarshal(r) } b1, err := json.Marshal(r.Refable) if err != nil { return nil, err } b2, err := json.Marshal(r.RequestBodyProps) if err != nil { return nil, err } b3, err := json.Marshal(r.VendorExtensible) if err != nil { return nil, err } return swag.ConcatJSON(b1, b2, b3), nil } func (r *RequestBody) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { var x struct { Ref string `json:"$ref,omitempty"` RequestBodyProps requestBodyPropsOmitZero `json:",inline"` spec.Extensions } x.Ref = r.Refable.Ref.String() x.Extensions = internal.SanitizeExtensions(r.Extensions) x.RequestBodyProps = requestBodyPropsOmitZero(r.RequestBodyProps) return opts.MarshalNext(enc, x) } func (r *RequestBody) UnmarshalJSON(data []byte) error { if internal.UseOptimizedJSONUnmarshalingV3 { return jsonv2.Unmarshal(data, r) } if err := json.Unmarshal(data, &r.Refable); err != nil { return err } if err := json.Unmarshal(data, &r.RequestBodyProps); err != nil { return err } if err := json.Unmarshal(data, &r.VendorExtensible); err != nil { return err } return nil } // RequestBodyProps describes a single request body, more at https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#requestBodyObject type RequestBodyProps struct { // Description holds a brief description of the request body Description string `json:"description,omitempty"` // Content is the content of the request body. The key is a media type or media type range and the value describes it Content map[string]*MediaType `json:"content,omitempty"` // Required determines if the request body is required in the request Required bool `json:"required,omitempty"` } type requestBodyPropsOmitZero struct { Description string `json:"description,omitempty"` Content map[string]*MediaType `json:"content,omitempty"` Required bool `json:"required,omitzero"` } func (r *RequestBody) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { var x struct { spec.Extensions RequestBodyProps } if err := opts.UnmarshalNext(dec, &x); err != nil { return err } if err := internal.JSONRefFromMap(&r.Ref.Ref, x.Extensions); err != nil { return err } r.Extensions = internal.SanitizeExtensions(x.Extensions) r.RequestBodyProps = x.RequestBodyProps return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/spec3/external_documentation.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/spec3/external_documentation.go
/* Copyright 2021 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 spec3 import ( "encoding/json" "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" "k8s.io/kube-openapi/pkg/validation/spec" ) type ExternalDocumentation struct { ExternalDocumentationProps spec.VendorExtensible } type ExternalDocumentationProps struct { // Description is a short description of the target documentation. CommonMark syntax MAY be used for rich text representation. Description string `json:"description,omitempty"` // URL is the URL for the target documentation. URL string `json:"url"` } // MarshalJSON is a custom marshal function that knows how to encode Responses as JSON func (e *ExternalDocumentation) MarshalJSON() ([]byte, error) { if internal.UseOptimizedJSONMarshalingV3 { return internal.DeterministicMarshal(e) } b1, err := json.Marshal(e.ExternalDocumentationProps) if err != nil { return nil, err } b2, err := json.Marshal(e.VendorExtensible) if err != nil { return nil, err } return swag.ConcatJSON(b1, b2), nil } func (e *ExternalDocumentation) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { var x struct { ExternalDocumentationProps `json:",inline"` spec.Extensions } x.Extensions = internal.SanitizeExtensions(e.Extensions) x.ExternalDocumentationProps = e.ExternalDocumentationProps return opts.MarshalNext(enc, x) } func (e *ExternalDocumentation) UnmarshalJSON(data []byte) error { if internal.UseOptimizedJSONUnmarshalingV3 { return jsonv2.Unmarshal(data, e) } if err := json.Unmarshal(data, &e.ExternalDocumentationProps); err != nil { return err } if err := json.Unmarshal(data, &e.VendorExtensible); err != nil { return err } return nil } func (e *ExternalDocumentation) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { var x struct { spec.Extensions ExternalDocumentationProps } if err := opts.UnmarshalNext(dec, &x); err != nil { return err } e.Extensions = internal.SanitizeExtensions(x.Extensions) e.ExternalDocumentationProps = x.ExternalDocumentationProps return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/spec3/component.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/spec3/component.go
/* Copyright 2021 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 spec3 import "k8s.io/kube-openapi/pkg/validation/spec" // Components holds a set of reusable objects for different aspects of the OAS. // All objects defined within the components object will have no effect on the API // unless they are explicitly referenced from properties outside the components object. // // more at https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#componentsObject type Components struct { // Schemas holds reusable Schema Objects Schemas map[string]*spec.Schema `json:"schemas,omitempty"` // SecuritySchemes holds reusable Security Scheme Objects, more at https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#securitySchemeObject SecuritySchemes SecuritySchemes `json:"securitySchemes,omitempty"` // Responses holds reusable Responses Objects Responses map[string]*Response `json:"responses,omitempty"` // Parameters holds reusable Parameters Objects Parameters map[string]*Parameter `json:"parameters,omitempty"` // Example holds reusable Example objects Examples map[string]*Example `json:"examples,omitempty"` // RequestBodies holds reusable Request Body objects RequestBodies map[string]*RequestBody `json:"requestBodies,omitempty"` // Links is a map of operations links that can be followed from the response Links map[string]*Link `json:"links,omitempty"` // Headers holds a maps of a headers name to its definition Headers map[string]*Header `json:"headers,omitempty"` // all fields are defined at https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#componentsObject } // SecuritySchemes holds reusable Security Scheme Objects, more at https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#securitySchemeObject type SecuritySchemes map[string]*SecurityScheme
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/spec3/path.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/spec3/path.go
/* Copyright 2021 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 spec3 import ( "encoding/json" "fmt" "strings" "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" "k8s.io/kube-openapi/pkg/validation/spec" ) // Paths describes the available paths and operations for the API, more at https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#pathsObject type Paths struct { Paths map[string]*Path spec.VendorExtensible } // MarshalJSON is a custom marshal function that knows how to encode Paths as JSON func (p *Paths) MarshalJSON() ([]byte, error) { if internal.UseOptimizedJSONMarshalingV3 { return internal.DeterministicMarshal(p) } b1, err := json.Marshal(p.VendorExtensible) if err != nil { return nil, err } pths := make(map[string]*Path) for k, v := range p.Paths { if strings.HasPrefix(k, "/") { pths[k] = v } } b2, err := json.Marshal(pths) if err != nil { return nil, err } concated := swag.ConcatJSON(b1, b2) return concated, nil } func (p *Paths) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { m := make(map[string]any, len(p.Extensions)+len(p.Paths)) for k, v := range p.Extensions { if internal.IsExtensionKey(k) { m[k] = v } } for k, v := range p.Paths { if strings.HasPrefix(k, "/") { m[k] = v } } return opts.MarshalNext(enc, m) } // UnmarshalJSON hydrates this items instance with the data from JSON func (p *Paths) UnmarshalJSON(data []byte) error { if internal.UseOptimizedJSONUnmarshalingV3 { return jsonv2.Unmarshal(data, p) } var res map[string]json.RawMessage if err := json.Unmarshal(data, &res); err != nil { return err } for k, v := range res { if strings.HasPrefix(strings.ToLower(k), "x-") { if p.Extensions == nil { p.Extensions = make(map[string]interface{}) } var d interface{} if err := json.Unmarshal(v, &d); err != nil { return err } p.Extensions[k] = d } if strings.HasPrefix(k, "/") { if p.Paths == nil { p.Paths = make(map[string]*Path) } var pi *Path if err := json.Unmarshal(v, &pi); err != nil { return err } p.Paths[k] = pi } } return nil } func (p *Paths) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { tok, err := dec.ReadToken() if err != nil { return err } switch k := tok.Kind(); k { case 'n': *p = Paths{} return nil case '{': for { tok, err := dec.ReadToken() if err != nil { return err } if tok.Kind() == '}' { return nil } switch k := tok.String(); { case internal.IsExtensionKey(k): var ext any if err := opts.UnmarshalNext(dec, &ext); err != nil { return err } if p.Extensions == nil { p.Extensions = make(map[string]any) } p.Extensions[k] = ext case len(k) > 0 && k[0] == '/': pi := Path{} if err := opts.UnmarshalNext(dec, &pi); err != nil { return err } if p.Paths == nil { p.Paths = make(map[string]*Path) } p.Paths[k] = &pi default: _, err := dec.ReadValue() // skip value if err != nil { return err } } } default: return fmt.Errorf("unknown JSON kind: %v", k) } } // Path describes the operations available on a single path, more at https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#pathItemObject // // Note that this struct is actually a thin wrapper around PathProps to make it referable and extensible type Path struct { spec.Refable PathProps spec.VendorExtensible } // MarshalJSON is a custom marshal function that knows how to encode Path as JSON func (p *Path) MarshalJSON() ([]byte, error) { if internal.UseOptimizedJSONMarshalingV3 { return internal.DeterministicMarshal(p) } b1, err := json.Marshal(p.Refable) if err != nil { return nil, err } b2, err := json.Marshal(p.PathProps) if err != nil { return nil, err } b3, err := json.Marshal(p.VendorExtensible) if err != nil { return nil, err } return swag.ConcatJSON(b1, b2, b3), nil } func (p *Path) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { var x struct { Ref string `json:"$ref,omitempty"` spec.Extensions PathProps } x.Ref = p.Refable.Ref.String() x.Extensions = internal.SanitizeExtensions(p.Extensions) x.PathProps = p.PathProps return opts.MarshalNext(enc, x) } func (p *Path) UnmarshalJSON(data []byte) error { if internal.UseOptimizedJSONUnmarshalingV3 { return jsonv2.Unmarshal(data, p) } if err := json.Unmarshal(data, &p.Refable); err != nil { return err } if err := json.Unmarshal(data, &p.PathProps); err != nil { return err } if err := json.Unmarshal(data, &p.VendorExtensible); err != nil { return err } return nil } func (p *Path) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { var x struct { spec.Extensions PathProps } if err := opts.UnmarshalNext(dec, &x); err != nil { return err } if err := internal.JSONRefFromMap(&p.Ref.Ref, x.Extensions); err != nil { return err } p.Extensions = internal.SanitizeExtensions(x.Extensions) p.PathProps = x.PathProps return nil } // PathProps describes the operations available on a single path, more at https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#pathItemObject type PathProps struct { // Summary holds a summary for all operations in this path Summary string `json:"summary,omitempty"` // Description holds a description for all operations in this path Description string `json:"description,omitempty"` // Get defines GET operation Get *Operation `json:"get,omitempty"` // Put defines PUT operation Put *Operation `json:"put,omitempty"` // Post defines POST operation Post *Operation `json:"post,omitempty"` // Delete defines DELETE operation Delete *Operation `json:"delete,omitempty"` // Options defines OPTIONS operation Options *Operation `json:"options,omitempty"` // Head defines HEAD operation Head *Operation `json:"head,omitempty"` // Patch defines PATCH operation Patch *Operation `json:"patch,omitempty"` // Trace defines TRACE operation Trace *Operation `json:"trace,omitempty"` // Servers is an alternative server array to service all operations in this path Servers []*Server `json:"servers,omitempty"` // Parameters a list of parameters that are applicable for this operation Parameters []*Parameter `json:"parameters,omitempty"` }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/spec3/response.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/spec3/response.go
/* Copyright 2021 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 spec3 import ( "encoding/json" "fmt" "strconv" "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" "k8s.io/kube-openapi/pkg/validation/spec" ) // Responses holds the list of possible responses as they are returned from executing this operation // // Note that this struct is actually a thin wrapper around ResponsesProps to make it referable and extensible type Responses struct { ResponsesProps spec.VendorExtensible } // MarshalJSON is a custom marshal function that knows how to encode Responses as JSON func (r *Responses) MarshalJSON() ([]byte, error) { if internal.UseOptimizedJSONMarshalingV3 { return internal.DeterministicMarshal(r) } b1, err := json.Marshal(r.ResponsesProps) if err != nil { return nil, err } b2, err := json.Marshal(r.VendorExtensible) if err != nil { return nil, err } return swag.ConcatJSON(b1, b2), nil } func (r Responses) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { type ArbitraryKeys map[string]interface{} var x struct { ArbitraryKeys Default *Response `json:"default,omitzero"` } x.ArbitraryKeys = make(map[string]any, len(r.Extensions)+len(r.StatusCodeResponses)) for k, v := range r.Extensions { if internal.IsExtensionKey(k) { x.ArbitraryKeys[k] = v } } for k, v := range r.StatusCodeResponses { x.ArbitraryKeys[strconv.Itoa(k)] = v } x.Default = r.Default return opts.MarshalNext(enc, x) } func (r *Responses) UnmarshalJSON(data []byte) error { if internal.UseOptimizedJSONUnmarshalingV3 { return jsonv2.Unmarshal(data, r) } if err := json.Unmarshal(data, &r.ResponsesProps); err != nil { return err } if err := json.Unmarshal(data, &r.VendorExtensible); err != nil { return err } return nil } // ResponsesProps holds the list of possible responses as they are returned from executing this operation type ResponsesProps struct { // Default holds the documentation of responses other than the ones declared for specific HTTP response codes. Use this field to cover undeclared responses Default *Response `json:"-"` // StatusCodeResponses holds a map of any HTTP status code to the response definition StatusCodeResponses map[int]*Response `json:"-"` } // MarshalJSON is a custom marshal function that knows how to encode ResponsesProps as JSON func (r ResponsesProps) MarshalJSON() ([]byte, error) { toser := map[string]*Response{} if r.Default != nil { toser["default"] = r.Default } for k, v := range r.StatusCodeResponses { toser[strconv.Itoa(k)] = v } return json.Marshal(toser) } // UnmarshalJSON unmarshals responses from JSON func (r *ResponsesProps) UnmarshalJSON(data []byte) error { if internal.UseOptimizedJSONUnmarshalingV3 { return jsonv2.Unmarshal(data, r) } var res map[string]json.RawMessage if err := json.Unmarshal(data, &res); err != nil { return err } if v, ok := res["default"]; ok { value := Response{} if err := json.Unmarshal(v, &value); err != nil { return err } r.Default = &value delete(res, "default") } for k, v := range res { // Take all integral keys if nk, err := strconv.Atoi(k); err == nil { if r.StatusCodeResponses == nil { r.StatusCodeResponses = map[int]*Response{} } value := Response{} if err := json.Unmarshal(v, &value); err != nil { return err } r.StatusCodeResponses[nk] = &value } } return nil } func (r *Responses) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) (err error) { tok, err := dec.ReadToken() if err != nil { return err } switch k := tok.Kind(); k { case 'n': *r = Responses{} return nil case '{': for { tok, err := dec.ReadToken() if err != nil { return err } if tok.Kind() == '}' { return nil } switch k := tok.String(); { case internal.IsExtensionKey(k): var ext any if err := opts.UnmarshalNext(dec, &ext); err != nil { return err } if r.Extensions == nil { r.Extensions = make(map[string]any) } r.Extensions[k] = ext case k == "default": resp := Response{} if err := opts.UnmarshalNext(dec, &resp); err != nil { return err } r.ResponsesProps.Default = &resp default: if nk, err := strconv.Atoi(k); err == nil { resp := Response{} if err := opts.UnmarshalNext(dec, &resp); err != nil { return err } if r.StatusCodeResponses == nil { r.StatusCodeResponses = map[int]*Response{} } r.StatusCodeResponses[nk] = &resp } } } default: return fmt.Errorf("unknown JSON kind: %v", k) } } // Response describes a single response from an API Operation, more at https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#responseObject // // Note that this struct is actually a thin wrapper around ResponseProps to make it referable and extensible type Response struct { spec.Refable ResponseProps spec.VendorExtensible } // MarshalJSON is a custom marshal function that knows how to encode Response as JSON func (r *Response) MarshalJSON() ([]byte, error) { if internal.UseOptimizedJSONMarshalingV3 { return internal.DeterministicMarshal(r) } b1, err := json.Marshal(r.Refable) if err != nil { return nil, err } b2, err := json.Marshal(r.ResponseProps) if err != nil { return nil, err } b3, err := json.Marshal(r.VendorExtensible) if err != nil { return nil, err } return swag.ConcatJSON(b1, b2, b3), nil } func (r Response) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { var x struct { Ref string `json:"$ref,omitempty"` spec.Extensions ResponseProps `json:",inline"` } x.Ref = r.Refable.Ref.String() x.Extensions = internal.SanitizeExtensions(r.Extensions) x.ResponseProps = r.ResponseProps return opts.MarshalNext(enc, x) } func (r *Response) UnmarshalJSON(data []byte) error { if internal.UseOptimizedJSONUnmarshalingV3 { return jsonv2.Unmarshal(data, r) } if err := json.Unmarshal(data, &r.Refable); err != nil { return err } if err := json.Unmarshal(data, &r.ResponseProps); err != nil { return err } if err := json.Unmarshal(data, &r.VendorExtensible); err != nil { return err } return nil } func (r *Response) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { var x struct { spec.Extensions ResponseProps } if err := opts.UnmarshalNext(dec, &x); err != nil { return err } if err := internal.JSONRefFromMap(&r.Ref.Ref, x.Extensions); err != nil { return err } r.Extensions = internal.SanitizeExtensions(x.Extensions) r.ResponseProps = x.ResponseProps return nil } // ResponseProps describes a single response from an API Operation, more at https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#responseObject type ResponseProps struct { // Description holds a short description of the response Description string `json:"description,omitempty"` // Headers holds a maps of a headers name to its definition Headers map[string]*Header `json:"headers,omitempty"` // Content holds a map containing descriptions of potential response payloads Content map[string]*MediaType `json:"content,omitempty"` // Links is a map of operations links that can be followed from the response Links map[string]*Link `json:"links,omitempty"` } // Link represents a possible design-time link for a response, more at https://swagger.io/specification/#link-object type Link struct { spec.Refable LinkProps spec.VendorExtensible } // MarshalJSON is a custom marshal function that knows how to encode Link as JSON func (r *Link) MarshalJSON() ([]byte, error) { if internal.UseOptimizedJSONMarshalingV3 { return internal.DeterministicMarshal(r) } b1, err := json.Marshal(r.Refable) if err != nil { return nil, err } b2, err := json.Marshal(r.LinkProps) if err != nil { return nil, err } b3, err := json.Marshal(r.VendorExtensible) if err != nil { return nil, err } return swag.ConcatJSON(b1, b2, b3), nil } func (r *Link) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { var x struct { Ref string `json:"$ref,omitempty"` spec.Extensions LinkProps `json:",inline"` } x.Ref = r.Refable.Ref.String() x.Extensions = internal.SanitizeExtensions(r.Extensions) x.LinkProps = r.LinkProps return opts.MarshalNext(enc, x) } func (r *Link) UnmarshalJSON(data []byte) error { if internal.UseOptimizedJSONUnmarshalingV3 { return jsonv2.Unmarshal(data, r) } if err := json.Unmarshal(data, &r.Refable); err != nil { return err } if err := json.Unmarshal(data, &r.LinkProps); err != nil { return err } if err := json.Unmarshal(data, &r.VendorExtensible); err != nil { return err } return nil } func (l *Link) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { var x struct { spec.Extensions LinkProps } if err := opts.UnmarshalNext(dec, &x); err != nil { return err } if err := internal.JSONRefFromMap(&l.Ref.Ref, x.Extensions); err != nil { return err } l.Extensions = internal.SanitizeExtensions(x.Extensions) l.LinkProps = x.LinkProps return nil } // LinkProps describes a single response from an API Operation, more at https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#responseObject type LinkProps struct { // OperationId is the name of an existing, resolvable OAS operation OperationId string `json:"operationId,omitempty"` // Parameters is a map representing parameters to pass to an operation as specified with operationId or identified via operationRef Parameters map[string]interface{} `json:"parameters,omitempty"` // Description holds a description of the link Description string `json:"description,omitempty"` // RequestBody is a literal value or expresion to use as a request body when calling the target operation RequestBody interface{} `json:"requestBody,omitempty"` // Server holds a server object used by the target operation Server *Server `json:"server,omitempty"` }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/spec3/example.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/spec3/example.go
/* Copyright 2021 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 spec3 import ( "encoding/json" "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" "k8s.io/kube-openapi/pkg/validation/spec" ) // Example https://swagger.io/specification/#example-object type Example struct { spec.Refable ExampleProps spec.VendorExtensible } // MarshalJSON is a custom marshal function that knows how to encode RequestBody as JSON func (e *Example) MarshalJSON() ([]byte, error) { if internal.UseOptimizedJSONMarshalingV3 { return internal.DeterministicMarshal(e) } b1, err := json.Marshal(e.Refable) if err != nil { return nil, err } b2, err := json.Marshal(e.ExampleProps) if err != nil { return nil, err } b3, err := json.Marshal(e.VendorExtensible) if err != nil { return nil, err } return swag.ConcatJSON(b1, b2, b3), nil } func (e *Example) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { var x struct { Ref string `json:"$ref,omitempty"` ExampleProps `json:",inline"` spec.Extensions } x.Ref = e.Refable.Ref.String() x.Extensions = internal.SanitizeExtensions(e.Extensions) x.ExampleProps = e.ExampleProps return opts.MarshalNext(enc, x) } func (e *Example) UnmarshalJSON(data []byte) error { if internal.UseOptimizedJSONUnmarshalingV3 { return jsonv2.Unmarshal(data, e) } if err := json.Unmarshal(data, &e.Refable); err != nil { return err } if err := json.Unmarshal(data, &e.ExampleProps); err != nil { return err } if err := json.Unmarshal(data, &e.VendorExtensible); err != nil { return err } return nil } func (e *Example) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { var x struct { spec.Extensions ExampleProps } if err := opts.UnmarshalNext(dec, &x); err != nil { return err } if err := internal.JSONRefFromMap(&e.Ref.Ref, x.Extensions); err != nil { return err } e.Extensions = internal.SanitizeExtensions(x.Extensions) e.ExampleProps = x.ExampleProps return nil } type ExampleProps struct { // Summary holds a short description of the example Summary string `json:"summary,omitempty"` // Description holds a long description of the example Description string `json:"description,omitempty"` // Embedded literal example. Value interface{} `json:"value,omitempty"` // A URL that points to the literal example. This provides the capability to reference examples that cannot easily be included in JSON or YAML documents. ExternalValue string `json:"externalValue,omitempty"` }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/spec3/spec.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/spec3/spec.go
/* Copyright 2021 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 spec3 import ( "encoding/json" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" "k8s.io/kube-openapi/pkg/validation/spec" ) // OpenAPI is an object that describes an API and conforms to the OpenAPI Specification. type OpenAPI struct { // Version represents the semantic version number of the OpenAPI Specification that this document uses Version string `json:"openapi"` // Info provides metadata about the API Info *spec.Info `json:"info"` // Paths holds the available target and operations for the API Paths *Paths `json:"paths,omitempty"` // Servers is an array of Server objects which provide connectivity information to a target server Servers []*Server `json:"servers,omitempty"` // Components hold various schemas for the specification Components *Components `json:"components,omitempty"` // SecurityRequirement holds a declaration of which security mechanisms can be used across the API SecurityRequirement []map[string][]string `json:"security,omitempty"` // ExternalDocs holds additional external documentation ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"` } func (o *OpenAPI) UnmarshalJSON(data []byte) error { type OpenAPIWithNoFunctions OpenAPI p := (*OpenAPIWithNoFunctions)(o) if internal.UseOptimizedJSONUnmarshalingV3 { return jsonv2.Unmarshal(data, &p) } return json.Unmarshal(data, &p) } func (o *OpenAPI) MarshalJSON() ([]byte, error) { if internal.UseOptimizedJSONMarshalingV3 { return internal.DeterministicMarshal(o) } type OpenAPIWithNoFunctions OpenAPI p := (*OpenAPIWithNoFunctions)(o) return json.Marshal(&p) } func (o *OpenAPI) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { type OpenAPIOmitZero struct { Version string `json:"openapi"` Info *spec.Info `json:"info"` Paths *Paths `json:"paths,omitzero"` Servers []*Server `json:"servers,omitempty"` Components *Components `json:"components,omitzero"` SecurityRequirement []map[string][]string `json:"security,omitempty"` ExternalDocs *ExternalDocumentation `json:"externalDocs,omitzero"` } x := (*OpenAPIOmitZero)(o) return opts.MarshalNext(enc, x) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/spec3/header.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/spec3/header.go
/* Copyright 2021 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 spec3 import ( "encoding/json" "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" "k8s.io/kube-openapi/pkg/validation/spec" ) // Header a struct that describes a single operation parameter, more at https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#parameterObject // // Note that this struct is actually a thin wrapper around HeaderProps to make it referable and extensible type Header struct { spec.Refable HeaderProps spec.VendorExtensible } // MarshalJSON is a custom marshal function that knows how to encode Header as JSON func (h *Header) MarshalJSON() ([]byte, error) { if internal.UseOptimizedJSONMarshalingV3 { return internal.DeterministicMarshal(h) } b1, err := json.Marshal(h.Refable) if err != nil { return nil, err } b2, err := json.Marshal(h.HeaderProps) if err != nil { return nil, err } b3, err := json.Marshal(h.VendorExtensible) if err != nil { return nil, err } return swag.ConcatJSON(b1, b2, b3), nil } func (h *Header) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { var x struct { Ref string `json:"$ref,omitempty"` HeaderProps headerPropsOmitZero `json:",inline"` spec.Extensions } x.Ref = h.Refable.Ref.String() x.Extensions = internal.SanitizeExtensions(h.Extensions) x.HeaderProps = headerPropsOmitZero(h.HeaderProps) return opts.MarshalNext(enc, x) } func (h *Header) UnmarshalJSON(data []byte) error { if internal.UseOptimizedJSONUnmarshalingV3 { return jsonv2.Unmarshal(data, h) } if err := json.Unmarshal(data, &h.Refable); err != nil { return err } if err := json.Unmarshal(data, &h.HeaderProps); err != nil { return err } if err := json.Unmarshal(data, &h.VendorExtensible); err != nil { return err } return nil } func (h *Header) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { var x struct { spec.Extensions HeaderProps } if err := opts.UnmarshalNext(dec, &x); err != nil { return err } if err := internal.JSONRefFromMap(&h.Ref.Ref, x.Extensions); err != nil { return err } h.Extensions = internal.SanitizeExtensions(x.Extensions) h.HeaderProps = x.HeaderProps return nil } // HeaderProps a struct that describes a header object type HeaderProps struct { // Description holds a brief description of the parameter Description string `json:"description,omitempty"` // Required determines whether this parameter is mandatory Required bool `json:"required,omitempty"` // Deprecated declares this operation to be deprecated Deprecated bool `json:"deprecated,omitempty"` // AllowEmptyValue sets the ability to pass empty-valued parameters AllowEmptyValue bool `json:"allowEmptyValue,omitempty"` // Style describes how the parameter value will be serialized depending on the type of the parameter value Style string `json:"style,omitempty"` // Explode when true, parameter values of type array or object generate separate parameters for each value of the array or key-value pair of the map Explode bool `json:"explode,omitempty"` // AllowReserved determines whether the parameter value SHOULD allow reserved characters, as defined by RFC3986 AllowReserved bool `json:"allowReserved,omitempty"` // Schema holds the schema defining the type used for the parameter Schema *spec.Schema `json:"schema,omitempty"` // Content holds a map containing the representations for the parameter Content map[string]*MediaType `json:"content,omitempty"` // Example of the header Example interface{} `json:"example,omitempty"` // Examples of the header Examples map[string]*Example `json:"examples,omitempty"` } // Marshaling structure only, always edit along with corresponding // struct (or compilation will fail). type headerPropsOmitZero struct { Description string `json:"description,omitempty"` Required bool `json:"required,omitzero"` Deprecated bool `json:"deprecated,omitzero"` AllowEmptyValue bool `json:"allowEmptyValue,omitzero"` Style string `json:"style,omitempty"` Explode bool `json:"explode,omitzero"` AllowReserved bool `json:"allowReserved,omitzero"` Schema *spec.Schema `json:"schema,omitzero"` Content map[string]*MediaType `json:"content,omitempty"` Example interface{} `json:"example,omitempty"` Examples map[string]*Example `json:"examples,omitempty"` }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/spec3/media_type.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/spec3/media_type.go
/* Copyright 2021 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 spec3 import ( "encoding/json" "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" "k8s.io/kube-openapi/pkg/validation/spec" ) // MediaType a struct that allows you to specify content format, more at https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#mediaTypeObject // // Note that this struct is actually a thin wrapper around MediaTypeProps to make it referable and extensible type MediaType struct { MediaTypeProps spec.VendorExtensible } // MarshalJSON is a custom marshal function that knows how to encode MediaType as JSON func (m *MediaType) MarshalJSON() ([]byte, error) { if internal.UseOptimizedJSONMarshalingV3 { return internal.DeterministicMarshal(m) } b1, err := json.Marshal(m.MediaTypeProps) if err != nil { return nil, err } b2, err := json.Marshal(m.VendorExtensible) if err != nil { return nil, err } return swag.ConcatJSON(b1, b2), nil } func (e *MediaType) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { var x struct { MediaTypeProps mediaTypePropsOmitZero `json:",inline"` spec.Extensions } x.Extensions = internal.SanitizeExtensions(e.Extensions) x.MediaTypeProps = mediaTypePropsOmitZero(e.MediaTypeProps) return opts.MarshalNext(enc, x) } func (m *MediaType) UnmarshalJSON(data []byte) error { if internal.UseOptimizedJSONUnmarshalingV3 { return jsonv2.Unmarshal(data, m) } if err := json.Unmarshal(data, &m.MediaTypeProps); err != nil { return err } if err := json.Unmarshal(data, &m.VendorExtensible); err != nil { return err } return nil } func (m *MediaType) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { var x struct { spec.Extensions MediaTypeProps } if err := opts.UnmarshalNext(dec, &x); err != nil { return err } m.Extensions = internal.SanitizeExtensions(x.Extensions) m.MediaTypeProps = x.MediaTypeProps return nil } // MediaTypeProps a struct that allows you to specify content format, more at https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#mediaTypeObject type MediaTypeProps struct { // Schema holds the schema defining the type used for the media type Schema *spec.Schema `json:"schema,omitempty"` // Example of the media type Example interface{} `json:"example,omitempty"` // Examples of the media type. Each example object should match the media type and specific schema if present Examples map[string]*Example `json:"examples,omitempty"` // A map between a property name and its encoding information. The key, being the property name, MUST exist in the schema as a property. The encoding object SHALL only apply to requestBody objects when the media type is multipart or application/x-www-form-urlencoded Encoding map[string]*Encoding `json:"encoding,omitempty"` } type mediaTypePropsOmitZero struct { Schema *spec.Schema `json:"schema,omitzero"` Example interface{} `json:"example,omitempty"` Examples map[string]*Example `json:"examples,omitempty"` Encoding map[string]*Encoding `json:"encoding,omitempty"` }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/spec3/server.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/spec3/server.go
/* Copyright 2021 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 spec3 import ( "encoding/json" "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" "k8s.io/kube-openapi/pkg/validation/spec" ) type Server struct { ServerProps spec.VendorExtensible } type ServerProps struct { // Description is a short description of the target documentation. CommonMark syntax MAY be used for rich text representation. Description string `json:"description,omitempty"` // URL is the URL for the target documentation. URL string `json:"url"` // Variables contains a map between a variable name and its value. The value is used for substitution in the server's URL templeate Variables map[string]*ServerVariable `json:"variables,omitempty"` } // MarshalJSON is a custom marshal function that knows how to encode Responses as JSON func (s *Server) MarshalJSON() ([]byte, error) { if internal.UseOptimizedJSONMarshalingV3 { return internal.DeterministicMarshal(s) } b1, err := json.Marshal(s.ServerProps) if err != nil { return nil, err } b2, err := json.Marshal(s.VendorExtensible) if err != nil { return nil, err } return swag.ConcatJSON(b1, b2), nil } func (s *Server) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { var x struct { ServerProps `json:",inline"` spec.Extensions } x.Extensions = internal.SanitizeExtensions(s.Extensions) x.ServerProps = s.ServerProps return opts.MarshalNext(enc, x) } func (s *Server) UnmarshalJSON(data []byte) error { if internal.UseOptimizedJSONUnmarshalingV3 { return jsonv2.Unmarshal(data, s) } if err := json.Unmarshal(data, &s.ServerProps); err != nil { return err } if err := json.Unmarshal(data, &s.VendorExtensible); err != nil { return err } return nil } func (s *Server) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { var x struct { spec.Extensions ServerProps } if err := opts.UnmarshalNext(dec, &x); err != nil { return err } s.Extensions = internal.SanitizeExtensions(x.Extensions) s.ServerProps = x.ServerProps return nil } type ServerVariable struct { ServerVariableProps spec.VendorExtensible } type ServerVariableProps struct { // Enum is an enumeration of string values to be used if the substitution options are from a limited set Enum []string `json:"enum,omitempty"` // Default is the default value to use for substitution, which SHALL be sent if an alternate value is not supplied Default string `json:"default"` // Description is a description for the server variable Description string `json:"description,omitempty"` } // MarshalJSON is a custom marshal function that knows how to encode Responses as JSON func (s *ServerVariable) MarshalJSON() ([]byte, error) { if internal.UseOptimizedJSONMarshalingV3 { return internal.DeterministicMarshal(s) } b1, err := json.Marshal(s.ServerVariableProps) if err != nil { return nil, err } b2, err := json.Marshal(s.VendorExtensible) if err != nil { return nil, err } return swag.ConcatJSON(b1, b2), nil } func (s *ServerVariable) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { var x struct { ServerVariableProps `json:",inline"` spec.Extensions } x.Extensions = internal.SanitizeExtensions(s.Extensions) x.ServerVariableProps = s.ServerVariableProps return opts.MarshalNext(enc, x) } func (s *ServerVariable) UnmarshalJSON(data []byte) error { if internal.UseOptimizedJSONUnmarshalingV3 { return jsonv2.Unmarshal(data, s) } if err := json.Unmarshal(data, &s.ServerVariableProps); err != nil { return err } if err := json.Unmarshal(data, &s.VendorExtensible); err != nil { return err } return nil } func (s *ServerVariable) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { var x struct { spec.Extensions ServerVariableProps } if err := opts.UnmarshalNext(dec, &x); err != nil { return err } s.Extensions = internal.SanitizeExtensions(x.Extensions) s.ServerVariableProps = x.ServerVariableProps return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/spec3/security_scheme.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/spec3/security_scheme.go
/* Copyright 2021 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 spec3 import ( "encoding/json" "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" "k8s.io/kube-openapi/pkg/validation/spec" ) // SecurityScheme defines reusable Security Scheme Object, more at https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#securitySchemeObject type SecurityScheme struct { spec.Refable SecuritySchemeProps spec.VendorExtensible } // MarshalJSON is a custom marshal function that knows how to encode SecurityScheme as JSON func (s *SecurityScheme) MarshalJSON() ([]byte, error) { if internal.UseOptimizedJSONMarshalingV3 { return internal.DeterministicMarshal(s) } b1, err := json.Marshal(s.SecuritySchemeProps) if err != nil { return nil, err } b2, err := json.Marshal(s.VendorExtensible) if err != nil { return nil, err } b3, err := json.Marshal(s.Refable) if err != nil { return nil, err } return swag.ConcatJSON(b1, b2, b3), nil } func (s *SecurityScheme) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { var x struct { Ref string `json:"$ref,omitempty"` SecuritySchemeProps `json:",inline"` spec.Extensions } x.Ref = s.Refable.Ref.String() x.Extensions = internal.SanitizeExtensions(s.Extensions) x.SecuritySchemeProps = s.SecuritySchemeProps return opts.MarshalNext(enc, x) } // UnmarshalJSON hydrates this items instance with the data from JSON func (s *SecurityScheme) UnmarshalJSON(data []byte) error { if err := json.Unmarshal(data, &s.SecuritySchemeProps); err != nil { return err } if err := json.Unmarshal(data, &s.VendorExtensible); err != nil { return err } return json.Unmarshal(data, &s.Refable) } // SecuritySchemeProps defines a security scheme that can be used by the operations type SecuritySchemeProps struct { // Type of the security scheme Type string `json:"type,omitempty"` // Description holds a short description for security scheme Description string `json:"description,omitempty"` // Name holds the name of the header, query or cookie parameter to be used Name string `json:"name,omitempty"` // In holds the location of the API key In string `json:"in,omitempty"` // Scheme holds the name of the HTTP Authorization scheme to be used in the Authorization header Scheme string `json:"scheme,omitempty"` // BearerFormat holds a hint to the client to identify how the bearer token is formatted BearerFormat string `json:"bearerFormat,omitempty"` // Flows contains configuration information for the flow types supported. Flows map[string]*OAuthFlow `json:"flows,omitempty"` // OpenIdConnectUrl holds an url to discover OAuth2 configuration values from OpenIdConnectUrl string `json:"openIdConnectUrl,omitempty"` } // OAuthFlow contains configuration information for the flow types supported. type OAuthFlow struct { OAuthFlowProps spec.VendorExtensible } // MarshalJSON is a custom marshal function that knows how to encode OAuthFlow as JSON func (o *OAuthFlow) MarshalJSON() ([]byte, error) { b1, err := json.Marshal(o.OAuthFlowProps) if err != nil { return nil, err } b2, err := json.Marshal(o.VendorExtensible) if err != nil { return nil, err } return swag.ConcatJSON(b1, b2), nil } // UnmarshalJSON hydrates this items instance with the data from JSON func (o *OAuthFlow) UnmarshalJSON(data []byte) error { if err := json.Unmarshal(data, &o.OAuthFlowProps); err != nil { return err } return json.Unmarshal(data, &o.VendorExtensible) } // OAuthFlowProps holds configuration details for a supported OAuth Flow type OAuthFlowProps struct { // AuthorizationUrl hold the authorization URL to be used for this flow AuthorizationUrl string `json:"authorizationUrl,omitempty"` // TokenUrl holds the token URL to be used for this flow TokenUrl string `json:"tokenUrl,omitempty"` // RefreshUrl holds the URL to be used for obtaining refresh tokens RefreshUrl string `json:"refreshUrl,omitempty"` // Scopes holds the available scopes for the OAuth2 security scheme Scopes map[string]string `json:"scopes,omitempty"` }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/spec3/operation.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/spec3/operation.go
/* Copyright 2021 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 spec3 import ( "encoding/json" "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" "k8s.io/kube-openapi/pkg/validation/spec" ) // Operation describes a single API operation on a path, more at https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#operationObject // // Note that this struct is actually a thin wrapper around OperationProps to make it referable and extensible type Operation struct { OperationProps spec.VendorExtensible } // MarshalJSON is a custom marshal function that knows how to encode Operation as JSON func (o *Operation) MarshalJSON() ([]byte, error) { if internal.UseOptimizedJSONMarshalingV3 { return internal.DeterministicMarshal(o) } b1, err := json.Marshal(o.OperationProps) if err != nil { return nil, err } b2, err := json.Marshal(o.VendorExtensible) if err != nil { return nil, err } return swag.ConcatJSON(b1, b2), nil } func (o *Operation) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { var x struct { spec.Extensions OperationProps operationPropsOmitZero `json:",inline"` } x.Extensions = internal.SanitizeExtensions(o.Extensions) x.OperationProps = operationPropsOmitZero(o.OperationProps) return opts.MarshalNext(enc, x) } // UnmarshalJSON hydrates this items instance with the data from JSON func (o *Operation) UnmarshalJSON(data []byte) error { if internal.UseOptimizedJSONUnmarshalingV3 { return jsonv2.Unmarshal(data, o) } if err := json.Unmarshal(data, &o.OperationProps); err != nil { return err } return json.Unmarshal(data, &o.VendorExtensible) } func (o *Operation) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { var x struct { spec.Extensions OperationProps } if err := opts.UnmarshalNext(dec, &x); err != nil { return err } o.Extensions = internal.SanitizeExtensions(x.Extensions) o.OperationProps = x.OperationProps return nil } // OperationProps describes a single API operation on a path, more at https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#operationObject type OperationProps struct { // Tags holds a list of tags for API documentation control Tags []string `json:"tags,omitempty"` // Summary holds a short summary of what the operation does Summary string `json:"summary,omitempty"` // Description holds a verbose explanation of the operation behavior Description string `json:"description,omitempty"` // ExternalDocs holds additional external documentation for this operation ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"` // OperationId holds a unique string used to identify the operation OperationId string `json:"operationId,omitempty"` // Parameters a list of parameters that are applicable for this operation Parameters []*Parameter `json:"parameters,omitempty"` // RequestBody holds the request body applicable for this operation RequestBody *RequestBody `json:"requestBody,omitempty"` // Responses holds the list of possible responses as they are returned from executing this operation Responses *Responses `json:"responses,omitempty"` // Deprecated declares this operation to be deprecated Deprecated bool `json:"deprecated,omitempty"` // SecurityRequirement holds a declaration of which security mechanisms can be used for this operation SecurityRequirement []map[string][]string `json:"security,omitempty"` // Servers contains an alternative server array to service this operation Servers []*Server `json:"servers,omitempty"` } type operationPropsOmitZero struct { Tags []string `json:"tags,omitempty"` Summary string `json:"summary,omitempty"` Description string `json:"description,omitempty"` ExternalDocs *ExternalDocumentation `json:"externalDocs,omitzero"` OperationId string `json:"operationId,omitempty"` Parameters []*Parameter `json:"parameters,omitempty"` RequestBody *RequestBody `json:"requestBody,omitzero"` Responses *Responses `json:"responses,omitzero"` Deprecated bool `json:"deprecated,omitzero"` SecurityRequirement []map[string][]string `json:"security,omitempty"` Servers []*Server `json:"servers,omitempty"` }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/spec3/encoding.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/spec3/encoding.go
/* Copyright 2021 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 spec3 import ( "encoding/json" "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" "k8s.io/kube-openapi/pkg/validation/spec" ) type Encoding struct { EncodingProps spec.VendorExtensible } // MarshalJSON is a custom marshal function that knows how to encode Encoding as JSON func (e *Encoding) MarshalJSON() ([]byte, error) { if internal.UseOptimizedJSONMarshalingV3 { return internal.DeterministicMarshal(e) } b1, err := json.Marshal(e.EncodingProps) if err != nil { return nil, err } b2, err := json.Marshal(e.VendorExtensible) if err != nil { return nil, err } return swag.ConcatJSON(b1, b2), nil } func (e *Encoding) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { var x struct { EncodingProps encodingPropsOmitZero `json:",inline"` spec.Extensions } x.Extensions = internal.SanitizeExtensions(e.Extensions) x.EncodingProps = encodingPropsOmitZero(e.EncodingProps) return opts.MarshalNext(enc, x) } func (e *Encoding) UnmarshalJSON(data []byte) error { if internal.UseOptimizedJSONUnmarshalingV3 { return jsonv2.Unmarshal(data, e) } if err := json.Unmarshal(data, &e.EncodingProps); err != nil { return err } if err := json.Unmarshal(data, &e.VendorExtensible); err != nil { return err } return nil } func (e *Encoding) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { var x struct { spec.Extensions EncodingProps } if err := opts.UnmarshalNext(dec, &x); err != nil { return err } e.Extensions = internal.SanitizeExtensions(x.Extensions) e.EncodingProps = x.EncodingProps return nil } type EncodingProps struct { // Content Type for encoding a specific property ContentType string `json:"contentType,omitempty"` // A map allowing additional information to be provided as headers Headers map[string]*Header `json:"headers,omitempty"` // Describes how a specific property value will be serialized depending on its type Style string `json:"style,omitempty"` // When this is true, property values of type array or object generate separate parameters for each value of the array, or key-value-pair of the map. For other types of properties this property has no effect Explode bool `json:"explode,omitempty"` // AllowReserved determines whether the parameter value SHOULD allow reserved characters, as defined by RFC3986 AllowReserved bool `json:"allowReserved,omitempty"` } type encodingPropsOmitZero struct { ContentType string `json:"contentType,omitempty"` Headers map[string]*Header `json:"headers,omitempty"` Style string `json:"style,omitempty"` Explode bool `json:"explode,omitzero"` AllowReserved bool `json:"allowReserved,omitzero"` }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/spec3/parameter.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/spec3/parameter.go
/* Copyright 2021 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 spec3 import ( "encoding/json" "github.com/go-openapi/swag" "k8s.io/kube-openapi/pkg/internal" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" "k8s.io/kube-openapi/pkg/validation/spec" ) // Parameter a struct that describes a single operation parameter, more at https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#parameterObject // // Note that this struct is actually a thin wrapper around ParameterProps to make it referable and extensible type Parameter struct { spec.Refable ParameterProps spec.VendorExtensible } // MarshalJSON is a custom marshal function that knows how to encode Parameter as JSON func (p *Parameter) MarshalJSON() ([]byte, error) { if internal.UseOptimizedJSONMarshalingV3 { return internal.DeterministicMarshal(p) } b1, err := json.Marshal(p.Refable) if err != nil { return nil, err } b2, err := json.Marshal(p.ParameterProps) if err != nil { return nil, err } b3, err := json.Marshal(p.VendorExtensible) if err != nil { return nil, err } return swag.ConcatJSON(b1, b2, b3), nil } func (p *Parameter) MarshalNextJSON(opts jsonv2.MarshalOptions, enc *jsonv2.Encoder) error { var x struct { Ref string `json:"$ref,omitempty"` ParameterProps parameterPropsOmitZero `json:",inline"` spec.Extensions } x.Ref = p.Refable.Ref.String() x.Extensions = internal.SanitizeExtensions(p.Extensions) x.ParameterProps = parameterPropsOmitZero(p.ParameterProps) return opts.MarshalNext(enc, x) } func (p *Parameter) UnmarshalJSON(data []byte) error { if internal.UseOptimizedJSONUnmarshalingV3 { return jsonv2.Unmarshal(data, p) } if err := json.Unmarshal(data, &p.Refable); err != nil { return err } if err := json.Unmarshal(data, &p.ParameterProps); err != nil { return err } if err := json.Unmarshal(data, &p.VendorExtensible); err != nil { return err } return nil } func (p *Parameter) UnmarshalNextJSON(opts jsonv2.UnmarshalOptions, dec *jsonv2.Decoder) error { var x struct { spec.Extensions ParameterProps } if err := opts.UnmarshalNext(dec, &x); err != nil { return err } if err := internal.JSONRefFromMap(&p.Ref.Ref, x.Extensions); err != nil { return err } p.Extensions = internal.SanitizeExtensions(x.Extensions) p.ParameterProps = x.ParameterProps return nil } // ParameterProps a struct that describes a single operation parameter, more at https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#parameterObject type ParameterProps struct { // Name holds the name of the parameter Name string `json:"name,omitempty"` // In holds the location of the parameter In string `json:"in,omitempty"` // Description holds a brief description of the parameter Description string `json:"description,omitempty"` // Required determines whether this parameter is mandatory Required bool `json:"required,omitempty"` // Deprecated declares this operation to be deprecated Deprecated bool `json:"deprecated,omitempty"` // AllowEmptyValue sets the ability to pass empty-valued parameters AllowEmptyValue bool `json:"allowEmptyValue,omitempty"` // Style describes how the parameter value will be serialized depending on the type of the parameter value Style string `json:"style,omitempty"` // Explode when true, parameter values of type array or object generate separate parameters for each value of the array or key-value pair of the map Explode bool `json:"explode,omitempty"` // AllowReserved determines whether the parameter value SHOULD allow reserved characters, as defined by RFC3986 AllowReserved bool `json:"allowReserved,omitempty"` // Schema holds the schema defining the type used for the parameter Schema *spec.Schema `json:"schema,omitempty"` // Content holds a map containing the representations for the parameter Content map[string]*MediaType `json:"content,omitempty"` // Example of the parameter's potential value Example interface{} `json:"example,omitempty"` // Examples of the parameter's potential value. Each example SHOULD contain a value in the correct format as specified in the parameter encoding Examples map[string]*Example `json:"examples,omitempty"` } type parameterPropsOmitZero struct { Name string `json:"name,omitempty"` In string `json:"in,omitempty"` Description string `json:"description,omitempty"` Required bool `json:"required,omitzero"` Deprecated bool `json:"deprecated,omitzero"` AllowEmptyValue bool `json:"allowEmptyValue,omitzero"` Style string `json:"style,omitempty"` Explode bool `json:"explode,omitzero"` AllowReserved bool `json:"allowReserved,omitzero"` Schema *spec.Schema `json:"schema,omitzero"` Content map[string]*MediaType `json:"content,omitempty"` Example interface{} `json:"example,omitempty"` Examples map[string]*Example `json:"examples,omitempty"` }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/cached/cache.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/cached/cache.go
/* Copyright 2022 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 cached provides a cache mechanism based on etags to lazily // build, and/or cache results from expensive operation such that those // operations are not repeated unnecessarily. The operations can be // created as a tree, and replaced dynamically as needed. // // All the operations in this module are thread-safe. // // # Dependencies and types of caches // // This package uses a source/transform/sink model of caches to build // the dependency tree, and can be used as follows: // - [Func]: A source cache that recomputes the content every time. // - [Once]: A source cache that always produces the // same content, it is only called once. // - [Transform]: A cache that transforms data from one format to // another. It's only refreshed when the source changes. // - [Merge]: A cache that aggregates multiple caches in a map into one. // It's only refreshed when the source changes. // - [MergeList]: A cache that aggregates multiple caches in a list into one. // It's only refreshed when the source changes. // - [Atomic]: A cache adapter that atomically replaces the source with a new one. // - [LastSuccess]: A cache adapter that caches the last successful and returns // it if the next call fails. It extends [Atomic]. // // # Etags // // Etags in this library is a cache version identifier. It doesn't // necessarily strictly match to the semantics of http `etags`, but are // somewhat inspired from it and function with the same principles. // Hashing the content is a good way to guarantee that your function is // never going to be called spuriously. In Kubernetes world, this could // be a `resourceVersion`, this can be an actual etag, a hash, a UUID // (if the cache always changes), or even a made-up string when the // content of the cache never changes. package cached import ( "fmt" "sync" "sync/atomic" ) // Value is wrapping a value behind a getter for lazy evaluation. type Value[T any] interface { Get() (value T, etag string, err error) } // Result is wrapping T and error into a struct for cases where a tuple is more // convenient or necessary in Golang. type Result[T any] struct { Value T Etag string Err error } func (r Result[T]) Get() (T, string, error) { return r.Value, r.Etag, r.Err } // Func wraps a (thread-safe) function as a Value[T]. func Func[T any](fn func() (T, string, error)) Value[T] { return valueFunc[T](fn) } type valueFunc[T any] func() (T, string, error) func (c valueFunc[T]) Get() (T, string, error) { return c() } // Static returns constant values. func Static[T any](value T, etag string) Value[T] { return Result[T]{Value: value, Etag: etag} } // Merge merges a of cached values. The merge function only gets called if any of // the dependency has changed. // // If any of the dependency returned an error before, or any of the // dependency returned an error this time, or if the mergeFn failed // before, then the function is run again. // // Note that this assumes there is no "partial" merge, the merge // function will remerge all the dependencies together everytime. Since // the list of dependencies is constant, there is no way to save some // partial merge information either. // // Also note that Golang map iteration is not stable. If the mergeFn // depends on the order iteration to be stable, it will need to // implement its own sorting or iteration order. func Merge[K comparable, T, V any](mergeFn func(results map[K]Result[T]) (V, string, error), caches map[K]Value[T]) Value[V] { list := make([]Value[T], 0, len(caches)) // map from index to key indexes := make(map[int]K, len(caches)) i := 0 for k := range caches { list = append(list, caches[k]) indexes[i] = k i++ } return MergeList(func(results []Result[T]) (V, string, error) { if len(results) != len(indexes) { panic(fmt.Errorf("invalid result length %d, expected %d", len(results), len(indexes))) } m := make(map[K]Result[T], len(results)) for i := range results { m[indexes[i]] = results[i] } return mergeFn(m) }, list) } // MergeList merges a list of cached values. The function only gets called if // any of the dependency has changed. // // The benefit of ListMerger over the basic Merger is that caches are // stored in an ordered list so the order of the cache will be // preserved in the order of the results passed to the mergeFn. // // If any of the dependency returned an error before, or any of the // dependency returned an error this time, or if the mergeFn failed // before, then the function is reran. // // Note that this assumes there is no "partial" merge, the merge // function will remerge all the dependencies together everytime. Since // the list of dependencies is constant, there is no way to save some // partial merge information either. func MergeList[T, V any](mergeFn func(results []Result[T]) (V, string, error), delegates []Value[T]) Value[V] { return &listMerger[T, V]{ mergeFn: mergeFn, delegates: delegates, } } type listMerger[T, V any] struct { lock sync.Mutex mergeFn func([]Result[T]) (V, string, error) delegates []Value[T] cache []Result[T] result Result[V] } func (c *listMerger[T, V]) prepareResultsLocked() []Result[T] { cacheResults := make([]Result[T], len(c.delegates)) ch := make(chan struct { int Result[T] }, len(c.delegates)) for i := range c.delegates { go func(index int) { value, etag, err := c.delegates[index].Get() ch <- struct { int Result[T] }{index, Result[T]{Value: value, Etag: etag, Err: err}} }(i) } for i := 0; i < len(c.delegates); i++ { res := <-ch cacheResults[res.int] = res.Result } return cacheResults } func (c *listMerger[T, V]) needsRunningLocked(results []Result[T]) bool { if c.cache == nil { return true } if c.result.Err != nil { return true } if len(results) != len(c.cache) { panic(fmt.Errorf("invalid number of results: %v (expected %v)", len(results), len(c.cache))) } for i, oldResult := range c.cache { newResult := results[i] if newResult.Etag != oldResult.Etag || newResult.Err != nil || oldResult.Err != nil { return true } } return false } func (c *listMerger[T, V]) Get() (V, string, error) { c.lock.Lock() defer c.lock.Unlock() cacheResults := c.prepareResultsLocked() if c.needsRunningLocked(cacheResults) { c.cache = cacheResults c.result.Value, c.result.Etag, c.result.Err = c.mergeFn(c.cache) } return c.result.Value, c.result.Etag, c.result.Err } // Transform the result of another cached value. The transformFn will only be called // if the source has updated, otherwise, the result will be returned. // // If the dependency returned an error before, or it returns an error // this time, or if the transformerFn failed before, the function is // reran. func Transform[T, V any](transformerFn func(T, string, error) (V, string, error), source Value[T]) Value[V] { return MergeList(func(delegates []Result[T]) (V, string, error) { if len(delegates) != 1 { panic(fmt.Errorf("invalid cache for transformer cache: %v", delegates)) } return transformerFn(delegates[0].Value, delegates[0].Etag, delegates[0].Err) }, []Value[T]{source}) } // Once calls Value[T].Get() lazily and only once, even in case of an error result. func Once[T any](d Value[T]) Value[T] { return &once[T]{ data: d, } } type once[T any] struct { once sync.Once data Value[T] result Result[T] } func (c *once[T]) Get() (T, string, error) { c.once.Do(func() { c.result.Value, c.result.Etag, c.result.Err = c.data.Get() }) return c.result.Value, c.result.Etag, c.result.Err } // Replaceable extends the Value[T] interface with the ability to change the // underlying Value[T] after construction. type Replaceable[T any] interface { Value[T] Store(Value[T]) } // Atomic wraps a Value[T] as an atomic value that can be replaced. It implements // Replaceable[T]. type Atomic[T any] struct { value atomic.Pointer[Value[T]] } var _ Replaceable[[]byte] = &Atomic[[]byte]{} func (x *Atomic[T]) Store(val Value[T]) { x.value.Store(&val) } func (x *Atomic[T]) Get() (T, string, error) { return (*x.value.Load()).Get() } // LastSuccess calls Value[T].Get(), but hides errors by returning the last // success if there has been any. type LastSuccess[T any] struct { Atomic[T] success atomic.Pointer[Result[T]] } var _ Replaceable[[]byte] = &LastSuccess[[]byte]{} func (c *LastSuccess[T]) Get() (T, string, error) { success := c.success.Load() value, etag, err := c.Atomic.Get() if err == nil { if success == nil { c.success.CompareAndSwap(nil, &Result[T]{Value: value, Etag: etag, Err: err}) } return value, etag, err } if success != nil { return success.Value, success.Etag, success.Err } return value, etag, err }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/schemaconv/proto_models.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/schemaconv/proto_models.go
/* Copyright 2022 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 schemaconv import ( "errors" "path" "strings" "k8s.io/kube-openapi/pkg/util/proto" "sigs.k8s.io/structured-merge-diff/v4/schema" ) // ToSchema converts openapi definitions into a schema suitable for structured // merge (i.e. kubectl apply v2). func ToSchema(models proto.Models) (*schema.Schema, error) { return ToSchemaWithPreserveUnknownFields(models, false) } // ToSchemaWithPreserveUnknownFields converts openapi definitions into a schema suitable for structured // merge (i.e. kubectl apply v2), it will preserve unknown fields if specified. func ToSchemaWithPreserveUnknownFields(models proto.Models, preserveUnknownFields bool) (*schema.Schema, error) { c := convert{ preserveUnknownFields: preserveUnknownFields, output: &schema.Schema{}, } for _, name := range models.ListModels() { model := models.LookupModel(name) var a schema.Atom c2 := c.push(name, &a) model.Accept(c2) c.pop(c2) c.insertTypeDef(name, a) } if len(c.errorMessages) > 0 { return nil, errors.New(strings.Join(c.errorMessages, "\n")) } c.addCommonTypes() return c.output, nil } func (c *convert) makeRef(model proto.Schema, preserveUnknownFields bool) schema.TypeRef { var tr schema.TypeRef if r, ok := model.(*proto.Ref); ok { if r.Reference() == "io.k8s.apimachinery.pkg.runtime.RawExtension" { return schema.TypeRef{ NamedType: &untypedName, } } // reference a named type _, n := path.Split(r.Reference()) tr.NamedType = &n mapRelationship, err := getMapElementRelationship(model.GetExtensions()) if err != nil { c.reportError(err.Error()) } // empty string means unset. if len(mapRelationship) > 0 { tr.ElementRelationship = &mapRelationship } } else { // compute the type inline c2 := c.push("inlined in "+c.currentName, &tr.Inlined) c2.preserveUnknownFields = preserveUnknownFields model.Accept(c2) c.pop(c2) if tr == (schema.TypeRef{}) { // emit warning? tr.NamedType = &untypedName } } return tr } func (c *convert) VisitKind(k *proto.Kind) { preserveUnknownFields := c.preserveUnknownFields if p, ok := k.GetExtensions()["x-kubernetes-preserve-unknown-fields"]; ok && p == true { preserveUnknownFields = true } a := c.top() a.Map = &schema.Map{} for _, name := range k.FieldOrder { member := k.Fields[name] tr := c.makeRef(member, preserveUnknownFields) a.Map.Fields = append(a.Map.Fields, schema.StructField{ Name: name, Type: tr, Default: member.GetDefault(), }) } unions, err := makeUnions(k.GetExtensions()) if err != nil { c.reportError(err.Error()) return } // TODO: We should check that the fields and discriminator // specified in the union are actual fields in the struct. a.Map.Unions = unions if preserveUnknownFields { a.Map.ElementType = schema.TypeRef{ NamedType: &deducedName, } } a.Map.ElementRelationship, err = getMapElementRelationship(k.GetExtensions()) if err != nil { c.reportError(err.Error()) } } func (c *convert) VisitArray(a *proto.Array) { relationship, mapKeys, err := getListElementRelationship(a.GetExtensions()) if err != nil { c.reportError(err.Error()) } atom := c.top() atom.List = &schema.List{ ElementType: c.makeRef(a.SubType, c.preserveUnknownFields), ElementRelationship: relationship, Keys: mapKeys, } } func (c *convert) VisitMap(m *proto.Map) { relationship, err := getMapElementRelationship(m.GetExtensions()) if err != nil { c.reportError(err.Error()) } a := c.top() a.Map = &schema.Map{ ElementType: c.makeRef(m.SubType, c.preserveUnknownFields), ElementRelationship: relationship, } } func (c *convert) VisitPrimitive(p *proto.Primitive) { a := c.top() if c.currentName == quantityResource { a.Scalar = ptr(schema.Scalar("untyped")) } else { *a = convertPrimitive(p.Type, p.Format) } } func (c *convert) VisitArbitrary(a *proto.Arbitrary) { *c.top() = deducedDef.Atom } func (c *convert) VisitReference(proto.Reference) { // Do nothing, we handle references specially }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/schemaconv/openapi.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/schemaconv/openapi.go
/* Copyright 2022 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 schemaconv import ( "errors" "path" "strings" "k8s.io/kube-openapi/pkg/validation/spec" "sigs.k8s.io/structured-merge-diff/v4/schema" ) // ToSchemaFromOpenAPI converts a directory of OpenAPI schemas to an smd Schema. // - models: a map from definition name to OpenAPI V3 structural schema for each definition. // Key in map is used to resolve references in the schema. // - preserveUnknownFields: flag indicating whether unknown fields in all schemas should be preserved. // - returns: nil and an error if there is a parse error, or if schema does not satisfy a // required structural schema invariant for conversion. If no error, returns // a new smd schema. // // Schema should be validated as structural before using with this function, or // there may be information lost. func ToSchemaFromOpenAPI(models map[string]*spec.Schema, preserveUnknownFields bool) (*schema.Schema, error) { c := convert{ preserveUnknownFields: preserveUnknownFields, output: &schema.Schema{}, } for name, spec := range models { // Skip/Ignore top-level references if len(spec.Ref.String()) > 0 { continue } var a schema.Atom // Hard-coded schemas for now as proto_models implementation functions. // https://github.com/kubernetes/kube-openapi/issues/364 if name == quantityResource { a = schema.Atom{ Scalar: untypedDef.Atom.Scalar, } } else if name == rawExtensionResource { a = untypedDef.Atom } else { c2 := c.push(name, &a) c2.visitSpec(spec) c.pop(c2) } c.insertTypeDef(name, a) } if len(c.errorMessages) > 0 { return nil, errors.New(strings.Join(c.errorMessages, "\n")) } c.addCommonTypes() return c.output, nil } func (c *convert) visitSpec(m *spec.Schema) { // Check if this schema opts its descendants into preserve-unknown-fields if p, ok := m.Extensions["x-kubernetes-preserve-unknown-fields"]; ok && p == true { c.preserveUnknownFields = true } a := c.top() *a = c.parseSchema(m) } func (c *convert) parseSchema(m *spec.Schema) schema.Atom { // k8s-generated OpenAPI specs have historically used only one value for // type and starting with OpenAPIV3 it is only allowed to be // a single string. typ := "" if len(m.Type) > 0 { typ = m.Type[0] } // Structural Schemas produced by kubernetes follow very specific rules which // we can use to infer the SMD type: switch typ { case "": // According to Swagger docs: // https://swagger.io/docs/specification/data-models/data-types/#any // // If no type is specified, it is equivalent to accepting any type. return schema.Atom{ Scalar: ptr(schema.Scalar("untyped")), List: c.parseList(m), Map: c.parseObject(m), } case "object": return schema.Atom{ Map: c.parseObject(m), } case "array": return schema.Atom{ List: c.parseList(m), } case "integer", "boolean", "number", "string": return convertPrimitive(typ, m.Format) default: c.reportError("unrecognized type: '%v'", typ) return schema.Atom{ Scalar: ptr(schema.Scalar("untyped")), } } } func (c *convert) makeOpenAPIRef(specSchema *spec.Schema) schema.TypeRef { refString := specSchema.Ref.String() // Special-case handling for $ref stored inside a single-element allOf if len(refString) == 0 && len(specSchema.AllOf) == 1 && len(specSchema.AllOf[0].Ref.String()) > 0 { refString = specSchema.AllOf[0].Ref.String() } if _, n := path.Split(refString); len(n) > 0 { //!TODO: Refactor the field ElementRelationship override // we can generate the types with overrides ahead of time rather than // requiring the hacky runtime support // (could just create a normalized key struct containing all customizations // to deduplicate) mapRelationship, err := getMapElementRelationship(specSchema.Extensions) if err != nil { c.reportError(err.Error()) } if len(mapRelationship) > 0 { return schema.TypeRef{ NamedType: &n, ElementRelationship: &mapRelationship, } } return schema.TypeRef{ NamedType: &n, } } var inlined schema.Atom // compute the type inline c2 := c.push("inlined in "+c.currentName, &inlined) c2.preserveUnknownFields = c.preserveUnknownFields c2.visitSpec(specSchema) c.pop(c2) return schema.TypeRef{ Inlined: inlined, } } func (c *convert) parseObject(s *spec.Schema) *schema.Map { var fields []schema.StructField for name, member := range s.Properties { fields = append(fields, schema.StructField{ Name: name, Type: c.makeOpenAPIRef(&member), Default: member.Default, }) } // AdditionalProperties informs the schema of any "unknown" keys // Unknown keys are enforced by the ElementType field. elementType := func() schema.TypeRef { if s.AdditionalProperties == nil { // According to openAPI spec, an object without properties and without // additionalProperties is assumed to be a free-form object. if c.preserveUnknownFields || len(s.Properties) == 0 { return schema.TypeRef{ NamedType: &deducedName, } } // If properties are specified, do not implicitly allow unknown // fields return schema.TypeRef{} } else if s.AdditionalProperties.Schema != nil { // Unknown fields use the referred schema return c.makeOpenAPIRef(s.AdditionalProperties.Schema) } else if s.AdditionalProperties.Allows { // A boolean instead of a schema was provided. Deduce the // type from the value provided at runtime. return schema.TypeRef{ NamedType: &deducedName, } } else { // Additional Properties are explicitly disallowed by the user. // Ensure element type is empty. return schema.TypeRef{} } }() relationship, err := getMapElementRelationship(s.Extensions) if err != nil { c.reportError(err.Error()) } return &schema.Map{ Fields: fields, ElementRelationship: relationship, ElementType: elementType, } } func (c *convert) parseList(s *spec.Schema) *schema.List { relationship, mapKeys, err := getListElementRelationship(s.Extensions) if err != nil { c.reportError(err.Error()) } elementType := func() schema.TypeRef { if s.Items != nil { if s.Items.Schema == nil || s.Items.Len() != 1 { c.reportError("structural schema arrays must have exactly one member subtype") return schema.TypeRef{ NamedType: &deducedName, } } subSchema := s.Items.Schema if subSchema == nil { subSchema = &s.Items.Schemas[0] } return c.makeOpenAPIRef(subSchema) } else if len(s.Type) > 0 && len(s.Type[0]) > 0 { c.reportError("`items` must be specified on arrays") } // A list with no items specified is treated as "untyped". return schema.TypeRef{ NamedType: &untypedName, } }() return &schema.List{ ElementRelationship: relationship, Keys: mapKeys, ElementType: elementType, } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/schemaconv/smd.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/schemaconv/smd.go
/* 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 schemaconv import ( "fmt" "sort" "sigs.k8s.io/structured-merge-diff/v4/schema" ) const ( quantityResource = "io.k8s.apimachinery.pkg.api.resource.Quantity" rawExtensionResource = "io.k8s.apimachinery.pkg.runtime.RawExtension" ) type convert struct { preserveUnknownFields bool output *schema.Schema currentName string current *schema.Atom errorMessages []string } func (c *convert) push(name string, a *schema.Atom) *convert { return &convert{ preserveUnknownFields: c.preserveUnknownFields, output: c.output, currentName: name, current: a, } } func (c *convert) top() *schema.Atom { return c.current } func (c *convert) pop(c2 *convert) { c.errorMessages = append(c.errorMessages, c2.errorMessages...) } func (c *convert) reportError(format string, args ...interface{}) { c.errorMessages = append(c.errorMessages, c.currentName+": "+fmt.Sprintf(format, args...), ) } func (c *convert) insertTypeDef(name string, atom schema.Atom) { def := schema.TypeDef{ Name: name, Atom: atom, } if def.Atom == (schema.Atom{}) { // This could happen if there were a top-level reference. return } c.output.Types = append(c.output.Types, def) } func (c *convert) addCommonTypes() { c.output.Types = append(c.output.Types, untypedDef) c.output.Types = append(c.output.Types, deducedDef) } var untypedName string = "__untyped_atomic_" var untypedDef schema.TypeDef = schema.TypeDef{ Name: untypedName, Atom: schema.Atom{ Scalar: ptr(schema.Scalar("untyped")), List: &schema.List{ ElementType: schema.TypeRef{ NamedType: &untypedName, }, ElementRelationship: schema.Atomic, }, Map: &schema.Map{ ElementType: schema.TypeRef{ NamedType: &untypedName, }, ElementRelationship: schema.Atomic, }, }, } var deducedName string = "__untyped_deduced_" var deducedDef schema.TypeDef = schema.TypeDef{ Name: deducedName, Atom: schema.Atom{ Scalar: ptr(schema.Scalar("untyped")), List: &schema.List{ ElementType: schema.TypeRef{ NamedType: &untypedName, }, ElementRelationship: schema.Atomic, }, Map: &schema.Map{ ElementType: schema.TypeRef{ NamedType: &deducedName, }, ElementRelationship: schema.Separable, }, }, } func makeUnions(extensions map[string]interface{}) ([]schema.Union, error) { schemaUnions := []schema.Union{} if iunions, ok := extensions["x-kubernetes-unions"]; ok { unions, ok := iunions.([]interface{}) if !ok { return nil, fmt.Errorf(`"x-kubernetes-unions" should be a list, got %#v`, unions) } for _, iunion := range unions { union, ok := iunion.(map[interface{}]interface{}) if !ok { return nil, fmt.Errorf(`"x-kubernetes-unions" items should be a map of string to unions, got %#v`, iunion) } unionMap := map[string]interface{}{} for k, v := range union { key, ok := k.(string) if !ok { return nil, fmt.Errorf(`"x-kubernetes-unions" has non-string key: %#v`, k) } unionMap[key] = v } schemaUnion, err := makeUnion(unionMap) if err != nil { return nil, err } schemaUnions = append(schemaUnions, schemaUnion) } } // Make sure we have no overlap between unions fs := map[string]struct{}{} for _, u := range schemaUnions { if u.Discriminator != nil { if _, ok := fs[*u.Discriminator]; ok { return nil, fmt.Errorf("%v field appears multiple times in unions", *u.Discriminator) } fs[*u.Discriminator] = struct{}{} } for _, f := range u.Fields { if _, ok := fs[f.FieldName]; ok { return nil, fmt.Errorf("%v field appears multiple times in unions", f.FieldName) } fs[f.FieldName] = struct{}{} } } return schemaUnions, nil } func makeUnion(extensions map[string]interface{}) (schema.Union, error) { union := schema.Union{ Fields: []schema.UnionField{}, } if idiscriminator, ok := extensions["discriminator"]; ok { discriminator, ok := idiscriminator.(string) if !ok { return schema.Union{}, fmt.Errorf(`"discriminator" must be a string, got: %#v`, idiscriminator) } union.Discriminator = &discriminator } if ifields, ok := extensions["fields-to-discriminateBy"]; ok { fields, ok := ifields.(map[interface{}]interface{}) if !ok { return schema.Union{}, fmt.Errorf(`"fields-to-discriminateBy" must be a map[string]string, got: %#v`, ifields) } // Needs sorted keys by field. keys := []string{} for ifield := range fields { field, ok := ifield.(string) if !ok { return schema.Union{}, fmt.Errorf(`"fields-to-discriminateBy": field must be a string, got: %#v`, ifield) } keys = append(keys, field) } sort.Strings(keys) reverseMap := map[string]struct{}{} for _, field := range keys { value := fields[field] discriminated, ok := value.(string) if !ok { return schema.Union{}, fmt.Errorf(`"fields-to-discriminateBy"/%v: value must be a string, got: %#v`, field, value) } union.Fields = append(union.Fields, schema.UnionField{ FieldName: field, DiscriminatorValue: discriminated, }) // Check that we don't have the same discriminateBy multiple times. if _, ok := reverseMap[discriminated]; ok { return schema.Union{}, fmt.Errorf("Multiple fields have the same discriminated name: %v", discriminated) } reverseMap[discriminated] = struct{}{} } } return union, nil } func toStringSlice(o interface{}) (out []string, ok bool) { switch t := o.(type) { case []interface{}: for _, v := range t { switch vt := v.(type) { case string: out = append(out, vt) } } return out, true case []string: return t, true } return nil, false } func ptr(s schema.Scalar) *schema.Scalar { return &s } // Basic conversion functions to convert OpenAPI schema definitions to // SMD Schema atoms func convertPrimitive(typ string, format string) (a schema.Atom) { switch typ { case "integer": a.Scalar = ptr(schema.Numeric) case "number": a.Scalar = ptr(schema.Numeric) case "string": switch format { case "": a.Scalar = ptr(schema.String) case "byte": // byte really means []byte and is encoded as a string. a.Scalar = ptr(schema.String) case "int-or-string": a.Scalar = ptr(schema.Scalar("untyped")) case "date-time": a.Scalar = ptr(schema.Scalar("untyped")) default: a.Scalar = ptr(schema.Scalar("untyped")) } case "boolean": a.Scalar = ptr(schema.Boolean) default: a.Scalar = ptr(schema.Scalar("untyped")) } return a } func getListElementRelationship(ext map[string]any) (schema.ElementRelationship, []string, error) { if val, ok := ext["x-kubernetes-list-type"]; ok { switch val { case "atomic": return schema.Atomic, nil, nil case "set": return schema.Associative, nil, nil case "map": keys, ok := ext["x-kubernetes-list-map-keys"] if !ok { return schema.Associative, nil, fmt.Errorf("missing map keys") } keyNames, ok := toStringSlice(keys) if !ok { return schema.Associative, nil, fmt.Errorf("uninterpreted map keys: %#v", keys) } return schema.Associative, keyNames, nil default: return schema.Atomic, nil, fmt.Errorf("unknown list type %v", val) } } else if val, ok := ext["x-kubernetes-patch-strategy"]; ok { switch val { case "merge", "merge,retainKeys": if key, ok := ext["x-kubernetes-patch-merge-key"]; ok { keyName, ok := key.(string) if !ok { return schema.Associative, nil, fmt.Errorf("uninterpreted merge key: %#v", key) } return schema.Associative, []string{keyName}, nil } // It's not an error for x-kubernetes-patch-merge-key to be absent, // it means it's a set return schema.Associative, nil, nil case "retainKeys": return schema.Atomic, nil, nil default: return schema.Atomic, nil, fmt.Errorf("unknown patch strategy %v", val) } } // Treat as atomic by default return schema.Atomic, nil, nil } // Returns map element relationship if specified, or empty string if unspecified func getMapElementRelationship(ext map[string]any) (schema.ElementRelationship, error) { val, ok := ext["x-kubernetes-map-type"] if !ok { // unset Map element relationship return "", nil } switch val { case "atomic": return schema.Atomic, nil case "granular": return schema.Separable, nil default: return "", fmt.Errorf("unknown map type %v", val) } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/common/interfaces.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/common/interfaces.go
package common // RouteContainer is the entrypoint for a service, which may contain multiple // routes under a common path with a common set of path parameters. type RouteContainer interface { // RootPath is the path that all contained routes are nested under. RootPath() string // PathParameters are common parameters defined in the root path. PathParameters() []Parameter // Routes are all routes exposed under the root path. Routes() []Route } // Route is a logical endpoint of a service. type Route interface { // Method defines the HTTP Method. Method() string // Path defines the route's endpoint. Path() string // OperationName defines a machine-readable ID for the route. OperationName() string // Parameters defines the list of accepted parameters. Parameters() []Parameter // Description is a human-readable route description. Description() string // Consumes defines the consumed content-types. Consumes() []string // Produces defines the produced content-types. Produces() []string // Metadata allows adding extensions to the generated spec. Metadata() map[string]interface{} // RequestPayloadSample defines an example request payload. Can return nil. RequestPayloadSample() interface{} // ResponsePayloadSample defines an example response payload. Can return nil. ResponsePayloadSample() interface{} // StatusCodeResponses defines a mapping of HTTP Status Codes to the specific response(s). // Multiple responses with the same HTTP Status Code are acceptable. StatusCodeResponses() []StatusCodeResponse } // StatusCodeResponse is an explicit response type with an HTTP Status Code. type StatusCodeResponse interface { // Code defines the HTTP Status Code. Code() int // Message returns the human-readable message. Message() string // Model defines an example payload for this response. Model() interface{} } // Parameter is a Route parameter. type Parameter interface { // Name defines the unique-per-route identifier. Name() string // Description is the human-readable description of the param. Description() string // Required defines if this parameter must be provided. Required() bool // Kind defines the type of the parameter itself. Kind() ParameterKind // DataType defines the type of data the parameter carries. DataType() string // AllowMultiple defines if more than one value can be supplied for the parameter. AllowMultiple() bool } // ParameterKind is an enum of route parameter types. type ParameterKind int const ( // PathParameterKind indicates the request parameter type is "path". PathParameterKind = ParameterKind(iota) // QueryParameterKind indicates the request parameter type is "query". QueryParameterKind // BodyParameterKind indicates the request parameter type is "body". BodyParameterKind // HeaderParameterKind indicates the request parameter type is "header". HeaderParameterKind // FormParameterKind indicates the request parameter type is "form". FormParameterKind // UnknownParameterKind indicates the request parameter type has not been specified. UnknownParameterKind )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/common/doc.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/common/doc.go
/* Copyright 2016 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 common holds shared code and types between open API code // generator and spec generator. package common
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/common/common.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/common/common.go
/* Copyright 2016 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 common import ( "net/http" "strings" "github.com/emicklei/go-restful/v3" "k8s.io/kube-openapi/pkg/spec3" "k8s.io/kube-openapi/pkg/validation/spec" ) const ( // TODO: Make this configurable. ExtensionPrefix = "x-kubernetes-" ExtensionV2Schema = ExtensionPrefix + "v2-schema" ) // OpenAPIDefinition describes single type. Normally these definitions are auto-generated using gen-openapi. type OpenAPIDefinition struct { Schema spec.Schema Dependencies []string } type ReferenceCallback func(path string) spec.Ref // GetOpenAPIDefinitions is collection of all definitions. type GetOpenAPIDefinitions func(ReferenceCallback) map[string]OpenAPIDefinition // OpenAPIDefinitionGetter gets openAPI definitions for a given type. If a type implements this interface, // the definition returned by it will be used, otherwise the auto-generated definitions will be used. See // GetOpenAPITypeFormat for more information about trade-offs of using this interface or GetOpenAPITypeFormat method when // possible. type OpenAPIDefinitionGetter interface { OpenAPIDefinition() *OpenAPIDefinition } type OpenAPIV3DefinitionGetter interface { OpenAPIV3Definition() *OpenAPIDefinition } type PathHandler interface { Handle(path string, handler http.Handler) } type PathHandlerByGroupVersion interface { Handle(path string, handler http.Handler) HandlePrefix(path string, handler http.Handler) } // Config is set of configuration for openAPI spec generation. type Config struct { // List of supported protocols such as https, http, etc. ProtocolList []string // Info is general information about the API. Info *spec.Info // DefaultResponse will be used if an operation does not have any responses listed. It // will show up as ... "responses" : {"default" : $DefaultResponse} in the spec. DefaultResponse *spec.Response // ResponseDefinitions will be added to "responses" under the top-level swagger object. This is an object // that holds responses definitions that can be used across operations. This property does not define // global responses for all operations. For more info please refer: // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#fixed-fields ResponseDefinitions map[string]spec.Response // CommonResponses will be added as a response to all operation specs. This is a good place to add common // responses such as authorization failed. CommonResponses map[int]spec.Response // List of webservice's path prefixes to ignore IgnorePrefixes []string // OpenAPIDefinitions should provide definition for all models used by routes. Failure to provide this map // or any of the models will result in spec generation failure. GetDefinitions GetOpenAPIDefinitions // Provides the definition for all models used by routes. One of GetDefinitions or Definitions must be defined to generate a spec. // This takes precedent over the GetDefinitions function Definitions map[string]OpenAPIDefinition // GetOperationIDAndTags returns operation id and tags for a restful route. It is an optional function to customize operation IDs. // // Deprecated: GetOperationIDAndTagsFromRoute should be used instead. This cannot be specified if using the new Route // interface set of funcs. GetOperationIDAndTags func(r *restful.Route) (string, []string, error) // GetOperationIDAndTagsFromRoute returns operation id and tags for a Route. It is an optional function to customize operation IDs. GetOperationIDAndTagsFromRoute func(r Route) (string, []string, error) // GetDefinitionName returns a friendly name for a definition base on the serving path. parameter `name` is the full name of the definition. // It is an optional function to customize model names. GetDefinitionName func(name string) (string, spec.Extensions) // PostProcessSpec runs after the spec is ready to serve. It allows a final modification to the spec before serving. PostProcessSpec func(*spec.Swagger) (*spec.Swagger, error) // SecurityDefinitions is list of all security definitions for OpenAPI service. If this is not nil, the user of config // is responsible to provide DefaultSecurity and (maybe) add unauthorized response to CommonResponses. SecurityDefinitions *spec.SecurityDefinitions // DefaultSecurity for all operations. This will pass as spec.SwaggerProps.Security to OpenAPI. // For most cases, this will be list of acceptable definitions in SecurityDefinitions. DefaultSecurity []map[string][]string } // OpenAPIV3Config is set of configuration for OpenAPI V3 spec generation. type OpenAPIV3Config struct { // Info is general information about the API. Info *spec.Info // DefaultResponse will be used if an operation does not have any responses listed. It // will show up as ... "responses" : {"default" : $DefaultResponse} in the spec. DefaultResponse *spec3.Response // ResponseDefinitions will be added to responses component. This is an object // that holds responses that can be used across operations. ResponseDefinitions map[string]*spec3.Response // CommonResponses will be added as a response to all operation specs. This is a good place to add common // responses such as authorization failed. CommonResponses map[int]*spec3.Response // List of webservice's path prefixes to ignore IgnorePrefixes []string // OpenAPIDefinitions should provide definition for all models used by routes. Failure to provide this map // or any of the models will result in spec generation failure. // One of GetDefinitions or Definitions must be defined to generate a spec. GetDefinitions GetOpenAPIDefinitions // Provides the definition for all models used by routes. One of GetDefinitions or Definitions must be defined to generate a spec. // This takes precedent over the GetDefinitions function Definitions map[string]OpenAPIDefinition // GetOperationIDAndTags returns operation id and tags for a restful route. It is an optional function to customize operation IDs. // // Deprecated: GetOperationIDAndTagsFromRoute should be used instead. This cannot be specified if using the new Route // interface set of funcs. GetOperationIDAndTags func(r *restful.Route) (string, []string, error) // GetOperationIDAndTagsFromRoute returns operation id and tags for a Route. It is an optional function to customize operation IDs. GetOperationIDAndTagsFromRoute func(r Route) (string, []string, error) // GetDefinitionName returns a friendly name for a definition base on the serving path. parameter `name` is the full name of the definition. // It is an optional function to customize model names. GetDefinitionName func(name string) (string, spec.Extensions) // PostProcessSpec runs after the spec is ready to serve. It allows a final modification to the spec before serving. PostProcessSpec func(*spec3.OpenAPI) (*spec3.OpenAPI, error) // SecuritySchemes is list of all security schemes for OpenAPI service. SecuritySchemes spec3.SecuritySchemes // DefaultSecurity for all operations. DefaultSecurity []map[string][]string } type typeInfo struct { name string format string zero interface{} } var schemaTypeFormatMap = map[string]typeInfo{ "uint": {"integer", "int32", 0.}, "uint8": {"integer", "byte", 0.}, "uint16": {"integer", "int32", 0.}, "uint32": {"integer", "int64", 0.}, "uint64": {"integer", "int64", 0.}, "int": {"integer", "int32", 0.}, "int8": {"integer", "byte", 0.}, "int16": {"integer", "int32", 0.}, "int32": {"integer", "int32", 0.}, "int64": {"integer", "int64", 0.}, "byte": {"integer", "byte", 0}, "float64": {"number", "double", 0.}, "float32": {"number", "float", 0.}, "bool": {"boolean", "", false}, "time.Time": {"string", "date-time", ""}, "string": {"string", "", ""}, "integer": {"integer", "", 0.}, "number": {"number", "", 0.}, "boolean": {"boolean", "", false}, "[]byte": {"string", "byte", ""}, // base64 encoded characters "interface{}": {"object", "", interface{}(nil)}, } // This function is a reference for converting go (or any custom type) to a simple open API type,format pair. There are // two ways to customize spec for a type. If you add it here, a type will be converted to a simple type and the type // comment (the comment that is added before type definition) will be lost. The spec will still have the property // comment. The second way is to implement OpenAPIDefinitionGetter interface. That function can customize the spec (so // the spec does not need to be simple type,format) or can even return a simple type,format (e.g. IntOrString). For simple // type formats, the benefit of adding OpenAPIDefinitionGetter interface is to keep both type and property documentation. // Example: // // type Sample struct { // ... // // port of the server // port IntOrString // ... // } // // // IntOrString documentation... // type IntOrString { ... } // // Adding IntOrString to this function: // // "port" : { // format: "string", // type: "int-or-string", // Description: "port of the server" // } // // Implement OpenAPIDefinitionGetter for IntOrString: // // "port" : { // $Ref: "#/definitions/IntOrString" // Description: "port of the server" // } // // ... // definitions: // // { // "IntOrString": { // format: "string", // type: "int-or-string", // Description: "IntOrString documentation..." // new // } // } func OpenAPITypeFormat(typeName string) (string, string) { mapped, ok := schemaTypeFormatMap[typeName] if !ok { return "", "" } return mapped.name, mapped.format } // Returns the zero-value for the given type along with true if the type // could be found. func OpenAPIZeroValue(typeName string) (interface{}, bool) { mapped, ok := schemaTypeFormatMap[typeName] if !ok { return nil, false } return mapped.zero, true } func EscapeJsonPointer(p string) string { // Escaping reference name using rfc6901 p = strings.Replace(p, "~", "~0", -1) p = strings.Replace(p, "/", "~1", -1) return p } func EmbedOpenAPIDefinitionIntoV2Extension(main OpenAPIDefinition, embedded OpenAPIDefinition) OpenAPIDefinition { if main.Schema.Extensions == nil { main.Schema.Extensions = make(map[string]interface{}) } main.Schema.Extensions[ExtensionV2Schema] = embedded.Schema return main } // GenerateOpenAPIV3OneOfSchema generate the set of schemas that MUST be assigned to SchemaProps.OneOf func GenerateOpenAPIV3OneOfSchema(types []string) (oneOf []spec.Schema) { for _, t := range types { oneOf = append(oneOf, spec.Schema{SchemaProps: spec.SchemaProps{Type: []string{t}}}) } return }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/internal/flags.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/internal/flags.go
/* Copyright 2022 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 internal // Used by tests to selectively disable experimental JSON unmarshaler var UseOptimizedJSONUnmarshaling bool = true var UseOptimizedJSONUnmarshalingV3 bool = true // Used by tests to selectively disable experimental JSON marshaler var UseOptimizedJSONMarshaling bool = true var UseOptimizedJSONMarshalingV3 bool = true
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/internal/serialization.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/internal/serialization.go
/* 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 internal import ( "github.com/go-openapi/jsonreference" jsonv2 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json" ) // DeterministicMarshal calls the jsonv2 library with the deterministic // flag in order to have stable marshaling. func DeterministicMarshal(in any) ([]byte, error) { return jsonv2.MarshalOptions{Deterministic: true}.Marshal(jsonv2.EncodeOptions{}, in) } // JSONRefFromMap populates a json reference object if the map v contains a $ref key. func JSONRefFromMap(jsonRef *jsonreference.Ref, v map[string]interface{}) error { if v == nil { return nil } if vv, ok := v["$ref"]; ok { if str, ok := vv.(string); ok { ref, err := jsonreference.New(str) if err != nil { return err } *jsonRef = ref } } return nil } // SanitizeExtensions sanitizes the input map such that non extension // keys (non x-*, X-*) keys are dropped from the map. Returns the new // modified map, or nil if the map is now empty. func SanitizeExtensions(e map[string]interface{}) map[string]interface{} { for k := range e { if !IsExtensionKey(k) { delete(e, k) } } if len(e) == 0 { e = nil } return e } // IsExtensionKey returns true if the input string is of format x-* or X-* func IsExtensionKey(k string) bool { return len(k) > 1 && (k[0] == 'x' || k[0] == 'X') && k[1] == '-' }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/fold.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/fold.go
// Copyright 2020 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package json import ( "unicode" "unicode/utf8" ) // foldName returns a folded string such that foldName(x) == foldName(y) // is similar to strings.EqualFold(x, y), but ignores underscore and dashes. // This allows foldName to match common naming conventions. func foldName(in []byte) []byte { // This is inlinable to take advantage of "function outlining". // See https://blog.filippo.io/efficient-go-apis-with-the-inliner/ var arr [32]byte // large enough for most JSON names return appendFoldedName(arr[:0], in) } func appendFoldedName(out, in []byte) []byte { for i := 0; i < len(in); { // Handle single-byte ASCII. if c := in[i]; c < utf8.RuneSelf { if c != '_' && c != '-' { if 'a' <= c && c <= 'z' { c -= 'a' - 'A' } out = append(out, c) } i++ continue } // Handle multi-byte Unicode. r, n := utf8.DecodeRune(in[i:]) out = utf8.AppendRune(out, foldRune(r)) i += n } return out } // foldRune is a variation on unicode.SimpleFold that returns the same rune // for all runes in the same fold set. // // Invariant: // // foldRune(x) == foldRune(y) ⇔ strings.EqualFold(string(x), string(y)) func foldRune(r rune) rune { for { r2 := unicode.SimpleFold(r) if r2 <= r { return r2 // smallest character in the fold set } r = r2 } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_default.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_default.go
// Copyright 2020 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package json import ( "bytes" "encoding/base32" "encoding/base64" "encoding/hex" "errors" "fmt" "math" "reflect" "sort" "strconv" "sync" ) // optimizeCommon specifies whether to use optimizations targeted for certain // common patterns, rather than using the slower, but more general logic. // All tests should pass regardless of whether this is true or not. const optimizeCommon = true var ( // Most natural Go type that correspond with each JSON type. anyType = reflect.TypeOf((*any)(nil)).Elem() // JSON value boolType = reflect.TypeOf((*bool)(nil)).Elem() // JSON bool stringType = reflect.TypeOf((*string)(nil)).Elem() // JSON string float64Type = reflect.TypeOf((*float64)(nil)).Elem() // JSON number mapStringAnyType = reflect.TypeOf((*map[string]any)(nil)).Elem() // JSON object sliceAnyType = reflect.TypeOf((*[]any)(nil)).Elem() // JSON array bytesType = reflect.TypeOf((*[]byte)(nil)).Elem() emptyStructType = reflect.TypeOf((*struct{})(nil)).Elem() ) const startDetectingCyclesAfter = 1000 type seenPointers map[typedPointer]struct{} type typedPointer struct { typ reflect.Type ptr any // always stores unsafe.Pointer, but avoids depending on unsafe } // visit visits pointer p of type t, reporting an error if seen before. // If successfully visited, then the caller must eventually call leave. func (m *seenPointers) visit(v reflect.Value) error { p := typedPointer{v.Type(), v.UnsafePointer()} if _, ok := (*m)[p]; ok { return &SemanticError{action: "marshal", GoType: p.typ, Err: errors.New("encountered a cycle")} } if *m == nil { *m = make(map[typedPointer]struct{}) } (*m)[p] = struct{}{} return nil } func (m *seenPointers) leave(v reflect.Value) { p := typedPointer{v.Type(), v.UnsafePointer()} delete(*m, p) } func makeDefaultArshaler(t reflect.Type) *arshaler { switch t.Kind() { case reflect.Bool: return makeBoolArshaler(t) case reflect.String: return makeStringArshaler(t) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return makeIntArshaler(t) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return makeUintArshaler(t) case reflect.Float32, reflect.Float64: return makeFloatArshaler(t) case reflect.Map: return makeMapArshaler(t) case reflect.Struct: return makeStructArshaler(t) case reflect.Slice: fncs := makeSliceArshaler(t) if t.AssignableTo(bytesType) { return makeBytesArshaler(t, fncs) } return fncs case reflect.Array: fncs := makeArrayArshaler(t) if reflect.SliceOf(t.Elem()).AssignableTo(bytesType) { return makeBytesArshaler(t, fncs) } return fncs case reflect.Pointer: return makePointerArshaler(t) case reflect.Interface: return makeInterfaceArshaler(t) default: return makeInvalidArshaler(t) } } func makeBoolArshaler(t reflect.Type) *arshaler { var fncs arshaler fncs.marshal = func(mo MarshalOptions, enc *Encoder, va addressableValue) error { if mo.format != "" && mo.formatDepth == enc.tokens.depth() { return newInvalidFormatError("marshal", t, mo.format) } // Optimize for marshaling without preceding whitespace. if optimizeCommon && !enc.options.multiline && !enc.tokens.last.needObjectName() { enc.buf = enc.tokens.mayAppendDelim(enc.buf, 't') if va.Bool() { enc.buf = append(enc.buf, "true"...) } else { enc.buf = append(enc.buf, "false"...) } enc.tokens.last.increment() if enc.needFlush() { return enc.flush() } return nil } return enc.WriteToken(Bool(va.Bool())) } fncs.unmarshal = func(uo UnmarshalOptions, dec *Decoder, va addressableValue) error { if uo.format != "" && uo.formatDepth == dec.tokens.depth() { return newInvalidFormatError("unmarshal", t, uo.format) } tok, err := dec.ReadToken() if err != nil { return err } k := tok.Kind() switch k { case 'n': va.SetBool(false) return nil case 't', 'f': va.SetBool(tok.Bool()) return nil } return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t} } return &fncs } func makeStringArshaler(t reflect.Type) *arshaler { var fncs arshaler fncs.marshal = func(mo MarshalOptions, enc *Encoder, va addressableValue) error { if mo.format != "" && mo.formatDepth == enc.tokens.depth() { return newInvalidFormatError("marshal", t, mo.format) } return enc.WriteToken(String(va.String())) } fncs.unmarshal = func(uo UnmarshalOptions, dec *Decoder, va addressableValue) error { if uo.format != "" && uo.formatDepth == dec.tokens.depth() { return newInvalidFormatError("unmarshal", t, uo.format) } var flags valueFlags val, err := dec.readValue(&flags) if err != nil { return err } k := val.Kind() switch k { case 'n': va.SetString("") return nil case '"': val = unescapeStringMayCopy(val, flags.isVerbatim()) if dec.stringCache == nil { dec.stringCache = new(stringCache) } str := dec.stringCache.make(val) va.SetString(str) return nil } return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t} } return &fncs } var ( encodeBase16 = func(dst, src []byte) { hex.Encode(dst, src) } encodeBase32 = base32.StdEncoding.Encode encodeBase32Hex = base32.HexEncoding.Encode encodeBase64 = base64.StdEncoding.Encode encodeBase64URL = base64.URLEncoding.Encode encodedLenBase16 = hex.EncodedLen encodedLenBase32 = base32.StdEncoding.EncodedLen encodedLenBase32Hex = base32.HexEncoding.EncodedLen encodedLenBase64 = base64.StdEncoding.EncodedLen encodedLenBase64URL = base64.URLEncoding.EncodedLen decodeBase16 = hex.Decode decodeBase32 = base32.StdEncoding.Decode decodeBase32Hex = base32.HexEncoding.Decode decodeBase64 = base64.StdEncoding.Decode decodeBase64URL = base64.URLEncoding.Decode decodedLenBase16 = hex.DecodedLen decodedLenBase32 = base32.StdEncoding.WithPadding(base32.NoPadding).DecodedLen decodedLenBase32Hex = base32.HexEncoding.WithPadding(base32.NoPadding).DecodedLen decodedLenBase64 = base64.StdEncoding.WithPadding(base64.NoPadding).DecodedLen decodedLenBase64URL = base64.URLEncoding.WithPadding(base64.NoPadding).DecodedLen ) func makeBytesArshaler(t reflect.Type, fncs *arshaler) *arshaler { // NOTE: This handles both []byte and [N]byte. marshalDefault := fncs.marshal fncs.marshal = func(mo MarshalOptions, enc *Encoder, va addressableValue) error { encode, encodedLen := encodeBase64, encodedLenBase64 if mo.format != "" && mo.formatDepth == enc.tokens.depth() { switch mo.format { case "base64": encode, encodedLen = encodeBase64, encodedLenBase64 case "base64url": encode, encodedLen = encodeBase64URL, encodedLenBase64URL case "base32": encode, encodedLen = encodeBase32, encodedLenBase32 case "base32hex": encode, encodedLen = encodeBase32Hex, encodedLenBase32Hex case "base16", "hex": encode, encodedLen = encodeBase16, encodedLenBase16 case "array": mo.format = "" return marshalDefault(mo, enc, va) default: return newInvalidFormatError("marshal", t, mo.format) } } val := enc.UnusedBuffer() b := va.Bytes() n := len(`"`) + encodedLen(len(b)) + len(`"`) if cap(val) < n { val = make([]byte, n) } else { val = val[:n] } val[0] = '"' encode(val[len(`"`):len(val)-len(`"`)], b) val[len(val)-1] = '"' return enc.WriteValue(val) } unmarshalDefault := fncs.unmarshal fncs.unmarshal = func(uo UnmarshalOptions, dec *Decoder, va addressableValue) error { decode, decodedLen, encodedLen := decodeBase64, decodedLenBase64, encodedLenBase64 if uo.format != "" && uo.formatDepth == dec.tokens.depth() { switch uo.format { case "base64": decode, decodedLen, encodedLen = decodeBase64, decodedLenBase64, encodedLenBase64 case "base64url": decode, decodedLen, encodedLen = decodeBase64URL, decodedLenBase64URL, encodedLenBase64URL case "base32": decode, decodedLen, encodedLen = decodeBase32, decodedLenBase32, encodedLenBase32 case "base32hex": decode, decodedLen, encodedLen = decodeBase32Hex, decodedLenBase32Hex, encodedLenBase32Hex case "base16", "hex": decode, decodedLen, encodedLen = decodeBase16, decodedLenBase16, encodedLenBase16 case "array": uo.format = "" return unmarshalDefault(uo, dec, va) default: return newInvalidFormatError("unmarshal", t, uo.format) } } var flags valueFlags val, err := dec.readValue(&flags) if err != nil { return err } k := val.Kind() switch k { case 'n': va.Set(reflect.Zero(t)) return nil case '"': val = unescapeStringMayCopy(val, flags.isVerbatim()) // For base64 and base32, decodedLen computes the maximum output size // when given the original input size. To compute the exact size, // adjust the input size by excluding trailing padding characters. // This is unnecessary for base16, but also harmless. n := len(val) for n > 0 && val[n-1] == '=' { n-- } n = decodedLen(n) b := va.Bytes() if va.Kind() == reflect.Array { if n != len(b) { err := fmt.Errorf("decoded base64 length of %d mismatches array length of %d", n, len(b)) return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t, Err: err} } } else { if b == nil || cap(b) < n { b = make([]byte, n) } else { b = b[:n] } } n2, err := decode(b, val) if err == nil && len(val) != encodedLen(n2) { // TODO(https://go.dev/issue/53845): RFC 4648, section 3.3, // specifies that non-alphabet characters must be rejected. // Unfortunately, the "base32" and "base64" packages allow // '\r' and '\n' characters by default. err = errors.New("illegal data at input byte " + strconv.Itoa(bytes.IndexAny(val, "\r\n"))) } if err != nil { return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t, Err: err} } if va.Kind() == reflect.Slice { va.SetBytes(b) } return nil } return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t} } return fncs } func makeIntArshaler(t reflect.Type) *arshaler { var fncs arshaler bits := t.Bits() fncs.marshal = func(mo MarshalOptions, enc *Encoder, va addressableValue) error { if mo.format != "" && mo.formatDepth == enc.tokens.depth() { return newInvalidFormatError("marshal", t, mo.format) } // Optimize for marshaling without preceding whitespace or string escaping. if optimizeCommon && !enc.options.multiline && !mo.StringifyNumbers && !enc.tokens.last.needObjectName() { enc.buf = enc.tokens.mayAppendDelim(enc.buf, '0') enc.buf = strconv.AppendInt(enc.buf, va.Int(), 10) enc.tokens.last.increment() if enc.needFlush() { return enc.flush() } return nil } x := math.Float64frombits(uint64(va.Int())) return enc.writeNumber(x, rawIntNumber, mo.StringifyNumbers) } fncs.unmarshal = func(uo UnmarshalOptions, dec *Decoder, va addressableValue) error { if uo.format != "" && uo.formatDepth == dec.tokens.depth() { return newInvalidFormatError("unmarshal", t, uo.format) } var flags valueFlags val, err := dec.readValue(&flags) if err != nil { return err } k := val.Kind() switch k { case 'n': va.SetInt(0) return nil case '"': if !uo.StringifyNumbers { break } val = unescapeStringMayCopy(val, flags.isVerbatim()) fallthrough case '0': var negOffset int neg := val[0] == '-' if neg { negOffset = 1 } n, ok := parseDecUint(val[negOffset:]) maxInt := uint64(1) << (bits - 1) overflow := (neg && n > maxInt) || (!neg && n > maxInt-1) if !ok { if n != math.MaxUint64 { err := fmt.Errorf("cannot parse %q as signed integer: %w", val, strconv.ErrSyntax) return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t, Err: err} } overflow = true } if overflow { err := fmt.Errorf("cannot parse %q as signed integer: %w", val, strconv.ErrRange) return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t, Err: err} } if neg { va.SetInt(int64(-n)) } else { va.SetInt(int64(+n)) } return nil } return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t} } return &fncs } func makeUintArshaler(t reflect.Type) *arshaler { var fncs arshaler bits := t.Bits() fncs.marshal = func(mo MarshalOptions, enc *Encoder, va addressableValue) error { if mo.format != "" && mo.formatDepth == enc.tokens.depth() { return newInvalidFormatError("marshal", t, mo.format) } // Optimize for marshaling without preceding whitespace or string escaping. if optimizeCommon && !enc.options.multiline && !mo.StringifyNumbers && !enc.tokens.last.needObjectName() { enc.buf = enc.tokens.mayAppendDelim(enc.buf, '0') enc.buf = strconv.AppendUint(enc.buf, va.Uint(), 10) enc.tokens.last.increment() if enc.needFlush() { return enc.flush() } return nil } x := math.Float64frombits(va.Uint()) return enc.writeNumber(x, rawUintNumber, mo.StringifyNumbers) } fncs.unmarshal = func(uo UnmarshalOptions, dec *Decoder, va addressableValue) error { if uo.format != "" && uo.formatDepth == dec.tokens.depth() { return newInvalidFormatError("unmarshal", t, uo.format) } var flags valueFlags val, err := dec.readValue(&flags) if err != nil { return err } k := val.Kind() switch k { case 'n': va.SetUint(0) return nil case '"': if !uo.StringifyNumbers { break } val = unescapeStringMayCopy(val, flags.isVerbatim()) fallthrough case '0': n, ok := parseDecUint(val) maxUint := uint64(1) << bits overflow := n > maxUint-1 if !ok { if n != math.MaxUint64 { err := fmt.Errorf("cannot parse %q as unsigned integer: %w", val, strconv.ErrSyntax) return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t, Err: err} } overflow = true } if overflow { err := fmt.Errorf("cannot parse %q as unsigned integer: %w", val, strconv.ErrRange) return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t, Err: err} } va.SetUint(n) return nil } return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t} } return &fncs } func makeFloatArshaler(t reflect.Type) *arshaler { var fncs arshaler bits := t.Bits() fncs.marshal = func(mo MarshalOptions, enc *Encoder, va addressableValue) error { var allowNonFinite bool if mo.format != "" && mo.formatDepth == enc.tokens.depth() { if mo.format == "nonfinite" { allowNonFinite = true } else { return newInvalidFormatError("marshal", t, mo.format) } } fv := va.Float() if math.IsNaN(fv) || math.IsInf(fv, 0) { if !allowNonFinite { err := fmt.Errorf("invalid value: %v", fv) return &SemanticError{action: "marshal", GoType: t, Err: err} } return enc.WriteToken(Float(fv)) } // Optimize for marshaling without preceding whitespace or string escaping. if optimizeCommon && !enc.options.multiline && !mo.StringifyNumbers && !enc.tokens.last.needObjectName() { enc.buf = enc.tokens.mayAppendDelim(enc.buf, '0') enc.buf = appendNumber(enc.buf, fv, bits) enc.tokens.last.increment() if enc.needFlush() { return enc.flush() } return nil } return enc.writeNumber(fv, bits, mo.StringifyNumbers) } fncs.unmarshal = func(uo UnmarshalOptions, dec *Decoder, va addressableValue) error { var allowNonFinite bool if uo.format != "" && uo.formatDepth == dec.tokens.depth() { if uo.format == "nonfinite" { allowNonFinite = true } else { return newInvalidFormatError("unmarshal", t, uo.format) } } var flags valueFlags val, err := dec.readValue(&flags) if err != nil { return err } k := val.Kind() switch k { case 'n': va.SetFloat(0) return nil case '"': val = unescapeStringMayCopy(val, flags.isVerbatim()) if allowNonFinite { switch string(val) { case "NaN": va.SetFloat(math.NaN()) return nil case "Infinity": va.SetFloat(math.Inf(+1)) return nil case "-Infinity": va.SetFloat(math.Inf(-1)) return nil } } if !uo.StringifyNumbers { break } if n, err := consumeNumber(val); n != len(val) || err != nil { err := fmt.Errorf("cannot parse %q as JSON number: %w", val, strconv.ErrSyntax) return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t, Err: err} } fallthrough case '0': // NOTE: Floating-point parsing is by nature a lossy operation. // We never report an overflow condition since we can always // round the input to the closest representable finite value. // For extremely large numbers, the closest value is ±MaxFloat. fv, _ := parseFloat(val, bits) va.SetFloat(fv) return nil } return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t} } return &fncs } func makeMapArshaler(t reflect.Type) *arshaler { // NOTE: The logic below disables namespaces for tracking duplicate names // when handling map keys with a unique representation. // NOTE: Values retrieved from a map are not addressable, // so we shallow copy the values to make them addressable and // store them back into the map afterwards. var fncs arshaler var ( once sync.Once keyFncs *arshaler valFncs *arshaler ) init := func() { keyFncs = lookupArshaler(t.Key()) valFncs = lookupArshaler(t.Elem()) } fncs.marshal = func(mo MarshalOptions, enc *Encoder, va addressableValue) error { // Check for cycles. if enc.tokens.depth() > startDetectingCyclesAfter { if err := enc.seenPointers.visit(va.Value); err != nil { return err } defer enc.seenPointers.leave(va.Value) } if mo.format != "" && mo.formatDepth == enc.tokens.depth() { if mo.format == "emitnull" { if va.IsNil() { return enc.WriteToken(Null) } mo.format = "" } else { return newInvalidFormatError("marshal", t, mo.format) } } // Optimize for marshaling an empty map without any preceding whitespace. n := va.Len() if optimizeCommon && n == 0 && !enc.options.multiline && !enc.tokens.last.needObjectName() { enc.buf = enc.tokens.mayAppendDelim(enc.buf, '{') enc.buf = append(enc.buf, "{}"...) enc.tokens.last.increment() if enc.needFlush() { return enc.flush() } return nil } once.Do(init) if err := enc.WriteToken(ObjectStart); err != nil { return err } if n > 0 { // Handle maps with numeric key types by stringifying them. mko := mo mko.StringifyNumbers = true nonDefaultKey := keyFncs.nonDefault marshalKey := keyFncs.marshal marshalVal := valFncs.marshal if mo.Marshalers != nil { var ok bool marshalKey, ok = mo.Marshalers.lookup(marshalKey, t.Key()) marshalVal, _ = mo.Marshalers.lookup(marshalVal, t.Elem()) nonDefaultKey = nonDefaultKey || ok } k := newAddressableValue(t.Key()) v := newAddressableValue(t.Elem()) // A Go map guarantees that each entry has a unique key. // As such, disable the expensive duplicate name check if we know // that every Go key will serialize as a unique JSON string. if !nonDefaultKey && mapKeyWithUniqueRepresentation(k.Kind(), enc.options.AllowInvalidUTF8) { enc.tokens.last.disableNamespace() } switch { case !mo.Deterministic || n <= 1: for iter := va.Value.MapRange(); iter.Next(); { k.SetIterKey(iter) if err := marshalKey(mko, enc, k); err != nil { // TODO: If err is errMissingName, then wrap it as a // SemanticError since this key type cannot be serialized // as a JSON string. return err } v.SetIterValue(iter) if err := marshalVal(mo, enc, v); err != nil { return err } } case !nonDefaultKey && t.Key().Kind() == reflect.String: names := getStrings(n) for i, iter := 0, va.Value.MapRange(); i < n && iter.Next(); i++ { k.SetIterKey(iter) (*names)[i] = k.String() } names.Sort() for _, name := range *names { if err := enc.WriteToken(String(name)); err != nil { return err } // TODO(https://go.dev/issue/57061): Use v.SetMapIndexOf. k.SetString(name) v.Set(va.MapIndex(k.Value)) if err := marshalVal(mo, enc, v); err != nil { return err } } putStrings(names) default: type member struct { name string // unquoted name key addressableValue } members := make([]member, n) keys := reflect.MakeSlice(reflect.SliceOf(t.Key()), n, n) for i, iter := 0, va.Value.MapRange(); i < n && iter.Next(); i++ { // Marshal the member name. k := addressableValue{keys.Index(i)} // indexed slice element is always addressable k.SetIterKey(iter) if err := marshalKey(mko, enc, k); err != nil { // TODO: If err is errMissingName, then wrap it as a // SemanticError since this key type cannot be serialized // as a JSON string. return err } name := enc.unwriteOnlyObjectMemberName() members[i] = member{name, k} } // TODO: If AllowDuplicateNames is enabled, then sort according // to reflect.Value as well if the names are equal. // See internal/fmtsort. // TODO(https://go.dev/issue/47619): Use slices.SortFunc instead. sort.Slice(members, func(i, j int) bool { return lessUTF16(members[i].name, members[j].name) }) for _, member := range members { if err := enc.WriteToken(String(member.name)); err != nil { return err } // TODO(https://go.dev/issue/57061): Use v.SetMapIndexOf. v.Set(va.MapIndex(member.key.Value)) if err := marshalVal(mo, enc, v); err != nil { return err } } } } if err := enc.WriteToken(ObjectEnd); err != nil { return err } return nil } fncs.unmarshal = func(uo UnmarshalOptions, dec *Decoder, va addressableValue) error { if uo.format != "" && uo.formatDepth == dec.tokens.depth() { if uo.format == "emitnull" { uo.format = "" // only relevant for marshaling } else { return newInvalidFormatError("unmarshal", t, uo.format) } } tok, err := dec.ReadToken() if err != nil { return err } k := tok.Kind() switch k { case 'n': va.Set(reflect.Zero(t)) return nil case '{': once.Do(init) if va.IsNil() { va.Set(reflect.MakeMap(t)) } // Handle maps with numeric key types by stringifying them. uko := uo uko.StringifyNumbers = true nonDefaultKey := keyFncs.nonDefault unmarshalKey := keyFncs.unmarshal unmarshalVal := valFncs.unmarshal if uo.Unmarshalers != nil { var ok bool unmarshalKey, ok = uo.Unmarshalers.lookup(unmarshalKey, t.Key()) unmarshalVal, _ = uo.Unmarshalers.lookup(unmarshalVal, t.Elem()) nonDefaultKey = nonDefaultKey || ok } k := newAddressableValue(t.Key()) v := newAddressableValue(t.Elem()) // Manually check for duplicate entries by virtue of whether the // unmarshaled key already exists in the destination Go map. // Consequently, syntactically different names (e.g., "0" and "-0") // will be rejected as duplicates since they semantically refer // to the same Go value. This is an unusual interaction // between syntax and semantics, but is more correct. if !nonDefaultKey && mapKeyWithUniqueRepresentation(k.Kind(), dec.options.AllowInvalidUTF8) { dec.tokens.last.disableNamespace() } // In the rare case where the map is not already empty, // then we need to manually track which keys we already saw // since existing presence alone is insufficient to indicate // whether the input had a duplicate name. var seen reflect.Value if !dec.options.AllowDuplicateNames && va.Len() > 0 { seen = reflect.MakeMap(reflect.MapOf(k.Type(), emptyStructType)) } for dec.PeekKind() != '}' { k.Set(reflect.Zero(t.Key())) if err := unmarshalKey(uko, dec, k); err != nil { return err } if k.Kind() == reflect.Interface && !k.IsNil() && !k.Elem().Type().Comparable() { err := fmt.Errorf("invalid incomparable key type %v", k.Elem().Type()) return &SemanticError{action: "unmarshal", GoType: t, Err: err} } if v2 := va.MapIndex(k.Value); v2.IsValid() { if !dec.options.AllowDuplicateNames && (!seen.IsValid() || seen.MapIndex(k.Value).IsValid()) { // TODO: Unread the object name. name := dec.previousBuffer() err := &SyntacticError{str: "duplicate name " + string(name) + " in object"} return err.withOffset(dec.InputOffset() - int64(len(name))) } v.Set(v2) } else { v.Set(reflect.Zero(v.Type())) } err := unmarshalVal(uo, dec, v) va.SetMapIndex(k.Value, v.Value) if seen.IsValid() { seen.SetMapIndex(k.Value, reflect.Zero(emptyStructType)) } if err != nil { return err } } if _, err := dec.ReadToken(); err != nil { return err } return nil } return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t} } return &fncs } // mapKeyWithUniqueRepresentation reports whether all possible values of k // marshal to a different JSON value, and whether all possible JSON values // that can unmarshal into k unmarshal to different Go values. // In other words, the representation must be a bijective. func mapKeyWithUniqueRepresentation(k reflect.Kind, allowInvalidUTF8 bool) bool { switch k { case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return true case reflect.String: // For strings, we have to be careful since names with invalid UTF-8 // maybe unescape to the same Go string value. return !allowInvalidUTF8 default: // Floating-point kinds are not listed above since NaNs // can appear multiple times and all serialize as "NaN". return false } } func makeStructArshaler(t reflect.Type) *arshaler { // NOTE: The logic below disables namespaces for tracking duplicate names // and does the tracking locally with an efficient bit-set based on which // Go struct fields were seen. var fncs arshaler var ( once sync.Once fields structFields errInit *SemanticError ) init := func() { fields, errInit = makeStructFields(t) } fncs.marshal = func(mo MarshalOptions, enc *Encoder, va addressableValue) error { if mo.format != "" && mo.formatDepth == enc.tokens.depth() { return newInvalidFormatError("marshal", t, mo.format) } once.Do(init) if errInit != nil { err := *errInit // shallow copy SemanticError err.action = "marshal" return &err } if err := enc.WriteToken(ObjectStart); err != nil { return err } var seenIdxs uintSet prevIdx := -1 enc.tokens.last.disableNamespace() // we manually ensure unique names below for i := range fields.flattened { f := &fields.flattened[i] v := addressableValue{va.Field(f.index[0])} // addressable if struct value is addressable if len(f.index) > 1 { v = v.fieldByIndex(f.index[1:], false) if !v.IsValid() { continue // implies a nil inlined field } } // OmitZero skips the field if the Go value is zero, // which we can determine up front without calling the marshaler. if f.omitzero && ((f.isZero == nil && v.IsZero()) || (f.isZero != nil && f.isZero(v))) { continue } marshal := f.fncs.marshal nonDefault := f.fncs.nonDefault if mo.Marshalers != nil { var ok bool marshal, ok = mo.Marshalers.lookup(marshal, f.typ) nonDefault = nonDefault || ok } // OmitEmpty skips the field if the marshaled JSON value is empty, // which we can know up front if there are no custom marshalers, // otherwise we must marshal the value and unwrite it if empty. if f.omitempty && !nonDefault && f.isEmpty != nil && f.isEmpty(v) { continue // fast path for omitempty } // Write the object member name. // // The logic below is semantically equivalent to: // enc.WriteToken(String(f.name)) // but specialized and simplified because: // 1. The Encoder must be expecting an object name. // 2. The object namespace is guaranteed to be disabled. // 3. The object name is guaranteed to be valid and pre-escaped. // 4. There is no need to flush the buffer (for unwrite purposes). // 5. There is no possibility of an error occurring. if optimizeCommon { // Append any delimiters or optional whitespace. if enc.tokens.last.length() > 0 { enc.buf = append(enc.buf, ',') } if enc.options.multiline { enc.buf = enc.appendIndent(enc.buf, enc.tokens.needIndent('"')) } // Append the token to the output and to the state machine. n0 := len(enc.buf) // offset before calling appendString if enc.options.EscapeRune == nil { enc.buf = append(enc.buf, f.quotedName...) } else { enc.buf, _ = appendString(enc.buf, f.name, false, enc.options.EscapeRune) } if !enc.options.AllowDuplicateNames { enc.names.replaceLastQuotedOffset(n0) } enc.tokens.last.increment() } else { if err := enc.WriteToken(String(f.name)); err != nil { return err } } // Write the object member value. mo2 := mo if f.string { mo2.StringifyNumbers = true } if f.format != "" { mo2.formatDepth = enc.tokens.depth() mo2.format = f.format } if err := marshal(mo2, enc, v); err != nil { return err } // Try unwriting the member if empty (slow path for omitempty). if f.omitempty { var prevName *string if prevIdx >= 0 { prevName = &fields.flattened[prevIdx].name } if enc.unwriteEmptyObjectMember(prevName) { continue } } // Remember the previous written object member. // The set of seen fields only needs to be updated to detect // duplicate names with those from the inlined fallback. if !enc.options.AllowDuplicateNames && fields.inlinedFallback != nil { seenIdxs.insert(uint(f.id)) } prevIdx = f.id } if fields.inlinedFallback != nil && !(mo.DiscardUnknownMembers && fields.inlinedFallback.unknown) { var insertUnquotedName func([]byte) bool if !enc.options.AllowDuplicateNames { insertUnquotedName = func(name []byte) bool { // Check that the name from inlined fallback does not match // one of the previously marshaled names from known fields. if foldedFields := fields.byFoldedName[string(foldName(name))]; len(foldedFields) > 0 { if f := fields.byActualName[string(name)]; f != nil { return seenIdxs.insert(uint(f.id)) } for _, f := range foldedFields { if f.nocase { return seenIdxs.insert(uint(f.id)) } } } // Check that the name does not match any other name // previously marshaled from the inlined fallback. return enc.namespaces.last().insertUnquoted(name) } } if err := marshalInlinedFallbackAll(mo, enc, va, fields.inlinedFallback, insertUnquotedName); err != nil { return err } } if err := enc.WriteToken(ObjectEnd); err != nil { return err } return nil } fncs.unmarshal = func(uo UnmarshalOptions, dec *Decoder, va addressableValue) error { if uo.format != "" && uo.formatDepth == dec.tokens.depth() { return newInvalidFormatError("unmarshal", t, uo.format) } tok, err := dec.ReadToken() if err != nil { return err } k := tok.Kind() switch k { case 'n': va.Set(reflect.Zero(t)) return nil case '{': once.Do(init) if errInit != nil { err := *errInit // shallow copy SemanticError err.action = "unmarshal" return &err } var seenIdxs uintSet dec.tokens.last.disableNamespace() for dec.PeekKind() != '}' { // Process the object member name. var flags valueFlags val, err := dec.readValue(&flags) if err != nil { return err } name := unescapeStringMayCopy(val, flags.isVerbatim()) f := fields.byActualName[string(name)] if f == nil { for _, f2 := range fields.byFoldedName[string(foldName(name))] { if f2.nocase { f = f2 break } } if f == nil { if uo.RejectUnknownMembers && (fields.inlinedFallback == nil || fields.inlinedFallback.unknown) { return &SemanticError{action: "unmarshal", GoType: t, Err: fmt.Errorf("unknown name %s", val)} } if !dec.options.AllowDuplicateNames && !dec.namespaces.last().insertUnquoted(name) { // TODO: Unread the object name. err := &SyntacticError{str: "duplicate name " + string(val) + " in object"} return err.withOffset(dec.InputOffset() - int64(len(val))) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
true
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal.go
// Copyright 2020 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package json import ( "errors" "io" "reflect" "sync" ) // MarshalOptions configures how Go data is serialized as JSON data. // The zero value is equivalent to the default marshal settings. type MarshalOptions struct { requireKeyedLiterals nonComparable // Marshalers is a list of type-specific marshalers to use. Marshalers *Marshalers // StringifyNumbers specifies that numeric Go types should be serialized // as a JSON string containing the equivalent JSON number value. // // According to RFC 8259, section 6, a JSON implementation may choose to // limit the representation of a JSON number to an IEEE 754 binary64 value. // This may cause decoders to lose precision for int64 and uint64 types. // Escaping JSON numbers as a JSON string preserves the exact precision. StringifyNumbers bool // DiscardUnknownMembers specifies that marshaling should ignore any // JSON object members stored in Go struct fields dedicated to storing // unknown JSON object members. DiscardUnknownMembers bool // Deterministic specifies that the same input value will be serialized // as the exact same output bytes. Different processes of // the same program will serialize equal values to the same bytes, // but different versions of the same program are not guaranteed // to produce the exact same sequence of bytes. Deterministic bool // formatDepth is the depth at which we respect the format flag. formatDepth int // format is custom formatting for the value at the specified depth. format string } // Marshal serializes a Go value as a []byte with default options. // It is a thin wrapper over MarshalOptions.Marshal. func Marshal(in any) (out []byte, err error) { return MarshalOptions{}.Marshal(EncodeOptions{}, in) } // MarshalFull serializes a Go value into an io.Writer with default options. // It is a thin wrapper over MarshalOptions.MarshalFull. func MarshalFull(out io.Writer, in any) error { return MarshalOptions{}.MarshalFull(EncodeOptions{}, out, in) } // Marshal serializes a Go value as a []byte according to the provided // marshal and encode options. It does not terminate the output with a newline. // See MarshalNext for details about the conversion of a Go value into JSON. func (mo MarshalOptions) Marshal(eo EncodeOptions, in any) (out []byte, err error) { enc := getBufferedEncoder(eo) defer putBufferedEncoder(enc) enc.options.omitTopLevelNewline = true err = mo.MarshalNext(enc, in) // TODO(https://go.dev/issue/45038): Use bytes.Clone. return append([]byte(nil), enc.buf...), err } // MarshalFull serializes a Go value into an io.Writer according to the provided // marshal and encode options. It does not terminate the output with a newline. // See MarshalNext for details about the conversion of a Go value into JSON. func (mo MarshalOptions) MarshalFull(eo EncodeOptions, out io.Writer, in any) error { enc := getStreamingEncoder(out, eo) defer putStreamingEncoder(enc) enc.options.omitTopLevelNewline = true err := mo.MarshalNext(enc, in) return err } // MarshalNext encodes a Go value as the next JSON value according to // the provided marshal options. // // Type-specific marshal functions and methods take precedence // over the default representation of a value. // Functions or methods that operate on *T are only called when encoding // a value of type T (by taking its address) or a non-nil value of *T. // MarshalNext ensures that a value is always addressable // (by boxing it on the heap if necessary) so that // these functions and methods can be consistently called. For performance, // it is recommended that MarshalNext be passed a non-nil pointer to the value. // // The input value is encoded as JSON according the following rules: // // - If any type-specific functions in MarshalOptions.Marshalers match // the value type, then those functions are called to encode the value. // If all applicable functions return SkipFunc, // then the value is encoded according to subsequent rules. // // - If the value type implements MarshalerV2, // then the MarshalNextJSON method is called to encode the value. // // - If the value type implements MarshalerV1, // then the MarshalJSON method is called to encode the value. // // - If the value type implements encoding.TextMarshaler, // then the MarshalText method is called to encode the value and // subsequently encode its result as a JSON string. // // - Otherwise, the value is encoded according to the value's type // as described in detail below. // // Most Go types have a default JSON representation. // Certain types support specialized formatting according to // a format flag optionally specified in the Go struct tag // for the struct field that contains the current value // (see the “JSON Representation of Go structs” section for more details). // // The representation of each type is as follows: // // - A Go boolean is encoded as a JSON boolean (e.g., true or false). // It does not support any custom format flags. // // - A Go string is encoded as a JSON string. // It does not support any custom format flags. // // - A Go []byte or [N]byte is encoded as a JSON string containing // the binary value encoded using RFC 4648. // If the format is "base64" or unspecified, then this uses RFC 4648, section 4. // If the format is "base64url", then this uses RFC 4648, section 5. // If the format is "base32", then this uses RFC 4648, section 6. // If the format is "base32hex", then this uses RFC 4648, section 7. // If the format is "base16" or "hex", then this uses RFC 4648, section 8. // If the format is "array", then the bytes value is encoded as a JSON array // where each byte is recursively JSON-encoded as each JSON array element. // // - A Go integer is encoded as a JSON number without fractions or exponents. // If MarshalOptions.StringifyNumbers is specified, then the JSON number is // encoded within a JSON string. It does not support any custom format // flags. // // - A Go float is encoded as a JSON number. // If MarshalOptions.StringifyNumbers is specified, // then the JSON number is encoded within a JSON string. // If the format is "nonfinite", then NaN, +Inf, and -Inf are encoded as // the JSON strings "NaN", "Infinity", and "-Infinity", respectively. // Otherwise, the presence of non-finite numbers results in a SemanticError. // // - A Go map is encoded as a JSON object, where each Go map key and value // is recursively encoded as a name and value pair in the JSON object. // The Go map key must encode as a JSON string, otherwise this results // in a SemanticError. When encoding keys, MarshalOptions.StringifyNumbers // is automatically applied so that numeric keys encode as JSON strings. // The Go map is traversed in a non-deterministic order. // For deterministic encoding, consider using RawValue.Canonicalize. // If the format is "emitnull", then a nil map is encoded as a JSON null. // Otherwise by default, a nil map is encoded as an empty JSON object. // // - A Go struct is encoded as a JSON object. // See the “JSON Representation of Go structs” section // in the package-level documentation for more details. // // - A Go slice is encoded as a JSON array, where each Go slice element // is recursively JSON-encoded as the elements of the JSON array. // If the format is "emitnull", then a nil slice is encoded as a JSON null. // Otherwise by default, a nil slice is encoded as an empty JSON array. // // - A Go array is encoded as a JSON array, where each Go array element // is recursively JSON-encoded as the elements of the JSON array. // The JSON array length is always identical to the Go array length. // It does not support any custom format flags. // // - A Go pointer is encoded as a JSON null if nil, otherwise it is // the recursively JSON-encoded representation of the underlying value. // Format flags are forwarded to the encoding of the underlying value. // // - A Go interface is encoded as a JSON null if nil, otherwise it is // the recursively JSON-encoded representation of the underlying value. // It does not support any custom format flags. // // - A Go time.Time is encoded as a JSON string containing the timestamp // formatted in RFC 3339 with nanosecond resolution. // If the format matches one of the format constants declared // in the time package (e.g., RFC1123), then that format is used. // Otherwise, the format is used as-is with time.Time.Format if non-empty. // // - A Go time.Duration is encoded as a JSON string containing the duration // formatted according to time.Duration.String. // If the format is "nanos", it is encoded as a JSON number // containing the number of nanoseconds in the duration. // // - All other Go types (e.g., complex numbers, channels, and functions) // have no default representation and result in a SemanticError. // // JSON cannot represent cyclic data structures and // MarshalNext does not handle them. // Passing cyclic structures will result in an error. func (mo MarshalOptions) MarshalNext(out *Encoder, in any) error { v := reflect.ValueOf(in) if !v.IsValid() || (v.Kind() == reflect.Pointer && v.IsNil()) { return out.WriteToken(Null) } // Shallow copy non-pointer values to obtain an addressable value. // It is beneficial to performance to always pass pointers to avoid this. if v.Kind() != reflect.Pointer { v2 := reflect.New(v.Type()) v2.Elem().Set(v) v = v2 } va := addressableValue{v.Elem()} // dereferenced pointer is always addressable t := va.Type() // Lookup and call the marshal function for this type. marshal := lookupArshaler(t).marshal if mo.Marshalers != nil { marshal, _ = mo.Marshalers.lookup(marshal, t) } if err := marshal(mo, out, va); err != nil { if !out.options.AllowDuplicateNames { out.tokens.invalidateDisabledNamespaces() } return err } return nil } // UnmarshalOptions configures how JSON data is deserialized as Go data. // The zero value is equivalent to the default unmarshal settings. type UnmarshalOptions struct { requireKeyedLiterals nonComparable // Unmarshalers is a list of type-specific unmarshalers to use. Unmarshalers *Unmarshalers // StringifyNumbers specifies that numeric Go types can be deserialized // from either a JSON number or a JSON string containing a JSON number // without any surrounding whitespace. StringifyNumbers bool // RejectUnknownMembers specifies that unknown members should be rejected // when unmarshaling a JSON object, regardless of whether there is a field // to store unknown members. RejectUnknownMembers bool // formatDepth is the depth at which we respect the format flag. formatDepth int // format is custom formatting for the value at the specified depth. format string } // Unmarshal deserializes a Go value from a []byte with default options. // It is a thin wrapper over UnmarshalOptions.Unmarshal. func Unmarshal(in []byte, out any) error { return UnmarshalOptions{}.Unmarshal(DecodeOptions{}, in, out) } // UnmarshalFull deserializes a Go value from an io.Reader with default options. // It is a thin wrapper over UnmarshalOptions.UnmarshalFull. func UnmarshalFull(in io.Reader, out any) error { return UnmarshalOptions{}.UnmarshalFull(DecodeOptions{}, in, out) } // Unmarshal deserializes a Go value from a []byte according to the // provided unmarshal and decode options. The output must be a non-nil pointer. // The input must be a single JSON value with optional whitespace interspersed. // See UnmarshalNext for details about the conversion of JSON into a Go value. func (uo UnmarshalOptions) Unmarshal(do DecodeOptions, in []byte, out any) error { dec := getBufferedDecoder(in, do) defer putBufferedDecoder(dec) return uo.unmarshalFull(dec, out) } // UnmarshalFull deserializes a Go value from an io.Reader according to the // provided unmarshal and decode options. The output must be a non-nil pointer. // The input must be a single JSON value with optional whitespace interspersed. // It consumes the entirety of io.Reader until io.EOF is encountered. // See UnmarshalNext for details about the conversion of JSON into a Go value. func (uo UnmarshalOptions) UnmarshalFull(do DecodeOptions, in io.Reader, out any) error { dec := getStreamingDecoder(in, do) defer putStreamingDecoder(dec) return uo.unmarshalFull(dec, out) } func (uo UnmarshalOptions) unmarshalFull(in *Decoder, out any) error { switch err := uo.UnmarshalNext(in, out); err { case nil: return in.checkEOF() case io.EOF: return io.ErrUnexpectedEOF default: return err } } // UnmarshalNext decodes the next JSON value into a Go value according to // the provided unmarshal options. The output must be a non-nil pointer. // // Type-specific unmarshal functions and methods take precedence // over the default representation of a value. // Functions or methods that operate on *T are only called when decoding // a value of type T (by taking its address) or a non-nil value of *T. // UnmarshalNext ensures that a value is always addressable // (by boxing it on the heap if necessary) so that // these functions and methods can be consistently called. // // The input is decoded into the output according the following rules: // // - If any type-specific functions in UnmarshalOptions.Unmarshalers match // the value type, then those functions are called to decode the JSON // value. If all applicable functions return SkipFunc, // then the input is decoded according to subsequent rules. // // - If the value type implements UnmarshalerV2, // then the UnmarshalNextJSON method is called to decode the JSON value. // // - If the value type implements UnmarshalerV1, // then the UnmarshalJSON method is called to decode the JSON value. // // - If the value type implements encoding.TextUnmarshaler, // then the input is decoded as a JSON string and // the UnmarshalText method is called with the decoded string value. // This fails with a SemanticError if the input is not a JSON string. // // - Otherwise, the JSON value is decoded according to the value's type // as described in detail below. // // Most Go types have a default JSON representation. // Certain types support specialized formatting according to // a format flag optionally specified in the Go struct tag // for the struct field that contains the current value // (see the “JSON Representation of Go structs” section for more details). // A JSON null may be decoded into every supported Go value where // it is equivalent to storing the zero value of the Go value. // If the input JSON kind is not handled by the current Go value type, // then this fails with a SemanticError. Unless otherwise specified, // the decoded value replaces any pre-existing value. // // The representation of each type is as follows: // // - A Go boolean is decoded from a JSON boolean (e.g., true or false). // It does not support any custom format flags. // // - A Go string is decoded from a JSON string. // It does not support any custom format flags. // // - A Go []byte or [N]byte is decoded from a JSON string // containing the binary value encoded using RFC 4648. // If the format is "base64" or unspecified, then this uses RFC 4648, section 4. // If the format is "base64url", then this uses RFC 4648, section 5. // If the format is "base32", then this uses RFC 4648, section 6. // If the format is "base32hex", then this uses RFC 4648, section 7. // If the format is "base16" or "hex", then this uses RFC 4648, section 8. // If the format is "array", then the Go slice or array is decoded from a // JSON array where each JSON element is recursively decoded for each byte. // When decoding into a non-nil []byte, the slice length is reset to zero // and the decoded input is appended to it. // When decoding into a [N]byte, the input must decode to exactly N bytes, // otherwise it fails with a SemanticError. // // - A Go integer is decoded from a JSON number. // It may also be decoded from a JSON string containing a JSON number // if UnmarshalOptions.StringifyNumbers is specified. // It fails with a SemanticError if the JSON number // has a fractional or exponent component. // It also fails if it overflows the representation of the Go integer type. // It does not support any custom format flags. // // - A Go float is decoded from a JSON number. // It may also be decoded from a JSON string containing a JSON number // if UnmarshalOptions.StringifyNumbers is specified. // The JSON number is parsed as the closest representable Go float value. // If the format is "nonfinite", then the JSON strings // "NaN", "Infinity", and "-Infinity" are decoded as NaN, +Inf, and -Inf. // Otherwise, the presence of such strings results in a SemanticError. // // - A Go map is decoded from a JSON object, // where each JSON object name and value pair is recursively decoded // as the Go map key and value. When decoding keys, // UnmarshalOptions.StringifyNumbers is automatically applied so that // numeric keys can decode from JSON strings. Maps are not cleared. // If the Go map is nil, then a new map is allocated to decode into. // If the decoded key matches an existing Go map entry, the entry value // is reused by decoding the JSON object value into it. // The only supported format is "emitnull" and has no effect when decoding. // // - A Go struct is decoded from a JSON object. // See the “JSON Representation of Go structs” section // in the package-level documentation for more details. // // - A Go slice is decoded from a JSON array, where each JSON element // is recursively decoded and appended to the Go slice. // Before appending into a Go slice, a new slice is allocated if it is nil, // otherwise the slice length is reset to zero. // The only supported format is "emitnull" and has no effect when decoding. // // - A Go array is decoded from a JSON array, where each JSON array element // is recursively decoded as each corresponding Go array element. // Each Go array element is zeroed before decoding into it. // It fails with a SemanticError if the JSON array does not contain // the exact same number of elements as the Go array. // It does not support any custom format flags. // // - A Go pointer is decoded based on the JSON kind and underlying Go type. // If the input is a JSON null, then this stores a nil pointer. // Otherwise, it allocates a new underlying value if the pointer is nil, // and recursively JSON decodes into the underlying value. // Format flags are forwarded to the decoding of the underlying type. // // - A Go interface is decoded based on the JSON kind and underlying Go type. // If the input is a JSON null, then this stores a nil interface value. // Otherwise, a nil interface value of an empty interface type is initialized // with a zero Go bool, string, float64, map[string]any, or []any if the // input is a JSON boolean, string, number, object, or array, respectively. // If the interface value is still nil, then this fails with a SemanticError // since decoding could not determine an appropriate Go type to decode into. // For example, unmarshaling into a nil io.Reader fails since // there is no concrete type to populate the interface value with. // Otherwise an underlying value exists and it recursively decodes // the JSON input into it. It does not support any custom format flags. // // - A Go time.Time is decoded from a JSON string containing the time // formatted in RFC 3339 with nanosecond resolution. // If the format matches one of the format constants declared in // the time package (e.g., RFC1123), then that format is used for parsing. // Otherwise, the format is used as-is with time.Time.Parse if non-empty. // // - A Go time.Duration is decoded from a JSON string by // passing the decoded string to time.ParseDuration. // If the format is "nanos", it is instead decoded from a JSON number // containing the number of nanoseconds in the duration. // // - All other Go types (e.g., complex numbers, channels, and functions) // have no default representation and result in a SemanticError. // // In general, unmarshaling follows merge semantics (similar to RFC 7396) // where the decoded Go value replaces the destination value // for any JSON kind other than an object. // For JSON objects, the input object is merged into the destination value // where matching object members recursively apply merge semantics. func (uo UnmarshalOptions) UnmarshalNext(in *Decoder, out any) error { v := reflect.ValueOf(out) if !v.IsValid() || v.Kind() != reflect.Pointer || v.IsNil() { var t reflect.Type if v.IsValid() { t = v.Type() if t.Kind() == reflect.Pointer { t = t.Elem() } } err := errors.New("value must be passed as a non-nil pointer reference") return &SemanticError{action: "unmarshal", GoType: t, Err: err} } va := addressableValue{v.Elem()} // dereferenced pointer is always addressable t := va.Type() // Lookup and call the unmarshal function for this type. unmarshal := lookupArshaler(t).unmarshal if uo.Unmarshalers != nil { unmarshal, _ = uo.Unmarshalers.lookup(unmarshal, t) } if err := unmarshal(uo, in, va); err != nil { if !in.options.AllowDuplicateNames { in.tokens.invalidateDisabledNamespaces() } return err } return nil } // addressableValue is a reflect.Value that is guaranteed to be addressable // such that calling the Addr and Set methods do not panic. // // There is no compile magic that enforces this property, // but rather the need to construct this type makes it easier to examine each // construction site to ensure that this property is upheld. type addressableValue struct{ reflect.Value } // newAddressableValue constructs a new addressable value of type t. func newAddressableValue(t reflect.Type) addressableValue { return addressableValue{reflect.New(t).Elem()} } // All marshal and unmarshal behavior is implemented using these signatures. type ( marshaler = func(MarshalOptions, *Encoder, addressableValue) error unmarshaler = func(UnmarshalOptions, *Decoder, addressableValue) error ) type arshaler struct { marshal marshaler unmarshal unmarshaler nonDefault bool } var lookupArshalerCache sync.Map // map[reflect.Type]*arshaler func lookupArshaler(t reflect.Type) *arshaler { if v, ok := lookupArshalerCache.Load(t); ok { return v.(*arshaler) } fncs := makeDefaultArshaler(t) fncs = makeMethodArshaler(fncs, t) fncs = makeTimeArshaler(fncs, t) // Use the last stored so that duplicate arshalers can be garbage collected. v, _ := lookupArshalerCache.LoadOrStore(t, fncs) return v.(*arshaler) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/errors.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/errors.go
// Copyright 2020 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package json import ( "errors" "reflect" "strconv" "strings" "unicode/utf8" ) const errorPrefix = "json: " // Error matches errors returned by this package according to errors.Is. const Error = jsonError("json error") type jsonError string func (e jsonError) Error() string { return string(e) } func (e jsonError) Is(target error) bool { return e == target || target == Error } type ioError struct { action string // either "read" or "write" err error } func (e *ioError) Error() string { return errorPrefix + e.action + " error: " + e.err.Error() } func (e *ioError) Unwrap() error { return e.err } func (e *ioError) Is(target error) bool { return e == target || target == Error || errors.Is(e.err, target) } // SemanticError describes an error determining the meaning // of JSON data as Go data or vice-versa. // // The contents of this error as produced by this package may change over time. type SemanticError struct { requireKeyedLiterals nonComparable action string // either "marshal" or "unmarshal" // ByteOffset indicates that an error occurred after this byte offset. ByteOffset int64 // JSONPointer indicates that an error occurred within this JSON value // as indicated using the JSON Pointer notation (see RFC 6901). JSONPointer string // JSONKind is the JSON kind that could not be handled. JSONKind Kind // may be zero if unknown // GoType is the Go type that could not be handled. GoType reflect.Type // may be nil if unknown // Err is the underlying error. Err error // may be nil } func (e *SemanticError) Error() string { var sb strings.Builder sb.WriteString(errorPrefix) // Hyrum-proof the error message by deliberately switching between // two equivalent renderings of the same error message. // The randomization is tied to the Hyrum-proofing already applied // on map iteration in Go. for phrase := range map[string]struct{}{"cannot": {}, "unable to": {}} { sb.WriteString(phrase) break // use whichever phrase we get in the first iteration } // Format action. var preposition string switch e.action { case "marshal": sb.WriteString(" marshal") preposition = " from" case "unmarshal": sb.WriteString(" unmarshal") preposition = " into" default: sb.WriteString(" handle") preposition = " with" } // Format JSON kind. var omitPreposition bool switch e.JSONKind { case 'n': sb.WriteString(" JSON null") case 'f', 't': sb.WriteString(" JSON boolean") case '"': sb.WriteString(" JSON string") case '0': sb.WriteString(" JSON number") case '{', '}': sb.WriteString(" JSON object") case '[', ']': sb.WriteString(" JSON array") default: omitPreposition = true } // Format Go type. if e.GoType != nil { if !omitPreposition { sb.WriteString(preposition) } sb.WriteString(" Go value of type ") sb.WriteString(e.GoType.String()) } // Format where. switch { case e.JSONPointer != "": sb.WriteString(" within JSON value at ") sb.WriteString(strconv.Quote(e.JSONPointer)) case e.ByteOffset > 0: sb.WriteString(" after byte offset ") sb.WriteString(strconv.FormatInt(e.ByteOffset, 10)) } // Format underlying error. if e.Err != nil { sb.WriteString(": ") sb.WriteString(e.Err.Error()) } return sb.String() } func (e *SemanticError) Is(target error) bool { return e == target || target == Error || errors.Is(e.Err, target) } func (e *SemanticError) Unwrap() error { return e.Err } // SyntacticError is a description of a syntactic error that occurred when // encoding or decoding JSON according to the grammar. // // The contents of this error as produced by this package may change over time. type SyntacticError struct { requireKeyedLiterals nonComparable // ByteOffset indicates that an error occurred after this byte offset. ByteOffset int64 str string } func (e *SyntacticError) Error() string { return errorPrefix + e.str } func (e *SyntacticError) Is(target error) bool { return e == target || target == Error } func (e *SyntacticError) withOffset(pos int64) error { return &SyntacticError{ByteOffset: pos, str: e.str} } func newInvalidCharacterError(prefix []byte, where string) *SyntacticError { what := quoteRune(prefix) return &SyntacticError{str: "invalid character " + what + " " + where} } func quoteRune(b []byte) string { r, n := utf8.DecodeRune(b) if r == utf8.RuneError && n == 1 { return `'\x` + strconv.FormatUint(uint64(b[0]), 16) + `'` } return strconv.QuoteRune(r) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_methods.go
cmd/vsphere-xcopy-volume-populator/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_methods.go
// Copyright 2020 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package json import ( "encoding" "errors" "reflect" ) // Interfaces for custom serialization. var ( jsonMarshalerV1Type = reflect.TypeOf((*MarshalerV1)(nil)).Elem() jsonMarshalerV2Type = reflect.TypeOf((*MarshalerV2)(nil)).Elem() jsonUnmarshalerV1Type = reflect.TypeOf((*UnmarshalerV1)(nil)).Elem() jsonUnmarshalerV2Type = reflect.TypeOf((*UnmarshalerV2)(nil)).Elem() textMarshalerType = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem() textUnmarshalerType = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem() ) // MarshalerV1 is implemented by types that can marshal themselves. // It is recommended that types implement MarshalerV2 unless the implementation // is trying to avoid a hard dependency on the "jsontext" package. // // It is recommended that implementations return a buffer that is safe // for the caller to retain and potentially mutate. type MarshalerV1 interface { MarshalJSON() ([]byte, error) } // MarshalerV2 is implemented by types that can marshal themselves. // It is recommended that types implement MarshalerV2 instead of MarshalerV1 // since this is both more performant and flexible. // If a type implements both MarshalerV1 and MarshalerV2, // then MarshalerV2 takes precedence. In such a case, both implementations // should aim to have equivalent behavior for the default marshal options. // // The implementation must write only one JSON value to the Encoder and // must not retain the pointer to Encoder. type MarshalerV2 interface { MarshalNextJSON(MarshalOptions, *Encoder) error // TODO: Should users call the MarshalOptions.MarshalNext method or // should/can they call this method directly? Does it matter? } // UnmarshalerV1 is implemented by types that can unmarshal themselves. // It is recommended that types implement UnmarshalerV2 unless // the implementation is trying to avoid a hard dependency on this package. // // The input can be assumed to be a valid encoding of a JSON value // if called from unmarshal functionality in this package. // UnmarshalJSON must copy the JSON data if it is retained after returning. // It is recommended that UnmarshalJSON implement merge semantics when // unmarshaling into a pre-populated value. // // Implementations must not retain or mutate the input []byte. type UnmarshalerV1 interface { UnmarshalJSON([]byte) error } // UnmarshalerV2 is implemented by types that can unmarshal themselves. // It is recommended that types implement UnmarshalerV2 instead of UnmarshalerV1 // since this is both more performant and flexible. // If a type implements both UnmarshalerV1 and UnmarshalerV2, // then UnmarshalerV2 takes precedence. In such a case, both implementations // should aim to have equivalent behavior for the default unmarshal options. // // The implementation must read only one JSON value from the Decoder. // It is recommended that UnmarshalNextJSON implement merge semantics when // unmarshaling into a pre-populated value. // // Implementations must not retain the pointer to Decoder. type UnmarshalerV2 interface { UnmarshalNextJSON(UnmarshalOptions, *Decoder) error // TODO: Should users call the UnmarshalOptions.UnmarshalNext method or // should/can they call this method directly? Does it matter? } func makeMethodArshaler(fncs *arshaler, t reflect.Type) *arshaler { // Avoid injecting method arshaler on the pointer or interface version // to avoid ever calling the method on a nil pointer or interface receiver. // Let it be injected on the value receiver (which is always addressable). if t.Kind() == reflect.Pointer || t.Kind() == reflect.Interface { return fncs } // Handle custom marshaler. switch which, needAddr := implementsWhich(t, jsonMarshalerV2Type, jsonMarshalerV1Type, textMarshalerType); which { case jsonMarshalerV2Type: fncs.nonDefault = true fncs.marshal = func(mo MarshalOptions, enc *Encoder, va addressableValue) error { prevDepth, prevLength := enc.tokens.depthLength() err := va.addrWhen(needAddr).Interface().(MarshalerV2).MarshalNextJSON(mo, enc) currDepth, currLength := enc.tokens.depthLength() if (prevDepth != currDepth || prevLength+1 != currLength) && err == nil { err = errors.New("must write exactly one JSON value") } if err != nil { err = wrapSkipFunc(err, "marshal method") // TODO: Avoid wrapping semantic or I/O errors. return &SemanticError{action: "marshal", GoType: t, Err: err} } return nil } case jsonMarshalerV1Type: fncs.nonDefault = true fncs.marshal = func(mo MarshalOptions, enc *Encoder, va addressableValue) error { marshaler := va.addrWhen(needAddr).Interface().(MarshalerV1) val, err := marshaler.MarshalJSON() if err != nil { err = wrapSkipFunc(err, "marshal method") // TODO: Avoid wrapping semantic errors. return &SemanticError{action: "marshal", GoType: t, Err: err} } if err := enc.WriteValue(val); err != nil { // TODO: Avoid wrapping semantic or I/O errors. return &SemanticError{action: "marshal", JSONKind: RawValue(val).Kind(), GoType: t, Err: err} } return nil } case textMarshalerType: fncs.nonDefault = true fncs.marshal = func(mo MarshalOptions, enc *Encoder, va addressableValue) error { marshaler := va.addrWhen(needAddr).Interface().(encoding.TextMarshaler) s, err := marshaler.MarshalText() if err != nil { err = wrapSkipFunc(err, "marshal method") // TODO: Avoid wrapping semantic errors. return &SemanticError{action: "marshal", JSONKind: '"', GoType: t, Err: err} } val := enc.UnusedBuffer() val, err = appendString(val, string(s), true, nil) if err != nil { return &SemanticError{action: "marshal", JSONKind: '"', GoType: t, Err: err} } if err := enc.WriteValue(val); err != nil { // TODO: Avoid wrapping syntactic or I/O errors. return &SemanticError{action: "marshal", JSONKind: '"', GoType: t, Err: err} } return nil } } // Handle custom unmarshaler. switch which, needAddr := implementsWhich(t, jsonUnmarshalerV2Type, jsonUnmarshalerV1Type, textUnmarshalerType); which { case jsonUnmarshalerV2Type: fncs.nonDefault = true fncs.unmarshal = func(uo UnmarshalOptions, dec *Decoder, va addressableValue) error { prevDepth, prevLength := dec.tokens.depthLength() err := va.addrWhen(needAddr).Interface().(UnmarshalerV2).UnmarshalNextJSON(uo, dec) currDepth, currLength := dec.tokens.depthLength() if (prevDepth != currDepth || prevLength+1 != currLength) && err == nil { err = errors.New("must read exactly one JSON value") } if err != nil { err = wrapSkipFunc(err, "unmarshal method") // TODO: Avoid wrapping semantic, syntactic, or I/O errors. return &SemanticError{action: "unmarshal", GoType: t, Err: err} } return nil } case jsonUnmarshalerV1Type: fncs.nonDefault = true fncs.unmarshal = func(uo UnmarshalOptions, dec *Decoder, va addressableValue) error { val, err := dec.ReadValue() if err != nil { return err // must be a syntactic or I/O error } unmarshaler := va.addrWhen(needAddr).Interface().(UnmarshalerV1) if err := unmarshaler.UnmarshalJSON(val); err != nil { err = wrapSkipFunc(err, "unmarshal method") // TODO: Avoid wrapping semantic, syntactic, or I/O errors. return &SemanticError{action: "unmarshal", JSONKind: val.Kind(), GoType: t, Err: err} } return nil } case textUnmarshalerType: fncs.nonDefault = true fncs.unmarshal = func(uo UnmarshalOptions, dec *Decoder, va addressableValue) error { var flags valueFlags val, err := dec.readValue(&flags) if err != nil { return err // must be a syntactic or I/O error } if val.Kind() != '"' { err = errors.New("JSON value must be string type") return &SemanticError{action: "unmarshal", JSONKind: val.Kind(), GoType: t, Err: err} } s := unescapeStringMayCopy(val, flags.isVerbatim()) unmarshaler := va.addrWhen(needAddr).Interface().(encoding.TextUnmarshaler) if err := unmarshaler.UnmarshalText(s); err != nil { err = wrapSkipFunc(err, "unmarshal method") // TODO: Avoid wrapping semantic, syntactic, or I/O errors. return &SemanticError{action: "unmarshal", JSONKind: val.Kind(), GoType: t, Err: err} } return nil } } return fncs } // implementsWhich is like t.Implements(ifaceType) for a list of interfaces, // but checks whether either t or reflect.PointerTo(t) implements the interface. // It returns the first interface type that matches and whether a value of t // needs to be addressed first before it implements the interface. func implementsWhich(t reflect.Type, ifaceTypes ...reflect.Type) (which reflect.Type, needAddr bool) { for _, ifaceType := range ifaceTypes { switch { case t.Implements(ifaceType): return ifaceType, false case reflect.PointerTo(t).Implements(ifaceType): return ifaceType, true } } return nil, false } // addrWhen returns va.Addr if addr is specified, otherwise it returns itself. func (va addressableValue) addrWhen(addr bool) reflect.Value { if addr { return va.Addr() } return va.Value }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false