|
| 1 | +//! The settings struct a CLI actually reads. |
| 2 | +//! |
| 3 | +//! The registry is what resolution needs; this is what the code needs. Between them they are the |
| 4 | +//! whole reason the fleet's hand-written key↔field match arms exist — pitchfork writes about three |
| 5 | +//! hundred and thirty lines of them, twice, and five settings still cannot be reached from its own |
| 6 | +//! `settings get`. |
| 7 | +//! |
| 8 | +//! Dotted keys become nested structs, because `settings.task.output` is how the setting reads in |
| 9 | +//! the file and there is no reason for the code to spell it differently. |
| 10 | +
|
| 11 | +use std::collections::BTreeMap; |
| 12 | +use std::fmt::Write as _; |
| 13 | + |
| 14 | +use usage::spec::config::SpecConfigProp; |
| 15 | +use usage::spec::config_type::{Base, SpecConfigType}; |
| 16 | + |
| 17 | +/// A group of settings under a common dotted prefix, which becomes one struct. |
| 18 | +#[derive(Default)] |
| 19 | +struct Group<'a> { |
| 20 | + /// Settings whose key ends here, by their last segment. |
| 21 | + leaves: BTreeMap<&'a str, Leaf<'a>>, |
| 22 | + /// Groups below this one, by their segment. |
| 23 | + groups: BTreeMap<&'a str, Group<'a>>, |
| 24 | +} |
| 25 | + |
| 26 | +struct Leaf<'a> { |
| 27 | + /// The whole dotted key. |
| 28 | + key: &'a str, |
| 29 | + /// The const in `prop`, and the local this is read into. |
| 30 | + ident: &'a str, |
| 31 | + prop: &'a SpecConfigProp, |
| 32 | +} |
| 33 | + |
| 34 | +/// The `Settings` struct, its nested structs, and the one function that reads them. |
| 35 | +pub(crate) fn settings( |
| 36 | + props: &[(&String, &SpecConfigProp)], |
| 37 | + idents: &[String], |
| 38 | + problems: &mut Vec<String>, |
| 39 | +) -> String { |
| 40 | + let mut root = Group::default(); |
| 41 | + for ((key, prop), ident) in props.iter().zip(idents) { |
| 42 | + // An old name is not a field: every read of it folds to the setting that replaced it, so a |
| 43 | + // field for it would be a second name for one value — and `config set old.key` writing to a |
| 44 | + // field nothing reads is exactly the pitchfork bug. |
| 45 | + if prop.renamed_to.is_some() { |
| 46 | + continue; |
| 47 | + } |
| 48 | + let segments: Vec<&str> = key.split('.').collect(); |
| 49 | + let (last, path) = segments.split_last().expect("a key has a segment"); |
| 50 | + let mut group = &mut root; |
| 51 | + for segment in path { |
| 52 | + group = group.groups.entry(segment).or_default(); |
| 53 | + } |
| 54 | + group.leaves.insert(last, Leaf { key, ident, prop }); |
| 55 | + } |
| 56 | + |
| 57 | + check_names(&root, "", problems); |
| 58 | + |
| 59 | + let mut structs = String::new(); |
| 60 | + let mut reads = String::new(); |
| 61 | + let root_body = emit(&root, "Settings", &mut structs, &mut reads); |
| 62 | + |
| 63 | + format!( |
| 64 | + "\n/// Every setting, as the types a CLI holds them in.\n\ |
| 65 | + ///\n\ |
| 66 | + /// Read with [`Settings::read`] from a resolution, which is the only way to build one:\n\ |
| 67 | + /// the values, and every reason one could not be read, come from the merge.\n\ |
| 68 | + #[derive(Debug, Clone, PartialEq)]\n\ |
| 69 | + pub struct Settings {{\n{root_body}}}\n\ |
| 70 | + {structs}\n\ |
| 71 | + impl Settings {{\n \ |
| 72 | + /// This resolution's values, as their types.\n \ |
| 73 | + ///\n \ |
| 74 | + /// Every setting is read before anything is returned, so the error is the whole list of\n \ |
| 75 | + /// what is wrong rather than the first thing found.\n \ |
| 76 | + pub fn read(\n \ |
| 77 | + resolved: &::usage_config::Resolved,\n \ |
| 78 | + ) -> ::std::result::Result<Self, ::usage_config::ReadErrors> {{\n \ |
| 79 | + let mut fold = resolved.fold();\n{reads} \ |
| 80 | + fold.finish()?;\n \ |
| 81 | + ::std::result::Result::Ok(Self {{\n{} }})\n }}\n}}\n", |
| 82 | + construct(&root, "Settings", 3), |
| 83 | + ) |
| 84 | +} |
| 85 | + |
| 86 | +/// One group's fields, its descendants' structs, and the reads that fill them. |
| 87 | +fn emit(group: &Group<'_>, name: &str, structs: &mut String, reads: &mut String) -> String { |
| 88 | + let mut fields = String::new(); |
| 89 | + for (segment, sub) in &group.groups { |
| 90 | + let sub_name = format!("{name}{}", camel(segment)); |
| 91 | + let body = emit(sub, &sub_name, structs, reads); |
| 92 | + let _ = write!( |
| 93 | + structs, |
| 94 | + "\n/// The `{segment}` settings.\n\ |
| 95 | + #[derive(Debug, Clone, PartialEq)]\n\ |
| 96 | + pub struct {sub_name} {{\n{body}}}\n" |
| 97 | + ); |
| 98 | + let _ = writeln!(fields, " pub {}: {sub_name},", field(segment)); |
| 99 | + } |
| 100 | + for (segment, leaf) in &group.leaves { |
| 101 | + let ty = rust_ty(leaf); |
| 102 | + if let Some(help) = leaf.prop.help.as_deref() { |
| 103 | + let _ = writeln!(fields, " /// {}", one_line(help)); |
| 104 | + } |
| 105 | + // The key as well as the help, because the field name is a translation of it and a reader |
| 106 | + // going from code to a config file needs the name the file uses. |
| 107 | + let _ = writeln!(fields, " /// (`{}`)", leaf.key); |
| 108 | + if optional(leaf) { |
| 109 | + let _ = writeln!(fields, " pub {}: Option<{ty}>,", field(segment)); |
| 110 | + let _ = writeln!( |
| 111 | + reads, |
| 112 | + " let {}: Option<{ty}> = fold.optional(prop::{});", |
| 113 | + local(leaf.ident), |
| 114 | + leaf.ident |
| 115 | + ); |
| 116 | + } else { |
| 117 | + let _ = writeln!(fields, " pub {}: {ty},", field(segment)); |
| 118 | + let _ = writeln!( |
| 119 | + reads, |
| 120 | + " let {}: Option<{ty}> = fold.required(prop::{});", |
| 121 | + local(leaf.ident), |
| 122 | + leaf.ident |
| 123 | + ); |
| 124 | + } |
| 125 | + } |
| 126 | + fields |
| 127 | +} |
| 128 | + |
| 129 | +/// The expression that builds one group, once the fold has proved every value read. |
| 130 | +fn construct(group: &Group<'_>, name: &str, depth: usize) -> String { |
| 131 | + let pad = " ".repeat(depth); |
| 132 | + let mut out = String::new(); |
| 133 | + for (segment, sub) in &group.groups { |
| 134 | + // Named, not inferred: a nested group is its own struct, and the name is the same one its |
| 135 | + // declaration got. |
| 136 | + let sub_name = format!("{name}{}", camel(segment)); |
| 137 | + let _ = writeln!(out, "{pad}{}: {sub_name} {{", field(segment)); |
| 138 | + let _ = write!(out, "{}", construct(sub, &sub_name, depth + 1)); |
| 139 | + let _ = writeln!(out, "{pad}}},"); |
| 140 | + } |
| 141 | + for (segment, leaf) in &group.leaves { |
| 142 | + if optional(leaf) { |
| 143 | + let name = field(segment); |
| 144 | + let read_into = local(leaf.ident); |
| 145 | + // `ci` rather than `ci: ci` where the two agree, which they do for every setting whose |
| 146 | + // key has one segment: clippy will not have the long form, and nor should it. |
| 147 | + if name == read_into { |
| 148 | + let _ = writeln!(out, "{pad}{name},"); |
| 149 | + } else { |
| 150 | + let _ = writeln!(out, "{pad}{name}: {read_into},"); |
| 151 | + } |
| 152 | + } else { |
| 153 | + // The unwrap the fold's own contract allows: `required` returns `None` only when it has |
| 154 | + // recorded an error, and `finish` has already turned any error into a return. |
| 155 | + let _ = writeln!( |
| 156 | + out, |
| 157 | + "{pad}{}: {}.expect(\"`{}` has a declared default, so the fold has already reported any absence\"),", |
| 158 | + field(segment), |
| 159 | + local(leaf.ident), |
| 160 | + leaf.key |
| 161 | + ); |
| 162 | + } |
| 163 | + } |
| 164 | + out |
| 165 | +} |
| 166 | + |
| 167 | +/// Whether a field holds an `Option`. |
| 168 | +/// |
| 169 | +/// Two ways to be optional and they mean the same thing to the code: the spec said `option<T>`, or |
| 170 | +/// nothing declared a default, in which case the resolution can perfectly well come back with no |
| 171 | +/// value. Writing the field as `T` would mean a failure at run time for a shape the spec allows. |
| 172 | +fn optional(leaf: &Leaf<'_>) -> bool { |
| 173 | + leaf.prop.default.is_none() && leaf.prop.default_list.is_empty() |
| 174 | + || leaf |
| 175 | + .prop |
| 176 | + .value_type |
| 177 | + .as_ref() |
| 178 | + .is_some_and(SpecConfigType::is_optional) |
| 179 | +} |
| 180 | + |
| 181 | +/// The Rust type for one setting, without the `Option` around it. |
| 182 | +fn rust_ty(leaf: &Leaf<'_>) -> String { |
| 183 | + fn of(ty: &SpecConfigType) -> String { |
| 184 | + match ty { |
| 185 | + SpecConfigType::Base(base) => base_ty(base).to_string(), |
| 186 | + // A `set` is a `Vec` too: the merge has already dropped duplicates, and a list keeps |
| 187 | + // the order the files were read in — which for a `PATH`-like setting is the meaning. |
| 188 | + SpecConfigType::List(inner) | SpecConfigType::Set(inner) => { |
| 189 | + format!("Vec<{}>", of(inner)) |
| 190 | + } |
| 191 | + SpecConfigType::Map(_, value) => { |
| 192 | + format!("::std::collections::BTreeMap<String, {}>", of(value)) |
| 193 | + } |
| 194 | + SpecConfigType::Option(inner) => of(inner), |
| 195 | + // A union is not a Rust type. The value arrives as it was written and the CLI decides, |
| 196 | + // which is what declaring a union asked for. |
| 197 | + SpecConfigType::Union(_) => "::usage_config::Value".to_string(), |
| 198 | + } |
| 199 | + } |
| 200 | + let Some(declared) = leaf.prop.value_type.as_ref() else { |
| 201 | + return "String".to_string(); |
| 202 | + }; |
| 203 | + // Every `Value` this can produce is one the spec asked for: an `object` says its keys are not |
| 204 | + // described, a union says usage cannot decide, and a name usage does not know says the same. So |
| 205 | + // there is nothing to refuse here — the type is as narrow as the declaration was. |
| 206 | + of(declared) |
| 207 | +} |
| 208 | + |
| 209 | +fn base_ty(base: &Base) -> &'static str { |
| 210 | + match base { |
| 211 | + Base::Bool => "bool", |
| 212 | + Base::Int => "i64", |
| 213 | + Base::Uint => "u64", |
| 214 | + Base::Float => "f64", |
| 215 | + Base::String => "String", |
| 216 | + Base::Path => "::std::path::PathBuf", |
| 217 | + // Read as text, both of them. What makes a string a URL is what the CLI does with it, and |
| 218 | + // the crate that owns the duration type owns its spelling — inventing one here would put a |
| 219 | + // dependency in every adopter's binary for a value they may only ever print. |
| 220 | + Base::Url | Base::Duration => "String", |
| 221 | + // A table whose keys the spec does not describe, and a name usage does not know: the value |
| 222 | + // as it was written. |
| 223 | + Base::Object | Base::Custom(_) => "::usage_config::Value", |
| 224 | + } |
| 225 | +} |
| 226 | + |
| 227 | +/// `task` → `Task`, for a nested struct's name. |
| 228 | +fn camel(segment: &str) -> String { |
| 229 | + let mut out = String::with_capacity(segment.len()); |
| 230 | + let mut upper = true; |
| 231 | + for c in segment.chars() { |
| 232 | + if !c.is_alphanumeric() { |
| 233 | + upper = true; |
| 234 | + continue; |
| 235 | + } |
| 236 | + if upper { |
| 237 | + out.extend(c.to_uppercase()); |
| 238 | + upper = false; |
| 239 | + } else { |
| 240 | + out.push(c); |
| 241 | + } |
| 242 | + } |
| 243 | + out |
| 244 | +} |
| 245 | + |
| 246 | +/// A key segment as a field name. |
| 247 | +fn field(segment: &str) -> String { |
| 248 | + let name: String = segment |
| 249 | + .chars() |
| 250 | + .map(|c| if c.is_alphanumeric() { c } else { '_' }) |
| 251 | + .collect(); |
| 252 | + raw(&name) |
| 253 | +} |
| 254 | + |
| 255 | +/// The local a setting is read into, which is its const in lower case. |
| 256 | +fn local(ident: &str) -> String { |
| 257 | + raw(&ident.to_lowercase()) |
| 258 | +} |
| 259 | + |
| 260 | +/// `name`, spelled so it can be an identifier. |
| 261 | +/// |
| 262 | +/// A `let` binding needs this as much as a field does: `match` is an unremarkable name for a |
| 263 | +/// setting, and `let match: Option<String>` is not Rust. |
| 264 | +fn raw(name: &str) -> String { |
| 265 | + if RAW_ALLOWED.contains(&name) { |
| 266 | + return format!("r#{name}"); |
| 267 | + } |
| 268 | + name.to_string() |
| 269 | +} |
| 270 | + |
| 271 | +/// Keywords a field can still be named, spelled `r#`. |
| 272 | +/// |
| 273 | +/// The four that cannot — `self`, `crate`, `super` and `Self` — are refused by name in |
| 274 | +/// [`check_names`], because there is no way to write them. |
| 275 | +const RAW_ALLOWED: [&str; 49] = [ |
| 276 | + "as", |
| 277 | + "break", |
| 278 | + "const", |
| 279 | + "continue", |
| 280 | + "else", |
| 281 | + "enum", |
| 282 | + "extern", |
| 283 | + "false", |
| 284 | + "fn", |
| 285 | + "for", |
| 286 | + "if", |
| 287 | + "impl", |
| 288 | + "in", |
| 289 | + "let", |
| 290 | + "loop", |
| 291 | + "match", |
| 292 | + "mod", |
| 293 | + "move", |
| 294 | + "mut", |
| 295 | + "pub", |
| 296 | + "ref", |
| 297 | + "return", |
| 298 | + "static", |
| 299 | + "struct", |
| 300 | + "trait", |
| 301 | + "true", |
| 302 | + "type", |
| 303 | + "unsafe", |
| 304 | + "use", |
| 305 | + "where", |
| 306 | + "while", |
| 307 | + "async", |
| 308 | + "await", |
| 309 | + "dyn", |
| 310 | + "abstract", |
| 311 | + "become", |
| 312 | + "box", |
| 313 | + "do", |
| 314 | + "final", |
| 315 | + "macro", |
| 316 | + "override", |
| 317 | + "priv", |
| 318 | + "typeof", |
| 319 | + "unsized", |
| 320 | + "virtual", |
| 321 | + "yield", |
| 322 | + "try", |
| 323 | + "gen", |
| 324 | + "macro_rules", |
| 325 | +]; |
| 326 | + |
| 327 | +/// Keywords no identifier can be, raw or otherwise. |
| 328 | +const NEVER_ALLOWED: [&str; 4] = ["self", "crate", "super", "Self"]; |
| 329 | + |
| 330 | +/// Refuse the names that cannot become fields, and the two that would collide. |
| 331 | +fn check_names(group: &Group<'_>, path: &str, problems: &mut Vec<String>) { |
| 332 | + for (segment, leaf) in &group.leaves { |
| 333 | + if NEVER_ALLOWED.contains(segment) { |
| 334 | + problems.push(format!( |
| 335 | + "`{}` cannot be a field: `{segment}` is a keyword Rust has no spelling for", |
| 336 | + leaf.key |
| 337 | + )); |
| 338 | + } |
| 339 | + if group.groups.contains_key(*segment) { |
| 340 | + // `python` as a setting *and* `python.compile` as another: one field name, two things |
| 341 | + // to be. The spec can say it and no struct can hold it. |
| 342 | + problems.push(format!( |
| 343 | + "`{}` is a setting and a group of settings: it cannot be both a value and a table", |
| 344 | + leaf.key |
| 345 | + )); |
| 346 | + } |
| 347 | + } |
| 348 | + for (segment, sub) in &group.groups { |
| 349 | + if NEVER_ALLOWED.contains(segment) { |
| 350 | + problems.push(format!( |
| 351 | + "`{path}{segment}` cannot be a field: `{segment}` is a keyword Rust has no \ |
| 352 | + spelling for" |
| 353 | + )); |
| 354 | + } |
| 355 | + check_names(sub, &format!("{path}{segment}."), problems); |
| 356 | + } |
| 357 | +} |
| 358 | + |
| 359 | +/// Help text as one line, for a doc comment. |
| 360 | +fn one_line(text: &str) -> String { |
| 361 | + text.replace(['\n', '\r'], " ") |
| 362 | +} |