Reputation: 9899
I am trying to use isort to automatically fix import orders. When I run pre-commit run --files=myfile.py
it correctly updates my imports (by adding a line between known third party imports and internal package imports). However, when I try to commit this, pre-commit will cause the commit to fail, and then remove the line between the third-party imports and internal packages.
I have tried setting the known_third_party
setting in both setup.cfg
and in .isort.cfg
and I get the same behaviour. However, I suspect the config itself is not the problem as it is clearly being recognised correctly when I run pre-commit run ...
. So why does pre-commit run
use the correct config, but on the actual commit, it seems to ignore it?
How can I get the hooks to respect the config on the actual commit?
The configuration is:
.pre-commit-config.yaml
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v3.2.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: check-added-large-files
- repo: https://github.com/psf/black
rev: 21.12b0
hooks:
- id: black
- repo: https://github.com/pycqa/isort
rev: 5.10.1
hooks:
- id: isort
name: isort (python)
.isort.cfg
[settings]
known_third_party=django
Additional Info: Sub-directory configs may have caused this behaviour
I have tried moving config files, and now the problem seems to be resolved. My repo consists of source code for multiple applications, one of which is a python django application. The config files were in this sub-directory. I have moved the config files to the root of the whole project and now this particular problem is resolved. I wonder if there is a way to get pre-commit or isort to recognise the configs in sub-directories but I will leave that for another question.
Upvotes: 6
Views: 1642
Reputation: 2328
Additional Info: Sub-directory configs may have caused this behaviour
You are 100% correct: the presence of multiple configs in the repository can trip up isort when run as a pre-commit hook. https://pycqa.github.io/isort/docs/configuration/git_hook.html sort of alludes to this behavior:
If you want to use a specific configuration file for the hook, you can pass its path to settings_file. If no path is specifically requested, git_hook will search for the configuration file starting at the directory containing the first staged file, as per git diff-index ordering, and going upward in the directory structure until a valid configuration file is found or MAX_CONFIG_SEARCH_DEPTH directories are checked.
The best fix is to explicitly point isort at the root of your repository in your .pre-commit-config.yaml
:
repos:
- repo: https://github.com/timothycrosley/isort
rev: 5.12.0
hooks:
- id: isort
additional_dependencies: [toml]
args: [--config-root=., --resolve-all-configs]
Upvotes: 2