config.rs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // -*- coding: utf-8 -*-
  2. //
  3. // Simple CMS
  4. //
  5. // Copyright (C) 2011-2024 Michael Büsch <m@bues.ch>
  6. //
  7. // Licensed under the Apache License version 2.0
  8. // or the MIT license, at your option.
  9. // SPDX-License-Identifier: Apache-2.0 OR MIT
  10. use crate::numparse::parse_bool;
  11. use anyhow::{self as ah, format_err as err};
  12. use configparser::ini::Ini;
  13. const CONF_PATH: &str = "/opt/cms/etc/cms/backd.conf";
  14. const SECT: &str = "CMS-BACKD";
  15. fn get_debug(ini: &Ini) -> ah::Result<bool> {
  16. if let Some(debug) = ini.get(SECT, "debug") {
  17. return parse_bool(&debug);
  18. }
  19. Ok(false)
  20. }
  21. fn get_domain(ini: &Ini) -> ah::Result<String> {
  22. if let Some(domain) = ini.get(SECT, "domain") {
  23. for c in domain.chars() {
  24. if !c.is_ascii_alphanumeric() && c != '.' && c != '-' {
  25. return Err(err!("'domain' has an invalid value."));
  26. }
  27. }
  28. return Ok(domain);
  29. }
  30. Ok("example.com".to_string())
  31. }
  32. fn get_url_base(ini: &Ini) -> ah::Result<String> {
  33. if let Some(url_base) = ini.get(SECT, "url-base") {
  34. for c in url_base.chars() {
  35. if !c.is_ascii_alphanumeric() && c != '/' && c != '_' && c != '-' {
  36. return Err(err!("'url-base' has an invalid value."));
  37. }
  38. }
  39. return Ok(url_base);
  40. }
  41. Ok("/cms".to_string())
  42. }
  43. pub struct CmsConfig {
  44. debug: bool,
  45. domain: String,
  46. url_base: String,
  47. }
  48. impl CmsConfig {
  49. pub fn new() -> ah::Result<Self> {
  50. let mut ini = Ini::new_cs();
  51. if let Err(e) = ini.load(CONF_PATH) {
  52. return Err(err!("Failed to load configuration {CONF_PATH}: {e}"));
  53. };
  54. let debug = get_debug(&ini)?;
  55. let domain = get_domain(&ini)?;
  56. let url_base = get_url_base(&ini)?;
  57. Ok(Self {
  58. debug,
  59. domain,
  60. url_base,
  61. })
  62. }
  63. pub fn debug(&self) -> bool {
  64. self.debug
  65. }
  66. pub fn domain(&self) -> &str {
  67. &self.domain
  68. }
  69. pub fn url_base(&self) -> &str {
  70. &self.url_base
  71. }
  72. }
  73. // vim: ts=4 sw=4 expandtab