|
| 1 | +use std::path::{Path, PathBuf}; |
| 2 | +use utils::error::Result; |
| 3 | + |
| 4 | +/// Find CODEOWNERS files recursively in the given directory and its subdirectories |
| 5 | +pub fn find_codeowners_files<P: AsRef<Path>>(base_path: P) -> Result<Vec<PathBuf>> { |
| 6 | + let mut result = Vec::new(); |
| 7 | + if let Ok(entries) = std::fs::read_dir(base_path) { |
| 8 | + for entry in entries.flatten() { |
| 9 | + let path = entry.path(); |
| 10 | + if path.is_file() |
| 11 | + && path |
| 12 | + .file_name() |
| 13 | + .and_then(|n| n.to_str()) |
| 14 | + .map(|n| n == "CODEOWNERS") |
| 15 | + .unwrap_or(false) |
| 16 | + { |
| 17 | + result.push(path); |
| 18 | + } else if path.is_dir() { |
| 19 | + result.extend(find_codeowners_files(path)?); |
| 20 | + } |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + Ok(result) |
| 25 | +} |
| 26 | + |
| 27 | +#[cfg(test)] |
| 28 | +mod tests { |
| 29 | + use super::*; |
| 30 | + use std::fs::{self, File}; |
| 31 | + use tempfile::TempDir; |
| 32 | + |
| 33 | + #[test] |
| 34 | + fn test_find_codeowners_files() -> Result<()> { |
| 35 | + // Create a temporary directory structure |
| 36 | + let temp_dir = TempDir::new()?; |
| 37 | + let base_path = temp_dir.path(); |
| 38 | + |
| 39 | + // Create test directory structure |
| 40 | + let sub_dir = base_path.join("subdir"); |
| 41 | + let nested_dir = sub_dir.join("nested"); |
| 42 | + fs::create_dir_all(&nested_dir)?; |
| 43 | + |
| 44 | + // Create CODEOWNERS files in different locations |
| 45 | + File::create(base_path.join("CODEOWNERS"))?; |
| 46 | + File::create(nested_dir.join("CODEOWNERS"))?; |
| 47 | + |
| 48 | + // Create some other files to verify we don't pick them up |
| 49 | + File::create(base_path.join("codeowners"))?; // wrong case |
| 50 | + File::create(sub_dir.join("not_codeowners"))?; |
| 51 | + |
| 52 | + // Find all CODEOWNERS files |
| 53 | + let found_files = find_codeowners_files(base_path)?; |
| 54 | + |
| 55 | + // Verify results |
| 56 | + assert_eq!(found_files.len(), 2); |
| 57 | + assert!( |
| 58 | + found_files |
| 59 | + .iter() |
| 60 | + .any(|p| p == &base_path.join("CODEOWNERS")) |
| 61 | + ); |
| 62 | + assert!( |
| 63 | + found_files |
| 64 | + .iter() |
| 65 | + .any(|p| p == &nested_dir.join("CODEOWNERS")) |
| 66 | + ); |
| 67 | + |
| 68 | + Ok(()) |
| 69 | + } |
| 70 | + |
| 71 | + #[test] |
| 72 | + fn test_find_codeowners_files_empty_dir() -> Result<()> { |
| 73 | + let temp_dir = TempDir::new()?; |
| 74 | + let found_files = find_codeowners_files(temp_dir.path())?; |
| 75 | + assert!(found_files.is_empty()); |
| 76 | + Ok(()) |
| 77 | + } |
| 78 | + |
| 79 | + #[test] |
| 80 | + fn test_find_codeowners_files_nonexistent_dir() -> Result<()> { |
| 81 | + let nonexistent_dir = PathBuf::from("/nonexistent/directory"); |
| 82 | + let found_files = find_codeowners_files(nonexistent_dir)?; |
| 83 | + assert!(found_files.is_empty()); |
| 84 | + Ok(()) |
| 85 | + } |
| 86 | +} |
0 commit comments