use std::cell::RefCell;
thread_local! {
static SCOPE: RefCell<Option<Scope>> = const { RefCell::new(None) };
}
struct Scope {
head: String,
sub: Option<String>,
inside: bool,
lines: Vec<String>,
}
fn block_head(line: &str) -> Option<(&str, Option<&str>)> {
let rest = line.strip_prefix(" ")?;
if rest.starts_with(' ') || rest.is_empty() {
return None;
}
let mut it = rest.split_whitespace();
let name = it.next()?;
Some((name, it.next()))
}
impl Scope {
fn feed(&mut self, line: String) {
if let Some((name, next)) = block_head(&line) {
self.inside = name == self.head
&& match self.sub.as_deref() {
Some(want) => next == Some(want),
None => true,
};
} else if !line.is_empty() && !line.starts_with(" ") {
self.inside = false;
}
if self.inside {
self.lines.push(line);
}
}
}
pub(super) fn emit(line: String) {
SCOPE.with(|cell| match cell.borrow_mut().as_mut() {
None => std::println!("{line}"),
Some(scope) => scope.feed(line),
});
}
pub(super) fn collect(head: &str, sub: Option<&str>, printer: impl Fn()) -> Vec<String> {
SCOPE.with(|cell| {
*cell.borrow_mut() = Some(Scope {
head: head.to_string(),
sub: sub.map(str::to_string),
inside: false,
lines: Vec::new(),
});
});
printer();
let mut lines = SCOPE
.with(|cell| cell.borrow_mut().take())
.map(|s| s.lines)
.unwrap_or_default();
while lines.last().is_some_and(|l| l.trim().is_empty()) {
lines.pop();
}
lines
}
macro_rules! println {
() => { $crate::cli::metadata::help::sink::emit(String::new()) };
($($arg:tt)*) => { $crate::cli::metadata::help::sink::emit(format!($($arg)*)) };
}
pub(super) use println;