use std::fmt::Display;
use anyhow::bail;
use is_terminal::IsTerminal;
use crate::{interact_or, util::prompt::prompt_options};
use super::{queries::project::ProjectProjectEnvironmentsEdgesNode, *};
#[derive(Parser)]
pub struct Args {
environment: Option<String>,
}
pub async fn command(args: Args, _json: bool) -> Result<()> {
let mut configs = Configs::new()?;
let client = GQLClient::new_authorized(&configs)?;
let linked_project = configs.get_linked_project().await?;
let vars = queries::project::Variables {
id: linked_project.project.to_owned(),
};
let res = post_graphql::<queries::Project, _>(&client, configs.get_backboard(), vars).await?;
let body = res
.data
.context("Failed to get environments (query project)")?;
let environments: Vec<_> = body
.project
.environments
.edges
.iter()
.map(|env| Environment(&env.node))
.collect();
let environment = match args.environment {
Some(environment) => {
let environment = environments
.iter()
.find(|env| env.0.id == environment || env.0.name == environment)
.context("Environment not found")?;
environment.clone()
}
None => {
interact_or!("Environment must be specified when not running in a terminal");
let environment = if environments.len() == 1 {
match environments.first() {
Some(environment) => environment.clone(),
None => bail!("Project has no environments"),
}
} else {
prompt_options("Select an environment", environments)?
};
environment
}
};
configs.link_project(
linked_project.project.clone(),
linked_project.name.clone(),
environment.0.id.clone(),
Some(environment.0.name.clone()),
)?;
configs.write()?;
Ok(())
}
#[derive(Debug, Clone)]
struct Environment<'a>(&'a ProjectProjectEnvironmentsEdgesNode);
impl<'a> Display for Environment<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0.name)
}
}