Skip to content

Commit 58ff7c4

Browse files
committed
functora-cfg lite refactoring
1 parent 35b2570 commit 58ff7c4

File tree

1 file changed

+17
-22
lines changed

1 file changed

+17
-22
lines changed

rust/functora-cfg/src/lib.rs

Lines changed: 17 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -19,14 +19,18 @@ where
1919

2020
// Def
2121
if let Some(cfg) = def {
22-
builder = builder.add_source(any_to_config(cfg)?);
22+
builder = builder.add_source(term_to_config(cfg)?);
2323
}
2424

2525
// Cfg
2626
if let Some(path) = get_cfg_path(cli) {
2727
let path = Path::new(&path);
28-
if path.exists() {
28+
if path.exists() && path.is_file() {
2929
builder = builder.add_source(File::from(path));
30+
} else {
31+
return Err(ConfigError::Message(
32+
"Config file path does not exist!".into(),
33+
));
3034
}
3135
}
3236

@@ -37,40 +41,31 @@ where
3741
);
3842

3943
// Cli
40-
builder = builder.add_source(any_to_config(cli)?);
44+
builder = builder.add_source(term_to_config(cli)?);
4145

4246
builder.build()?.try_deserialize()
4347
}
4448

45-
fn any_to_config<T: Serialize>(
49+
fn term_to_config<T: Serialize>(
4650
value: &T,
4751
) -> Result<Config, ConfigError> {
4852
let toml = toml::Value::try_from(value)
4953
.map_err(|e| ConfigError::Message(e.to_string()))?;
5054

51-
if let TomlValue::Table(table) = toml {
52-
toml_to_config_table(table)
55+
if let TomlValue::Table(kv) = toml {
56+
kv.into_iter()
57+
.try_fold(Config::builder(), |acc, (k, v)| {
58+
acc.set_override(k, toml_to_config(v))
59+
})?
60+
.build()
5361
} else {
5462
Err(ConfigError::Message(
5563
"Expected table at root".into(),
5664
))
5765
}
5866
}
5967

60-
fn toml_to_config_table(
61-
table: toml::value::Table,
62-
) -> Result<Config, ConfigError> {
63-
let mut builder = Config::builder();
64-
65-
for (k, v) in table {
66-
builder = builder
67-
.set_override(k, toml_to_config_value(v))?;
68-
}
69-
70-
builder.build()
71-
}
72-
73-
fn toml_to_config_value(toml: TomlValue) -> Value {
68+
fn toml_to_config(toml: TomlValue) -> Value {
7469
match toml {
7570
TomlValue::String(x) => Value::from(x),
7671
TomlValue::Integer(x) => Value::from(x),
@@ -81,12 +76,12 @@ fn toml_to_config_value(toml: TomlValue) -> Value {
8176
}
8277
TomlValue::Array(xs) => Value::from(
8378
xs.into_iter()
84-
.map(toml_to_config_value)
79+
.map(toml_to_config)
8580
.collect::<Vec<_>>(),
8681
),
8782
TomlValue::Table(kv) => Value::from(
8883
kv.into_iter()
89-
.map(|(k, v)| (k, toml_to_config_value(v)))
84+
.map(|(k, v)| (k, toml_to_config(v)))
9085
.collect::<config::Map<String, Value>>(),
9186
),
9287
}

0 commit comments

Comments
 (0)