use std::io::Write;
use serde::Serialize;
use serde_json::Value;
use crate::client::{
CallerResource, CompanyOfficerPage, CompanyPage, CompanyResource, DocumentResource,
ResolutionCandidate, ResolutionResource,
};
use crate::config::{display_origin, ConfigProfiles, EffectiveConfig, OutputFormat};
use crate::credential_store::CredentialReference;
use crate::error::CgdError;
pub struct Renderer<'a, W> {
writer: &'a mut W,
format: OutputFormat,
quiet: bool,
}
impl<'a, W: Write> Renderer<'a, W> {
pub fn new(writer: &'a mut W, format: OutputFormat, quiet: bool) -> Self {
Self {
writer,
format,
quiet,
}
}
pub fn resolution(
&mut self,
resource: &ResolutionResource,
raw: &Value,
) -> Result<(), CgdError> {
if self.quiet {
if let Some(result) = resource.result.as_ref() {
return self.line(result.id.as_str());
}
for candidate in &resource.candidates {
self.line(candidate.id.as_str())?;
}
return Ok(());
}
match self.format {
OutputFormat::Json => self.json(envelope_data(raw)?),
OutputFormat::Jsonl => self.json_line(envelope_data(raw)?),
OutputFormat::Csv => self.resolution_csv(resource),
OutputFormat::Table => self.resolution_table(resource),
}
}
pub fn company(&mut self, resource: &CompanyResource, raw: &Value) -> Result<(), CgdError> {
if self.quiet {
return self.line(resource.id.as_str());
}
match self.format {
OutputFormat::Json => self.json(envelope_data(raw)?),
OutputFormat::Jsonl => self.json_line(envelope_data(raw)?),
OutputFormat::Csv => self.company_csv(resource),
OutputFormat::Table => self.company_table(resource),
}
}
pub fn company_page(&mut self, page: &CompanyPage, raw: &Value) -> Result<(), CgdError> {
if self.quiet {
for item in &page.data {
self.line(item.company.id.as_str())?;
}
return Ok(());
}
match self.format {
OutputFormat::Json => self.json(raw),
OutputFormat::Jsonl => {
let items = raw.get("data").and_then(Value::as_array).ok_or_else(|| {
CgdError::Decode("search response is missing its data array".to_owned())
})?;
for item in items {
self.json_line(item)?;
}
Ok(())
}
OutputFormat::Csv => self.company_page_csv(page),
OutputFormat::Table => self.company_page_table(page),
}
}
pub fn company_officers(
&mut self,
page: &CompanyOfficerPage,
raw: &Value,
) -> Result<(), CgdError> {
match self.format {
OutputFormat::Json => self.json(raw),
OutputFormat::Jsonl => {
let officers = raw.get("data").and_then(Value::as_array).ok_or_else(|| {
CgdError::Decode("officer response is missing its data array".to_owned())
})?;
for officer in officers {
self.json_line(officer)?;
}
Ok(())
}
OutputFormat::Csv => self.company_officers_csv(page),
OutputFormat::Table => self.company_officers_table(page),
}
}
pub fn document(&mut self, document: &DocumentResource, raw: &Value) -> Result<(), CgdError> {
if self.quiet {
return self.line(document.id.as_str());
}
match self.format {
OutputFormat::Json => self.json(envelope_data(raw)?),
OutputFormat::Jsonl => self.json_line(envelope_data(raw)?),
OutputFormat::Csv => self.document_csv(document),
OutputFormat::Table => self.document_table(document),
}
}
pub fn caller(
&mut self,
caller: &CallerResource,
raw: &Value,
config: &EffectiveConfig,
) -> Result<(), CgdError> {
match self.format {
OutputFormat::Json => self.json(envelope_data(raw)?),
OutputFormat::Jsonl => self.json_line(envelope_data(raw)?),
OutputFormat::Csv => Err(CgdError::Usage(
"CSV output is not supported for auth status".to_owned(),
)),
OutputFormat::Table => {
self.kv("API endpoint", &display_origin(&config.api_base_url))?;
self.kv("profile", &config.profile)?;
self.kv(
"workspace",
config.workspace.as_deref().unwrap_or("server-derived"),
)?;
self.kv(
"credential source",
&config
.credential
.as_ref()
.map(|credential| credential.source_description())
.unwrap_or_else(|| "none".to_owned()),
)?;
self.kv("authenticated", "yes")?;
self.kv("principal type", &caller.principal_type)?;
self.kv("organization", &caller.organization_id)?;
self.kv("credential", &caller.credential_id)?;
self.kv("scopes", &display_list(&caller.scopes))?;
self.kv(
"max search results",
&caller.limits.max_search_results.to_string(),
)
}
}
}
pub fn auth_login(
&mut self,
caller: &CallerResource,
raw: &Value,
config: &EffectiveConfig,
reference: &CredentialReference,
) -> Result<(), CgdError> {
let value = serde_json::json!({
"status": "authenticated",
"profile": config.profile,
"credential_ref": reference.to_string(),
"caller": envelope_data(raw)?,
});
match self.format {
OutputFormat::Json => self.json(&value),
OutputFormat::Jsonl => self.json_line(&value),
OutputFormat::Csv => Err(CgdError::Usage(
"CSV output is not supported for auth login".to_owned(),
)),
OutputFormat::Table => {
self.kv("status", "authenticated")?;
self.kv("profile", &config.profile)?;
self.kv("credential reference", &reference.to_string())?;
self.kv("principal type", &caller.principal_type)?;
self.kv("organization", &caller.organization_id)?;
self.kv("credential", &caller.credential_id)?;
self.kv("scopes", &display_list(&caller.scopes))
}
}
}
pub fn auth_logout(
&mut self,
profile: &str,
reference: Option<&CredentialReference>,
credential_deleted: bool,
environment_credential_active: bool,
) -> Result<(), CgdError> {
let status = if reference.is_some() {
"logged_out_local"
} else {
"already_logged_out_local"
};
let value = serde_json::json!({
"status": status,
"profile": profile,
"credential_ref": reference.map(ToString::to_string),
"credential_deleted": credential_deleted,
"environment_credential_active": environment_credential_active,
});
match self.format {
OutputFormat::Json => self.json(&value),
OutputFormat::Jsonl => self.json_line(&value),
OutputFormat::Csv => Err(CgdError::Usage(
"CSV output is not supported for auth logout".to_owned(),
)),
OutputFormat::Table => {
self.kv("status", status)?;
self.kv("profile", profile)?;
self.kv(
"credential reference",
&reference
.map(ToString::to_string)
.unwrap_or_else(|| "none".to_owned()),
)?;
self.kv("credential deleted", yes_no(credential_deleted))?;
self.kv(
"environment credential active",
yes_no(environment_credential_active),
)
}
}
}
pub fn config(&mut self, config: &EffectiveConfig) -> Result<(), CgdError> {
let credential_source = config
.credential
.as_ref()
.map(|credential| credential.source_description())
.unwrap_or_else(|| "none".to_owned());
let value = serde_json::json!({
"profile": config.profile,
"api_base_url": config.api_base_url.as_str(),
"api_origin": display_origin(&config.api_base_url),
"workspace": config.workspace,
"output": config.output.to_string(),
"timeout": humantime::format_duration(config.timeout).to_string(),
"no_color": config.no_color,
"credential_source": credential_source,
"credential_ref": config.credential_ref.as_ref().map(ToString::to_string),
"config_path": config.config_path,
});
match self.format {
OutputFormat::Json => self.json(&value),
OutputFormat::Jsonl => self.json_line(&value),
OutputFormat::Csv => Err(CgdError::Usage(
"CSV output is not supported for config list".to_owned(),
)),
OutputFormat::Table => {
let object = value.as_object().expect("config value is an object");
for (key, value) in object {
self.kv(key, &scalar(value))?;
}
Ok(())
}
}
}
pub fn config_value<T: Serialize + std::fmt::Display>(
&mut self,
key: &str,
value: T,
) -> Result<(), CgdError> {
match self.format {
OutputFormat::Json | OutputFormat::Jsonl => {
let value = serde_json::to_value(value).map_err(|error| {
CgdError::Internal(format!("cannot encode config output: {error}"))
})?;
let object = serde_json::json!({ key: value });
if self.format == OutputFormat::Json {
self.json(&object)
} else {
self.json_line(&object)
}
}
OutputFormat::Csv => Err(CgdError::Usage(
"CSV output is not supported for config get".to_owned(),
)),
OutputFormat::Table => self.line(&value.to_string()),
}
}
pub fn config_profiles(&mut self, profiles: &ConfigProfiles) -> Result<(), CgdError> {
let value = serde_json::json!({
"current_profile": profiles.current,
"profiles": profiles.names,
});
match self.format {
OutputFormat::Json => self.json(&value),
OutputFormat::Jsonl => {
for profile in &profiles.names {
self.json_line(&serde_json::json!({
"profile": profile,
"current": profile == &profiles.current,
}))?;
}
Ok(())
}
OutputFormat::Csv => Err(CgdError::Usage(
"CSV output is not supported for config profiles".to_owned(),
)),
OutputFormat::Table => {
for profile in &profiles.names {
self.line(&format!(
"{} {profile}",
if profile == &profiles.current {
"*"
} else {
" "
}
))?;
}
Ok(())
}
}
}
pub fn version(&mut self) -> Result<(), CgdError> {
let version = env!("CARGO_PKG_VERSION");
match self.format {
OutputFormat::Json | OutputFormat::Jsonl => {
let value = serde_json::json!({
"name": "cgd",
"version": version,
"rust_msrv": "1.88",
"api_contract": "v1-alpha"
});
if self.format == OutputFormat::Json {
self.json(&value)
} else {
self.json_line(&value)
}
}
OutputFormat::Csv => Err(CgdError::Usage(
"CSV output is not supported for version".to_owned(),
)),
OutputFormat::Table => {
self.line(&format!("cgd {version}"))?;
self.line("public API contract: v1-alpha")?;
self.line("minimum Rust for source builds: 1.88")
}
}
}
fn resolution_table(&mut self, resource: &ResolutionResource) -> Result<(), CgdError> {
self.kv("status", &resource.status)?;
if let Some(requested) = resource.requested_id.as_ref() {
self.kv("requested ID", requested.as_str())?;
}
if let Some(canonical) = resource.canonical_id.as_ref() {
self.kv("canonical ID", canonical.as_str())?;
}
if let Some(result) = resource.result.as_ref() {
self.line("")?;
self.candidate_table(result)?;
}
if !resource.candidates.is_empty() {
self.line("")?;
self.line(
"ID COUNTRY NAME MATCH",
)?;
for candidate in &resource.candidates {
self.line(&format!(
"{:<30} {:<8} {:<28} {}",
candidate.id,
clip(candidate.jurisdiction.as_deref().unwrap_or("n/a"), 8),
clip(candidate.name.as_deref().unwrap_or("n/a"), 28),
display_list(&candidate.match_reasons)
))?;
}
}
if !resource.successor_ids.is_empty() {
self.kv(
"successors",
&resource
.successor_ids
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(", "),
)?;
}
Ok(())
}
fn candidate_table(&mut self, candidate: &ResolutionCandidate) -> Result<(), CgdError> {
self.kv("ID", candidate.id.as_str())?;
self.kv("name", candidate.name.as_deref().unwrap_or("n/a"))?;
self.kv(
"jurisdiction",
candidate.jurisdiction.as_deref().unwrap_or("n/a"),
)?;
self.kv("match", &display_list(&candidate.match_reasons))
}
fn resolution_csv(&mut self, resource: &ResolutionResource) -> Result<(), CgdError> {
let mut csv = csv::Writer::from_writer(&mut *self.writer);
csv.write_record(["status", "id", "name", "jurisdiction", "match_reasons"])?;
if let Some(result) = resource.result.as_ref() {
write_candidate_csv(&mut csv, &resource.status, result)?;
}
for candidate in &resource.candidates {
write_candidate_csv(&mut csv, &resource.status, candidate)?;
}
csv.flush()?;
Ok(())
}
fn company_table(&mut self, company: &CompanyResource) -> Result<(), CgdError> {
self.kv("ID", company.id.as_str())?;
self.kv("lifecycle", &company.lifecycle.status)?;
if let Some(canonical) = company.lifecycle.canonical_id.as_ref() {
self.kv("canonical ID", canonical.as_str())?;
}
if !company.lifecycle.successor_ids.is_empty() {
self.kv(
"successors",
&company
.lifecycle
.successor_ids
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(", "),
)?;
}
self.kv("name", company.name.as_deref().unwrap_or("n/a"))?;
self.kv("country", company.country_code.as_deref().unwrap_or("n/a"))?;
self.kv(
"company status",
company.company_status.as_deref().unwrap_or("n/a"),
)?;
self.kv(
"company type",
company.company_type.as_deref().unwrap_or("n/a"),
)?;
self.kv("industry", company.industry.as_deref().unwrap_or("n/a"))?;
self.kv("summary", company.summary.as_deref().unwrap_or("n/a"))?;
self.kv("as of", company.as_of_date.as_deref().unwrap_or("n/a"))
}
fn company_csv(&mut self, company: &CompanyResource) -> Result<(), CgdError> {
let mut csv = csv::Writer::from_writer(&mut *self.writer);
csv.write_record(company_headers())?;
csv.write_record(company_row(company, None))?;
csv.flush()?;
Ok(())
}
fn company_page_table(&mut self, page: &CompanyPage) -> Result<(), CgdError> {
self.line("ID COUNTRY STATUS SCORE NAME")?;
for item in &page.data {
self.line(&format!(
"{:<30} {:<8} {:<12} {:<10} {}",
item.company.id,
clip(item.company.country_code.as_deref().unwrap_or("n/a"), 8),
clip(item.company.company_status.as_deref().unwrap_or("n/a"), 12),
item.relevance_score
.map(|score| format!("{score:.4}"))
.unwrap_or_else(|| "n/a".to_owned()),
clip(item.company.name.as_deref().unwrap_or("n/a"), 48)
))?;
}
if let Some(cursor) = page.next_cursor.as_ref() {
self.line("")?;
self.kv("next cursor", cursor)?;
}
Ok(())
}
fn company_page_csv(&mut self, page: &CompanyPage) -> Result<(), CgdError> {
let mut csv = csv::Writer::from_writer(&mut *self.writer);
csv.write_record(company_headers())?;
for item in &page.data {
csv.write_record(company_row(&item.company, item.relevance_score))?;
}
csv.flush()?;
Ok(())
}
fn company_officers_table(&mut self, page: &CompanyOfficerPage) -> Result<(), CgdError> {
self.kv("company", page.company_id.as_str())?;
if page.requested_company_id != page.company_id {
self.kv("requested ID", page.requested_company_id.as_str())?;
}
self.line("")?;
self.line(
"NAME ROLE APPOINTED SOURCE",
)?;
for officer in &page.data {
self.line(&format!(
"{:<32} {:<30} {:<12} {}",
clip(&officer.name, 32),
clip(&display_list(&officer.roles), 30),
officer.appointed_on.as_deref().unwrap_or("n/a"),
clip(&officer.source.system, 24),
))?;
}
if page.has_more {
self.line("")?;
self.line("More current officers are available; rerun with a higher --limit.")?;
}
Ok(())
}
fn company_officers_csv(&mut self, page: &CompanyOfficerPage) -> Result<(), CgdError> {
let mut csv = csv::Writer::from_writer(&mut *self.writer);
csv.write_record([
"company_id",
"name",
"roles",
"appointed_on",
"resigned_on",
"source_system",
"source_url",
"observed_at",
])?;
for officer in &page.data {
csv.write_record([
page.company_id.as_str(),
&officer.name,
&officer.roles.join("|"),
officer.appointed_on.as_deref().unwrap_or_default(),
officer.resigned_on.as_deref().unwrap_or_default(),
&officer.source.system,
officer.source.url.as_deref().unwrap_or_default(),
officer.source.observed_at.as_deref().unwrap_or_default(),
])?;
}
csv.flush()?;
Ok(())
}
fn document_table(&mut self, document: &DocumentResource) -> Result<(), CgdError> {
self.kv("ID", document.id.as_str())?;
self.kv("lifecycle", &document.lifecycle.status)?;
if let Some(canonical) = document.lifecycle.canonical_id.as_ref() {
self.kv("canonical ID", canonical.as_str())?;
}
self.kv("company", document.company_id.as_str())?;
self.kv("type", &document.document_type)?;
self.kv(
"category",
document.document_category.as_deref().unwrap_or("n/a"),
)?;
self.kv("title", document.title.as_deref().unwrap_or("n/a"))?;
self.kv("source", &document.source.system)?;
self.kv("source record", &document.source.record_id)?;
self.kv(
"content type",
document.content_type.as_deref().unwrap_or("n/a"),
)?;
self.kv(
"size (bytes)",
&document
.byte_size
.map(|value| value.to_string())
.unwrap_or_else(|| "n/a".to_owned()),
)?;
self.kv("SHA-256", document.sha256.as_deref().unwrap_or("n/a"))?;
self.kv(
"published",
document
.published_at
.as_deref()
.or(document.published_date.as_deref())
.unwrap_or("n/a"),
)?;
self.kv("collected", &document.collected_at)?;
self.kv("availability", &document.availability)?;
self.kv(
"metadata access",
if document.access.metadata {
"yes"
} else {
"no"
},
)?;
self.kv(
"byte access",
if document.access.bytes { "yes" } else { "no" },
)
}
fn document_csv(&mut self, document: &DocumentResource) -> Result<(), CgdError> {
let mut csv = csv::Writer::from_writer(&mut *self.writer);
csv.write_record([
"id",
"lifecycle",
"canonical_id",
"company_id",
"document_type",
"document_category",
"title",
"source_system",
"source_record_id",
"file_name",
"content_type",
"file_extension",
"sha256",
"byte_size",
"filed_at",
"published_date",
"published_at",
"collected_at",
"availability",
"metadata_access",
"byte_access",
])?;
csv.write_record([
document.id.as_str(),
&document.lifecycle.status,
document
.lifecycle
.canonical_id
.as_ref()
.map(|id| id.as_str())
.unwrap_or_default(),
document.company_id.as_str(),
&document.document_type,
document.document_category.as_deref().unwrap_or_default(),
document.title.as_deref().unwrap_or_default(),
&document.source.system,
&document.source.record_id,
document.file_name.as_deref().unwrap_or_default(),
document.content_type.as_deref().unwrap_or_default(),
document.file_extension.as_deref().unwrap_or_default(),
document.sha256.as_deref().unwrap_or_default(),
&document
.byte_size
.map(|value| value.to_string())
.unwrap_or_default(),
document.filed_at.as_deref().unwrap_or_default(),
document.published_date.as_deref().unwrap_or_default(),
document.published_at.as_deref().unwrap_or_default(),
&document.collected_at,
&document.availability,
if document.access.metadata {
"true"
} else {
"false"
},
if document.access.bytes {
"true"
} else {
"false"
},
])?;
csv.flush()?;
Ok(())
}
fn kv(&mut self, key: &str, value: &str) -> Result<(), CgdError> {
self.line(&format!("{key:<20} {value}"))
}
fn json(&mut self, value: &Value) -> Result<(), CgdError> {
serde_json::to_writer_pretty(&mut *self.writer, value)
.map_err(|error| CgdError::Internal(format!("cannot encode JSON output: {error}")))?;
self.line("")
}
fn json_line(&mut self, value: &Value) -> Result<(), CgdError> {
serde_json::to_writer(&mut *self.writer, value)
.map_err(|error| CgdError::Internal(format!("cannot encode JSON output: {error}")))?;
self.line("")
}
fn line(&mut self, value: &str) -> Result<(), CgdError> {
self.writer.write_all(value.as_bytes())?;
self.writer.write_all(b"\n")?;
Ok(())
}
}
fn envelope_data(raw: &Value) -> Result<&Value, CgdError> {
raw.get("data")
.ok_or_else(|| CgdError::Decode("API envelope is missing its data member".to_owned()))
}
fn display_list(values: &[String]) -> String {
if values.is_empty() {
"n/a".to_owned()
} else {
values.join(", ")
}
}
const fn yes_no(value: bool) -> &'static str {
if value {
"yes"
} else {
"no"
}
}
fn clip(value: &str, max_chars: usize) -> String {
let count = value.chars().count();
if count <= max_chars {
return value.to_owned();
}
if max_chars <= 1 {
return "…".to_owned();
}
let mut result = value.chars().take(max_chars - 1).collect::<String>();
result.push('…');
result
}
fn scalar(value: &Value) -> String {
match value {
Value::Null => "n/a".to_owned(),
Value::String(value) => value.clone(),
_ => value.to_string(),
}
}
fn company_headers() -> [&'static str; 9] {
[
"id",
"lifecycle",
"name",
"country_code",
"company_status",
"company_type",
"industry",
"as_of_date",
"relevance_score",
]
}
fn company_row(company: &CompanyResource, score: Option<f32>) -> [String; 9] {
[
company.id.to_string(),
company.lifecycle.status.clone(),
company.name.clone().unwrap_or_default(),
company.country_code.clone().unwrap_or_default(),
company.company_status.clone().unwrap_or_default(),
company.company_type.clone().unwrap_or_default(),
company.industry.clone().unwrap_or_default(),
company.as_of_date.clone().unwrap_or_default(),
score.map(|value| value.to_string()).unwrap_or_default(),
]
}
fn write_candidate_csv<W: Write>(
csv: &mut csv::Writer<W>,
status: &str,
candidate: &ResolutionCandidate,
) -> Result<(), CgdError> {
csv.write_record([
status,
candidate.id.as_str(),
candidate.name.as_deref().unwrap_or_default(),
candidate.jurisdiction.as_deref().unwrap_or_default(),
&candidate.match_reasons.join("|"),
])?;
Ok(())
}
impl From<csv::Error> for CgdError {
fn from(error: csv::Error) -> Self {
match error.into_kind() {
csv::ErrorKind::Io(error) => error.into(),
other => CgdError::Internal(format!("cannot encode CSV output: {other:?}")),
}
}
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
use crate::client::{CompanyId, CompanyLifecycle};
fn company() -> CompanyResource {
CompanyResource {
id: "co_014d2pf2dbsqqg28t5cy4tqkff"
.parse::<CompanyId>()
.unwrap(),
object: "company".to_owned(),
lifecycle: CompanyLifecycle {
status: "active".to_owned(),
canonical_id: None,
successor_ids: Vec::new(),
},
name: Some("Example Robotics Oy".to_owned()),
summary: None,
country_code: Some("FI".to_owned()),
company_status: Some("active".to_owned()),
company_type: None,
industry: None,
business_model: None,
product_category: None,
operating_geography: None,
as_of_date: None,
identifiers: Vec::new(),
}
}
#[test]
fn json_output_preserves_unknown_public_api_fields() {
let raw = json!({
"data": {
"id": "co_014d2pf2dbsqqg28t5cy4tqkff",
"object": "company",
"lifecycle": {"status": "active"},
"future_field": {"preserved": true}
}
});
let mut bytes = Vec::new();
Renderer::new(&mut bytes, OutputFormat::Json, false)
.company(&company(), &raw)
.unwrap();
let output: Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(output["future_field"]["preserved"], true);
}
#[test]
fn quiet_company_output_is_exactly_the_public_id() {
let mut bytes = Vec::new();
Renderer::new(&mut bytes, OutputFormat::Table, true)
.company(&company(), &json!({"data": {}}))
.unwrap();
assert_eq!(
String::from_utf8(bytes).unwrap(),
"co_014d2pf2dbsqqg28t5cy4tqkff\n"
);
}
}