Skip to content

Commit

Permalink
Extract _field_path_string into internal
Browse files Browse the repository at this point in the history
  • Loading branch information
jchadwick-buf committed Nov 26, 2024
1 parent 47775ea commit 069935c
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 22 deletions.
36 changes: 36 additions & 0 deletions protovalidate/internal/field_path.py
Original file line number Diff line number Diff line change
@@ -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)
24 changes: 2 additions & 22 deletions protovalidate/validator.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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):
"""
Expand Down

0 comments on commit 069935c

Please sign in to comment.