knotra 0.34.0

knotra: multi-project VCS dashboard and bulk-operation tool.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
//! RFC-056 Stage 2 D4/R8: catches a raw `.size(<numeric literal>)` re-entering
//! the view tree. RFC-056 Stage 3 D5/R4 adds a second guard beside it: every
//! `body_size(`/`body_small_size(` call must carry a matching
//! `.line_height(...)` — the pairing Stage 3 exists to establish. RFC-071
//! Amendment A3 D14 adds a third: every remaining `body_small` *text* site
//! is pinned by file and count in `EXPECTED_BODY_SMALL_SITES`, the same
//! non-empty, justified-map shape `suppressions_guard.rs` and
//! `text_outside_catalog_guard.rs` use.
//!
//! `crates/knotra-app/src/view/` and `crates/knotra-ui/src/widget/` had 249
//! such call sites before Stage 2 — 159 via the retired `FONT_BODY`/
//! `FONT_SMALL` constants (and their `+ N.0` arithmetic), 90 as bare
//! literals, 38 of those below snora's 12px legibility floor. All 249 now
//! read a size from a `snora::design::style::text::*_size(tokens)` role
//! helper. This is the guard that keeps a literal from quietly coming back —
//! the same shape `suppressions_guard.rs` and `text_outside_catalog_guard.rs`
//! use for their own regressions, widened to a fourth source-scanning guard.
//!
//! **Text-scanning, not a real parser** — same tradeoff every guard in this
//! project accepts. Two things this scan deliberately does *not* count:
//!
//! - **Comment lines** (`//`, `///`, `//!`). A raw `.size(11)` is common
//!   prose when a doc comment explains what a role replaced — two
//!   fixed-width layout constants `detail_panel.rs` once carried (removed
//!   in RFC-071 Amendment A2, once their own guessed fit broke) did exactly
//!   this, describing their original fit. Counting lines like those would
//!   make the guard fail on migration notes, not on live code. A line is
//!   skipped whenever its trimmed text starts with `//` — this cannot be
//!   fooled by a real call site, since Rust syntax never places `.size(`
//!   at the start of a comment-opening line.
//! - **`.size(<identifier>)` calls that are not a bare number** —
//!   `checkbox.rs`'s `.size(BOX_SIZE)` sizes an icon glyph, not text, and a
//!   named constant is not the literal this guard exists to catch. The scan
//!   only flags a `.size(` immediately followed (after optional whitespace)
//!   by an ASCII digit.
//!
//! **Why the pairing check is assertable at all (Stage 3 §3/§4)**: Stage 3
//! applies `body`/`body_small` line-height *uniformly*, not per site judged
//! for whether it might wrap. That is what makes "every `body_size(`/
//! `body_small_size(` call has a paired `.line_height(...)`" a rule with no
//! exceptions to track — unlike `suppressions_guard.rs`'s non-empty
//! `EXPECTED` map, this guard's own map stays empty by design. `label_size(`/
//! `title_size(`/`heading_size(`/`display_size(` are deliberately **not**
//! checked for a pairing — `title` is byte-for-byte iced's own default
//! (1.3), and `label`/`heading` are tighter than default and single-line by
//! construction (RFC-056 Stage 3 §2); pairing them would be a defect this
//! guard would then have to un-invent. Do not widen this check to those four
//! roles without a decision to do so — silently "simplifying" the rule to
//! "every role gets a line-height" is exactly the drift this comment exists
//! to head off.
//!
//! The pairing scan walks the whole (comment-blanked) source as one string,
//! not line-by-line — `cargo fmt` wraps a long `.size(...).line_height(...)`
//! chain across several lines, so a per-line check would miss real pairs.
//! It does not compare the `.size(...)`/`.line_height(...)` call's argument
//! token for equality (e.g. catching a `tokens` paired with a stray
//! `other_tokens`) — every real call site in this codebase passes the same
//! binding to both, and a parser precise enough to compare expressions is
//! more machinery than this guard's stated tradeoff accepts.
//!
//! `#[cfg(test)]`-only: this module never compiles into the shipped binary.

#[cfg(test)]
mod tests {
    /// Recursively collect every `.rs` file under `dir` — copied from
    /// `suppressions_guard.rs`/`text_outside_catalog_guard.rs` rather than
    /// shared, matching this project's established precedent of a small
    /// hand-rolled walk per guard.
    fn rust_files_under(dir: &std::path::Path) -> Vec<std::path::PathBuf> {
        let mut files = Vec::new();
        let Ok(entries) = std::fs::read_dir(dir) else {
            return files;
        };
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_dir() {
                files.extend(rust_files_under(&path));
            } else if path.extension().is_some_and(|ext| ext == "rs") {
                files.push(path);
            }
        }
        files
    }

    /// The two directories R8 scopes this guard to, resolved from this
    /// crate's own manifest directory the same way `suppressions_guard.rs`'s
    /// `crates_dir()` reaches a sibling crate.
    fn scan_dirs() -> Vec<std::path::PathBuf> {
        let manifest = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
        vec![
            manifest.join("src/view"),
            manifest.join("../knotra-ui/src/widget"),
        ]
    }

    /// This file's own doc comment names the exact pattern it scans for
    /// (`.size(11)`, `.size(BOX_SIZE)`) inside backtick-quoted prose —
    /// scanning `text_size_guard.rs` itself would find those, not real call
    /// sites. Same self-exclusion reasoning every guard in this project
    /// uses (`suppressions_guard.rs`, `text_outside_catalog_guard.rs`).
    fn is_scan_target(path: &std::path::Path) -> bool {
        !path.ends_with("text_size_guard.rs")
    }

    /// True if `trimmed` (a line with leading whitespace already stripped)
    /// is a comment line — `//`, `///`, or `//!`. Rust syntax never places
    /// a real `.size(` call at the start of a line beginning with `//`, so
    /// this cannot mask a live call site; it exists only to skip the prose
    /// this guard's own doc comment above explains.
    fn is_comment_line(trimmed: &str) -> bool {
        trimmed.starts_with("//")
    }

    /// The count of `.size(` occurrences in `source`, outside comment
    /// lines, whose next non-whitespace character is an ASCII digit — a
    /// raw numeric literal, not a role helper call (`.size(snora::design::
    /// style::text::body_size(tokens))`, which is never immediately
    /// followed by a digit) or a named constant (`.size(BOX_SIZE)`).
    fn count_raw_size_literals(source: &str) -> usize {
        let mut count = 0;
        for line in source.lines() {
            let trimmed = line.trim_start();
            if is_comment_line(trimmed) {
                continue;
            }
            let mut rest = line;
            while let Some(pos) = rest.find(".size(") {
                let after = &rest[pos + ".size(".len()..];
                if after.trim_start().starts_with(|c: char| c.is_ascii_digit()) {
                    count += 1;
                }
                rest = after;
            }
        }
        count
    }

    /// R8: zero raw `.size(<numeric literal>)` sites remain under either
    /// scanned directory after RFC-056 Stage 2's migration. Unlike
    /// `suppressions_guard.rs`'s non-empty `EXPECTED` map (five tracked,
    /// justified suppressions), this guard's own map is empty by design —
    /// every one of the 249 pre-migration sites has a role, and R3 requires
    /// every future site to get one too, not to earn a place on an
    /// exceptions list. A new entry appearing here means a literal came
    /// back, not that one was blessed.
    #[test]
    fn no_raw_text_size_literal_remains_in_the_view_tree() {
        let mut actual: std::collections::BTreeMap<String, usize> =
            std::collections::BTreeMap::new();
        let mut total_files = 0;

        for dir in scan_dirs() {
            let files = rust_files_under(&dir);
            total_files += files.len();
            for file in files.iter().filter(|f| is_scan_target(f)) {
                let Ok(source) = std::fs::read_to_string(file) else {
                    continue;
                };
                let n = count_raw_size_literals(&source);
                if n > 0 {
                    actual.insert(file.display().to_string(), n);
                }
            }
        }

        assert!(
            total_files > 20,
            "found only {total_files} .rs files under the two scanned \
             directories -- path resolution is broken (expected 20+ across \
             view/ and widget/), not that nothing needed checking"
        );

        assert!(
            actual.is_empty(),
            "raw `.size(<numeric literal>)` call sites found outside \
             comments -- RFC-056 R8 requires every text size to come from a \
             `snora::design::style::text::*_size(tokens)` role helper, not \
             a literal:\n{actual:#?}"
        );
    }

    /// `source` with every comment line (`//`, `///`, `//!`) replaced by
    /// spaces of the same length — preserves every other byte's offset and
    /// every line's length, so the pairing scan below can walk the result as
    /// one string without a comment's prose being mistaken for a call site,
    /// the same reasoning `is_comment_line` applies per-line above.
    fn blank_comment_lines(source: &str) -> String {
        source
            .lines()
            .map(|line| {
                if is_comment_line(line.trim_start()) {
                    " ".repeat(line.len())
                } else {
                    line.to_owned()
                }
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    /// The byte offset of the `)` matching the `(` at `open_paren`
    /// (`source.as_bytes()[open_paren]` must be `b'('`), by depth counting.
    /// Sufficient for this guard's call shapes — none of the arguments it
    /// scans (`tokens`, `&tokens`, `&state.theme.tokens`) contain a `(`.
    fn matching_close_paren(source: &str, open_paren: usize) -> Option<usize> {
        let bytes = source.as_bytes();
        let mut depth = 1i32;
        let mut i = open_paren + 1;
        while i < bytes.len() {
            match bytes[i] {
                b'(' => depth += 1,
                b')' => {
                    depth -= 1;
                    if depth == 0 {
                        return Some(i);
                    }
                }
                _ => {}
            }
            i += 1;
        }
        None
    }

    /// `(size role fn, its required line_height role fn)` — the only two
    /// roles Stage 3 applies leading to (D5/§2).
    const PAIRED_ROLES: &[(&str, &str)] = &[
        ("body_size", "body_line_height"),
        ("body_small_size", "body_small_line_height"),
    ];

    /// True if `after` (already whitespace-trimmed from the left) opens with
    /// `.line_height(` — allowing further whitespace, then a matching
    /// `snora::design::style::text::{lh_fn}(` — before the inner call.
    /// `cargo fmt` wraps `.line_height(` onto its own line when the whole
    /// chain is long, putting a newline *inside* what would otherwise be one
    /// contiguous literal (`".line_height(snora::design::..."`); checking
    /// `.line_height(` and the role call as two separately-trimmed pieces,
    /// rather than one fixed string, is what makes that wrap not a false
    /// mismatch.
    fn starts_with_line_height_call(after: &str, lh_fn: &str) -> bool {
        let Some(rest) = after.strip_prefix(".line_height(") else {
            return false;
        };
        rest.trim_start()
            .starts_with(&format!("snora::design::style::text::{lh_fn}("))
    }

    /// The count of `.size(snora::design::style::text::<role>_size(...))`
    /// call sites in `source` (comment lines already blanked) whose very
    /// next construct, after any whitespace, is **not** the matching
    /// `.line_height(snora::design::style::text::<role>_line_height(...))`.
    fn count_unpaired_body_roles(clean_source: &str) -> usize {
        let mut count = 0;
        for (size_fn, lh_fn) in PAIRED_ROLES {
            let size_prefix = format!(".size(snora::design::style::text::{size_fn}(");
            let mut search_from = 0;
            while let Some(rel) = clean_source[search_from..].find(&size_prefix) {
                let call_start = search_from + rel;
                // Position of `.size`'s own `(` — depth-counting from here
                // balances the inner `<role>_size(...)` call and returns the
                // outer `.size(...)` expression's own closing `)`.
                let outer_open = call_start + ".size".len();
                let Some(outer_close) = matching_close_paren(clean_source, outer_open) else {
                    search_from = call_start + size_prefix.len();
                    continue;
                };
                let after = clean_source[outer_close + 1..].trim_start();
                if !starts_with_line_height_call(after, lh_fn) {
                    count += 1;
                }
                search_from = outer_close + 1;
            }
        }
        count
    }

    /// R4: every `body_size(`/`body_small_size(` call in either scanned
    /// directory carries a matching `.line_height(...)` call — assertable
    /// only because Stage 3 applies it uniformly rather than per site (see
    /// this file's module doc comment). Like `no_raw_text_size_literal_
    /// remains_in_the_view_tree` above, the expected map is empty by
    /// design: a new entry means a `body`/`body_small` size gained no
    /// leading, not that one earned a place on an exceptions list.
    #[test]
    fn every_body_role_size_call_carries_a_matching_line_height() {
        let mut actual: std::collections::BTreeMap<String, usize> =
            std::collections::BTreeMap::new();
        let mut total_files = 0;

        for dir in scan_dirs() {
            let files = rust_files_under(&dir);
            total_files += files.len();
            for file in files.iter().filter(|f| is_scan_target(f)) {
                let Ok(source) = std::fs::read_to_string(file) else {
                    continue;
                };
                let clean = blank_comment_lines(&source);
                let n = count_unpaired_body_roles(&clean);
                if n > 0 {
                    actual.insert(file.display().to_string(), n);
                }
            }
        }

        assert!(
            total_files > 20,
            "found only {total_files} .rs files under the two scanned \
             directories -- path resolution is broken (expected 20+ across \
             view/ and widget/), not that nothing needed checking"
        );

        assert!(
            actual.is_empty(),
            "`body_size(`/`body_small_size(` call sites found with no \
             matching `.line_height(...)` -- RFC-056 Stage 3 R4 requires \
             every body/body_small text size to carry its role's \
             line-height (label/title/heading/display are correctly \
             unpaired -- see this file's module doc comment):\n{actual:#?}"
        );
    }

    /// The count of real `.size(snora::design::style::text::body_small_size(`
    /// text-role call sites in `source` (comment lines already blanked) —
    /// requires the `.size(` prefix on the same textual run as
    /// `count_unpaired_body_roles` does, so a bare
    /// `body_small_size(tokens).0` read for its numeric value (an icon's
    /// own size parameter, not a text role — `row.rs`'s "›" cue) is not
    /// counted; it was never a text-size call to begin with.
    fn count_body_small_text_sites(clean_source: &str) -> usize {
        clean_source
            .matches(".size(snora::design::style::text::body_small_size(")
            .count()
    }

    /// RFC-071 Amendment A3 D14, corrected by Amendment A6 §2: every
    /// remaining `body_small` TEXT site, classified once and pinned here
    /// by file and count — the same shape `suppressions_guard.rs` and
    /// `text_outside_catalog_guard.rs` use for their own non-empty,
    /// justified exception maps, not the two empty maps above (those stay
    /// empty by design; this one does not, because D14 names a real
    /// "incidental metadata" category that legitimately keeps
    /// `body_small`).
    ///
    /// A6 §2 corrected two over-eager keeps from D14's first pass: the
    /// keyboard-shortcuts sheet (a page a user opens to read in full, not
    /// a key shown beside a control — D14's own "keyboard hints" example
    /// means the latter) moved entirely to `body`; the detail panel's
    /// field *values* (the content the panel exists to show) moved to
    /// `body`, while their labels stay `body_small` captions.
    ///
    /// Each entry's own site(s) already carry a `kept body_small` comment
    /// at the call site stating which of D14's named categories it falls
    /// under (timestamp, VCS kind, branch beside a name, count inside
    /// metadata, keyboard hint, or a documented close analogue —
    /// `add_project_modal.rs`'s step count, `field.rs`'s unit suffix,
    /// `buttons.rs`'s/`checkbox.rs`'s tooltip per D10's "today's tooltip"
    /// ruling) — this map does not repeat that reasoning, only pins the
    /// count so a new site cannot join silently.
    ///
    /// - `view/add_project_modal.rs`, 1 — the wizard step count ("Step 1
    ///   of 2"), a count inside metadata.
    /// - `view/dashboard/row.rs`, 1 — the VCS kind sub-line under a
    ///   project's name.
    /// - `view/detail_panel.rs`, 2 — the shared identity/status field
    ///   primitive's label only (its value is now `body`, A6 §2); a
    ///   commit's author/date line (metadata beside the commit, the same
    ///   role as a project's VCS kind beside its name).
    /// - `view/history.rs`, 2 — an entry's timestamp and project count.
    /// - `view/overlays/context_switch.rs`, 2 — the VCS kind and branch/
    ///   bookmark detail beside a candidate's name, and the VCS kind label
    ///   beside the confirm-switch target's own name. (Three other sites
    ///   in this same file were moved to `body` during classification —
    ///   see the Stage 3 review request's table — because they named the
    ///   message's own content, not a detail beside another name.)
    /// - `widget/buttons.rs`, 1 — `icon_button_maybe`'s tooltip.
    /// - `widget/checkbox.rs`, 1 — the checkbox tooltip (consistency with
    ///   `buttons.rs`'s tooltip, D10's "today's tooltip" ruling).
    /// - `widget/field.rs`, 1 — `validated_field`'s unit suffix ("seconds"
    ///   beside a value), the same kind of terse qualifier as a count
    ///   inside metadata.
    const EXPECTED_BODY_SMALL_SITES: &[(&str, usize)] = &[
        ("view/add_project_modal.rs", 1),
        ("view/dashboard/row.rs", 1),
        ("view/detail_panel.rs", 2),
        ("view/history.rs", 2),
        ("view/overlays/context_switch.rs", 2),
        ("widget/buttons.rs", 1),
        ("widget/checkbox.rs", 1),
        ("widget/field.rs", 1),
    ];

    /// RFC-071 Amendment A3 D14: pins `EXPECTED_BODY_SMALL_SITES` — a new
    /// `body_small` text site anywhere under either scanned directory must
    /// be a deliberate addition to this map (with its own one-line "why",
    /// same discipline `suppressions_guard.rs` requires), not a silent
    /// drift back toward the smaller size D14 exists to move text away
    /// from. Keys are `<scan-dir-name>/<path relative to that dir>`
    /// (`view/...` or `widget/...`), portable across checkouts — unlike
    /// the two empty-map tests above, whose `file.display()` keys were
    /// never exercised against a real mismatch and so never had to be.
    #[test]
    fn body_small_text_sites_match_the_d14_classification_map() {
        let mut actual: std::collections::BTreeMap<String, usize> =
            std::collections::BTreeMap::new();
        let mut total_files = 0;

        for dir in scan_dirs() {
            let dir_name = dir
                .file_name()
                .and_then(|n| n.to_str())
                .expect("scan dir has a UTF-8 name")
                .to_owned();
            let files = rust_files_under(&dir);
            total_files += files.len();
            for file in files.iter().filter(|f| is_scan_target(f)) {
                let Ok(source) = std::fs::read_to_string(file) else {
                    continue;
                };
                let clean = blank_comment_lines(&source);
                let n = count_body_small_text_sites(&clean);
                if n > 0 {
                    let rel = file
                        .strip_prefix(&dir)
                        .unwrap_or(file)
                        .to_string_lossy()
                        .replace('\\', "/");
                    actual.insert(format!("{dir_name}/{rel}"), n);
                }
            }
        }

        assert!(
            total_files > 20,
            "found only {total_files} .rs files under the two scanned \
             directories -- path resolution is broken (expected 20+ across \
             view/ and widget/), not that nothing needed checking"
        );

        let expected: std::collections::BTreeMap<String, usize> = EXPECTED_BODY_SMALL_SITES
            .iter()
            .map(|(path, n)| ((*path).to_owned(), *n))
            .collect();

        assert_eq!(
            actual, expected,
            "`body_small` text sites changed -- RFC-071 Amendment A3 D14 \
             requires every `body_small` site to be classified once (kept, \
             with a one-line reason at the call site, and an entry here; or \
             moved to `body`). If you added a new kept site, add it to \
             `EXPECTED_BODY_SMALL_SITES` with the same per-item \
             justification its neighbours carry. If you moved or removed \
             one, remove its entry (or lower its count) here too.\n\
             actual:   {actual:#?}\n\
             expected: {expected:#?}"
        );
    }
}