1use crate::cargo::{BuildTarget, Features, Metadata};
2use crate::{Config, Flavor};
3
4use anyhow::{Context, Result, bail};
5use std::path::PathBuf;
6
7pub struct Project {
12 pub package_name: String,
14
15 pub package_root: PathBuf,
17
18 pub workspace_root: PathBuf,
20
21 pub bin_names: Vec<String>,
23
24 pub has_lib: bool,
26
27 pub config: Config,
29
30 pub features: Features,
32}
33
34impl Project {
35 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 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 pub fn migrations_dir(&self) -> PathBuf {
88 self.package_root
89 .join(self.config.migration.get_migrations_dir())
90 }
91
92 pub fn snapshots_dir(&self) -> PathBuf {
94 self.package_root
95 .join(self.config.migration.get_snapshots_dir())
96 }
97
98 pub fn history_file_path(&self) -> PathBuf {
100 self.package_root
101 .join(self.config.migration.get_history_file_path())
102 }
103
104 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}