#[cfg(test)]
mod tests;
use std::{
fs,
io::{self, BufWriter, Write},
path::{Path, PathBuf},
};
use ic_host_fs::{
durable::{PublicationMode, WriteOptions, write_bytes, write_with},
path::canonicalize_allow_missing,
};
use ic_host_text::escape::terminal_text;
use serde::{Serialize, de::DeserializeOwned};
pub fn render_terminal_lines(lines: &[String]) -> String {
lines
.iter()
.map(|line| terminal_text(line))
.collect::<Vec<_>>()
.join("\n")
}
pub fn resolve_operator_path(path: &Path) -> io::Result<PathBuf> {
let file_name = path.file_name().ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidInput,
"output target has no file name",
)
})?;
let parent = path
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.unwrap_or_else(|| Path::new("."));
let mut resolved = canonicalize_allow_missing(parent, &std::env::current_dir()?, usize::MAX)?;
resolved.push(file_name);
match fs::symlink_metadata(&resolved) {
Ok(metadata) if !metadata.is_file() => {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"output target is not a regular file",
));
}
Ok(_) => {}
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
Err(error) => return Err(error),
}
Ok(resolved)
}
pub fn write_pretty_json<T, E>(out: Option<&Path>, value: &T) -> Result<(), E>
where
T: Serialize,
E: From<io::Error> + From<serde_json::Error>,
{
if let Some(path) = out {
return write_pretty_json_file(path, value);
}
let stdout = io::stdout();
let mut handle = stdout.lock();
serde_json::to_writer_pretty(&mut handle, value)?;
writeln!(handle)?;
Ok(())
}
pub fn write_pretty_json_file<T, E>(path: &Path, value: &T) -> Result<(), E>
where
T: Serialize,
E: From<io::Error> + From<serde_json::Error>,
{
write_with(
&resolve_operator_path(path)?,
WriteOptions {
mode: PublicationMode::Replace,
permissions: 0o666,
},
|file| {
let mut writer = BufWriter::new(file);
serde_json::to_writer_pretty(&mut writer, value)?;
writer.flush().map_err(serde_json::Error::io)
},
)
.map_err(canic_host::publication::ops::json_error)?;
Ok(())
}
pub fn write_text<E>(out: Option<&Path>, text: &str) -> Result<(), E>
where
E: From<io::Error>,
{
if let Some(path) = out {
write_bytes(
&resolve_operator_path(path)?,
WriteOptions {
mode: PublicationMode::Replace,
permissions: 0o666,
},
text.as_bytes(),
)
.map_err(canic_host::publication::ops::io_error)?;
} else {
println!("{text}");
}
Ok(())
}
pub fn read_json_file<T, E>(path: &Path) -> Result<T, E>
where
T: DeserializeOwned,
E: From<io::Error> + From<serde_json::Error>,
{
let data = fs::read_to_string(path)?;
serde_json::from_str(&data).map_err(E::from)
}