// interpretStrategicMergePatchError interprets the error type and returns an error with appropriate HTTP code.
499764
func interpretStrategicMergePatchError(err error) error {
	switch err {
	case mergepatch.ErrBadJSONDoc, mergepatch.ErrBadPatchFormatForPrimitiveList, mergepatch.ErrBadPatchFormatForRetainKeys, mergepatch.ErrBadPatchFormatForSetElementOrderList, mergepatch.ErrUnsupportedStrategicMergePatchFormat:
		return errors.NewBadRequest(err.Error())
	case mergepatch.ErrNoListOfLists, mergepatch.ErrPatchContentNotMatchRetainKeys:
		return errors.NewGenericServerResponse(http.StatusUnprocessableEntity, "", schema.GroupResource{}, "", err.Error(), 0, false)
	default:
		return err
	}
}
273356
func transformDecodeError(typer runtime.ObjectTyper, baseErr error, into runtime.Object, gvk *schema.GroupVersionKind, body []byte) error {
	objGVKs, _, err := typer.ObjectKinds(into)
	if err != nil {
		return errors.NewBadRequest(err.Error())
	}
	objGVK := objGVKs[0]
	if gvk != nil && len(gvk.Kind) > 0 {
		return errors.NewBadRequest(fmt.Sprintf("%s in version %q cannot be handled as a %s: %v", gvk.Kind, gvk.Version, objGVK.Kind, baseErr))
	}
	summary := summarizeData(body, 30)
	return errors.NewBadRequest(fmt.Sprintf("the object provided is unrecognized (must be of type %s): %v (%s)", objGVK.Kind, baseErr, summary))
}
1026375
func (rc *RediffContext) AnalyzePatch(patchReader savior.SeekSource) error {
	var err error

	if rc.RediffSizeLimit == 0 {
		rc.RediffSizeLimit = DefaultRediffSizeLimit
	}

	rctx := wire.NewReadContext(patchReader)

	err = rctx.ExpectMagic(PatchMagic)
	if err != nil {
		return errors.WithStack(err)
	}

	ph := &PatchHeader{}
	err = rctx.ReadMessage(ph)
	if err != nil {
		return errors.WithStack(err)
	}

	rctx, err = DecompressWire(rctx, ph.Compression)
	if err != nil {
		return errors.WithStack(err)
	}

	targetContainer := &tlc.Container{}
	err = rctx.ReadMessage(targetContainer)
	if err != nil {
		return errors.WithStack(err)
	}
	rc.TargetContainer = targetContainer

	sourceContainer := &tlc.Container{}
	err = rctx.ReadMessage(sourceContainer)
	if err != nil {
		return errors.WithStack(err)
	}
	rc.SourceContainer = sourceContainer

	rop := &SyncOp{}

	targetPathsToIndex := make(map[string]int64)
	for targetFileIndex, file := range targetContainer.Files {
		targetPathsToIndex[file.Path] = int64(targetFileIndex)
	}

	rc.DiffMappings = make(DiffMappings)

	var doneBytes int64

	sh := &SyncHeader{}

	for sourceFileIndex, sourceFile := range sourceContainer.Files {
		sh.Reset()
		err = rctx.ReadMessage(sh)
		if err != nil {
			return errors.WithStack(err)
		}

		if sh.FileIndex != int64(sourceFileIndex) {
			return errors.WithStack(fmt.Errorf("Malformed patch, expected index %d, got %d", sourceFileIndex, sh.FileIndex))
		}

		rc.Consumer.ProgressLabel(sourceFile.Path)
		rc.Consumer.Progress(float64(doneBytes) / float64(sourceContainer.Size))

		bytesReusedPerFileIndex := make(FileOrigin)
		readingOps := true
		var numBlockRange int64
		var numData int64

		for readingOps {
			rop.Reset()
			err = rctx.ReadMessage(rop)
			if err != nil {
				return errors.WithStack(err)
			}

			switch rop.Type {
			case SyncOp_BLOCK_RANGE:
				numBlockRange++
				alreadyReused := bytesReusedPerFileIndex[rop.FileIndex]
				lastBlockIndex := rop.BlockIndex + rop.BlockSpan
				targetFile := targetContainer.Files[rop.FileIndex]
				lastBlockSize := ComputeBlockSize(targetFile.Size, lastBlockIndex)
				otherBlocksSize := BlockSize*rop.BlockSpan - 1

				bytesReusedPerFileIndex[rop.FileIndex] = alreadyReused + otherBlocksSize + lastBlockSize

			case SyncOp_DATA:
				numData++

			default:
				switch rop.Type {
				case SyncOp_HEY_YOU_DID_IT:
					readingOps = false
				default:
					return errors.WithStack(ErrMalformedPatch)
				}
			}
		}

		if numBlockRange == 1 && numData == 0 && !rc.ForceMapAll {
			// transpositions (renames, etc.) don't need bsdiff'ing :)
		} else {
			var diffMapping *DiffMapping

			for targetFileIndex, numBytes := range bytesReusedPerFileIndex {
				targetFile := targetContainer.Files[targetFileIndex]
				// first, better, or equal target file with same name (prefer natural mappings)
				if diffMapping == nil || numBytes > diffMapping.NumBytes || (numBytes == diffMapping.NumBytes && targetFile.Path == sourceFile.Path) {
					diffMapping = &DiffMapping{
						TargetIndex: targetFileIndex,
						NumBytes:    numBytes,
					}
				}
			}

			if diffMapping == nil {
				// even without any common blocks, bsdiff might still be worth it
				// if the file is named the same
				if samePathTargetFileIndex, ok := targetPathsToIndex[sourceFile.Path]; ok {
					targetFile := targetContainer.Files[samePathTargetFileIndex]

					// don't take into account files that were 0 bytes (it happens). bsdiff won't like that.
					if targetFile.Size > 0 {
						diffMapping = &DiffMapping{
							TargetIndex: samePathTargetFileIndex,
							NumBytes:    0,
						}
					}
				}
			}

			if sourceFile.Size > rc.RediffSizeLimit {
				// source file is too large, skip rediff
				diffMapping = nil
			}

			if diffMapping != nil {
				targetFile := targetContainer.Files[diffMapping.TargetIndex]
				if targetFile.Size > rc.RediffSizeLimit {
					// target file is too large, skip rediff
					diffMapping = nil
				}
			}

			if diffMapping != nil {
				rc.DiffMappings[int64(sourceFileIndex)] = diffMapping
			}
		}

		doneBytes += sourceFile.Size
	}

	return nil
}
1111112
func ErrorToAPIStatus(err error) *metav1.Status {
	switch t := err.(type) {
	case statusError:
		status := t.Status()
		if len(status.Status) == 0 {
			status.Status = metav1.StatusFailure
		}
		switch status.Status {
		case metav1.StatusSuccess:
			if status.Code == 0 {
				status.Code = http.StatusOK
			}
		case metav1.StatusFailure:
			if status.Code == 0 {
				status.Code = http.StatusInternalServerError
			}
		default:
			runtime.HandleError(fmt.Errorf("apiserver received an error with wrong status field : %#+v", err))
			if status.Code == 0 {
				status.Code = http.StatusInternalServerError
			}
		}
		status.Kind = "Status"
		status.APIVersion = "v1"
		//TODO: check for invalid responses
		return &status
	default:
		status := http.StatusInternalServerError
		switch {
		//TODO: replace me with NewConflictErr
		case storage.IsConflict(err):
			status = http.StatusConflict
		}
		// Log errors that were not converted to an error status
		// by REST storage - these typically indicate programmer
		// error by not using pkg/api/errors, or unexpected failure
		// cases.
		runtime.HandleError(fmt.Errorf("apiserver received an error that is not an metav1.Status: %#+v", err))
		return &metav1.Status{
			TypeMeta: metav1.TypeMeta{
				Kind:       "Status",
				APIVersion: "v1",
			},
			Status:  metav1.StatusFailure,
			Code:    int32(status),
			Reason:  metav1.StatusReasonUnknown,
			Message: err.Error(),
		}
	}
}
1045312
func InterpretGetError(err error, qualifiedResource unversioned.GroupResource, name string) error {
	switch {
	case storage.IsNotFound(err):
		return errors.NewNotFound(qualifiedResource, name)
	case storage.IsUnreachable(err):
		return errors.NewServerTimeout(qualifiedResource, "get", 2) // TODO: make configurable or handled at a higher level
	default:
		return err
	}
}
225012
func InterpretMessageRange(imapMessageRange string) (seqRange SequenceRange, err error) {
	result := rangeRegexp.FindStringSubmatch(imapMessageRange)
	if len(result) == 0 {
		return SequenceRange{}, errInvalidRangeString(imapMessageRange)
	}

	first := SequenceNumber(result[1])
	second := SequenceNumber(result[2])

	// Reduce *:* to *
	if first.Last() && second.Last() {
		return SequenceRange{Min: SequenceNumber("*"), Max: SequenceNumber("")}, nil
	}

	// Ensure "*" is always placed in 'Max'
	if first.Last() && !second.Nil() {
		return SequenceRange{Min: second, Max: first}, nil
	}

	// If both sequence numbers are integer values, we need to sort them
	if first.IsValue() && second.IsValue() {
		firstVal, _ := first.Value()
		secondVal, _ := second.Value()
		if firstVal > secondVal {
			return SequenceRange{Min: second, Max: first}, nil
		}
	}

	return SequenceRange{Min: first, Max: second}, nil
}
288352
func (c *StatusCommand) logMultiMatchError(id string, matches map[contexts.Context][]string) {
	c.Ui.Error(fmt.Sprintf("Multiple matches found for id %q", id))
	for ctx, vers := range matches {
		if len(vers) == 0 {
			continue
		}

		c.Ui.Error(fmt.Sprintf("\n%s:", strings.Title(string(ctx))))
		c.Ui.Error(fmt.Sprintf("%s", strings.Join(vers, ", ")))
	}
}
122474
func WrapAPIError(err error) error {
	if IsTransientAPIError(err) {
		return transient.Tag.Apply(err)
	}
	return err
}
1313232
func IsInvalidPatch(err error) bool {
	switch err := err.(type) {
	case *Error:
		return err.Code == InvalidPatchErr
	}
	return false
}
203088
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...)
}
1159238
func MaybeTermsAgreementError(err error) error {
	const code = "term agreement required"
	e, ok := errors.Cause(err).(*httpbakery.DischargeError)
	if !ok || e.Reason == nil || e.Reason.Code != code {
		return err
	}
	magicMarker := code + ":"
	index := strings.LastIndex(e.Reason.Message, magicMarker)
	if index == -1 {
		return err
	}
	return &TermsRequiredError{strings.Fields(e.Reason.Message[index+len(magicMarker):])}
}
1329527
func IsRequestEntityTooLargeError(err error) bool {
	if ReasonForError(err) == metav1.StatusReasonRequestEntityTooLarge {
		return true
	}
	switch t := err.(type) {
	case APIStatus:
		return t.Status().Code == http.StatusRequestEntityTooLarge
	}
	return false
}
842669
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
	}

	return newS, nil
}
1255459
func StrategicMergePatch(original, patch []byte, dataStruct interface{}) ([]byte, error) {
	if original == nil {
		original = []byte{}
	}

	if patch == nil {
		patch = []byte{}
	}

	originalMap := map[string]interface{}{}
	err := json.Unmarshal(original, &originalMap)
	if err != nil {
		return nil, errBadJSONDoc
	}

	patchMap := map[string]interface{}{}
	err = json.Unmarshal(patch, &patchMap)
	if err != nil {
		return nil, errBadJSONDoc
	}

	t, err := getTagStructType(dataStruct)
	if err != nil {
		return nil, err
	}

	result, err := mergeMap(originalMap, patchMap, t)
	if err != nil {
		return nil, err
	}

	return json.Marshal(result)
}
358206
func (h *ScraperHandler) handlePatchScraperTarget(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	update, err := decodeScraperTargetUpdateRequest(ctx, r)
	if err != nil {
		EncodeError(ctx, err, w)
		return
	}

	target, err := h.ScraperStorageService.UpdateTarget(ctx, update)
	if err != nil {
		EncodeError(ctx, err, w)
		return
	}

	if err := encodeResponse(ctx, w, http.StatusOK, newTargetResponse(*target)); err != nil {
		logEncodingError(h.Logger, r, err)
		return
	}
}
762584
func (gc *GarbageCollector) unblockOwnerReferencesJSONMergePatch(n *node) ([]byte, error) {
	accessor, err := gc.getMetadata(n.identity.APIVersion, n.identity.Kind, n.identity.Namespace, n.identity.Name)
	if err != nil {
		return nil, err
	}
	expectedObjectMeta := ObjectMetaForPatch{}
	expectedObjectMeta.ResourceVersion = accessor.GetResourceVersion()
	var expectedOwners []metav1.OwnerReference
	falseVar := false
	for _, owner := range n.owners {
		owner.BlockOwnerDeletion = &falseVar
		expectedOwners = append(expectedOwners, owner)
	}
	expectedObjectMeta.OwnerReferences = expectedOwners
	return json.Marshal(objectForPatch{expectedObjectMeta})
}
771774
func (m *nativeGitClient) goGitFetch() error {
	repo, err := git.PlainOpen(m.root)
	if err != nil {
		return err
	}

	log.Debug("git fetch origin --tags --force")
	err = repo.Fetch(&git.FetchOptions{
		RemoteName: git.DefaultRemoteName,
		Auth:       m.auth,
		Tags:       git.AllTags,
		Force:      true,
	})
	if err == git.NoErrAlreadyUpToDate {
		return nil
	}
	return err
}