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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
fix: handle cloudpath client (#4130)
Myles Scolnickacb547f08394
diff --git a/marimo/_plugins/ui/_impl/file_browser.py b/marimo/_plugins/ui/_impl/file_browser.pyindex ffb4ba2ea0..1889d8e7bf 100644--- a/marimo/_plugins/ui/_impl/file_browser.py+++ b/marimo/_plugins/ui/_impl/file_browser.py@@ -6,8 +6,10 @@ from collections.abc import Sequencefrom dataclasses import dataclassfrom pathlib import Pathfrom typing import (+ Any,Callable,Final,+ Literal,Optional,TypedDict,Union,@@ -16,6 +18,7 @@ from typing import (from marimo import _loggersfrom marimo._output.rich_help import mddocfrom marimo._plugins.ui._core.ui_element import UIElement+from marimo._plugins.validators import validate_one_offrom marimo._runtime.functions import FunctionLOGGER = _loggers.marimo_logger()@@ -72,7 +75,7 @@ class file_browser(from cloudpathlib import S3Pathfile_browser = mo.ui.file_browser(- initial_path=S3Path("s3://mybucket/mydir")+ initial_path=S3Path("s3://my-bucket/folder/"))# Access the selected file path(s):@@ -82,6 +85,20 @@ class file_browser(file_browser.path(index).read_text()```+ Using with client credentials:+ ```python+ from cloudpathlib import GSClient, GSPath++ # Create a client with credentials+ gs_client = GSClient("storage_credentials.json", project="my-project")++ # Create a path with the client+ cloudpath = GSPath("gs://my-bucket/folder", client=gs_client)++ # Use the path with file_browser+ file_browser = mo.ui.file_browser(initial_path=cloudpath)+ ```+Attributes:value (Sequence[FileInfo]): A sequence of file paths representing selectedfiles.@@ -93,10 +110,11 @@ class file_browser(If a Path, it will be interpreted as a local path.If a CloudPath (from cloudpathlib), such as S3Path, GCSPath, or AzurePath,files will be loaded from the respective cloud storage bucket.+ If a CloudPath with a client is provided, that client will be used for all operations.filetypes (Sequence[str], optional): The file types to display in eachdirectory; for example, filetypes=[".txt", ".csv"]. If None, allfiles are displayed. Defaults to None.- selection_mode (str, optional): Either "file" or "directory". Defaults to+ selection_mode (Literal["file", "directory"], optional): Either "file" or "directory". Defaults to"file".multiple (bool, optional): If True, allow the user to select multiplefiles. Defaults to True.@@ -114,7 +132,7 @@ class file_browser(self,initial_path: Union[str, Path] = "",filetypes: Optional[Sequence[str]] = None,- selection_mode: str = "file",+ selection_mode: Literal["file", "directory"] = "file",multiple: bool = True,restrict_navigation: bool = False,*,@@ -124,17 +142,7 @@ class file_browser(Callable[[Sequence[FileBrowserFileInfo]], None]] = None,) -> None:- if (- selection_mode != "file"- and selection_mode != "directory"- and selection_mode != "all"- ):- raise ValueError(- "Invalid argument for selection_mode. "- + "Must be either 'file' or 'directory'."- )- else:- self.selection_mode = selection_mode+ validate_one_of(selection_mode, ["file", "directory"])if not initial_path:initial_path = Path.cwd()@@ -149,16 +157,17 @@ class file_browser(f"Initial path {initial_path} is not a directory.")- self.filetypes: set[str] = set(filetypes) if filetypes else set()- self.restrict_navigation = restrict_navigation- self.initial_path: Path = initial_path- self.limit = limit+ self._selection_mode = selection_mode+ self._filetypes: set[str] = set(filetypes) if filetypes else set()+ self._restrict_navigation = restrict_navigation+ self._initial_path: Path = initial_path+ self._limit = limit- self.path_cls: type[Path]+ self._path_cls: type[Path]if isinstance(initial_path, str):- self.path_cls = Path+ self._path_cls = Pathelse:- self.path_cls = initial_path.__class__+ self._path_cls = initial_path.__class__super().__init__(component_name=file_browser._name,@@ -181,6 +190,18 @@ class file_browser(on_change=on_change,)+ def _create_path(self, path_str: str) -> 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)+ return path+def _list_directory(self, args: ListDirectoryArgs) -> ListDirectoryResponse:@@ -190,9 +211,9 @@ class file_browser(# Convert to original class of initial_path# so that it works with anything that extended Path# such as CloudPath- path = self.path_cls(args.path)+ path = self._create_path(args.path)- if self.restrict_navigation and path in self.initial_path.parents:+ if self._restrict_navigation and path in self._initial_path.parents:raise RuntimeError("Navigation is restricted; navigating to a ""parent of initial path is not allowed."@@ -203,12 +224,12 @@ class file_browser(_, extension = os.path.splitext(file.name)# Skip non-directories if selection mode is directory- if self.selection_mode == "directory" and not file.is_dir():+ if self._selection_mode == "directory" and not file.is_dir():continue# Skip non-matching file types- if self.filetypes and not file.is_dir():- if extension not in self.filetypes:+ if self._filetypes and not file.is_dir():+ if extension not in self._filetypes:continuefiles.append(@@ -220,7 +241,7 @@ class file_browser())- if len(files) >= self.limit:+ if len(files) >= self._limit:breakreturn ListDirectoryResponse(files)@@ -232,7 +253,7 @@ class file_browser(FileBrowserFileInfo(id=file["id"],name=file["name"],- path=self.path_cls(file["path"]),+ path=self._create_path(file["path"]),is_directory=file["is_directory"],)for file in valuediff --git a/marimo/_plugins/validators.py b/marimo/_plugins/validators.pyindex 83d3b5faa9..9122e865a5 100644--- a/marimo/_plugins/validators.py+++ b/marimo/_plugins/validators.py@@ -85,3 +85,8 @@ def validate_page_size(page_size: int) -> None:raise ValueError("Page size limited to 200 rows. If you'd like this increased, please file an issue")+++def validate_one_of(value: Any, options: list[Any]) -> None:+ if value not in options:+ raise ValueError(f"Value must be one of {options}")diff --git a/tests/_plugins/ui/_impl/test_file_browser.py b/tests/_plugins/ui/_impl/test_file_browser.pyindex ecf2c55bdc..cbb1c5a19a 100644--- a/tests/_plugins/ui/_impl/test_file_browser.py+++ b/tests/_plugins/ui/_impl/test_file_browser.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport sysimport tempfilefrom pathlib import Path+from typing import Any, Optionalimport pytest@@ -18,11 +19,11 @@ def test_file_browser_init() -> None:# Use a temporary directory for testingwith tempfile.TemporaryDirectory() as temp_dir:fb = file_browser(initial_path=temp_dir)- assert isinstance(fb.initial_path, Path)- assert str(fb.initial_path) == str(Path(temp_dir).resolve())- assert fb.selection_mode == "file"- assert fb.filetypes == set()- assert fb.restrict_navigation is False+ assert isinstance(fb._initial_path, Path)+ assert str(fb._initial_path) == str(Path(temp_dir).resolve())+ assert fb._selection_mode == "file"+ assert fb._filetypes == set()+ assert fb._restrict_navigation is False# Test with custom filetypescustom_filetypes = [".txt", ".csv"]@@ -32,10 +33,10 @@ def test_file_browser_init() -> None:selection_mode="directory",restrict_navigation=True,)- assert fb.initial_path == Path(temp_dir).resolve()- assert fb.filetypes == set(custom_filetypes)- assert fb.selection_mode == "directory"- assert fb.restrict_navigation is True+ assert fb._initial_path == Path(temp_dir).resolve()+ assert fb._filetypes == set(custom_filetypes)+ assert fb._selection_mode == "directory"+ assert fb._restrict_navigation is Truedef test_list_directory() -> None:@@ -46,7 +47,7 @@ def test_list_directory() -> None:assert isinstance(response, ListDirectoryResponse)for file_info in response.files:assert file_info["is_directory"] or file_info["path"].endswith(- tuple(fb.filetypes)+ tuple(fb._filetypes))@@ -108,3 +109,30 @@ def test_extended_path_class(tmp_path: Path) -> None:assert len(value) == 1assert isinstance(value[0], FileBrowserFileInfo)assert isinstance(value[0].path, CustomPath)++ class CustomPathWithClient(Path):+ def __init__(self, path: Path, client: Optional[Any] = None) -> None:+ super().__init__(path)+ self.client = client++ def resolve(self) -> CustomPathWithClient:+ return CustomPathWithClient(super().resolve(), self.client)++ fb = file_browser(+ initial_path=CustomPathWithClient(tmp_path, "custom_client")+ )+ response = fb._list_directory(+ ListDirectoryArgs(path=str(tmp_path)),+ )+ value = fb._convert_value(response.files)+ assert isinstance(value, tuple)+ assert len(value) == 1+ assert isinstance(value[0], FileBrowserFileInfo)+ assert isinstance(value[0].path, CustomPathWithClient)+ assert value[0].path.client == "custom_client"+++def test_validation() -> None:+ with pytest.raises(ValueError) as e:+ file_browser(initial_path="invalid", selection_mode="invalid")+ assert "Value must be one of" in str(e.value)