ic-query-cli 0.103.0

Command-line wrapper for read-only Internet Computer metadata queries
Documentation
//! Module: cli::common
//!
//! Responsibility: shared CLI output format and clock helpers.
//! Does not own: command parsing, report construction, or command-specific rendering.
//! Boundary: writes text/JSON reports and builds common CLI arguments.

use crate::output::{write_pretty_json, write_text};
use clap::Args;
use serde::Serialize;
use std::{
    io,
    time::{SystemTime, SystemTimeError, UNIX_EPOCH},
};
use thiserror::Error as ThisError;

pub const SOURCE_ENDPOINT_ARG: &str = "source-endpoint";
pub const COLLECTION_MODE_CACHE_ONLY: &str =
    "Local cache inspection; does not make a network request.";
pub const COLLECTION_MODE_CACHE_PREFERRED_LIVE_FALLBACK: &str = "Cache-preferred read; uses a complete local snapshot when available and otherwise makes a live query.";
pub const COLLECTION_MODE_CACHE_REFRESH_MISSING: &str =
    "Cache-backed read; refreshes and stores a complete snapshot only when the cache is missing.";
/// Cache-backed read that repairs absent or recoverably invalid content.
pub const COLLECTION_MODE_CACHE_REFRESH_MISSING_OR_INVALID: &str = "Cache-backed read; refreshes and stores a complete snapshot when the cache is missing or recoverably invalid.";
/// Cache-backed collection that visibly refreshes a missing or stale snapshot.
pub const COLLECTION_MODE_CACHE_REFRESH_STALE: &str = "Cache-backed read; refreshes and stores a complete snapshot when the cache is missing or older than its documented age policy.";
pub const COLLECTION_MODE_FORCE_REFRESH: &str = "Forced live refresh; fetches and validates a complete snapshot before any atomic cache replacement.";
pub const COLLECTION_MODE_LIVE: &str = "Live query; does not read or write a report cache.";
pub const COLLECTION_MODE_LIVE_OR_CACHE_BY_VIEW: &str = "View-dependent read; --sort api makes a bounded live query and other sorts use a complete local cache.";

///
/// OutputFormat
///
/// User-selected CLI output format for report rendering.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum OutputFormat {
    Text,
    Json,
}

impl OutputFormat {
    pub const fn from_json(json: bool) -> Self {
        if json { Self::Json } else { Self::Text }
    }
}

///
/// SourceOutputOptions
///
/// Common explicit source endpoint and output format for report commands.
///

#[derive(Args, Clone, Debug, Eq, PartialEq)]
#[group(skip)]
pub struct SourceOutputOptions {
    #[arg(long, help = "Print raw JSON instead of human-readable text")]
    json: bool,
    #[arg(id = SOURCE_ENDPOINT_ARG, long = SOURCE_ENDPOINT_ARG, value_name = "url", default_value = ic_query::icrc::DEFAULT_ICRC_SOURCE_ENDPOINT)]
    pub(crate) source_endpoint: String,
}

impl SourceOutputOptions {
    pub(crate) const fn format(&self) -> OutputFormat {
        OutputFormat::from_json(self.json)
    }

    pub(crate) fn into_dashboard_request(
        self,
        now_unix_secs: u64,
    ) -> (OutputFormat, ic_query::ic::IcDashboardRequest) {
        (
            self.format(),
            ic_query::ic::IcDashboardRequest::new(self.source_endpoint, now_unix_secs),
        )
    }
}

///
/// CurrentUnixSecsError
///
/// Error returned when the system clock cannot be represented as Unix seconds.
///

#[derive(Debug, ThisError)]
pub enum CurrentUnixSecsError {
    #[error("system clock before unix epoch: {source}")]
    BeforeUnixEpoch { source: SystemTimeError },
}

pub fn write_text_or_json<T, E>(
    format: OutputFormat,
    report: &T,
    render_text: impl FnOnce(&T) -> String,
) -> Result<(), E>
where
    T: Serialize,
    E: From<io::Error> + From<serde_json::Error>,
{
    match format {
        OutputFormat::Text => {
            let text = render_text(report);
            write_text::<E>(&text)
        }
        OutputFormat::Json => write_pretty_json(report),
    }
}

/// Resolve omitted bounds without altering explicitly supplied timestamps.
pub fn resolve_time_bounds(
    start: Option<u64>,
    end: Option<u64>,
    now_unix_secs: u64,
    default_window_secs: u64,
    minimum_default_start: u64,
) -> (u64, u64) {
    let end = end.unwrap_or(now_unix_secs);
    let start = start.unwrap_or_else(|| {
        end.saturating_sub(default_window_secs)
            .max(minimum_default_start)
    });
    (start, end)
}

/// Admit shared direction flags while the family owns sort semantics and defaults.
pub fn resolve_proposal_sort_direction(
    asc: bool,
    desc: bool,
    uses_local_direction: bool,
    default_direction: ic_query::report::SortDirection,
    local_sort_names: impl FnOnce() -> String,
) -> Result<ic_query::report::SortDirection, String> {
    let explicit = if asc {
        Some(("asc", ic_query::report::SortDirection::Asc))
    } else if desc {
        Some(("desc", ic_query::report::SortDirection::Desc))
    } else {
        None
    };
    match explicit {
        Some((_, direction)) if uses_local_direction => Ok(direction),
        Some((flag, _)) => Err(format!("--{flag} requires --sort {}", local_sort_names())),
        None => Ok(default_direction),
    }
}

pub fn write_text_or_json_verbose<T, E>(
    format: OutputFormat,
    report: &T,
    verbose: bool,
    render_text: impl FnOnce(&T, crate::presentation::TextOptions) -> String,
) -> Result<(), E>
where
    T: Serialize,
    E: From<io::Error> + From<serde_json::Error>,
{
    write_text_or_json(format, report, |report| {
        render_text(report, crate::presentation::TextOptions { verbose })
    })
}

pub fn current_unix_secs() -> Result<u64, CurrentUnixSecsError> {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|duration| duration.as_secs())
        .map_err(|source| CurrentUnixSecsError::BeforeUnixEpoch { source })
}

pub fn collection_help(mode: &str, examples: &str) -> String {
    format!("Collection mode: {mode}\n\n{examples}")
}