forge
Explore
Log in

Don't you dare go Hollow

config: Add a nicer error for recursive includes

Browse files at this commit

a250fcf252d54c83b808322c8f46de0732fcec13Ivan MolodetskikhParent: 24b3cbf
We can't check recursive includes across "dir/" followed by "../"
because dir may be a symlink, so "dir/../" may resolve to a different
folder. But this is already good within the same folder.
niri-config/src/lib.rsmodified+17 -0
@@ -114,6 +114,10 @@ struct Recursion(u8);
114114 struct Includes(Vec<PathBuf>);
115115 #[derive(Default)]
116116 struct IncludeErrors(Vec<knuffel::Error>);
117+// Used for recursive include detection.
118+//
119+// We don't *need* it because we have a recursion limit, but it makes for nicer error messages.
120+struct IncludeStack(HashSet<PathBuf>);
117121
118122 // Rather than listing all fields and deriving knuffel::Decode, we implement
119123 // knuffel::DecodeChildren by hand, since we need custom logic for every field anyway: we want to
@@ -294,6 +298,16 @@ where
294298 };
295299 let base = path.parent().map(Path::to_path_buf).unwrap_or_default();
296300
301+ // Check for recursive include for a nicer error message.
302+ let mut include_stack = ctx.get::<IncludeStack>().unwrap().0.clone();
303+ if !include_stack.insert(path.to_path_buf()) {
304+ ctx.emit_error(DecodeError::missing(
305+ node,
306+ "recursive include (file includes itself)",
307+ ));
308+ continue;
309+ }
310+
297311 // Store even if the include fails to read or parse, so it gets watched.
298312 includes.borrow_mut().0.push(path.to_path_buf());
299313
@@ -316,6 +330,7 @@ where
316330 ctx.set(Recursion(recursion));
317331 ctx.set(includes.clone());
318332 ctx.set(include_errors.clone());
333+ ctx.set(IncludeStack(include_stack));
319334 ctx.set(config.clone());
320335 });
321336
@@ -397,6 +412,7 @@ impl Config {
397412 let config = Rc::new(RefCell::new(Config::default()));
398413 let includes = Rc::new(RefCell::new(Includes(Vec::new())));
399414 let include_errors = Rc::new(RefCell::new(IncludeErrors(Vec::new())));
415+ let include_stack = HashSet::from([path.to_path_buf()]);
400416
401417 let part = knuffel::parse_with_context::<ConfigPart, knuffel::span::Span, _>(
402418 filename,
@@ -407,6 +423,7 @@ impl Config {
407423 ctx.set(Recursion(0));
408424 ctx.set(includes.clone());
409425 ctx.set(include_errors.clone());
426+ ctx.set(IncludeStack(include_stack));
410427 ctx.set(config.clone());
411428 },
412429 );