Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions docs/cli-reference/general-options.md
Original file line number Diff line number Diff line change
Expand Up @@ -1896,7 +1896,9 @@ comparison, not continuous watching.

??? example "Output"

> **Error:** File not found: /home/runner/work/datamodel-code-generator/datamodel-code-generator/tests/data/expected/Error: --watch and --check cannot be used together
```
Error: --watch and --check cannot be used together
```

---

Expand Down Expand Up @@ -1950,7 +1952,9 @@ rapid file changes. Press Ctrl+C to stop watching.

??? example "Output"

> **Error:** File not found: /home/runner/work/datamodel-code-generator/datamodel-code-generator/tests/data/expected/Watching
```
Watching
```

---

19 changes: 13 additions & 6 deletions scripts/build_cli_docs.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ def safe_read_file(base_path: Path, relative_path: str, file_types: tuple[str, .
raise ValueError(msg) from None

if not full_path.exists():
msg = f"File not found: {full_path}"
msg = f"File not found: {relative_path}"
raise FileNotFoundError(msg)

if full_path.is_dir():
Expand Down Expand Up @@ -312,14 +312,21 @@ def generate_option_section(

md += '??? example "Output"\n\n'
if "expected_stdout" in kwargs:
try:
content = read_expected_file(kwargs["expected_stdout"])
stdout_value = kwargs["expected_stdout"]
if "/" in stdout_value or stdout_value.endswith((".py", ".txt")):
try:
content = read_expected_file(stdout_value)
md += " ```\n"
for line in content.strip().split("\n"):
md += f" {line}\n" if line else " \n"
md += " ```\n\n"
except (FileNotFoundError, ValueError) as e:
md += f" > **Error:** {e}\n\n"
else:
md += " ```\n"
for line in content.strip().split("\n"):
for line in stdout_value.strip().split("\n"):
md += f" {line}\n" if line else " \n"
md += " ```\n\n"
except (FileNotFoundError, ValueError) as e:
md += f" > **Error:** {e}\n\n"
elif "comparison_output" in kwargs and "model_outputs" in kwargs:
model_labels = {
"pydantic_v1": "Pydantic v1",
Expand Down
1 change: 1 addition & 0 deletions src/datamodel_code_generator/parser/jsonschema.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ def get_model_by_path(
"decimal": Types.decimal,
"date-time": Types.date_time,
"time": Types.time,
"time-delta": Types.timedelta,
"default": Types.number,
},
"string": {
Expand Down
17 changes: 17 additions & 0 deletions tests/data/expected/main/jsonschema/time_delta_msgspec.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# generated by datamodel-codegen:
# filename: time_delta.json
# timestamp: 2019-07-26T00:00:00+00:00

from __future__ import annotations

from datetime import timedelta
from typing import Any, Union

from msgspec import UNSET, Struct, UnsetType
from typing_extensions import TypeAlias

Model: TypeAlias = Any


class Test(Struct):
n_timedelta: Union[timedelta, UnsetType] = UNSET
18 changes: 18 additions & 0 deletions tests/data/expected/main/jsonschema/time_delta_pydantic_v2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# generated by datamodel-codegen:
# filename: time_delta.json
# timestamp: 2019-07-26T00:00:00+00:00

from __future__ import annotations

from datetime import timedelta
from typing import Any, Optional

from pydantic import BaseModel, RootModel


class Model(RootModel[Any]):
root: Any


class Test(BaseModel):
n_timedelta: Optional[timedelta] = None
14 changes: 14 additions & 0 deletions tests/data/jsonschema/time_delta.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"Test": {
"type": "object",
"properties": {
"n_timedelta": {
"type": "number",
"format": "time-delta"
}
}
}
}
}
27 changes: 27 additions & 0 deletions tests/main/jsonschema/test_main_jsonschema.py
Original file line number Diff line number Diff line change
Expand Up @@ -3135,6 +3135,33 @@ def test_main_jsonschema_duration(output_model: str, expected_output: str, min_v
)


@pytest.mark.parametrize(
("output_model", "expected_output"),
[
(
"pydantic_v2.BaseModel",
"time_delta_pydantic_v2.py",
),
(
"msgspec.Struct",
"time_delta_msgspec.py",
),
],
)
def test_main_jsonschema_time_delta(
output_model: str, expected_output: str, min_version: str, output_file: Path
) -> None:
"""Test time-delta type handling for number format."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "time_delta.json",
output_path=output_file,
input_file_type=None,
assert_func=assert_file_content,
expected_file=expected_output,
extra_args=["--output-model-type", output_model, "--target-python", min_version],
)


@pytest.mark.skipif(
int(black.__version__.split(".")[0]) < 24,
reason="Installed black doesn't support the new style",
Expand Down
2 changes: 2 additions & 0 deletions tests/parser/test_jsonschema.py
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,8 @@ def test_parse_nested_array(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) ->
("string", "date-time", "DateTime", "pendulum", "DateTime", True),
("string", "duration", "timedelta", "datetime", "timedelta", False),
("string", "duration", "Duration", "pendulum", "Duration", True),
("number", "time-delta", "timedelta", "datetime", "timedelta", False),
("number", "time-delta", "Duration", "pendulum", "Duration", True),
("string", "path", "Path", "pathlib", "Path", False),
("string", "password", "SecretStr", "pydantic", "SecretStr", False),
("string", "email", "EmailStr", "pydantic", "EmailStr", False),
Expand Down
Loading