use std::io::IsTerminal;
use std::path::PathBuf;
use anyhow::Result;
use clap_complete::aot::Shell;
use colored::Colorize;
use inquire::{Select, Text};
use crate::api_client::CxClient;
use crate::banner;
use crate::commands::{completions, profiles, skills};
use crate::config::{self, has_managed_completions, list_profile_names};
use crate::identity;
use crate::region::{region_from_url, RegionMatch};
const DEFAULT_PROFILE_NAME: &str = "default";
pub struct InitArgs {
pub url: Option<String>,
pub region: Option<String>,
pub api_key: Option<String>,
pub oauth: bool,
pub install_skills: bool,
pub agents: Vec<String>,
pub scope: Option<skills::SkillsScope>,
pub install_completions: Option<Shell>,
}
pub async fn run_init(args: InitArgs) -> Result<()> {
let InitArgs {
url,
region,
api_key,
oauth,
install_skills,
agents,
scope,
install_completions,
} = args;
if list_profile_names()?.is_empty() {
let oauth = oauth || api_key.is_none();
println!("Setting up your Coralogix profile...\n");
profiles::run_add(profiles::AddArgs {
name: Some(DEFAULT_PROFILE_NAME.to_string()),
url,
region,
api_key,
oauth,
force: false,
set_default: false,
disable_olly: false,
quick: true,
})
.await?;
} else {
println!("A Coralogix profile is already configured - skipping profile setup.");
}
let verified = verify_credentials().await?;
if install_skills {
println!("\nInstalling the cx agent skills for coding agents...");
match skills::run_install(skills::InstallOptions {
scope,
agents,
skip_if_installed: true,
}) {
Ok(skills::InstallOutcome::Installed) => {}
Ok(skills::InstallOutcome::AlreadyInstalled) => {
println!(
"cx agent skills are already installed - skipping.\n\
Update them anytime with `cx skills install`."
);
}
Err(error) => eprintln!("warning: skipped the agent-skills install: {error:#}"),
}
}
if has_managed_completions() {
println!("\nShell completions are already installed - skipping.");
} else {
let completions_choice = if let Some(shell) = install_completions {
Some((shell, None))
} else if std::io::stdin().is_terminal() {
prompt_completions_shell()?
} else {
None
};
if let Some((shell, path)) = completions_choice {
println!("\nInstalling {shell} shell completions...");
if let Err(error) = completions::run_install(shell, path) {
eprintln!("warning: skipped the shell-completions install: {error:#}");
}
}
}
print_success(verified);
Ok(())
}
fn prompt_completions_shell() -> Result<Option<(Shell, Option<PathBuf>)>> {
const SKIP: &str = "Don't install";
const OTHER: &str = "Other (specify shell and path)";
let options = vec![SKIP, "zsh", "bash", "fish", OTHER];
let choice = Select::new(
"Install shell completions? (enables <Tab> completion for cx)",
options,
)
.prompt()?;
let selection = if choice == "zsh" {
Some((Shell::Zsh, None))
} else if choice == "bash" {
Some((Shell::Bash, None))
} else if choice == "fish" {
Some((Shell::Fish, None))
} else if choice == OTHER {
let shell = Select::new(
"Which shell?",
vec![Shell::Bash, Shell::Zsh, Shell::Fish, Shell::PowerShell],
)
.prompt()?;
let path = Text::new("Install path:")
.with_help_message("Absolute path to write the completion script to.")
.with_validator(inquire::validator::MinLengthValidator::new(1))
.prompt()?;
Some((shell, Some(PathBuf::from(path))))
} else {
None
};
Ok(selection)
}
async fn verify_credentials() -> Result<bool> {
let cfg = config::resolve(None, None, None)
.await
.map_err(|e| anyhow::anyhow!("could not load the profile to verify it: {e:#}"))?;
if matches!(region_from_url(&cfg.endpoint), RegionMatch::Unresolved) {
return Ok(false);
}
let client = CxClient::new(&cfg.endpoint, &cfg.api_key)?;
identity::verify_identity(&client).await?;
Ok(true)
}
const GREEN: (u8, u8, u8) = (37, 222, 179);
fn print_connected_box() {
let (r, g, b) = GREEN;
let interior = " ✓ Connected ";
let width = interior.chars().count();
let top = format!("┌{}┐", "─".repeat(width));
let mid = format!("│{interior}│");
let bot = format!("└{}┘", "─".repeat(width));
println!("{}", top.truecolor(r, g, b));
println!("{}", mid.truecolor(r, g, b));
println!("{}", bot.truecolor(r, g, b));
}
fn print_success(verified: bool) {
if banner::should_show() {
println!("\n{}", banner::render_logo());
}
println!();
if verified {
print_connected_box();
} else {
println!("Profile configured. Skipped the automatic credential check");
}
println!();
println!("Try it out:");
println!(" cx logs 'source logs | limit 10'");
println!(" cx schema # discover every command as JSON");
}