Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

feature: Infer file browser initial path from initial value (#10362)

Yair Chuchemb8c9ce29c395
diff --git a/marimo/_plugins/ui/_impl/file_browser.py b/marimo/_plugins/ui/_impl/file_browser.py
index cabe4e32be..cbffd9b7d4 100644
--- a/marimo/_plugins/ui/_impl/file_browser.py
+++ b/marimo/_plugins/ui/_impl/file_browser.py
@@ -66,6 +66,52 @@ def _normalize_selection_mode(
)
+def _normalize_values(
+ value: str | Path | Sequence[str | Path] | None,
+ *,
+ multiple: bool,
+) -> Sequence[str | Path]:
+ """Normalize the file browser's default values to a sequence."""
+ if value is None:
+ values: Sequence[str | Path] = ()
+ elif isinstance(value, Sequence) and not isinstance(value, str):
+ values = value
+ else:
+ values = (value,)
+
+ if not multiple and len(values) > 1:
+ raise ValueError(
+ "File browser with multiple=False cannot have more than one "
+ "default value."
+ )
+
+ return values
+
+
+def _common_parent(paths: Sequence[Path]) -> Path:
+ """Return the nearest directory containing all paths.
+
+ When paths are on different drives (Windows) or have no common parent,
+ returns the root directory of the first path.
+ """
+ candidate = paths[0].parent
+ while (
+ any(candidate not in path.parents for path in paths)
+ and candidate != candidate.parent
+ ):
+ candidate = candidate.parent
+ return candidate
+
+
+def _is_path_within(path: Path, parent: Path) -> bool:
+ """Return whether `path` resolves within `parent`."""
+ try:
+ path.resolve(strict=True).relative_to(parent.resolve())
+ except (ValueError, RuntimeError, OSError):
+ return False
+ return True
+
+
@dataclass
class ListDirectoryArgs:
path: str
@@ -158,8 +204,9 @@ class file_browser(
files.
Args:
- initial_path (Union[str, Path, AnyPath], optional): Starting directory. Defaults to current
- working directory.
+ initial_path (Union[str, Path, AnyPath], optional): Starting directory.
+ Defaults to the common parent directory of `value`, when provided,
+ or the current working directory otherwise.
If a string, it will be interpreted as a local path.
If a Path, it will be interpreted as a local path.
If a CloudPath (from cloudpathlib), such as S3Path, GCSPath, or AzurePath,
@@ -219,16 +266,53 @@ class file_browser(
) -> None:
self._selection_mode = _normalize_selection_mode(selection_mode)
- # Save the Path class of the initial path
+ values = _normalize_values(value, multiple=multiple)
+
+ # Save the Path class and client used to construct paths
+ path_source = values[0] if values else initial_path
self._path_cls: type[Path]
- if isinstance(initial_path, str):
+ if isinstance(path_source, str):
self._path_cls = Path
else:
- self._path_cls = initial_path.__class__
+ self._path_cls = path_source.__class__
+ self._path_kwargs: dict[str, Any] = {}
+ if hasattr(path_source, "client"):
+ self._path_kwargs["client"] = path_source.client # type: ignore
+
+ selected_paths: list[Path] = []
+ initial_value: list[TypedFileBrowserFileInfo] = []
+ for selected_value in values:
+ selected_path = self._create_path(
+ normalize_path(self._create_path(selected_value))
+ )
+ if not selected_path.exists():
+ raise ValueError(
+ f"Default value {selected_path} does not exist."
+ )
+ is_directory = selected_path.is_dir()
+ kind = "directory" if is_directory else "file"
+ if kind not in self._selection_mode:
+ raise ValueError(
+ f"Default value {selected_path} is a {kind}, but "
+ f"selection_mode {self._selection_mode} does not allow it."
+ )
+ selected_paths.append(selected_path)
+ initial_value.append(
+ TypedFileBrowserFileInfo(
+ id=str(selected_path),
+ path=str(selected_path),
+ name=selected_path.name,
+ is_directory=is_directory,
+ )
+ )
# Make a Path object
if not initial_path:
- initial_path = Path.cwd()
+ initial_path = (
+ _common_parent(selected_paths)
+ if selected_paths and not restrict_navigation
+ else Path.cwd()
+ )
elif isinstance(initial_path, str):
initial_path = Path(initial_path)
self._initial_path = initial_path
@@ -243,6 +327,14 @@ class file_browser(
f"Initial path {initial_path} is not a directory."
)
+ if restrict_navigation:
+ for selected_path in selected_paths:
+ if not _is_path_within(selected_path, self._initial_path):
+ raise ValueError(
+ f"Default value {selected_path} is outside the "
+ f"restricted initial path {self._initial_path}."
+ )
+
# Normalize filetypes: ensure lowercase and dot prefix for case-insensitive matching
if filetypes:
normalized_filetypes = set()
@@ -286,40 +378,6 @@ class file_browser(
else:
(wire_selection_mode,) = self._selection_mode
- if value is None:
- values: Sequence[str | Path] = ()
- elif isinstance(value, Sequence) and not isinstance(value, str):
- values = value
- else:
- values = (value,)
-
- if not multiple and len(values) > 1:
- raise ValueError(
- "File browser with multiple=False cannot have more than one "
- "default value."
- )
-
- initial_value: list[TypedFileBrowserFileInfo] = []
- for selected_value in values:
- selected_path = self._create_path(
- normalize_path(self._create_path(selected_value))
- )
- is_directory = selected_path.is_dir()
- kind = "directory" if is_directory else "file"
- if kind not in self._selection_mode:
- raise ValueError(
- f"Default value {selected_path} is a {kind}, but "
- f"selection_mode {self._selection_mode} does not allow it."
- )
- initial_value.append(
- TypedFileBrowserFileInfo(
- id=str(selected_path),
- path=str(selected_path),
- name=selected_path.name,
- is_directory=is_directory,
- )
- )
-
super().__init__(
component_name=file_browser._name,
initial_value=initial_value,
@@ -343,14 +401,7 @@ class file_browser(
def _create_path(self, path_str: str | Path) -> Path:
"""Create a path object with the same class and client as the initial path."""
- kwargs: dict[str, Any] = {}
-
- # If we have a client on the initial path, pass it to the path constructor
- # This covers the case when the initial path is a CloudPath with a client
- if hasattr(self._initial_path, "client"):
- kwargs["client"] = self._initial_path.client # type: ignore
-
- path = self._path_cls(path_str, **kwargs)
+ path = self._path_cls(path_str, **self._path_kwargs)
return path
def _passes_filter(self, file: Path) -> bool:
@@ -438,12 +489,7 @@ class file_browser(
path = self._create_path(args.path)
if self._restrict_navigation:
- try:
- path.resolve(strict=True).relative_to(
- self._initial_path.resolve()
- )
- # NB. RuntimeError vs OSError depends on the version of python.
- except (ValueError, RuntimeError, OSError):
+ if not _is_path_within(path, self._initial_path):
raise RuntimeError(
"Navigation is restricted; navigating outside the initial path is not allowed."
) from None
diff --git a/tests/_plugins/ui/_impl/test_file_browser.py b/tests/_plugins/ui/_impl/test_file_browser.py
index d49ed4b1d3..a870a51238 100644
--- a/tests/_plugins/ui/_impl/test_file_browser.py
+++ b/tests/_plugins/ui/_impl/test_file_browser.py
@@ -12,11 +12,34 @@ from marimo._plugins.ui._impl.file_browser import (
ListDirectoryArgs,
ListDirectoryResponse,
_normalize_selection_mode,
+ _normalize_values,
file_browser,
)
from marimo._utils.paths import normalize_path
+ ("value", "expected"),
+ [
+ (None, ()),
+ ("file.txt", ("file.txt",)),
+ (Path("file.txt"), (Path("file.txt"),)),
+ (["first.txt", "second.txt"], ["first.txt", "second.txt"]),
+ (("first.txt", "second.txt"), ("first.txt", "second.txt")),
+ ],
+)
+def test_normalize_values(
+ value: str | Path | list[str] | tuple[str, ...] | None,
+ expected: list[str | Path] | tuple[str | Path, ...],
+) -> None:
+ assert _normalize_values(value, multiple=True) == expected
+
+
+def test_normalize_values_rejects_multiple_values() -> None:
+ with pytest.raises(ValueError, match="multiple=False"):
+ _normalize_values(["first.txt", "second.txt"], multiple=False)
+
+
def test_file_browser_init(tmp_path: Path) -> None:
# Use tmp_path fixture for testing
fb = file_browser(initial_path=tmp_path)
@@ -52,6 +75,148 @@ def test_file_browser_default_value(tmp_path: Path) -> None:
assert [file.name for file in fb.value] == ["first.txt", "second.txt"]
+def test_file_browser_infers_initial_path_from_default_value(
+ tmp_path: Path,
+) -> None:
+ selected = tmp_path / "nested" / "selected.txt"
+ selected.parent.mkdir()
+ selected.touch()
+
+ fb = file_browser(value=selected)
+
+ assert fb._initial_path == selected.parent
+
+
+def test_file_browser_infers_initial_path_from_string_value(
+ tmp_path: Path,
+) -> None:
+ selected = tmp_path / "nested" / "selected.txt"
+ selected.parent.mkdir()
+ selected.touch()
+
+ fb = file_browser(value=str(selected))
+
+ assert fb._initial_path == selected.parent
+
+
+def test_file_browser_infers_common_initial_path_from_default_values(
+ tmp_path: Path,
+) -> None:
+ first = tmp_path / "nested" / "first" / "selected.txt"
+ second = tmp_path / "nested" / "second" / "selected.txt"
+ first.parent.mkdir(parents=True)
+ second.parent.mkdir(parents=True)
+ first.touch()
+ second.touch()
+
+ fb = file_browser(value=[first, second])
+
+ assert fb._initial_path == tmp_path / "nested"
+
+
+ sys.version_info <= (3, 12), reason="Only works with Python 3.12+"
+)
+def test_file_browser_infers_custom_path_class_and_client(
+ tmp_path: Path,
+) -> None:
+ class CustomPathWithClient(Path):
+ def __init__(self, path: Path, client: Any | None = None) -> None:
+ super().__init__(path)
+ self.client = client
+
+ selected = tmp_path / "nested" / "selected.txt"
+ selected.parent.mkdir()
+ selected.touch()
+
+ fb = file_browser(
+ value=CustomPathWithClient(selected, client="custom_client")
+ )
+
+ assert isinstance(fb._initial_path, CustomPathWithClient)
+ assert isinstance(fb.path(), CustomPathWithClient)
+ assert fb.path().client == "custom_client"
+
+
+def test_file_browser_explicit_initial_path_takes_precedence(
+ tmp_path: Path,
+) -> None:
+ selected = tmp_path / "nested" / "selected.txt"
+ selected.parent.mkdir()
+ selected.touch()
+
+ fb = file_browser(initial_path=tmp_path, value=selected)
+
+ assert fb._initial_path == tmp_path
+
+
+def test_restricted_file_browser_does_not_infer_initial_path(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ selected = tmp_path / "nested" / "selected.txt"
+ selected.parent.mkdir()
+ selected.touch()
+ monkeypatch.chdir(tmp_path)
+
+ fb = file_browser(value=selected, restrict_navigation=True)
+
+ assert fb._initial_path == tmp_path
+
+
+def test_restricted_file_browser_accepts_symlinked_cwd_value(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ real_directory = tmp_path / "real"
+ real_directory.mkdir()
+ symlinked_directory = tmp_path / "symlink"
+ try:
+ symlinked_directory.symlink_to(real_directory)
+ except OSError:
+ pytest.skip("Cannot create symlinks on this system")
+
+ selected = symlinked_directory / "selected.txt"
+ selected.touch()
+ monkeypatch.chdir(symlinked_directory)
+
+ fb = file_browser(value=selected, restrict_navigation=True)
+
+ assert fb.path() == selected
+
+
+def test_restricted_file_browser_rejects_unreachable_default_value(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ root = tmp_path / "root"
+ root.mkdir()
+ selected = tmp_path / "outside.txt"
+ selected.touch()
+ monkeypatch.chdir(root)
+
+ with pytest.raises(
+ ValueError, match="outside the restricted initial path"
+ ):
+ file_browser(value=selected, restrict_navigation=True)
+
+
+def test_restricted_file_browser_accepts_explicit_reachable_default_value(
+ tmp_path: Path,
+) -> None:
+ selected = tmp_path / "nested" / "selected.txt"
+ selected.parent.mkdir()
+ selected.touch()
+
+ fb = file_browser(
+ initial_path=tmp_path,
+ value=selected,
+ restrict_navigation=True,
+ )
+
+ assert fb._initial_path == tmp_path
+
+
def test_file_browser_single_default_value(tmp_path: Path) -> None:
selected = tmp_path / "selected.txt"
selected.touch()
@@ -61,6 +226,13 @@ def test_file_browser_single_default_value(tmp_path: Path) -> None:
assert fb.path() == selected
+def test_file_browser_rejects_missing_default_value(tmp_path: Path) -> None:
+ missing = tmp_path / "missing.txt"
+
+ with pytest.raises(ValueError, match="does not exist"):
+ file_browser(initial_path=tmp_path, value=missing)
+
+
def test_file_browser_rejects_multiple_default_values(
tmp_path: Path,
) -> None: