use crate::core::backend::GeneratedFile;
use std::path::Path;
const SWIFT_TARGET_PARENT_DIR: &str = "Sources";
const SWIFT_EXTENSION: &str = "swift";
fn owning_module(path: &Path) -> Option<&str> {
if path.extension()?.to_str()? != SWIFT_EXTENSION {
return None;
}
let target_dir = path.parent()?;
let module = target_dir.file_name()?.to_str()?;
let sources_dir = target_dir.parent()?.file_name()?.to_str()?;
(sources_dir == SWIFT_TARGET_PARENT_DIR).then_some(module)
}
fn without_self_import(content: &str, module: &str) -> Option<String> {
let self_import = format!("import {module}");
if !content.lines().any(|line| line.trim() == self_import) {
return None;
}
let kept: Vec<&str> = content.lines().filter(|line| line.trim() != self_import).collect();
let mut stripped = kept.join("\n");
if content.ends_with('\n') {
stripped.push('\n');
}
Some(stripped)
}
pub(super) fn strip_self_module_imports(mut files: Vec<GeneratedFile>) -> Vec<GeneratedFile> {
for file in &mut files {
let Some(module) = owning_module(&file.path).map(str::to_owned) else {
continue;
};
if let Some(stripped) = without_self_import(&file.content, &module) {
file.content = stripped;
}
}
files
}
#[cfg(test)]
mod tests;