use base64ct::Encoding;
use crate::error_mod::{Error, Result};
use crate::public_api_mod::{RESET, YELLOW};
pub fn copy_folder_files_into_module(
folder_path: &std::path::Path,
module_path: &std::path::Path,
ext_for_binary_files: &[&str],
exclude_big_folders: &[String],
) -> Result<()> {
let folder_path = camino::Utf8Path::from_path(folder_path).ok_or_else(|| Error::ErrorFromStr("folder_path is None"))?;
let module_path = camino::Utf8Path::from_path(module_path).ok_or_else(|| Error::ErrorFromStr("module_path is None"))?;
println!(" {YELLOW}copy_folder_files_into_module {folder_path}, {module_path}{RESET}");
let files = crate::traverse_dir_with_exclude_dir(folder_path.as_std_path(), "", exclude_big_folders)?;
let mut new_code = String::new();
for file_name in files.iter() {
let file_name_short = file_name.trim_start_matches(&format!("{folder_path}/"));
if file_name_short == "Cargo.lock" {
continue;
}
let mut is_binary_file = false;
for x in ext_for_binary_files.iter() {
if file_name_short.ends_with(x) {
is_binary_file = true;
break;
}
}
let file_content = if is_binary_file {
let b = std::fs::read(file_name)?;
base64ct::Base64::encode_string(&b)
} else {
std::fs::read_to_string(file_name)?
};
new_code.push_str(&format!(
r####"vec_file.push(crate::FileItem{{
file_name :"{}",
file_content : r###"{}"###,
}});
"####,
&file_name_short, &file_content
));
}
let module_content = std::fs::read_to_string(module_path)?;
let start_pos =
crate::find_pos_start_data_after_delimiter(&module_content, 0, "// region: files copied into strings by automation tasks\n")
.expect("didn't find // region: files copied..");
let end_pos =
crate::find_pos_end_data_before_delimiter(&module_content, 0, "// endregion: files copied into strings by automation tasks")
.expect("didn't find // endregion: files copied..");
let old_code = &module_content[start_pos..end_pos];
if old_code != new_code {
let mut new_module_content = String::new();
new_module_content.push_str(&module_content[..start_pos]);
new_module_content.push_str(&new_code);
new_module_content.push_str(&module_content[end_pos..]);
std::fs::write(module_path, &new_module_content)?;
}
Ok(())
}