diff --git a/protovalidate/internal/field_path.py b/protovalidate/internal/field_path.py new file mode 100644 index 0000000..22173df --- /dev/null +++ b/protovalidate/internal/field_path.py @@ -0,0 +1,36 @@ +# Copyright 2023 Buf Technologies, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from buf.validate import validate_pb2 +from . import string_format + + +def string(path: validate_pb2.FieldPath) -> str: + result: list[str] = [] + for element in path.elements: + if len(result) > 0: + result.append(".") + subscript_case = element.WhichOneof("subscript") + if subscript_case is not None: + result.extend( + ( + element.field_name, + "[", + string_format.format_value(getattr(element, subscript_case)), + "]", + ) + ) + else: + result.append(element.field_name) + return "".join(result) diff --git a/protovalidate/validator.py b/protovalidate/validator.py index 7e3b1a7..12253cb 100644 --- a/protovalidate/validator.py +++ b/protovalidate/validator.py @@ -16,7 +16,7 @@ from buf.validate import validate_pb2 # type: ignore from protovalidate.internal import constraints as _constraints -from protovalidate.internal import extra_func, string_format +from protovalidate.internal import extra_func, field_path CompilationError = _constraints.CompilationError Violations = validate_pb2.Violations @@ -89,29 +89,9 @@ def collect_violations( violation.field.elements.reverse() if violation.HasField("rule"): violation.rule.elements.reverse() - violation.field_path = Validator._field_path_string(violation.field) + violation.field_path = field_path.string(violation.field) return ctx.violations - @classmethod - def _field_path_string(cls, path: validate_pb2.FieldPath) -> str: - result: list[str] = [] - for element in path.elements: - if len(result) > 0: - result.append(".") - subscript_case = element.WhichOneof("subscript") - if subscript_case is not None: - result.extend( - ( - element.field_name, - "[", - string_format.format_value(getattr(element, subscript_case)), - "]", - ) - ) - else: - result.append(element.field_name) - return "".join(result) - class ValidationError(ValueError): """