Cotton code
196 lines · 9.1 KB · SwiftRaw
// No screen says its own name twice.//// 4l's walk found eight screens drawing the SAME sentence in the `ScreenBar`// and again, a few points below it, as a `.pageTitle` — "Devices" over// "Devices", "Activity" over "Activity". Both were visible at rest, because// `ScreenBar` is a pinned overlay and not a collapsing large title, so the// word simply appeared twice on first paint.//// The app has always had BOTH shapes and they are both right on their own:// a bar title for a screen whose content starts straight in (Todos, the Bin,// Money), and a bare back circle over a big page heading for a screen that// opens with one (`SettingsScreen`,// `PeopleImportSheet`). What is never right is both at once with the same// words in them.//// A SWEEP rather than a list, per the rule the other guards in this directory// keep: a list is green on the day a ninth screen does it.import Foundationimport XCTestfinal class ScreenTitleGuardTests: XCTestCase {    // Matched by EXPRESSION **or by LITERAL**, never by `CottonStrings.` name.    // The first cut of this guard keyed on `CottonStrings.<name>` and went quiet    // on the worst instance of the bug in the app: `WorkNotYet` (gone since 2026-09-14) passed one    // `title` property to `ScreenBar(title:)` AND to `QuietState(title:)`, so    // every stub route it answers said its name twice — eight screens' worth of    // the bug in one shared component, and the sweep could not see it because    // neither call spelled a `CottonStrings` constant.    //    // Since I4 a title is usually a LITERAL — `ScreenBar(title: "Todos")` — so    // the old note here ("a call taking a literal matches nothing, which is    // correct") had become the same quiet failure one rewrite later: every    // inlined screen would have been invisible to it. Both shapes are matched    // now, and held to the one rule, because a screen that says "Todos" twice    // and a screen that says `CottonStrings.todos` twice are one bug. TWO    // DIFFERENT literals are still not this bug: the comparison is on the token    // as written, and a literal is carried WITH its quotes so it can never    // equal an identifier of the same spelling.    private static let expression = #"[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*"#    /// A single-line Swift literal, quotes included — interpolation and all,    /// since the same interpolated sentence drawn twice is the same defect.    private static let literal = #""(?:[^"\\]|\\.)*""#    /// What a title may be. ONE capture group, so `names(of:in:)` reads group 1    /// whichever side matched.    private static var title: String { "(" + literal + "|" + expression + ")" }    /// `ScreenBar(title: <title>` — the name in the bar.    private static var barTitle: String { #"ScreenBar\(\s*title:\s*"# + title }    /// The same name as a HEADING, in either of the two shapes the app draws    /// one in: `Text(<expr>).cottonType(.pageTitle)` and `QuietState(title:)`,    /// whose own first line is `Text(title).cottonType(.screenTitle)`.    private static var pageTitle: String {        // `\s*` and NOT `\s*\n\s*`: the first cut demanded a line break        // between the two, and `LegalDocument` writes        // `Text(title).cottonType(.pageTitle)` on ONE line — so Privacy and        // Terms drew "Privacy" over "Privacy" with the sweep green. A guard        // that only sees one of two formattings is a guard for a formatter.        #"Text\("# + title + #"\)\s*\.cottonType\(\.pageTitle"#    }    private static var quietTitle: String { #"QuietState\(\s*title:\s*"# + title }    /// Nothing here, and nothing is expected to arrive.    ///    /// An entry would have to say why THAT screen wants its name read twice —    /// which is a design question, not an exemption. It exists so that if the    /// answer is ever yes, the yes is written down where the sweep is.    private static let allowed: Set<String> = []    func testNoScreenDrawsOneNameInTheBarAndAgainAsItsPageTitle() throws {        var offenders: [String] = []        for source in try AppSources.all() {            // Per DECLARATION, not per file. One file routinely holds two            // views that share one string — a screen whose bar carries the            // name, and a sibling whose `QuietState` draws it. Intersecting            // the whole file calls that a double header, which it is not, and            // a false name in a guard is how a guard gets an allow-list entry            // it did not deserve.            for declaration in ScreenTitleGuardTests.declarations(in: source.text) {                for name in ScreenTitleGuardTests.doubled(in: declaration)                where !Self.allowed.contains("\(source.name):\(name)") {                    offenders.append("\(source.name) draws \(name) twice")                }            }        }        XCTAssertEqual(            offenders, [],            """            A screen may carry its name in the bar, OR open with it as a page \            title — never both, because `ScreenBar` is pinned and does not \            collapse, so the word is on screen twice at rest. Drop the bar's \            title (`ScreenBar(onBack:)`) and keep the heading, or drop the \            heading and keep the bar.            """        )    }    /// The titles ONE declaration draws in the bar and again as a heading.    ///    /// Sorted, so a failure reads the same on two runs.    static func doubled(in declaration: String) -> [String] {        let bars = Set(names(of: barTitle, in: declaration))        var titles = Set(names(of: pageTitle, in: declaration))        titles.formUnion(names(of: quietTitle, in: declaration))        return bars.intersection(titles).sorted()    }    /// One file, cut into its top-level type declarations.    ///    /// A `struct`/`class`/`extension` at column zero starts a new one; anything    /// before the first is the file's header and imports, which declare no    /// views. Crude on purpose: the alternative is a Swift parser, and what    /// this needs is only "are these two calls in the same view".    private static func declarations(in text: String) -> [String] {        var out: [String] = []        var current = ""        for line in text.split(separator: "\n", omittingEmptySubsequences: false) {            let starts =                ["struct ", "final class ", "class ", "extension ", "public struct ",                 "public final class ", "public class ", "public extension "]                .contains { line.hasPrefix($0) }            if starts {                if !current.isEmpty { out.append(current) }                current = String(line)            } else {                current += "\n" + line            }        }        if !current.isEmpty { out.append(current) }        return out    }    /// Both shapes of the bug, over source written here rather than read off    /// the disk — so the matchers are proved by a case that cannot go green by    /// the app happening to be clean, and the literal form is proved at all    /// (the sweep above finds nothing today and would pass with the literal    /// matcher deleted).    func testAnExpressionTitleAndALiteralTitleAreBothCaught() {        let expressionForm = """        struct DevicesScreen: View {            var body: some View {                ScreenBar(title: CottonStrings.devices)                QuietState(title: CottonStrings.devices)            }        }        """        XCTAssertEqual(            ScreenTitleGuardTests.doubled(in: expressionForm), ["CottonStrings.devices"]        )        let literalForm = """        struct TodosScreen: View {            var body: some View {                ScreenBar(title: "Todos")                Text("Todos").cottonType(.pageTitle)            }        }        """        XCTAssertEqual(ScreenTitleGuardTests.doubled(in: literalForm), ["\"Todos\""])        let twoDifferentWords = """        struct FineScreen: View {            var body: some View {                ScreenBar(title: "Todos")                Text("Everything you owe today").cottonType(.pageTitle)            }        }        """        XCTAssertEqual(            ScreenTitleGuardTests.doubled(in: twoDifferentWords), [],            "two different sentences are not this bug"        )        let literalAndIdentifier = """        struct AlsoFine: View {            var body: some View {                ScreenBar(title: "Todos")                QuietState(title: Todos)            }        }        """        XCTAssertEqual(            ScreenTitleGuardTests.doubled(in: literalAndIdentifier), [],            "a literal carries its quotes, so it never equals an identifier spelled the same"        )    }    private static func names(of pattern: String, in text: String) -> [String] {        guard let regex = try? NSRegularExpression(pattern: pattern) else { return [] }        let whole = NSRange(text.startIndex..<text.endIndex, in: text)        return regex.matches(in: text, range: whole).compactMap { match in            guard let range = Range(match.range(at: 1), in: text) else { return nil }            return String(text[range])        }    }}