Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## [Unreleased]

## [0.3.2]

- **TUI folder picker:** **D** shows disks/volumes (Windows drive letters; `/`, `/mnt/*`, and common mount roots on Linux/WSL). Disks also appear above `..` when browsing a volume root.

## [0.3.1]

- **TUI pre-flight:** Modal before batch **P** with file count, output mode, size/token warnings, Continue/Cancel.
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ Synonyms everywhere: `mda-cli`, `mda-tui`.
- **Enter** opens a folder
- **Backspace** goes up
- **H** jumps to your home folder
- **D** opens the disk list (drive letters on Windows; `/`, `/mnt/*`, etc. on Linux/WSL)
- **U** = **Use this folder** when you are in the right place
- **I** toggles the live document preview pane (highlight a supported file to see original content)
- **Q** quits
Expand Down
2 changes: 1 addition & 1 deletion mda_cli/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
"""Markdown Document Architect CLI package."""

__version__ = "0.3.1"
__version__ = "0.3.2"
128 changes: 126 additions & 2 deletions mda_cli/folder_picker.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from __future__ import annotations

import os
import string
from pathlib import Path

from textual import events
Expand All @@ -29,6 +30,96 @@ def _is_windows_hidden(path: Path) -> bool:
return False


def list_windows_drives() -> list[Path]:
"""Return existing Windows drive roots (e.g. ``C:\\``, ``D:\\``)."""
drives: list[Path] = []
for letter in string.ascii_uppercase:
root = f"{letter}:\\"
if os.path.exists(root):
drives.append(Path(root))
return drives


def list_unix_mount_roots() -> list[Path]:
"""Return common filesystem roots on Linux, macOS, and WSL."""
roots: list[Path] = []
seen: set[Path] = set()

def add(path: Path) -> None:
try:
resolved = path.resolve()
except OSError:
return
if not resolved.is_dir() or resolved in seen:
return
seen.add(resolved)
roots.append(resolved)

add(Path("/"))

mnt = Path("/mnt")
if mnt.is_dir():
try:
for child in sorted(mnt.iterdir(), key=lambda p: p.name.lower()):
if child.is_dir():
add(child)
except OSError:
pass

for base in (Path("/media"), Path("/run/media")):
if not base.is_dir():
continue
try:
for user_dir in sorted(base.iterdir(), key=lambda p: p.name.lower()):
if not user_dir.is_dir():
continue
for mount in sorted(user_dir.iterdir(), key=lambda p: p.name.lower()):
if mount.is_dir():
add(mount)
except OSError:
pass

return sorted(roots, key=lambda p: str(p).lower())


def list_disks() -> list[Path]:
"""Return selectable disk/volume roots for the current platform."""
if os.name == "nt":
return list_windows_drives()
return list_unix_mount_roots()


def is_volume_root(path: Path) -> bool:
"""True when ``path`` is a top-level volume root (drive or mount)."""
if os.name == "nt":
try:
resolved = path.resolve()
except OSError:
return False
drive = resolved.drive
if not drive:
return False
return resolved == Path(f"{drive}\\")

posix = path.as_posix().rstrip("/") or "/"
if posix == "/":
return True
segments = [part for part in posix.split("/") if part]
if len(segments) == 2 and segments[0] == "mnt":
return True
if len(segments) == 3 and segments[0] == "media":
return True
if len(segments) == 4 and segments[0] == "run" and segments[1] == "media":
return True
return False


def _disk_row_label(path: Path) -> str:
if os.name == "nt" and path.drive:
return f"{path.drive}\\"
return str(path)


class FolderPickerApp(App[Path | None]):
"""Browse directories and confirm a working folder for MDA."""

Expand All @@ -44,6 +135,7 @@ class FolderPickerApp(App[Path | None]):
Binding("q", "quit_cancel", "Quit", show=True),
Binding("escape", "quit_cancel", "Quit"),
Binding("u", "use_folder", "Use this folder", show=True),
Binding("d", "show_disks", "Disks", show=True),
Binding("h", "go_home", "Home", show=True),
Binding("k", "cursor_up", "Up", show=False),
Binding("j", "cursor_down", "Down", show=False),
Expand All @@ -57,6 +149,7 @@ def __init__(self, *, start: Path | None) -> None:
self._rows: list[tuple[Path | None, str]] = []
self._row_key_seq = 0
self.selected_folder: Path | None = None
self._disk_only_view = False

def _alloc_row_key(self) -> str:
self._row_key_seq += 1
Expand All @@ -69,7 +162,7 @@ def compose(self) -> ComposeResult:
yield Label(id="path-label")
yield Label(id="file-count-label")
yield Label(
"Enter = open | Backspace = up | U = use folder | H = home | Q = quit",
"Enter = open | Backspace = up | D = disks | U = use folder | H = home | Q = quit",
id="hint",
)
yield DataTable(id="listing", zebra_stripes=True, cursor_type="row")
Expand Down Expand Up @@ -109,6 +202,16 @@ def on_key(self, event: events.Key) -> None:
event.prevent_default()
event.stop()

def _add_disk_rows(self, table: DataTable) -> None:
for disk in list_disks():
table.add_row(
_disk_row_label(disk),
"disk",
"",
key=self._alloc_row_key(),
)
self._rows.append((disk, "disk"))

def refresh_listing(self) -> None:
table = self.query_one("#listing", DataTable)
table.clear()
Expand All @@ -121,12 +224,21 @@ def refresh_listing(self) -> None:
f"Supported files in this folder ({exts}): {here_n}"
)

if self._disk_only_view:
self._add_disk_rows(table)
table.focus()
return

if not self.cwd.is_dir():
return

if is_volume_root(self.cwd):
self._add_disk_rows(table)

try:
entries = list(self.cwd.iterdir())
except OSError:
table.focus()
return

dirs = sorted([p for p in entries if p.is_dir()], key=lambda p: p.name.lower())
Expand Down Expand Up @@ -158,24 +270,36 @@ def _cursor_row_index(self) -> int | None:
return row

def action_go_up(self) -> None:
if self._disk_only_view:
self._disk_only_view = False
self.refresh_listing()
return
parent = self.cwd.parent
if parent == self.cwd:
return
self.cwd = parent.resolve()
self.refresh_listing()

def action_go_home(self) -> None:
self._disk_only_view = False
self.cwd = Path.home().resolve()
self.refresh_listing()

def action_show_disks(self) -> None:
self._disk_only_view = not self._disk_only_view
self.refresh_listing()

def action_open(self) -> None:
idx = self._cursor_row_index()
if idx is None:
return
path, kind = self._rows[idx]
if path is None:
return
if kind == "up":
if kind == "disk":
self.cwd = path.resolve()
self._disk_only_view = False
elif kind == "up":
self.cwd = path.resolve()
elif kind == "dir":
self.cwd = path.resolve()
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "hatchling.build"

[project]
name = "mda-cli"
version = "0.3.1"
version = "0.3.2"
description = "CLI wrapper for Markdown Document Architect — restructure Markdown via Anthropic using local SKILL.md + MDA-STANDARD.md"
readme = "README.md"
requires-python = ">=3.10"
Expand Down
111 changes: 110 additions & 1 deletion tests/test_folder_picker.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,13 @@
import pytest

from mda_cli.document_io import count_supported_files_in_dir
from mda_cli.folder_picker import FolderPickerApp
from mda_cli.folder_picker import (
FolderPickerApp,
is_volume_root,
list_disks,
list_unix_mount_roots,
list_windows_drives,
)


def test_count_supported_files_in_dir_non_recursive(tmp_path: Path) -> None:
Expand All @@ -18,6 +24,60 @@ def test_count_supported_files_in_dir_non_recursive(tmp_path: Path) -> None:
assert count_supported_files_in_dir(sub) == 1


def test_list_windows_drives(monkeypatch: pytest.MonkeyPatch) -> None:
def fake_exists(path: str) -> bool:
return path in ("C:\\", "E:\\")

monkeypatch.setattr("mda_cli.folder_picker.os.path.exists", fake_exists)
drives = list_windows_drives()
assert drives == [Path("C:\\"), Path("E:\\")]


def test_list_unix_mount_roots_includes_root() -> None:
import os

if os.name == "nt":
pytest.skip("unix-only")
roots = list_unix_mount_roots()
assert Path("/").resolve() in roots
assert roots == sorted(roots, key=lambda p: str(p).lower())


def test_list_disks_delegates_by_platform(monkeypatch: pytest.MonkeyPatch) -> None:
win = [Path("C:\\")]
unix = [Path("/")]

monkeypatch.setattr("mda_cli.folder_picker.os.name", "nt")
monkeypatch.setattr("mda_cli.folder_picker.list_windows_drives", lambda: win)
assert list_disks() == win

monkeypatch.setattr("mda_cli.folder_picker.os.name", "posix")
monkeypatch.setattr("mda_cli.folder_picker.list_unix_mount_roots", lambda: unix)
assert list_disks() == unix


@pytest.mark.parametrize(
("path", "expected"),
[
(Path("/"), True),
(Path("/mnt/c"), True),
(Path("/media/user/USB"), True),
(Path("/run/media/user/USB"), True),
(Path("/home/user"), False),
(Path("/mnt"), False),
],
)
def test_is_volume_root_unix(path: Path, expected: bool, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr("mda_cli.folder_picker.os.name", "posix")
assert is_volume_root(path) is expected


def test_is_volume_root_windows(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr("mda_cli.folder_picker.os.name", "nt")
assert is_volume_root(Path("C:\\")) is True
assert is_volume_root(Path("C:\\Users")) is False


@pytest.mark.asyncio
async def test_folder_picker_use_folder(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
vault = tmp_path / "vault"
Expand Down Expand Up @@ -45,3 +105,52 @@ async def test_folder_picker_enter_subdirectory(tmp_path: Path) -> None:
await pilot.press("enter")
assert app.cwd.resolve() == sub.resolve()
await pilot.press("q")


@pytest.mark.asyncio
async def test_folder_picker_disk_only_view(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
disks = [tmp_path / "disk-a", tmp_path / "disk-b"]
for d in disks:
d.mkdir()
target = disks[1]

monkeypatch.setattr("mda_cli.folder_picker.list_disks", lambda: disks)
monkeypatch.setattr("mda_cli.folder_picker.set_last_folder", lambda p: None)

app = FolderPickerApp(start=tmp_path / "start")
(tmp_path / "start").mkdir()
async with app.run_test() as pilot:
await pilot.press("d")
assert app._disk_only_view is True
await pilot.press("down")
await pilot.press("enter")
assert app.cwd.resolve() == target.resolve()
assert app._disk_only_view is False
await pilot.press("q")


@pytest.mark.asyncio
async def test_folder_picker_disks_at_volume_root(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
disk = tmp_path / "vol"
disk.mkdir()
sub = disk / "nested"
sub.mkdir()

monkeypatch.setattr("mda_cli.folder_picker.list_disks", lambda: [disk])
monkeypatch.setattr("mda_cli.folder_picker.is_volume_root", lambda p: p.resolve() == disk.resolve())

app = FolderPickerApp(start=disk)
async with app.run_test() as pilot:
kinds = [kind for _, kind in app._rows]
assert kinds.count("disk") == 1
assert "up" in kinds
await pilot.press("down") # disk row
await pilot.press("down") # ..
await pilot.press("down") # nested/
await pilot.press("enter")
assert app.cwd.resolve() == sub.resolve()
await pilot.press("q")