Repository navigation
Expand file tree
/
Copy pathgates.rs
More file actions
535 lines (503 loc) · 20.1 KB
/
Copy pathgates.rs
File metadata and controls
535 lines (503 loc) · 20.1 KB
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
//! Ratchet counters for the GUI substrate migration: each counter measures a
//! form of TUI/core coupling that must reach zero before a second frontend
//! can share the core (`crate::tui` imports outside `tui/`, direct `App`
//! field writes in handlers, raw `IoEvent` dispatch from the TUI, mouse
//! handling that synthesizes keystrokes, wildcard arms in the action tree,
//! producers outside the TUI that write its `App::view` presentation state,
//! `App` fields any module can still write, reads of the cached Spotify
//! playback context that bypass the ownership resolver).
//!
//! `tools/gates.count` holds the measured baselines. The test below pins every
//! coupling counter to its baseline exactly, so a PR that moves one must also
//! move the file. The two adoption counters are floors: a PR that adds tests
//! leaves the file alone, and the `gates-floor` workflow raises the floors on
//! `main` after the merge (`GATES_BLESS=1` does the same locally). The
//! direction is enforced by `tools/check_gates_ratchet.sh` against the merge
//! base: coupling counters may only fall, while the adoption counters may only
//! rise.
//! `test_attribute_total` is the first adoption counter, so a refactor cannot
//! silently delete a test module's worth of tests (it is a text count over
//! `src/`, so it catches deletions, not a module that still compiles under a
//! stale feature gate but stops running). `action_refs_in_tui_handlers` is
//! the second: shared `Action::` uses in production handler code, which must
//! rise with every handler conversion. Without it a conversion could replace
//! field writes with arbitrary `App` method calls and never adopt the shared
//! vocabulary.
use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
fn repo_root() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
}
fn collect_rs_files(dir: &Path, out: &mut Vec<PathBuf>) {
let Ok(entries) = fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
collect_rs_files(&path, out);
} else if path.extension().and_then(|ext| ext.to_str()) == Some("rs") {
out.push(path);
}
}
}
fn read_source(path: &Path) -> String {
fs::read_to_string(path).unwrap_or_else(|err| panic!("failed to read {}: {err}", path.display()))
}
/// Sums non-overlapping occurrences of `needle` across every `.rs` file under
/// `dirs` (recursive) plus the standalone `files`.
fn count_occurrences(dirs: &[&str], files: &[&str], needle: &str) -> usize {
let root = repo_root();
let mut paths = Vec::new();
for dir in dirs {
collect_rs_files(&root.join(dir), &mut paths);
}
for file in files {
paths.push(root.join(file));
}
paths
.iter()
.map(|path| read_source(path).matches(needle).count())
.sum()
}
fn is_ident_byte(byte: u8) -> bool {
byte.is_ascii_alphanumeric() || byte == b'_'
}
/// True when the byte before `pos` continues an identifier, so a needle found
/// at `pos` is the tail of a longer name (`wrapped_app.`, `PlaybackAction::`).
fn preceded_by_ident(source: &str, pos: usize) -> bool {
pos > 0 && is_ident_byte(source.as_bytes()[pos - 1])
}
/// Walks the `field(.field)*` chain that starts at `chain_start` and reports
/// whether an assignment operator follows it on the same line. False when no
/// field name starts there. Comparisons (`==`), match guards (`=>`), method
/// calls, and indexed writes are not writes. This is the exact matcher the
/// write baselines were measured with.
fn chain_is_written(source: &str, chain_start: usize) -> bool {
let bytes = source.as_bytes();
let mut pos = chain_start;
loop {
let ident_start = pos;
while pos < bytes.len() && is_ident_byte(bytes[pos]) {
pos += 1;
}
if pos == ident_start {
break;
}
if pos < bytes.len() && bytes[pos] == b'.' {
pos += 1;
continue;
}
break;
}
if pos == chain_start {
return false; // no field name after the prefix
}
// Only same-line spacing may separate the chain from the operator.
while pos < bytes.len() && (bytes[pos] == b' ' || bytes[pos] == b'\t') {
pos += 1;
}
match bytes.get(pos) {
Some(b'+' | b'-' | b'*' | b'/' | b'%' | b'|' | b'&' | b'^') => {
bytes.get(pos + 1) == Some(&b'=')
}
Some(shift @ (b'<' | b'>')) => {
bytes.get(pos + 1) == Some(shift) && bytes.get(pos + 2) == Some(&b'=')
}
Some(b'=') => !matches!(bytes.get(pos + 1), Some(b'=') | Some(b'>')),
_ => false,
}
}
/// Counts reads of `App::current_playback_context`: a `.current_playback_context`
/// access outside a line comment that is not a whole-value assignment, so the
/// `= Some(..)` seeds in tests and the producers' whole-value writes do not
/// count. A nested write (`.is_playing = false`) and a `&mut` borrow through
/// the field do count: both reach into the cached context. A whole-value
/// assignment rustfmt wrapped onto the next line would count too; none
/// exists today. String literals are not stripped (no other counter does).
/// The cached context names the *suspended* Spotify track while a decoded
/// source or the native queue slot owns the sink, so every reader outside
/// the ownership resolver (`core/app/playback_routing.rs`), the snapshot
/// builder (`infra/media_metadata.rs`) and this file is a candidate for
/// reading the wrong track. No `#[cfg(test)]` cut: production code can follow
/// a test module (`tui/runner.rs`), and every test occurrence is a write anyway.
fn count_playback_context_reads(source: &str) -> usize {
let needle = concat!(".current_", "playback_context");
source
.lines()
.filter(|line| !line.trim_start().starts_with("//"))
.flat_map(|line| {
line.match_indices(needle).filter(move |&(start, needle)| {
// A whole-value assignment is a write; anything deeper (`.item`,
// `.as_ref()`, `.is_playing = ..`) reads through the field.
line.as_bytes().get(start + needle.len()) == Some(&b'.')
|| !chain_is_written(line, start + 1)
})
})
.count()
}
/// Counts direct `App` field writes: `app.<field>` (optionally a deeper
/// `.field` chain) followed on the same line by `=` or a compound assignment
/// operator. Chains into `app.view` (the TUI's own presentation state, see
/// `core::app::ViewState`) are not coupling and do not count.
fn count_app_field_writes(source: &str) -> usize {
source
.match_indices("app.")
.filter(|&(start, _)| !preceded_by_ident(source, start))
.map(|(start, needle)| start + needle.len())
.filter(|&chain_start| !source[chain_start..].starts_with("view."))
.filter(|&chain_start| chain_is_written(source, chain_start))
.count()
}
/// Counts writes into `App::view`: `<receiver>.view.<field>` (optionally a
/// deeper chain) followed on the same line by an assignment operator. Measured
/// over every file outside `src/tui/` and `src/core/app/` (and this file),
/// tests included like the handler write counter: a producer that resets or
/// clamps a cursor after it replaces a list, and the test that pins that
/// behavior. Each one is a place where the TUI's presentation state leaks into
/// shared code; the end state is a producer-side revision the frontend reacts to.
fn count_view_field_writes(source: &str) -> usize {
let bytes = source.as_bytes();
// A field access has a receiver directly before the dot; a `.view.` that
// opens a string literal or a line is not one.
let has_receiver = |start: usize| {
start > 0 && (is_ident_byte(bytes[start - 1]) || matches!(bytes[start - 1], b')' | b']'))
};
source
.match_indices(".view.")
.filter(|&(start, _)| has_receiver(start))
.filter(|&(start, needle)| chain_is_written(source, start + needle.len()))
.count()
}
/// Counts shared `Action::` uses in the production half of one handler file:
/// the text before its first test-gated item (every handler keeps its tests in
/// one tail module, gated by `#[cfg(test)]` or `#[cfg(all(test, …))]`). The
/// match is word-bounded, so `PlaybackAction::` and similar do not count.
fn count_production_action_refs(source: &str) -> usize {
let tests_start = ["#[cfg(test)]", "#[cfg(all(test"]
.iter()
.filter_map(|gate| source.find(gate))
.min()
.unwrap_or(source.len());
let production = &source[..tests_start];
production
.match_indices("Action::")
.filter(|&(start, _)| !preceded_by_ident(production, start))
.count()
}
/// Counts the fields of `pub struct App` that any module can write: `pub` and
/// `pub(crate)`. A `pub(super)` or private field is reached only through `App`
/// methods. The body is brace-matched from the struct header; a field is a
/// two-space-indented `[pub[(crate)] ]name:` line, with no space required
/// after the colon, because a field whose type wraps to the next line ends
/// at the colon.
fn count_public_app_fields(source: &str) -> usize {
let header = "pub struct App {";
let start = source
.find(header)
.expect("src/core/app/mod.rs declares `pub struct App {`");
let body = &source[start + header.len()..];
let mut depth = 1usize;
let mut end = body.len();
for (index, byte) in body.bytes().enumerate() {
match byte {
b'{' => depth += 1,
b'}' => {
depth -= 1;
if depth == 0 {
end = index;
break;
}
}
_ => {}
}
}
body[..end]
.lines()
.filter_map(|line| line.strip_prefix(" "))
.filter(|rest| !rest.starts_with(' '))
.filter(|rest| {
let name = rest
.strip_prefix("pub(crate) ")
.or_else(|| rest.strip_prefix("pub "))
.unwrap_or("");
let name_len = name.bytes().take_while(|byte| is_ident_byte(*byte)).count();
name_len > 0 && name.as_bytes().get(name_len) == Some(&b':')
})
.count()
}
/// Counters checked as floors; `tools/check_gates_ratchet.sh` lists the same two in `RISE_ONLY`.
const ADOPTION_COUNTERS: [&str; 2] = ["action_refs_in_tui_handlers", "test_attribute_total"];
fn load_baselines() -> BTreeMap<String, usize> {
let path = repo_root().join("tools").join("gates.count");
let text = read_source(&path);
let mut map = BTreeMap::new();
for raw in text.lines() {
let line = raw.split('#').next().unwrap_or("").trim();
if line.is_empty() {
continue;
}
let (key, value) = line
.split_once('=')
.unwrap_or_else(|| panic!("malformed line in tools/gates.count: {raw}"));
let value = value
.trim()
.parse::<usize>()
.unwrap_or_else(|_| panic!("bad number in tools/gates.count: {raw}"));
map.insert(key.trim().to_string(), value);
}
map
}
#[test]
fn ratchet_counters_match_the_checked_in_baselines() {
let root = repo_root();
let mut handler_files = Vec::new();
collect_rs_files(&root.join("src/tui/handlers"), &mut handler_files);
let (app_field_writes, action_refs) =
handler_files
.iter()
.fold((0usize, 0usize), |(writes, refs), path| {
let source = read_source(path);
(
writes + count_app_field_writes(&source),
refs + count_production_action_refs(&source),
)
});
// Needles that would otherwise count their own literal in this file are
// assembled with concat! (this file lives under the `src/` scan).
let test_attribute_total = count_occurrences(&["src"], &[], concat!("#[", "test]"))
+ count_occurrences(&["src"], &[], concat!("#[", "tokio::test"));
// Every Rust file outside `src/tui/` is in scope, so a new top-level module
// (or a future `src/gui.rs`) cannot re-import the TUI unseen. This file is
// the one exclusion: it names the needle in its own doc and data, and being
// test-only it cannot couple anything to `tui/`.
let mut non_tui_files = Vec::new();
collect_rs_files(&root.join("src"), &mut non_tui_files);
let tui_dir = root.join("src").join("tui");
let gates_file = root.join("src").join("gates.rs");
non_tui_files.retain(|path| !path.starts_with(&tui_dir) && *path != gates_file);
// The view-write scan also skips `src/core/app/` (whose methods are `App`'s
// own presentation helpers): it counts every producer that still writes a
// TUI cursor.
let app_dir = root.join("src").join("core").join("app");
let (crate_tui_refs, view_writes) =
non_tui_files
.iter()
.fold((0usize, 0usize), |(refs, writes), path| {
let source = read_source(path);
let view_writes = if path.starts_with(&app_dir) {
0
} else {
count_view_field_writes(&source)
};
(
refs + source.matches("crate::tui").count(),
writes + view_writes,
)
});
// (name, measured value). Every counter must match its baseline exactly;
// the direction a baseline may move is enforced against the merge base by
// tools/check_gates_ratchet.sh.
let public_app_fields = count_public_app_fields(&read_source(&root.join("src/core/app/mod.rs")));
// Every Rust file under `src/` except the two that resolve playback from the
// raw field on purpose, and this file (its matcher test spells the needle).
let resolver_files = [
app_dir.join("playback_routing.rs"),
root.join("src").join("infra").join("media_metadata.rs"),
gates_file.clone(),
];
let mut playback_reader_files = Vec::new();
collect_rs_files(&root.join("src"), &mut playback_reader_files);
playback_reader_files.retain(|path| !resolver_files.contains(path));
let playback_context_reads = playback_reader_files
.iter()
.map(|path| count_playback_context_reads(&read_source(path)))
.sum();
let measured: [(&str, usize); 10] = [
("crate_tui_refs_outside_tui", crate_tui_refs),
("app_field_writes_in_tui_handlers", app_field_writes),
(
"ioevent_refs_in_tui",
count_occurrences(&["src/tui"], &[], "IoEvent::"),
),
// Both spellings of a synthesized keystroke.
(
"synthetic_keys_in_mouse_handler",
count_occurrences(&[], &["src/tui/handlers/mouse.rs"], "handler(Key::")
+ count_occurrences(
&[],
&["src/tui/handlers/mouse.rs"],
"handle_block_events(Key::",
),
),
(
"wildcard_arms_in_action_tree",
count_occurrences(&["src/core/action"], &[], "_ =>"),
),
("view_writes_outside_tui", view_writes),
("pub_fields_on_app", public_app_fields),
("direct_playback_context_reads", playback_context_reads),
("action_refs_in_tui_handlers", action_refs),
("test_attribute_total", test_attribute_total),
];
let bless = std::env::var_os("GATES_BLESS").is_some();
let mut baselines = load_baselines();
let mut raised = Vec::new();
let mut report = String::new();
for (name, actual) in measured {
let is_floor = ADOPTION_COUNTERS.contains(&name);
match baselines.remove(name) {
None => report.push_str(&format!(
"{name}: missing from tools/gates.count (measured {actual})\n"
)),
Some(baseline) if is_floor && actual > baseline => {
if bless {
raised.push((name, actual));
}
}
Some(baseline) if is_floor && actual < baseline => report.push_str(&format!(
"{name}: floor {baseline}, measured {actual}; the adoption counters may \
only rise, so restore what the PR removed\n"
)),
Some(baseline) if baseline != actual => report.push_str(&format!(
"{name}: baseline {baseline}, measured {actual}; move the baseline in \
tools/gates.count in this same PR (tools/check_gates_ratchet.sh enforces \
the direction it may move)\n"
)),
Some(_) => {}
}
}
for (name, baseline) in baselines {
report.push_str(&format!(
"{name} = {baseline}: unknown counter in tools/gates.count, remove or fix the name\n"
));
}
assert!(report.is_empty(), "\nratchet violations:\n{report}");
if !raised.is_empty() {
let path = root.join("tools").join("gates.count");
fs::write(&path, raise_floors(&read_source(&path), &raised))
.unwrap_or_else(|err| panic!("failed to write {}: {err}", path.display()));
}
}
/// Rewrites the value on each `name = N` line in `raised`, keeping the comment column.
fn raise_floors(text: &str, raised: &[(&str, usize)]) -> String {
let mut out = String::new();
for line in text.lines() {
let (code, comment) = match line.split_once('#') {
Some((code, comment)) => (code, Some(comment)),
None => (line, None),
};
let floor = code
.split_once('=')
.and_then(|(key, _)| raised.iter().find(|(name, _)| *name == key.trim()));
match (floor, comment) {
(Some((name, value)), Some(comment)) => {
let code = format!("{name} = {value}");
let width = code.len().max(line.len() - comment.len() - 1);
out.push_str(&format!("{code:<width$}"));
if !out.ends_with(' ') {
out.push(' ');
}
out.push('#');
out.push_str(comment);
}
(Some((name, value)), None) => out.push_str(&format!("{name} = {value}")),
(None, _) => out.push_str(line),
}
out.push('\n');
}
out
}
#[test]
fn field_write_matcher_counts_assignment_operators() {
let src = "app.x = 1;\napp.a.b += 2;\napp.c -= 3;\napp.d *= 4;\napp.e <<= 1;\napp.f >>= 2;\n";
assert_eq!(count_app_field_writes(src), 6);
}
#[test]
fn field_write_matcher_ignores_comparisons_guards_calls_and_other_idents() {
let src = "if app.x == 1 {}\n\
Key::Up if app.flag => {}\n\
app.list.push(1);\n\
foo(app.x);\n\
if app.x != y {}\n\
if app.x <= y {}\n\
if app.x >= y {}\n\
let s = app.y << 2;\n\
wrapped_app.x = 1;\n";
assert_eq!(count_app_field_writes(src), 0);
}
#[test]
fn field_write_matcher_skips_view_chains() {
let src = "app.view.x = 1;\napp.view.a.b += 2;\napp.y = 3;\napp.viewer = 4;\n";
assert_eq!(count_app_field_writes(src), 2);
}
#[test]
fn view_write_matcher_needs_a_receiver_and_an_assignment() {
let src = "app.view.x = 1;\n\
guard.view.a.b += 2;\n\
if app.view.x == 1 {}\n\
app.view.list.push(1);\n\
let s = \".view.x = 1\";\n\
foo(app.view.x);\n";
assert_eq!(count_view_field_writes(src), 2);
}
#[test]
fn playback_context_read_matcher_skips_whole_value_writes_and_comments() {
let src = "let item = self.current_playback_context.as_ref();\n\
app.current_playback_context = Some(ctx);\n\
if let Some(c) = &app.current_playback_context {}\n\
ctx.current_playback_context.is_playing = false;\n\
app.current_playback_context.item = None;\n\
/// reads `app.current_playback_context` in a doc comment\n\
let current_playback_context = None;\n";
assert_eq!(count_playback_context_reads(src), 4);
}
#[test]
fn public_field_matcher_counts_pub_and_pub_crate_fields_only() {
let src = "pub struct App {\n\
\x20 pub a: u8,\n\
\x20 pub(crate) b: u8,\n\
\x20 pub(super) c: u8,\n\
\x20 d: u8,\n\
\x20 /// pub e: u8 in a doc comment\n\
\x20 #[cfg(feature = \"x\")]\n\
\x20 pub wrapped:\n\
\x20 Option<u8>,\n\
\x20 pub view: ViewState,\n\
}\n\
pub struct Other {\n\
\x20 pub z: u8,\n\
}\n";
assert_eq!(count_public_app_fields(src), 4);
}
#[test]
fn action_ref_matcher_is_word_bounded_and_stops_at_the_test_module() {
let src = "app.apply(Action::Play);\n\
let x = PlaybackAction::Pause;\n\
app.apply(Action::Next)?;\n\
#[cfg(test)]\n\
mod tests { fn t() { app.apply(Action::Play); } }\n";
assert_eq!(count_production_action_refs(src), 2);
let gated = "app.apply(Action::Play);\n\
#[cfg(all(test, feature = \"x\"))]\n\
mod tests { fn t() { app.apply(Action::Play); } }\n";
assert_eq!(count_production_action_refs(gated), 1);
}
#[test]
fn raise_floors_rewrites_only_the_named_lines_and_keeps_the_comment_column() {
let src = "# header\n\
a = 5 # coupling\n\
b = 9 # adoption\n\
c = 99999 # adoption\n\
d = 1\n";
let raised = raise_floors(src, &[("b", 12), ("c", 1234567), ("d", 2)]);
assert_eq!(
raised,
"# header\n\
a = 5 # coupling\n\
b = 12 # adoption\n\
c = 1234567 # adoption\n\
d = 2\n"
);
}