use crate::infra::{FileSystem, RealFileSystem};
use std::path::{Path, PathBuf};
pub struct CargoFileFinder<FS: FileSystem = RealFileSystem> {
project_root: PathBuf,
fs: FS,
}
impl CargoFileFinder<RealFileSystem> {
pub fn new(project_root: &Path) -> Self {
Self::with_fs(project_root, RealFileSystem)
}
}
impl<FS: FileSystem> CargoFileFinder<FS> {
pub fn with_fs(project_root: &Path, fs: FS) -> Self {
Self {
project_root: project_root.to_path_buf(),
fs,
}
}
pub fn find_cargo_tomls(&self) -> Result<Vec<PathBuf>, std::io::Error> {
let mut tomls = Vec::new();
let root_toml = self.project_root.join("Cargo.toml");
if self.fs.metadata(&root_toml).is_ok() {
tomls.push(root_toml);
}
Ok(tomls)
}
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::TempDir;
#[test]
fn test_find_cargo_tomls_in_empty_directory_returns_empty_list() {
let temp_dir = TempDir::new().unwrap();
let finder = CargoFileFinder::new(temp_dir.path());
let tomls = finder.find_cargo_tomls().unwrap();
assert!(tomls.is_empty());
}
#[test]
fn test_find_cargo_tomls_with_root_cargo_toml() {
let temp_dir = TempDir::new().unwrap();
let cargo_toml = temp_dir.path().join("Cargo.toml");
std::fs::write(&cargo_toml, "[package]\nname = \"test\"\n").unwrap();
let finder = CargoFileFinder::new(temp_dir.path());
let tomls = finder.find_cargo_tomls().unwrap();
assert_eq!(tomls.len(), 1);
assert_eq!(tomls[0], cargo_toml);
}
}