blockwatch 0.4.0

Language agnostic linter that keeps your code and documentation in sync and valid
Documentation
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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
use crate::blocks::{Block, BlockWithContext, FileBlocks, every_block, parse_file};
use crate::fs::FileSystem;
use crate::repo_path::RepoPath;
use crate::validators;
use crate::validators::{ValidationReport, ValidatorType, Violation, ViolationRange};
use anyhow::Context;
use serde::Serialize;
use std::collections::hash_map::Entry;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;

/// Enforces `affects="file:name"`: when a block's content changes, every block it declares it
/// affects must have changed in the same diff.
///
/// E.g., catches a constant edited without its documentation, or an enum extended without its
/// switch statement.
pub(crate) struct AffectsValidator<Fs: FileSystem> {
    /// Reads target files that the run's scope excluded but the diff still names.
    file_system: Arc<Fs>,
}

impl<Fs: FileSystem + 'static> AffectsValidator<Fs> {
    /// Creates the validator over the filesystem it will read excluded target files from.
    pub(super) fn new(file_system: Arc<Fs>) -> Self {
        Self { file_system }
    }
}

#[derive(Serialize)]
struct AffectsViolation<'a> {
    affected_block_file_path: &'a RepoPath,
    affected_block_name: &'a str,
}

impl<Fs: FileSystem + 'static> validators::ValidatorSync for AffectsValidator<Fs> {
    fn validate(
        &self,
        context: Arc<validators::ValidationContext>,
    ) -> anyhow::Result<ValidationReport> {
        let modified_names = modified_block_names(&context);
        // Caches target files read from disk so each is parsed at most once. `validate` runs on a
        // single thread, so no synchronization is needed.
        let mut cache: HashMap<RepoPath, FileBlocks> = HashMap::new();
        let mut report = ValidationReport::default();
        for (file_path, block_with_context) in content_modified_blocks(&context) {
            // A block without the attribute places no obligation on anything, and must not be
            // recorded as checked either.
            let Some(affects) = block_with_context.block.attributes.get("affects") else {
                continue;
            };
            let violations = self.unsatisfied_references(
                &context,
                &modified_names,
                &mut cache,
                file_path,
                block_with_context,
                affects,
            )?;
            report.add_all(file_path, &block_with_context.block, violations);
        }
        Ok(report)
    }
}

impl<Fs: FileSystem + 'static> AffectsValidator<Fs> {
    /// One violation for every block that `affects` names but the same diff left unchanged.
    ///
    /// `affects` is the attribute's raw value; the caller has already established that
    /// `block_with_context` carries it and that the diff modified the block's content.
    fn unsatisfied_references(
        &self,
        context: &validators::ValidationContext,
        modified_names: &HashSet<(RepoPath, String)>,
        cache: &mut HashMap<RepoPath, FileBlocks>,
        file_path: &RepoPath,
        block_with_context: &BlockWithContext,
        affects: &str,
    ) -> anyhow::Result<Vec<Violation>> {
        let references = validators::parse_block_references(affects).with_context(|| {
            format!(
                "invalid affects reference on block {}:{} at line {}",
                file_path,
                block_with_context.block.name_display(),
                block_with_context
                    .block
                    .start_tag_position_range
                    .start()
                    .line,
            )
        })?;
        let mut violations = Vec::new();
        for (target_file, target_name) in references {
            // A reference like ":foo" is resolved relative to the file the block is in.
            let target_file = target_file.unwrap_or_else(|| file_path.clone());
            let was_modified = modified_names.contains(&(target_file.clone(), target_name.clone()))
                || target_modified_outside_scope(
                    context,
                    self.file_system.as_ref(),
                    cache,
                    &target_file,
                    &target_name,
                )?;
            if !was_modified {
                violations.push(create_violation(
                    file_path,
                    &block_with_context.block,
                    &target_file,
                    target_name.as_str(),
                )?);
            }
        }
        Ok(violations)
    }
}

/// Every block in the run whose content the diff changed, paired with the file it was found in.
fn content_modified_blocks(
    context: &validators::ValidationContext,
) -> impl Iterator<Item = (&RepoPath, &BlockWithContext)> {
    context.blocks.iter().flat_map(|(file_path, file_blocks)| {
        file_blocks
            .blocks_with_context
            .iter()
            .filter(|block_with_context| block_with_context.is_content_modified)
            .map(move |block_with_context| (file_path, block_with_context))
    })
}

/// The `(file, name)` key of every named block the diff modified, which is what a reference has to
/// match to be satisfied. Unnamed blocks are skipped because they can't be referenced.
fn modified_block_names(context: &validators::ValidationContext) -> HashSet<(RepoPath, String)> {
    content_modified_blocks(context)
        .filter_map(|(file_path, block_with_context)| {
            block_with_context
                .block
                .name()
                .map(|name| (file_path.clone(), name.to_string()))
        })
        .collect()
}

/// Whether the target *outside* the validation context was modified.
///
/// This can happen when the globs constrain the validation context: the diff may mention a block in
/// a file that does not match the given globs.
fn target_modified_outside_scope<Fs: FileSystem>(
    context: &validators::ValidationContext,
    file_system: &Fs,
    cache: &mut HashMap<RepoPath, FileBlocks>,
    target_file: &RepoPath,
    target_name: &str,
) -> anyhow::Result<bool> {
    if context.blocks.contains_key(target_file) {
        // Target file is in the validation context, so it must already be in scope.
        return Ok(false);
    }
    let Some(line_changes) = context.line_changes_for(target_file) else {
        // The target file is not in the diff.
        return Ok(false);
    };
    if !file_system.exists(target_file.as_path()) {
        return Ok(false);
    }
    let file_blocks = match cache.entry(target_file.clone()) {
        Entry::Occupied(entry) => entry.into_mut(),
        Entry::Vacant(entry) => {
            // Referenced target files are resolved without applying extension overrides, matching
            // how `same-as` reads the files it references.
            let Some(parsed) = parse_file(
                file_system,
                target_file.as_path(),
                line_changes,
                every_block,
                context.parsers(),
                &HashMap::new(),
            )?
            else {
                return Ok(false);
            };
            entry.insert(parsed)
        }
    };
    Ok(file_blocks
        .blocks_with_context
        .iter()
        .any(|block| block.is_content_modified && block.block.name() == Some(target_name)))
}

/// Selects [`AffectsValidator`] for blocks that carry an `affects` attribute *and* were modified —
/// an unchanged block places no obligation on anything.
pub(crate) struct AffectsValidatorDetector();

impl AffectsValidatorDetector {
    /// Creates the detector. Registered in [`crate::validators::detector_factories`].
    pub fn new() -> Self {
        Self {}
    }
}

impl<Fs: FileSystem + 'static> validators::ValidatorDetector<Fs> for AffectsValidatorDetector {
    fn detect(
        &self,
        block_with_context: &BlockWithContext,
        file_system: &Arc<Fs>,
    ) -> anyhow::Result<Option<ValidatorType>> {
        if block_with_context.is_content_modified
            && block_with_context.block.attributes.contains_key("affects")
        {
            Ok(Some(ValidatorType::Sync(Box::new(AffectsValidator::new(
                Arc::clone(file_system),
            )))))
        } else {
            Ok(None)
        }
    }
}

fn create_violation(
    modified_block_file_path: &RepoPath,
    modified_block: &Block,
    affected_block_file_path: &RepoPath,
    affected_block_name: &str,
) -> anyhow::Result<Violation> {
    let message = format!(
        "Block {}:{} at line {} is modified, but {}:{} is not",
        modified_block_file_path.display(),
        modified_block.name_display(),
        modified_block.start_tag_position_range.start().line,
        affected_block_file_path.display(),
        affected_block_name
    );
    let details = serde_json::to_value(AffectsViolation {
        affected_block_file_path,
        affected_block_name,
    })
    .context("failed to serialize AffectsViolation block")?;
    Ok(Violation::new(
        ViolationRange::new(
            modified_block.start_tag_position_range.start().clone(),
            modified_block.start_tag_position_range.end().clone(),
        ),
        "affects".to_string(),
        message,
        modified_block.severity()?,
        Some(details),
    ))
}

#[cfg(test)]
mod validate_tests {
    use super::*;
    use crate::diff_parser::LineChange;
    use crate::fs::test_utils::FakeFileSystem;
    use crate::repo_path::RepoPath;
    use crate::test_utils::{
        checked_lines, merge_validation_contexts, validation_context,
        validation_context_with_changes,
    };
    use crate::validators::ValidatorSync;

    /// Builds a validator with a fake filesystem seeded with `files` (path, contents).
    fn validator(files: &[(&str, &str)]) -> AffectsValidator<FakeFileSystem> {
        let map = files
            .iter()
            .map(|(p, c)| (p.to_string(), c.to_string()))
            .collect();
        AffectsValidator::new(Arc::new(FakeFileSystem::new(map)))
    }

    /// The two-file setup where a block in `source.py` references a block in `target.py`.
    fn two_file_system() -> FakeFileSystem {
        FakeFileSystem::new(HashMap::from([
            (
                "source.py".to_string(),
                "# <block name=\"s\" affects=\"target.py:t\">\nvalue = 2\n# </block>".to_string(),
            ),
            (
                "target.py".to_string(),
                "# <block name=\"t\">\nvalue = 2\n# </block>".to_string(),
            ),
        ]))
    }

    /// Parses `line_changes` into a context that only `source.py` is in scope for, the way a run
    /// given a glob matching just that file would.
    fn context_scoped_to_source(
        file_system: &FakeFileSystem,
        line_changes: HashMap<RepoPath, Vec<LineChange>>,
    ) -> anyhow::Result<Arc<validators::ValidationContext>> {
        let parsers = crate::language_parsers::language_parsers()?;
        let parsed = crate::blocks::parse_blocks(
            &line_changes,
            crate::blocks::ScanMode::OnlyChanged,
            file_system,
            &crate::fs::test_utils::FakePathChecker::allow_only("source.py"),
            &parsers,
            HashMap::new(),
        )?;
        assert!(
            !parsed
                .blocks
                .contains_key(&RepoPath::from_reference("target.py")?),
            "the glob must keep the target out of the validated set"
        );
        Ok(Arc::new(validators::ValidationContext::new(
            parsed.blocks,
            parsers,
            line_changes,
        )))
    }

    #[test]
    fn modified_block_with_modified_targets_validate_returns_no_violations() -> anyhow::Result<()> {
        let validator = validator(&[]);
        let context = merge_validation_contexts(vec![
            validation_context(
                "file1.py",
                r#"# <block affects="file2.py:foo">
print("first")
# </block>

# <block affects="file3.py:bar">
print("second")
# </block>
"#,
            ),
            validation_context(
                "file2.py",
                r#"# <block name="foo">
print("foo")
# </block>
"#,
            ),
            validation_context(
                "file3.py",
                r#"# <block name="bar">
print("bar")
# </block>
"#,
            ),
        ]);

        let violations = validator.validate(context)?.violations;

        assert!(violations.is_empty());
        Ok(())
    }

    #[test]
    fn modified_block_with_unmodified_targets_validate_returns_violations() -> anyhow::Result<()> {
        let validator = validator(&[]);
        let context = merge_validation_contexts(vec![
            validation_context(
                "file1.py",
                r#"# <block affects="file2.py:foo">
print("first")
# </block>

# <block affects="file3.py:bar">
print("second")
# </block>
"#,
            ),
            validation_context_with_changes(
                "file2.py",
                r#"# <block name="foo">
print("file2")
# </block>
"#,
                vec![LineChange {
                    line: 1, // Only the start tag is changed, not the content.
                    ranges: Some(vec![3..8, 10..15]),
                }],
            ),
            validation_context_with_changes(
                "file3.py",
                r#"# <block name="not-bar">
print("file3")
# </block>
"#,
                vec![LineChange {
                    line: 3, // Only the end tag is modified, not the content.
                    ranges: None,
                }],
            ),
        ]);

        let violations = validator.validate(context)?.violations;

        assert_eq!(violations.len(), 1);
        let file1_violations = violations
            .get(&RepoPath::from_reference("file1.py").unwrap())
            .unwrap();
        assert_eq!(file1_violations.len(), 2);
        assert_eq!(
            file1_violations[0].message,
            "Block file1.py:(unnamed) at line 1 is modified, but file2.py:foo is not"
        );
        assert_eq!(
            file1_violations[1].message,
            "Block file1.py:(unnamed) at line 5 is modified, but file3.py:bar is not"
        );

        Ok(())
    }

    #[test]
    fn modified_block_with_unmodified_target_in_same_file_validate_returns_violation()
    -> anyhow::Result<()> {
        let validator = validator(&[]);
        let context = validation_context_with_changes(
            "file1.py",
            r#"# <block affects=":foo">
print("first")
# </block>

# <block name="foo">
print("second")
# </block>
"#,
            vec![LineChange {
                line: 2,
                ranges: None,
            }],
        );

        let violations = validator.validate(context)?.violations;

        assert_eq!(violations.len(), 1);
        let file1_violations = violations
            .get(&RepoPath::from_reference("file1.py").unwrap())
            .unwrap();
        assert_eq!(file1_violations.len(), 1);
        assert_eq!(
            file1_violations[0].message,
            "Block file1.py:(unnamed) at line 1 is modified, but file1.py:foo is not"
        );

        Ok(())
    }

    #[test]
    fn block_with_unmodified_content_validate_returns_no_violations() -> anyhow::Result<()> {
        let validator = validator(&[]);
        let context = merge_validation_contexts(vec![
            validation_context_with_changes(
                "file1.py",
                r#"# <block affects="file2.py:foo">
pass
# </block>

# <block affects="file3.py:bar">
pass
# </block>
"#,
                vec![
                    LineChange {
                        line: 1,
                        ranges: Some(vec![0..10, 12..15]),
                    }, // First block start tag
                    LineChange {
                        line: 7,
                        ranges: None,
                    }, // Second block end tag
                ],
            ),
            validation_context_with_changes(
                "file2.py",
                r#"# <block name="foo">
pass
# </block>
"#,
                vec![LineChange {
                    line: 1,
                    ranges: Some(vec![0..4, 6..10]),
                }], // Only start tag modified
            ),
            validation_context_with_changes(
                "file3.py",
                r#"# <block name="bar">
pass
# </block>
"#,
                vec![LineChange {
                    line: 3,
                    ranges: None,
                }], // Only end tag modified
            ),
        ]);

        let violations = validator.validate(context)?.violations;

        assert!(violations.is_empty());
        Ok(())
    }

    #[test]
    fn modified_block_with_multiple_modified_targets_validate_returns_no_violations()
    -> anyhow::Result<()> {
        let validator = validator(&[]);
        let context = merge_validation_contexts(vec![
            validation_context(
                "file1.py",
                r#"# <block name="foo" affects=":bar, file2.py:buzz">
print("foo")
# </block>

# <block name="bar" affects=":foo">
print("bar")
# </block>
"#,
            ),
            validation_context(
                "file2.py",
                r#"# <block name="buzz" affects="file1.py:bar">
print("buzz")
# </block>
"#,
            ),
        ]);

        let violations = validator.validate(context)?.violations;

        assert!(violations.is_empty());
        Ok(())
    }

    #[test]
    fn modified_block_with_one_unmodified_target_validate_returns_violation() -> anyhow::Result<()>
    {
        let validator = validator(&[]);
        let context = merge_validation_contexts(vec![
            validation_context(
                "file1.py",
                r#"# <block name="foo" affects=":bar, file2.py:buzz">
print("foo")
# </block>

# <block name="bar" affects=":foo">
print("bar")
# </block>
"#,
            ),
            validation_context_with_changes(
                "file2.py",
                r#"# <block name="buzz" affects="file1.py:bar">
print("not-buzz")
# </block>
print("hello")
"#,
                vec![LineChange {
                    line: 4, // Line outside the block is changed.
                    ranges: None,
                }],
            ),
        ]);

        let violations = validator.validate(context)?.violations;

        assert_eq!(violations.len(), 1);
        let file1_violations = violations
            .get(&RepoPath::from_reference("file1.py").unwrap())
            .unwrap();
        assert_eq!(file1_violations.len(), 1);
        assert_eq!(
            file1_violations[0].message,
            "Block file1.py:foo at line 1 is modified, but file2.py:buzz is not"
        );
        Ok(())
    }

    #[test]
    fn modified_target_outside_the_globs_validate_returns_no_violations() -> anyhow::Result<()> {
        let file_system = two_file_system();
        let line_changes = HashMap::from([
            (
                RepoPath::from_reference("source.py")?,
                vec![LineChange {
                    line: 2,
                    ranges: None,
                }],
            ),
            (
                RepoPath::from_reference("target.py")?,
                vec![LineChange {
                    line: 2,
                    ranges: None,
                }],
            ),
        ]);
        let context = context_scoped_to_source(&file_system, line_changes)?;

        let violations = AffectsValidator::new(Arc::new(file_system))
            .validate(context)?
            .violations;

        assert!(violations.is_empty());
        Ok(())
    }

    #[test]
    fn unmodified_target_outside_the_globs_validate_returns_violation() -> anyhow::Result<()> {
        // The counterpart of the test above: resolving a target the run did not read must report
        // the ones the diff never touched, rather than assuming anything out of scope is fine.
        let file_system = two_file_system();
        let line_changes = HashMap::from([(
            RepoPath::from_reference("source.py")?,
            vec![LineChange {
                line: 2,
                ranges: None,
            }],
        )]);
        let context = context_scoped_to_source(&file_system, line_changes)?;

        let violations = AffectsValidator::new(Arc::new(file_system))
            .validate(context)?
            .violations;

        assert_eq!(violations.len(), 1);
        Ok(())
    }

    #[test]
    fn blocks_with_cyclic_references_all_modified_validate_returns_no_violations()
    -> anyhow::Result<()> {
        let validator = validator(&[]);
        let context = validation_context(
            "file1.py",
            r#"# <block name="foo" affects=":bar">
print("foo")
# </block>

# <block name="bar" affects=":foo">
print("bar")
# </block>
"#,
        );

        let violations = validator.validate(context)?.violations;

        assert!(violations.is_empty());
        Ok(())
    }

    #[test]
    fn blocks_with_cyclic_references_partly_modified_validate_returns_violations()
    -> anyhow::Result<()> {
        let validator = validator(&[]);
        let contents = r#"# <block name="foo" affects=":bar">
print("foo")
# </block>

# <block name="bar" affects=":foo">
pass
# </block>
"#;
        let line_changes = vec![
            LineChange {
                line: 2,
                ranges: None,
            }, // First block's content line
            LineChange {
                line: 4, // Not in any of the blocks.
                ranges: None,
            },
        ];
        let context = validation_context_with_changes("file1.py", contents, line_changes);

        let violations = validator.validate(context)?.violations;

        assert!(!violations.is_empty());
        Ok(())
    }

    #[test]
    fn reference_with_leading_current_directory_validate_returns_no_violations()
    -> anyhow::Result<()> {
        // `./target.py` and `target.py` name the same file, so a change to both blocks satisfies
        // the reference regardless of which spelling the author used.
        let context = merge_validation_contexts(vec![
            validation_context(
                "source.py",
                "# <block name=\"s\" affects=\"./target.py:t\">\nvalue = 2\n# </block>",
            ),
            validation_context("target.py", "# <block name=\"t\">\nvalue = 2\n# </block>"),
        ]);
        assert!(validator(&[]).validate(context)?.violations.is_empty());
        Ok(())
    }

    #[test]
    fn blocks_without_affects_attribute_validate_returns_no_violations() -> anyhow::Result<()> {
        let validator = validator(&[]);
        let context = validation_context(
            "file1.py",
            r#"# <block name="foo">
pass
# </block>
"#,
        );

        let violations = validator.validate(context)?.violations;

        assert!(violations.is_empty());
        Ok(())
    }

    #[test]
    fn modified_block_with_affects_validate_records_one_check() -> anyhow::Result<()> {
        let context = validation_context(
            "example.py",
            r#"# <block name="source" affects=":target">
a = 1
# </block>
# <block name="target">
b = 2
# </block>"#,
        );

        let report = validator(&[]).validate(context)?;

        // Only the block with the `affects` attribute is checked. The target block is not.
        assert_eq!(checked_lines(&report), vec![1]);
        Ok(())
    }
}