Skip to main content

toasty_cli/
lib.rs

1//! The standalone `toasty` command-line tool.
2//!
3//! Installed with `cargo install toasty-cli` and run from any Cargo package
4//! that uses Toasty. Schema-bound commands build the package's bin (or its
5//! lib as a `cdylib`) and run it with `TOASTY_DUMP_SCHEMA` set, which makes a
6//! constructor inside `toasty` dump the schema and exit. See
7//! `docs/dev/design/standalone-cli.md`.
8//!
9//! The library exists for the binary and its tests; its API is not stable.
10
11mod cargo;
12mod config;
13mod extract;
14mod flavor;
15mod load_cdylib;
16mod migrate;
17mod project;
18mod theme;
19mod utility;
20
21pub use cargo::Features;
22pub use config::Config;
23pub use flavor::Flavor;
24pub use migrate::{MigrationConfig, MigrationPrefixStyle};
25pub use project::Project;
26
27use anyhow::{Context, Result};
28use clap::Parser;
29
30/// Parses `std::env::args` and runs the matching subcommand.
31pub fn run() -> Result<()> {
32    run_parsed(Cli::parse())
33}
34
35/// Parses from an explicit argument list and runs the matching subcommand.
36/// Useful for testing.
37pub fn run_from<I, T>(args: I) -> Result<()>
38where
39    I: IntoIterator<Item = T>,
40    T: Into<std::ffi::OsString> + Clone,
41{
42    run_parsed(Cli::parse_from(args))
43}
44
45fn run_parsed(cli: Cli) -> Result<()> {
46    match cli.command {
47        // Runs before the async runtime exists: the subcommand mutates its
48        // environment, which is only sound while single-threaded.
49        Command::LoadCdylib(cmd) => cmd.run(),
50        Command::Migrate(cmd) => {
51            let project = Project::locate(cli.package.as_deref(), cli.features)?;
52            runtime()?.block_on(cmd.run(&project))
53        }
54    }
55}
56
57/// Built here rather than with `#[tokio::main]` so `__load-cdylib` runs
58/// before any worker thread exists.
59fn runtime() -> Result<tokio::runtime::Runtime> {
60    tokio::runtime::Builder::new_multi_thread()
61        .enable_all()
62        .build()
63        .context("failed to start the async runtime")
64}
65
66#[derive(Parser, Debug)]
67#[command(name = "toasty")]
68#[command(about = "Toasty schema management and migrations")]
69#[command(version)]
70struct Cli {
71    /// Package to operate on, when the workspace has more than one
72    #[arg(short, long, global = true, value_name = "PKG")]
73    package: Option<String>,
74
75    #[command(flatten)]
76    features: Features,
77
78    #[command(subcommand)]
79    command: Command,
80}
81
82#[derive(Parser, Debug)]
83enum Command {
84    /// Database migration commands
85    Migrate(migrate::MigrateCommand),
86
87    /// Internal: load a cdylib so its schema-dump constructor runs. Only
88    /// invoked by `toasty` itself.
89    #[command(name = "__load-cdylib", hide = true)]
90    LoadCdylib(load_cdylib::LoadCdylibCommand),
91}