use crate::config;
use crate::engine::run_treefmt;
use anyhow::anyhow;
use directories::ProjectDirs;
use log::debug;
use std::fs;
use std::path::{Path, PathBuf};
pub fn format_cmd(
tree_root: &Option<PathBuf>,
work_dir: &Path,
paths: &[PathBuf],
clear_cache: bool,
fail_on_change: bool,
) -> anyhow::Result<()> {
let proj_dirs = match ProjectDirs::from("com", "NumTide", "treefmt") {
Some(x) => x,
None => {
return Err(anyhow!(
"Could not find the project directories. On Unix, check if the HOME env is missing."
))
}
};
let config_file = match config::lookup(&work_dir) {
Some(path) => path,
None => {
return Err(anyhow!(
"{} could not be found in {} and up. Use the --init option to create one.",
config::FILENAME,
work_dir.display()
))
}
};
let tree_root = tree_root.clone().unwrap_or_else(|| {
config_file.clone().parent().unwrap().to_path_buf()
});
let paths = if paths.is_empty() {
vec![tree_root.clone()]
} else {
paths.to_owned()
};
let cache_dir = proj_dirs.cache_dir().join("eval-cache");
fs::create_dir_all(&cache_dir)?;
debug!(
"tree_root={} work_dir={} cache_dir={} config_file={} paths={:?}",
tree_root.display(),
work_dir.display(),
cache_dir.display(),
config_file.display(),
paths
);
run_treefmt(
&tree_root,
&work_dir,
&cache_dir,
&config_file,
&paths,
clear_cache,
fail_on_change,
)?;
Ok(())
}