Skip to main content

sokf_core/compare/
mod.rs

1//! The `compare` module asks the library same-same whether a generated block
2//! that differs from its expected text byte for byte means the same as it
3//! (design-loading, "Comparing by meaning"). same-same compares the formats
4//! that it knows by their meaning, and any other format through the project's
5//! formatter, or else by the bytes. The module builds the two sides of each
6//! pair, reads each answer as current or stale, and words the warning of a
7//! formatter that failed (CLI-4_AC-49). It passes same-same no type of sokf.
8//!
9//! A pass of the check collects its pairs, and `Session::settle` compares
10//! them in one batch, so that the check and the fix read the same answers
11//! from the `Layout` of `Expected`.
12
13mod names;
14mod session;
15mod words;
16
17use std::{
18    collections::{BTreeSet, HashMap},
19    ops::Range,
20};
21
22pub(crate) use names::name_of;
23pub use session::Session;
24
25use crate::{Finding, RepoPath};
26
27/// `WARNING` is the key of the warning that the formatter failed on a text
28/// or didn't start (CLI-4_AC-49).
29pub const WARNING: &str = "CLI-4_AC-49";
30
31/// A `Pair` is a text that sokf would write and the text that a file holds,
32/// which differ byte for byte, with the name under which same-same reads
33/// both, and the file that holds the text.
34#[derive(Debug, Clone, PartialEq, Eq, Hash)]
35pub struct Pair {
36    /// The file that holds the text.
37    pub path: RepoPath,
38    /// The name of both texts, the path of their file from the repository's
39    /// root, such as `src/package.json` or `.vscode/settings.json`, which
40    /// tells same-same their format by the file's name and, for a pattern of
41    /// two parts, its folder (CLI-4_AC-113).
42    pub name: String,
43    /// Whether both texts are a part of a file, read without the indentation
44    /// that all their lines share.
45    pub fragment: bool,
46    /// The text that sokf would write.
47    pub expected: String,
48    /// The text that the file holds.
49    pub actual: String,
50    /// Where the expected text lies in its source, for an include of a file.
51    pub source: Option<Source>,
52}
53
54/// A `Source` is where the expected text of an include of a file lies in
55/// the file.
56#[derive(Debug, Clone, PartialEq, Eq, Hash)]
57pub struct Source {
58    /// The included file.
59    pub path: RepoPath,
60    /// The lines of the file that the expected text is, as one run of whole
61    /// lines, for an include of a region, or `None` where the text leaves
62    /// out a line of the run, or where it is the whole file.
63    pub range: Option<Range<u32>>,
64    /// The line of the file of each line of the expected text.
65    pub lines: Vec<u32>,
66}
67
68/// A `Reading` is what sokf takes from same-same's answer for a pair.
69#[derive(Debug, Clone, Default, PartialEq, Eq)]
70struct Reading {
71    /// Whether the block is current.
72    current: bool,
73    /// The first line of the included file that differs, for a stale
74    /// include of a file where same-same gives it.
75    line: Option<usize>,
76    /// The warning that the formatter failed on the pair or didn't start.
77    warning: Option<Finding>,
78    /// Whether the formatter left the pair unsettled, so that the next run
79    /// compares it again.
80    unsettled: bool,
81}
82
83/// A `Layout` records what same-same answered for each pair that a pass
84/// settled, and the files that hold a pair that the formatter left
85/// unsettled.
86#[derive(Debug, Clone, Default)]
87pub struct Layout {
88    /// The reading of each pair.
89    readings: HashMap<Pair, Reading>,
90    /// The files that hold a pair that the formatter left unsettled.
91    unsettled: BTreeSet<RepoPath>,
92}
93
94impl Layout {
95    /// `same` returns whether the pair `pair` means the same: whether its
96    /// texts are equal, or same-same finds them the same, apart from the
97    /// named things that `[format]` reads as the same (CLI-4_AC-44,
98    /// CLI-4_AC-45, CLI-4_AC-109).
99    // sokf-implements: CLI-4_AC-44
100    // sokf-implements: CLI-4_AC-45
101    // sokf-implements: CLI-4_AC-48
102    pub fn same(&self, pair: &Pair) -> bool {
103        pair.expected == pair.actual || self.readings.get(pair).is_some_and(|r| r.current)
104    }
105
106    /// `warning` returns the warning that the formatter failed on the pair
107    /// `pair` or didn't start, when it did and the pair is stale
108    /// (CLI-4_AC-49).
109    pub fn warning(&self, pair: &Pair) -> Option<Finding> {
110        self.readings.get(pair).and_then(|r| r.warning.clone())
111    }
112
113    /// `line` returns the first line of the source that differs, for a
114    /// stale pair where same-same gives it (CLI-4_AC-110).
115    pub fn line(&self, pair: &Pair) -> Option<usize> {
116        self.readings
117            .get(pair)
118            .filter(|r| !r.current)
119            .and_then(|r| r.line)
120    }
121
122    /// `unsettled` returns the files that hold a pair that the formatter
123    /// left unsettled, which the next run checks again (CACHE-2_AC-9).
124    pub fn unsettled(&self) -> &BTreeSet<RepoPath> {
125        &self.unsettled
126    }
127
128    /// `holds` returns whether the layout has a reading of the pair.
129    pub(crate) fn holds(&self, pair: &Pair) -> bool {
130        self.readings.contains_key(pair)
131    }
132
133    /// `extend` adds what `other` records to this layout.
134    pub fn extend(&mut self, other: Layout) {
135        self.readings.extend(other.readings);
136        self.unsettled.extend(other.unsettled);
137    }
138
139    /// `insert` records the reading of a pair.
140    fn insert(&mut self, pair: Pair, reading: Reading) {
141        if reading.unsettled {
142            self.unsettled.insert(pair.path.clone());
143        }
144        self.readings.insert(pair, reading);
145    }
146}
147
148/// `stale_message` returns the message of a stale include block whose
149/// target is written as `written`, with the first line of its source that
150/// differs, where same-same gives it (CLI-4_AC-110).
151pub fn stale_message(written: &str, source: Option<&RepoPath>, line: Option<usize>) -> String {
152    match (source, line) {
153        (Some(source), Some(line)) => {
154            format!("`sokf:include {written}` is stale: `{source}` differs from line {line}")
155        }
156        _ => format!("`sokf:include {written}` is stale"),
157    }
158}
159
160#[cfg(test)]
161mod tests;