Split JSON patch out into a new module (#99)

Co-authored-by: Abhijeet Kasurde <akasurde@redhat.com>
This commit is contained in:
Mike Graves
2021-05-24 08:35:48 -04:00
committed by GitHub
parent 1f47931c7c
commit 5b5777d202
7 changed files with 467 additions and 151 deletions

View File

@@ -97,17 +97,6 @@ except ImportError as e:
K8S_IMP_ERR = traceback.format_exc()
JSON_PATCH_IMP_ERR = None
try:
import jsonpatch
HAS_JSON_PATCH = True
jsonpatch_import_exception = None
except ImportError as e:
HAS_JSON_PATCH = False
jsonpatch_import_exception = e
JSON_PATCH_IMP_ERR = traceback.format_exc()
def configuration_digest(configuration):
m = hashlib.sha256()
for k in AUTH_ARG_MAP:
@@ -841,42 +830,16 @@ class K8sAnsibleMixin(object):
self.fail_json(msg=msg, **result)
return result
def json_patch(self, existing, definition, merge_type):
if merge_type == "json":
if not HAS_JSON_PATCH:
error = {
"msg": missing_required_lib('jsonpatch'),
"exception": JSON_PATCH_IMP_ERR,
"error": to_native(jsonpatch_import_exception)
}
return None, error
try:
patch = jsonpatch.JsonPatch([definition])
result_patch = patch.apply(existing.to_dict())
return result_patch, None
except jsonpatch.InvalidJsonPatch as e:
error = {
"msg": "invalid json patch",
"error": to_native(e)
}
return None, error
except jsonpatch.JsonPatchConflict as e:
error = {
"msg": "patch could not be applied due to conflict situation",
"error": to_native(e)
}
return None, error
return definition, None
def patch_resource(self, resource, definition, existing, name, namespace, merge_type=None):
if merge_type == "json":
self.module.deprecate(
msg="json as a merge_type value is deprecated. Please use the k8s_json_patch module instead.",
version="3.0.0", collection_name="kubernetes.core")
try:
params = dict(name=name, namespace=namespace)
if merge_type:
params['content_type'] = 'application/{0}-patch+json'.format(merge_type)
patch_data, error = self.json_patch(existing, definition, merge_type)
if error is not None:
return None, error
k8s_obj = resource.patch(patch_data, **params).to_dict()
k8s_obj = resource.patch(definition, **params).to_dict()
match, diffs = self.diff_objects(existing.to_dict(), k8s_obj)
error = {}
return k8s_obj, {}