cgd 0.1.0-alpha.2

Official command-line interface for Coragrid source-linked private-market data infrastructure
Documentation
//! Internal application entry point for the `cgd` binary.
//!
//! `cgd` is currently distributed as a command-line application and does not
//! expose a supported Rust library API. Use the executable and its documented
//! command and output contracts instead.

#![forbid(unsafe_code)]

use std::io::{self, Write};

use clap::{CommandFactory, Parser};

mod cli;
mod client;
mod commands;
mod config;
mod credential_store;
mod error;
mod output;
mod signals;
mod tui;

use cli::{AuthSubcommand, Cli, Command, ConfigSubcommand};
use config::{EffectiveConfig, OutputFormat};
use error::{CgdError, ExitStatus};
use output::Renderer;

/// Returns the compiled command tree for repository-owned documentation tools.
///
/// This is an internal release hook rather than a supported client-library API.
#[doc(hidden)]
pub fn command_for_documentation() -> clap::Command {
    Cli::command()
}

#[doc(hidden)]
pub async fn entrypoint() -> std::process::ExitCode {
    let cli = match Cli::try_parse() {
        Ok(cli) => cli,
        Err(error) => {
            let status = error.exit_code();
            let _ = error.print();
            return std::process::ExitCode::from(status.clamp(0, u8::MAX as i32) as u8);
        }
    };
    if let Some(options) = requested_tui(&cli) {
        let result = if tui::is_suitable(&cli) {
            run_tui(&cli, options).await
        } else {
            Err(CgdError::Usage(
                "the TUI requires interactive stdin, stdout, and stderr; no machine output mode, TERM=dumb, or CI environment"
                    .to_owned(),
            ))
        };
        return finish_interactive(result);
    }
    let stdout = io::stdout();
    let stderr = io::stderr();
    let mut stdout = stdout.lock();
    let mut stderr = stderr.lock();
    match run(&cli, &mut stdout, &mut stderr).await {
        Ok(status) => std::process::ExitCode::from(status.code()),
        Err(CgdError::BrokenPipe) => std::process::ExitCode::SUCCESS,
        Err(error) => {
            let status = error.exit_status();
            if !matches!(error, CgdError::Interrupted) {
                let _ = writeln!(stderr, "error: {error}");
                if let Some(request_id) = error.request_id() {
                    let _ = writeln!(stderr, "request: {request_id}");
                }
            }
            std::process::ExitCode::from(status.code())
        }
    }
}

async fn run<W: Write, E: Write>(
    cli: &Cli,
    stdout: &mut W,
    stderr: &mut E,
) -> Result<ExitStatus, CgdError> {
    let Some(command) = cli.command.as_ref() else {
        let mut command = Cli::command();
        command
            .write_long_help(&mut *stdout)
            .map_err(CgdError::from)?;
        writeln!(stdout)?;
        return Ok(ExitStatus::Success);
    };

    match command {
        Command::Completions(arguments) => {
            let mut bytes = Vec::new();
            clap_complete::generate(arguments.shell, &mut Cli::command(), "cgd", &mut bytes);
            stdout.write_all(&bytes)?;
            return Ok(ExitStatus::Success);
        }
        Command::Version => {
            let format = if cli.json {
                OutputFormat::Json
            } else {
                cli.output.unwrap_or(OutputFormat::Table)
            };
            Renderer::new(stdout, format, cli.quiet).version()?;
            return Ok(ExitStatus::Success);
        }
        Command::Tui(_) => {
            return Err(CgdError::Usage(
                "the TUI requires a suitable interactive terminal".to_owned(),
            ));
        }
        _ => {}
    }

    let overrides = cli.config_overrides()?;
    let config = match command {
        Command::Config(crate::cli::ConfigCommand {
            command: ConfigSubcommand::Set { .. },
        }) => EffectiveConfig::load_for_profile_update(&overrides)?,
        Command::Auth(crate::cli::AuthCommand {
            command: AuthSubcommand::Login,
        }) => EffectiveConfig::load_for_credential_update(&overrides, true)?,
        Command::Auth(crate::cli::AuthCommand {
            command: AuthSubcommand::Logout,
        }) => EffectiveConfig::load_for_credential_update(&overrides, false)?,
        _ => EffectiveConfig::load(&overrides)?,
    };
    let mut shutdown = signals::ShutdownSignals::new().map_err(|error| {
        CgdError::Internal(format!("cannot initialize signal handling: {error}"))
    })?;
    let operation = commands::execute(cli, command, &config, stdout, stderr);
    tokio::select! {
        result = operation => result,
        signal = shutdown.recv() => {
            signal.map_err(|error| CgdError::Internal(format!("cannot listen for interruption: {error}")))?;
            Err(CgdError::Interrupted)
        }
    }
}

fn requested_tui(cli: &Cli) -> Option<tui::TuiOptions> {
    match cli.command.as_ref() {
        Some(Command::Tui(arguments)) => Some(tui::TuiOptions {
            mouse: !arguments.no_mouse,
            theme: arguments.theme,
        }),
        None if tui::is_suitable(cli) => Some(tui::TuiOptions {
            mouse: true,
            theme: cli::ThemeArg::Dark,
        }),
        _ => None,
    }
}

async fn run_tui(cli: &Cli, mut options: tui::TuiOptions) -> Result<(), CgdError> {
    let config = EffectiveConfig::load(&cli.config_overrides()?)?;
    if cli.no_color || config.no_color {
        options.theme = cli::ThemeArg::Mono;
    }
    tui::run(config, options).await
}

fn finish_interactive(result: Result<(), CgdError>) -> std::process::ExitCode {
    match result {
        Ok(()) | Err(CgdError::BrokenPipe) => std::process::ExitCode::SUCCESS,
        Err(error) => {
            let status = error.exit_status();
            if !matches!(error, CgdError::Interrupted) {
                eprintln!("error: {error}");
                if let Some(request_id) = error.request_id() {
                    eprintln!("request: {request_id}");
                }
            }
            std::process::ExitCode::from(status.code())
        }
    }
}