We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
msgspec: Optional fields are missing a default when using `--snake-case-field`
### Steps to reproduce
1. Download the NVD CVE [schema][schema]
2. Generate a msgpsec model:
```sh
datamodel-codegen \
    --input $schema_json \
    --input-file-type jsonschema \
    --output-model-type 'msgspec.Struct' \
   # This is important I think
    --snake-case-field \
    --output "."
```
3. (Ignore the circular imports #836)
4. (Ignore wrong field ordering #1919 
5. Look at the `class CpeMatch` (and most other classes as well).
```python
class CpeMatch(Struct, kw_only=True):
    vulnerable: bool
    criteria: str
    match_criteria_id: str = field(name='matchCriteriaId')
    version_start_excluding: Optional[str] = field(name='versionStartExcluding')
    version_start_including: Optional[str] = field(name='versionStartIncluding')
    version_end_excluding: Optional[str] = field(name='versionEndExcluding')
    version_end_including: Optional[str] = field(name='versionEndIncluding')

```
vs
```json

"cpe_match": {
	"description": "CPE match string or range",
	"type": "object",
	"properties": {
		"vulnerable": {"type": "boolean"},
		"criteria": {"type": "string"},
		"matchCriteriaId": {"type": "string", "format": "uuid"},
		"versionStartExcluding": {"type": "string"},
		"versionStartIncluding": {"type": "string"},
		"versionEndExcluding": {"type": "string"},
		"versionEndIncluding": {"type": "string"}
	},
	"required": ["vulnerable", "criteria", "matchCriteriaId"],
	"additionalProperties": false
},
```

Note that the optional fields are missing the `default=None` parameter in the `field` call.

[schema]: https://csrc.nist.gov/schema/nvd/api/2.0/cve_api_json_2.0.schema

### Expected behavior
The field should have a default of value `None`.

### Workaround
Do not use `--snake-case-field`.

### Setup

```sh
$ datamodel-codegen --version
0.25.5

$ python --version
Python 3.11.8
```


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `datamodel_code_generator/model/msgspec.py`
Content:
```
1 from functools import wraps
2 from pathlib import Path
3 from typing import (
4     Any,
5     ClassVar,
6     DefaultDict,
7     Dict,
8     List,
9     Optional,
10     Set,
11     Tuple,
12     Type,
13     TypeVar,
14 )
15 
16 from pydantic import Field
17 
18 from datamodel_code_generator.imports import Import
19 from datamodel_code_generator.model import DataModel, DataModelFieldBase
20 from datamodel_code_generator.model.base import UNDEFINED
21 from datamodel_code_generator.model.imports import (
22     IMPORT_MSGSPEC_CONVERT,
23     IMPORT_MSGSPEC_FIELD,
24     IMPORT_MSGSPEC_META,
25     IMPORT_MSGSPEC_STRUCT,
26 )
27 from datamodel_code_generator.model.pydantic.base_model import (
28     Constraints as _Constraints,
29 )
30 from datamodel_code_generator.model.rootmodel import RootModel as _RootModel
31 from datamodel_code_generator.reference import Reference
32 from datamodel_code_generator.types import chain_as_tuple, get_optional_type
33 
34 
35 def _has_field_assignment(field: DataModelFieldBase) -> bool:
36     return bool(field.field) or not (
37         field.required
38         or (field.represented_default == 'None' and field.strip_default_none)
39     )
40 
41 
42 DataModelFieldBaseT = TypeVar('DataModelFieldBaseT', bound=DataModelFieldBase)
43 
44 
45 def import_extender(cls: Type[DataModelFieldBaseT]) -> Type[DataModelFieldBaseT]:
46     original_imports: property = getattr(cls, 'imports', None)  # type: ignore
47 
48     @wraps(original_imports.fget)  # type: ignore
49     def new_imports(self: DataModelFieldBaseT) -> Tuple[Import, ...]:
50         extra_imports = []
51         if self.field:
52             extra_imports.append(IMPORT_MSGSPEC_FIELD)
53         if self.field and 'lambda: convert' in self.field:
54             extra_imports.append(IMPORT_MSGSPEC_CONVERT)
55         if self.annotated:
56             extra_imports.append(IMPORT_MSGSPEC_META)
57         return chain_as_tuple(original_imports.fget(self), extra_imports)  # type: ignore
58 
59     setattr(cls, 'imports', property(new_imports))
60     return cls
61 
62 
63 class RootModel(_RootModel):
64     pass
65 
66 
67 class Struct(DataModel):
68     TEMPLATE_FILE_PATH: ClassVar[str] = 'msgspec.jinja2'
69     BASE_CLASS: ClassVar[str] = 'msgspec.Struct'
70     DEFAULT_IMPORTS: ClassVar[Tuple[Import, ...]] = (IMPORT_MSGSPEC_STRUCT,)
71 
72     def __init__(
73         self,
74         *,
75         reference: Reference,
76         fields: List[DataModelFieldBase],
77         decorators: Optional[List[str]] = None,
78         base_classes: Optional[List[Reference]] = None,
79         custom_base_class: Optional[str] = None,
80         custom_template_dir: Optional[Path] = None,
81         extra_template_data: Optional[DefaultDict[str, Dict[str, Any]]] = None,
82         methods: Optional[List[str]] = None,
83         path: Optional[Path] = None,
84         description: Optional[str] = None,
85         default: Any = UNDEFINED,
86         nullable: bool = False,
87     ) -> None:
88         super().__init__(
89             reference=reference,
90             fields=sorted(fields, key=_has_field_assignment, reverse=False),
91             decorators=decorators,
92             base_classes=base_classes,
93             custom_base_class=custom_base_class,
94             custom_template_dir=custom_template_dir,
95             extra_template_data=extra_template_data,
96             methods=methods,
97             path=path,
98             description=description,
99             default=default,
100             nullable=nullable,
101         )
102 
103 
104 class Constraints(_Constraints):
105     # To override existing pattern alias
106     regex: Optional[str] = Field(None, alias='regex')
107     pattern: Optional[str] = Field(None, alias='pattern')
108 
109 
110 @import_extender
111 class DataModelField(DataModelFieldBase):
112     _FIELD_KEYS: ClassVar[Set[str]] = {
113         'default',
114         'default_factory',
115     }
116     _META_FIELD_KEYS: ClassVar[Set[str]] = {
117         'title',
118         'description',
119         'gt',
120         'ge',
121         'lt',
122         'le',
123         'multiple_of',
124         # 'min_items', # not supported by msgspec
125         # 'max_items', # not supported by msgspec
126         'min_length',
127         'max_length',
128         'pattern',
129         'examples',
130         # 'unique_items', # not supported by msgspec
131     }
132     _PARSE_METHOD = 'convert'
133     _COMPARE_EXPRESSIONS: ClassVar[Set[str]] = {'gt', 'ge', 'lt', 'le', 'multiple_of'}
134     constraints: Optional[Constraints] = None
135 
136     def self_reference(self) -> bool:  # pragma: no cover
137         return isinstance(self.parent, Struct) and self.parent.reference.path in {
138             d.reference.path for d in self.data_type.all_data_types if d.reference
139         }
140 
141     def process_const(self) -> None:
142         if 'const' not in self.extras:
143             return None
144         self.const = True
145         self.nullable = False
146         const = self.extras['const']
147         if self.data_type.type == 'str' and isinstance(
148             const, str
149         ):  # pragma: no cover # Literal supports only str
150             self.data_type = self.data_type.__class__(literals=[const])
151 
152     def _get_strict_field_constraint_value(self, constraint: str, value: Any) -> Any:
153         if value is None or constraint not in self._COMPARE_EXPRESSIONS:
154             return value
155 
156         if any(
157             data_type.type == 'float' for data_type in self.data_type.all_data_types
158         ):
159             return float(value)
160         return int(value)
161 
162     @property
163     def field(self) -> Optional[str]:
164         """for backwards compatibility"""
165         result = str(self)
166         if result == '':
167             return None
168 
169         return result
170 
171     def __str__(self) -> str:
172         data: Dict[str, Any] = {
173             k: v for k, v in self.extras.items() if k in self._FIELD_KEYS
174         }
175         if self.alias:
176             data['name'] = self.alias
177 
178         if self.default != UNDEFINED and self.default is not None:
179             data['default'] = self.default
180 
181         if self.required:
182             data = {
183                 k: v
184                 for k, v in data.items()
185                 if k
186                 not in (
187                     'default',
188                     'default_factory',
189                 )
190             }
191         elif self.default and 'default_factory' not in data:
192             default_factory = self._get_default_as_struct_model()
193             if default_factory is not None:
194                 data.pop('default')
195                 data['default_factory'] = default_factory
196 
197         if not data:
198             return ''
199 
200         if len(data) == 1 and 'default' in data:
201             return repr(data['default'])
202 
203         kwargs = [
204             f'{k}={v if k == "default_factory" else repr(v)}' for k, v in data.items()
205         ]
206         return f'field({", ".join(kwargs)})'
207 
208     @property
209     def annotated(self) -> Optional[str]:
210         if not self.use_annotated:  # pragma: no cover
211             return None
212 
213         data: Dict[str, Any] = {
214             k: v for k, v in self.extras.items() if k in self._META_FIELD_KEYS
215         }
216         if (
217             self.constraints is not None
218             and not self.self_reference()
219             and not self.data_type.strict
220         ):
221             data = {
222                 **data,
223                 **{
224                     k: self._get_strict_field_constraint_value(k, v)
225                     for k, v in self.constraints.dict().items()
226                     if k in self._META_FIELD_KEYS
227                 },
228             }
229 
230         meta_arguments = sorted(
231             f'{k}={repr(v)}' for k, v in data.items() if v is not None
232         )
233         if not meta_arguments:
234             return None
235 
236         meta = f'Meta({", ".join(meta_arguments)})'
237 
238         if not self.required:
239             type_hint = self.data_type.type_hint
240             annotated_type = f'Annotated[{type_hint}, {meta}]'
241             return get_optional_type(annotated_type, self.data_type.use_union_operator)
242         return f'Annotated[{self.type_hint}, {meta}]'
243 
244     def _get_default_as_struct_model(self) -> Optional[str]:
245         for data_type in self.data_type.data_types or (self.data_type,):
246             # TODO: Check nested data_types
247             if data_type.is_dict or self.data_type.is_union:
248                 # TODO: Parse Union and dict model for default
249                 continue  # pragma: no cover
250             elif data_type.is_list and len(data_type.data_types) == 1:
251                 data_type = data_type.data_types[0]
252                 if (  # pragma: no cover
253                     data_type.reference
254                     and (
255                         isinstance(data_type.reference.source, Struct)
256                         or isinstance(data_type.reference.source, RootModel)
257                     )
258                     and isinstance(self.default, list)
259                 ):
260                     return f'lambda: {self._PARSE_METHOD}({repr(self.default)},  type=list[{data_type.alias or data_type.reference.source.class_name}])'
261             elif data_type.reference and isinstance(data_type.reference.source, Struct):
262                 return f'lambda: {self._PARSE_METHOD}({repr(self.default)},  type={data_type.alias or data_type.reference.source.class_name})'
263         return None
264
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/datamodel_code_generator/model/msgspec.py b/datamodel_code_generator/model/msgspec.py
--- a/datamodel_code_generator/model/msgspec.py
+++ b/datamodel_code_generator/model/msgspec.py
@@ -33,7 +33,7 @@
 
 
 def _has_field_assignment(field: DataModelFieldBase) -> bool:
-    return bool(field.field) or not (
+    return not (
         field.required
         or (field.represented_default == 'None' and field.strip_default_none)
     )
@@ -48,7 +48,9 @@
     @wraps(original_imports.fget)  # type: ignore
     def new_imports(self: DataModelFieldBaseT) -> Tuple[Import, ...]:
         extra_imports = []
-        if self.field:
+        field = self.field
+        # TODO: Improve field detection
+        if field and field.startswith('field('):
             extra_imports.append(IMPORT_MSGSPEC_FIELD)
         if self.field and 'lambda: convert' in self.field:
             extra_imports.append(IMPORT_MSGSPEC_CONVERT)
@@ -177,6 +179,8 @@
 
         if self.default != UNDEFINED and self.default is not None:
             data['default'] = self.default
+        elif not self.required:
+            data['default'] = None
 
         if self.required:
             data = {

{"golden_diff": "diff --git a/datamodel_code_generator/model/msgspec.py b/datamodel_code_generator/model/msgspec.py\n--- a/datamodel_code_generator/model/msgspec.py\n+++ b/datamodel_code_generator/model/msgspec.py\n@@ -33,7 +33,7 @@\n \n \n def _has_field_assignment(field: DataModelFieldBase) -> bool:\n-    return bool(field.field) or not (\n+    return not (\n         field.required\n         or (field.represented_default == 'None' and field.strip_default_none)\n     )\n@@ -48,7 +48,9 @@\n     @wraps(original_imports.fget)  # type: ignore\n     def new_imports(self: DataModelFieldBaseT) -> Tuple[Import, ...]:\n         extra_imports = []\n-        if self.field:\n+        field = self.field\n+        # TODO: Improve field detection\n+        if field and field.startswith('field('):\n             extra_imports.append(IMPORT_MSGSPEC_FIELD)\n         if self.field and 'lambda: convert' in self.field:\n             extra_imports.append(IMPORT_MSGSPEC_CONVERT)\n@@ -177,6 +179,8 @@\n \n         if self.default != UNDEFINED and self.default is not None:\n             data['default'] = self.default\n+        elif not self.required:\n+            data['default'] = None\n \n         if self.required:\n             data = {\n", "issue": "msgspec: Optional fields are missing a default when using `--snake-case-field`\n### Steps to reproduce\r\n1. Download the NVD CVE [schema][schema]\r\n2. Generate a msgpsec model:\r\n```sh\r\ndatamodel-codegen \\\r\n    --input $schema_json \\\r\n    --input-file-type jsonschema \\\r\n    --output-model-type 'msgspec.Struct' \\\r\n   # This is important I think\r\n    --snake-case-field \\\r\n    --output \".\"\r\n```\r\n3. (Ignore the circular imports #836)\r\n4. (Ignore wrong field ordering #1919 \r\n5. Look at the `class CpeMatch` (and most other classes as well).\r\n```python\r\nclass CpeMatch(Struct, kw_only=True):\r\n    vulnerable: bool\r\n    criteria: str\r\n    match_criteria_id: str = field(name='matchCriteriaId')\r\n    version_start_excluding: Optional[str] = field(name='versionStartExcluding')\r\n    version_start_including: Optional[str] = field(name='versionStartIncluding')\r\n    version_end_excluding: Optional[str] = field(name='versionEndExcluding')\r\n    version_end_including: Optional[str] = field(name='versionEndIncluding')\r\n\r\n```\r\nvs\r\n```json\r\n\r\n\"cpe_match\": {\r\n\t\"description\": \"CPE match string or range\",\r\n\t\"type\": \"object\",\r\n\t\"properties\": {\r\n\t\t\"vulnerable\": {\"type\": \"boolean\"},\r\n\t\t\"criteria\": {\"type\": \"string\"},\r\n\t\t\"matchCriteriaId\": {\"type\": \"string\", \"format\": \"uuid\"},\r\n\t\t\"versionStartExcluding\": {\"type\": \"string\"},\r\n\t\t\"versionStartIncluding\": {\"type\": \"string\"},\r\n\t\t\"versionEndExcluding\": {\"type\": \"string\"},\r\n\t\t\"versionEndIncluding\": {\"type\": \"string\"}\r\n\t},\r\n\t\"required\": [\"vulnerable\", \"criteria\", \"matchCriteriaId\"],\r\n\t\"additionalProperties\": false\r\n},\r\n```\r\n\r\nNote that the optional fields are missing the `default=None` parameter in the `field` call.\r\n\r\n[schema]: https://csrc.nist.gov/schema/nvd/api/2.0/cve_api_json_2.0.schema\r\n\r\n### Expected behavior\r\nThe field should have a default of value `None`.\r\n\r\n### Workaround\r\nDo not use `--snake-case-field`.\r\n\r\n### Setup\r\n\r\n```sh\r\n$ datamodel-codegen --version\r\n0.25.5\r\n\r\n$ python --version\r\nPython 3.11.8\r\n```\r\n\n", "before_files": [{"content": "from functools import wraps\nfrom pathlib import Path\nfrom typing import (\n    Any,\n    ClassVar,\n    DefaultDict,\n    Dict,\n    List,\n    Optional,\n    Set,\n    Tuple,\n    Type,\n    TypeVar,\n)\n\nfrom pydantic import Field\n\nfrom datamodel_code_generator.imports import Import\nfrom datamodel_code_generator.model import DataModel, DataModelFieldBase\nfrom datamodel_code_generator.model.base import UNDEFINED\nfrom datamodel_code_generator.model.imports import (\n    IMPORT_MSGSPEC_CONVERT,\n    IMPORT_MSGSPEC_FIELD,\n    IMPORT_MSGSPEC_META,\n    IMPORT_MSGSPEC_STRUCT,\n)\nfrom datamodel_code_generator.model.pydantic.base_model import (\n    Constraints as _Constraints,\n)\nfrom datamodel_code_generator.model.rootmodel import RootModel as _RootModel\nfrom datamodel_code_generator.reference import Reference\nfrom datamodel_code_generator.types import chain_as_tuple, get_optional_type\n\n\ndef _has_field_assignment(field: DataModelFieldBase) -> bool:\n    return bool(field.field) or not (\n        field.required\n        or (field.represented_default == 'None' and field.strip_default_none)\n    )\n\n\nDataModelFieldBaseT = TypeVar('DataModelFieldBaseT', bound=DataModelFieldBase)\n\n\ndef import_extender(cls: Type[DataModelFieldBaseT]) -> Type[DataModelFieldBaseT]:\n    original_imports: property = getattr(cls, 'imports', None)  # type: ignore\n\n    @wraps(original_imports.fget)  # type: ignore\n    def new_imports(self: DataModelFieldBaseT) -> Tuple[Import, ...]:\n        extra_imports = []\n        if self.field:\n            extra_imports.append(IMPORT_MSGSPEC_FIELD)\n        if self.field and 'lambda: convert' in self.field:\n            extra_imports.append(IMPORT_MSGSPEC_CONVERT)\n        if self.annotated:\n            extra_imports.append(IMPORT_MSGSPEC_META)\n        return chain_as_tuple(original_imports.fget(self), extra_imports)  # type: ignore\n\n    setattr(cls, 'imports', property(new_imports))\n    return cls\n\n\nclass RootModel(_RootModel):\n    pass\n\n\nclass Struct(DataModel):\n    TEMPLATE_FILE_PATH: ClassVar[str] = 'msgspec.jinja2'\n    BASE_CLASS: ClassVar[str] = 'msgspec.Struct'\n    DEFAULT_IMPORTS: ClassVar[Tuple[Import, ...]] = (IMPORT_MSGSPEC_STRUCT,)\n\n    def __init__(\n        self,\n        *,\n        reference: Reference,\n        fields: List[DataModelFieldBase],\n        decorators: Optional[List[str]] = None,\n        base_classes: Optional[List[Reference]] = None,\n        custom_base_class: Optional[str] = None,\n        custom_template_dir: Optional[Path] = None,\n        extra_template_data: Optional[DefaultDict[str, Dict[str, Any]]] = None,\n        methods: Optional[List[str]] = None,\n        path: Optional[Path] = None,\n        description: Optional[str] = None,\n        default: Any = UNDEFINED,\n        nullable: bool = False,\n    ) -> None:\n        super().__init__(\n            reference=reference,\n            fields=sorted(fields, key=_has_field_assignment, reverse=False),\n            decorators=decorators,\n            base_classes=base_classes,\n            custom_base_class=custom_base_class,\n            custom_template_dir=custom_template_dir,\n            extra_template_data=extra_template_data,\n            methods=methods,\n            path=path,\n            description=description,\n            default=default,\n            nullable=nullable,\n        )\n\n\nclass Constraints(_Constraints):\n    # To override existing pattern alias\n    regex: Optional[str] = Field(None, alias='regex')\n    pattern: Optional[str] = Field(None, alias='pattern')\n\n\n@import_extender\nclass DataModelField(DataModelFieldBase):\n    _FIELD_KEYS: ClassVar[Set[str]] = {\n        'default',\n        'default_factory',\n    }\n    _META_FIELD_KEYS: ClassVar[Set[str]] = {\n        'title',\n        'description',\n        'gt',\n        'ge',\n        'lt',\n        'le',\n        'multiple_of',\n        # 'min_items', # not supported by msgspec\n        # 'max_items', # not supported by msgspec\n        'min_length',\n        'max_length',\n        'pattern',\n        'examples',\n        # 'unique_items', # not supported by msgspec\n    }\n    _PARSE_METHOD = 'convert'\n    _COMPARE_EXPRESSIONS: ClassVar[Set[str]] = {'gt', 'ge', 'lt', 'le', 'multiple_of'}\n    constraints: Optional[Constraints] = None\n\n    def self_reference(self) -> bool:  # pragma: no cover\n        return isinstance(self.parent, Struct) and self.parent.reference.path in {\n            d.reference.path for d in self.data_type.all_data_types if d.reference\n        }\n\n    def process_const(self) -> None:\n        if 'const' not in self.extras:\n            return None\n        self.const = True\n        self.nullable = False\n        const = self.extras['const']\n        if self.data_type.type == 'str' and isinstance(\n            const, str\n        ):  # pragma: no cover # Literal supports only str\n            self.data_type = self.data_type.__class__(literals=[const])\n\n    def _get_strict_field_constraint_value(self, constraint: str, value: Any) -> Any:\n        if value is None or constraint not in self._COMPARE_EXPRESSIONS:\n            return value\n\n        if any(\n            data_type.type == 'float' for data_type in self.data_type.all_data_types\n        ):\n            return float(value)\n        return int(value)\n\n    @property\n    def field(self) -> Optional[str]:\n        \"\"\"for backwards compatibility\"\"\"\n        result = str(self)\n        if result == '':\n            return None\n\n        return result\n\n    def __str__(self) -> str:\n        data: Dict[str, Any] = {\n            k: v for k, v in self.extras.items() if k in self._FIELD_KEYS\n        }\n        if self.alias:\n            data['name'] = self.alias\n\n        if self.default != UNDEFINED and self.default is not None:\n            data['default'] = self.default\n\n        if self.required:\n            data = {\n                k: v\n                for k, v in data.items()\n                if k\n                not in (\n                    'default',\n                    'default_factory',\n                )\n            }\n        elif self.default and 'default_factory' not in data:\n            default_factory = self._get_default_as_struct_model()\n            if default_factory is not None:\n                data.pop('default')\n                data['default_factory'] = default_factory\n\n        if not data:\n            return ''\n\n        if len(data) == 1 and 'default' in data:\n            return repr(data['default'])\n\n        kwargs = [\n            f'{k}={v if k == \"default_factory\" else repr(v)}' for k, v in data.items()\n        ]\n        return f'field({\", \".join(kwargs)})'\n\n    @property\n    def annotated(self) -> Optional[str]:\n        if not self.use_annotated:  # pragma: no cover\n            return None\n\n        data: Dict[str, Any] = {\n            k: v for k, v in self.extras.items() if k in self._META_FIELD_KEYS\n        }\n        if (\n            self.constraints is not None\n            and not self.self_reference()\n            and not self.data_type.strict\n        ):\n            data = {\n                **data,\n                **{\n                    k: self._get_strict_field_constraint_value(k, v)\n                    for k, v in self.constraints.dict().items()\n                    if k in self._META_FIELD_KEYS\n                },\n            }\n\n        meta_arguments = sorted(\n            f'{k}={repr(v)}' for k, v in data.items() if v is not None\n        )\n        if not meta_arguments:\n            return None\n\n        meta = f'Meta({\", \".join(meta_arguments)})'\n\n        if not self.required:\n            type_hint = self.data_type.type_hint\n            annotated_type = f'Annotated[{type_hint}, {meta}]'\n            return get_optional_type(annotated_type, self.data_type.use_union_operator)\n        return f'Annotated[{self.type_hint}, {meta}]'\n\n    def _get_default_as_struct_model(self) -> Optional[str]:\n        for data_type in self.data_type.data_types or (self.data_type,):\n            # TODO: Check nested data_types\n            if data_type.is_dict or self.data_type.is_union:\n                # TODO: Parse Union and dict model for default\n                continue  # pragma: no cover\n            elif data_type.is_list and len(data_type.data_types) == 1:\n                data_type = data_type.data_types[0]\n                if (  # pragma: no cover\n                    data_type.reference\n                    and (\n                        isinstance(data_type.reference.source, Struct)\n                        or isinstance(data_type.reference.source, RootModel)\n                    )\n                    and isinstance(self.default, list)\n                ):\n                    return f'lambda: {self._PARSE_METHOD}({repr(self.default)},  type=list[{data_type.alias or data_type.reference.source.class_name}])'\n            elif data_type.reference and isinstance(data_type.reference.source, Struct):\n                return f'lambda: {self._PARSE_METHOD}({repr(self.default)},  type={data_type.alias or data_type.reference.source.class_name})'\n        return None\n", "path": "datamodel_code_generator/model/msgspec.py"}], "after_files": [{"content": "from functools import wraps\nfrom pathlib import Path\nfrom typing import (\n    Any,\n    ClassVar,\n    DefaultDict,\n    Dict,\n    List,\n    Optional,\n    Set,\n    Tuple,\n    Type,\n    TypeVar,\n)\n\nfrom pydantic import Field\n\nfrom datamodel_code_generator.imports import Import\nfrom datamodel_code_generator.model import DataModel, DataModelFieldBase\nfrom datamodel_code_generator.model.base import UNDEFINED\nfrom datamodel_code_generator.model.imports import (\n    IMPORT_MSGSPEC_CONVERT,\n    IMPORT_MSGSPEC_FIELD,\n    IMPORT_MSGSPEC_META,\n    IMPORT_MSGSPEC_STRUCT,\n)\nfrom datamodel_code_generator.model.pydantic.base_model import (\n    Constraints as _Constraints,\n)\nfrom datamodel_code_generator.model.rootmodel import RootModel as _RootModel\nfrom datamodel_code_generator.reference import Reference\nfrom datamodel_code_generator.types import chain_as_tuple, get_optional_type\n\n\ndef _has_field_assignment(field: DataModelFieldBase) -> bool:\n    return not (\n        field.required\n        or (field.represented_default == 'None' and field.strip_default_none)\n    )\n\n\nDataModelFieldBaseT = TypeVar('DataModelFieldBaseT', bound=DataModelFieldBase)\n\n\ndef import_extender(cls: Type[DataModelFieldBaseT]) -> Type[DataModelFieldBaseT]:\n    original_imports: property = getattr(cls, 'imports', None)  # type: ignore\n\n    @wraps(original_imports.fget)  # type: ignore\n    def new_imports(self: DataModelFieldBaseT) -> Tuple[Import, ...]:\n        extra_imports = []\n        field = self.field\n        # TODO: Improve field detection\n        if field and field.startswith('field('):\n            extra_imports.append(IMPORT_MSGSPEC_FIELD)\n        if self.field and 'lambda: convert' in self.field:\n            extra_imports.append(IMPORT_MSGSPEC_CONVERT)\n        if self.annotated:\n            extra_imports.append(IMPORT_MSGSPEC_META)\n        return chain_as_tuple(original_imports.fget(self), extra_imports)  # type: ignore\n\n    setattr(cls, 'imports', property(new_imports))\n    return cls\n\n\nclass RootModel(_RootModel):\n    pass\n\n\nclass Struct(DataModel):\n    TEMPLATE_FILE_PATH: ClassVar[str] = 'msgspec.jinja2'\n    BASE_CLASS: ClassVar[str] = 'msgspec.Struct'\n    DEFAULT_IMPORTS: ClassVar[Tuple[Import, ...]] = (IMPORT_MSGSPEC_STRUCT,)\n\n    def __init__(\n        self,\n        *,\n        reference: Reference,\n        fields: List[DataModelFieldBase],\n        decorators: Optional[List[str]] = None,\n        base_classes: Optional[List[Reference]] = None,\n        custom_base_class: Optional[str] = None,\n        custom_template_dir: Optional[Path] = None,\n        extra_template_data: Optional[DefaultDict[str, Dict[str, Any]]] = None,\n        methods: Optional[List[str]] = None,\n        path: Optional[Path] = None,\n        description: Optional[str] = None,\n        default: Any = UNDEFINED,\n        nullable: bool = False,\n    ) -> None:\n        super().__init__(\n            reference=reference,\n            fields=sorted(fields, key=_has_field_assignment, reverse=False),\n            decorators=decorators,\n            base_classes=base_classes,\n            custom_base_class=custom_base_class,\n            custom_template_dir=custom_template_dir,\n            extra_template_data=extra_template_data,\n            methods=methods,\n            path=path,\n            description=description,\n            default=default,\n            nullable=nullable,\n        )\n\n\nclass Constraints(_Constraints):\n    # To override existing pattern alias\n    regex: Optional[str] = Field(None, alias='regex')\n    pattern: Optional[str] = Field(None, alias='pattern')\n\n\n@import_extender\nclass DataModelField(DataModelFieldBase):\n    _FIELD_KEYS: ClassVar[Set[str]] = {\n        'default',\n        'default_factory',\n    }\n    _META_FIELD_KEYS: ClassVar[Set[str]] = {\n        'title',\n        'description',\n        'gt',\n        'ge',\n        'lt',\n        'le',\n        'multiple_of',\n        # 'min_items', # not supported by msgspec\n        # 'max_items', # not supported by msgspec\n        'min_length',\n        'max_length',\n        'pattern',\n        'examples',\n        # 'unique_items', # not supported by msgspec\n    }\n    _PARSE_METHOD = 'convert'\n    _COMPARE_EXPRESSIONS: ClassVar[Set[str]] = {'gt', 'ge', 'lt', 'le', 'multiple_of'}\n    constraints: Optional[Constraints] = None\n\n    def self_reference(self) -> bool:  # pragma: no cover\n        return isinstance(self.parent, Struct) and self.parent.reference.path in {\n            d.reference.path for d in self.data_type.all_data_types if d.reference\n        }\n\n    def process_const(self) -> None:\n        if 'const' not in self.extras:\n            return None\n        self.const = True\n        self.nullable = False\n        const = self.extras['const']\n        if self.data_type.type == 'str' and isinstance(\n            const, str\n        ):  # pragma: no cover # Literal supports only str\n            self.data_type = self.data_type.__class__(literals=[const])\n\n    def _get_strict_field_constraint_value(self, constraint: str, value: Any) -> Any:\n        if value is None or constraint not in self._COMPARE_EXPRESSIONS:\n            return value\n\n        if any(\n            data_type.type == 'float' for data_type in self.data_type.all_data_types\n        ):\n            return float(value)\n        return int(value)\n\n    @property\n    def field(self) -> Optional[str]:\n        \"\"\"for backwards compatibility\"\"\"\n        result = str(self)\n        if result == '':\n            return None\n\n        return result\n\n    def __str__(self) -> str:\n        data: Dict[str, Any] = {\n            k: v for k, v in self.extras.items() if k in self._FIELD_KEYS\n        }\n        if self.alias:\n            data['name'] = self.alias\n\n        if self.default != UNDEFINED and self.default is not None:\n            data['default'] = self.default\n        elif not self.required:\n            data['default'] = None\n\n        if self.required:\n            data = {\n                k: v\n                for k, v in data.items()\n                if k\n                not in (\n                    'default',\n                    'default_factory',\n                )\n            }\n        elif self.default and 'default_factory' not in data:\n            default_factory = self._get_default_as_struct_model()\n            if default_factory is not None:\n                data.pop('default')\n                data['default_factory'] = default_factory\n\n        if not data:\n            return ''\n\n        if len(data) == 1 and 'default' in data:\n            return repr(data['default'])\n\n        kwargs = [\n            f'{k}={v if k == \"default_factory\" else repr(v)}' for k, v in data.items()\n        ]\n        return f'field({\", \".join(kwargs)})'\n\n    @property\n    def annotated(self) -> Optional[str]:\n        if not self.use_annotated:  # pragma: no cover\n            return None\n\n        data: Dict[str, Any] = {\n            k: v for k, v in self.extras.items() if k in self._META_FIELD_KEYS\n        }\n        if (\n            self.constraints is not None\n            and not self.self_reference()\n            and not self.data_type.strict\n        ):\n            data = {\n                **data,\n                **{\n                    k: self._get_strict_field_constraint_value(k, v)\n                    for k, v in self.constraints.dict().items()\n                    if k in self._META_FIELD_KEYS\n                },\n            }\n\n        meta_arguments = sorted(\n            f'{k}={repr(v)}' for k, v in data.items() if v is not None\n        )\n        if not meta_arguments:\n            return None\n\n        meta = f'Meta({\", \".join(meta_arguments)})'\n\n        if not self.required:\n            type_hint = self.data_type.type_hint\n            annotated_type = f'Annotated[{type_hint}, {meta}]'\n            return get_optional_type(annotated_type, self.data_type.use_union_operator)\n        return f'Annotated[{self.type_hint}, {meta}]'\n\n    def _get_default_as_struct_model(self) -> Optional[str]:\n        for data_type in self.data_type.data_types or (self.data_type,):\n            # TODO: Check nested data_types\n            if data_type.is_dict or self.data_type.is_union:\n                # TODO: Parse Union and dict model for default\n                continue  # pragma: no cover\n            elif data_type.is_list and len(data_type.data_types) == 1:\n                data_type = data_type.data_types[0]\n                if (  # pragma: no cover\n                    data_type.reference\n                    and (\n                        isinstance(data_type.reference.source, Struct)\n                        or isinstance(data_type.reference.source, RootModel)\n                    )\n                    and isinstance(self.default, list)\n                ):\n                    return f'lambda: {self._PARSE_METHOD}({repr(self.default)},  type=list[{data_type.alias or data_type.reference.source.class_name}])'\n            elif data_type.reference and isinstance(data_type.reference.source, Struct):\n                return f'lambda: {self._PARSE_METHOD}({repr(self.default)},  type={data_type.alias or data_type.reference.source.class_name})'\n        return None\n", "path": "datamodel_code_generator/model/msgspec.py"}]}