From db4bb239a8a006f66e7358e58399f4cb6634cf32 Mon Sep 17 00:00:00 2001 From: Gary Coady Date: Thu, 8 Aug 2024 00:41:41 +0200 Subject: [PATCH] Feat: recursively search parent directories for leptosfmt.toml (#135) * Recursively search parent directories for leptosfmt.toml. * Read leptosfmt.toml from multiple places, implemented in a more functional style. --- cli/src/main.rs | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/cli/src/main.rs b/cli/src/main.rs index 33cd003..7b08154 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -1,7 +1,7 @@ #![deny(clippy::dbg_macro)] use std::{ - fs, + env, fs, io::{Read, Write}, panic, path::{Path, PathBuf}, @@ -264,24 +264,25 @@ fn format_file( }) } +fn find_config_file() -> anyhow::Result> { + Ok(fs::canonicalize(env::current_dir()?)? + .ancestors() + .map(|p| p.join("leptosfmt.toml")) + .find(|p| p.exists())) +} + fn create_settings(args: &Args) -> anyhow::Result { let mut settings = args .config_file .as_ref() - .map(|path| { - load_config(path) - .with_context(|| format!("failed to load config file: {}", path.display())) + .map(load_config) + .or_else(|| { + find_config_file() + .and_then(|v| v.as_ref().map(load_config).transpose()) + .transpose() }) - .unwrap_or_else(|| { - let default_config: PathBuf = "leptosfmt.toml".into(); - if default_config.exists() { - load_config(&default_config).with_context(|| { - format!("failed to load config file: {}", default_config.display()) - }) - } else { - Ok(FormatterSettings::default()) - } - })?; + .transpose()? + .unwrap_or_default(); if let Some(max_width) = args.max_width { settings.max_width = max_width; @@ -311,11 +312,10 @@ fn create_settings(args: &Args) -> anyhow::Result { } fn load_config(path: &PathBuf) -> anyhow::Result { - let config = fs::read_to_string(path).context("could not read config file")?; - let settings: FormatterSettings = - toml::from_str(&config).context("could not parse config file")?; - - Ok(settings) + fs::read_to_string(path) + .context("could not read config file") + .and_then(|contents| toml::from_str(&contents).context("could not parse config file")) + .with_context(|| format!("failed to load config file: {}", path.display())) } fn run_rustfmt(source: &str) -> Option {