use std::io::IsTerminal;
use anyhow::Result;
use inquire::{Confirm, Password, PasswordDisplayMode, Select, Text};
use crate::config::{
has_managed_completions, list_profile_names, load_config, load_profile, profile_file,
save_config, save_profile, AuthKind, CredentialStorage, OutputFormat, Profile, Region,
};
use crate::keyring_store;
use crate::oauth;
use crate::region::{region_from_url, RegionMatch};
const AUTH_METHODS: &[&str] = &["OAuth (browser login)", "API key (paste manually)"];
const CUSTOM_ENDPOINT_OPTION: &str = "Custom endpoint (BYOC / private link)";
const PICKER_REGIONS: &[Region] = &[
Region::Us1,
Region::Us2,
Region::Us3,
Region::Eu1,
Region::Eu2,
Region::Ap1,
Region::Ap2,
Region::Ap3,
];
const REGION_DEFAULT_CURSOR: usize = 4;
fn region_option_label(region: &Region) -> String {
match region.app_url_template() {
Some(template) => format!("({region}) {template}"),
None => region.to_string(),
}
}
fn region_picker_options() -> Vec<String> {
PICKER_REGIONS
.iter()
.map(region_option_label)
.chain([CUSTOM_ENDPOINT_OPTION.to_string()])
.collect()
}
fn is_picker_region(region: &Region) -> bool {
PICKER_REGIONS.iter().any(|r| r == region)
}
#[derive(Debug)]
enum RegionChoice {
Known(Region),
Custom { base_url: String },
}
const OUTPUT_FORMATS: &[&str] = &["text", "json", "toon"];
#[cfg(all(target_os = "linux", target_env = "musl"))]
const CREDENTIAL_STORAGE_OPTIONS: &[(&str, CredentialStorage)] =
&[("file", CredentialStorage::File)];
#[cfg(not(all(target_os = "linux", target_env = "musl")))]
const CREDENTIAL_STORAGE_OPTIONS: &[(&str, CredentialStorage)] = &[
("os-store (encrypted)", CredentialStorage::OsStore),
("file", CredentialStorage::File),
];
fn credential_storage_starting_cursor() -> usize {
CREDENTIAL_STORAGE_OPTIONS
.iter()
.position(|(_, storage)| *storage == CredentialStorage::OsStore)
.unwrap_or(0)
}
fn credential_storage_help_message(file_description: &str) -> String {
if cfg!(all(target_os = "linux", target_env = "musl")) {
format!("Linux musl builds do not have an OS credential store. 'file' {file_description}")
} else {
format!(
"'os-store' uses the OS credential store (macOS Keychain, Windows Credential Manager, \
Linux Secret Service). 'file' {file_description} Falls back to file if the OS store \
is unavailable."
)
}
}
fn select_credential_storage(prompt: &str, help_message: &str) -> Result<CredentialStorage> {
let labels: Vec<&str> = CREDENTIAL_STORAGE_OPTIONS.iter().map(|(l, _)| *l).collect();
let chosen = Select::new(prompt, labels)
.with_help_message(help_message)
.with_starting_cursor(credential_storage_starting_cursor())
.prompt()?;
Ok(CREDENTIAL_STORAGE_OPTIONS
.iter()
.find(|(label, _)| *label == chosen)
.map(|(_, storage)| *storage)
.expect("inquire returns one of the labels we passed in"))
}
fn os_store_or_file_fallback<T>(
profile: &str,
store_result: Result<()>,
file_payload: T,
os_desc: &'static str,
file_desc: &'static str,
) -> (CredentialStorage, Option<T>, &'static str) {
match store_result {
Ok(()) => (CredentialStorage::OsStore, None, os_desc),
Err(err) => {
keyring_store::delete_profile(profile);
eprintln!(
"Warning: OS credential store unavailable ({err}); falling back to file storage."
);
(CredentialStorage::File, Some(file_payload), file_desc)
}
}
}
fn select_region_interactive() -> Result<RegionChoice> {
let last_input = std::cell::RefCell::new(String::new());
let scorer = |input: &str, option: &String, string_value: &str, idx: usize| -> Option<i64> {
*last_input.borrow_mut() = input.to_string();
match region_from_url(input) {
RegionMatch::Known(region) if is_picker_region(®ion) => {
(region_option_label(®ion) == string_value).then_some(i64::MAX)
}
_ => {
if (input.contains("://") || input.contains('.'))
&& string_value == CUSTOM_ENDPOINT_OPTION
{
return Some(0);
}
(Select::<String>::DEFAULT_SCORER)(input, option, string_value, idx)
}
}
};
let choice = Select::new("Region / Coralogix URL:", region_picker_options())
.with_starting_cursor(REGION_DEFAULT_CURSOR)
.with_help_message("Enter your Coralogix URL to auto-detect the region, or type to filter.")
.with_scorer(&scorer)
.prompt()?;
if choice == CUSTOM_ENDPOINT_OPTION {
let typed = last_input.into_inner().trim().to_string();
if typed.contains("://") || typed.contains('.') {
return resolve_url_choice(&typed);
}
prompt_custom_endpoint()
} else {
let region = PICKER_REGIONS
.iter()
.find(|r| region_option_label(r) == choice)
.cloned()
.expect("inquire returns one of the labels we passed in");
Ok(RegionChoice::Known(region))
}
}
fn resolve_url_choice(raw: &str) -> Result<RegionChoice> {
match region_from_url(raw) {
RegionMatch::Known(region) if is_picker_region(®ion) => {
println!("Detected region: {region}");
Ok(RegionChoice::Known(region))
}
_ => match custom_base_url_from(raw) {
Some(base_url) => {
println!(
"Couldn't map that URL to a known region - \
using it as a custom endpoint: {base_url}"
);
Ok(RegionChoice::Custom { base_url })
}
None => {
println!(
"Couldn't map that URL to a known region - \
enter your API endpoint manually."
);
prompt_custom_endpoint()
}
},
}
}
fn custom_base_url_from(raw: &str) -> Option<String> {
let cleaned = raw.trim().trim_end_matches('/');
if cleaned.is_empty() {
return None;
}
let with_scheme = if cleaned.contains("://") {
cleaned.to_string()
} else {
format!("https://{cleaned}")
};
crate::region::extract_host(&with_scheme).map(|_| with_scheme)
}
fn prompt_custom_endpoint() -> Result<RegionChoice> {
use inquire::validator::Validation;
let raw_url = Text::new("Base URL (e.g. https://api.myenv.coralogix.com):")
.with_validator(|input: &str| {
if crate::region::extract_host(input).is_some() {
Ok(Validation::Valid)
} else {
Ok(Validation::Invalid(
"Enter a URL with a host, e.g. https://api.myenv.coralogix.com".into(),
))
}
})
.prompt()?;
let base_url = custom_base_url_from(&raw_url).expect("validator guarantees a parseable host");
Ok(RegionChoice::Custom { base_url })
}
fn parse_region_flag(raw: &str) -> Result<Region> {
let region: Region = raw.parse().expect("Region::from_str is infallible");
if matches!(region, Region::Custom(_)) {
anyhow::bail!(
"unknown region '{raw}' — expected one of us1, us2, us3, eu1, eu2, ap1, ap2, ap3, \
or pass --url with your Coralogix URL"
);
}
Ok(region)
}
fn resolve_region_flags(url: Option<&str>, region: Option<&str>) -> Result<Option<RegionChoice>> {
if let Some(raw) = region {
return Ok(Some(RegionChoice::Known(parse_region_flag(raw)?)));
}
let Some(raw) = url else {
return Ok(None);
};
match region_from_url(raw) {
RegionMatch::Known(region) if is_picker_region(®ion) => {
println!("Detected region: {region}");
Ok(Some(RegionChoice::Known(region)))
}
_ => {
if crate::region::extract_host(raw).is_none() {
anyhow::bail!(
"'--url {raw}' is not a valid URL — pass your Coralogix URL \
(e.g. https://myteam.app.eu2.coralogix.com) or use --region"
);
}
println!("Couldn't map '{raw}' to a known region — using it as a custom API endpoint.");
let base_url = raw.trim().trim_end_matches('/').to_string();
Ok(Some(RegionChoice::Custom { base_url }))
}
}
}
fn hint_completions_refresh() {
if has_managed_completions() {
println!(
"Tip: profile list changed - run `cx completions refresh` \
to update static completion scripts."
);
}
}
pub fn run_list() -> Result<()> {
let global_config = load_config().unwrap_or_default();
let names = list_profile_names()?;
let entries: Vec<(String, Profile)> = names
.into_iter()
.filter_map(|name| {
let profile = load_profile(&name).ok()?;
Some((name, profile))
})
.collect();
if entries.is_empty() {
println!("No profiles configured. Run `cx profiles add` to create one.");
return Ok(());
}
let name_w = entries
.iter()
.map(|(n, _)| n.len())
.max()
.unwrap_or(4)
.max(4);
let label_w = entries
.iter()
.map(|(_, p)| p.label.as_deref().unwrap_or("-").len())
.max()
.unwrap_or(5)
.max(5);
let region_w = entries
.iter()
.map(|(_, p)| p.region.to_string().len())
.max()
.unwrap_or(6)
.max(6);
let output_w = 6;
println!(
"{:<name_w$} {:<label_w$} {:<region_w$} {:<8} {:<output_w$} DEFAULT",
"NAME",
"LABEL",
"REGION",
"AUTH",
"OUTPUT",
name_w = name_w,
label_w = label_w,
region_w = region_w,
output_w = output_w,
);
println!(
"{:<name_w$} {:<label_w$} {:<region_w$} {:<8} {:<output_w$} -------",
"-".repeat(name_w),
"-".repeat(label_w),
"-".repeat(region_w),
"--------",
"-".repeat(output_w),
name_w = name_w,
label_w = label_w,
region_w = region_w,
output_w = output_w,
);
for (name, profile) in &entries {
let label = profile.label.as_deref().unwrap_or("-");
let region = profile.region.to_string();
let auth = match profile.auth {
AuthKind::OAuth => "oauth",
AuthKind::ApiKey => "api-key",
};
let output_fmt = profile
.default_output_format
.map(|f| f.as_str())
.unwrap_or("-");
let is_default = if *name == global_config.default_profile {
"yes"
} else {
""
};
println!(
"{:<name_w$} {:<label_w$} {:<region_w$} {:<8} {:<output_w$} {}",
name,
label,
region,
auth,
output_fmt,
is_default,
name_w = name_w,
label_w = label_w,
region_w = region_w,
output_w = output_w,
);
}
Ok(())
}
pub struct AddArgs {
pub name: Option<String>,
pub url: Option<String>,
pub region: Option<String>,
pub api_key: Option<String>,
pub oauth: bool,
pub signup: bool,
pub force: bool,
pub set_default: bool,
pub disable_olly: bool,
pub quick: bool,
}
pub async fn run_add(args: AddArgs) -> Result<()> {
let AddArgs {
name,
url,
region,
api_key,
oauth,
signup,
force,
set_default,
disable_olly,
quick,
} = args;
let oauth = oauth || signup;
let api_key = api_key.filter(|k| !k.trim().is_empty()).filter(|_| !oauth);
let region_choice = resolve_region_flags(url.as_deref(), region.as_deref())?;
let fully_specified = api_key.is_some() && region_choice.is_some();
let interactive = std::io::stdin().is_terminal() && !fully_specified;
let is_first_profile = list_profile_names()?.is_empty();
let name = match name {
Some(n) => {
if n.is_empty() {
anyhow::bail!("Profile name cannot be empty.");
}
n
}
None if interactive => {
let mut prompt = Text::new("Profile name:")
.with_help_message("A short identifier for this profile, e.g. 'prod' or 'staging'.")
.with_validator(inquire::validator::MinLengthValidator::new(1));
if is_first_profile {
prompt = prompt.with_default("default");
}
prompt.prompt()?
}
None => "default".to_string(),
};
if profile_file(&name)?.exists() && !force {
if interactive {
let confirmed = Confirm::new(&format!("Reconfigure profile '{name}'?"))
.with_default(false)
.with_help_message("The profile already exists; reconfiguring replaces it.")
.prompt()?;
if !confirmed {
println!("Cancelled.");
return Ok(());
}
} else {
anyhow::bail!("profile '{name}' already exists — pass --force to overwrite");
}
}
println!("Configuring profile '{name}'\n");
let (mut profile, storage_desc) = if oauth {
configure_oauth(&name, region_choice, interactive, quick, signup).await?
} else if !interactive {
build_profile_non_interactive(&name, api_key, region_choice)?
} else if api_key.is_some() {
configure_api_key(&name, api_key, region_choice, quick)?
} else {
let auth_choice = Select::new("Authentication method:", AUTH_METHODS.to_vec())
.with_starting_cursor(0) .with_help_message(
"OAuth opens your browser for secure login. \
API key lets you paste credentials directly \
(must be a Team Key or Personal Key - not a Send-Your-Data key).",
)
.prompt()?;
if auth_choice.starts_with("OAuth") {
configure_oauth(&name, region_choice, interactive, quick, signup).await?
} else {
configure_api_key(&name, None, region_choice, quick)?
}
};
if quick {
profile.default_output_format = Some(OutputFormat::Json);
} else if interactive {
let global_config = load_config().unwrap_or_default();
let current_fmt = profile
.default_output_format
.unwrap_or(global_config.default_output_format);
let current_idx = OUTPUT_FORMATS
.iter()
.position(|&f| f == current_fmt.as_str())
.unwrap_or(0);
let format_str = Select::new("Default output format:", OUTPUT_FORMATS.to_vec())
.with_starting_cursor(current_idx)
.prompt()?;
profile.default_output_format = Some(match format_str {
"json" => OutputFormat::Json,
"toon" => OutputFormat::Toon,
_ => OutputFormat::Text,
});
}
save_profile(&name, &profile)?;
if is_first_profile {
let mut global_config = load_config().unwrap_or_default();
global_config.olly_enabled = !disable_olly;
global_config.default_profile = name.clone();
save_config(&global_config)?;
}
if !is_first_profile {
let mut global_config = load_config().unwrap_or_default();
let should_set_default = if set_default {
true
} else if interactive {
Confirm::new(&format!("Set '{name}' as the default profile?"))
.with_default(false)
.prompt()?
} else {
false
};
if should_set_default {
global_config.default_profile = name.clone();
save_config(&global_config)?;
}
}
report_onboarding(Some(&name)).await;
let cx_dir = crate::config::config_dir()?;
println!(
"\nProfile '{name}' saved to {}\nCredentials stored in {storage_desc}",
cx_dir.display()
);
hint_completions_refresh();
Ok(())
}
pub async fn report_onboarding(name: Option<&str>) {
let Ok(cfg) = crate::config::resolve(name, None, None).await else {
return;
};
let outcome = crate::onboarding::report(&cfg.profile_name, &cfg.endpoint, &cfg.api_key).await;
if outcome == Some(crate::onboarding::Outcome::Forbidden) {
let profile = match name {
Some(name) => name.to_string(),
None => load_config().unwrap_or_default().default_profile,
};
eprintln!(
"note: profile '{profile}' signs in with an API key, so this setup isn't linked \
to your Coralogix user. To link it, sign in as yourself with \
`cx profiles add {profile} --oauth --force`."
);
}
}
pub async fn run_refresh(profile_name: String) -> Result<()> {
if !profile_file(&profile_name)?.exists() {
anyhow::bail!(
"Profile '{profile_name}' not found. Run `cx profiles add {profile_name}` to set it up."
);
}
crate::config::refresh_oauth_profile(&profile_name).await
}
pub fn run_delete(profile_name: String, force: bool) -> Result<()> {
let path = profile_file(&profile_name)?;
if !path.exists() {
anyhow::bail!("Profile '{profile_name}' not found.");
}
let global_config = load_config().unwrap_or_default();
let is_default = profile_name == global_config.default_profile;
if !force {
let warning = if is_default {
format!(
"Delete profile '{profile_name}'? This is your default profile.\n\
All stored credentials will be removed."
)
} else {
format!(
"Delete profile '{profile_name}'?\n\
All stored credentials will be removed."
)
};
let confirmed = Confirm::new(&warning).with_default(false).prompt()?;
if !confirmed {
println!("Cancelled.");
return Ok(());
}
}
keyring_store::delete_profile(&profile_name);
std::fs::remove_file(&path)?;
println!("Profile '{profile_name}' deleted.");
if is_default {
println!(
"Note: '{profile_name}' was your default profile. \
Run `cx profiles set-default <name>` to set a new default."
);
}
hint_completions_refresh();
Ok(())
}
pub fn run_set_default(profile_name: String) -> Result<()> {
let path = profile_file(&profile_name)?;
if !path.exists() {
anyhow::bail!("Profile '{profile_name}' not found.");
}
let mut global_config = load_config().unwrap_or_default();
if global_config.default_profile == profile_name {
println!("Profile '{profile_name}' is already the default.");
return Ok(());
}
global_config.default_profile = profile_name.clone();
save_config(&global_config)?;
println!("Default profile set to '{profile_name}'.");
Ok(())
}
fn build_profile_non_interactive(
name: &str,
api_key: Option<String>,
region_choice: Option<RegionChoice>,
) -> Result<(Profile, &'static str)> {
let mut missing = Vec::new();
if region_choice.is_none() {
missing.push("no region — pass --url or --region");
}
if api_key.is_none() {
missing.push("no API key — pass --api-key or set CX_API_KEY");
}
if !missing.is_empty() {
anyhow::bail!("{}", missing.join("\n"));
}
let (api_key, region_choice) = (api_key.unwrap(), region_choice.unwrap());
let region = match region_choice {
RegionChoice::Known(region) => region,
RegionChoice::Custom { base_url } => Region::Custom(base_url),
};
keyring_store::delete_profile(name);
let profile = Profile {
auth: AuthKind::ApiKey,
credential_storage: CredentialStorage::File,
api_key: Some(api_key),
region,
label: None,
oauth_client_id: None,
oauth_base_url: None,
oauth_tokens: None,
default_output_format: None,
default_tier: None,
console_url: None,
cached_console_url: None,
cached_console_url_at: None,
cached_team_id: None,
cached_team_name: None,
};
Ok((profile, "profile file"))
}
async fn configure_oauth(
name: &str,
region_choice: Option<RegionChoice>,
interactive: bool,
quick: bool,
signup: bool,
) -> Result<(Profile, &'static str)> {
let region_choice = match region_choice {
Some(choice) => choice,
None if interactive => select_region_interactive()?,
None => anyhow::bail!("no region — pass --url or --region"),
};
let is_custom;
let (region, base_url, client_id, oauth_client_id_for_profile) = match region_choice {
RegionChoice::Custom { base_url } => {
is_custom = true;
if !interactive {
anyhow::bail!(
"a custom endpoint needs an OAuth client ID, which is prompted \
interactively — run on a terminal, or use --api-key/CX_API_KEY"
);
}
let client_id = Text::new("OAuth client ID:").prompt()?;
let region = Region::Custom(base_url.clone());
let client_id_for_profile = Some(client_id.clone());
(region, base_url, client_id, client_id_for_profile)
}
RegionChoice::Known(region) => {
is_custom = false;
let base_url = region.api_endpoint().to_string();
let region_name = region.to_string();
let client_id = oauth::client_id_for_region(®ion_name)
.map(|s| s.to_string())
.ok_or_else(|| {
anyhow::anyhow!(
"No OAuth client ID found for region '{region_name}'.\n\
Please choose \"{CUSTOM_ENDPOINT_OPTION}\" to provide your own \
base URL and client ID."
)
})?;
(region, base_url, client_id, None)
}
};
let label = if interactive && !quick {
Text::new("Label (e.g. 'prod'):")
.prompt_skippable()?
.filter(|s| !s.is_empty())
} else {
None
};
keyring_store::delete_profile(name);
println!();
let login = oauth::LoginOptions {
signup,
..oauth::LoginOptions::default()
};
let tokens = oauth::browser_login(&base_url, &client_id, login).await?;
println!("Login successful!");
let credential_storage = if interactive {
let help_message =
credential_storage_help_message("stores tokens in the profile config (0600 perms).");
select_credential_storage("Where should OAuth tokens be stored?", &help_message)?
} else {
CredentialStorage::File
};
let oauth_base_url_for_profile = if is_custom { Some(base_url) } else { None };
let (credential_storage, oauth_tokens, storage_desc) = match credential_storage {
CredentialStorage::OsStore => os_store_or_file_fallback(
name,
oauth::store_tokens_keyring(name, &tokens),
oauth::tokens_to_stored(&tokens),
"OS credential store (OAuth tokens)",
"profile file (OAuth tokens)",
),
CredentialStorage::File => (
CredentialStorage::File,
Some(oauth::tokens_to_stored(&tokens)),
"profile file (OAuth tokens)",
),
};
let profile = Profile {
auth: AuthKind::OAuth,
credential_storage,
api_key: None,
region,
label,
oauth_client_id: oauth_client_id_for_profile,
oauth_base_url: oauth_base_url_for_profile,
oauth_tokens,
default_output_format: None,
default_tier: None,
console_url: None,
cached_console_url: None,
cached_console_url_at: None,
cached_team_id: None,
cached_team_name: None,
};
Ok((profile, storage_desc))
}
fn configure_api_key(
name: &str,
api_key: Option<String>,
region_choice: Option<RegionChoice>,
quick: bool,
) -> Result<(Profile, &'static str)> {
let api_key = match api_key {
Some(key) => key,
None => {
println!(
"The API key must be a Team Key or a Personal Key.\n \
• Team Key: Data Flow → API Keys → Team Keys\n \
• Personal Key: User menu (top-right) → Personal Keys\n\
Send-Your-Data / ingress keys will NOT work for querying."
);
Password::new("Coralogix API key (Team Key or Personal Key):")
.with_display_mode(PasswordDisplayMode::Masked)
.without_confirmation()
.with_validator(|input: &str| {
use inquire::validator::Validation;
if input.trim().is_empty() {
Ok(Validation::Invalid("API key cannot be empty".into()))
} else {
Ok(Validation::Valid)
}
})
.prompt()?
}
};
let region_choice = match region_choice {
Some(choice) => choice,
None => select_region_interactive()?,
};
let region = match region_choice {
RegionChoice::Known(region) => region,
RegionChoice::Custom { base_url } => Region::Custom(base_url),
};
let label = if quick {
None
} else {
Text::new("Label (e.g. 'prod'):")
.prompt_skippable()?
.filter(|s| !s.is_empty())
};
let help_message =
credential_storage_help_message("stores credentials in the profile config (0600 perms).");
let credential_storage =
select_credential_storage("Where should API keys be stored?", &help_message)?;
let (credential_storage, api_key, storage_desc) = match credential_storage {
CredentialStorage::OsStore => os_store_or_file_fallback(
name,
keyring_store::store_secret(name, "api_key", &api_key),
api_key,
"OS credential store",
"profile file",
),
CredentialStorage::File => {
keyring_store::delete_profile(name);
(CredentialStorage::File, Some(api_key), "profile file")
}
};
let profile = Profile {
auth: AuthKind::ApiKey,
credential_storage,
api_key,
region,
label,
oauth_client_id: None,
oauth_base_url: None,
oauth_tokens: None,
default_output_format: None,
default_tier: None,
console_url: None,
cached_console_url: None,
cached_console_url_at: None,
cached_team_id: None,
cached_team_name: None,
};
Ok((profile, storage_desc))
}
#[cfg(test)]
mod tests {
use super::*;
use clap::ValueEnum;
#[test]
fn every_output_format_is_selectable_in_picker() {
for variant in OutputFormat::value_variants() {
assert!(
OUTPUT_FORMATS.contains(&variant.as_str()),
"OUTPUT_FORMATS is missing canonical variant {:?}; picker cursor would \
not preselect it",
variant.as_str(),
);
}
}
#[test]
fn credential_storage_default_is_os_store_when_keyring_is_available() {
let (_, storage) = CREDENTIAL_STORAGE_OPTIONS[credential_storage_starting_cursor()];
if cfg!(all(target_os = "linux", target_env = "musl")) {
assert_eq!(storage, CredentialStorage::File);
assert_eq!(CREDENTIAL_STORAGE_OPTIONS.len(), 1);
} else {
assert_eq!(storage, CredentialStorage::OsStore);
}
}
#[test]
fn os_store_fallback_keeps_os_store_on_success() {
let (storage, payload, desc) = os_store_or_file_fallback(
"cx_test_os_store_ok",
Ok(()),
"secret",
"OS credential store",
"profile file",
);
assert_eq!(storage, CredentialStorage::OsStore);
assert_eq!(payload, None);
assert_eq!(desc, "OS credential store");
}
#[test]
fn os_store_fallback_uses_file_when_keyring_unavailable() {
let (storage, payload, desc) = os_store_or_file_fallback(
"cx_test_os_store_fallback",
Err(anyhow::anyhow!("no secret service")),
"secret",
"OS credential store",
"profile file",
);
assert_eq!(storage, CredentialStorage::File);
assert_eq!(payload.as_deref(), Some("secret"));
assert_eq!(desc, "profile file");
}
#[test]
fn region_default_cursor_points_at_eu2() {
assert_eq!(
PICKER_REGIONS[REGION_DEFAULT_CURSOR],
Region::Eu2,
"REGION_DEFAULT_CURSOR must point at eu2 in PICKER_REGIONS"
);
}
#[test]
fn region_flag_parses_known_shortname() {
let region = parse_region_flag("eu2").expect("eu2 is a known region");
assert_eq!(region, Region::Eu2);
}
#[test]
fn region_flag_is_case_insensitive() {
let region = parse_region_flag("EU2").expect("region flag should be case-insensitive");
assert_eq!(region, Region::Eu2);
}
#[test]
fn region_flag_rejects_unknown_shortname() {
let err = parse_region_flag("eu22").expect_err("eu22 is not a region");
assert!(
err.to_string().contains("unknown region 'eu22'"),
"error should name the bad value, got: {err}"
);
}
#[test]
fn no_region_flags_resolve_to_none() {
assert!(resolve_region_flags(None, None)
.expect("no flags is valid")
.is_none());
}
#[test]
fn url_flag_derives_known_region() {
let choice = resolve_region_flags(Some("https://myteam.app.eu2.coralogix.com"), None)
.expect("recognizable URL")
.expect("URL flag should produce a choice");
assert!(
matches!(choice, RegionChoice::Known(Region::Eu2)),
"app URL should derive eu2"
);
}
#[test]
fn url_flag_unresolved_becomes_custom_endpoint() {
let choice = resolve_region_flags(Some("https://api.myenv.internal/"), None)
.expect("host-bearing URL")
.expect("URL flag should produce a choice");
match choice {
RegionChoice::Custom { base_url } => assert_eq!(base_url, "https://api.myenv.internal"),
RegionChoice::Known(_) => panic!("unknown host must not resolve to a known region"),
}
}
#[test]
fn url_flag_without_host_is_rejected() {
let err = resolve_region_flags(Some(""), None).expect_err("empty URL has no host");
assert!(
err.to_string().contains("not a valid URL"),
"error should say the URL is invalid, got: {err}"
);
}
#[test]
fn url_flag_schemeless_host_is_stored_verbatim() {
let choice = resolve_region_flags(Some("api.myenv.internal"), None)
.expect("host-bearing input")
.expect("URL flag should produce a choice");
match choice {
RegionChoice::Custom { base_url } => {
assert_eq!(base_url, "api.myenv.internal")
}
RegionChoice::Known(region) => {
panic!("unknown host must not resolve to a known region {region}")
}
}
}
#[test]
fn url_flag_unlisted_region_becomes_custom_endpoint() {
let choice = resolve_region_flags(Some("https://team.app.stg1.coralogix.net"), None)
.expect("host-bearing URL")
.expect("URL flag should produce a choice");
match choice {
RegionChoice::Custom { base_url } => {
assert_eq!(base_url, "https://team.app.stg1.coralogix.net")
}
RegionChoice::Known(region) => {
panic!("expected custom endpoint, got known region {region}")
}
}
}
#[test]
fn every_region_option_is_short_name_and_url_template() {
for region in PICKER_REGIONS {
let template = region
.app_url_template()
.expect("picker region must have an app URL template");
assert_eq!(
region_option_label(region),
format!("({region}) {template}")
);
assert!(
!matches!(region, Region::Custom(_)),
"PICKER_REGIONS entry {region} is not a known region"
);
}
}
#[test]
fn region_picker_ends_with_custom_endpoint() {
let options = region_picker_options();
assert_eq!(options[options.len() - 1], CUSTOM_ENDPOINT_OPTION);
assert_eq!(options.len(), PICKER_REGIONS.len() + 1);
}
#[test]
fn custom_base_url_adds_scheme_when_missing() {
assert_eq!(
custom_base_url_from("api.myenv.example.com").as_deref(),
Some("https://api.myenv.example.com")
);
}
#[test]
fn custom_base_url_preserves_scheme_and_strips_slash() {
assert_eq!(
custom_base_url_from("http://api.myenv.example.com/").as_deref(),
Some("http://api.myenv.example.com")
);
}
#[test]
fn custom_base_url_rejects_hostless_input() {
assert_eq!(custom_base_url_from(""), None);
assert_eq!(custom_base_url_from(" "), None);
}
#[test]
fn paste_url_for_listed_region_stays_known() {
match resolve_url_choice("https://team.app.eu2.coralogix.com").unwrap() {
RegionChoice::Known(region) => assert_eq!(region.to_string(), "eu2"),
RegionChoice::Custom { base_url } => {
panic!("expected known region eu2, got custom endpoint {base_url}")
}
}
}
#[test]
fn paste_url_for_unlisted_region_becomes_custom_endpoint() {
match resolve_url_choice("https://team.app.stg1.coralogix.net").unwrap() {
RegionChoice::Custom { base_url } => {
assert_eq!(base_url, "https://team.app.stg1.coralogix.net")
}
RegionChoice::Known(region) => {
panic!("expected custom endpoint, got known region {region}")
}
}
}
}