aboutsummaryrefslogtreecommitdiffstats
path: root/letmein-conf/src/ini.rs
blob: 861342c83e72527bb5737603159de80dd322f444 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
// -*- coding: utf-8 -*-
//
// Copyright (C) 2024 Michael Büsch <m@bues.ch>
//
// Licensed under the Apache License version 2.0
// or the MIT license, at your option.
// SPDX-License-Identifier: Apache-2.0 OR MIT

use anyhow::{self as ah, format_err as err, Context as _};
use std::{
    collections::{hash_map, HashMap},
    io::Read as _,
    path::Path,
};

pub type IniSectionIter<'a> = hash_map::Iter<'a, String, String>;

/// All options from a `.ini` file section.
struct IniSection {
    options: HashMap<String, String>,
}

impl IniSection {
    fn new() -> Self {
        Self {
            options: HashMap::new(),
        }
    }

    fn options(&self) -> &HashMap<String, String> {
        &self.options
    }

    fn options_mut(&mut self) -> &mut HashMap<String, String> {
        &mut self.options
    }

    fn iter(&self) -> IniSectionIter {
        self.options.iter()
    }
}

/// Simple `.ini` file parser.
pub struct Ini {
    sections: HashMap<String, IniSection>,
}

impl Ini {
    pub fn new() -> Self {
        Self {
            sections: HashMap::new(),
        }
    }

    pub fn new_from_file(path: &Path) -> ah::Result<Self> {
        let mut this = Self::new();
        this.read_file(path)?;
        Ok(this)
    }

    pub fn read_file(&mut self, path: &Path) -> ah::Result<()> {
        let mut file = std::fs::OpenOptions::new()
            .read(true)
            .open(path)
            .context("Open configuration file")?;
        let mut buf = vec![];
        file.read_to_end(&mut buf)
            .context("Read configuration file")?;
        self.parse_bytes(buf)
    }

    pub fn parse_bytes(&mut self, content: Vec<u8>) -> ah::Result<()> {
        self.parse_str(
            &String::from_utf8(content)
                .context("Configuration content file to UTF-8 conversion")?,
        )
    }

    pub fn parse_str(&mut self, content: &str) -> ah::Result<()> {
        let mut sections = HashMap::new();
        let mut in_section = None;
        for line in content.lines() {
            let line = line.trim_start();
            if line.is_empty() {
                continue; // This is an empty line.
            }
            if line.starts_with('#') {
                continue; // This is a comment.
            }
            // Section start?
            if line.starts_with('[') {
                let line = line.trim_end();
                if line.ends_with(']') {
                    let begin_chlen = '['.len_utf8();
                    let end_chlen = ']'.len_utf8();
                    let sname = &line[begin_chlen..line.len() - end_chlen];
                    if sname.is_empty() {
                        return Err(err!("Section name is empty: '{line}'"));
                    }
                    if sections.contains_key(sname) {
                        return Err(err!("Duplicate section name: '{line}'"));
                    }
                    sections.insert(sname.to_string(), IniSection::new());
                    in_section = Some(sname.to_string());
                    continue;
                } else {
                    return Err(err!("Invalid section name: '{line}'"));
                }
            }
            // Are we inside of a section?
            if let Some(section) = &in_section {
                if let Some(idx) = line.find('=') {
                    let chlen = '='.len_utf8();
                    if idx >= chlen {
                        // We have an option
                        let opt_name = line[..=(idx - chlen)].trim_end().to_string();
                        let opt_value = line[idx + chlen..].to_string();
                        sections
                            .get_mut(section)
                            .unwrap()
                            .options_mut()
                            .insert(opt_name, opt_value);
                    } else {
                        return Err(err!("Option has no name before equal sign '=': '{line}'"));
                    }
                } else {
                    return Err(err!("Option has no equal sign '=': '{line}'"));
                }
            } else {
                return Err(err!("Option is not inside of a section: '{line}'"));
            }
        }
        self.sections = sections;
        Ok(())
    }

    /// Get the value of an option from the given section.
    pub fn get(&self, section: &str, option: &str) -> Option<&str> {
        if let Some(sect) = self.sections.get(section) {
            if let Some(opt) = sect.options().get(option) {
                return Some(opt);
            }
        }
        None
    }

    /// Get an iterator over all options from a section.
    pub fn options_iter(&self, section: &str) -> Option<IniSectionIter> {
        self.sections.get(section).map(|s| s.iter())
    }
}

// vim: ts=4 sw=4 expandtab
bues.ch cgit interface