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
use std::collections::HashMap;
use std::error::Error;
use std::io::{BufRead, Write};
use std::{fmt, io};

#[derive(Debug)]
pub struct PropertyNotFoundError<'a>(&'a str);

impl<'a> Error for PropertyNotFoundError<'a> {}

impl<'a> fmt::Display for PropertyNotFoundError<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "Property {:?} not found", self.0)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Properties(HashMap<String, String>);

impl Properties {
    pub fn get_property<'a>(&self, key: &'a str) -> Result<&'_ str, PropertyNotFoundError<'a>> {
        self.0
            .get(key)
            .map(String::as_ref)
            .ok_or(PropertyNotFoundError(key))
    }

    pub fn write_without_spaces<W: Write>(&self, writer: &mut W) -> Result<(), io::Error> {
        for (key, value) in &self.0 {
            writeln!(writer, "{}={}", key, value)?;
        }

        Ok(())
    }

    pub fn write_with_spaces<W: Write>(&self, writer: &mut W) -> Result<(), io::Error> {
        for (key, value) in &self.0 {
            writeln!(writer, "{} = {}", key, value)?;
        }

        Ok(())
    }

    pub fn write_aligned<W: Write>(&self, writer: &mut W) -> Result<(), io::Error> {
        let max_length = self.0.keys().map(|k| k.len()).max().unwrap_or_default();

        for (key, value) in &self.0 {
            let padded_key = {
                let pad = " ".repeat(max_length.saturating_sub(key.len()));
                let mut padded = String::with_capacity(max_length);
                padded += key;
                padded += &pad;
                padded
            };

            writeln!(writer, "{padded_key} = {value}")?;
        }

        Ok(())
    }
}

#[derive(Debug)]
pub struct PropertiesParseError {
    pub line_number: usize,
    pub kind: PropertiesParseErrorKind,
}

impl PropertiesParseError {
    fn new_io(line_number: usize, error: io::Error) -> Self {
        Self {
            line_number,
            kind: PropertiesParseErrorKind::Io(error),
        }
    }

    fn new_invalid_kvp(line_number: usize, line: &str) -> Self {
        Self {
            line_number,
            kind: PropertiesParseErrorKind::InvalidKeyValuePair(InvalidKeyValuePairError(
                line.to_string(),
            )),
        }
    }
}

#[derive(Debug)]
pub struct InvalidKeyValuePairError(String);

impl Error for InvalidKeyValuePairError {}

impl fmt::Display for InvalidKeyValuePairError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "cannot parse a key-value pair from {:?}", self.0)
    }
}

#[derive(Debug)]
pub enum PropertiesParseErrorKind {
    Io(io::Error),
    InvalidKeyValuePair(InvalidKeyValuePairError),
}

impl Error for PropertiesParseError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match &self.kind {
            PropertiesParseErrorKind::Io(e) => Some(e),
            PropertiesParseErrorKind::InvalidKeyValuePair(e) => Some(e),
        }
    }
}

impl fmt::Display for PropertiesParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Error while parsing properties file (line {})",
            self.line_number
        )
    }
}

pub fn read_properties<R: BufRead>(reader: &mut R) -> Result<Properties, PropertiesParseError> {
    let mut properties = Properties::default();

    for (i, line) in reader.lines().enumerate() {
        let line_number = i + 1;

        let line = line.map_err(|e| PropertiesParseError::new_io(line_number, e))?;

        let (field, value) = line
            .split_once('=')
            .ok_or_else(|| PropertiesParseError::new_invalid_kvp(line_number, &line))?;

        let key = field.trim().to_string();
        let value = value.trim().to_string();
        properties.0.insert(key, value);
    }

    Ok(properties)
}