cgd 0.1.0-alpha.2

Official command-line interface for Coragrid source-linked private-market data infrastructure
Documentation
use clap::{ArgAction, Args, Parser, Subcommand, ValueEnum};
use clap_complete::Shell;

use crate::config::{ConfigOverrides, ConfigSetKey, OutputFormat};
use crate::error::CgdError;

#[derive(Debug, Parser)]
#[command(
    name = "cgd",
    version,
    about = "Source-linked private-market data from Coragrid",
    long_about = "The official Coragrid CLI. Explicit commands are deterministic and headless; stdout is data and stderr is diagnostics.",
    disable_help_subcommand = true
)]
pub struct Cli {
    /// Select a local configuration profile.
    #[arg(long, global = true)]
    pub profile: Option<String>,

    /// Select the output representation.
    #[arg(long, global = true, value_enum)]
    pub output: Option<OutputFormat>,

    /// Convenience alias for --output json.
    #[arg(long, global = true, conflicts_with = "output")]
    pub json: bool,

    /// Disable ANSI color output.
    #[arg(long, global = true)]
    pub no_color: bool,

    /// Print the primary identifier only where supported.
    #[arg(long, global = true)]
    pub quiet: bool,

    /// Increase diagnostic detail without exposing credentials or response bodies.
    #[arg(short, long, global = true, action = ArgAction::Count)]
    pub verbose: u8,

    /// Bound the complete request, such as 500ms, 10s, or 2m.
    #[arg(long, global = true)]
    pub timeout: Option<String>,

    /// Override the API endpoint. Remote endpoints must use HTTPS.
    #[arg(long, global = true, value_name = "URL")]
    pub api_base_url: Option<String>,

    /// Disable paging of human output. Paging is currently off by default.
    #[arg(long, global = true)]
    pub no_pager: bool,

    #[command(subcommand)]
    pub command: Option<Command>,
}

impl Cli {
    pub fn config_overrides(&self) -> Result<ConfigOverrides, CgdError> {
        Ok(ConfigOverrides {
            profile: self.profile.clone(),
            api_base_url: self.api_base_url.clone(),
            output: if self.json {
                Some(OutputFormat::Json)
            } else {
                self.output
            },
            timeout: self.timeout.clone(),
            no_color: self.no_color,
        })
    }
}

#[derive(Debug, Subcommand)]
pub enum Command {
    /// Inspect private-alpha authentication.
    Auth(AuthCommand),
    /// Inspect effective non-secret configuration.
    Config(ConfigCommand),
    /// Resolve a name, domain, external identifier, or Coragrid company ID.
    Resolve(ResolveArgs),
    /// Search and retrieve canonical companies.
    Companies(CompaniesCommand),
    /// Inspect rights-qualified source document metadata.
    Documents(DocumentsCommand),
    /// Launch the interactive Coragrid terminal interface.
    Tui(TuiArgs),
    /// Generate deterministic shell completions.
    Completions(CompletionsArgs),
    /// Print detailed client version information.
    Version,
}

#[derive(Debug, Args)]
pub struct AuthCommand {
    #[command(subcommand)]
    pub command: AuthSubcommand,
}

#[derive(Debug, Subcommand)]
pub enum AuthSubcommand {
    /// Interactively verify and store a private-alpha API key.
    Login,
    /// Remove the selected profile's local credential binding.
    Logout,
    /// Verify the configured credential and show safe caller capabilities.
    Status,
}

#[derive(Debug, Args)]
pub struct ConfigCommand {
    #[command(subcommand)]
    pub command: ConfigSubcommand,
}

#[derive(Debug, Subcommand)]
pub enum ConfigSubcommand {
    /// Print all effective non-secret settings.
    List,
    /// Print one effective non-secret setting.
    Get {
        #[arg(value_enum)]
        key: ConfigKey,
    },
    /// Set one validated value on the selected profile.
    Set {
        #[arg(value_enum)]
        key: ConfigSetKey,
        value: String,
    },
    /// List configured profiles without exposing credentials.
    Profiles,
    /// Select an existing profile as the default.
    Use { profile: String },
}

#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum ConfigKey {
    Profile,
    ApiBaseUrl,
    Workspace,
    Output,
    Timeout,
    NoColor,
    CredentialSource,
    CredentialRef,
    ConfigPath,
}

#[derive(Debug, Args)]
pub struct ResolveArgs {
    /// Company name, domain, or permanent co_ identifier.
    pub query: String,

    /// ISO 3166-1 alpha-2 jurisdiction hint.
    #[arg(long, value_name = "ISO2")]
    pub country: Option<String>,

    /// Canonical company domain hint.
    #[arg(long)]
    pub domain: Option<String>,

    /// Strong external selector in scheme:value form. One is supported in alpha.
    #[arg(long, value_name = "SCHEME:VALUE")]
    pub identifier: Vec<String>,

    /// Maximum candidates returned.
    #[arg(long, default_value_t = 5)]
    pub limit: u16,

    /// Exit with code 5 unless exactly one company resolves.
    #[arg(long)]
    pub require_unique: bool,
}

#[derive(Debug, Args)]
pub struct CompaniesCommand {
    #[command(subcommand)]
    pub command: CompaniesSubcommand,
}

#[derive(Debug, Subcommand)]
pub enum CompaniesSubcommand {
    /// Search canonical company profiles.
    Search(CompanySearchArgs),
    /// Get one canonical company by permanent co_ identifier.
    Get(CompanyGetArgs),
    /// List current source-attributed officers for a canonical company.
    Officers(CompanyOfficersArgs),
}

#[derive(Debug, Args)]
pub struct CompanyGetArgs {
    /// Permanent Coragrid company ID.
    pub company_id: String,
}

#[derive(Debug, Args)]
pub struct CompanyOfficersArgs {
    /// Permanent Coragrid company ID.
    pub company_id: String,

    /// Maximum current officer records to return.
    #[arg(long, default_value_t = 100, value_parser = clap::value_parser!(u16).range(1..=200))]
    pub limit: u16,
}

#[derive(Debug, Args)]
pub struct DocumentsCommand {
    #[command(subcommand)]
    pub command: DocumentsSubcommand,
}

#[derive(Debug, Subcommand)]
pub enum DocumentsSubcommand {
    /// Get metadata for one permanent Coragrid document ID.
    Get(DocumentGetArgs),
}

#[derive(Debug, Args)]
pub struct DocumentGetArgs {
    /// Permanent Coragrid document ID.
    pub document_id: String,

    /// Retrieve metadata only. Document bytes are not available in this release.
    #[arg(long, required = true)]
    pub metadata: bool,
}

#[derive(Debug, Args)]
pub struct CompanySearchArgs {
    /// Semantic company thesis. Omit only when structured filters are present.
    #[arg(long)]
    pub query: Option<String>,

    /// ISO 3166-1 alpha-2 country filter.
    #[arg(long, value_name = "ISO2")]
    pub country: Vec<String>,

    /// Canonical company status filter.
    #[arg(long)]
    pub status: Vec<String>,

    /// Canonical company type filter.
    #[arg(long = "type")]
    pub company_type: Vec<String>,

    /// Page size, bounded by caller entitlement.
    #[arg(long, default_value_t = 25)]
    pub limit: u16,

    /// Opaque continuation cursor returned by Coragrid.
    #[arg(long)]
    pub cursor: Option<String>,

    /// Follow all pages up to --max-results.
    #[arg(long, requires = "max_results", conflicts_with = "cursor")]
    pub all: bool,

    /// Required safety bound when --all is used.
    #[arg(long, value_name = "N")]
    pub max_results: Option<usize>,

    /// Financial field used for a structured range. Currently revenue.
    #[arg(long, value_enum)]
    pub financial_field: Option<FinancialFieldArg>,

    /// Fiscal period in FYYYYY form, for example FY2025.
    #[arg(long)]
    pub financial_period: Option<String>,

    /// ISO 4217 currency for the financial filter.
    #[arg(long)]
    pub financial_currency: Option<String>,

    /// Inclusive lower financial bound in minor-independent whole units.
    #[arg(long, allow_hyphen_values = true)]
    pub financial_gte: Option<i64>,

    /// Inclusive upper financial bound in minor-independent whole units.
    #[arg(long, allow_hyphen_values = true)]
    pub financial_lte: Option<i64>,

    /// Reporting scope for the financial filter.
    #[arg(long, value_enum, default_value = "company")]
    pub financial_scope: ReportingScopeArg,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum FinancialFieldArg {
    Revenue,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum ReportingScopeArg {
    Company,
    Group,
}

#[derive(Debug, Args)]
pub struct TuiArgs {
    /// Disable mouse capture while the terminal interface is active.
    #[arg(long)]
    pub no_mouse: bool,

    /// Select a terminal theme.
    #[arg(long, value_enum, default_value = "dark")]
    pub theme: ThemeArg,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum ThemeArg {
    Dark,
    Light,
    Mono,
}

#[derive(Debug, Args)]
pub struct CompletionsArgs {
    /// Shell whose completion script should be generated.
    #[arg(value_enum)]
    pub shell: Shell,
}

#[cfg(test)]
mod tests {
    use clap::Parser;

    use super::*;

    #[test]
    fn explicit_data_commands_parse_without_tty_assumptions() {
        let cli = Cli::try_parse_from([
            "cgd",
            "--output",
            "jsonl",
            "companies",
            "search",
            "--query",
            "Nordic automation",
            "--country",
            "FI",
            "--country",
            "SE",
            "--limit",
            "25",
        ])
        .unwrap();
        assert!(matches!(
            cli.command,
            Some(Command::Companies(CompaniesCommand {
                command: CompaniesSubcommand::Search(_)
            }))
        ));
        assert_eq!(cli.output, Some(OutputFormat::Jsonl));
    }

    #[test]
    fn credentials_are_not_accepted_as_command_line_arguments() {
        let error =
            Cli::try_parse_from(["cgd", "--api-key", "secret", "auth", "status"]).unwrap_err();
        assert_eq!(error.exit_code(), 2);
        assert!(!error.to_string().contains("secret"));
    }

    #[test]
    fn document_get_requires_an_explicit_metadata_mode() {
        assert!(
            Cli::try_parse_from(["cgd", "documents", "get", "doc_014d2pf2dbsqqg28t5cy4tqkff"])
                .is_err()
        );
        assert!(Cli::try_parse_from([
            "cgd",
            "documents",
            "get",
            "doc_014d2pf2dbsqqg28t5cy4tqkff",
            "--metadata"
        ])
        .is_ok());
    }
}