Skip to main content

toasty_cli/
project.rs

1use crate::cargo::{BuildTarget, Features, Metadata};
2use crate::{Config, Flavor};
3
4use anyhow::{Context, Result, bail};
5use std::path::PathBuf;
6
7/// The Cargo package the CLI operates on, plus its Toasty configuration.
8///
9/// All migration files live under the package's directory (`Toasty.toml`,
10/// `toasty/`), so workspace members keep independent migration histories.
11pub struct Project {
12    /// Name of the selected package.
13    pub package_name: String,
14
15    /// Directory containing the package's `Cargo.toml`.
16    pub package_root: PathBuf,
17
18    /// The workspace root directory.
19    pub workspace_root: PathBuf,
20
21    /// Bin target names declared by the package.
22    pub bin_names: Vec<String>,
23
24    /// Whether the package has a lib target.
25    pub has_lib: bool,
26
27    /// Configuration loaded from the package's `Toasty.toml` (or defaults).
28    pub config: Config,
29
30    /// Cargo feature selection, applied to the schema build.
31    pub features: Features,
32}
33
34impl Project {
35    /// Locates the target package via `cargo metadata` and loads its
36    /// configuration.
37    pub fn locate(package: Option<&str>, features: Features) -> Result<Self> {
38        let metadata = Metadata::load()?;
39        let pkg = metadata.select_package(package)?;
40
41        let package_root = pkg.root();
42        let config = Config::load_or_default(&package_root)?;
43
44        Ok(Project {
45            package_name: pkg.name().to_string(),
46            package_root,
47            workspace_root: metadata.workspace_root().to_path_buf(),
48            bin_names: pkg.bin_names(),
49            has_lib: pkg.has_lib(),
50            config,
51            features,
52        })
53    }
54
55    /// Picks the artifact to build for schema extraction.
56    ///
57    /// A bin target is preferred; lib-only packages fall back to building the
58    /// lib as a `cdylib`. `bin` selects among multiple bin targets.
59    pub fn build_target(&self, bin: Option<&str>) -> Result<BuildTarget> {
60        if let Some(name) = bin {
61            if !self.bin_names.iter().any(|b| b == name) {
62                bail!(
63                    "package `{}` has no bin target named `{name}`; available bins: {}",
64                    self.package_name,
65                    self.bin_names.join(", ")
66                );
67            }
68            return Ok(BuildTarget::Bin(name.to_string()));
69        }
70
71        match self.bin_names.as_slice() {
72            [] if self.has_lib => Ok(BuildTarget::Cdylib),
73            [] => bail!(
74                "package `{}` has no bin or lib target to extract a schema from",
75                self.package_name
76            ),
77            [only] => Ok(BuildTarget::Bin(only.clone())),
78            many => bail!(
79                "package `{}` has multiple bin targets; select one with `--bin <name>`: {}",
80                self.package_name,
81                many.join(", ")
82            ),
83        }
84    }
85
86    /// Directory holding generated migration SQL files.
87    pub fn migrations_dir(&self) -> PathBuf {
88        self.package_root
89            .join(self.config.migration.get_migrations_dir())
90    }
91
92    /// Directory holding schema snapshot files.
93    pub fn snapshots_dir(&self) -> PathBuf {
94        self.package_root
95            .join(self.config.migration.get_snapshots_dir())
96    }
97
98    /// Path of the migration history file.
99    pub fn history_file_path(&self) -> PathBuf {
100        self.package_root
101            .join(self.config.migration.get_history_file_path())
102    }
103
104    /// The flavor to use: the command-line flag when given, otherwise the
105    /// `migration.flavor` entry in `Toasty.toml`.
106    pub fn flavor(&self, flag: Option<Flavor>) -> Result<Flavor> {
107        flag.or(self.config.migration.flavor).context(
108            "no flavor selected; pass `--flavor <sqlite|postgresql|mysql|mariadb|turso>` or \
109             set `migration.flavor` in Toasty.toml",
110        )
111    }
112}