Skip to content

Commit

Permalink
Feat: recursively search parent directories for leptosfmt.toml (#135)
Browse files Browse the repository at this point in the history
* Recursively search parent directories for leptosfmt.toml.

* Read leptosfmt.toml from multiple places, implemented in a more functional style.
  • Loading branch information
fiadliel authored Aug 7, 2024
1 parent 5df8d2a commit db4bb23
Showing 1 changed file with 19 additions and 19 deletions.
38 changes: 19 additions & 19 deletions cli/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#![deny(clippy::dbg_macro)]

use std::{
fs,
env, fs,
io::{Read, Write},
panic,
path::{Path, PathBuf},
Expand Down Expand Up @@ -264,24 +264,25 @@ fn format_file(
})
}

fn find_config_file() -> anyhow::Result<Option<PathBuf>> {
Ok(fs::canonicalize(env::current_dir()?)?
.ancestors()
.map(|p| p.join("leptosfmt.toml"))
.find(|p| p.exists()))
}

fn create_settings(args: &Args) -> anyhow::Result<FormatterSettings> {
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;
Expand Down Expand Up @@ -311,11 +312,10 @@ fn create_settings(args: &Args) -> anyhow::Result<FormatterSettings> {
}

fn load_config(path: &PathBuf) -> anyhow::Result<FormatterSettings> {
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<String> {
Expand Down

0 comments on commit db4bb23

Please sign in to comment.