config: Add a nicer error for recursive includes
Browse files at this commita250fcf252d54c83b808322c8f46de0732fcec13Parent: 24b3cbf1 changed file +17 -0
- niri-config/src/lib.rs +17 -0
niri-config/src/lib.rsmodified+17 -0
| @@ -114,6 +114,10 @@ struct Recursion(u8); | ||
| 114 | 114 | struct Includes(Vec<PathBuf>); |
| 115 | 115 | #[derive(Default)] |
| 116 | 116 | 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>); | |
| 117 | 121 | |
| 118 | 122 | // Rather than listing all fields and deriving knuffel::Decode, we implement |
| 119 | 123 | // knuffel::DecodeChildren by hand, since we need custom logic for every field anyway: we want to |
| @@ -294,6 +298,16 @@ where | ||
| 294 | 298 | }; |
| 295 | 299 | let base = path.parent().map(Path::to_path_buf).unwrap_or_default(); |
| 296 | 300 | |
| 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 | + | |
| 297 | 311 | // Store even if the include fails to read or parse, so it gets watched. |
| 298 | 312 | includes.borrow_mut().0.push(path.to_path_buf()); |
| 299 | 313 | |
| @@ -316,6 +330,7 @@ where | ||
| 316 | 330 | ctx.set(Recursion(recursion)); |
| 317 | 331 | ctx.set(includes.clone()); |
| 318 | 332 | ctx.set(include_errors.clone()); |
| 333 | + ctx.set(IncludeStack(include_stack)); | |
| 319 | 334 | ctx.set(config.clone()); |
| 320 | 335 | }); |
| 321 | 336 | |
| @@ -397,6 +412,7 @@ impl Config { | ||
| 397 | 412 | let config = Rc::new(RefCell::new(Config::default())); |
| 398 | 413 | let includes = Rc::new(RefCell::new(Includes(Vec::new()))); |
| 399 | 414 | let include_errors = Rc::new(RefCell::new(IncludeErrors(Vec::new()))); |
| 415 | + let include_stack = HashSet::from([path.to_path_buf()]); | |
| 400 | 416 | |
| 401 | 417 | let part = knuffel::parse_with_context::<ConfigPart, knuffel::span::Span, _>( |
| 402 | 418 | filename, |
| @@ -407,6 +423,7 @@ impl Config { | ||
| 407 | 423 | ctx.set(Recursion(0)); |
| 408 | 424 | ctx.set(includes.clone()); |
| 409 | 425 | ctx.set(include_errors.clone()); |
| 426 | + ctx.set(IncludeStack(include_stack)); | |
| 410 | 427 | ctx.set(config.clone()); |
| 411 | 428 | }, |
| 412 | 429 | ); |