Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove references to plugins #487

Merged
merged 21 commits into from
Apr 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -69,3 +69,4 @@ ctrlc = "3.2.5"
which = "4.4.0"
thiserror = "1.0.40"
winapi = {version="0.3.9", features = ["minwindef", "tlhelp32", "processthreadsapi", "handleapi", "winerror"]}
strum = { version = "0.26.1", features = ["derive"] }
174 changes: 105 additions & 69 deletions src/commands/add.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,22 @@
use std::time::Duration;

use anyhow::bail;
use clap::ValueEnum;
use is_terminal::IsTerminal;
use std::collections::BTreeMap;
use std::time::Duration;
use strum::IntoEnumIterator;

use crate::{
consts::{PLUGINS, TICK_STRING},
controllers::project::get_project,
consts::TICK_STRING, controllers::database::DatabaseType, mutations::TemplateVolume,
util::prompt::prompt_multi_options,
};

use super::{queries::project::PluginType, *};
use super::*;

/// Add a new plugin to your project
/// Provision a database into your project
#[derive(Parser)]
pub struct Args {
/// The name of the plugin to add
/// The name of the database to add
#[arg(short, long, value_enum)]
plugin: Vec<ClapPluginEnum>,
database: Vec<DatabaseType>,
}

pub async fn command(args: Args, _json: bool) -> Result<()> {
Expand All @@ -26,86 +25,123 @@ pub async fn command(args: Args, _json: bool) -> Result<()> {
let client = GQLClient::new_authorized(&configs)?;
let linked_project = configs.get_linked_project().await?;

let project = get_project(&client, &configs, linked_project.project.clone()).await?;

let project_plugins: Vec<_> = project
.plugins
.edges
.iter()
.map(|p| p.node.name.to_string())
.collect();

let filtered_plugins: Vec<_> = PLUGINS
.iter()
.map(|p| p.to_string())
.filter(|plugin| !project_plugins.contains(&plugin.to_string()))
.collect();

let selected = if !std::io::stdout().is_terminal() || !args.plugin.is_empty() {
if args.plugin.is_empty() {
bail!("No plugins specified");
let databases = if args.database.is_empty() {
if !std::io::stdout().is_terminal() {
bail!("No database specified");
}
let filtered: Vec<_> = args
.plugin
.iter()
.map(clap_plugin_enum_to_plugin_enum)
.map(|p| p.to_string())
.filter(|plugin| !project_plugins.contains(&plugin.to_string()))
.collect();

if filtered.is_empty() {
bail!("Plugins already exist");
}

filtered
prompt_multi_options("Select databases to add", DatabaseType::iter().collect())?
} else {
prompt_multi_options("Select plugins to add", filtered_plugins)?
args.database
};

if selected.is_empty() {
bail!("No plugins selected");
if databases.is_empty() {
bail!("No database selected");
}

for plugin in selected {
let vars = mutations::plugin_create::Variables {
project_id: linked_project.project.clone(),
name: plugin.to_lowercase(),
};
for db in databases {
if std::io::stdout().is_terminal() {
let spinner = indicatif::ProgressBar::new_spinner()
.with_style(
indicatif::ProgressStyle::default_spinner()
.tick_chars(TICK_STRING)
.template("{spinner:.green} {msg}")?,
)
.with_message(format!("Creating {plugin}..."));
.with_message(format!("Creating {db}..."));
spinner.enable_steady_tick(Duration::from_millis(100));
post_graphql::<mutations::PluginCreate, _>(&client, configs.get_backboard(), vars)
.await?;
spinner.finish_with_message(format!("Created {plugin}"));
fetch_and_create(&client, &configs, db.clone(), &linked_project).await?;
spinner.finish_with_message(format!("Created {db}"));
} else {
println!("Creating {}...", plugin);
post_graphql::<mutations::PluginCreate, _>(&client, configs.get_backboard(), vars)
.await?;
println!("Creating {}...", db);
fetch_and_create(&client, &configs, db, &linked_project).await?;
}
}

Ok(())
}
/// fetch database details via `TemplateDetail`
/// create database via `TemplateDeploy`
async fn fetch_and_create(
client: &reqwest::Client,
configs: &Configs,
db: DatabaseType,
linked_project: &LinkedProject,
) -> Result<(), anyhow::Error> {
let details = post_graphql::<queries::TemplateDetail, _>(
client,
configs.get_backboard(),
queries::template_detail::Variables { code: db.to_slug() },
)
.await?;

let services: Vec<mutations::template_deploy::TemplateDeployService> = details
.template
.services
.edges
.iter()
.map(|s| {
let s_var = s
.node
.config
.variables
.iter()
.map(|variable| {
(
variable.name.clone(),
variable.default_value.clone().unwrap(),
)
})
.collect::<BTreeMap<String, String>>();

let s_vol = s
.node
.config
.volumes
.clone()
.map(|volumes| {
volumes
.into_iter()
.map(|volume| TemplateVolume {
mount_path: volume.mount_path.clone(),
name: volume.name.clone(),
})
.collect::<Vec<TemplateVolume>>()
})
.unwrap_or_default();

mutations::template_deploy::TemplateDeployService {
commit: None,
has_domain: Some(s.node.config.domains.iter().any(|d| d.has_service_domain)),
healthcheck_path: None,
id: Some(s.node.id.clone()),
is_private: None,
name: Some(s.node.config.name.clone()),
owner: None,
root_directory: None,
service_icon: s.node.config.icon.clone(),
service_name: s.node.config.name.clone(),
start_command: s
.node
.config
.deploy_config
.as_ref()
.and_then(|deploy_config| deploy_config.start_command.clone()),
tcp_proxy_application_port: s.node.config.tcp_proxies.as_ref().and_then(
|tcp_proxies| tcp_proxies.first().map(|first| first.application_port),
),
template: s.node.config.source.image.clone(),
variables: (!s_var.is_empty()).then_some(s_var),
volumes: (!s_vol.is_empty()).then_some(s_vol),
}
})
.collect();

#[derive(ValueEnum, Clone, Debug)]
enum ClapPluginEnum {
Postgresql,
Mysql,
Redis,
Mongodb,
}
let vars = mutations::template_deploy::Variables {
project_id: linked_project.project.clone(),
environment_id: linked_project.environment.clone(),
services,
template_code: db.to_slug(),
};

fn clap_plugin_enum_to_plugin_enum(clap_plugin_enum: &ClapPluginEnum) -> PluginType {
match clap_plugin_enum {
ClapPluginEnum::Postgresql => PluginType::postgresql,
ClapPluginEnum::Mysql => PluginType::mysql,
ClapPluginEnum::Redis => PluginType::redis,
ClapPluginEnum::Mongodb => PluginType::mongodb,
}
post_graphql::<mutations::TemplateDeploy, _>(client, configs.get_backboard(), vars).await?;
Ok(())
}
Loading
Loading