use std::path::Path;
use super::{ask, line, says};
use crate::context::Context;
use crate::failure::{Failure, Refusal};
pub const CLI: &str = "oci";
pub const CONFIG_FILE_VAR: &str = "OCI_CLI_CONFIG_FILE";
#[must_use]
pub fn refusal(said: &str) -> Refusal {
if isothrum_runner::sign_in_expired(said) || says(said, &["NotAuthenticated", "config", "private key", "401"]) {
Refusal::CredentialsExpired
} else if says(said, &["NotAuthorizedOrNotFound"]) {
Refusal::Denied
} else {
Refusal::Other
}
}
pub async fn signed_in(cx: &Context) -> Result<(), Failure> {
ask(cx, CLI, &["iam", "region", "list", "--output", "json"], refusal).await.map(drop)
}
pub async fn compartment_name(cx: &Context, id: &str) -> Result<String, Failure> {
ask(
cx,
CLI,
&["iam", "compartment", "get", "--compartment-id", id, "--query", "data.name", "--raw-output"],
refusal,
)
.await
.map(|out| line(&out))
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Config {
pub tenancy: String,
pub region: String,
}
#[must_use]
pub fn config(path: &Path) -> Option<Config> {
std::fs::read_to_string(path).ok().map(|text| parse_config(&text))
}
#[must_use]
pub fn parse_config(text: &str) -> Config {
let mut config = Config::default();
let mut in_default = false;
for line in text.lines() {
let l = line.trim();
if l.starts_with('[') {
in_default = l.eq_ignore_ascii_case("[DEFAULT]");
continue;
}
if !in_default {
continue;
}
if let Some((k, v)) = l.split_once('=') {
match k.trim() {
"tenancy" => v.trim().clone_into(&mut config.tenancy),
"region" => v.trim().clone_into(&mut config.region),
_ => {}
}
}
}
config
}
#[cfg(test)]
mod tests;