#![allow(clippy::redundant_closure)]
mod format;
mod format_stdin;
mod init;
use self::format::format_cmd;
use self::format_stdin::format_stdin_cmd;
use self::init::init_cmd;
use crate::config;
use crate::expand_path;
use anyhow::anyhow;
use std::path::PathBuf;
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
pub struct Cli {
#[structopt(long = "init")]
pub init: bool,
#[structopt(long = "stdin", conflicts_with("init"))]
pub stdin: bool,
#[structopt(long = "no-cache", conflicts_with("stdin"), conflicts_with("init"))]
pub no_cache: bool,
#[structopt(long = "clear-cache", conflicts_with("stdin"), conflicts_with("init"))]
pub clear_cache: bool,
#[structopt(
long = "fail-on-change",
conflicts_with("stdin"),
conflicts_with("init")
)]
pub fail_on_change: bool,
#[structopt(long = "allow-missing-formatter")]
pub allow_missing_formatter: bool,
#[structopt(long = "verbose", short = "v", parse(from_occurrences))]
pub verbosity: u8,
#[structopt(long = "quiet", short = "q")]
pub quiet: bool,
#[structopt(short = "C", default_value = ".")]
pub work_dir: PathBuf,
#[structopt(long = "tree-root", env = "PRJ_ROOT")]
pub tree_root: Option<PathBuf>,
#[structopt(long = "config-file")]
pub config_file: Option<PathBuf>,
#[structopt()]
pub paths: Vec<PathBuf>,
#[structopt(long = "formatters", short = "f")]
pub formatters: Option<Vec<String>>,
}
pub fn cli_from_args() -> anyhow::Result<Cli> {
let mut cli = Cli::from_args();
let cwd = std::env::current_dir()?;
assert!(cwd.is_absolute());
cli.work_dir = expand_path(&cli.work_dir, &cwd);
if let Some(tree_root) = cli.tree_root {
cli.tree_root = Some(expand_path(&tree_root, &cwd));
}
match cli.config_file {
None => {
cli.config_file = config::lookup(&cli.work_dir);
}
Some(_) => {
if cli.tree_root.is_none() {
return Err(anyhow!(
"If --config-file is set, --tree-root must also be set"
));
}
}
}
if let Some(config_file) = cli.config_file {
cli.config_file = Some(expand_path(&config_file, &cwd));
}
Ok(cli)
}
pub fn run_cli(cli: &Cli) -> anyhow::Result<()> {
if cli.init {
init_cmd(&cli.work_dir)?
} else if cli.stdin {
format_stdin_cmd(&cli.tree_root, &cli.work_dir, &cli.paths, &cli.formatters)?
} else {
if cli.config_file.is_none() {
return Err(anyhow!(
"{} could not be found in {} and up. Use the --init option to create one or specify --config-file if it is in a non-standard location.",
config::FILENAME,
cli.work_dir.display(),
));
}
format_cmd(
&cli.tree_root,
&cli.work_dir,
cli.config_file
.as_ref()
.expect("presence asserted in ::cli_from_args"),
&cli.paths,
cli.no_cache,
cli.clear_cache,
cli.fail_on_change,
cli.allow_missing_formatter,
&cli.formatters,
)?
}
Ok(())
}