1use std::env;
4use std::ffi::OsStr;
5use std::path::PathBuf;
6use std::process::ExitCode;
7use std::str::FromStr;
8use std::time::Instant;
9
10use anyhow::{
11 Context as _,
12 Result,
13};
14use clap::parser::ValueSource;
15use clap::{
16 Arg,
17 ArgMatches,
18 Command,
19};
20use clap_complete::Shell;
21use midas::config::{
22 Config,
23 ConfigOverrides,
24 ProcessEnv,
25};
26use tracing_subscriber::EnvFilter;
27
28use crate::commands;
29
30const PKG_VERSION: &str = env!("CARGO_PKG_VERSION");
32
33const PKG_DESCRIPTION: &str = env!("CARGO_PKG_DESCRIPTION");
35
36pub fn main_entry(command_name: &str, is_subcommand: bool) -> ExitCode {
38 match midas_entry(command_name, is_subcommand) {
39 Ok(()) => ExitCode::SUCCESS,
40 Err(error) => {
41 eprintln!("error: {error:#}");
42 ExitCode::from(exit_code(&error))
43 },
44 }
45}
46
47pub fn exit_code(error: &anyhow::Error) -> u8 {
52 for cause in error.chain() {
53 let Some(error) = cause.downcast_ref::<midas::Error>() else {
54 continue;
55 };
56 return match error {
57 midas::Error::DirtyMigration { .. } => 3,
58 midas::Error::Drift(_) => 4,
59 midas::Error::Database(_) | midas::Error::Lock(_) | midas::Error::LockTimeout { .. } => 2,
60 _ => 1,
61 };
62 }
63 1
64}
65
66pub fn midas_entry(command_name: &str, is_subcommand: bool) -> Result<()> {
68 dotenvy::dotenv()
69 .or_else(|_| dotenvy::from_filename(".env.midas"))
70 .ok();
71
72 if env::var("RUST_LOG").is_err() {
73 env::set_var("RUST_LOG", "midas=info,midas_cli=info");
74 }
75
76 let mut cli_app = build_cli(command_name, is_subcommand);
77 let matches = if is_subcommand {
78 cli_app
79 .clone()
80 .get_matches()
81 .subcommand_matches(command_name)
82 .with_context(|| format!("cargo-{command_name} not invoked via cargo command"))?
83 .to_owned()
84 } else {
85 cli_app.clone().get_matches()
86 };
87
88 let no_color = no_color_requested(matches.get_flag("no-color"), env::var_os("NO_COLOR").as_deref());
89 configure_color(no_color);
90 tracing_subscriber::fmt()
91 .with_env_filter(EnvFilter::from_default_env())
92 .with_ansi(!no_color)
93 .init();
94
95 if matches.subcommand_name().is_none() {
96 cli_app.print_long_help()?;
97 return Ok(());
98 }
99
100 if let Some(("completion", sub)) = matches.subcommand() {
101 return dispatch_completion(sub, command_name, is_subcommand);
102 }
103
104 let overrides = ConfigOverrides {
105 database_url: command_line_value(&matches, "database"),
106 migrations_dir: command_line_value::<String>(&matches, "source").map(PathBuf::from),
107 ..ConfigOverrides::default()
108 };
109 let cwd = env::current_dir().context("failed to read current directory")?;
110 let config_dir = (matches.subcommand_name() != Some("init")).then_some(cwd.as_path());
113 let config = Config::load(&ProcessEnv, &overrides, config_dir)?;
114 let context = commands::Context::new(config).with_flags(
115 matches.get_flag("dry-run"),
116 matches.get_flag("no-lock"),
117 matches.get_flag("ignore-missing"),
118 );
119
120 let start = Instant::now();
121 commands::dispatch(&matches, &context)?;
122 let duration = start.elapsed();
123 tracing::trace!(
124 seconds = duration.as_secs(),
125 milliseconds = duration.subsec_millis(),
126 "command completed"
127 );
128
129 Ok(())
130}
131
132fn build_cli(command_name: &str, is_subcommand: bool) -> Command {
133 let name = command_name.to_owned();
134 let mut cli_app = if is_subcommand {
135 Command::new(name)
136 } else {
137 Command::new(name.clone()).bin_name(name)
138 };
139
140 cli_app = cli_app
141 .version(PKG_VERSION)
142 .about(PKG_DESCRIPTION)
143 .arg_required_else_help(true)
144 .propagate_version(true)
145 .arg(
146 Arg::new("database")
147 .short('d')
148 .long("database")
149 .env("DATABASE_URL")
150 .value_name("url")
151 .help("Sets the database connection url")
152 .num_args(1)
153 .required(false)
154 .global(true),
155 )
156 .arg(
157 Arg::new("source")
158 .short('s')
159 .long("source")
160 .env("MIGRATIONS_DIR")
161 .value_name("path")
162 .help("Sets the migration store directory")
163 .num_args(1)
164 .required(false)
165 .global(true),
166 )
167 .arg(
168 Arg::new("no-color")
169 .long("no-color")
170 .help("Disable colored output (honors NO_COLOR)")
171 .action(clap::ArgAction::SetTrue)
172 .global(true),
173 )
174 .arg(
175 Arg::new("dry-run")
176 .long("dry-run")
177 .help("Print SQL without executing it")
178 .action(clap::ArgAction::SetTrue)
179 .global(true),
180 )
181 .arg(
182 Arg::new("no-lock")
183 .long("no-lock")
184 .help("Skip the advisory migration lock")
185 .action(clap::ArgAction::SetTrue)
186 .global(true),
187 )
188 .arg(
189 Arg::new("ignore-missing")
190 .long("ignore-missing")
191 .help("Ignore applied migrations whose files are no longer present")
192 .action(clap::ArgAction::SetTrue)
193 .global(true),
194 );
195
196 let cli_app = commands::register(cli_app).subcommand(
197 Command::new("completion")
198 .visible_alias("comp")
199 .about("Generates shell completion scripts")
200 .arg(
201 Arg::new("shell")
202 .help("The shell to generate completion for")
203 .required(true)
204 .num_args(1),
205 ),
206 );
207
208 if is_subcommand {
209 Command::new("cargo").bin_name("cargo").subcommand(cli_app)
210 } else {
211 cli_app
212 }
213}
214
215fn write_completions(command_name: &str, is_subcommand: bool, shell: &str) -> Result<()> {
216 let shell = Shell::from_str(shell).map_err(|error| anyhow::anyhow!("invalid shell: {error}"))?;
217
218 let mut app = build_cli(command_name, is_subcommand);
219 if is_subcommand {
220 clap_complete::generate(shell, &mut app, "cargo", &mut std::io::stdout().lock());
221 } else {
222 clap_complete::generate(shell, &mut app, command_name, &mut std::io::stdout().lock());
223 }
224
225 Ok(())
226}
227
228fn command_line_value<T>(matches: &ArgMatches, id: &str) -> Option<T>
229where
230 T: Clone + Send + Sync + 'static,
231{
232 if matches.value_source(id) == Some(ValueSource::CommandLine) {
233 matches.get_one::<T>(id).cloned()
234 } else {
235 None
236 }
237}
238
239fn no_color_requested(flag: bool, env_value: Option<&OsStr>) -> bool {
240 flag || env_value.is_some()
241}
242
243fn configure_color(disabled: bool) {
244 if disabled {
245 console::set_colors_enabled(false);
246 console::set_colors_enabled_stderr(false);
247 }
248}
249
250pub fn dispatch_completion(matches: &ArgMatches, command_name: &str, is_subcommand: bool) -> Result<()> {
252 let shell = matches.get_one::<String>("shell").context("shell is required")?;
253 write_completions(command_name, is_subcommand, shell)
254}
255
256#[cfg(test)]
257mod tests {
258 use super::*;
259
260 #[test]
261 fn no_color_honors_flag_and_environment() {
262 assert!(no_color_requested(true, None));
263 assert!(no_color_requested(false, Some(OsStr::new("1"))));
264 assert!(!no_color_requested(false, None));
265 }
266
267 #[test]
268 fn build_cli_registers_faker_and_setup() {
269 let app = build_cli("midas", false);
270 let names = app
271 .get_subcommands()
272 .map(|command| command.get_name())
273 .collect::<Vec<_>>();
274
275 for removed in ["update", "upto", "drop"] {
276 assert!(!names.contains(&removed), "`{removed}` must be removed");
277 }
278 for present in [
279 "init",
280 "add",
281 "run",
282 "info",
283 "list",
284 "resolve",
285 "completion",
286 "faker",
287 "setup",
288 ] {
289 assert!(names.contains(&present), "`{present}` must exist");
290 }
291 }
292
293 #[test]
294 fn exit_codes_follow_the_contract() {
295 let error = anyhow::Error::new(midas::Error::DirtyMigration { version: 1 });
296 assert_eq!(exit_code(&error), 3);
297
298 let error = anyhow::Error::new(midas::Error::LockTimeout { backend: "postgres" });
299 assert_eq!(exit_code(&error), 2);
300
301 let error = anyhow::Error::new(midas::Error::Drift("boom".to_string()));
302 assert_eq!(exit_code(&error), 4);
303
304 let error = anyhow::Error::new(midas::Error::migration("boom"));
305 assert_eq!(exit_code(&error), 1);
306
307 let error = anyhow::anyhow!("plain");
308 assert_eq!(exit_code(&error), 1);
309 }
310}