Skip to content

Commit 069935c

Browse files
author
John Chadwick
committed
Extract _field_path_string into internal
1 parent 47775ea commit 069935c

File tree

2 files changed

+38
-22
lines changed

2 files changed

+38
-22
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# Copyright 2023 Buf Technologies, Inc.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
from buf.validate import validate_pb2
16+
from . import string_format
17+
18+
19+
def string(path: validate_pb2.FieldPath) -> str:
20+
result: list[str] = []
21+
for element in path.elements:
22+
if len(result) > 0:
23+
result.append(".")
24+
subscript_case = element.WhichOneof("subscript")
25+
if subscript_case is not None:
26+
result.extend(
27+
(
28+
element.field_name,
29+
"[",
30+
string_format.format_value(getattr(element, subscript_case)),
31+
"]",
32+
)
33+
)
34+
else:
35+
result.append(element.field_name)
36+
return "".join(result)

protovalidate/validator.py

Lines changed: 2 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616

1717
from buf.validate import validate_pb2 # type: ignore
1818
from protovalidate.internal import constraints as _constraints
19-
from protovalidate.internal import extra_func, string_format
19+
from protovalidate.internal import extra_func, field_path
2020

2121
CompilationError = _constraints.CompilationError
2222
Violations = validate_pb2.Violations
@@ -89,29 +89,9 @@ def collect_violations(
8989
violation.field.elements.reverse()
9090
if violation.HasField("rule"):
9191
violation.rule.elements.reverse()
92-
violation.field_path = Validator._field_path_string(violation.field)
92+
violation.field_path = field_path.string(violation.field)
9393
return ctx.violations
9494

95-
@classmethod
96-
def _field_path_string(cls, path: validate_pb2.FieldPath) -> str:
97-
result: list[str] = []
98-
for element in path.elements:
99-
if len(result) > 0:
100-
result.append(".")
101-
subscript_case = element.WhichOneof("subscript")
102-
if subscript_case is not None:
103-
result.extend(
104-
(
105-
element.field_name,
106-
"[",
107-
string_format.format_value(getattr(element, subscript_case)),
108-
"]",
109-
)
110-
)
111-
else:
112-
result.append(element.field_name)
113-
return "".join(result)
114-
11595

11696
class ValidationError(ValueError):
11797
"""

0 commit comments

Comments
 (0)