Skip to content

Commit ecce820

Browse files
committed
fix(config): answer config get for every key rumdl accepts
`rumdl config get` hand-listed the keys it could read back, and the list had drifted from the keys rumdl actually takes. `global.line-length` set to 99 in the project config was reported as an unknown key, as were `cache`, `flavor`, `fixable`, the extend lists and a rule's `severity`. Reading a setting back is how a user confirms it took effect, so calling a live setting unknown is worse than silence. Global keys are now read through the same table that applies them, so the two halves cannot drift, and a test walks the key list to prove every one answers. Rule keys resolve through the validator's own schema. A key that is accepted but holds nothing now reports `<unset> [no default]` and exits 0, distinct from an unknown key, which still errors. Collapsing those two would tell a user that a real setting does not exist. `<unset>` is deliberately not valid TOML so it cannot be copied back as a value. Unset nullable keys were previously skipped entirely from a rule's listing, so `rumdl config get MD001` showed one of its four settable keys.
1 parent 77c8c65 commit ecce820

3 files changed

Lines changed: 220 additions & 104 deletions

File tree

‎src/commands/config.rs‎

Lines changed: 120 additions & 103 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,41 @@ pub fn handle_config(
5252
}
5353
}
5454

55+
/// Stands in for the value of a key rumdl accepts that is neither set nor backed by a
56+
/// default it could show (an unset `Option`). Deliberately not valid TOML, so it can
57+
/// never be read back as a real setting.
58+
const UNSET_DISPLAY: &str = "<unset>";
59+
60+
fn print_config_value(rule: &str, field: &str, value: &toml::Value, source: ConfigSource) {
61+
println!(
62+
"{}.{} = {} [from {}]",
63+
rule,
64+
field,
65+
formatter::format_toml_value(value),
66+
formatter::format_provenance(source)
67+
);
68+
}
69+
70+
/// Reports a key as accepted but carrying no value, which is a different answer from
71+
/// "unknown key" and must not be collapsed into one.
72+
fn print_unset_config_value(rule: &str, field: &str) {
73+
println!("{rule}.{field} = {UNSET_DISPLAY} [no default]");
74+
}
75+
76+
/// The defaults a rule publishes for display, which is where a shown value comes from.
77+
/// Distinct from the validation schema in [`rumdl_config::RuleRegistry`]: that one
78+
/// carries sentinels for keys whose type cannot be checked, and a sentinel must never
79+
/// reach output.
80+
fn default_config_values_for_rule(rule_name: &str) -> toml::map::Map<String, toml::Value> {
81+
rumdl_lib::rules::all_rules(&rumdl_config::Config::default())
82+
.iter()
83+
.find_map(|rule| match rule.default_config_section() {
84+
Some((name, toml::Value::Table(table))) if normalize_key(&name) == rule_name => Some(table),
85+
_ => None,
86+
})
87+
.unwrap_or_default()
88+
}
89+
5590
fn handle_config_get(key: &str, config_path: Option<&str>, no_config: bool, inline_overrides: &[toml::Table]) {
5691
// Load config once; both dot-key and bare-rule paths use the same sourced state.
5792
let mut sourced = match rumdl_config::SourcedConfig::load_with_discovery(config_path, None, no_config) {
@@ -70,94 +105,49 @@ fn handle_config_get(key: &str, config_path: Option<&str>, no_config: bool, inli
70105

71106
// Handle GLOBAL keys
72107
if section_part.eq_ignore_ascii_case("global") {
73-
let maybe_value_source: Option<(toml::Value, ConfigSource)> = match normalized_field.as_str() {
74-
"enable" => Some((
75-
toml::Value::Array(
76-
final_config
77-
.global
78-
.enable
79-
.iter()
80-
.map(|s| toml::Value::String(s.clone()))
81-
.collect(),
82-
),
83-
sourced.global.enable.source,
84-
)),
85-
"disable" => Some((
86-
toml::Value::Array(
87-
final_config
88-
.global
89-
.disable
90-
.iter()
91-
.map(|s| toml::Value::String(s.clone()))
92-
.collect(),
93-
),
94-
sourced.global.disable.source,
95-
)),
96-
"exclude" => Some((
97-
toml::Value::Array(
98-
final_config
99-
.global
100-
.exclude
101-
.iter()
102-
.map(|s| toml::Value::String(s.clone()))
103-
.collect(),
104-
),
105-
sourced.global.exclude.source,
106-
)),
107-
"include" => Some((
108-
toml::Value::Array(
109-
final_config
110-
.global
111-
.include
112-
.iter()
113-
.map(|s| toml::Value::String(s.clone()))
114-
.collect(),
115-
),
116-
sourced.global.include.source,
117-
)),
118-
"respect-gitignore" => Some((
119-
toml::Value::Boolean(final_config.global.respect_gitignore),
120-
sourced.global.respect_gitignore.source,
121-
)),
122-
"output-format" | "output_format" => {
123-
if let Some(ref output_format) = final_config.global.output_format {
124-
Some((
125-
toml::Value::String(output_format.clone()),
126-
sourced
127-
.global
128-
.output_format
129-
.as_ref()
130-
.map(|v| v.source)
131-
.unwrap_or(ConfigSource::Default),
132-
))
133-
} else {
134-
None
135-
}
108+
match rumdl_config::read_global_key(&sourced.global, &normalized_field) {
109+
Some(rumdl_config::GlobalKeyValue::Set(value, source)) => {
110+
print_config_value("global", &normalized_field, &value, source);
111+
}
112+
Some(rumdl_config::GlobalKeyValue::Unset) => {
113+
print_unset_config_value("global", &normalized_field);
114+
}
115+
None => {
116+
eprintln!("Unknown global key: {field_part}");
117+
exit::tool_error();
136118
}
137-
"flavor" => Some((
138-
toml::Value::String(final_config.global.flavor.to_string()),
139-
sourced.global.flavor.source,
140-
)),
141-
_ => None,
142-
};
143-
144-
if let Some((value, source)) = maybe_value_source {
145-
println!(
146-
"{} = {} [from {}]",
147-
key,
148-
formatter::format_toml_value(&value),
149-
formatter::format_provenance(source)
150-
);
151-
} else {
152-
eprintln!("Unknown global key: {field_part}");
153-
exit::tool_error();
154119
}
155120
}
156121
// Handle RULE keys (MDxxx.field or alias.field)
157122
else {
158123
let normalized_rule_name = rumdl_config::resolve_rule_name_alias(section_part)
159124
.map(|s| s.to_string())
160125
.unwrap_or_else(|| normalize_key(section_part));
126+
let registry = rumdl_config::default_registry();
127+
128+
if !registry.rule_schemas.contains_key(&normalized_rule_name) {
129+
eprintln!("Unknown config key: {normalized_rule_name}.{normalized_field}");
130+
exit::tool_error();
131+
}
132+
133+
// `severity` is accepted for every rule but is parsed into its own field
134+
// rather than into `values`, so it needs its own lookup.
135+
if normalized_field == "severity" {
136+
match sourced
137+
.rules
138+
.get(&normalized_rule_name)
139+
.and_then(|sc| sc.severity.as_ref())
140+
{
141+
Some(sourced_severity) => print_config_value(
142+
&normalized_rule_name,
143+
&normalized_field,
144+
&toml::Value::try_from(sourced_severity.value).expect("Severity serializes to a TOML string"),
145+
sourced_severity.source,
146+
),
147+
None => print_unset_config_value(&normalized_rule_name, &normalized_field),
148+
}
149+
return;
150+
}
161151

162152
// Try to get the value from the final config first
163153
let final_value: Option<&toml::Value> = final_config
@@ -172,22 +162,30 @@ fn handle_config_get(key: &str, config_path: Option<&str>, no_config: bool, inli
172162
.and_then(|sc| sc.values.get(&normalized_field))
173163
.map_or(ConfigSource::Default, |sv| sv.source);
174164

175-
println!(
176-
"{}.{} = {} [from {}]",
177-
normalized_rule_name,
178-
normalized_field,
179-
formatter::format_toml_value(value),
180-
formatter::format_provenance(provenance)
181-
);
182-
} else {
183-
let registry = rumdl_config::default_registry();
184-
if let Some(v) = registry.expected_value_for(&normalized_rule_name, &normalized_field) {
185-
let value_str = formatter::format_toml_value(v);
186-
println!("{normalized_rule_name}.{normalized_field} = {value_str} [from default]");
165+
print_config_value(&normalized_rule_name, &normalized_field, value, provenance);
166+
return;
167+
}
168+
169+
// `enabled` is accepted for every rule and belongs to no rule's schema,
170+
// so an unset one is reported as unset rather than as an unknown key.
171+
let Some(canonical_key) = registry.canonical_config_key(&normalized_rule_name, &normalized_field) else {
172+
if normalized_field == "enabled" {
173+
print_unset_config_value(&normalized_rule_name, &normalized_field);
187174
return;
188175
}
189176
eprintln!("Unknown config key: {normalized_rule_name}.{normalized_field}");
190177
exit::tool_error();
178+
};
179+
180+
// The default comes from the rule's user-facing table, not from the
181+
// validation schema: a key whose schema entry is a sentinel can still have
182+
// a displayable default (a polymorphic key), and one that has none is unset
183+
// rather than unknown.
184+
match default_config_values_for_rule(&normalized_rule_name).get(canonical_key) {
185+
Some(value) => {
186+
print_config_value(&normalized_rule_name, &normalized_field, value, ConfigSource::Default)
187+
}
188+
None => print_unset_config_value(&normalized_rule_name, &normalized_field),
191189
}
192190
}
193191
} else {
@@ -199,12 +197,37 @@ fn handle_config_get(key: &str, config_path: Option<&str>, no_config: bool, inli
199197

200198
if registry.rule_schemas.contains_key(&normalized_rule_name) {
201199
let schema = &registry.rule_schemas[&normalized_rule_name];
202-
let mut fields: Vec<&String> = schema.keys().collect();
203-
fields.sort();
200+
let defaults = default_config_values_for_rule(&normalized_rule_name);
201+
202+
// Every key the rule accepts, so the listing is the answer to "what can I
203+
// set here?": the rule's own schema plus the two keys every rule takes.
204+
let mut fields: Vec<&str> = schema.keys().map(String::as_str).collect();
205+
fields.push("enabled");
206+
fields.push("severity");
207+
fields.sort_unstable();
208+
fields.dedup();
204209

205210
for field in fields {
206211
let normalized_field = normalize_key(field);
207212

213+
if normalized_field == "severity" {
214+
match sourced
215+
.rules
216+
.get(&normalized_rule_name)
217+
.and_then(|sc| sc.severity.as_ref())
218+
{
219+
Some(sourced_severity) => print_config_value(
220+
&normalized_rule_name,
221+
&normalized_field,
222+
&toml::Value::try_from(sourced_severity.value)
223+
.expect("Severity serializes to a TOML string"),
224+
sourced_severity.source,
225+
),
226+
None => print_unset_config_value(&normalized_rule_name, &normalized_field),
227+
}
228+
continue;
229+
}
230+
208231
let final_value = final_config
209232
.rules
210233
.get(&normalized_rule_name)
@@ -217,20 +240,14 @@ fn handle_config_get(key: &str, config_path: Option<&str>, no_config: bool, inli
217240
.and_then(|sc| sc.values.get(&normalized_field))
218241
.map_or(rumdl_config::ConfigSource::Default, |sv| sv.source);
219242
(v, provenance)
220-
} else if let Some(v) = registry.expected_value_for(&normalized_rule_name, &normalized_field) {
243+
} else if let Some(v) = defaults.get(field) {
221244
(v, rumdl_config::ConfigSource::Default)
222245
} else {
223-
// Nullable sentinel field — no displayable default, skip
246+
print_unset_config_value(&normalized_rule_name, &normalized_field);
224247
continue;
225248
};
226249

227-
println!(
228-
"{}.{} = {} [from {}]",
229-
normalized_rule_name,
230-
normalized_field,
231-
formatter::format_toml_value(value),
232-
formatter::format_provenance(source)
233-
);
250+
print_config_value(&normalized_rule_name, &normalized_field, value, source);
234251
}
235252
} else {
236253
eprintln!(

‎src/config/global_keys.rs‎

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,62 @@ pub fn is_global_value_key(key: &str) -> bool {
4444
GLOBAL_VALUE_KEYS.contains(&key)
4545
}
4646

47+
/// What reading a global key found.
48+
#[derive(Debug)]
49+
pub enum GlobalKeyValue {
50+
/// The key holds a value, shown with where it came from.
51+
Set(toml::Value, ConfigSource),
52+
/// The key is accepted but holds nothing and has no default to show. A caller
53+
/// must report this as unset, never as an unknown key: the two are different
54+
/// answers and collapsing them tells the user a real setting does not exist.
55+
Unset,
56+
}
57+
58+
/// Read one global key back out of the global config section.
59+
///
60+
/// The read half of [`apply_global_key`], kept beside it so the two cannot drift:
61+
/// every key in [`GLOBAL_VALUE_KEYS`] answers here. Returns `None` only for a key
62+
/// that is not a global setting at all.
63+
pub fn read_global_key(global: &SourcedGlobalConfig, norm_key: &str) -> Option<GlobalKeyValue> {
64+
let strings = |sv: &SourcedValue<Vec<String>>| {
65+
GlobalKeyValue::Set(
66+
toml::Value::Array(sv.value.iter().map(|s| toml::Value::String(s.clone())).collect()),
67+
sv.source,
68+
)
69+
};
70+
let boolean = |sv: &SourcedValue<bool>| GlobalKeyValue::Set(toml::Value::Boolean(sv.value), sv.source);
71+
let optional_string = |slot: &Option<SourcedValue<String>>| match slot {
72+
Some(sv) => GlobalKeyValue::Set(toml::Value::String(sv.value.clone()), sv.source),
73+
None => GlobalKeyValue::Unset,
74+
};
75+
76+
Some(match norm_key {
77+
"enable" => strings(&global.enable),
78+
"disable" => strings(&global.disable),
79+
"include" => strings(&global.include),
80+
"exclude" => strings(&global.exclude),
81+
"extend-enable" => strings(&global.extend_enable),
82+
"extend-disable" => strings(&global.extend_disable),
83+
"fixable" => strings(&global.fixable),
84+
"unfixable" => strings(&global.unfixable),
85+
"respect-gitignore" => boolean(&global.respect_gitignore),
86+
"force-exclude" => boolean(&global.force_exclude),
87+
"cache" => boolean(&global.cache),
88+
"editorconfig" => boolean(&global.editorconfig),
89+
"line-length" => GlobalKeyValue::Set(
90+
toml::Value::Integer(global.line_length.value.get() as i64),
91+
global.line_length.source,
92+
),
93+
"output-format" => optional_string(&global.output_format),
94+
"cache-dir" => optional_string(&global.cache_dir),
95+
"flavor" => GlobalKeyValue::Set(
96+
toml::Value::String(global.flavor.value.to_string()),
97+
global.flavor.source,
98+
),
99+
_ => return None,
100+
})
101+
}
102+
47103
/// Result of applying a candidate global key.
48104
#[derive(Debug)]
49105
pub enum ApplyOutcome {
@@ -204,6 +260,49 @@ mod tests {
204260
assert!(matches!(outcome, ApplyOutcome::Unrecognized));
205261
}
206262

263+
#[test]
264+
fn every_global_key_reads_back() {
265+
// The read half must cover the same key list as the write half, or
266+
// `rumdl config get global.<key>` calls a real setting unknown.
267+
let global = SourcedGlobalConfig::default();
268+
for key in GLOBAL_VALUE_KEYS {
269+
assert!(
270+
read_global_key(&global, key).is_some(),
271+
"key '{key}' is listed but cannot be read back"
272+
);
273+
}
274+
assert!(read_global_key(&global, "not-a-key").is_none());
275+
}
276+
277+
#[test]
278+
fn a_set_value_reads_back_with_its_provenance() {
279+
let (global, _) = apply("line-length", &toml::Value::Integer(120));
280+
let Some(GlobalKeyValue::Set(value, source)) = read_global_key(&global, "line-length") else {
281+
panic!("a set line-length must read back as Set");
282+
};
283+
assert_eq!(value, toml::Value::Integer(120));
284+
assert_eq!(source, ConfigSource::ProjectConfig);
285+
}
286+
287+
#[test]
288+
fn an_unset_optional_key_reads_back_as_unset_not_missing() {
289+
let global = SourcedGlobalConfig::default();
290+
assert!(matches!(
291+
read_global_key(&global, "output-format"),
292+
Some(GlobalKeyValue::Unset)
293+
));
294+
assert!(matches!(
295+
read_global_key(&global, "cache-dir"),
296+
Some(GlobalKeyValue::Unset)
297+
));
298+
299+
let (global, _) = apply("output-format", &toml::Value::String("json".to_string()));
300+
assert!(matches!(
301+
read_global_key(&global, "output-format"),
302+
Some(GlobalKeyValue::Set(toml::Value::String(_), _))
303+
));
304+
}
305+
207306
#[test]
208307
fn applies_values_with_origin() {
209308
let (global, outcome) = apply("line-length", &toml::Value::Integer(120));

0 commit comments

Comments
 (0)