Can the python pre-commit tool consider a subdirectory as a base of the project?
Asked Answered
I

1

9

I have a repo like this:

myrepo/
      .git
      tool1/  
           src/main.py
           tests/test.py
           .pre-commit-config.yaml

Where the config is:

repos:
- repo: local
  hooks:
    - id: pytest-cov
      name: pytest coverage
      stages: [push]
      language: system
      entry: pwd  # originally: pytest testtool --cov --cov-fail-under=0 
      types: [python]
      pass_filenames: false

Changed the entry to 'pwd' just to see what the basedir is in pre-commit's context.. Now, when I run this from the myrepo/tool1 dir, by pre-commit run --hook-stage=push --verbose, pwd will say "myrepo", rather than "myrepo/tool1". I would need to run in the tool1 as all paths etc are relative to that.

Is there some setting or another way to run precommit so that the base directory would be myrepo/tool1? or does the project really have to live in the root of the repo?

Isfahan answered 10/11, 2020 at 16:51 Comment(0)
D
16

you can put the configuration anywhere as you've seen but git hooks themselves always run from the root of the repository (this is how git works). there's also only one set of git hooks per repository so functionality for a monorepo doesn't really make sense for git hooks

there's a few issues on the tracker that are of interest: pre-commit/pre-commit/issues search:monorepo

the suggestion is to write a wrapper around whatever tool in question and use cd if you need to change the working directory -- for instance from #1417:

-   repo: local
    hooks:
    -   id: go-unit-tests
        name: run go test s(go test)
        language: system
        entry: bash -c 'cd subdir && exec go test ./...'
        pass_filenames: false
        types: [go]
        files: ^subdir/

disclaimer: I'm the author of pre-commit

Decrescent answered 10/11, 2020 at 16:58 Comment(1)
Thanks for the prompt answer.Yes I know git hooks are run from the root of the repo.. The "problem" is that pre-commit seems to be used not only as a git hook tool, but also, (abused?) to run eg unit tests. If you have several modules inside one repo (you may not want to split it up just yet), it would useful to allow this more explicity and make the modular.Yes when you actually install them into git hooks, you'd have to merge them - but I see the point the keep the config modular/local.Maybe this would go against the design goals and something like make/scons/etc.. is what I'm looking for?Isfahan

© 2022 - 2024 — McMap. All rights reserved.