datamodel-code-generator icon indicating copy to clipboard operation
datamodel-code-generator copied to clipboard

Emit output without formatting to help investigate syntax errors

Open ncoghlan opened this issue 9 months ago • 2 comments
trafficstars

Is your feature request related to a problem? Please describe.

I had messed up my custom template formatting, so a required line break was missing, so the class header line was getting concatenated to a preceding comment.

The result was a cryptic syntax error pointing to a context-free field declaration that otherwise looked fine.

Similar to #1969, I investigated by patching datamodel-code-generator locally to pass format_=False to the underlying parser call.

Describe the solution you'd like

Rather than anything more elaborate, the simplest approach to make these cases easier to investigate would be to offer a --skip-formatting CLI option (skip_formatting generate parameter) that was passed down as parser.parse(format_=not skip_formatting)

Describe alternatives you've considered

The only other idea that occurred to me is to save the unformatted output somewhere when generated the formatted output fails. That seemed like it would be harder to discover and explain than a --skip-formatting option, though.

ncoghlan avatar Feb 10 '25 09:02 ncoghlan

I'm not a super huge fan of having a lot of flags. We already have too many in my opinion. Instead, I would prefer if you would still write out the content, just not apply the formatting.

gaborbernat avatar Feb 10 '25 14:02 gaborbernat

One way to achieve "write the output even if formatting fails" would be to do something like:

try:
    results = parser.parse()
except Exception as exc:
    warnings.warn(f"Failed to produce formatted output due to {exc!r}. Trying without formatting.")
    results = parser.parse(format_=False)

Would that approach be reasonable?

ncoghlan avatar Feb 11 '25 01:02 ncoghlan