Skip to content

fix: handle cross-drive ValueError in _adjust_args_and_chdir on Windows#3658

Closed
terminalchai wants to merge 1 commit intopre-commit:mainfrom
terminalchai:fix/relpath-cross-drive-valueerror
Closed

fix: handle cross-drive ValueError in _adjust_args_and_chdir on Windows#3658
terminalchai wants to merge 1 commit intopre-commit:mainfrom
terminalchai:fix/relpath-cross-drive-valueerror

Conversation

@terminalchai
Copy link
Copy Markdown

Summary

Fixes #2530

On Windows, os.path.relpath() raises ValueError when the path and the current working directory are on different drives — e.g. a config at C:\Users\me.pre-commit-config.yaml while the git repo lives on D:. This causes an unhandled traceback instead of a helpful error message.

Root cause

_adjust_args_and_chdir calls os.path.relpath() unconditionally on �rgs.config, �rgs.files, �rgs.commit_msg_filename, and �rgs.repo after doing os.chdir(toplevel). When the git root and the path being relativised are on different Windows drives, Python raises:

\
ValueError: path is on mount 'C:', start on mount 'D:'
\\

Fix

Introduce a small _try_relpath() helper (as suggested by @asottile in #2530 — option 2):

\\python
def _try_relpath(path: str) -> str:
try:
return os.path.relpath(path)
except ValueError:
return path
\\

All four os.path.relpath calls in _adjust_args_and_chdir are updated to use _try_relpath, so every cross-drive combination (config, files list, commit-msg filename, try-repo repo path) is covered. On POSIX and same-drive Windows the behaviour is identical to before.

Tests added

  • est_try_relpath_returns_relpath_when_same_drive — normal case, same drive
  • est_try_relpath_returns_original_on_cross_drive_valueerror — mocks os.path.relpath to raise ValueError, asserts original path is returned unchanged
  • est_adjust_args_config_on_different_drive — Windows-only integration test for the full _adjust_args_and_chdir path

On Windows, os.path.relpath() raises ValueError when the path and the
current working directory are on different drives (e.g. config on C:
but the git repo is on D:).

Introduce a small _try_relpath() helper that wraps os.path.relpath in
a try/except ValueError and returns the original path unchanged when
the drives differ.  All four os.path.relpath calls in
_adjust_args_and_chdir (config, files, commit_msg_filename, repo) are
updated to use this helper, so every cross-drive combination is
covered.

Fixes pre-commit#2530
@asottile
Copy link
Copy Markdown
Member

sorry we don't accept ai slop prs

@asottile asottile closed this Apr 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

ValueError on Windows when config is on a different drive than the git repo

2 participants