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
improvement: make our file-explorer more compatible with s3 mount (#5286)
Myles Scolnick2b8e7b21a34c
diff --git a/marimo/_server/export/exporter.py b/marimo/_server/export/exporter.pyindex 76440f1b7a..2c13b4ff8d 100644--- a/marimo/_server/export/exporter.py+++ b/marimo/_server/export/exporter.py@@ -516,6 +516,8 @@ class AutoExporter:def _write_file_sync(self, filepath: Path, content: str) -> None:"""Synchronous file write (runs in thread pool)"""+ if content == "":+ returnfilepath.write_text(content, encoding="utf-8")async def _ensure_export_dir_async(self, directory: Path) -> None:diff --git a/marimo/_server/files/file_system.py b/marimo/_server/files/file_system.pyindex 5712a4b195..70dab10f31 100644--- a/marimo/_server/files/file_system.py+++ b/marimo/_server/files/file_system.py@@ -19,8 +19,13 @@ class FileSystem(ABC):pass@abstractmethod- def get_details(self, path: str) -> FileDetailsResponse:- """Get details of a specific file or directory."""+ def get_details(+ self,+ path: str,+ encoding: str | None = None,+ contents: str | None = None,+ ) -> FileDetailsResponse:+ """Get details of a specific file or directory. If contents is provided, use it instead of reading from disk."""pass@abstractmethoddiff --git a/marimo/_server/files/os_file_system.py b/marimo/_server/files/os_file_system.pyindex 970bc80185..6b2cf6581b 100644--- a/marimo/_server/files/os_file_system.py+++ b/marimo/_server/files/os_file_system.py@@ -84,17 +84,21 @@ class OSFileSystem(FileSystem):)def get_details(- self, path: str, encoding: str | None = None+ self,+ path: str,+ encoding: str | None = None,+ contents: str | None = None,) -> FileDetailsResponse:file_info = self._get_file_info(path)- contents = (- self.open_file(path, encoding=encoding)- if not file_info.is_directory- else None- )+ if file_info.is_directory:+ actual_contents = None+ elif contents is not None:+ actual_contents = contents+ else:+ actual_contents = self.open_file(path, encoding=encoding)mime_type = mimetypes.guess_type(path)[0]return FileDetailsResponse(- file=file_info, contents=contents, mime_type=mime_type+ file=file_info, contents=actual_contents, mime_type=mime_type)def _is_marimo_file(self, path: str) -> bool:@@ -105,13 +109,12 @@ class OSFileSystem(FileSystem):return b"app = marimo.App(" in file_path.read_bytes()def open_file(self, path: str, encoding: str | None = None) -> str:+ file_path = Path(path)try:- with open(path, encoding=encoding) as file:- return file.read()+ return file_path.read_text(encoding=encoding)except UnicodeDecodeError:# If its a UnicodeDecodeError, try as bytes and convert to base64- with open(path, mode="rb") as file:- return base64.b64encode(file.read()).decode("utf-8")+ return base64.b64encode(file_path.read_bytes()).decode("utf-8")def create_file_or_directory(self,@@ -148,11 +151,17 @@ class OSFileSystem(FileSystem):full_path.write_bytes(contents or b"")# encoding latin-1 to get an invertible representation of the# bytes as a string ...- return self.get_details(str(full_path), encoding="latin-1").file+ return self.get_details(+ str(full_path),+ encoding="latin-1",+ contents=(+ contents.decode("latin-1") if contents is not None else None+ ),+ ).filedef delete_file_or_directory(self, path: str) -> bool:if os.path.isdir(path):- shutil.rmtree(path)+ safe_rmtree(path)else:os.remove(path)return True@@ -162,14 +171,18 @@ class OSFileSystem(FileSystem):# Disallow renaming to . or ..if file_name in DISALLOWED_NAMES:raise ValueError(f"Cannot rename to {new_path}")-- shutil.move(path, new_path)+ # Disallow moving to an existing path or directory+ if os.path.exists(new_path) or os.path.isdir(new_path):+ raise ValueError(+ f"Destination path {new_path} already exists or is a directory"+ )+ safe_move(path, new_path)return self.get_details(new_path).filedef update_file(self, path: str, contents: str) -> FileInfo:file_path = Path(path)file_path.write_text(contents)- return self.get_details(path).file+ return self.get_details(path, contents=contents).filedef open_in_editor(self, path: str) -> bool:try:@@ -230,3 +243,50 @@ def _is_terminal_editor(editor: str) -> bool:"micro",])+++def safe_rmtree(path: str) -> None:+ """+ Remove a directory tree. If shutil.rmtree fails, recursively delete all files from the leaves up.++ This is so we can be compatible with https://github.com/awslabs/mountpoint-s3.+ """+ try:+ shutil.rmtree(path)+ except PermissionError:+ # Fallback: manual post-order traversal+ p = Path(path)+ for sub in sorted(+ p.rglob("*"), key=lambda x: -x.as_posix().count("/")+ ):+ try:+ if sub.is_file() or sub.is_symlink():+ sub.unlink()+ elif sub.is_dir():+ sub.rmdir()+ except Exception as inner_e:+ LOGGER.warning("Failed to delete %s: %s", sub, inner_e)+ try:+ p.rmdir()+ except Exception as final_e:+ LOGGER.warning("Failed to delete directory %s: %s", p, final_e)+++def safe_move(src: str, dst: str) -> None:+ """+ Move a file or directory, but if it fails due to permissions,+ copy the file or directory and then delete the original.++ This is so we can be compatible with https://github.com/awslabs/mountpoint-s3.+ """+ try:+ shutil.move(src, dst)+ except PermissionError:+ # Fallback: copy then delete+ src_path = Path(src)+ if src_path.is_dir():+ shutil.copytree(src, dst)+ safe_rmtree(src)+ else:+ shutil.copy2(src, dst)+ src_path.unlink()diff --git a/pyproject.toml b/pyproject.tomlindex 88d64b99a5..6e4a83bec5 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -509,6 +509,7 @@ wheres = "wheres"Ue = "Ue" # Used in one of the cell IDsNd = "Nd" # Confused with Andpn = "pn" # Panel+caf = "caf" # cafe[tool.typos.files]extend-exclude = [diff --git a/tests/_server/files/test_os_file_system.py b/tests/_server/files/test_os_file_system.pyindex 3ad5cb2c5c..b8a4ef2d0d 100644--- a/tests/_server/files/test_os_file_system.py+++ b/tests/_server/files/test_os_file_system.py@@ -1,7 +1,6 @@from __future__ import annotations-import os-from tempfile import TemporaryDirectory+from pathlib import Pathimport pytest@@ -10,13 +9,10 @@ from marimo._server.models.files import FileDetailsResponse@pytest.fixture-def test_dir():- # Create a temporary directory for the tests- temp_dir = TemporaryDirectory()- test_dir = temp_dir.name- yield test_dir- # Cleanup the temporary directory after each test- temp_dir.cleanup()+def test_dir(tmp_path_factory: pytest.TempPathFactory) -> Path:+ temp_dir = tmp_path_factory.mktemp("marimo_test")+ # pytest handles cleanup+ return temp_dir@pytest.fixture@@ -24,89 +20,90 @@ def fs():return OSFileSystem()-def test_create_file(test_dir: str, fs: OSFileSystem) -> None:+def test_create_file(test_dir: Path, fs: OSFileSystem) -> None:test_file_name = "test_file.txt"- fs.create_file_or_directory(test_dir, "file", test_file_name, None)- expected_path = os.path.join(test_dir, test_file_name)- assert os.path.exists(expected_path)+ fs.create_file_or_directory(str(test_dir), "file", test_file_name, None)+ expected_path = test_dir / test_file_name+ assert expected_path.exists()def test_create_file_with_duplicate_name(- test_dir: str, fs: OSFileSystem+ test_dir: Path, fs: OSFileSystem) -> None:test_file_name = "test_file.txt"- fs.create_file_or_directory(test_dir, "file", test_file_name, None)- # Create a file with the same name- fs.create_file_or_directory(test_dir, "file", test_file_name, None)- # Expecting a new file with a different name- expected_path = os.path.join(test_dir, "test_file_1.txt")- assert os.path.exists(expected_path)+ fs.create_file_or_directory(str(test_dir), "file", test_file_name, None)+ fs.create_file_or_directory(str(test_dir), "file", test_file_name, None)+ expected_path = test_dir / "test_file_1.txt"+ assert expected_path.exists()def test_create_file_and_parent_directories(- test_dir: str, fs: OSFileSystem+ test_dir: Path, fs: OSFileSystem) -> None:test_file_name = "test_file.txt"fs.create_file_or_directory(- f"{test_dir}/parent", "file", test_file_name, None+ str(test_dir / "parent"), "file", test_file_name, None)- expected_path = os.path.join(test_dir, "parent", test_file_name)- assert os.path.exists(expected_path)+ expected_path = test_dir / "parent" / test_file_name+ assert expected_path.exists()-def test_create_directory(test_dir: str, fs: OSFileSystem) -> None:+def test_create_directory(test_dir: Path, fs: OSFileSystem) -> None:test_dir_name = "test_dir"- fs.create_file_or_directory(test_dir, "directory", test_dir_name, None)- expected_path = os.path.join(test_dir, test_dir_name)- assert os.path.isdir(expected_path)+ fs.create_file_or_directory(+ str(test_dir), "directory", test_dir_name, None+ )+ expected_path = test_dir / test_dir_name+ assert expected_path.is_dir()-def test_create_with_empty_name(test_dir: str, fs: OSFileSystem) -> None:+def test_create_with_empty_name(test_dir: Path, fs: OSFileSystem) -> None:with pytest.raises(ValueError):- fs.create_file_or_directory(test_dir, "file", "", None)+ fs.create_file_or_directory(str(test_dir), "file", "", None)-def test_create_with_disallowed_name(test_dir: str, fs: OSFileSystem) -> None:+def test_create_with_disallowed_name(test_dir: Path, fs: OSFileSystem) -> None:with pytest.raises(ValueError):- fs.create_file_or_directory(test_dir, "file", ".", None)+ fs.create_file_or_directory(str(test_dir), "file", ".", None)-def test_list_files(test_dir: str, fs: OSFileSystem) -> None:- # Create a test file and directory+def test_list_files(test_dir: Path, fs: OSFileSystem) -> None:test_create_file(test_dir, fs)test_create_directory(test_dir, fs)- files = fs.list_files(test_dir)+ files = fs.list_files(str(test_dir))assert len(files) == 2 # Expecting 1 file and 1 directorydef test_list_files_with_broken_directory_symlink(- test_dir: str, fs: OSFileSystem+ test_dir: Path, fs: OSFileSystem) -> None:- # Create a broken symlink- broken_symlink = os.path.join(test_dir, "broken_symlink")- os.symlink("non_existent_file", broken_symlink)- files = fs.list_files(test_dir)+ broken_symlink = test_dir / "broken_symlink"+ broken_symlink.symlink_to("non_existent_file")+ files = fs.list_files(str(test_dir))assert len(files) == 0-def test_get_details(test_dir: str, fs: OSFileSystem) -> None:+def test_get_details(test_dir: Path, fs: OSFileSystem) -> None:test_file_name = "test_file.txt"fs.create_file_or_directory(- test_dir,+ str(test_dir),"file",test_file_name,b"some content",)- file_info = fs.get_details(os.path.join(test_dir, test_file_name))+ file_path = test_dir / test_file_name+ file_info = fs.get_details(str(file_path))assert isinstance(file_info, FileDetailsResponse)assert file_info.file.name == test_file_nameassert file_info.mime_type == "text/plain"assert file_info.contents == "some content"+ file_info2 = fs.get_details(str(file_path), contents="direct content")+ assert file_info2.contents == "direct content"@pytest.mark.parametrize("encoding", ["utf-8", "iso-8859-1"])def test_get_details_marimo_file(- test_dir: str, fs: OSFileSystem, encoding+ test_dir: Path, fs: OSFileSystem, encoding: str) -> None:test_file_name = "app.py"content = """@@ -123,64 +120,62 @@ def test_get_details_marimo_file(app.run()"""fs.create_file_or_directory(- test_dir, "file", test_file_name, content.encode(encoding=encoding)+ str(test_dir),+ "file",+ test_file_name,+ content.encode(encoding=encoding),)- file_path = os.path.join(test_dir, test_file_name)- file_info = fs.get_details(file_path)+ file_path = test_dir / test_file_name+ file_info = fs.get_details(str(file_path))assert isinstance(file_info, FileDetailsResponse)assert file_info.file.is_marimo_file-def test_open_file(test_dir: str, fs: OSFileSystem) -> None:+def test_open_file(test_dir: Path, fs: OSFileSystem) -> None:test_file_name = "test_file.txt"test_content = "Hello, World!"- with open(os.path.join(test_dir, test_file_name), "w") as f:- f.write(test_content)- content = fs.open_file(os.path.join(test_dir, test_file_name))+ file_path = test_dir / test_file_name+ file_path.write_text(test_content)+ content = fs.open_file(str(file_path))assert content == test_content-def test_delete_file(test_dir: str, fs: OSFileSystem) -> None:+def test_delete_file(test_dir: Path, fs: OSFileSystem) -> None:test_file_name = "test_file.txt"- file_path = os.path.join(test_dir, test_file_name)- with open(file_path, "w"):- pass- fs.delete_file_or_directory(file_path)- assert not os.path.exists(file_path)+ file_path = test_dir / test_file_name+ file_path.write_text("")+ fs.delete_file_or_directory(str(file_path))+ assert not file_path.exists()-def test_move_file(test_dir: str, fs: OSFileSystem) -> None:+def test_move_file(test_dir: Path, fs: OSFileSystem) -> None:original_file_name = "original.txt"new_file_name = "new.txt"- original_path = os.path.join(test_dir, original_file_name)- new_path = os.path.join(test_dir, new_file_name)- with open(original_path, "w") as f:- f.write("Test")- fs.move_file_or_directory(original_path, new_path)- assert os.path.exists(new_path)- assert not os.path.exists(original_path)+ original_path = test_dir / original_file_name+ new_path = test_dir / new_file_name+ original_path.write_text("Test")+ fs.move_file_or_directory(str(original_path), str(new_path))+ assert new_path.exists()+ assert not original_path.exists()-def test_move_with_disallowed_name(test_dir: str, fs: OSFileSystem) -> None:+def test_move_with_disallowed_name(test_dir: Path, fs: OSFileSystem) -> None:original_file_name = "original.txt"new_file_name = "."- original_path = os.path.join(test_dir, original_file_name)- new_path = os.path.join(test_dir, new_file_name)- with open(original_path, "w"):- pass+ original_path = test_dir / original_file_name+ new_path = test_dir / new_file_name+ original_path.write_text("")with pytest.raises(ValueError):- fs.move_file_or_directory(original_path, new_path)+ fs.move_file_or_directory(str(original_path), str(new_path))-def test_update_file(test_dir: str, fs: OSFileSystem) -> None:+def test_update_file(test_dir: Path, fs: OSFileSystem) -> None:test_file_name = "test_file.txt"- file_path = os.path.join(test_dir, test_file_name)- with open(file_path, "w") as f:- f.write("Initial content")+ file_path = test_dir / test_file_name+ file_path.write_text("Initial content")new_content = "Updated content"- fs.update_file(file_path, new_content)- with open(file_path) as f:- assert f.read() == new_content+ fs.update_file(str(file_path), new_content)+ assert file_path.read_text() == new_contentdef test_natural_sort_key() -> None:@@ -206,3 +201,87 @@ def test_natural_sort_key() -> None:"file20.txt",]assert sorted_files == expected_order+++def test_get_details_with_encoding_and_contents(+ test_dir: Path, fs: OSFileSystem+) -> None:+ test_file_name = "test_file.txt"+ file_path = test_dir / test_file_name+ file_path.write_text("should not see this", encoding="utf-8")+ result = fs.get_details(+ str(file_path), encoding="utf-8", contents="override"+ )+ assert result.contents == "override"+++def test_get_details_directory(test_dir: Path, fs: OSFileSystem) -> None:+ dir_path = test_dir / "subdir"+ dir_path.mkdir()+ result = fs.get_details(str(dir_path))+ assert result.file.is_directory+ assert result.contents is None+++def test_get_details_nonexistent_file(fs: OSFileSystem) -> None:+ from tempfile import gettempdir++ non_existent = Path(gettempdir()) / "this_file_does_not_exist.txt"+ with pytest.raises(FileNotFoundError):+ fs.get_details(str(non_existent))+++def test_get_details_binary_file(test_dir: Path, fs: OSFileSystem) -> None:+ file_path = test_dir / "binfile.bin"+ file_path.write_bytes(b"\x00\x01\x02\x03")+ result = fs.get_details(str(file_path))++ assert result.contents == "\x00\x01\x02\x03"+++def test_get_details_empty_string_contents(+ test_dir: Path, fs: OSFileSystem+) -> None:+ test_file_name = "test_file.txt"+ file_path = test_dir / test_file_name+ file_path.write_text("should not see this", encoding="utf-8")+ result = fs.get_details(str(file_path), contents="")+ assert result.contents == ""+++def test_get_details_none_contents_reads_disk(+ test_dir: Path, fs: OSFileSystem+) -> None:+ test_file_name = "test_file.txt"+ file_path = test_dir / test_file_name+ file_path.write_text("disk content", encoding="utf-8")+ result = fs.get_details(str(file_path), contents=None)+ assert result.contents == "disk content"+++def test_get_details_contents_for_directory(+ test_dir: Path, fs: OSFileSystem+) -> None:+ dir_path = test_dir / "subdir"+ dir_path.mkdir()+ result = fs.get_details(str(dir_path), contents="should be ignored")+ assert result.file.is_directory+ assert result.contents is None+++def test_get_details_non_utf8_encoding_and_contents(+ test_dir: Path, fs: OSFileSystem+) -> None:+ test_file_name = "latin1.txt"+ file_path = test_dir / test_file_name+ content = "caf\xe9".encode("latin-1")+ file_path.write_bytes(content)+ result = fs.get_details(str(file_path), encoding="latin-1")+ assert result.contents == "café"+ base64_content = __import__("base64").b64encode(content).decode("utf-8")+ result_utf8 = fs.get_details(str(file_path), encoding="utf-8")+ assert result_utf8.contents == base64_content+ result2 = fs.get_details(+ str(file_path), encoding="utf-8", contents="override"+ )+ assert result2.contents == "override"