Skip to content

Commit

Permalink
Pass through resolve_path when the path is not accessible (#783)
Browse files Browse the repository at this point in the history
* Resolve path only if accessible, otherwise return unchanged

Fixes #771
  • Loading branch information
dagewa authored Feb 6, 2025
1 parent 8f8574d commit 62e3332
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 9 deletions.
1 change: 1 addition & 0 deletions newsfragments/772.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Do not try to resolve file paths if they are not accessible.
18 changes: 13 additions & 5 deletions src/dxtbx/serialize/filename.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
from __future__ import annotations

import glob
import os

from dxtbx.sequence_filenames import template_string_to_glob_expr


def resolve_path(path, directory=None):
"""Resolve a file path.
Expand All @@ -14,11 +17,16 @@ def resolve_path(path, directory=None):
directory (Optional[str]): The local path to resolve relative links
Returns:
str: The absolute path to the file to read
str: The absolute path to the file to read if accessible, otherwise
return the original path as provided
"""
if not path:
return ""
path = os.path.expanduser(os.path.expandvars(path))
if directory and not os.path.isabs(path):
path = os.path.join(directory, path)
return os.path.abspath(path)
trial_path = os.path.expanduser(os.path.expandvars(path))
if directory and not os.path.isabs(trial_path):
trial_path = os.path.join(directory, trial_path)
trial_path = os.path.abspath(trial_path)
if glob.glob(template_string_to_glob_expr(trial_path)):
return trial_path
else:
return path
24 changes: 20 additions & 4 deletions tests/serialize/test_filename.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,31 @@
from __future__ import annotations

import glob
import os
import uuid

from dxtbx.serialize.filename import resolve_path


def test_resolve_path(monkeypatch):
# Resolve path
def alwaystrue(path):
return True

# Set an environment variable
monkeypatch.setenv("HELLO_WORLD", "EXPANDED")
new_path = os.path.join("~", "$HELLO_WORLD", "path")

# First try a path that does not exist
filename = str(uuid.uuid4())
new_path = os.path.join("~", "$HELLO_WORLD", filename)
path = resolve_path(new_path)
assert path == os.path.join(os.path.expanduser("~"), "EXPANDED", "path")
new_path = os.path.join("$HELLO_WORLD", "path")
assert path == new_path

# Now pretend the path exists by ensuring its glob is truthy
monkeypatch.setattr(glob, "glob", alwaystrue)
path = resolve_path(new_path)
assert path == os.path.join(os.path.expanduser("~"), "EXPANDED", filename)

new_path = os.path.join("$HELLO_WORLD", filename)
path = resolve_path(new_path)
assert path == os.path.abspath(os.path.join("EXPANDED", "path"))
assert path == os.path.abspath(os.path.join("EXPANDED", filename))

0 comments on commit 62e3332

Please sign in to comment.