use std::time::Duration;
use isothrum_runner::ProcessSpec;
use serde_json::Value;
use super::{ask, json_list, line, run, says};
use crate::context::Context;
use crate::failure::{Failure, Refusal};
pub const CLI: &str = "gcloud";
#[must_use]
pub fn refusal(said: &str) -> Refusal {
if isothrum_runner::sign_in_expired(said) || says(said, &["gcloud auth", "credentials"]) {
Refusal::CredentialsExpired
} else if names_status(said, "NOT_FOUND") {
Refusal::NotFound
} else if names_status(said, "SERVICE_DISABLED") || says(said, &["has not been used in project", "it is disabled"]) {
Refusal::NotEnabled
} else if says(said, &["does not have permission", "PERMISSION_DENIED", "Permission denied", "was not found"]) {
Refusal::Denied
} else if says(said, &["quota", "FAILED_PRECONDITION", "Precondition"]) {
Refusal::QuotaExceeded
} else {
Refusal::Other
}
}
fn names_status(said: &str, status: &str) -> bool {
said.split(|c: char| !(c.is_ascii_uppercase() || c == '_')).any(|word| word == status)
}
pub async fn active_account(cx: &Context) -> Result<Option<String>, Failure> {
let out = ask(cx, CLI, &["auth", "list", "--filter=status:ACTIVE", "--format=value(account)"], refusal).await?;
Ok(Some(line(&out)).filter(|a| !a.is_empty()))
}
pub async fn access_token(cx: &Context) -> Result<(), Failure> {
ask(cx, CLI, &["auth", "print-access-token", "--quiet"], refusal).await.map(drop)
}
pub async fn signed_in(cx: &Context) -> Result<(), Failure> {
ask(cx, CLI, &["auth", "application-default", "print-access-token"], refusal).await.map(drop)
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct BillingAccount {
pub id: String,
pub name: String,
pub open: bool,
}
pub async fn billing_accounts(cx: &Context) -> Result<Vec<BillingAccount>, Failure> {
let out = ask(cx, CLI, &["billing", "accounts", "list", "--format", "json"], refusal).await?;
Ok(read_billing_accounts(&json_list(CLI, &out)?))
}
fn read_billing_accounts(list: &[Value]) -> Vec<BillingAccount> {
list.iter()
.map(|v| BillingAccount {
id: id(v, "billingAccounts/"),
name: v["displayName"].as_str().unwrap_or_default().to_owned(),
open: v["open"].as_bool().unwrap_or(false),
})
.filter(|b| !b.id.is_empty())
.collect()
}
fn id(v: &Value, prefix: &str) -> String {
v["name"].as_str().unwrap_or_default().trim_start_matches(prefix).to_owned()
}
pub async fn billing_account_name(cx: &Context, id: &str) -> Result<String, Failure> {
ask(cx, CLI, &["billing", "accounts", "describe", id, "--format", "value(displayName)"], refusal)
.await
.map(|out| line(&out))
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Organization {
pub id: String,
pub name: String,
}
pub async fn organizations(cx: &Context) -> Result<Vec<Organization>, Failure> {
let out = ask(cx, CLI, &["organizations", "list", "--format", "json"], refusal).await?;
Ok(read_organizations(&json_list(CLI, &out)?))
}
fn read_organizations(list: &[Value]) -> Vec<Organization> {
list.iter()
.map(|v| Organization {
id: id(v, "organizations/"),
name: v["displayName"].as_str().unwrap_or_default().to_owned(),
})
.filter(|o| !o.id.is_empty())
.collect()
}
pub const PROJECT_TIMEOUT: Duration = Duration::from_secs(5 * 60);
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ProjectState {
Active,
Gone,
Other(String),
}
pub async fn project_state(cx: &Context, id: &str) -> Result<ProjectState, Failure> {
match ask(cx, CLI, &["projects", "describe", id, "--format", "value(lifecycleState)"], refusal).await {
Ok(state) => Ok(match state.trim() {
"ACTIVE" => ProjectState::Active,
"DELETE_REQUESTED" | "DELETE_IN_PROGRESS" => ProjectState::Gone,
other => ProjectState::Other(other.to_owned()),
}),
Err(Failure::Refused {
refusal: Refusal::NotFound, ..
}) => Ok(ProjectState::Gone),
Err(other) => Err(other),
}
}
async fn change(cx: &Context, args: &[&str]) -> Result<(), Failure> {
run(cx, PROJECT_TIMEOUT, &ProcessSpec::new(CLI, args.iter().copied()), refusal).await.map(drop)
}
#[must_use]
pub fn create_args(id: &str, name: &str, organization: Option<&str>) -> Vec<String> {
let mut args: Vec<String> = ["projects", "create", id, "--name", name].map(str::to_owned).to_vec();
args.extend(organization.map(|o| format!("--organization={o}")));
args
}
pub async fn create_project(cx: &Context, id: &str, name: &str, organization: Option<&str>) -> Result<(), Failure> {
let args = create_args(id, name, organization);
change(cx, &args.iter().map(String::as_str).collect::<Vec<_>>()).await
}
pub async fn link_billing(cx: &Context, id: &str, billing: &str) -> Result<(), Failure> {
change(cx, &["billing", "projects", "link", id, "--billing-account", billing]).await
}
pub async fn enable_service(cx: &Context, id: &str, service: &str) -> Result<(), Failure> {
change(cx, &["services", "enable", service, "--project", id]).await
}
pub async fn delete_project(cx: &Context, id: &str) -> Result<(), Failure> {
change(cx, &["projects", "delete", id, "--quiet"]).await
}
#[cfg(test)]
mod tests;