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.

improvement: better sort order for mo.ui.file_browser() (#5350)

Myles Scolnick90ea30356845
diff --git a/marimo/_plugins/ui/_impl/file_browser.py b/marimo/_plugins/ui/_impl/file_browser.py
index 6850ee84be..396aa70ad6 100644
--- a/marimo/_plugins/ui/_impl/file_browser.py
+++ b/marimo/_plugins/ui/_impl/file_browser.py
@@ -1,7 +1,6 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
-import os
from collections.abc import Sequence
from dataclasses import dataclass
from pathlib import Path
@@ -20,6 +19,7 @@ from marimo._output.rich_help import mddoc
from marimo._plugins.ui._core.ui_element import UIElement
from marimo._plugins.validators import validate_one_of
from marimo._runtime.functions import Function
+from marimo._utils.files import natural_sort
LOGGER = _loggers.marimo_logger()
@@ -218,33 +218,47 @@ class file_browser(
"Navigation is restricted; navigating to a "
"parent of initial path is not allowed."
)
-
+ folders: list[TypedFileBrowserFileInfo] = []
files: list[TypedFileBrowserFileInfo] = []
+
for file in path.iterdir():
- _, extension = os.path.splitext(file.name)
+ extension = file.suffix
+ is_directory = file.is_dir()
# 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 is_directory:
continue
# Skip non-matching file types
- if self._filetypes and not file.is_dir():
+ if self._filetypes and not is_directory:
if extension not in self._filetypes:
continue
- files.append(
- TypedFileBrowserFileInfo(
- id=str(file),
- path=str(file),
- name=file.name,
- is_directory=file.is_dir(),
- )
+ file_info = TypedFileBrowserFileInfo(
+ id=str(file),
+ path=str(file),
+ name=file.name,
+ is_directory=is_directory,
)
- if len(files) >= self._limit:
+ if is_directory:
+ folders.append(file_info)
+ else:
+ files.append(file_info)
+
+ if len(folders) + len(files) >= self._limit:
break
- return ListDirectoryResponse(files)
+ def natural_sort_info(
+ info: TypedFileBrowserFileInfo,
+ ) -> list[Union[int, str]]:
+ return natural_sort(info["name"])
+
+ # Sort folders then files, based on natural sort (alpha, then num)
+ all_files = sorted(folders, key=natural_sort_info) + sorted(
+ files, key=natural_sort_info
+ )
+ return ListDirectoryResponse(all_files)
def _convert_value(
self, value: list[TypedFileBrowserFileInfo]
diff --git a/marimo/_server/files/os_file_system.py b/marimo/_server/files/os_file_system.py
index 6b2cf6581b..c7064a56ca 100644
--- a/marimo/_server/files/os_file_system.py
+++ b/marimo/_server/files/os_file_system.py
@@ -5,7 +5,6 @@ import base64
import mimetypes
import os
import platform
-import re
import shutil
import subprocess
from pathlib import Path
@@ -14,6 +13,7 @@ from typing import Literal, Optional, Union
from marimo import _loggers
from marimo._server.files.file_system import FileSystem
from marimo._server.models.files import FileDetailsResponse, FileInfo
+from marimo._utils.files import natural_sort
LOGGER = _loggers.marimo_logger()
@@ -219,16 +219,6 @@ def natural_sort_file(file: FileInfo) -> list[Union[int, str]]:
return natural_sort(file.name)
-def natural_sort(filename: str) -> list[Union[int, str]]:
- def convert(text: str) -> Union[int, str]:
- return int(text) if text.isdigit() else text.lower()
-
- def alphanum_key(key: str) -> list[Union[int, str]]:
- return [convert(c) for c in re.split("([0-9]+)", key)]
-
- return alphanum_key(filename)
-
-
def _is_terminal_editor(editor: str) -> bool:
return any(
ed in editor.lower()
diff --git a/marimo/_utils/files.py b/marimo/_utils/files.py
new file mode 100644
index 0000000000..6e6bead1e2
--- /dev/null
+++ b/marimo/_utils/files.py
@@ -0,0 +1,12 @@
+import re
+from typing import Union
+
+
+def natural_sort(filename: str) -> list[Union[int, str]]:
+ def convert(text: str) -> Union[int, str]:
+ return int(text) if text.isdigit() else text.lower()
+
+ def alphanum_key(key: str) -> list[Union[int, str]]:
+ return [convert(c) for c in re.split("([0-9]+)", key)]
+
+ return alphanum_key(filename)
diff --git a/tests/_plugins/ui/_impl/test_file_browser.py b/tests/_plugins/ui/_impl/test_file_browser.py
index cbb1c5a19a..8e2830d1eb 100644
--- a/tests/_plugins/ui/_impl/test_file_browser.py
+++ b/tests/_plugins/ui/_impl/test_file_browser.py
@@ -63,7 +63,7 @@ def test_name_method() -> None:
fb._value = [
FileBrowserFileInfo(
id="1",
- path="/some/path/file.txt",
+ path=Path("/some/path/file.txt"),
name="file.txt",
is_directory=False,
)
@@ -77,15 +77,118 @@ def test_path_method() -> None:
fb._value = [
FileBrowserFileInfo(
id="1",
- path="/some/path/file.txt",
+ path=Path("/some/path/file.txt"),
name="file.txt",
is_directory=False,
)
]
- assert fb.path(0) == "/some/path/file.txt"
+ assert fb.path(0) == Path("/some/path/file.txt")
assert fb.path(1) is None
+def test_natural_sorting(tmp_path: Path) -> None:
+ """Test that files are sorted using natural sort order."""
+ # Create test files with names that should be naturally sorted
+ test_files = [
+ "file10.txt",
+ "file2.txt",
+ "file1.txt",
+ "file20.txt",
+ "fileB.txt",
+ "fileA.txt",
+ "file100.txt",
+ ]
+
+ for filename in test_files:
+ (tmp_path / filename).touch()
+
+ fb = file_browser(initial_path=tmp_path)
+ response = fb._list_directory(ListDirectoryArgs(path=str(tmp_path)))
+
+ # Extract file names from response
+ file_names = [f["name"] for f in response.files if not f["is_directory"]]
+
+ # Expected natural sort order
+ expected_order = [
+ "file1.txt",
+ "file2.txt",
+ "file10.txt",
+ "file20.txt",
+ "file100.txt",
+ "fileA.txt",
+ "fileB.txt",
+ ]
+
+ assert file_names == expected_order
+
+
+def test_directories_sorted_before_files(tmp_path: Path) -> None:
+ """Test that directories are sorted before files."""
+ # Create test directories and files
+ (tmp_path / "z_directory").mkdir()
+ (tmp_path / "a_directory").mkdir()
+ (tmp_path / "a_file.txt").touch()
+ (tmp_path / "z_file.txt").touch()
+
+ fb = file_browser(initial_path=tmp_path)
+ response = fb._list_directory(ListDirectoryArgs(path=str(tmp_path)))
+
+ # Extract names and types
+ items = [(f["name"], f["is_directory"]) for f in response.files]
+
+ # Check that all directories come before all files
+ directory_names = [name for name, is_dir in items if is_dir]
+ file_names = [name for name, is_dir in items if not is_dir]
+
+ # Directories should be sorted naturally among themselves
+ assert directory_names == ["a_directory", "z_directory"]
+ # Files should be sorted naturally among themselves
+ assert file_names == ["a_file.txt", "z_file.txt"]
+
+ # All directory names should come before all file names in the full list
+ all_names = [name for name, _ in items]
+ directory_end_index = len(directory_names)
+ assert all_names[:directory_end_index] == directory_names
+ assert all_names[directory_end_index:] == file_names
+
+
+def test_mixed_alphanumeric_sorting(tmp_path: Path) -> None:
+ """Test natural sorting with mixed alphanumeric patterns."""
+ test_items = [
+ ("dir100", True), # directory
+ ("dir2", True), # directory
+ ("dir10", True), # directory
+ ("file100.txt", False), # file
+ ("file2.txt", False), # file
+ ("file10.txt", False), # file
+ ]
+
+ # Create test directories and files
+ for name, is_dir in test_items:
+ if is_dir:
+ (tmp_path / name).mkdir()
+ else:
+ (tmp_path / name).touch()
+
+ fb = file_browser(initial_path=tmp_path)
+ response = fb._list_directory(ListDirectoryArgs(path=str(tmp_path)))
+
+ # Extract names preserving order from response
+ result_names = [f["name"] for f in response.files]
+
+ # Expected order: directories first (naturally sorted), then files (naturally sorted)
+ expected_order = [
+ "dir2", # directories first, naturally sorted
+ "dir10",
+ "dir100",
+ "file2.txt", # files second, naturally sorted
+ "file10.txt",
+ "file100.txt",
+ ]
+
+ assert result_names == expected_order
+
+
@pytest.mark.skipif(
sys.version_info <= (3, 12), reason="Only works with Python 3.12+"
)
diff --git a/tests/_server/files/test_os_file_system.py b/tests/_server/files/test_os_file_system.py
index b8a4ef2d0d..6bab7973a9 100644
--- a/tests/_server/files/test_os_file_system.py
+++ b/tests/_server/files/test_os_file_system.py
@@ -4,8 +4,9 @@ from pathlib import Path
import pytest
-from marimo._server.files.os_file_system import OSFileSystem, natural_sort
+from marimo._server.files.os_file_system import OSFileSystem
from marimo._server.models.files import FileDetailsResponse
+from marimo._utils.files import natural_sort
@pytest.fixture