use std::env;
use std::process::{Command, Stdio};
use clap::{Parser, builder::styling::{AnsiColor, Styles}};
const CARGO_STYLE: Styles = Styles::styled()
.header(AnsiColor::Green.on_default().bold())
.usage(AnsiColor::Green.on_default().bold())
.literal(AnsiColor::Cyan.on_default().bold())
.placeholder(AnsiColor::Cyan.on_default());
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None, styles = CARGO_STYLE)]
struct Args {
#[arg(short, long)]
editor: Option<String>,
}
fn main() -> anyhow::Result<()> {
let raw_args: Vec<String> = env::args().collect();
let args_to_parse = if raw_args.get(1).map(|s| s == "edit-toml").unwrap_or(false) {
raw_args.iter().enumerate()
.filter_map(|(i, v)| if i != 1 { Some(v.clone()) } else { None })
.collect::<Vec<_>>()
} else {
raw_args.clone()
};
let args = Args::parse_from(args_to_parse);
let editor = match args.editor {
Some(e) => e,
None => env::var("EDITOR").unwrap_or_else(|_| {
"vi".to_string()
}),
};
let proj_loc = Command::new("cargo")
.args(&["locate-project", "--message-format", "plain"])
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.output()?;
if !proj_loc.status.success() {
anyhow::bail!(
"`cargo locate-project` failed – are you inside a Cargo project?"
);
}
let manifest_path = String::from_utf8(proj_loc.stdout)?
.trim_end_matches('\n')
.to_owned();
let status = Command::new(editor)
.arg(&manifest_path)
.status()
.map_err(|e| {
anyhow::anyhow!(
"Failed to spawn the editor. Make sure the editor binary is in your PATH. ({})",
e
)
})?;
if !status.success() {
anyhow::bail!("Editor exited with a non‑zero status");
}
Ok(())
}