diff --git a/experimental/python/databricks/bundles/build.py b/experimental/python/databricks/bundles/build.py index 86c9d1f7c7..b058e4510b 100644 --- a/experimental/python/databricks/bundles/build.py +++ b/experimental/python/databricks/bundles/build.py @@ -528,11 +528,23 @@ def _relativize_location(location: Location) -> Location: def _relativize_path(path: str) -> str: + """ + Attempt to relativize an absolute path to the current working directory. + + If the path is not absolute or cannot be relativized, return it as is. + Used to relativize paths in locations to show shorter paths in diagnostics. + """ + if not os.path.isabs(path): return path cwd = os.getcwd() - common = os.path.commonpath([os.getcwd(), path]) + + try: + common = os.path.commonpath([cwd, path]) + except ValueError: + # On Windows, paths on different drives don't have a common path + return path if common == cwd: return os.path.relpath(path, cwd) diff --git a/experimental/python/databricks_tests/test_build.py b/experimental/python/databricks_tests/test_build.py index 6906adbcac..65d9683e92 100644 --- a/experimental/python/databricks_tests/test_build.py +++ b/experimental/python/databricks_tests/test_build.py @@ -15,6 +15,7 @@ _parse_bundle_info, _read_conf, _relativize_location, + _relativize_path, _write_diagnostics, _write_locations, _write_output, @@ -117,6 +118,25 @@ def test_relativize_location(): assert _relativize_location(location) == Location(file="bar.py", line=42, column=1) +def test_relativize_path_relative(): + assert _relativize_path("bar.py") == "bar.py" + + +def test_relativize_path_absolute_in_cwd(): + file = Path("bar.py").absolute().as_posix() + assert _relativize_path(file) == "bar.py" + + +def test_relativize_path_absolute_outside_cwd(): + assert _relativize_path("/some/other/path/bar.py") == "/some/other/path/bar.py" + + +def test_relativize_path_different_drive(): + # On Windows, paths on different drives should return the absolute path + # On Unix, this test will still pass as it will be treated as outside cwd + assert _relativize_path("C:\\other\\path\\bar.py") == "C:\\other\\path\\bar.py" + + def test_load_object_common_error(): obj, diagnostics = _load_object("resources:load_resources") [item] = diagnostics.items