use std::borrow::Cow;
use std::path::Path;
use crate::error::DatabaseError;
use crate::file::File;
use crate::file::FileType;
pub(crate) fn read_file(workspace: &Path, path: &Path, file_type: FileType) -> Result<File, DatabaseError> {
let logical_name = path
.strip_prefix(workspace)
.unwrap_or(path) .to_string_lossy()
.to_string();
let bytes = std::fs::read(path)?;
let contents = match str::from_utf8(&bytes) {
Ok(s) => s.to_string(),
Err(e) => {
let warning_message = format!(
"File `{}` contains invalid UTF-8 at byte {}. Lossy conversion applied, which may cause undefined behavior.",
logical_name,
e.valid_up_to()
);
match file_type {
FileType::Host => tracing::warn!("{}", warning_message),
FileType::Vendored | FileType::Builtin => tracing::info!("{}", warning_message),
}
String::from_utf8_lossy(&bytes).into_owned()
}
};
Ok(File::new(Cow::Owned(logical_name), file_type, Some(path.to_path_buf()), Cow::Owned(contents)))
}