danielgtaylor / python-betterproto

Clean, modern, Python 3.6+ code generator & library for Protobuf 3 and async gRPC
MIT License
1.51k stars 214 forks source link

Use Ruff on generated code (can replace isort) #488

Open MicaelJarniac opened 1 year ago

MicaelJarniac commented 1 year ago

https://beta.ruff.rs

Config example:

# pyproject.toml

[tool.ruff]
# https://beta.ruff.rs/docs/rules
line-length = 88  # Default
select = ["ALL"]
ignore = [
  # "D203",
  # "D213",
  "D",
  "RUF009",  # See `extend-immutable-calls`
  "ERA001",  # Detects comments as code
  # "A003",  # See `builtins-ignorelist`
  "UP006",  # https://github.com/danielgtaylor/python-betterproto/issues/485
]

[tool.ruff.flake8-builtins]
builtins-ignorelist = ["id", "type"]

[tool.ruff.flake8-bugbear]
# https://github.com/charliermarsh/ruff/issues/4355
extend-immutable-calls = ["betterproto.*"]

It's possible to have it only emulate isort, but I've tried to enable as much as possible from it, which is still incredibly fast.

Can be run as ruff check --fix.

MicaelJarniac commented 1 year ago

This is very low priority, and it's easy enough for users to add this functionality manually, via Nox for example, as I have. The example configuration I showed is basically the one I use to run Ruff on generated code.

redbmk commented 1 year ago

I just noticed that when installing betterproto[compiler] it includes isort, which is now running on all files in my editor (I have it configured to run whichever linting tools are installed in the virtualenv so it can easily vary by project) and conflicting with ruff (which I'm using instead of isort as you are).

Is either ruff or isort even needed? Feels like formatting and linting tools shouldn't be a dependency of code generators. It would be pretty hard to predict what tools someone is using and what their settings are. IMO for generated code as long as the code works it doesn't need to look super pretty. I typically tell black, ruff, etc to ignore generated code, but of course you can add it as a post-generate step if you like, as you mentioned you're doing.

MicaelJarniac commented 1 year ago

I format it myself with a Nox session after the code is generated, so I wouldn't mind if Betterproto didn't format code itself.

In your case, though, I'd suggest installing and running betterproto[compiler] only in a Nox session, which would keep its dependencies separate from your dev environment, and fix the issue you're having with your editor running isort.

StefanBRas commented 5 months ago

Would you accept a PR that made the formatting optional? That way users can still compile without having to install black and isort and then just run their own formatting after

Maybe the check at https://github.com/danielgtaylor/python-betterproto/blob/1f88b67eeb9871d33da154fd2c859b9d1aed62c1/src/betterproto/plugin/compiler.py#L9-L18 could just be a warning instead of exiting and if either black or isort is not found, they are just not run?