Skip to content

Commit 449a250

Browse files
authored
[Python] Fix relative paths on Windows PCs with multiple drives (#3718)
## Changes Fix a problem in `_relativize_path` where it crashes on Windows if the supplied path is on a different drive from CWD. Since paths on different drives don't have anything common, we simply return the supplied path as-is. ## Why Fixes #3658 ## Tests Unit tests
1 parent 6da414b commit 449a250

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

experimental/python/databricks/bundles/build.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -528,11 +528,23 @@ def _relativize_location(location: Location) -> Location:
528528

529529

530530
def _relativize_path(path: str) -> str:
531+
"""
532+
Attempt to relativize an absolute path to the current working directory.
533+
534+
If the path is not absolute or cannot be relativized, return it as is.
535+
Used to relativize paths in locations to show shorter paths in diagnostics.
536+
"""
537+
531538
if not os.path.isabs(path):
532539
return path
533540

534541
cwd = os.getcwd()
535-
common = os.path.commonpath([os.getcwd(), path])
542+
543+
try:
544+
common = os.path.commonpath([cwd, path])
545+
except ValueError:
546+
# On Windows, paths on different drives don't have a common path
547+
return path
536548

537549
if common == cwd:
538550
return os.path.relpath(path, cwd)

experimental/python/databricks_tests/test_build.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
_parse_bundle_info,
1616
_read_conf,
1717
_relativize_location,
18+
_relativize_path,
1819
_write_diagnostics,
1920
_write_locations,
2021
_write_output,
@@ -117,6 +118,25 @@ def test_relativize_location():
117118
assert _relativize_location(location) == Location(file="bar.py", line=42, column=1)
118119

119120

121+
def test_relativize_path_relative():
122+
assert _relativize_path("bar.py") == "bar.py"
123+
124+
125+
def test_relativize_path_absolute_in_cwd():
126+
file = Path("bar.py").absolute().as_posix()
127+
assert _relativize_path(file) == "bar.py"
128+
129+
130+
def test_relativize_path_absolute_outside_cwd():
131+
assert _relativize_path("/some/other/path/bar.py") == "/some/other/path/bar.py"
132+
133+
134+
def test_relativize_path_different_drive():
135+
# On Windows, paths on different drives should return the absolute path
136+
# On Unix, this test will still pass as it will be treated as outside cwd
137+
assert _relativize_path("C:\\other\\path\\bar.py") == "C:\\other\\path\\bar.py"
138+
139+
120140
def test_load_object_common_error():
121141
obj, diagnostics = _load_object("resources:load_resources")
122142
[item] = diagnostics.items

0 commit comments

Comments
 (0)