From dbc803562ba3a58b9be21ccc604ee9af25626bcf Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Fri, 23 Oct 2026 18:51:10 +0100 Subject: [PATCH 01/17] fix: ureq 3.5 drops the Mozilla root store the binary never read, 115 KB smaller on macOS and 55 KB on Linux --- Cargo.lock | 23 ++++++----------------- Cargo.toml | 9 +++++---- src/http.rs | 8 +++++++- 3 files changed, 18 insertions(+), 22 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9779b66..14d6a1d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1318,9 +1318,9 @@ dependencies = [ [[package]] name = "pulldown-cmark" -version = "0.13.4" +version = "0.13.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e9f068eba8e7071c5f9511831b44f32c740d5adf574e990f946ddb53db2f314e" +checksum = "278e9268c93b9e498a2da46c34d90ba93a3255eb99009646398f34bc73ab36eb" dependencies = [ "bitflags", "memchr", @@ -1997,9 +1997,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "ureq" -version = "3.4.2" +version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a7ac20be9b7726e0bbdbf974c059676d9acb1cd414961f570a4e8231cacd7fc" +checksum = "cde93ff05758a36a851a398a772b0b79a82fbe3c186a46f2696baaeaf84c966b" dependencies = [ "base64", "cookie_store", @@ -2015,15 +2015,13 @@ dependencies = [ "serde_json", "ureq-proto", "utf8-zero", - "webpki-root-certs", - "webpki-roots", ] [[package]] name = "ureq-proto" -version = "0.6.4" +version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f86fd172ccca569e458f61b6bdd6220965a9ef36e672a6852953b51a0e1583be" +checksum = "841583fc36089d7d59419568ae157f43a5a03a2e5a81ba87c77d1596ef46e922" dependencies = [ "base64", "http", @@ -2125,15 +2123,6 @@ dependencies = [ "rustls-pki-types", ] -[[package]] -name = "webpki-roots" -version = "1.0.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" -dependencies = [ - "rustls-pki-types", -] - [[package]] name = "winapi-util" version = "0.1.11" diff --git a/Cargo.toml b/Cargo.toml index bb94e72..de656fc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -64,14 +64,15 @@ signal-hook = { version = "0.4", default-features = false } # have for Windows or macOS, so this split is what lets ADR 0002's # cross-checks compile (ADR 0011). Every platform trusts the OS's root # certificates; platform-verifier gives rustls the system store (ADR 0014). -# src/http.rs picks the matching provider. +# Neither ureq feature set bundles Mozilla roots, which PlatformVerifier +# never reads; src/http.rs picks the matching provider. [target.'cfg(any(windows, target_os = "macos"))'.dependencies] -ureq = { version = "3", default-features = false, features = ["json", "gzip", "native-tls"] } +ureq = { version = "3.5", default-features = false, features = ["json", "gzip", "native-tls-no-default"] } # rustls itself only to tell a refused certificate from a dead host. [target.'cfg(not(any(windows, target_os = "macos")))'.dependencies] -rustls = { version = "0.23", default-features = false, features = ["std"] } -ureq = { version = "3", features = ["json", "platform-verifier"] } +rustls = { version = "0.23", default-features = false, features = ["ring", "std"] } +ureq = { version = "3.5", default-features = false, features = ["json", "gzip", "rustls-no-provider", "platform-verifier"] } [features] # Re-exports for benches/ and the relevance example only; unstable and diff --git a/src/http.rs b/src/http.rs index ddcf923..5322e46 100644 --- a/src/http.rs +++ b/src/http.rs @@ -158,12 +158,18 @@ impl Http { /// The OS's trust store everywhere, so a root certificate installed for a /// TLS-inspecting proxy is trusted: through the OS's own TLS stack on Windows /// and macOS, through rustls and rustls-platform-verifier elsewhere. -/// `Cargo.toml` enables the matching ureq features per platform. +/// `Cargo.toml` enables the matching ureq features per platform, leaving out +/// the bundled Mozilla roots `PlatformVerifier` never reads, so rustls is +/// handed ring here instead of through ureq's default features. fn tls() -> ureq::tls::TlsConfig { let builder = ureq::tls::TlsConfig::builder() .root_certs(ureq::tls::RootCerts::PlatformVerifier); #[cfg(any(windows, target_os = "macos"))] let builder = builder.provider(ureq::tls::TlsProvider::NativeTls); + #[cfg(not(any(windows, target_os = "macos")))] + let builder = builder.unversioned_rustls_crypto_provider( + std::sync::Arc::new(rustls::crypto::ring::default_provider()), + ); builder.build() } From 84231ab88de09c485cfa3d961e630ab01b9b2c83 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Fri, 23 Oct 2026 18:51:28 +0100 Subject: [PATCH 02/17] perf: Markdown descriptions are stripped without pulldown-cmark, 180 to 310 KB smaller, and Latin-1 entities decode --- Cargo.lock | 18 -- Cargo.toml | 1 - _typos.toml | 3 + src/record.rs | 467 ++++++++++++++++++++++++++++++++++++++++++++++---- 4 files changed, 440 insertions(+), 49 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 14d6a1d..2aa4c22 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -514,7 +514,6 @@ dependencies = [ "insta", "predicates", "proptest", - "pulldown-cmark", "quick-xml", "rcgen", "rustls", @@ -1316,17 +1315,6 @@ dependencies = [ "unarray", ] -[[package]] -name = "pulldown-cmark" -version = "0.13.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "278e9268c93b9e498a2da46c34d90ba93a3255eb99009646398f34bc73ab36eb" -dependencies = [ - "bitflags", - "memchr", - "unicase", -] - [[package]] name = "quick-error" version = "1.2.3" @@ -1965,12 +1953,6 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" -[[package]] -name = "unicase" -version = "2.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f" - [[package]] name = "unicode-ident" version = "1.0.26" diff --git a/Cargo.toml b/Cargo.toml index de656fc..41b86c1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -46,7 +46,6 @@ clap_complete = "4" clap_mangen = "0.3" etcetera = "0.11" indicatif = { version = "0.18", default-features = false, features = ["unicode-width"] } -pulldown-cmark = { version = "0.13", default-features = false } quick-xml = "0.42" serde = { version = "1", features = ["derive"] } serde_json = "1" diff --git a/_typos.toml b/_typos.toml index 191bea1..bde257d 100644 --- a/_typos.toml +++ b/_typos.toml @@ -14,4 +14,7 @@ extend-ignore-re = [ "has\\(\"nd\"\\)", "Burnt Area \\(BA\\)", "census for BA 44/45", + # HTML entity names, decoded in src/record.rs. + "\"curren\"", + "café", ] diff --git a/src/record.rs b/src/record.rs index d28a846..ba31f28 100644 --- a/src/record.rs +++ b/src/record.rs @@ -4,7 +4,9 @@ //! them across sources. Adapters fill what they have and leave the rest `None`; //! they never invent a value to make a record look complete. -use pulldown_cmark::{Event, Options, Parser, Tag, TagEnd}; +use std::collections::HashMap; +use std::ops::Range; + use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -209,39 +211,367 @@ impl Spaced { } /// Markdown as the text its rendered page shows: link and emphasis text kept, -/// images and markup dropped, a space between blocks. For fields a source -/// documents as Markdown; HTML inside it is left for [`clean`] to strip. +/// images, rules, fences and other markup dropped, a space between lines. +/// For fields a source documents as Markdown. Entities are decoded, as a +/// Markdown renderer does, so `<br>` becomes a tag; HTML is left for +/// [`clean`] to strip. It reads one line at a time, so emphasis or a link +/// broken across two lines keeps its marks, which a description can afford. pub fn from_markdown(text: &str) -> String { let mut plain = String::with_capacity(text.len()); - let mut in_image = false; - let options = Options::ENABLE_TABLES | Options::ENABLE_STRIKETHROUGH; - for event in Parser::new_ext(text, options) { - match event { - Event::Start(Tag::Image { .. }) => in_image = true, - Event::End(TagEnd::Image) => in_image = false, - Event::Text(t) - | Event::Code(t) - | Event::Html(t) - | Event::InlineHtml(t) - if !in_image => - { - plain.push_str(&t); + let mut fence = None; + for line in text.lines().map(str::trim) { + if let Some(open) = fence { + if line.starts_with(open) { + fence = None; + } else { + plain.push_str(line); } - Event::End( - TagEnd::Emphasis - | TagEnd::Strong - | TagEnd::Strikethrough - | TagEnd::Link, - ) => {} - Event::End(_) | Event::SoftBreak | Event::HardBreak => { - plain.push(' '); + } else if let Some(open) = + ["```", "~~~"].into_iter().find(|f| line.starts_with(f)) + { + fence = Some(open); + } else if !is_rule(line) && !is_link_definition(line) { + let content = block_content(line); + if content.starts_with('|') || content.ends_with('|') { + inline(&content.replace('|', " "), &mut plain); + } else { + inline(content, &mut plain); } - _ => {} } + plain.push(' '); + } + let mut shown = Spaced::with_capacity(plain.len()); + decode_entities(&plain, &mut shown); + shown.text +} + +/// A line that renders as no text: a thematic break, a setext heading's +/// underline or a table's delimiter row. +fn is_rule(line: &str) -> bool { + let marks = || line.chars().filter(|c| !c.is_whitespace()); + let delimiter_row = marks().any(|c| c == '-') + && marks().all(|c| matches!(c, '|' | ':' | '-')); + let first = marks().next(); + let thematic = marks().nth(2).is_some() + && first.is_some_and(|f| { + matches!(f, '*' | '_' | '=') && marks().all(|c| c == f) + }); + delimiter_row || thematic +} + +/// `[label]: url`, which defines a link target and shows nothing. +fn is_link_definition(line: &str) -> bool { + line.strip_prefix('[') + .and_then(|rest| rest.split_once("]:")) + .is_some_and(|(label, _)| !label.contains(['[', ']'])) +} + +/// The line without the markers that make it a quote, a list item or a +/// heading. +fn block_content(mut line: &str) -> &str { + while let Some(rest) = line.strip_prefix('>').or_else(|| list_marker(line)) + { + line = rest.trim_start(); + } + heading(line).unwrap_or(line) +} + +/// The rest of a list item after its `-`, `*`, `+`, `1.` or `1)`. +fn list_marker(line: &str) -> Option<&str> { + let rest = line.strip_prefix(['-', '*', '+']).or_else(|| { + let digits = line.trim_start_matches(|c: char| c.is_ascii_digit()); + (digits.len() < line.len()) + .then(|| digits.strip_prefix(['.', ')'])) + .flatten() + })?; + (rest.is_empty() || rest.starts_with([' ', '\t'])).then_some(rest) +} + +/// An ATX heading's text, without its opening and closing `#`s. +fn heading(line: &str) -> Option<&str> { + let text = line.trim_start_matches('#'); + let level = line.len().saturating_sub(text.len()); + if !(1..=6).contains(&level) + || !(text.is_empty() || text.starts_with([' ', '\t'])) + { + return None; + } + let text = text.trim_end(); + let unclosed = text.trim_end_matches('#'); + Some(if unclosed.is_empty() || unclosed.ends_with([' ', '\t']) { + unclosed + } else { + text + }) +} + +/// One line's inline Markdown as text: emphasis marks and escaping +/// backslashes dropped, a link as its label, an image as nothing, code as +/// its content, an autolink as its address. Code spans, brackets and +/// emphasis are matched up front and the line is then read once, so a +/// hostile description costs no recursion and no quadratic scan. Text +/// between marks is copied a run at a time, and a line without the byte a +/// match starts from skips that match, so plain prose costs a few scans. +fn inline(line: &str, out: &mut String) { + let code = if line.contains('`') { code_spans(line) } else { Vec::new() }; + let closers = if line.contains('[') { + brackets(line, &code) + } else { + HashMap::new() + }; + let mut marks = if line.contains(['*', '_', '~']) { + emphasis(line, &code) + } else { + Vec::new() + }; + marks.sort_unstable(); + let mut labels: Vec<(usize, usize)> = Vec::new(); + let mut at = 0; + while let Some(c) = line.get(at..).and_then(|rest| rest.chars().next()) { + if let Some(&(close, end)) = labels.last() + && at >= close + { + labels.pop(); + at = at.max(end); + continue; + } + let next = at.saturating_add(c.len_utf8()); + let mark = marks.binary_search_by_key(&at, |&(start, _)| start).ok(); + let span = code.binary_search_by_key(&at, |span| span.start).ok(); + if let Some(&(_, end)) = mark.and_then(|i| marks.get(i)) { + at = end; + } else if let Some(span) = span.and_then(|i| code.get(i)) { + out.push_str(line.get(span.text.clone()).unwrap_or_default()); + at = span.end; + } else if c == '\\' { + match line.get(next..).and_then(|rest| rest.chars().next()) { + Some(p) if p.is_ascii_punctuation() => { + out.push(p); + at = next.saturating_add(1); + } + Some(_) => { + out.push(c); + at = next; + } + None => at = next, + } + } else if let Some(label) = + (c == '[').then(|| link(line, &closers, at)).flatten() + { + labels.push(label); + at = next; + } else if let Some((_, end)) = + (c == '!').then(|| link(line, &closers, next)).flatten() + { + at = end; + } else if let Some((address, end)) = + (c == '<').then(|| autolink(line, next)).flatten() + { + out.push_str(address); + at = end; + } else { + let marked = ['*', '_', '~', '`', '\\', '[', '!', '<', ']']; + let run = line.get(at..).unwrap_or_default(); + let stop = run + .get(c.len_utf8()..) + .and_then(|rest| rest.find(marked)) + .map_or(run.len(), |i| i.saturating_add(c.len_utf8())); + out.push_str(run.get(..stop).unwrap_or_default()); + at = at.saturating_add(stop); + } + } +} + +/// A code span: the bytes it covers and, inside them, its content. +struct CodeSpan { + start: usize, + text: Range, + end: usize, +} + +/// Every code span in `line`, in order. A run of backticks nothing closes +/// is text, and once a run length has failed to close, later runs of that +/// length are not searched again, so unmatched backticks stay cheap. +fn code_spans(line: &str) -> Vec { + let mut spans = Vec::new(); + let mut unclosed: Vec = Vec::new(); + let mut at = 0; + while let Some(offset) = line.get(at..).and_then(|r| r.find(['`', '\\'])) { + let start = at.saturating_add(offset); + let tail = line.get(start..).unwrap_or_default(); + if tail.starts_with('\\') { + let escaped = tail.chars().nth(1).map_or(0, char::len_utf8); + at = start.saturating_add(1).saturating_add(escaped); + continue; + } + let body = tail.trim_start_matches('`'); + let fence = tail.len().saturating_sub(body.len()); + let text_start = start.saturating_add(fence); + let closed = if unclosed.contains(&fence) { + None + } else { + fence_in(body, fence) + }; + if let Some(offset) = closed { + let text_end = text_start.saturating_add(offset); + let end = text_end.saturating_add(fence); + spans.push(CodeSpan { start, text: text_start..text_end, end }); + at = end; + } else { + unclosed.push(fence); + at = text_start; + } + } + spans +} + +/// Where in `body` a run of exactly `len` backticks starts. +fn fence_in(body: &str, len: usize) -> Option { + let mut at = 0; + while let Some(offset) = body.get(at..)?.find('`') { + let start = at.saturating_add(offset); + let run = body.get(start..)?; + let run_len = + run.len().saturating_sub(run.trim_start_matches('`').len()); + if run_len == len { + return Some(start); + } + at = start.saturating_add(run_len); } - plain + None } +/// The closing `]` or `)` of every `[` and `(` in `line` outside code spans +/// and escapes, by the opener's byte offset: one stack per kind, one pass. +fn brackets(line: &str, code: &[CodeSpan]) -> HashMap { + let mut closers = HashMap::new(); + let (mut squares, mut rounds) = (Vec::new(), Vec::new()); + let mut spans = code.iter().peekable(); + let mut at = 0; + while let Some(c) = line.get(at..).and_then(|rest| rest.chars().next()) { + if let Some(span) = spans.next_if(|span| span.start <= at) { + at = span.end; + continue; + } + let next = at.saturating_add(c.len_utf8()); + let opened = match c { + '\\' => { + let escaped = line.get(next..).and_then(|r| r.chars().next()); + at = next.saturating_add(escaped.map_or(0, char::len_utf8)); + continue; + } + '[' => { + squares.push(at); + None + } + '(' => { + rounds.push(at); + None + } + ']' => squares.pop(), + ')' => rounds.pop(), + _ => None, + }; + if let Some(open) = opened { + closers.insert(open, at); + } + at = next; + } + closers +} + +/// A link or image whose `[` is at `open`: the offset of the `]` closing +/// its label, and the end of the `(url)` or `[ref]` after it. +fn link( + line: &str, + closers: &HashMap, + open: usize, +) -> Option<(usize, usize)> { + if !line.get(open..)?.starts_with('[') { + return None; + } + let close = *closers.get(&open)?; + let target = close.saturating_add(1); + if !line.get(target..)?.starts_with(['(', '[']) { + return None; + } + Some((close, closers.get(&target)?.saturating_add(1))) +} + +/// `https://x.org>` or `a@b.org>` at `from`, just after a `<`: the address +/// and the end of the autolink. Anything else after a `<` is HTML for +/// [`clean`]. The address ends at the first space or bracket, so a line of +/// `<`s is read once. +fn autolink(line: &str, from: usize) -> Option<(&str, usize)> { + let rest = line.get(from..)?; + let end = + rest.find(|c: char| matches!(c, '>' | '<') || c.is_whitespace())?; + let (address, tail) = rest.split_at_checked(end)?; + let is_address = address.contains("://") || address.contains('@'); + (tail.starts_with('>') && is_address) + .then(|| (address, from.saturating_add(end).saturating_add(1))) +} + +/// Byte ranges of the `*`, `_` and `~~` runs in `line` that open or close +/// emphasis, paired by CommonMark's flanking rules. A run that pairs with +/// nothing, like the `*` in `*.csv` or `5 * 3`, or a `_` inside a word, as in +/// `sentinel_2_l2a`, stays text. At most 64 openers wait for a closer, which +/// bounds the search for one. +fn emphasis(line: &str, code: &[CodeSpan]) -> Vec<(usize, usize)> { + const OPENERS: usize = 64; + let mut paired = Vec::new(); + let mut open: Vec<(char, usize, usize)> = Vec::new(); + let mut spans = code.iter().peekable(); + let mut prev = ' '; + let mut at = 0; + while let Some(c) = line.get(at..).and_then(|rest| rest.chars().next()) { + if let Some(span) = spans.next_if(|span| span.start <= at) { + at = span.end; + prev = '`'; + continue; + } + let next = at.saturating_add(c.len_utf8()); + if c == '\\' { + let escaped = line.get(next..).and_then(|r| r.chars().next()); + at = next.saturating_add(escaped.map_or(0, char::len_utf8)); + prev = escaped.unwrap_or(c); + continue; + } + if !matches!(c, '*' | '_' | '~') { + at = next; + prev = c; + continue; + } + let run = line.get(at..).unwrap_or_default(); + let body = run.trim_start_matches(c); + let end = at.saturating_add(run.len().saturating_sub(body.len())); + let after = body.chars().next().unwrap_or(' '); + let left = !after.is_whitespace(); + let right = !prev.is_whitespace(); + let (opens, closes) = match c { + '_' => ( + left && !prev.is_alphanumeric(), + right && !after.is_alphanumeric(), + ), + '~' if end.saturating_sub(at) != 2 => (false, false), + _ => (left, right), + }; + let opener = + open.iter().rposition(|&(d, ..)| d == c).filter(|_| closes); + if let Some(i) = opener { + if let Some(&(_, s, e)) = open.get(i) { + paired.push((s, e)); + paired.push((at, end)); + } + open.truncate(i); + } else if opens && open.len() < OPENERS { + open.push((c, at, end)); + } + at = end; + prev = c; + } + paired +} /// HTML entities decoded in one pass, so `&lt;` stays the text `<`. /// Unknown names and numeric codes for control characters stay as written. /// The `;` is looked for only as far as the longest name, so text full of @@ -283,11 +613,21 @@ fn entity(name: &str) -> Option { "mdash" => '\u{2014}', "hellip" => '\u{2026}', "rarr" => '\u{2192}', + "bull" => '\u{2022}', + "minus" => '\u{2212}', + "euro" => '\u{20ac}', + "trade" => '\u{2122}', _ => { - let code = name.strip_prefix('#')?; - let number = match code.strip_prefix(['x', 'X']) { - Some(hex) => u32::from_str_radix(hex, 16).ok()?, - None => code.parse().ok()?, + let number = match name.strip_prefix('#') { + Some(code) => match code.strip_prefix(['x', 'X']) { + Some(hex) => u32::from_str_radix(hex, 16).ok()?, + None => code.parse().ok()?, + }, + None => LATIN1 + .iter() + .position(|&n| n == name) + .and_then(|i| u32::try_from(i).ok())? + .checked_add(0xa0)?, }; return char::from_u32(number) .filter(|&c| !c.is_control() && !invisible(c)); @@ -296,6 +636,22 @@ fn entity(name: &str) -> Option { Some(named) } +/// The entity names of U+00A0 to U+00FF, in code point order. +const LATIN1: [&str; 96] = [ + "nbsp", "iexcl", "cent", "pound", "curren", "yen", "brvbar", "sect", + "uml", "copy", "ordf", "laquo", "not", "shy", "reg", "macr", "deg", + "plusmn", "sup2", "sup3", "acute", "micro", "para", "middot", "cedil", + "sup1", "ordm", "raquo", "frac14", "frac12", "frac34", "iquest", "Agrave", + "Aacute", "Acirc", "Atilde", "Auml", "Aring", "AElig", "Ccedil", "Egrave", + "Eacute", "Ecirc", "Euml", "Igrave", "Iacute", "Icirc", "Iuml", "ETH", + "Ntilde", "Ograve", "Oacute", "Ocirc", "Otilde", "Ouml", "times", + "Oslash", "Ugrave", "Uacute", "Ucirc", "Uuml", "Yacute", "THORN", "szlig", + "agrave", "aacute", "acirc", "atilde", "auml", "aring", "aelig", "ccedil", + "egrave", "eacute", "ecirc", "euml", "igrave", "iacute", "icirc", "iuml", + "eth", "ntilde", "ograve", "oacute", "ocirc", "otilde", "ouml", "divide", + "oslash", "ugrave", "uacute", "ucirc", "uuml", "yacute", "thorn", "yuml", +]; + /// [`clean`], cut to a teaser on a char boundary. `None` when nothing is left. pub fn summary(text: &str) -> Option { shortened(text, SUMMARY_CHARS) @@ -822,6 +1178,57 @@ mod tests { ); } + #[test] + fn hostile_markdown_costs_linear_time_and_no_recursion() { + let n = 50_000; + let nested = format!("{}x{}", "[".repeat(n), "](u)".repeat(n)); + let fences: Vec = (1..=300).map(|k| "`".repeat(k)).collect(); + let hostile = [ + "[".repeat(n), + "![".repeat(n), + "(".repeat(n), + "<".repeat(n), + "*a ".repeat(n), + "_a ".repeat(n), + fences.join(" "), + ]; + let started = std::time::Instant::now(); + assert_eq!(clean(&from_markdown(&nested)), "x"); + for md in &hostile { + assert_ne!(from_markdown(md), ""); + } + assert!(started.elapsed() < std::time::Duration::from_secs(10)); + } + + #[test] + fn markdown_marks_that_pair_with_nothing_stay_text() { + let cases = [ + ("*.csv and *.nc files", "*.csv and *.nc files"), + ("5 * 3 = 15", "5 * 3 = 15"), + ("a **bold** and _em_ ~~gone~~ word", "a bold and em gone word"), + ( + "[![build](https://x.org/b.svg)](https://ci.org) Data from \ + \\*not em\\*", + "Data from https://x.org/d *not em*", + ), + ( + "```\nlet a = 1;\n```\n---\n[ref]: https://x.org\n\ + > quoted `code_span`", + "let a = 1; quoted code_span", + ), + ("## C# notes ##", "C# notes"), + ( + "A [page](https://en.wikipedia.org/wiki/Foo_(bar)) here", + "A page here", + ), + ("café »x« <br>end", "café »x« end"), + ]; + for (md, shown) in cases { + assert_eq!(clean(&from_markdown(md)), shown, "{md:?}"); + } + assert_eq!(clean("Matías über"), "Matías über"); + } + #[test] fn invisible_format_characters_are_dropped_but_joiners_stay() { assert_eq!( From 0b8d3ff6c30255ac93714bfca5fc22e2b1e0e710 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Fri, 23 Oct 2026 18:52:30 +0100 Subject: [PATCH 03/17] perf: credentials.toml is read without the toml crate, 67 to 98 KB smaller --- Cargo.toml | 3 +- docs/reference/keys-and-cache.md | 2 + src/credentials.rs | 108 ++++++++++++++++++++++++++++++- 3 files changed, 111 insertions(+), 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 41b86c1..6b087a6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -52,7 +52,6 @@ serde_json = "1" tempfile = "3" terminal_size = "0.4" thiserror = "2" -toml = { version = "1", default-features = false, features = ["parse", "serde", "std"] } [target.'cfg(unix)'.dependencies] signal-hook = { version = "0.4", default-features = false } @@ -85,6 +84,8 @@ criterion = { version = "5", package = "codspeed-criterion-compat", default-feat insta = { version = "1", features = ["filters"] } predicates = "3" proptest = "1" +# The relevance example reads its queries file. +toml = { version = "1", default-features = false, features = ["parse", "serde", "std"] } # A local HTTPS server under a private root, for the test that Linux trusts # what SSL_CERT_FILE names; rustls with ring is already in the build there. diff --git a/docs/reference/keys-and-cache.md b/docs/reference/keys-and-cache.md index 859c9b6..c0b4aba 100644 --- a/docs/reference/keys-and-cache.md +++ b/docs/reference/keys-and-cache.md @@ -9,6 +9,8 @@ fred = "..." datagov = "..." ``` +Each key is one `name = "value"` line, in double or single quotes, with `#` comments allowed. A file holding anything else, such as a `[table]` header, a multi-line string or a name given twice, supplies no key at all. + | source | environment variable | file key | without it | get one | |---|---|---|---|---| | Hugging Face | `HF_TOKEN` | `huggingface` | 500 requests per 5 min per IP | https://huggingface.co/settings/tokens | diff --git a/src/credentials.rs b/src/credentials.rs index 4d3ab26..7e4f7e5 100644 --- a/src/credentials.rs +++ b/src/credentials.rs @@ -182,10 +182,89 @@ fn env(var: &str) -> Option { fn read_toml(path: &Path) -> HashMap { std::fs::read_to_string(path) .ok() - .and_then(|text| toml::from_str::>(&text).ok()) + .and_then(|text| flat_table(&text)) .unwrap_or_default() } +/// `credentials.toml` as the flat table of `name = "value"` lines it is +/// documented to be, with comments and either kind of one-line string. Any +/// other line, such as a `[table]` header, a value that is not a string, a +/// multi-line string or a name given twice, makes the whole file unreadable, +/// so a file is read as TOML reads it or not at all. +fn flat_table(text: &str) -> Option> { + let mut table = HashMap::new(); + for line in text.lines().map(str::trim) { + if line.is_empty() || line.starts_with('#') { + continue; + } + let (name, rest) = if line.starts_with(['"', '\'']) { + toml_string(line)? + } else { + let end = line.find(|c: char| { + !(c.is_ascii_alphanumeric() || c == '_' || c == '-') + })?; + let (name, rest) = line.split_at_checked(end)?; + (!name.is_empty()).then(|| (name.to_owned(), rest))? + }; + let rest = rest.trim_start().strip_prefix('=')?.trim_start(); + let (value, rest) = toml_string(rest)?; + let rest = rest.trim_start(); + if !(rest.is_empty() || rest.starts_with('#')) + || table.insert(name, value).is_some() + { + return None; + } + } + Some(table) +} + +/// A one-line TOML string at the start of `text`, `"basic"` with its escapes +/// or `'literal'` without, and the text after it. +fn toml_string(text: &str) -> Option<(String, &str)> { + if text.starts_with("\"\"\"") || text.starts_with("'''") { + return None; + } + if let Some(literal) = text.strip_prefix('\'') { + let (value, rest) = literal.split_once('\'')?; + return Some((value.to_owned(), rest)); + } + let body = text.strip_prefix('"')?; + let mut chars = body.char_indices(); + let mut value = String::new(); + while let Some((i, c)) = chars.next() { + match c { + '"' => return Some((value, body.get(i..)?.get(1..)?)), + '\\' => value.push(match chars.next()?.1 { + '"' => '"', + '\\' => '\\', + 'b' => '\u{8}', + 't' => '\t', + 'n' => '\n', + 'f' => '\u{c}', + 'r' => '\r', + 'u' => unicode_escape(&mut chars, 4)?, + 'U' => unicode_escape(&mut chars, 8)?, + _ => return None, + }), + c if c.is_control() && c != '\t' => return None, + c => value.push(c), + } + } + None +} + +fn unicode_escape( + chars: &mut impl Iterator, + digits: usize, +) -> Option { + let hex: String = chars.take(digits).map(|(_, c)| c).collect(); + let all_hex = hex.chars().all(|c| c.is_ascii_hexdigit()); + (hex.len() == digits && all_hex) + .then(|| u32::from_str_radix(&hex, 16).ok()) + .flatten() + .and_then(char::from_u32) +} + fn kaggle_dir() -> Option { env("KAGGLE_CONFIG_DIR") .map(PathBuf::from) @@ -272,6 +351,33 @@ mod tests { assert!(!format!("{secret:?}").contains("abc123")); } + #[test] + fn the_credentials_file_reads_as_toml_or_not_at_all() { + let table = flat_table( + "# keys\n\nfred = \"a\\\"b\\u00e9\" # comment\n \ + 'datagov' = 'C:\\raw'\nnc-bi_2=\"x\"\n", + ) + .unwrap(); + assert_eq!(table.get("fred").map(String::as_str), Some("a\"bé")); + assert_eq!(table.get("datagov").map(String::as_str), Some("C:\\raw")); + assert_eq!(table.get("nc-bi_2").map(String::as_str), Some("x")); + assert_eq!(flat_table("").unwrap().len(), 0); + for refused in [ + "[keys]\nfred = \"a\"", + "fred = 1", + "fred = \"a\"\nfred = \"b\"", + "fred = \"\"\"a\"\"\"", + "fred = \"a\" b", + "fred = \"unterminated", + "fred = \"\\q\"", + "fred.key = \"a\"", + "= \"a\"", + "fred", + ] { + assert_eq!(flat_table(refused), None, "{refused:?}"); + } + } + #[test] fn the_credentials_file_supplies_missing_keys() { let dir = tempfile::tempdir().unwrap(); From 8fa9f64294496a441938c126b66b16c048f65fc1 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Fri, 23 Oct 2026 18:56:27 +0100 Subject: [PATCH 04/17] build: release archives are .tar.xz, which holds dsk next to dataseek almost free, 60% smaller downloads --- .github/workflows/release.yml | 12 +++++++----- docs/adr/0017-release-builds-on-a-platform-matrix.md | 2 +- docs/reference/release.md | 2 +- scripts/homebrew-formula.sh | 12 ++++++------ 4 files changed, 15 insertions(+), 13 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e4d0bf2..b9774ba 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -56,8 +56,10 @@ jobs: target: ${{ matrix.target }} manylinux: ${{ matrix.manylinux || 'auto' }} args: --release --locked --out dist - # The binaries the wheel carries, archived under the name cargo binstall - # looks for: dataseek-.tar.gz, or .zip on Windows. + # The binaries the wheel carries, archived under a name cargo binstall + # looks for: dataseek-.tar.xz, or .zip on Windows. dsk is a + # copy of dataseek, and xz, unlike gzip, reaches back far enough to + # store the second copy almost free. - name: archive shell: bash env: @@ -73,8 +75,8 @@ jobs: archive="$dir.zip" 7z a -bd "archives/$archive" "$dir" > /dev/null else - archive="$dir.tar.gz" - tar czf "archives/$archive" "$dir" + archive="$dir.tar.xz" + tar cJf "archives/$archive" "$dir" fi cd archives if command -v sha256sum > /dev/null; then @@ -226,7 +228,7 @@ jobs: REPO: ${{ github.repository }} TAG: ${{ github.event.release.tag_name }} run: | - gh release download "$TAG" --repo "$REPO" -p '*.tar.gz.sha256' -D sums + gh release download "$TAG" --repo "$REPO" -p '*.tar.xz.sha256' -D sums scripts/homebrew-formula.sh "$TAG" sums > tap/Formula/dataseek.rb - name: push working-directory: tap diff --git a/docs/adr/0017-release-builds-on-a-platform-matrix.md b/docs/adr/0017-release-builds-on-a-platform-matrix.md index 140eecf..adafbba 100644 --- a/docs/adr/0017-release-builds-on-a-platform-matrix.md +++ b/docs/adr/0017-release-builds-on-a-platform-matrix.md @@ -9,7 +9,7 @@ PyPI wheels and `cargo binstall` both need prebuilt binaries for Linux (x86_64, ## Decision -`.github/workflows/release.yml` runs when a GitHub release is published, which release-plz does when its release PR merges. One job per target builds the wheel with maturin, on a machine of the target's OS (Linux aarch64 in maturin's cross container), and archives the same binaries as `dataseek-.tar.gz` (`.zip` on Windows) with a SHA-256 file. The archives are attested and attached to the release; the wheels and an sdist go to PyPI with `uv publish` through trusted publishing. A pull request that changes the release build runs the builds and publishes nothing. CI stays one Linux job. +`.github/workflows/release.yml` runs when a GitHub release is published, which release-plz does when its release PR merges. One job per target builds the wheel with maturin, on a machine of the target's OS (Linux aarch64 in maturin's cross container), and archives the same binaries as `dataseek-.tar.xz` (`.zip` on Windows) with a SHA-256 file. The archives are attested and attached to the release; the wheels and an sdist go to PyPI with `uv publish` through trusted publishing. A pull request that changes the release build runs the builds and publishes nothing. CI stays one Linux job. ## Consequences diff --git a/docs/reference/release.md b/docs/reference/release.md index 3fdcaca..d8cbb06 100644 --- a/docs/reference/release.md +++ b/docs/reference/release.md @@ -62,7 +62,7 @@ The `release` job publishes through crates.io trusted publishing (`lmarkmann/dat ## Publishing to PyPI -`uvx dataseek` runs a wheel holding both binaries, built by maturin with the version from `Cargo.toml`. `release.yml` builds the wheels on each GitHub release and uploads them with `uv publish` through trusted publishing ([ADR 0017](../adr/0017-release-builds-on-a-platform-matrix.md)). The same jobs attach `dataseek-.tar.gz` (`.zip` on Windows) with a `.sha256` to the release, which `cargo binstall dataseek` downloads, and its `homebrew` job rewrites `Formula/dataseek.rb` in [lmarkmann/homebrew-tap](https://github.com/lmarkmann/homebrew-tap) from them with `scripts/homebrew-formula.sh`, through a release App token scoped to the tap. +`uvx dataseek` runs a wheel holding both binaries, built by maturin with the version from `Cargo.toml`. `release.yml` builds the wheels on each GitHub release and uploads them with `uv publish` through trusted publishing ([ADR 0017](../adr/0017-release-builds-on-a-platform-matrix.md)). The same jobs attach `dataseek-.tar.xz` (`.zip` on Windows) with a `.sha256` to the release, which `cargo binstall dataseek` downloads, and its `homebrew` job rewrites `Formula/dataseek.rb` in [lmarkmann/homebrew-tap](https://github.com/lmarkmann/homebrew-tap) from them with `scripts/homebrew-formula.sh`, through a release App token scoped to the tap. Before the first release, add a pending publisher at : project `dataseek`, `lmarkmann/dataseek`, workflow `release.yml`, environment `pypi`. diff --git a/scripts/homebrew-formula.sh b/scripts/homebrew-formula.sh index 193d940..44f5cf3 100755 --- a/scripts/homebrew-formula.sh +++ b/scripts/homebrew-formula.sh @@ -2,7 +2,7 @@ # Prints the Homebrew formula for one release, from the .sha256 files the # release workflow attaches next to each archive: # -# scripts/homebrew-formula.sh v0.8.0 +# scripts/homebrew-formula.sh v0.8.0 # # The release workflow writes the output to Formula/dataseek.rb in # lmarkmann/homebrew-tap (docs/reference/release.md). @@ -15,7 +15,7 @@ releases="https://github.com/lmarkmann/dataseek/releases/download/$tag" # A failure inside the here-document below would not stop the script, so # every hash is read and checked first. sha() { - hash=$(cut -d' ' -f1 "$sums/dataseek-$1.tar.gz.sha256") + hash=$(cut -d' ' -f1 "$sums/dataseek-$1.tar.xz.sha256") case $hash in *[!0-9a-f]* | "") ;; *) [ ${#hash} -eq 64 ] && echo "$hash" && return ;; @@ -38,22 +38,22 @@ class Dataseek < Formula on_macos do on_arm do - url "$releases/dataseek-aarch64-apple-darwin.tar.gz" + url "$releases/dataseek-aarch64-apple-darwin.tar.xz" sha256 "$mac_arm" end on_intel do - url "$releases/dataseek-x86_64-apple-darwin.tar.gz" + url "$releases/dataseek-x86_64-apple-darwin.tar.xz" sha256 "$mac_intel" end end on_linux do on_arm do - url "$releases/dataseek-aarch64-unknown-linux-gnu.tar.gz" + url "$releases/dataseek-aarch64-unknown-linux-gnu.tar.xz" sha256 "$linux_arm" end on_intel do - url "$releases/dataseek-x86_64-unknown-linux-gnu.tar.gz" + url "$releases/dataseek-x86_64-unknown-linux-gnu.tar.xz" sha256 "$linux_intel" end end From cce34f5c4da999c7d0a43983ee2fc22a28707065 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Fri, 23 Oct 2026 19:02:56 +0100 Subject: [PATCH 05/17] perf: spinners and progress bars are drawn without indicatif, 83 to 88 KB smaller --- Cargo.lock | 33 +--- Cargo.toml | 2 +- examples/relevance/record.rs | 5 +- src/lib.rs | 1 + src/palette.rs | 46 ------ src/search.rs | 12 +- src/ui.rs | 301 ++++++++++++++++++++++++++++------- 7 files changed, 255 insertions(+), 145 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2aa4c22..f63bb9a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -417,7 +417,6 @@ checksum = "e96a4956774c13c126a8b5af4daa79384f4d826534c95a02d76afb39e2ab64e3" dependencies = [ "encode_unicode", "libc", - "unicode-width", "windows-sys 0.61.2", ] @@ -503,6 +502,7 @@ version = "0.10.0" dependencies = [ "allocation-counter", "anstream", + "anstyle-query", "anyhow", "assert_cmd", "clap", @@ -510,7 +510,6 @@ dependencies = [ "clap_mangen", "codspeed-criterion-compat", "etcetera", - "indicatif", "insta", "predicates", "proptest", @@ -882,18 +881,6 @@ dependencies = [ "hashbrown", ] -[[package]] -name = "indicatif" -version = "0.18.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9433806cd6b4ec1aba79c021c7e4c58fb4c3b9977c085062e611ac929998fb0c" -dependencies = [ - "console", - "portable-atomic", - "unicode-width", - "unit-prefix", -] - [[package]] name = "insta" version = "1.49.0" @@ -1227,12 +1214,6 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" -[[package]] -name = "portable-atomic" -version = "1.15.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" - [[package]] name = "potential_utf" version = "0.1.6" @@ -1959,18 +1940,6 @@ version = "1.0.26" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" -[[package]] -name = "unicode-width" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" - -[[package]] -name = "unit-prefix" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81e544489bf3d8ef66c953931f56617f423cd4b5494be343d9b9d3dda037b9a3" - [[package]] name = "untrusted" version = "0.9.0" diff --git a/Cargo.toml b/Cargo.toml index 6b087a6..edf857a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -41,11 +41,11 @@ doc_markdown = "allow" [dependencies] anyhow = "1" anstream = "1" +anstyle-query = "1" clap = { version = "4", features = ["derive", "env", "wrap_help"] } clap_complete = "4" clap_mangen = "0.3" etcetera = "0.11" -indicatif = { version = "0.18", default-features = false, features = ["unicode-width"] } quick-xml = "0.42" serde = { version = "1", features = ["derive"] } serde_json = "1" diff --git a/examples/relevance/record.rs b/examples/relevance/record.rs index 842f46b..a78705c 100644 --- a/examples/relevance/record.rs +++ b/examples/relevance/record.rs @@ -10,9 +10,8 @@ use std::time::Duration; use anyhow::{Result, bail}; use dataseek::internals::{ - Outcome, Plan, SOURCES, Services, Source, search, select, + Outcome, Plan, Progress, SOURCES, Services, Source, search, select, }; -use indicatif::ProgressBar; use crate::snapshot::{self, Answered, Lists, Query}; @@ -54,7 +53,7 @@ pub fn run(queries: &[Query], args: &[String]) -> Result<()> { forced: true, since: None, }); - search(&services, false, &plan, &ProgressBar::hidden(), None) + search(&services, false, &plan, &Progress::hidden(), None) }; let mut outcomes = ask(sources.clone()); let failed: Vec<_> = outcomes diff --git a/src/lib.rs b/src/lib.rs index 097e11e..1d2e661 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -60,6 +60,7 @@ pub mod internals { pub use crate::sources::eurostat::parse as eurostat_toc; pub use crate::sources::sdmx::flows as sdmx_dataflows; pub use crate::sources::{SOURCES, Services, Source, select}; + pub use crate::ui::Progress; } use std::ffi::OsString; diff --git a/src/palette.rs b/src/palette.rs index dad7c88..5976627 100644 --- a/src/palette.rs +++ b/src/palette.rs @@ -57,56 +57,10 @@ pub fn help() -> Styles { .invalid(warning()) } -/// The accent as an indicatif template token, which accepts names, `#rrggbb` -/// and 256-color indices. -pub fn accent_token() -> String { - token_for(ACCENT) -} - -fn token_for(color: Color) -> String { - match color { - Color::Ansi(c) => ansi_name(c).to_owned(), - Color::Rgb(RgbColor(r, g, b)) => format!("#{r:02x}{g:02x}{b:02x}"), - Color::Ansi256(c) => c.index().to_string(), - } -} - -fn ansi_name(c: AnsiColor) -> &'static str { - match c { - AnsiColor::Black | AnsiColor::BrightBlack => "black", - AnsiColor::Red | AnsiColor::BrightRed => "red", - AnsiColor::Green | AnsiColor::BrightGreen => "green", - AnsiColor::Yellow | AnsiColor::BrightYellow => "yellow", - AnsiColor::Blue | AnsiColor::BrightBlue => "blue", - AnsiColor::Magenta | AnsiColor::BrightMagenta => "magenta", - AnsiColor::Cyan | AnsiColor::BrightCyan => "cyan", - AnsiColor::White | AnsiColor::BrightWhite => "white", - } -} - #[cfg(test)] mod tests { use super::*; - #[test] - fn named_accent_maps_exactly() { - assert_eq!(ansi_name(AnsiColor::Cyan), "cyan"); - assert_eq!(ansi_name(AnsiColor::BrightCyan), "cyan"); - } - - // A token console's parser rejects drops the color silently. - #[test] - fn every_role_shape_produces_a_token_console_accepts() { - use clap::builder::styling::Ansi256Color; - - assert_eq!(token_for(Color::Ansi(AnsiColor::Blue)), "blue"); - assert_eq!( - token_for(Color::Rgb(RgbColor(0x7a, 0xa2, 0xf7))), - "#7aa2f7" - ); - assert_eq!(token_for(Color::Ansi256(Ansi256Color(42))), "42"); - } - #[test] fn roles_carry_a_foreground_color() { assert!(accent().get_fg_color().is_some()); diff --git a/src/search.rs b/src/search.rs index 00fe2e5..733125f 100644 --- a/src/search.rs +++ b/src/search.rs @@ -32,7 +32,7 @@ use std::sync::atomic::Ordering; use std::sync::mpsc::{self, RecvTimeoutError}; use std::time::{Duration, Instant}; -use indicatif::ProgressBar; +use crate::ui::Progress; use crate::cache::{Freshness, Kind, QUERY_TTL, query_key}; use crate::credentials::Key; @@ -119,7 +119,7 @@ pub fn run( services: &Arc, refresh: bool, plan: &Arc, - progress: &ProgressBar, + progress: &Progress, deadline: Option, ) -> Vec { let started = Instant::now(); @@ -224,7 +224,7 @@ fn spawn( services: &Arc, refresh: bool, plan: &Arc, - progress: &ProgressBar, + progress: &Progress, skip: &[bool], ) -> (mpsc::Receiver<(usize, Outcome)>, usize) { let (sender, receiver) = mpsc::channel(); @@ -630,7 +630,7 @@ mod tests { let services = Arc::new(Services::scratch(dir.path())); let plan = Arc::new(plan(source, true)); let mut outcomes = - run(&services, false, &plan, &ProgressBar::hidden(), deadline); + run(&services, false, &plan, &Progress::hidden(), deadline); assert_eq!(outcomes.len(), 1); outcomes.remove(0) } @@ -661,7 +661,7 @@ mod tests { let plan = Arc::new(Plan { sources, ..plan(&ANSWERS, forced) }); let started = Instant::now(); let outcomes = - run(&services, false, &plan, &ProgressBar::hidden(), deadline); + run(&services, false, &plan, &Progress::hidden(), deadline); (outcomes, started.elapsed()) } @@ -821,7 +821,7 @@ mod tests { &services, false, &plan, - &ProgressBar::hidden(), + &Progress::hidden(), Some(Duration::from_millis(50)), ); assert!( diff --git a/src/ui.rs b/src/ui.rs index 23a5e73..bd15923 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -5,16 +5,17 @@ //! plus live bars and spinners; a pipe, or `--no-progress`, gets the status //! lines alone, so a slow command still says what it is doing without frames; //! `--json` turns each line into an NDJSON event; `--quiet` silences it. -//! Outside Live mode the bars are hidden `ProgressBar`s, so callers never -//! branch. +//! Outside Live mode the bars are hidden [`Progress`] values, so callers +//! never branch. use std::fmt::Display; use std::io::{IsTerminal, Write}; -use std::sync::atomic::{AtomicBool, AtomicU8, Ordering}; -use std::time::Duration; +use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, PoisonError}; +use std::thread::JoinHandle; +use std::time::{Duration, Instant}; use clap::builder::styling::Style; -use indicatif::{ProgressBar, ProgressStyle}; use crate::output::{Out, Verbosity}; use crate::palette; @@ -43,7 +44,7 @@ pub fn init(out: &Out) { Mode::Off } else if out.json { Mode::Events - } else if out.progress && std::io::stderr().is_terminal() { + } else if out.progress && std::io::stderr().is_terminal() && redraws() { Mode::Live } else { Mode::Lines @@ -51,6 +52,15 @@ pub fn init(out: &Out) { set(mode, !out.plain, out.color_on_stderr()); } +/// Whether the terminal erases a line on `\x1b[K`, which a live display +/// redraws with. A Windows console does once virtual terminal processing is +/// on, which this turns on; it fails when stdout or stderr is not a console, +/// and the display then falls back to status lines. Off Windows there is +/// nothing to turn on. +fn redraws() -> bool { + anstyle_query::windows::enable_ansi_colors().unwrap_or(true) +} + fn set(mode: Mode, unicode: bool, color: bool) { MODE.store(mode as u8, Ordering::Relaxed); UNICODE.store(unicode, Ordering::Relaxed); @@ -132,66 +142,220 @@ pub fn count(n: usize, noun: &str) -> String { /// A spinner for work of unknown length. Without a live terminal the message /// becomes a stage line instead, so the wait is still announced. -pub fn spinner(msg: impl Into) -> ProgressBar { +pub fn spinner(msg: impl Into) -> Progress { let msg = msg.into(); if mode() != Mode::Live { stage(&msg); - return ProgressBar::hidden(); + return Progress::hidden(); } - let ticks = - if unicode() { "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏" } else { "|/-\\" }; - let pb = ProgressBar::new_spinner(); - pb.set_style( - ProgressStyle::with_template(&spinner_template()) - .unwrap_or_else(|_| ProgressStyle::default_spinner()) - .tick_chars(ticks), - ); - pb.set_message(msg); - pb.enable_steady_tick(Duration::from_millis(90)); - pb + Progress::start(msg, None) } /// A bar over `len` known units; use a [`spinner`] when the total is unknown. /// Hidden unless a terminal is watching; the stage line before it carries the /// news everywhere else. -pub fn bar(len: u64, msg: impl Into) -> ProgressBar { +pub fn bar(len: u64, msg: impl Into) -> Progress { if mode() != Mode::Live { - return ProgressBar::hidden(); - } - let chars = if unicode() { "█▓░" } else { "#=-" }; - let pb = ProgressBar::new(len); - pb.set_style( - ProgressStyle::with_template(&bar_template()) - .unwrap_or_else(|_| ProgressStyle::default_bar()) - .progress_chars(chars), - ); - pb.set_message(msg.into()); - pb -} - -// Built here so the tests can parse them without a terminal. -fn spinner_template() -> String { - if color() { - format!( - " {{spinner:.{}}} {{msg}} {{elapsed}}", - palette::accent_token() - ) - } else { - " {spinner} {msg} {elapsed}".to_owned() + return Progress::hidden(); } + Progress::start(msg.into(), Some(len)) } -fn bar_template() -> String { - if color() { - format!( - " {{msg}} [{{bar:30.{}}}] {{pos}}/{{len}} {{elapsed}}", - palette::accent_token() - ) +/// How often a live spinner or bar is redrawn. +const TICK: Duration = Duration::from_millis(90); + +/// A spinner or a bar on stderr, redrawn by a thread of its own. Clones share +/// one display, so workers can count on it; a hidden one draws nothing. +#[derive(Clone)] +pub struct Progress(Option>); + +struct Live { + msg: String, + len: Option, + pos: AtomicU64, + started: Instant, + done: AtomicBool, + ticker: Mutex>>, +} + +impl Progress { + pub fn hidden() -> Self { + Self(None) + } + + #[cfg(test)] + fn is_hidden(&self) -> bool { + self.0.is_none() + } + + fn start(msg: String, len: Option) -> Self { + let live = Arc::new(Live { + msg, + len, + pos: AtomicU64::new(0), + started: Instant::now(), + done: AtomicBool::new(false), + ticker: Mutex::new(None), + }); + let watched = Arc::downgrade(&live); + let ticker = std::thread::spawn(move || { + let mut tick = 0_usize; + while let Some(live) = watched.upgrade() + && !live.done.load(Ordering::Relaxed) + { + live.draw(tick); + drop(live); + tick = tick.wrapping_add(1); + std::thread::park_timeout(TICK); + } + }); + *live.ticker.lock().unwrap_or_else(PoisonError::into_inner) = + Some(ticker); + Self(Some(live)) + } + + pub fn inc(&self, units: u64) { + if let Some(live) = &self.0 { + live.pos.fetch_add(units, Ordering::Relaxed); + } + } + + /// Stop drawing and wipe the line, at once rather than at the next tick. + pub fn finish_and_clear(&self) { + let Some(live) = &self.0 else { return }; + live.done.store(true, Ordering::Relaxed); + let ticker = + live.ticker.lock().unwrap_or_else(PoisonError::into_inner).take(); + if let Some(ticker) = ticker { + ticker.thread().unpark(); + let _ = ticker.join(); + } + clear_line(); + } +} + +impl Live { + fn draw(&self, tick: usize) { + let width = terminal_size::terminal_size_of(std::io::stderr()) + .map_or(80, |(w, _)| usize::from(w.0)); + let line = frame( + &self.msg, + self.len, + self.pos.load(Ordering::Relaxed), + self.started.elapsed(), + tick, + width, + ); + let _ = write!(anstream::stderr(), "\r{line}"); + erase_to_end(); + } +} + +/// A display dropped without [`Progress::finish_and_clear`], as on an early +/// return, still leaves a clean line. One already cleared is left alone, since +/// the line under the cursor may by then be output. +impl Drop for Live { + fn drop(&mut self) { + if !self.done.load(Ordering::Relaxed) { + clear_line(); + } + } +} + +fn clear_line() { + let _ = write!(std::io::stderr(), "\r"); + erase_to_end(); +} + +/// Erase from the cursor to the end of the line. Written past anstream, +/// which strips every escape sequence when color is off, not only colors, +/// so `NO_COLOR` would leave each frame's tail and the last frame on screen. +/// A display draws only on a live terminal, which understands it. +fn erase_to_end() { + let _ = write!(std::io::stderr(), "\x1b[K"); +} + +/// One frame, ` ⠹ msg 3s` or ` msg [███░░░] 2/4 3s`, cut to fit a terminal +/// `width` columns wide by shortening the message, so it never wraps. +fn frame( + msg: &str, + len: Option, + pos: u64, + elapsed: Duration, + tick: usize, + width: usize, +) -> String { + const BAR: usize = 30; + let secs = elapsed.as_secs(); + let time = if secs < 60 { + format!("{secs}s") } else { - " {msg} [{bar:30}] {pos}/{len} {elapsed}".to_owned() + format!("{}m {:02}s", secs / 60, secs % 60) + }; + let (mark, suffix) = match len { + None => { + let ticks = if unicode() { + "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏" + } else { + "|/-\\" + }; + let at = tick.checked_rem(ticks.chars().count()).unwrap_or(0); + let spin = ticks.chars().nth(at).unwrap_or(' ').to_string(); + (Some(spin), format!(" {time}")) + } + Some(len) => { + let (full, empty) = + if unicode() { ("█", "░") } else { ("#", "-") }; + let filled = pos + .min(len) + .saturating_mul(BAR as u64) + .checked_div(len) + .and_then(|f| usize::try_from(f).ok()) + .unwrap_or(0); + let bar = full.repeat(filled) + + &empty.repeat(BAR.saturating_sub(filled)); + ( + None, + format!( + " [{}] {pos}/{len} {time}", + paint(palette::accent(), bar) + ), + ) + } + }; + let indent = if mark.is_some() { 4 } else { 2 }; + let fixed = visible(&suffix).saturating_add(indent); + let room = width.saturating_sub(1).saturating_sub(fixed); + let msg = if msg.chars().count() <= room { + msg.to_owned() + } else { + let cut: String = msg.chars().take(room.saturating_sub(3)).collect(); + cut + "..." + }; + match mark { + Some(spin) => { + format!(" {} {msg}{suffix}", paint(palette::accent(), spin)) + } + None => format!(" {msg}{suffix}"), } } +/// Columns a string takes, escape sequences not counted. +fn visible(text: &str) -> usize { + let mut in_escape = false; + text.chars() + .filter(|&c| { + if c == '\x1b' { + in_escape = true; + } else if in_escape { + in_escape = !c.is_ascii_alphabetic(); + return false; + } + !in_escape + }) + .count() +} + #[cfg(test)] mod tests { use std::sync::{Mutex, MutexGuard}; @@ -217,16 +381,39 @@ mod tests { } } - // A bad template falls back to indicatif's default at runtime, so this is - // the only thing that catches a typo. #[test] - fn templates_parse_in_both_color_modes() { + fn frames_show_progress_and_never_wrap() { let _guard = locked(); - for color in [true, false] { - set(Mode::Live, true, color); - ProgressStyle::with_template(&spinner_template()).unwrap(); - ProgressStyle::with_template(&bar_template()).unwrap(); - } + set(Mode::Live, false, false); + let secs = Duration::from_secs; + assert_eq!( + frame("scanning", None, 0, secs(3), 1, 80), + " / scanning 3s" + ); + assert_eq!( + frame("sources", Some(4), 2, secs(75), 0, 80), + " sources [###############---------------] 2/4 1m 15s" + ); + assert_eq!( + frame("sources", Some(0), 0, secs(0), 0, 80), + " sources [------------------------------] 0/0 0s" + ); + assert_eq!( + frame( + "a very long message about catalogs", + None, + 0, + secs(0), + 4, + 20 + ), + " | a very lo... 0s" + ); + let plain = frame("x", Some(1), 1, secs(0), 0, 80); + set(Mode::Live, false, true); + let colored = frame("x", Some(1), 1, secs(0), 0, 80); + assert_ne!(colored, plain); + assert_eq!(visible(&colored), plain.chars().count()); } #[test] From 02cfe5f77198b442402ae7a9640ee647c8bff374 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Fri, 23 Oct 2026 19:11:35 +0100 Subject: [PATCH 06/17] perf: the man page is written without clap_mangen, 33 to 39 KB smaller, and names commands instead of pages that do not exist --- Cargo.lock | 17 ----- Cargo.toml | 1 - docs/reference/contract.md | 2 +- src/help.rs | 152 ++++++++++++++++++++++++++++--------- src/lib.rs | 7 +- tests/cli.rs | 14 +++- 6 files changed, 132 insertions(+), 61 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f63bb9a..eb7755d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -318,16 +318,6 @@ version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" -[[package]] -name = "clap_mangen" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "211d617eaa4b735c96c9e0228fcbdb5120ef623f2b8cb67ffb84c3e02dbc28a4" -dependencies = [ - "clap", - "roff", -] - [[package]] name = "codspeed" version = "5.0.2" @@ -507,7 +497,6 @@ dependencies = [ "assert_cmd", "clap", "clap_complete", - "clap_mangen", "codspeed-criterion-compat", "etcetera", "insta", @@ -1427,12 +1416,6 @@ dependencies = [ "windows-sys 0.52.0", ] -[[package]] -name = "roff" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "323c417e1d9665a65b263ec744ba09030cfb277e9daa0b018a4ab62e57bc8189" - [[package]] name = "rustc_version" version = "0.4.1" diff --git a/Cargo.toml b/Cargo.toml index edf857a..ef5d696 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -44,7 +44,6 @@ anstream = "1" anstyle-query = "1" clap = { version = "4", features = ["derive", "env", "wrap_help"] } clap_complete = "4" -clap_mangen = "0.3" etcetera = "0.11" quick-xml = "0.42" serde = { version = "1", features = ["derive"] } diff --git a/docs/reference/contract.md b/docs/reference/contract.md index ac8355a..ae25321 100644 --- a/docs/reference/contract.md +++ b/docs/reference/contract.md @@ -118,7 +118,7 @@ dsk man > ~/.local/share/man/man1/dsk.1 # then: man dsk `man` is a hidden command: the overview, `-h` and `--help` leave it out, `dataseek help --json` still lists it, as it lists every command that runs. -Both are data, so both go to stdout, and both are derived from the clap definition rather than maintained by hand. The man page is rendered on demand by `clap_mangen` instead of at build time by a build script, so it cannot drift from the flags. `help::man_page` adds two things clap_mangen does not: a flag hidden from `-h` still gets its description, and the examples, exit codes (from `EXIT_CODES`, like `help exit-codes`) and bug address become EXAMPLES, EXIT STATUS and REPORTING BUGS sections. The tests assert the page carries the manifest version, renders without errors, names every command, describes every option and has those three sections, and that fish parses the completion script. +Both are data, so both go to stdout, and both are derived from the clap definition rather than maintained by hand. The man page is rendered on demand by `help::man_page`, which writes the roff itself from the clap definition instead of at build time by a build script, so it cannot drift from the flags. A flag hidden from `-h` still gets its description, and the examples, exit codes (from `EXIT_CODES`, like `help exit-codes`) and bug address become EXAMPLES, EXIT STATUS and REPORTING BUGS sections. It leaves the date empty, so two builds of one commit print the same page. The tests assert the page carries the manifest version, renders without errors, names every command, describes every option and has those three sections, and that fish parses the completion script. ## Color diff --git a/src/help.rs b/src/help.rs index 16e4ca4..7244ddf 100644 --- a/src/help.rs +++ b/src/help.rs @@ -197,46 +197,94 @@ pub fn show_man(page: &[u8]) -> bool { .is_ok_and(|status| status.success()) } -/// The man page, in roff. clap_mangen draws the flags and commands from the -/// plain definition, because roff would run together the value lists that -/// `cli::command()` writes into the long help. Two fixes on top: -/// -/// - A flag hidden from `-h` has no long help of its own, and clap_mangen -/// would print it with no description, so its help becomes its long help. -/// - The examples, exit codes and bug address that `--help` closes with -/// become EXAMPLES, EXIT STATUS and REPORTING BUGS instead of one EXTRA -/// section, from the same examples and from [`EXIT_CODES`]. -pub fn man_page() -> std::io::Result> { +/// The man page, in roff, drawn from the plain definition, because roff +/// would run together the value lists that `cli::command()` writes into the +/// long help. A flag hidden from `-h` has no long help of its own, so its +/// help stands in. The examples, exit codes and bug address that `--help` +/// closes with become EXAMPLES, EXIT STATUS and REPORTING BUGS, from the +/// same examples and from [`EXIT_CODES`]. +pub fn man_page() -> String { + use std::fmt::Write as _; + use clap::CommandFactory; - let cmd = cli::Cli::command() - .after_help(None::<&'static str>) - .after_long_help(None::<&'static str>) - .mut_args(|arg| match arg.get_help().cloned() { - Some(help) - if arg.is_hide_short_help_set() - && arg.get_long_help().is_none() => - { - arg.long_help(help) + let mut cmd = cli::Cli::command(); + cmd.build(); + let name = cmd.get_name(); + let version = env!("CARGO_PKG_VERSION"); + let about = cmd.get_about().map(ToString::to_string).unwrap_or_default(); + let mut page = format!( + ".ie \\n(.g .ds Aq \\(aq\n.el .ds Aq '\n\ + .TH {name} 1 \"\" \"{name} {version}\"\n\ + .SH NAME\n{name} \\- {}\n.SH SYNOPSIS\n\\fB{name}\\fR", + roff(&about) + ); + let options: Vec<&Arg> = cmd + .get_arguments() + .filter(|arg| !arg.is_hide_set() && !arg.is_positional()) + .collect(); + for arg in &options { + let repeats = matches!(arg.get_action(), ArgAction::Count); + let _ = write!( + page, + " [{}]{}", + flags(arg, "|"), + if repeats { "..." } else { "" } + ); + } + page.push_str(" [\\fIcommand\\fR]\n.SH DESCRIPTION\n"); + let description = cmd.get_long_about().map(ToString::to_string); + page.push_str(&lines(&description.unwrap_or(about), ".PP")); + page.push_str(".SH OPTIONS\n"); + for arg in &options { + let _ = write!(page, ".TP\n{}", flags(arg, ", ")); + if arg.get_action().takes_values() { + for value in arg.get_value_names().unwrap_or_default() { + let _ = write!(page, " \\fI<{}>\\fR", roff(value.as_str())); } - _ => arg, - }); - let mut rendered = Vec::new(); - clap_mangen::Man::new(cmd).render(&mut rendered)?; - let mut page = String::from_utf8_lossy(&rendered).into_owned(); - let closing = closing_sections(); - match page.find(".SH VERSION") { - Some(at) => page.insert_str(at, &closing), - None => page.push_str(&closing), + let defaults: Vec<_> = arg + .get_default_values() + .iter() + .map(|value| value.to_string_lossy()) + .collect(); + if !defaults.is_empty() && !arg.is_hide_default_value_set() { + let _ = + write!(page, " [default: {}]", roff(&defaults.join(","))); + } + } + let help = arg.get_long_help().or_else(|| arg.get_help()); + let help = help.map(ToString::to_string).unwrap_or_default(); + let _ = write!(page, "\n{}", lines(&help, ".br")); + let values: Vec<_> = arg + .get_possible_values() + .into_iter() + .filter(|value| !value.is_hide_set()) + .collect(); + if !values.is_empty() && !arg.is_hide_possible_values_set() { + page.push_str(".br\n\\fIPossible values:\\fR\n.RS 14\n"); + for value in values { + let meaning = value.get_help().map(|help| format!(": {help}")); + let item = format!( + "{}{}", + value.get_name(), + meaning.unwrap_or_default() + ); + let _ = writeln!(page, ".IP \\(bu 2\n{}", roff(&item)); + } + page.push_str(".RE\n"); + } } - Ok(page.into_bytes()) -} - -fn closing_sections() -> String { - use std::fmt::Write as _; - - let roff = |text: &str| text.replace('\\', "\\e").replace('-', "\\-"); - let mut page = String::from(".SH EXAMPLES\n.nf\n"); + page.push_str(".SH COMMANDS\n"); + for sub in cmd.get_subcommands().filter(|sub| !sub.is_hide_set()) { + let about = sub.get_about().map(ToString::to_string); + let _ = writeln!( + page, + ".TP\n\\fB{}\\fR\n{}", + roff(sub.get_name()), + roff(&about.unwrap_or_default()) + ); + } + page.push_str(".SH EXAMPLES\n.nf\n"); for line in cli::examples!().lines().skip(1) { let _ = writeln!(page, "{}", roff(line)); } @@ -246,9 +294,41 @@ fn closing_sections() -> String { } let issues = concat!(env!("CARGO_PKG_REPOSITORY"), "/issues"); let _ = writeln!(page, ".SH \"REPORTING BUGS\"\n{}", roff(issues)); + let _ = writeln!(page, ".SH VERSION\nv{version}"); page } +/// An option's flags in bold, `-q` before `--quiet`, joined by `separator`. +fn flags(arg: &Arg, separator: &str) -> String { + let short = arg.get_short().map(|c| format!("-{c}")); + let long = arg.get_long().map(|long| format!("--{long}")); + short + .into_iter() + .chain(long) + .map(|flag| format!("\\fB{}\\fR", roff(&flag))) + .collect::>() + .join(separator) +} + +/// Each line of `text` as a line of roff, a blank one as the `blank` +/// request. +fn lines(text: &str, blank: &str) -> String { + text.lines() + .map(|line| match line.trim() { + "" => format!("{blank}\n"), + _ => format!("{}\n", roff(line)), + }) + .collect() +} + +/// `text` as roff text: backslashes, hyphens and quotes escaped, and a +/// leading period kept from reading as a request. +fn roff(text: &str) -> String { + let escaped = + text.replace('\\', "\\e").replace('-', "\\-").replace('\'', "\\*(Aq"); + if escaped.starts_with('.') { format!("\\&{escaped}") } else { escaped } +} + /// clap's styled help as ANSI text; the stream decides whether it stays. fn ansi(help: &StyledStr) -> String { help.ansi().to_string() diff --git a/src/lib.rs b/src/lib.rs index 1d2e661..fbba63e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -303,9 +303,10 @@ fn run(cli: Cli, out: &Out) -> anyhow::Result<()> { } // Rendered on demand so the page cannot drift from the flags. Command::Man => { - let page = help::man_page()?; - if !(io::stdout().is_terminal() && help::show_man(&page)) { - out.stdout().write_all(&page)?; + let page = help::man_page(); + if !(io::stdout().is_terminal() && help::show_man(page.as_bytes())) + { + out.stdout().write_all(page.as_bytes())?; } } Command::Help { topic } => help::run(topic.as_deref(), out)?, diff --git a/tests/cli.rs b/tests/cli.rs index 9c8d404..fd284b8 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -1366,15 +1366,23 @@ fn man_renders_roff_with_the_manifest_version() { #[test] fn the_man_page_renders_and_lists_every_command() { let Some(mut renderer) = tool("mandoc") else { return }; - // Errors only: clap_mangen's output draws style warnings (the date - // field, paragraph macros) that are not ours to fix. + // Errors only: the page leaves its date empty, which mandoc warns about, + // because a build date would make two builds of one commit differ. renderer.args(["-T", "utf8", "-W", "error"]); let dir = tempfile::tempdir().unwrap(); let page = dir.path().join("dataseek.1"); std::fs::write(&page, stdout_text(&["man"])).unwrap(); let out = renderer.arg(&page).output().unwrap(); assert!(out.status.success(), "{out:?}"); - let text = String::from_utf8_lossy(&out.stdout); + // Bold is drawn by overstriking, `m\bm`; keep the second of each pair. + let mut text = String::new(); + for c in String::from_utf8_lossy(&out.stdout).chars() { + if c == '\u{8}' { + text.pop(); + } else { + text.push(c); + } + } let help = json_of(&["help", "--json"]); for command in help["command"]["commands"].as_array().unwrap() { let name = command["name"].as_str().unwrap(); From 15304fed1bcf318943c399ab5cbacee947283db2 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Fri, 23 Oct 2026 19:26:52 +0100 Subject: [PATCH 07/17] test: a bench for Markdown descriptions, which CKAN, data.gov and OpenNeuro records go through --- benches/search.rs | 32 +++++++++++++++++++++++++++++--- src/lib.rs | 2 +- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/benches/search.rs b/benches/search.rs index b37a0d5..dd65fd0 100644 --- a/benches/search.rs +++ b/benches/search.rs @@ -1,6 +1,6 @@ //! The CPU side of a search, by stage: parsing downloaded catalogs, loading //! a cached catalog, searching it, fusing the per-source lists and cleaning -//! remote text. Network time dwarfs all of it; these exist so a change that +//! remote text, Markdown descriptions included. Network time dwarfs all of it; these exist so a change that //! makes one stage grow faster than its input shows up before a user waits //! on it (ADR 0012). //! @@ -25,8 +25,8 @@ use criterion::{ criterion_main, }; use dataseek::internals::{ - Cache, Dataset, Kind, catalog_search, clean, eurostat_toc, merge, - sdmx_dataflows, weigh, + Cache, Dataset, Kind, catalog_search, clean, eurostat_toc, from_markdown, + merge, sdmx_dataflows, weigh, }; #[rustfmt::skip] @@ -179,6 +179,18 @@ fn html(bytes: usize) -> String { paragraph.repeat(bytes.div_ceil(paragraph.len())) } +/// A CKAN `notes` field: a heading, a list, links, emphasis, code and an +/// image, the marks `from_markdown` strips. +fn markdown(bytes: usize) -> String { + let section = "## Sea surface temperature\n\n\ + Monthly **gridded** fields from [NOAA ERSST](https://example.org/sst) \ + and _partners_, with `sst_anomaly` in kelvin.\n\n\ + - Coverage: 1854 to present\n\ + - Resolution: 2 degrees\n\ + ![map](https://example.org/map.png)\n\n"; + section.repeat(bytes.div_ceil(section.len())) +} + /// Prose whose ampersands start no entity, as in "R&D" or "Q&A", and which /// has no semicolon to end one. fn ampersands(bytes: usize) -> String { @@ -303,6 +315,20 @@ fn sanitize(c: &mut Criterion) { } group.finish(); + let mut group = c.benchmark_group("markdown"); + for bytes in [200, 2_000, 20_000] { + let text = markdown(bytes); + group.throughput(Throughput::Bytes(text.len() as u64)); + group.bench_with_input( + BenchmarkId::from_parameter(bytes), + &text, + |b, text| { + b.iter(|| from_markdown(black_box(text))); + }, + ); + } + group.finish(); + let mut group = c.benchmark_group("clean/ampersands"); for bytes in [2_000, 20_000] { let text = ampersands(bytes); diff --git a/src/lib.rs b/src/lib.rs index fbba63e..99bb7ed 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -55,7 +55,7 @@ pub mod internals { pub use crate::catalog::search as catalog_search; pub use crate::catalog::{MAX_TERMS, found, needles, terms, words}; pub use crate::dedup::{Hit, identity_keys, idf, merge, weigh}; - pub use crate::record::{Dataset, clean}; + pub use crate::record::{Dataset, clean, from_markdown}; pub use crate::search::{Outcome, Plan, Status, quorum, run as search}; pub use crate::sources::eurostat::parse as eurostat_toc; pub use crate::sources::sdmx::flows as sdmx_dataflows; From 11cad236ee9ecff354e87e31790509d3b21c3b8b Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Fri, 23 Oct 2026 19:31:13 +0100 Subject: [PATCH 08/17] doc: binary size after the dependency replacements, measured per commit, and the ureq watch item closed --- _typos.toml | 2 + docs/adr/watchlist.md | 6 -- docs/bench/2026-10-07-binary-size.md | 2 +- docs/bench/2026-10-23-binary-size.md | 102 +++++++++++++++++++++++++++ 4 files changed, 105 insertions(+), 7 deletions(-) create mode 100644 docs/bench/2026-10-23-binary-size.md diff --git a/_typos.toml b/_typos.toml index bde257d..3b47e98 100644 --- a/_typos.toml +++ b/_typos.toml @@ -17,4 +17,6 @@ extend-ignore-re = [ # HTML entity names, decoded in src/record.rs. "\"curren\"", "café", + # The ELF section of dynamic relocation records. + "\\.rela\\.dyn", ] diff --git a/docs/adr/watchlist.md b/docs/adr/watchlist.md index 29d8bc0..d008c92 100644 --- a/docs/adr/watchlist.md +++ b/docs/adr/watchlist.md @@ -81,9 +81,3 @@ Trigger: published documentation and terms for the API, or the v2 indicator list `-Zfmt-debug=none` (-224 KiB), `-Zlocation-detail=none` (-96 KiB) and the `optimize_for_size` std feature through `build-std` (-288 KiB) all shrink the release binary further ([measurement](../bench/2026-10-07-binary-size.md)). Parked because `rust-toolchain.toml` pins stable and a release profile cannot set them there. Trigger: any of them stabilizes as a `[profile]` key or a stable `-C` flag. Re-run `just bloat --what-if --levers=` before adopting it. - -## ureq without the bundled root store on macOS and Windows - -`src/http.rs` verifies through the platform's trust store there, yet ureq's `native-tls` feature also links `webpki-root-certs`. `native-tls-no-default` would drop it, but ureq 3.4.2 compiles its native-tls connector only under `native-tls`, so that build panics on the first HTTPS request. - -Trigger: a ureq release whose native-tls connector works under `native-tls-no-default`. A live `dataseek search` on macOS is the test, because no test here makes a real TLS connection. diff --git a/docs/bench/2026-10-07-binary-size.md b/docs/bench/2026-10-07-binary-size.md index 826dd97..28307c3 100644 --- a/docs/bench/2026-10-07-binary-size.md +++ b/docs/bench/2026-10-07-binary-size.md @@ -93,7 +93,7 @@ Criterion, `just bench --baseline main`, median change against v0.6.0: ### Dependencies - `toml`, `signal-hook` and `indicatif` lost the default features dataseek never uses (`display`, `channel` and `iterator`, `wasmbind`). Thin LTO had already dropped that code, so the binary did not change; the lockfile lost 13 crates. -- `ureq` on macOS and Windows still bundles the Mozilla root store (`webpki-root-certs`), which the platform verifier never reads. ureq 3.4.2 compiles its native-tls connector only under the `native-tls` feature, which always pulls the roots in; `native-tls-no-default` builds, then panics on the first HTTPS request. See the watch list. +- `ureq` on macOS and Windows still bundles the Mozilla root store (`webpki-root-certs`), which the platform verifier never reads. ureq 3.4.2 compiles its native-tls connector only under the `native-tls` feature, which always pulls the roots in; `native-tls-no-default` builds, then panics on the first HTTPS request. ureq 3.5 fixed it ([2026-10-23](2026-10-23-binary-size.md)). - The duplicate `base64` (0.22 through jaq-std, 0.23 through ureq) left with `--jq`. ### --jq diff --git a/docs/bench/2026-10-23-binary-size.md b/docs/bench/2026-10-23-binary-size.md new file mode 100644 index 0000000..1c445f5 --- /dev/null +++ b/docs/bench/2026-10-23-binary-size.md @@ -0,0 +1,102 @@ +# Release binary size, 2026-10-23 + +## Question + +Which dependencies cost more bytes than the part of them dataseek uses, and what does replacing or trimming each one save, without slowing a search? Primary metric: the file size of the stripped release `dataseek` binary, which is what a download costs. Second metric: the size of the release archive. Speed must not regress: `just relevance`, `just bench-startup`, the replaced code timed against what it replaced, and CodSpeed on the pull request. + +## Machine + +```text +date 2026-10-23 UTC +os macOS 27.0.1 arm64 +cpu Apple M4 +performance_cores 4 +efficiency_cores 6 +memory_gib 16 +power mains, battery charged +rustc 1.99.1 +llvm 23.1.1 +host aarch64-apple-darwin +cross builds cargo-zigbuild with zig 0.17.0 +size tool cargo-bsize 0.0.2 +baseline commit 2f5c27c (v0.10.0) +``` + +## Setup + +- Every build ran under `flock /tmp/heavy-build.lock`, so nothing else compiled while a size or a time was taken. +- `aarch64-apple-darwin` was built with `cargo build --release`, `x86_64-unknown-linux-gnu` with `cargo zigbuild --release`. Each commit of the branch was built on its own, so each row's change is that commit alone. +- Candidates were first measured as stubs: the dependency's call replaced by the cheapest stand-in, which bounds what a rewrite can save. Only candidates whose bound was worth a rewrite were rewritten, and the rewrite was measured again. +- Clean build times were taken with `RUSTC_WRAPPER=` so sccache could not serve cached crates, twice per commit. + +## Results + +File size of the stripped release binary, in bytes, each commit on top of the one before. + +| commit | `aarch64-apple-darwin` | change | `x86_64-unknown-linux-gnu` | change | +|---|---:|---:|---:|---:| +| v0.10.0 | 2,764,128 | | 4,351,152 | | +| ureq 3.5 without the Mozilla root store | 2,648,672 | -115,456 | 4,296,232 | -54,920 | +| Markdown stripped without pulldown-cmark | 2,466,608 | -182,064 | 3,983,720 | -312,512 | +| `credentials.toml` read without toml | 2,399,952 | -66,656 | 3,885,536 | -98,184 | +| progress drawn without indicatif | 2,316,560 | -83,392 | 3,797,176 | -88,360 | +| man page written without clap_mangen | 2,283,248 | -33,312 | 3,758,392 | -38,784 | +| total | | -480,880 (-17.4%) | | -592,760 (-13.6%) | + +Release archive of the final build, `dataseek` and `dsk` inside: + +| archive | `aarch64-apple-darwin` | `x86_64-unknown-linux-gnu` | +|---|---:|---:| +| `.tar.gz`, as v0.10.0 packed it | 2,363,031 | 3,689,377 | +| `.tar.xz` | 863,412 | 1,493,620 | + +gzip's 32 KB window never sees that `dsk` repeats `dataseek`, so a `.tar.gz` holds two compressed copies. xz's window spans both, so `dsk` costs a few hundred bytes. The `.tar.xz` is 63% (macOS) and 60% (Linux) smaller than a `.tar.gz` of the same binaries; against v0.10.0's Linux archive, 4,059,170 bytes, the download is 63% smaller. + +### What each change replaced + +- **ureq 3.5.** `native-tls-no-default` now builds a working connector (ureq PR #1204), so macOS and Windows stop linking `webpki-root-certs`, which `RootCerts::PlatformVerifier` never reads. Linux moved to `rustls-no-provider` with ring's provider passed in `src/http.rs`, which drops the same roots there. A live `dataseek search` over each TLS stack is the test, because no test here makes a real TLS connection. +- **pulldown-cmark.** Descriptions only need Markdown turned into plain text, not parsed into a tree. `record::from_markdown` strips fences, rules, link definitions, list and quote markers and headings line by line, then pairs code spans, brackets and emphasis in one linear, non-recursive pass. Over every string in the recorded fixtures, 4,693 of 4,697 come out the same as before; of the four that differ, one reads better (`**Title:**Plasma`) and three are an opendatasoft field that never goes through Markdown. A test feeds it 50,000 nested openers of every kind and asserts linear time. Over the same strings, `clean(from_markdown(..))`, which is what a record's description goes through, takes 56 ms per 20 passes against 62 ms with pulldown-cmark, best of 7, and 3.65 ms against 4.41 ms on a 20 KB synthetic description. The new `markdown` bench group keeps it measured. The first version was twice as slow as pulldown-cmark, because it matched every line for code, links and emphasis and copied one character at a time; it now skips a match whose opening byte the line lacks and copies plain runs whole. +- **toml.** `credentials.toml` holds one `name = "value"` per line. `credentials::flat_table` reads exactly that, with TOML's string escapes, and treats anything else (a table, a multi-line string, a duplicate key) as supplying no key at all. +- **indicatif.** dataseek draws one spinner or one bar at a time. `ui::Progress` is a ticker thread redrawing one line every 90 ms and clearing it when the work finishes or the handle drops. +- **clap_mangen.** The page has one fixed shape: options, commands, examples, exit status. `help::man_page` writes that roff from the clap definition. It also stopped referring to `dataseek-search(1)` and the other per-command pages, which were never installed. + +### Measured and not adopted + +On `aarch64-apple-darwin` unless the row says otherwise; the base is the binary before the man page change, 2,316,560 bytes. + +| lever | change | why not | +|---|---:|---| +| clap without `suggestions` | -16,560 | a mistyped flag loses its `a similar argument exists` tip | +| clap without `wrap_help` | -48 | nothing to gain | +| clap without `error-context` | 0 | nothing to gain | +| ASCII-only uppercasing in `record::file_format` | -16 | the 25 KiB case table bsize flags is the lowercase one, which matching needs | +| Linux: ring provider cut to AES-GCM suites and X25519, P-256 | +384 | ring links every cipher either way | +| Linux: `--icf=all` | | zig's linker rejects it; fat LTO with one codegen unit already merges identical functions | +| `panic = "abort"`, on v0.10.0 | -413,936 | a panicking adapter would end the whole search instead of failing one source | +| replacing anyhow | | 5.3 KiB of crate code; a boxed error with a context wrapper adds back most of it | + +### Why Linux stays larger + +On macOS and Windows the TLS stack is the operating system's, linked dynamically. On Linux it is in the binary: rustls (306 KiB), ring's C and assembly (316 KiB, of which `ecp_nistz256_precomputed`, the P-256 table, is 148 KiB), ring's Rust (90 KiB) and webpki (53 KiB), about 760 KiB together. A position-independent ELF adds 112 KiB of `.rela.dyn` relocation records, x86_64 code is less dense than arm64, and its unwind tables are larger. Linking the system OpenSSL instead is not an option for the manylinux wheels the Linux binaries ship in: auditwheel would vendor libssl into the wheel. + +### Compile time + +Clean builds of `dataseek` with sccache off (`RUSTC_WRAPPER=`) and eight jobs, twice each: + +| build | v0.10.0 | after | crates linked on macOS | +|---|---:|---:|---:| +| release | 30 s | 27 s | 95 -> 79 | +| dev | 7 s | 6 to 7 s | | + +The release build spends most of its time in one fat-LTO codegen unit, so sixteen fewer crates save three seconds. A faster linker would save less: on Linux, rustc already links with rust-lld, and mold or wild cut a link that is a few percent of a release build to about one percent. Neither runs on macOS. + +## Verdict + +Five dependencies were each replaced by the few dozen to few hundred lines dataseek needed of them: the binary is 17.4% smaller on macOS and 13.6% on Linux, and the archive a user downloads is about 60% smaller. Every test passes and `just relevance` is unchanged at nDCG@10 0.6403. The largest lever left is `panic = "abort"`, kept off because one adapter's panic would end the whole search. + +## Caveats + +- A live search over native-tls on macOS answered from 70 of 71 sources. The Linux TLS change (rustls without a bundled provider, ring's passed in) was not tried live: no Linux machine or container was available, and CI's Linux job builds and tests it without a TLS connection. +- The Linux binary was cross-built with zig as the linker; the release job builds natively. Its relative changes are the result, its absolute size is not. +- Windows was not built. Its TLS stack and dependencies follow macOS, so its changes should too. +- The stub bounds overstate what a rewrite saves, because the rewrite's own code comes back: pulldown-cmark's stub saved 199 KB on macOS, the rewrite 182 KB. From a98aa4ccda22dccd87391726d99bdc3acadef4b0 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Fri, 23 Oct 2026 19:32:43 +0100 Subject: [PATCH 09/17] build: webpki-root-certs 1.0.11 clears RUSTSEC-2026-0383; no released target links it --- Cargo.lock | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index eb7755d..f84be2f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2050,9 +2050,9 @@ dependencies = [ [[package]] name = "webpki-root-certs" -version = "1.0.9" +version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b" +checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a" dependencies = [ "rustls-pki-types", ] From fc1c7c576b168d7f5ca12289f9e56567a4698b36 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Fri, 23 Oct 2026 19:33:00 +0100 Subject: [PATCH 10/17] fix: Linux builds reject certificate paths through the distrusted emSign intermediates (rustls-webpki 0.103.16, RUSTSEC-2026-0382) --- Cargo.lock | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f84be2f..e464071 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1512,9 +1512,9 @@ checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" [[package]] name = "rustls-webpki" -version = "0.103.15" +version = "0.103.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" dependencies = [ "ring", "rustls-pki-types", From 0ca3249f4c4ba5727f172f2a8189f81c2936b06c Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Fri, 23 Oct 2026 20:18:08 +0100 Subject: [PATCH 11/17] doc: binary size note covers the trixie archive and TLS check, the final Linux size, and why dataseek is not compiled for size --- docs/bench/2026-10-23-binary-size.md | 30 ++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/docs/bench/2026-10-23-binary-size.md b/docs/bench/2026-10-23-binary-size.md index 1c445f5..a60ea29 100644 --- a/docs/bench/2026-10-23-binary-size.md +++ b/docs/bench/2026-10-23-binary-size.md @@ -18,7 +18,9 @@ rustc 1.99.1 llvm 23.1.1 host aarch64-apple-darwin cross builds cargo-zigbuild with zig 0.17.0 -size tool cargo-bsize 0.0.2 +size tool cargo-bsize 0.0.2, bloaty +nightly rustc 1.101.0-nightly (2026-10-20), for the #[optimize] rows +containers colima 0.10.3, Docker Engine 29.5.2, debian:trixie baseline commit 2f5c27c (v0.10.0) ``` @@ -41,7 +43,10 @@ File size of the stripped release binary, in bytes, each commit on top of the on | `credentials.toml` read without toml | 2,399,952 | -66,656 | 3,885,536 | -98,184 | | progress drawn without indicatif | 2,316,560 | -83,392 | 3,797,176 | -88,360 | | man page written without clap_mangen | 2,283,248 | -33,312 | 3,758,392 | -38,784 | -| total | | -480,880 (-17.4%) | | -592,760 (-13.6%) | +| Windows console check, rustls-webpki 0.103.16 | 2,283,248 | 0 | 3,763,816 | +5,424 | +| total | | -480,880 (-17.4%) | | -587,336 (-13.5%) | + +The last row is two fixes that came after the size work: the progress line's check that a Windows console understands escape codes (`anstyle-query`, 1,200 bytes on Linux), and the rustls-webpki release that distrusts the emSign intermediates (4,224 bytes). Release archive of the final build, `dataseek` and `dsk` inside: @@ -74,6 +79,22 @@ On `aarch64-apple-darwin` unless the row says otherwise; the base is the binary | Linux: `--icf=all` | | zig's linker rejects it; fat LTO with one codegen unit already merges identical functions | | `panic = "abort"`, on v0.10.0 | -413,936 | a panicking adapter would end the whole search instead of failing one source | | replacing anyhow | | 5.3 KiB of crate code; a boxed error with a context wrapper adds back most of it | +| dataseek's own code at `opt-level = "z"`, on the final build | -558,112 | not timed; it can only be slower than the next row | +| the same, with every function in `cache`, `catalog`, `dedup`, `record`, `sdmx` and `eurostat` marked `#[optimize(speed)]` (nightly; stable from Rust 1.101) | -525,456 | parsing, matching and merging 10% to 75% slower | + +The last two rows are the largest lever left, and the reason it stays unused. Under fat LTO, dependency code inlined into dataseek is compiled at dataseek's level, so `z` shrinks clap's parser, `core` and the unwind tables along with dataseek's own functions. `#[optimize(speed)]` only covers the body of the function it marks: the serde, iterator, sort and hash code a marked function instantiates for dataseek's types is compiled as separate functions at the crate's `z`. Criterion medians on nightly, the shipped profile run before and after the split to bound noise (the two runs agreed within 1.3%): + +| group | split against shipped | +|---|---:| +| `markdown` | +75% | +| `catalog/load` | +60% | +| `parse/eurostat` | +54% | +| `merge` | +32% to +40% | +| `catalog/search` | +31% to +36% | +| `parse/sdmx` | +11% | +| `clean` | +10% | + +Keeping the hot modules at `opt-level = 3` on stable would need them in a second crate of the workspace, which would have to be published alongside dataseek for `cargo install` to build it. ### Why Linux stays larger @@ -92,11 +113,12 @@ The release build spends most of its time in one fat-LTO codegen unit, so sixtee ## Verdict -Five dependencies were each replaced by the few dozen to few hundred lines dataseek needed of them: the binary is 17.4% smaller on macOS and 13.6% on Linux, and the archive a user downloads is about 60% smaller. Every test passes and `just relevance` is unchanged at nDCG@10 0.6403. The largest lever left is `panic = "abort"`, kept off because one adapter's panic would end the whole search. +Five dependencies were each replaced by the few dozen to few hundred lines dataseek needed of them: the binary is 17.4% smaller on macOS and 13.5% on Linux, and the archive a user downloads is about 60% smaller. Every test passes and `just relevance` is unchanged at nDCG@10 0.6403. The two largest levers left are both kept off: compiling dataseek for size (-525 to -558 KB) slows parsing, matching and merging by up to 75%, and `panic = "abort"` (-414 KB) would let one adapter's panic end the whole search. ## Caveats -- A live search over native-tls on macOS answered from 70 of 71 sources. The Linux TLS change (rustls without a bundled provider, ring's passed in) was not tried live: no Linux machine or container was available, and CI's Linux job builds and tests it without a TLS connection. +- A live search over native-tls on macOS answered from 70 of 71 sources. The Linux binaries were tried in a `debian:trixie` container, arm64 natively and x86_64 under Rosetta: the release workflow's archive step, run as written, packed both targets; a fresh container checked each `.sha256` and unpacked the archive; both binaries printed their version and man page; without `ca-certificates` a search failed with the `Try:` line naming that package; with it, the v0.10.0 binary and this one, given the same query and `--timeout 0`, both answered from 70 of 71 sources, the same one (OpenNeuro, HTTP 502) failing for both. +- Debian's base image has no `xz`, so `tar xJf` on the archive fails there until `xz-utils` is installed. Desktop installs and most CI images carry it, and none of the documented installs needs the system's: Homebrew installs its own `xz` to unpack the formula's archive, `cargo binstall` decompresses in process, `uv` installs the wheel and `cargo install` builds from source. - The Linux binary was cross-built with zig as the linker; the release job builds natively. Its relative changes are the result, its absolute size is not. - Windows was not built. Its TLS stack and dependencies follow macOS, so its changes should too. - The stub bounds overstate what a rewrite saves, because the rewrite's own code comes back: pulldown-cmark's stub saved 199 KB on macOS, the rewrite 182 KB. From 732cd933a9e79cbce6a5656a2aad7ae3b8327322 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Fri, 23 Oct 2026 20:32:31 +0100 Subject: [PATCH 12/17] doc: std without its backtrace feature is 130 KiB smaller at the same speed, parked with the other nightly levers --- docs/adr/watchlist.md | 2 +- docs/bench/2026-10-23-binary-size.md | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/adr/watchlist.md b/docs/adr/watchlist.md index d008c92..05cbf31 100644 --- a/docs/adr/watchlist.md +++ b/docs/adr/watchlist.md @@ -78,6 +78,6 @@ Trigger: published documentation and terms for the API, or the v2 indicator list ## Nightly size levers -`-Zfmt-debug=none` (-224 KiB), `-Zlocation-detail=none` (-96 KiB) and the `optimize_for_size` std feature through `build-std` (-288 KiB) all shrink the release binary further ([measurement](../bench/2026-10-07-binary-size.md)). Parked because `rust-toolchain.toml` pins stable and a release profile cannot set them there. +`-Zfmt-debug=none` (-224 KiB), `-Zlocation-detail=none` (-96 KiB) and the `optimize_for_size` std feature through `build-std` (-288 KiB) all shrink the release binary further ([measurement](../bench/2026-10-07-binary-size.md)). So does `build-std` with std's `backtrace` feature left out (-130 KiB on macOS, search speed unchanged, [measurement](../bench/2026-10-23-binary-size.md)): panics still unwind and print their message, but `RUST_BACKTRACE=1` prints no frames. Parked because `rust-toolchain.toml` pins stable and a release profile cannot set them there. Trigger: any of them stabilizes as a `[profile]` key or a stable `-C` flag. Re-run `just bloat --what-if --levers=` before adopting it. diff --git a/docs/bench/2026-10-23-binary-size.md b/docs/bench/2026-10-23-binary-size.md index a60ea29..a3ff532 100644 --- a/docs/bench/2026-10-23-binary-size.md +++ b/docs/bench/2026-10-23-binary-size.md @@ -94,6 +94,8 @@ The last two rows are the largest lever left, and the reason it stays unused. Un | `parse/sdmx` | +11% | | `clean` | +10% | +std rebuilt without its `backtrace` feature (nightly `-Zbuild-std=std,panic_unwind -Zbuild-std-features=panic-unwind`, with `core`, `alloc`, `std` and `hashbrown` held at `opt-level = 3`) is the one lever here that costs no speed: 2,150,560 bytes against 2,283,296 for the same rebuild with the feature, -132,736, and every bench group within 2% of the shipped profile except `catalog/load/4000` at +4%, inside the 10% the two shipped runs differed by. It drops gimli, addr2line and rustc_demangle, which only symbolize a `RUST_BACKTRACE=1` trace; panics still unwind. It needs a nightly toolchain for the release build, so it joins the parked nightly levers in the watchlist. + Keeping the hot modules at `opt-level = 3` on stable would need them in a second crate of the workspace, which would have to be published alongside dataseek for `cargo install` to build it. ### Why Linux stays larger From 02cec7c00456c1ee1328f48573268ccba9ffe619 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Mon, 26 Oct 2026 12:42:13 +0000 Subject: [PATCH 13/17] fix: credentials.toml with a byte order mark or TOML 1.1 escapes supplies its keys again, and doctor names a file that supplies none --- docs/reference/keys-and-cache.md | 2 +- src/credentials.rs | 72 ++++++++++++++++++++++++++------ src/doctor.rs | 14 ++++++- tests/cli.rs | 12 ++++++ 4 files changed, 86 insertions(+), 14 deletions(-) diff --git a/docs/reference/keys-and-cache.md b/docs/reference/keys-and-cache.md index c0b4aba..ebe39e5 100644 --- a/docs/reference/keys-and-cache.md +++ b/docs/reference/keys-and-cache.md @@ -9,7 +9,7 @@ fred = "..." datagov = "..." ``` -Each key is one `name = "value"` line, in double or single quotes, with `#` comments allowed. A file holding anything else, such as a `[table]` header, a multi-line string or a name given twice, supplies no key at all. +Each key is one `name = "value"` line, in double or single quotes, with `#` comments allowed. A file holding anything else, such as a `[table]` header, a multi-line string or a name given twice, supplies no key at all, and `dataseek doctor` names it. | source | environment variable | file key | without it | get one | |---|---|---|---|---| diff --git a/src/credentials.rs b/src/credentials.rs index 7e4f7e5..fcbf9d3 100644 --- a/src/credentials.rs +++ b/src/credentials.rs @@ -128,16 +128,22 @@ impl fmt::Debug for Secret { #[derive(Default)] pub struct Credentials { found: HashMap, - /// Files holding a key that other users on the machine can read. + /// Key files that other users on the machine can read. pub loose_files: Vec, + /// A `credentials.toml` that exists but could not be read as a flat + /// table, so it supplied no key. + pub unread_file: Option, } impl Credentials { pub fn load(config_dir: &Path) -> Self { let mut creds = Self::default(); let file = config_dir.join("credentials.toml"); - let from_file = read_toml(&file); - if !from_file.is_empty() && is_loose(&file) { + let from_file = read_toml(&file).unwrap_or_else(|| { + creds.unread_file = Some(file.clone()); + HashMap::new() + }); + if is_loose(&file) { creds.loose_files.push(file.clone()); } for key in Key::ALL { @@ -179,19 +185,26 @@ fn env(var: &str) -> Option { .filter(|v| !v.is_empty()) } -fn read_toml(path: &Path) -> HashMap { - std::fs::read_to_string(path) - .ok() - .and_then(|text| flat_table(&text)) - .unwrap_or_default() +/// The table in `credentials.toml`, empty when there is no such file and +/// `None` when there is one that cannot be read as a table. +fn read_toml(path: &Path) -> Option> { + match std::fs::read_to_string(path) { + Ok(text) => flat_table(&text), + Err(err) if err.kind() == std::io::ErrorKind::NotFound => { + Some(HashMap::new()) + } + Err(_) => None, + } } /// `credentials.toml` as the flat table of `name = "value"` lines it is -/// documented to be, with comments and either kind of one-line string. Any -/// other line, such as a `[table]` header, a value that is not a string, a -/// multi-line string or a name given twice, makes the whole file unreadable, -/// so a file is read as TOML reads it or not at all. +/// documented to be, with comments, a leading byte order mark and either +/// kind of one-line string. Any other line, such as a `[table]` header, a +/// value that is not a string, a multi-line string or a name given twice, +/// makes the whole file unreadable, so a file is read as TOML reads it or +/// not at all. fn flat_table(text: &str) -> Option> { + let text = text.strip_prefix('\u{feff}').unwrap_or(text); let mut table = HashMap::new(); for line in text.lines().map(str::trim) { if line.is_empty() || line.starts_with('#') { @@ -242,6 +255,8 @@ fn toml_string(text: &str) -> Option<(String, &str)> { 'n' => '\n', 'f' => '\u{c}', 'r' => '\r', + 'e' => '\u{1b}', + 'x' => unicode_escape(&mut chars, 2)?, 'u' => unicode_escape(&mut chars, 4)?, 'U' => unicode_escape(&mut chars, 8)?, _ => return None, @@ -378,6 +393,39 @@ mod tests { } } + // The toml crate is the oracle: the file is TOML, read the way it was + // before dataseek read it by hand. + #[test] + fn the_credentials_file_reads_as_the_toml_crate_reads_it() { + for file in [ + "\u{feff}fred = \"a\"\n", + "\u{feff}# keys\nfred = \"a\"", + "fred = \"a\"\r\ndatagov = 'b'\r\n", + "fred = \"a#b\" # \"quoted\" comment", + "fred=\"a\"#tight", + "fred = \"\\e[0m\\x41\\t\\u00e9\\U0001F600\"", + "\"fred\" = \"a\"\nfred = \"b\"", + "fred = \"\\ud800\"", + "fred = \"\\x4\"", + "fred = 'a'b'", + "[keys]", + "fred = true", + ] { + let expected = + toml::from_str::>(file).ok(); + assert_eq!(flat_table(file), expected, "{file:?}"); + } + } + + #[test] + fn an_unreadable_credentials_file_is_reported_not_skipped() { + let dir = tempfile::tempdir().unwrap(); + assert_eq!(Credentials::load(dir.path()).unread_file, None); + let file = dir.path().join("credentials.toml"); + std::fs::write(&file, "[keys]\nfred = \"a\"\n").unwrap(); + assert_eq!(Credentials::load(dir.path()).unread_file, Some(file)); + } + #[test] fn the_credentials_file_supplies_missing_keys() { let dir = tempfile::tempdir().unwrap(); diff --git a/src/doctor.rs b/src/doctor.rs index 3b802bf..304e4fe 100644 --- a/src/doctor.rs +++ b/src/doctor.rs @@ -110,7 +110,8 @@ fn gather(out: &Out) -> Result> { /// One line per API key: where it was found, or where to get one. A missing /// key is never a failure, since sources without one run anonymously or are -/// skipped; a key file other users can read is. +/// skipped; a key file that supplies no key, or that other users can read, +/// is. fn keys(config: &std::path::Path) -> Vec { let creds = Credentials::load(config); let mut checks: Vec = Key::ALL @@ -124,6 +125,17 @@ fn keys(config: &std::path::Path) -> Vec { ok: true, }) .collect(); + if let Some(path) = &creds.unread_file { + checks.push(Check { + label: "key file".to_owned(), + detail: format!( + "{} supplies no key; write one name = \"value\" line per \ + key, nothing else", + path.display() + ), + ok: false, + }); + } for path in &creds.loose_files { checks.push(Check { label: "key file".to_owned(), diff --git a/tests/cli.rs b/tests/cli.rs index fd284b8..6aa7851 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -1221,6 +1221,18 @@ fn linux_with_no_roots_says_how_to_install_them() { assert_refused_certificate(&out); } +#[test] +fn doctor_names_a_credentials_file_that_supplies_no_key() { + let mut cmd = bin(); + let config = cmd.dir.path().join("config").join("dataseek"); + std::fs::create_dir_all(&config).unwrap(); + std::fs::write(config.join("credentials.toml"), "[keys]\nfred = \"a\"\n") + .unwrap(); + let out = cmd.args(["doctor", "--plain"]).output().unwrap(); + let text = String::from_utf8_lossy(&out.stdout); + assert!(text.contains("credentials.toml supplies no key"), "{text}"); +} + #[test] fn doctor_reports_ready_with_clean_pipe() { let out = bin().arg("doctor").output().unwrap(); From 8da8ff64b5b85505e3c56819154367a1fbc13f82 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Mon, 26 Oct 2026 12:45:24 +0000 Subject: [PATCH 14/17] fix: Markdown descriptions keep a wrapped line that starts with a year, a [label]: line that is not a link definition, and text after a line opening with a code span; Greek and math entities decode --- src/record.rs | 208 ++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 166 insertions(+), 42 deletions(-) diff --git a/src/record.rs b/src/record.rs index ba31f28..6e363a3 100644 --- a/src/record.rs +++ b/src/record.rs @@ -211,14 +211,16 @@ impl Spaced { } /// Markdown as the text its rendered page shows: link and emphasis text kept, -/// images, rules, fences and other markup dropped, a space between lines. -/// For fields a source documents as Markdown. Entities are decoded, as a -/// Markdown renderer does, so `<br>` becomes a tag; HTML is left for -/// [`clean`] to strip. It reads one line at a time, so emphasis or a link -/// broken across two lines keeps its marks, which a description can afford. +/// images, rules, fence lines and other markup dropped, a space between +/// lines. For fields a source documents as Markdown. Entities are decoded, +/// code included, so an escaped tag such as `<br>` reaches [`clean`] +/// as `
` and is stripped, where a rendered page would show it. It reads +/// one line at a time, so emphasis or a link broken across two lines keeps +/// its marks, which a description can afford. pub fn from_markdown(text: &str) -> String { let mut plain = String::with_capacity(text.len()); let mut fence = None; + let mut paragraph = false; for line in text.lines().map(str::trim) { if let Some(open) = fence { if line.starts_with(open) { @@ -226,12 +228,15 @@ pub fn from_markdown(text: &str) -> String { } else { plain.push_str(line); } - } else if let Some(open) = - ["```", "~~~"].into_iter().find(|f| line.starts_with(f)) - { + paragraph = false; + } else if let Some(open) = fence_opener(line) { fence = Some(open); - } else if !is_rule(line) && !is_link_definition(line) { - let content = block_content(line); + paragraph = false; + } else if is_rule(line) || is_link_definition(line) { + paragraph = false; + } else { + let content; + (content, paragraph) = block_content(line, paragraph); if content.starts_with('|') || content.ends_with('|') { inline(&content.replace('|', " "), &mut plain); } else { @@ -259,28 +264,64 @@ fn is_rule(line: &str) -> bool { delimiter_row || thematic } -/// `[label]: url`, which defines a link target and shows nothing. +/// The fence a line opens, ```` ``` ```` or `~~~`. A backtick fence's info +/// string holds no backtick, so a line starting with a ```` ```code``` ```` +/// span opens nothing. +fn fence_opener(line: &str) -> Option<&'static str> { + if line.starts_with("~~~") { + Some("~~~") + } else { + (line.starts_with("```") + && !line.trim_start_matches('`').contains('`')) + .then_some("```") + } +} + +/// `[label]: url`, with an optional quoted title, which defines a link +/// target and shows nothing. `[Note]: the data is preliminary` is text. fn is_link_definition(line: &str) -> bool { - line.strip_prefix('[') - .and_then(|rest| rest.split_once("]:")) - .is_some_and(|(label, _)| !label.contains(['[', ']'])) + line.strip_prefix('[').and_then(|rest| rest.split_once("]:")).is_some_and( + |(label, target)| { + let mut words = target.split_whitespace(); + !label.contains(['[', ']']) + && words.next().is_some() + && words + .next() + .is_none_or(|title| title.starts_with(['"', '\'', '('])) + }, + ) } /// The line without the markers that make it a quote, a list item or a -/// heading. -fn block_content(mut line: &str) -> &str { - while let Some(rest) = line.strip_prefix('>').or_else(|| list_marker(line)) - { - line = rest.trim_start(); +/// heading, and whether what is left is paragraph text. Paragraph text on +/// the line before means only a `1.` or `1)` starts a list, so a wrapped +/// line that begins `2020.` stays text. +fn block_content(mut line: &str, after_paragraph: bool) -> (&str, bool) { + let mut item = false; + loop { + if let Some(rest) = line.strip_prefix('>') { + line = rest.trim_start(); + } else if let Some(rest) = list_marker(line, after_paragraph && !item) + { + line = rest.trim_start(); + item = true; + } else { + break; + } + } + match heading(line) { + Some(text) => (text, false), + None => (line, !item && !line.is_empty()), } - heading(line).unwrap_or(line) } -/// The rest of a list item after its `-`, `*`, `+`, `1.` or `1)`. -fn list_marker(line: &str) -> Option<&str> { +/// The rest of a list item after its `-`, `*`, `+`, `1.` or `1)`, numbered +/// from 1 only when it would interrupt a paragraph. +fn list_marker(line: &str, interrupts: bool) -> Option<&str> { let rest = line.strip_prefix(['-', '*', '+']).or_else(|| { let digits = line.trim_start_matches(|c: char| c.is_ascii_digit()); - (digits.len() < line.len()) + let number = line.get(..line.len().saturating_sub(digits.len()))?; + (!number.is_empty() && (!interrupts || number == "1")) .then(|| digits.strip_prefix(['.', ')'])) .flatten() })?; @@ -500,7 +541,7 @@ fn link( /// `https://x.org>` or `a@b.org>` at `from`, just after a `<`: the address /// and the end of the autolink. Anything else after a `<` is HTML for -/// [`clean`]. The address ends at the first space or bracket, so a line of +/// [`clean`]. The address ends at the first space or angle bracket, so a line of /// `<`s is read once. fn autolink(line: &str, from: usize) -> Option<(&str, usize)> { let rest = line.get(from..)?; @@ -513,10 +554,11 @@ fn autolink(line: &str, from: usize) -> Option<(&str, usize)> { } /// Byte ranges of the `*`, `_` and `~~` runs in `line` that open or close -/// emphasis, paired by CommonMark's flanking rules. A run that pairs with -/// nothing, like the `*` in `*.csv` or `5 * 3`, or a `_` inside a word, as in -/// `sentinel_2_l2a`, stays text. At most 64 openers wait for a closer, which -/// bounds the search for one. +/// emphasis, paired by CommonMark's flanking rules for whitespace and words +/// but not its punctuation cases, so `**Title:**Plasma` loses its marks. A +/// run that pairs with nothing, like the `*` in `*.csv` or `5 * 3`, or a `_` +/// inside a word, as in `sentinel_2_l2a`, stays text. At most 64 openers +/// wait for a closer, which bounds the search for one. fn emphasis(line: &str, code: &[CodeSpan]) -> Vec<(usize, usize)> { const OPENERS: usize = 64; let mut paired = Vec::new(); @@ -572,10 +614,12 @@ fn emphasis(line: &str, code: &[CodeSpan]) -> Vec<(usize, usize)> { } paired } + /// HTML entities decoded in one pass, so `&lt;` stays the text `<`. -/// Unknown names and numeric codes for control characters stay as written. -/// The `;` is looked for only as far as the longest name, so text full of -/// bare `&` stays linear. +/// Unknown names and numeric codes for control characters stay as written; +/// an invisible format character such as `­` decodes to nothing. The +/// `;` is looked for only as far as the longest name, so text full of bare +/// `&` stays linear. fn decode_entities(text: &str, out: &mut Spaced) { let mut rest = text; while let Some((head, tail)) = rest.split_once('&') { @@ -587,7 +631,9 @@ fn decode_entities(text: &str, out: &mut Spaced) { .and_then(|end| tail.split_at_checked(end)) .and_then(|(name, after)| Some((entity(name)?, after.get(1..)?))); if let Some((c, after)) = decoded { - out.push(c); + if !invisible(c) { + out.push(c); + } rest = after; } else { out.push('&'); @@ -604,7 +650,7 @@ fn entity(name: &str) -> Option { "gt" => '>', "quot" => '"', "apos" => '\'', - "nbsp" => ' ', + "nbsp" | "thinsp" | "ensp" | "emsp" => ' ', "lsquo" => '\u{2018}', "rsquo" => '\u{2019}', "ldquo" => '\u{201c}', @@ -617,25 +663,82 @@ fn entity(name: &str) -> Option { "minus" => '\u{2212}', "euro" => '\u{20ac}', "trade" => '\u{2122}', + "dagger" => '\u{2020}', + "Dagger" => '\u{2021}', + "permil" => '\u{2030}', + "prime" => '\u{2032}', + "Prime" => '\u{2033}', + "larr" => '\u{2190}', + "uarr" => '\u{2191}', + "darr" => '\u{2193}', + "harr" => '\u{2194}', + "rArr" => '\u{21d2}', + "hArr" => '\u{21d4}', + "forall" => '\u{2200}', + "part" => '\u{2202}', + "exist" => '\u{2203}', + "nabla" => '\u{2207}', + "isin" => '\u{2208}', + "notin" => '\u{2209}', + "prod" => '\u{220f}', + "sum" => '\u{2211}', + "lowast" => '\u{2217}', + "radic" => '\u{221a}', + "prop" => '\u{221d}', + "infin" => '\u{221e}', + "and" => '\u{2227}', + "or" => '\u{2228}', + "cap" => '\u{2229}', + "cup" => '\u{222a}', + "int" => '\u{222b}', + "sim" => '\u{223c}', + "asymp" => '\u{2248}', + "ne" => '\u{2260}', + "equiv" => '\u{2261}', + "le" => '\u{2264}', + "ge" => '\u{2265}', + "sub" => '\u{2282}', + "sup" => '\u{2283}', _ => { let number = match name.strip_prefix('#') { Some(code) => match code.strip_prefix(['x', 'X']) { Some(hex) => u32::from_str_radix(hex, 16).ok()?, None => code.parse().ok()?, }, - None => LATIN1 - .iter() - .position(|&n| n == name) - .and_then(|i| u32::try_from(i).ok())? - .checked_add(0xa0)?, + None => greek(name).or_else(|| { + LATIN1 + .iter() + .position(|&n| n == name) + .and_then(|i| u32::try_from(i).ok())? + .checked_add(0xa0) + })?, }; - return char::from_u32(number) - .filter(|&c| !c.is_control() && !invisible(c)); + return char::from_u32(number).filter(|&c| !c.is_control()); } }; Some(named) } +/// `alpha` to `omega` from U+03B1, and capitalized, `Alpha` to `Omega` from +/// U+0391, where there is no capital final sigma. +fn greek(name: &str) -> Option { + let mut chars = name.chars(); + let first = chars.next()?; + let base = if first.is_ascii_uppercase() { 0x391 } else { 0x3b1 }; + let lower = first.to_ascii_lowercase(); + let i = GREEK + .iter() + .position(|n| n.strip_prefix(lower) == Some(chars.as_str()))?; + (name != "Sigmaf").then(|| u32::try_from(i).ok()?.checked_add(base))? +} + +/// The Greek letters' entity names, in code point order. +const GREEK: [&str; 25] = [ + "alpha", "beta", "gamma", "delta", "epsilon", "zeta", "eta", "theta", + "iota", "kappa", "lambda", "mu", "nu", "xi", "omicron", "pi", "rho", + "sigmaf", "sigma", "tau", "upsilon", "phi", "chi", "psi", "omega", +]; + /// The entity names of U+00A0 to U+00FF, in code point order. const LATIN1: [&str; 96] = [ "nbsp", "iexcl", "cent", "pound", "curren", "yen", "brvbar", "sect", @@ -1179,7 +1282,7 @@ mod tests { } #[test] - fn hostile_markdown_costs_linear_time_and_no_recursion() { + fn hostile_markdown_costs_no_quadratic_time_and_no_recursion() { let n = 50_000; let nested = format!("{}x{}", "[".repeat(n), "](u)".repeat(n)); let fences: Vec = (1..=300).map(|k| "`".repeat(k)).collect(); @@ -1222,6 +1325,27 @@ mod tests { "A page here", ), ("café »x« <br>end", "café »x« end"), + ( + "```dsk search``` runs\nthen *more*", + "dsk search runs then more", + ), + ("~~~\n*kept* as code\n~~~\nafter", "*kept* as code after"), + ( + "[1]: Smith et al. 2020\n[ref]: https://x.org \"Title\"", + "[1]: Smith et al. 2020", + ), + ( + "Collected from 1990 to\n2020. Measurements follow.", + "Collected from 1990 to 2020. Measurements follow.", + ), + ("Steps:\n\n2. second\n3. third", "Steps: second third"), + ("- item\n2) next", "item next"), + ("soft­ware", "software"), + ( + "ΔT ≤ 5 μm, σ² ≠ ∞", + "ΔT ≤ 5 μm, σ² ≠ ∞", + ), + ("&Sigmaf; &ALPHA;", "&Sigmaf; &ALPHA;"), ]; for (md, shown) in cases { assert_eq!(clean(&from_markdown(md)), shown, "{md:?}"); @@ -1238,7 +1362,7 @@ mod tests { "Monthly software data" ); let v = json!({"t": "\u{200b} x\u{200f}", "m": {"en": "\u{2060}y"}}); - assert_eq!(clean("a​b‎"), "a​b‎"); + assert_eq!(clean("a​b‎ soft­ware"), "ab software"); assert_eq!(text(&v, "/t").as_deref(), Some("x")); assert_eq!(localized(v.get("m")).as_deref(), Some("y")); assert_eq!(clean("\u{645}\u{200c}\u{647}"), "\u{645}\u{200c}\u{647}"); From 2bf46538339f8db1ddeaccb7506bebe1bd573d39 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Mon, 26 Oct 2026 12:48:08 +0000 Subject: [PATCH 15/17] fix: on Windows the live progress line stays on when stdout is redirected, and the line drops its bar instead of wrapping on a narrow terminal --- Cargo.lock | 11 +++++++++- Cargo.toml | 2 +- src/ui.rs | 59 ++++++++++++++++++++++++++++++++++++++++-------------- 3 files changed, 55 insertions(+), 17 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e464071..e7e0ddf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -492,12 +492,12 @@ version = "0.10.0" dependencies = [ "allocation-counter", "anstream", - "anstyle-query", "anyhow", "assert_cmd", "clap", "clap_complete", "codspeed-criterion-compat", + "enable-ansi-support", "etcetera", "insta", "predicates", @@ -577,6 +577,15 @@ version = "1.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34" +[[package]] +name = "enable-ansi-support" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea7457668b3da8a4b702f3d79e131aa3e81cd7e81cc95fb2d54fce9f182ecc77" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "encode_unicode" version = "1.0.0" diff --git a/Cargo.toml b/Cargo.toml index ef5d696..3b5cf4a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -41,7 +41,6 @@ doc_markdown = "allow" [dependencies] anyhow = "1" anstream = "1" -anstyle-query = "1" clap = { version = "4", features = ["derive", "env", "wrap_help"] } clap_complete = "4" etcetera = "0.11" @@ -51,6 +50,7 @@ serde_json = "1" tempfile = "3" terminal_size = "0.4" thiserror = "2" +enable-ansi-support = "0.3" [target.'cfg(unix)'.dependencies] signal-hook = { version = "0.4", default-features = false } diff --git a/src/ui.rs b/src/ui.rs index bd15923..96e615e 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -54,11 +54,11 @@ pub fn init(out: &Out) { /// Whether the terminal erases a line on `\x1b[K`, which a live display /// redraws with. A Windows console does once virtual terminal processing is -/// on, which this turns on; it fails when stdout or stderr is not a console, -/// and the display then falls back to status lines. Off Windows there is -/// nothing to turn on. +/// on, which this turns on for the console itself, so a redirected stdout +/// does not keep it off; a console too old for it fails, and the display +/// then falls back to status lines. Off Windows there is nothing to turn on. fn redraws() -> bool { - anstyle_query::windows::enable_ansi_colors().unwrap_or(true) + enable_ansi_support::enable_ansi_support().is_ok() } fn set(mode: Mode, unicode: bool, color: bool) { @@ -276,7 +276,8 @@ fn erase_to_end() { } /// One frame, ` ⠹ msg 3s` or ` msg [███░░░] 2/4 3s`, cut to fit a terminal -/// `width` columns wide by shortening the message, so it never wraps. +/// `width` columns wide by shortening the message and, below a bar's width, +/// dropping the bar, so it does not wrap where the counts alone fit. fn frame( msg: &str, len: Option, @@ -314,13 +315,17 @@ fn frame( .unwrap_or(0); let bar = full.repeat(filled) + &empty.repeat(BAR.saturating_sub(filled)); - ( - None, - format!( - " [{}] {pos}/{len} {time}", - paint(palette::accent(), bar) - ), - ) + let counts = format!(" {pos}/{len} {time}"); + // The indent, the brackets, four columns of message and the + // column the cursor rests in. + let bar_fits = + BAR.saturating_add(10).saturating_add(counts.len()) <= width; + let suffix = if bar_fits { + format!(" [{}]{counts}", paint(palette::accent(), bar)) + } else { + counts + }; + (None, suffix) } }; let indent = if mark.is_some() { 4 } else { 2 }; @@ -328,9 +333,11 @@ fn frame( let room = width.saturating_sub(1).saturating_sub(fixed); let msg = if msg.chars().count() <= room { msg.to_owned() - } else { + } else if room > 3 { let cut: String = msg.chars().take(room.saturating_sub(3)).collect(); cut + "..." + } else { + msg.chars().take(room).collect() }; match mark { Some(spin) => { @@ -340,7 +347,7 @@ fn frame( } } -/// Columns a string takes, escape sequences not counted. +/// Characters a string shows, escape sequences not counted. fn visible(text: &str) -> usize { let mut in_escape = false; text.chars() @@ -382,7 +389,7 @@ mod tests { } #[test] - fn frames_show_progress_and_never_wrap() { + fn frames_show_progress_and_fit_the_terminal() { let _guard = locked(); set(Mode::Live, false, false); let secs = Duration::from_secs; @@ -409,6 +416,11 @@ mod tests { ), " | a very lo... 0s" ); + assert_eq!(frame("scanning", None, 0, secs(3), 1, 10), " / sc 3s"); + assert_eq!( + frame("sources", Some(4), 2, secs(75), 0, 30), + " sources 2/4 1m 15s" + ); let plain = frame("x", Some(1), 1, secs(0), 0, 80); set(Mode::Live, false, true); let colored = frame("x", Some(1), 1, secs(0), 0, 80); @@ -416,6 +428,23 @@ mod tests { assert_eq!(visible(&colored), plain.chars().count()); } + #[test] + fn a_live_display_stops_at_once_and_with_its_last_handle() { + let _guard = locked(); + let started = Instant::now(); + let finished = Progress::start("x".to_owned(), Some(2)); + finished.inc(1); + finished.finish_and_clear(); + assert!(started.elapsed() < Duration::from_secs(1)); + let dropped = Progress::start("y".to_owned(), None); + let watched = dropped.0.as_ref().map(Arc::downgrade).unwrap(); + drop(dropped); + while watched.upgrade().is_some() { + assert!(started.elapsed() < Duration::from_secs(1)); + std::thread::sleep(Duration::from_millis(5)); + } + } + #[test] fn counts_agree_with_their_noun() { assert_eq!(count(0, "source"), "0 sources"); From b3e9e1979c89847fedf2e7092b15842262861ada Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Mon, 26 Oct 2026 12:55:41 +0000 Subject: [PATCH 16/17] doc: comments and docs match the rewrites, the binary size note counts the review fixes, and the man page test checks COMMANDS --- Cargo.toml | 3 ++- benches/search.rs | 6 +++--- docs/bench/2026-10-23-binary-size.md | 13 +++++++------ docs/reference/contract.md | 4 ++-- src/help.rs | 2 +- src/http.rs | 7 ++++--- tests/cli.rs | 14 +++++++++++++- 7 files changed, 32 insertions(+), 17 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 3b5cf4a..70f4028 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -66,7 +66,8 @@ signal-hook = { version = "0.4", default-features = false } [target.'cfg(any(windows, target_os = "macos"))'.dependencies] ureq = { version = "3.5", default-features = false, features = ["json", "gzip", "native-tls-no-default"] } -# rustls itself only to tell a refused certificate from a dead host. +# rustls itself to hand ureq ring's provider and to tell a refused +# certificate from a dead host. [target.'cfg(not(any(windows, target_os = "macos")))'.dependencies] rustls = { version = "0.23", default-features = false, features = ["ring", "std"] } ureq = { version = "3.5", default-features = false, features = ["json", "gzip", "rustls-no-provider", "platform-verifier"] } diff --git a/benches/search.rs b/benches/search.rs index dd65fd0..05ca327 100644 --- a/benches/search.rs +++ b/benches/search.rs @@ -1,8 +1,8 @@ //! The CPU side of a search, by stage: parsing downloaded catalogs, loading //! a cached catalog, searching it, fusing the per-source lists and cleaning -//! remote text, Markdown descriptions included. Network time dwarfs all of it; these exist so a change that -//! makes one stage grow faster than its input shows up before a user waits -//! on it (ADR 0012). +//! remote text, Markdown descriptions included. Network time dwarfs all of +//! it; these exist so a change that makes one stage grow faster than its +//! input shows up before a user waits on it (ADR 0012). //! //! Inputs are synthetic, shaped after real responses (ECB's SDMX-ML dataflow //! list, Eurostat's table of contents, 2026-10-06) and built from a word list diff --git a/docs/bench/2026-10-23-binary-size.md b/docs/bench/2026-10-23-binary-size.md index a3ff532..003f153 100644 --- a/docs/bench/2026-10-23-binary-size.md +++ b/docs/bench/2026-10-23-binary-size.md @@ -44,11 +44,12 @@ File size of the stripped release binary, in bytes, each commit on top of the on | progress drawn without indicatif | 2,316,560 | -83,392 | 3,797,176 | -88,360 | | man page written without clap_mangen | 2,283,248 | -33,312 | 3,758,392 | -38,784 | | Windows console check, rustls-webpki 0.103.16 | 2,283,248 | 0 | 3,763,816 | +5,424 | -| total | | -480,880 (-17.4%) | | -587,336 (-13.5%) | +| review fixes | 2,299,744 | +16,496 | 3,769,912 | +6,096 | +| total | | -464,384 (-16.8%) | | -581,240 (-13.4%) | -The last row is two fixes that came after the size work: the progress line's check that a Windows console understands escape codes (`anstyle-query`, 1,200 bytes on Linux), and the rustls-webpki release that distrusts the emSign intermediates (4,224 bytes). +The last two rows came after the size work. The first is the progress line's check that a Windows console understands escape codes (1,200 bytes on Linux) and the rustls-webpki release that distrusts the emSign intermediates (4,224 bytes). The second is what review of the rewrites found: `credentials.toml` with a byte order mark or TOML 1.1's `\e` and `\x` escapes read again, Markdown that the first rewrite read differently from pulldown-cmark (a wrapped line starting `2020.`, a `[label]: text` line, a line opening with a code span), Greek and math entity names, the progress bar dropped on a narrow terminal, and `enable-ansi-support` in place of `anstyle-query`, which gave up when stdout was redirected. Its code is 5.2 KB on macOS; the rest of the 16 KB is `__TEXT` crossing a 16 KiB page. -Release archive of the final build, `dataseek` and `dsk` inside: +Release archive of the build before the review fixes, `dataseek` and `dsk` inside: | archive | `aarch64-apple-darwin` | `x86_64-unknown-linux-gnu` | |---|---:|---:| @@ -60,8 +61,8 @@ gzip's 32 KB window never sees that `dsk` repeats `dataseek`, so a `.tar.gz` hol ### What each change replaced - **ureq 3.5.** `native-tls-no-default` now builds a working connector (ureq PR #1204), so macOS and Windows stop linking `webpki-root-certs`, which `RootCerts::PlatformVerifier` never reads. Linux moved to `rustls-no-provider` with ring's provider passed in `src/http.rs`, which drops the same roots there. A live `dataseek search` over each TLS stack is the test, because no test here makes a real TLS connection. -- **pulldown-cmark.** Descriptions only need Markdown turned into plain text, not parsed into a tree. `record::from_markdown` strips fences, rules, link definitions, list and quote markers and headings line by line, then pairs code spans, brackets and emphasis in one linear, non-recursive pass. Over every string in the recorded fixtures, 4,693 of 4,697 come out the same as before; of the four that differ, one reads better (`**Title:**Plasma`) and three are an opendatasoft field that never goes through Markdown. A test feeds it 50,000 nested openers of every kind and asserts linear time. Over the same strings, `clean(from_markdown(..))`, which is what a record's description goes through, takes 56 ms per 20 passes against 62 ms with pulldown-cmark, best of 7, and 3.65 ms against 4.41 ms on a 20 KB synthetic description. The new `markdown` bench group keeps it measured. The first version was twice as slow as pulldown-cmark, because it matched every line for code, links and emphasis and copied one character at a time; it now skips a match whose opening byte the line lacks and copies plain runs whole. -- **toml.** `credentials.toml` holds one `name = "value"` per line. `credentials::flat_table` reads exactly that, with TOML's string escapes, and treats anything else (a table, a multi-line string, a duplicate key) as supplying no key at all. +- **pulldown-cmark.** Descriptions only need Markdown turned into plain text, not parsed into a tree. `record::from_markdown` strips fences, rules, link definitions, list and quote markers and headings line by line, then pairs code spans, brackets and emphasis in one non-recursive pass. Over every string in the recorded fixtures, 4,693 of 4,697 come out the same as before; of the four that differ, one reads better (`**Title:**Plasma`) and three are an opendatasoft field that never goes through Markdown. A test feeds it 50,000 nested openers of every kind and asserts it finishes in seconds, which a quadratic scan would not. Over the same strings, `clean(from_markdown(..))`, which is what a record's description goes through, takes 56 ms per 20 passes against 62 ms with pulldown-cmark, best of 7, and 3.65 ms against 4.41 ms on a 20 KB synthetic description. The new `markdown` bench group keeps it measured. The first version was twice as slow as pulldown-cmark, because it matched every line for code, links and emphasis and copied one character at a time; it now skips a match whose opening byte the line lacks and copies plain runs whole. +- **toml.** `credentials.toml` holds one `name = "value"` per line. `credentials::flat_table` reads exactly that, with TOML 1.1's string escapes and a leading byte order mark, and treats anything else (a table, a multi-line string, a duplicate key) as supplying no key at all. - **indicatif.** dataseek draws one spinner or one bar at a time. `ui::Progress` is a ticker thread redrawing one line every 90 ms and clearing it when the work finishes or the handle drops. - **clap_mangen.** The page has one fixed shape: options, commands, examples, exit status. `help::man_page` writes that roff from the clap definition. It also stopped referring to `dataseek-search(1)` and the other per-command pages, which were never installed. @@ -115,7 +116,7 @@ The release build spends most of its time in one fat-LTO codegen unit, so sixtee ## Verdict -Five dependencies were each replaced by the few dozen to few hundred lines dataseek needed of them: the binary is 17.4% smaller on macOS and 13.5% on Linux, and the archive a user downloads is about 60% smaller. Every test passes and `just relevance` is unchanged at nDCG@10 0.6403. The two largest levers left are both kept off: compiling dataseek for size (-525 to -558 KB) slows parsing, matching and merging by up to 75%, and `panic = "abort"` (-414 KB) would let one adapter's panic end the whole search. +Four dependencies were replaced by the few dozen to few hundred lines dataseek needed of them, and ureq stopped linking a root store it never read: the binary is 16.8% smaller on macOS and 13.4% on Linux, and the archive a user downloads is about 60% smaller. Every test passes and `just relevance` is unchanged at nDCG@10 0.6403. The two largest levers left are both kept off: compiling dataseek for size (-525 to -558 KB) slows parsing, matching and merging by up to 75%, and `panic = "abort"` (-414 KB) would let one adapter's panic end the whole search. ## Caveats diff --git a/docs/reference/contract.md b/docs/reference/contract.md index ae25321..0621dcd 100644 --- a/docs/reference/contract.md +++ b/docs/reference/contract.md @@ -118,7 +118,7 @@ dsk man > ~/.local/share/man/man1/dsk.1 # then: man dsk `man` is a hidden command: the overview, `-h` and `--help` leave it out, `dataseek help --json` still lists it, as it lists every command that runs. -Both are data, so both go to stdout, and both are derived from the clap definition rather than maintained by hand. The man page is rendered on demand by `help::man_page`, which writes the roff itself from the clap definition instead of at build time by a build script, so it cannot drift from the flags. A flag hidden from `-h` still gets its description, and the examples, exit codes (from `EXIT_CODES`, like `help exit-codes`) and bug address become EXAMPLES, EXIT STATUS and REPORTING BUGS sections. It leaves the date empty, so two builds of one commit print the same page. The tests assert the page carries the manifest version, renders without errors, names every command, describes every option and has those three sections, and that fish parses the completion script. +Both are data, so both go to stdout, and both are derived from the clap definition rather than maintained by hand. The man page is rendered on demand by `help::man_page`, which writes the roff itself from the clap definition instead of at build time by a build script, so it cannot drift from the flags. A flag hidden from `-h` still gets its description, and the examples, exit codes (from `EXIT_CODES`, like `help exit-codes`) and bug address become EXAMPLES, EXIT STATUS and REPORTING BUGS sections. It leaves the date empty, so two builds of one commit print the same page. The tests assert the page carries the manifest version, renders without errors, names every command but the hidden `man` under COMMANDS, describes every option and has those three sections, and that fish parses the completion script. ## Color @@ -136,7 +136,7 @@ Roles are semantic (`accent`, `success`, `danger`), not literal, so swapping a c The same roles drive clap help styling, stdout text, and the stderr progress accent. `anstream` strips escapes whenever the stream is not a terminal, so call sites style unconditionally and never branch on color. On a color terminal, result URLs are OSC 8 hyperlinks. When stdout is a terminal, color or not, a result's title and facts line are cut to the terminal width (`COLUMNS` wins) with an ellipsis, and its description to that width held between 40 and 80 columns, so it reads as prose on a wide terminal; URLs are never cut. In a pipe, and with `--plain`, every line stays whole. -indicatif parses its color token with `console::Style::from_dotted_str`, which understands named colors, `#rrggbb` truecolor, and a bare 256-color index, so `palette::accent_token()` renders whichever shape the accent takes exactly. Spinners and bars match help and stdout rather than approximating them. +Spinners and bars paint with `palette::accent()` through `anstream`, like help and stdout, so they match whatever shape the accent takes. The one escape they write past `anstream` is `\x1b[K`, which erases the rest of the line between frames; `anstream` would strip it with color off and leave stale text behind. ## Platform directories diff --git a/src/help.rs b/src/help.rs index 7244ddf..5e675cc 100644 --- a/src/help.rs +++ b/src/help.rs @@ -321,7 +321,7 @@ fn lines(text: &str, blank: &str) -> String { .collect() } -/// `text` as roff text: backslashes, hyphens and quotes escaped, and a +/// `text` as roff text: backslashes, hyphens and apostrophes escaped, and a /// leading period kept from reading as a request. fn roff(text: &str) -> String { let escaped = diff --git a/src/http.rs b/src/http.rs index 5322e46..21334d1 100644 --- a/src/http.rs +++ b/src/http.rs @@ -158,9 +158,10 @@ impl Http { /// The OS's trust store everywhere, so a root certificate installed for a /// TLS-inspecting proxy is trusted: through the OS's own TLS stack on Windows /// and macOS, through rustls and rustls-platform-verifier elsewhere. -/// `Cargo.toml` enables the matching ureq features per platform, leaving out -/// the bundled Mozilla roots `PlatformVerifier` never reads, so rustls is -/// handed ring here instead of through ureq's default features. +/// `Cargo.toml` enables the matching ureq features per platform, with the +/// defaults off to leave out the bundled Mozilla roots `PlatformVerifier` +/// never reads. ureq then brings no crypto provider, so the rustls build +/// passes ring's. fn tls() -> ureq::tls::TlsConfig { let builder = ureq::tls::TlsConfig::builder() .root_certs(ureq::tls::RootCerts::PlatformVerifier); diff --git a/tests/cli.rs b/tests/cli.rs index 6aa7851..44a0853 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -1395,10 +1395,22 @@ fn the_man_page_renders_and_lists_every_command() { text.push(c); } } + let commands = text + .split_once("COMMANDS") + .and_then(|(_, rest)| rest.split_once("EXAMPLES")) + .unwrap() + .0; + let listed: Vec<&str> = commands + .lines() + .filter_map(|line| line.split_whitespace().next()) + .collect(); let help = json_of(&["help", "--json"]); for command in help["command"]["commands"].as_array().unwrap() { let name = command["name"].as_str().unwrap(); - assert!(text.contains(name), "{name} missing from the man page"); + // `man` is hidden, so its own page leaves it out. + if name != "man" { + assert!(listed.contains(&name), "{name} missing from COMMANDS"); + } } } From f2170214dce487ec0853db0e0cd663dabaa98bc1 Mon Sep 17 00:00:00 2001 From: Luis Markmann <110569833+lmarkmann@users.noreply.github.com> Date: Mon, 26 Oct 2026 13:06:43 +0000 Subject: [PATCH 17/17] fix: a Markdown fence closes only on a run of its own mark at least as long, and credentials.toml refuses control characters in literal strings as TOML does --- src/credentials.rs | 5 ++++- src/record.rs | 28 +++++++++++++++------------- 2 files changed, 19 insertions(+), 14 deletions(-) diff --git a/src/credentials.rs b/src/credentials.rs index fcbf9d3..607b28e 100644 --- a/src/credentials.rs +++ b/src/credentials.rs @@ -239,7 +239,8 @@ fn toml_string(text: &str) -> Option<(String, &str)> { } if let Some(literal) = text.strip_prefix('\'') { let (value, rest) = literal.split_once('\'')?; - return Some((value.to_owned(), rest)); + let controls = value.chars().any(|c| c.is_control() && c != '\t'); + return (!controls).then(|| (value.to_owned(), rest)); } let body = text.strip_prefix('"')?; let mut chars = body.char_indices(); @@ -408,6 +409,8 @@ mod tests { "fred = \"\\ud800\"", "fred = \"\\x4\"", "fred = 'a'b'", + "fred = 'a\u{0}b'", + "fred = 'a\tb'", "[keys]", "fred = true", ] { diff --git a/src/record.rs b/src/record.rs index 6e363a3..80757d9 100644 --- a/src/record.rs +++ b/src/record.rs @@ -222,8 +222,10 @@ pub fn from_markdown(text: &str) -> String { let mut fence = None; let mut paragraph = false; for line in text.lines().map(str::trim) { - if let Some(open) = fence { - if line.starts_with(open) { + if let Some((mark, len)) = fence { + let rest = line.trim_start_matches(mark); + if line.len().saturating_sub(rest.len()) >= len && rest.is_empty() + { fence = None; } else { plain.push_str(line); @@ -264,17 +266,15 @@ fn is_rule(line: &str) -> bool { delimiter_row || thematic } -/// The fence a line opens, ```` ``` ```` or `~~~`. A backtick fence's info -/// string holds no backtick, so a line starting with a ```` ```code``` ```` -/// span opens nothing. -fn fence_opener(line: &str) -> Option<&'static str> { - if line.starts_with("~~~") { - Some("~~~") - } else { - (line.starts_with("```") - && !line.trim_start_matches('`').contains('`')) - .then_some("```") - } +/// The mark and length of the fence a line opens, three or more backticks +/// or tildes; only a run of the same mark at least as long, alone on its +/// line, closes it. A backtick fence's info string holds no backtick, so a +/// line starting with a ```` ```code``` ```` span opens nothing. +fn fence_opener(line: &str) -> Option<(char, usize)> { + let mark = line.chars().next().filter(|c| matches!(c, '`' | '~'))?; + let info = line.trim_start_matches(mark); + let len = line.len().saturating_sub(info.len()); + (len >= 3 && !(mark == '`' && info.contains('`'))).then_some((mark, len)) } /// `[label]: url`, with an optional quoted title, which defines a link @@ -1330,6 +1330,8 @@ mod tests { "dsk search runs then more", ), ("~~~\n*kept* as code\n~~~\nafter", "*kept* as code after"), + ("````\n```\ninner\n```\n````\n**after**", "``` inner ``` after"), + ("```\n```bash\n```\n**after**", "```bash after"), ( "[1]: Smith et al. 2020\n[ref]: https://x.org \"Title\"", "[1]: Smith et al. 2020",