astral-sh / rye

a Hassle-Free Python Experience
https://rye.astral.sh
MIT License
13.82k stars 467 forks source link

Add pre-commit hook for `rye lock` #1052

Open Jeffrey-Lim opened 6 months ago

Jeffrey-Lim commented 6 months ago

Add a pre-commit hook that simply runs rye lock to ensure that requirements.lock is up to date with pyproject.toml. This is supposed to act similarly to the poetry-lock pre-commit hook.

Jeffrey-Lim commented 6 months ago

I've tried to create a hook myself, but there is no straightforward way. You would expect that you could add a .pre-commit-hooks.yaml file like this:

- id: rye-lock
  name: rye-lock
  description: Run rye lock to update lock files
  entry: rye lock
  language: rust
  pass_filenames: false
  files: ^(.*/)?(requirements(-dev)?\.lock|pyproject\.toml)$

Unfortunately, pre-commit internally runs cargo install --bins --path ., which results in the error error: found a virtual manifest at <path> instead of a package manifest. Running cargo install --bins --path ./rye instead does work, but the pre-commit maintainer is against making --path configurable.

I tried to make a hook that relies on the host installation of rye instead like this:

- id: rye-lock
  name: rye-lock
  description: Run rye lock to update lock files
  entry: rye.exe lock
  language: system
  pass_filenames: false
  files: ^(.*/)?(requirements(-dev)?\.lock|pyproject\.toml)$

This works, but only on Windows, as you need to call rye.exe instead of just rye, so this hook is now platform-dependent.

You could also create a docker file and make use that in a docker pre-commit hook, but I don't think that is a good solution as you would need to install docker on your host machine.

Anyway, I hope that my findings will be a useful starting point for whoever wants to pick up on this.

itsjohncs commented 3 months ago

Here's a working cross-platform hook: https://github.com/itsjohncs/rye-pre-commit. It supports rye lock and rye test out of the box, and allows you to pass in arbitrary arguments to rye to do whatever you'd like besides that.

I wanted to dive into pre-commit a little since I've been cargo-culting its configuration for awhile (mission accomplished ✨). But having made this using a Python script, I think an upstream change (in pre-commit) to the system language to automatically add .exe to the executable on Windows is probably a better idea. pre-commit already does this for other executables it runs. (Never mind, it's a bug in Rye that's preventing the system language from working, not a problem with pre-commit! TIL about how windows will use PATHEXT to try adding file extensions like .exe automatically)