evilmartians / lefthook

Fast and powerful Git hooks manager for any type of projects.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Commands are run from the current path when applying the commit

maxdinech opened this issue Β· comments

πŸ”§ Summary

If I run a commit in ./ or ./backend/, the results differ. In this case, with Pyright (but other commands are affected too)
The python venv is attached to the backend folder.

Lefthook version

1.6.1

Steps to reproduce

pre-commit:
  commands:
    backend-pyright:
      root: "backend/"
      run: pyright .
cd ./
git commit -m "test from root"
cd backend/
git commit -m "test from backend"

Expected results

Pyright (including config) loaded from the backend in both cases

Actual results

A lot of pyright errors such as Unable to resolve import X in the first case but not in the second

Possible Solution

Make the command run from the path specified in root.

Hey! Actually with 1.6.0 release I've mad an effort to make lefthook commands run inside the root. Like in this example

test:
  commands:
    ls:
      run: echo $(ls)

lefthook run test prints files in project root, and if you add some root: subfolder to the ls command it will list files in this subfolder.

Could you please provide some logs and config example, so I could reproduce your issue. An example repo would be even better.

The issue seems to stem from where commands are executed in relation to a virtual environment. Commands run from the root directory (./) do not have access to the virtual environment, whereas commands executed within the ./backend directory are run within an activated virtual environment. This difference in execution context leads to command failures.

This setup:

# lefthook.yml
test:
  commands:
    which:
      run: echo $(which python)

with the folder structure

.
β”œβ”€β”€ backend
β”‚   └── .venv
└── lefthook.yml

shows that this is the case depending on the folder I run the git commit (or lefthook run pre-commit) from.

A suggested approach to resolve this issue could be to consider executing the commands as though they were initiated from the root: directory, aiming for a consistent environment across executions.

Or I could just simply setup the python venv at the project root, but this is not really desirable in my case.

Oh, I see, so, looks like python venv runs some hook when you are inside the backend directory, right? When lefthook runs the command it just changes the cwd to backend, but no hooks get applied. All ENVs are taken from the caller (from your shell), so if you run the hook from the root folder, the executed commands will have the same ENVs.

If assumption about some cd hooks I can suggest you to use rc option to apply the changes that force using pyenv.

I can be wrong since I haven't worked with the pyenv closely. But I'll be glad to figure it out.

Hey! Have you tried the rc option? Do you still fight with this issue?