config.rs (51481B)
1 /* 2 This file is part of TALER 3 Copyright (C) 2025-2026 Taler Systems SA 4 5 TALER is free software; you can redistribute it and/or modify it under the 6 terms of the GNU Affero General Public License as published by the Free Software 7 Foundation; either version 3, or (at your option) any later version. 8 9 TALER is distributed in the hope that it will be useful, but WITHOUT ANY 10 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 11 A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. 12 13 You should have received a copy of the GNU Affero General Public License along with 14 TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/> 15 */ 16 17 use std::{ 18 borrow::Cow, fs::Permissions, os::unix::fs::PermissionsExt, path::PathBuf, str::FromStr, 19 sync::Arc, time::Duration, 20 }; 21 22 use compact_str::{CompactString, ToCompactString}; 23 use indexmap::IndexMap; 24 use jiff::{SignedDuration, Span}; 25 use url::Url; 26 27 use crate::types::{ 28 amount::{Amount, Currency}, 29 payto::PaytoURI, 30 validate_base_url, 31 }; 32 33 pub mod parser { 34 use std::{ 35 borrow::Cow, 36 fmt::Display, 37 io::{BufRead, BufReader}, 38 path::PathBuf, 39 str::FromStr, 40 sync::Arc, 41 }; 42 43 use indexmap::IndexMap; 44 use tracing::{trace, warn}; 45 46 use super::Config; 47 use crate::config::{CfgErr, Inner, Line, Location, make_lowercase}; 48 49 fn io_err( 50 action: impl Into<Cow<'static, str>>, 51 path: impl Into<PathBuf>, 52 err: std::io::Error, 53 ) -> CfgErr { 54 CfgErr::IO(action.into(), path.into(), err) 55 } 56 fn line_err( 57 msg: impl Into<Cow<'static, str>>, 58 path: impl Into<PathBuf>, 59 line: usize, 60 ) -> CfgErr { 61 CfgErr::Line(msg.into(), path.into(), line, None) 62 } 63 fn line_cause_err( 64 msg: impl Into<Cow<'static, str>>, 65 cause: impl Display, 66 path: impl Into<PathBuf>, 67 line: usize, 68 ) -> CfgErr { 69 CfgErr::Line(msg.into(), path.into(), line, Some(cause.to_string())) 70 } 71 pub struct Parser { 72 sections: IndexMap<String, IndexMap<String, Line>>, 73 files: Vec<PathBuf>, 74 install_path: PathBuf, 75 buf: String, 76 } 77 78 impl Parser { 79 pub fn empty() -> Self { 80 Self { 81 sections: IndexMap::new(), 82 files: Vec::new(), 83 install_path: PathBuf::new(), 84 buf: String::new(), 85 } 86 } 87 88 pub fn load_env(&mut self, src: ConfigSource) -> Result<(), CfgErr> { 89 let ConfigSource { project_name, .. } = src; 90 91 // Load default path 92 let dir = src 93 .install_path() 94 .map_err(|(p, e)| io_err("find installation path", p, e))?; 95 self.install_path = dir.clone(); 96 97 let paths = IndexMap::from_iter( 98 [ 99 ("PREFIX", dir.join("")), 100 ("BINDIR", dir.join("bin")), 101 ("LIBEXECDIR", dir.join(project_name).join("libexec")), 102 ("DOCDIR", dir.join("share").join("doc").join(project_name)), 103 ("ICONDIR", dir.join("bin").join("share").join("icons")), 104 ("LOCALEDIR", dir.join("share").join("locale")), 105 ("LIBDIR", dir.join("lib").join(project_name)), 106 ("DATADIR", dir.join("share").join(project_name)), 107 ] 108 .map(|(a, b)| { 109 ( 110 a.to_owned(), 111 Line { 112 content: b.to_string_lossy().into_owned(), 113 loc: None, 114 }, 115 ) 116 }), 117 ); 118 self.sections.insert("paths".to_owned(), paths); 119 120 // Load default configs 121 let cfg_dir = dir.join("share").join(project_name).join("config.d"); 122 match std::fs::read_dir(&cfg_dir) { 123 Ok(entries) => { 124 for entry in entries { 125 match entry { 126 Ok(entry) => self.parse_file(entry.path(), 0)?, 127 Err(err) => { 128 warn!(target: "config", "{}", io_err("read base config directory", &cfg_dir, err)); 129 } 130 } 131 } 132 } 133 Err(err) => { 134 warn!(target: "config", "{}", io_err("read base config directory", &cfg_dir, err)) 135 } 136 } 137 138 Ok(()) 139 } 140 141 pub fn parse_str(&mut self, str: &str) -> Result<(), CfgErr> { 142 self.parse( 143 std::io::Cursor::new(str), 144 PathBuf::from_str("mem").unwrap(), 145 0, 146 ) 147 } 148 149 pub fn parse_file(&mut self, src: PathBuf, depth: u8) -> Result<(), CfgErr> { 150 trace!(target: "config", "load file at '{}'", src.to_string_lossy()); 151 match std::fs::File::open(&src) { 152 Ok(file) => self.parse(BufReader::new(file), src, depth + 1), 153 Err(e) => Err(io_err("read config", src, e)), 154 } 155 } 156 157 fn parse<B: BufRead>( 158 &mut self, 159 mut reader: B, 160 src: PathBuf, 161 depth: u8, 162 ) -> Result<(), CfgErr> { 163 let file = self.files.len(); 164 self.files.push(src.clone()); 165 let src = &src; 166 167 let mut current_section: Option<&mut IndexMap<String, Line>> = None; 168 let mut line = 0; 169 170 loop { 171 // Read a new line 172 line += 1; 173 self.buf.clear(); 174 match reader.read_line(&mut self.buf) { 175 Ok(0) => break, 176 Ok(_) => {} 177 Err(e) => return Err(io_err("read config", src, e)), 178 } 179 // Trim whitespace 180 let l = self.buf.trim_ascii(); 181 182 if l.is_empty() || l.starts_with(['#', '%']) { 183 // Skip empty lines and comments 184 continue; 185 } else if let Some(directive) = l.strip_prefix("@") { 186 // Parse directive 187 let Some((name, arg)) = directive.split_once('@') else { 188 return Err(line_err(format!("invalid directive line '{l}'"), src, line)); 189 }; 190 let arg = arg.trim_ascii_start(); 191 // Exit current section 192 current_section = None; 193 // Check current file has a parent 194 let Some(parent) = src.parent() else { 195 return Err(line_err("no parent", src, line)); 196 }; 197 // Check recursion depth 198 if depth > 128 { 199 return Err(line_err("recursion limit in config inlining", src, line)); 200 } 201 202 match make_lowercase(name).as_ref() { 203 "inline" => self.parse_file(parent.join(arg), depth)?, 204 "inline-matching" => { 205 let paths = 206 glob::glob(&parent.join(arg).to_string_lossy()).map_err(|e| { 207 line_cause_err("malformed glob regex", e, src, line) 208 })?; 209 for path in paths { 210 let path = 211 path.map_err(|e| line_cause_err("Glob error", e, src, line))?; 212 self.parse_file(path, depth)?; 213 } 214 } 215 "inline-secret" => { 216 let (section, secret_file) = arg.split_once(" ").ok_or_else(|| 217 line_err( 218 "invalid configuration, @inline-secret@ directive requires exactly two arguments", 219 src, 220 line 221 ) 222 )?; 223 224 let section = section.to_lowercase(); 225 let mut secret_cfg = Parser::empty(); 226 227 if let Err(e) = secret_cfg.parse_file(parent.join(secret_file), depth) { 228 if let CfgErr::IO(_, path, err) = e { 229 warn!(target: "config", "{}", io_err(format!("read secret section [{section}]"), &path, err)) 230 } else { 231 return Err(e); 232 } 233 } else if let Some(mut secret_section) = 234 secret_cfg.sections.swap_remove(§ion) 235 { 236 let file_offset = self.files.len(); 237 self.files.extend(secret_cfg.files); 238 for value in secret_section.values_mut() { 239 if let Some(loc) = &mut value.loc { 240 loc.file += file_offset; 241 } 242 } 243 self.sections 244 .entry(section) 245 .or_default() 246 .extend(secret_section); 247 } else { 248 warn!(target: "config", "{}", line_err(format!("configuration file at '{secret_file}' loaded with @inline-secret@ does not contain section [{section}]"), src, line)); 249 } 250 } 251 unknown => { 252 return Err(line_err( 253 format!("invalid directive '{unknown}'"), 254 src, 255 line, 256 )); 257 } 258 } 259 } else if let Some(section) = l.strip_prefix('[').and_then(|l| l.strip_suffix(']')) 260 { 261 current_section = 262 Some(self.sections.entry(section.to_lowercase()).or_default()); 263 } else if let Some((name, value)) = l.split_once('=') { 264 if let Some(current_section) = &mut current_section { 265 // Trim whitespace 266 let name = name.trim_ascii_end().to_uppercase(); 267 let value = value.trim_ascii_start(); 268 // Escape value 269 let value = 270 if value.len() > 1 && value.starts_with('"') && value.ends_with('"') { 271 &value[1..value.len() - 1] 272 } else { 273 value 274 }; 275 current_section.insert( 276 name, 277 Line { 278 content: value.to_owned(), 279 loc: Some(Location { file, line }), 280 }, 281 ); 282 } else { 283 return Err(line_err("expected section header or directive", src, line)); 284 } 285 } else { 286 return Err(line_err( 287 "expected section header, option assignment or directive", 288 src, 289 line, 290 )); 291 } 292 } 293 Ok(()) 294 } 295 296 /// Get a read-only shareable Config from the parser 297 pub fn finish(self) -> Config { 298 // Convert to a read-only config struct without location info 299 Config(Arc::new(Inner { 300 sections: self.sections, 301 files: self.files, 302 install_path: self.install_path, 303 })) 304 } 305 } 306 307 /** Information about how the configuration is loaded */ 308 #[derive(Debug, Clone, Copy)] 309 pub struct ConfigSource { 310 /** Name of the high-level project */ 311 pub project_name: &'static str, 312 /** Name of the component within the package */ 313 pub component_name: &'static str, 314 /** 315 * Executable name that will be located on $PATH to 316 * find the installation path of the package 317 */ 318 pub exec_name: &'static str, 319 } 320 321 impl ConfigSource { 322 /// Create a new config source 323 pub const fn new( 324 project_name: &'static str, 325 component_name: &'static str, 326 exec_name: &'static str, 327 ) -> Self { 328 Self { 329 project_name, 330 component_name, 331 exec_name, 332 } 333 } 334 335 /// Create a config source where the project, component and exec names are the same 336 pub const fn simple(name: &'static str) -> Self { 337 Self::new(name, name, name) 338 } 339 340 /** 341 * Search the default configuration file path 342 * 343 * I will be the first existing file from this list: 344 * - $XDG_CONFIG_HOME/$componentName.conf 345 * - $HOME/.config/$componentName.conf 346 * - /etc/$componentName.conf 347 * - /etc/$projectName/$componentName.conf 348 * */ 349 fn default_config_path(&self) -> Result<Option<PathBuf>, (PathBuf, std::io::Error)> { 350 // TODO use a generator 351 let conf_name = format!("{}.conf", self.component_name); 352 353 if let Some(xdg) = std::env::var_os("XDG_CONFIG_HOME") { 354 let path = PathBuf::from(xdg).join(&conf_name); 355 match path.try_exists() { 356 Ok(false) => {} 357 Ok(true) => return Ok(Some(path)), 358 Err(e) => return Err((path, e)), 359 } 360 } 361 362 if let Some(home) = std::env::var_os("HOME") { 363 let path = PathBuf::from(home).join(".config").join(&conf_name); 364 match path.try_exists() { 365 Ok(false) => {} 366 Ok(true) => return Ok(Some(path)), 367 Err(e) => return Err((path, e)), 368 } 369 } 370 371 let path = PathBuf::from("/etc").join(&conf_name); 372 match path.try_exists() { 373 Ok(false) => {} 374 Ok(true) => return Ok(Some(path)), 375 Err(e) => return Err((path, e)), 376 } 377 378 let path = PathBuf::from("/etc") 379 .join(self.project_name) 380 .join(&conf_name); 381 match path.try_exists() { 382 Ok(false) => {} 383 Ok(true) => return Ok(Some(path)), 384 Err(e) => return Err((path, e)), 385 } 386 387 Ok(None) 388 } 389 390 /** Search for the binary installation path in PATH */ 391 fn install_path(&self) -> Result<PathBuf, (PathBuf, std::io::Error)> { 392 let path_env = std::env::var("PATH").unwrap_or_default(); 393 for path_dir in path_env.split(':') { 394 let path_dir = PathBuf::from(path_dir); 395 let bin_path = path_dir.join(self.exec_name); 396 if bin_path.exists() 397 && let Some(parent) = path_dir.parent() 398 { 399 return parent.canonicalize().map_err(|e| (parent.to_path_buf(), e)); 400 } 401 } 402 Ok(PathBuf::from("/usr")) 403 } 404 } 405 406 impl Config { 407 /// Load a config for a Taler component, optionally also load from a file. 408 /// This is the standard way to load a Taler component config 409 pub fn load(src: ConfigSource, path: Option<impl Into<PathBuf>>) -> Result<Config, CfgErr> { 410 let mut parser = Parser::empty(); 411 parser.load_env(src)?; 412 match path { 413 Some(path) => parser.parse_file(path.into(), 0)?, 414 None => { 415 if let Some(default) = src 416 .default_config_path() 417 .map_err(|(p, e)| io_err("find default config path", p, e))? 418 { 419 parser.parse_file(default, 0)?; 420 } 421 } 422 } 423 Ok(parser.finish()) 424 } 425 426 /// Load config from an in memory string for testing 427 pub fn from_mem(str: &str) -> Result<Config, CfgErr> { 428 let mut parser = Parser::empty(); 429 parser.parse_str(str)?; 430 Ok(parser.finish()) 431 } 432 433 /// Load config from an in memory string with env from a Taler component for testing 434 pub fn from_mem_with_env(src: ConfigSource, str: &str) -> Result<Config, CfgErr> { 435 let mut parser = Parser::empty(); 436 parser.load_env(src)?; 437 parser.parse_str(str)?; 438 Ok(parser.finish()) 439 } 440 441 /// Load a config for a Taler component, optionally also load from a file and an in memory string, for testing 442 pub fn from_file_override( 443 src: ConfigSource, 444 path: Option<impl Into<PathBuf>>, 445 str: &str, 446 ) -> Result<Config, CfgErr> { 447 let mut parser = Parser::empty(); 448 parser.load_env(src)?; 449 match path { 450 Some(path) => { 451 parser.parse_file(path.into(), 0)?; 452 } 453 None => { 454 if let Some(default) = src 455 .default_config_path() 456 .map_err(|(p, e)| io_err("find default config path", p, e))? 457 { 458 parser.parse_file(default, 0)?; 459 } 460 } 461 } 462 parser.parse_str(str)?; 463 Ok(parser.finish()) 464 } 465 } 466 } 467 468 #[macro_export] 469 macro_rules! config_bail { 470 ($msg:literal $(,)?) => { 471 return Err($crate::config::CfgErr::Custom(format!($msg))) 472 }; 473 ($err:expr $(,)?) => { 474 return Err($crate::config::CfgErr::Custom(format!($err))) 475 }; 476 ($fmt:expr, $($arg:tt)*) => { 477 return Err($crate::config::CfgErr::Custom(format!($fmt, $($arg)*))) 478 }; 479 } 480 481 /// DD102: will fail with exit code 6 and will not be restarted by systemd 482 #[derive(Debug)] 483 pub enum CfgErr { 484 IO(Cow<'static, str>, PathBuf, std::io::Error), 485 Line(Cow<'static, str>, PathBuf, usize, Option<String>), 486 Missing { 487 ty: CompactString, 488 section: CompactString, 489 option: CompactString, 490 }, 491 Invalid { 492 ty: Option<CompactString>, 493 section: CompactString, 494 option: CompactString, 495 err: String, 496 }, 497 Custom(String), 498 } 499 500 impl std::error::Error for CfgErr {} 501 502 impl std::fmt::Display for CfgErr { 503 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 504 match self { 505 CfgErr::IO(action, path, err) => write!( 506 f, 507 "could not {action} at '{}': {}", 508 path.to_string_lossy(), 509 err.kind() 510 ), 511 CfgErr::Line(msg, path, line, cause) => { 512 if let Some(cause) = cause { 513 write!(f, "{msg} at '{}:{line}': {cause}", path.to_string_lossy()) 514 } else { 515 write!(f, "{msg} at '{}:{line}'", path.to_string_lossy()) 516 } 517 } 518 CfgErr::Missing { 519 ty, 520 section, 521 option, 522 } => write!(f, "missing {ty} option {option} in section [{section}]"), 523 CfgErr::Invalid { 524 ty, 525 section, 526 option, 527 err, 528 } => { 529 f.write_str("invalid ")?; 530 if let Some(ty) = ty { 531 write!(f, "{ty} ")?; 532 } 533 write!(f, "option {option} in section [{section}]: {err}") 534 } 535 CfgErr::Custom(e) => e.fmt(f), 536 } 537 } 538 } 539 540 impl CfgErr { 541 pub fn custom(cause: impl std::fmt::Display) -> Self { 542 Self::Custom(cause.to_string()) 543 } 544 } 545 546 #[derive(Debug, thiserror::Error)] 547 pub enum PathsubErr { 548 #[error("recursion limit in path substitution exceeded for '{0}'")] 549 Recursion(String), 550 #[error("unbalanced variable expression '{0}'")] 551 Unbalanced(String), 552 #[error("bad substitution '{0}'")] 553 Substitution(String), 554 #[error("unbound variable '{0}'")] 555 Unbound(String), 556 } 557 558 #[derive(Debug, Clone)] 559 struct Location { 560 file: usize, 561 line: usize, 562 } 563 564 #[derive(Debug, Clone)] 565 struct Line { 566 content: String, 567 loc: Option<Location>, 568 } 569 570 #[derive(Debug)] 571 struct Inner { 572 sections: IndexMap<String, IndexMap<String, Line>>, 573 files: Vec<PathBuf>, 574 install_path: PathBuf, 575 } 576 577 #[derive(Clone)] 578 pub struct Config(Arc<Inner>); 579 580 impl std::fmt::Debug for Config { 581 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 582 self.0.fmt(f) 583 } 584 } 585 586 fn make_lowercase<'a>(s: &'a str) -> Cow<'a, str> { 587 if s.chars().all(|c| c.is_ascii_lowercase()) { 588 Cow::Borrowed(s) 589 } else { 590 Cow::Owned(s.to_ascii_lowercase()) 591 } 592 } 593 594 fn make_uppercase<'a>(s: &'a str) -> Cow<'a, str> { 595 if s.chars().all(|c| c.is_ascii_uppercase()) { 596 Cow::Borrowed(s) 597 } else { 598 Cow::Owned(s.to_ascii_uppercase()) 599 } 600 } 601 602 impl Config { 603 /// Get a config section from its name 604 pub fn section<'cfg, 'arg>(&'cfg self, name: &'arg str) -> Section<'cfg, 'arg> { 605 Section { 606 name, 607 config: self, 608 values: self.0.sections.get(make_lowercase(name).as_ref()), 609 } 610 } 611 612 /// List all config sections 613 pub fn sections<'cfg>(&'cfg self) -> impl Iterator<Item = Section<'cfg, 'cfg>> { 614 self.0.sections.iter().map(|(name, values)| Section { 615 name, 616 config: self, 617 values: Some(values), 618 }) 619 } 620 621 /** 622 * Substitute ${...} and $... placeholders in a string 623 * with values from the PATHS section in the 624 * configuration and environment variables 625 * 626 * This substitution is typically only done for paths. 627 */ 628 pub fn pathsub(&self, str: &str, depth: u8) -> Result<String, PathsubErr> { 629 if depth > 128 { 630 return Err(PathsubErr::Recursion(str.to_owned())); 631 } else if !str.contains('$') { 632 return Ok(str.to_owned()); 633 } 634 635 /** Lookup for variable value from PATHS section in the configuration and environment variables */ 636 fn lookup(cfg: &Config, name: &str, depth: u8) -> Option<Result<String, PathsubErr>> { 637 if let Some(path_res) = cfg 638 .0 639 .sections 640 .get("paths") 641 .and_then(|section| section.get(make_uppercase(name).as_ref())) 642 { 643 return Some(cfg.pathsub(&path_res.content, depth + 1)); 644 } 645 646 if let Ok(val) = std::env::var(name) { 647 return Some(Ok(val)); 648 } 649 None 650 } 651 652 let mut result = String::new(); 653 let mut remaining = str; 654 loop { 655 // Look for the next variable 656 let Some((normal, value)) = remaining.split_once('$') else { 657 result.push_str(remaining); 658 return Ok(result); 659 }; 660 661 // Append normal character 662 result.push_str(normal); 663 remaining = value; 664 665 // Check if variable is enclosed 666 let is_enclosed = if let Some(enclosed) = remaining.strip_prefix('{') { 667 // ${var 668 remaining = enclosed; 669 true 670 } else { 671 false // $var 672 }; 673 674 // Extract variable name 675 let name_end = remaining 676 .find(|c: char| !c.is_alphanumeric() && c != '_') 677 .unwrap_or(remaining.len()); 678 let (name, after_name) = remaining.split_at(name_end); 679 680 // Extract variable default if enclosed 681 let default = if !is_enclosed { 682 remaining = after_name; 683 None 684 } else if let Some(after_enclosed) = after_name.strip_prefix('}') { 685 // ${var} 686 remaining = after_enclosed; 687 None 688 } else if let Some(default) = after_name.strip_prefix(":-") { 689 // ${var:-default} 690 let mut depth = 1; 691 let Some((default, after_default)) = default.split_once(|c| { 692 if c == '{' { 693 depth += 1; 694 false 695 } else if c == '}' { 696 depth -= 1; 697 depth == 0 698 } else { 699 false 700 } 701 }) else { 702 return Err(PathsubErr::Unbalanced(default.to_owned())); 703 }; 704 remaining = after_default; 705 Some(default) 706 } else { 707 return Err(PathsubErr::Substitution(after_name.to_owned())); 708 }; 709 if let Some(resolved) = lookup(self, name, depth + 1) { 710 result.push_str(&resolved?); 711 continue; 712 } else if let Some(default) = default { 713 let resolved = self.pathsub(default, depth + 1)?; 714 result.push_str(&resolved); 715 continue; 716 } 717 return Err(PathsubErr::Unbound(name.to_owned())); 718 } 719 } 720 721 /// Print config in a human format, optionally with diagnostics information 722 pub fn print(&self, mut f: impl std::io::Write, diagnostics: bool) -> std::io::Result<()> { 723 let Inner { 724 sections, 725 files, 726 install_path, 727 } = self.0.as_ref(); 728 if diagnostics { 729 writeln!(f, "#")?; 730 writeln!(f, "# Configuration file diagnostics")?; 731 writeln!(f, "#")?; 732 writeln!(f, "# File Loaded:")?; 733 for path in files { 734 writeln!(f, "# {}", path.to_string_lossy())?; 735 } 736 writeln!(f, "#")?; 737 writeln!(f, "# Installation path: {}", install_path.to_string_lossy())?; 738 writeln!(f, "#")?; 739 writeln!(f)?; 740 } 741 for (sect, values) in sections { 742 writeln!(f, "[{sect}]")?; 743 if diagnostics { 744 writeln!(f)?; 745 } 746 for (key, Line { content, loc }) in values { 747 if diagnostics { 748 match loc { 749 Some(Location { file, line }) => { 750 let path = &files[*file]; 751 writeln!(f, "# {}:{line}", path.to_string_lossy())?; 752 } 753 None => writeln!(f, "# default")?, 754 } 755 } 756 writeln!(f, "{key} = {content}")?; 757 if diagnostics { 758 writeln!(f)?; 759 } 760 } 761 writeln!(f)?; 762 } 763 Ok(()) 764 } 765 } 766 767 /** Accessor/Converter for Taler-like configuration sections */ 768 pub struct Section<'cfg, 'arg> { 769 pub name: &'arg str, 770 config: &'cfg Config, 771 values: Option<&'cfg IndexMap<String, Line>>, 772 } 773 774 #[macro_export] 775 macro_rules! map_config { 776 ($self:expr, $ty:expr, $option:expr, $($key:expr => $parse:block),*$(,)?) => { 777 { 778 let keys = &[$($key,)*]; 779 $self.map($ty, $option, |value| { 780 match value { 781 $($key => { 782 (||Ok($parse))().map_err(|e| $crate::config::MapErr::Err(e)) 783 })*, 784 _ => Err($crate::config::MapErr::Invalid(keys)) 785 } 786 }) 787 } 788 } 789 } 790 791 pub use map_config; 792 793 #[doc(hidden)] 794 pub enum MapErr { 795 Invalid(&'static [&'static str]), 796 Err(CfgErr), 797 } 798 799 impl<'cfg, 'arg> Section<'cfg, 'arg> { 800 /// Report a logical validation error for an option in this section. 801 pub fn invalid(&self, option: &str, err: impl std::fmt::Display) -> CfgErr { 802 CfgErr::Invalid { 803 ty: None, 804 section: self.name.to_compact_string().to_lowercase(), 805 option: option.to_compact_string().to_uppercase(), 806 err: err.to_string(), 807 } 808 } 809 810 #[doc(hidden)] 811 fn inner<T>( 812 &self, 813 ty: &'arg str, 814 option: &'arg str, 815 transform: impl FnOnce(&'cfg str) -> Result<T, CfgErr>, 816 ) -> Value<'arg, T> { 817 let value = self 818 .values 819 .and_then(|m| m.get(make_uppercase(option).as_ref())) 820 .filter(|it| !it.content.is_empty()) 821 .map(|raw| transform(&raw.content)) 822 .transpose(); 823 Value { 824 value, 825 option, 826 ty, 827 section: self.name, 828 } 829 } 830 831 #[doc(hidden)] 832 pub fn map<T>( 833 &self, 834 ty: &'arg str, 835 option: &'arg str, 836 transform: impl FnOnce(&'cfg str) -> Result<T, MapErr>, 837 ) -> Value<'arg, T> { 838 self.inner(ty, option, |v| { 839 transform(v).map_err(|e| match e { 840 MapErr::Invalid(keys) => { 841 let mut buf = "expected '".to_owned(); 842 match keys { 843 [] => unreachable!("you must provide at least one mapping"), 844 [unique] => buf.push_str(unique), 845 [first, other @ .., last] => { 846 buf.push_str(first); 847 for k in other { 848 buf.push_str("', '"); 849 buf.push_str(k); 850 } 851 buf.push_str("' or '"); 852 buf.push_str(last); 853 } 854 } 855 buf.push_str("' got '"); 856 buf.push_str(v); 857 buf.push('\''); 858 CfgErr::Invalid { 859 ty: Some(ty.to_compact_string()), 860 section: self.name.to_compact_string().to_lowercase(), 861 option: option.to_compact_string().to_uppercase(), 862 err: buf, 863 } 864 } 865 MapErr::Err(e) => e, 866 }) 867 }) 868 } 869 870 /** Setup an accessor/converted for a [type] at [option] using [transform] */ 871 pub fn value<T, E: std::fmt::Display>( 872 &self, 873 ty: &'arg str, 874 option: &'arg str, 875 transform: impl FnOnce(&'cfg str) -> Result<T, E>, 876 ) -> Value<'arg, T> { 877 self.inner(ty, option, |v| { 878 transform(v).map_err(|e| CfgErr::Invalid { 879 ty: Some(ty.to_compact_string()), 880 section: self.name.to_compact_string().to_lowercase(), 881 option: option.to_compact_string().to_uppercase(), 882 err: e.to_string(), 883 }) 884 }) 885 } 886 887 /** Access [option] as a parsable type */ 888 pub fn parse<E: std::fmt::Display, T: FromStr<Err = E>>( 889 &self, 890 ty: &'arg str, 891 option: &'arg str, 892 ) -> Value<'arg, T> { 893 self.value(ty, option, |it| it.parse::<T>().map_err(|e| e.to_string())) 894 } 895 896 /** Access [option] as str */ 897 pub fn str(&self, option: &'arg str) -> Value<'arg, String> { 898 self.value("string", option, |it| Ok::<_, &str>(it.to_owned())) 899 } 900 901 /** Access [option] as compact str */ 902 pub fn cstr(&self, option: &'arg str) -> Value<'arg, CompactString> { 903 self.value("string", option, |it| Ok::<_, CompactString>(it.into())) 904 } 905 906 /** Access [option] as hex encode bytes */ 907 pub fn hex(&self, option: &'arg str) -> Value<'arg, Vec<u8>> { 908 self.value("hex", option, |it| { 909 crate::encoding::hex::decode(it.as_bytes()) 910 }) 911 } 912 913 /** Access [option] as base32 encode bytes */ 914 pub fn b32(&self, option: &'arg str) -> Value<'arg, Vec<u8>> { 915 self.value("b32", option, |it| { 916 crate::encoding::base32::decode(it.as_bytes()) 917 }) 918 } 919 920 /** Access [option] as base64 encode bytes */ 921 pub fn b64(&self, option: &'arg str) -> Value<'arg, Vec<u8>> { 922 self.value("b64", option, |it| { 923 crate::encoding::base64::decode(it.as_bytes()) 924 }) 925 } 926 927 /** Access [option] as path */ 928 pub fn path(&self, option: &'arg str) -> Value<'arg, String> { 929 self.value("path", option, |it| self.config.pathsub(it, 0)) 930 } 931 932 /** Access [option] as UNIX permissions */ 933 pub fn unix_mode(&self, option: &'arg str) -> Value<'arg, Permissions> { 934 self.value("unix mode", option, |it| { 935 u32::from_str_radix(it, 8) 936 .map(Permissions::from_mode) 937 .map_err(|_| format!("'{it}' not a valid number")) 938 }) 939 } 940 941 /** Access [option] as a number */ 942 pub fn number<T: FromStr>(&self, option: &'arg str) -> Value<'arg, T> { 943 self.value("number", option, |it| { 944 it.parse::<T>() 945 .map_err(|_| format!("'{it}' not a valid number")) 946 }) 947 } 948 949 /** Access [option] as Boolean */ 950 pub fn boolean(&self, option: &'arg str) -> Value<'arg, bool> { 951 self.value("boolean", option, |it| match it.to_uppercase().as_str() { 952 "YES" => Ok(true), 953 "NO" => Ok(false), 954 _ => Err(format!("expected 'YES' or 'NO' got '{it}'")), 955 }) 956 } 957 958 /** Access [option] as a Currency */ 959 pub fn currency(&self, option: &'arg str) -> Value<'arg, Currency> { 960 self.parse("currency", option) 961 } 962 963 /** Access [option] as an Amount */ 964 pub fn amount(&self, option: &'arg str, currency: &Currency) -> Value<'arg, Amount> { 965 self.value("amount", option, |it| { 966 let amount = it.parse::<Amount>().map_err(|e| e.to_string())?; 967 if amount.currency != *currency { 968 return Err(format!( 969 "expected currency {currency} got {}", 970 amount.currency 971 )); 972 } 973 Ok(amount) 974 }) 975 } 976 977 /** Access [option] as url */ 978 pub fn url(&self, option: &'arg str) -> Value<'arg, Url> { 979 self.parse("url", option) 980 } 981 982 /** Access [option] as base url */ 983 pub fn base_url(&self, option: &'arg str) -> Value<'arg, Url> { 984 self.value("url", option, |s| { 985 let url = Url::from_str(s).map_err(|e| e.to_string())?; 986 validate_base_url(&url)?; 987 Ok::<_, String>(url) 988 }) 989 } 990 991 /** Access [option] as payto */ 992 pub fn payto(&self, option: &'arg str) -> Value<'arg, PaytoURI> { 993 self.parse("payto", option) 994 } 995 996 /** Access [option] as Postgres URI */ 997 pub fn postgres(&self, option: &'arg str) -> Value<'arg, sqlx::postgres::PgConnectOptions> { 998 self.parse("Postgres URI", option) 999 } 1000 1001 /** Access [option] as a timestamp */ 1002 pub fn timestamp(&self, option: &'arg str) -> Value<'arg, jiff::Timestamp> { 1003 self.parse("Timestamp", option) 1004 } 1005 1006 /** Access [option] as a time */ 1007 pub fn time(&self, option: &'arg str) -> Value<'arg, jiff::civil::Time> { 1008 self.parse("Time", option) 1009 } 1010 1011 /** Access [option] as a date */ 1012 pub fn date(&self, option: &'arg str) -> Value<'arg, jiff::civil::Date> { 1013 self.parse("Date", option) 1014 } 1015 1016 /** Access [option] as a duration */ 1017 pub fn duration(&self, option: &'arg str) -> Value<'arg, Duration> { 1018 self.value("temporal", option, |it| { 1019 let tmp = SignedDuration::from_str(it).map_err(|e| e.to_string())?; 1020 if tmp < SignedDuration::ZERO { 1021 return Err("temporal must not be negative".to_owned()); 1022 } 1023 let millis = 1024 u64::try_from(tmp.as_millis()).map_err(|_| "temporal overflow".to_owned())?; 1025 Ok::<_, String>(Duration::from_millis(millis)) 1026 }) 1027 } 1028 1029 /** Access [option] as a duration */ 1030 pub fn span(&self, option: &'arg str) -> Value<'arg, Span> { 1031 self.parse("temporal", option) 1032 } 1033 1034 /** Access [option] as a regex */ 1035 pub fn regex(&self, option: &'arg str) -> Value<'arg, regex::Regex> { 1036 self.parse("Pattern", option) 1037 } 1038 1039 /** Access option as json object */ 1040 pub fn json<'de, T: serde::Deserialize<'de>>(&'de self, option: &'arg str) -> Value<'arg, T> { 1041 self.value("json", option, |it| serde_json::from_str(it)) 1042 } 1043 } 1044 1045 pub struct Value<'arg, T> { 1046 value: Result<Option<T>, CfgErr>, 1047 option: &'arg str, 1048 ty: &'arg str, 1049 section: &'arg str, 1050 } 1051 1052 impl<T> Value<'_, T> { 1053 pub fn opt(self) -> Result<Option<T>, CfgErr> { 1054 self.value 1055 } 1056 1057 /** Converted value of default if missing */ 1058 pub fn default(self, default: T) -> Result<T, CfgErr> { 1059 Ok(self.value?.unwrap_or(default)) 1060 } 1061 1062 /** Converted value or throw if missing */ 1063 pub fn require(self) -> Result<T, CfgErr> { 1064 self.value?.ok_or_else(|| CfgErr::Missing { 1065 ty: self.ty.to_compact_string(), 1066 section: self.section.to_compact_string().to_lowercase(), 1067 option: self.option.to_compact_string().to_uppercase(), 1068 }) 1069 } 1070 } 1071 1072 #[cfg(test)] 1073 mod test { 1074 use std::{ 1075 fmt::{Debug, Display}, 1076 fs::{File, Permissions}, 1077 os::unix::fs::PermissionsExt, 1078 time::Duration, 1079 }; 1080 1081 use tracing::error; 1082 1083 use super::{Config, Section, Value}; 1084 use crate::{ 1085 config::parser::ConfigSource, 1086 types::amount::{self, Currency}, 1087 }; 1088 1089 const SOURCE: ConfigSource = ConfigSource::new("test", "test", "test"); 1090 1091 #[track_caller] 1092 fn check_err<T: Debug, E: Display>(err: impl AsRef<str>, lambda: Result<T, E>) { 1093 let failure = lambda.unwrap_err(); 1094 let fmt = failure.to_string(); 1095 assert_eq!(err.as_ref(), fmt); 1096 } 1097 1098 /// [`check_err`] for messages with an environment-dependent middle: only 1099 /// the head and the tail are compared. 1100 #[track_caller] 1101 fn check_err_loose<T: Debug, E: Display>( 1102 head: impl AsRef<str>, 1103 tail: impl AsRef<str>, 1104 lambda: Result<T, E>, 1105 ) { 1106 let failure = lambda.unwrap_err(); 1107 let fmt = failure.to_string(); 1108 let (head, tail) = (head.as_ref(), tail.as_ref()); 1109 assert!( 1110 fmt.starts_with(head) && fmt.ends_with(tail), 1111 "expected an error starting with '{head}' and ending with '{tail}', got '{fmt}'" 1112 ); 1113 } 1114 1115 #[test] 1116 fn fs() { 1117 let dir = tempfile::tempdir().unwrap(); 1118 let config_path = dir.path().join("test-conf.conf"); 1119 let second_path = dir.path().join("test-second-conf.conf"); 1120 1121 let config_path_fmt = config_path.to_string_lossy(); 1122 let second_path_fmt = second_path.to_string_lossy(); 1123 1124 let check_err = |err: String| check_err(err, Config::load(SOURCE, Some(&config_path))); 1125 let check_ok = || Config::load(SOURCE, Some(&config_path)).unwrap(); 1126 1127 check_err(format!( 1128 "could not read config at '{config_path_fmt}': entity not found" 1129 )); 1130 1131 let config_file = std::fs::File::create_new(&config_path).unwrap(); 1132 config_file 1133 .set_permissions(Permissions::from_mode(0o222)) 1134 .unwrap(); 1135 if File::open(&config_path).is_ok() { 1136 error!("Cannot finish this test if root"); 1137 return; 1138 } 1139 check_err(format!( 1140 "could not read config at '{config_path_fmt}': permission denied" 1141 )); 1142 1143 config_file 1144 .set_permissions(Permissions::from_mode(0o666)) 1145 .unwrap(); 1146 check_ok(); 1147 std::fs::write(&config_path, "@inline@ test-second-conf.conf").unwrap(); 1148 check_err(format!( 1149 "could not read config at '{second_path_fmt}': entity not found" 1150 )); 1151 1152 let second_file = std::fs::File::create_new(&second_path).unwrap(); 1153 second_file 1154 .set_permissions(Permissions::from_mode(0o222)) 1155 .unwrap(); 1156 check_err(format!( 1157 "could not read config at '{second_path_fmt}': permission denied" 1158 )); 1159 1160 std::fs::write(&config_path, "@inline-matching@[*").unwrap(); 1161 // glob reports the offset of the '[' within the *expanded* pattern 1162 // (<tempdir>/[*), so the position moves with the length of $TMPDIR. 1163 check_err_loose( 1164 format!( 1165 "malformed glob regex at '{config_path_fmt}:1': Pattern syntax error near position " 1166 ), 1167 ": invalid range pattern", 1168 Config::load(SOURCE, Some(&config_path)), 1169 ); 1170 1171 std::fs::write(&config_path, "@inline-matching@*second-conf.conf").unwrap(); 1172 check_err(format!( 1173 "could not read config at '{second_path_fmt}': permission denied" 1174 )); 1175 1176 std::fs::write(&config_path, "\n@inline-matching@*.conf").unwrap(); 1177 check_err(format!( 1178 "recursion limit in config inlining at '{config_path_fmt}:2'" 1179 )); 1180 std::fs::write(&config_path, "\n\n@inline-matching@ *.conf").unwrap(); 1181 check_err(format!( 1182 "recursion limit in config inlining at '{config_path_fmt}:3'" 1183 )); 1184 1185 std::fs::write(&config_path, "@inline-secret@ secret test-second-conf.conf").unwrap(); 1186 check_ok(); 1187 } 1188 1189 #[test] 1190 fn inline_secret_diagnostics() { 1191 let dir = tempfile::tempdir().unwrap(); 1192 let main_path = dir.path().join("main.conf"); 1193 let secret_path = dir.path().join("secret.conf"); 1194 let extra_path = dir.path().join("extra.conf"); 1195 1196 std::fs::write(&main_path, "[a]\nX = 1\n@inline-secret@ s secret.conf\n").unwrap(); 1197 std::fs::write(&secret_path, "[s]\nKEY = k\n@inline@ extra.conf\n").unwrap(); 1198 std::fs::write(&extra_path, "[s]\n\n# Extra setting\n\nEXTRA = value\n").unwrap(); 1199 1200 let mut parser = super::parser::Parser::empty(); 1201 parser.parse_file(main_path.clone(), 0).unwrap(); 1202 let mut output = Vec::new(); 1203 parser.finish().print(&mut output, true).unwrap(); 1204 let output = String::from_utf8(output).unwrap(); 1205 1206 let main = main_path.display(); 1207 let secret = secret_path.display(); 1208 let extra = extra_path.display(); 1209 assert_eq!( 1210 output, 1211 format!( 1212 "#\n\ 1213 # Configuration file diagnostics\n\ 1214 #\n\ 1215 # File Loaded:\n\ 1216 # {main}\n\ 1217 # {secret}\n\ 1218 # {extra}\n\ 1219 #\n\ 1220 # Installation path: \n\ 1221 #\n\n\ 1222 [a]\n\n\ 1223 # {main}:2\n\ 1224 X = 1\n\n\n\ 1225 [s]\n\n\ 1226 # {secret}:2\n\ 1227 KEY = k\n\n\ 1228 # {extra}:5\n\ 1229 EXTRA = value\n\n\n" 1230 ) 1231 ); 1232 } 1233 1234 #[test] 1235 fn parsing() { 1236 let check = |err: &str, content: &str| check_err(err, Config::from_mem(content)); 1237 1238 check( 1239 "expected section header, option assignment or directive at 'mem:1'", 1240 "syntax error", 1241 ); 1242 check( 1243 "expected section header or directive at 'mem:1'", 1244 "key=value", 1245 ); 1246 check( 1247 "expected section header, option assignment or directive at 'mem:2'", 1248 "[section]\nbad-line", 1249 ); 1250 1251 let cfg = Config::from_mem( 1252 r#" 1253 1254 [section-a] 1255 1256 bar = baz 1257 1258 [section-b] 1259 1260 first_value = 1 1261 second_value = "test" 1262 1263 "#, 1264 ) 1265 .unwrap(); 1266 1267 // Missing section 1268 check_err( 1269 "missing string option VALUE in section [unknown]", 1270 cfg.section("unknown").str("value").require(), 1271 ); 1272 1273 // Missing value 1274 check_err( 1275 "missing string option VALUE in section [section-a]", 1276 cfg.section("section-a").str("value").require(), 1277 ); 1278 } 1279 1280 #[allow(clippy::type_complexity)] 1281 fn routine<T: Debug + Eq>( 1282 ty: &str, 1283 mut lambda: impl for<'cfg, 'arg> FnMut(&Section<'cfg, 'arg>, &'arg str) -> Value<'arg, T>, 1284 wellformed: &[(&[&str], T)], 1285 malformed: &[(&[&str], fn(&str) -> String)], 1286 ) { 1287 let conf = |content: &str| { 1288 Config::from_mem(&format!( 1289 "[PATHS]\nDATADIR=mydir\nRECURSIVE=$RECURSIVE\n{content}" 1290 )) 1291 .unwrap() 1292 }; 1293 1294 // Check missing msg 1295 let cfg = conf(""); 1296 check_err( 1297 format!("missing {ty} option VALUE in section [section]"), 1298 lambda(&cfg.section("section"), "value").require(), 1299 ); 1300 1301 // Check wellformed options are properly parsed 1302 for (raws, expected) in wellformed { 1303 for raw in *raws { 1304 let cfg = conf(&format!("[section]\nvalue={raw}")); 1305 assert_eq!( 1306 *expected, 1307 lambda(&cfg.section("section"), "value").require().unwrap() 1308 ); 1309 } 1310 } 1311 1312 // Check malformed options have proper error message 1313 for (raws, error_fmt) in malformed { 1314 for raw in *raws { 1315 let cfg = conf(&format!("[section]\nvalue={raw}")); 1316 check_err( 1317 format!( 1318 "invalid {ty} option VALUE in section [section]: {}", 1319 error_fmt(raw) 1320 ), 1321 lambda(&cfg.section("section"), "value").require(), 1322 ) 1323 } 1324 } 1325 } 1326 1327 #[test] 1328 fn string() { 1329 routine( 1330 "string", 1331 |sect, value| sect.str(value), 1332 &[ 1333 (&["1", "\"1\""], "1".to_owned()), 1334 (&["test", "\"test\""], "test".to_owned()), 1335 (&["\""], "\"".to_owned()), 1336 ], 1337 &[], 1338 ); 1339 } 1340 1341 #[test] 1342 fn path() { 1343 routine( 1344 "path", 1345 |sect, value| sect.path(value), 1346 &[ 1347 (&["path"], "path".to_owned()), 1348 ( 1349 &["foo/$DATADIR/bar", "foo/${DATADIR}/bar"], 1350 "foo/mydir/bar".to_owned(), 1351 ), 1352 ( 1353 &["foo/$DATADIR$DATADIR/bar"], 1354 "foo/mydirmydir/bar".to_owned(), 1355 ), 1356 ( 1357 &["foo/pre_$DATADIR/bar", "foo/pre_${DATADIR}/bar"], 1358 "foo/pre_mydir/bar".to_owned(), 1359 ), 1360 ( 1361 &[ 1362 "foo/${DATADIR}_next/bar", 1363 "foo/${UNKNOWN:-$DATADIR}_next/bar", 1364 ], 1365 "foo/mydir_next/bar".to_owned(), 1366 ), 1367 ( 1368 &[ 1369 "foo/${UNKNOWN:-default}_next/bar", 1370 "foo/${UNKNOWN:-${UNKNOWN:-default}}_next/bar", 1371 ], 1372 "foo/default_next/bar".to_owned(), 1373 ), 1374 ( 1375 &["foo/${UNKNOWN:-pre_${UNKNOWN:-default}_next}_next/bar"], 1376 "foo/pre_default_next_next/bar".to_owned(), 1377 ), 1378 ], 1379 &[ 1380 (&["foo/${A/bar"], |_| "bad substitution '/bar'".to_owned()), 1381 (&["foo/${A:-pre_${B}/bar"], |_| { 1382 "unbalanced variable expression 'pre_${B}/bar'".to_owned() 1383 }), 1384 (&["foo/${A:-${B${C}/bar"], |_| { 1385 "unbalanced variable expression '${B${C}/bar'".to_owned() 1386 }), 1387 (&["foo/$UNKNOWN/bar", "foo/${UNKNOWN}/bar"], |_| { 1388 "unbound variable 'UNKNOWN'".to_owned() 1389 }), 1390 (&["foo/$RECURSIVE/bar"], |_| { 1391 "recursion limit in path substitution exceeded for '$RECURSIVE'".to_owned() 1392 }), 1393 ], 1394 ) 1395 } 1396 1397 #[test] 1398 fn number() { 1399 routine( 1400 "number", 1401 |sect, value| sect.number(value), 1402 &[(&["1"], 1), (&["42"], 42)], 1403 &[(&["true", "YES"], |it| format!("'{it}' not a valid number"))], 1404 ); 1405 } 1406 1407 #[test] 1408 fn boolean() { 1409 routine( 1410 "boolean", 1411 |sect, value| sect.boolean(value), 1412 &[(&["yes", "YES", "Yes"], true), (&["no", "NO", "No"], false)], 1413 &[(&["true", "1"], |it| { 1414 format!("expected 'YES' or 'NO' got '{it}'") 1415 })], 1416 ); 1417 } 1418 1419 #[test] 1420 fn amount() { 1421 routine( 1422 "amount", 1423 |sect, value| sect.amount(value, &Currency::KUDOS), 1424 &[( 1425 &["KUDOS:12", "KUDOS:12.0", "KUDOS:012.0"], 1426 amount::amount("KUDOS:12"), 1427 )], 1428 &[ 1429 (&["test", "42"], |it| { 1430 format!("amount '{it}' invalid format") 1431 }), 1432 (&["KUDOS:0.3ABC"], |it| { 1433 format!("amount '{it}' invalid fraction (invalid digit found in string)") 1434 }), 1435 (&["KUDOS:999999999999999999"], |it| { 1436 format!("amount '{it}' value overflow (must be <= 4503599627370496)") 1437 }), 1438 (&["EUR:12"], |_| { 1439 "expected currency KUDOS got EUR".to_owned() 1440 }), 1441 ], 1442 ) 1443 } 1444 1445 #[test] 1446 fn duration() { 1447 routine( 1448 "temporal", 1449 |sect, value| sect.duration(value), 1450 &[(&["1.5s", "1500ms"], Duration::from_secs_f64(1.5))], 1451 &[(&["-1s", "-1ns"], |_| { 1452 "temporal must not be negative".to_string() 1453 })], 1454 ) 1455 } 1456 1457 #[test] 1458 fn map() { 1459 #[derive(Debug, PartialEq, Eq)] 1460 enum Mode { 1461 Tcp(u16), 1462 Unix, 1463 Systemd, 1464 } 1465 1466 fn parse<'cfg, 'arg>(sect: &Section<'cfg, 'arg>, value: &'arg str) -> Value<'arg, Mode> { 1467 map_config!(sect, "mode", value, 1468 "tcp" => { Mode::Tcp(sect.number("PORT").require()?) }, 1469 "unix" => { Mode::Unix }, 1470 "systemd" => { Mode::Systemd }, 1471 ) 1472 } 1473 1474 routine( 1475 "mode", 1476 parse, 1477 &[(&["unix"], Mode::Unix), (&["systemd"], Mode::Systemd)], 1478 &[(&["udp", "TCP"], |it| { 1479 format!("expected 'tcp', 'unix' or 'systemd' got '{it}'") 1480 })], 1481 ); 1482 1483 let cfg = Config::from_mem("[section]\nvalue=tcp").unwrap(); 1484 1485 check_err( 1486 "missing number option PORT in section [section]", 1487 parse(&cfg.section("section"), "value").require(), 1488 ); 1489 1490 check_err( 1491 "invalid mode option VALUE in section [section]: expected 'unix' got 'tcp'", 1492 map_config!(&cfg.section("section"), "mode", "value", 1493 "unix" => { Mode::Unix }, 1494 ) 1495 .require(), 1496 ); 1497 } 1498 }