| 1 | use std::env::home_dir; |
| 2 | use std::path::PathBuf; |
| 3 | use std::str::FromStr; |
| 4 | |
| 5 | use knuffel::ast::SpannedNode; |
| 6 | use knuffel::errors::DecodeError; |
| 7 | use miette::miette; |
| 8 | use regex::Regex; |
| 9 | |
| 10 | mod merge_with; |
| 11 | pub use merge_with::*; |
| 12 | |
| 13 | use crate::BasePath; |
| 14 | |
| 15 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 16 | pub struct Percent(pub f64); |
| 17 | |
| 18 | |
| 19 | #[derive(Debug, Default, Clone, Copy, PartialEq)] |
| 20 | pub struct FloatOrInt<const MIN: i32, const MAX: i32>(pub f64); |
| 21 | |
| 22 | |
| 23 | |
| 24 | |
| 25 | |
| 26 | |
| 27 | |
| 28 | #[derive(knuffel::Decode, Debug, Clone, Copy, PartialEq, Eq)] |
| 29 | pub struct Flag(#[knuffel(argument, default = true)] pub bool); |
| 30 | |
| 31 | |
| 32 | #[derive(Debug, Clone)] |
| 33 | pub struct RegexEq(pub Regex); |
| 34 | |
| 35 | impl PartialEq for RegexEq { |
| 36 | fn eq(&self, other: &Self) -> bool { |
| 37 | self.0.as_str() == other.0.as_str() |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | impl Eq for RegexEq {} |
| 42 | |
| 43 | impl FromStr for RegexEq { |
| 44 | type Err = <Regex as FromStr>::Err; |
| 45 | |
| 46 | fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 47 | Regex::from_str(s).map(Self) |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | impl FromStr for Percent { |
| 52 | type Err = miette::Error; |
| 53 | |
| 54 | fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 55 | let Some((value, empty)) = s.split_once('%') else { |
| 56 | return Err(miette!("value must end with '%'")); |
| 57 | }; |
| 58 | |
| 59 | if !empty.is_empty() { |
| 60 | return Err(miette!("trailing characters after '%' are not allowed")); |
| 61 | } |
| 62 | |
| 63 | let value: f64 = value.parse().map_err(|_| miette!("error parsing value"))?; |
| 64 | Ok(Percent(value / 100.)) |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | impl<const MIN: i32, const MAX: i32> MergeWith<FloatOrInt<MIN, MAX>> for f64 { |
| 69 | fn merge_with(&mut self, part: &FloatOrInt<MIN, MAX>) { |
| 70 | *self = part.0; |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | impl MergeWith<Flag> for bool { |
| 75 | fn merge_with(&mut self, part: &Flag) { |
| 76 | *self = part.0; |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | impl<S: knuffel::traits::ErrorSpan, const MIN: i32, const MAX: i32> knuffel::DecodeScalar<S> |
| 81 | for FloatOrInt<MIN, MAX> |
| 82 | { |
| 83 | fn type_check( |
| 84 | type_name: &Option<knuffel::span::Spanned<knuffel::ast::TypeName, S>>, |
| 85 | ctx: &mut knuffel::decode::Context<S>, |
| 86 | ) { |
| 87 | if let Some(type_name) = &type_name { |
| 88 | ctx.emit_error(DecodeError::unexpected( |
| 89 | type_name, |
| 90 | "type name", |
| 91 | "no type name expected for this node", |
| 92 | )); |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | fn raw_decode( |
| 97 | val: &knuffel::span::Spanned<knuffel::ast::Literal, S>, |
| 98 | ctx: &mut knuffel::decode::Context<S>, |
| 99 | ) -> Result<Self, DecodeError<S>> { |
| 100 | match &**val { |
| 101 | knuffel::ast::Literal::Int(ref value) => match value.try_into() { |
| 102 | Ok(v) => { |
| 103 | if (MIN..=MAX).contains(&v) { |
| 104 | Ok(FloatOrInt(f64::from(v))) |
| 105 | } else { |
| 106 | ctx.emit_error(DecodeError::conversion( |
| 107 | val, |
| 108 | format!("value must be between {MIN} and {MAX}"), |
| 109 | )); |
| 110 | Ok(FloatOrInt::default()) |
| 111 | } |
| 112 | } |
| 113 | Err(e) => { |
| 114 | ctx.emit_error(DecodeError::conversion(val, e)); |
| 115 | Ok(FloatOrInt::default()) |
| 116 | } |
| 117 | }, |
| 118 | knuffel::ast::Literal::Decimal(ref value) => match value.try_into() { |
| 119 | Ok(v) => { |
| 120 | if (f64::from(MIN)..=f64::from(MAX)).contains(&v) { |
| 121 | Ok(FloatOrInt(v)) |
| 122 | } else { |
| 123 | ctx.emit_error(DecodeError::conversion( |
| 124 | val, |
| 125 | format!("value must be between {MIN} and {MAX}"), |
| 126 | )); |
| 127 | Ok(FloatOrInt::default()) |
| 128 | } |
| 129 | } |
| 130 | Err(e) => { |
| 131 | ctx.emit_error(DecodeError::conversion(val, e)); |
| 132 | Ok(FloatOrInt::default()) |
| 133 | } |
| 134 | }, |
| 135 | _ => { |
| 136 | ctx.emit_error(DecodeError::unsupported( |
| 137 | val, |
| 138 | "Unsupported value, only numbers are recognized", |
| 139 | )); |
| 140 | Ok(FloatOrInt::default()) |
| 141 | } |
| 142 | } |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | pub fn expect_only_children<S>( |
| 147 | node: &knuffel::ast::SpannedNode<S>, |
| 148 | ctx: &mut knuffel::decode::Context<S>, |
| 149 | ) where |
| 150 | S: knuffel::traits::ErrorSpan, |
| 151 | { |
| 152 | if let Some(type_name) = &node.type_name { |
| 153 | ctx.emit_error(DecodeError::unexpected( |
| 154 | type_name, |
| 155 | "type name", |
| 156 | "no type name expected for this node", |
| 157 | )); |
| 158 | } |
| 159 | |
| 160 | for val in node.arguments.iter() { |
| 161 | ctx.emit_error(DecodeError::unexpected( |
| 162 | &val.literal, |
| 163 | "argument", |
| 164 | "no arguments expected for this node", |
| 165 | )) |
| 166 | } |
| 167 | |
| 168 | for name in node.properties.keys() { |
| 169 | ctx.emit_error(DecodeError::unexpected( |
| 170 | name, |
| 171 | "property", |
| 172 | "no properties expected for this node", |
| 173 | )) |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | pub fn parse_arg_node<S: knuffel::traits::ErrorSpan, T: knuffel::traits::DecodeScalar<S>>( |
| 178 | name: &str, |
| 179 | node: &knuffel::ast::SpannedNode<S>, |
| 180 | ctx: &mut knuffel::decode::Context<S>, |
| 181 | ) -> Result<T, DecodeError<S>> { |
| 182 | let mut iter_args = node.arguments.iter(); |
| 183 | let val = iter_args.next().ok_or_else(|| { |
| 184 | DecodeError::missing(node, format!("additional argument `{name}` is required")) |
| 185 | })?; |
| 186 | |
| 187 | let value = knuffel::traits::DecodeScalar::decode(val, ctx)?; |
| 188 | |
| 189 | if let Some(val) = iter_args.next() { |
| 190 | ctx.emit_error(DecodeError::unexpected( |
| 191 | &val.literal, |
| 192 | "argument", |
| 193 | "unexpected argument", |
| 194 | )); |
| 195 | } |
| 196 | for name in node.properties.keys() { |
| 197 | ctx.emit_error(DecodeError::unexpected( |
| 198 | name, |
| 199 | "property", |
| 200 | format!("unexpected property `{}`", name.escape_default()), |
| 201 | )); |
| 202 | } |
| 203 | for child in node.children() { |
| 204 | ctx.emit_error(DecodeError::unexpected( |
| 205 | child, |
| 206 | "node", |
| 207 | format!("unexpected node `{}`", child.node_name.escape_default()), |
| 208 | )); |
| 209 | } |
| 210 | |
| 211 | Ok(value) |
| 212 | } |
| 213 | |
| 214 | pub fn expand_home_path<S: knuffel::traits::ErrorSpan>( |
| 215 | path: PathBuf, |
| 216 | spanned: &SpannedNode<S>, |
| 217 | ctx: &mut knuffel::decode::Context<S>, |
| 218 | ) -> Option<PathBuf> { |
| 219 | if let Ok(rest) = path.strip_prefix("~") { |
| 220 | let Some(home) = home_dir() else { |
| 221 | ctx.emit_error(DecodeError::missing( |
| 222 | spanned, |
| 223 | format!("error retrieving home directory to expand {:?}", path), |
| 224 | )); |
| 225 | return None; |
| 226 | }; |
| 227 | home.join(rest).into() |
| 228 | } else { |
| 229 | let base = ctx.get::<BasePath>().unwrap(); |
| 230 | base.0.join(path).into() |
| 231 | } |
| 232 | } |