canic-cli 0.115.0

Operator CLI for Canic fleet setup, builds, evidence, catalog, and diagnostics
Documentation
//! Module: canic_cli::output
//!
//! Responsibility: share safe report-line rendering and CLI file/stdout helpers.
//! Does not own: command-specific report formats, serialization schema, or diagnostics.
//! Boundary: writes caller-provided text/JSON payloads to stdout or filesystem paths.

#[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};

/// Escape each data-bearing report line before adding trusted line separators.
pub fn render_terminal_lines(lines: &[String]) -> String {
    lines
        .iter()
        .map(|line| terminal_text(line))
        .collect::<Vec<_>>()
        .join("\n")
}

/// Resolve the selected output's existing parent once, including macOS `/tmp`.
/// Missing directories remain for durable publication; the final file cannot be a link.
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)
}

/// Write a pretty JSON payload to a requested file or stdout.
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(())
}

/// Write a pretty JSON artifact file, creating its parent directory when needed.
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(())
}

/// Write a plain text payload to a requested file or stdout.
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(())
}

/// Read and decode one JSON file.
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)
}