Skip to content

Commit 52e617d

Browse files
authored
Generically handle all entities in DocGen entity expansion. (#130)
1 parent 37d262e commit 52e617d

File tree

5 files changed

+46
-46
lines changed

5 files changed

+46
-46
lines changed

aws_doc_sdk_examples_tools/doc_gen.py

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import json
66

77
from collections import defaultdict
8-
from dataclasses import dataclass, field, is_dataclass, asdict
8+
from dataclasses import dataclass, field, fields, is_dataclass, asdict
99
from functools import reduce
1010
from pathlib import Path
1111
from typing import Dict, Iterable, Optional, Set, Tuple, List, Any
@@ -90,6 +90,24 @@ def languages(self) -> Set[str]:
9090
def expand_entities(self, text: str) -> Tuple[str, EntityErrors]:
9191
return expand_all_entities(text, self.entities)
9292

93+
def expand_entity_fields(self, obj: object):
94+
if isinstance(obj, list):
95+
for o in obj:
96+
self.expand_entity_fields(o)
97+
if isinstance(obj, dict):
98+
for val in obj.values():
99+
self.expand_entity_fields(val)
100+
if is_dataclass(obj) and not isinstance(obj, type):
101+
for f in fields(obj):
102+
val = getattr(obj, f.name)
103+
if isinstance(val, str):
104+
[expanded, errs] = self.expand_entities(val)
105+
if errs:
106+
self.errors.extend(errs)
107+
else:
108+
setattr(obj, f.name, expanded)
109+
self.expand_entity_fields(val)
110+
93111
def merge(self, other: "DocGen") -> MetadataErrors:
94112
"""Merge fields from other into self, prioritizing self fields."""
95113
warnings = MetadataErrors()
@@ -332,7 +350,7 @@ def count_genai(d: Dict[str, int], e: Example):
332350
# and arguably not useful either.
333351
class DocGenEncoder(json.JSONEncoder):
334352
def default(self, obj):
335-
if is_dataclass(obj):
353+
if is_dataclass(obj) and not isinstance(obj, type):
336354
return asdict(obj)
337355

338356
if isinstance(obj, Path):

aws_doc_sdk_examples_tools/doc_gen_cli.py

Lines changed: 4 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -48,43 +48,13 @@ def main():
4848
unmerged_doc_gen = DocGen.from_root(Path(root))
4949
merged_doc_gen.merge(unmerged_doc_gen)
5050

51-
if args.strict and merged_doc_gen.errors:
52-
logging.error("Errors found in metadata: %s", merged_doc_gen.errors)
53-
exit(1)
54-
5551
if not args.skip_entity_expansion:
5652
# Replace entities
57-
for example in merged_doc_gen.examples.values():
58-
errors = EntityErrors()
59-
title, title_errors = merged_doc_gen.expand_entities(example.title)
60-
errors.extend(title_errors)
61-
62-
title_abbrev, title_abbrev_errors = merged_doc_gen.expand_entities(
63-
example.title_abbrev
64-
)
65-
errors.extend(title_abbrev_errors)
66-
67-
synopsis, synopsis_errors = merged_doc_gen.expand_entities(example.synopsis)
68-
errors.extend(synopsis_errors)
53+
merged_doc_gen.expand_entity_fields(merged_doc_gen)
6954

70-
synopsis_list = []
71-
for synopsis in example.synopsis_list:
72-
expanded_synopsis, synopsis_errors = merged_doc_gen.expand_entities(
73-
synopsis
74-
)
75-
synopsis_list.append(expanded_synopsis)
76-
errors.extend(synopsis_errors)
77-
78-
if args.strict and errors:
79-
logging.error(
80-
f"Errors expanding entities for example: {example}. {errors}"
81-
)
82-
exit(1)
83-
84-
example.title = title
85-
example.title_abbrev = title_abbrev
86-
example.synopsis = synopsis
87-
example.synopsis_list = synopsis_list
55+
if args.strict and merged_doc_gen.errors:
56+
logging.error("Errors found in metadata: %s", merged_doc_gen.errors)
57+
exit(1)
8858

8959
serialized = json.dumps(merged_doc_gen, cls=DocGenEncoder)
9060

aws_doc_sdk_examples_tools/doc_gen_test.py

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -80,13 +80,16 @@ def sample_doc_gen() -> DocGen:
8080
root=Path("/test/root"),
8181
errors=metadata_errors,
8282
prefix="test_prefix",
83-
entities={"&S3long;": "Amazon Simple Storage Service", "&S3;": "Amazon S3"},
83+
entities={
84+
"&S3long;": "Amazon Simple Storage Service",
85+
"&S3;": "Amazon S3",
86+
"&PYLong;": "Python SDK v1",
87+
"&PYShort;": "Python V1",
88+
},
8489
sdks={
8590
"python": Sdk(
8691
name="python",
87-
versions=[
88-
SdkVersion(version=1, long="Python SDK v1", short="Python v1")
89-
],
92+
versions=[SdkVersion(version=1, long="&PYLong;", short="&PYShort;")],
9093
guide="Python Guide",
9194
property="python",
9295
)
@@ -123,6 +126,15 @@ def test_expand_entities(sample_doc_gen: DocGen):
123126
assert not errors
124127

125128

129+
def test_expand_entity_fields(sample_doc_gen: DocGen):
130+
error_count = len(sample_doc_gen.errors)
131+
sample_doc_gen.expand_entity_fields(sample_doc_gen)
132+
assert sample_doc_gen.services["s3"].long == "Amazon Simple Storage Service"
133+
assert sample_doc_gen.sdks["python"].versions[0].long == "Python SDK v1"
134+
# The fixture has an error, so make sure we don't have _more_ errors.
135+
assert error_count == len(sample_doc_gen.errors)
136+
137+
126138
def test_doc_gen_encoder(sample_doc_gen: DocGen):
127139
encoded = json.dumps(sample_doc_gen, cls=DocGenEncoder)
128140
decoded = json.loads(encoded)
@@ -137,7 +149,7 @@ def test_doc_gen_encoder(sample_doc_gen: DocGen):
137149
assert decoded["sdks"]["python"]["name"] == "python"
138150
assert decoded["sdks"]["python"]["guide"] == "Python Guide"
139151
assert decoded["sdks"]["python"]["versions"][0]["version"] == 1
140-
assert decoded["sdks"]["python"]["versions"][0]["long"] == "Python SDK v1"
152+
assert decoded["sdks"]["python"]["versions"][0]["long"] == "&PYLong;"
141153

142154
# Verify service information
143155
assert "services" in decoded

aws_doc_sdk_examples_tools/entities.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,16 @@
22
from dataclasses import dataclass
33
import re
44

5-
from .metadata_errors import ErrorsList
5+
from .metadata_errors import ErrorsList, MetadataError
66

77

88
@dataclass
9-
class EntityError(Exception):
9+
class EntityError(MetadataError):
1010
"""
1111
Base error. Do not use directly.
1212
"""
1313

14-
entity: Optional[str]
14+
entity: Optional[str] = None
1515

1616
def message(self) -> str:
1717
return ""
@@ -54,4 +54,4 @@ def expand_entity(
5454
if expanded is not None:
5555
return entity.replace(entity, expanded), None
5656
else:
57-
return entity, MissingEntityError(entity)
57+
return entity, MissingEntityError(entity=entity)

aws_doc_sdk_examples_tools/entities_test.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
def test_entity_errors_append():
1111
errors = EntityErrors()
12-
errors.append(MissingEntityError("entity1"))
12+
errors.append(MissingEntityError(entity="entity1"))
1313
assert len(errors._errors) == 1
1414
assert errors._errors[0].entity == "entity1"
1515

0 commit comments

Comments
 (0)