Skip to content

Commit c7f3f47

Browse files
committed
feat: use oscal_read and oscal_write for component definition update
1 parent 5a4409e commit c7f3f47

File tree

2 files changed

+20
-28
lines changed

2 files changed

+20
-28
lines changed

trestlebot/tasks/sync_cac_content_task.py

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
"""Trestle Bot Sync CaC Content Tasks"""
55

6+
import datetime
67
import json
78
import logging
89
import os
@@ -33,7 +34,6 @@
3334
RuleInfo,
3435
RulesTransformer,
3536
get_component_info,
36-
update_component_definition,
3737
)
3838

3939

@@ -190,17 +190,25 @@ def _create_or_update_compdef(self, compdef_type: str = "service") -> None:
190190
cd_json = cd_dir / "component-definition.json"
191191
if cd_json.exists():
192192
logger.info(f"The component definition for {self.product} exists.")
193-
with open(cd_json, "r", encoding="utf-8") as f:
194-
data = json.load(f)
195-
components = data["component-definition"]["components"]
196-
for index, component in enumerate(components):
197-
if component.get("title") == oscal_component.title:
198-
# The update should be skipped if no content changes
199-
logger.info(f"Update props of component {product_name}")
200-
data["component-definition"]["components"][index][
201-
"props"
202-
] = oscal_component.props
203-
update_component_definition(cd_json)
193+
compdef = ComponentDefinition.oscal_read(cd_json)
194+
updated = False
195+
for index, component in enumerate(compdef.components):
196+
if component.title == oscal_component.title:
197+
if component.props != oscal_component.props:
198+
compdef.components[index].props = oscal_component.props
199+
updated = True
200+
break
201+
if updated:
202+
logger.info(f"Update component definition: {cd_json}")
203+
compdef.metadata.version = str(
204+
"{:.1f}".format(float(compdef.metadata.version) + 0.1)
205+
)
206+
compdef.metadata.last_modified = (
207+
datetime.datetime.now(datetime.timezone.utc)
208+
.replace(microsecond=0)
209+
.isoformat()
210+
)
211+
compdef.oscal_write(cd_json)
204212
else:
205213
logger.info(f"Creating component definition for product {self.product}")
206214
cd_dir.mkdir(exist_ok=True, parents=True)

trestlebot/transformers/cac_transformer.py

Lines changed: 0 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,11 @@
33

44
"""Transform rules from existing Compliance as Code locations into OSCAL properties."""
55

6-
import datetime
76
import json
87
import logging
98
import os
109
import re
1110
from html.parser import HTMLParser
12-
from pathlib import Path
1311
from typing import Any, Dict, List, Optional, Tuple
1412

1513
import ssg.build_yaml
@@ -43,20 +41,6 @@ def get_component_info(product_name: str, cac_path: str) -> Tuple[str, str]:
4341
raise ValueError("component_title is empty or None")
4442

4543

46-
def update_component_definition(compdef_file: Path) -> None:
47-
# Update the component definition version and modify time
48-
with open(compdef_file, "r", encoding="utf-8") as f:
49-
data = json.load(f)
50-
current_version = data["component-definition"]["metadata"]["version"]
51-
data["component-definition"]["metadata"]["version"] = str(
52-
"{:.1f}".format(float(current_version) + 0.1)
53-
)
54-
current_time = datetime.datetime.now().isoformat()
55-
data["component-definition"]["metadata"]["last-modified"] = current_time
56-
with open(compdef_file, "w", encoding="utf-8") as f:
57-
json.dump(data, f, ensure_ascii=False, indent=2)
58-
59-
6044
def add_prop(name: str, value: str, remarks: Optional[str] = None) -> Property:
6145
"""Add a property to a set of rule properties."""
6246
prop = generate_sample_model(Property)

0 commit comments

Comments
 (0)