Skip to content

Commit d347d29

Browse files
committed
[ts_utils] Update jsonc_to_json function
1 parent 84c2067 commit d347d29

File tree

2 files changed

+28
-8
lines changed

2 files changed

+28
-8
lines changed

lib/ts_utils/utils.py

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,20 +28,40 @@ def colored(text: str, color: str | None = None, **kwargs: Any) -> str: # type:
2828
return text
2929

3030

31+
_REMOVE_COMMENT_RE = re.compile(
32+
r"""
33+
(\"(?:\\.|[^\\\"])*?\")
34+
|
35+
(\/\*.*?\*\/ | \/\/[^\r\n]*?(?:[\r\n]))
36+
""",
37+
re.DOTALL | re.VERBOSE,
38+
)
39+
_REMOVE_TRAILING_COMMA_RE = re.compile(
40+
r"""
41+
(\"(?:\\.|[^\\\"])*?\")
42+
|
43+
,\s*([\]}])
44+
""",
45+
re.DOTALL | re.VERBOSE,
46+
)
47+
48+
3149
PYTHON_VERSION: Final = f"{sys.version_info.major}.{sys.version_info.minor}"
3250

3351

3452
def strip_comments(text: str) -> str:
3553
return text.split("#")[0].strip()
3654

3755

38-
def json5_to_json(text: str) -> str:
39-
"""Incomplete conversion from JSON5-like input to valid JSON."""
40-
# Remove full-line // comments only
41-
# (Can not remove inline comments)
42-
text = re.sub(r"(?m)^\s*//.*\n?", "", text)
56+
def jsonc_to_json(text: str) -> str:
57+
"""Conversion from JSONC format input to valid JSON."""
58+
# Remove comments
59+
if not text.endswith("\n"):
60+
text += "\n"
61+
text = _REMOVE_COMMENT_RE.sub(lambda m: m.group(1) or "", text)
62+
4363
# Remove trailing commas before } or ]
44-
text = re.sub(r",\s*([}\]])", r"\1", text)
64+
text = _REMOVE_TRAILING_COMMA_RE.sub(lambda m: m.group(1) or m.group(2), text)
4565
return text
4666

4767

tests/check_typeshed_structure.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
from ts_utils.utils import (
1818
get_all_testcase_directories,
1919
get_gitignore_spec,
20-
json5_to_json,
20+
jsonc_to_json,
2121
parse_requirements,
2222
parse_stdlib_versions_file,
2323
spec_matches_path,
@@ -178,7 +178,7 @@ def check_requirement_pins() -> None:
178178
def check_pyright_exclude_order() -> None:
179179
"""Check that 'exclude' entries in pyrightconfig.stricter.json are sorted alphabetically."""
180180
text = PYRIGHT_CONFIG.read_text(encoding="utf-8")
181-
text = json5_to_json(text)
181+
text = jsonc_to_json(text)
182182
data = json.loads(text)
183183
exclude: list[str] = data.get("exclude", [])
184184

0 commit comments

Comments
 (0)