forge
Explore
Log in

Don't you dare go Hollow

config: Move some stuff to utils

Browse files at this commit

c637d4ce9978d2ceb9aa678c37dd69374d479bd6Ivan MolodetskikhParent: a03a7bd
niri-config/src/animations.rsmodified+2 -1
@@ -1,7 +1,8 @@
11 use knuffel::errors::DecodeError;
22 use knuffel::Decode as _;
33
4-use crate::{expect_only_children, parse_arg_node, FloatOrInt};
4+use crate::utils::{expect_only_children, parse_arg_node};
5+use crate::FloatOrInt;
56
67 #[derive(knuffel::Decode, Debug, Clone, PartialEq)]
78 pub struct Animations {
niri-config/src/binds.rsmodified+1 -1
@@ -12,7 +12,7 @@ use smithay::input::keyboard::keysyms::KEY_NoSymbol;
1212 use smithay::input::keyboard::xkb::{keysym_from_name, KEYSYM_CASE_INSENSITIVE};
1313 use smithay::input::keyboard::Keysym;
1414
15-use crate::expect_only_children;
15+use crate::utils::expect_only_children;
1616
1717 #[derive(Debug, Default, PartialEq)]
1818 pub struct Binds(pub Vec<Bind>);
niri-config/src/input.rsmodified+2 -1
@@ -5,7 +5,8 @@ use smithay::input::keyboard::XkbConfig;
55 use smithay::reexports::input;
66
77 use crate::binds::Modifiers;
8-use crate::{FloatOrInt, Percent};
8+use crate::utils::Percent;
9+use crate::FloatOrInt;
910
1011 #[derive(knuffel::Decode, Debug, Default, PartialEq)]
1112 pub struct Input {
niri-config/src/layout.rsmodified+2 -1
@@ -4,7 +4,8 @@ use niri_ipc::{ColumnDisplay, SizeChange};
44 use crate::appearance::{
55 Border, FocusRing, InsertHint, Shadow, TabIndicator, DEFAULT_BACKGROUND_COLOR,
66 };
7-use crate::{expect_only_children, Color, FloatOrInt};
7+use crate::utils::expect_only_children;
8+use crate::{Color, FloatOrInt};
89
910 #[derive(knuffel::Decode, Debug, Clone, PartialEq)]
1011 pub struct Layout {
niri-config/src/lib.rsmodified+2 -160
@@ -5,10 +5,9 @@ use std::ffi::OsStr;
55 use std::fs::{self, File};
66 use std::io::Write;
77 use std::path::{Path, PathBuf};
8-use std::str::FromStr;
98
109 use knuffel::errors::DecodeError;
11-use miette::{miette, Context, IntoDiagnostic};
10+use miette::{Context, IntoDiagnostic};
1211
1312 pub mod animations;
1413 pub mod appearance;
@@ -33,6 +32,7 @@ pub use crate::input::{Input, ModKey, ScrollMethod, TrackLayout, WarpMouseToFocu
3332 pub use crate::layer_rule::LayerRule;
3433 pub use crate::layout::*;
3534 pub use crate::output::{Output, OutputName, Outputs, Position, Vrr};
35+pub use crate::utils::FloatOrInt;
3636 pub use crate::window_rule::{FloatingPosition, RelativeTo, WindowRule};
3737
3838 #[derive(knuffel::Decode, Debug, PartialEq)]
@@ -89,13 +89,6 @@ pub struct Config {
8989 pub workspaces: Vec<Workspace>,
9090 }
9191
92-#[derive(Debug, Clone, Copy, PartialEq)]
93-pub struct Percent(pub f64);
94-
95-// MIN and MAX generics are only used during parsing to check the value.
96-#[derive(Debug, Default, Clone, Copy, PartialEq)]
97-pub struct FloatOrInt<const MIN: i32, const MAX: i32>(pub f64);
98-
9992 #[derive(knuffel::Decode, Debug, Clone, PartialEq, Eq)]
10093 pub struct SpawnAtStartup {
10194 #[knuffel(arguments)]
@@ -210,72 +203,6 @@ pub struct Workspace {
210203 #[derive(Debug, Clone, PartialEq, Eq)]
211204 pub struct WorkspaceName(pub String);
212205
213-impl<S: knuffel::traits::ErrorSpan, const MIN: i32, const MAX: i32> knuffel::DecodeScalar<S>
214- for FloatOrInt<MIN, MAX>
215-{
216- fn type_check(
217- type_name: &Option<knuffel::span::Spanned<knuffel::ast::TypeName, S>>,
218- ctx: &mut knuffel::decode::Context<S>,
219- ) {
220- if let Some(type_name) = &type_name {
221- ctx.emit_error(DecodeError::unexpected(
222- type_name,
223- "type name",
224- "no type name expected for this node",
225- ));
226- }
227- }
228-
229- fn raw_decode(
230- val: &knuffel::span::Spanned<knuffel::ast::Literal, S>,
231- ctx: &mut knuffel::decode::Context<S>,
232- ) -> Result<Self, DecodeError<S>> {
233- match &**val {
234- knuffel::ast::Literal::Int(ref value) => match value.try_into() {
235- Ok(v) => {
236- if (MIN..=MAX).contains(&v) {
237- Ok(FloatOrInt(f64::from(v)))
238- } else {
239- ctx.emit_error(DecodeError::conversion(
240- val,
241- format!("value must be between {MIN} and {MAX}"),
242- ));
243- Ok(FloatOrInt::default())
244- }
245- }
246- Err(e) => {
247- ctx.emit_error(DecodeError::conversion(val, e));
248- Ok(FloatOrInt::default())
249- }
250- },
251- knuffel::ast::Literal::Decimal(ref value) => match value.try_into() {
252- Ok(v) => {
253- if (f64::from(MIN)..=f64::from(MAX)).contains(&v) {
254- Ok(FloatOrInt(v))
255- } else {
256- ctx.emit_error(DecodeError::conversion(
257- val,
258- format!("value must be between {MIN} and {MAX}"),
259- ));
260- Ok(FloatOrInt::default())
261- }
262- }
263- Err(e) => {
264- ctx.emit_error(DecodeError::conversion(val, e));
265- Ok(FloatOrInt::default())
266- }
267- },
268- _ => {
269- ctx.emit_error(DecodeError::unsupported(
270- val,
271- "Unsupported value, only numbers are recognized",
272- ));
273- Ok(FloatOrInt::default())
274- }
275- }
276- }
277-}
278-
279206 #[derive(Debug, Clone)]
280207 pub enum ConfigPath {
281208 /// Explicitly set config path.
@@ -418,74 +345,6 @@ impl Default for Config {
418345 }
419346 }
420347
421-fn expect_only_children<S>(
422- node: &knuffel::ast::SpannedNode<S>,
423- ctx: &mut knuffel::decode::Context<S>,
424-) where
425- S: knuffel::traits::ErrorSpan,
426-{
427- if let Some(type_name) = &node.type_name {
428- ctx.emit_error(DecodeError::unexpected(
429- type_name,
430- "type name",
431- "no type name expected for this node",
432- ));
433- }
434-
435- for val in node.arguments.iter() {
436- ctx.emit_error(DecodeError::unexpected(
437- &val.literal,
438- "argument",
439- "no arguments expected for this node",
440- ))
441- }
442-
443- for name in node.properties.keys() {
444- ctx.emit_error(DecodeError::unexpected(
445- name,
446- "property",
447- "no properties expected for this node",
448- ))
449- }
450-}
451-
452-fn parse_arg_node<S: knuffel::traits::ErrorSpan, T: knuffel::traits::DecodeScalar<S>>(
453- name: &str,
454- node: &knuffel::ast::SpannedNode<S>,
455- ctx: &mut knuffel::decode::Context<S>,
456-) -> Result<T, DecodeError<S>> {
457- let mut iter_args = node.arguments.iter();
458- let val = iter_args.next().ok_or_else(|| {
459- DecodeError::missing(node, format!("additional argument `{name}` is required"))
460- })?;
461-
462- let value = knuffel::traits::DecodeScalar::decode(val, ctx)?;
463-
464- if let Some(val) = iter_args.next() {
465- ctx.emit_error(DecodeError::unexpected(
466- &val.literal,
467- "argument",
468- "unexpected argument",
469- ));
470- }
471- for name in node.properties.keys() {
472- ctx.emit_error(DecodeError::unexpected(
473- name,
474- "property",
475- format!("unexpected property `{}`", name.escape_default()),
476- ));
477- }
478- for child in node.children() {
479- ctx.emit_error(DecodeError::unexpected(
480- child,
481- "node",
482- format!("unexpected node `{}`", child.node_name.escape_default()),
483- ));
484- }
485-
486- Ok(value)
487-}
488-
489348 impl<S: knuffel::traits::ErrorSpan> knuffel::DecodeScalar<S> for WorkspaceName {
490349 fn type_check(
491350 type_name: &Option<knuffel::span::Spanned<knuffel::ast::TypeName, S>>,
@@ -537,23 +396,6 @@ impl<S: knuffel::traits::ErrorSpan> knuffel::DecodeScalar<S> for WorkspaceName {
537396 }
538397 }
539398
540-impl FromStr for Percent {
541- type Err = miette::Error;
542-
543- fn from_str(s: &str) -> Result<Self, Self::Err> {
544- let Some((value, empty)) = s.split_once('%') else {
545- return Err(miette!("value must end with '%'"));
546- };
547-
548- if !empty.is_empty() {
549- return Err(miette!("trailing characters after '%' are not allowed"));
550- }
551-
552- let value: f64 = value.parse().map_err(|_| miette!("error parsing value"))?;
553- Ok(Percent(value / 100.))
554- }
555-}
556-
557399 #[cfg(test)]
558400 mod tests {
559401 use insta::assert_debug_snapshot;
niri-config/src/utils.rsmodified+160 -0
@@ -1,7 +1,16 @@
11 use std::str::FromStr;
22
3+use knuffel::errors::DecodeError;
4+use miette::miette;
35 use regex::Regex;
46
7+#[derive(Debug, Clone, Copy, PartialEq)]
8+pub struct Percent(pub f64);
9+
10+// MIN and MAX generics are only used during parsing to check the value.
11+#[derive(Debug, Default, Clone, Copy, PartialEq)]
12+pub struct FloatOrInt<const MIN: i32, const MAX: i32>(pub f64);
13+
514 /// `Regex` that implements `PartialEq` by its string form.
615 #[derive(Debug, Clone)]
716 pub struct RegexEq(pub Regex);
@@ -21,3 +30,154 @@ impl FromStr for RegexEq {
2130 Regex::from_str(s).map(Self)
2231 }
2332 }
33+
34+impl FromStr for Percent {
35+ type Err = miette::Error;
36+
37+ fn from_str(s: &str) -> Result<Self, Self::Err> {
38+ let Some((value, empty)) = s.split_once('%') else {
39+ return Err(miette!("value must end with '%'"));
40+ };
41+
42+ if !empty.is_empty() {
43+ return Err(miette!("trailing characters after '%' are not allowed"));
44+ }
45+
46+ let value: f64 = value.parse().map_err(|_| miette!("error parsing value"))?;
47+ Ok(Percent(value / 100.))
48+ }
49+}
50+
51+impl<S: knuffel::traits::ErrorSpan, const MIN: i32, const MAX: i32> knuffel::DecodeScalar<S>
52+ for FloatOrInt<MIN, MAX>
53+{
54+ fn type_check(
55+ type_name: &Option<knuffel::span::Spanned<knuffel::ast::TypeName, S>>,
56+ ctx: &mut knuffel::decode::Context<S>,
57+ ) {
58+ if let Some(type_name) = &type_name {
59+ ctx.emit_error(DecodeError::unexpected(
60+ type_name,
61+ "type name",
62+ "no type name expected for this node",
63+ ));
64+ }
65+ }
66+
67+ fn raw_decode(
68+ val: &knuffel::span::Spanned<knuffel::ast::Literal, S>,
69+ ctx: &mut knuffel::decode::Context<S>,
70+ ) -> Result<Self, DecodeError<S>> {
71+ match &**val {
72+ knuffel::ast::Literal::Int(ref value) => match value.try_into() {
73+ Ok(v) => {
74+ if (MIN..=MAX).contains(&v) {
75+ Ok(FloatOrInt(f64::from(v)))
76+ } else {
77+ ctx.emit_error(DecodeError::conversion(
78+ val,
79+ format!("value must be between {MIN} and {MAX}"),
80+ ));
81+ Ok(FloatOrInt::default())
82+ }
83+ }
84+ Err(e) => {
85+ ctx.emit_error(DecodeError::conversion(val, e));
86+ Ok(FloatOrInt::default())
87+ }
88+ },
89+ knuffel::ast::Literal::Decimal(ref value) => match value.try_into() {
90+ Ok(v) => {
91+ if (f64::from(MIN)..=f64::from(MAX)).contains(&v) {
92+ Ok(FloatOrInt(v))
93+ } else {
94+ ctx.emit_error(DecodeError::conversion(
95+ val,
96+ format!("value must be between {MIN} and {MAX}"),
97+ ));
98+ Ok(FloatOrInt::default())
99+ }
100+ }
101+ Err(e) => {
102+ ctx.emit_error(DecodeError::conversion(val, e));
103+ Ok(FloatOrInt::default())
104+ }
105+ },
106+ _ => {
107+ ctx.emit_error(DecodeError::unsupported(
108+ val,
109+ "Unsupported value, only numbers are recognized",
110+ ));
111+ Ok(FloatOrInt::default())
112+ }
113+ }
114+ }
115+}
116+
117+pub fn expect_only_children<S>(
118+ node: &knuffel::ast::SpannedNode<S>,
119+ ctx: &mut knuffel::decode::Context<S>,
120+) where
121+ S: knuffel::traits::ErrorSpan,
122+{
123+ if let Some(type_name) = &node.type_name {
124+ ctx.emit_error(DecodeError::unexpected(
125+ type_name,
126+ "type name",
127+ "no type name expected for this node",
128+ ));
129+ }
130+
131+ for val in node.arguments.iter() {
132+ ctx.emit_error(DecodeError::unexpected(
133+ &val.literal,
134+ "argument",
135+ "no arguments expected for this node",
136+ ))
137+ }
138+
139+ for name in node.properties.keys() {
140+ ctx.emit_error(DecodeError::unexpected(
141+ name,
142+ "property",
143+ "no properties expected for this node",
144+ ))
145+ }
146+}
147+
148+pub fn parse_arg_node<S: knuffel::traits::ErrorSpan, T: knuffel::traits::DecodeScalar<S>>(
149+ name: &str,
150+ node: &knuffel::ast::SpannedNode<S>,
151+ ctx: &mut knuffel::decode::Context<S>,
152+) -> Result<T, DecodeError<S>> {
153+ let mut iter_args = node.arguments.iter();
154+ let val = iter_args.next().ok_or_else(|| {
155+ DecodeError::missing(node, format!("additional argument `{name}` is required"))
156+ })?;
157+
158+ let value = knuffel::traits::DecodeScalar::decode(val, ctx)?;
159+
160+ if let Some(val) = iter_args.next() {
161+ ctx.emit_error(DecodeError::unexpected(
162+ &val.literal,
163+ "argument",
164+ "unexpected argument",
165+ ));
166+ }
167+ for name in node.properties.keys() {
168+ ctx.emit_error(DecodeError::unexpected(
169+ name,
170+ "property",
171+ format!("unexpected property `{}`", name.escape_default()),
172+ ));
173+ }
174+ for child in node.children() {
175+ ctx.emit_error(DecodeError::unexpected(
176+ child,
177+ "node",
178+ format!("unexpected node `{}`", child.node_name.escape_default()),
179+ ));
180+ }
181+
182+ Ok(value)
183+}