pub mod assets;
pub mod database;
pub mod functions;
pub mod secrets;
use crate::cmds::accounts::get_current_account;
use crate::cmds::logs::{Logs, Sync, print_logs_metadata_table};
use crate::{HostCallFlags, deploy_app_local};
use anyhow::bail;
use assets::Assets;
use clap::Subcommand;
use clap::builder::PossibleValue;
use clio::ClioPath;
use database::Database;
use functions::Functions;
use ordinary_build::traverse;
use ordinary_config::OrdinaryAppConfig;
use ordinaryd::{AppHost, GlobalArgs};
use saferlmdb::Environment;
use secrets::Secrets;
use std::env::home_dir;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tracing::instrument;
#[derive(Subcommand, Debug)]
pub enum App {
#[clap(visible_aliases(["create", "init"]))]
New {
domain: String,
#[arg(long)]
dir: Option<PathBuf>,
},
Build {
#[arg(short, long, default_value_t = false)]
force: bool,
#[arg(short, long, value_parser = clap::value_parser!(ClioPath).exists().is_dir(), default_value = ".")]
project: ClioPath,
},
#[clap(visible_aliases(["run", "preview"]))]
Start {
#[command(flatten)]
app_host: AppHost,
#[command(flatten)]
global_args: GlobalArgs,
#[arg(long)]
host: Option<String>,
#[arg(short, long, default_value_t = false)]
disable_defaults: bool,
},
Publish {
#[command(flatten)]
host: HostCallFlags,
#[arg(long, default_value_t = false)]
skip_limits_check: bool,
#[arg(long, default_value_t = false)]
no_seed: bool,
#[arg(short, long, value_parser = clap::value_parser!(ClioPath).exists().is_dir(), default_value = ".")]
project: ClioPath,
},
Deploy {
#[command(flatten)]
host: HostCallFlags,
#[arg(short, long, default_value_t = false)]
json_to_stdout: bool,
#[arg(long, default_value_t = false)]
skip_limits_check: bool,
#[arg(short, long, value_parser = clap::value_parser!(ClioPath).exists().is_dir(), default_value = ".")]
project: ClioPath,
#[arg(short, long, default_value_t = false)]
local: bool,
},
Kill {
#[command(flatten)]
host: HostCallFlags,
#[arg(short, long, value_parser = clap::value_parser!(ClioPath).exists().is_dir(), default_value = ".")]
project: ClioPath,
},
Restart {
#[command(flatten)]
host: HostCallFlags,
#[arg(short, long, default_value_t = false)]
json_to_stdout: bool,
#[arg(short, long, value_parser = clap::value_parser!(ClioPath).exists().is_dir(), default_value = ".")]
project: ClioPath,
},
Erase {
#[command(flatten)]
host: HostCallFlags,
#[arg(short, long, value_parser = clap::value_parser!(ClioPath).exists().is_dir(), default_value = ".")]
project: ClioPath,
},
Logs {
#[command(flatten)]
host: HostCallFlags,
#[command(subcommand)]
logs: Logs,
#[arg(short, long, value_parser = clap::value_parser!(ClioPath).exists().is_dir(), default_value = ".")]
project: ClioPath,
},
Assets {
#[command(subcommand)]
assets: Assets,
#[arg(short, long, value_parser = clap::value_parser!(ClioPath).exists().is_dir(), default_value = ".")]
project: ClioPath,
},
#[clap(visible_aliases(["account", "accts", "acct"]))]
Accounts {
#[command(subcommand)]
accounts: Accounts,
#[arg(short, long, value_parser = clap::value_parser!(ClioPath).exists().is_dir(), default_value = ".")]
project: ClioPath,
},
#[clap(visible_aliases(["fns", "fn", "function"]))]
Functions {
#[command(subcommand)]
functions: Functions,
#[arg(short, long, value_parser = clap::value_parser!(ClioPath).exists().is_dir(), default_value = ".")]
project: ClioPath,
},
#[clap(visible_aliases(["db"]))]
Database {
#[command(subcommand)]
database: Database,
#[arg(short, long, value_parser = clap::value_parser!(ClioPath).exists().is_dir(), default_value = ".")]
project: ClioPath,
},
Secrets {
#[command(subcommand)]
secrets: Secrets,
#[arg(short, long, value_parser = clap::value_parser!(ClioPath).exists().is_dir(), default_value = ".")]
project: ClioPath,
},
Config {
#[command(subcommand)]
config: Config,
#[command(flatten)]
host: HostCallFlags,
#[arg(short, long, value_parser = clap::value_parser!(ClioPath).exists().is_dir(), default_value = ".")]
project: ClioPath,
},
Routes {
#[arg(short, long, value_parser = clap::value_parser!(ClioPath).exists().is_dir(), default_value = ".")]
project: ClioPath,
},
}
#[derive(Subcommand, Debug)]
pub enum Accounts {
#[clap(visible_aliases(["ls"]))]
List {
#[command(flatten)]
host: HostCallFlags,
},
}
#[derive(Subcommand, Debug)]
pub enum Config {
View {
#[arg(short, long, default_value = "build")]
r#for: For,
},
Validate {
#[arg(short, long, default_value = "build")]
r#for: For,
},
}
#[derive(Clone, Debug, PartialOrd, PartialEq)]
pub enum For {
Build,
Deploy,
}
impl clap::ValueEnum for For {
fn value_variants<'a>() -> &'a [Self] {
&[Self::Build, Self::Deploy]
}
fn to_possible_value(&self) -> Option<PossibleValue> {
match self {
Self::Build => Some(PossibleValue::new("build")),
Self::Deploy => Some(PossibleValue::new("deploy")),
}
}
}
impl App {
#[expect(clippy::missing_panics_doc, clippy::too_many_lines)]
#[instrument(skip_all, name = "app")]
pub async fn handle(&self, env: &Arc<Environment>) -> anyhow::Result<()> {
match self {
Self::New { dir, domain } => ordinary_modify::app::new(dir.as_deref(), domain)?,
Self::Build { force, project } => {
let project = project.to_str().expect("failed to get string from project");
let env_file = Path::new(project).join(".env");
if env_file.exists() {
dotenvy::from_path(env_file)?;
}
let env_file = Path::new(project).join(".env");
if env_file.exists() {
dotenvy::from_path(env_file)?;
}
ordinary_build::app(project, *force)?;
}
Self::Publish {
no_seed,
skip_limits_check,
project,
host,
} => {
let project = project.to_str().expect("failed to get string from project");
let env_file = Path::new(project).join(".env");
if env_file.exists() {
dotenvy::from_path(env_file)?;
}
ordinary_build::app(project, true)?;
let account = get_current_account()?;
let client = host.client(&account, env)?;
let config = OrdinaryAppConfig::get(project, Some(client.host()), true)?;
client.app_deploy(project, *skip_limits_check).await?;
if !no_seed {
client.database_items_seed(project).await?;
}
if config.assets.is_some() {
client.assets_write_all(project).await?;
}
if config.functions.is_some() {
client.functions_upload_all(project).await?;
}
}
Self::Deploy {
json_to_stdout,
skip_limits_check,
project,
host,
local,
} => {
let project = project.to_str().expect("failed to get string from project");
if *local {
let data_dir = match home_dir() {
Some(home) => home.join(".ordinary"),
None => bail!("no home dir"),
};
let config =
OrdinaryAppConfig::get(project, host.host_domain.as_deref(), true)?;
deploy_app_local(host.host_domain.as_deref(), data_dir, project, &config)?;
tracing::info!("app deployed");
} else {
let account = get_current_account()?;
let client = host.client(&account, env)?;
let env_file = Path::new(project).join(".env");
if env_file.exists() {
dotenvy::from_path(env_file)?;
}
let ports_res = client.app_deploy(project, *skip_limits_check).await?;
tracing::info!("app deployed");
if *json_to_stdout {
println!("{}", serde_json::to_string(&ports_res)?);
}
}
}
Self::Kill { project, host } => {
let project = project.to_str().expect("failed to get string from project");
let account = get_current_account()?;
let client = host.client(&account, env)?;
client.app_kill(project).await?;
}
Self::Restart {
json_to_stdout,
project,
host,
} => {
let project = project.to_str().expect("failed to get string from project");
let account = get_current_account()?;
let client = host.client(&account, env)?;
let ports_res = client.app_restart(project).await?;
tracing::info!("app restarted");
if *json_to_stdout {
println!("{}", serde_json::to_string(&ports_res)?);
}
}
Self::Erase { project, host } => {
let project = project.to_str().expect("failed to get string from project");
let account = get_current_account()?;
let client = host.client(&account, env)?;
client.app_erase(project).await?;
}
Self::Logs {
logs,
project,
host,
} => {
let project = project.to_str().expect("failed to get string from project");
let account = get_current_account()?;
let client = host.client(&account, env)?;
let host = client.host();
match logs {
Logs::Query {
query,
json_columns,
sync,
} => {
if sync == &Some(true) {
client
.app_logs_sync(project, None, None, Some(host))
.await?;
}
let res = client.app_logs_query(
project,
query,
json_columns.as_ref(),
Some(host),
)?;
print!("{res}");
}
Logs::List => client.app_logs_file_list(project, Some(host))?,
Logs::Read { name } => {
if let Some(name) = name {
client.app_logs_file_read(project, name, Some(host))?;
} else {
client.app_logs_file_read_all(project, Some(host))?;
}
}
Logs::Sync { sync } => match sync {
Sync::Info => {
let remote_metadata =
client.app_logs_remote_metadata(project, Some(host)).await?;
let local_metadata =
client.app_logs_local_metadata(project, Some(host))?;
print_logs_metadata_table(remote_metadata, local_metadata);
}
Sync::All { force } => {
client
.app_logs_sync(project, *force, None, Some(host))
.await?;
}
Sync::File { name } => {
client
.app_logs_sync(project, None, Some(name), Some(host))
.await?;
}
},
}
}
Self::Accounts { accounts, project } => {
let project = project.to_str().expect("failed to get string from project");
match accounts {
Accounts::List { host } => {
let account = get_current_account()?;
let client = host.client(&account, env)?;
let res = client.app_accounts_list(project).await?;
print!("{res}");
}
}
}
Self::Routes { project } => {
let project = project.to_str().expect("failed to get string from project");
let config = OrdinaryAppConfig::get(project, None, true)?;
println!("ROUTES\n");
if let Some(assets) = config.assets {
let Some(assets_dir_path) = &assets.dir_path else {
bail!("assets.dir_path cannot be unset");
};
println!("assets:");
let base_route = assets.base_route.as_str();
let assets_dir = Path::new(project).join(assets_dir_path);
traverse(&assets_dir, &|entry| {
let path = entry.path();
let path = path.strip_prefix(&assets_dir)?;
if base_route == "/" {
println!("- GET /{}", path.display());
} else {
println!("- GET {base_route}/{}", path.display());
}
Ok(())
})?;
println!();
}
if let Some(http_config) = &config.http {
if let Some(routes) = &http_config.routes {
println!("functions:");
for http_route in routes {
println!("- {} {}", http_route.method, http_route.path);
}
println!();
}
if let Some(redirects) = &http_config.redirects
&& let Some(redirects) = &redirects.route
{
println!("redirects:");
for redirect in redirects {
println!(
"- {} {} [ {} -> {} ]",
redirect.method,
redirect.condition,
redirect.rule.0,
redirect.rule.1
);
}
println!();
}
if let Some(proxies) = &http_config.proxies {
println!("proxies:");
for proxy in proxies {
if let Some(path) = &proxy.path {
println!("- ANY {path} -> {}", proxy.target);
} else if let Some(domain) = &proxy.domain {
println!("- ANY http(s)://{domain}/{{*path}} -> {}", proxy.target);
}
}
println!();
}
}
}
Self::Assets { assets, project } => {
let project = project.to_str().expect("failed to get string from project");
assets.handle(project, env).await?;
}
Self::Functions { functions, project } => {
let project = project.to_str().expect("failed to get string from project");
functions.handle(project, env).await?;
}
Self::Database {
database: models,
project,
} => {
let project = project.to_str().expect("failed to get string from project");
models.handle(project, env).await?;
}
Self::Secrets { secrets, project } => {
let project = project.to_str().expect("failed to get string from project");
secrets.handle(project, env).await?;
}
Self::Config {
config,
project,
host,
} => {
let project = project.to_str().expect("failed to get string from project");
let account = get_current_account()?;
let client = host.client(&account, env)?;
let host = client.host();
let app_config = OrdinaryAppConfig::get(project, Some(host), true)?;
match config {
Config::View { r#for } => match r#for {
For::Build => {
println!("{}", serde_json::to_string_pretty(&app_config)?);
}
For::Deploy => {
println!("{}", serde_json::to_string_pretty(&app_config.for_send()?)?);
}
},
Config::Validate { r#for } => match r#for {
For::Build => {
app_config.validate(Some(host))?;
println!("valid");
}
For::Deploy => {
app_config.for_send()?.validate(Some(host))?;
println!("valid");
}
},
}
}
Self::Start { .. } => unreachable!("handled in main.rs"),
}
Ok(())
}
}