Skip to main content

qanglang_test/
test_file.rs

1use std::path::{Path, PathBuf};
2
3/// Represents a source file with both its actual file location and how it should be displayed
4#[derive(Debug, Clone)]
5pub struct SourceFile {
6    /// The actual file path that can be used to read the file
7    pub file_path: PathBuf,
8    /// The path to display to the user (relative to their context)
9    pub display_path: String,
10}
11
12impl SourceFile {
13    pub fn new(file_path: PathBuf, display_path: String) -> Self {
14        Self {
15            file_path,
16            display_path,
17        }
18    }
19}
20
21pub struct SourceFileResolver {
22    user_working_dir: PathBuf,
23}
24
25// TODO add support for ignore patterns when resolving a dir of files.
26
27impl SourceFileResolver {
28    pub fn new() -> std::io::Result<Self> {
29        let user_working_dir = std::env::current_dir()?;
30        Ok(Self { user_working_dir })
31    }
32
33    /// Resolve a single file or directory path into source files
34    pub fn resolve(&self, user_input: &str) -> std::io::Result<Vec<SourceFile>> {
35        let input_path = Path::new(user_input);
36
37        // Convert to absolute path for file operations
38        let absolute_path = if input_path.is_absolute() {
39            input_path.to_path_buf()
40        } else {
41            self.user_working_dir.join(input_path)
42        };
43
44        // Canonicalize to resolve any .. components
45        let canonical_path = absolute_path
46            .canonicalize()
47            .unwrap_or_else(|_| absolute_path.clone());
48
49        if canonical_path.is_file() {
50            // Single file case
51            self.resolve_single_file(&canonical_path)
52        } else if canonical_path.is_dir() {
53            // Directory case - find all .ql files
54            self.resolve_directory(&canonical_path)
55        } else {
56            Err(std::io::Error::new(
57                std::io::ErrorKind::NotFound,
58                format!("Path '{}' does not exist", user_input),
59            ))
60        }
61    }
62
63    fn resolve_single_file(&self, absolute_path: &Path) -> std::io::Result<Vec<SourceFile>> {
64        // For single files, use a clean display path
65        let display_path = self.create_display_path(absolute_path);
66
67        Ok(vec![SourceFile::new(
68            absolute_path.to_path_buf(),
69            display_path,
70        )])
71    }
72
73    fn resolve_directory(&self, absolute_path: &Path) -> std::io::Result<Vec<SourceFile>> {
74        let mut source_files = Vec::new();
75        self.collect_ql_files(absolute_path, &mut source_files)?;
76
77        // Sort for consistent output
78        source_files.sort_by(|a, b| a.display_path.cmp(&b.display_path));
79
80        Ok(source_files)
81    }
82
83    fn collect_ql_files(&self, dir: &Path, files: &mut Vec<SourceFile>) -> std::io::Result<()> {
84        for entry in std::fs::read_dir(dir)? {
85            let entry = entry?;
86            let path = entry.path();
87
88            if path.is_dir() {
89                self.collect_ql_files(&path, files)?;
90            } else if path.extension().and_then(|s| s.to_str()) == Some("ql") {
91                let display_path = self.create_display_path(&path);
92                files.push(SourceFile::new(path, display_path));
93            }
94        }
95        Ok(())
96    }
97
98    fn create_display_path(&self, absolute_path: &Path) -> String {
99        // Canonicalize the working directory to match the format of absolute_path
100        let canonical_work_dir = self
101            .user_working_dir
102            .canonicalize()
103            .unwrap_or_else(|_| self.user_working_dir.clone());
104
105        // Try to create a nice relative path from the user's working directory
106        if let Ok(relative) = absolute_path.strip_prefix(&canonical_work_dir) {
107            relative.to_string_lossy().to_string()
108        } else {
109            // If we can't make it relative, find a sensible common ancestor
110            self.find_best_display_path(absolute_path)
111        }
112    }
113
114    fn find_best_display_path(&self, absolute_path: &Path) -> String {
115        // Find common path components between the file and user's working directory
116        let file_components: Vec<_> = absolute_path.components().collect();
117        let work_components: Vec<_> = self.user_working_dir.components().collect();
118
119        // Find the longest common prefix
120        let mut common_len = 0;
121        for (file_comp, work_comp) in file_components.iter().zip(work_components.iter()) {
122            if file_comp == work_comp {
123                common_len += 1;
124            } else {
125                break;
126            }
127        }
128
129        if common_len > 0 {
130            // Build path from common root (usually the project root)
131            let remaining_components = &file_components[common_len..];
132            let mut result = PathBuf::new();
133            for component in remaining_components {
134                result.push(component);
135            }
136            result.to_string_lossy().to_string()
137        } else {
138            // Last resort: just use the filename
139            absolute_path
140                .file_name()
141                .unwrap_or(absolute_path.as_os_str())
142                .to_string_lossy()
143                .to_string()
144        }
145    }
146}