1use ailloli_ui_fs::{FileEntry, FileError, FileKind, FileMetadata, FileProvider, FileUri};
4
5use super::model::FileExplorerNode;
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum FileTreeLoadMode {
22 Lazy,
24 Controlled {
26 preload_depth: usize,
28 },
29 Full,
31}
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum LargeDirectoryPolicy {
43 Load,
45 Placeholder,
47}
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum SymlinkTraversalPolicy {
59 Never,
61 ExplicitExpansionOnly,
63 RecursiveWithCycleGuard,
65}
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
79pub struct FileTreeOptions {
80 pub include_hidden: bool,
82 pub max_depth: usize,
84 pub reveal_selected: bool,
86 pub load_mode: FileTreeLoadMode,
88 pub exclude_defaults: bool,
90 pub max_entries_per_directory: Option<usize>,
92 pub large_directory_policy: LargeDirectoryPolicy,
94 pub symlink_traversal_policy: SymlinkTraversalPolicy,
96}
97
98impl Default for FileTreeOptions {
100 fn default() -> Self {
101 Self {
102 include_hidden: false,
103 max_depth: 8,
104 reveal_selected: true,
105 load_mode: FileTreeLoadMode::Lazy,
106 exclude_defaults: false,
107 max_entries_per_directory: None,
108 large_directory_policy: LargeDirectoryPolicy::Load,
109 symlink_traversal_policy: SymlinkTraversalPolicy::ExplicitExpansionOnly,
110 }
111 }
112}
113
114#[derive(Debug, Clone, Copy, PartialEq, Eq)]
124pub(crate) enum ChildLoadReason {
125 Explicit,
127 Preload,
129}
130
131struct LoadEntryContext<'a> {
133 provider: &'a dyn FileProvider,
135 root: &'a FileUri,
137 expanded: &'a [FileUri],
139 selected: Option<&'a FileUri>,
141 options: FileTreeOptions,
143}
144
145pub fn load_file_tree(
168 provider: &dyn FileProvider,
169 root: &FileUri,
170 expanded: &[FileUri],
171 selected: Option<&FileUri>,
172 options: FileTreeOptions,
173) -> Result<Vec<FileExplorerNode>, FileError> {
174 let metadata = provider.metadata(root)?;
175 let entry = FileEntry::new(root.clone(), metadata);
176 let ctx = LoadEntryContext {
177 provider,
178 root,
179 expanded,
180 selected,
181 options,
182 };
183 let node = load_entry(&ctx, entry, 0, &[])?;
184 Ok(vec![node])
185}
186
187pub fn file_uri_is_ancestor_or_self(parent: &FileUri, child: &FileUri) -> bool {
203 if parent.scheme() != child.scheme() || parent.authority() != child.authority() {
204 return false;
205 }
206 let parent_path = parent.path().trim_end_matches('/');
207 let child_path = child.path().trim_end_matches('/');
208 parent_path == child_path
209 || child_path
210 .strip_prefix(parent_path)
211 .is_some_and(|rest| rest.starts_with('/'))
212}
213
214pub fn file_uri_parent(uri: &FileUri) -> Option<FileUri> {
230 let path = uri.path().trim_end_matches('/');
231 let (parent, _) = path.rsplit_once('/')?;
232 let parent = if parent.is_empty() { "/" } else { parent };
233 FileUri::new(
234 uri.scheme().to_string(),
235 uri.authority().map(str::to_string),
236 parent.to_string(),
237 )
238 .ok()
239}
240
241pub fn file_uri_ancestors_between(root: &FileUri, target: &FileUri) -> Vec<FileUri> {
257 if !file_uri_is_ancestor_or_self(root, target) {
258 return Vec::new();
259 }
260
261 let mut out = Vec::new();
262 let mut current = Some(target.clone());
263 while let Some(uri) = current {
264 if file_uri_is_ancestor_or_self(root, &uri) {
265 out.push(uri.clone());
266 }
267 if &uri == root {
268 break;
269 }
270 current = file_uri_parent(&uri);
271 }
272 out.reverse();
273 dedupe_file_uris(out)
274}
275
276pub fn dedupe_file_uris(uris: impl IntoIterator<Item = FileUri>) -> Vec<FileUri> {
292 let mut out = Vec::new();
293 for uri in uris {
294 if !out.iter().any(|item| item == &uri) {
295 out.push(uri);
296 }
297 }
298 out
299}
300
301fn load_entry(
309 ctx: &LoadEntryContext<'_>,
310 entry: FileEntry,
311 depth: usize,
312 canonical_ancestors: &[FileUri],
313) -> Result<FileExplorerNode, FileError> {
314 let mut node = FileExplorerNode::new(entry);
315 let should_descend = should_descend_entry(
316 &node.entry,
317 ctx.root,
318 ctx.expanded,
319 ctx.selected,
320 ctx.options,
321 depth,
322 );
323 if should_descend {
324 let mut next_ancestors = canonical_ancestors.to_vec();
325 if let Some(canonical) = ctx.provider.canonical_uri(&node.entry.uri)? {
326 if canonical_ancestors
327 .iter()
328 .any(|ancestor| ancestor == &canonical)
329 {
330 node.children
331 .push(error_placeholder(&node.entry.uri, "symlink cycle"));
332 return Ok(node);
333 }
334 next_ancestors.push(canonical);
335 }
336 let mut entries = ctx
337 .provider
338 .read_dir(&node.entry.uri)?
339 .into_iter()
340 .filter(|entry| should_include_file_entry(entry, ctx.selected, ctx.options))
341 .collect::<Vec<_>>();
342 sort_file_entries(&mut entries);
343 let truncated = truncate_entries(&mut entries, ctx.options);
344 let mut children = entries
345 .into_iter()
346 .map(|entry| load_entry(ctx, entry, depth + 1, &next_ancestors))
347 .collect::<Result<Vec<_>, FileError>>()?;
348 if truncated {
349 children.push(large_directory_placeholder(&node.entry.uri));
350 }
351 node.children = children;
352 }
353 Ok(node)
354}
355
356fn should_descend_entry(
358 entry: &FileEntry,
359 root: &FileUri,
360 expanded: &[FileUri],
361 selected: Option<&FileUri>,
362 options: FileTreeOptions,
363 depth: usize,
364) -> bool {
365 if !entry.metadata.is_directory_like() || depth >= options.max_depth {
366 return false;
367 }
368 let Some(reason) = child_load_reason(&entry.uri, root, expanded, selected, options, depth)
369 else {
370 return false;
371 };
372 symlink_policy_allows_descend(&entry.metadata, reason, options.symlink_traversal_policy)
373}
374
375fn child_load_reason(
377 uri: &FileUri,
378 root: &FileUri,
379 expanded: &[FileUri],
380 selected: Option<&FileUri>,
381 options: FileTreeOptions,
382 depth: usize,
383) -> Option<ChildLoadReason> {
384 if uri == root || expanded.iter().any(|item| item == uri) {
385 return Some(ChildLoadReason::Explicit);
386 }
387
388 if options.reveal_selected
389 && selected.is_some_and(|selected| file_uri_is_ancestor_or_self(uri, selected))
390 {
391 return Some(ChildLoadReason::Explicit);
392 }
393
394 match options.load_mode {
395 FileTreeLoadMode::Lazy => None,
396 FileTreeLoadMode::Controlled { preload_depth } => {
397 (depth <= preload_depth).then_some(ChildLoadReason::Preload)
398 }
399 FileTreeLoadMode::Full => Some(ChildLoadReason::Preload),
400 }
401}
402
403pub(crate) fn symlink_policy_allows_descend(
415 metadata: &FileMetadata,
416 reason: ChildLoadReason,
417 policy: SymlinkTraversalPolicy,
418) -> bool {
419 if !metadata.is_symlink() {
420 return true;
421 }
422 match policy {
423 SymlinkTraversalPolicy::Never => false,
424 SymlinkTraversalPolicy::ExplicitExpansionOnly => reason == ChildLoadReason::Explicit,
425 SymlinkTraversalPolicy::RecursiveWithCycleGuard => true,
426 }
427}
428
429pub(crate) fn should_include_file_entry(
441 entry: &FileEntry,
442 selected: Option<&FileUri>,
443 options: FileTreeOptions,
444) -> bool {
445 let selected_kept =
446 selected.is_some_and(|selected| file_uri_is_ancestor_or_self(&entry.uri, selected));
447 if selected_kept {
448 return true;
449 }
450 if !options.include_hidden && entry.name.starts_with('.') {
451 return false;
452 }
453 !(options.exclude_defaults
454 && entry.metadata.is_directory_like()
455 && is_default_excluded_dir(&entry.name))
456}
457
458pub(crate) fn sort_file_entries(entries: &mut [FileEntry]) {
474 entries.sort_by(|a, b| {
475 file_entry_directory_rank(&a.metadata)
476 .cmp(&file_entry_directory_rank(&b.metadata))
477 .then_with(|| {
478 a.name
479 .to_ascii_lowercase()
480 .cmp(&b.name.to_ascii_lowercase())
481 })
482 .then_with(|| a.name.cmp(&b.name))
483 .then_with(|| a.uri.path().cmp(b.uri.path()))
484 });
485}
486
487pub(crate) fn truncate_entries(entries: &mut Vec<FileEntry>, options: FileTreeOptions) -> bool {
504 let Some(max) = options.max_entries_per_directory else {
505 return false;
506 };
507 if options.large_directory_policy == LargeDirectoryPolicy::Load || entries.len() <= max {
508 return false;
509 }
510 entries.truncate(max);
511 true
512}
513
514pub(crate) fn large_directory_placeholder(parent: &FileUri) -> FileExplorerNode {
528 FileExplorerNode::named(
529 synthetic_child_uri(parent, ".ailloli_ui-large-directory"),
530 "Large directory - open explicitly to load more",
531 FileKind::Other,
532 )
533 .disabled(true)
534}
535
536pub(crate) fn loading_placeholder(parent: &FileUri) -> FileExplorerNode {
546 FileExplorerNode::named(
547 synthetic_child_uri(parent, ".ailloli_ui-loading"),
548 "Loading...",
549 FileKind::Other,
550 )
551 .disabled(true)
552}
553
554pub(crate) fn error_placeholder(parent: &FileUri, message: impl AsRef<str>) -> FileExplorerNode {
566 FileExplorerNode::named(
567 synthetic_child_uri(parent, ".ailloli_ui-error"),
568 format!("Error: {}", message.as_ref()),
569 FileKind::Other,
570 )
571 .disabled(true)
572}
573
574fn synthetic_child_uri(parent: &FileUri, name: &str) -> FileUri {
576 FileUri::new(
577 parent.scheme().to_string(),
578 parent.authority().map(str::to_string),
579 format!("{}/{}", parent.path().trim_end_matches('/'), name),
580 )
581 .expect("synthetic file explorer uri")
582}
583
584fn is_default_excluded_dir(name: &str) -> bool {
586 matches!(
587 name,
588 ".git" | "target" | "node_modules" | "vendor" | "dist" | "build" | ".cache"
589 )
590}
591
592fn file_entry_directory_rank(metadata: &FileMetadata) -> u8 {
594 if metadata.is_directory_like() {
595 0
596 } else {
597 match metadata.kind {
598 FileKind::File | FileKind::Symlink | FileKind::Other | FileKind::Directory => 1,
599 }
600 }
601}
602
603#[cfg(test)]
604mod tests {
606 use std::collections::HashMap;
607
608 use ailloli_ui_fs::{FileCapabilities, FileMetadata};
609
610 use super::*;
611
612 #[derive(Default)]
614 struct MockProvider {
615 metadata: HashMap<FileUri, FileMetadata>,
616 dirs: HashMap<FileUri, Vec<FileEntry>>,
617 canonical: HashMap<FileUri, FileUri>,
618 }
619
620 impl MockProvider {
621 fn dir(mut self, path: &str, entries: &[(&str, FileKind)]) -> Self {
623 let uri = uri(path);
624 self.metadata
625 .insert(uri.clone(), FileMetadata::new(FileKind::Directory));
626 let entries = entries
627 .iter()
628 .map(|(name, kind)| {
629 let child = child_uri(path, name);
630 self.metadata
631 .insert(child.clone(), FileMetadata::new(*kind));
632 FileEntry {
633 uri: child,
634 name: (*name).to_string(),
635 metadata: FileMetadata::new(*kind),
636 }
637 })
638 .collect::<Vec<_>>();
639 self.dirs.insert(uri, entries);
640 self
641 }
642
643 fn dir_entries(mut self, path: &str, entries: Vec<FileEntry>) -> Self {
645 let uri = uri(path);
646 self.metadata
647 .insert(uri.clone(), FileMetadata::new(FileKind::Directory));
648 for entry in &entries {
649 self.metadata
650 .insert(entry.uri.clone(), entry.metadata.clone());
651 }
652 self.dirs.insert(uri, entries);
653 self
654 }
655
656 fn canonical(mut self, path: &str, canonical_path: &str) -> Self {
658 self.canonical.insert(uri(path), uri(canonical_path));
659 self
660 }
661 }
662
663 impl FileProvider for MockProvider {
664 fn capabilities(&self) -> FileCapabilities {
665 FileCapabilities::READ_ONLY
666 }
667
668 fn read_dir(&self, uri: &FileUri) -> Result<Vec<FileEntry>, FileError> {
669 Ok(self.dirs.get(uri).cloned().unwrap_or_default())
670 }
671
672 fn read_file(&self, _uri: &FileUri) -> Result<Vec<u8>, FileError> {
673 Err(FileError::Unsupported("mock read_file".into()))
674 }
675
676 fn write_file(&self, _uri: &FileUri, _bytes: &[u8]) -> Result<(), FileError> {
677 Err(FileError::Unsupported("mock write_file".into()))
678 }
679
680 fn metadata(&self, uri: &FileUri) -> Result<FileMetadata, FileError> {
681 self.metadata
682 .get(uri)
683 .cloned()
684 .ok_or_else(|| FileError::NotFound(uri.to_string()))
685 }
686
687 fn canonical_uri(&self, uri: &FileUri) -> Result<Option<FileUri>, FileError> {
688 Ok(self.canonical.get(uri).cloned())
689 }
690
691 fn create_dir(&self, _uri: &FileUri) -> Result<(), FileError> {
692 Err(FileError::Unsupported("mock create_dir".into()))
693 }
694
695 fn rename(&self, _from: &FileUri, _to: &FileUri) -> Result<(), FileError> {
696 Err(FileError::Unsupported("mock rename".into()))
697 }
698
699 fn remove(&self, _uri: &FileUri) -> Result<(), FileError> {
700 Err(FileError::Unsupported("mock remove".into()))
701 }
702 }
703
704 #[test]
705 fn load_file_tree_respects_expanded_hidden_and_sorting() {
706 let provider = MockProvider::default()
707 .dir(
708 "/repo",
709 &[
710 ("z.rs", FileKind::File),
711 ("src", FileKind::Directory),
712 (".hidden", FileKind::Directory),
713 ("Cargo.toml", FileKind::File),
714 ],
715 )
716 .dir(
717 "/repo/src",
718 &[("main.rs", FileKind::File), ("lib.rs", FileKind::File)],
719 );
720 let root = uri("/repo");
721 let src = uri("/repo/src");
722
723 let tree = load_file_tree(
724 &provider,
725 &root,
726 std::slice::from_ref(&src),
727 None,
728 FileTreeOptions::default(),
729 )
730 .expect("tree");
731
732 let root = &tree[0];
733 let names = root
734 .children
735 .iter()
736 .map(FileExplorerNode::name)
737 .collect::<Vec<_>>();
738 assert_eq!(names, ["src", "Cargo.toml", "z.rs"]);
739 assert_eq!(root.children[0].children[0].name(), "lib.rs");
740 }
741
742 #[test]
743 fn load_file_tree_reveals_selected_ancestors() {
744 let provider = MockProvider::default()
745 .dir("/repo", &[("src", FileKind::Directory)])
746 .dir("/repo/src", &[("view", FileKind::Directory)])
747 .dir("/repo/src/view", &[("left.rs", FileKind::File)]);
748 let root = uri("/repo");
749 let selected = uri("/repo/src/view/left.rs");
750
751 let tree = load_file_tree(
752 &provider,
753 &root,
754 &[],
755 Some(&selected),
756 FileTreeOptions::default(),
757 )
758 .expect("tree");
759
760 assert_eq!(tree[0].children[0].name(), "src");
761 assert_eq!(tree[0].children[0].children[0].name(), "view");
762 assert_eq!(
763 tree[0].children[0].children[0].children[0].name(),
764 "left.rs"
765 );
766 }
767
768 #[test]
769 fn load_file_tree_lazy_keeps_unexpanded_sibling_directories_unloaded() {
770 let provider = MockProvider::default()
771 .dir(
772 "/repo",
773 &[
774 ("src", FileKind::Directory),
775 ("sample_app", FileKind::Directory),
776 ],
777 )
778 .dir("/repo/src", &[("lib.rs", FileKind::File)])
779 .dir("/repo/sample_app", &[("main.rs", FileKind::File)]);
780 let root = uri("/repo");
781 let selected = uri("/repo/sample_app/main.rs");
782
783 let tree = load_file_tree(
784 &provider,
785 &root,
786 &[],
787 Some(&selected),
788 FileTreeOptions::default(),
789 )
790 .expect("tree");
791
792 let root = &tree[0];
793 assert!(
794 child(root, "src").children.is_empty(),
795 "lazy must not preload sibling directories"
796 );
797 assert!(
798 child(root, "sample_app")
799 .children
800 .iter()
801 .any(|node| node.name() == "main.rs"),
802 "selected ancestors remain loaded in lazy mode"
803 );
804 }
805
806 #[test]
807 fn load_file_tree_controlled_preloads_directories_until_depth() {
808 let provider = MockProvider::default()
809 .dir(
810 "/repo",
811 &[
812 ("src", FileKind::Directory),
813 ("sample_app", FileKind::Directory),
814 ],
815 )
816 .dir("/repo/src", &[("lib.rs", FileKind::File)])
817 .dir(
818 "/repo/sample_app",
819 &[("src", FileKind::Directory), ("Cargo.toml", FileKind::File)],
820 )
821 .dir("/repo/sample_app/src", &[("main.rs", FileKind::File)]);
822 let root = uri("/repo");
823
824 let tree = load_file_tree(
825 &provider,
826 &root,
827 &[],
828 None,
829 FileTreeOptions {
830 load_mode: FileTreeLoadMode::Controlled { preload_depth: 1 },
831 ..FileTreeOptions::default()
832 },
833 )
834 .expect("tree");
835
836 let root = &tree[0];
837 assert!(child(root, "src")
838 .children
839 .iter()
840 .any(|node| node.name() == "lib.rs"));
841 let sample = child(root, "sample_app");
842 assert!(sample
843 .children
844 .iter()
845 .any(|node| node.name() == "Cargo.toml"));
846 assert!(
847 child(sample, "src").children.is_empty(),
848 "preload_depth=1 does not recurse into second-level directories"
849 );
850 }
851
852 #[test]
853 fn load_file_tree_controlled_respects_max_depth() {
854 let provider = MockProvider::default()
855 .dir("/repo", &[("src", FileKind::Directory)])
856 .dir("/repo/src", &[("lib.rs", FileKind::File)]);
857 let root = uri("/repo");
858
859 let tree = load_file_tree(
860 &provider,
861 &root,
862 &[],
863 None,
864 FileTreeOptions {
865 max_depth: 1,
866 load_mode: FileTreeLoadMode::Controlled { preload_depth: 4 },
867 ..FileTreeOptions::default()
868 },
869 )
870 .expect("tree");
871
872 assert!(
873 child(&tree[0], "src").children.is_empty(),
874 "max_depth remains a hard cap"
875 );
876 }
877
878 #[test]
879 fn load_file_tree_full_loads_recursively_until_max_depth() {
880 let provider = MockProvider::default()
881 .dir("/repo", &[("src", FileKind::Directory)])
882 .dir("/repo/src", &[("view", FileKind::Directory)])
883 .dir("/repo/src/view", &[("left.rs", FileKind::File)]);
884 let root = uri("/repo");
885
886 let tree = load_file_tree(
887 &provider,
888 &root,
889 &[],
890 None,
891 FileTreeOptions {
892 max_depth: 3,
893 load_mode: FileTreeLoadMode::Full,
894 ..FileTreeOptions::default()
895 },
896 )
897 .expect("tree");
898
899 let src = child(&tree[0], "src");
900 let view = child(src, "view");
901 assert!(view.children.iter().any(|node| node.name() == "left.rs"));
902
903 let capped = load_file_tree(
904 &provider,
905 &root,
906 &[],
907 None,
908 FileTreeOptions {
909 max_depth: 2,
910 load_mode: FileTreeLoadMode::Full,
911 ..FileTreeOptions::default()
912 },
913 )
914 .expect("tree");
915 let view = child(child(&capped[0], "src"), "view");
916 assert!(view.children.is_empty());
917 }
918
919 #[test]
920 fn symlink_directory_can_expand_explicitly() {
921 let provider = MockProvider::default()
922 .dir_entries(
923 "/repo",
924 vec![entry_with_metadata(
925 "/repo/linked",
926 "linked",
927 symlink_metadata(Some(FileKind::Directory)),
928 )],
929 )
930 .dir("/repo/linked", &[("child.rs", FileKind::File)]);
931 let root = uri("/repo");
932 let linked = uri("/repo/linked");
933
934 let tree = load_file_tree(
935 &provider,
936 &root,
937 std::slice::from_ref(&linked),
938 None,
939 FileTreeOptions::default(),
940 )
941 .expect("tree");
942
943 let linked = child(&tree[0], "linked");
944 assert_eq!(linked.entry.metadata.kind, FileKind::Symlink);
945 assert!(linked.children.iter().any(|node| node.name() == "child.rs"));
946 }
947
948 #[test]
949 fn full_load_does_not_preload_symlink_directories_by_default() {
950 let provider = MockProvider::default()
951 .dir_entries(
952 "/repo",
953 vec![entry_with_metadata(
954 "/repo/linked",
955 "linked",
956 symlink_metadata(Some(FileKind::Directory)),
957 )],
958 )
959 .dir("/repo/linked", &[("child.rs", FileKind::File)]);
960 let root = uri("/repo");
961
962 let tree = load_file_tree(
963 &provider,
964 &root,
965 &[],
966 None,
967 FileTreeOptions {
968 load_mode: FileTreeLoadMode::Full,
969 ..FileTreeOptions::default()
970 },
971 )
972 .expect("tree");
973
974 assert!(child(&tree[0], "linked").children.is_empty());
975 }
976
977 #[test]
978 fn recursive_policy_allows_full_load_for_symlink_directories() {
979 let provider = MockProvider::default()
980 .dir_entries(
981 "/repo",
982 vec![entry_with_metadata(
983 "/repo/linked",
984 "linked",
985 symlink_metadata(Some(FileKind::Directory)),
986 )],
987 )
988 .dir("/repo/linked", &[("child.rs", FileKind::File)]);
989 let root = uri("/repo");
990
991 let tree = load_file_tree(
992 &provider,
993 &root,
994 &[],
995 None,
996 FileTreeOptions {
997 load_mode: FileTreeLoadMode::Full,
998 symlink_traversal_policy: SymlinkTraversalPolicy::RecursiveWithCycleGuard,
999 ..FileTreeOptions::default()
1000 },
1001 )
1002 .expect("tree");
1003
1004 assert!(child(&tree[0], "linked")
1005 .children
1006 .iter()
1007 .any(|node| node.name() == "child.rs"));
1008 }
1009
1010 #[test]
1011 fn symlink_cycle_does_not_recurse_forever() {
1012 let provider = MockProvider::default()
1013 .dir_entries(
1014 "/repo",
1015 vec![entry_with_metadata(
1016 "/repo/loop",
1017 "loop",
1018 symlink_metadata(Some(FileKind::Directory)),
1019 )],
1020 )
1021 .dir("/repo/loop", &[("unreachable.rs", FileKind::File)])
1022 .canonical("/repo", "/repo")
1023 .canonical("/repo/loop", "/repo");
1024 let root = uri("/repo");
1025 let loop_uri = uri("/repo/loop");
1026
1027 let tree = load_file_tree(
1028 &provider,
1029 &root,
1030 std::slice::from_ref(&loop_uri),
1031 None,
1032 FileTreeOptions::default(),
1033 )
1034 .expect("tree");
1035
1036 let loop_node = child(&tree[0], "loop");
1037 assert!(loop_node
1038 .children
1039 .iter()
1040 .any(|node| node.name().contains("symlink cycle")));
1041 assert!(!loop_node
1042 .children
1043 .iter()
1044 .any(|node| node.name() == "unreachable.rs"));
1045 }
1046
1047 #[test]
1048 fn load_file_tree_load_modes_keep_hidden_and_reveal_selected_rules() {
1049 let provider = MockProvider::default()
1050 .dir(
1051 "/repo",
1052 &[
1053 (".hidden", FileKind::Directory),
1054 ("sample_app", FileKind::Directory),
1055 ],
1056 )
1057 .dir("/repo/.hidden", &[("metadata.json", FileKind::File)])
1058 .dir("/repo/sample_app", &[(".env", FileKind::File)]);
1059 let root = uri("/repo");
1060 let selected = uri("/repo/.hidden/metadata.json");
1061
1062 let tree = load_file_tree(
1063 &provider,
1064 &root,
1065 &[],
1066 Some(&selected),
1067 FileTreeOptions {
1068 load_mode: FileTreeLoadMode::Controlled { preload_depth: 1 },
1069 ..FileTreeOptions::default()
1070 },
1071 )
1072 .expect("tree");
1073
1074 assert!(
1075 tree[0].children.iter().any(|node| node.name() == ".hidden"),
1076 "selected hidden ancestor is kept even when hidden files are excluded"
1077 );
1078 let sample = child(&tree[0], "sample_app");
1079 assert!(
1080 sample.children.iter().all(|node| node.name() != ".env"),
1081 "unselected hidden children are still filtered"
1082 );
1083
1084 let full_hidden = load_file_tree(
1085 &provider,
1086 &root,
1087 &[],
1088 None,
1089 FileTreeOptions {
1090 include_hidden: true,
1091 load_mode: FileTreeLoadMode::Full,
1092 ..FileTreeOptions::default()
1093 },
1094 )
1095 .expect("tree");
1096 assert!(child(&full_hidden[0], ".hidden")
1097 .children
1098 .iter()
1099 .any(|node| node.name() == "metadata.json"));
1100 }
1101
1102 fn child<'a>(node: &'a FileExplorerNode, name: &str) -> &'a FileExplorerNode {
1104 node.children
1105 .iter()
1106 .find(|child| child.name() == name)
1107 .unwrap_or_else(|| panic!("missing child {name} in {}", node.name()))
1108 }
1109
1110 fn child_uri(parent: &str, name: &str) -> FileUri {
1112 uri(&format!("{}/{}", parent.trim_end_matches('/'), name))
1113 }
1114
1115 fn entry_with_metadata(
1117 path: &str,
1118 name: impl Into<String>,
1119 metadata: FileMetadata,
1120 ) -> FileEntry {
1121 FileEntry {
1122 uri: uri(path),
1123 name: name.into(),
1124 metadata,
1125 }
1126 }
1127
1128 fn symlink_metadata(target: Option<FileKind>) -> FileMetadata {
1130 let mut metadata = FileMetadata::new(FileKind::Symlink);
1131 metadata.symlink_target_kind = target;
1132 metadata
1133 }
1134
1135 fn uri(path: &str) -> FileUri {
1137 FileUri::parse(format!("file://{path}")).expect("file uri")
1138 }
1139}