code
stringlengths 12
335k
| docstring
stringlengths 20
20.8k
| func_name
stringlengths 1
105
| language
stringclasses 1
value | repo
stringclasses 498
values | path
stringlengths 5
172
| url
stringlengths 43
235
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
func (w *lengthDelimitedFrameWriter) Write(data []byte) (int, error) {
binary.BigEndian.PutUint32(w.h[:], uint32(len(data)))
n, err := w.w.Write(w.h[:])
if err != nil {
return 0, err
}
if n != len(w.h) {
return 0, io.ErrShortWrite
}
return w.w.Write(data)
} | Write writes a single frame to the nested writer, prepending it with the length
in bytes of data (as a 4 byte, bigendian uint32). | Write | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/framer/framer.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/framer/framer.go | Apache-2.0 |
func NewLengthDelimitedFrameReader(r io.ReadCloser) io.ReadCloser {
return &lengthDelimitedFrameReader{r: r}
} | NewLengthDelimitedFrameReader returns an io.Reader that will decode length-prefixed
frames off of a stream.
The protocol is:
stream: message ...
message: prefix body
prefix: 4 byte uint32 in BigEndian order, denotes length of body
body: bytes (0..prefix)
If the buffer passed to Read is not long enough to contain an entire frame, io.ErrShortRead
will be returned along with the number of bytes read. | NewLengthDelimitedFrameReader | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/framer/framer.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/framer/framer.go | Apache-2.0 |
func (r *lengthDelimitedFrameReader) Read(data []byte) (int, error) {
if r.remaining <= 0 {
header := [4]byte{}
n, err := io.ReadAtLeast(r.r, header[:4], 4)
if err != nil {
return 0, err
}
if n != 4 {
return 0, io.ErrUnexpectedEOF
}
frameLength := int(binary.BigEndian.Uint32(header[:]))
r.remaining = frameLength
}
expect := r.remaining
max := expect
if max > len(data) {
max = len(data)
}
n, err := io.ReadAtLeast(r.r, data[:max], int(max))
r.remaining -= n
if err == io.ErrShortBuffer || r.remaining > 0 {
return n, io.ErrShortBuffer
}
if err != nil {
return n, err
}
if n != expect {
return n, io.ErrUnexpectedEOF
}
return n, nil
} | Read attempts to read an entire frame into data. If that is not possible, io.ErrShortBuffer
is returned and subsequent calls will attempt to read the last frame. A frame is complete when
err is nil. | Read | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/framer/framer.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/framer/framer.go | Apache-2.0 |
func NewJSONFramedReader(r io.ReadCloser) io.ReadCloser {
return &jsonFrameReader{
r: r,
decoder: json.NewDecoder(r),
}
} | NewJSONFramedReader returns an io.Reader that will decode individual JSON objects off
of a wire.
The boundaries between each frame are valid JSON objects. A JSON parsing error will terminate
the read. | NewJSONFramedReader | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/framer/framer.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/framer/framer.go | Apache-2.0 |
func (r *jsonFrameReader) Read(data []byte) (int, error) {
// Return whatever remaining data exists from an in progress frame
if n := len(r.remaining); n > 0 {
if n <= len(data) {
//nolint:staticcheck // SA4006,SA4010 underlying array of data is modified here.
data = append(data[0:0], r.remaining...)
r.remaining = nil
return n, nil
}
n = len(data)
//nolint:staticcheck // SA4006,SA4010 underlying array of data is modified here.
data = append(data[0:0], r.remaining[:n]...)
r.remaining = r.remaining[n:]
return n, io.ErrShortBuffer
}
// RawMessage#Unmarshal appends to data - we reset the slice down to 0 and will either see
// data written to data, or be larger than data and a different array.
n := len(data)
m := json.RawMessage(data[:0])
if err := r.decoder.Decode(&m); err != nil {
return 0, err
}
// If capacity of data is less than length of the message, decoder will allocate a new slice
// and set m to it, which means we need to copy the partial result back into data and preserve
// the remaining result for subsequent reads.
if len(m) > n {
//nolint:staticcheck // SA4006,SA4010 underlying array of data is modified here.
data = append(data[0:0], m[:n]...)
r.remaining = m[n:]
return n, io.ErrShortBuffer
}
return len(m), nil
} | ReadFrame decodes the next JSON object in the stream, or returns an error. The returned
byte slice will be modified the next time ReadFrame is invoked and should not be altered. | Read | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/framer/framer.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/framer/framer.go | Apache-2.0 |
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
} | 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. | IsQualifiedName | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | Apache-2.0 |
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
} | 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. | IsFullyQualifiedName | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | Apache-2.0 |
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
} | 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. | IsFullyQualifiedDomainName | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | Apache-2.0 |
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
} | 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. | IsDomainPrefixedPath | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | Apache-2.0 |
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
} | 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. | IsValidLabelValue | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | Apache-2.0 |
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
} | IsDNS1123Label tests for a string that conforms to the definition of a label in
DNS (RFC 1123). | IsDNS1123Label | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | Apache-2.0 |
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
} | IsDNS1123Subdomain tests for a string that conforms to the definition of a
subdomain in DNS (RFC 1123). | IsDNS1123Subdomain | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | Apache-2.0 |
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
} | IsDNS1035Label tests for a string that conforms to the definition of a label in
DNS (RFC 1035). | IsDNS1035Label | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | Apache-2.0 |
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
} | IsWildcardDNS1123Subdomain tests for a string that conforms to the definition of a
wildcard subdomain in DNS (RFC 1034 section 4.3.3). | IsWildcardDNS1123Subdomain | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | Apache-2.0 |
func IsCIdentifier(value string) []string {
if !cIdentifierRegexp.MatchString(value) {
return []string{RegexError(identifierErrMsg, cIdentifierFmt, "my_name", "MY_NAME", "MyName")}
}
return nil
} | IsCIdentifier tests for a string that conforms the definition of an identifier
in C. This checks the format, but not the length. | IsCIdentifier | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | Apache-2.0 |
func IsValidPortNum(port int) []string {
if 1 <= port && port <= 65535 {
return nil
}
return []string{InclusiveRangeError(1, 65535)}
} | IsValidPortNum tests that the argument is a valid, non-zero port number. | IsValidPortNum | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | Apache-2.0 |
func IsInRange(value int, min int, max int) []string {
if value >= min && value <= max {
return nil
}
return []string{InclusiveRangeError(min, max)}
} | IsInRange tests that the argument is in an inclusive range. | IsInRange | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | Apache-2.0 |
func IsValidGroupID(gid int64) []string {
if minGroupID <= gid && gid <= maxGroupID {
return nil
}
return []string{InclusiveRangeError(minGroupID, maxGroupID)}
} | IsValidGroupID tests that the argument is a valid Unix GID. | IsValidGroupID | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | Apache-2.0 |
func IsValidUserID(uid int64) []string {
if minUserID <= uid && uid <= maxUserID {
return nil
}
return []string{InclusiveRangeError(minUserID, maxUserID)}
} | IsValidUserID tests that the argument is a valid Unix UID. | IsValidUserID | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | Apache-2.0 |
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
} | 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. | IsValidPortName | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | Apache-2.0 |
func IsValidIP(value string) []string {
if netutils.ParseIPSloppy(value) == nil {
return []string{"must be a valid IP address, (e.g. 10.9.8.7 or 2001:db8::ffff)"}
}
return nil
} | IsValidIP tests that the argument is a valid IP address. | IsValidIP | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | Apache-2.0 |
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
} | IsValidIPv4Address tests that the argument is a valid IPv4 address. | IsValidIPv4Address | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | Apache-2.0 |
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
} | IsValidIPv6Address tests that the argument is a valid IPv6 address. | IsValidIPv6Address | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | Apache-2.0 |
func IsValidPercent(percent string) []string {
if !percentRegexp.MatchString(percent) {
return []string{RegexError(percentErrMsg, percentFmt, "1%", "93%")}
}
return nil
} | IsValidPercent checks that string is in the form of a percentage | IsValidPercent | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | Apache-2.0 |
func IsHTTPHeaderName(value string) []string {
if !httpHeaderNameRegexp.MatchString(value) {
return []string{RegexError(httpHeaderNameErrMsg, httpHeaderNameFmt, "X-Header-Name")}
}
return nil
} | IsHTTPHeaderName checks that a string conforms to the Go HTTP library's
definition of a valid header field name (a stricter subset than RFC7230). | IsHTTPHeaderName | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | Apache-2.0 |
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
} | IsEnvVarName tests if a string is a valid environment variable name. | IsEnvVarName | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | Apache-2.0 |
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
} | IsConfigMapKey tests for a string that is a valid key for a ConfigMap or Secret | IsConfigMapKey | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | Apache-2.0 |
func MaxLenError(length int) string {
return fmt.Sprintf("must be no more than %d characters", length)
} | MaxLenError returns a string explanation of a "string too long" validation
failure. | MaxLenError | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | Apache-2.0 |
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
} | RegexError returns a string explanation of a regex validation failure. | RegexError | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | Apache-2.0 |
func EmptyError() string {
return "must be non-empty"
} | EmptyError returns a string explanation of a "must not be empty" validation
failure. | EmptyError | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | Apache-2.0 |
func InclusiveRangeError(lo, hi int) string {
return fmt.Sprintf(`must be between %d and %d, inclusive`, lo, hi)
} | InclusiveRangeError returns a string explanation of a numeric "must be
between" validation failure. | InclusiveRangeError | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | Apache-2.0 |
func IsValidSocketAddr(value string) []string {
var errs []string
ip, port, err := net.SplitHostPort(value)
if err != nil {
errs = append(errs, "must be a valid socket address format, (e.g. 0.0.0.0:10254 or [::]:10254)")
return errs
}
portInt, _ := strconv.Atoi(port)
errs = append(errs, IsValidPortNum(portInt)...)
errs = append(errs, IsValidIP(ip)...)
return errs
} | IsValidSocketAddr checks that string represents a valid socket address
as defined in RFC 789. (e.g 0.0.0.0:10254 or [::]:10254)) | IsValidSocketAddr | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/validation/validation.go | Apache-2.0 |
func WithPath(p *Path) PathOption {
return func(o *pathOptions) {
o.path = p
}
} | WithPath generates a PathOption | WithPath | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/validation/field/path.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/validation/field/path.go | Apache-2.0 |
func ToPath(opts ...PathOption) *Path {
c := &pathOptions{}
for _, opt := range opts {
opt(c)
}
return c.path
} | ToPath produces *Path from a set of PathOption | ToPath | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/validation/field/path.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/validation/field/path.go | Apache-2.0 |
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
} | NewPath creates a root Path object. | NewPath | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/validation/field/path.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/validation/field/path.go | Apache-2.0 |
func (p *Path) Root() *Path {
for ; p.parent != nil; p = p.parent {
// Do nothing.
}
return p
} | Root returns the root element of this Path. | Root | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/validation/field/path.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/validation/field/path.go | Apache-2.0 |
func (p *Path) Child(name string, moreNames ...string) *Path {
r := NewPath(name, moreNames...)
r.Root().parent = p
return r
} | Child creates a new Path that is a child of the method receiver. | Child | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/validation/field/path.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/validation/field/path.go | Apache-2.0 |
func (p *Path) Index(index int) *Path {
return &Path{index: strconv.Itoa(index), parent: p}
} | Index indicates that the previous Path is to be subscripted by an int.
This sets the same underlying value as Key. | Index | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/validation/field/path.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/validation/field/path.go | Apache-2.0 |
func (p *Path) Key(key string) *Path {
return &Path{index: key, parent: p}
} | Key indicates that the previous Path is to be subscripted by a string.
This sets the same underlying value as Index. | Key | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/validation/field/path.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/validation/field/path.go | Apache-2.0 |
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()
} | String produces a string representation of the Path. | String | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/validation/field/path.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/validation/field/path.go | Apache-2.0 |
func (v *Error) Error() string {
return fmt.Sprintf("%s: %s", v.Field, v.ErrorBody())
} | Error implements the error interface. | Error | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/validation/field/errors.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/validation/field/errors.go | Apache-2.0 |
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)
}
} | ErrorBody returns the error message without the field name. This is useful
for building nice-looking higher-level error reporting. | ErrorBody | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/validation/field/errors.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/validation/field/errors.go | Apache-2.0 |
func IsPreconditionFailed(err error) bool {
_, ok := err.(ErrPreconditionFailed)
return ok
} | IsPreconditionFailed returns true if the provided error indicates
a precondition failed. | IsPreconditionFailed | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/mergepatch/errors.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/mergepatch/errors.go | Apache-2.0 |
func IsConflict(err error) bool {
_, ok := err.(ErrConflict)
return ok
} | IsConflict returns true if the provided error indicates
a conflict between the patch and the current configuration. | IsConflict | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/mergepatch/errors.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/mergepatch/errors.go | Apache-2.0 |
func RequireKeyUnchanged(key string) PreconditionFunc {
return func(patch interface{}) bool {
patchMap, ok := patch.(map[string]interface{})
if !ok {
return true
}
// The presence of key means that its value has been changed, so the test fails.
_, ok = patchMap[key]
return !ok
}
} | RequireKeyUnchanged returns a precondition function that fails if the provided key
is present in the patch (indicating that its value has changed). | RequireKeyUnchanged | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/mergepatch/util.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/mergepatch/util.go | Apache-2.0 |
func RequireMetadataKeyUnchanged(key string) PreconditionFunc {
return func(patch interface{}) bool {
patchMap, ok := patch.(map[string]interface{})
if !ok {
return true
}
patchMap1, ok := patchMap["metadata"]
if !ok {
return true
}
patchMap2, ok := patchMap1.(map[string]interface{})
if !ok {
return true
}
_, ok = patchMap2[key]
return !ok
}
} | RequireMetadataKeyUnchanged creates a precondition function that fails
if the metadata.key is present in the patch (indicating its value
has changed). | RequireMetadataKeyUnchanged | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/mergepatch/util.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/mergepatch/util.go | Apache-2.0 |
func HasConflicts(left, right interface{}) (bool, error) {
switch typedLeft := left.(type) {
case map[string]interface{}:
switch typedRight := right.(type) {
case map[string]interface{}:
for key, leftValue := range typedLeft {
rightValue, ok := typedRight[key]
if !ok {
continue
}
if conflict, err := HasConflicts(leftValue, rightValue); err != nil || conflict {
return conflict, err
}
}
return false, nil
default:
return true, nil
} | HasConflicts returns true if the left and right JSON interface objects overlap with
different values in any key. All keys are required to be strings. Since patches of the
same Type have congruent keys, this is valid for multiple patch types. This method
supports JSON merge patch semantics.
NOTE: Numbers with different types (e.g. int(0) vs int64(0)) will be detected as conflicts.
Make sure the unmarshaling of left and right are consistent (e.g. use the same library). | HasConflicts | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/mergepatch/util.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/mergepatch/util.go | Apache-2.0 |
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...)
} | 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. | CreateTwoWayMergePatch | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
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...)
} | 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. | CreateTwoWayMergeMapPatch | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
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
}
} | 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 | diffMaps | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
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
} | handleDirectiveMarker handles how to diff directive marker between 2 objects | handleDirectiveMarker | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
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
} | 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. | handleMapDiff | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
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
} | 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. | handleSliceDiff | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
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
} | 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 | replacePatchFieldIfNotEqual | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
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
}
}
} | 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 | updatePatchIfMissing | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
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
} | validateMergeKeyInLists checks if each map in the list has the mentryerge key. | validateMergeKeyInLists | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
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
} | 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`. | normalizeElementOrder | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
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
} | 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. | mergeSortedSlice | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
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
} | 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. | index | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
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
} | extractToDeleteItems takes a list and
returns 2 lists: one contains items that should be kept and the other contains items to be deleted. | extractToDeleteItems | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
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
} | normalizeSliceOrder sort `toSort` list by `order` | normalizeSliceOrder | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
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
} | 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. | diffLists | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
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
} | isOrderSame checks if the order in a list has changed | isOrderSame | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
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
} | 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 | diffListsOfScalars | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
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
}
} | 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 | compareListValuesAtIndex | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
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
} | diffListsOfMaps takes a pair of lists and
returns a (recursive) strategic merge patch list contains additions and changes and
a deletion list contains deletions | diffListsOfMaps | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
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
} | getMapAndMergeKeyValueByIndex return a map in the list and its merge key value given the index of the map. | getMapAndMergeKeyValueByIndex | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
func StrategicMergePatch(original, patch []byte, dataStruct interface{}) ([]byte, error) {
schema, err := NewPatchMetaFromStruct(dataStruct)
if err != nil {
return nil, err
}
return StrategicMergePatchUsingLookupPatchMeta(original, patch, schema)
} | 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. | StrategicMergePatch | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
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)
} | 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. | StrategicMergeMapPatch | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
func MergeStrategicMergeMapPatchUsingLookupPatchMeta(schema LookupPatchMeta, patches ...JSONMap) (JSONMap, error) {
mergeOptions := MergeOptions{
MergeParallelList: false,
IgnoreUnmatchedNulls: false,
}
merged := JSONMap{}
var err error
for _, patch := range patches {
merged, err = mergeMap(merged, patch, schema, mergeOptions)
if err != nil {
return nil, err
}
}
return merged, nil
} | 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
merging these patches. Applying the resulting merged merge patch to a JSONMap
yields the same as merging each strategic merge patch to the JSONMap in
succession. | MergeStrategicMergeMapPatchUsingLookupPatchMeta | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
func handleDirectiveInMergeMap(directive interface{}, patch map[string]interface{}) (map[string]interface{}, error) {
if directive == replaceDirective {
// If the patch contains "$patch: replace", don't merge it, just use the
// patch directly. Later on, we can add a single level replace that only
// affects the map that the $patch is in.
delete(patch, directiveMarker)
return patch, nil
}
if directive == deleteDirective {
// If the patch contains "$patch: delete", don't merge it, just return
// an empty map.
return map[string]interface{}{}, nil
}
return nil, mergepatch.ErrBadPatchType(directive, patch)
} | handleDirectiveInMergeMap handles the patch directive when merging 2 maps. | handleDirectiveInMergeMap | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
func extractKey(s, prefix string) (string, error) {
substrings := strings.SplitN(s, "/", 2)
if len(substrings) <= 1 || substrings[0] != prefix {
switch prefix {
case deleteFromPrimitiveListDirectivePrefix:
return "", mergepatch.ErrBadPatchFormatForPrimitiveList
case setElementOrderDirectivePrefix:
return "", mergepatch.ErrBadPatchFormatForSetElementOrderList
default:
return "", fmt.Errorf("fail to find unknown prefix %q in %s\n", prefix, s)
}
}
return substrings[1], nil
} | extractKey trims the prefix and return the original key | extractKey | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
func validatePatchWithSetOrderList(patchList, setOrderList interface{}, mergeKey string) error {
typedSetOrderList, ok := setOrderList.([]interface{})
if !ok {
return mergepatch.ErrBadPatchFormatForSetElementOrderList
}
typedPatchList, ok := patchList.([]interface{})
if !ok {
return mergepatch.ErrBadPatchFormatForSetElementOrderList
}
if len(typedSetOrderList) == 0 || len(typedPatchList) == 0 {
return nil
}
var nonDeleteList []interface{}
var err error
if len(mergeKey) > 0 {
nonDeleteList, _, err = extractToDeleteItems(typedPatchList)
if err != nil {
return err
}
} else {
nonDeleteList = typedPatchList
}
patchIndex, setOrderIndex := 0, 0
for patchIndex < len(nonDeleteList) && setOrderIndex < len(typedSetOrderList) {
if containsDirectiveMarker(nonDeleteList[patchIndex]) {
patchIndex++
continue
}
mergeKeyEqual, err := mergeKeyValueEqual(nonDeleteList[patchIndex], typedSetOrderList[setOrderIndex], mergeKey)
if err != nil {
return err
}
if mergeKeyEqual {
patchIndex++
}
setOrderIndex++
}
// If patchIndex is inbound but setOrderIndex if out of bound mean there are items mismatching between the patch list and setElementOrder list.
// the second check is a sanity check, and should always be true if the first is true.
if patchIndex < len(nonDeleteList) && setOrderIndex >= len(typedSetOrderList) {
return fmt.Errorf("The order in patch list:\n%v\n doesn't match %s list:\n%v\n", typedPatchList, setElementOrderDirectivePrefix, setOrderList)
}
return nil
} | validatePatchUsingSetOrderList verifies:
the relative order of any two items in the setOrderList list matches that in the patch list.
the items in the patch list must be a subset or the same as the $setElementOrder list (deletions are ignored). | validatePatchWithSetOrderList | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
func preprocessDeletionListForMerging(key string, original map[string]interface{},
patchVal interface{}, mergeDeletionList bool) (bool, bool, string, error) {
// If found a parallel list for deletion and we are going to merge the list,
// overwrite the key to the original key and set flag isDeleteList
foundParallelListPrefix := strings.HasPrefix(key, deleteFromPrimitiveListDirectivePrefix)
if foundParallelListPrefix {
if !mergeDeletionList {
original[key] = patchVal
return true, false, "", nil
}
originalKey, err := extractKey(key, deleteFromPrimitiveListDirectivePrefix)
return false, true, originalKey, err
}
return false, false, "", nil
} | preprocessDeletionListForMerging preprocesses the deletion list.
it returns shouldContinue, isDeletionList, noPrefixKey | preprocessDeletionListForMerging | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
func applyRetainKeysDirective(original, patch map[string]interface{}, options MergeOptions) error {
retainKeysInPatch, foundInPatch := patch[retainKeysDirective]
if !foundInPatch {
return nil
}
// cleanup the directive
delete(patch, retainKeysDirective)
if !options.MergeParallelList {
// If original is actually a patch, make sure the retainKeys directives are the same in both patches if present in both.
// If not present in the original patch, copy from the modified patch.
retainKeysInOriginal, foundInOriginal := original[retainKeysDirective]
if foundInOriginal {
if !reflect.DeepEqual(retainKeysInOriginal, retainKeysInPatch) {
// This error actually should never happen.
return fmt.Errorf("%v and %v are not deep equal: this may happen when calculating the 3-way diff patch", retainKeysInOriginal, retainKeysInPatch)
}
} else {
original[retainKeysDirective] = retainKeysInPatch
}
return nil
}
retainKeysList, ok := retainKeysInPatch.([]interface{})
if !ok {
return mergepatch.ErrBadPatchFormatForRetainKeys
}
// validate patch to make sure all fields in the patch are present in the retainKeysList.
// The map is used only as a set, the value is never referenced
m := map[interface{}]struct{}{}
for _, v := range retainKeysList {
m[v] = struct{}{}
}
for k, v := range patch {
if v == nil || strings.HasPrefix(k, deleteFromPrimitiveListDirectivePrefix) ||
strings.HasPrefix(k, setElementOrderDirectivePrefix) {
continue
}
// If there is an item present in the patch but not in the retainKeys list,
// the patch is invalid.
if _, found := m[k]; !found {
return mergepatch.ErrBadPatchFormatForRetainKeys
}
}
// clear not present fields
for k := range original {
if _, found := m[k]; !found {
delete(original, k)
}
}
return nil
} | applyRetainKeysDirective looks for a retainKeys directive and applies to original
- if no directive exists do nothing
- if directive is found, clear keys in original missing from the directive list
- validate that all keys present in the patch are present in the retainKeys directive
note: original may be another patch request, e.g. applying the add+modified patch to the deletions patch. In this case it may have directives | applyRetainKeysDirective | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
func mergePatchIntoOriginal(original, patch map[string]interface{}, schema LookupPatchMeta, mergeOptions MergeOptions) error {
for key, patchV := range patch {
// Do nothing if there is no ordering directive
if !strings.HasPrefix(key, setElementOrderDirectivePrefix) {
continue
}
setElementOrderInPatch := patchV
// Copies directive from the second patch (`patch`) to the first patch (`original`)
// and checks they are equal and delete the directive in the second patch
if !mergeOptions.MergeParallelList {
setElementOrderListInOriginal, ok := original[key]
if ok {
// check if the setElementOrder list in original and the one in patch matches
if !reflect.DeepEqual(setElementOrderListInOriginal, setElementOrderInPatch) {
return mergepatch.ErrBadPatchFormatForSetElementOrderList
}
} else {
// move the setElementOrder list from patch to original
original[key] = setElementOrderInPatch
}
}
delete(patch, key)
var (
ok bool
originalFieldValue, patchFieldValue, merged []interface{}
patchStrategy string
patchMeta PatchMeta
subschema LookupPatchMeta
)
typedSetElementOrderList, ok := setElementOrderInPatch.([]interface{})
if !ok {
return mergepatch.ErrBadArgType(typedSetElementOrderList, setElementOrderInPatch)
}
// Trim the setElementOrderDirectivePrefix to get the key of the list field in original.
originalKey, err := extractKey(key, setElementOrderDirectivePrefix)
if err != nil {
return err
}
// try to find the list with `originalKey` in `original` and `modified` and merge them.
originalList, foundOriginal := original[originalKey]
patchList, foundPatch := patch[originalKey]
if foundOriginal {
originalFieldValue, ok = originalList.([]interface{})
if !ok {
return mergepatch.ErrBadArgType(originalFieldValue, originalList)
}
}
if foundPatch {
patchFieldValue, ok = patchList.([]interface{})
if !ok {
return mergepatch.ErrBadArgType(patchFieldValue, patchList)
}
}
subschema, patchMeta, err = schema.LookupPatchMetadataForSlice(originalKey)
if err != nil {
return err
}
_, patchStrategy, err = extractRetainKeysPatchStrategy(patchMeta.GetPatchStrategies())
if err != nil {
return err
}
// Check for consistency between the element order list and the field it applies to
err = validatePatchWithSetOrderList(patchFieldValue, typedSetElementOrderList, patchMeta.GetPatchMergeKey())
if err != nil {
return err
}
switch {
case foundOriginal && !foundPatch:
// no change to list contents
merged = originalFieldValue
case !foundOriginal && foundPatch:
// list was added
v, keep := removeDirectives(patchFieldValue)
if !keep {
// Shouldn't be possible since patchFieldValue is a slice
continue
}
merged = v.([]interface{})
case foundOriginal && foundPatch:
merged, err = mergeSliceHandler(originalList, patchList, subschema,
patchStrategy, patchMeta.GetPatchMergeKey(), false, mergeOptions)
if err != nil {
return err
}
case !foundOriginal && !foundPatch:
continue
}
// Split all items into patch items and server-only items and then enforce the order.
var patchItems, serverOnlyItems []interface{}
if len(patchMeta.GetPatchMergeKey()) == 0 {
// Primitives doesn't need merge key to do partitioning.
patchItems, serverOnlyItems = partitionPrimitivesByPresentInList(merged, typedSetElementOrderList)
} else {
// Maps need merge key to do partitioning.
patchItems, serverOnlyItems, err = partitionMapsByPresentInList(merged, typedSetElementOrderList, patchMeta.GetPatchMergeKey())
if err != nil {
return err
}
}
elementType, err := sliceElementType(originalFieldValue, patchFieldValue)
if err != nil {
return err
}
kind := elementType.Kind()
// normalize merged list
// typedSetElementOrderList contains all the relative order in typedPatchList,
// so don't need to use typedPatchList
both, err := normalizeElementOrder(patchItems, serverOnlyItems, typedSetElementOrderList, originalFieldValue, patchMeta.GetPatchMergeKey(), kind)
if err != nil {
return err
}
original[originalKey] = both
// delete patch list from patch to prevent process again in the future
delete(patch, originalKey)
}
return nil
} | mergePatchIntoOriginal processes $setElementOrder list.
When not merging the directive, it will make sure $setElementOrder list exist only in original.
When merging the directive, it will try to find the $setElementOrder list and
its corresponding patch list, validate it and merge it.
Then, sort them by the relative order in setElementOrder, patch list and live list.
The precedence is $setElementOrder > order in patch list > order in live list.
This function will delete the item after merging it to prevent process it again in the future.
Ref: https://git.k8s.io/design-proposals-archive/cli/preserve-order-in-strategic-merge-patch.md | mergePatchIntoOriginal | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
func partitionPrimitivesByPresentInList(original, partitionBy []interface{}) ([]interface{}, []interface{}) {
patch := make([]interface{}, 0, len(original))
serverOnly := make([]interface{}, 0, len(original))
inPatch := map[interface{}]bool{}
for _, v := range partitionBy {
inPatch[v] = true
}
for _, v := range original {
if !inPatch[v] {
serverOnly = append(serverOnly, v)
} else {
patch = append(patch, v)
}
}
return patch, serverOnly
} | partitionPrimitivesByPresentInList partitions elements into 2 slices, the first containing items present in partitionBy, the other not. | partitionPrimitivesByPresentInList | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
func partitionMapsByPresentInList(original, partitionBy []interface{}, mergeKey string) ([]interface{}, []interface{}, error) {
patch := make([]interface{}, 0, len(original))
serverOnly := make([]interface{}, 0, len(original))
for _, v := range original {
typedV, ok := v.(map[string]interface{})
if !ok {
return nil, nil, mergepatch.ErrBadArgType(typedV, v)
}
mergeKeyValue, foundMergeKey := typedV[mergeKey]
if !foundMergeKey {
return nil, nil, mergepatch.ErrNoMergeKey(typedV, mergeKey)
}
_, _, found, err := findMapInSliceBasedOnKeyValue(partitionBy, mergeKey, mergeKeyValue)
if err != nil {
return nil, nil, err
}
if !found {
serverOnly = append(serverOnly, v)
} else {
patch = append(patch, v)
}
}
return patch, serverOnly, nil
} | partitionMapsByPresentInList partitions elements into 2 slices, the first containing items present in partitionBy, the other not. | partitionMapsByPresentInList | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
func removeDirectives(obj interface{}) (interface{}, bool) {
if obj == nil {
return obj, true
} else if typedV, ok := obj.(map[string]interface{}); ok {
if _, hasDirective := typedV[directiveMarker]; hasDirective {
return nil, false
}
for k, v := range typedV {
var keep bool
typedV[k], keep = removeDirectives(v)
if !keep {
delete(typedV, k)
}
}
return typedV, true
} else if typedV, ok := obj.([]interface{}); ok {
var res []interface{}
if typedV != nil {
// Make sure res is non-nil if patch is non-nil
res = []interface{}{}
}
for _, v := range typedV {
if newV, keep := removeDirectives(v); keep {
res = append(res, newV)
}
}
return res, true
} else {
return obj, true
}
} | Removes directives from an object and returns value to use instead and whether
or not the field/index should even be kept
May modify input | removeDirectives | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
func mergeMap(original, patch map[string]interface{}, schema LookupPatchMeta, mergeOptions MergeOptions) (map[string]interface{}, error) {
if v, ok := patch[directiveMarker]; ok {
return handleDirectiveInMergeMap(v, patch)
}
// nil is an accepted value for original to simplify logic in other places.
// If original is nil, replace it with an empty map and then apply the patch.
if original == nil {
original = map[string]interface{}{}
}
err := applyRetainKeysDirective(original, patch, mergeOptions)
if err != nil {
return nil, err
}
// Process $setElementOrder list and other lists sharing the same key.
// When not merging the directive, it will make sure $setElementOrder list exist only in original.
// When merging the directive, it will process $setElementOrder and its patch list together.
// This function will delete the merged elements from patch so they will not be reprocessed
err = mergePatchIntoOriginal(original, patch, schema, mergeOptions)
if err != nil {
return nil, err
}
// Start merging the patch into the original.
for k, patchV := range patch {
skipProcessing, isDeleteList, noPrefixKey, err := preprocessDeletionListForMerging(k, original, patchV, mergeOptions.MergeParallelList)
if err != nil {
return nil, err
}
if skipProcessing {
continue
}
if len(noPrefixKey) > 0 {
k = noPrefixKey
}
// If the value of this key is null, delete the key if it exists in the
// original. Otherwise, check if we want to preserve it or skip it.
// Preserving the null value is useful when we want to send an explicit
// delete to the API server.
if patchV == nil {
delete(original, k)
if mergeOptions.IgnoreUnmatchedNulls {
continue
}
}
_, ok := original[k]
if !ok {
if !isDeleteList {
// If it's not in the original document, just take the patch value.
if mergeOptions.IgnoreUnmatchedNulls {
discardNullValuesFromPatch(patchV)
}
original[k], ok = removeDirectives(patchV)
if !ok {
delete(original, k)
}
}
continue
}
originalType := reflect.TypeOf(original[k])
patchType := reflect.TypeOf(patchV)
if originalType != patchType {
if !isDeleteList {
if mergeOptions.IgnoreUnmatchedNulls {
discardNullValuesFromPatch(patchV)
}
original[k], ok = removeDirectives(patchV)
if !ok {
delete(original, k)
}
}
continue
}
// If they're both maps or lists, recurse into the value.
switch originalType.Kind() {
case reflect.Map:
subschema, patchMeta, err2 := schema.LookupPatchMetadataForStruct(k)
if err2 != nil {
return nil, err2
}
_, patchStrategy, err2 := extractRetainKeysPatchStrategy(patchMeta.GetPatchStrategies())
if err2 != nil {
return nil, err2
}
original[k], err = mergeMapHandler(original[k], patchV, subschema, patchStrategy, mergeOptions)
case reflect.Slice:
subschema, patchMeta, err2 := schema.LookupPatchMetadataForSlice(k)
if err2 != nil {
return nil, err2
}
_, patchStrategy, err2 := extractRetainKeysPatchStrategy(patchMeta.GetPatchStrategies())
if err2 != nil {
return nil, err2
}
original[k], err = mergeSliceHandler(original[k], patchV, subschema, patchStrategy, patchMeta.GetPatchMergeKey(), isDeleteList, mergeOptions)
default:
original[k], ok = removeDirectives(patchV)
if !ok {
// if patchV itself is a directive, then don't keep it
delete(original, k)
}
}
if err != nil {
return nil, err
}
}
return original, nil
} | Merge fields from a patch map into the original map. Note: This may modify
both the original map and the patch because getting a deep copy of a map in
golang is highly non-trivial.
flag mergeOptions.MergeParallelList controls if using the parallel list to delete or keeping the list.
If patch contains any null field (e.g. field_1: null) that is not
present in original, then to propagate it to the end result use
mergeOptions.IgnoreUnmatchedNulls == false. | mergeMap | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
func discardNullValuesFromPatch(patchV interface{}) {
switch patchV := patchV.(type) {
case map[string]interface{}:
for k, v := range patchV {
if v == nil {
delete(patchV, k)
} else {
discardNullValuesFromPatch(v)
}
}
case []interface{}:
for _, v := range patchV {
discardNullValuesFromPatch(v)
}
} | discardNullValuesFromPatch discards all null property values from patch.
It traverses all slices and map types. | discardNullValuesFromPatch | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
func mergeMapHandler(original, patch interface{}, schema LookupPatchMeta,
fieldPatchStrategy string, mergeOptions MergeOptions) (map[string]interface{}, error) {
typedOriginal, typedPatch, err := mapTypeAssertion(original, patch)
if err != nil {
return nil, err
}
if fieldPatchStrategy != replaceDirective {
return mergeMap(typedOriginal, typedPatch, schema, mergeOptions)
} else {
return typedPatch, nil
}
} | mergeMapHandler handles how to merge `patchV` whose key is `key` with `original` respecting
fieldPatchStrategy and mergeOptions. | mergeMapHandler | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
func mergeSliceHandler(original, patch interface{}, schema LookupPatchMeta,
fieldPatchStrategy, fieldPatchMergeKey string, isDeleteList bool, mergeOptions MergeOptions) ([]interface{}, error) {
typedOriginal, typedPatch, err := sliceTypeAssertion(original, patch)
if err != nil {
return nil, err
}
// Delete lists are handled the same way regardless of what the field's patch strategy is
if fieldPatchStrategy == mergeDirective || isDeleteList {
return mergeSlice(typedOriginal, typedPatch, schema, fieldPatchMergeKey, mergeOptions, isDeleteList)
} else {
return typedPatch, nil
}
} | mergeSliceHandler handles how to merge `patchV` whose key is `key` with `original` respecting
fieldPatchStrategy, fieldPatchMergeKey, isDeleteList and mergeOptions. | mergeSliceHandler | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
func mergeSlice(original, patch []interface{}, schema LookupPatchMeta, mergeKey string, mergeOptions MergeOptions, isDeleteList bool) ([]interface{}, error) {
if len(original) == 0 && len(patch) == 0 {
return original, nil
}
// All the values must be of the same type, but not a list.
t, err := sliceElementType(original, patch)
if err != nil {
return nil, err
}
var merged []interface{}
kind := t.Kind()
// If the elements are not maps, merge the slices of scalars.
if kind != reflect.Map {
if mergeOptions.MergeParallelList && isDeleteList {
return deleteFromSlice(original, patch), nil
}
// Maybe in the future add a "concat" mode that doesn't
// deduplicate.
both := append(original, patch...)
merged = deduplicateScalars(both)
} else {
if mergeKey == "" {
return nil, fmt.Errorf("cannot merge lists without merge key for %s", schema.Name())
}
original, patch, err = mergeSliceWithSpecialElements(original, patch, mergeKey)
if err != nil {
return nil, err
}
merged, err = mergeSliceWithoutSpecialElements(original, patch, mergeKey, schema, mergeOptions)
if err != nil {
return nil, err
}
}
// enforce the order
var patchItems, serverOnlyItems []interface{}
if len(mergeKey) == 0 {
patchItems, serverOnlyItems = partitionPrimitivesByPresentInList(merged, patch)
} else {
patchItems, serverOnlyItems, err = partitionMapsByPresentInList(merged, patch, mergeKey)
if err != nil {
return nil, err
}
}
return normalizeElementOrder(patchItems, serverOnlyItems, patch, original, mergeKey, kind)
} | Merge two slices together. Note: This may modify both the original slice and
the patch because getting a deep copy of a slice in golang is highly
non-trivial. | mergeSlice | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
func mergeSliceWithSpecialElements(original, patch []interface{}, mergeKey string) ([]interface{}, []interface{}, error) {
patchWithoutSpecialElements := []interface{}{}
replace := false
for _, v := range patch {
typedV := v.(map[string]interface{})
patchType, ok := typedV[directiveMarker]
if !ok {
patchWithoutSpecialElements = append(patchWithoutSpecialElements, v)
} else {
switch patchType {
case deleteDirective:
mergeValue, ok := typedV[mergeKey]
if ok {
var err error
original, err = deleteMatchingEntries(original, mergeKey, mergeValue)
if err != nil {
return nil, nil, err
}
} else {
return nil, nil, mergepatch.ErrNoMergeKey(typedV, mergeKey)
}
case replaceDirective:
replace = true
// Continue iterating through the array to prune any other $patch elements.
case mergeDirective:
return nil, nil, fmt.Errorf("merging lists cannot yet be specified in the patch")
default:
return nil, nil, mergepatch.ErrBadPatchType(patchType, typedV)
}
}
}
if replace {
return patchWithoutSpecialElements, nil, nil
}
return original, patchWithoutSpecialElements, nil
} | mergeSliceWithSpecialElements handles special elements with directiveMarker
before merging the slices. It returns a updated `original` and a patch without special elements.
original and patch must be slices of maps, they should be checked before calling this function. | mergeSliceWithSpecialElements | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
func deleteMatchingEntries(original []interface{}, mergeKey string, mergeValue interface{}) ([]interface{}, error) {
for {
_, originalKey, found, err := findMapInSliceBasedOnKeyValue(original, mergeKey, mergeValue)
if err != nil {
return nil, err
}
if !found {
break
}
// Delete the element at originalKey.
original = append(original[:originalKey], original[originalKey+1:]...)
}
return original, nil
} | delete all matching entries (based on merge key) from a merging list | deleteMatchingEntries | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
func mergeSliceWithoutSpecialElements(original, patch []interface{}, mergeKey string, schema LookupPatchMeta, mergeOptions MergeOptions) ([]interface{}, error) {
for _, v := range patch {
typedV := v.(map[string]interface{})
mergeValue, ok := typedV[mergeKey]
if !ok {
return nil, mergepatch.ErrNoMergeKey(typedV, mergeKey)
}
// If we find a value with this merge key value in original, merge the
// maps. Otherwise append onto original.
originalMap, originalKey, found, err := findMapInSliceBasedOnKeyValue(original, mergeKey, mergeValue)
if err != nil {
return nil, err
}
if found {
var mergedMaps interface{}
var err error
// Merge into original.
mergedMaps, err = mergeMap(originalMap, typedV, schema, mergeOptions)
if err != nil {
return nil, err
}
original[originalKey] = mergedMaps
} else {
original = append(original, v)
}
}
return original, nil
} | mergeSliceWithoutSpecialElements merges slices with non-special elements.
original and patch must be slices of maps, they should be checked before calling this function. | mergeSliceWithoutSpecialElements | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
func deleteFromSlice(current, toDelete []interface{}) []interface{} {
toDeleteMap := map[interface{}]interface{}{}
processed := make([]interface{}, 0, len(current))
for _, v := range toDelete {
toDeleteMap[v] = true
}
for _, v := range current {
if _, found := toDeleteMap[v]; !found {
processed = append(processed, v)
}
}
return processed
} | deleteFromSlice uses the parallel list to delete the items in a list of scalars | deleteFromSlice | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
func findMapInSliceBasedOnKeyValue(m []interface{}, key string, value interface{}) (map[string]interface{}, int, bool, error) {
for k, v := range m {
typedV, ok := v.(map[string]interface{})
if !ok {
return nil, 0, false, fmt.Errorf("value for key %v is not a map", k)
}
valueToMatch, ok := typedV[key]
if ok && valueToMatch == value {
return typedV, k, true, nil
}
}
return nil, 0, false, nil
} | This method no longer panics if any element of the slice is not a map. | findMapInSliceBasedOnKeyValue | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
func sortMergeListsByName(mapJSON []byte, schema LookupPatchMeta) ([]byte, error) {
var m map[string]interface{}
err := json.Unmarshal(mapJSON, &m)
if err != nil {
return nil, mergepatch.ErrBadJSONDoc
}
newM, err := sortMergeListsByNameMap(m, schema)
if err != nil {
return nil, err
}
return json.Marshal(newM)
} | This function takes a JSON map and sorts all the lists that should be merged
by key. This is needed by tests because in JSON, list order is significant,
but in Strategic Merge Patch, merge lists do not have significant order.
Sorting the lists allows for order-insensitive comparison of patched maps. | sortMergeListsByName | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
func sortMergeListsByNameMap(s map[string]interface{}, schema LookupPatchMeta) (map[string]interface{}, error) {
newS := map[string]interface{}{}
for k, v := range s {
if k == retainKeysDirective {
typedV, ok := v.([]interface{})
if !ok {
return nil, mergepatch.ErrBadPatchFormatForRetainKeys
}
v = sortScalars(typedV)
} else if strings.HasPrefix(k, deleteFromPrimitiveListDirectivePrefix) {
typedV, ok := v.([]interface{})
if !ok {
return nil, mergepatch.ErrBadPatchFormatForPrimitiveList
}
v = sortScalars(typedV)
} else if strings.HasPrefix(k, setElementOrderDirectivePrefix) {
_, ok := v.([]interface{})
if !ok {
return nil, mergepatch.ErrBadPatchFormatForSetElementOrderList
}
} else if k != directiveMarker {
// recurse for map and slice.
switch typedV := v.(type) {
case map[string]interface{}:
subschema, _, err := schema.LookupPatchMetadataForStruct(k)
if err != nil {
return nil, err
}
v, err = sortMergeListsByNameMap(typedV, subschema)
if err != nil {
return nil, err
}
case []interface{}:
subschema, patchMeta, err := schema.LookupPatchMetadataForSlice(k)
if err != nil {
return nil, err
}
_, patchStrategy, err := extractRetainKeysPatchStrategy(patchMeta.GetPatchStrategies())
if err != nil {
return nil, err
}
if patchStrategy == mergeDirective {
var err error
v, err = sortMergeListsByNameArray(typedV, subschema, patchMeta.GetPatchMergeKey(), true)
if err != nil {
return nil, err
}
}
}
}
newS[k] = v
} | Function sortMergeListsByNameMap recursively sorts the merge lists by its mergeKey in a map. | sortMergeListsByNameMap | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
func sortMergeListsByNameArray(s []interface{}, schema LookupPatchMeta, mergeKey string, recurse bool) ([]interface{}, error) {
if len(s) == 0 {
return s, nil
}
// We don't support lists of lists yet.
t, err := sliceElementType(s)
if err != nil {
return nil, err
}
// If the elements are not maps...
if t.Kind() != reflect.Map {
// Sort the elements, because they may have been merged out of order.
return deduplicateAndSortScalars(s), nil
}
// Elements are maps - if one of the keys of the map is a map or a
// list, we may need to recurse into it.
newS := []interface{}{}
for _, elem := range s {
if recurse {
typedElem := elem.(map[string]interface{})
newElem, err := sortMergeListsByNameMap(typedElem, schema)
if err != nil {
return nil, err
}
newS = append(newS, newElem)
} else {
newS = append(newS, elem)
}
}
// Sort the maps.
newS = sortMapsBasedOnField(newS, mergeKey)
return newS, nil
} | Function sortMergeListsByNameMap recursively sorts the merge lists by its mergeKey in an array. | sortMergeListsByNameArray | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
func sliceElementType(slices ...[]interface{}) (reflect.Type, error) {
var prevType reflect.Type
for _, s := range slices {
// Go through elements of all given slices and make sure they are all the same type.
for _, v := range s {
currentType := reflect.TypeOf(v)
if prevType == nil {
prevType = currentType
// We don't support lists of lists yet.
if prevType.Kind() == reflect.Slice {
return nil, mergepatch.ErrNoListOfLists
}
} else {
if prevType != currentType {
return nil, fmt.Errorf("list element types are not identical: %v", fmt.Sprint(slices))
}
prevType = currentType
}
}
}
if prevType == nil {
return nil, fmt.Errorf("no elements in any of the given slices")
}
return prevType, nil
} | Returns the type of the elements of N slice(s). If the type is different,
another slice or undefined, returns an error. | sliceElementType | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
func MergingMapsHaveConflicts(left, right map[string]interface{}, schema LookupPatchMeta) (bool, error) {
return mergingMapFieldsHaveConflicts(left, right, schema, "", "")
} | MergingMapsHaveConflicts returns true if the left and right JSON interface
objects overlap with different values in any key. All keys are required to be
strings. Since patches of the same Type have congruent keys, this is valid
for multiple patch types. This method supports strategic merge patch semantics. | MergingMapsHaveConflicts | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch.go | Apache-2.0 |
func NewInt(items ...int) Int {
return Int(New[int](items...))
} | NewInt creates a Int from a list of values. | NewInt | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/sets/int.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/sets/int.go | Apache-2.0 |
func NewByte(items ...byte) Byte {
return Byte(New[byte](items...))
} | NewByte creates a Byte from a list of values. | NewByte | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/sets/byte.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/sets/byte.go | Apache-2.0 |
func NewInt64(items ...int64) Int64 {
return Int64(New[int64](items...))
} | NewInt64 creates a Int64 from a list of values. | NewInt64 | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/sets/int64.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/sets/int64.go | Apache-2.0 |
func NewInt32(items ...int32) Int32 {
return Int32(New[int32](items...))
} | NewInt32 creates a Int32 from a list of values. | NewInt32 | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/sets/int32.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/sets/int32.go | Apache-2.0 |
func NewString(items ...string) String {
return String(New[string](items...))
} | NewString creates a String from a list of values. | NewString | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/sets/string.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/sets/string.go | Apache-2.0 |
func Unmarshal(data []byte, v interface{}) error {
preserveIntFloat := func(d *json.Decoder) *json.Decoder {
d.UseNumber()
return d
}
switch v := v.(type) {
case *map[string]interface{}:
if err := yaml.Unmarshal(data, v, preserveIntFloat); err != nil {
return err
}
return jsonutil.ConvertMapNumbers(*v, 0)
case *[]interface{}:
if err := yaml.Unmarshal(data, v, preserveIntFloat); err != nil {
return err
}
return jsonutil.ConvertSliceNumbers(*v, 0)
case *interface{}:
if err := yaml.Unmarshal(data, v, preserveIntFloat); err != nil {
return err
}
return jsonutil.ConvertInterfaceNumbers(v, 0)
default:
return yaml.Unmarshal(data, v)
} | Unmarshal unmarshals the given data
If v is a *map[string]interface{}, *[]interface{}, or *interface{} numbers
are converted to int64 or float64 | Unmarshal | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/apimachinery/pkg/util/yaml/decoder.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/apimachinery/pkg/util/yaml/decoder.go | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.