fix(file-manager): browse symlinked directories and expand home

Symlinked directories were listed as files, so Enter opened them in the
editor instead of browsing them. Mappings and the remote control API reach
the panel without a shell, so --start-dir now expands a leading ~ itself.
Add the missing Python integration tests for the result handler.
This commit is contained in:
BlackAngelTV committed 2026-11-26 10:17:34 +01:00
1 parent f2f026c748
commit 603ef78a6e
4 files changed
+195 -3

No files matched your search

+8 -2
View File
@@ -27,7 +27,8 @@ Il peut aussi tourner dans un :doc:`panneau du bureau </kittens/panel>` ou dans
n'importe quelle :term:`fenêtre kitty <window>` classique.
Le répertoire de départ est celui de la fenêtre courante, sauf si un répertoire
est passé en argument ou avec ``--start-dir``.
est passé en argument ou avec ``--start-dir``. Un chemin commençant par ``~``
y est développé, même lorsqu'il vient d'un mappage où le shell ne l'a pas fait.
.. note::
@@ -61,7 +62,9 @@ Actions
:kbd:`→` ou :kbd:`L`
descend dans le répertoire sélectionné ; le shell y va aussi, au prompt
suivant, quand la synchronisation est active.
suivant, quand la synchronisation est active. Un lien symbolique vers un
répertoire se parcourt comme un répertoire ; un lien cassé reste une entrée
ordinaire, ouverte dans l'éditeur.
:kbd:`←`, :kbd:`Retour arrière` ou :kbd:`H`
remonte au répertoire parent.
@@ -232,6 +235,9 @@ Limites
pour changer de répertoire ; utilisez-le depuis une fenêtre de shell.
- Le panneau ne suit pas les modifications faites par d'autres programmes :
utilisez :kbd:`Ctrl+R` pour relire le répertoire.
- Les liens symboliques ne sont pas distingués des fichiers ordinaires dans
l'affichage : seul le fait qu'ils pointent vers un répertoire change leur
comportement à l'ouverture.
.. include:: /generated/conf-kitten-file_manager.rst
+32 -1
View File
@@ -80,7 +80,17 @@ func read_dir(dir string, show_hidden bool, sort_by string) ([]Entry, error) {
continue
}
e := Entry{Name: name, IsDir: item.IsDir()}
if info, ierr := item.Info(); ierr == nil {
info, ierr := item.Info()
if item.Type()&os.ModeSymlink != 0 {
// A symlink is reported as its own type, so a link to a directory
// would be opened in the editor instead of being browsed. Follow
// it to classify the entry; broken links stay plain entries.
if target, terr := os.Stat(filepath.Join(dir, name)); terr == nil {
info, ierr = target, nil
e.IsDir = target.IsDir()
}
}
if ierr == nil {
e.ModTime = info.ModTime().Unix()
e.Size = info.Size()
}
@@ -90,6 +100,23 @@ func read_dir(dir string, show_hidden bool, sort_by string) ([]Entry, error) {
return entries, nil
}
// expand_home expands a leading ~ so that a directory given in a mapping or by
// the remote control API, where no shell expands it, names the same directory
// as it would on the command line.
func expand_home(path string) (string, error) {
if path != "~" && !strings.HasPrefix(path, "~/") {
return path, nil
}
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
if path == "~" {
return home, nil
}
return filepath.Join(home, path[2:]), nil
}
func entry_path(dir, name string) string {
return filepath.Join(dir, name)
}
@@ -169,6 +196,10 @@ func resolve_start_dir(candidate string) (string, error) {
}
candidate = cwd
}
candidate, err := expand_home(candidate)
if err != nil {
return "", err
}
abs, err := filepath.Abs(candidate)
if err != nil {
return "", err
+76
View File
@@ -80,6 +80,66 @@ func TestReadDirReportsErrors(t *testing.T) {
}
}
func TestReadDirAcceptsAnEmptyDirectory(t *testing.T) {
entries, err := read_dir(t.TempDir(), false, "name")
if err != nil {
t.Fatal(err)
}
if len(entries) != 0 {
t.Fatalf("an empty directory must list nothing, got %#v", entries)
}
}
func TestReadDirReportsPermissionDenied(t *testing.T) {
dir := t.TempDir()
if err := os.Chmod(dir, 0o000); err != nil {
t.Skipf("cannot change permissions: %v", err)
}
// Make the directory readable again before TempDir cleans it up.
defer os.Chmod(dir, 0o700) //nolint:errcheck
if _, err := read_dir(dir, false, "name"); err == nil {
t.Skip("the current user can read a mode 000 directory, probably running as root")
}
}
func TestReadDirTreatsSymlinkedDirectoryAsDirectory(t *testing.T) {
dir := t.TempDir()
if err := os.Mkdir(filepath.Join(dir, "target"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.Symlink("target", filepath.Join(dir, "link")); err != nil {
t.Skipf("cannot create symlinks: %v", err)
}
entries, err := read_dir(dir, false, "name")
if err != nil {
t.Fatal(err)
}
for _, e := range entries {
if e.Name == "link" {
if !e.IsDir {
t.Fatal("a symlink to a directory must be browsable, not opened as a file")
}
return
}
}
t.Fatalf("the symlink is missing from the listing: %#v", entries)
}
func TestReadDirHandlesNonUTF8Names(t *testing.T) {
dir := t.TempDir()
name := string([]byte{'b', 'a', 'd', 0xff, '.', 't', 'x', 't'})
if err := os.WriteFile(filepath.Join(dir, name), nil, 0o644); err != nil {
t.Skipf("the filesystem rejects non-UTF-8 names: %v", err)
}
entries, err := read_dir(dir, false, "name")
if err != nil {
t.Fatal(err)
}
if len(entries) != 1 || entries[0].Name != name {
t.Fatalf("the non-UTF-8 name must be listed unchanged, got %#v", entries)
}
}
func TestValidateEntryName(t *testing.T) {
for _, name := range []string{"", ".", "..", "a/b", "a\x00b"} {
if err := validate_entry_name(name); err == nil {
@@ -148,6 +208,22 @@ func TestCreateRenameAndDelete(t *testing.T) {
}
}
func TestResolveStartDirExpandsHome(t *testing.T) {
home := t.TempDir()
projects := filepath.Join(home, "projects")
if err := os.Mkdir(projects, 0o755); err != nil {
t.Fatal(err)
}
t.Setenv("HOME", home)
got, err := resolve_start_dir("~/projects")
if err != nil {
t.Fatal(err)
}
if got != projects {
t.Fatalf("resolve_start_dir(~/projects) = %q, wanted %q", got, projects)
}
}
func TestResolveStartDirAcceptsFiles(t *testing.T) {
dir := t.TempDir()
file := filepath.Join(dir, "file.txt")
+79
View File
@@ -0,0 +1,79 @@
#!/usr/bin/env python
# License: GPLv3 Copyright: 2026, FWS
from unittest.mock import MagicMock, patch
from kittens.file_manager.main import change_directory, handle_result
from .base import BaseTest
class TestFileManager(BaseTest):
def test_file_manager(self):
"""The documented defaults are the ones the panel starts with."""
from kittens.file_manager.main import definition
options = {o.name: o for o in definition.iter_all_options()}
for name, expected in (
('show_hidden', 'no'),
('sort_by', 'name'),
('sync_cwd', 'yes'),
):
self.assertIn(name, options, f'{name} must be a documented option')
self.ae(options[name].defval_as_string, expected, name)
self.assertTrue(options[name].long_text, f'{name} must have help text')
def test_change_directory_at_the_prompt(self):
w = MagicMock()
w.at_prompt = True
change_directory(w, '/tmp/a b')
w.write_to_child.assert_called_once_with("cd '/tmp/a b'\r")
w.paste_text.assert_not_called()
def test_change_directory_while_a_program_runs(self):
# While a program owns the terminal the command is only pasted, so that
# it can be reviewed instead of being fed to the program's stdin.
w = MagicMock()
w.at_prompt = False
change_directory(w, "/tmp/it's")
w.paste_text.assert_called_once_with("cd '/tmp/it'\"'\"'s'")
w.write_to_child.assert_not_called()
def test_result_changes_the_target_window_directory(self):
boss = MagicMock()
window = MagicMock()
boss.window_id_map.get.return_value = window
with patch('kittens.file_manager.main.change_directory') as cd:
handle_result([], {'action': 'cd', 'path': '/tmp/project'}, 42, boss)
cd.assert_called_once_with(window, '/tmp/project')
boss.ring_bell_if_allowed.assert_not_called()
def test_result_with_sync_does_not_type_into_the_shell(self):
# With sync_cwd on, the panel wrote the directory in the session file
# and the shell hook applies it; typing a second cd would move twice.
boss = MagicMock()
with patch('kittens.file_manager.main.change_directory') as cd:
handle_result([], {'action': 'cd', 'path': '/tmp/project', 'sync': True}, 42, boss)
cd.assert_not_called()
boss.window_id_map.get.assert_not_called()
def test_result_without_the_target_window_rings_the_bell(self):
boss = MagicMock()
boss.window_id_map.get.return_value = None
handle_result([], {'action': 'cd', 'path': '/tmp/project'}, 42, boss)
boss.ring_bell_if_allowed.assert_called_once()
def test_result_ignores_incomplete_payloads(self):
boss = MagicMock()
with patch('kittens.file_manager.main.change_directory') as cd:
handle_result([], {}, 42, boss)
handle_result([], {'action': 'open', 'path': '/tmp'}, 42, boss)
handle_result([], {'action': 'cd'}, 42, boss)
cd.assert_not_called()
boss.ring_bell_if_allowed.assert_not_called()