1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
use std::{
ffi::OsString,
fs::create_dir_all,
io::{self, ErrorKind},
path::PathBuf,
};
use anyhow::{bail, Context};
use cargo_metadata::MetadataCommand;
use clap::{
builder::{OsStringValueParser, PossibleValue, TypedValueParser},
Parser, ValueEnum,
};
use clap_complete::Shell;
use shuttle_common::constants::DEFAULT_IDLE_MINUTES;
use shuttle_common::resource;
use uuid::Uuid;
#[derive(Parser)]
#[command(
version,
// Cargo passes in the subcommand name to the invoked executable. Use a
// hidden, optional positional argument to deal with it.
arg(clap::Arg::new("dummy")
.value_parser([PossibleValue::new("shuttle")])
.required(false)
.hide(true))
)]
pub struct ShuttleArgs {
#[command(flatten)]
pub project_args: ProjectArgs,
/// Run this command against the API at the supplied URL
/// (allows targeting a custom deployed instance for this command only, mainly for development)
#[arg(long, env = "SHUTTLE_API")]
pub api_url: Option<String>,
#[command(subcommand)]
pub cmd: Command,
}
// Common args for subcommands that deal with projects.
#[derive(Parser, Debug)]
pub struct ProjectArgs {
/// Specify the working directory
#[arg(global = true, long, visible_alias = "wd", default_value = ".", value_parser = OsStringValueParser::new().try_map(parse_init_path))]
pub working_directory: PathBuf,
/// Specify the name of the project (overrides crate name)
#[arg(global = true, long)]
pub name: Option<String>,
}
impl ProjectArgs {
pub fn workspace_path(&self) -> anyhow::Result<PathBuf> {
// NOTE: If crates cache is missing this blocks for several seconds during download
let path = MetadataCommand::new()
.current_dir(&self.working_directory)
.exec()
.context("failed to get cargo metadata")?
.workspace_root
.into();
Ok(path)
}
pub fn project_name(&self) -> anyhow::Result<String> {
let workspace_path = self.workspace_path()?;
// NOTE: If crates cache is missing this blocks for several seconds during download
let meta = MetadataCommand::new()
.current_dir(&workspace_path)
.exec()
.context("failed to get cargo metadata")?;
let package_name = if let Some(root_package) = meta.root_package() {
root_package.name.clone()
} else {
workspace_path
.file_name()
.context("failed to get project name from workspace path")?
.to_os_string()
.into_string()
.expect("workspace directory name should be valid unicode")
};
Ok(package_name)
}
}
/// A cargo command for the Shuttle platform (https://www.shuttle.rs/)
///
/// See the CLI docs (https://docs.shuttle.rs/getting-started/shuttle-commands)
/// for more information.
#[derive(Parser)]
pub enum Command {
/// Create a new Shuttle project
Init(InitArgs),
/// Run a Shuttle service locally
Run(RunArgs),
/// Deploy a Shuttle service
Deploy(DeployArgs),
/// Manage deployments of a Shuttle service
#[command(subcommand)]
Deployment(DeploymentCommand),
/// View the status of a Shuttle service
Status,
/// Stop this Shuttle service
Stop,
/// View the logs of a deployment in this Shuttle service
Logs {
/// Deployment ID to get logs for. Defaults to currently running deployment
id: Option<Uuid>,
#[arg(short, long)]
/// View logs from the most recent deployment (which is not always the latest running one)
latest: bool,
#[arg(short, long)]
/// Follow log output
follow: bool,
#[arg(long)]
/// Don't display timestamps and log origin tags
raw: bool,
},
/// List or manage projects on Shuttle
#[command(subcommand)]
Project(ProjectCommand),
/// Manage resources of a Shuttle project
#[command(subcommand)]
Resource(ResourceCommand),
/// Remove cargo build artifacts in the Shuttle environment
Clean,
/// Login to the Shuttle platform
Login(LoginArgs),
/// Log out of the Shuttle platform
Logout(LogoutArgs),
/// Generate shell completions and man page
#[command(subcommand)]
Generate(GenerateCommand),
/// Open an issue on GitHub and provide feedback
Feedback,
}
#[derive(Parser)]
pub enum GenerateCommand {
/// Generate shell completions
Shell {
/// The shell to generate shell completion for
shell: Shell,
/// Output to a file (stdout by default)
#[arg(short, long)]
output: Option<PathBuf>,
},
/// Generate man page to the standard output
Manpage,
}
#[derive(Parser)]
pub enum DeploymentCommand {
/// List all the deployments for a service
List {
#[arg(long, default_value = "1")]
/// Which page to display
page: u32,
#[arg(long, default_value = "10")]
/// How many projects per page to display
limit: u32,
#[arg(long, default_value_t = false)]
/// Output table in `raw` format
raw: bool,
},
/// View status of a deployment
Status {
/// ID of deployment to get status for
id: Uuid,
},
}
#[derive(Parser)]
pub enum ResourceCommand {
/// List all the resources for a project
List {
#[arg(long, default_value_t = false)]
/// Output table in `raw` format
raw: bool,
#[arg(
long,
default_value_t = false,
help = "Show secrets from resources (e.g. a password in a connection string)"
)]
show_secrets: bool,
},
/// Delete a resource
Delete {
/// Type of the resource to delete.
/// Use the string in the 'Type' column as displayed in the `resource list` command.
/// For example, 'database::shared::postgres'.
resource_type: resource::Type,
#[command(flatten)]
confirmation: ConfirmationArgs,
},
}
#[derive(Parser)]
pub enum ProjectCommand {
/// Create an environment for this project on Shuttle
Start(ProjectStartArgs),
/// Check the status of this project's environment on Shuttle
Status {
#[arg(short, long)]
/// Follow status of project command
follow: bool,
},
/// Destroy this project's environment (container) on Shuttle
Stop,
/// Destroy and create an environment for this project on Shuttle
Restart(ProjectStartArgs),
/// List all projects belonging to the calling account
List {
#[arg(long, default_value = "1")]
/// Which page to display
page: u32,
#[arg(long, default_value = "10")]
/// How many projects per page to display
limit: u32,
#[arg(long, default_value_t = false)]
/// Output table in `raw` format
raw: bool,
},
/// Delete a project and all linked data
Delete(ConfirmationArgs),
}
#[derive(Parser, Debug)]
pub struct ConfirmationArgs {
#[arg(long, short, default_value_t = false)]
/// Skip confirmations and proceed
pub yes: bool,
}
#[derive(Parser, Debug)]
pub struct ProjectStartArgs {
#[arg(long, default_value_t = DEFAULT_IDLE_MINUTES)]
/// How long to wait before putting the project in an idle state due to inactivity.
/// 0 means the project will never idle
pub idle_minutes: u64,
}
#[derive(Parser, Clone, Debug, Default)]
pub struct LoginArgs {
/// API key for the Shuttle platform
#[arg(long)]
pub api_key: Option<String>,
}
#[derive(Parser, Clone, Debug)]
pub struct LogoutArgs {
/// Reset the API key before logging out
#[arg(long)]
pub reset_api_key: bool,
}
#[derive(Parser)]
pub struct DeployArgs {
/// Allow deployment with uncommitted files
#[arg(long, visible_alias = "ad")]
pub allow_dirty: bool,
/// Don't run pre-deploy tests
#[arg(long, visible_alias = "nt")]
pub no_test: bool,
}
#[derive(Parser, Debug)]
pub struct RunArgs {
/// Port to start service on
#[arg(long, short = 'p', env, default_value = "8000")]
pub port: u16,
/// Use 0.0.0.0 instead of localhost (for usage with local external devices)
#[arg(long)]
pub external: bool,
/// Use release mode for building the project
#[arg(long, short = 'r')]
pub release: bool,
}
#[derive(Parser, Clone, Debug, Default)]
pub struct InitArgs {
/// Clone a starter template from Shuttle's official examples
#[arg(long, short, value_enum, conflicts_with_all = &["from", "subfolder"])]
pub template: Option<InitTemplateArg>,
/// Clone a template from a git repository or local path using cargo-generate
#[arg(long)]
pub from: Option<String>,
/// Path to the template in the source (used with --from)
#[arg(long, requires = "from")]
pub subfolder: Option<String>,
/// Path where to place the new Shuttle project
#[arg(default_value = ".", value_parser = OsStringValueParser::new().try_map(parse_init_path))]
pub path: PathBuf,
/// Don't check the project name's validity or availability and use it anyways
#[arg(long)]
pub force_name: bool,
/// Whether to start the container for this project on Shuttle, and claim the project name
#[arg(long)]
pub create_env: bool,
/// Don't initialize a new git repository
#[arg(long)]
pub no_git: bool,
#[command(flatten)]
pub login_args: LoginArgs,
}
#[derive(ValueEnum, Clone, Debug, strum::Display, strum::EnumIter)]
#[strum(serialize_all = "kebab-case")]
pub enum InitTemplateArg {
/// Actix Web framework
ActixWeb,
/// Axum web framework
Axum,
/// Poem web framework
Poem,
/// Poise Discord framework
Poise,
/// Rocket web framework
Rocket,
/// Salvo web framework
Salvo,
/// Serenity Discord framework
Serenity,
/// Thruster web framework
Thruster,
/// Tide web framework
Tide,
/// Tower web framework
Tower,
/// Warp web framework
Warp,
/// No template - Custom empty service
None,
}
pub const EXAMPLES_REPO: &str = "https://github.com/shuttle-hq/shuttle-examples";
#[derive(Clone, Debug, PartialEq)]
pub struct TemplateLocation {
pub auto_path: String,
pub subfolder: Option<String>,
}
impl InitArgs {
pub fn git_template(&self) -> anyhow::Result<Option<TemplateLocation>> {
if self.from.is_some() && self.template.is_some() {
bail!("Template and From args can not be set at the same time.");
}
Ok(if let Some(from) = self.from.clone() {
Some(TemplateLocation {
auto_path: from,
subfolder: self.subfolder.clone(),
})
} else {
self.template.as_ref().map(|t| t.template())
})
}
}
impl InitTemplateArg {
pub fn template(&self) -> TemplateLocation {
use InitTemplateArg::*;
let path = match self {
ActixWeb => "actix-web/hello-world",
Axum => "axum/hello-world",
Poem => "poem/hello-world",
Poise => "poise/hello-world",
Rocket => "rocket/hello-world",
Salvo => "salvo/hello-world",
Serenity => "serenity/hello-world",
Thruster => "thruster/hello-world",
Tide => "tide/hello-world",
Tower => "tower/hello-world",
Warp => "warp/hello-world",
None => "custom-service/none",
};
TemplateLocation {
auto_path: EXAMPLES_REPO.into(),
subfolder: Some(path.to_string()),
}
}
}
/// Helper function to parse and return the absolute path
fn parse_path(path: OsString) -> Result<PathBuf, String> {
dunce::canonicalize(&path).map_err(|e| format!("could not turn {path:?} into a real path: {e}"))
}
/// Helper function to parse, create if not exists, and return the absolute path
pub(crate) fn parse_init_path(path: OsString) -> Result<PathBuf, io::Error> {
// Create the directory if does not exist
create_dir_all(&path).map_err(|e| {
io::Error::new(
ErrorKind::InvalidInput,
format!("Could not create directory: {e}"),
)
})?;
parse_path(path).map_err(|e| io::Error::new(ErrorKind::InvalidInput, e))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tests::path_from_workspace_root;
use clap::CommandFactory;
#[test]
fn test_shuttle_args() {
ShuttleArgs::command().debug_assert();
}
#[test]
fn test_init_args_framework() {
// pre-defined template (only hello world)
let init_args = InitArgs {
template: Some(InitTemplateArg::Tower),
from: None,
subfolder: None,
..Default::default()
};
assert_eq!(
init_args.git_template().unwrap(),
Some(TemplateLocation {
auto_path: EXAMPLES_REPO.into(),
subfolder: Some("tower/hello-world".into())
})
);
// pre-defined template (multiple)
let init_args = InitArgs {
template: Some(InitTemplateArg::Axum),
from: None,
subfolder: None,
..Default::default()
};
assert_eq!(
init_args.git_template().unwrap(),
Some(TemplateLocation {
auto_path: EXAMPLES_REPO.into(),
subfolder: Some("axum/hello-world".into())
})
);
// pre-defined "none" template
let init_args = InitArgs {
template: Some(InitTemplateArg::None),
from: None,
subfolder: None,
..Default::default()
};
assert_eq!(
init_args.git_template().unwrap(),
Some(TemplateLocation {
auto_path: EXAMPLES_REPO.into(),
subfolder: Some("custom-service/none".into())
})
);
// git template with path
let init_args = InitArgs {
template: None,
from: Some("https://github.com/some/repo".into()),
subfolder: Some("some/path".into()),
..Default::default()
};
assert_eq!(
init_args.git_template().unwrap(),
Some(TemplateLocation {
auto_path: "https://github.com/some/repo".into(),
subfolder: Some("some/path".into())
})
);
// No template or repo chosen
let init_args = InitArgs {
template: None,
from: None,
subfolder: None,
..Default::default()
};
assert_eq!(init_args.git_template().unwrap(), None);
}
#[test]
fn workspace_path() {
let project_args = ProjectArgs {
working_directory: path_from_workspace_root("examples/axum/hello-world/src"),
name: None,
};
assert_eq!(
project_args.workspace_path().unwrap(),
path_from_workspace_root("examples/axum/hello-world/")
);
}
#[test]
fn project_name() {
let project_args = ProjectArgs {
working_directory: path_from_workspace_root("examples/axum/hello-world/src"),
name: None,
};
assert_eq!(
project_args.project_name().unwrap().to_string(),
"hello-world"
);
}
#[test]
fn project_name_in_workspace() {
let project_args = ProjectArgs {
working_directory: path_from_workspace_root(
"examples/rocket/workspace/hello-world/src",
),
name: None,
};
assert_eq!(
project_args.project_name().unwrap().to_string(),
"workspace"
);
}
}