//! A collection is a folder of `.http` files. Scanning builds the sidebar //! tree (folder → file → requests), parses every file and reads the folder //! settings ([`crate::folder`]). use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use crate::folder::FolderSettings; use crate::httpfile::HttpFile; #[derive(Debug, Clone, PartialEq, Eq)] pub enum Node { Folder { name: String, path: PathBuf, children: Vec, }, File { name: String, path: PathBuf, }, } impl Node { pub fn name(&self) -> &str { match self { Node::Folder { name, .. } | Node::File { name, .. } => name, } } pub fn path(&self) -> &Path { match self { Node::Folder { path, .. } | Node::File { path, .. } => path, } } } #[derive(Debug, Clone)] pub struct Collection { pub root: PathBuf, pub tree: Node, /// Parsed files by absolute path. pub files: BTreeMap, /// Folder settings by folder path (only folders that have a file). pub folders: BTreeMap, /// Folder settings files that could not be read. pub folder_errors: Vec, } pub fn is_http_file(path: &Path) -> bool { matches!(path.extension().and_then(|e| e.to_str()), Some("http" | "rest")) } fn skip_dir(name: &str) -> bool { name.starts_with('.') || matches!(name, "node_modules" | "target") } /// Scans `root` recursively. Folders without `.http` files are left out. pub fn scan(root: &Path) -> std::io::Result { let mut files = BTreeMap::new(); let mut folders = Folders::default(); let tree = scan_dir(root, &mut files, &mut folders)?.unwrap_or_else(|| Node::Folder { name: dir_name(root), path: root.to_path_buf(), children: Vec::new(), }); Ok(Collection { root: root.to_path_buf(), tree, files, folders: folders.settings, folder_errors: folders.errors, }) } #[derive(Default)] struct Folders { settings: BTreeMap, errors: Vec, } fn dir_name(p: &Path) -> String { p.file_name() .map(|n| n.to_string_lossy().into_owned()) .unwrap_or_else(|| p.display().to_string()) } fn scan_dir( dir: &Path, files: &mut BTreeMap, settings: &mut Folders, ) -> std::io::Result> { match FolderSettings::load(dir) { Ok(Some(s)) => { settings.settings.insert(dir.to_path_buf(), s); } Ok(None) => {} Err(e) => settings.errors.push(e.to_string()), } let mut entries: Vec<_> = std::fs::read_dir(dir)?.filter_map(Result::ok).collect(); entries.sort_by_key(|e| e.file_name().to_string_lossy().to_lowercase()); let mut folders = Vec::new(); let mut leaves = Vec::new(); for e in entries { let path = e.path(); let name = e.file_name().to_string_lossy().into_owned(); let Ok(ft) = e.file_type() else { continue }; if ft.is_dir() { if skip_dir(&name) { continue; } if let Some(n) = scan_dir(&path, files, settings)? { folders.push(n); } } else if is_http_file(&path) { let text = std::fs::read_to_string(&path)?; files.insert(path.clone(), HttpFile::parse(text)); leaves.push(Node::File { name, path }); } } if folders.is_empty() && leaves.is_empty() { return Ok(None); } folders.extend(leaves); Ok(Some(Node::Folder { name: dir_name(dir), path: dir.to_path_buf(), children: folders, })) } #[cfg(test)] mod tests { use super::*; #[test] fn scans_folders_files_and_requests() { let dir = tempfile::tempdir().unwrap(); let root = dir.path(); std::fs::write( root.join("users.http"), "### List\nGET /users\n\n### Get\nGET /users/1\n", ) .unwrap(); std::fs::create_dir_all(root.join("orders/payloads")).unwrap(); std::fs::write(root.join("orders/create.http"), "POST /orders\n").unwrap(); std::fs::write(root.join("orders/payloads/order.json"), "{}").unwrap(); std::fs::create_dir(root.join(".git")).unwrap(); std::fs::write(root.join(".git/x.http"), "GET /").unwrap(); std::fs::create_dir(root.join("empty")).unwrap(); std::fs::create_dir_all(root.join("orders/.reqlite")).unwrap(); std::fs::write(root.join("orders/.reqlite/folder.json"), r#"{"auth": "Bearer x"}"#).unwrap(); let c = scan(root).unwrap(); let Node::Folder { children, .. } = &c.tree else { panic!() }; let names: Vec<&str> = children.iter().map(Node::name).collect(); assert_eq!(names, vec!["orders", "users.http"]); let Node::Folder { children: orders, .. } = &children[0] else { panic!() }; assert_eq!(orders.len(), 1); assert_eq!(c.files.len(), 2); assert_eq!(c.files[&root.join("users.http")].request_count(), 2); assert_eq!(c.folders.keys().collect::>(), vec![&root.join("orders")]); assert!(c.folder_errors.is_empty()); } }