Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 15 additions & 6 deletions pre_commit/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,17 @@ def _add_run_options(parser: argparse.ArgumentParser) -> None:
)


def _relpath(path: str) -> str:
# On Windows, os.path.relpath raises ValueError when `path` and the
# current directory are on different drives (e.g. config on C:\ but the
# git repo is on D:\). Fall back to the absolute path in that case so
# pre-commit still works cross-drive.
try:
return os.path.relpath(path)
except ValueError:
return path


def _adjust_args_and_chdir(args: argparse.Namespace) -> None:
# `--config` was specified relative to the non-root working directory
if os.path.exists(args.config):
Expand All @@ -188,15 +199,13 @@ def _adjust_args_and_chdir(args: argparse.Namespace) -> None:
toplevel = git.get_root()
os.chdir(toplevel)

args.config = os.path.relpath(args.config)
args.config = _relpath(args.config)
if args.command in {'run', 'try-repo'}:
args.files = [os.path.relpath(filename) for filename in args.files]
args.files = [_relpath(filename) for filename in args.files]
if args.commit_msg_filename is not None:
args.commit_msg_filename = os.path.relpath(
args.commit_msg_filename,
)
args.commit_msg_filename = _relpath(args.commit_msg_filename)
if args.command == 'try-repo' and os.path.exists(args.repo):
args.repo = os.path.relpath(args.repo)
args.repo = _relpath(args.repo)


def main(argv: Sequence[str] | None = None) -> int:
Expand Down
14 changes: 14 additions & 0 deletions tests/main_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,20 @@ def test_adjust_args_try_repo_repo_relative(in_git_dir):
assert args.repo == 'foo'


def test_relpath_falls_back_on_cross_drive_valueerror():
# On Windows, os.path.relpath raises ValueError when path and cwd are on
# different drives. _relpath must return the original path unchanged.
abs_path = 'C:\\configs\\pre-commit-config.yaml'
with mock.patch('os.path.relpath', side_effect=ValueError('different drives')):
assert main._relpath(abs_path) == abs_path


def test_relpath_returns_relative_path_on_same_drive():
# Normal case: os.path.relpath succeeds and the result is returned.
with mock.patch('os.path.relpath', return_value=os.path.join('foo', 'bar')):
assert main._relpath('/any/path') == os.path.join('foo', 'bar')


FNS = (
'autoupdate', 'clean', 'gc', 'install', 'install_hooks',
'migrate_config', 'run', 'sample_config', 'uninstall',
Expand Down
Loading