|
| 1 | +use crate::errors::{GrimpError, GrimpResult}; |
| 2 | +use crate::filesystem::get_file_system_boxed; |
| 3 | +use crate::import_scanning::{DirectImport, imports_by_module_to_py}; |
| 4 | +use crate::module_finding::Module; |
| 5 | +use pyo3::types::PyDict; |
| 6 | +use pyo3::{Bound, PyAny, PyResult, Python, pyfunction}; |
| 7 | +use std::collections::{HashMap, HashSet}; |
| 8 | + |
| 9 | +/// Reads the cache file containing all the imports for a given package. |
| 10 | +/// Args: |
| 11 | +/// - filename: str |
| 12 | +/// - file_system: The file system interface to use. (A BasicFileSystem.) |
| 13 | +/// Returns Dict[Module, Set[DirectImport]] |
| 14 | +#[pyfunction] |
| 15 | +pub fn read_cache_data_map_file<'py>( |
| 16 | + py: Python<'py>, |
| 17 | + filename: &str, |
| 18 | + file_system: Bound<'py, PyAny>, |
| 19 | +) -> PyResult<Bound<'py, PyDict>> { |
| 20 | + let file_system_boxed = get_file_system_boxed(&file_system)?; |
| 21 | + |
| 22 | + let file_contents = file_system_boxed.read(filename)?; |
| 23 | + |
| 24 | + let imports_by_module = parse_json_to_map(&file_contents, filename)?; |
| 25 | + |
| 26 | + Ok(imports_by_module_to_py(py, imports_by_module)) |
| 27 | +} |
| 28 | + |
| 29 | +pub fn parse_json_to_map( |
| 30 | + json_str: &str, |
| 31 | + filename: &str, |
| 32 | +) -> GrimpResult<HashMap<Module, HashSet<DirectImport>>> { |
| 33 | + let raw_map: HashMap<String, Vec<(String, usize, String)>> = serde_json::from_str(json_str) |
| 34 | + .map_err(|_| GrimpError::CorruptCache(filename.to_string()))?; |
| 35 | + |
| 36 | + let mut parsed_map: HashMap<Module, HashSet<DirectImport>> = HashMap::new(); |
| 37 | + |
| 38 | + for (module_name, imports) in raw_map { |
| 39 | + let module = Module { |
| 40 | + name: module_name.clone(), |
| 41 | + }; |
| 42 | + let import_set: HashSet<DirectImport> = imports |
| 43 | + .into_iter() |
| 44 | + .map(|(imported, line_number, line_contents)| DirectImport { |
| 45 | + importer: module_name.clone(), |
| 46 | + imported, |
| 47 | + line_number, |
| 48 | + line_contents, |
| 49 | + }) |
| 50 | + .collect(); |
| 51 | + parsed_map.insert(module, import_set); |
| 52 | + } |
| 53 | + |
| 54 | + Ok(parsed_map) |
| 55 | +} |
0 commit comments