Skip to content

Commit ae88e3a

Browse files
authored
Fix internal reference resolution for stdin JSON Schema input (#2578)
1 parent 8f78a9b commit ae88e3a

4 files changed

Lines changed: 47 additions & 1 deletion

File tree

src/datamodel_code_generator/reference.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,8 @@ def short_name(self) -> str:
175175

176176
ID_PATTERN: Pattern[str] = re.compile(r"^#[^/].*")
177177

178+
SPECIAL_PATH_MARKER: str = "#-datamodel-code-generator-#-"
179+
178180
T = TypeVar("T")
179181

180182

@@ -509,7 +511,7 @@ def resolve_ref(self, path: Sequence[str] | str) -> str: # noqa: PLR0911, PLR09
509511
joined_path = get_relative_path(self._base_path, resolved_file_path).as_posix()
510512
if fragment:
511513
joined_path += f"#{fragment}"
512-
if ID_PATTERN.match(joined_path):
514+
if ID_PATTERN.match(joined_path) and SPECIAL_PATH_MARKER not in joined_path:
513515
id_scope = "/".join(self.current_root)
514516
scoped_ids = self.ids[id_scope]
515517
ref: str | None = scoped_ids.get(joined_path)
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# generated by datamodel-codegen:
2+
# filename: <stdin>
3+
# timestamp: 2019-07-26T00:00:00+00:00
4+
5+
from __future__ import annotations
6+
7+
from typing import Optional
8+
9+
from pydantic import BaseModel
10+
11+
12+
class Test(BaseModel):
13+
name: Optional[str] = None
14+
15+
16+
class Model(BaseModel):
17+
__root__: Test
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
{
2+
"$schema": "https://json-schema.org/draft/2019-09/schema",
3+
"type": "object",
4+
"oneOf": [
5+
{ "$ref": "#/definitions/test" }
6+
],
7+
"definitions": {
8+
"test": {
9+
"type": "object",
10+
"properties": {
11+
"name": { "type": "string" }
12+
}
13+
}
14+
}
15+
}

tests/main/jsonschema/test_main_jsonschema.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -561,6 +561,18 @@ def test_main_jsonschema_id_as_stdin(monkeypatch: pytest.MonkeyPatch, output_fil
561561
)
562562

563563

564+
def test_main_jsonschema_stdin_oneof_ref(monkeypatch: pytest.MonkeyPatch, output_file: Path) -> None:
565+
"""Test JSON Schema with oneOf $ref from stdin."""
566+
run_main_and_assert(
567+
stdin_path=JSON_SCHEMA_DATA_PATH / "stdin_oneof_ref.json",
568+
output_path=output_file,
569+
monkeypatch=monkeypatch,
570+
input_file_type="jsonschema",
571+
assert_func=assert_file_content,
572+
expected_file="stdin_oneof_ref.py",
573+
)
574+
575+
564576
def test_main_jsonschema_ids(output_dir: Path) -> None:
565577
"""Test JSON Schema with multiple IDs."""
566578
with freeze_time(TIMESTAMP):

0 commit comments

Comments
 (0)