Skip to content

Commit 4426918

Browse files
committed
feat: helpers for formatting
1 parent a69bc75 commit 4426918

1 file changed

Lines changed: 64 additions & 0 deletions

File tree

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
# Copyright 2025 Google LLC
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+
"""Formatting helper functions for Chronicle."""
16+
17+
import json
18+
from typing import Any
19+
20+
from secops.exceptions import APIError
21+
22+
23+
def format_resource_id(resource_id: str) -> str:
24+
"""Extracts the correct ID for a resource string when the full
25+
resource name is provided.
26+
27+
Example:
28+
full resource string:
29+
"projects/12345/locations/eu/instances/.../123-ID-abc"
30+
extracted ID: "123-ID-abc"
31+
32+
Args:
33+
resource_id: The full resource string or just the ID.
34+
35+
Returns:
36+
The extracted ID from the resource string, or the original string if it doesn't match the expected format.
37+
"""
38+
if resource_id.startswith("projects/"):
39+
return resource_id.split("projects/")[-1]
40+
return resource_id
41+
42+
43+
def parse_json_list(
44+
value: list[dict[str, Any]] | str, field_name: str
45+
) -> list[dict[str, Any]]:
46+
"""Parse a JSON string into a list, or return the list as-is.
47+
48+
Args:
49+
value: A list of dictionaries or a JSON string representing a list of dictionaries.
50+
field_name: The name of the field being parsed, used for error messages.
51+
52+
Returns:
53+
A list of dictionaries parsed from the JSON string, or the original list if it was already a list.
54+
55+
Raises:
56+
APIError: If the input is a string but cannot be parsed as valid JSON.
57+
"""
58+
if isinstance(value, str):
59+
try:
60+
parsed = json.loads(value)
61+
return parsed if isinstance(parsed, list) else [parsed]
62+
except ValueError as e:
63+
raise APIError(f"Invalid {field_name} JSON") from e
64+
return value

0 commit comments

Comments
 (0)