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/vendor/github.com/ncruces/go-strftime/strftime.go
vendor/github.com/ncruces/go-strftime/strftime.go
package strftime import ( "bytes" "strconv" "time" ) // Format returns a textual representation of the time value // formatted according to the strftime format specification. func Format(fmt string, t time.Time) string { buf := buffer(fmt) return string(AppendFormat(buf, fmt, t)) } // AppendFormat is like Format, but appends the textual representation // to dst and returns the extended buffer. func AppendFormat(dst []byte, fmt string, t time.Time) []byte { var parser parser parser.literal = func(b byte) error { dst = append(dst, b) return nil } parser.format = func(spec, flag byte) error { switch spec { case 'A': dst = append(dst, t.Weekday().String()...) return nil case 'a': dst = append(dst, t.Weekday().String()[:3]...) return nil case 'B': dst = append(dst, t.Month().String()...) return nil case 'b', 'h': dst = append(dst, t.Month().String()[:3]...) return nil case 'm': dst = appendInt2(dst, int(t.Month()), flag) return nil case 'd': dst = appendInt2(dst, int(t.Day()), flag) return nil case 'e': dst = appendInt2(dst, int(t.Day()), ' ') return nil case 'I': dst = append12Hour(dst, t, flag) return nil case 'l': dst = append12Hour(dst, t, ' ') return nil case 'H': dst = appendInt2(dst, t.Hour(), flag) return nil case 'k': dst = appendInt2(dst, t.Hour(), ' ') return nil case 'M': dst = appendInt2(dst, t.Minute(), flag) return nil case 'S': dst = appendInt2(dst, t.Second(), flag) return nil case 'L': dst = append(dst, t.Format(".000")[1:]...) return nil case 'f': dst = append(dst, t.Format(".000000")[1:]...) return nil case 'N': dst = append(dst, t.Format(".000000000")[1:]...) return nil case 'y': dst = t.AppendFormat(dst, "06") return nil case 'Y': dst = t.AppendFormat(dst, "2006") return nil case 'C': dst = t.AppendFormat(dst, "2006") dst = dst[:len(dst)-2] return nil case 'U': dst = appendWeekNumber(dst, t, flag, true) return nil case 'W': dst = appendWeekNumber(dst, t, flag, false) return nil case 'V': _, w := t.ISOWeek() dst = appendInt2(dst, w, flag) return nil case 'g': y, _ := t.ISOWeek() dst = year(y).AppendFormat(dst, "06") return nil case 'G': y, _ := t.ISOWeek() dst = year(y).AppendFormat(dst, "2006") return nil case 's': dst = strconv.AppendInt(dst, t.Unix(), 10) return nil case 'Q': dst = strconv.AppendInt(dst, t.UnixMilli(), 10) return nil case 'w': w := t.Weekday() dst = appendInt1(dst, int(w)) return nil case 'u': if w := t.Weekday(); w == 0 { dst = append(dst, '7') } else { dst = appendInt1(dst, int(w)) } return nil case 'j': if flag == '-' { dst = strconv.AppendInt(dst, int64(t.YearDay()), 10) } else { dst = t.AppendFormat(dst, "002") } return nil } if layout := goLayout(spec, flag, false); layout != "" { dst = t.AppendFormat(dst, layout) return nil } dst = append(dst, '%') if flag != 0 { dst = append(dst, flag) } dst = append(dst, spec) return nil } parser.parse(fmt) return dst } // Parse converts a textual representation of time to the time value it represents // according to the strptime format specification. func Parse(fmt, value string) (time.Time, error) { pattern, err := layout(fmt, true) if err != nil { return time.Time{}, err } return time.Parse(pattern, value) } // Layout converts a strftime format specification // to a Go time pattern specification. func Layout(fmt string) (string, error) { return layout(fmt, false) } func layout(fmt string, parsing bool) (string, error) { dst := buffer(fmt) var parser parser parser.literal = func(b byte) error { if '0' <= b && b <= '9' { return literalErr(b) } dst = append(dst, b) if b == 'M' || b == 'T' || b == 'm' || b == 'n' { switch { case bytes.HasSuffix(dst, []byte("Jan")): return literalErr("Jan") case bytes.HasSuffix(dst, []byte("Mon")): return literalErr("Mon") case bytes.HasSuffix(dst, []byte("MST")): return literalErr("MST") case bytes.HasSuffix(dst, []byte("PM")): return literalErr("PM") case bytes.HasSuffix(dst, []byte("pm")): return literalErr("pm") } } return nil } parser.format = func(spec, flag byte) error { if layout := goLayout(spec, flag, parsing); layout != "" { dst = append(dst, layout...) return nil } switch spec { default: return formatError{} case 'L', 'f', 'N': if bytes.HasSuffix(dst, []byte(".")) || bytes.HasSuffix(dst, []byte(",")) { switch spec { default: dst = append(dst, "000"...) case 'f': dst = append(dst, "000000"...) case 'N': dst = append(dst, "000000000"...) } return nil } return formatError{message: "must follow '.' or ','"} } } if err := parser.parse(fmt); err != nil { return "", err } return string(dst), nil } // UTS35 converts a strftime format specification // to a Unicode Technical Standard #35 Date Format Pattern. func UTS35(fmt string) (string, error) { const quote = '\'' var quoted bool dst := buffer(fmt) var parser parser parser.literal = func(b byte) error { if b == quote { dst = append(dst, quote, quote) return nil } if !quoted && ('a' <= b && b <= 'z' || 'A' <= b && b <= 'Z') { dst = append(dst, quote) quoted = true } dst = append(dst, b) return nil } parser.format = func(spec, flag byte) error { if quoted { dst = append(dst, quote) quoted = false } if pattern := uts35Pattern(spec, flag); pattern != "" { dst = append(dst, pattern...) return nil } return formatError{} } if err := parser.parse(fmt); err != nil { return "", err } if quoted { dst = append(dst, quote) } return string(dst), nil } func buffer(format string) (buf []byte) { const bufSize = 64 max := len(format) + 10 if max < bufSize { var b [bufSize]byte buf = b[:0] } else { buf = make([]byte, 0, max) } return } func year(y int) time.Time { return time.Date(y, time.January, 1, 0, 0, 0, 0, time.UTC) } func appendWeekNumber(dst []byte, t time.Time, flag byte, sunday bool) []byte { offset := int(t.Weekday()) if sunday { offset = 6 - offset } else if offset != 0 { offset = 7 - offset } return appendInt2(dst, (t.YearDay()+offset)/7, flag) } func append12Hour(dst []byte, t time.Time, flag byte) []byte { h := t.Hour() if h == 0 { h = 12 } else if h > 12 { h -= 12 } return appendInt2(dst, h, flag) } func appendInt1(dst []byte, i int) []byte { return append(dst, byte('0'+i)) } func appendInt2(dst []byte, i int, flag byte) []byte { if flag == 0 || i >= 10 { return append(dst, smallsString[i*2:i*2+2]...) } if flag == ' ' { dst = append(dst, flag) } return appendInt1(dst, i) } const smallsString = "" + "00010203040506070809" + "10111213141516171819" + "20212223242526272829" + "30313233343536373839" + "40414243444546474849" + "50515253545556575859" + "60616263646566676869" + "70717273747576777879" + "80818283848586878889" + "90919293949596979899"
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/ncruces/go-strftime/pkg.go
vendor/github.com/ncruces/go-strftime/pkg.go
/* Package strftime provides strftime/strptime compatible time formatting and parsing. The following specifiers are available: Date (Year, Month, Day): %Y - Year with century (can be negative, 4 digits at least) -0001, 0000, 1995, 2009, 14292, etc. %C - year / 100 (round down, 20 in 2009) %y - year % 100 (00..99) %m - Month of the year, zero-padded (01..12) %-m no-padded (1..12) %B - Full month name (January) %b - Abbreviated month name (Jan) %h - Equivalent to %b %d - Day of the month, zero-padded (01..31) %-d no-padded (1..31) %e - Day of the month, blank-padded ( 1..31) %j - Day of the year (001..366) %-j no-padded (1..366) Time (Hour, Minute, Second, Subsecond): %H - Hour of the day, 24-hour clock, zero-padded (00..23) %-H no-padded (0..23) %k - Hour of the day, 24-hour clock, blank-padded ( 0..23) %I - Hour of the day, 12-hour clock, zero-padded (01..12) %-I no-padded (1..12) %l - Hour of the day, 12-hour clock, blank-padded ( 1..12) %P - Meridian indicator, lowercase (am or pm) %p - Meridian indicator, uppercase (AM or PM) %M - Minute of the hour (00..59) %-M no-padded (0..59) %S - Second of the minute (00..60) %-S no-padded (0..60) %L - Millisecond of the second (000..999) %f - Microsecond of the second (000000..999999) %N - Nanosecond of the second (000000000..999999999) Time zone: %z - Time zone as hour and minute offset from UTC (e.g. +0900) %:z - hour and minute offset from UTC with a colon (e.g. +09:00) %Z - Time zone abbreviation (e.g. MST) Weekday: %A - Full weekday name (Sunday) %a - Abbreviated weekday name (Sun) %u - Day of the week (Monday is 1, 1..7) %w - Day of the week (Sunday is 0, 0..6) ISO 8601 week-based year and week number: Week 1 of YYYY starts with a Monday and includes YYYY-01-04. The days in the year before the first week are in the last week of the previous year. %G - Week-based year %g - Last 2 digits of the week-based year (00..99) %V - Week number of the week-based year (01..53) %-V no-padded (1..53) Week number: Week 1 of YYYY starts with a Sunday or Monday (according to %U or %W). The days in the year before the first week are in week 0. %U - Week number of the year. The week starts with Sunday. (00..53) %-U no-padded (0..53) %W - Week number of the year. The week starts with Monday. (00..53) %-W no-padded (0..53) Seconds since the Unix Epoch: %s - Number of seconds since 1970-01-01 00:00:00 UTC. %Q - Number of milliseconds since 1970-01-01 00:00:00 UTC. Literal string: %n - Newline character (\n) %t - Tab character (\t) %% - Literal % character Combination: %c - date and time (%a %b %e %T %Y) %D - Date (%m/%d/%y) %F - ISO 8601 date format (%Y-%m-%d) %v - VMS date (%e-%b-%Y) %x - Same as %D %X - Same as %T %r - 12-hour time (%I:%M:%S %p) %R - 24-hour time (%H:%M) %T - 24-hour time (%H:%M:%S) %+ - date(1) (%a %b %e %H:%M:%S %Z %Y) The modifiers ``E'' and ``O'' are ignored. */ package strftime
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/ncruces/go-strftime/specifiers.go
vendor/github.com/ncruces/go-strftime/specifiers.go
package strftime import "strings" // https://strftime.org/ func goLayout(spec, flag byte, parsing bool) string { switch spec { default: return "" case 'B': return "January" case 'b', 'h': return "Jan" case 'm': if flag == '-' || parsing { return "1" } return "01" case 'A': return "Monday" case 'a': return "Mon" case 'e': return "_2" case 'd': if flag == '-' || parsing { return "2" } return "02" case 'j': if flag == '-' { if parsing { return "__2" } return "" } return "002" case 'I': if flag == '-' || parsing { return "3" } return "03" case 'H': if flag == '-' && !parsing { return "" } return "15" case 'M': if flag == '-' || parsing { return "4" } return "04" case 'S': if flag == '-' || parsing { return "5" } return "05" case 'y': return "06" case 'Y': return "2006" case 'p': return "PM" case 'P': return "pm" case 'Z': return "MST" case 'z': if flag == ':' { if parsing { return "Z07:00" } return "-07:00" } if parsing { return "Z0700" } return "-0700" case '+': if parsing { return "Mon Jan _2 15:4:5 MST 2006" } return "Mon Jan _2 15:04:05 MST 2006" case 'c': if parsing { return "Mon Jan _2 15:4:5 2006" } return "Mon Jan _2 15:04:05 2006" case 'v': return "_2-Jan-2006" case 'F': if parsing { return "2006-1-2" } return "2006-01-02" case 'D', 'x': if parsing { return "1/2/06" } return "01/02/06" case 'r': if parsing { return "3:4:5 PM" } return "03:04:05 PM" case 'T', 'X': if parsing { return "15:4:5" } return "15:04:05" case 'R': if parsing { return "15:4" } return "15:04" case '%': return "%" case 't': return "\t" case 'n': return "\n" } } // https://nsdateformatter.com/ func uts35Pattern(spec, flag byte) string { switch spec { default: return "" case 'B': return "MMMM" case 'b', 'h': return "MMM" case 'm': if flag == '-' { return "M" } return "MM" case 'A': return "EEEE" case 'a': return "E" case 'd': if flag == '-' { return "d" } return "dd" case 'j': if flag == '-' { return "D" } return "DDD" case 'I': if flag == '-' { return "h" } return "hh" case 'H': if flag == '-' { return "H" } return "HH" case 'M': if flag == '-' { return "m" } return "mm" case 'S': if flag == '-' { return "s" } return "ss" case 'y': return "yy" case 'Y': return "yyyy" case 'g': return "YY" case 'G': return "YYYY" case 'V': if flag == '-' { return "w" } return "ww" case 'p': return "a" case 'Z': return "zzz" case 'z': if flag == ':' { return "xxx" } return "xx" case 'L': return "SSS" case 'f': return "SSSSSS" case 'N': return "SSSSSSSSS" case '+': return "E MMM d HH:mm:ss zzz yyyy" case 'c': return "E MMM d HH:mm:ss yyyy" case 'v': return "d-MMM-yyyy" case 'F': return "yyyy-MM-dd" case 'D', 'x': return "MM/dd/yy" case 'r': return "hh:mm:ss a" case 'T', 'X': return "HH:mm:ss" case 'R': return "HH:mm" case '%': return "%" case 't': return "\t" case 'n': return "\n" } } // http://man.he.net/man3/strftime func okModifier(mod, spec byte) bool { if mod == 'E' { return strings.Contains("cCxXyY", string(spec)) } if mod == 'O' { return strings.Contains("deHImMSuUVwWy", string(spec)) } return false }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/apiserver/pkg/storage/names/generate.go
vendor/k8s.io/apiserver/pkg/storage/names/generate.go
/* Copyright 2014 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 names import ( "fmt" utilrand "k8s.io/apimachinery/pkg/util/rand" ) // NameGenerator generates names for objects. Some backends may have more information // available to guide selection of new names and this interface hides those details. type NameGenerator interface { // GenerateName generates a valid name from the base name, adding a random suffix to // the base. If base is valid, the returned name must also be valid. The generator is // responsible for knowing the maximum valid name length. GenerateName(base string) string } // simpleNameGenerator generates random names. type simpleNameGenerator struct{} // SimpleNameGenerator is a generator that returns the name plus a random suffix of five alphanumerics // when a name is requested. The string is guaranteed to not exceed the length of a standard Kubernetes // name (63 characters) var SimpleNameGenerator NameGenerator = simpleNameGenerator{} const ( // TODO: make this flexible for non-core resources with alternate naming rules. maxNameLength = 63 randomLength = 5 MaxGeneratedNameLength = maxNameLength - randomLength ) func (simpleNameGenerator) GenerateName(base string) string { if len(base) > MaxGeneratedNameLength { base = base[:MaxGeneratedNameLength] } return fmt.Sprintf("%s%s", base, utilrand.String(randomLength)) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/kube-openapi/pkg/validation/spec/ref.go
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/vendor/k8s.io/kube-openapi/pkg/validation/spec/items.go
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/vendor/k8s.io/kube-openapi/pkg/validation/spec/response.go
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/vendor/k8s.io/kube-openapi/pkg/validation/spec/contact_info.go
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/vendor/k8s.io/kube-openapi/pkg/validation/spec/path_item.go
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/vendor/k8s.io/kube-openapi/pkg/validation/spec/gnostic.go
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/vendor/k8s.io/kube-openapi/pkg/validation/spec/header.go
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/vendor/k8s.io/kube-openapi/pkg/validation/spec/tag.go
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/vendor/k8s.io/kube-openapi/pkg/validation/spec/paths.go
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/vendor/k8s.io/kube-openapi/pkg/validation/spec/swagger.go
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/vendor/k8s.io/kube-openapi/pkg/validation/spec/responses.go
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/vendor/k8s.io/kube-openapi/pkg/validation/spec/license.go
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/vendor/k8s.io/kube-openapi/pkg/validation/spec/security_scheme.go
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/vendor/k8s.io/kube-openapi/pkg/validation/spec/operation.go
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/vendor/k8s.io/kube-openapi/pkg/validation/spec/parameter.go
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/vendor/k8s.io/kube-openapi/pkg/validation/spec/info.go
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/vendor/k8s.io/kube-openapi/pkg/validation/spec/schema.go
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/vendor/k8s.io/kube-openapi/pkg/validation/spec/external_docs.go
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/vendor/k8s.io/kube-openapi/pkg/util/proto/document.go
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/vendor/k8s.io/kube-openapi/pkg/util/proto/openapi.go
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/vendor/k8s.io/kube-openapi/pkg/util/proto/doc.go
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/vendor/k8s.io/kube-openapi/pkg/util/proto/document_v3.go
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/vendor/k8s.io/kube-openapi/pkg/spec3/fuzz.go
vendor/k8s.io/kube-openapi/pkg/spec3/fuzz.go
package spec3 import ( "math/rand" "strings" fuzz "github.com/google/gofuzz" "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 fuzz.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 fuzz.Continue) { c.FuzzNoCustom(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 fuzz.Continue) { switch c.Intn(3) { case 0: *r = nil case 1: n := c.RandString() + "x" *r = n case 2: n := c.Float64() *r = n } }, func(v **spec.Info, c fuzz.Continue) { // Info is never nil *v = &spec.Info{} c.FuzzNoCustom(*v) (*v).Title = c.RandString() + "x" }, func(v *Paths, c fuzz.Continue) { c.Fuzz(&v.VendorExtensible) num := c.Intn(5) if num > 0 { v.Paths = make(map[string]*Path) } for i := 0; i < num; i++ { val := Path{} c.Fuzz(&val) v.Paths["/"+c.RandString()] = &val } }, func(v *SecurityScheme, c fuzz.Continue) { if c.Intn(refChance) == 0 { c.Fuzz(&v.Refable) return } switch c.Intn(4) { case 0: v.Type = "apiKey" v.Name = c.RandString() + "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.RandString() + "x" v.Flows["implicit"] = &flow flow.Scopes = make(map[string]string) flow.Scopes["foo"] = "bar" case 3: v.Type = "openIdConnect" v.OpenIdConnectUrl = "https://" + c.RandString() } v.Scheme = "basic" }, func(v *spec.Ref, c fuzz.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 fuzz.Continue) { if c.Intn(refChance) == 0 { c.Fuzz(&v.Refable) return } c.Fuzz(&v.ParameterProps) c.Fuzz(&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 fuzz.Continue) { if c.Intn(refChance) == 0 { c.Fuzz(&v.Refable) return } c.Fuzz(&v.RequestBodyProps) c.Fuzz(&v.VendorExtensible) }, func(v *Header, c fuzz.Continue) { if c.Intn(refChance) == 0 { c.Fuzz(&v.Refable) return } c.Fuzz(&v.HeaderProps) c.Fuzz(&v.VendorExtensible) }, func(v *ResponsesProps, c fuzz.Continue) { c.Fuzz(&v.Default) n := c.Intn(5) for i := 0; i < n; i++ { r2 := Response{} c.Fuzz(&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 fuzz.Continue) { if c.Intn(refChance) == 0 { c.Fuzz(&v.Refable) return } c.Fuzz(&v.ResponseProps) c.Fuzz(&v.VendorExtensible) }, func(v *Operation, c fuzz.Continue) { c.FuzzNoCustom(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 fuzz.Continue) { numChildren := c.Intn(5) for i := 0; i < numChildren; i++ { if *v == nil { *v = spec.Extensions{} } (*v)["x-"+c.RandString()] = c.RandString() } }, func(v *spec.ExternalDocumentation, c fuzz.Continue) { c.Fuzz(&v.Description) v.URL = "https://" + randAlphanumString() }, func(v *spec.SchemaURL, c fuzz.Continue) { *v = spec.SchemaURL("https://" + randAlphanumString()) }, func(v *spec.SchemaOrBool, c fuzz.Continue) { *v = spec.SchemaOrBool{} if c.RandBool() { v.Allows = c.RandBool() } else { v.Schema = &spec.Schema{} v.Allows = true c.Fuzz(&v.Schema) } }, func(v *spec.SchemaOrArray, c fuzz.Continue) { *v = spec.SchemaOrArray{} if c.RandBool() { schema := spec.Schema{} c.Fuzz(&schema) v.Schema = &schema } else { v.Schemas = []spec.Schema{} numChildren := c.Intn(5) for i := 0; i < numChildren; i++ { schema := spec.Schema{} c.Fuzz(&schema) v.Schemas = append(v.Schemas, schema) } } }, func(v *spec.SchemaOrStringArray, c fuzz.Continue) { if c.RandBool() { *v = spec.SchemaOrStringArray{} if c.RandBool() { c.Fuzz(&v.Property) } else { c.Fuzz(&v.Schema) } } }, func(v *spec.Schema, c fuzz.Continue) { if c.Intn(refChance) == 0 { c.Fuzz(&v.Ref) return } if c.RandBool() { // file schema c.Fuzz(&v.Default) c.Fuzz(&v.Description) c.Fuzz(&v.Example) c.Fuzz(&v.ExternalDocs) c.Fuzz(&v.Format) c.Fuzz(&v.ReadOnly) c.Fuzz(&v.Required) c.Fuzz(&v.Title) v.Type = spec.StringOrArray{"file"} } else { // normal schema c.Fuzz(&v.SchemaProps) c.Fuzz(&v.SwaggerSchemaProps) c.Fuzz(&v.VendorExtensible) c.Fuzz(&v.ExtraProps) } }, }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/kube-openapi/pkg/spec3/request_body.go
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/vendor/k8s.io/kube-openapi/pkg/spec3/external_documentation.go
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/vendor/k8s.io/kube-openapi/pkg/spec3/component.go
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/vendor/k8s.io/kube-openapi/pkg/spec3/path.go
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/vendor/k8s.io/kube-openapi/pkg/spec3/response.go
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/vendor/k8s.io/kube-openapi/pkg/spec3/example.go
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/vendor/k8s.io/kube-openapi/pkg/spec3/spec.go
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/vendor/k8s.io/kube-openapi/pkg/spec3/header.go
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/vendor/k8s.io/kube-openapi/pkg/spec3/media_type.go
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/vendor/k8s.io/kube-openapi/pkg/spec3/server.go
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/vendor/k8s.io/kube-openapi/pkg/spec3/security_scheme.go
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/vendor/k8s.io/kube-openapi/pkg/spec3/operation.go
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/vendor/k8s.io/kube-openapi/pkg/spec3/encoding.go
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/vendor/k8s.io/kube-openapi/pkg/spec3/parameter.go
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/vendor/k8s.io/kube-openapi/pkg/cached/cache.go
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/vendor/k8s.io/kube-openapi/pkg/schemaconv/proto_models.go
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/vendor/k8s.io/kube-openapi/pkg/schemaconv/openapi.go
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/vendor/k8s.io/kube-openapi/pkg/schemaconv/smd.go
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/vendor/k8s.io/kube-openapi/pkg/common/interfaces.go
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/vendor/k8s.io/kube-openapi/pkg/common/doc.go
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/vendor/k8s.io/kube-openapi/pkg/common/common.go
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/vendor/k8s.io/kube-openapi/pkg/internal/flags.go
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/vendor/k8s.io/kube-openapi/pkg/internal/serialization.go
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/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/fold.go
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/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_default.go
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/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal.go
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/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/errors.go
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/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_methods.go
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
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/token.go
vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/token.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 ( "math" "strconv" ) // NOTE: Token is analogous to v1 json.Token. const ( maxInt64 = math.MaxInt64 minInt64 = math.MinInt64 maxUint64 = math.MaxUint64 minUint64 = 0 // for consistency and readability purposes invalidTokenPanic = "invalid json.Token; it has been voided by a subsequent json.Decoder call" ) // Token represents a lexical JSON token, which may be one of the following: // - a JSON literal (i.e., null, true, or false) // - a JSON string (e.g., "hello, world!") // - a JSON number (e.g., 123.456) // - a start or end delimiter for a JSON object (i.e., { or } ) // - a start or end delimiter for a JSON array (i.e., [ or ] ) // // A Token cannot represent entire array or object values, while a RawValue can. // There is no Token to represent commas and colons since // these structural tokens can be inferred from the surrounding context. type Token struct { nonComparable // Tokens can exist in either a "raw" or an "exact" form. // Tokens produced by the Decoder are in the "raw" form. // Tokens returned by constructors are usually in the "exact" form. // The Encoder accepts Tokens in either the "raw" or "exact" form. // // The following chart shows the possible values for each Token type: // ╔═════════════════╦════════════╤════════════╤════════════╗ // ║ Token type ║ raw field │ str field │ num field ║ // ╠═════════════════╬════════════╪════════════╪════════════╣ // ║ null (raw) ║ "null" │ "" │ 0 ║ // ║ false (raw) ║ "false" │ "" │ 0 ║ // ║ true (raw) ║ "true" │ "" │ 0 ║ // ║ string (raw) ║ non-empty │ "" │ offset ║ // ║ string (string) ║ nil │ non-empty │ 0 ║ // ║ number (raw) ║ non-empty │ "" │ offset ║ // ║ number (float) ║ nil │ "f" │ non-zero ║ // ║ number (int64) ║ nil │ "i" │ non-zero ║ // ║ number (uint64) ║ nil │ "u" │ non-zero ║ // ║ object (delim) ║ "{" or "}" │ "" │ 0 ║ // ║ array (delim) ║ "[" or "]" │ "" │ 0 ║ // ╚═════════════════╩════════════╧════════════╧════════════╝ // // Notes: // - For tokens stored in "raw" form, the num field contains the // absolute offset determined by raw.previousOffsetStart(). // The buffer itself is stored in raw.previousBuffer(). // - JSON literals and structural characters are always in the "raw" form. // - JSON strings and numbers can be in either "raw" or "exact" forms. // - The exact zero value of JSON strings and numbers in the "exact" forms // have ambiguous representation. Thus, they are always represented // in the "raw" form. // raw contains a reference to the raw decode buffer. // If non-nil, then its value takes precedence over str and num. // It is only valid if num == raw.previousOffsetStart(). raw *decodeBuffer // str is the unescaped JSON string if num is zero. // Otherwise, it is "f", "i", or "u" if num should be interpreted // as a float64, int64, or uint64, respectively. str string // num is a float64, int64, or uint64 stored as a uint64 value. // It is non-zero for any JSON number in the "exact" form. num uint64 } // TODO: Does representing 1-byte delimiters as *decodeBuffer cause performance issues? var ( Null Token = rawToken("null") False Token = rawToken("false") True Token = rawToken("true") ObjectStart Token = rawToken("{") ObjectEnd Token = rawToken("}") ArrayStart Token = rawToken("[") ArrayEnd Token = rawToken("]") zeroString Token = rawToken(`""`) zeroNumber Token = rawToken(`0`) nanString Token = String("NaN") pinfString Token = String("Infinity") ninfString Token = String("-Infinity") ) func rawToken(s string) Token { return Token{raw: &decodeBuffer{buf: []byte(s), prevStart: 0, prevEnd: len(s)}} } // Bool constructs a Token representing a JSON boolean. func Bool(b bool) Token { if b { return True } return False } // String constructs a Token representing a JSON string. // The provided string should contain valid UTF-8, otherwise invalid characters // may be mangled as the Unicode replacement character. func String(s string) Token { if len(s) == 0 { return zeroString } return Token{str: s} } // Float constructs a Token representing a JSON number. // The values NaN, +Inf, and -Inf will be represented // as a JSON string with the values "NaN", "Infinity", and "-Infinity". func Float(n float64) Token { switch { case math.Float64bits(n) == 0: return zeroNumber case math.IsNaN(n): return nanString case math.IsInf(n, +1): return pinfString case math.IsInf(n, -1): return ninfString } return Token{str: "f", num: math.Float64bits(n)} } // Int constructs a Token representing a JSON number from an int64. func Int(n int64) Token { if n == 0 { return zeroNumber } return Token{str: "i", num: uint64(n)} } // Uint constructs a Token representing a JSON number from a uint64. func Uint(n uint64) Token { if n == 0 { return zeroNumber } return Token{str: "u", num: uint64(n)} } // Clone makes a copy of the Token such that its value remains valid // even after a subsequent Decoder.Read call. func (t Token) Clone() Token { // TODO: Allow caller to avoid any allocations? if raw := t.raw; raw != nil { // Avoid copying globals. if t.raw.prevStart == 0 { switch t.raw { case Null.raw: return Null case False.raw: return False case True.raw: return True case ObjectStart.raw: return ObjectStart case ObjectEnd.raw: return ObjectEnd case ArrayStart.raw: return ArrayStart case ArrayEnd.raw: return ArrayEnd } } if uint64(raw.previousOffsetStart()) != t.num { panic(invalidTokenPanic) } // TODO(https://go.dev/issue/45038): Use bytes.Clone. buf := append([]byte(nil), raw.previousBuffer()...) return Token{raw: &decodeBuffer{buf: buf, prevStart: 0, prevEnd: len(buf)}} } return t } // Bool returns the value for a JSON boolean. // It panics if the token kind is not a JSON boolean. func (t Token) Bool() bool { switch t.raw { case True.raw: return true case False.raw: return false default: panic("invalid JSON token kind: " + t.Kind().String()) } } // appendString appends a JSON string to dst and returns it. // It panics if t is not a JSON string. func (t Token) appendString(dst []byte, validateUTF8, preserveRaw bool, escapeRune func(rune) bool) ([]byte, error) { if raw := t.raw; raw != nil { // Handle raw string value. buf := raw.previousBuffer() if Kind(buf[0]) == '"' { if escapeRune == nil && consumeSimpleString(buf) == len(buf) { return append(dst, buf...), nil } dst, _, err := reformatString(dst, buf, validateUTF8, preserveRaw, escapeRune) return dst, err } } else if len(t.str) != 0 && t.num == 0 { // Handle exact string value. return appendString(dst, t.str, validateUTF8, escapeRune) } panic("invalid JSON token kind: " + t.Kind().String()) } // String returns the unescaped string value for a JSON string. // For other JSON kinds, this returns the raw JSON representation. func (t Token) String() string { // This is inlinable to take advantage of "function outlining". // This avoids an allocation for the string(b) conversion // if the caller does not use the string in an escaping manner. // See https://blog.filippo.io/efficient-go-apis-with-the-inliner/ s, b := t.string() if len(b) > 0 { return string(b) } return s } func (t Token) string() (string, []byte) { if raw := t.raw; raw != nil { if uint64(raw.previousOffsetStart()) != t.num { panic(invalidTokenPanic) } buf := raw.previousBuffer() if buf[0] == '"' { // TODO: Preserve valueFlags in Token? isVerbatim := consumeSimpleString(buf) == len(buf) return "", unescapeStringMayCopy(buf, isVerbatim) } // Handle tokens that are not JSON strings for fmt.Stringer. return "", buf } if len(t.str) != 0 && t.num == 0 { return t.str, nil } // Handle tokens that are not JSON strings for fmt.Stringer. if t.num > 0 { switch t.str[0] { case 'f': return string(appendNumber(nil, math.Float64frombits(t.num), 64)), nil case 'i': return strconv.FormatInt(int64(t.num), 10), nil case 'u': return strconv.FormatUint(uint64(t.num), 10), nil } } return "<invalid json.Token>", nil } // appendNumber appends a JSON number to dst and returns it. // It panics if t is not a JSON number. func (t Token) appendNumber(dst []byte, canonicalize bool) ([]byte, error) { if raw := t.raw; raw != nil { // Handle raw number value. buf := raw.previousBuffer() if Kind(buf[0]).normalize() == '0' { if !canonicalize { return append(dst, buf...), nil } dst, _, err := reformatNumber(dst, buf, canonicalize) return dst, err } } else if t.num != 0 { // Handle exact number value. switch t.str[0] { case 'f': return appendNumber(dst, math.Float64frombits(t.num), 64), nil case 'i': return strconv.AppendInt(dst, int64(t.num), 10), nil case 'u': return strconv.AppendUint(dst, uint64(t.num), 10), nil } } panic("invalid JSON token kind: " + t.Kind().String()) } // Float returns the floating-point value for a JSON number. // It returns a NaN, +Inf, or -Inf value for any JSON string // with the values "NaN", "Infinity", or "-Infinity". // It panics for all other cases. func (t Token) Float() float64 { if raw := t.raw; raw != nil { // Handle raw number value. if uint64(raw.previousOffsetStart()) != t.num { panic(invalidTokenPanic) } buf := raw.previousBuffer() if Kind(buf[0]).normalize() == '0' { fv, _ := parseFloat(buf, 64) return fv } } else if t.num != 0 { // Handle exact number value. switch t.str[0] { case 'f': return math.Float64frombits(t.num) case 'i': return float64(int64(t.num)) case 'u': return float64(uint64(t.num)) } } // Handle string values with "NaN", "Infinity", or "-Infinity". if t.Kind() == '"' { switch t.String() { case "NaN": return math.NaN() case "Infinity": return math.Inf(+1) case "-Infinity": return math.Inf(-1) } } panic("invalid JSON token kind: " + t.Kind().String()) } // Int returns the signed integer value for a JSON number. // The fractional component of any number is ignored (truncation toward zero). // Any number beyond the representation of an int64 will be saturated // to the closest representable value. // It panics if the token kind is not a JSON number. func (t Token) Int() int64 { if raw := t.raw; raw != nil { // Handle raw integer value. if uint64(raw.previousOffsetStart()) != t.num { panic(invalidTokenPanic) } neg := false buf := raw.previousBuffer() if len(buf) > 0 && buf[0] == '-' { neg, buf = true, buf[1:] } if numAbs, ok := parseDecUint(buf); ok { if neg { if numAbs > -minInt64 { return minInt64 } return -1 * int64(numAbs) } else { if numAbs > +maxInt64 { return maxInt64 } return +1 * int64(numAbs) } } } else if t.num != 0 { // Handle exact integer value. switch t.str[0] { case 'i': return int64(t.num) case 'u': if t.num > maxInt64 { return maxInt64 } return int64(t.num) } } // Handle JSON number that is a floating-point value. if t.Kind() == '0' { switch fv := t.Float(); { case fv >= maxInt64: return maxInt64 case fv <= minInt64: return minInt64 default: return int64(fv) // truncation toward zero } } panic("invalid JSON token kind: " + t.Kind().String()) } // Uint returns the unsigned integer value for a JSON number. // The fractional component of any number is ignored (truncation toward zero). // Any number beyond the representation of an uint64 will be saturated // to the closest representable value. // It panics if the token kind is not a JSON number. func (t Token) Uint() uint64 { // NOTE: This accessor returns 0 for any negative JSON number, // which might be surprising, but is at least consistent with the behavior // of saturating out-of-bounds numbers to the closest representable number. if raw := t.raw; raw != nil { // Handle raw integer value. if uint64(raw.previousOffsetStart()) != t.num { panic(invalidTokenPanic) } neg := false buf := raw.previousBuffer() if len(buf) > 0 && buf[0] == '-' { neg, buf = true, buf[1:] } if num, ok := parseDecUint(buf); ok { if neg { return minUint64 } return num } } else if t.num != 0 { // Handle exact integer value. switch t.str[0] { case 'u': return t.num case 'i': if int64(t.num) < minUint64 { return minUint64 } return uint64(int64(t.num)) } } // Handle JSON number that is a floating-point value. if t.Kind() == '0' { switch fv := t.Float(); { case fv >= maxUint64: return maxUint64 case fv <= minUint64: return minUint64 default: return uint64(fv) // truncation toward zero } } panic("invalid JSON token kind: " + t.Kind().String()) } // Kind returns the token kind. func (t Token) Kind() Kind { switch { case t.raw != nil: raw := t.raw if uint64(raw.previousOffsetStart()) != t.num { panic(invalidTokenPanic) } return Kind(t.raw.buf[raw.prevStart]).normalize() case t.num != 0: return '0' case len(t.str) != 0: return '"' default: return invalidKind } } // Kind represents each possible JSON token kind with a single byte, // which is conveniently the first byte of that kind's grammar // with the restriction that numbers always be represented with '0': // // - 'n': null // - 'f': false // - 't': true // - '"': string // - '0': number // - '{': object start // - '}': object end // - '[': array start // - ']': array end // // An invalid kind is usually represented using 0, // but may be non-zero due to invalid JSON data. type Kind byte const invalidKind Kind = 0 // String prints the kind in a humanly readable fashion. func (k Kind) String() string { switch k { case 'n': return "null" case 'f': return "false" case 't': return "true" case '"': return "string" case '0': return "number" case '{': return "{" case '}': return "}" case '[': return "[" case ']': return "]" default: return "<invalid json.Kind: " + quoteRune([]byte{byte(k)}) + ">" } } // normalize coalesces all possible starting characters of a number as just '0'. func (k Kind) normalize() Kind { if k == '-' || ('0' <= k && k <= '9') { return '0' } return k }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_any.go
vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_any.go
// Copyright 2022 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 "reflect" // This files contains an optimized marshal and unmarshal implementation // for the any type. This type is often used when the Go program has // no knowledge of the JSON schema. This is a common enough occurrence // to justify the complexity of adding logic for this. func marshalValueAny(mo MarshalOptions, enc *Encoder, val any) error { switch val := val.(type) { case nil: return enc.WriteToken(Null) case bool: return enc.WriteToken(Bool(val)) case string: return enc.WriteToken(String(val)) case float64: return enc.WriteToken(Float(val)) case map[string]any: return marshalObjectAny(mo, enc, val) case []any: return marshalArrayAny(mo, enc, val) default: v := newAddressableValue(reflect.TypeOf(val)) v.Set(reflect.ValueOf(val)) marshal := lookupArshaler(v.Type()).marshal if mo.Marshalers != nil { marshal, _ = mo.Marshalers.lookup(marshal, v.Type()) } return marshal(mo, enc, v) } } func unmarshalValueAny(uo UnmarshalOptions, dec *Decoder) (any, error) { switch k := dec.PeekKind(); k { case '{': return unmarshalObjectAny(uo, dec) case '[': return unmarshalArrayAny(uo, dec) default: var flags valueFlags val, err := dec.readValue(&flags) if err != nil { return nil, err } switch val.Kind() { case 'n': return nil, nil case 'f': return false, nil case 't': return true, nil case '"': val = unescapeStringMayCopy(val, flags.isVerbatim()) if dec.stringCache == nil { dec.stringCache = new(stringCache) } return dec.stringCache.make(val), nil case '0': fv, _ := parseFloat(val, 64) // ignore error since readValue guarantees val is valid return fv, nil default: panic("BUG: invalid kind: " + k.String()) } } } func marshalObjectAny(mo MarshalOptions, enc *Encoder, obj map[string]any) error { // Check for cycles. if enc.tokens.depth() > startDetectingCyclesAfter { v := reflect.ValueOf(obj) if err := enc.seenPointers.visit(v); err != nil { return err } defer enc.seenPointers.leave(v) } // Optimize for marshaling an empty map without any preceding whitespace. if len(obj) == 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 } if err := enc.WriteToken(ObjectStart); err != nil { return err } // A Go map guarantees that each entry has a unique key // The only possibility of duplicates is due to invalid UTF-8. if !enc.options.AllowInvalidUTF8 { enc.tokens.last.disableNamespace() } if !mo.Deterministic || len(obj) <= 1 { for name, val := range obj { if err := enc.WriteToken(String(name)); err != nil { return err } if err := marshalValueAny(mo, enc, val); err != nil { return err } } } else { names := getStrings(len(obj)) var i int for name := range obj { (*names)[i] = name i++ } names.Sort() for _, name := range *names { if err := enc.WriteToken(String(name)); err != nil { return err } if err := marshalValueAny(mo, enc, obj[name]); err != nil { return err } } putStrings(names) } if err := enc.WriteToken(ObjectEnd); err != nil { return err } return nil } func unmarshalObjectAny(uo UnmarshalOptions, dec *Decoder) (map[string]any, error) { tok, err := dec.ReadToken() if err != nil { return nil, err } k := tok.Kind() switch k { case 'n': return nil, nil case '{': obj := make(map[string]any) // A Go map guarantees that each entry has a unique key // The only possibility of duplicates is due to invalid UTF-8. if !dec.options.AllowInvalidUTF8 { dec.tokens.last.disableNamespace() } for dec.PeekKind() != '}' { tok, err := dec.ReadToken() if err != nil { return obj, err } name := tok.String() // Manually check for duplicate names. if _, ok := obj[name]; ok { name := dec.previousBuffer() err := &SyntacticError{str: "duplicate name " + string(name) + " in object"} return obj, err.withOffset(dec.InputOffset() - int64(len(name))) } val, err := unmarshalValueAny(uo, dec) obj[name] = val if err != nil { return obj, err } } if _, err := dec.ReadToken(); err != nil { return obj, err } return obj, nil } return nil, &SemanticError{action: "unmarshal", JSONKind: k, GoType: mapStringAnyType} } func marshalArrayAny(mo MarshalOptions, enc *Encoder, arr []any) error { // Check for cycles. if enc.tokens.depth() > startDetectingCyclesAfter { v := reflect.ValueOf(arr) if err := enc.seenPointers.visit(v); err != nil { return err } defer enc.seenPointers.leave(v) } // Optimize for marshaling an empty slice without any preceding whitespace. if len(arr) == 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 } if err := enc.WriteToken(ArrayStart); err != nil { return err } for _, val := range arr { if err := marshalValueAny(mo, enc, val); err != nil { return err } } if err := enc.WriteToken(ArrayEnd); err != nil { return err } return nil } func unmarshalArrayAny(uo UnmarshalOptions, dec *Decoder) ([]any, error) { tok, err := dec.ReadToken() if err != nil { return nil, err } k := tok.Kind() switch k { case 'n': return nil, nil case '[': arr := []any{} for dec.PeekKind() != ']' { val, err := unmarshalValueAny(uo, dec) arr = append(arr, val) if err != nil { return arr, err } } if _, err := dec.ReadToken(); err != nil { return arr, err } return arr, nil } return nil, &SemanticError{action: "unmarshal", JSONKind: k, GoType: sliceAnyType} }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/state.go
vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/state.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 ( "math" "strconv" ) var ( errMissingName = &SyntacticError{str: "missing string for object name"} errMissingColon = &SyntacticError{str: "missing character ':' after object name"} errMissingValue = &SyntacticError{str: "missing value after object name"} errMissingComma = &SyntacticError{str: "missing character ',' after object or array value"} errMismatchDelim = &SyntacticError{str: "mismatching structural token for object or array"} ) const errInvalidNamespace = jsonError("object namespace is in an invalid state") type state struct { // tokens validates whether the next token kind is valid. tokens stateMachine // names is a stack of object names. // Not used if AllowDuplicateNames is true. names objectNameStack // namespaces is a stack of object namespaces. // For performance reasons, Encoder or Decoder may not update this // if Marshal or Unmarshal is able to track names in a more efficient way. // See makeMapArshaler and makeStructArshaler. // Not used if AllowDuplicateNames is true. namespaces objectNamespaceStack } func (s *state) reset() { s.tokens.reset() s.names.reset() s.namespaces.reset() } // appendStackPointer appends a JSON Pointer (RFC 6901) to the current value. // The returned pointer is only accurate if s.names is populated, // otherwise it uses the numeric index as the object member name. // // Invariant: Must call s.names.copyQuotedBuffer beforehand. func (s state) appendStackPointer(b []byte) []byte { var objectDepth int for i := 1; i < s.tokens.depth(); i++ { e := s.tokens.index(i) if e.length() == 0 { break // empty object or array } b = append(b, '/') switch { case e.isObject(): if objectDepth < s.names.length() { for _, c := range s.names.getUnquoted(objectDepth) { // Per RFC 6901, section 3, escape '~' and '/' characters. switch c { case '~': b = append(b, "~0"...) case '/': b = append(b, "~1"...) default: b = append(b, c) } } } else { // Since the names stack is unpopulated, the name is unknown. // As a best-effort replacement, use the numeric member index. // While inaccurate, it produces a syntactically valid pointer. b = strconv.AppendUint(b, uint64((e.length()-1)/2), 10) } objectDepth++ case e.isArray(): b = strconv.AppendUint(b, uint64(e.length()-1), 10) } } return b } // stateMachine is a push-down automaton that validates whether // a sequence of tokens is valid or not according to the JSON grammar. // It is useful for both encoding and decoding. // // It is a stack where each entry represents a nested JSON object or array. // The stack has a minimum depth of 1 where the first level is a // virtual JSON array to handle a stream of top-level JSON values. // The top-level virtual JSON array is special in that it doesn't require commas // between each JSON value. // // For performance, most methods are carefully written to be inlineable. // The zero value is a valid state machine ready for use. type stateMachine struct { stack []stateEntry last stateEntry } // reset resets the state machine. // The machine always starts with a minimum depth of 1. func (m *stateMachine) reset() { m.stack = m.stack[:0] if cap(m.stack) > 1<<10 { m.stack = nil } m.last = stateTypeArray } // depth is the current nested depth of JSON objects and arrays. // It is one-indexed (i.e., top-level values have a depth of 1). func (m stateMachine) depth() int { return len(m.stack) + 1 } // index returns a reference to the ith entry. // It is only valid until the next push method call. func (m *stateMachine) index(i int) *stateEntry { if i == len(m.stack) { return &m.last } return &m.stack[i] } // depthLength reports the current nested depth and // the length of the last JSON object or array. func (m stateMachine) depthLength() (int, int) { return m.depth(), m.last.length() } // appendLiteral appends a JSON literal as the next token in the sequence. // If an error is returned, the state is not mutated. func (m *stateMachine) appendLiteral() error { switch { case m.last.needObjectName(): return errMissingName case !m.last.isValidNamespace(): return errInvalidNamespace default: m.last.increment() return nil } } // appendString appends a JSON string as the next token in the sequence. // If an error is returned, the state is not mutated. func (m *stateMachine) appendString() error { switch { case !m.last.isValidNamespace(): return errInvalidNamespace default: m.last.increment() return nil } } // appendNumber appends a JSON number as the next token in the sequence. // If an error is returned, the state is not mutated. func (m *stateMachine) appendNumber() error { return m.appendLiteral() } // pushObject appends a JSON start object token as next in the sequence. // If an error is returned, the state is not mutated. func (m *stateMachine) pushObject() error { switch { case m.last.needObjectName(): return errMissingName case !m.last.isValidNamespace(): return errInvalidNamespace default: m.last.increment() m.stack = append(m.stack, m.last) m.last = stateTypeObject return nil } } // popObject appends a JSON end object token as next in the sequence. // If an error is returned, the state is not mutated. func (m *stateMachine) popObject() error { switch { case !m.last.isObject(): return errMismatchDelim case m.last.needObjectValue(): return errMissingValue case !m.last.isValidNamespace(): return errInvalidNamespace default: m.last = m.stack[len(m.stack)-1] m.stack = m.stack[:len(m.stack)-1] return nil } } // pushArray appends a JSON start array token as next in the sequence. // If an error is returned, the state is not mutated. func (m *stateMachine) pushArray() error { switch { case m.last.needObjectName(): return errMissingName case !m.last.isValidNamespace(): return errInvalidNamespace default: m.last.increment() m.stack = append(m.stack, m.last) m.last = stateTypeArray return nil } } // popArray appends a JSON end array token as next in the sequence. // If an error is returned, the state is not mutated. func (m *stateMachine) popArray() error { switch { case !m.last.isArray() || len(m.stack) == 0: // forbid popping top-level virtual JSON array return errMismatchDelim case !m.last.isValidNamespace(): return errInvalidNamespace default: m.last = m.stack[len(m.stack)-1] m.stack = m.stack[:len(m.stack)-1] return nil } } // needIndent reports whether indent whitespace should be injected. // A zero value means that no whitespace should be injected. // A positive value means '\n', indentPrefix, and (n-1) copies of indentBody // should be appended to the output immediately before the next token. func (m stateMachine) needIndent(next Kind) (n int) { willEnd := next == '}' || next == ']' switch { case m.depth() == 1: return 0 // top-level values are never indented case m.last.length() == 0 && willEnd: return 0 // an empty object or array is never indented case m.last.length() == 0 || m.last.needImplicitComma(next): return m.depth() case willEnd: return m.depth() - 1 default: return 0 } } // mayAppendDelim appends a colon or comma that may precede the next token. func (m stateMachine) mayAppendDelim(b []byte, next Kind) []byte { switch { case m.last.needImplicitColon(): return append(b, ':') case m.last.needImplicitComma(next) && len(m.stack) != 0: // comma not needed for top-level values return append(b, ',') default: return b } } // needDelim reports whether a colon or comma token should be implicitly emitted // before the next token of the specified kind. // A zero value means no delimiter should be emitted. func (m stateMachine) needDelim(next Kind) (delim byte) { switch { case m.last.needImplicitColon(): return ':' case m.last.needImplicitComma(next) && len(m.stack) != 0: // comma not needed for top-level values return ',' default: return 0 } } // checkDelim reports whether the specified delimiter should be there given // the kind of the next token that appears immediately afterwards. func (m stateMachine) checkDelim(delim byte, next Kind) error { switch needDelim := m.needDelim(next); { case needDelim == delim: return nil case needDelim == ':': return errMissingColon case needDelim == ',': return errMissingComma default: return newInvalidCharacterError([]byte{delim}, "before next token") } } // invalidateDisabledNamespaces marks all disabled namespaces as invalid. // // For efficiency, Marshal and Unmarshal may disable namespaces since there are // more efficient ways to track duplicate names. However, if an error occurs, // the namespaces in Encoder or Decoder will be left in an inconsistent state. // Mark the namespaces as invalid so that future method calls on // Encoder or Decoder will return an error. func (m *stateMachine) invalidateDisabledNamespaces() { for i := 0; i < m.depth(); i++ { e := m.index(i) if !e.isActiveNamespace() { e.invalidateNamespace() } } } // stateEntry encodes several artifacts within a single unsigned integer: // - whether this represents a JSON object or array, // - whether this object should check for duplicate names, and // - how many elements are in this JSON object or array. type stateEntry uint64 const ( // The type mask (1 bit) records whether this is a JSON object or array. stateTypeMask stateEntry = 0x8000_0000_0000_0000 stateTypeObject stateEntry = 0x8000_0000_0000_0000 stateTypeArray stateEntry = 0x0000_0000_0000_0000 // The name check mask (2 bit) records whether to update // the namespaces for the current JSON object and // whether the namespace is valid. stateNamespaceMask stateEntry = 0x6000_0000_0000_0000 stateDisableNamespace stateEntry = 0x4000_0000_0000_0000 stateInvalidNamespace stateEntry = 0x2000_0000_0000_0000 // The count mask (61 bits) records the number of elements. stateCountMask stateEntry = 0x1fff_ffff_ffff_ffff stateCountLSBMask stateEntry = 0x0000_0000_0000_0001 stateCountOdd stateEntry = 0x0000_0000_0000_0001 stateCountEven stateEntry = 0x0000_0000_0000_0000 ) // length reports the number of elements in the JSON object or array. // Each name and value in an object entry is treated as a separate element. func (e stateEntry) length() int { return int(e & stateCountMask) } // isObject reports whether this is a JSON object. func (e stateEntry) isObject() bool { return e&stateTypeMask == stateTypeObject } // isArray reports whether this is a JSON array. func (e stateEntry) isArray() bool { return e&stateTypeMask == stateTypeArray } // needObjectName reports whether the next token must be a JSON string, // which is necessary for JSON object names. func (e stateEntry) needObjectName() bool { return e&(stateTypeMask|stateCountLSBMask) == stateTypeObject|stateCountEven } // needImplicitColon reports whether an colon should occur next, // which always occurs after JSON object names. func (e stateEntry) needImplicitColon() bool { return e.needObjectValue() } // needObjectValue reports whether the next token must be a JSON value, // which is necessary after every JSON object name. func (e stateEntry) needObjectValue() bool { return e&(stateTypeMask|stateCountLSBMask) == stateTypeObject|stateCountOdd } // needImplicitComma reports whether an comma should occur next, // which always occurs after a value in a JSON object or array // before the next value (or name). func (e stateEntry) needImplicitComma(next Kind) bool { return !e.needObjectValue() && e.length() > 0 && next != '}' && next != ']' } // increment increments the number of elements for the current object or array. // This assumes that overflow won't practically be an issue since // 1<<bits.OnesCount(stateCountMask) is sufficiently large. func (e *stateEntry) increment() { (*e)++ } // decrement decrements the number of elements for the current object or array. // It is the callers responsibility to ensure that e.length > 0. func (e *stateEntry) decrement() { (*e)-- } // disableNamespace disables the JSON object namespace such that the // Encoder or Decoder no longer updates the namespace. func (e *stateEntry) disableNamespace() { *e |= stateDisableNamespace } // isActiveNamespace reports whether the JSON object namespace is actively // being updated and used for duplicate name checks. func (e stateEntry) isActiveNamespace() bool { return e&(stateDisableNamespace) == 0 } // invalidateNamespace marks the JSON object namespace as being invalid. func (e *stateEntry) invalidateNamespace() { *e |= stateInvalidNamespace } // isValidNamespace reports whether the JSON object namespace is valid. func (e stateEntry) isValidNamespace() bool { return e&(stateInvalidNamespace) == 0 } // objectNameStack is a stack of names when descending into a JSON object. // In contrast to objectNamespaceStack, this only has to remember a single name // per JSON object. // // This data structure may contain offsets to encodeBuffer or decodeBuffer. // It violates clean abstraction of layers, but is significantly more efficient. // This ensures that popping and pushing in the common case is a trivial // push/pop of an offset integer. // // The zero value is an empty names stack ready for use. type objectNameStack struct { // offsets is a stack of offsets for each name. // A non-negative offset is the ending offset into the local names buffer. // A negative offset is the bit-wise inverse of a starting offset into // a remote buffer (e.g., encodeBuffer or decodeBuffer). // A math.MinInt offset at the end implies that the last object is empty. // Invariant: Positive offsets always occur before negative offsets. offsets []int // unquotedNames is a back-to-back concatenation of names. unquotedNames []byte } func (ns *objectNameStack) reset() { ns.offsets = ns.offsets[:0] ns.unquotedNames = ns.unquotedNames[:0] if cap(ns.offsets) > 1<<6 { ns.offsets = nil // avoid pinning arbitrarily large amounts of memory } if cap(ns.unquotedNames) > 1<<10 { ns.unquotedNames = nil // avoid pinning arbitrarily large amounts of memory } } func (ns *objectNameStack) length() int { return len(ns.offsets) } // getUnquoted retrieves the ith unquoted name in the namespace. // It returns an empty string if the last object is empty. // // Invariant: Must call copyQuotedBuffer beforehand. func (ns *objectNameStack) getUnquoted(i int) []byte { ns.ensureCopiedBuffer() if i == 0 { return ns.unquotedNames[:ns.offsets[0]] } else { return ns.unquotedNames[ns.offsets[i-1]:ns.offsets[i-0]] } } // invalidOffset indicates that the last JSON object currently has no name. const invalidOffset = math.MinInt // push descends into a nested JSON object. func (ns *objectNameStack) push() { ns.offsets = append(ns.offsets, invalidOffset) } // replaceLastQuotedOffset replaces the last name with the starting offset // to the quoted name in some remote buffer. All offsets provided must be // relative to the same buffer until copyQuotedBuffer is called. func (ns *objectNameStack) replaceLastQuotedOffset(i int) { // Use bit-wise inversion instead of naive multiplication by -1 to avoid // ambiguity regarding zero (which is a valid offset into the names field). // Bit-wise inversion is mathematically equivalent to -i-1, // such that 0 becomes -1, 1 becomes -2, and so forth. // This ensures that remote offsets are always negative. ns.offsets[len(ns.offsets)-1] = ^i } // replaceLastUnquotedName replaces the last name with the provided name. // // Invariant: Must call copyQuotedBuffer beforehand. func (ns *objectNameStack) replaceLastUnquotedName(s string) { ns.ensureCopiedBuffer() var startOffset int if len(ns.offsets) > 1 { startOffset = ns.offsets[len(ns.offsets)-2] } ns.unquotedNames = append(ns.unquotedNames[:startOffset], s...) ns.offsets[len(ns.offsets)-1] = len(ns.unquotedNames) } // clearLast removes any name in the last JSON object. // It is semantically equivalent to ns.push followed by ns.pop. func (ns *objectNameStack) clearLast() { ns.offsets[len(ns.offsets)-1] = invalidOffset } // pop ascends out of a nested JSON object. func (ns *objectNameStack) pop() { ns.offsets = ns.offsets[:len(ns.offsets)-1] } // copyQuotedBuffer copies names from the remote buffer into the local names // buffer so that there are no more offset references into the remote buffer. // This allows the remote buffer to change contents without affecting // the names that this data structure is trying to remember. func (ns *objectNameStack) copyQuotedBuffer(b []byte) { // Find the first negative offset. var i int for i = len(ns.offsets) - 1; i >= 0 && ns.offsets[i] < 0; i-- { continue } // Copy each name from the remote buffer into the local buffer. for i = i + 1; i < len(ns.offsets); i++ { if i == len(ns.offsets)-1 && ns.offsets[i] == invalidOffset { if i == 0 { ns.offsets[i] = 0 } else { ns.offsets[i] = ns.offsets[i-1] } break // last JSON object had a push without any names } // As a form of Hyrum proofing, we write an invalid character into the // buffer to make misuse of Decoder.ReadToken more obvious. // We need to undo that mutation here. quotedName := b[^ns.offsets[i]:] if quotedName[0] == invalidateBufferByte { quotedName[0] = '"' } // Append the unquoted name to the local buffer. var startOffset int if i > 0 { startOffset = ns.offsets[i-1] } if n := consumeSimpleString(quotedName); n > 0 { ns.unquotedNames = append(ns.unquotedNames[:startOffset], quotedName[len(`"`):n-len(`"`)]...) } else { ns.unquotedNames, _ = unescapeString(ns.unquotedNames[:startOffset], quotedName) } ns.offsets[i] = len(ns.unquotedNames) } } func (ns *objectNameStack) ensureCopiedBuffer() { if len(ns.offsets) > 0 && ns.offsets[len(ns.offsets)-1] < 0 { panic("BUG: copyQuotedBuffer not called beforehand") } } // objectNamespaceStack is a stack of object namespaces. // This data structure assists in detecting duplicate names. type objectNamespaceStack []objectNamespace // reset resets the object namespace stack. func (nss *objectNamespaceStack) reset() { if cap(*nss) > 1<<10 { *nss = nil } *nss = (*nss)[:0] } // push starts a new namespace for a nested JSON object. func (nss *objectNamespaceStack) push() { if cap(*nss) > len(*nss) { *nss = (*nss)[:len(*nss)+1] nss.last().reset() } else { *nss = append(*nss, objectNamespace{}) } } // last returns a pointer to the last JSON object namespace. func (nss objectNamespaceStack) last() *objectNamespace { return &nss[len(nss)-1] } // pop terminates the namespace for a nested JSON object. func (nss *objectNamespaceStack) pop() { *nss = (*nss)[:len(*nss)-1] } // objectNamespace is the namespace for a JSON object. // In contrast to objectNameStack, this needs to remember a all names // per JSON object. // // The zero value is an empty namespace ready for use. type objectNamespace struct { // It relies on a linear search over all the names before switching // to use a Go map for direct lookup. // endOffsets is a list of offsets to the end of each name in buffers. // The length of offsets is the number of names in the namespace. endOffsets []uint // allUnquotedNames is a back-to-back concatenation of every name in the namespace. allUnquotedNames []byte // mapNames is a Go map containing every name in the namespace. // Only valid if non-nil. mapNames map[string]struct{} } // reset resets the namespace to be empty. func (ns *objectNamespace) reset() { ns.endOffsets = ns.endOffsets[:0] ns.allUnquotedNames = ns.allUnquotedNames[:0] ns.mapNames = nil if cap(ns.endOffsets) > 1<<6 { ns.endOffsets = nil // avoid pinning arbitrarily large amounts of memory } if cap(ns.allUnquotedNames) > 1<<10 { ns.allUnquotedNames = nil // avoid pinning arbitrarily large amounts of memory } } // length reports the number of names in the namespace. func (ns *objectNamespace) length() int { return len(ns.endOffsets) } // getUnquoted retrieves the ith unquoted name in the namespace. func (ns *objectNamespace) getUnquoted(i int) []byte { if i == 0 { return ns.allUnquotedNames[:ns.endOffsets[0]] } else { return ns.allUnquotedNames[ns.endOffsets[i-1]:ns.endOffsets[i-0]] } } // lastUnquoted retrieves the last name in the namespace. func (ns *objectNamespace) lastUnquoted() []byte { return ns.getUnquoted(ns.length() - 1) } // insertQuoted inserts a name and reports whether it was inserted, // which only occurs if name is not already in the namespace. // The provided name must be a valid JSON string. func (ns *objectNamespace) insertQuoted(name []byte, isVerbatim bool) bool { if isVerbatim { name = name[len(`"`) : len(name)-len(`"`)] } return ns.insert(name, !isVerbatim) } func (ns *objectNamespace) insertUnquoted(name []byte) bool { return ns.insert(name, false) } func (ns *objectNamespace) insert(name []byte, quoted bool) bool { var allNames []byte if quoted { allNames, _ = unescapeString(ns.allUnquotedNames, name) } else { allNames = append(ns.allUnquotedNames, name...) } name = allNames[len(ns.allUnquotedNames):] // Switch to a map if the buffer is too large for linear search. // This does not add the current name to the map. if ns.mapNames == nil && (ns.length() > 64 || len(ns.allUnquotedNames) > 1024) { ns.mapNames = make(map[string]struct{}) var startOffset uint for _, endOffset := range ns.endOffsets { name := ns.allUnquotedNames[startOffset:endOffset] ns.mapNames[string(name)] = struct{}{} // allocates a new string startOffset = endOffset } } if ns.mapNames == nil { // Perform linear search over the buffer to find matching names. // It provides O(n) lookup, but does not require any allocations. var startOffset uint for _, endOffset := range ns.endOffsets { if string(ns.allUnquotedNames[startOffset:endOffset]) == string(name) { return false } startOffset = endOffset } } else { // Use the map if it is populated. // It provides O(1) lookup, but requires a string allocation per name. if _, ok := ns.mapNames[string(name)]; ok { return false } ns.mapNames[string(name)] = struct{}{} // allocates a new string } ns.allUnquotedNames = allNames ns.endOffsets = append(ns.endOffsets, uint(len(ns.allUnquotedNames))) return true } // removeLast removes the last name in the namespace. func (ns *objectNamespace) removeLast() { if ns.mapNames != nil { delete(ns.mapNames, string(ns.lastUnquoted())) } if ns.length()-1 == 0 { ns.endOffsets = ns.endOffsets[:0] ns.allUnquotedNames = ns.allUnquotedNames[:0] } else { ns.endOffsets = ns.endOffsets[:ns.length()-1] ns.allUnquotedNames = ns.allUnquotedNames[:ns.endOffsets[ns.length()-1]] } } type uintSet64 uint64 func (s uintSet64) has(i uint) bool { return s&(1<<i) > 0 } func (s *uintSet64) set(i uint) { *s |= 1 << i } // uintSet is a set of unsigned integers. // It is optimized for most integers being close to zero. type uintSet struct { lo uintSet64 hi []uintSet64 } // has reports whether i is in the set. func (s *uintSet) has(i uint) bool { if i < 64 { return s.lo.has(i) } else { i -= 64 iHi, iLo := int(i/64), i%64 return iHi < len(s.hi) && s.hi[iHi].has(iLo) } } // insert inserts i into the set and reports whether it was the first insertion. func (s *uintSet) insert(i uint) bool { // TODO: Make this inlineable at least for the lower 64-bit case. if i < 64 { has := s.lo.has(i) s.lo.set(i) return !has } else { i -= 64 iHi, iLo := int(i/64), i%64 if iHi >= len(s.hi) { s.hi = append(s.hi, make([]uintSet64, iHi+1-len(s.hi))...) s.hi = s.hi[:cap(s.hi)] } has := s.hi[iHi].has(iLo) s.hi[iHi].set(iLo) return !has } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_funcs.go
vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_funcs.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" "fmt" "reflect" "sync" ) // SkipFunc may be returned by MarshalFuncV2 and UnmarshalFuncV2 functions. // // Any function that returns SkipFunc must not cause observable side effects // on the provided Encoder or Decoder. For example, it is permissible to call // Decoder.PeekKind, but not permissible to call Decoder.ReadToken or // Encoder.WriteToken since such methods mutate the state. const SkipFunc = jsonError("skip function") // Marshalers is a list of functions that may override the marshal behavior // of specific types. Populate MarshalOptions.Marshalers to use it. // A nil *Marshalers is equivalent to an empty list. type Marshalers = typedMarshalers // NewMarshalers constructs a flattened list of marshal functions. // If multiple functions in the list are applicable for a value of a given type, // then those earlier in the list take precedence over those that come later. // If a function returns SkipFunc, then the next applicable function is called, // otherwise the default marshaling behavior is used. // // For example: // // m1 := NewMarshalers(f1, f2) // m2 := NewMarshalers(f0, m1, f3) // equivalent to m3 // m3 := NewMarshalers(f0, f1, f2, f3) // equivalent to m2 func NewMarshalers(ms ...*Marshalers) *Marshalers { return newMarshalers(ms...) } // Unmarshalers is a list of functions that may override the unmarshal behavior // of specific types. Populate UnmarshalOptions.Unmarshalers to use it. // A nil *Unmarshalers is equivalent to an empty list. type Unmarshalers = typedUnmarshalers // NewUnmarshalers constructs a flattened list of unmarshal functions. // If multiple functions in the list are applicable for a value of a given type, // then those earlier in the list take precedence over those that come later. // If a function returns SkipFunc, then the next applicable function is called, // otherwise the default unmarshaling behavior is used. // // For example: // // u1 := NewUnmarshalers(f1, f2) // u2 := NewUnmarshalers(f0, u1, f3) // equivalent to u3 // u3 := NewUnmarshalers(f0, f1, f2, f3) // equivalent to u2 func NewUnmarshalers(us ...*Unmarshalers) *Unmarshalers { return newUnmarshalers(us...) } type typedMarshalers = typedArshalers[MarshalOptions, Encoder] type typedUnmarshalers = typedArshalers[UnmarshalOptions, Decoder] type typedArshalers[Options, Coder any] struct { nonComparable fncVals []typedArshaler[Options, Coder] fncCache sync.Map // map[reflect.Type]arshaler // fromAny reports whether any of Go types used to represent arbitrary JSON // (i.e., any, bool, string, float64, map[string]any, or []any) matches // any of the provided type-specific arshalers. // // This bit of information is needed in arshal_default.go to determine // whether to use the specialized logic in arshal_any.go to handle // the any interface type. The logic in arshal_any.go does not support // type-specific arshal functions, so we must avoid using that logic // if this is true. fromAny bool } type typedMarshaler = typedArshaler[MarshalOptions, Encoder] type typedUnmarshaler = typedArshaler[UnmarshalOptions, Decoder] type typedArshaler[Options, Coder any] struct { typ reflect.Type fnc func(Options, *Coder, addressableValue) error maySkip bool } func newMarshalers(ms ...*Marshalers) *Marshalers { return newTypedArshalers(ms...) } func newUnmarshalers(us ...*Unmarshalers) *Unmarshalers { return newTypedArshalers(us...) } func newTypedArshalers[Options, Coder any](as ...*typedArshalers[Options, Coder]) *typedArshalers[Options, Coder] { var a typedArshalers[Options, Coder] for _, a2 := range as { if a2 != nil { a.fncVals = append(a.fncVals, a2.fncVals...) a.fromAny = a.fromAny || a2.fromAny } } if len(a.fncVals) == 0 { return nil } return &a } func (a *typedArshalers[Options, Coder]) lookup(fnc func(Options, *Coder, addressableValue) error, t reflect.Type) (func(Options, *Coder, addressableValue) error, bool) { if a == nil { return fnc, false } if v, ok := a.fncCache.Load(t); ok { if v == nil { return fnc, false } return v.(func(Options, *Coder, addressableValue) error), true } // Collect a list of arshalers that can be called for this type. // This list may be longer than 1 since some arshalers can be skipped. var fncs []func(Options, *Coder, addressableValue) error for _, fncVal := range a.fncVals { if !castableTo(t, fncVal.typ) { continue } fncs = append(fncs, fncVal.fnc) if !fncVal.maySkip { break // subsequent arshalers will never be called } } if len(fncs) == 0 { a.fncCache.Store(t, nil) // nil to indicate that no funcs found return fnc, false } // Construct an arshaler that may call every applicable arshaler. fncDefault := fnc fnc = func(o Options, c *Coder, v addressableValue) error { for _, fnc := range fncs { if err := fnc(o, c, v); err != SkipFunc { return err // may be nil or non-nil } } return fncDefault(o, c, v) } // Use the first stored so duplicate work can be garbage collected. v, _ := a.fncCache.LoadOrStore(t, fnc) return v.(func(Options, *Coder, addressableValue) error), true } // MarshalFuncV1 constructs a type-specific marshaler that // specifies how to marshal values of type T. // T can be any type except a named pointer. // The function is always provided with a non-nil pointer value // if T is an interface or pointer type. // // The function must marshal exactly one JSON value. // The value of T must not be retained outside the function call. // It may not return SkipFunc. func MarshalFuncV1[T any](fn func(T) ([]byte, error)) *Marshalers { t := reflect.TypeOf((*T)(nil)).Elem() assertCastableTo(t, true) typFnc := typedMarshaler{ typ: t, fnc: func(mo MarshalOptions, enc *Encoder, va addressableValue) error { val, err := fn(va.castTo(t).Interface().(T)) if err != nil { err = wrapSkipFunc(err, "marshal function of type func(T) ([]byte, error)") // 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 }, } return &Marshalers{fncVals: []typedMarshaler{typFnc}, fromAny: castableToFromAny(t)} } // MarshalFuncV2 constructs a type-specific marshaler that // specifies how to marshal values of type T. // T can be any type except a named pointer. // The function is always provided with a non-nil pointer value // if T is an interface or pointer type. // // The function must marshal exactly one JSON value by calling write methods // on the provided encoder. It may return SkipFunc such that marshaling can // move on to the next marshal function. However, no mutable method calls may // be called on the encoder if SkipFunc is returned. // The pointer to Encoder and the value of T must not be retained // outside the function call. func MarshalFuncV2[T any](fn func(MarshalOptions, *Encoder, T) error) *Marshalers { t := reflect.TypeOf((*T)(nil)).Elem() assertCastableTo(t, true) typFnc := typedMarshaler{ typ: t, fnc: func(mo MarshalOptions, enc *Encoder, va addressableValue) error { prevDepth, prevLength := enc.tokens.depthLength() err := fn(mo, enc, va.castTo(t).Interface().(T)) currDepth, currLength := enc.tokens.depthLength() if err == nil && (prevDepth != currDepth || prevLength+1 != currLength) { err = errors.New("must write exactly one JSON value") } if err != nil { if err == SkipFunc { if prevDepth == currDepth && prevLength == currLength { return SkipFunc } err = errors.New("must not write any JSON tokens when skipping") } // TODO: Avoid wrapping semantic or I/O errors. return &SemanticError{action: "marshal", GoType: t, Err: err} } return nil }, maySkip: true, } return &Marshalers{fncVals: []typedMarshaler{typFnc}, fromAny: castableToFromAny(t)} } // UnmarshalFuncV1 constructs a type-specific unmarshaler that // specifies how to unmarshal values of type T. // T must be an unnamed pointer or an interface type. // The function is always provided with a non-nil pointer value. // // The function must unmarshal exactly one JSON value. // The input []byte must not be mutated. // The input []byte and value T must not be retained outside the function call. // It may not return SkipFunc. func UnmarshalFuncV1[T any](fn func([]byte, T) error) *Unmarshalers { t := reflect.TypeOf((*T)(nil)).Elem() assertCastableTo(t, false) typFnc := typedUnmarshaler{ typ: t, fnc: 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 } err = fn(val, va.castTo(t).Interface().(T)) if err != nil { err = wrapSkipFunc(err, "unmarshal function of type func([]byte, T) error") // TODO: Avoid wrapping semantic, syntactic, or I/O errors. return &SemanticError{action: "unmarshal", JSONKind: val.Kind(), GoType: t, Err: err} } return nil }, } return &Unmarshalers{fncVals: []typedUnmarshaler{typFnc}, fromAny: castableToFromAny(t)} } // UnmarshalFuncV2 constructs a type-specific unmarshaler that // specifies how to unmarshal values of type T. // T must be an unnamed pointer or an interface type. // The function is always provided with a non-nil pointer value. // // The function must unmarshal exactly one JSON value by calling read methods // on the provided decoder. It may return SkipFunc such that unmarshaling can // move on to the next unmarshal function. However, no mutable method calls may // be called on the decoder if SkipFunc is returned. // The pointer to Decoder and the value of T must not be retained // outside the function call. func UnmarshalFuncV2[T any](fn func(UnmarshalOptions, *Decoder, T) error) *Unmarshalers { t := reflect.TypeOf((*T)(nil)).Elem() assertCastableTo(t, false) typFnc := typedUnmarshaler{ typ: t, fnc: func(uo UnmarshalOptions, dec *Decoder, va addressableValue) error { prevDepth, prevLength := dec.tokens.depthLength() err := fn(uo, dec, va.castTo(t).Interface().(T)) currDepth, currLength := dec.tokens.depthLength() if err == nil && (prevDepth != currDepth || prevLength+1 != currLength) { err = errors.New("must read exactly one JSON value") } if err != nil { if err == SkipFunc { if prevDepth == currDepth && prevLength == currLength { return SkipFunc } err = errors.New("must not read any JSON tokens when skipping") } // TODO: Avoid wrapping semantic, syntactic, or I/O errors. return &SemanticError{action: "unmarshal", GoType: t, Err: err} } return nil }, maySkip: true, } return &Unmarshalers{fncVals: []typedUnmarshaler{typFnc}, fromAny: castableToFromAny(t)} } // assertCastableTo asserts that "to" is a valid type to be casted to. // These are the Go types that type-specific arshalers may operate upon. // // Let AllTypes be the universal set of all possible Go types. // This function generally asserts that: // // len([from for from in AllTypes if castableTo(from, to)]) > 0 // // otherwise it panics. // // As a special-case if marshal is false, then we forbid any non-pointer or // non-interface type since it is almost always a bug trying to unmarshal // into something where the end-user caller did not pass in an addressable value // since they will not observe the mutations. func assertCastableTo(to reflect.Type, marshal bool) { switch to.Kind() { case reflect.Interface: return case reflect.Pointer: // Only allow unnamed pointers to be consistent with the fact that // taking the address of a value produces an unnamed pointer type. if to.Name() == "" { return } default: // Technically, non-pointer types are permissible for unmarshal. // However, they are often a bug since the receiver would be immutable. // Thus, only allow them for marshaling. if marshal { return } } if marshal { panic(fmt.Sprintf("input type %v must be an interface type, an unnamed pointer type, or a non-pointer type", to)) } else { panic(fmt.Sprintf("input type %v must be an interface type or an unnamed pointer type", to)) } } // castableTo checks whether values of type "from" can be casted to type "to". // Nil pointer or interface "from" values are never considered castable. // // This function must be kept in sync with addressableValue.castTo. func castableTo(from, to reflect.Type) bool { switch to.Kind() { case reflect.Interface: // TODO: This breaks when ordinary interfaces can have type sets // since interfaces now exist where only the value form of a type (T) // implements the interface, but not the pointer variant (*T). // See https://go.dev/issue/45346. return reflect.PointerTo(from).Implements(to) case reflect.Pointer: // Common case for unmarshaling. // From must be a concrete or interface type. return reflect.PointerTo(from) == to default: // Common case for marshaling. // From must be a concrete type. return from == to } } // castTo casts va to the specified type. // If the type is an interface, then the underlying type will always // be a non-nil pointer to a concrete type. // // Requirement: castableTo(va.Type(), to) must hold. func (va addressableValue) castTo(to reflect.Type) reflect.Value { switch to.Kind() { case reflect.Interface: return va.Addr().Convert(to) case reflect.Pointer: return va.Addr() default: return va.Value } } // castableToFromAny reports whether "to" can be casted to from any // of the dynamic types used to represent arbitrary JSON. func castableToFromAny(to reflect.Type) bool { for _, from := range []reflect.Type{anyType, boolType, stringType, float64Type, mapStringAnyType, sliceAnyType} { if castableTo(from, to) { return true } } return false } func wrapSkipFunc(err error, what string) error { if err == SkipFunc { return errors.New(what + " cannot be skipped") } return err }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_time.go
vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_time.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" "fmt" "reflect" "strings" "time" ) var ( timeDurationType = reflect.TypeOf((*time.Duration)(nil)).Elem() timeTimeType = reflect.TypeOf((*time.Time)(nil)).Elem() ) func makeTimeArshaler(fncs *arshaler, t reflect.Type) *arshaler { // Ideally, time types would implement MarshalerV2 and UnmarshalerV2, // but that would incur a dependency on package json from package time. // Given how widely used time is, it is more acceptable that we incur a // dependency on time from json. // // Injecting the arshaling functionality like this will not be identical // to actually declaring methods on the time types since embedding of the // time types will not be able to forward this functionality. switch t { case timeDurationType: fncs.nonDefault = true marshalNanos := fncs.marshal fncs.marshal = func(mo MarshalOptions, enc *Encoder, va addressableValue) error { if mo.format != "" && mo.formatDepth == enc.tokens.depth() { if mo.format == "nanos" { mo.format = "" return marshalNanos(mo, enc, va) } else { return newInvalidFormatError("marshal", t, mo.format) } } td := va.Interface().(time.Duration) b := enc.UnusedBuffer() b = append(b, '"') b = append(b, td.String()...) // never contains special characters b = append(b, '"') return enc.WriteValue(b) } unmarshalNanos := fncs.unmarshal fncs.unmarshal = func(uo UnmarshalOptions, dec *Decoder, va addressableValue) error { // TODO: Should there be a flag that specifies that we can unmarshal // from either form since there would be no ambiguity? if uo.format != "" && uo.formatDepth == dec.tokens.depth() { if uo.format == "nanos" { uo.format = "" return unmarshalNanos(uo, dec, va) } else { return newInvalidFormatError("unmarshal", t, uo.format) } } var flags valueFlags td := va.Addr().Interface().(*time.Duration) val, err := dec.readValue(&flags) if err != nil { return err } switch k := val.Kind(); k { case 'n': *td = time.Duration(0) return nil case '"': val = unescapeStringMayCopy(val, flags.isVerbatim()) td2, err := time.ParseDuration(string(val)) if err != nil { return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t, Err: err} } *td = td2 return nil default: return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t} } } case timeTimeType: fncs.nonDefault = true fncs.marshal = func(mo MarshalOptions, enc *Encoder, va addressableValue) error { format := time.RFC3339Nano isRFC3339 := true if mo.format != "" && mo.formatDepth == enc.tokens.depth() { var err error format, isRFC3339, err = checkTimeFormat(mo.format) if err != nil { return &SemanticError{action: "marshal", GoType: t, Err: err} } } tt := va.Interface().(time.Time) b := enc.UnusedBuffer() b = append(b, '"') b = tt.AppendFormat(b, format) b = append(b, '"') if isRFC3339 { // Not all Go timestamps can be represented as valid RFC 3339. // Explicitly check for these edge cases. // See https://go.dev/issue/4556 and https://go.dev/issue/54580. var err error switch b := b[len(`"`) : len(b)-len(`"`)]; { case b[len("9999")] != '-': // year must be exactly 4 digits wide err = errors.New("year outside of range [0,9999]") case b[len(b)-1] != 'Z': c := b[len(b)-len("Z07:00")] if ('0' <= c && c <= '9') || parseDec2(b[len(b)-len("07:00"):]) >= 24 { err = errors.New("timezone hour outside of range [0,23]") } } if err != nil { return &SemanticError{action: "marshal", GoType: t, Err: err} } return enc.WriteValue(b) // RFC 3339 never needs JSON escaping } // The format may contain special characters that need escaping. // Verify that the result is a valid JSON string (common case), // otherwise escape the string correctly (slower case). if consumeSimpleString(b) != len(b) { b, _ = appendString(nil, string(b[len(`"`):len(b)-len(`"`)]), true, nil) } return enc.WriteValue(b) } fncs.unmarshal = func(uo UnmarshalOptions, dec *Decoder, va addressableValue) error { format := time.RFC3339 isRFC3339 := true if uo.format != "" && uo.formatDepth == dec.tokens.depth() { var err error format, isRFC3339, err = checkTimeFormat(uo.format) if err != nil { return &SemanticError{action: "unmarshal", GoType: t, Err: err} } } var flags valueFlags tt := va.Addr().Interface().(*time.Time) val, err := dec.readValue(&flags) if err != nil { return err } k := val.Kind() switch k { case 'n': *tt = time.Time{} return nil case '"': val = unescapeStringMayCopy(val, flags.isVerbatim()) tt2, err := time.Parse(format, string(val)) if isRFC3339 && err == nil { // TODO(https://go.dev/issue/54580): RFC 3339 specifies // the exact grammar of a valid timestamp. However, // the parsing functionality in "time" is too loose and // incorrectly accepts invalid timestamps as valid. // Remove these manual checks when "time" checks it for us. newParseError := func(layout, value, layoutElem, valueElem, message string) error { return &time.ParseError{Layout: layout, Value: value, LayoutElem: layoutElem, ValueElem: valueElem, Message: message} } switch { case val[len("2006-01-02T")+1] == ':': // hour must be two digits err = newParseError(format, string(val), "15", string(val[len("2006-01-02T"):][:1]), "") case val[len("2006-01-02T15:04:05")] == ',': // sub-second separator must be a period err = newParseError(format, string(val), ".", ",", "") case val[len(val)-1] != 'Z': switch { case parseDec2(val[len(val)-len("07:00"):]) >= 24: // timezone hour must be in range err = newParseError(format, string(val), "Z07:00", string(val[len(val)-len("Z07:00"):]), ": timezone hour out of range") case parseDec2(val[len(val)-len("00"):]) >= 60: // timezone minute must be in range err = newParseError(format, string(val), "Z07:00", string(val[len(val)-len("Z07:00"):]), ": timezone minute out of range") } } } if err != nil { return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t, Err: err} } *tt = tt2 return nil default: return &SemanticError{action: "unmarshal", JSONKind: k, GoType: t} } } } return fncs } func checkTimeFormat(format string) (string, bool, error) { // We assume that an exported constant in the time package will // always start with an uppercase ASCII letter. if len(format) > 0 && 'A' <= format[0] && format[0] <= 'Z' { switch format { case "ANSIC": return time.ANSIC, false, nil case "UnixDate": return time.UnixDate, false, nil case "RubyDate": return time.RubyDate, false, nil case "RFC822": return time.RFC822, false, nil case "RFC822Z": return time.RFC822Z, false, nil case "RFC850": return time.RFC850, false, nil case "RFC1123": return time.RFC1123, false, nil case "RFC1123Z": return time.RFC1123Z, false, nil case "RFC3339": return time.RFC3339, true, nil case "RFC3339Nano": return time.RFC3339Nano, true, nil case "Kitchen": return time.Kitchen, false, nil case "Stamp": return time.Stamp, false, nil case "StampMilli": return time.StampMilli, false, nil case "StampMicro": return time.StampMicro, false, nil case "StampNano": return time.StampNano, false, nil default: // Reject any format that is an exported Go identifier in case // new format constants are added to the time package. if strings.TrimFunc(format, isLetterOrDigit) == "" { return "", false, fmt.Errorf("undefined format layout: %v", format) } } } return format, false, nil } // parseDec2 parses b as an unsigned, base-10, 2-digit number. // It panics if len(b) < 2. The result is undefined if digits are not base-10. func parseDec2(b []byte) byte { return 10*(b[0]-'0') + (b[1] - '0') }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/encode.go
vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/encode.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" "io" "math" "math/bits" "strconv" "unicode/utf16" "unicode/utf8" ) // EncodeOptions configures how JSON encoding operates. // The zero value is equivalent to the default settings, // which is compliant with both RFC 7493 and RFC 8259. type EncodeOptions struct { requireKeyedLiterals nonComparable // multiline specifies whether the encoder should emit multiline output. multiline bool // omitTopLevelNewline specifies whether to omit the newline // that is appended after every top-level JSON value when streaming. omitTopLevelNewline bool // AllowDuplicateNames specifies that JSON objects may contain // duplicate member names. Disabling the duplicate name check may provide // performance benefits, but breaks compliance with RFC 7493, section 2.3. // The output will still be compliant with RFC 8259, // which leaves the handling of duplicate names as unspecified behavior. AllowDuplicateNames bool // AllowInvalidUTF8 specifies that JSON strings may contain invalid UTF-8, // which will be mangled as the Unicode replacement character, U+FFFD. // This causes the encoder to break compliance with // RFC 7493, section 2.1, and RFC 8259, section 8.1. AllowInvalidUTF8 bool // preserveRawStrings specifies that WriteToken and WriteValue should not // reformat any JSON string, but keep the formatting verbatim. preserveRawStrings bool // canonicalizeNumbers specifies that WriteToken and WriteValue should // reformat any JSON numbers according to RFC 8785, section 3.2.2.3. canonicalizeNumbers bool // EscapeRune reports whether the provided character should be escaped // as a hexadecimal Unicode codepoint (e.g., \ufffd). // If nil, the shortest and simplest encoding will be used, // which is also the formatting specified by RFC 8785, section 3.2.2.2. EscapeRune func(rune) bool // Indent (if non-empty) specifies that the encoder should emit multiline // output where each element in a JSON object or array begins on a new, // indented line beginning with the indent prefix followed by one or more // copies of indent according to the indentation nesting. // It may only be composed of space or tab characters. Indent string // IndentPrefix is prepended to each line within a JSON object or array. // The purpose of the indent prefix is to encode data that can more easily // be embedded inside other formatted JSON data. // It may only be composed of space or tab characters. // It is ignored if Indent is empty. IndentPrefix string } // Encoder is a streaming encoder from raw JSON tokens and values. // It is used to write a stream of top-level JSON values, // each terminated with a newline character. // // WriteToken and WriteValue calls may be interleaved. // For example, the following JSON value: // // {"name":"value","array":[null,false,true,3.14159],"object":{"k":"v"}} // // can be composed with the following calls (ignoring errors for brevity): // // e.WriteToken(ObjectStart) // { // e.WriteToken(String("name")) // "name" // e.WriteToken(String("value")) // "value" // e.WriteValue(RawValue(`"array"`)) // "array" // e.WriteToken(ArrayStart) // [ // e.WriteToken(Null) // null // e.WriteToken(False) // false // e.WriteValue(RawValue("true")) // true // e.WriteToken(Float(3.14159)) // 3.14159 // e.WriteToken(ArrayEnd) // ] // e.WriteValue(RawValue(`"object"`)) // "object" // e.WriteValue(RawValue(`{"k":"v"}`)) // {"k":"v"} // e.WriteToken(ObjectEnd) // } // // The above is one of many possible sequence of calls and // may not represent the most sensible method to call for any given token/value. // For example, it is probably more common to call WriteToken with a string // for object names. type Encoder struct { state encodeBuffer options EncodeOptions seenPointers seenPointers // only used when marshaling } // encodeBuffer is a buffer split into 2 segments: // // - buf[0:len(buf)] // written (but unflushed) portion of the buffer // - buf[len(buf):cap(buf)] // unused portion of the buffer type encodeBuffer struct { buf []byte // may alias wr if it is a bytes.Buffer // baseOffset is added to len(buf) to obtain the absolute offset // relative to the start of io.Writer stream. baseOffset int64 wr io.Writer // maxValue is the approximate maximum RawValue size passed to WriteValue. maxValue int // unusedCache is the buffer returned by the UnusedBuffer method. unusedCache []byte // bufStats is statistics about buffer utilization. // It is only used with pooled encoders in pools.go. bufStats bufferStatistics } // NewEncoder constructs a new streaming encoder writing to w. func NewEncoder(w io.Writer) *Encoder { return EncodeOptions{}.NewEncoder(w) } // NewEncoder constructs a new streaming encoder writing to w // configured with the provided options. // It flushes the internal buffer when the buffer is sufficiently full or // when a top-level value has been written. // // If w is a bytes.Buffer, then the encoder appends directly into the buffer // without copying the contents from an intermediate buffer. func (o EncodeOptions) NewEncoder(w io.Writer) *Encoder { e := new(Encoder) o.ResetEncoder(e, w) return e } // ResetEncoder resets an encoder such that it is writing afresh to w and // configured with the provided options. func (o EncodeOptions) ResetEncoder(e *Encoder, w io.Writer) { if e == nil { panic("json: invalid nil Encoder") } if w == nil { panic("json: invalid nil io.Writer") } e.reset(nil, w, o) } func (e *Encoder) reset(b []byte, w io.Writer, o EncodeOptions) { if len(o.Indent) > 0 { o.multiline = true if s := trimLeftSpaceTab(o.IndentPrefix); len(s) > 0 { panic("json: invalid character " + quoteRune([]byte(s)) + " in indent prefix") } if s := trimLeftSpaceTab(o.Indent); len(s) > 0 { panic("json: invalid character " + quoteRune([]byte(s)) + " in indent") } } e.state.reset() e.encodeBuffer = encodeBuffer{buf: b, wr: w, bufStats: e.bufStats} e.options = o if bb, ok := w.(*bytes.Buffer); ok && bb != nil { e.buf = bb.Bytes()[bb.Len():] // alias the unused buffer of bb } } // Reset resets an encoder such that it is writing afresh to w but // keeps any pre-existing encoder options. func (e *Encoder) Reset(w io.Writer) { e.options.ResetEncoder(e, w) } // needFlush determines whether to flush at this point. func (e *Encoder) needFlush() bool { // NOTE: This function is carefully written to be inlineable. // Avoid flushing if e.wr is nil since there is no underlying writer. // Flush if less than 25% of the capacity remains. // Flushing at some constant fraction ensures that the buffer stops growing // so long as the largest Token or Value fits within that unused capacity. return e.wr != nil && (e.tokens.depth() == 1 || len(e.buf) > 3*cap(e.buf)/4) } // flush flushes the buffer to the underlying io.Writer. // It may append a trailing newline after the top-level value. func (e *Encoder) flush() error { if e.wr == nil || e.avoidFlush() { return nil } // In streaming mode, always emit a newline after the top-level value. if e.tokens.depth() == 1 && !e.options.omitTopLevelNewline { e.buf = append(e.buf, '\n') } // Inform objectNameStack that we are about to flush the buffer content. e.names.copyQuotedBuffer(e.buf) // Specialize bytes.Buffer for better performance. if bb, ok := e.wr.(*bytes.Buffer); ok { // If e.buf already aliases the internal buffer of bb, // then the Write call simply increments the internal offset, // otherwise Write operates as expected. // See https://go.dev/issue/42986. n, _ := bb.Write(e.buf) // never fails unless bb is nil e.baseOffset += int64(n) // If the internal buffer of bytes.Buffer is too small, // append operations elsewhere in the Encoder may grow the buffer. // This would be semantically correct, but hurts performance. // As such, ensure 25% of the current length is always available // to reduce the probability that other appends must allocate. if avail := bb.Cap() - bb.Len(); avail < bb.Len()/4 { bb.Grow(avail + 1) } e.buf = bb.Bytes()[bb.Len():] // alias the unused buffer of bb return nil } // Flush the internal buffer to the underlying io.Writer. n, err := e.wr.Write(e.buf) e.baseOffset += int64(n) if err != nil { // In the event of an error, preserve the unflushed portion. // Thus, write errors aren't fatal so long as the io.Writer // maintains consistent state after errors. if n > 0 { e.buf = e.buf[:copy(e.buf, e.buf[n:])] } return &ioError{action: "write", err: err} } e.buf = e.buf[:0] // Check whether to grow the buffer. // Note that cap(e.buf) may already exceed maxBufferSize since // an append elsewhere already grew it to store a large token. const maxBufferSize = 4 << 10 const growthSizeFactor = 2 // higher value is faster const growthRateFactor = 2 // higher value is slower // By default, grow if below the maximum buffer size. grow := cap(e.buf) <= maxBufferSize/growthSizeFactor // Growing can be expensive, so only grow // if a sufficient number of bytes have been processed. grow = grow && int64(cap(e.buf)) < e.previousOffsetEnd()/growthRateFactor if grow { e.buf = make([]byte, 0, cap(e.buf)*growthSizeFactor) } return nil } func (e *encodeBuffer) previousOffsetEnd() int64 { return e.baseOffset + int64(len(e.buf)) } func (e *encodeBuffer) unflushedBuffer() []byte { return e.buf } // avoidFlush indicates whether to avoid flushing to ensure there is always // enough in the buffer to unwrite the last object member if it were empty. func (e *Encoder) avoidFlush() bool { switch { case e.tokens.last.length() == 0: // Never flush after ObjectStart or ArrayStart since we don't know yet // if the object or array will end up being empty. return true case e.tokens.last.needObjectValue(): // Never flush before the object value since we don't know yet // if the object value will end up being empty. return true case e.tokens.last.needObjectName() && len(e.buf) >= 2: // Never flush after the object value if it does turn out to be empty. switch string(e.buf[len(e.buf)-2:]) { case `ll`, `""`, `{}`, `[]`: // last two bytes of every empty value return true } } return false } // unwriteEmptyObjectMember unwrites the last object member if it is empty // and reports whether it performed an unwrite operation. func (e *Encoder) unwriteEmptyObjectMember(prevName *string) bool { if last := e.tokens.last; !last.isObject() || !last.needObjectName() || last.length() == 0 { panic("BUG: must be called on an object after writing a value") } // The flushing logic is modified to never flush a trailing empty value. // The encoder never writes trailing whitespace eagerly. b := e.unflushedBuffer() // Detect whether the last value was empty. var n int if len(b) >= 3 { switch string(b[len(b)-2:]) { case "ll": // last two bytes of `null` n = len(`null`) case `""`: // It is possible for a non-empty string to have `""` as a suffix // if the second to the last quote was escaped. if b[len(b)-3] == '\\' { return false // e.g., `"\""` is not empty } n = len(`""`) case `{}`: n = len(`{}`) case `[]`: n = len(`[]`) } } if n == 0 { return false } // Unwrite the value, whitespace, colon, name, whitespace, and comma. b = b[:len(b)-n] b = trimSuffixWhitespace(b) b = trimSuffixByte(b, ':') b = trimSuffixString(b) b = trimSuffixWhitespace(b) b = trimSuffixByte(b, ',') e.buf = b // store back truncated unflushed buffer // Undo state changes. e.tokens.last.decrement() // for object member value e.tokens.last.decrement() // for object member name if !e.options.AllowDuplicateNames { if e.tokens.last.isActiveNamespace() { e.namespaces.last().removeLast() } e.names.clearLast() if prevName != nil { e.names.copyQuotedBuffer(e.buf) // required by objectNameStack.replaceLastUnquotedName e.names.replaceLastUnquotedName(*prevName) } } return true } // unwriteOnlyObjectMemberName unwrites the only object member name // and returns the unquoted name. func (e *Encoder) unwriteOnlyObjectMemberName() string { if last := e.tokens.last; !last.isObject() || last.length() != 1 { panic("BUG: must be called on an object after writing first name") } // Unwrite the name and whitespace. b := trimSuffixString(e.buf) isVerbatim := bytes.IndexByte(e.buf[len(b):], '\\') < 0 name := string(unescapeStringMayCopy(e.buf[len(b):], isVerbatim)) e.buf = trimSuffixWhitespace(b) // Undo state changes. e.tokens.last.decrement() if !e.options.AllowDuplicateNames { if e.tokens.last.isActiveNamespace() { e.namespaces.last().removeLast() } e.names.clearLast() } return name } func trimSuffixWhitespace(b []byte) []byte { // NOTE: The arguments and logic are kept simple to keep this inlineable. n := len(b) - 1 for n >= 0 && (b[n] == ' ' || b[n] == '\t' || b[n] == '\r' || b[n] == '\n') { n-- } return b[:n+1] } func trimSuffixString(b []byte) []byte { // NOTE: The arguments and logic are kept simple to keep this inlineable. if len(b) > 0 && b[len(b)-1] == '"' { b = b[:len(b)-1] } for len(b) >= 2 && !(b[len(b)-1] == '"' && b[len(b)-2] != '\\') { b = b[:len(b)-1] // trim all characters except an unescaped quote } if len(b) > 0 && b[len(b)-1] == '"' { b = b[:len(b)-1] } return b } func hasSuffixByte(b []byte, c byte) bool { // NOTE: The arguments and logic are kept simple to keep this inlineable. return len(b) > 0 && b[len(b)-1] == c } func trimSuffixByte(b []byte, c byte) []byte { // NOTE: The arguments and logic are kept simple to keep this inlineable. if len(b) > 0 && b[len(b)-1] == c { return b[:len(b)-1] } return b } // WriteToken writes the next token and advances the internal write offset. // // The provided token kind must be consistent with the JSON grammar. // For example, it is an error to provide a number when the encoder // is expecting an object name (which is always a string), or // to provide an end object delimiter when the encoder is finishing an array. // If the provided token is invalid, then it reports a SyntacticError and // the internal state remains unchanged. func (e *Encoder) WriteToken(t Token) error { k := t.Kind() b := e.buf // use local variable to avoid mutating e in case of error // Append any delimiters or optional whitespace. b = e.tokens.mayAppendDelim(b, k) if e.options.multiline { b = e.appendWhitespace(b, k) } // Append the token to the output and to the state machine. var err error switch k { case 'n': b = append(b, "null"...) err = e.tokens.appendLiteral() case 'f': b = append(b, "false"...) err = e.tokens.appendLiteral() case 't': b = append(b, "true"...) err = e.tokens.appendLiteral() case '"': n0 := len(b) // offset before calling t.appendString if b, err = t.appendString(b, !e.options.AllowInvalidUTF8, e.options.preserveRawStrings, e.options.EscapeRune); err != nil { break } if !e.options.AllowDuplicateNames && e.tokens.last.needObjectName() { if !e.tokens.last.isValidNamespace() { err = errInvalidNamespace break } if e.tokens.last.isActiveNamespace() && !e.namespaces.last().insertQuoted(b[n0:], false) { err = &SyntacticError{str: "duplicate name " + string(b[n0:]) + " in object"} break } e.names.replaceLastQuotedOffset(n0) // only replace if insertQuoted succeeds } err = e.tokens.appendString() case '0': if b, err = t.appendNumber(b, e.options.canonicalizeNumbers); err != nil { break } err = e.tokens.appendNumber() case '{': b = append(b, '{') if err = e.tokens.pushObject(); err != nil { break } if !e.options.AllowDuplicateNames { e.names.push() e.namespaces.push() } case '}': b = append(b, '}') if err = e.tokens.popObject(); err != nil { break } if !e.options.AllowDuplicateNames { e.names.pop() e.namespaces.pop() } case '[': b = append(b, '[') err = e.tokens.pushArray() case ']': b = append(b, ']') err = e.tokens.popArray() default: return &SyntacticError{str: "invalid json.Token"} } if err != nil { return err } // Finish off the buffer and store it back into e. e.buf = b if e.needFlush() { return e.flush() } return nil } const ( rawIntNumber = -1 rawUintNumber = -2 ) // writeNumber is specialized version of WriteToken, but optimized for numbers. // As a special-case, if bits is -1 or -2, it will treat v as // the raw-encoded bits of an int64 or uint64, respectively. // It is only called from arshal_default.go. func (e *Encoder) writeNumber(v float64, bits int, quote bool) error { b := e.buf // use local variable to avoid mutating e in case of error // Append any delimiters or optional whitespace. b = e.tokens.mayAppendDelim(b, '0') if e.options.multiline { b = e.appendWhitespace(b, '0') } if quote { // Append the value to the output. n0 := len(b) // offset before appending the number b = append(b, '"') switch bits { case rawIntNumber: b = strconv.AppendInt(b, int64(math.Float64bits(v)), 10) case rawUintNumber: b = strconv.AppendUint(b, uint64(math.Float64bits(v)), 10) default: b = appendNumber(b, v, bits) } b = append(b, '"') // Escape the string if necessary. if e.options.EscapeRune != nil { b2 := append(e.unusedCache, b[n0+len(`"`):len(b)-len(`"`)]...) b, _ = appendString(b[:n0], string(b2), false, e.options.EscapeRune) e.unusedCache = b2[:0] } // Update the state machine. if !e.options.AllowDuplicateNames && e.tokens.last.needObjectName() { if !e.tokens.last.isValidNamespace() { return errInvalidNamespace } if e.tokens.last.isActiveNamespace() && !e.namespaces.last().insertQuoted(b[n0:], false) { return &SyntacticError{str: "duplicate name " + string(b[n0:]) + " in object"} } e.names.replaceLastQuotedOffset(n0) // only replace if insertQuoted succeeds } if err := e.tokens.appendString(); err != nil { return err } } else { switch bits { case rawIntNumber: b = strconv.AppendInt(b, int64(math.Float64bits(v)), 10) case rawUintNumber: b = strconv.AppendUint(b, uint64(math.Float64bits(v)), 10) default: b = appendNumber(b, v, bits) } if err := e.tokens.appendNumber(); err != nil { return err } } // Finish off the buffer and store it back into e. e.buf = b if e.needFlush() { return e.flush() } return nil } // WriteValue writes the next raw value and advances the internal write offset. // The Encoder does not simply copy the provided value verbatim, but // parses it to ensure that it is syntactically valid and reformats it // according to how the Encoder is configured to format whitespace and strings. // // The provided value kind must be consistent with the JSON grammar // (see examples on Encoder.WriteToken). If the provided value is invalid, // then it reports a SyntacticError and the internal state remains unchanged. func (e *Encoder) WriteValue(v RawValue) error { e.maxValue |= len(v) // bitwise OR is a fast approximation of max k := v.Kind() b := e.buf // use local variable to avoid mutating e in case of error // Append any delimiters or optional whitespace. b = e.tokens.mayAppendDelim(b, k) if e.options.multiline { b = e.appendWhitespace(b, k) } // Append the value the output. var err error v = v[consumeWhitespace(v):] n0 := len(b) // offset before calling e.reformatValue b, v, err = e.reformatValue(b, v, e.tokens.depth()) if err != nil { return err } v = v[consumeWhitespace(v):] if len(v) > 0 { return newInvalidCharacterError(v[0:], "after top-level value") } // Append the kind to the state machine. switch k { case 'n', 'f', 't': err = e.tokens.appendLiteral() case '"': if !e.options.AllowDuplicateNames && e.tokens.last.needObjectName() { if !e.tokens.last.isValidNamespace() { err = errInvalidNamespace break } if e.tokens.last.isActiveNamespace() && !e.namespaces.last().insertQuoted(b[n0:], false) { err = &SyntacticError{str: "duplicate name " + string(b[n0:]) + " in object"} break } e.names.replaceLastQuotedOffset(n0) // only replace if insertQuoted succeeds } err = e.tokens.appendString() case '0': err = e.tokens.appendNumber() case '{': if err = e.tokens.pushObject(); err != nil { break } if err = e.tokens.popObject(); err != nil { panic("BUG: popObject should never fail immediately after pushObject: " + err.Error()) } case '[': if err = e.tokens.pushArray(); err != nil { break } if err = e.tokens.popArray(); err != nil { panic("BUG: popArray should never fail immediately after pushArray: " + err.Error()) } } if err != nil { return err } // Finish off the buffer and store it back into e. e.buf = b if e.needFlush() { return e.flush() } return nil } // appendWhitespace appends whitespace that immediately precedes the next token. func (e *Encoder) appendWhitespace(b []byte, next Kind) []byte { if e.tokens.needDelim(next) == ':' { return append(b, ' ') } else { return e.appendIndent(b, e.tokens.needIndent(next)) } } // appendIndent appends the appropriate number of indentation characters // for the current nested level, n. func (e *Encoder) appendIndent(b []byte, n int) []byte { if n == 0 { return b } b = append(b, '\n') b = append(b, e.options.IndentPrefix...) for ; n > 1; n-- { b = append(b, e.options.Indent...) } return b } // reformatValue parses a JSON value from the start of src and // appends it to the end of dst, reformatting whitespace and strings as needed. // It returns the updated versions of dst and src. func (e *Encoder) reformatValue(dst []byte, src RawValue, depth int) ([]byte, RawValue, error) { // TODO: Should this update valueFlags as input? if len(src) == 0 { return dst, src, io.ErrUnexpectedEOF } var n int var err error switch k := Kind(src[0]).normalize(); k { case 'n': if n = consumeNull(src); n == 0 { n, err = consumeLiteral(src, "null") } case 'f': if n = consumeFalse(src); n == 0 { n, err = consumeLiteral(src, "false") } case 't': if n = consumeTrue(src); n == 0 { n, err = consumeLiteral(src, "true") } case '"': if n := consumeSimpleString(src); n > 0 && e.options.EscapeRune == nil { dst, src = append(dst, src[:n]...), src[n:] // copy simple strings verbatim return dst, src, nil } return reformatString(dst, src, !e.options.AllowInvalidUTF8, e.options.preserveRawStrings, e.options.EscapeRune) case '0': if n := consumeSimpleNumber(src); n > 0 && !e.options.canonicalizeNumbers { dst, src = append(dst, src[:n]...), src[n:] // copy simple numbers verbatim return dst, src, nil } return reformatNumber(dst, src, e.options.canonicalizeNumbers) case '{': return e.reformatObject(dst, src, depth) case '[': return e.reformatArray(dst, src, depth) default: return dst, src, newInvalidCharacterError(src, "at start of value") } if err != nil { return dst, src, err } dst, src = append(dst, src[:n]...), src[n:] return dst, src, nil } // reformatObject parses a JSON object from the start of src and // appends it to the end of src, reformatting whitespace and strings as needed. // It returns the updated versions of dst and src. func (e *Encoder) reformatObject(dst []byte, src RawValue, depth int) ([]byte, RawValue, error) { // Append object start. if src[0] != '{' { panic("BUG: reformatObject must be called with a buffer that starts with '{'") } dst, src = append(dst, '{'), src[1:] // Append (possible) object end. src = src[consumeWhitespace(src):] if len(src) == 0 { return dst, src, io.ErrUnexpectedEOF } if src[0] == '}' { dst, src = append(dst, '}'), src[1:] return dst, src, nil } var err error var names *objectNamespace if !e.options.AllowDuplicateNames { e.namespaces.push() defer e.namespaces.pop() names = e.namespaces.last() } depth++ for { // Append optional newline and indentation. if e.options.multiline { dst = e.appendIndent(dst, depth) } // Append object name. src = src[consumeWhitespace(src):] if len(src) == 0 { return dst, src, io.ErrUnexpectedEOF } n0 := len(dst) // offset before calling reformatString n := consumeSimpleString(src) if n > 0 && e.options.EscapeRune == nil { dst, src = append(dst, src[:n]...), src[n:] // copy simple strings verbatim } else { dst, src, err = reformatString(dst, src, !e.options.AllowInvalidUTF8, e.options.preserveRawStrings, e.options.EscapeRune) } if err != nil { return dst, src, err } if !e.options.AllowDuplicateNames && !names.insertQuoted(dst[n0:], false) { return dst, src, &SyntacticError{str: "duplicate name " + string(dst[n0:]) + " in object"} } // Append colon. src = src[consumeWhitespace(src):] if len(src) == 0 { return dst, src, io.ErrUnexpectedEOF } if src[0] != ':' { return dst, src, newInvalidCharacterError(src, "after object name (expecting ':')") } dst, src = append(dst, ':'), src[1:] if e.options.multiline { dst = append(dst, ' ') } // Append object value. src = src[consumeWhitespace(src):] if len(src) == 0 { return dst, src, io.ErrUnexpectedEOF } dst, src, err = e.reformatValue(dst, src, depth) if err != nil { return dst, src, err } // Append comma or object end. src = src[consumeWhitespace(src):] if len(src) == 0 { return dst, src, io.ErrUnexpectedEOF } switch src[0] { case ',': dst, src = append(dst, ','), src[1:] continue case '}': if e.options.multiline { dst = e.appendIndent(dst, depth-1) } dst, src = append(dst, '}'), src[1:] return dst, src, nil default: return dst, src, newInvalidCharacterError(src, "after object value (expecting ',' or '}')") } } } // reformatArray parses a JSON array from the start of src and // appends it to the end of dst, reformatting whitespace and strings as needed. // It returns the updated versions of dst and src. func (e *Encoder) reformatArray(dst []byte, src RawValue, depth int) ([]byte, RawValue, error) { // Append array start. if src[0] != '[' { panic("BUG: reformatArray must be called with a buffer that starts with '['") } dst, src = append(dst, '['), src[1:] // Append (possible) array end. src = src[consumeWhitespace(src):] if len(src) == 0 { return dst, src, io.ErrUnexpectedEOF } if src[0] == ']' { dst, src = append(dst, ']'), src[1:] return dst, src, nil } var err error depth++ for { // Append optional newline and indentation. if e.options.multiline { dst = e.appendIndent(dst, depth) } // Append array value. src = src[consumeWhitespace(src):] if len(src) == 0 { return dst, src, io.ErrUnexpectedEOF } dst, src, err = e.reformatValue(dst, src, depth) if err != nil { return dst, src, err } // Append comma or array end. src = src[consumeWhitespace(src):] if len(src) == 0 { return dst, src, io.ErrUnexpectedEOF } switch src[0] { case ',': dst, src = append(dst, ','), src[1:] continue case ']': if e.options.multiline { dst = e.appendIndent(dst, depth-1) } dst, src = append(dst, ']'), src[1:] return dst, src, nil default: return dst, src, newInvalidCharacterError(src, "after array value (expecting ',' or ']')") } } } // OutputOffset returns the current output byte offset. It gives the location // of the next byte immediately after the most recently written token or value. // The number of bytes actually written to the underlying io.Writer may be less // than this offset due to internal buffering effects. func (e *Encoder) OutputOffset() int64 { return e.previousOffsetEnd() } // UnusedBuffer returns a zero-length buffer with a possible non-zero capacity. // This buffer is intended to be used to populate a RawValue // being passed to an immediately succeeding WriteValue call. // // Example usage: // // b := d.UnusedBuffer() // b = append(b, '"') // b = appendString(b, v) // append the string formatting of v // b = append(b, '"') // ... := d.WriteValue(b) // // It is the user's responsibility to ensure that the value is valid JSON. func (e *Encoder) UnusedBuffer() []byte { // NOTE: We don't return e.buf[len(e.buf):cap(e.buf)] since WriteValue would // need to take special care to avoid mangling the data while reformatting. // WriteValue can't easily identify whether the input RawValue aliases e.buf // without using unsafe.Pointer. Thus, we just return a different buffer. // Should this ever alias e.buf, we need to consider how it operates with // the specialized performance optimization for bytes.Buffer. n := 1 << bits.Len(uint(e.maxValue|63)) // fast approximation for max length if cap(e.unusedCache) < n { e.unusedCache = make([]byte, 0, n) } return e.unusedCache } // StackDepth returns the depth of the state machine for written JSON data. // Each level on the stack represents a nested JSON object or array. // It is incremented whenever an ObjectStart or ArrayStart token is encountered // and decremented whenever an ObjectEnd or ArrayEnd token is encountered. // The depth is zero-indexed, where zero represents the top-level JSON value. func (e *Encoder) StackDepth() int { // NOTE: Keep in sync with Decoder.StackDepth. return e.tokens.depth() - 1 } // StackIndex returns information about the specified stack level. // It must be a number between 0 and StackDepth, inclusive. // For each level, it reports the kind: // // - 0 for a level of zero, // - '{' for a level representing a JSON object, and // - '[' for a level representing a JSON array. // // It also reports the length of that JSON object or array. // Each name and value in a JSON object is counted separately, // so the effective number of members would be half the length. // A complete JSON object must have an even length. func (e *Encoder) StackIndex(i int) (Kind, int) { // NOTE: Keep in sync with Decoder.StackIndex. switch s := e.tokens.index(i); { case i > 0 && s.isObject(): return '{', s.length() case i > 0 && s.isArray(): return '[', s.length() default: return 0, s.length() } } // StackPointer returns a JSON Pointer (RFC 6901) to the most recently written value. // Object names are only present if AllowDuplicateNames is false, otherwise // object members are represented using their index within the object. func (e *Encoder) StackPointer() string { e.names.copyQuotedBuffer(e.buf) return string(e.appendStackPointer(nil)) } // appendString appends src to dst as a JSON string per RFC 7159, section 7. // // If validateUTF8 is specified, this rejects input that contains invalid UTF-8 // otherwise invalid bytes are replaced with the Unicode replacement character. // If escapeRune is provided, it specifies which runes to escape using // hexadecimal sequences. If nil, the shortest representable form is used, // which is also the canonical form for strings (RFC 8785, section 3.2.2.2). // // Note that this API allows full control over the formatting of strings // except for whether a forward solidus '/' may be formatted as '\/' and // the casing of hexadecimal Unicode escape sequences. func appendString(dst []byte, src string, validateUTF8 bool, escapeRune func(rune) bool) ([]byte, error) { appendEscapedASCII := func(dst []byte, c byte) []byte { switch c { case '"', '\\': dst = append(dst, '\\', c) case '\b': dst = append(dst, "\\b"...) case '\f': dst = append(dst, "\\f"...) case '\n': dst = append(dst, "\\n"...) case '\r': dst = append(dst, "\\r"...) case '\t': dst = append(dst, "\\t"...) default: dst = append(dst, "\\u"...) dst = appendHexUint16(dst, uint16(c)) } return dst } appendEscapedUnicode := func(dst []byte, r rune) []byte { if r1, r2 := utf16.EncodeRune(r); r1 != '\ufffd' && r2 != '\ufffd' { dst = append(dst, "\\u"...) dst = appendHexUint16(dst, uint16(r1)) dst = append(dst, "\\u"...) dst = appendHexUint16(dst, uint16(r2)) } else { dst = append(dst, "\\u"...) dst = appendHexUint16(dst, uint16(r)) } return dst } // Optimize for when escapeRune is nil. if escapeRune == nil { var i, n int dst = append(dst, '"') for uint(len(src)) > uint(n) { // Handle single-byte ASCII. if c := src[n]; c < utf8.RuneSelf { n++ if c < ' ' || c == '"' || c == '\\' { dst = append(dst, src[i:n-1]...) dst = appendEscapedASCII(dst, c) i = n } continue } // Handle multi-byte Unicode. _, rn := utf8.DecodeRuneInString(src[n:])
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
true
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_inlined.go
vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/arshal_inlined.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" "errors" "reflect" ) // This package supports "inlining" a Go struct field, where the contents // of the serialized field (which must be a JSON object) are treated as if // they are part of the parent Go struct (which represents a JSON object). // // Generally, inlined fields are of a Go struct type, where the fields of the // nested struct are virtually hoisted up to the parent struct using rules // similar to how Go embedding works (but operating within the JSON namespace). // // However, inlined fields may also be of a Go map type with a string key // or a RawValue. Such inlined fields are called "fallback" fields since they // represent any arbitrary JSON object member. Explicitly named fields take // precedence over the inlined fallback. Only one inlined fallback is allowed. var rawValueType = reflect.TypeOf((*RawValue)(nil)).Elem() // marshalInlinedFallbackAll marshals all the members in an inlined fallback. func marshalInlinedFallbackAll(mo MarshalOptions, enc *Encoder, va addressableValue, f *structField, insertUnquotedName func([]byte) bool) error { 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() { return nil // implies a nil inlined field } } v = v.indirect(false) if !v.IsValid() { return nil } if v.Type() == rawValueType { b := v.Interface().(RawValue) if len(b) == 0 { // TODO: Should this be nil? What if it were all whitespace? return nil } dec := getBufferedDecoder(b, DecodeOptions{AllowDuplicateNames: true, AllowInvalidUTF8: true}) defer putBufferedDecoder(dec) tok, err := dec.ReadToken() if err != nil { return &SemanticError{action: "marshal", GoType: rawValueType, Err: err} } if tok.Kind() != '{' { err := errors.New("inlined raw value must be a JSON object") return &SemanticError{action: "marshal", JSONKind: tok.Kind(), GoType: rawValueType, Err: err} } for dec.PeekKind() != '}' { // Parse the JSON object name. var flags valueFlags val, err := dec.readValue(&flags) if err != nil { return &SemanticError{action: "marshal", GoType: rawValueType, Err: err} } if insertUnquotedName != nil { name := unescapeStringMayCopy(val, flags.isVerbatim()) if !insertUnquotedName(name) { return &SyntacticError{str: "duplicate name " + string(val) + " in object"} } } if err := enc.WriteValue(val); err != nil { return err } // Parse the JSON object value. val, err = dec.readValue(&flags) if err != nil { return &SemanticError{action: "marshal", GoType: rawValueType, Err: err} } if err := enc.WriteValue(val); err != nil { return err } } if _, err := dec.ReadToken(); err != nil { return &SemanticError{action: "marshal", GoType: rawValueType, Err: err} } if err := dec.checkEOF(); err != nil { return &SemanticError{action: "marshal", GoType: rawValueType, Err: err} } return nil } else { m := v // must be a map[string]V n := m.Len() if n == 0 { return nil } mk := newAddressableValue(stringType) mv := newAddressableValue(m.Type().Elem()) marshalKey := func(mk addressableValue) error { b, err := appendString(enc.UnusedBuffer(), mk.String(), !enc.options.AllowInvalidUTF8, nil) if err != nil { return err } if insertUnquotedName != nil { isVerbatim := bytes.IndexByte(b, '\\') < 0 name := unescapeStringMayCopy(b, isVerbatim) if !insertUnquotedName(name) { return &SyntacticError{str: "duplicate name " + string(b) + " in object"} } } return enc.WriteValue(b) } marshalVal := f.fncs.marshal if mo.Marshalers != nil { marshalVal, _ = mo.Marshalers.lookup(marshalVal, mv.Type()) } if !mo.Deterministic || n <= 1 { for iter := m.MapRange(); iter.Next(); { mk.SetIterKey(iter) if err := marshalKey(mk); err != nil { return err } mv.Set(iter.Value()) if err := marshalVal(mo, enc, mv); err != nil { return err } } } else { names := getStrings(n) for i, iter := 0, m.Value.MapRange(); i < n && iter.Next(); i++ { mk.SetIterKey(iter) (*names)[i] = mk.String() } names.Sort() for _, name := range *names { mk.SetString(name) if err := marshalKey(mk); err != nil { return err } // TODO(https://go.dev/issue/57061): Use mv.SetMapIndexOf. mv.Set(m.MapIndex(mk.Value)) if err := marshalVal(mo, enc, mv); err != nil { return err } } putStrings(names) } return nil } } // unmarshalInlinedFallbackNext unmarshals only the next member in an inlined fallback. func unmarshalInlinedFallbackNext(uo UnmarshalOptions, dec *Decoder, va addressableValue, f *structField, quotedName, unquotedName []byte) error { v := addressableValue{va.Field(f.index[0])} // addressable if struct value is addressable if len(f.index) > 1 { v = v.fieldByIndex(f.index[1:], true) } v = v.indirect(true) if v.Type() == rawValueType { b := v.Addr().Interface().(*RawValue) if len(*b) == 0 { // TODO: Should this be nil? What if it were all whitespace? *b = append(*b, '{') } else { *b = trimSuffixWhitespace(*b) if hasSuffixByte(*b, '}') { // TODO: When merging into an object for the first time, // should we verify that it is valid? *b = trimSuffixByte(*b, '}') *b = trimSuffixWhitespace(*b) if !hasSuffixByte(*b, ',') && !hasSuffixByte(*b, '{') { *b = append(*b, ',') } } else { err := errors.New("inlined raw value must be a JSON object") return &SemanticError{action: "unmarshal", GoType: rawValueType, Err: err} } } *b = append(*b, quotedName...) *b = append(*b, ':') rawValue, err := dec.ReadValue() if err != nil { return err } *b = append(*b, rawValue...) *b = append(*b, '}') return nil } else { name := string(unquotedName) // TODO: Intern this? m := v // must be a map[string]V if m.IsNil() { m.Set(reflect.MakeMap(m.Type())) } mk := reflect.ValueOf(name) mv := newAddressableValue(v.Type().Elem()) // TODO: Cache across calls? if v2 := m.MapIndex(mk); v2.IsValid() { mv.Set(v2) } unmarshal := f.fncs.unmarshal if uo.Unmarshalers != nil { unmarshal, _ = uo.Unmarshalers.lookup(unmarshal, mv.Type()) } err := unmarshal(uo, dec, mv) m.SetMapIndex(mk, mv.Value) if err != nil { return err } return nil } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/value.go
vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/value.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" "errors" "io" "sort" "sync" "unicode/utf16" "unicode/utf8" ) // NOTE: RawValue is analogous to v1 json.RawMessage. // RawValue represents a single raw JSON value, which may be one of the following: // - a JSON literal (i.e., null, true, or false) // - a JSON string (e.g., "hello, world!") // - a JSON number (e.g., 123.456) // - an entire JSON object (e.g., {"fizz":"buzz"} ) // - an entire JSON array (e.g., [1,2,3] ) // // RawValue can represent entire array or object values, while Token cannot. // RawValue may contain leading and/or trailing whitespace. type RawValue []byte // Clone returns a copy of v. func (v RawValue) Clone() RawValue { if v == nil { return nil } return append(RawValue{}, v...) } // String returns the string formatting of v. func (v RawValue) String() string { if v == nil { return "null" } return string(v) } // IsValid reports whether the raw JSON value is syntactically valid // according to RFC 7493. // // It verifies whether the input is properly encoded as UTF-8, // that escape sequences within strings decode to valid Unicode codepoints, and // that all names in each object are unique. // It does not verify whether numbers are representable within the limits // of any common numeric type (e.g., float64, int64, or uint64). func (v RawValue) IsValid() bool { d := getBufferedDecoder(v, DecodeOptions{}) defer putBufferedDecoder(d) _, errVal := d.ReadValue() _, errEOF := d.ReadToken() return errVal == nil && errEOF == io.EOF } // Compact removes all whitespace from the raw JSON value. // // It does not reformat JSON strings to use any other representation. // It is guaranteed to succeed if the input is valid. // If the value is already compacted, then the buffer is not mutated. func (v *RawValue) Compact() error { return v.reformat(false, false, "", "") } // Indent reformats the whitespace in the raw JSON value so that each element // in a JSON object or array begins on a new, indented line beginning with // prefix followed by one or more copies of indent according to the nesting. // The value does not begin with the prefix nor any indention, // to make it easier to embed inside other formatted JSON data. // // It does not reformat JSON strings to use any other representation. // It is guaranteed to succeed if the input is valid. // If the value is already indented properly, then the buffer is not mutated. func (v *RawValue) Indent(prefix, indent string) error { return v.reformat(false, true, prefix, indent) } // Canonicalize canonicalizes the raw JSON value according to the // JSON Canonicalization Scheme (JCS) as defined by RFC 8785 // where it produces a stable representation of a JSON value. // // The output stability is dependent on the stability of the application data // (see RFC 8785, Appendix E). It cannot produce stable output from // fundamentally unstable input. For example, if the JSON value // contains ephemeral data (e.g., a frequently changing timestamp), // then the value is still unstable regardless of whether this is called. // // Note that JCS treats all JSON numbers as IEEE 754 double precision numbers. // Any numbers with precision beyond what is representable by that form // will lose their precision when canonicalized. For example, integer values // beyond ±2⁵³ will lose their precision. It is recommended that // int64 and uint64 data types be represented as a JSON string. // // It is guaranteed to succeed if the input is valid. // If the value is already canonicalized, then the buffer is not mutated. func (v *RawValue) Canonicalize() error { return v.reformat(true, false, "", "") } // TODO: Instead of implementing the v1 Marshaler/Unmarshaler, // consider implementing the v2 versions instead. // MarshalJSON returns v as the JSON encoding of v. // It returns the stored value as the raw JSON output without any validation. // If v is nil, then this returns a JSON null. func (v RawValue) MarshalJSON() ([]byte, error) { // NOTE: This matches the behavior of v1 json.RawMessage.MarshalJSON. if v == nil { return []byte("null"), nil } return v, nil } // UnmarshalJSON sets v as the JSON encoding of b. // It stores a copy of the provided raw JSON input without any validation. func (v *RawValue) UnmarshalJSON(b []byte) error { // NOTE: This matches the behavior of v1 json.RawMessage.UnmarshalJSON. if v == nil { return errors.New("json.RawValue: UnmarshalJSON on nil pointer") } *v = append((*v)[:0], b...) return nil } // Kind returns the starting token kind. // For a valid value, this will never include '}' or ']'. func (v RawValue) Kind() Kind { if v := v[consumeWhitespace(v):]; len(v) > 0 { return Kind(v[0]).normalize() } return invalidKind } func (v *RawValue) reformat(canonical, multiline bool, prefix, indent string) error { var eo EncodeOptions if canonical { eo.AllowInvalidUTF8 = false // per RFC 8785, section 3.2.4 eo.AllowDuplicateNames = false // per RFC 8785, section 3.1 eo.canonicalizeNumbers = true // per RFC 8785, section 3.2.2.3 eo.EscapeRune = nil // per RFC 8785, section 3.2.2.2 eo.multiline = false // per RFC 8785, section 3.2.1 } else { if s := trimLeftSpaceTab(prefix); len(s) > 0 { panic("json: invalid character " + quoteRune([]byte(s)) + " in indent prefix") } if s := trimLeftSpaceTab(indent); len(s) > 0 { panic("json: invalid character " + quoteRune([]byte(s)) + " in indent") } eo.AllowInvalidUTF8 = true eo.AllowDuplicateNames = true eo.preserveRawStrings = true eo.multiline = multiline // in case indent is empty eo.IndentPrefix = prefix eo.Indent = indent } eo.omitTopLevelNewline = true // Write the entire value to reformat all tokens and whitespace. e := getBufferedEncoder(eo) defer putBufferedEncoder(e) if err := e.WriteValue(*v); err != nil { return err } // For canonical output, we may need to reorder object members. if canonical { // Obtain a buffered encoder just to use its internal buffer as // a scratch buffer in reorderObjects for reordering object members. e2 := getBufferedEncoder(EncodeOptions{}) defer putBufferedEncoder(e2) // Disable redundant checks performed earlier during encoding. d := getBufferedDecoder(e.buf, DecodeOptions{AllowInvalidUTF8: true, AllowDuplicateNames: true}) defer putBufferedDecoder(d) reorderObjects(d, &e2.buf) // per RFC 8785, section 3.2.3 } // Store the result back into the value if different. if !bytes.Equal(*v, e.buf) { *v = append((*v)[:0], e.buf...) } return nil } func trimLeftSpaceTab(s string) string { for i, r := range s { switch r { case ' ', '\t': default: return s[i:] } } return "" } type memberName struct { // name is the unescaped name. name []byte // before and after are byte offsets into Decoder.buf that represents // the entire name/value pair. It may contain leading commas. before, after int64 } var memberNamePool = sync.Pool{New: func() any { return new(memberNames) }} func getMemberNames() *memberNames { ns := memberNamePool.Get().(*memberNames) *ns = (*ns)[:0] return ns } func putMemberNames(ns *memberNames) { if cap(*ns) < 1<<10 { for i := range *ns { (*ns)[i] = memberName{} // avoid pinning name } memberNamePool.Put(ns) } } type memberNames []memberName func (m *memberNames) Len() int { return len(*m) } func (m *memberNames) Less(i, j int) bool { return lessUTF16((*m)[i].name, (*m)[j].name) } func (m *memberNames) Swap(i, j int) { (*m)[i], (*m)[j] = (*m)[j], (*m)[i] } // reorderObjects recursively reorders all object members in place // according to the ordering specified in RFC 8785, section 3.2.3. // // Pre-conditions: // - The value is valid (i.e., no decoder errors should ever occur). // - The value is compact (i.e., no whitespace is present). // - Initial call is provided a Decoder reading from the start of v. // // Post-conditions: // - Exactly one JSON value is read from the Decoder. // - All fully-parsed JSON objects are reordered by directly moving // the members in the value buffer. // // The runtime is approximately O(n·log(n)) + O(m·log(m)), // where n is len(v) and m is the total number of object members. func reorderObjects(d *Decoder, scratch *[]byte) { switch tok, _ := d.ReadToken(); tok.Kind() { case '{': // Iterate and collect the name and offsets for every object member. members := getMemberNames() defer putMemberNames(members) var prevName []byte isSorted := true beforeBody := d.InputOffset() // offset after '{' for d.PeekKind() != '}' { beforeName := d.InputOffset() var flags valueFlags name, _ := d.readValue(&flags) name = unescapeStringMayCopy(name, flags.isVerbatim()) reorderObjects(d, scratch) afterValue := d.InputOffset() if isSorted && len(*members) > 0 { isSorted = lessUTF16(prevName, []byte(name)) } *members = append(*members, memberName{name, beforeName, afterValue}) prevName = name } afterBody := d.InputOffset() // offset before '}' d.ReadToken() // Sort the members; return early if it's already sorted. if isSorted { return } // TODO(https://go.dev/issue/47619): Use slices.Sort. sort.Sort(members) // Append the reordered members to a new buffer, // then copy the reordered members back over the original members. // Avoid swapping in place since each member may be a different size // where moving a member over a smaller member may corrupt the data // for subsequent members before they have been moved. // // The following invariant must hold: // sum([m.after-m.before for m in members]) == afterBody-beforeBody sorted := (*scratch)[:0] for i, member := range *members { if d.buf[member.before] == ',' { member.before++ // trim leading comma } sorted = append(sorted, d.buf[member.before:member.after]...) if i < len(*members)-1 { sorted = append(sorted, ',') // append trailing comma } } if int(afterBody-beforeBody) != len(sorted) { panic("BUG: length invariant violated") } copy(d.buf[beforeBody:afterBody], sorted) // Update scratch buffer to the largest amount ever used. if len(sorted) > len(*scratch) { *scratch = sorted } case '[': for d.PeekKind() != ']' { reorderObjects(d, scratch) } d.ReadToken() } } // lessUTF16 reports whether x is lexicographically less than y according // to the UTF-16 codepoints of the UTF-8 encoded input strings. // This implements the ordering specified in RFC 8785, section 3.2.3. // The inputs must be valid UTF-8, otherwise this may panic. func lessUTF16[Bytes []byte | string](x, y Bytes) bool { // NOTE: This is an optimized, allocation-free implementation // of lessUTF16Simple in fuzz_test.go. FuzzLessUTF16 verifies that the // two implementations agree on the result of comparing any two strings. isUTF16Self := func(r rune) bool { return ('\u0000' <= r && r <= '\uD7FF') || ('\uE000' <= r && r <= '\uFFFF') } var invalidUTF8 bool x0, y0 := x, y for { if len(x) == 0 || len(y) == 0 { if len(x) == len(y) && invalidUTF8 { return string(x0) < string(y0) } return len(x) < len(y) } // ASCII fast-path. if x[0] < utf8.RuneSelf || y[0] < utf8.RuneSelf { if x[0] != y[0] { return x[0] < y[0] } x, y = x[1:], y[1:] continue } // Decode next pair of runes as UTF-8. // TODO(https://go.dev/issue/56948): Use a generic implementation // of utf8.DecodeRune, or rely on a compiler optimization to statically // hide the cost of a type switch (https://go.dev/issue/57072). var rx, ry rune var nx, ny int switch any(x).(type) { case string: rx, nx = utf8.DecodeRuneInString(string(x)) ry, ny = utf8.DecodeRuneInString(string(y)) case []byte: rx, nx = utf8.DecodeRune([]byte(x)) ry, ny = utf8.DecodeRune([]byte(y)) } selfx := isUTF16Self(rx) selfy := isUTF16Self(ry) switch { // The x rune is a single UTF-16 codepoint, while // the y rune is a surrogate pair of UTF-16 codepoints. case selfx && !selfy: ry, _ = utf16.EncodeRune(ry) // The y rune is a single UTF-16 codepoint, while // the x rune is a surrogate pair of UTF-16 codepoints. case selfy && !selfx: rx, _ = utf16.EncodeRune(rx) } if rx != ry { return rx < ry } invalidUTF8 = invalidUTF8 || (rx == utf8.RuneError && nx == 1) || (ry == utf8.RuneError && ny == 1) x, y = x[nx:], y[ny:] } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/pools.go
vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/pools.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" "io" "math/bits" "sort" "sync" ) // TODO(https://go.dev/issue/47657): Use sync.PoolOf. var ( // This owns the internal buffer since there is no io.Writer to output to. // Since the buffer can get arbitrarily large in normal usage, // there is statistical tracking logic to determine whether to recycle // the internal buffer or not based on a history of utilization. bufferedEncoderPool = &sync.Pool{New: func() any { return new(Encoder) }} // This owns the internal buffer, but it is only used to temporarily store // buffered JSON before flushing it to the underlying io.Writer. // In a sufficiently efficient streaming mode, we do not expect the buffer // to grow arbitrarily large. Thus, we avoid recycling large buffers. streamingEncoderPool = &sync.Pool{New: func() any { return new(Encoder) }} // This does not own the internal buffer since // it is taken directly from the provided bytes.Buffer. bytesBufferEncoderPool = &sync.Pool{New: func() any { return new(Encoder) }} ) // bufferStatistics is statistics to track buffer utilization. // It is used to determine whether to recycle a buffer or not // to avoid https://go.dev/issue/23199. type bufferStatistics struct { strikes int // number of times the buffer was under-utilized prevLen int // length of previous buffer } func getBufferedEncoder(o EncodeOptions) *Encoder { e := bufferedEncoderPool.Get().(*Encoder) if e.buf == nil { // Round up to nearest 2ⁿ to make best use of malloc size classes. // See runtime/sizeclasses.go on Go1.15. // Logical OR with 63 to ensure 64 as the minimum buffer size. n := 1 << bits.Len(uint(e.bufStats.prevLen|63)) e.buf = make([]byte, 0, n) } e.reset(e.buf[:0], nil, o) return e } func putBufferedEncoder(e *Encoder) { // Recycle large buffers only if sufficiently utilized. // If a buffer is under-utilized enough times sequentially, // then it is discarded, ensuring that a single large buffer // won't be kept alive by a continuous stream of small usages. // // The worst case utilization is computed as: // MIN_UTILIZATION_THRESHOLD / (1 + MAX_NUM_STRIKES) // // For the constants chosen below, this is (25%)/(1+4) ⇒ 5%. // This may seem low, but it ensures a lower bound on // the absolute worst-case utilization. Without this check, // this would be theoretically 0%, which is infinitely worse. // // See https://go.dev/issue/27735. switch { case cap(e.buf) <= 4<<10: // always recycle buffers smaller than 4KiB e.bufStats.strikes = 0 case cap(e.buf)/4 <= len(e.buf): // at least 25% utilization e.bufStats.strikes = 0 case e.bufStats.strikes < 4: // at most 4 strikes e.bufStats.strikes++ default: // discard the buffer; too large and too often under-utilized e.bufStats.strikes = 0 e.bufStats.prevLen = len(e.buf) // heuristic for size to allocate next time e.buf = nil } bufferedEncoderPool.Put(e) } func getStreamingEncoder(w io.Writer, o EncodeOptions) *Encoder { if _, ok := w.(*bytes.Buffer); ok { e := bytesBufferEncoderPool.Get().(*Encoder) e.reset(nil, w, o) // buffer taken from bytes.Buffer return e } else { e := streamingEncoderPool.Get().(*Encoder) e.reset(e.buf[:0], w, o) // preserve existing buffer return e } } func putStreamingEncoder(e *Encoder) { if _, ok := e.wr.(*bytes.Buffer); ok { bytesBufferEncoderPool.Put(e) } else { if cap(e.buf) > 64<<10 { e.buf = nil // avoid pinning arbitrarily large amounts of memory } streamingEncoderPool.Put(e) } } var ( // This does not own the internal buffer since it is externally provided. bufferedDecoderPool = &sync.Pool{New: func() any { return new(Decoder) }} // This owns the internal buffer, but it is only used to temporarily store // buffered JSON fetched from the underlying io.Reader. // In a sufficiently efficient streaming mode, we do not expect the buffer // to grow arbitrarily large. Thus, we avoid recycling large buffers. streamingDecoderPool = &sync.Pool{New: func() any { return new(Decoder) }} // This does not own the internal buffer since // it is taken directly from the provided bytes.Buffer. bytesBufferDecoderPool = bufferedDecoderPool ) func getBufferedDecoder(b []byte, o DecodeOptions) *Decoder { d := bufferedDecoderPool.Get().(*Decoder) d.reset(b, nil, o) return d } func putBufferedDecoder(d *Decoder) { bufferedDecoderPool.Put(d) } func getStreamingDecoder(r io.Reader, o DecodeOptions) *Decoder { if _, ok := r.(*bytes.Buffer); ok { d := bytesBufferDecoderPool.Get().(*Decoder) d.reset(nil, r, o) // buffer taken from bytes.Buffer return d } else { d := streamingDecoderPool.Get().(*Decoder) d.reset(d.buf[:0], r, o) // preserve existing buffer return d } } func putStreamingDecoder(d *Decoder) { if _, ok := d.rd.(*bytes.Buffer); ok { bytesBufferDecoderPool.Put(d) } else { if cap(d.buf) > 64<<10 { d.buf = nil // avoid pinning arbitrarily large amounts of memory } streamingDecoderPool.Put(d) } } var stringsPools = &sync.Pool{New: func() any { return new(stringSlice) }} type stringSlice []string // getStrings returns a non-nil pointer to a slice with length n. func getStrings(n int) *stringSlice { s := stringsPools.Get().(*stringSlice) if cap(*s) < n { *s = make([]string, n) } *s = (*s)[:n] return s } func putStrings(s *stringSlice) { if cap(*s) > 1<<10 { *s = nil // avoid pinning arbitrarily large amounts of memory } stringsPools.Put(s) } // Sort sorts the string slice according to RFC 8785, section 3.2.3. func (ss *stringSlice) Sort() { // TODO(https://go.dev/issue/47619): Use slices.SortFunc instead. sort.Sort(ss) } func (ss *stringSlice) Len() int { return len(*ss) } func (ss *stringSlice) Less(i, j int) bool { return lessUTF16((*ss)[i], (*ss)[j]) } func (ss *stringSlice) Swap(i, j int) { (*ss)[i], (*ss)[j] = (*ss)[j], (*ss)[i] }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/doc.go
vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/doc.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 implements serialization of JSON // as specified in RFC 4627, RFC 7159, RFC 7493, RFC 8259, and RFC 8785. // JSON is a simple data interchange format that can represent // primitive data types such as booleans, strings, and numbers, // in addition to structured data types such as objects and arrays. // // # Terminology // // This package uses the terms "encode" and "decode" for syntactic functionality // that is concerned with processing JSON based on its grammar, and // uses the terms "marshal" and "unmarshal" for semantic functionality // that determines the meaning of JSON values as Go values and vice-versa. // It aims to provide a clear distinction between functionality that // is purely concerned with encoding versus that of marshaling. // For example, one can directly encode a stream of JSON tokens without // needing to marshal a concrete Go value representing them. // Similarly, one can decode a stream of JSON tokens without // needing to unmarshal them into a concrete Go value. // // This package uses JSON terminology when discussing JSON, which may differ // from related concepts in Go or elsewhere in computing literature. // // - A JSON "object" refers to an unordered collection of name/value members. // - A JSON "array" refers to an ordered sequence of elements. // - A JSON "value" refers to either a literal (i.e., null, false, or true), // string, number, object, or array. // // See RFC 8259 for more information. // // # Specifications // // Relevant specifications include RFC 4627, RFC 7159, RFC 7493, RFC 8259, // and RFC 8785. Each RFC is generally a stricter subset of another RFC. // In increasing order of strictness: // // - RFC 4627 and RFC 7159 do not require (but recommend) the use of UTF-8 // and also do not require (but recommend) that object names be unique. // - RFC 8259 requires the use of UTF-8, // but does not require (but recommends) that object names be unique. // - RFC 7493 requires the use of UTF-8 // and also requires that object names be unique. // - RFC 8785 defines a canonical representation. It requires the use of UTF-8 // and also requires that object names be unique and in a specific ordering. // It specifies exactly how strings and numbers must be formatted. // // The primary difference between RFC 4627 and RFC 7159 is that the former // restricted top-level values to only JSON objects and arrays, while // RFC 7159 and subsequent RFCs permit top-level values to additionally be // JSON nulls, booleans, strings, or numbers. // // By default, this package operates on RFC 7493, but can be configured // to operate according to the other RFC specifications. // RFC 7493 is a stricter subset of RFC 8259 and fully compliant with it. // In particular, it makes specific choices about behavior that RFC 8259 // leaves as undefined in order to ensure greater interoperability. // // # JSON Representation of Go structs // // A Go struct is naturally represented as a JSON object, // where each Go struct field corresponds with a JSON object member. // When marshaling, all Go struct fields are recursively encoded in depth-first // order as JSON object members except those that are ignored or omitted. // When unmarshaling, JSON object members are recursively decoded // into the corresponding Go struct fields. // Object members that do not match any struct fields, // also known as “unknown members”, are ignored by default or rejected // if UnmarshalOptions.RejectUnknownMembers is specified. // // The representation of each struct field can be customized in the // "json" struct field tag, where the tag is a comma separated list of options. // As a special case, if the entire tag is `json:"-"`, // then the field is ignored with regard to its JSON representation. // // The first option is the JSON object name override for the Go struct field. // If the name is not specified, then the Go struct field name // is used as the JSON object name. JSON names containing commas or quotes, // or names identical to "" or "-", can be specified using // a single-quoted string literal, where the syntax is identical to // the Go grammar for a double-quoted string literal, // but instead uses single quotes as the delimiters. // By default, unmarshaling uses case-sensitive matching to identify // the Go struct field associated with a JSON object name. // // After the name, the following tag options are supported: // // - omitzero: When marshaling, the "omitzero" option specifies that // the struct field should be omitted if the field value is zero // as determined by the "IsZero() bool" method if present, // otherwise based on whether the field is the zero Go value. // This option has no effect when unmarshaling. // // - omitempty: When marshaling, the "omitempty" option specifies that // the struct field should be omitted if the field value would have been // encoded as a JSON null, empty string, empty object, or empty array. // This option has no effect when unmarshaling. // // - string: The "string" option specifies that // MarshalOptions.StringifyNumbers and UnmarshalOptions.StringifyNumbers // be set when marshaling or unmarshaling a struct field value. // This causes numeric types to be encoded as a JSON number // within a JSON string, and to be decoded from either a JSON number or // a JSON string containing a JSON number. // This extra level of encoding is often necessary since // many JSON parsers cannot precisely represent 64-bit integers. // // - nocase: When unmarshaling, the "nocase" option specifies that // if the JSON object name does not exactly match the JSON name // for any of the struct fields, then it attempts to match the struct field // using a case-insensitive match that also ignores dashes and underscores. // If multiple fields match, the first declared field in breadth-first order // takes precedence. This option has no effect when marshaling. // // - inline: The "inline" option specifies that // the JSON representable content of this field type is to be promoted // as if they were specified in the parent struct. // It is the JSON equivalent of Go struct embedding. // A Go embedded field is implicitly inlined unless an explicit JSON name // is specified. The inlined field must be a Go struct // (that does not implement any JSON methods), RawValue, map[string]T, // or an unnamed pointer to such types. When marshaling, // inlined fields from a pointer type are omitted if it is nil. // Inlined fields of type RawValue and map[string]T are called // “inlined fallbacks” as they can represent all possible // JSON object members not directly handled by the parent struct. // Only one inlined fallback field may be specified in a struct, // while many non-fallback fields may be specified. This option // must not be specified with any other option (including the JSON name). // // - unknown: The "unknown" option is a specialized variant // of the inlined fallback to indicate that this Go struct field // contains any number of unknown JSON object members. The field type // must be a RawValue, map[string]T, or an unnamed pointer to such types. // If MarshalOptions.DiscardUnknownMembers is specified when marshaling, // the contents of this field are ignored. // If UnmarshalOptions.RejectUnknownMembers is specified when unmarshaling, // any unknown object members are rejected regardless of whether // an inlined fallback with the "unknown" option exists. This option // must not be specified with any other option (including the JSON name). // // - format: The "format" option specifies a format flag // used to specialize the formatting of the field value. // The option is a key-value pair specified as "format:value" where // the value must be either a literal consisting of letters and numbers // (e.g., "format:RFC3339") or a single-quoted string literal // (e.g., "format:'2006-01-02'"). The interpretation of the format flag // is determined by the struct field type. // // The "omitzero" and "omitempty" options are mostly semantically identical. // The former is defined in terms of the Go type system, // while the latter in terms of the JSON type system. // Consequently they behave differently in some circumstances. // For example, only a nil slice or map is omitted under "omitzero", while // an empty slice or map is omitted under "omitempty" regardless of nilness. // The "omitzero" option is useful for types with a well-defined zero value // (e.g., netip.Addr) or have an IsZero method (e.g., time.Time). // // Every Go struct corresponds to a list of JSON representable fields // which is constructed by performing a breadth-first search over // all struct fields (excluding unexported or ignored fields), // where the search recursively descends into inlined structs. // The set of non-inlined fields in a struct must have unique JSON names. // If multiple fields all have the same JSON name, then the one // at shallowest depth takes precedence and the other fields at deeper depths // are excluded from the list of JSON representable fields. // If multiple fields at the shallowest depth have the same JSON name, // then all of those fields are excluded from the list. This is analogous to // Go visibility rules for struct field selection with embedded struct types. // // Marshaling or unmarshaling a non-empty struct // without any JSON representable fields results in a SemanticError. // Unexported fields must not have any `json` tags except for `json:"-"`. package json // requireKeyedLiterals can be embedded in a struct to require keyed literals. type requireKeyedLiterals struct{} // nonComparable can be embedded in a struct to prevent comparability. type nonComparable [0]func()
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/decode.go
vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/decode.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" "errors" "io" "math" "strconv" "unicode/utf16" "unicode/utf8" ) // NOTE: The logic for decoding is complicated by the fact that reading from // an io.Reader into a temporary buffer means that the buffer may contain a // truncated portion of some valid input, requiring the need to fetch more data. // // This file is structured in the following way: // // - consumeXXX functions parse an exact JSON token from a []byte. // If the buffer appears truncated, then it returns io.ErrUnexpectedEOF. // The consumeSimpleXXX functions are so named because they only handle // a subset of the grammar for the JSON token being parsed. // They do not handle the full grammar to keep these functions inlineable. // // - Decoder.consumeXXX methods parse the next JSON token from Decoder.buf, // automatically fetching more input if necessary. These methods take // a position relative to the start of Decoder.buf as an argument and // return the end of the consumed JSON token as a position, // also relative to the start of Decoder.buf. // // - In the event of an I/O errors or state machine violations, // the implementation avoids mutating the state of Decoder // (aside from the book-keeping needed to implement Decoder.fetch). // For this reason, only Decoder.ReadToken and Decoder.ReadValue are // responsible for updated Decoder.prevStart and Decoder.prevEnd. // // - For performance, much of the implementation uses the pattern of calling // the inlineable consumeXXX functions first, and if more work is necessary, // then it calls the slower Decoder.consumeXXX methods. // TODO: Revisit this pattern if the Go compiler provides finer control // over exactly which calls are inlined or not. // DecodeOptions configures how JSON decoding operates. // The zero value is equivalent to the default settings, // which is compliant with both RFC 7493 and RFC 8259. type DecodeOptions struct { requireKeyedLiterals nonComparable // AllowDuplicateNames specifies that JSON objects may contain // duplicate member names. Disabling the duplicate name check may provide // computational and performance benefits, but breaks compliance with // RFC 7493, section 2.3. The input will still be compliant with RFC 8259, // which leaves the handling of duplicate names as unspecified behavior. AllowDuplicateNames bool // AllowInvalidUTF8 specifies that JSON strings may contain invalid UTF-8, // which will be mangled as the Unicode replacement character, U+FFFD. // This causes the decoder to break compliance with // RFC 7493, section 2.1, and RFC 8259, section 8.1. AllowInvalidUTF8 bool } // Decoder is a streaming decoder for raw JSON tokens and values. // It is used to read a stream of top-level JSON values, // each separated by optional whitespace characters. // // ReadToken and ReadValue calls may be interleaved. // For example, the following JSON value: // // {"name":"value","array":[null,false,true,3.14159],"object":{"k":"v"}} // // can be parsed with the following calls (ignoring errors for brevity): // // d.ReadToken() // { // d.ReadToken() // "name" // d.ReadToken() // "value" // d.ReadValue() // "array" // d.ReadToken() // [ // d.ReadToken() // null // d.ReadToken() // false // d.ReadValue() // true // d.ReadToken() // 3.14159 // d.ReadToken() // ] // d.ReadValue() // "object" // d.ReadValue() // {"k":"v"} // d.ReadToken() // } // // The above is one of many possible sequence of calls and // may not represent the most sensible method to call for any given token/value. // For example, it is probably more common to call ReadToken to obtain a // string token for object names. type Decoder struct { state decodeBuffer options DecodeOptions stringCache *stringCache // only used when unmarshaling } // decodeBuffer is a buffer split into 4 segments: // // - buf[0:prevEnd] // already read portion of the buffer // - buf[prevStart:prevEnd] // previously read value // - buf[prevEnd:len(buf)] // unread portion of the buffer // - buf[len(buf):cap(buf)] // unused portion of the buffer // // Invariants: // // 0 ≤ prevStart ≤ prevEnd ≤ len(buf) ≤ cap(buf) type decodeBuffer struct { peekPos int // non-zero if valid offset into buf for start of next token peekErr error // implies peekPos is -1 buf []byte // may alias rd if it is a bytes.Buffer prevStart int prevEnd int // baseOffset is added to prevStart and prevEnd to obtain // the absolute offset relative to the start of io.Reader stream. baseOffset int64 rd io.Reader } // NewDecoder constructs a new streaming decoder reading from r. // // If r is a bytes.Buffer, then the decoder parses directly from the buffer // without first copying the contents to an intermediate buffer. // Additional writes to the buffer must not occur while the decoder is in use. func NewDecoder(r io.Reader) *Decoder { return DecodeOptions{}.NewDecoder(r) } // NewDecoder constructs a new streaming decoder reading from r // configured with the provided options. func (o DecodeOptions) NewDecoder(r io.Reader) *Decoder { d := new(Decoder) o.ResetDecoder(d, r) return d } // ResetDecoder resets a decoder such that it is reading afresh from r and // configured with the provided options. func (o DecodeOptions) ResetDecoder(d *Decoder, r io.Reader) { if d == nil { panic("json: invalid nil Decoder") } if r == nil { panic("json: invalid nil io.Reader") } d.reset(nil, r, o) } func (d *Decoder) reset(b []byte, r io.Reader, o DecodeOptions) { d.state.reset() d.decodeBuffer = decodeBuffer{buf: b, rd: r} d.options = o } // Reset resets a decoder such that it is reading afresh from r but // keep any pre-existing decoder options. func (d *Decoder) Reset(r io.Reader) { d.options.ResetDecoder(d, r) } var errBufferWriteAfterNext = errors.New("invalid bytes.Buffer.Write call after calling bytes.Buffer.Next") // fetch reads at least 1 byte from the underlying io.Reader. // It returns io.ErrUnexpectedEOF if zero bytes were read and io.EOF was seen. func (d *Decoder) fetch() error { if d.rd == nil { return io.ErrUnexpectedEOF } // Inform objectNameStack that we are about to fetch new buffer content. d.names.copyQuotedBuffer(d.buf) // Specialize bytes.Buffer for better performance. if bb, ok := d.rd.(*bytes.Buffer); ok { switch { case bb.Len() == 0: return io.ErrUnexpectedEOF case len(d.buf) == 0: d.buf = bb.Next(bb.Len()) // "read" all data in the buffer return nil default: // This only occurs if a partially filled bytes.Buffer was provided // and more data is written to it while Decoder is reading from it. // This practice will lead to data corruption since future writes // may overwrite the contents of the current buffer. // // The user is trying to use a bytes.Buffer as a pipe, // but a bytes.Buffer is poor implementation of a pipe, // the purpose-built io.Pipe should be used instead. return &ioError{action: "read", err: errBufferWriteAfterNext} } } // Allocate initial buffer if empty. if cap(d.buf) == 0 { d.buf = make([]byte, 0, 64) } // Check whether to grow the buffer. const maxBufferSize = 4 << 10 const growthSizeFactor = 2 // higher value is faster const growthRateFactor = 2 // higher value is slower // By default, grow if below the maximum buffer size. grow := cap(d.buf) <= maxBufferSize/growthSizeFactor // Growing can be expensive, so only grow // if a sufficient number of bytes have been processed. grow = grow && int64(cap(d.buf)) < d.previousOffsetEnd()/growthRateFactor // If prevStart==0, then fetch was called in order to fetch more data // to finish consuming a large JSON value contiguously. // Grow if less than 25% of the remaining capacity is available. // Note that this may cause the input buffer to exceed maxBufferSize. grow = grow || (d.prevStart == 0 && len(d.buf) >= 3*cap(d.buf)/4) if grow { // Allocate a new buffer and copy the contents of the old buffer over. // TODO: Provide a hard limit on the maximum internal buffer size? buf := make([]byte, 0, cap(d.buf)*growthSizeFactor) d.buf = append(buf, d.buf[d.prevStart:]...) } else { // Move unread portion of the data to the front. n := copy(d.buf[:cap(d.buf)], d.buf[d.prevStart:]) d.buf = d.buf[:n] } d.baseOffset += int64(d.prevStart) d.prevEnd -= d.prevStart d.prevStart = 0 // Read more data into the internal buffer. for { n, err := d.rd.Read(d.buf[len(d.buf):cap(d.buf)]) switch { case n > 0: d.buf = d.buf[:len(d.buf)+n] return nil // ignore errors if any bytes are read case err == io.EOF: return io.ErrUnexpectedEOF case err != nil: return &ioError{action: "read", err: err} default: continue // Read returned (0, nil) } } } const invalidateBufferByte = '#' // invalid starting character for JSON grammar // invalidatePreviousRead invalidates buffers returned by Peek and Read calls // so that the first byte is an invalid character. // This Hyrum-proofs the API against faulty application code that assumes // values returned by ReadValue remain valid past subsequent Read calls. func (d *decodeBuffer) invalidatePreviousRead() { // Avoid mutating the buffer if d.rd is nil which implies that d.buf // is provided by the user code and may not expect mutations. isBytesBuffer := func(r io.Reader) bool { _, ok := r.(*bytes.Buffer) return ok } if d.rd != nil && !isBytesBuffer(d.rd) && d.prevStart < d.prevEnd && uint(d.prevStart) < uint(len(d.buf)) { d.buf[d.prevStart] = invalidateBufferByte d.prevStart = d.prevEnd } } // needMore reports whether there are no more unread bytes. func (d *decodeBuffer) needMore(pos int) bool { // NOTE: The arguments and logic are kept simple to keep this inlineable. return pos == len(d.buf) } // injectSyntacticErrorWithPosition wraps a SyntacticError with the position, // otherwise it returns the error as is. // It takes a position relative to the start of the start of d.buf. func (d *decodeBuffer) injectSyntacticErrorWithPosition(err error, pos int) error { if serr, ok := err.(*SyntacticError); ok { return serr.withOffset(d.baseOffset + int64(pos)) } return err } func (d *decodeBuffer) previousOffsetStart() int64 { return d.baseOffset + int64(d.prevStart) } func (d *decodeBuffer) previousOffsetEnd() int64 { return d.baseOffset + int64(d.prevEnd) } func (d *decodeBuffer) previousBuffer() []byte { return d.buf[d.prevStart:d.prevEnd] } func (d *decodeBuffer) unreadBuffer() []byte { return d.buf[d.prevEnd:len(d.buf)] } // PeekKind retrieves the next token kind, but does not advance the read offset. // It returns 0 if there are no more tokens. func (d *Decoder) PeekKind() Kind { // Check whether we have a cached peek result. if d.peekPos > 0 { return Kind(d.buf[d.peekPos]).normalize() } var err error d.invalidatePreviousRead() pos := d.prevEnd // Consume leading whitespace. pos += consumeWhitespace(d.buf[pos:]) if d.needMore(pos) { if pos, err = d.consumeWhitespace(pos); err != nil { if err == io.ErrUnexpectedEOF && d.tokens.depth() == 1 { err = io.EOF // EOF possibly if no Tokens present after top-level value } d.peekPos, d.peekErr = -1, err return invalidKind } } // Consume colon or comma. var delim byte if c := d.buf[pos]; c == ':' || c == ',' { delim = c pos += 1 pos += consumeWhitespace(d.buf[pos:]) if d.needMore(pos) { if pos, err = d.consumeWhitespace(pos); err != nil { d.peekPos, d.peekErr = -1, err return invalidKind } } } next := Kind(d.buf[pos]).normalize() if d.tokens.needDelim(next) != delim { pos = d.prevEnd // restore position to right after leading whitespace pos += consumeWhitespace(d.buf[pos:]) err = d.tokens.checkDelim(delim, next) err = d.injectSyntacticErrorWithPosition(err, pos) d.peekPos, d.peekErr = -1, err return invalidKind } // This may set peekPos to zero, which is indistinguishable from // the uninitialized state. While a small hit to performance, it is correct // since ReadValue and ReadToken will disregard the cached result and // recompute the next kind. d.peekPos, d.peekErr = pos, nil return next } // SkipValue is semantically equivalent to calling ReadValue and discarding // the result except that memory is not wasted trying to hold the entire result. func (d *Decoder) SkipValue() error { switch d.PeekKind() { case '{', '[': // For JSON objects and arrays, keep skipping all tokens // until the depth matches the starting depth. depth := d.tokens.depth() for { if _, err := d.ReadToken(); err != nil { return err } if depth >= d.tokens.depth() { return nil } } default: // Trying to skip a value when the next token is a '}' or ']' // will result in an error being returned here. if _, err := d.ReadValue(); err != nil { return err } return nil } } // ReadToken reads the next Token, advancing the read offset. // The returned token is only valid until the next Peek, Read, or Skip call. // It returns io.EOF if there are no more tokens. func (d *Decoder) ReadToken() (Token, error) { // Determine the next kind. var err error var next Kind pos := d.peekPos if pos != 0 { // Use cached peek result. if d.peekErr != nil { err := d.peekErr d.peekPos, d.peekErr = 0, nil // possibly a transient I/O error return Token{}, err } next = Kind(d.buf[pos]).normalize() d.peekPos = 0 // reset cache } else { d.invalidatePreviousRead() pos = d.prevEnd // Consume leading whitespace. pos += consumeWhitespace(d.buf[pos:]) if d.needMore(pos) { if pos, err = d.consumeWhitespace(pos); err != nil { if err == io.ErrUnexpectedEOF && d.tokens.depth() == 1 { err = io.EOF // EOF possibly if no Tokens present after top-level value } return Token{}, err } } // Consume colon or comma. var delim byte if c := d.buf[pos]; c == ':' || c == ',' { delim = c pos += 1 pos += consumeWhitespace(d.buf[pos:]) if d.needMore(pos) { if pos, err = d.consumeWhitespace(pos); err != nil { return Token{}, err } } } next = Kind(d.buf[pos]).normalize() if d.tokens.needDelim(next) != delim { pos = d.prevEnd // restore position to right after leading whitespace pos += consumeWhitespace(d.buf[pos:]) err = d.tokens.checkDelim(delim, next) return Token{}, d.injectSyntacticErrorWithPosition(err, pos) } } // Handle the next token. var n int switch next { case 'n': if consumeNull(d.buf[pos:]) == 0 { pos, err = d.consumeLiteral(pos, "null") if err != nil { return Token{}, d.injectSyntacticErrorWithPosition(err, pos) } } else { pos += len("null") } if err = d.tokens.appendLiteral(); err != nil { return Token{}, d.injectSyntacticErrorWithPosition(err, pos-len("null")) // report position at start of literal } d.prevStart, d.prevEnd = pos, pos return Null, nil case 'f': if consumeFalse(d.buf[pos:]) == 0 { pos, err = d.consumeLiteral(pos, "false") if err != nil { return Token{}, d.injectSyntacticErrorWithPosition(err, pos) } } else { pos += len("false") } if err = d.tokens.appendLiteral(); err != nil { return Token{}, d.injectSyntacticErrorWithPosition(err, pos-len("false")) // report position at start of literal } d.prevStart, d.prevEnd = pos, pos return False, nil case 't': if consumeTrue(d.buf[pos:]) == 0 { pos, err = d.consumeLiteral(pos, "true") if err != nil { return Token{}, d.injectSyntacticErrorWithPosition(err, pos) } } else { pos += len("true") } if err = d.tokens.appendLiteral(); err != nil { return Token{}, d.injectSyntacticErrorWithPosition(err, pos-len("true")) // report position at start of literal } d.prevStart, d.prevEnd = pos, pos return True, nil case '"': var flags valueFlags // TODO: Preserve this in Token? if n = consumeSimpleString(d.buf[pos:]); n == 0 { oldAbsPos := d.baseOffset + int64(pos) pos, err = d.consumeString(&flags, pos) newAbsPos := d.baseOffset + int64(pos) n = int(newAbsPos - oldAbsPos) if err != nil { return Token{}, d.injectSyntacticErrorWithPosition(err, pos) } } else { pos += n } if !d.options.AllowDuplicateNames && d.tokens.last.needObjectName() { if !d.tokens.last.isValidNamespace() { return Token{}, errInvalidNamespace } if d.tokens.last.isActiveNamespace() && !d.namespaces.last().insertQuoted(d.buf[pos-n:pos], flags.isVerbatim()) { err = &SyntacticError{str: "duplicate name " + string(d.buf[pos-n:pos]) + " in object"} return Token{}, d.injectSyntacticErrorWithPosition(err, pos-n) // report position at start of string } d.names.replaceLastQuotedOffset(pos - n) // only replace if insertQuoted succeeds } if err = d.tokens.appendString(); err != nil { return Token{}, d.injectSyntacticErrorWithPosition(err, pos-n) // report position at start of string } d.prevStart, d.prevEnd = pos-n, pos return Token{raw: &d.decodeBuffer, num: uint64(d.previousOffsetStart())}, nil case '0': // NOTE: Since JSON numbers are not self-terminating, // we need to make sure that the next byte is not part of a number. if n = consumeSimpleNumber(d.buf[pos:]); n == 0 || d.needMore(pos+n) { oldAbsPos := d.baseOffset + int64(pos) pos, err = d.consumeNumber(pos) newAbsPos := d.baseOffset + int64(pos) n = int(newAbsPos - oldAbsPos) if err != nil { return Token{}, d.injectSyntacticErrorWithPosition(err, pos) } } else { pos += n } if err = d.tokens.appendNumber(); err != nil { return Token{}, d.injectSyntacticErrorWithPosition(err, pos-n) // report position at start of number } d.prevStart, d.prevEnd = pos-n, pos return Token{raw: &d.decodeBuffer, num: uint64(d.previousOffsetStart())}, nil case '{': if err = d.tokens.pushObject(); err != nil { return Token{}, d.injectSyntacticErrorWithPosition(err, pos) } if !d.options.AllowDuplicateNames { d.names.push() d.namespaces.push() } pos += 1 d.prevStart, d.prevEnd = pos, pos return ObjectStart, nil case '}': if err = d.tokens.popObject(); err != nil { return Token{}, d.injectSyntacticErrorWithPosition(err, pos) } if !d.options.AllowDuplicateNames { d.names.pop() d.namespaces.pop() } pos += 1 d.prevStart, d.prevEnd = pos, pos return ObjectEnd, nil case '[': if err = d.tokens.pushArray(); err != nil { return Token{}, d.injectSyntacticErrorWithPosition(err, pos) } pos += 1 d.prevStart, d.prevEnd = pos, pos return ArrayStart, nil case ']': if err = d.tokens.popArray(); err != nil { return Token{}, d.injectSyntacticErrorWithPosition(err, pos) } pos += 1 d.prevStart, d.prevEnd = pos, pos return ArrayEnd, nil default: err = newInvalidCharacterError(d.buf[pos:], "at start of token") return Token{}, d.injectSyntacticErrorWithPosition(err, pos) } } type valueFlags uint const ( _ valueFlags = (1 << iota) / 2 // powers of two starting with zero stringNonVerbatim // string cannot be naively treated as valid UTF-8 stringNonCanonical // string not formatted according to RFC 8785, section 3.2.2.2. // TODO: Track whether a number is a non-integer? ) func (f *valueFlags) set(f2 valueFlags) { *f |= f2 } func (f valueFlags) isVerbatim() bool { return f&stringNonVerbatim == 0 } func (f valueFlags) isCanonical() bool { return f&stringNonCanonical == 0 } // ReadValue returns the next raw JSON value, advancing the read offset. // The value is stripped of any leading or trailing whitespace. // The returned value is only valid until the next Peek, Read, or Skip call and // may not be mutated while the Decoder remains in use. // If the decoder is currently at the end token for an object or array, // then it reports a SyntacticError and the internal state remains unchanged. // It returns io.EOF if there are no more values. func (d *Decoder) ReadValue() (RawValue, error) { var flags valueFlags return d.readValue(&flags) } func (d *Decoder) readValue(flags *valueFlags) (RawValue, error) { // Determine the next kind. var err error var next Kind pos := d.peekPos if pos != 0 { // Use cached peek result. if d.peekErr != nil { err := d.peekErr d.peekPos, d.peekErr = 0, nil // possibly a transient I/O error return nil, err } next = Kind(d.buf[pos]).normalize() d.peekPos = 0 // reset cache } else { d.invalidatePreviousRead() pos = d.prevEnd // Consume leading whitespace. pos += consumeWhitespace(d.buf[pos:]) if d.needMore(pos) { if pos, err = d.consumeWhitespace(pos); err != nil { if err == io.ErrUnexpectedEOF && d.tokens.depth() == 1 { err = io.EOF // EOF possibly if no Tokens present after top-level value } return nil, err } } // Consume colon or comma. var delim byte if c := d.buf[pos]; c == ':' || c == ',' { delim = c pos += 1 pos += consumeWhitespace(d.buf[pos:]) if d.needMore(pos) { if pos, err = d.consumeWhitespace(pos); err != nil { return nil, err } } } next = Kind(d.buf[pos]).normalize() if d.tokens.needDelim(next) != delim { pos = d.prevEnd // restore position to right after leading whitespace pos += consumeWhitespace(d.buf[pos:]) err = d.tokens.checkDelim(delim, next) return nil, d.injectSyntacticErrorWithPosition(err, pos) } } // Handle the next value. oldAbsPos := d.baseOffset + int64(pos) pos, err = d.consumeValue(flags, pos) newAbsPos := d.baseOffset + int64(pos) n := int(newAbsPos - oldAbsPos) if err != nil { return nil, d.injectSyntacticErrorWithPosition(err, pos) } switch next { case 'n', 't', 'f': err = d.tokens.appendLiteral() case '"': if !d.options.AllowDuplicateNames && d.tokens.last.needObjectName() { if !d.tokens.last.isValidNamespace() { err = errInvalidNamespace break } if d.tokens.last.isActiveNamespace() && !d.namespaces.last().insertQuoted(d.buf[pos-n:pos], flags.isVerbatim()) { err = &SyntacticError{str: "duplicate name " + string(d.buf[pos-n:pos]) + " in object"} break } d.names.replaceLastQuotedOffset(pos - n) // only replace if insertQuoted succeeds } err = d.tokens.appendString() case '0': err = d.tokens.appendNumber() case '{': if err = d.tokens.pushObject(); err != nil { break } if err = d.tokens.popObject(); err != nil { panic("BUG: popObject should never fail immediately after pushObject: " + err.Error()) } case '[': if err = d.tokens.pushArray(); err != nil { break } if err = d.tokens.popArray(); err != nil { panic("BUG: popArray should never fail immediately after pushArray: " + err.Error()) } } if err != nil { return nil, d.injectSyntacticErrorWithPosition(err, pos-n) // report position at start of value } d.prevEnd = pos d.prevStart = pos - n return d.buf[pos-n : pos : pos], nil } // checkEOF verifies that the input has no more data. func (d *Decoder) checkEOF() error { switch pos, err := d.consumeWhitespace(d.prevEnd); err { case nil: return newInvalidCharacterError(d.buf[pos:], "after top-level value") case io.ErrUnexpectedEOF: return nil default: return err } } // consumeWhitespace consumes all whitespace starting at d.buf[pos:]. // It returns the new position in d.buf immediately after the last whitespace. // If it returns nil, there is guaranteed to at least be one unread byte. // // The following pattern is common in this implementation: // // pos += consumeWhitespace(d.buf[pos:]) // if d.needMore(pos) { // if pos, err = d.consumeWhitespace(pos); err != nil { // return ... // } // } // // It is difficult to simplify this without sacrificing performance since // consumeWhitespace must be inlined. The body of the if statement is // executed only in rare situations where we need to fetch more data. // Since fetching may return an error, we also need to check the error. func (d *Decoder) consumeWhitespace(pos int) (newPos int, err error) { for { pos += consumeWhitespace(d.buf[pos:]) if d.needMore(pos) { absPos := d.baseOffset + int64(pos) err = d.fetch() // will mutate d.buf and invalidate pos pos = int(absPos - d.baseOffset) if err != nil { return pos, err } continue } return pos, nil } } // consumeValue consumes a single JSON value starting at d.buf[pos:]. // It returns the new position in d.buf immediately after the value. func (d *Decoder) consumeValue(flags *valueFlags, pos int) (newPos int, err error) { for { var n int var err error switch next := Kind(d.buf[pos]).normalize(); next { case 'n': if n = consumeNull(d.buf[pos:]); n == 0 { n, err = consumeLiteral(d.buf[pos:], "null") } case 'f': if n = consumeFalse(d.buf[pos:]); n == 0 { n, err = consumeLiteral(d.buf[pos:], "false") } case 't': if n = consumeTrue(d.buf[pos:]); n == 0 { n, err = consumeLiteral(d.buf[pos:], "true") } case '"': if n = consumeSimpleString(d.buf[pos:]); n == 0 { return d.consumeString(flags, pos) } case '0': // NOTE: Since JSON numbers are not self-terminating, // we need to make sure that the next byte is not part of a number. if n = consumeSimpleNumber(d.buf[pos:]); n == 0 || d.needMore(pos+n) { return d.consumeNumber(pos) } case '{': return d.consumeObject(flags, pos) case '[': return d.consumeArray(flags, pos) default: return pos, newInvalidCharacterError(d.buf[pos:], "at start of value") } if err == io.ErrUnexpectedEOF { absPos := d.baseOffset + int64(pos) err = d.fetch() // will mutate d.buf and invalidate pos pos = int(absPos - d.baseOffset) if err != nil { return pos, err } continue } return pos + n, err } } // consumeLiteral consumes a single JSON literal starting at d.buf[pos:]. // It returns the new position in d.buf immediately after the literal. func (d *Decoder) consumeLiteral(pos int, lit string) (newPos int, err error) { for { n, err := consumeLiteral(d.buf[pos:], lit) if err == io.ErrUnexpectedEOF { absPos := d.baseOffset + int64(pos) err = d.fetch() // will mutate d.buf and invalidate pos pos = int(absPos - d.baseOffset) if err != nil { return pos, err } continue } return pos + n, err } } // consumeString consumes a single JSON string starting at d.buf[pos:]. // It returns the new position in d.buf immediately after the string. func (d *Decoder) consumeString(flags *valueFlags, pos int) (newPos int, err error) { var n int for { n, err = consumeStringResumable(flags, d.buf[pos:], n, !d.options.AllowInvalidUTF8) if err == io.ErrUnexpectedEOF { absPos := d.baseOffset + int64(pos) err = d.fetch() // will mutate d.buf and invalidate pos pos = int(absPos - d.baseOffset) if err != nil { return pos, err } continue } return pos + n, err } } // consumeNumber consumes a single JSON number starting at d.buf[pos:]. // It returns the new position in d.buf immediately after the number. func (d *Decoder) consumeNumber(pos int) (newPos int, err error) { var n int var state consumeNumberState for { n, state, err = consumeNumberResumable(d.buf[pos:], n, state) // NOTE: Since JSON numbers are not self-terminating, // we need to make sure that the next byte is not part of a number. if err == io.ErrUnexpectedEOF || d.needMore(pos+n) { mayTerminate := err == nil absPos := d.baseOffset + int64(pos) err = d.fetch() // will mutate d.buf and invalidate pos pos = int(absPos - d.baseOffset) if err != nil { if mayTerminate && err == io.ErrUnexpectedEOF { return pos + n, nil } return pos, err } continue } return pos + n, err } } // consumeObject consumes a single JSON object starting at d.buf[pos:]. // It returns the new position in d.buf immediately after the object. func (d *Decoder) consumeObject(flags *valueFlags, pos int) (newPos int, err error) { var n int var names *objectNamespace if !d.options.AllowDuplicateNames { d.namespaces.push() defer d.namespaces.pop() names = d.namespaces.last() } // Handle before start. if d.buf[pos] != '{' { panic("BUG: consumeObject must be called with a buffer that starts with '{'") } pos++ // Handle after start. pos += consumeWhitespace(d.buf[pos:]) if d.needMore(pos) { if pos, err = d.consumeWhitespace(pos); err != nil { return pos, err } } if d.buf[pos] == '}' { pos++ return pos, nil } for { // Handle before name. pos += consumeWhitespace(d.buf[pos:]) if d.needMore(pos) { if pos, err = d.consumeWhitespace(pos); err != nil { return pos, err } } var flags2 valueFlags if n = consumeSimpleString(d.buf[pos:]); n == 0 { oldAbsPos := d.baseOffset + int64(pos) pos, err = d.consumeString(&flags2, pos) newAbsPos := d.baseOffset + int64(pos) n = int(newAbsPos - oldAbsPos) flags.set(flags2) if err != nil { return pos, err } } else { pos += n } if !d.options.AllowDuplicateNames && !names.insertQuoted(d.buf[pos-n:pos], flags2.isVerbatim()) { return pos - n, &SyntacticError{str: "duplicate name " + string(d.buf[pos-n:pos]) + " in object"} } // Handle after name. pos += consumeWhitespace(d.buf[pos:]) if d.needMore(pos) { if pos, err = d.consumeWhitespace(pos); err != nil { return pos, err } } if d.buf[pos] != ':' { return pos, newInvalidCharacterError(d.buf[pos:], "after object name (expecting ':')") } pos++ // Handle before value. pos += consumeWhitespace(d.buf[pos:]) if d.needMore(pos) { if pos, err = d.consumeWhitespace(pos); err != nil { return pos, err } } pos, err = d.consumeValue(flags, pos) if err != nil { return pos, err } // Handle after value. pos += consumeWhitespace(d.buf[pos:]) if d.needMore(pos) { if pos, err = d.consumeWhitespace(pos); err != nil { return pos, err } } switch d.buf[pos] { case ',': pos++ continue case '}': pos++ return pos, nil default: return pos, newInvalidCharacterError(d.buf[pos:], "after object value (expecting ',' or '}')") } } } // consumeArray consumes a single JSON array starting at d.buf[pos:]. // It returns the new position in d.buf immediately after the array. func (d *Decoder) consumeArray(flags *valueFlags, pos int) (newPos int, err error) { // Handle before start. if d.buf[pos] != '[' { panic("BUG: consumeArray must be called with a buffer that starts with '['") } pos++ // Handle after start. pos += consumeWhitespace(d.buf[pos:]) if d.needMore(pos) { if pos, err = d.consumeWhitespace(pos); err != nil { return pos, err } } if d.buf[pos] == ']' { pos++ return pos, nil } for { // Handle before value. pos += consumeWhitespace(d.buf[pos:]) if d.needMore(pos) { if pos, err = d.consumeWhitespace(pos); err != nil { return pos, err } } pos, err = d.consumeValue(flags, pos) if err != nil { return pos, err } // Handle after value. pos += consumeWhitespace(d.buf[pos:]) if d.needMore(pos) { if pos, err = d.consumeWhitespace(pos); err != nil { return pos, err } } switch d.buf[pos] { case ',': pos++ continue case ']': pos++ return pos, nil default: return pos, newInvalidCharacterError(d.buf[pos:], "after array value (expecting ',' or ']')") } } } // InputOffset returns the current input byte offset. It gives the location // of the next byte immediately after the most recently returned token or value. // The number of bytes actually read from the underlying io.Reader may be more // than this offset due to internal buffering effects. func (d *Decoder) InputOffset() int64 { return d.previousOffsetEnd() } // UnreadBuffer returns the data remaining in the unread buffer, // which may contain zero or more bytes. // The returned buffer must not be mutated while Decoder continues to be used. // The buffer contents are valid until the next Peek, Read, or Skip call. func (d *Decoder) UnreadBuffer() []byte { return d.unreadBuffer() } // StackDepth returns the depth of the state machine for read JSON data. // Each level on the stack represents a nested JSON object or array. // It is incremented whenever an ObjectStart or ArrayStart token is encountered // and decremented whenever an ObjectEnd or ArrayEnd token is encountered. // The depth is zero-indexed, where zero represents the top-level JSON value. func (d *Decoder) StackDepth() int { // NOTE: Keep in sync with Encoder.StackDepth. return d.tokens.depth() - 1 } // StackIndex returns information about the specified stack level.
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
true
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/intern.go
vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/intern.go
// Copyright 2022 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/binary" "math/bits" ) // stringCache is a cache for strings converted from a []byte. type stringCache [256]string // 256*unsafe.Sizeof(string("")) => 4KiB // make returns the string form of b. // It returns a pre-allocated string from c if present, otherwise // it allocates a new string, inserts it into the cache, and returns it. func (c *stringCache) make(b []byte) string { const ( minCachedLen = 2 // single byte strings are already interned by the runtime maxCachedLen = 256 // large enough for UUIDs, IPv6 addresses, SHA-256 checksums, etc. ) if c == nil || len(b) < minCachedLen || len(b) > maxCachedLen { return string(b) } // Compute a hash from the fixed-width prefix and suffix of the string. // This ensures hashing a string is a constant time operation. var h uint32 switch { case len(b) >= 8: lo := binary.LittleEndian.Uint64(b[:8]) hi := binary.LittleEndian.Uint64(b[len(b)-8:]) h = hash64(uint32(lo), uint32(lo>>32)) ^ hash64(uint32(hi), uint32(hi>>32)) case len(b) >= 4: lo := binary.LittleEndian.Uint32(b[:4]) hi := binary.LittleEndian.Uint32(b[len(b)-4:]) h = hash64(lo, hi) case len(b) >= 2: lo := binary.LittleEndian.Uint16(b[:2]) hi := binary.LittleEndian.Uint16(b[len(b)-2:]) h = hash64(uint32(lo), uint32(hi)) } // Check the cache for the string. i := h % uint32(len(*c)) if s := (*c)[i]; s == string(b) { return s } s := string(b) (*c)[i] = s return s } // hash64 returns the hash of two uint32s as a single uint32. func hash64(lo, hi uint32) uint32 { // If avalanche=true, this is identical to XXH32 hash on a 8B string: // var b [8]byte // binary.LittleEndian.PutUint32(b[:4], lo) // binary.LittleEndian.PutUint32(b[4:], hi) // return xxhash.Sum32(b[:]) const ( prime1 = 0x9e3779b1 prime2 = 0x85ebca77 prime3 = 0xc2b2ae3d prime4 = 0x27d4eb2f prime5 = 0x165667b1 ) h := prime5 + uint32(8) h += lo * prime3 h = bits.RotateLeft32(h, 17) * prime4 h += hi * prime3 h = bits.RotateLeft32(h, 17) * prime4 // Skip final mix (avalanche) step of XXH32 for performance reasons. // Empirical testing shows that the improvements in unbiased distribution // does not outweigh the extra cost in computational complexity. const avalanche = false if avalanche { h ^= h >> 15 h *= prime2 h ^= h >> 13 h *= prime3 h ^= h >> 16 } return h }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/fields.go
vendor/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/fields.go
// Copyright 2021 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" "fmt" "io" "reflect" "sort" "strconv" "strings" "unicode" "unicode/utf8" ) var errIgnoredField = errors.New("ignored field") type isZeroer interface { IsZero() bool } var isZeroerType = reflect.TypeOf((*isZeroer)(nil)).Elem() type structFields struct { flattened []structField // listed in depth-first ordering byActualName map[string]*structField byFoldedName map[string][]*structField inlinedFallback *structField } type structField struct { id int // unique numeric ID in breadth-first ordering index []int // index into a struct according to reflect.Type.FieldByIndex typ reflect.Type fncs *arshaler isZero func(addressableValue) bool isEmpty func(addressableValue) bool fieldOptions } func makeStructFields(root reflect.Type) (structFields, *SemanticError) { var fs structFields fs.byActualName = make(map[string]*structField, root.NumField()) fs.byFoldedName = make(map[string][]*structField, root.NumField()) // ambiguous is a sentinel value to indicate that at least two fields // at the same depth have the same name, and thus cancel each other out. // This follows the same rules as selecting a field on embedded structs // where the shallowest field takes precedence. If more than one field // exists at the shallowest depth, then the selection is illegal. // See https://go.dev/ref/spec#Selectors. ambiguous := new(structField) // Setup a queue for a breath-first search. var queueIndex int type queueEntry struct { typ reflect.Type index []int visitChildren bool // whether to recursively visit inlined field in this struct } queue := []queueEntry{{root, nil, true}} seen := map[reflect.Type]bool{root: true} // Perform a breadth-first search over all reachable fields. // This ensures that len(f.index) will be monotonically increasing. for queueIndex < len(queue) { qe := queue[queueIndex] queueIndex++ t := qe.typ inlinedFallbackIndex := -1 // index of last inlined fallback field in current struct namesIndex := make(map[string]int) // index of each field with a given JSON object name in current struct var hasAnyJSONTag bool // whether any Go struct field has a `json` tag var hasAnyJSONField bool // whether any JSON serializable fields exist in current struct for i := 0; i < t.NumField(); i++ { sf := t.Field(i) _, hasTag := sf.Tag.Lookup("json") hasAnyJSONTag = hasAnyJSONTag || hasTag options, err := parseFieldOptions(sf) if err != nil { if err == errIgnoredField { continue } return structFields{}, &SemanticError{GoType: t, Err: err} } hasAnyJSONField = true f := structField{ // Allocate a new slice (len=N+1) to hold both // the parent index (len=N) and the current index (len=1). // Do this to avoid clobbering the memory of the parent index. index: append(append(make([]int, 0, len(qe.index)+1), qe.index...), i), typ: sf.Type, fieldOptions: options, } if sf.Anonymous && !f.hasName { f.inline = true // implied by use of Go embedding without an explicit name } if f.inline || f.unknown { // Handle an inlined field that serializes to/from // zero or more JSON object members. if f.inline && f.unknown { err := fmt.Errorf("Go struct field %s cannot have both `inline` and `unknown` specified", sf.Name) return structFields{}, &SemanticError{GoType: t, Err: err} } switch f.fieldOptions { case fieldOptions{name: f.name, quotedName: f.quotedName, inline: true}: case fieldOptions{name: f.name, quotedName: f.quotedName, unknown: true}: default: err := fmt.Errorf("Go struct field %s cannot have any options other than `inline` or `unknown` specified", sf.Name) return structFields{}, &SemanticError{GoType: t, Err: err} } // Unwrap one level of pointer indirection similar to how Go // only allows embedding either T or *T, but not **T. tf := f.typ if tf.Kind() == reflect.Pointer && tf.Name() == "" { tf = tf.Elem() } // Reject any types with custom serialization otherwise // it becomes impossible to know what sub-fields to inline. if which, _ := implementsWhich(tf, jsonMarshalerV2Type, jsonMarshalerV1Type, textMarshalerType, jsonUnmarshalerV2Type, jsonUnmarshalerV1Type, textUnmarshalerType, ); which != nil && tf != rawValueType { err := fmt.Errorf("inlined Go struct field %s of type %s must not implement JSON marshal or unmarshal methods", sf.Name, tf) return structFields{}, &SemanticError{GoType: t, Err: err} } // Handle an inlined field that serializes to/from // a finite number of JSON object members backed by a Go struct. if tf.Kind() == reflect.Struct { if f.unknown { err := fmt.Errorf("inlined Go struct field %s of type %s with `unknown` tag must be a Go map of string key or a json.RawValue", sf.Name, tf) return structFields{}, &SemanticError{GoType: t, Err: err} } if qe.visitChildren { queue = append(queue, queueEntry{tf, f.index, !seen[tf]}) } seen[tf] = true continue } // Handle an inlined field that serializes to/from any number of // JSON object members back by a Go map or RawValue. switch { case tf == rawValueType: f.fncs = nil // specially handled in arshal_inlined.go case tf.Kind() == reflect.Map && tf.Key() == stringType: f.fncs = lookupArshaler(tf.Elem()) default: err := fmt.Errorf("inlined Go struct field %s of type %s must be a Go struct, Go map of string key, or json.RawValue", sf.Name, tf) return structFields{}, &SemanticError{GoType: t, Err: err} } // Reject multiple inlined fallback fields within the same struct. if inlinedFallbackIndex >= 0 { err := fmt.Errorf("inlined Go struct fields %s and %s cannot both be a Go map or json.RawValue", t.Field(inlinedFallbackIndex).Name, sf.Name) return structFields{}, &SemanticError{GoType: t, Err: err} } inlinedFallbackIndex = i // Multiple inlined fallback fields across different structs // follow the same precedence rules as Go struct embedding. if fs.inlinedFallback == nil { fs.inlinedFallback = &f // store first occurrence at lowest depth } else if len(fs.inlinedFallback.index) == len(f.index) { fs.inlinedFallback = ambiguous // at least two occurrences at same depth } } else { // Handle normal Go struct field that serializes to/from // a single JSON object member. // Provide a function that uses a type's IsZero method. switch { case sf.Type.Kind() == reflect.Interface && sf.Type.Implements(isZeroerType): f.isZero = func(va addressableValue) bool { // Avoid panics calling IsZero on a nil interface or // non-nil interface with nil pointer. return va.IsNil() || (va.Elem().Kind() == reflect.Pointer && va.Elem().IsNil()) || va.Interface().(isZeroer).IsZero() } case sf.Type.Kind() == reflect.Pointer && sf.Type.Implements(isZeroerType): f.isZero = func(va addressableValue) bool { // Avoid panics calling IsZero on nil pointer. return va.IsNil() || va.Interface().(isZeroer).IsZero() } case sf.Type.Implements(isZeroerType): f.isZero = func(va addressableValue) bool { return va.Interface().(isZeroer).IsZero() } case reflect.PointerTo(sf.Type).Implements(isZeroerType): f.isZero = func(va addressableValue) bool { return va.Addr().Interface().(isZeroer).IsZero() } } // Provide a function that can determine whether the value would // serialize as an empty JSON value. switch sf.Type.Kind() { case reflect.String, reflect.Map, reflect.Array, reflect.Slice: f.isEmpty = func(va addressableValue) bool { return va.Len() == 0 } case reflect.Pointer, reflect.Interface: f.isEmpty = func(va addressableValue) bool { return va.IsNil() } } f.id = len(fs.flattened) f.fncs = lookupArshaler(sf.Type) fs.flattened = append(fs.flattened, f) // Reject user-specified names with invalid UTF-8. if !utf8.ValidString(f.name) { err := fmt.Errorf("Go struct field %s has JSON object name %q with invalid UTF-8", sf.Name, f.name) return structFields{}, &SemanticError{GoType: t, Err: err} } // Reject multiple fields with same name within the same struct. if j, ok := namesIndex[f.name]; ok { err := fmt.Errorf("Go struct fields %s and %s conflict over JSON object name %q", t.Field(j).Name, sf.Name, f.name) return structFields{}, &SemanticError{GoType: t, Err: err} } namesIndex[f.name] = i // Multiple fields of the same name across different structs // follow the same precedence rules as Go struct embedding. if f2 := fs.byActualName[f.name]; f2 == nil { fs.byActualName[f.name] = &fs.flattened[len(fs.flattened)-1] // store first occurrence at lowest depth } else if len(f2.index) == len(f.index) { fs.byActualName[f.name] = ambiguous // at least two occurrences at same depth } } } // NOTE: New users to the json package are occasionally surprised that // unexported fields are ignored. This occurs by necessity due to our // inability to directly introspect such fields with Go reflection // without the use of unsafe. // // To reduce friction here, refuse to serialize any Go struct that // has no JSON serializable fields, has at least one Go struct field, // and does not have any `json` tags present. For example, // errors returned by errors.New would fail to serialize. isEmptyStruct := t.NumField() == 0 if !isEmptyStruct && !hasAnyJSONTag && !hasAnyJSONField { err := errors.New("Go struct has no exported fields") return structFields{}, &SemanticError{GoType: t, Err: err} } } // Remove all fields that are duplicates. // This may move elements forward to fill the holes from removed fields. var n int for _, f := range fs.flattened { switch f2 := fs.byActualName[f.name]; { case f2 == ambiguous: delete(fs.byActualName, f.name) case f2 == nil: continue // may be nil due to previous delete // TODO(https://go.dev/issue/45955): Use slices.Equal. case reflect.DeepEqual(f.index, f2.index): f.id = n fs.flattened[n] = f fs.byActualName[f.name] = &fs.flattened[n] // fix pointer to new location n++ } } fs.flattened = fs.flattened[:n] if fs.inlinedFallback == ambiguous { fs.inlinedFallback = nil } if len(fs.flattened) != len(fs.byActualName) { panic(fmt.Sprintf("BUG: flattened list of fields mismatches fields mapped by name: %d != %d", len(fs.flattened), len(fs.byActualName))) } // Sort the fields according to a depth-first ordering. // This operation will cause pointers in byActualName to become incorrect, // which we will correct in another loop shortly thereafter. sort.Slice(fs.flattened, func(i, j int) bool { si := fs.flattened[i].index sj := fs.flattened[j].index for len(si) > 0 && len(sj) > 0 { switch { case si[0] < sj[0]: return true case si[0] > sj[0]: return false default: si = si[1:] sj = sj[1:] } } return len(si) < len(sj) }) // Recompute the mapping of fields in the byActualName map. // Pre-fold all names so that we can lookup folded names quickly. for i, f := range fs.flattened { foldedName := string(foldName([]byte(f.name))) fs.byActualName[f.name] = &fs.flattened[i] fs.byFoldedName[foldedName] = append(fs.byFoldedName[foldedName], &fs.flattened[i]) } for foldedName, fields := range fs.byFoldedName { if len(fields) > 1 { // The precedence order for conflicting nocase names // is by breadth-first order, rather than depth-first order. sort.Slice(fields, func(i, j int) bool { return fields[i].id < fields[j].id }) fs.byFoldedName[foldedName] = fields } } return fs, nil } type fieldOptions struct { name string quotedName string // quoted name per RFC 8785, section 3.2.2.2. hasName bool nocase bool inline bool unknown bool omitzero bool omitempty bool string bool format string } // parseFieldOptions parses the `json` tag in a Go struct field as // a structured set of options configuring parameters such as // the JSON member name and other features. // As a special case, it returns errIgnoredField if the field is ignored. func parseFieldOptions(sf reflect.StructField) (out fieldOptions, err error) { tag, hasTag := sf.Tag.Lookup("json") // Check whether this field is explicitly ignored. if tag == "-" { return fieldOptions{}, errIgnoredField } // Check whether this field is unexported. if !sf.IsExported() { // In contrast to v1, v2 no longer forwards exported fields from // embedded fields of unexported types since Go reflection does not // allow the same set of operations that are available in normal cases // of purely exported fields. // See https://go.dev/issue/21357 and https://go.dev/issue/24153. if sf.Anonymous { return fieldOptions{}, fmt.Errorf("embedded Go struct field %s of an unexported type must be explicitly ignored with a `json:\"-\"` tag", sf.Type.Name()) } // Tag options specified on an unexported field suggests user error. if hasTag { return fieldOptions{}, fmt.Errorf("unexported Go struct field %s cannot have non-ignored `json:%q` tag", sf.Name, tag) } return fieldOptions{}, errIgnoredField } // Determine the JSON member name for this Go field. A user-specified name // may be provided as either an identifier or a single-quoted string. // The single-quoted string allows arbitrary characters in the name. // See https://go.dev/issue/2718 and https://go.dev/issue/3546. out.name = sf.Name // always starts with an uppercase character if len(tag) > 0 && !strings.HasPrefix(tag, ",") { // For better compatibility with v1, accept almost any unescaped name. n := len(tag) - len(strings.TrimLeftFunc(tag, func(r rune) bool { return !strings.ContainsRune(",\\'\"`", r) // reserve comma, backslash, and quotes })) opt := tag[:n] if n == 0 { // Allow a single quoted string for arbitrary names. opt, n, err = consumeTagOption(tag) if err != nil { return fieldOptions{}, fmt.Errorf("Go struct field %s has malformed `json` tag: %v", sf.Name, err) } } out.hasName = true out.name = opt tag = tag[n:] } b, _ := appendString(nil, out.name, false, nil) out.quotedName = string(b) // Handle any additional tag options (if any). var wasFormat bool seenOpts := make(map[string]bool) for len(tag) > 0 { // Consume comma delimiter. if tag[0] != ',' { return fieldOptions{}, fmt.Errorf("Go struct field %s has malformed `json` tag: invalid character %q before next option (expecting ',')", sf.Name, tag[0]) } tag = tag[len(","):] if len(tag) == 0 { return fieldOptions{}, fmt.Errorf("Go struct field %s has malformed `json` tag: invalid trailing ',' character", sf.Name) } // Consume and process the tag option. opt, n, err := consumeTagOption(tag) if err != nil { return fieldOptions{}, fmt.Errorf("Go struct field %s has malformed `json` tag: %v", sf.Name, err) } rawOpt := tag[:n] tag = tag[n:] switch { case wasFormat: return fieldOptions{}, fmt.Errorf("Go struct field %s has `format` tag option that was not specified last", sf.Name) case strings.HasPrefix(rawOpt, "'") && strings.TrimFunc(opt, isLetterOrDigit) == "": return fieldOptions{}, fmt.Errorf("Go struct field %s has unnecessarily quoted appearance of `%s` tag option; specify `%s` instead", sf.Name, rawOpt, opt) } switch opt { case "nocase": out.nocase = true case "inline": out.inline = true case "unknown": out.unknown = true case "omitzero": out.omitzero = true case "omitempty": out.omitempty = true case "string": out.string = true case "format": if !strings.HasPrefix(tag, ":") { return fieldOptions{}, fmt.Errorf("Go struct field %s is missing value for `format` tag option", sf.Name) } tag = tag[len(":"):] opt, n, err := consumeTagOption(tag) if err != nil { return fieldOptions{}, fmt.Errorf("Go struct field %s has malformed value for `format` tag option: %v", sf.Name, err) } tag = tag[n:] out.format = opt wasFormat = true default: // Reject keys that resemble one of the supported options. // This catches invalid mutants such as "omitEmpty" or "omit_empty". normOpt := strings.ReplaceAll(strings.ToLower(opt), "_", "") switch normOpt { case "nocase", "inline", "unknown", "omitzero", "omitempty", "string", "format": return fieldOptions{}, fmt.Errorf("Go struct field %s has invalid appearance of `%s` tag option; specify `%s` instead", sf.Name, opt, normOpt) } // NOTE: Everything else is ignored. This does not mean it is // forward compatible to insert arbitrary tag options since // a future version of this package may understand that tag. } // Reject duplicates. if seenOpts[opt] { return fieldOptions{}, fmt.Errorf("Go struct field %s has duplicate appearance of `%s` tag option", sf.Name, rawOpt) } seenOpts[opt] = true } return out, nil } func consumeTagOption(in string) (string, int, error) { switch r, _ := utf8.DecodeRuneInString(in); { // Option as a Go identifier. case r == '_' || unicode.IsLetter(r): n := len(in) - len(strings.TrimLeftFunc(in, isLetterOrDigit)) return in[:n], n, nil // Option as a single-quoted string. case r == '\'': // The grammar is nearly identical to a double-quoted Go string literal, // but uses single quotes as the terminators. The reason for a custom // grammar is because both backtick and double quotes cannot be used // verbatim in a struct tag. // // Convert a single-quoted string to a double-quote string and rely on // strconv.Unquote to handle the rest. var inEscape bool b := []byte{'"'} n := len(`'`) for len(in) > n { r, rn := utf8.DecodeRuneInString(in[n:]) switch { case inEscape: if r == '\'' { b = b[:len(b)-1] // remove escape character: `\'` => `'` } inEscape = false case r == '\\': inEscape = true case r == '"': b = append(b, '\\') // insert escape character: `"` => `\"` case r == '\'': b = append(b, '"') n += len(`'`) out, err := strconv.Unquote(string(b)) if err != nil { return "", 0, fmt.Errorf("invalid single-quoted string: %s", in[:n]) } return out, n, nil } b = append(b, in[n:][:rn]...) n += rn } if n > 10 { n = 10 // limit the amount of context printed in the error } return "", 0, fmt.Errorf("single-quoted string not terminated: %s...", in[:n]) case len(in) == 0: return "", 0, io.ErrUnexpectedEOF default: return "", 0, fmt.Errorf("invalid character %q at start of option (expecting Unicode letter or single quote)", r) } } func isLetterOrDigit(r rune) bool { return r == '_' || unicode.IsLetter(r) || unicode.IsNumber(r) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/kube-openapi/pkg/handler3/handler.go
vendor/k8s.io/kube-openapi/pkg/handler3/handler.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 handler3 import ( "bytes" "crypto/sha512" "encoding/json" "fmt" "net/http" "net/url" "path" "strconv" "strings" "sync" "time" "github.com/golang/protobuf/proto" openapi_v3 "github.com/google/gnostic-models/openapiv3" "github.com/google/uuid" "github.com/munnerz/goautoneg" "k8s.io/klog/v2" "k8s.io/kube-openapi/pkg/cached" "k8s.io/kube-openapi/pkg/common" "k8s.io/kube-openapi/pkg/spec3" ) const ( subTypeProtobufDeprecated = "com.github.proto-openapi.spec.v3@v1.0+protobuf" subTypeProtobuf = "com.github.proto-openapi.spec.v3.v1.0+protobuf" subTypeJSON = "json" ) // OpenAPIV3Discovery is the format of the Discovery document for OpenAPI V3 // It maps Discovery paths to their corresponding URLs with a hash parameter included type OpenAPIV3Discovery struct { Paths map[string]OpenAPIV3DiscoveryGroupVersion `json:"paths"` } // OpenAPIV3DiscoveryGroupVersion includes information about a group version and URL // for accessing the OpenAPI. The URL includes a hash parameter to support client side caching type OpenAPIV3DiscoveryGroupVersion struct { // Path is an absolute path of an OpenAPI V3 document in the form of /openapi/v3/apis/apps/v1?hash=014fbff9a07c ServerRelativeURL string `json:"serverRelativeURL"` } func ToV3ProtoBinary(json []byte) ([]byte, error) { document, err := openapi_v3.ParseDocument(json) if err != nil { return nil, err } return proto.Marshal(document) } type timedSpec struct { spec []byte lastModified time.Time } // This type is protected by the lock on OpenAPIService. type openAPIV3Group struct { specCache cached.LastSuccess[*spec3.OpenAPI] pbCache cached.Value[timedSpec] jsonCache cached.Value[timedSpec] } func newOpenAPIV3Group() *openAPIV3Group { o := &openAPIV3Group{} o.jsonCache = cached.Transform[*spec3.OpenAPI](func(spec *spec3.OpenAPI, etag string, err error) (timedSpec, string, error) { if err != nil { return timedSpec{}, "", err } json, err := json.Marshal(spec) if err != nil { return timedSpec{}, "", err } return timedSpec{spec: json, lastModified: time.Now()}, computeETag(json), nil }, &o.specCache) o.pbCache = cached.Transform(func(ts timedSpec, etag string, err error) (timedSpec, string, error) { if err != nil { return timedSpec{}, "", err } proto, err := ToV3ProtoBinary(ts.spec) if err != nil { return timedSpec{}, "", err } return timedSpec{spec: proto, lastModified: ts.lastModified}, etag, nil }, o.jsonCache) return o } func (o *openAPIV3Group) UpdateSpec(openapi cached.Value[*spec3.OpenAPI]) { o.specCache.Store(openapi) } // OpenAPIService is the service responsible for serving OpenAPI spec. It has // the ability to safely change the spec while serving it. type OpenAPIService struct { // Mutex protects the schema map. mutex sync.Mutex v3Schema map[string]*openAPIV3Group discoveryCache cached.LastSuccess[timedSpec] } func computeETag(data []byte) string { if data == nil { return "" } return fmt.Sprintf("%X", sha512.Sum512(data)) } func constructServerRelativeURL(gvString, etag string) string { u := url.URL{Path: path.Join("/openapi/v3", gvString)} query := url.Values{} query.Set("hash", etag) u.RawQuery = query.Encode() return u.String() } // NewOpenAPIService builds an OpenAPIService starting with the given spec. func NewOpenAPIService() *OpenAPIService { o := &OpenAPIService{} o.v3Schema = make(map[string]*openAPIV3Group) // We're not locked because we haven't shared the structure yet. o.discoveryCache.Store(o.buildDiscoveryCacheLocked()) return o } func (o *OpenAPIService) buildDiscoveryCacheLocked() cached.Value[timedSpec] { caches := make(map[string]cached.Value[timedSpec], len(o.v3Schema)) for gvName, group := range o.v3Schema { caches[gvName] = group.jsonCache } return cached.Merge(func(results map[string]cached.Result[timedSpec]) (timedSpec, string, error) { discovery := &OpenAPIV3Discovery{Paths: make(map[string]OpenAPIV3DiscoveryGroupVersion)} for gvName, result := range results { if result.Err != nil { return timedSpec{}, "", result.Err } discovery.Paths[gvName] = OpenAPIV3DiscoveryGroupVersion{ ServerRelativeURL: constructServerRelativeURL(gvName, result.Etag), } } j, err := json.Marshal(discovery) if err != nil { return timedSpec{}, "", err } return timedSpec{spec: j, lastModified: time.Now()}, computeETag(j), nil }, caches) } func (o *OpenAPIService) getSingleGroupBytes(getType string, group string) ([]byte, string, time.Time, error) { o.mutex.Lock() defer o.mutex.Unlock() v, ok := o.v3Schema[group] if !ok { return nil, "", time.Now(), fmt.Errorf("Cannot find CRD group %s", group) } switch getType { case subTypeJSON: ts, etag, err := v.jsonCache.Get() return ts.spec, etag, ts.lastModified, err case subTypeProtobuf, subTypeProtobufDeprecated: ts, etag, err := v.pbCache.Get() return ts.spec, etag, ts.lastModified, err default: return nil, "", time.Now(), fmt.Errorf("Invalid accept clause %s", getType) } } // UpdateGroupVersionLazy adds or updates an existing group with the new cached. func (o *OpenAPIService) UpdateGroupVersionLazy(group string, openapi cached.Value[*spec3.OpenAPI]) { o.mutex.Lock() defer o.mutex.Unlock() if _, ok := o.v3Schema[group]; !ok { o.v3Schema[group] = newOpenAPIV3Group() // Since there is a new item, we need to re-build the cache map. o.discoveryCache.Store(o.buildDiscoveryCacheLocked()) } o.v3Schema[group].UpdateSpec(openapi) } func (o *OpenAPIService) UpdateGroupVersion(group string, openapi *spec3.OpenAPI) { o.UpdateGroupVersionLazy(group, cached.Static(openapi, uuid.New().String())) } func (o *OpenAPIService) DeleteGroupVersion(group string) { o.mutex.Lock() defer o.mutex.Unlock() delete(o.v3Schema, group) // Rebuild the merge cache map since the items have changed. o.discoveryCache.Store(o.buildDiscoveryCacheLocked()) } func (o *OpenAPIService) HandleDiscovery(w http.ResponseWriter, r *http.Request) { ts, etag, err := o.discoveryCache.Get() if err != nil { klog.Errorf("Error serving discovery: %s", err) w.WriteHeader(http.StatusInternalServerError) return } w.Header().Set("Etag", strconv.Quote(etag)) w.Header().Set("Content-Type", "application/json") http.ServeContent(w, r, "/openapi/v3", ts.lastModified, bytes.NewReader(ts.spec)) } func (o *OpenAPIService) HandleGroupVersion(w http.ResponseWriter, r *http.Request) { url := strings.SplitAfterN(r.URL.Path, "/", 4) group := url[3] decipherableFormats := r.Header.Get("Accept") if decipherableFormats == "" { decipherableFormats = "*/*" } clauses := goautoneg.ParseAccept(decipherableFormats) w.Header().Add("Vary", "Accept") if len(clauses) == 0 { return } accepted := []struct { Type string SubType string ReturnedContentType string }{ {"application", subTypeJSON, "application/" + subTypeJSON}, {"application", subTypeProtobuf, "application/" + subTypeProtobuf}, {"application", subTypeProtobufDeprecated, "application/" + subTypeProtobuf}, } for _, clause := range clauses { for _, accepts := range accepted { if clause.Type != accepts.Type && clause.Type != "*" { continue } if clause.SubType != accepts.SubType && clause.SubType != "*" { continue } data, etag, lastModified, err := o.getSingleGroupBytes(accepts.SubType, group) if err != nil { return } // Set Content-Type header in the reponse w.Header().Set("Content-Type", accepts.ReturnedContentType) // ETag must be enclosed in double quotes: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag w.Header().Set("Etag", strconv.Quote(etag)) if hash := r.URL.Query().Get("hash"); hash != "" { if hash != etag { u := constructServerRelativeURL(group, etag) http.Redirect(w, r, u, 301) return } // The Vary header is required because the Accept header can // change the contents returned. This prevents clients from caching // protobuf as JSON and vice versa. w.Header().Set("Vary", "Accept") // Only set these headers when a hash is given. w.Header().Set("Cache-Control", "public, immutable") // Set the Expires directive to the maximum value of one year from the request, // effectively indicating that the cache never expires. w.Header().Set("Expires", time.Now().AddDate(1, 0, 0).Format(time.RFC1123)) } http.ServeContent(w, r, "", lastModified, bytes.NewReader(data)) return } } w.WriteHeader(406) return } func (o *OpenAPIService) RegisterOpenAPIV3VersionedService(servePath string, handler common.PathHandlerByGroupVersion) error { handler.Handle(servePath, http.HandlerFunc(o.HandleDiscovery)) handler.HandlePrefix(servePath+"/", http.HandlerFunc(o.HandleGroupVersion)) return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/apimachinery/third_party/forked/golang/json/fields.go
vendor/k8s.io/apimachinery/third_party/forked/golang/json/fields.go
// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package json is forked from the Go standard library to enable us to find the // field of a struct that a given JSON key maps to. package json import ( "bytes" "fmt" "reflect" "sort" "strings" "sync" "unicode" "unicode/utf8" ) const ( patchStrategyTagKey = "patchStrategy" patchMergeKeyTagKey = "patchMergeKey" ) // Finds the patchStrategy and patchMergeKey struct tag fields on a given // struct field given the struct type and the JSON name of the field. // It returns field type, a slice of patch strategies, merge key and error. // TODO: fix the returned errors to be introspectable. func LookupPatchMetadataForStruct(t reflect.Type, jsonField string) ( elemType reflect.Type, patchStrategies []string, patchMergeKey string, e error) { if t.Kind() == reflect.Pointer { t = t.Elem() } if t.Kind() != reflect.Struct { e = fmt.Errorf("merging an object in json but data type is not struct, instead is: %s", t.Kind().String()) return } jf := []byte(jsonField) // Find the field that the JSON library would use. var f *field fields := cachedTypeFields(t) for i := range fields { ff := &fields[i] if bytes.Equal(ff.nameBytes, jf) { f = ff break } // Do case-insensitive comparison. if f == nil && ff.equalFold(ff.nameBytes, jf) { f = ff } } if f != nil { // Find the reflect.Value of the most preferential struct field. tjf := t.Field(f.index[0]) // we must navigate down all the anonymously included structs in the chain for i := 1; i < len(f.index); i++ { tjf = tjf.Type.Field(f.index[i]) } patchStrategy := tjf.Tag.Get(patchStrategyTagKey) patchMergeKey = tjf.Tag.Get(patchMergeKeyTagKey) patchStrategies = strings.Split(patchStrategy, ",") elemType = tjf.Type return } e = fmt.Errorf("unable to find api field in struct %s for the json field %q", t.Name(), jsonField) return } // A field represents a single field found in a struct. type field struct { name string nameBytes []byte // []byte(name) equalFold func(s, t []byte) bool // bytes.EqualFold or equivalent tag bool // index is the sequence of indexes from the containing type fields to this field. // it is a slice because anonymous structs will need multiple navigation steps to correctly // resolve the proper fields index []int typ reflect.Type omitEmpty bool quoted bool } func (f field) String() string { return fmt.Sprintf("{name: %s, type: %v, tag: %v, index: %v, omitEmpty: %v, quoted: %v}", f.name, f.typ, f.tag, f.index, f.omitEmpty, f.quoted) } func fillField(f field) field { f.nameBytes = []byte(f.name) f.equalFold = foldFunc(f.nameBytes) return f } // byName sorts field by name, breaking ties with depth, // then breaking ties with "name came from json tag", then // breaking ties with index sequence. type byName []field func (x byName) Len() int { return len(x) } func (x byName) Swap(i, j int) { x[i], x[j] = x[j], x[i] } func (x byName) Less(i, j int) bool { if x[i].name != x[j].name { return x[i].name < x[j].name } if len(x[i].index) != len(x[j].index) { return len(x[i].index) < len(x[j].index) } if x[i].tag != x[j].tag { return x[i].tag } return byIndex(x).Less(i, j) } // byIndex sorts field by index sequence. type byIndex []field func (x byIndex) Len() int { return len(x) } func (x byIndex) Swap(i, j int) { x[i], x[j] = x[j], x[i] } func (x byIndex) Less(i, j int) bool { for k, xik := range x[i].index { if k >= len(x[j].index) { return false } if xik != x[j].index[k] { return xik < x[j].index[k] } } return len(x[i].index) < len(x[j].index) } // typeFields returns a list of fields that JSON should recognize for the given type. // The algorithm is breadth-first search over the set of structs to include - the top struct // and then any reachable anonymous structs. func typeFields(t reflect.Type) []field { // Anonymous fields to explore at the current level and the next. current := []field{} next := []field{{typ: t}} // Count of queued names for current level and the next. count := map[reflect.Type]int{} nextCount := map[reflect.Type]int{} // Types already visited at an earlier level. visited := map[reflect.Type]bool{} // Fields found. var fields []field for len(next) > 0 { current, next = next, current[:0] count, nextCount = nextCount, map[reflect.Type]int{} for _, f := range current { if visited[f.typ] { continue } visited[f.typ] = true // Scan f.typ for fields to include. for i := 0; i < f.typ.NumField(); i++ { sf := f.typ.Field(i) if sf.PkgPath != "" { // unexported continue } tag := sf.Tag.Get("json") if tag == "-" { continue } name, opts := parseTag(tag) if !isValidTag(name) { name = "" } index := make([]int, len(f.index)+1) copy(index, f.index) index[len(f.index)] = i ft := sf.Type if ft.Name() == "" && ft.Kind() == reflect.Pointer { // Follow pointer. ft = ft.Elem() } // Record found field and index sequence. if name != "" || !sf.Anonymous || ft.Kind() != reflect.Struct { tagged := name != "" if name == "" { name = sf.Name } fields = append(fields, fillField(field{ name: name, tag: tagged, index: index, typ: ft, omitEmpty: opts.Contains("omitempty"), quoted: opts.Contains("string"), })) if count[f.typ] > 1 { // If there were multiple instances, add a second, // so that the annihilation code will see a duplicate. // It only cares about the distinction between 1 or 2, // so don't bother generating any more copies. fields = append(fields, fields[len(fields)-1]) } continue } // Record new anonymous struct to explore in next round. nextCount[ft]++ if nextCount[ft] == 1 { next = append(next, fillField(field{name: ft.Name(), index: index, typ: ft})) } } } } sort.Sort(byName(fields)) // Delete all fields that are hidden by the Go rules for embedded fields, // except that fields with JSON tags are promoted. // The fields are sorted in primary order of name, secondary order // of field index length. Loop over names; for each name, delete // hidden fields by choosing the one dominant field that survives. out := fields[:0] for advance, i := 0, 0; i < len(fields); i += advance { // One iteration per name. // Find the sequence of fields with the name of this first field. fi := fields[i] name := fi.name for advance = 1; i+advance < len(fields); advance++ { fj := fields[i+advance] if fj.name != name { break } } if advance == 1 { // Only one field with this name out = append(out, fi) continue } dominant, ok := dominantField(fields[i : i+advance]) if ok { out = append(out, dominant) } } fields = out sort.Sort(byIndex(fields)) return fields } // dominantField looks through the fields, all of which are known to // have the same name, to find the single field that dominates the // others using Go's embedding rules, modified by the presence of // JSON tags. If there are multiple top-level fields, the boolean // will be false: This condition is an error in Go and we skip all // the fields. func dominantField(fields []field) (field, bool) { // The fields are sorted in increasing index-length order. The winner // must therefore be one with the shortest index length. Drop all // longer entries, which is easy: just truncate the slice. length := len(fields[0].index) tagged := -1 // Index of first tagged field. for i, f := range fields { if len(f.index) > length { fields = fields[:i] break } if f.tag { if tagged >= 0 { // Multiple tagged fields at the same level: conflict. // Return no field. return field{}, false } tagged = i } } if tagged >= 0 { return fields[tagged], true } // All remaining fields have the same length. If there's more than one, // we have a conflict (two fields named "X" at the same level) and we // return no field. if len(fields) > 1 { return field{}, false } return fields[0], true } var fieldCache struct { sync.RWMutex m map[reflect.Type][]field } // cachedTypeFields is like typeFields but uses a cache to avoid repeated work. func cachedTypeFields(t reflect.Type) []field { fieldCache.RLock() f := fieldCache.m[t] fieldCache.RUnlock() if f != nil { return f } // Compute fields without lock. // Might duplicate effort but won't hold other computations back. f = typeFields(t) if f == nil { f = []field{} } fieldCache.Lock() if fieldCache.m == nil { fieldCache.m = map[reflect.Type][]field{} } fieldCache.m[t] = f fieldCache.Unlock() return f } func isValidTag(s string) bool { if s == "" { return false } for _, c := range s { switch { case strings.ContainsRune("!#$%&()*+-./:<=>?@[]^_{|}~ ", c): // Backslash and quote chars are reserved, but // otherwise any punctuation chars are allowed // in a tag name. default: if !unicode.IsLetter(c) && !unicode.IsDigit(c) { return false } } } return true } const ( caseMask = ^byte(0x20) // Mask to ignore case in ASCII. kelvin = '\u212a' smallLongEss = '\u017f' ) // foldFunc returns one of four different case folding equivalence // functions, from most general (and slow) to fastest: // // 1) bytes.EqualFold, if the key s contains any non-ASCII UTF-8 // 2) equalFoldRight, if s contains special folding ASCII ('k', 'K', 's', 'S') // 3) asciiEqualFold, no special, but includes non-letters (including _) // 4) simpleLetterEqualFold, no specials, no non-letters. // // The letters S and K are special because they map to 3 runes, not just 2: // * S maps to s and to U+017F 'ſ' Latin small letter long s // * k maps to K and to U+212A 'K' Kelvin sign // See http://play.golang.org/p/tTxjOc0OGo // // The returned function is specialized for matching against s and // should only be given s. It's not curried for performance reasons. func foldFunc(s []byte) func(s, t []byte) bool { nonLetter := false special := false // special letter for _, b := range s { if b >= utf8.RuneSelf { return bytes.EqualFold } upper := b & caseMask if upper < 'A' || upper > 'Z' { nonLetter = true } else if upper == 'K' || upper == 'S' { // See above for why these letters are special. special = true } } if special { return equalFoldRight } if nonLetter { return asciiEqualFold } return simpleLetterEqualFold } // equalFoldRight is a specialization of bytes.EqualFold when s is // known to be all ASCII (including punctuation), but contains an 's', // 'S', 'k', or 'K', requiring a Unicode fold on the bytes in t. // See comments on foldFunc. func equalFoldRight(s, t []byte) bool { for _, sb := range s { if len(t) == 0 { return false } tb := t[0] if tb < utf8.RuneSelf { if sb != tb { sbUpper := sb & caseMask if 'A' <= sbUpper && sbUpper <= 'Z' { if sbUpper != tb&caseMask { return false } } else { return false } } t = t[1:] continue } // sb is ASCII and t is not. t must be either kelvin // sign or long s; sb must be s, S, k, or K. tr, size := utf8.DecodeRune(t) switch sb { case 's', 'S': if tr != smallLongEss { return false } case 'k', 'K': if tr != kelvin { return false } default: return false } t = t[size:] } if len(t) > 0 { return false } return true } // asciiEqualFold is a specialization of bytes.EqualFold for use when // s is all ASCII (but may contain non-letters) and contains no // special-folding letters. // See comments on foldFunc. func asciiEqualFold(s, t []byte) bool { if len(s) != len(t) { return false } for i, sb := range s { tb := t[i] if sb == tb { continue } if ('a' <= sb && sb <= 'z') || ('A' <= sb && sb <= 'Z') { if sb&caseMask != tb&caseMask { return false } } else { return false } } return true } // simpleLetterEqualFold is a specialization of bytes.EqualFold for // use when s is all ASCII letters (no underscores, etc) and also // doesn't contain 'k', 'K', 's', or 'S'. // See comments on foldFunc. func simpleLetterEqualFold(s, t []byte) bool { if len(s) != len(t) { return false } for i, b := range s { if b&caseMask != t[i]&caseMask { return false } } return true } // tagOptions is the string following a comma in a struct field's "json" // tag, or the empty string. It does not include the leading comma. type tagOptions string // parseTag splits a struct field's json tag into its name and // comma-separated options. func parseTag(tag string) (string, tagOptions) { if idx := strings.Index(tag, ","); idx != -1 { return tag[:idx], tagOptions(tag[idx+1:]) } return tag, tagOptions("") } // Contains reports whether a comma-separated list of options // contains a particular substr flag. substr must be surrounded by a // string boundary or commas. func (o tagOptions) Contains(optionName string) bool { if len(o) == 0 { return false } s := string(o) for s != "" { var next string i := strings.Index(s, ",") if i >= 0 { s, next = s[:i], s[i+1:] } if s == optionName { return true } s = next } return false }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/apimachinery/third_party/forked/golang/reflect/deep_equal.go
vendor/k8s.io/apimachinery/third_party/forked/golang/reflect/deep_equal.go
// Copyright 2009 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 reflect is a fork of go's standard library reflection package, which // allows for deep equal with equality functions defined. package reflect import ( "fmt" "reflect" "strings" ) // Equalities is a map from type to a function comparing two values of // that type. type Equalities map[reflect.Type]reflect.Value // For convenience, panics on errors func EqualitiesOrDie(funcs ...interface{}) Equalities { e := Equalities{} if err := e.AddFuncs(funcs...); err != nil { panic(err) } return e } // AddFuncs is a shortcut for multiple calls to AddFunc. func (e Equalities) AddFuncs(funcs ...interface{}) error { for _, f := range funcs { if err := e.AddFunc(f); err != nil { return err } } return nil } // AddFunc uses func as an equality function: it must take // two parameters of the same type, and return a boolean. func (e Equalities) AddFunc(eqFunc interface{}) error { fv := reflect.ValueOf(eqFunc) ft := fv.Type() if ft.Kind() != reflect.Func { return fmt.Errorf("expected func, got: %v", ft) } if ft.NumIn() != 2 { return fmt.Errorf("expected two 'in' params, got: %v", ft) } if ft.NumOut() != 1 { return fmt.Errorf("expected one 'out' param, got: %v", ft) } if ft.In(0) != ft.In(1) { return fmt.Errorf("expected arg 1 and 2 to have same type, but got %v", ft) } var forReturnType bool boolType := reflect.TypeOf(forReturnType) if ft.Out(0) != boolType { return fmt.Errorf("expected bool return, got: %v", ft) } e[ft.In(0)] = fv return nil } // Below here is forked from go's reflect/deepequal.go // During deepValueEqual, must keep track of checks that are // in progress. The comparison algorithm assumes that all // checks in progress are true when it reencounters them. // Visited comparisons are stored in a map indexed by visit. type visit struct { a1 uintptr a2 uintptr typ reflect.Type } // unexportedTypePanic is thrown when you use this DeepEqual on something that has an // unexported type. It indicates a programmer error, so should not occur at runtime, // which is why it's not public and thus impossible to catch. type unexportedTypePanic []reflect.Type func (u unexportedTypePanic) Error() string { return u.String() } func (u unexportedTypePanic) String() string { strs := make([]string, len(u)) for i, t := range u { strs[i] = fmt.Sprintf("%v", t) } return "an unexported field was encountered, nested like this: " + strings.Join(strs, " -> ") } func makeUsefulPanic(v reflect.Value) { if x := recover(); x != nil { if u, ok := x.(unexportedTypePanic); ok { u = append(unexportedTypePanic{v.Type()}, u...) x = u } panic(x) } } // Tests for deep equality using reflected types. The map argument tracks // comparisons that have already been seen, which allows short circuiting on // recursive types. // equateNilAndEmpty controls whether empty maps/slices are equivalent to nil func (e Equalities) deepValueEqual(v1, v2 reflect.Value, visited map[visit]bool, equateNilAndEmpty bool, depth int) bool { defer makeUsefulPanic(v1) if !v1.IsValid() || !v2.IsValid() { return v1.IsValid() == v2.IsValid() } if v1.Type() != v2.Type() { return false } if fv, ok := e[v1.Type()]; ok { return fv.Call([]reflect.Value{v1, v2})[0].Bool() } hard := func(k reflect.Kind) bool { switch k { case reflect.Array, reflect.Map, reflect.Slice, reflect.Struct: return true } return false } if v1.CanAddr() && v2.CanAddr() && hard(v1.Kind()) { addr1 := v1.UnsafeAddr() addr2 := v2.UnsafeAddr() if addr1 > addr2 { // Canonicalize order to reduce number of entries in visited. addr1, addr2 = addr2, addr1 } // Short circuit if references are identical ... if addr1 == addr2 { return true } // ... or already seen typ := v1.Type() v := visit{addr1, addr2, typ} if visited[v] { return true } // Remember for later. visited[v] = true } switch v1.Kind() { case reflect.Array: // We don't need to check length here because length is part of // an array's type, which has already been filtered for. for i := 0; i < v1.Len(); i++ { if !e.deepValueEqual(v1.Index(i), v2.Index(i), visited, equateNilAndEmpty, depth+1) { return false } } return true case reflect.Slice: if equateNilAndEmpty { if (v1.IsNil() || v1.Len() == 0) != (v2.IsNil() || v2.Len() == 0) { return false } if v1.IsNil() || v1.Len() == 0 { return true } } else { if v1.IsNil() != v2.IsNil() { return false } // Optimize nil and empty cases // Two lists that are BOTH nil are equal // No need to check v2 is nil since v1.IsNil == v2.IsNil from above if v1.IsNil() { return true } // Two lists that are both empty and both non nil are equal if v1.Len() == 0 || v2.Len() == 0 { return true } } if v1.Len() != v2.Len() { return false } if v1.Pointer() == v2.Pointer() { return true } for i := 0; i < v1.Len(); i++ { if !e.deepValueEqual(v1.Index(i), v2.Index(i), visited, equateNilAndEmpty, depth+1) { return false } } return true case reflect.Interface: if v1.IsNil() || v2.IsNil() { return v1.IsNil() == v2.IsNil() } return e.deepValueEqual(v1.Elem(), v2.Elem(), visited, equateNilAndEmpty, depth+1) case reflect.Ptr: return e.deepValueEqual(v1.Elem(), v2.Elem(), visited, equateNilAndEmpty, depth+1) case reflect.Struct: for i, n := 0, v1.NumField(); i < n; i++ { if !e.deepValueEqual(v1.Field(i), v2.Field(i), visited, equateNilAndEmpty, depth+1) { return false } } return true case reflect.Map: if equateNilAndEmpty { if (v1.IsNil() || v1.Len() == 0) != (v2.IsNil() || v2.Len() == 0) { return false } if v1.IsNil() || v1.Len() == 0 { return true } } else { if v1.IsNil() != v2.IsNil() { return false } // Optimize nil and empty cases // Two maps that are BOTH nil are equal // No need to check v2 is nil since v1.IsNil == v2.IsNil from above if v1.IsNil() { return true } // Two maps that are both empty and both non nil are equal if v1.Len() == 0 || v2.Len() == 0 { return true } } if v1.Len() != v2.Len() { return false } if v1.Pointer() == v2.Pointer() { return true } for _, k := range v1.MapKeys() { if !e.deepValueEqual(v1.MapIndex(k), v2.MapIndex(k), visited, equateNilAndEmpty, depth+1) { return false } } return true case reflect.Func: if v1.IsNil() && v2.IsNil() { return true } // Can't do better than this: return false default: // Normal equality suffices if !v1.CanInterface() || !v2.CanInterface() { panic(unexportedTypePanic{}) } return v1.Interface() == v2.Interface() } } // DeepEqual is like reflect.DeepEqual, but focused on semantic equality // instead of memory equality. // // It will use e's equality functions if it finds types that match. // // An empty slice *is* equal to a nil slice for our purposes; same for maps. // // Unexported field members cannot be compared and will cause an informative panic; you must add an Equality // function for these types. func (e Equalities) DeepEqual(a1, a2 interface{}) bool { return e.deepEqual(a1, a2, true) } func (e Equalities) DeepEqualWithNilDifferentFromEmpty(a1, a2 interface{}) bool { return e.deepEqual(a1, a2, false) } func (e Equalities) deepEqual(a1, a2 interface{}, equateNilAndEmpty bool) bool { if a1 == nil || a2 == nil { return a1 == a2 } v1 := reflect.ValueOf(a1) v2 := reflect.ValueOf(a2) if v1.Type() != v2.Type() { return false } return e.deepValueEqual(v1, v2, make(map[visit]bool), equateNilAndEmpty, 0) } func (e Equalities) deepValueDerive(v1, v2 reflect.Value, visited map[visit]bool, depth int) bool { defer makeUsefulPanic(v1) if !v1.IsValid() || !v2.IsValid() { return v1.IsValid() == v2.IsValid() } if v1.Type() != v2.Type() { return false } if fv, ok := e[v1.Type()]; ok { return fv.Call([]reflect.Value{v1, v2})[0].Bool() } hard := func(k reflect.Kind) bool { switch k { case reflect.Array, reflect.Map, reflect.Slice, reflect.Struct: return true } return false } if v1.CanAddr() && v2.CanAddr() && hard(v1.Kind()) { addr1 := v1.UnsafeAddr() addr2 := v2.UnsafeAddr() if addr1 > addr2 { // Canonicalize order to reduce number of entries in visited. addr1, addr2 = addr2, addr1 } // Short circuit if references are identical ... if addr1 == addr2 { return true } // ... or already seen typ := v1.Type() v := visit{addr1, addr2, typ} if visited[v] { return true } // Remember for later. visited[v] = true } switch v1.Kind() { case reflect.Array: // We don't need to check length here because length is part of // an array's type, which has already been filtered for. for i := 0; i < v1.Len(); i++ { if !e.deepValueDerive(v1.Index(i), v2.Index(i), visited, depth+1) { return false } } return true case reflect.Slice: if v1.IsNil() || v1.Len() == 0 { return true } if v1.Len() > v2.Len() { return false } if v1.Pointer() == v2.Pointer() { return true } for i := 0; i < v1.Len(); i++ { if !e.deepValueDerive(v1.Index(i), v2.Index(i), visited, depth+1) { return false } } return true case reflect.String: if v1.Len() == 0 { return true } if v1.Len() > v2.Len() { return false } return v1.String() == v2.String() case reflect.Interface: if v1.IsNil() { return true } return e.deepValueDerive(v1.Elem(), v2.Elem(), visited, depth+1) case reflect.Pointer: if v1.IsNil() { return true } return e.deepValueDerive(v1.Elem(), v2.Elem(), visited, depth+1) case reflect.Struct: for i, n := 0, v1.NumField(); i < n; i++ { if !e.deepValueDerive(v1.Field(i), v2.Field(i), visited, depth+1) { return false } } return true case reflect.Map: if v1.IsNil() || v1.Len() == 0 { return true } if v1.Len() > v2.Len() { return false } if v1.Pointer() == v2.Pointer() { return true } for _, k := range v1.MapKeys() { if !e.deepValueDerive(v1.MapIndex(k), v2.MapIndex(k), visited, depth+1) { return false } } return true case reflect.Func: if v1.IsNil() && v2.IsNil() { return true } // Can't do better than this: return false default: // Normal equality suffices if !v1.CanInterface() || !v2.CanInterface() { panic(unexportedTypePanic{}) } return v1.Interface() == v2.Interface() } } // DeepDerivative is similar to DeepEqual except that unset fields in a1 are // ignored (not compared). This allows us to focus on the fields that matter to // the semantic comparison. // // The unset fields include a nil pointer and an empty string. func (e Equalities) DeepDerivative(a1, a2 interface{}) bool { if a1 == nil { return true } v1 := reflect.ValueOf(a1) v2 := reflect.ValueOf(a2) if v1.Type() != v2.Type() { return false } return e.deepValueDerive(v1, v2, make(map[visit]bool), 0) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/apimachinery/third_party/forked/golang/netutil/addr.go
vendor/k8s.io/apimachinery/third_party/forked/golang/netutil/addr.go
package netutil import ( "net/url" "strings" ) // FROM: http://golang.org/src/net/http/client.go // Given a string of the form "host", "host:port", or "[ipv6::address]:port", // return true if the string includes a port. func hasPort(s string) bool { return strings.LastIndex(s, ":") > strings.LastIndex(s, "]") } // FROM: http://golang.org/src/net/http/transport.go var portMap = map[string]string{ "http": "80", "https": "443", "socks5": "1080", } // FROM: http://golang.org/src/net/http/transport.go // canonicalAddr returns url.Host but always with a ":port" suffix func CanonicalAddr(url *url.URL) string { addr := url.Host if !hasPort(addr) { return addr + ":" + portMap[url.Scheme] } return addr }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/apimachinery/pkg/util/validation/validation.go
vendor/k8s.io/apimachinery/pkg/util/validation/validation.go
/* Copyright 2014 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 validation import ( "fmt" "math" "regexp" "strings" "unicode" "k8s.io/apimachinery/pkg/util/validation/field" netutils "k8s.io/utils/net" ) const qnameCharFmt string = "[A-Za-z0-9]" const qnameExtCharFmt string = "[-A-Za-z0-9_.]" const qualifiedNameFmt string = "(" + qnameCharFmt + qnameExtCharFmt + "*)?" + qnameCharFmt const qualifiedNameErrMsg string = "must consist of alphanumeric characters, '-', '_' or '.', and must start and end with an alphanumeric character" const qualifiedNameMaxLength int = 63 var qualifiedNameRegexp = regexp.MustCompile("^" + qualifiedNameFmt + "$") // IsQualifiedName tests whether the value passed is what Kubernetes calls a // "qualified name". This is a format used in various places throughout the // system. If the value is not valid, a list of error strings is returned. // Otherwise an empty list (or nil) is returned. func IsQualifiedName(value string) []string { var errs []string parts := strings.Split(value, "/") var name string switch len(parts) { case 1: name = parts[0] case 2: var prefix string prefix, name = parts[0], parts[1] if len(prefix) == 0 { errs = append(errs, "prefix part "+EmptyError()) } else if msgs := IsDNS1123Subdomain(prefix); len(msgs) != 0 { errs = append(errs, prefixEach(msgs, "prefix part ")...) } default: return append(errs, "a qualified name "+RegexError(qualifiedNameErrMsg, qualifiedNameFmt, "MyName", "my.name", "123-abc")+ " with an optional DNS subdomain prefix and '/' (e.g. 'example.com/MyName')") } if len(name) == 0 { errs = append(errs, "name part "+EmptyError()) } else if len(name) > qualifiedNameMaxLength { errs = append(errs, "name part "+MaxLenError(qualifiedNameMaxLength)) } if !qualifiedNameRegexp.MatchString(name) { errs = append(errs, "name part "+RegexError(qualifiedNameErrMsg, qualifiedNameFmt, "MyName", "my.name", "123-abc")) } return errs } // IsFullyQualifiedName checks if the name is fully qualified. This is similar // to IsFullyQualifiedDomainName but requires a minimum of 3 segments instead of // 2 and does not accept a trailing . as valid. // TODO: This function is deprecated and preserved until all callers migrate to // IsFullyQualifiedDomainName; please don't add new callers. func IsFullyQualifiedName(fldPath *field.Path, name string) field.ErrorList { var allErrors field.ErrorList if len(name) == 0 { return append(allErrors, field.Required(fldPath, "")) } if errs := IsDNS1123Subdomain(name); len(errs) > 0 { return append(allErrors, field.Invalid(fldPath, name, strings.Join(errs, ","))) } if len(strings.Split(name, ".")) < 3 { return append(allErrors, field.Invalid(fldPath, name, "should be a domain with at least three segments separated by dots")) } return allErrors } // IsFullyQualifiedDomainName checks if the domain name is fully qualified. This // is similar to IsFullyQualifiedName but only requires a minimum of 2 segments // instead of 3 and accepts a trailing . as valid. func IsFullyQualifiedDomainName(fldPath *field.Path, name string) field.ErrorList { var allErrors field.ErrorList if len(name) == 0 { return append(allErrors, field.Required(fldPath, "")) } if strings.HasSuffix(name, ".") { name = name[:len(name)-1] } if errs := IsDNS1123Subdomain(name); len(errs) > 0 { return append(allErrors, field.Invalid(fldPath, name, strings.Join(errs, ","))) } if len(strings.Split(name, ".")) < 2 { return append(allErrors, field.Invalid(fldPath, name, "should be a domain with at least two segments separated by dots")) } for _, label := range strings.Split(name, ".") { if errs := IsDNS1123Label(label); len(errs) > 0 { return append(allErrors, field.Invalid(fldPath, label, strings.Join(errs, ","))) } } return allErrors } // Allowed characters in an HTTP Path as defined by RFC 3986. A HTTP path may // contain: // * unreserved characters (alphanumeric, '-', '.', '_', '~') // * percent-encoded octets // * sub-delims ("!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=") // * a colon character (":") const httpPathFmt string = `[A-Za-z0-9/\-._~%!$&'()*+,;=:]+` var httpPathRegexp = regexp.MustCompile("^" + httpPathFmt + "$") // IsDomainPrefixedPath checks if the given string is a domain-prefixed path // (e.g. acme.io/foo). All characters before the first "/" must be a valid // subdomain as defined by RFC 1123. All characters trailing the first "/" must // be valid HTTP Path characters as defined by RFC 3986. func IsDomainPrefixedPath(fldPath *field.Path, dpPath string) field.ErrorList { var allErrs field.ErrorList if len(dpPath) == 0 { return append(allErrs, field.Required(fldPath, "")) } segments := strings.SplitN(dpPath, "/", 2) if len(segments) != 2 || len(segments[0]) == 0 || len(segments[1]) == 0 { return append(allErrs, field.Invalid(fldPath, dpPath, "must be a domain-prefixed path (such as \"acme.io/foo\")")) } host := segments[0] for _, err := range IsDNS1123Subdomain(host) { allErrs = append(allErrs, field.Invalid(fldPath, host, err)) } path := segments[1] if !httpPathRegexp.MatchString(path) { return append(allErrs, field.Invalid(fldPath, path, RegexError("Invalid path", httpPathFmt))) } return allErrs } const labelValueFmt string = "(" + qualifiedNameFmt + ")?" const labelValueErrMsg string = "a valid label must be an empty string or consist of alphanumeric characters, '-', '_' or '.', and must start and end with an alphanumeric character" // LabelValueMaxLength is a label's max length const LabelValueMaxLength int = 63 var labelValueRegexp = regexp.MustCompile("^" + labelValueFmt + "$") // IsValidLabelValue tests whether the value passed is a valid label value. If // the value is not valid, a list of error strings is returned. Otherwise an // empty list (or nil) is returned. func IsValidLabelValue(value string) []string { var errs []string if len(value) > LabelValueMaxLength { errs = append(errs, MaxLenError(LabelValueMaxLength)) } if !labelValueRegexp.MatchString(value) { errs = append(errs, RegexError(labelValueErrMsg, labelValueFmt, "MyValue", "my_value", "12345")) } return errs } const dns1123LabelFmt string = "[a-z0-9]([-a-z0-9]*[a-z0-9])?" const dns1123LabelFmtWithUnderscore string = "_?[a-z0-9]([-_a-z0-9]*[a-z0-9])?" const dns1123LabelErrMsg string = "a lowercase RFC 1123 label must consist of lower case alphanumeric characters or '-', and must start and end with an alphanumeric character" // DNS1123LabelMaxLength is a label's max length in DNS (RFC 1123) const DNS1123LabelMaxLength int = 63 var dns1123LabelRegexp = regexp.MustCompile("^" + dns1123LabelFmt + "$") // IsDNS1123Label tests for a string that conforms to the definition of a label in // DNS (RFC 1123). func IsDNS1123Label(value string) []string { var errs []string if len(value) > DNS1123LabelMaxLength { errs = append(errs, MaxLenError(DNS1123LabelMaxLength)) } if !dns1123LabelRegexp.MatchString(value) { if dns1123SubdomainRegexp.MatchString(value) { // It was a valid subdomain and not a valid label. Since we // already checked length, it must be dots. errs = append(errs, "must not contain dots") } else { errs = append(errs, RegexError(dns1123LabelErrMsg, dns1123LabelFmt, "my-name", "123-abc")) } } return errs } const dns1123SubdomainFmt string = dns1123LabelFmt + "(\\." + dns1123LabelFmt + ")*" const dns1123SubdomainErrorMsg string = "a lowercase RFC 1123 subdomain must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character" const dns1123SubdomainFmtWithUnderscore string = dns1123LabelFmtWithUnderscore + "(\\." + dns1123LabelFmtWithUnderscore + ")*" const dns1123SubdomainErrorMsgFG string = "a lowercase RFC 1123 subdomain must consist of lower case alphanumeric characters, '_', '-' or '.', and must start and end with an alphanumeric character" // DNS1123SubdomainMaxLength is a subdomain's max length in DNS (RFC 1123) const DNS1123SubdomainMaxLength int = 253 var dns1123SubdomainRegexp = regexp.MustCompile("^" + dns1123SubdomainFmt + "$") var dns1123SubdomainRegexpWithUnderscore = regexp.MustCompile("^" + dns1123SubdomainFmtWithUnderscore + "$") // IsDNS1123Subdomain tests for a string that conforms to the definition of a // subdomain in DNS (RFC 1123). func IsDNS1123Subdomain(value string) []string { var errs []string if len(value) > DNS1123SubdomainMaxLength { errs = append(errs, MaxLenError(DNS1123SubdomainMaxLength)) } if !dns1123SubdomainRegexp.MatchString(value) { errs = append(errs, RegexError(dns1123SubdomainErrorMsg, dns1123SubdomainFmt, "example.com")) } return errs } // IsDNS1123SubdomainWithUnderscore tests for a string that conforms to the definition of a // subdomain in DNS (RFC 1123), but allows the use of an underscore in the string func IsDNS1123SubdomainWithUnderscore(value string) []string { var errs []string if len(value) > DNS1123SubdomainMaxLength { errs = append(errs, MaxLenError(DNS1123SubdomainMaxLength)) } if !dns1123SubdomainRegexpWithUnderscore.MatchString(value) { errs = append(errs, RegexError(dns1123SubdomainErrorMsgFG, dns1123SubdomainFmt, "example.com")) } return errs } const dns1035LabelFmt string = "[a-z]([-a-z0-9]*[a-z0-9])?" const dns1035LabelErrMsg string = "a DNS-1035 label must consist of lower case alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character" // DNS1035LabelMaxLength is a label's max length in DNS (RFC 1035) const DNS1035LabelMaxLength int = 63 var dns1035LabelRegexp = regexp.MustCompile("^" + dns1035LabelFmt + "$") // IsDNS1035Label tests for a string that conforms to the definition of a label in // DNS (RFC 1035). func IsDNS1035Label(value string) []string { var errs []string if len(value) > DNS1035LabelMaxLength { errs = append(errs, MaxLenError(DNS1035LabelMaxLength)) } if !dns1035LabelRegexp.MatchString(value) { errs = append(errs, RegexError(dns1035LabelErrMsg, dns1035LabelFmt, "my-name", "abc-123")) } return errs } // wildcard definition - RFC 1034 section 4.3.3. // examples: // - valid: *.bar.com, *.foo.bar.com // - invalid: *.*.bar.com, *.foo.*.com, *bar.com, f*.bar.com, * const wildcardDNS1123SubdomainFmt = "\\*\\." + dns1123SubdomainFmt const wildcardDNS1123SubdomainErrMsg = "a wildcard DNS-1123 subdomain must start with '*.', followed by a valid DNS subdomain, which must consist of lower case alphanumeric characters, '-' or '.' and end with an alphanumeric character" // IsWildcardDNS1123Subdomain tests for a string that conforms to the definition of a // wildcard subdomain in DNS (RFC 1034 section 4.3.3). func IsWildcardDNS1123Subdomain(value string) []string { wildcardDNS1123SubdomainRegexp := regexp.MustCompile("^" + wildcardDNS1123SubdomainFmt + "$") var errs []string if len(value) > DNS1123SubdomainMaxLength { errs = append(errs, MaxLenError(DNS1123SubdomainMaxLength)) } if !wildcardDNS1123SubdomainRegexp.MatchString(value) { errs = append(errs, RegexError(wildcardDNS1123SubdomainErrMsg, wildcardDNS1123SubdomainFmt, "*.example.com")) } return errs } const cIdentifierFmt string = "[A-Za-z_][A-Za-z0-9_]*" const identifierErrMsg string = "a valid C identifier must start with alphabetic character or '_', followed by a string of alphanumeric characters or '_'" var cIdentifierRegexp = regexp.MustCompile("^" + cIdentifierFmt + "$") // IsCIdentifier tests for a string that conforms the definition of an identifier // in C. This checks the format, but not the length. func IsCIdentifier(value string) []string { if !cIdentifierRegexp.MatchString(value) { return []string{RegexError(identifierErrMsg, cIdentifierFmt, "my_name", "MY_NAME", "MyName")} } return nil } // IsValidPortNum tests that the argument is a valid, non-zero port number. func IsValidPortNum(port int) []string { if 1 <= port && port <= 65535 { return nil } return []string{InclusiveRangeError(1, 65535)} } // IsInRange tests that the argument is in an inclusive range. func IsInRange(value int, min int, max int) []string { if value >= min && value <= max { return nil } return []string{InclusiveRangeError(min, max)} } // Now in libcontainer UID/GID limits is 0 ~ 1<<31 - 1 // TODO: once we have a type for UID/GID we should make these that type. const ( minUserID = 0 maxUserID = math.MaxInt32 minGroupID = 0 maxGroupID = math.MaxInt32 ) // IsValidGroupID tests that the argument is a valid Unix GID. func IsValidGroupID(gid int64) []string { if minGroupID <= gid && gid <= maxGroupID { return nil } return []string{InclusiveRangeError(minGroupID, maxGroupID)} } // IsValidUserID tests that the argument is a valid Unix UID. func IsValidUserID(uid int64) []string { if minUserID <= uid && uid <= maxUserID { return nil } return []string{InclusiveRangeError(minUserID, maxUserID)} } var portNameCharsetRegex = regexp.MustCompile("^[-a-z0-9]+$") var portNameOneLetterRegexp = regexp.MustCompile("[a-z]") // IsValidPortName check that the argument is valid syntax. It must be // non-empty and no more than 15 characters long. It may contain only [-a-z0-9] // and must contain at least one letter [a-z]. It must not start or end with a // hyphen, nor contain adjacent hyphens. // // Note: We only allow lower-case characters, even though RFC 6335 is case // insensitive. func IsValidPortName(port string) []string { var errs []string if len(port) > 15 { errs = append(errs, MaxLenError(15)) } if !portNameCharsetRegex.MatchString(port) { errs = append(errs, "must contain only alpha-numeric characters (a-z, 0-9), and hyphens (-)") } if !portNameOneLetterRegexp.MatchString(port) { errs = append(errs, "must contain at least one letter (a-z)") } if strings.Contains(port, "--") { errs = append(errs, "must not contain consecutive hyphens") } if len(port) > 0 && (port[0] == '-' || port[len(port)-1] == '-') { errs = append(errs, "must not begin or end with a hyphen") } return errs } // IsValidIP tests that the argument is a valid IP address. func IsValidIP(fldPath *field.Path, value string) field.ErrorList { var allErrors field.ErrorList if netutils.ParseIPSloppy(value) == nil { allErrors = append(allErrors, field.Invalid(fldPath, value, "must be a valid IP address, (e.g. 10.9.8.7 or 2001:db8::ffff)")) } return allErrors } // IsValidIPv4Address tests that the argument is a valid IPv4 address. func IsValidIPv4Address(fldPath *field.Path, value string) field.ErrorList { var allErrors field.ErrorList ip := netutils.ParseIPSloppy(value) if ip == nil || ip.To4() == nil { allErrors = append(allErrors, field.Invalid(fldPath, value, "must be a valid IPv4 address")) } return allErrors } // IsValidIPv6Address tests that the argument is a valid IPv6 address. func IsValidIPv6Address(fldPath *field.Path, value string) field.ErrorList { var allErrors field.ErrorList ip := netutils.ParseIPSloppy(value) if ip == nil || ip.To4() != nil { allErrors = append(allErrors, field.Invalid(fldPath, value, "must be a valid IPv6 address")) } return allErrors } // IsValidCIDR tests that the argument is a valid CIDR value. func IsValidCIDR(fldPath *field.Path, value string) field.ErrorList { var allErrors field.ErrorList _, _, err := netutils.ParseCIDRSloppy(value) if err != nil { allErrors = append(allErrors, field.Invalid(fldPath, value, "must be a valid CIDR value, (e.g. 10.9.8.0/24 or 2001:db8::/64)")) } return allErrors } const percentFmt string = "[0-9]+%" const percentErrMsg string = "a valid percent string must be a numeric string followed by an ending '%'" var percentRegexp = regexp.MustCompile("^" + percentFmt + "$") // IsValidPercent checks that string is in the form of a percentage func IsValidPercent(percent string) []string { if !percentRegexp.MatchString(percent) { return []string{RegexError(percentErrMsg, percentFmt, "1%", "93%")} } return nil } const httpHeaderNameFmt string = "[-A-Za-z0-9]+" const httpHeaderNameErrMsg string = "a valid HTTP header must consist of alphanumeric characters or '-'" var httpHeaderNameRegexp = regexp.MustCompile("^" + httpHeaderNameFmt + "$") // IsHTTPHeaderName checks that a string conforms to the Go HTTP library's // definition of a valid header field name (a stricter subset than RFC7230). func IsHTTPHeaderName(value string) []string { if !httpHeaderNameRegexp.MatchString(value) { return []string{RegexError(httpHeaderNameErrMsg, httpHeaderNameFmt, "X-Header-Name")} } return nil } const envVarNameFmt = "[-._a-zA-Z][-._a-zA-Z0-9]*" const envVarNameFmtErrMsg string = "a valid environment variable name must consist of alphabetic characters, digits, '_', '-', or '.', and must not start with a digit" // TODO(hirazawaui): Rename this when the RelaxedEnvironmentVariableValidation gate is removed. const relaxedEnvVarNameFmtErrMsg string = "a valid environment variable name must consist only of printable ASCII characters other than '='" var envVarNameRegexp = regexp.MustCompile("^" + envVarNameFmt + "$") // IsEnvVarName tests if a string is a valid environment variable name. func IsEnvVarName(value string) []string { var errs []string if !envVarNameRegexp.MatchString(value) { errs = append(errs, RegexError(envVarNameFmtErrMsg, envVarNameFmt, "my.env-name", "MY_ENV.NAME", "MyEnvName1")) } errs = append(errs, hasChDirPrefix(value)...) return errs } // IsRelaxedEnvVarName tests if a string is a valid environment variable name. func IsRelaxedEnvVarName(value string) []string { var errs []string if len(value) == 0 { errs = append(errs, "environment variable name "+EmptyError()) } for _, r := range value { if r > unicode.MaxASCII || !unicode.IsPrint(r) || r == '=' { errs = append(errs, relaxedEnvVarNameFmtErrMsg) break } } return errs } const configMapKeyFmt = `[-._a-zA-Z0-9]+` const configMapKeyErrMsg string = "a valid config key must consist of alphanumeric characters, '-', '_' or '.'" var configMapKeyRegexp = regexp.MustCompile("^" + configMapKeyFmt + "$") // IsConfigMapKey tests for a string that is a valid key for a ConfigMap or Secret func IsConfigMapKey(value string) []string { var errs []string if len(value) > DNS1123SubdomainMaxLength { errs = append(errs, MaxLenError(DNS1123SubdomainMaxLength)) } if !configMapKeyRegexp.MatchString(value) { errs = append(errs, RegexError(configMapKeyErrMsg, configMapKeyFmt, "key.name", "KEY_NAME", "key-name")) } errs = append(errs, hasChDirPrefix(value)...) return errs } // MaxLenError returns a string explanation of a "string too long" validation // failure. func MaxLenError(length int) string { return fmt.Sprintf("must be no more than %d characters", length) } // RegexError returns a string explanation of a regex validation failure. func RegexError(msg string, fmt string, examples ...string) string { if len(examples) == 0 { return msg + " (regex used for validation is '" + fmt + "')" } msg += " (e.g. " for i := range examples { if i > 0 { msg += " or " } msg += "'" + examples[i] + "', " } msg += "regex used for validation is '" + fmt + "')" return msg } // EmptyError returns a string explanation of a "must not be empty" validation // failure. func EmptyError() string { return "must be non-empty" } func prefixEach(msgs []string, prefix string) []string { for i := range msgs { msgs[i] = prefix + msgs[i] } return msgs } // InclusiveRangeError returns a string explanation of a numeric "must be // between" validation failure. func InclusiveRangeError(lo, hi int) string { return fmt.Sprintf(`must be between %d and %d, inclusive`, lo, hi) } func hasChDirPrefix(value string) []string { var errs []string switch { case value == ".": errs = append(errs, `must not be '.'`) case value == "..": errs = append(errs, `must not be '..'`) case strings.HasPrefix(value, ".."): errs = append(errs, `must not start with '..'`) } return errs }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/apimachinery/pkg/util/validation/field/path.go
vendor/k8s.io/apimachinery/pkg/util/validation/field/path.go
/* Copyright 2015 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 field import ( "bytes" "fmt" "strconv" ) type pathOptions struct { path *Path } // PathOption modifies a pathOptions type PathOption func(o *pathOptions) // WithPath generates a PathOption func WithPath(p *Path) PathOption { return func(o *pathOptions) { o.path = p } } // ToPath produces *Path from a set of PathOption func ToPath(opts ...PathOption) *Path { c := &pathOptions{} for _, opt := range opts { opt(c) } return c.path } // Path represents the path from some root to a particular field. type Path struct { name string // the name of this field or "" if this is an index index string // if name == "", this is a subscript (index or map key) of the previous element parent *Path // nil if this is the root element } // NewPath creates a root Path object. func NewPath(name string, moreNames ...string) *Path { r := &Path{name: name, parent: nil} for _, anotherName := range moreNames { r = &Path{name: anotherName, parent: r} } return r } // Root returns the root element of this Path. func (p *Path) Root() *Path { for ; p.parent != nil; p = p.parent { // Do nothing. } return p } // Child creates a new Path that is a child of the method receiver. func (p *Path) Child(name string, moreNames ...string) *Path { r := NewPath(name, moreNames...) r.Root().parent = p return r } // Index indicates that the previous Path is to be subscripted by an int. // This sets the same underlying value as Key. func (p *Path) Index(index int) *Path { return &Path{index: strconv.Itoa(index), parent: p} } // Key indicates that the previous Path is to be subscripted by a string. // This sets the same underlying value as Index. func (p *Path) Key(key string) *Path { return &Path{index: key, parent: p} } // String produces a string representation of the Path. func (p *Path) String() string { if p == nil { return "<nil>" } // make a slice to iterate elems := []*Path{} for ; p != nil; p = p.parent { elems = append(elems, p) } // iterate, but it has to be backwards buf := bytes.NewBuffer(nil) for i := range elems { p := elems[len(elems)-1-i] if p.parent != nil && len(p.name) > 0 { // This is either the root or it is a subscript. buf.WriteString(".") } if len(p.name) > 0 { buf.WriteString(p.name) } else { fmt.Fprintf(buf, "[%s]", p.index) } } return buf.String() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/apimachinery/pkg/util/validation/field/errors.go
vendor/k8s.io/apimachinery/pkg/util/validation/field/errors.go
/* Copyright 2014 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 field import ( "fmt" "reflect" "strconv" "strings" utilerrors "k8s.io/apimachinery/pkg/util/errors" "k8s.io/apimachinery/pkg/util/sets" ) // Error is an implementation of the 'error' interface, which represents a // field-level validation error. type Error struct { Type ErrorType Field string BadValue interface{} Detail string } var _ error = &Error{} // Error implements the error interface. func (v *Error) Error() string { return fmt.Sprintf("%s: %s", v.Field, v.ErrorBody()) } type OmitValueType struct{} var omitValue = OmitValueType{} // ErrorBody returns the error message without the field name. This is useful // for building nice-looking higher-level error reporting. func (v *Error) ErrorBody() string { var s string switch { case v.Type == ErrorTypeRequired: s = v.Type.String() case v.Type == ErrorTypeForbidden: s = v.Type.String() case v.Type == ErrorTypeTooLong: s = v.Type.String() case v.Type == ErrorTypeInternal: s = v.Type.String() case v.BadValue == omitValue: s = v.Type.String() default: value := v.BadValue valueType := reflect.TypeOf(value) if value == nil || valueType == nil { value = "null" } else if valueType.Kind() == reflect.Pointer { if reflectValue := reflect.ValueOf(value); reflectValue.IsNil() { value = "null" } else { value = reflectValue.Elem().Interface() } } switch t := value.(type) { case int64, int32, float64, float32, bool: // use simple printer for simple types s = fmt.Sprintf("%s: %v", v.Type, value) case string: s = fmt.Sprintf("%s: %q", v.Type, t) case fmt.Stringer: // anything that defines String() is better than raw struct s = fmt.Sprintf("%s: %s", v.Type, t.String()) default: // fallback to raw struct // TODO: internal types have panic guards against json.Marshalling to prevent // accidental use of internal types in external serialized form. For now, use // %#v, although it would be better to show a more expressive output in the future s = fmt.Sprintf("%s: %#v", v.Type, value) } } if len(v.Detail) != 0 { s += fmt.Sprintf(": %s", v.Detail) } return s } // ErrorType is a machine readable value providing more detail about why // a field is invalid. These values are expected to match 1-1 with // CauseType in api/types.go. type ErrorType string // TODO: These values are duplicated in api/types.go, but there's a circular dep. Fix it. const ( // ErrorTypeNotFound is used to report failure to find a requested value // (e.g. looking up an ID). See NotFound(). ErrorTypeNotFound ErrorType = "FieldValueNotFound" // ErrorTypeRequired is used to report required values that are not // provided (e.g. empty strings, null values, or empty arrays). See // Required(). ErrorTypeRequired ErrorType = "FieldValueRequired" // ErrorTypeDuplicate is used to report collisions of values that must be // unique (e.g. unique IDs). See Duplicate(). ErrorTypeDuplicate ErrorType = "FieldValueDuplicate" // ErrorTypeInvalid is used to report malformed values (e.g. failed regex // match, too long, out of bounds). See Invalid(). ErrorTypeInvalid ErrorType = "FieldValueInvalid" // ErrorTypeNotSupported is used to report unknown values for enumerated // fields (e.g. a list of valid values). See NotSupported(). ErrorTypeNotSupported ErrorType = "FieldValueNotSupported" // ErrorTypeForbidden is used to report valid (as per formatting rules) // values which would be accepted under some conditions, but which are not // permitted by the current conditions (such as security policy). See // Forbidden(). ErrorTypeForbidden ErrorType = "FieldValueForbidden" // ErrorTypeTooLong is used to report that the given value is too long. // This is similar to ErrorTypeInvalid, but the error will not include the // too-long value. See TooLong(). ErrorTypeTooLong ErrorType = "FieldValueTooLong" // ErrorTypeTooMany is used to report "too many". This is used to // report that a given list has too many items. This is similar to FieldValueTooLong, // but the error indicates quantity instead of length. ErrorTypeTooMany ErrorType = "FieldValueTooMany" // ErrorTypeInternal is used to report other errors that are not related // to user input. See InternalError(). ErrorTypeInternal ErrorType = "InternalError" // ErrorTypeTypeInvalid is for the value did not match the schema type for that field ErrorTypeTypeInvalid ErrorType = "FieldValueTypeInvalid" ) // String converts a ErrorType into its corresponding canonical error message. func (t ErrorType) String() string { switch t { case ErrorTypeNotFound: return "Not found" case ErrorTypeRequired: return "Required value" case ErrorTypeDuplicate: return "Duplicate value" case ErrorTypeInvalid: return "Invalid value" case ErrorTypeNotSupported: return "Unsupported value" case ErrorTypeForbidden: return "Forbidden" case ErrorTypeTooLong: return "Too long" case ErrorTypeTooMany: return "Too many" case ErrorTypeInternal: return "Internal error" case ErrorTypeTypeInvalid: return "Invalid value" default: panic(fmt.Sprintf("unrecognized validation error: %q", string(t))) } } // TypeInvalid returns a *Error indicating "type is invalid" func TypeInvalid(field *Path, value interface{}, detail string) *Error { return &Error{ErrorTypeTypeInvalid, field.String(), value, detail} } // NotFound returns a *Error indicating "value not found". This is // used to report failure to find a requested value (e.g. looking up an ID). func NotFound(field *Path, value interface{}) *Error { return &Error{ErrorTypeNotFound, field.String(), value, ""} } // Required returns a *Error indicating "value required". This is used // to report required values that are not provided (e.g. empty strings, null // values, or empty arrays). func Required(field *Path, detail string) *Error { return &Error{ErrorTypeRequired, field.String(), "", detail} } // Duplicate returns a *Error indicating "duplicate value". This is // used to report collisions of values that must be unique (e.g. names or IDs). func Duplicate(field *Path, value interface{}) *Error { return &Error{ErrorTypeDuplicate, field.String(), value, ""} } // Invalid returns a *Error indicating "invalid value". This is used // to report malformed values (e.g. failed regex match, too long, out of bounds). func Invalid(field *Path, value interface{}, detail string) *Error { return &Error{ErrorTypeInvalid, field.String(), value, detail} } // NotSupported returns a *Error indicating "unsupported value". // This is used to report unknown values for enumerated fields (e.g. a list of // valid values). func NotSupported[T ~string](field *Path, value interface{}, validValues []T) *Error { detail := "" if len(validValues) > 0 { quotedValues := make([]string, len(validValues)) for i, v := range validValues { quotedValues[i] = strconv.Quote(fmt.Sprint(v)) } detail = "supported values: " + strings.Join(quotedValues, ", ") } return &Error{ErrorTypeNotSupported, field.String(), value, detail} } // Forbidden returns a *Error indicating "forbidden". This is used to // report valid (as per formatting rules) values which would be accepted under // some conditions, but which are not permitted by current conditions (e.g. // security policy). func Forbidden(field *Path, detail string) *Error { return &Error{ErrorTypeForbidden, field.String(), "", detail} } // TooLong returns a *Error indicating "too long". This is used to report that // the given value is too long. This is similar to Invalid, but the returned // error will not include the too-long value. If maxLength is negative, it will // be included in the message. The value argument is not used. func TooLong(field *Path, value interface{}, maxLength int) *Error { var msg string if maxLength >= 0 { msg = fmt.Sprintf("may not be more than %d bytes", maxLength) } else { msg = "value is too long" } return &Error{ErrorTypeTooLong, field.String(), "<value omitted>", msg} } // TooLongMaxLength returns a *Error indicating "too long". // Deprecated: Use TooLong instead. func TooLongMaxLength(field *Path, value interface{}, maxLength int) *Error { return TooLong(field, "", maxLength) } // TooMany returns a *Error indicating "too many". This is used to // report that a given list has too many items. This is similar to TooLong, // but the returned error indicates quantity instead of length. func TooMany(field *Path, actualQuantity, maxQuantity int) *Error { var msg string if maxQuantity >= 0 { msg = fmt.Sprintf("must have at most %d items", maxQuantity) } else { msg = "has too many items" } var actual interface{} if actualQuantity >= 0 { actual = actualQuantity } else { actual = omitValue } return &Error{ErrorTypeTooMany, field.String(), actual, msg} } // InternalError returns a *Error indicating "internal error". This is used // to signal that an error was found that was not directly related to user // input. The err argument must be non-nil. func InternalError(field *Path, err error) *Error { return &Error{ErrorTypeInternal, field.String(), nil, err.Error()} } // ErrorList holds a set of Errors. It is plausible that we might one day have // non-field errors in this same umbrella package, but for now we don't, so // we can keep it simple and leave ErrorList here. type ErrorList []*Error // NewErrorTypeMatcher returns an errors.Matcher that returns true // if the provided error is a Error and has the provided ErrorType. func NewErrorTypeMatcher(t ErrorType) utilerrors.Matcher { return func(err error) bool { if e, ok := err.(*Error); ok { return e.Type == t } return false } } // ToAggregate converts the ErrorList into an errors.Aggregate. func (list ErrorList) ToAggregate() utilerrors.Aggregate { if len(list) == 0 { return nil } errs := make([]error, 0, len(list)) errorMsgs := sets.NewString() for _, err := range list { msg := fmt.Sprintf("%v", err) if errorMsgs.Has(msg) { continue } errorMsgs.Insert(msg) errs = append(errs, err) } return utilerrors.NewAggregate(errs) } func fromAggregate(agg utilerrors.Aggregate) ErrorList { errs := agg.Errors() list := make(ErrorList, len(errs)) for i := range errs { list[i] = errs[i].(*Error) } return list } // Filter removes items from the ErrorList that match the provided fns. func (list ErrorList) Filter(fns ...utilerrors.Matcher) ErrorList { err := utilerrors.FilterOut(list.ToAggregate(), fns...) if err == nil { return nil } // FilterOut takes an Aggregate and returns an Aggregate return fromAggregate(err.(utilerrors.Aggregate)) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/apimachinery/pkg/util/portforward/constants.go
vendor/k8s.io/apimachinery/pkg/util/portforward/constants.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 portforward const ( PortForwardV1Name = "portforward.k8s.io" WebsocketsSPDYTunnelingPrefix = "SPDY/3.1+" KubernetesSuffix = ".k8s.io" WebsocketsSPDYTunnelingPortForwardV1 = WebsocketsSPDYTunnelingPrefix + PortForwardV1Name )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/apimachinery/pkg/util/httpstream/httpstream.go
vendor/k8s.io/apimachinery/pkg/util/httpstream/httpstream.go
/* Copyright 2015 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 httpstream import ( "errors" "fmt" "io" "net/http" "strings" "time" ) const ( HeaderConnection = "Connection" HeaderUpgrade = "Upgrade" HeaderProtocolVersion = "X-Stream-Protocol-Version" HeaderAcceptedProtocolVersions = "X-Accepted-Stream-Protocol-Versions" ) // NewStreamHandler defines a function that is called when a new Stream is // received. If no error is returned, the Stream is accepted; otherwise, // the stream is rejected. After the reply frame has been sent, replySent is closed. type NewStreamHandler func(stream Stream, replySent <-chan struct{}) error // NoOpNewStreamHandler is a stream handler that accepts a new stream and // performs no other logic. func NoOpNewStreamHandler(stream Stream, replySent <-chan struct{}) error { return nil } // Dialer knows how to open a streaming connection to a server. type Dialer interface { // Dial opens a streaming connection to a server using one of the protocols // specified (in order of most preferred to least preferred). Dial(protocols ...string) (Connection, string, error) } // UpgradeRoundTripper is a type of http.RoundTripper that is able to upgrade // HTTP requests to support multiplexed bidirectional streams. After RoundTrip() // is invoked, if the upgrade is successful, clients may retrieve the upgraded // connection by calling UpgradeRoundTripper.Connection(). type UpgradeRoundTripper interface { http.RoundTripper // NewConnection validates the response and creates a new Connection. NewConnection(resp *http.Response) (Connection, error) } // ResponseUpgrader knows how to upgrade HTTP requests and responses to // add streaming support to them. type ResponseUpgrader interface { // UpgradeResponse upgrades an HTTP response to one that supports multiplexed // streams. newStreamHandler will be called asynchronously whenever the // other end of the upgraded connection creates a new stream. UpgradeResponse(w http.ResponseWriter, req *http.Request, newStreamHandler NewStreamHandler) Connection } // Connection represents an upgraded HTTP connection. type Connection interface { // CreateStream creates a new Stream with the supplied headers. CreateStream(headers http.Header) (Stream, error) // Close resets all streams and closes the connection. Close() error // CloseChan returns a channel that is closed when the underlying connection is closed. CloseChan() <-chan bool // SetIdleTimeout sets the amount of time the connection may remain idle before // it is automatically closed. SetIdleTimeout(timeout time.Duration) // RemoveStreams can be used to remove a set of streams from the Connection. RemoveStreams(streams ...Stream) } // Stream represents a bidirectional communications channel that is part of an // upgraded connection. type Stream interface { io.ReadWriteCloser // Reset closes both directions of the stream, indicating that neither client // or server can use it any more. Reset() error // Headers returns the headers used to create the stream. Headers() http.Header // Identifier returns the stream's ID. Identifier() uint32 } // UpgradeFailureError encapsulates the cause for why the streaming // upgrade request failed. Implements error interface. type UpgradeFailureError struct { Cause error } func (u *UpgradeFailureError) Error() string { return fmt.Sprintf("unable to upgrade streaming request: %s", u.Cause) } // IsUpgradeFailure returns true if the passed error is (or wrapped error contains) // the UpgradeFailureError. func IsUpgradeFailure(err error) bool { if err == nil { return false } var upgradeErr *UpgradeFailureError return errors.As(err, &upgradeErr) } // isHTTPSProxyError returns true if error is Gorilla/Websockets HTTPS Proxy dial error; // false otherwise (see https://github.com/kubernetes/kubernetes/issues/126134). func IsHTTPSProxyError(err error) bool { if err == nil { return false } return strings.Contains(err.Error(), "proxy: unknown scheme: https") } // IsUpgradeRequest returns true if the given request is a connection upgrade request func IsUpgradeRequest(req *http.Request) bool { for _, h := range req.Header[http.CanonicalHeaderKey(HeaderConnection)] { if strings.Contains(strings.ToLower(h), strings.ToLower(HeaderUpgrade)) { return true } } return false } func negotiateProtocol(clientProtocols, serverProtocols []string) string { for i := range clientProtocols { for j := range serverProtocols { if clientProtocols[i] == serverProtocols[j] { return clientProtocols[i] } } } return "" } func commaSeparatedHeaderValues(header []string) []string { var parsedClientProtocols []string for i := range header { for _, clientProtocol := range strings.Split(header[i], ",") { if proto := strings.Trim(clientProtocol, " "); len(proto) > 0 { parsedClientProtocols = append(parsedClientProtocols, proto) } } } return parsedClientProtocols } // Handshake performs a subprotocol negotiation. If the client did request a // subprotocol, Handshake will select the first common value found in // serverProtocols. If a match is found, Handshake adds a response header // indicating the chosen subprotocol. If no match is found, HTTP forbidden is // returned, along with a response header containing the list of protocols the // server can accept. func Handshake(req *http.Request, w http.ResponseWriter, serverProtocols []string) (string, error) { clientProtocols := commaSeparatedHeaderValues(req.Header[http.CanonicalHeaderKey(HeaderProtocolVersion)]) if len(clientProtocols) == 0 { return "", fmt.Errorf("unable to upgrade: %s is required", HeaderProtocolVersion) } if len(serverProtocols) == 0 { panic(fmt.Errorf("unable to upgrade: serverProtocols is required")) } negotiatedProtocol := negotiateProtocol(clientProtocols, serverProtocols) if len(negotiatedProtocol) == 0 { for i := range serverProtocols { w.Header().Add(HeaderAcceptedProtocolVersions, serverProtocols[i]) } err := fmt.Errorf("unable to upgrade: unable to negotiate protocol: client supports %v, server accepts %v", clientProtocols, serverProtocols) http.Error(w, err.Error(), http.StatusForbidden) return "", err } w.Header().Add(HeaderProtocolVersion, negotiatedProtocol) return negotiatedProtocol, nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/apimachinery/pkg/util/httpstream/doc.go
vendor/k8s.io/apimachinery/pkg/util/httpstream/doc.go
/* Copyright 2015 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 httpstream adds multiplexed streaming support to HTTP requests and // responses via connection upgrades. package httpstream // import "k8s.io/apimachinery/pkg/util/httpstream"
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/apimachinery/pkg/util/httpstream/wsstream/stream.go
vendor/k8s.io/apimachinery/pkg/util/httpstream/wsstream/stream.go
/* Copyright 2015 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 wsstream import ( "encoding/base64" "io" "net/http" "sync" "time" "golang.org/x/net/websocket" "k8s.io/apimachinery/pkg/util/runtime" ) // The WebSocket subprotocol "binary.k8s.io" will only send messages to the // client and ignore messages sent to the server. The received messages are // the exact bytes written to the stream. Zero byte messages are possible. const binaryWebSocketProtocol = "binary.k8s.io" // The WebSocket subprotocol "base64.binary.k8s.io" will only send messages to the // client and ignore messages sent to the server. The received messages are // a base64 version of the bytes written to the stream. Zero byte messages are // possible. const base64BinaryWebSocketProtocol = "base64.binary.k8s.io" // ReaderProtocolConfig describes a websocket subprotocol with one stream. type ReaderProtocolConfig struct { Binary bool } // NewDefaultReaderProtocols returns a stream protocol map with the // subprotocols "", "channel.k8s.io", "base64.channel.k8s.io". func NewDefaultReaderProtocols() map[string]ReaderProtocolConfig { return map[string]ReaderProtocolConfig{ "": {Binary: true}, binaryWebSocketProtocol: {Binary: true}, base64BinaryWebSocketProtocol: {Binary: false}, } } // Reader supports returning an arbitrary byte stream over a websocket channel. type Reader struct { err chan error r io.Reader ping bool timeout time.Duration protocols map[string]ReaderProtocolConfig selectedProtocol string handleCrash func(additionalHandlers ...func(interface{})) // overridable for testing } // NewReader creates a WebSocket pipe that will copy the contents of r to a provided // WebSocket connection. If ping is true, a zero length message will be sent to the client // before the stream begins reading. // // The protocols parameter maps subprotocol names to StreamProtocols. The empty string // subprotocol name is used if websocket.Config.Protocol is empty. func NewReader(r io.Reader, ping bool, protocols map[string]ReaderProtocolConfig) *Reader { return &Reader{ r: r, err: make(chan error), ping: ping, protocols: protocols, handleCrash: runtime.HandleCrash, } } // SetIdleTimeout sets the interval for both reads and writes before timeout. If not specified, // there is no timeout on the reader. func (r *Reader) SetIdleTimeout(duration time.Duration) { r.timeout = duration } func (r *Reader) handshake(config *websocket.Config, req *http.Request) error { supportedProtocols := make([]string, 0, len(r.protocols)) for p := range r.protocols { supportedProtocols = append(supportedProtocols, p) } return handshake(config, req, supportedProtocols) } // Copy the reader to the response. The created WebSocket is closed after this // method completes. func (r *Reader) Copy(w http.ResponseWriter, req *http.Request) error { go func() { defer r.handleCrash() websocket.Server{Handshake: r.handshake, Handler: r.handle}.ServeHTTP(w, req) }() return <-r.err } // handle implements a WebSocket handler. func (r *Reader) handle(ws *websocket.Conn) { // Close the connection when the client requests it, or when we finish streaming, whichever happens first closeConnOnce := &sync.Once{} closeConn := func() { closeConnOnce.Do(func() { ws.Close() }) } negotiated := ws.Config().Protocol r.selectedProtocol = negotiated[0] defer close(r.err) defer closeConn() go func() { defer runtime.HandleCrash() // This blocks until the connection is closed. // Client should not send anything. IgnoreReceives(ws, r.timeout) // Once the client closes, we should also close closeConn() }() r.err <- messageCopy(ws, r.r, !r.protocols[r.selectedProtocol].Binary, r.ping, r.timeout) } func resetTimeout(ws *websocket.Conn, timeout time.Duration) { if timeout > 0 { ws.SetDeadline(time.Now().Add(timeout)) } } func messageCopy(ws *websocket.Conn, r io.Reader, base64Encode, ping bool, timeout time.Duration) error { buf := make([]byte, 2048) if ping { resetTimeout(ws, timeout) if base64Encode { if err := websocket.Message.Send(ws, ""); err != nil { return err } } else { if err := websocket.Message.Send(ws, []byte{}); err != nil { return err } } } for { resetTimeout(ws, timeout) n, err := r.Read(buf) if err != nil { if err == io.EOF { return nil } return err } if n > 0 { if base64Encode { if err := websocket.Message.Send(ws, base64.StdEncoding.EncodeToString(buf[:n])); err != nil { return err } } else { if err := websocket.Message.Send(ws, buf[:n]); err != nil { return err } } } } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/apimachinery/pkg/util/httpstream/wsstream/conn.go
vendor/k8s.io/apimachinery/pkg/util/httpstream/wsstream/conn.go
/* Copyright 2015 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 wsstream import ( "encoding/base64" "fmt" "io" "net/http" "strings" "time" "golang.org/x/net/websocket" "k8s.io/apimachinery/pkg/util/httpstream" "k8s.io/apimachinery/pkg/util/portforward" "k8s.io/apimachinery/pkg/util/remotecommand" "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/klog/v2" ) const WebSocketProtocolHeader = "Sec-Websocket-Protocol" // The Websocket subprotocol "channel.k8s.io" prepends each binary message with a byte indicating // the channel number (zero indexed) the message was sent on. Messages in both directions should // prefix their messages with this channel byte. When used for remote execution, the channel numbers // are by convention defined to match the POSIX file-descriptors assigned to STDIN, STDOUT, and STDERR // (0, 1, and 2). No other conversion is performed on the raw subprotocol - writes are sent as they // are received by the server. // // Example client session: // // CONNECT http://server.com with subprotocol "channel.k8s.io" // WRITE []byte{0, 102, 111, 111, 10} # send "foo\n" on channel 0 (STDIN) // READ []byte{1, 10} # receive "\n" on channel 1 (STDOUT) // CLOSE const ChannelWebSocketProtocol = "channel.k8s.io" // The Websocket subprotocol "base64.channel.k8s.io" base64 encodes each message with a character // indicating the channel number (zero indexed) the message was sent on. Messages in both directions // should prefix their messages with this channel char. When used for remote execution, the channel // numbers are by convention defined to match the POSIX file-descriptors assigned to STDIN, STDOUT, // and STDERR ('0', '1', and '2'). The data received on the server is base64 decoded (and must be // be valid) and data written by the server to the client is base64 encoded. // // Example client session: // // CONNECT http://server.com with subprotocol "base64.channel.k8s.io" // WRITE []byte{48, 90, 109, 57, 118, 67, 103, 111, 61} # send "foo\n" (base64: "Zm9vCgo=") on channel '0' (STDIN) // READ []byte{49, 67, 103, 61, 61} # receive "\n" (base64: "Cg==") on channel '1' (STDOUT) // CLOSE const Base64ChannelWebSocketProtocol = "base64.channel.k8s.io" type codecType int const ( rawCodec codecType = iota base64Codec ) type ChannelType int const ( IgnoreChannel ChannelType = iota ReadChannel WriteChannel ReadWriteChannel ) // IsWebSocketRequest returns true if the incoming request contains connection upgrade headers // for WebSockets. func IsWebSocketRequest(req *http.Request) bool { if !strings.EqualFold(req.Header.Get("Upgrade"), "websocket") { return false } return httpstream.IsUpgradeRequest(req) } // IsWebSocketRequestWithStreamCloseProtocol returns true if the request contains headers // identifying that it is requesting a websocket upgrade with a remotecommand protocol // version that supports the "CLOSE" signal; false otherwise. func IsWebSocketRequestWithStreamCloseProtocol(req *http.Request) bool { if !IsWebSocketRequest(req) { return false } requestedProtocols := strings.TrimSpace(req.Header.Get(WebSocketProtocolHeader)) for _, requestedProtocol := range strings.Split(requestedProtocols, ",") { if protocolSupportsStreamClose(strings.TrimSpace(requestedProtocol)) { return true } } return false } // IsWebSocketRequestWithTunnelingProtocol returns true if the request contains headers // identifying that it is requesting a websocket upgrade with a tunneling protocol; // false otherwise. func IsWebSocketRequestWithTunnelingProtocol(req *http.Request) bool { if !IsWebSocketRequest(req) { return false } requestedProtocols := strings.TrimSpace(req.Header.Get(WebSocketProtocolHeader)) for _, requestedProtocol := range strings.Split(requestedProtocols, ",") { if protocolSupportsWebsocketTunneling(strings.TrimSpace(requestedProtocol)) { return true } } return false } // IgnoreReceives reads from a WebSocket until it is closed, then returns. If timeout is set, the // read and write deadlines are pushed every time a new message is received. func IgnoreReceives(ws *websocket.Conn, timeout time.Duration) { defer runtime.HandleCrash() var data []byte for { resetTimeout(ws, timeout) if err := websocket.Message.Receive(ws, &data); err != nil { return } } } // handshake ensures the provided user protocol matches one of the allowed protocols. It returns // no error if no protocol is specified. func handshake(config *websocket.Config, req *http.Request, allowed []string) error { protocols := config.Protocol if len(protocols) == 0 { protocols = []string{""} } for _, protocol := range protocols { for _, allow := range allowed { if allow == protocol { config.Protocol = []string{protocol} return nil } } } return fmt.Errorf("requested protocol(s) are not supported: %v; supports %v", config.Protocol, allowed) } // ChannelProtocolConfig describes a websocket subprotocol with channels. type ChannelProtocolConfig struct { Binary bool Channels []ChannelType } // NewDefaultChannelProtocols returns a channel protocol map with the // subprotocols "", "channel.k8s.io", "base64.channel.k8s.io" and the given // channels. func NewDefaultChannelProtocols(channels []ChannelType) map[string]ChannelProtocolConfig { return map[string]ChannelProtocolConfig{ "": {Binary: true, Channels: channels}, ChannelWebSocketProtocol: {Binary: true, Channels: channels}, Base64ChannelWebSocketProtocol: {Binary: false, Channels: channels}, } } // Conn supports sending multiple binary channels over a websocket connection. type Conn struct { protocols map[string]ChannelProtocolConfig selectedProtocol string channels []*websocketChannel codec codecType ready chan struct{} ws *websocket.Conn timeout time.Duration } // NewConn creates a WebSocket connection that supports a set of channels. Channels begin each // web socket message with a single byte indicating the channel number (0-N). 255 is reserved for // future use. The channel types for each channel are passed as an array, supporting the different // duplex modes. Read and Write refer to whether the channel can be used as a Reader or Writer. // // The protocols parameter maps subprotocol names to ChannelProtocols. The empty string subprotocol // name is used if websocket.Config.Protocol is empty. func NewConn(protocols map[string]ChannelProtocolConfig) *Conn { return &Conn{ ready: make(chan struct{}), protocols: protocols, } } // SetIdleTimeout sets the interval for both reads and writes before timeout. If not specified, // there is no timeout on the connection. func (conn *Conn) SetIdleTimeout(duration time.Duration) { conn.timeout = duration } // SetWriteDeadline sets a timeout on writing to the websocket connection. The // passed "duration" identifies how far into the future the write must complete // by before the timeout fires. func (conn *Conn) SetWriteDeadline(duration time.Duration) { conn.ws.SetWriteDeadline(time.Now().Add(duration)) //nolint:errcheck } // Open the connection and create channels for reading and writing. It returns // the selected subprotocol, a slice of channels and an error. func (conn *Conn) Open(w http.ResponseWriter, req *http.Request) (string, []io.ReadWriteCloser, error) { // serveHTTPComplete is channel that is closed/selected when "websocket#ServeHTTP" finishes. serveHTTPComplete := make(chan struct{}) // Ensure panic in spawned goroutine is propagated into the parent goroutine. panicChan := make(chan any, 1) go func() { // If websocket server returns, propagate panic if necessary. Otherwise, // signal HTTPServe finished by closing "serveHTTPComplete". defer func() { if p := recover(); p != nil { panicChan <- p } else { close(serveHTTPComplete) } }() websocket.Server{Handshake: conn.handshake, Handler: conn.handle}.ServeHTTP(w, req) }() // In normal circumstances, "websocket.Server#ServeHTTP" calls "initialize" which closes // "conn.ready" and then blocks until serving is complete. select { case <-conn.ready: klog.V(8).Infof("websocket server initialized--serving") case <-serveHTTPComplete: // websocket server returned before completing initialization; cleanup and return error. conn.closeNonThreadSafe() //nolint:errcheck return "", nil, fmt.Errorf("websocket server finished before becoming ready") case p := <-panicChan: panic(p) } rwc := make([]io.ReadWriteCloser, len(conn.channels)) for i := range conn.channels { rwc[i] = conn.channels[i] } return conn.selectedProtocol, rwc, nil } func (conn *Conn) initialize(ws *websocket.Conn) { negotiated := ws.Config().Protocol conn.selectedProtocol = negotiated[0] p := conn.protocols[conn.selectedProtocol] if p.Binary { conn.codec = rawCodec } else { conn.codec = base64Codec } conn.ws = ws conn.channels = make([]*websocketChannel, len(p.Channels)) for i, t := range p.Channels { switch t { case ReadChannel: conn.channels[i] = newWebsocketChannel(conn, byte(i), true, false) case WriteChannel: conn.channels[i] = newWebsocketChannel(conn, byte(i), false, true) case ReadWriteChannel: conn.channels[i] = newWebsocketChannel(conn, byte(i), true, true) case IgnoreChannel: conn.channels[i] = newWebsocketChannel(conn, byte(i), false, false) } } close(conn.ready) } func (conn *Conn) handshake(config *websocket.Config, req *http.Request) error { supportedProtocols := make([]string, 0, len(conn.protocols)) for p := range conn.protocols { supportedProtocols = append(supportedProtocols, p) } return handshake(config, req, supportedProtocols) } func (conn *Conn) resetTimeout() { if conn.timeout > 0 { conn.ws.SetDeadline(time.Now().Add(conn.timeout)) } } // closeNonThreadSafe cleans up by closing streams and the websocket // connection *without* waiting for the "ready" channel. func (conn *Conn) closeNonThreadSafe() error { for _, s := range conn.channels { s.Close() } var err error if conn.ws != nil { err = conn.ws.Close() } return err } // Close is only valid after Open has been called func (conn *Conn) Close() error { <-conn.ready return conn.closeNonThreadSafe() } // protocolSupportsStreamClose returns true if the passed protocol // supports the stream close signal (currently only V5 remotecommand); // false otherwise. func protocolSupportsStreamClose(protocol string) bool { return protocol == remotecommand.StreamProtocolV5Name } // protocolSupportsWebsocketTunneling returns true if the passed protocol // is a tunneled Kubernetes spdy protocol; false otherwise. func protocolSupportsWebsocketTunneling(protocol string) bool { return strings.HasPrefix(protocol, portforward.WebsocketsSPDYTunnelingPrefix) && strings.HasSuffix(protocol, portforward.KubernetesSuffix) } // handle implements a websocket handler. func (conn *Conn) handle(ws *websocket.Conn) { conn.initialize(ws) defer conn.Close() supportsStreamClose := protocolSupportsStreamClose(conn.selectedProtocol) for { conn.resetTimeout() var data []byte if err := websocket.Message.Receive(ws, &data); err != nil { if err != io.EOF { klog.Errorf("Error on socket receive: %v", err) } break } if len(data) == 0 { continue } if supportsStreamClose && data[0] == remotecommand.StreamClose { if len(data) != 2 { klog.Errorf("Single channel byte should follow stream close signal. Got %d bytes", len(data)-1) break } else { channel := data[1] if int(channel) >= len(conn.channels) { klog.Errorf("Close is targeted for a channel %d that is not valid, possible protocol error", channel) break } klog.V(4).Infof("Received half-close signal from client; close %d stream", channel) conn.channels[channel].Close() // After first Close, other closes are noop. } continue } channel := data[0] if conn.codec == base64Codec { channel = channel - '0' } data = data[1:] if int(channel) >= len(conn.channels) { klog.V(6).Infof("Frame is targeted for a reader %d that is not valid, possible protocol error", channel) continue } if _, err := conn.channels[channel].DataFromSocket(data); err != nil { klog.Errorf("Unable to write frame (%d bytes) to %d: %v", len(data), channel, err) continue } } } // write multiplexes the specified channel onto the websocket func (conn *Conn) write(num byte, data []byte) (int, error) { conn.resetTimeout() switch conn.codec { case rawCodec: frame := make([]byte, len(data)+1) frame[0] = num copy(frame[1:], data) if err := websocket.Message.Send(conn.ws, frame); err != nil { return 0, err } case base64Codec: frame := string('0'+num) + base64.StdEncoding.EncodeToString(data) if err := websocket.Message.Send(conn.ws, frame); err != nil { return 0, err } } return len(data), nil } // websocketChannel represents a channel in a connection type websocketChannel struct { conn *Conn num byte r io.Reader w io.WriteCloser read, write bool } // newWebsocketChannel creates a pipe for writing to a websocket. Do not write to this pipe // prior to the connection being opened. It may be no, half, or full duplex depending on // read and write. func newWebsocketChannel(conn *Conn, num byte, read, write bool) *websocketChannel { r, w := io.Pipe() return &websocketChannel{conn, num, r, w, read, write} } func (p *websocketChannel) Write(data []byte) (int, error) { if !p.write { return len(data), nil } return p.conn.write(p.num, data) } // DataFromSocket is invoked by the connection receiver to move data from the connection // into a specific channel. func (p *websocketChannel) DataFromSocket(data []byte) (int, error) { if !p.read { return len(data), nil } switch p.conn.codec { case rawCodec: return p.w.Write(data) case base64Codec: dst := make([]byte, len(data)) n, err := base64.StdEncoding.Decode(dst, data) if err != nil { return 0, err } return p.w.Write(dst[:n]) } return 0, nil } func (p *websocketChannel) Read(data []byte) (int, error) { if !p.read { return 0, io.EOF } return p.r.Read(data) } func (p *websocketChannel) Close() error { return p.w.Close() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/apimachinery/pkg/util/httpstream/wsstream/doc.go
vendor/k8s.io/apimachinery/pkg/util/httpstream/wsstream/doc.go
/* Copyright 2015 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 wsstream contains utilities for streaming content over WebSockets. // The Conn type allows callers to multiplex multiple read/write channels over // a single websocket. // // "channel.k8s.io" // // The Websocket RemoteCommand subprotocol "channel.k8s.io" prepends each binary message with a // byte indicating the channel number (zero indexed) the message was sent on. Messages in both // directions should prefix their messages with this channel byte. Used for remote execution, // the channel numbers are by convention defined to match the POSIX file-descriptors assigned // to STDIN, STDOUT, and STDERR (0, 1, and 2). No other conversion is performed on the raw // subprotocol - writes are sent as they are received by the server. // // Example client session: // // CONNECT http://server.com with subprotocol "channel.k8s.io" // WRITE []byte{0, 102, 111, 111, 10} # send "foo\n" on channel 0 (STDIN) // READ []byte{1, 10} # receive "\n" on channel 1 (STDOUT) // CLOSE // // "v2.channel.k8s.io" // // The second Websocket subprotocol version "v2.channel.k8s.io" is the same as version 1, // but it is the first "versioned" subprotocol. // // "v3.channel.k8s.io" // // The third version of the Websocket RemoteCommand subprotocol adds another channel // for terminal resizing events. This channel is prepended with the byte '3', and it // transmits two window sizes (encoding TerminalSize struct) with integers in the range // (0,65536]. // // "v4.channel.k8s.io" // // The fourth version of the Websocket RemoteCommand subprotocol adds a channel for // errors. This channel returns structured errors containing process exit codes. The // error is "apierrors.StatusError{}". // // "v5.channel.k8s.io" // // The fifth version of the Websocket RemoteCommand subprotocol adds a CLOSE signal, // which is sent as the first byte of the message. The second byte is the channel // id. This CLOSE signal is handled by the websocket server by closing the stream, // allowing the other streams to complete transmission if necessary, and gracefully // shutdown the connection. // // Example client session: // // CONNECT http://server.com with subprotocol "v5.channel.k8s.io" // WRITE []byte{0, 102, 111, 111, 10} # send "foo\n" on channel 0 (STDIN) // WRITE []byte{255, 0} # send CLOSE signal (STDIN) // CLOSE package wsstream // import "k8s.io/apimachinery/pkg/util/httpstream/wsstream"
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/apimachinery/pkg/util/httpstream/spdy/connection.go
vendor/k8s.io/apimachinery/pkg/util/httpstream/spdy/connection.go
/* Copyright 2015 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 spdy import ( "net" "net/http" "sync" "time" "github.com/moby/spdystream" "k8s.io/apimachinery/pkg/util/httpstream" "k8s.io/klog/v2" ) // connection maintains state about a spdystream.Connection and its associated // streams. type connection struct { conn *spdystream.Connection streams map[uint32]httpstream.Stream streamLock sync.Mutex newStreamHandler httpstream.NewStreamHandler ping func() (time.Duration, error) } // NewClientConnection creates a new SPDY client connection. func NewClientConnection(conn net.Conn) (httpstream.Connection, error) { return NewClientConnectionWithPings(conn, 0) } // NewClientConnectionWithPings creates a new SPDY client connection. // // If pingPeriod is non-zero, a background goroutine will send periodic Ping // frames to the server. Use this to keep idle connections through certain load // balancers alive longer. func NewClientConnectionWithPings(conn net.Conn, pingPeriod time.Duration) (httpstream.Connection, error) { spdyConn, err := spdystream.NewConnection(conn, false) if err != nil { defer conn.Close() return nil, err } return newConnection(spdyConn, httpstream.NoOpNewStreamHandler, pingPeriod, spdyConn.Ping), nil } // NewServerConnection creates a new SPDY server connection. newStreamHandler // will be invoked when the server receives a newly created stream from the // client. func NewServerConnection(conn net.Conn, newStreamHandler httpstream.NewStreamHandler) (httpstream.Connection, error) { return NewServerConnectionWithPings(conn, newStreamHandler, 0) } // NewServerConnectionWithPings creates a new SPDY server connection. // newStreamHandler will be invoked when the server receives a newly created // stream from the client. // // If pingPeriod is non-zero, a background goroutine will send periodic Ping // frames to the server. Use this to keep idle connections through certain load // balancers alive longer. func NewServerConnectionWithPings(conn net.Conn, newStreamHandler httpstream.NewStreamHandler, pingPeriod time.Duration) (httpstream.Connection, error) { spdyConn, err := spdystream.NewConnection(conn, true) if err != nil { defer conn.Close() return nil, err } return newConnection(spdyConn, newStreamHandler, pingPeriod, spdyConn.Ping), nil } // newConnection returns a new connection wrapping conn. newStreamHandler // will be invoked when the server receives a newly created stream from the // client. func newConnection(conn *spdystream.Connection, newStreamHandler httpstream.NewStreamHandler, pingPeriod time.Duration, pingFn func() (time.Duration, error)) httpstream.Connection { c := &connection{ conn: conn, newStreamHandler: newStreamHandler, ping: pingFn, streams: make(map[uint32]httpstream.Stream), } go conn.Serve(c.newSpdyStream) if pingPeriod > 0 && pingFn != nil { go c.sendPings(pingPeriod) } return c } // createStreamResponseTimeout indicates how long to wait for the other side to // acknowledge the new stream before timing out. const createStreamResponseTimeout = 30 * time.Second // Close first sends a reset for all of the connection's streams, and then // closes the underlying spdystream.Connection. func (c *connection) Close() error { c.streamLock.Lock() for _, s := range c.streams { // calling Reset instead of Close ensures that all streams are fully torn down s.Reset() } c.streams = make(map[uint32]httpstream.Stream, 0) c.streamLock.Unlock() // now that all streams are fully torn down, it's safe to call close on the underlying connection, // which should be able to terminate immediately at this point, instead of waiting for any // remaining graceful stream termination. return c.conn.Close() } // RemoveStreams can be used to removes a set of streams from the Connection. func (c *connection) RemoveStreams(streams ...httpstream.Stream) { c.streamLock.Lock() for _, stream := range streams { // It may be possible that the provided stream is nil if timed out. if stream != nil { delete(c.streams, stream.Identifier()) } } c.streamLock.Unlock() } // CreateStream creates a new stream with the specified headers and registers // it with the connection. func (c *connection) CreateStream(headers http.Header) (httpstream.Stream, error) { stream, err := c.conn.CreateStream(headers, nil, false) if err != nil { return nil, err } if err = stream.WaitTimeout(createStreamResponseTimeout); err != nil { return nil, err } c.registerStream(stream) return stream, nil } // registerStream adds the stream s to the connection's list of streams that // it owns. func (c *connection) registerStream(s httpstream.Stream) { c.streamLock.Lock() c.streams[s.Identifier()] = s c.streamLock.Unlock() } // CloseChan returns a channel that, when closed, indicates that the underlying // spdystream.Connection has been closed. func (c *connection) CloseChan() <-chan bool { return c.conn.CloseChan() } // newSpdyStream is the internal new stream handler used by spdystream.Connection.Serve. // It calls connection's newStreamHandler, giving it the opportunity to accept or reject // the stream. If newStreamHandler returns an error, the stream is rejected. If not, the // stream is accepted and registered with the connection. func (c *connection) newSpdyStream(stream *spdystream.Stream) { replySent := make(chan struct{}) err := c.newStreamHandler(stream, replySent) rejectStream := (err != nil) if rejectStream { klog.Warningf("Stream rejected: %v", err) stream.Reset() return } c.registerStream(stream) stream.SendReply(http.Header{}, rejectStream) close(replySent) } // SetIdleTimeout sets the amount of time the connection may remain idle before // it is automatically closed. func (c *connection) SetIdleTimeout(timeout time.Duration) { c.conn.SetIdleTimeout(timeout) } func (c *connection) sendPings(period time.Duration) { t := time.NewTicker(period) defer t.Stop() for { select { case <-c.conn.CloseChan(): return case <-t.C: } if _, err := c.ping(); err != nil { klog.V(3).Infof("SPDY Ping failed: %v", err) // Continue, in case this is a transient failure. // c.conn.CloseChan above will tell us when the connection is // actually closed. } } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/apimachinery/pkg/util/httpstream/spdy/roundtripper.go
vendor/k8s.io/apimachinery/pkg/util/httpstream/spdy/roundtripper.go
/* Copyright 2015 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 spdy import ( "bufio" "context" "crypto/tls" "encoding/base64" "errors" "fmt" "io" "net" "net/http" "net/http/httputil" "net/url" "strings" "time" "golang.org/x/net/proxy" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/serializer" "k8s.io/apimachinery/pkg/util/httpstream" utilnet "k8s.io/apimachinery/pkg/util/net" apiproxy "k8s.io/apimachinery/pkg/util/proxy" "k8s.io/apimachinery/third_party/forked/golang/netutil" ) // SpdyRoundTripper knows how to upgrade an HTTP request to one that supports // multiplexed streams. After RoundTrip() is invoked, Conn will be set // and usable. SpdyRoundTripper implements the UpgradeRoundTripper interface. type SpdyRoundTripper struct { //tlsConfig holds the TLS configuration settings to use when connecting //to the remote server. tlsConfig *tls.Config /* TODO according to http://golang.org/pkg/net/http/#RoundTripper, a RoundTripper must be safe for use by multiple concurrent goroutines. If this is absolutely necessary, we could keep a map from http.Request to net.Conn. In practice, a client will create an http.Client, set the transport to a new insteace of SpdyRoundTripper, and use it a single time, so this hopefully won't be an issue. */ // conn is the underlying network connection to the remote server. conn net.Conn // Dialer is the dialer used to connect. Used if non-nil. Dialer *net.Dialer // proxier knows which proxy to use given a request, defaults to http.ProxyFromEnvironment // Used primarily for mocking the proxy discovery in tests. proxier func(req *http.Request) (*url.URL, error) // pingPeriod is a period for sending Ping frames over established // connections. pingPeriod time.Duration // upgradeTransport is an optional substitute for dialing if present. This field is // mutually exclusive with the "tlsConfig", "Dialer", and "proxier". upgradeTransport http.RoundTripper } var _ utilnet.TLSClientConfigHolder = &SpdyRoundTripper{} var _ httpstream.UpgradeRoundTripper = &SpdyRoundTripper{} var _ utilnet.Dialer = &SpdyRoundTripper{} // NewRoundTripper creates a new SpdyRoundTripper that will use the specified // tlsConfig. func NewRoundTripper(tlsConfig *tls.Config) (*SpdyRoundTripper, error) { return NewRoundTripperWithConfig(RoundTripperConfig{ TLS: tlsConfig, UpgradeTransport: nil, }) } // NewRoundTripperWithProxy creates a new SpdyRoundTripper that will use the // specified tlsConfig and proxy func. func NewRoundTripperWithProxy(tlsConfig *tls.Config, proxier func(*http.Request) (*url.URL, error)) (*SpdyRoundTripper, error) { return NewRoundTripperWithConfig(RoundTripperConfig{ TLS: tlsConfig, Proxier: proxier, UpgradeTransport: nil, }) } // NewRoundTripperWithConfig creates a new SpdyRoundTripper with the specified // configuration. Returns an error if the SpdyRoundTripper is misconfigured. func NewRoundTripperWithConfig(cfg RoundTripperConfig) (*SpdyRoundTripper, error) { // Process UpgradeTransport, which is mutually exclusive to TLSConfig and Proxier. if cfg.UpgradeTransport != nil { if cfg.TLS != nil || cfg.Proxier != nil { return nil, fmt.Errorf("SpdyRoundTripper: UpgradeTransport is mutually exclusive to TLSConfig or Proxier") } tlsConfig, err := utilnet.TLSClientConfig(cfg.UpgradeTransport) if err != nil { return nil, fmt.Errorf("SpdyRoundTripper: Unable to retrieve TLSConfig from UpgradeTransport: %v", err) } cfg.TLS = tlsConfig } if cfg.Proxier == nil { cfg.Proxier = utilnet.NewProxierWithNoProxyCIDR(http.ProxyFromEnvironment) } return &SpdyRoundTripper{ tlsConfig: cfg.TLS, proxier: cfg.Proxier, pingPeriod: cfg.PingPeriod, upgradeTransport: cfg.UpgradeTransport, }, nil } // RoundTripperConfig is a set of options for an SpdyRoundTripper. type RoundTripperConfig struct { // TLS configuration used by the round tripper if UpgradeTransport not present. TLS *tls.Config // Proxier is a proxy function invoked on each request. Optional. Proxier func(*http.Request) (*url.URL, error) // PingPeriod is a period for sending SPDY Pings on the connection. // Optional. PingPeriod time.Duration // UpgradeTransport is a subtitute transport used for dialing. If set, // this field will be used instead of "TLS" and "Proxier" for connection creation. // Optional. UpgradeTransport http.RoundTripper } // TLSClientConfig implements pkg/util/net.TLSClientConfigHolder for proper TLS checking during // proxying with a spdy roundtripper. func (s *SpdyRoundTripper) TLSClientConfig() *tls.Config { return s.tlsConfig } // Dial implements k8s.io/apimachinery/pkg/util/net.Dialer. func (s *SpdyRoundTripper) Dial(req *http.Request) (net.Conn, error) { var conn net.Conn var err error if s.upgradeTransport != nil { conn, err = apiproxy.DialURL(req.Context(), req.URL, s.upgradeTransport) } else { conn, err = s.dial(req) } if err != nil { return nil, err } if err := req.Write(conn); err != nil { conn.Close() return nil, err } return conn, nil } // dial dials the host specified by req, using TLS if appropriate, optionally // using a proxy server if one is configured via environment variables. func (s *SpdyRoundTripper) dial(req *http.Request) (net.Conn, error) { proxyURL, err := s.proxier(req) if err != nil { return nil, err } if proxyURL == nil { return s.dialWithoutProxy(req.Context(), req.URL) } switch proxyURL.Scheme { case "socks5": return s.dialWithSocks5Proxy(req, proxyURL) case "https", "http", "": return s.dialWithHttpProxy(req, proxyURL) } return nil, fmt.Errorf("proxy URL scheme not supported: %s", proxyURL.Scheme) } // dialWithHttpProxy dials the host specified by url through an http or an https proxy. func (s *SpdyRoundTripper) dialWithHttpProxy(req *http.Request, proxyURL *url.URL) (net.Conn, error) { // ensure we use a canonical host with proxyReq targetHost := netutil.CanonicalAddr(req.URL) // proxying logic adapted from http://blog.h6t.eu/post/74098062923/golang-websocket-with-http-proxy-support proxyReq := http.Request{ Method: "CONNECT", URL: &url.URL{}, Host: targetHost, } proxyReq = *proxyReq.WithContext(req.Context()) if pa := s.proxyAuth(proxyURL); pa != "" { proxyReq.Header = http.Header{} proxyReq.Header.Set("Proxy-Authorization", pa) } proxyDialConn, err := s.dialWithoutProxy(proxyReq.Context(), proxyURL) if err != nil { return nil, err } //nolint:staticcheck // SA1019 ignore deprecated httputil.NewProxyClientConn proxyClientConn := httputil.NewProxyClientConn(proxyDialConn, nil) response, err := proxyClientConn.Do(&proxyReq) //nolint:staticcheck // SA1019 ignore deprecated httputil.ErrPersistEOF: it might be // returned from the invocation of proxyClientConn.Do if err != nil && err != httputil.ErrPersistEOF { return nil, err } if response != nil && response.StatusCode >= 300 || response.StatusCode < 200 { return nil, fmt.Errorf("CONNECT request to %s returned response: %s", proxyURL.Redacted(), response.Status) } rwc, _ := proxyClientConn.Hijack() if req.URL.Scheme == "https" { return s.tlsConn(proxyReq.Context(), rwc, targetHost) } return rwc, nil } // dialWithSocks5Proxy dials the host specified by url through a socks5 proxy. func (s *SpdyRoundTripper) dialWithSocks5Proxy(req *http.Request, proxyURL *url.URL) (net.Conn, error) { // ensure we use a canonical host with proxyReq targetHost := netutil.CanonicalAddr(req.URL) proxyDialAddr := netutil.CanonicalAddr(proxyURL) var auth *proxy.Auth if proxyURL.User != nil { pass, _ := proxyURL.User.Password() auth = &proxy.Auth{ User: proxyURL.User.Username(), Password: pass, } } dialer := s.Dialer if dialer == nil { dialer = &net.Dialer{ Timeout: 30 * time.Second, } } proxyDialer, err := proxy.SOCKS5("tcp", proxyDialAddr, auth, dialer) if err != nil { return nil, err } // According to the implementation of proxy.SOCKS5, the type assertion will always succeed contextDialer, ok := proxyDialer.(proxy.ContextDialer) if !ok { return nil, errors.New("SOCKS5 Dialer must implement ContextDialer") } proxyDialConn, err := contextDialer.DialContext(req.Context(), "tcp", targetHost) if err != nil { return nil, err } if req.URL.Scheme == "https" { return s.tlsConn(req.Context(), proxyDialConn, targetHost) } return proxyDialConn, nil } // tlsConn returns a TLS client side connection using rwc as the underlying transport. func (s *SpdyRoundTripper) tlsConn(ctx context.Context, rwc net.Conn, targetHost string) (net.Conn, error) { host, _, err := net.SplitHostPort(targetHost) if err != nil { return nil, err } tlsConfig := s.tlsConfig switch { case tlsConfig == nil: tlsConfig = &tls.Config{ServerName: host} case len(tlsConfig.ServerName) == 0: tlsConfig = tlsConfig.Clone() tlsConfig.ServerName = host } tlsConn := tls.Client(rwc, tlsConfig) if err := tlsConn.HandshakeContext(ctx); err != nil { tlsConn.Close() return nil, err } return tlsConn, nil } // dialWithoutProxy dials the host specified by url, using TLS if appropriate. func (s *SpdyRoundTripper) dialWithoutProxy(ctx context.Context, url *url.URL) (net.Conn, error) { dialAddr := netutil.CanonicalAddr(url) dialer := s.Dialer if dialer == nil { dialer = &net.Dialer{} } if url.Scheme == "http" { return dialer.DialContext(ctx, "tcp", dialAddr) } tlsDialer := tls.Dialer{ NetDialer: dialer, Config: s.tlsConfig, } return tlsDialer.DialContext(ctx, "tcp", dialAddr) } // proxyAuth returns, for a given proxy URL, the value to be used for the Proxy-Authorization header func (s *SpdyRoundTripper) proxyAuth(proxyURL *url.URL) string { if proxyURL == nil || proxyURL.User == nil { return "" } username := proxyURL.User.Username() password, _ := proxyURL.User.Password() auth := username + ":" + password return "Basic " + base64.StdEncoding.EncodeToString([]byte(auth)) } // RoundTrip executes the Request and upgrades it. After a successful upgrade, // clients may call SpdyRoundTripper.Connection() to retrieve the upgraded // connection. func (s *SpdyRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { req = utilnet.CloneRequest(req) req.Header.Add(httpstream.HeaderConnection, httpstream.HeaderUpgrade) req.Header.Add(httpstream.HeaderUpgrade, HeaderSpdy31) conn, err := s.Dial(req) if err != nil { return nil, err } responseReader := bufio.NewReader(conn) resp, err := http.ReadResponse(responseReader, nil) if err != nil { conn.Close() return nil, err } s.conn = conn return resp, nil } // NewConnection validates the upgrade response, creating and returning a new // httpstream.Connection if there were no errors. func (s *SpdyRoundTripper) NewConnection(resp *http.Response) (httpstream.Connection, error) { connectionHeader := strings.ToLower(resp.Header.Get(httpstream.HeaderConnection)) upgradeHeader := strings.ToLower(resp.Header.Get(httpstream.HeaderUpgrade)) if (resp.StatusCode != http.StatusSwitchingProtocols) || !strings.Contains(connectionHeader, strings.ToLower(httpstream.HeaderUpgrade)) || !strings.Contains(upgradeHeader, strings.ToLower(HeaderSpdy31)) { defer resp.Body.Close() responseError := "" responseErrorBytes, err := io.ReadAll(resp.Body) if err != nil { responseError = "unable to read error from server response" } else { // TODO: I don't belong here, I should be abstracted from this class if obj, _, err := statusCodecs.UniversalDecoder().Decode(responseErrorBytes, nil, &metav1.Status{}); err == nil { if status, ok := obj.(*metav1.Status); ok { return nil, &apierrors.StatusError{ErrStatus: *status} } } responseError = string(responseErrorBytes) responseError = strings.TrimSpace(responseError) } return nil, fmt.Errorf("unable to upgrade connection: %s", responseError) } return NewClientConnectionWithPings(s.conn, s.pingPeriod) } // statusScheme is private scheme for the decoding here until someone fixes the TODO in NewConnection var statusScheme = runtime.NewScheme() // ParameterCodec knows about query parameters used with the meta v1 API spec. var statusCodecs = serializer.NewCodecFactory(statusScheme) func init() { statusScheme.AddUnversionedTypes(metav1.SchemeGroupVersion, &metav1.Status{}, ) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/apimachinery/pkg/util/httpstream/spdy/upgrade.go
vendor/k8s.io/apimachinery/pkg/util/httpstream/spdy/upgrade.go
/* Copyright 2015 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 spdy import ( "bufio" "fmt" "io" "net" "net/http" "strings" "sync/atomic" "time" "k8s.io/apimachinery/pkg/util/httpstream" "k8s.io/apimachinery/pkg/util/runtime" ) const HeaderSpdy31 = "SPDY/3.1" // responseUpgrader knows how to upgrade HTTP responses. It // implements the httpstream.ResponseUpgrader interface. type responseUpgrader struct { pingPeriod time.Duration } // connWrapper is used to wrap a hijacked connection and its bufio.Reader. All // calls will be handled directly by the underlying net.Conn with the exception // of Read and Close calls, which will consider data in the bufio.Reader. This // ensures that data already inside the used bufio.Reader instance is also // read. type connWrapper struct { net.Conn closed int32 bufReader *bufio.Reader } func (w *connWrapper) Read(b []byte) (n int, err error) { if atomic.LoadInt32(&w.closed) == 1 { return 0, io.EOF } return w.bufReader.Read(b) } func (w *connWrapper) Close() error { err := w.Conn.Close() atomic.StoreInt32(&w.closed, 1) return err } // NewResponseUpgrader returns a new httpstream.ResponseUpgrader that is // capable of upgrading HTTP responses using SPDY/3.1 via the // spdystream package. func NewResponseUpgrader() httpstream.ResponseUpgrader { return NewResponseUpgraderWithPings(0) } // NewResponseUpgraderWithPings returns a new httpstream.ResponseUpgrader that // is capable of upgrading HTTP responses using SPDY/3.1 via the spdystream // package. // // If pingPeriod is non-zero, for each incoming connection a background // goroutine will send periodic Ping frames to the server. Use this to keep // idle connections through certain load balancers alive longer. func NewResponseUpgraderWithPings(pingPeriod time.Duration) httpstream.ResponseUpgrader { return responseUpgrader{pingPeriod: pingPeriod} } // UpgradeResponse upgrades an HTTP response to one that supports multiplexed // streams. newStreamHandler will be called synchronously whenever the // other end of the upgraded connection creates a new stream. func (u responseUpgrader) UpgradeResponse(w http.ResponseWriter, req *http.Request, newStreamHandler httpstream.NewStreamHandler) httpstream.Connection { connectionHeader := strings.ToLower(req.Header.Get(httpstream.HeaderConnection)) upgradeHeader := strings.ToLower(req.Header.Get(httpstream.HeaderUpgrade)) if !strings.Contains(connectionHeader, strings.ToLower(httpstream.HeaderUpgrade)) || !strings.Contains(upgradeHeader, strings.ToLower(HeaderSpdy31)) { errorMsg := fmt.Sprintf("unable to upgrade: missing upgrade headers in request: %#v", req.Header) http.Error(w, errorMsg, http.StatusBadRequest) return nil } hijacker, ok := w.(http.Hijacker) if !ok { errorMsg := "unable to upgrade: unable to hijack response" http.Error(w, errorMsg, http.StatusInternalServerError) return nil } w.Header().Add(httpstream.HeaderConnection, httpstream.HeaderUpgrade) w.Header().Add(httpstream.HeaderUpgrade, HeaderSpdy31) w.WriteHeader(http.StatusSwitchingProtocols) conn, bufrw, err := hijacker.Hijack() if err != nil { runtime.HandleError(fmt.Errorf("unable to upgrade: error hijacking response: %v", err)) return nil } connWithBuf := &connWrapper{Conn: conn, bufReader: bufrw.Reader} spdyConn, err := NewServerConnectionWithPings(connWithBuf, newStreamHandler, u.pingPeriod) if err != nil { runtime.HandleError(fmt.Errorf("unable to upgrade: error creating SPDY server connection: %v", err)) return nil } return spdyConn }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/apimachinery/pkg/util/proxy/upgradeaware.go
vendor/k8s.io/apimachinery/pkg/util/proxy/upgradeaware.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 proxy import ( "bufio" "bytes" "fmt" "io" "log" "net" "net/http" "net/http/httputil" "net/url" "os" "strings" "time" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/util/httpstream" utilnet "k8s.io/apimachinery/pkg/util/net" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "github.com/mxk/go-flowrate/flowrate" "k8s.io/klog/v2" ) // UpgradeRequestRoundTripper provides an additional method to decorate a request // with any authentication or other protocol level information prior to performing // an upgrade on the server. Any response will be handled by the intercepting // proxy. type UpgradeRequestRoundTripper interface { http.RoundTripper // WrapRequest takes a valid HTTP request and returns a suitably altered version // of request with any HTTP level values required to complete the request half of // an upgrade on the server. It does not get a chance to see the response and // should bypass any request side logic that expects to see the response. WrapRequest(*http.Request) (*http.Request, error) } // UpgradeAwareHandler is a handler for proxy requests that may require an upgrade type UpgradeAwareHandler struct { // UpgradeRequired will reject non-upgrade connections if true. UpgradeRequired bool // Location is the location of the upstream proxy. It is used as the location to Dial on the upstream server // for upgrade requests unless UseRequestLocationOnUpgrade is true. Location *url.URL // AppendLocationPath determines if the original path of the Location should be appended to the upstream proxy request path AppendLocationPath bool // Transport provides an optional round tripper to use to proxy. If nil, the default proxy transport is used Transport http.RoundTripper // UpgradeTransport, if specified, will be used as the backend transport when upgrade requests are provided. // This allows clients to disable HTTP/2. UpgradeTransport UpgradeRequestRoundTripper // WrapTransport indicates whether the provided Transport should be wrapped with default proxy transport behavior (URL rewriting, X-Forwarded-* header setting) WrapTransport bool // UseRequestLocation will use the incoming request URL when talking to the backend server. UseRequestLocation bool // UseLocationHost overrides the HTTP host header in requests to the backend server to use the Host from Location. // This will override the req.Host field of a request, while UseRequestLocation will override the req.URL field // of a request. The req.URL.Host specifies the server to connect to, while the req.Host field // specifies the Host header value to send in the HTTP request. If this is false, the incoming req.Host header will // just be forwarded to the backend server. UseLocationHost bool // FlushInterval controls how often the standard HTTP proxy will flush content from the upstream. FlushInterval time.Duration // MaxBytesPerSec controls the maximum rate for an upstream connection. No rate is imposed if the value is zero. MaxBytesPerSec int64 // Responder is passed errors that occur while setting up proxying. Responder ErrorResponder // Reject to forward redirect response RejectForwardingRedirects bool } const defaultFlushInterval = 200 * time.Millisecond // ErrorResponder abstracts error reporting to the proxy handler to remove the need to hardcode a particular // error format. type ErrorResponder interface { Error(w http.ResponseWriter, req *http.Request, err error) } // SimpleErrorResponder is the legacy implementation of ErrorResponder for callers that only // service a single request/response per proxy. type SimpleErrorResponder interface { Error(err error) } func NewErrorResponder(r SimpleErrorResponder) ErrorResponder { return simpleResponder{r} } type simpleResponder struct { responder SimpleErrorResponder } func (r simpleResponder) Error(w http.ResponseWriter, req *http.Request, err error) { r.responder.Error(err) } // upgradeRequestRoundTripper implements proxy.UpgradeRequestRoundTripper. type upgradeRequestRoundTripper struct { http.RoundTripper upgrader http.RoundTripper } var ( _ UpgradeRequestRoundTripper = &upgradeRequestRoundTripper{} _ utilnet.RoundTripperWrapper = &upgradeRequestRoundTripper{} ) // WrappedRoundTripper returns the round tripper that a caller would use. func (rt *upgradeRequestRoundTripper) WrappedRoundTripper() http.RoundTripper { return rt.RoundTripper } // WriteToRequest calls the nested upgrader and then copies the returned request // fields onto the passed request. func (rt *upgradeRequestRoundTripper) WrapRequest(req *http.Request) (*http.Request, error) { resp, err := rt.upgrader.RoundTrip(req) if err != nil { return nil, err } return resp.Request, nil } // onewayRoundTripper captures the provided request - which is assumed to have // been modified by other round trippers - and then returns a fake response. type onewayRoundTripper struct{} // RoundTrip returns a simple 200 OK response that captures the provided request. func (onewayRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { return &http.Response{ Status: "200 OK", StatusCode: http.StatusOK, Body: io.NopCloser(&bytes.Buffer{}), Request: req, }, nil } // MirrorRequest is a round tripper that can be called to get back the calling request as // the core round tripper in a chain. var MirrorRequest http.RoundTripper = onewayRoundTripper{} // NewUpgradeRequestRoundTripper takes two round trippers - one for the underlying TCP connection, and // one that is able to write headers to an HTTP request. The request rt is used to set the request headers // and that is written to the underlying connection rt. func NewUpgradeRequestRoundTripper(connection, request http.RoundTripper) UpgradeRequestRoundTripper { return &upgradeRequestRoundTripper{ RoundTripper: connection, upgrader: request, } } // normalizeLocation returns the result of parsing the full URL, with scheme set to http if missing func normalizeLocation(location *url.URL) *url.URL { normalized, _ := url.Parse(location.String()) if len(normalized.Scheme) == 0 { normalized.Scheme = "http" } return normalized } // NewUpgradeAwareHandler creates a new proxy handler with a default flush interval. Responder is required for returning // errors to the caller. func NewUpgradeAwareHandler(location *url.URL, transport http.RoundTripper, wrapTransport, upgradeRequired bool, responder ErrorResponder) *UpgradeAwareHandler { return &UpgradeAwareHandler{ Location: normalizeLocation(location), Transport: transport, WrapTransport: wrapTransport, UpgradeRequired: upgradeRequired, FlushInterval: defaultFlushInterval, Responder: responder, } } func proxyRedirectsforRootPath(path string, w http.ResponseWriter, req *http.Request) bool { redirect := false method := req.Method // From pkg/genericapiserver/endpoints/handlers/proxy.go#ServeHTTP: // Redirect requests with an empty path to a location that ends with a '/' // This is essentially a hack for https://issue.k8s.io/4958. // Note: Keep this code after tryUpgrade to not break that flow. if len(path) == 0 && (method == http.MethodGet || method == http.MethodHead) { var queryPart string if len(req.URL.RawQuery) > 0 { queryPart = "?" + req.URL.RawQuery } w.Header().Set("Location", req.URL.Path+"/"+queryPart) w.WriteHeader(http.StatusMovedPermanently) redirect = true } return redirect } // ServeHTTP handles the proxy request func (h *UpgradeAwareHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { if h.tryUpgrade(w, req) { return } if h.UpgradeRequired { h.Responder.Error(w, req, errors.NewBadRequest("Upgrade request required")) return } loc := *h.Location loc.RawQuery = req.URL.RawQuery // If original request URL ended in '/', append a '/' at the end of the // of the proxy URL if !strings.HasSuffix(loc.Path, "/") && strings.HasSuffix(req.URL.Path, "/") { loc.Path += "/" } proxyRedirect := proxyRedirectsforRootPath(loc.Path, w, req) if proxyRedirect { return } if h.Transport == nil || h.WrapTransport { h.Transport = h.defaultProxyTransport(req.URL, h.Transport) } // WithContext creates a shallow clone of the request with the same context. newReq := req.WithContext(req.Context()) newReq.Header = utilnet.CloneHeader(req.Header) if !h.UseRequestLocation { newReq.URL = &loc } if h.UseLocationHost { // exchanging req.Host with the backend location is necessary for backends that act on the HTTP host header (e.g. API gateways), // because req.Host has preference over req.URL.Host in filling this header field newReq.Host = h.Location.Host } // create the target location to use for the reverse proxy reverseProxyLocation := &url.URL{Scheme: h.Location.Scheme, Host: h.Location.Host} if h.AppendLocationPath { reverseProxyLocation.Path = h.Location.Path } proxy := httputil.NewSingleHostReverseProxy(reverseProxyLocation) proxy.Transport = h.Transport proxy.FlushInterval = h.FlushInterval proxy.ErrorLog = log.New(noSuppressPanicError{}, "", log.LstdFlags) if h.RejectForwardingRedirects { oldModifyResponse := proxy.ModifyResponse proxy.ModifyResponse = func(response *http.Response) error { code := response.StatusCode if code >= 300 && code <= 399 && len(response.Header.Get("Location")) > 0 { // close the original response response.Body.Close() msg := "the backend attempted to redirect this request, which is not permitted" // replace the response *response = http.Response{ StatusCode: http.StatusBadGateway, Status: fmt.Sprintf("%d %s", response.StatusCode, http.StatusText(response.StatusCode)), Body: io.NopCloser(strings.NewReader(msg)), ContentLength: int64(len(msg)), } } else { if oldModifyResponse != nil { if err := oldModifyResponse(response); err != nil { return err } } } return nil } } if h.Responder != nil { // if an optional error interceptor/responder was provided wire it // the custom responder might be used for providing a unified error reporting // or supporting retry mechanisms by not sending non-fatal errors to the clients proxy.ErrorHandler = h.Responder.Error } proxy.ServeHTTP(w, newReq) } type noSuppressPanicError struct{} func (noSuppressPanicError) Write(p []byte) (n int, err error) { // skip "suppressing panic for copyResponse error in test; copy error" error message // that ends up in CI tests on each kube-apiserver termination as noise and // everybody thinks this is fatal. if strings.Contains(string(p), "suppressing panic") { return len(p), nil } return os.Stderr.Write(p) } // tryUpgrade returns true if the request was handled. func (h *UpgradeAwareHandler) tryUpgrade(w http.ResponseWriter, req *http.Request) bool { if !httpstream.IsUpgradeRequest(req) { klog.V(6).Infof("Request was not an upgrade") return false } var ( backendConn net.Conn rawResponse []byte err error ) location := *h.Location if h.UseRequestLocation { location = *req.URL location.Scheme = h.Location.Scheme location.Host = h.Location.Host if h.AppendLocationPath { location.Path = singleJoiningSlash(h.Location.Path, location.Path) } } clone := utilnet.CloneRequest(req) // Only append X-Forwarded-For in the upgrade path, since httputil.NewSingleHostReverseProxy // handles this in the non-upgrade path. utilnet.AppendForwardedForHeader(clone) klog.V(6).Infof("Connecting to backend proxy (direct dial) %s\n Headers: %v", &location, clone.Header) if h.UseLocationHost { clone.Host = h.Location.Host } clone.URL = &location klog.V(6).Infof("UpgradeAwareProxy: dialing for SPDY upgrade with headers: %v", clone.Header) backendConn, err = h.DialForUpgrade(clone) if err != nil { klog.V(6).Infof("Proxy connection error: %v", err) h.Responder.Error(w, req, err) return true } defer backendConn.Close() // determine the http response code from the backend by reading from rawResponse+backendConn backendHTTPResponse, headerBytes, err := getResponse(io.MultiReader(bytes.NewReader(rawResponse), backendConn)) if err != nil { klog.V(6).Infof("Proxy connection error: %v", err) h.Responder.Error(w, req, err) return true } if len(headerBytes) > len(rawResponse) { // we read beyond the bytes stored in rawResponse, update rawResponse to the full set of bytes read from the backend rawResponse = headerBytes } // If the backend did not upgrade the request, return an error to the client. If the response was // an error, the error is forwarded directly after the connection is hijacked. Otherwise, just // return a generic error here. if backendHTTPResponse.StatusCode != http.StatusSwitchingProtocols && backendHTTPResponse.StatusCode < 400 { err := fmt.Errorf("invalid upgrade response: status code %d", backendHTTPResponse.StatusCode) klog.Errorf("Proxy upgrade error: %v", err) h.Responder.Error(w, req, err) return true } // Once the connection is hijacked, the ErrorResponder will no longer work, so // hijacking should be the last step in the upgrade. requestHijacker, ok := w.(http.Hijacker) if !ok { klog.Errorf("Unable to hijack response writer: %T", w) h.Responder.Error(w, req, fmt.Errorf("request connection cannot be hijacked: %T", w)) return true } requestHijackedConn, _, err := requestHijacker.Hijack() if err != nil { klog.Errorf("Unable to hijack response: %v", err) h.Responder.Error(w, req, fmt.Errorf("error hijacking connection: %v", err)) return true } defer requestHijackedConn.Close() if backendHTTPResponse.StatusCode != http.StatusSwitchingProtocols { // If the backend did not upgrade the request, echo the response from the backend to the client and return, closing the connection. klog.V(6).Infof("Proxy upgrade error, status code %d", backendHTTPResponse.StatusCode) // set read/write deadlines deadline := time.Now().Add(10 * time.Second) backendConn.SetReadDeadline(deadline) requestHijackedConn.SetWriteDeadline(deadline) // write the response to the client err := backendHTTPResponse.Write(requestHijackedConn) if err != nil && !strings.Contains(err.Error(), "use of closed network connection") { klog.Errorf("Error proxying data from backend to client: %v", err) } // Indicate we handled the request return true } // Forward raw response bytes back to client. if len(rawResponse) > 0 { klog.V(6).Infof("Writing %d bytes to hijacked connection", len(rawResponse)) if _, err = requestHijackedConn.Write(rawResponse); err != nil { utilruntime.HandleError(fmt.Errorf("Error proxying response from backend to client: %v", err)) } } // Proxy the connection. This is bidirectional, so we need a goroutine // to copy in each direction. Once one side of the connection exits, we // exit the function which performs cleanup and in the process closes // the other half of the connection in the defer. writerComplete := make(chan struct{}) readerComplete := make(chan struct{}) go func() { var writer io.WriteCloser if h.MaxBytesPerSec > 0 { writer = flowrate.NewWriter(backendConn, h.MaxBytesPerSec) } else { writer = backendConn } _, err := io.Copy(writer, requestHijackedConn) if err != nil && !strings.Contains(err.Error(), "use of closed network connection") { klog.Errorf("Error proxying data from client to backend: %v", err) } close(writerComplete) }() go func() { var reader io.ReadCloser if h.MaxBytesPerSec > 0 { reader = flowrate.NewReader(backendConn, h.MaxBytesPerSec) } else { reader = backendConn } _, err := io.Copy(requestHijackedConn, reader) if err != nil && !strings.Contains(err.Error(), "use of closed network connection") { klog.Errorf("Error proxying data from backend to client: %v", err) } close(readerComplete) }() // Wait for one half the connection to exit. Once it does the defer will // clean up the other half of the connection. select { case <-writerComplete: case <-readerComplete: } klog.V(6).Infof("Disconnecting from backend proxy %s\n Headers: %v", &location, clone.Header) return true } // FIXME: Taken from net/http/httputil/reverseproxy.go as singleJoiningSlash is not exported to be re-used. // See-also: https://github.com/golang/go/issues/44290 func singleJoiningSlash(a, b string) string { aslash := strings.HasSuffix(a, "/") bslash := strings.HasPrefix(b, "/") switch { case aslash && bslash: return a + b[1:] case !aslash && !bslash: return a + "/" + b } return a + b } func (h *UpgradeAwareHandler) DialForUpgrade(req *http.Request) (net.Conn, error) { if h.UpgradeTransport == nil { return dial(req, h.Transport) } updatedReq, err := h.UpgradeTransport.WrapRequest(req) if err != nil { return nil, err } return dial(updatedReq, h.UpgradeTransport) } // getResponseCode reads a http response from the given reader, returns the response, // the bytes read from the reader, and any error encountered func getResponse(r io.Reader) (*http.Response, []byte, error) { rawResponse := bytes.NewBuffer(make([]byte, 0, 256)) // Save the bytes read while reading the response headers into the rawResponse buffer resp, err := http.ReadResponse(bufio.NewReader(io.TeeReader(r, rawResponse)), nil) if err != nil { return nil, nil, err } // return the http response and the raw bytes consumed from the reader in the process return resp, rawResponse.Bytes(), nil } // dial dials the backend at req.URL and writes req to it. func dial(req *http.Request, transport http.RoundTripper) (net.Conn, error) { conn, err := DialURL(req.Context(), req.URL, transport) if err != nil { return nil, fmt.Errorf("error dialing backend: %v", err) } if err = req.Write(conn); err != nil { conn.Close() return nil, fmt.Errorf("error sending request: %v", err) } return conn, err } func (h *UpgradeAwareHandler) defaultProxyTransport(url *url.URL, internalTransport http.RoundTripper) http.RoundTripper { scheme := url.Scheme host := url.Host suffix := h.Location.Path if strings.HasSuffix(url.Path, "/") && !strings.HasSuffix(suffix, "/") { suffix += "/" } pathPrepend := strings.TrimSuffix(url.Path, suffix) rewritingTransport := &Transport{ Scheme: scheme, Host: host, PathPrepend: pathPrepend, RoundTripper: internalTransport, } return &corsRemovingTransport{ RoundTripper: rewritingTransport, } } // corsRemovingTransport is a wrapper for an internal transport. It removes CORS headers // from the internal response. // Implements pkg/util/net.RoundTripperWrapper type corsRemovingTransport struct { http.RoundTripper } var _ = utilnet.RoundTripperWrapper(&corsRemovingTransport{}) func (rt *corsRemovingTransport) RoundTrip(req *http.Request) (*http.Response, error) { resp, err := rt.RoundTripper.RoundTrip(req) if err != nil { return nil, err } removeCORSHeaders(resp) return resp, nil } func (rt *corsRemovingTransport) WrappedRoundTripper() http.RoundTripper { return rt.RoundTripper } // removeCORSHeaders strip CORS headers sent from the backend // This should be called on all responses before returning func removeCORSHeaders(resp *http.Response) { resp.Header.Del("Access-Control-Allow-Credentials") resp.Header.Del("Access-Control-Allow-Headers") resp.Header.Del("Access-Control-Allow-Methods") resp.Header.Del("Access-Control-Allow-Origin") }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/apimachinery/pkg/util/proxy/doc.go
vendor/k8s.io/apimachinery/pkg/util/proxy/doc.go
/* Copyright 2014 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 proxy provides transport and upgrade support for proxies. package proxy // import "k8s.io/apimachinery/pkg/util/proxy"
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/apimachinery/pkg/util/proxy/transport.go
vendor/k8s.io/apimachinery/pkg/util/proxy/transport.go
/* Copyright 2014 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 proxy import ( "bytes" "compress/flate" "compress/gzip" "fmt" "io" "net/http" "net/url" "path" "strings" "golang.org/x/net/html" "golang.org/x/net/html/atom" "k8s.io/klog/v2" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/util/net" "k8s.io/apimachinery/pkg/util/sets" ) // atomsToAttrs states which attributes of which tags require URL substitution. // Sources: http://www.w3.org/TR/REC-html40/index/attributes.html // // http://www.w3.org/html/wg/drafts/html/master/index.html#attributes-1 var atomsToAttrs = map[atom.Atom]sets.String{ atom.A: sets.NewString("href"), atom.Applet: sets.NewString("codebase"), atom.Area: sets.NewString("href"), atom.Audio: sets.NewString("src"), atom.Base: sets.NewString("href"), atom.Blockquote: sets.NewString("cite"), atom.Body: sets.NewString("background"), atom.Button: sets.NewString("formaction"), atom.Command: sets.NewString("icon"), atom.Del: sets.NewString("cite"), atom.Embed: sets.NewString("src"), atom.Form: sets.NewString("action"), atom.Frame: sets.NewString("longdesc", "src"), atom.Head: sets.NewString("profile"), atom.Html: sets.NewString("manifest"), atom.Iframe: sets.NewString("longdesc", "src"), atom.Img: sets.NewString("longdesc", "src", "usemap"), atom.Input: sets.NewString("src", "usemap", "formaction"), atom.Ins: sets.NewString("cite"), atom.Link: sets.NewString("href"), atom.Object: sets.NewString("classid", "codebase", "data", "usemap"), atom.Q: sets.NewString("cite"), atom.Script: sets.NewString("src"), atom.Source: sets.NewString("src"), atom.Video: sets.NewString("poster", "src"), // TODO: css URLs hidden in style elements. } // Transport is a transport for text/html content that replaces URLs in html // content with the prefix of the proxy server type Transport struct { Scheme string Host string PathPrepend string http.RoundTripper } // RoundTrip implements the http.RoundTripper interface func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) { // Add reverse proxy headers. forwardedURI := path.Join(t.PathPrepend, req.URL.EscapedPath()) if strings.HasSuffix(req.URL.Path, "/") { forwardedURI = forwardedURI + "/" } req.Header.Set("X-Forwarded-Uri", forwardedURI) if len(t.Host) > 0 { req.Header.Set("X-Forwarded-Host", t.Host) } if len(t.Scheme) > 0 { req.Header.Set("X-Forwarded-Proto", t.Scheme) } rt := t.RoundTripper if rt == nil { rt = http.DefaultTransport } resp, err := rt.RoundTrip(req) if err != nil { return nil, errors.NewServiceUnavailable(fmt.Sprintf("error trying to reach service: %v", err)) } if redirect := resp.Header.Get("Location"); redirect != "" { targetURL, err := url.Parse(redirect) if err != nil { return nil, errors.NewInternalError(fmt.Errorf("error trying to parse Location header: %v", err)) } resp.Header.Set("Location", t.rewriteURL(targetURL, req.URL, req.Host)) return resp, nil } cType := resp.Header.Get("Content-Type") cType = strings.TrimSpace(strings.SplitN(cType, ";", 2)[0]) if cType != "text/html" { // Do nothing, simply pass through return resp, nil } return t.rewriteResponse(req, resp) } var _ = net.RoundTripperWrapper(&Transport{}) func (rt *Transport) WrappedRoundTripper() http.RoundTripper { return rt.RoundTripper } // rewriteURL rewrites a single URL to go through the proxy, if the URL refers // to the same host as sourceURL, which is the page on which the target URL // occurred, or if the URL matches the sourceRequestHost. func (t *Transport) rewriteURL(url *url.URL, sourceURL *url.URL, sourceRequestHost string) string { // Example: // When API server processes a proxy request to a service (e.g. /api/v1/namespace/foo/service/bar/proxy/), // the sourceURL.Host (i.e. req.URL.Host) is the endpoint IP address of the service. The // sourceRequestHost (i.e. req.Host) is the Host header that specifies the host on which the // URL is sought, which can be different from sourceURL.Host. For example, if user sends the // request through "kubectl proxy" locally (i.e. localhost:8001/api/v1/namespace/foo/service/bar/proxy/), // sourceRequestHost is "localhost:8001". // // If the service's response URL contains non-empty host, and url.Host is equal to either sourceURL.Host // or sourceRequestHost, we should not consider the returned URL to be a completely different host. // It's the API server's responsibility to rewrite a same-host-and-absolute-path URL and append the // necessary URL prefix (i.e. /api/v1/namespace/foo/service/bar/proxy/). isDifferentHost := url.Host != "" && url.Host != sourceURL.Host && url.Host != sourceRequestHost isRelative := !strings.HasPrefix(url.Path, "/") if isDifferentHost || isRelative { return url.String() } // Do not rewrite scheme and host if the Transport has empty scheme and host // when targetURL already contains the sourceRequestHost if !(url.Host == sourceRequestHost && t.Scheme == "" && t.Host == "") { url.Scheme = t.Scheme url.Host = t.Host } origPath := url.Path // Do not rewrite URL if the sourceURL already contains the necessary prefix. if strings.HasPrefix(url.Path, t.PathPrepend) { return url.String() } url.Path = path.Join(t.PathPrepend, url.Path) if strings.HasSuffix(origPath, "/") { // Add back the trailing slash, which was stripped by path.Join(). url.Path += "/" } return url.String() } // rewriteHTML scans the HTML for tags with url-valued attributes, and updates // those values with the urlRewriter function. The updated HTML is output to the // writer. func rewriteHTML(reader io.Reader, writer io.Writer, urlRewriter func(*url.URL) string) error { // Note: This assumes the content is UTF-8. tokenizer := html.NewTokenizer(reader) var err error for err == nil { tokenType := tokenizer.Next() switch tokenType { case html.ErrorToken: err = tokenizer.Err() case html.StartTagToken, html.SelfClosingTagToken: token := tokenizer.Token() if urlAttrs, ok := atomsToAttrs[token.DataAtom]; ok { for i, attr := range token.Attr { if urlAttrs.Has(attr.Key) { url, err := url.Parse(attr.Val) if err != nil { // Do not rewrite the URL if it isn't valid. It is intended not // to error here to prevent the inability to understand the // content of the body to cause a fatal error. continue } token.Attr[i].Val = urlRewriter(url) } } } _, err = writer.Write([]byte(token.String())) default: _, err = writer.Write(tokenizer.Raw()) } } if err != io.EOF { return err } return nil } // rewriteResponse modifies an HTML response by updating absolute links referring // to the original host to instead refer to the proxy transport. func (t *Transport) rewriteResponse(req *http.Request, resp *http.Response) (*http.Response, error) { origBody := resp.Body defer origBody.Close() newContent := &bytes.Buffer{} var reader io.Reader = origBody var writer io.Writer = newContent encoding := resp.Header.Get("Content-Encoding") switch encoding { case "gzip": var err error reader, err = gzip.NewReader(reader) if err != nil { return nil, fmt.Errorf("errorf making gzip reader: %v", err) } gzw := gzip.NewWriter(writer) defer gzw.Close() writer = gzw case "deflate": var err error reader = flate.NewReader(reader) flw, err := flate.NewWriter(writer, flate.BestCompression) if err != nil { return nil, fmt.Errorf("errorf making flate writer: %v", err) } defer func() { flw.Close() flw.Flush() }() writer = flw case "": // This is fine default: // Some encoding we don't understand-- don't try to parse this klog.Errorf("Proxy encountered encoding %v for text/html; can't understand this so not fixing links.", encoding) return resp, nil } urlRewriter := func(targetUrl *url.URL) string { return t.rewriteURL(targetUrl, req.URL, req.Host) } err := rewriteHTML(reader, writer, urlRewriter) if err != nil { klog.Errorf("Failed to rewrite URLs: %v", err) return resp, err } resp.Body = io.NopCloser(newContent) // Update header node with new content-length // TODO: Remove any hash/signature headers here? resp.Header.Del("Content-Length") resp.ContentLength = int64(newContent.Len()) return resp, err }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/apimachinery/pkg/util/proxy/dial.go
vendor/k8s.io/apimachinery/pkg/util/proxy/dial.go
/* Copyright 2015 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 proxy import ( "context" "crypto/tls" "fmt" "net" "net/http" "net/url" utilnet "k8s.io/apimachinery/pkg/util/net" "k8s.io/apimachinery/third_party/forked/golang/netutil" "k8s.io/klog/v2" ) // DialURL will dial the specified URL using the underlying dialer held by the passed // RoundTripper. The primary use of this method is to support proxying upgradable connections. // For this reason this method will prefer to negotiate http/1.1 if the URL scheme is https. // If you wish to ensure ALPN negotiates http2 then set NextProto=[]string{"http2"} in the // TLSConfig of the http.Transport func DialURL(ctx context.Context, url *url.URL, transport http.RoundTripper) (net.Conn, error) { dialAddr := netutil.CanonicalAddr(url) dialer, err := utilnet.DialerFor(transport) if err != nil { klog.V(5).Infof("Unable to unwrap transport %T to get dialer: %v", transport, err) } switch url.Scheme { case "http": if dialer != nil { return dialer(ctx, "tcp", dialAddr) } var d net.Dialer return d.DialContext(ctx, "tcp", dialAddr) case "https": // Get the tls config from the transport if we recognize it tlsConfig, err := utilnet.TLSClientConfig(transport) if err != nil { klog.V(5).Infof("Unable to unwrap transport %T to get at TLS config: %v", transport, err) } if dialer != nil { // We have a dialer; use it to open the connection, then // create a tls client using the connection. netConn, err := dialer(ctx, "tcp", dialAddr) if err != nil { return nil, err } if tlsConfig == nil { // tls.Client requires non-nil config klog.Warning("using custom dialer with no TLSClientConfig. Defaulting to InsecureSkipVerify") // tls.Handshake() requires ServerName or InsecureSkipVerify tlsConfig = &tls.Config{ InsecureSkipVerify: true, } } else if len(tlsConfig.ServerName) == 0 && !tlsConfig.InsecureSkipVerify { // tls.HandshakeContext() requires ServerName or InsecureSkipVerify // infer the ServerName from the hostname we're connecting to. inferredHost := dialAddr if host, _, err := net.SplitHostPort(dialAddr); err == nil { inferredHost = host } // Make a copy to avoid polluting the provided config tlsConfigCopy := tlsConfig.Clone() tlsConfigCopy.ServerName = inferredHost tlsConfig = tlsConfigCopy } // Since this method is primarily used within a "Connection: Upgrade" call we assume the caller is // going to write HTTP/1.1 request to the wire. http2 should not be allowed in the TLSConfig.NextProtos, // so we explicitly set that here. We only do this check if the TLSConfig support http/1.1. if supportsHTTP11(tlsConfig.NextProtos) { tlsConfig = tlsConfig.Clone() tlsConfig.NextProtos = []string{"http/1.1"} } tlsConn := tls.Client(netConn, tlsConfig) if err := tlsConn.HandshakeContext(ctx); err != nil { netConn.Close() return nil, err } return tlsConn, nil } else { // Dial. tlsDialer := tls.Dialer{ Config: tlsConfig, } return tlsDialer.DialContext(ctx, "tcp", dialAddr) } default: return nil, fmt.Errorf("unknown scheme: %s", url.Scheme) } } func supportsHTTP11(nextProtos []string) bool { if len(nextProtos) == 0 { return true } for _, proto := range nextProtos { if proto == "http/1.1" { return true } } return false }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/apimachinery/pkg/util/cache/lruexpirecache.go
vendor/k8s.io/apimachinery/pkg/util/cache/lruexpirecache.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 cache import ( "container/list" "sync" "time" ) // Clock defines an interface for obtaining the current time type Clock interface { Now() time.Time } // realClock implements the Clock interface by calling time.Now() type realClock struct{} func (realClock) Now() time.Time { return time.Now() } // LRUExpireCache is a cache that ensures the mostly recently accessed keys are returned with // a ttl beyond which keys are forcibly expired. type LRUExpireCache struct { // clock is used to obtain the current time clock Clock lock sync.Mutex maxSize int evictionList list.List entries map[interface{}]*list.Element } // NewLRUExpireCache creates an expiring cache with the given size func NewLRUExpireCache(maxSize int) *LRUExpireCache { return NewLRUExpireCacheWithClock(maxSize, realClock{}) } // NewLRUExpireCacheWithClock creates an expiring cache with the given size, using the specified clock to obtain the current time. func NewLRUExpireCacheWithClock(maxSize int, clock Clock) *LRUExpireCache { if maxSize <= 0 { panic("maxSize must be > 0") } return &LRUExpireCache{ clock: clock, maxSize: maxSize, entries: map[interface{}]*list.Element{}, } } type cacheEntry struct { key interface{} value interface{} expireTime time.Time } // Add adds the value to the cache at key with the specified maximum duration. func (c *LRUExpireCache) Add(key interface{}, value interface{}, ttl time.Duration) { c.lock.Lock() defer c.lock.Unlock() // Key already exists oldElement, ok := c.entries[key] if ok { c.evictionList.MoveToFront(oldElement) oldElement.Value.(*cacheEntry).value = value oldElement.Value.(*cacheEntry).expireTime = c.clock.Now().Add(ttl) return } // Make space if necessary if c.evictionList.Len() >= c.maxSize { toEvict := c.evictionList.Back() c.evictionList.Remove(toEvict) delete(c.entries, toEvict.Value.(*cacheEntry).key) } // Add new entry entry := &cacheEntry{ key: key, value: value, expireTime: c.clock.Now().Add(ttl), } element := c.evictionList.PushFront(entry) c.entries[key] = element } // Get returns the value at the specified key from the cache if it exists and is not // expired, or returns false. func (c *LRUExpireCache) Get(key interface{}) (interface{}, bool) { c.lock.Lock() defer c.lock.Unlock() element, ok := c.entries[key] if !ok { return nil, false } if c.clock.Now().After(element.Value.(*cacheEntry).expireTime) { c.evictionList.Remove(element) delete(c.entries, key) return nil, false } c.evictionList.MoveToFront(element) return element.Value.(*cacheEntry).value, true } // Remove removes the specified key from the cache if it exists func (c *LRUExpireCache) Remove(key interface{}) { c.lock.Lock() defer c.lock.Unlock() element, ok := c.entries[key] if !ok { return } c.evictionList.Remove(element) delete(c.entries, key) } // RemoveAll removes all keys that match predicate. func (c *LRUExpireCache) RemoveAll(predicate func(key any) bool) { c.lock.Lock() defer c.lock.Unlock() for key, element := range c.entries { if predicate(key) { c.evictionList.Remove(element) delete(c.entries, key) } } } // Keys returns all unexpired keys in the cache. // // Keep in mind that subsequent calls to Get() for any of the returned keys // might return "not found". // // Keys are returned ordered from least recently used to most recently used. func (c *LRUExpireCache) Keys() []interface{} { c.lock.Lock() defer c.lock.Unlock() now := c.clock.Now() val := make([]interface{}, 0, c.evictionList.Len()) for element := c.evictionList.Back(); element != nil; element = element.Prev() { // Only return unexpired keys if !now.After(element.Value.(*cacheEntry).expireTime) { val = append(val, element.Value.(*cacheEntry).key) } } return val }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/apimachinery/pkg/util/cache/expiring.go
vendor/k8s.io/apimachinery/pkg/util/cache/expiring.go
/* Copyright 2019 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cache import ( "container/heap" "sync" "time" "k8s.io/utils/clock" ) // NewExpiring returns an initialized expiring cache. func NewExpiring() *Expiring { return NewExpiringWithClock(clock.RealClock{}) } // NewExpiringWithClock is like NewExpiring but allows passing in a custom // clock for testing. func NewExpiringWithClock(clock clock.Clock) *Expiring { return &Expiring{ clock: clock, cache: make(map[interface{}]entry), } } // Expiring is a map whose entries expire after a per-entry timeout. type Expiring struct { // AllowExpiredGet causes the expiration check to be skipped on Get. // It should only be used when a key always corresponds to the exact same value. // Thus when this field is true, expired keys are considered valid // until the next call to Set (which causes the GC to run). // It may not be changed concurrently with calls to Get. AllowExpiredGet bool clock clock.Clock // mu protects the below fields mu sync.RWMutex // cache is the internal map that backs the cache. cache map[interface{}]entry // generation is used as a cheap resource version for cache entries. Cleanups // are scheduled with a key and generation. When the cleanup runs, it first // compares its generation with the current generation of the entry. It // deletes the entry iff the generation matches. This prevents cleanups // scheduled for earlier versions of an entry from deleting later versions of // an entry when Set() is called multiple times with the same key. // // The integer value of the generation of an entry is meaningless. generation uint64 heap expiringHeap } type entry struct { val interface{} expiry time.Time generation uint64 } // Get looks up an entry in the cache. func (c *Expiring) Get(key interface{}) (val interface{}, ok bool) { c.mu.RLock() defer c.mu.RUnlock() e, ok := c.cache[key] if !ok { return nil, false } if !c.AllowExpiredGet && !c.clock.Now().Before(e.expiry) { return nil, false } return e.val, true } // Set sets a key/value/expiry entry in the map, overwriting any previous entry // with the same key. The entry expires at the given expiry time, but its TTL // may be lengthened or shortened by additional calls to Set(). Garbage // collection of expired entries occurs during calls to Set(), however calls to // Get() will not return expired entries that have not yet been garbage // collected. func (c *Expiring) Set(key interface{}, val interface{}, ttl time.Duration) { now := c.clock.Now() expiry := now.Add(ttl) c.mu.Lock() defer c.mu.Unlock() c.generation++ c.cache[key] = entry{ val: val, expiry: expiry, generation: c.generation, } // Run GC inline before pushing the new entry. c.gc(now) heap.Push(&c.heap, &expiringHeapEntry{ key: key, expiry: expiry, generation: c.generation, }) } // Delete deletes an entry in the map. func (c *Expiring) Delete(key interface{}) { c.mu.Lock() defer c.mu.Unlock() c.del(key, 0) } // del deletes the entry for the given key. The generation argument is the // generation of the entry that should be deleted. If the generation has been // changed (e.g. if a set has occurred on an existing element but the old // cleanup still runs), this is a noop. If the generation argument is 0, the // entry's generation is ignored and the entry is deleted. // // del must be called under the write lock. func (c *Expiring) del(key interface{}, generation uint64) { e, ok := c.cache[key] if !ok { return } if generation != 0 && generation != e.generation { return } delete(c.cache, key) } // Len returns the number of items in the cache. func (c *Expiring) Len() int { c.mu.RLock() defer c.mu.RUnlock() return len(c.cache) } func (c *Expiring) gc(now time.Time) { for { // Return from gc if the heap is empty or the next element is not yet // expired. // // heap[0] is a peek at the next element in the heap, which is not obvious // from looking at the (*expiringHeap).Pop() implementation below. // heap.Pop() swaps the first entry with the last entry of the heap, then // calls (*expiringHeap).Pop() which returns the last element. if len(c.heap) == 0 || now.Before(c.heap[0].expiry) { return } cleanup := heap.Pop(&c.heap).(*expiringHeapEntry) c.del(cleanup.key, cleanup.generation) } } type expiringHeapEntry struct { key interface{} expiry time.Time generation uint64 } // expiringHeap is a min-heap ordered by expiration time of its entries. The // expiring cache uses this as a priority queue to efficiently organize entries // which will be garbage collected once they expire. type expiringHeap []*expiringHeapEntry var _ heap.Interface = &expiringHeap{} func (cq expiringHeap) Len() int { return len(cq) } func (cq expiringHeap) Less(i, j int) bool { return cq[i].expiry.Before(cq[j].expiry) } func (cq expiringHeap) Swap(i, j int) { cq[i], cq[j] = cq[j], cq[i] } func (cq *expiringHeap) Push(c interface{}) { *cq = append(*cq, c.(*expiringHeapEntry)) } func (cq *expiringHeap) Pop() interface{} { c := (*cq)[cq.Len()-1] *cq = (*cq)[:cq.Len()-1] return c }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/apimachinery/pkg/util/version/version.go
vendor/k8s.io/apimachinery/pkg/util/version/version.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 version import ( "bytes" "errors" "fmt" "regexp" "strconv" "strings" apimachineryversion "k8s.io/apimachinery/pkg/version" ) // Version is an opaque representation of a version number type Version struct { components []uint semver bool preRelease string buildMetadata string info apimachineryversion.Info } var ( // versionMatchRE splits a version string into numeric and "extra" parts versionMatchRE = regexp.MustCompile(`^\s*v?([0-9]+(?:\.[0-9]+)*)(.*)*$`) // extraMatchRE splits the "extra" part of versionMatchRE into semver pre-release and build metadata; it does not validate the "no leading zeroes" constraint for pre-release extraMatchRE = regexp.MustCompile(`^(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?\s*$`) ) func parse(str string, semver bool) (*Version, error) { parts := versionMatchRE.FindStringSubmatch(str) if parts == nil { return nil, fmt.Errorf("could not parse %q as version", str) } numbers, extra := parts[1], parts[2] components := strings.Split(numbers, ".") if (semver && len(components) != 3) || (!semver && len(components) < 2) { return nil, fmt.Errorf("illegal version string %q", str) } v := &Version{ components: make([]uint, len(components)), semver: semver, } for i, comp := range components { if (i == 0 || semver) && strings.HasPrefix(comp, "0") && comp != "0" { return nil, fmt.Errorf("illegal zero-prefixed version component %q in %q", comp, str) } num, err := strconv.ParseUint(comp, 10, 0) if err != nil { return nil, fmt.Errorf("illegal non-numeric version component %q in %q: %v", comp, str, err) } v.components[i] = uint(num) } if semver && extra != "" { extraParts := extraMatchRE.FindStringSubmatch(extra) if extraParts == nil { return nil, fmt.Errorf("could not parse pre-release/metadata (%s) in version %q", extra, str) } v.preRelease, v.buildMetadata = extraParts[1], extraParts[2] for _, comp := range strings.Split(v.preRelease, ".") { if _, err := strconv.ParseUint(comp, 10, 0); err == nil { if strings.HasPrefix(comp, "0") && comp != "0" { return nil, fmt.Errorf("illegal zero-prefixed version component %q in %q", comp, str) } } } } return v, nil } // HighestSupportedVersion returns the highest supported version // This function assumes that the highest supported version must be v1.x. func HighestSupportedVersion(versions []string) (*Version, error) { if len(versions) == 0 { return nil, errors.New("empty array for supported versions") } var ( highestSupportedVersion *Version theErr error ) for i := len(versions) - 1; i >= 0; i-- { currentHighestVer, err := ParseGeneric(versions[i]) if err != nil { theErr = err continue } if currentHighestVer.Major() > 1 { continue } if highestSupportedVersion == nil || highestSupportedVersion.LessThan(currentHighestVer) { highestSupportedVersion = currentHighestVer } } if highestSupportedVersion == nil { return nil, fmt.Errorf( "could not find a highest supported version from versions (%v) reported: %+v", versions, theErr) } if highestSupportedVersion.Major() != 1 { return nil, fmt.Errorf("highest supported version reported is %v, must be v1.x", highestSupportedVersion) } return highestSupportedVersion, nil } // ParseGeneric parses a "generic" version string. The version string must consist of two // or more dot-separated numeric fields (the first of which can't have leading zeroes), // followed by arbitrary uninterpreted data (which need not be separated from the final // numeric field by punctuation). For convenience, leading and trailing whitespace is // ignored, and the version can be preceded by the letter "v". See also ParseSemantic. func ParseGeneric(str string) (*Version, error) { return parse(str, false) } // MustParseGeneric is like ParseGeneric except that it panics on error func MustParseGeneric(str string) *Version { v, err := ParseGeneric(str) if err != nil { panic(err) } return v } // Parse tries to do ParseSemantic first to keep more information. // If ParseSemantic fails, it would just do ParseGeneric. func Parse(str string) (*Version, error) { v, err := parse(str, true) if err != nil { return parse(str, false) } return v, err } // MustParse is like Parse except that it panics on error func MustParse(str string) *Version { v, err := Parse(str) if err != nil { panic(err) } return v } // ParseMajorMinor parses a "generic" version string and returns a version with the major and minor version. func ParseMajorMinor(str string) (*Version, error) { v, err := ParseGeneric(str) if err != nil { return nil, err } return MajorMinor(v.Major(), v.Minor()), nil } // MustParseMajorMinor is like ParseMajorMinor except that it panics on error func MustParseMajorMinor(str string) *Version { v, err := ParseMajorMinor(str) if err != nil { panic(err) } return v } // ParseSemantic parses a version string that exactly obeys the syntax and semantics of // the "Semantic Versioning" specification (http://semver.org/) (although it ignores // leading and trailing whitespace, and allows the version to be preceded by "v"). For // version strings that are not guaranteed to obey the Semantic Versioning syntax, use // ParseGeneric. func ParseSemantic(str string) (*Version, error) { return parse(str, true) } // MustParseSemantic is like ParseSemantic except that it panics on error func MustParseSemantic(str string) *Version { v, err := ParseSemantic(str) if err != nil { panic(err) } return v } // MajorMinor returns a version with the provided major and minor version. func MajorMinor(major, minor uint) *Version { return &Version{components: []uint{major, minor}} } // Major returns the major release number func (v *Version) Major() uint { return v.components[0] } // Minor returns the minor release number func (v *Version) Minor() uint { return v.components[1] } // Patch returns the patch release number if v is a Semantic Version, or 0 func (v *Version) Patch() uint { if len(v.components) < 3 { return 0 } return v.components[2] } // BuildMetadata returns the build metadata, if v is a Semantic Version, or "" func (v *Version) BuildMetadata() string { return v.buildMetadata } // PreRelease returns the prerelease metadata, if v is a Semantic Version, or "" func (v *Version) PreRelease() string { return v.preRelease } // Components returns the version number components func (v *Version) Components() []uint { return v.components } // WithMajor returns copy of the version object with requested major number func (v *Version) WithMajor(major uint) *Version { result := *v result.components = []uint{major, v.Minor(), v.Patch()} return &result } // WithMinor returns copy of the version object with requested minor number func (v *Version) WithMinor(minor uint) *Version { result := *v result.components = []uint{v.Major(), minor, v.Patch()} return &result } // SubtractMinor returns the version with offset from the original minor, with the same major and no patch. // If -offset >= current minor, the minor would be 0. func (v *Version) OffsetMinor(offset int) *Version { var minor uint if offset >= 0 { minor = v.Minor() + uint(offset) } else { diff := uint(-offset) if diff < v.Minor() { minor = v.Minor() - diff } } return MajorMinor(v.Major(), minor) } // SubtractMinor returns the version diff minor versions back, with the same major and no patch. // If diff >= current minor, the minor would be 0. func (v *Version) SubtractMinor(diff uint) *Version { return v.OffsetMinor(-int(diff)) } // AddMinor returns the version diff minor versions forward, with the same major and no patch. func (v *Version) AddMinor(diff uint) *Version { return v.OffsetMinor(int(diff)) } // WithPatch returns copy of the version object with requested patch number func (v *Version) WithPatch(patch uint) *Version { result := *v result.components = []uint{v.Major(), v.Minor(), patch} return &result } // WithPreRelease returns copy of the version object with requested prerelease func (v *Version) WithPreRelease(preRelease string) *Version { if len(preRelease) == 0 { return v } result := *v result.components = []uint{v.Major(), v.Minor(), v.Patch()} result.preRelease = preRelease return &result } // WithBuildMetadata returns copy of the version object with requested buildMetadata func (v *Version) WithBuildMetadata(buildMetadata string) *Version { result := *v result.components = []uint{v.Major(), v.Minor(), v.Patch()} result.buildMetadata = buildMetadata return &result } // String converts a Version back to a string; note that for versions parsed with // ParseGeneric, this will not include the trailing uninterpreted portion of the version // number. func (v *Version) String() string { if v == nil { return "<nil>" } var buffer bytes.Buffer for i, comp := range v.components { if i > 0 { buffer.WriteString(".") } buffer.WriteString(fmt.Sprintf("%d", comp)) } if v.preRelease != "" { buffer.WriteString("-") buffer.WriteString(v.preRelease) } if v.buildMetadata != "" { buffer.WriteString("+") buffer.WriteString(v.buildMetadata) } return buffer.String() } // compareInternal returns -1 if v is less than other, 1 if it is greater than other, or 0 // if they are equal func (v *Version) compareInternal(other *Version) int { vLen := len(v.components) oLen := len(other.components) for i := 0; i < vLen && i < oLen; i++ { switch { case other.components[i] < v.components[i]: return 1 case other.components[i] > v.components[i]: return -1 } } // If components are common but one has more items and they are not zeros, it is bigger switch { case oLen < vLen && !onlyZeros(v.components[oLen:]): return 1 case oLen > vLen && !onlyZeros(other.components[vLen:]): return -1 } if !v.semver || !other.semver { return 0 } switch { case v.preRelease == "" && other.preRelease != "": return 1 case v.preRelease != "" && other.preRelease == "": return -1 case v.preRelease == other.preRelease: // includes case where both are "" return 0 } vPR := strings.Split(v.preRelease, ".") oPR := strings.Split(other.preRelease, ".") for i := 0; i < len(vPR) && i < len(oPR); i++ { vNum, err := strconv.ParseUint(vPR[i], 10, 0) if err == nil { oNum, err := strconv.ParseUint(oPR[i], 10, 0) if err == nil { switch { case oNum < vNum: return 1 case oNum > vNum: return -1 default: continue } } } if oPR[i] < vPR[i] { return 1 } else if oPR[i] > vPR[i] { return -1 } } switch { case len(oPR) < len(vPR): return 1 case len(oPR) > len(vPR): return -1 } return 0 } // returns false if array contain any non-zero element func onlyZeros(array []uint) bool { for _, num := range array { if num != 0 { return false } } return true } // EqualTo tests if a version is equal to a given version. func (v *Version) EqualTo(other *Version) bool { if v == nil { return other == nil } if other == nil { return false } return v.compareInternal(other) == 0 } // AtLeast tests if a version is at least equal to a given minimum version. If both // Versions are Semantic Versions, this will use the Semantic Version comparison // algorithm. Otherwise, it will compare only the numeric components, with non-present // components being considered "0" (ie, "1.4" is equal to "1.4.0"). func (v *Version) AtLeast(min *Version) bool { return v.compareInternal(min) != -1 } // LessThan tests if a version is less than a given version. (It is exactly the opposite // of AtLeast, for situations where asking "is v too old?" makes more sense than asking // "is v new enough?".) func (v *Version) LessThan(other *Version) bool { return v.compareInternal(other) == -1 } // GreaterThan tests if a version is greater than a given version. func (v *Version) GreaterThan(other *Version) bool { return v.compareInternal(other) == 1 } // Compare compares v against a version string (which will be parsed as either Semantic // or non-Semantic depending on v). On success it returns -1 if v is less than other, 1 if // it is greater than other, or 0 if they are equal. func (v *Version) Compare(other string) (int, error) { ov, err := parse(other, v.semver) if err != nil { return 0, err } return v.compareInternal(ov), nil } // WithInfo returns copy of the version object with requested info func (v *Version) WithInfo(info apimachineryversion.Info) *Version { result := *v result.info = info return &result } func (v *Version) Info() *apimachineryversion.Info { if v == nil { return nil } // in case info is empty, or the major and minor in info is different from the actual major and minor v.info.Major = itoa(v.Major()) v.info.Minor = itoa(v.Minor()) if v.info.GitVersion == "" { v.info.GitVersion = v.String() } return &v.info } func itoa(i uint) string { if i == 0 { return "" } return strconv.Itoa(int(i)) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/apimachinery/pkg/util/version/doc.go
vendor/k8s.io/apimachinery/pkg/util/version/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 version provides utilities for version number comparisons package version // import "k8s.io/apimachinery/pkg/util/version"
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/types.go
vendor/k8s.io/apimachinery/pkg/util/strategicpatch/types.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 strategicpatch import ( "errors" "strings" "k8s.io/apimachinery/pkg/util/mergepatch" openapi "k8s.io/kube-openapi/pkg/util/proto" ) const ( patchStrategyOpenapiextensionKey = "x-kubernetes-patch-strategy" patchMergeKeyOpenapiextensionKey = "x-kubernetes-patch-merge-key" ) type LookupPatchItem interface { openapi.SchemaVisitor Error() error Path() *openapi.Path } type kindItem struct { key string path *openapi.Path err error patchmeta PatchMeta subschema openapi.Schema hasVisitKind bool } func NewKindItem(key string, path *openapi.Path) *kindItem { return &kindItem{ key: key, path: path, } } var _ LookupPatchItem = &kindItem{} func (item *kindItem) Error() error { return item.err } func (item *kindItem) Path() *openapi.Path { return item.path } func (item *kindItem) VisitPrimitive(schema *openapi.Primitive) { item.err = errors.New("expected kind, but got primitive") } func (item *kindItem) VisitArray(schema *openapi.Array) { item.err = errors.New("expected kind, but got slice") } func (item *kindItem) VisitMap(schema *openapi.Map) { item.err = errors.New("expected kind, but got map") } func (item *kindItem) VisitReference(schema openapi.Reference) { if !item.hasVisitKind { schema.SubSchema().Accept(item) } } func (item *kindItem) VisitKind(schema *openapi.Kind) { subschema, ok := schema.Fields[item.key] if !ok { item.err = FieldNotFoundError{Path: schema.GetPath().String(), Field: item.key} return } mergeKey, patchStrategies, err := parsePatchMetadata(subschema.GetExtensions()) if err != nil { item.err = err return } item.patchmeta = PatchMeta{ patchStrategies: patchStrategies, patchMergeKey: mergeKey, } item.subschema = subschema } type sliceItem struct { key string path *openapi.Path err error patchmeta PatchMeta subschema openapi.Schema hasVisitKind bool } func NewSliceItem(key string, path *openapi.Path) *sliceItem { return &sliceItem{ key: key, path: path, } } var _ LookupPatchItem = &sliceItem{} func (item *sliceItem) Error() error { return item.err } func (item *sliceItem) Path() *openapi.Path { return item.path } func (item *sliceItem) VisitPrimitive(schema *openapi.Primitive) { item.err = errors.New("expected slice, but got primitive") } func (item *sliceItem) VisitArray(schema *openapi.Array) { if !item.hasVisitKind { item.err = errors.New("expected visit kind first, then visit array") } subschema := schema.SubType item.subschema = subschema } func (item *sliceItem) VisitMap(schema *openapi.Map) { item.err = errors.New("expected slice, but got map") } func (item *sliceItem) VisitReference(schema openapi.Reference) { if !item.hasVisitKind { schema.SubSchema().Accept(item) } else { item.subschema = schema.SubSchema() } } func (item *sliceItem) VisitKind(schema *openapi.Kind) { subschema, ok := schema.Fields[item.key] if !ok { item.err = FieldNotFoundError{Path: schema.GetPath().String(), Field: item.key} return } mergeKey, patchStrategies, err := parsePatchMetadata(subschema.GetExtensions()) if err != nil { item.err = err return } item.patchmeta = PatchMeta{ patchStrategies: patchStrategies, patchMergeKey: mergeKey, } item.hasVisitKind = true subschema.Accept(item) } func parsePatchMetadata(extensions map[string]interface{}) (string, []string, error) { ps, foundPS := extensions[patchStrategyOpenapiextensionKey] var patchStrategies []string var mergeKey, patchStrategy string var ok bool if foundPS { patchStrategy, ok = ps.(string) if ok { patchStrategies = strings.Split(patchStrategy, ",") } else { return "", nil, mergepatch.ErrBadArgType(patchStrategy, ps) } } mk, foundMK := extensions[patchMergeKeyOpenapiextensionKey] if foundMK { mergeKey, ok = mk.(string) if !ok { return "", nil, mergepatch.ErrBadArgType(mergeKey, mk) } } return mergeKey, patchStrategies, nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/errors.go
vendor/k8s.io/apimachinery/pkg/util/strategicpatch/errors.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 strategicpatch import ( "fmt" ) type LookupPatchMetaError struct { Path string Err error } func (e LookupPatchMetaError) Error() string { return fmt.Sprintf("LookupPatchMetaError(%s): %v", e.Path, e.Err) } type FieldNotFoundError struct { Path string Field string } func (e FieldNotFoundError) Error() string { return fmt.Sprintf("unable to find api field %q in %s", e.Field, e.Path) } type InvalidTypeError struct { Path string Expected string Actual string } func (e InvalidTypeError) Error() string { return fmt.Sprintf("invalid type for %s: got %q, expected %q", e.Path, e.Actual, e.Expected) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/meta.go
vendor/k8s.io/apimachinery/pkg/util/strategicpatch/meta.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 strategicpatch import ( "errors" "fmt" "reflect" "strings" "k8s.io/apimachinery/pkg/util/mergepatch" forkedjson "k8s.io/apimachinery/third_party/forked/golang/json" openapi "k8s.io/kube-openapi/pkg/util/proto" "k8s.io/kube-openapi/pkg/validation/spec" ) const patchMergeKey = "x-kubernetes-patch-merge-key" const patchStrategy = "x-kubernetes-patch-strategy" type PatchMeta struct { patchStrategies []string patchMergeKey string } func (pm *PatchMeta) GetPatchStrategies() []string { if pm.patchStrategies == nil { return []string{} } return pm.patchStrategies } func (pm *PatchMeta) SetPatchStrategies(ps []string) { pm.patchStrategies = ps } func (pm *PatchMeta) GetPatchMergeKey() string { return pm.patchMergeKey } func (pm *PatchMeta) SetPatchMergeKey(pmk string) { pm.patchMergeKey = pmk } type LookupPatchMeta interface { // LookupPatchMetadataForStruct gets subschema and the patch metadata (e.g. patch strategy and merge key) for map. LookupPatchMetadataForStruct(key string) (LookupPatchMeta, PatchMeta, error) // LookupPatchMetadataForSlice get subschema and the patch metadata for slice. LookupPatchMetadataForSlice(key string) (LookupPatchMeta, PatchMeta, error) // Get the type name of the field Name() string } type PatchMetaFromStruct struct { T reflect.Type } func NewPatchMetaFromStruct(dataStruct interface{}) (PatchMetaFromStruct, error) { t, err := getTagStructType(dataStruct) return PatchMetaFromStruct{T: t}, err } var _ LookupPatchMeta = PatchMetaFromStruct{} func (s PatchMetaFromStruct) LookupPatchMetadataForStruct(key string) (LookupPatchMeta, PatchMeta, error) { fieldType, fieldPatchStrategies, fieldPatchMergeKey, err := forkedjson.LookupPatchMetadataForStruct(s.T, key) if err != nil { return nil, PatchMeta{}, err } return PatchMetaFromStruct{T: fieldType}, PatchMeta{ patchStrategies: fieldPatchStrategies, patchMergeKey: fieldPatchMergeKey, }, nil } func (s PatchMetaFromStruct) LookupPatchMetadataForSlice(key string) (LookupPatchMeta, PatchMeta, error) { subschema, patchMeta, err := s.LookupPatchMetadataForStruct(key) if err != nil { return nil, PatchMeta{}, err } elemPatchMetaFromStruct := subschema.(PatchMetaFromStruct) t := elemPatchMetaFromStruct.T var elemType reflect.Type switch t.Kind() { // If t is an array or a slice, get the element type. // If element is still an array or a slice, return an error. // Otherwise, return element type. case reflect.Array, reflect.Slice: elemType = t.Elem() if elemType.Kind() == reflect.Array || elemType.Kind() == reflect.Slice { return nil, PatchMeta{}, errors.New("unexpected slice of slice") } // If t is an pointer, get the underlying element. // If the underlying element is neither an array nor a slice, the pointer is pointing to a slice, // e.g. https://github.com/kubernetes/kubernetes/blob/bc22e206c79282487ea0bf5696d5ccec7e839a76/staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/patch_test.go#L2782-L2822 // If the underlying element is either an array or a slice, return its element type. case reflect.Pointer: t = t.Elem() if t.Kind() == reflect.Array || t.Kind() == reflect.Slice { t = t.Elem() } elemType = t default: return nil, PatchMeta{}, fmt.Errorf("expected slice or array type, but got: %s", s.T.Kind().String()) } return PatchMetaFromStruct{T: elemType}, patchMeta, nil } func (s PatchMetaFromStruct) Name() string { return s.T.Kind().String() } func getTagStructType(dataStruct interface{}) (reflect.Type, error) { if dataStruct == nil { return nil, mergepatch.ErrBadArgKind(struct{}{}, nil) } t := reflect.TypeOf(dataStruct) // Get the underlying type for pointers if t.Kind() == reflect.Pointer { t = t.Elem() } if t.Kind() != reflect.Struct { return nil, mergepatch.ErrBadArgKind(struct{}{}, dataStruct) } return t, nil } func GetTagStructTypeOrDie(dataStruct interface{}) reflect.Type { t, err := getTagStructType(dataStruct) if err != nil { panic(err) } return t } type PatchMetaFromOpenAPIV3 struct { // SchemaList is required to resolve OpenAPI V3 references SchemaList map[string]*spec.Schema Schema *spec.Schema } func (s PatchMetaFromOpenAPIV3) traverse(key string) (PatchMetaFromOpenAPIV3, error) { if s.Schema == nil { return PatchMetaFromOpenAPIV3{}, nil } if len(s.Schema.Properties) == 0 { return PatchMetaFromOpenAPIV3{}, fmt.Errorf("unable to find api field \"%s\"", key) } subschema, ok := s.Schema.Properties[key] if !ok { return PatchMetaFromOpenAPIV3{}, fmt.Errorf("unable to find api field \"%s\"", key) } return PatchMetaFromOpenAPIV3{SchemaList: s.SchemaList, Schema: &subschema}, nil } func resolve(l *PatchMetaFromOpenAPIV3) error { if len(l.Schema.AllOf) > 0 { l.Schema = &l.Schema.AllOf[0] } if refString := l.Schema.Ref.String(); refString != "" { str := strings.TrimPrefix(refString, "#/components/schemas/") sch, ok := l.SchemaList[str] if ok { l.Schema = sch } else { return fmt.Errorf("unable to resolve %s in OpenAPI V3", refString) } } return nil } func (s PatchMetaFromOpenAPIV3) LookupPatchMetadataForStruct(key string) (LookupPatchMeta, PatchMeta, error) { l, err := s.traverse(key) if err != nil { return l, PatchMeta{}, err } p := PatchMeta{} f, ok := l.Schema.Extensions[patchMergeKey] if ok { p.SetPatchMergeKey(f.(string)) } g, ok := l.Schema.Extensions[patchStrategy] if ok { p.SetPatchStrategies(strings.Split(g.(string), ",")) } err = resolve(&l) return l, p, err } func (s PatchMetaFromOpenAPIV3) LookupPatchMetadataForSlice(key string) (LookupPatchMeta, PatchMeta, error) { l, err := s.traverse(key) if err != nil { return l, PatchMeta{}, err } p := PatchMeta{} f, ok := l.Schema.Extensions[patchMergeKey] if ok { p.SetPatchMergeKey(f.(string)) } g, ok := l.Schema.Extensions[patchStrategy] if ok { p.SetPatchStrategies(strings.Split(g.(string), ",")) } if l.Schema.Items != nil { l.Schema = l.Schema.Items.Schema } err = resolve(&l) return l, p, err } func (s PatchMetaFromOpenAPIV3) Name() string { schema := s.Schema if len(schema.Type) > 0 { return strings.Join(schema.Type, "") } return "Struct" } type PatchMetaFromOpenAPI struct { Schema openapi.Schema } func NewPatchMetaFromOpenAPI(s openapi.Schema) PatchMetaFromOpenAPI { return PatchMetaFromOpenAPI{Schema: s} } var _ LookupPatchMeta = PatchMetaFromOpenAPI{} func (s PatchMetaFromOpenAPI) LookupPatchMetadataForStruct(key string) (LookupPatchMeta, PatchMeta, error) { if s.Schema == nil { return nil, PatchMeta{}, nil } kindItem := NewKindItem(key, s.Schema.GetPath()) s.Schema.Accept(kindItem) err := kindItem.Error() if err != nil { return nil, PatchMeta{}, err } return PatchMetaFromOpenAPI{Schema: kindItem.subschema}, kindItem.patchmeta, nil } func (s PatchMetaFromOpenAPI) LookupPatchMetadataForSlice(key string) (LookupPatchMeta, PatchMeta, error) { if s.Schema == nil { return nil, PatchMeta{}, nil } sliceItem := NewSliceItem(key, s.Schema.GetPath()) s.Schema.Accept(sliceItem) err := sliceItem.Error() if err != nil { return nil, PatchMeta{}, err } return PatchMetaFromOpenAPI{Schema: sliceItem.subschema}, sliceItem.patchmeta, nil } func (s PatchMetaFromOpenAPI) Name() string { schema := s.Schema return schema.GetName() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go
vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go
/* Copyright 2014 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 strategicpatch import ( "fmt" "reflect" "sort" "strings" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/util/json" "k8s.io/apimachinery/pkg/util/mergepatch" ) // An alternate implementation of JSON Merge Patch // (https://tools.ietf.org/html/rfc7386) which supports the ability to annotate // certain fields with metadata that indicates whether the elements of JSON // lists should be merged or replaced. // // For more information, see the PATCH section of docs/devel/api-conventions.md. // // Some of the content of this package was borrowed with minor adaptations from // evanphx/json-patch and openshift/origin. const ( directiveMarker = "$patch" deleteDirective = "delete" replaceDirective = "replace" mergeDirective = "merge" retainKeysStrategy = "retainKeys" deleteFromPrimitiveListDirectivePrefix = "$deleteFromPrimitiveList" retainKeysDirective = "$" + retainKeysStrategy setElementOrderDirectivePrefix = "$setElementOrder" ) // JSONMap is a representations of JSON object encoded as map[string]interface{} // where the children can be either map[string]interface{}, []interface{} or // primitive type). // Operating on JSONMap representation is much faster as it doesn't require any // json marshaling and/or unmarshaling operations. type JSONMap map[string]interface{} type DiffOptions struct { // SetElementOrder determines whether we generate the $setElementOrder parallel list. SetElementOrder bool // IgnoreChangesAndAdditions indicates if we keep the changes and additions in the patch. IgnoreChangesAndAdditions bool // IgnoreDeletions indicates if we keep the deletions in the patch. IgnoreDeletions bool // We introduce a new value retainKeys for patchStrategy. // It indicates that all fields needing to be preserved must be // present in the `retainKeys` list. // And the fields that are present will be merged with live object. // All the missing fields will be cleared when patching. BuildRetainKeysDirective bool } type MergeOptions struct { // MergeParallelList indicates if we are merging the parallel list. // We don't merge parallel list when calling mergeMap() in CreateThreeWayMergePatch() // which is called client-side. // We merge parallel list iff when calling mergeMap() in StrategicMergeMapPatch() // which is called server-side MergeParallelList bool // IgnoreUnmatchedNulls indicates if we should process the unmatched nulls. IgnoreUnmatchedNulls bool } // The following code is adapted from github.com/openshift/origin/pkg/util/jsonmerge. // Instead of defining a Delta that holds an original, a patch and a set of preconditions, // the reconcile method accepts a set of preconditions as an argument. // CreateTwoWayMergePatch creates a patch that can be passed to StrategicMergePatch from an original // document and a modified document, which are passed to the method as json encoded content. It will // return a patch that yields the modified document when applied to the original document, or an error // if either of the two documents is invalid. func CreateTwoWayMergePatch(original, modified []byte, dataStruct interface{}, fns ...mergepatch.PreconditionFunc) ([]byte, error) { schema, err := NewPatchMetaFromStruct(dataStruct) if err != nil { return nil, err } return CreateTwoWayMergePatchUsingLookupPatchMeta(original, modified, schema, fns...) } func CreateTwoWayMergePatchUsingLookupPatchMeta( original, modified []byte, schema LookupPatchMeta, fns ...mergepatch.PreconditionFunc) ([]byte, error) { originalMap := map[string]interface{}{} if len(original) > 0 { if err := json.Unmarshal(original, &originalMap); err != nil { return nil, mergepatch.ErrBadJSONDoc } } modifiedMap := map[string]interface{}{} if len(modified) > 0 { if err := json.Unmarshal(modified, &modifiedMap); err != nil { return nil, mergepatch.ErrBadJSONDoc } } patchMap, err := CreateTwoWayMergeMapPatchUsingLookupPatchMeta(originalMap, modifiedMap, schema, fns...) if err != nil { return nil, err } return json.Marshal(patchMap) } // CreateTwoWayMergeMapPatch creates a patch from an original and modified JSON objects, // encoded JSONMap. // The serialized version of the map can then be passed to StrategicMergeMapPatch. func CreateTwoWayMergeMapPatch(original, modified JSONMap, dataStruct interface{}, fns ...mergepatch.PreconditionFunc) (JSONMap, error) { schema, err := NewPatchMetaFromStruct(dataStruct) if err != nil { return nil, err } return CreateTwoWayMergeMapPatchUsingLookupPatchMeta(original, modified, schema, fns...) } func CreateTwoWayMergeMapPatchUsingLookupPatchMeta(original, modified JSONMap, schema LookupPatchMeta, fns ...mergepatch.PreconditionFunc) (JSONMap, error) { diffOptions := DiffOptions{ SetElementOrder: true, } patchMap, err := diffMaps(original, modified, schema, diffOptions) if err != nil { return nil, err } // Apply the preconditions to the patch, and return an error if any of them fail. for _, fn := range fns { if !fn(patchMap) { return nil, mergepatch.NewErrPreconditionFailed(patchMap) } } return patchMap, nil } // Returns a (recursive) strategic merge patch that yields modified when applied to original. // Including: // - Adding fields to the patch present in modified, missing from original // - Setting fields to the patch present in modified and original with different values // - Delete fields present in original, missing from modified through // - IFF map field - set to nil in patch // - IFF list of maps && merge strategy - use deleteDirective for the elements // - IFF list of primitives && merge strategy - use parallel deletion list // - IFF list of maps or primitives with replace strategy (default) - set patch value to the value in modified // - Build $retainKeys directive for fields with retainKeys patch strategy func diffMaps(original, modified map[string]interface{}, schema LookupPatchMeta, diffOptions DiffOptions) (map[string]interface{}, error) { patch := map[string]interface{}{} // This will be used to build the $retainKeys directive sent in the patch retainKeysList := make([]interface{}, 0, len(modified)) // Compare each value in the modified map against the value in the original map for key, modifiedValue := range modified { // Get the underlying type for pointers if diffOptions.BuildRetainKeysDirective && modifiedValue != nil { retainKeysList = append(retainKeysList, key) } originalValue, ok := original[key] if !ok { // Key was added, so add to patch if !diffOptions.IgnoreChangesAndAdditions { patch[key] = modifiedValue } continue } // The patch may have a patch directive // TODO: figure out if we need this. This shouldn't be needed by apply. When would the original map have patch directives in it? foundDirectiveMarker, err := handleDirectiveMarker(key, originalValue, modifiedValue, patch) if err != nil { return nil, err } if foundDirectiveMarker { continue } if reflect.TypeOf(originalValue) != reflect.TypeOf(modifiedValue) { // Types have changed, so add to patch if !diffOptions.IgnoreChangesAndAdditions { patch[key] = modifiedValue } continue } // Types are the same, so compare values switch originalValueTyped := originalValue.(type) { case map[string]interface{}: modifiedValueTyped := modifiedValue.(map[string]interface{}) err = handleMapDiff(key, originalValueTyped, modifiedValueTyped, patch, schema, diffOptions) case []interface{}: modifiedValueTyped := modifiedValue.([]interface{}) err = handleSliceDiff(key, originalValueTyped, modifiedValueTyped, patch, schema, diffOptions) default: replacePatchFieldIfNotEqual(key, originalValue, modifiedValue, patch, diffOptions) } if err != nil { return nil, err } } updatePatchIfMissing(original, modified, patch, diffOptions) // Insert the retainKeysList iff there are values present in the retainKeysList and // either of the following is true: // - the patch is not empty // - there are additional field in original that need to be cleared if len(retainKeysList) > 0 && (len(patch) > 0 || hasAdditionalNewField(original, modified)) { patch[retainKeysDirective] = sortScalars(retainKeysList) } return patch, nil } // handleDirectiveMarker handles how to diff directive marker between 2 objects func handleDirectiveMarker(key string, originalValue, modifiedValue interface{}, patch map[string]interface{}) (bool, error) { if key == directiveMarker { originalString, ok := originalValue.(string) if !ok { return false, fmt.Errorf("invalid value for special key: %s", directiveMarker) } modifiedString, ok := modifiedValue.(string) if !ok { return false, fmt.Errorf("invalid value for special key: %s", directiveMarker) } if modifiedString != originalString { patch[directiveMarker] = modifiedValue } return true, nil } return false, nil } // handleMapDiff diff between 2 maps `originalValueTyped` and `modifiedValue`, // puts the diff in the `patch` associated with `key` // key is the key associated with originalValue and modifiedValue. // originalValue, modifiedValue are the old and new value respectively.They are both maps // patch is the patch map that contains key and the updated value, and it is the parent of originalValue, modifiedValue // diffOptions contains multiple options to control how we do the diff. func handleMapDiff(key string, originalValue, modifiedValue, patch map[string]interface{}, schema LookupPatchMeta, diffOptions DiffOptions) error { subschema, patchMeta, err := schema.LookupPatchMetadataForStruct(key) if err != nil { // We couldn't look up metadata for the field // If the values are identical, this doesn't matter, no patch is needed if reflect.DeepEqual(originalValue, modifiedValue) { return nil } // Otherwise, return the error return err } retainKeys, patchStrategy, err := extractRetainKeysPatchStrategy(patchMeta.GetPatchStrategies()) if err != nil { return err } diffOptions.BuildRetainKeysDirective = retainKeys switch patchStrategy { // The patch strategic from metadata tells us to replace the entire object instead of diffing it case replaceDirective: if !diffOptions.IgnoreChangesAndAdditions { patch[key] = modifiedValue } default: patchValue, err := diffMaps(originalValue, modifiedValue, subschema, diffOptions) if err != nil { return err } // Maps were not identical, use provided patch value if len(patchValue) > 0 { patch[key] = patchValue } } return nil } // handleSliceDiff diff between 2 slices `originalValueTyped` and `modifiedValue`, // puts the diff in the `patch` associated with `key` // key is the key associated with originalValue and modifiedValue. // originalValue, modifiedValue are the old and new value respectively.They are both slices // patch is the patch map that contains key and the updated value, and it is the parent of originalValue, modifiedValue // diffOptions contains multiple options to control how we do the diff. func handleSliceDiff(key string, originalValue, modifiedValue []interface{}, patch map[string]interface{}, schema LookupPatchMeta, diffOptions DiffOptions) error { subschema, patchMeta, err := schema.LookupPatchMetadataForSlice(key) if err != nil { // We couldn't look up metadata for the field // If the values are identical, this doesn't matter, no patch is needed if reflect.DeepEqual(originalValue, modifiedValue) { return nil } // Otherwise, return the error return err } retainKeys, patchStrategy, err := extractRetainKeysPatchStrategy(patchMeta.GetPatchStrategies()) if err != nil { return err } switch patchStrategy { // Merge the 2 slices using mergePatchKey case mergeDirective: diffOptions.BuildRetainKeysDirective = retainKeys addList, deletionList, setOrderList, err := diffLists(originalValue, modifiedValue, subschema, patchMeta.GetPatchMergeKey(), diffOptions) if err != nil { return err } if len(addList) > 0 { patch[key] = addList } // generate a parallel list for deletion if len(deletionList) > 0 { parallelDeletionListKey := fmt.Sprintf("%s/%s", deleteFromPrimitiveListDirectivePrefix, key) patch[parallelDeletionListKey] = deletionList } if len(setOrderList) > 0 { parallelSetOrderListKey := fmt.Sprintf("%s/%s", setElementOrderDirectivePrefix, key) patch[parallelSetOrderListKey] = setOrderList } default: replacePatchFieldIfNotEqual(key, originalValue, modifiedValue, patch, diffOptions) } return nil } // replacePatchFieldIfNotEqual updates the patch if original and modified are not deep equal // if diffOptions.IgnoreChangesAndAdditions is false. // original is the old value, maybe either the live cluster object or the last applied configuration // modified is the new value, is always the users new config func replacePatchFieldIfNotEqual(key string, original, modified interface{}, patch map[string]interface{}, diffOptions DiffOptions) { if diffOptions.IgnoreChangesAndAdditions { // Ignoring changes - do nothing return } if reflect.DeepEqual(original, modified) { // Contents are identical - do nothing return } // Create a patch to replace the old value with the new one patch[key] = modified } // updatePatchIfMissing iterates over `original` when ignoreDeletions is false. // Clear the field whose key is not present in `modified`. // original is the old value, maybe either the live cluster object or the last applied configuration // modified is the new value, is always the users new config func updatePatchIfMissing(original, modified, patch map[string]interface{}, diffOptions DiffOptions) { if diffOptions.IgnoreDeletions { // Ignoring deletion - do nothing return } // Add nils for deleted values for key := range original { if _, found := modified[key]; !found { patch[key] = nil } } } // validateMergeKeyInLists checks if each map in the list has the mentryerge key. func validateMergeKeyInLists(mergeKey string, lists ...[]interface{}) error { for _, list := range lists { for _, item := range list { m, ok := item.(map[string]interface{}) if !ok { return mergepatch.ErrBadArgType(m, item) } if _, ok = m[mergeKey]; !ok { return mergepatch.ErrNoMergeKey(m, mergeKey) } } } return nil } // normalizeElementOrder sort `patch` list by `patchOrder` and sort `serverOnly` list by `serverOrder`. // Then it merges the 2 sorted lists. // It guarantee the relative order in the patch list and in the serverOnly list is kept. // `patch` is a list of items in the patch, and `serverOnly` is a list of items in the live object. // `patchOrder` is the order we want `patch` list to have and // `serverOrder` is the order we want `serverOnly` list to have. // kind is the kind of each item in the lists `patch` and `serverOnly`. func normalizeElementOrder(patch, serverOnly, patchOrder, serverOrder []interface{}, mergeKey string, kind reflect.Kind) ([]interface{}, error) { patch, err := normalizeSliceOrder(patch, patchOrder, mergeKey, kind) if err != nil { return nil, err } serverOnly, err = normalizeSliceOrder(serverOnly, serverOrder, mergeKey, kind) if err != nil { return nil, err } all := mergeSortedSlice(serverOnly, patch, serverOrder, mergeKey, kind) return all, nil } // mergeSortedSlice merges the 2 sorted lists by serverOrder with best effort. // It will insert each item in `left` list to `right` list. In most cases, the 2 lists will be interleaved. // The relative order of left and right are guaranteed to be kept. // They have higher precedence than the order in the live list. // The place for a item in `left` is found by: // scan from the place of last insertion in `right` to the end of `right`, // the place is before the first item that is greater than the item we want to insert. // example usage: using server-only items as left and patch items as right. We insert server-only items // to patch list. We use the order of live object as record for comparison. func mergeSortedSlice(left, right, serverOrder []interface{}, mergeKey string, kind reflect.Kind) []interface{} { // Returns if l is less than r, and if both have been found. // If l and r both present and l is in front of r, l is less than r. less := func(l, r interface{}) (bool, bool) { li := index(serverOrder, l, mergeKey, kind) ri := index(serverOrder, r, mergeKey, kind) if li >= 0 && ri >= 0 { return li < ri, true } else { return false, false } } // left and right should be non-overlapping. size := len(left) + len(right) i, j := 0, 0 s := make([]interface{}, size, size) for k := 0; k < size; k++ { if i >= len(left) && j < len(right) { // have items left in `right` list s[k] = right[j] j++ } else if j >= len(right) && i < len(left) { // have items left in `left` list s[k] = left[i] i++ } else { // compare them if i and j are both in bound less, foundBoth := less(left[i], right[j]) if foundBoth && less { s[k] = left[i] i++ } else { s[k] = right[j] j++ } } } return s } // index returns the index of the item in the given items, or -1 if it doesn't exist // l must NOT be a slice of slices, this should be checked before calling. func index(l []interface{}, valToLookUp interface{}, mergeKey string, kind reflect.Kind) int { var getValFn func(interface{}) interface{} // Get the correct `getValFn` based on item `kind`. // It should return the value of merge key for maps and // return the item for other kinds. switch kind { case reflect.Map: getValFn = func(item interface{}) interface{} { typedItem, ok := item.(map[string]interface{}) if !ok { return nil } val := typedItem[mergeKey] return val } default: getValFn = func(item interface{}) interface{} { return item } } for i, v := range l { if getValFn(valToLookUp) == getValFn(v) { return i } } return -1 } // extractToDeleteItems takes a list and // returns 2 lists: one contains items that should be kept and the other contains items to be deleted. func extractToDeleteItems(l []interface{}) ([]interface{}, []interface{}, error) { var nonDelete, toDelete []interface{} for _, v := range l { m, ok := v.(map[string]interface{}) if !ok { return nil, nil, mergepatch.ErrBadArgType(m, v) } directive, foundDirective := m[directiveMarker] if foundDirective && directive == deleteDirective { toDelete = append(toDelete, v) } else { nonDelete = append(nonDelete, v) } } return nonDelete, toDelete, nil } // normalizeSliceOrder sort `toSort` list by `order` func normalizeSliceOrder(toSort, order []interface{}, mergeKey string, kind reflect.Kind) ([]interface{}, error) { var toDelete []interface{} if kind == reflect.Map { // make sure each item in toSort, order has merge key err := validateMergeKeyInLists(mergeKey, toSort, order) if err != nil { return nil, err } toSort, toDelete, err = extractToDeleteItems(toSort) if err != nil { return nil, err } } sort.SliceStable(toSort, func(i, j int) bool { if ii := index(order, toSort[i], mergeKey, kind); ii >= 0 { if ij := index(order, toSort[j], mergeKey, kind); ij >= 0 { return ii < ij } } return true }) toSort = append(toSort, toDelete...) return toSort, nil } // Returns a (recursive) strategic merge patch, a parallel deletion list if necessary and // another list to set the order of the list // Only list of primitives with merge strategy will generate a parallel deletion list. // These two lists should yield modified when applied to original, for lists with merge semantics. func diffLists(original, modified []interface{}, schema LookupPatchMeta, mergeKey string, diffOptions DiffOptions) ([]interface{}, []interface{}, []interface{}, error) { if len(original) == 0 { // Both slices are empty - do nothing if len(modified) == 0 || diffOptions.IgnoreChangesAndAdditions { return nil, nil, nil, nil } // Old slice was empty - add all elements from the new slice return modified, nil, nil, nil } elementType, err := sliceElementType(original, modified) if err != nil { return nil, nil, nil, err } var patchList, deleteList, setOrderList []interface{} kind := elementType.Kind() switch kind { case reflect.Map: patchList, deleteList, err = diffListsOfMaps(original, modified, schema, mergeKey, diffOptions) if err != nil { return nil, nil, nil, err } patchList, err = normalizeSliceOrder(patchList, modified, mergeKey, kind) if err != nil { return nil, nil, nil, err } orderSame, err := isOrderSame(original, modified, mergeKey) if err != nil { return nil, nil, nil, err } // append the deletions to the end of the patch list. patchList = append(patchList, deleteList...) deleteList = nil // generate the setElementOrder list when there are content changes or order changes if diffOptions.SetElementOrder && ((!diffOptions.IgnoreChangesAndAdditions && (len(patchList) > 0 || !orderSame)) || (!diffOptions.IgnoreDeletions && len(patchList) > 0)) { // Generate a list of maps that each item contains only the merge key. setOrderList = make([]interface{}, len(modified)) for i, v := range modified { typedV := v.(map[string]interface{}) setOrderList[i] = map[string]interface{}{ mergeKey: typedV[mergeKey], } } } case reflect.Slice: // Lists of Lists are not permitted by the api return nil, nil, nil, mergepatch.ErrNoListOfLists default: patchList, deleteList, err = diffListsOfScalars(original, modified, diffOptions) if err != nil { return nil, nil, nil, err } patchList, err = normalizeSliceOrder(patchList, modified, mergeKey, kind) // generate the setElementOrder list when there are content changes or order changes if diffOptions.SetElementOrder && ((!diffOptions.IgnoreDeletions && len(deleteList) > 0) || (!diffOptions.IgnoreChangesAndAdditions && !reflect.DeepEqual(original, modified))) { setOrderList = modified } } return patchList, deleteList, setOrderList, err } // isOrderSame checks if the order in a list has changed func isOrderSame(original, modified []interface{}, mergeKey string) (bool, error) { if len(original) != len(modified) { return false, nil } for i, modifiedItem := range modified { equal, err := mergeKeyValueEqual(original[i], modifiedItem, mergeKey) if err != nil || !equal { return equal, err } } return true, nil } // diffListsOfScalars returns 2 lists, the first one is addList and the second one is deletionList. // Argument diffOptions.IgnoreChangesAndAdditions controls if calculate addList. true means not calculate. // Argument diffOptions.IgnoreDeletions controls if calculate deletionList. true means not calculate. // original may be changed, but modified is guaranteed to not be changed func diffListsOfScalars(original, modified []interface{}, diffOptions DiffOptions) ([]interface{}, []interface{}, error) { modifiedCopy := make([]interface{}, len(modified)) copy(modifiedCopy, modified) // Sort the scalars for easier calculating the diff originalScalars := sortScalars(original) modifiedScalars := sortScalars(modifiedCopy) originalIndex, modifiedIndex := 0, 0 addList := []interface{}{} deletionList := []interface{}{} for { originalInBounds := originalIndex < len(originalScalars) modifiedInBounds := modifiedIndex < len(modifiedScalars) if !originalInBounds && !modifiedInBounds { break } // we need to compare the string representation of the scalar, // because the scalar is an interface which doesn't support either < or > // And that's how func sortScalars compare scalars. var originalString, modifiedString string var originalValue, modifiedValue interface{} if originalInBounds { originalValue = originalScalars[originalIndex] originalString = fmt.Sprintf("%v", originalValue) } if modifiedInBounds { modifiedValue = modifiedScalars[modifiedIndex] modifiedString = fmt.Sprintf("%v", modifiedValue) } originalV, modifiedV := compareListValuesAtIndex(originalInBounds, modifiedInBounds, originalString, modifiedString) switch { case originalV == nil && modifiedV == nil: originalIndex++ modifiedIndex++ case originalV != nil && modifiedV == nil: if !diffOptions.IgnoreDeletions { deletionList = append(deletionList, originalValue) } originalIndex++ case originalV == nil && modifiedV != nil: if !diffOptions.IgnoreChangesAndAdditions { addList = append(addList, modifiedValue) } modifiedIndex++ default: return nil, nil, fmt.Errorf("Unexpected returned value from compareListValuesAtIndex: %v and %v", originalV, modifiedV) } } return addList, deduplicateScalars(deletionList), nil } // If first return value is non-nil, list1 contains an element not present in list2 // If second return value is non-nil, list2 contains an element not present in list1 func compareListValuesAtIndex(list1Inbounds, list2Inbounds bool, list1Value, list2Value string) (interface{}, interface{}) { bothInBounds := list1Inbounds && list2Inbounds switch { // scalars are identical case bothInBounds && list1Value == list2Value: return nil, nil // only list2 is in bound case !list1Inbounds: fallthrough // list2 has additional scalar case bothInBounds && list1Value > list2Value: return nil, list2Value // only original is in bound case !list2Inbounds: fallthrough // original has additional scalar case bothInBounds && list1Value < list2Value: return list1Value, nil default: return nil, nil } } // diffListsOfMaps takes a pair of lists and // returns a (recursive) strategic merge patch list contains additions and changes and // a deletion list contains deletions func diffListsOfMaps(original, modified []interface{}, schema LookupPatchMeta, mergeKey string, diffOptions DiffOptions) ([]interface{}, []interface{}, error) { patch := make([]interface{}, 0, len(modified)) deletionList := make([]interface{}, 0, len(original)) originalSorted, err := sortMergeListsByNameArray(original, schema, mergeKey, false) if err != nil { return nil, nil, err } modifiedSorted, err := sortMergeListsByNameArray(modified, schema, mergeKey, false) if err != nil { return nil, nil, err } originalIndex, modifiedIndex := 0, 0 for { originalInBounds := originalIndex < len(originalSorted) modifiedInBounds := modifiedIndex < len(modifiedSorted) bothInBounds := originalInBounds && modifiedInBounds if !originalInBounds && !modifiedInBounds { break } var originalElementMergeKeyValueString, modifiedElementMergeKeyValueString string var originalElementMergeKeyValue, modifiedElementMergeKeyValue interface{} var originalElement, modifiedElement map[string]interface{} if originalInBounds { originalElement, originalElementMergeKeyValue, err = getMapAndMergeKeyValueByIndex(originalIndex, mergeKey, originalSorted) if err != nil { return nil, nil, err } originalElementMergeKeyValueString = fmt.Sprintf("%v", originalElementMergeKeyValue) } if modifiedInBounds { modifiedElement, modifiedElementMergeKeyValue, err = getMapAndMergeKeyValueByIndex(modifiedIndex, mergeKey, modifiedSorted) if err != nil { return nil, nil, err } modifiedElementMergeKeyValueString = fmt.Sprintf("%v", modifiedElementMergeKeyValue) } switch { case bothInBounds && ItemMatchesOriginalAndModifiedSlice(originalElementMergeKeyValueString, modifiedElementMergeKeyValueString): // Merge key values are equal, so recurse patchValue, err := diffMaps(originalElement, modifiedElement, schema, diffOptions) if err != nil { return nil, nil, err } if len(patchValue) > 0 { patchValue[mergeKey] = modifiedElementMergeKeyValue patch = append(patch, patchValue) } originalIndex++ modifiedIndex++ // only modified is in bound case !originalInBounds: fallthrough // modified has additional map case bothInBounds && ItemAddedToModifiedSlice(originalElementMergeKeyValueString, modifiedElementMergeKeyValueString): if !diffOptions.IgnoreChangesAndAdditions { patch = append(patch, modifiedElement) } modifiedIndex++ // only original is in bound case !modifiedInBounds: fallthrough // original has additional map case bothInBounds && ItemRemovedFromModifiedSlice(originalElementMergeKeyValueString, modifiedElementMergeKeyValueString): if !diffOptions.IgnoreDeletions { // Item was deleted, so add delete directive deletionList = append(deletionList, CreateDeleteDirective(mergeKey, originalElementMergeKeyValue)) } originalIndex++ } } return patch, deletionList, nil } // getMapAndMergeKeyValueByIndex return a map in the list and its merge key value given the index of the map. func getMapAndMergeKeyValueByIndex(index int, mergeKey string, listOfMaps []interface{}) (map[string]interface{}, interface{}, error) { m, ok := listOfMaps[index].(map[string]interface{}) if !ok { return nil, nil, mergepatch.ErrBadArgType(m, listOfMaps[index]) } val, ok := m[mergeKey] if !ok { return nil, nil, mergepatch.ErrNoMergeKey(m, mergeKey) } return m, val, nil } // StrategicMergePatch applies a strategic merge patch. The patch and the original document // must be json encoded content. A patch can be created from an original and a modified document // by calling CreateStrategicMergePatch. func StrategicMergePatch(original, patch []byte, dataStruct interface{}) ([]byte, error) { schema, err := NewPatchMetaFromStruct(dataStruct) if err != nil { return nil, err } return StrategicMergePatchUsingLookupPatchMeta(original, patch, schema) } func StrategicMergePatchUsingLookupPatchMeta(original, patch []byte, schema LookupPatchMeta) ([]byte, error) { originalMap, err := handleUnmarshal(original) if err != nil { return nil, err } patchMap, err := handleUnmarshal(patch) if err != nil { return nil, err } result, err := StrategicMergeMapPatchUsingLookupPatchMeta(originalMap, patchMap, schema) if err != nil { return nil, err } return json.Marshal(result) } func handleUnmarshal(j []byte) (map[string]interface{}, error) { if j == nil { j = []byte("{}") } m := map[string]interface{}{} err := json.Unmarshal(j, &m) if err != nil { return nil, mergepatch.ErrBadJSONDoc } return m, nil } // StrategicMergeMapPatch applies a strategic merge patch. The original and patch documents // must be JSONMap. A patch can be created from an original and modified document by // calling CreateTwoWayMergeMapPatch. // Warning: the original and patch JSONMap objects are mutated by this function and should not be reused. func StrategicMergeMapPatch(original, patch JSONMap, dataStruct interface{}) (JSONMap, error) { schema, err := NewPatchMetaFromStruct(dataStruct) if err != nil { return nil, err } // We need the go struct tags `patchMergeKey` and `patchStrategy` for fields that support a strategic merge patch. // For native resources, we can easily figure out these tags since we know the fields. // Because custom resources are decoded as Unstructured and because we're missing the metadata about how to handle // each field in a strategic merge patch, we can't find the go struct tags. Hence, we can't easily do a strategic merge // for custom resources. So we should fail fast and return an error. if _, ok := dataStruct.(*unstructured.Unstructured); ok { return nil, mergepatch.ErrUnsupportedStrategicMergePatchFormat } return StrategicMergeMapPatchUsingLookupPatchMeta(original, patch, schema) } func StrategicMergeMapPatchUsingLookupPatchMeta(original, patch JSONMap, schema LookupPatchMeta) (JSONMap, error) { mergeOptions := MergeOptions{ MergeParallelList: true, IgnoreUnmatchedNulls: true, } return mergeMap(original, patch, schema, mergeOptions) } // MergeStrategicMergeMapPatchUsingLookupPatchMeta merges strategic merge // patches retaining `null` fields and parallel lists. If 2 patches change the // same fields and the latter one will override the former one. If you don't // want that happen, you need to run func MergingMapsHaveConflicts before
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
true
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/apimachinery/pkg/util/errors/errors.go
vendor/k8s.io/apimachinery/pkg/util/errors/errors.go
/* Copyright 2015 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 errors import ( "errors" "fmt" "k8s.io/apimachinery/pkg/util/sets" ) // MessageCountMap contains occurrence for each error message. type MessageCountMap map[string]int // Aggregate represents an object that contains multiple errors, but does not // necessarily have singular semantic meaning. // The aggregate can be used with `errors.Is()` to check for the occurrence of // a specific error type. // Errors.As() is not supported, because the caller presumably cares about a // specific error of potentially multiple that match the given type. type Aggregate interface { error Errors() []error Is(error) bool } // NewAggregate converts a slice of errors into an Aggregate interface, which // is itself an implementation of the error interface. If the slice is empty, // this returns nil. // It will check if any of the element of input error list is nil, to avoid // nil pointer panic when call Error(). func NewAggregate(errlist []error) Aggregate { if len(errlist) == 0 { return nil } // In case of input error list contains nil var errs []error for _, e := range errlist { if e != nil { errs = append(errs, e) } } if len(errs) == 0 { return nil } return aggregate(errs) } // This helper implements the error and Errors interfaces. Keeping it private // prevents people from making an aggregate of 0 errors, which is not // an error, but does satisfy the error interface. type aggregate []error // Error is part of the error interface. func (agg aggregate) Error() string { if len(agg) == 0 { // This should never happen, really. return "" } if len(agg) == 1 { return agg[0].Error() } seenerrs := sets.NewString() result := "" agg.visit(func(err error) bool { msg := err.Error() if seenerrs.Has(msg) { return false } seenerrs.Insert(msg) if len(seenerrs) > 1 { result += ", " } result += msg return false }) if len(seenerrs) == 1 { return result } return "[" + result + "]" } func (agg aggregate) Is(target error) bool { return agg.visit(func(err error) bool { return errors.Is(err, target) }) } func (agg aggregate) visit(f func(err error) bool) bool { for _, err := range agg { switch err := err.(type) { case aggregate: if match := err.visit(f); match { return match } case Aggregate: for _, nestedErr := range err.Errors() { if match := f(nestedErr); match { return match } } default: if match := f(err); match { return match } } } return false } // Errors is part of the Aggregate interface. func (agg aggregate) Errors() []error { return []error(agg) } // Matcher is used to match errors. Returns true if the error matches. type Matcher func(error) bool // FilterOut removes all errors that match any of the matchers from the input // error. If the input is a singular error, only that error is tested. If the // input implements the Aggregate interface, the list of errors will be // processed recursively. // // This can be used, for example, to remove known-OK errors (such as io.EOF or // os.PathNotFound) from a list of errors. func FilterOut(err error, fns ...Matcher) error { if err == nil { return nil } if agg, ok := err.(Aggregate); ok { return NewAggregate(filterErrors(agg.Errors(), fns...)) } if !matchesError(err, fns...) { return err } return nil } // matchesError returns true if any Matcher returns true func matchesError(err error, fns ...Matcher) bool { for _, fn := range fns { if fn(err) { return true } } return false } // filterErrors returns any errors (or nested errors, if the list contains // nested Errors) for which all fns return false. If no errors // remain a nil list is returned. The resulting slice will have all // nested slices flattened as a side effect. func filterErrors(list []error, fns ...Matcher) []error { result := []error{} for _, err := range list { r := FilterOut(err, fns...) if r != nil { result = append(result, r) } } return result } // Flatten takes an Aggregate, which may hold other Aggregates in arbitrary // nesting, and flattens them all into a single Aggregate, recursively. func Flatten(agg Aggregate) Aggregate { result := []error{} if agg == nil { return nil } for _, err := range agg.Errors() { if a, ok := err.(Aggregate); ok { r := Flatten(a) if r != nil { result = append(result, r.Errors()...) } } else { if err != nil { result = append(result, err) } } } return NewAggregate(result) } // CreateAggregateFromMessageCountMap converts MessageCountMap Aggregate func CreateAggregateFromMessageCountMap(m MessageCountMap) Aggregate { if m == nil { return nil } result := make([]error, 0, len(m)) for errStr, count := range m { var countStr string if count > 1 { countStr = fmt.Sprintf(" (repeated %v times)", count) } result = append(result, fmt.Errorf("%v%v", errStr, countStr)) } return NewAggregate(result) } // Reduce will return err or nil, if err is an Aggregate and only has one item, // the first item in the aggregate. func Reduce(err error) error { if agg, ok := err.(Aggregate); ok && err != nil { switch len(agg.Errors()) { case 1: return agg.Errors()[0] case 0: return nil } } return err } // AggregateGoroutines runs the provided functions in parallel, stuffing all // non-nil errors into the returned Aggregate. // Returns nil if all the functions complete successfully. func AggregateGoroutines(funcs ...func() error) Aggregate { errChan := make(chan error, len(funcs)) for _, f := range funcs { go func(f func() error) { errChan <- f() }(f) } errs := make([]error, 0) for i := 0; i < cap(errChan); i++ { if err := <-errChan; err != nil { errs = append(errs, err) } } return NewAggregate(errs) } // ErrPreconditionViolated is returned when the precondition is violated var ErrPreconditionViolated = errors.New("precondition is violated")
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/apimachinery/pkg/util/errors/doc.go
vendor/k8s.io/apimachinery/pkg/util/errors/doc.go
/* Copyright 2015 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 errors implements various utility functions and types around errors. package errors // import "k8s.io/apimachinery/pkg/util/errors"
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/apimachinery/pkg/util/json/json.go
vendor/k8s.io/apimachinery/pkg/util/json/json.go
/* Copyright 2015 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 json import ( "encoding/json" "fmt" "io" kjson "sigs.k8s.io/json" ) // NewEncoder delegates to json.NewEncoder // It is only here so this package can be a drop-in for common encoding/json uses func NewEncoder(w io.Writer) *json.Encoder { return json.NewEncoder(w) } // Marshal delegates to json.Marshal // It is only here so this package can be a drop-in for common encoding/json uses func Marshal(v interface{}) ([]byte, error) { return json.Marshal(v) } // limit recursive depth to prevent stack overflow errors const maxDepth = 10000 // Unmarshal unmarshals the given data. // Object keys are case-sensitive. // Numbers decoded into interface{} fields are converted to int64 or float64. func Unmarshal(data []byte, v interface{}) error { return kjson.UnmarshalCaseSensitivePreserveInts(data, v) } // ConvertInterfaceNumbers converts any json.Number values to int64 or float64. // Values which are map[string]interface{} or []interface{} are recursively visited func ConvertInterfaceNumbers(v *interface{}, depth int) error { var err error switch v2 := (*v).(type) { case json.Number: *v, err = convertNumber(v2) case map[string]interface{}: err = ConvertMapNumbers(v2, depth+1) case []interface{}: err = ConvertSliceNumbers(v2, depth+1) } return err } // ConvertMapNumbers traverses the map, converting any json.Number values to int64 or float64. // values which are map[string]interface{} or []interface{} are recursively visited func ConvertMapNumbers(m map[string]interface{}, depth int) error { if depth > maxDepth { return fmt.Errorf("exceeded max depth of %d", maxDepth) } var err error for k, v := range m { switch v := v.(type) { case json.Number: m[k], err = convertNumber(v) case map[string]interface{}: err = ConvertMapNumbers(v, depth+1) case []interface{}: err = ConvertSliceNumbers(v, depth+1) } if err != nil { return err } } return nil } // ConvertSliceNumbers traverses the slice, converting any json.Number values to int64 or float64. // values which are map[string]interface{} or []interface{} are recursively visited func ConvertSliceNumbers(s []interface{}, depth int) error { if depth > maxDepth { return fmt.Errorf("exceeded max depth of %d", maxDepth) } var err error for i, v := range s { switch v := v.(type) { case json.Number: s[i], err = convertNumber(v) case map[string]interface{}: err = ConvertMapNumbers(v, depth+1) case []interface{}: err = ConvertSliceNumbers(v, depth+1) } if err != nil { return err } } return nil } // convertNumber converts a json.Number to an int64 or float64, or returns an error func convertNumber(n json.Number) (interface{}, error) { // Attempt to convert to an int64 first if i, err := n.Int64(); err == nil { return i, nil } // Return a float64 (default json.Decode() behavior) // An overflow will return an error return n.Float64() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/k8s.io/apimachinery/pkg/util/runtime/runtime.go
vendor/k8s.io/apimachinery/pkg/util/runtime/runtime.go
/* Copyright 2014 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 runtime import ( "context" "fmt" "net/http" "runtime" "sync" "time" "k8s.io/klog/v2" ) var ( // ReallyCrash controls the behavior of HandleCrash and defaults to // true. It's exposed so components can optionally set to false // to restore prior behavior. This flag is mostly used for tests to validate // crash conditions. ReallyCrash = true ) // PanicHandlers is a list of functions which will be invoked when a panic happens. var PanicHandlers = []func(context.Context, interface{}){logPanic} // HandleCrash simply catches a crash and logs an error. Meant to be called via // defer. Additional context-specific handlers can be provided, and will be // called in case of panic. HandleCrash actually crashes, after calling the // handlers and logging the panic message. // // E.g., you can provide one or more additional handlers for something like shutting down go routines gracefully. // // Contextual logging: HandleCrashWithContext should be used instead of HandleCrash in code which supports contextual logging. func HandleCrash(additionalHandlers ...func(interface{})) { if r := recover(); r != nil { additionalHandlersWithContext := make([]func(context.Context, interface{}), len(additionalHandlers)) for i, handler := range additionalHandlers { handler := handler // capture loop variable additionalHandlersWithContext[i] = func(_ context.Context, r interface{}) { handler(r) } } handleCrash(context.Background(), r, additionalHandlersWithContext...) } } // HandleCrashWithContext simply catches a crash and logs an error. Meant to be called via // defer. Additional context-specific handlers can be provided, and will be // called in case of panic. HandleCrash actually crashes, after calling the // handlers and logging the panic message. // // E.g., you can provide one or more additional handlers for something like shutting down go routines gracefully. // // The context is used to determine how to log. func HandleCrashWithContext(ctx context.Context, additionalHandlers ...func(context.Context, interface{})) { if r := recover(); r != nil { handleCrash(ctx, r, additionalHandlers...) } } // handleCrash is the common implementation of HandleCrash and HandleCrash. // Having those call a common implementation ensures that the stack depth // is the same regardless through which path the handlers get invoked. func handleCrash(ctx context.Context, r any, additionalHandlers ...func(context.Context, interface{})) { for _, fn := range PanicHandlers { fn(ctx, r) } for _, fn := range additionalHandlers { fn(ctx, r) } if ReallyCrash { // Actually proceed to panic. panic(r) } } // logPanic logs the caller tree when a panic occurs (except in the special case of http.ErrAbortHandler). func logPanic(ctx context.Context, r interface{}) { if r == http.ErrAbortHandler { // honor the http.ErrAbortHandler sentinel panic value: // ErrAbortHandler is a sentinel panic value to abort a handler. // While any panic from ServeHTTP aborts the response to the client, // panicking with ErrAbortHandler also suppresses logging of a stack trace to the server's error log. return } // Same as stdlib http server code. Manually allocate stack trace buffer size // to prevent excessively large logs const size = 64 << 10 stacktrace := make([]byte, size) stacktrace = stacktrace[:runtime.Stack(stacktrace, false)] // We don't really know how many call frames to skip because the Go // panic handler is between us and the code where the panic occurred. // If it's one function (as in Go 1.21), then skipping four levels // gets us to the function which called the `defer HandleCrashWithontext(...)`. logger := klog.FromContext(ctx).WithCallDepth(4) // For backwards compatibility, conversion to string // is handled here instead of defering to the logging // backend. if _, ok := r.(string); ok { logger.Error(nil, "Observed a panic", "panic", r, "stacktrace", string(stacktrace)) } else { logger.Error(nil, "Observed a panic", "panic", fmt.Sprintf("%v", r), "panicGoValue", fmt.Sprintf("%#v", r), "stacktrace", string(stacktrace)) } } // ErrorHandlers is a list of functions which will be invoked when a nonreturnable // error occurs. // TODO(lavalamp): for testability, this and the below HandleError function // should be packaged up into a testable and reusable object. var ErrorHandlers = []ErrorHandler{ logError, func(_ context.Context, _ error, _ string, _ ...interface{}) { (&rudimentaryErrorBackoff{ lastErrorTime: time.Now(), // 1ms was the number folks were able to stomach as a global rate limit. // If you need to log errors more than 1000 times a second you // should probably consider fixing your code instead. :) minPeriod: time.Millisecond, }).OnError() }, } type ErrorHandler func(ctx context.Context, err error, msg string, keysAndValues ...interface{}) // HandlerError is a method to invoke when a non-user facing piece of code cannot // return an error and needs to indicate it has been ignored. Invoking this method // is preferable to logging the error - the default behavior is to log but the // errors may be sent to a remote server for analysis. // // Contextual logging: HandleErrorWithContext should be used instead of HandleError in code which supports contextual logging. func HandleError(err error) { // this is sometimes called with a nil error. We probably shouldn't fail and should do nothing instead if err == nil { return } handleError(context.Background(), err, "Unhandled Error") } // HandlerErrorWithContext is a method to invoke when a non-user facing piece of code cannot // return an error and needs to indicate it has been ignored. Invoking this method // is preferable to logging the error - the default behavior is to log but the // errors may be sent to a remote server for analysis. The context is used to // determine how to log the error. // // If contextual logging is enabled, the default log output is equivalent to // // logr.FromContext(ctx).WithName("UnhandledError").Error(err, msg, keysAndValues...) // // Without contextual logging, it is equivalent to: // // klog.ErrorS(err, msg, keysAndValues...) // // In contrast to HandleError, passing nil for the error is still going to // trigger a log entry. Don't construct a new error or wrap an error // with fmt.Errorf. Instead, add additional information via the mssage // and key/value pairs. // // This variant should be used instead of HandleError because it supports // structured, contextual logging. func HandleErrorWithContext(ctx context.Context, err error, msg string, keysAndValues ...interface{}) { handleError(ctx, err, msg, keysAndValues...) } // handleError is the common implementation of HandleError and HandleErrorWithContext. // Using this common implementation ensures that the stack depth // is the same regardless through which path the handlers get invoked. func handleError(ctx context.Context, err error, msg string, keysAndValues ...interface{}) { for _, fn := range ErrorHandlers { fn(ctx, err, msg, keysAndValues...) } } // logError prints an error with the call stack of the location it was reported. // It expects to be called as <caller> -> HandleError[WithContext] -> handleError -> logError. func logError(ctx context.Context, err error, msg string, keysAndValues ...interface{}) { logger := klog.FromContext(ctx).WithCallDepth(3) logger = klog.LoggerWithName(logger, "UnhandledError") logger.Error(err, msg, keysAndValues...) //nolint:logcheck // logcheck complains about unknown key/value pairs. } type rudimentaryErrorBackoff struct { minPeriod time.Duration // immutable // TODO(lavalamp): use the clock for testability. Need to move that // package for that to be accessible here. lastErrorTimeLock sync.Mutex lastErrorTime time.Time } // OnError will block if it is called more often than the embedded period time. // This will prevent overly tight hot error loops. func (r *rudimentaryErrorBackoff) OnError() { now := time.Now() // start the timer before acquiring the lock r.lastErrorTimeLock.Lock() d := now.Sub(r.lastErrorTime) r.lastErrorTime = time.Now() r.lastErrorTimeLock.Unlock() // Do not sleep with the lock held because that causes all callers of HandleError to block. // We only want the current goroutine to block. // A negative or zero duration causes time.Sleep to return immediately. // If the time moves backwards for any reason, do nothing. time.Sleep(r.minPeriod - d) } // GetCaller returns the caller of the function that calls it. func GetCaller() string { var pc [1]uintptr runtime.Callers(3, pc[:]) f := runtime.FuncForPC(pc[0]) if f == nil { return "Unable to find caller" } return f.Name() } // RecoverFromPanic replaces the specified error with an error containing the // original error, and the call tree when a panic occurs. This enables error // handlers to handle errors and panics the same way. func RecoverFromPanic(err *error) { if r := recover(); r != nil { // Same as stdlib http server code. Manually allocate stack trace buffer size // to prevent excessively large logs const size = 64 << 10 stacktrace := make([]byte, size) stacktrace = stacktrace[:runtime.Stack(stacktrace, false)] *err = fmt.Errorf( "recovered from panic %q. (err=%v) Call stack:\n%s", r, *err, stacktrace) } } // Must panics on non-nil errors. Useful to handling programmer level errors. func Must(err error) { if err != nil { panic(err) } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false