diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e95cd58 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +.build/ +build/ +.swiftpm/ +screenshots/* +!screenshots/.gitignore diff --git a/Package.resolved b/Package.resolved new file mode 100644 index 0000000..b6dd7f9 --- /dev/null +++ b/Package.resolved @@ -0,0 +1,24 @@ +{ + "originHash" : "f18733abbc475ad9967fc14270c950518a6b14bcf4ea7cfaa6cd11f7916bc628", + "pins" : [ + { + "identity" : "swift-argument-parser", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-argument-parser", + "state" : { + "revision" : "6a52f3251125d74daf04fcbd5e6f08a75d074382", + "version" : "1.8.2" + } + }, + { + "identity" : "swiftterm", + "kind" : "remoteSourceControl", + "location" : "https://github.com/migueldeicaza/SwiftTerm", + "state" : { + "revision" : "5d14406844143538cd8f8851d2d8a67c1fe443e5", + "version" : "1.20.0" + } + } + ], + "version" : 3 +} diff --git a/Package.swift b/Package.swift new file mode 100644 index 0000000..1019ff6 --- /dev/null +++ b/Package.swift @@ -0,0 +1,42 @@ +// swift-tools-version: 6.0 +import PackageDescription + +let package = Package( + name: "Helder", + platforms: [.macOS(.v14)], + products: [ + .executable(name: "Helder", targets: ["Helder"]), + ], + dependencies: [ + .package(url: "https://github.com/migueldeicaza/SwiftTerm", from: "1.9.0"), + ], + targets: [ + .target( + name: "HelderCore", + swiftSettings: [.swiftLanguageMode(.v6)] + ), + .target( + name: "HelderServices", + dependencies: ["HelderCore"], + swiftSettings: [.swiftLanguageMode(.v5)] + ), + .target( + name: "HelderUI", + dependencies: [ + "HelderCore", + "HelderServices", + .product(name: "SwiftTerm", package: "SwiftTerm"), + ], + resources: [.copy("Resources/Fonts")], + swiftSettings: [.swiftLanguageMode(.v5)] + ), + .executableTarget( + name: "Helder", + dependencies: ["HelderUI"], + swiftSettings: [.swiftLanguageMode(.v5)] + ), + .testTarget(name: "HelderCoreTests", dependencies: ["HelderCore"]), + .testTarget(name: "HelderServicesTests", dependencies: ["HelderServices"]), + .testTarget(name: "HelderUITests", dependencies: ["HelderUI"]), + ] +) diff --git a/README.md b/README.md index 847342f..ee4f53b 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ -# Claude Storm. +# Helder. -Claude Storm is the dark workbench for reviewing the code Claude Code writes: a native macOS rewrite (Swift, SwiftUI and AppKit) of the Electron app in `old-app/`, which was called Helder. That original stays the behavioural and visual reference; see [docs/architecture.md](docs/architecture.md). +Helder is the dark workbench for reviewing the code Claude Code writes: a native macOS app in Swift, SwiftUI and AppKit. See [docs/index.md](docs/index.md) for the architecture, the design tokens and the behaviour spec. ## Build, test, run @@ -8,10 +8,10 @@ Claude Storm is the dark workbench for reviewing the code Claude Code writes: a scripts/build.sh # debug build (--release for release) scripts/test.sh # all three test targets; e.g. --filter WorkspaceModel scripts/run.sh [project] # build and run; the optional folder opens in the first window -scripts/bundle.sh # "build/Claude Storm.app", ad-hoc signed, with ripgrep inside (--install copies it to ~/Applications) +scripts/bundle.sh # "build/Helder.app", ad-hoc signed, with ripgrep inside (--install copies it to ~/Applications) ``` -Always use the scripts: they select the toolchain this machine needs. Search uses ripgrep when it can find one (`Contents/Helpers/rg` in the bundle, or `$RG_BINARY`) and a slower Swift walk otherwise. +Always use the scripts: they select the toolchain this machine needs. Search uses ripgrep when it can find one (`Contents/Helpers/rg` in the bundle, copied from `vendor/ripgrep/rg`, or `$RG_BINARY`) and a slower Swift walk otherwise. ## What it does @@ -53,7 +53,7 @@ Closing a window, switching project or quitting (⌘Q) first asks about every un ## Testing -Three test targets mirror the three library targets: `Tests/ClaudeStormCoreTests`, `Tests/ClaudeStormServicesTests` and `Tests/ClaudeStormUITests`. Inside each target, the folders mirror `Sources//` (a test for `Sources/ClaudeStormUI/State/EditorStore.swift` sits in `Tests/ClaudeStormUITests/State/`). +Three test targets mirror the three library targets: `Tests/HelderCoreTests`, `Tests/HelderServicesTests` and `Tests/HelderUITests`. Inside each target, the folders mirror `Sources//` (a test for `Sources/HelderUI/State/EditorStore.swift` sits in `Tests/HelderUITests/State/`). The tests use Swift Testing. For a PHPUnit reader: @@ -66,8 +66,8 @@ The tests use Swift Testing. For a PHPUnit reader: | `@dataProvider` | `@Test(arguments: [...]) func x(_ value: …)` | | `setUp()` | the suite's `init()`, or a helper that builds the fixture | -- **Fakes and harnesses** live in `Tests/ClaudeStormUITests/Support/`: one fake per service protocol in `Fakes/` (`FakeGit`, `FakeFiles`, `FakeSystem`, `FakeTerminal`, …), and `WorkspaceHarness`, which wires a whole window to those fakes. UI tests never touch the disk, git, the user's defaults or the log. -- **Integration tests** in `ClaudeStormServicesTests` run the real `git` and file system. `TempGitRepo` creates a throwaway repository (`commit`, `write`, `run`); `TempDirectory` a throwaway folder. +- **Fakes and harnesses** live in `Tests/HelderUITests/Support/`: one fake per service protocol in `Fakes/` (`FakeGit`, `FakeFiles`, `FakeSystem`, `FakeTerminal`, …), and `WorkspaceHarness`, which wires a whole window to those fakes. UI tests never touch the disk, git, the user's defaults or the log. +- **Integration tests** in `HelderServicesTests` run the real `git` and file system. `TempGitRepo` creates a throwaway repository (`commit`, `write`, `run`); `TempDirectory` a throwaway folder. - **Waiting**: `await model.settle()` or `eventually { … }`, never a sleep. ```bash diff --git a/Sources/Helder/HelderApp.swift b/Sources/Helder/HelderApp.swift new file mode 100644 index 0000000..96171b4 --- /dev/null +++ b/Sources/Helder/HelderApp.swift @@ -0,0 +1,11 @@ +import HelderUI +import SwiftUI + +@main +struct HelderApp: App { + @NSApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate + + var body: some Scene { + HelderScene() + } +} diff --git a/Sources/HelderCore/Agent/AgentReference.swift b/Sources/HelderCore/Agent/AgentReference.swift new file mode 100644 index 0000000..95e0e11 --- /dev/null +++ b/Sources/HelderCore/Agent/AgentReference.swift @@ -0,0 +1,57 @@ +import Foundation + +/// A pointer at code the agent understands: `path`, `path:42` or `path:42-58`. +public struct AgentReference: Sendable, Equatable, CustomStringConvertible { + public var path: String + /// First line, 1-based; nil for a whole-file (or folder) reference. + public var startLine: Int? + /// Last line; equal to `startLine` for a single line. + public var endLine: Int? + + public init(path: String, startLine: Int? = nil, endLine: Int? = nil) { + self.path = path + self.startLine = startLine + self.endLine = endLine ?? startLine + } + + /// A reference to a line range. + public init(path: String, lines: ClosedRange) { + self.init(path: path, startLine: lines.lowerBound, endLine: lines.upperBound) + } + + public var description: String { + guard let start = startLine else { return path } + guard let end = endLine, end != start else { return "\(path):\(start)" } + return "\(path):\(start)-\(end)" + } +} + +public enum PassOn { + /// The exact text a "Pass on …" action inserts into the agent. + /// + /// With code: `note ref` then the code in a fenced block. Without: `note => ref`, + /// or just `ref` when the note is empty. + public static func compose(note: String, reference: String, code: String? = nil) -> String { + let n = note.trimmingCharacters(in: .whitespacesAndNewlines) + if let code { + let head = (n.isEmpty ? "" : n + " ") + reference + return head + "\n```\n" + code + "\n```" + } + return n.isEmpty ? reference : "\(n) => \(reference)" + } +} + +public enum BracketedPaste { + public static let start = "\u{1b}[200~" + public static let end = "\u{1b}[201~" + + /// Wraps text so the CLI treats it as pasted and does not submit it. + /// + /// ESC and the 8-bit CSI are stripped from the payload: a file or note holding `ESC[201~` + /// would otherwise end the paste early and let the rest run as typed input. + public static func wrap(_ text: String, composerHasText: Bool) -> String { + var payload = String.UnicodeScalarView() + payload.append(contentsOf: text.unicodeScalars.lazy.filter { $0 != "\u{1b}" && $0 != "\u{9b}" }) + return start + (composerHasText ? "\n" : "") + String(payload) + end + } +} diff --git a/Sources/HelderCore/Agent/TerminalLaunch.swift b/Sources/HelderCore/Agent/TerminalLaunch.swift new file mode 100644 index 0000000..dd98c0b --- /dev/null +++ b/Sources/HelderCore/Agent/TerminalLaunch.swift @@ -0,0 +1,45 @@ +import Foundation + +public enum TerminalKind: String, Sendable, Equatable, CaseIterable { + /// The top pane: a shell that runs the `claude` CLI. + case agent + /// The bottom pane: a plain login shell. + case shell +} + +/// Executable, arguments and environment for one terminal pane. +public struct TerminalLaunch: Sendable, Equatable { + public var executable: String + public var arguments: [String] + public var environment: [String: String] + public var workingDirectory: String + + public init(executable: String, arguments: [String], environment: [String: String], workingDirectory: String) { + self.executable = executable + self.arguments = arguments + self.environment = environment + self.workingDirectory = workingDirectory + } + + /// The launch for a pane. The agent runs as `$SHELL -i -c `: `-i` still sources the rc + /// files (nvm etc.) but leaves no prompt line or echoed command behind. + public static func make(kind: TerminalKind, config: HelderConfig, projectRoot: String?, environment base: [String: String]) -> TerminalLaunch { + let shell = config.terminal.shell ?? base["SHELL"] ?? "/bin/zsh" + let args = kind == .agent && config.ai.autoLaunch ? ["-i", "-c", config.ai.command] : [] + let cwd = projectRoot ?? base["HOME"] ?? "/" + return TerminalLaunch(executable: shell, arguments: args, environment: environment(from: base), workingDirectory: cwd) + } + + /// The child environment. A GUI launch inherits no locale and no COLORTERM, which turns + /// multibyte output into mojibake and shifts the CLI's 24-bit colours; npm's prefix + /// variables make nvm refuse to load. + public static func environment(from base: [String: String]) -> [String: String] { + var env = base + env["npm_config_prefix"] = nil + env["npm_config_globalconfig"] = nil + if env["LC_ALL"] == nil && env["LC_CTYPE"] == nil && env["LANG"] == nil { env["LANG"] = "en_US.UTF-8" } + if env["COLORTERM"] == nil { env["COLORTERM"] = "truecolor" } + env["TERM"] = "xterm-256color" + return env + } +} diff --git a/Sources/HelderCore/Config/ConfigResolution.swift b/Sources/HelderCore/Config/ConfigResolution.swift new file mode 100644 index 0000000..3004ba1 --- /dev/null +++ b/Sources/HelderCore/Config/ConfigResolution.swift @@ -0,0 +1,25 @@ +import Foundation + +extension HelderConfig { + /// Folder in the project root that holds Helder's per-project state. + public static let folderName = ".helder" + public static let overridesFileName = "config.json" + public static let defaultsFileName = "config.default.json" + /// The whole `.helder` folder is machine-local state, so it ignores itself. + public static let gitignoreBody = "# Helder — local, machine-specific state (do not commit).\n*\n" + + /// The effective config for a sparse `config.json`; nil, empty or invalid JSON yields the defaults. + public static func resolved(overrides data: Data?) -> HelderConfig { + guard let data, !data.isEmpty else { return .defaults } + return (try? JSONDecoder().decode(HelderConfig.self, from: data)) ?? .defaults + } + + /// Pretty JSON of every default, rewritten to `config.default.json` on each launch as documentation. + public static func defaultsJSON() -> Data { + let encoder = JSONEncoder() + encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes] + var data = (try? encoder.encode(HelderConfig.defaults)) ?? Data() + data.append(0x0A) + return data + } +} diff --git a/Sources/HelderCore/Config/HelderConfig.swift b/Sources/HelderCore/Config/HelderConfig.swift new file mode 100644 index 0000000..37e0164 --- /dev/null +++ b/Sources/HelderCore/Config/HelderConfig.swift @@ -0,0 +1,291 @@ +import Foundation + +/// The view a changed file opens in. Raw values are what config files on disk hold; +/// an unknown value, such as an older config's "original", falls back to `.updated`. +public enum DefaultDiffMode: String, Codable, Sendable, CaseIterable { + case updated + case diff +} + +/// Soft wrap of long lines: never, always, or only in Markdown files. +public enum WordWrap: String, Codable, Sendable, CaseIterable { + case off + case on + case markdown +} + +public enum TerminalCursorStyle: String, Codable, Sendable, CaseIterable { + case bar + case block + case underline +} + +/// The terminal colour table. Every value is a CSS colour string; only the selection entries may carry alpha. +public struct TerminalTheme: Codable, Sendable, Equatable { + public var background = "#101720" + public var foreground = "#E4E7E6" + public var cursor = "#E8913A" + public var cursorAccent = "#101720" + public var selectionBackground = "rgba(232,145,58,0.22)" + public var selectionInactiveBackground = "rgba(232,145,58,0.12)" + public var black = "#232C39" + public var red = "#C4741F" + public var green = "#8FBFB4" + public var yellow = "#F0B476" + public var blue = "#8FA9C4" + public var magenta = "#C3A6CE" + public var cyan = "#8FC4C4" + public var white = "#BAC0C0" + public var brightBlack = "#6C7783" + public var brightRed = "#E8913A" + public var brightGreen = "#A6D2C7" + public var brightYellow = "#F5C79A" + public var brightBlue = "#A9BFD6" + public var brightMagenta = "#D6BFDF" + public var brightCyan = "#A9D6D6" + public var brightWhite = "#F4F5F4" + + public init() {} + + /// The sixteen ANSI colours in SGR order (black … brightWhite). + public var ansi: [String] { + [black, red, green, yellow, blue, magenta, cyan, white, + brightBlack, brightRed, brightGreen, brightYellow, brightBlue, brightMagenta, brightCyan, brightWhite] + } +} + +/// Effective project settings: `.helder/config.json` merged key by key over these defaults. +public struct HelderConfig: Codable, Sendable, Equatable { + public struct AI: Codable, Sendable, Equatable { + public var command = "claude" + public var autoLaunch = true + public init() {} + } + + public struct Editor: Codable, Sendable, Equatable { + public var autoSave = false + public var tabSize = 4 + public var wordWrap = WordWrap.markdown + public init() {} + } + + public struct Git: Codable, Sendable, Equatable { + public var confirmDiscard = true + public var confirmStage = false + public var confirmUnstage = false + public var defaultDiffMode = DefaultDiffMode.updated + /// Milliseconds between git status polls; 0 disables the poll. + public var refreshInterval = 10_000 + public init() {} + } + + public struct Files: Codable, Sendable, Equatable { + /// Extra ripgrep globs to leave out of the tree and the search. + public var exclude: [String] = [] + /// False on purpose: the tree and the search show git-ignored files such as `.env` unless a project opts in. + public var followGitignore = false + public init() {} + } + + public struct Terminal: Codable, Sendable, Equatable { + /// Login shell for both panes; nil means `$SHELL`. + public var shell: String? + /// nil means the bundled IBM Plex Mono. + public var fontFamily: String? + /// nil means the Typography default for terminals. + public var fontSize: Double? + public var lineHeight = 1.7 + public var letterSpacing = 0.0 + public var cursorStyle = TerminalCursorStyle.bar + public var cursorBlink = true + /// Off keeps bold text in its own hue, so a CLI's bold labels do not wash out. + public var boldIsBright = false + public var scrollback = 8000 + /// Needed for a CLI's ⌥↵ binding, but it stops Option from typing accents, hence off. + public var optionIsMeta = false + public var theme = TerminalTheme() + public init() {} + } + + public struct Session: Codable, Sendable, Equatable { + public var restoreOnLaunch = true + public init() {} + } + + public var ai = AI() + public var editor = Editor() + public var git = Git() + public var files = Files() + public var terminal = Terminal() + public var session = Session() + + public init() {} + + public static let defaults = HelderConfig() +} + +// MARK: - Tolerant decoding +// +// A key that is missing, null or of the wrong type keeps its default, so a +// sparse or half-broken config.json never throws the whole file away. + +extension KeyedDecodingContainer { + fileprivate func value(_ key: Key, _ fallback: T) -> T { + (try? decodeIfPresent(T.self, forKey: key)) ?? fallback + } + + /// For optional settings, where an explicit `null` means "use the default behaviour". + fileprivate func optional(_ key: Key, _ fallback: T?) -> T? { + guard contains(key) else { return fallback } + if (try? decodeNil(forKey: key)) == true { return nil } + return (try? decode(T.self, forKey: key)) ?? fallback + } +} + +extension HelderConfig { + private enum CodingKeys: String, CodingKey { case ai, editor, git, files, terminal, session } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + let d = HelderConfig.defaults + ai = c.value(.ai, d.ai) + editor = c.value(.editor, d.editor) + git = c.value(.git, d.git) + files = c.value(.files, d.files) + terminal = c.value(.terminal, d.terminal) + session = c.value(.session, d.session) + } +} + +extension HelderConfig.AI { + private enum CodingKeys: String, CodingKey { case command, autoLaunch } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + let d = Self() + command = c.value(.command, d.command) + autoLaunch = c.value(.autoLaunch, d.autoLaunch) + } +} + +extension HelderConfig.Editor { + private enum CodingKeys: String, CodingKey { case autoSave, tabSize, wordWrap } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + let d = Self() + autoSave = c.value(.autoSave, d.autoSave) + tabSize = c.value(.tabSize, d.tabSize) + wordWrap = c.value(.wordWrap, d.wordWrap) + } +} + +extension HelderConfig.Git { + private enum CodingKeys: String, CodingKey { + case confirmDiscard, confirmStage, confirmUnstage, defaultDiffMode, refreshInterval + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + let d = Self() + confirmDiscard = c.value(.confirmDiscard, d.confirmDiscard) + confirmStage = c.value(.confirmStage, d.confirmStage) + confirmUnstage = c.value(.confirmUnstage, d.confirmUnstage) + defaultDiffMode = c.value(.defaultDiffMode, d.defaultDiffMode) + refreshInterval = c.value(.refreshInterval, d.refreshInterval) + } +} + +extension HelderConfig.Files { + private enum CodingKeys: String, CodingKey { case exclude, followGitignore } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + let d = Self() + exclude = c.value(.exclude, d.exclude) + followGitignore = c.value(.followGitignore, d.followGitignore) + } +} + +extension HelderConfig.Terminal { + private enum CodingKeys: String, CodingKey { + case shell, fontFamily, fontSize, lineHeight, letterSpacing, cursorStyle + case cursorBlink, boldIsBright, scrollback, optionIsMeta, theme + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + let d = Self() + shell = c.optional(.shell, d.shell) + fontFamily = c.optional(.fontFamily, d.fontFamily) + fontSize = c.optional(.fontSize, d.fontSize) + lineHeight = c.value(.lineHeight, d.lineHeight) + letterSpacing = c.value(.letterSpacing, d.letterSpacing) + cursorStyle = c.value(.cursorStyle, d.cursorStyle) + cursorBlink = c.value(.cursorBlink, d.cursorBlink) + boldIsBright = c.value(.boldIsBright, d.boldIsBright) + scrollback = c.value(.scrollback, d.scrollback) + optionIsMeta = c.value(.optionIsMeta, d.optionIsMeta) + theme = c.value(.theme, d.theme) + } + + /// Writes explicit nulls, because config.default.json documents every key. + public func encode(to encoder: Encoder) throws { + var c = encoder.container(keyedBy: CodingKeys.self) + try c.encode(shell, forKey: .shell) + try c.encode(fontFamily, forKey: .fontFamily) + try c.encode(fontSize, forKey: .fontSize) + try c.encode(lineHeight, forKey: .lineHeight) + try c.encode(letterSpacing, forKey: .letterSpacing) + try c.encode(cursorStyle, forKey: .cursorStyle) + try c.encode(cursorBlink, forKey: .cursorBlink) + try c.encode(boldIsBright, forKey: .boldIsBright) + try c.encode(scrollback, forKey: .scrollback) + try c.encode(optionIsMeta, forKey: .optionIsMeta) + try c.encode(theme, forKey: .theme) + } +} + +extension HelderConfig.Session { + private enum CodingKeys: String, CodingKey { case restoreOnLaunch } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + restoreOnLaunch = c.value(.restoreOnLaunch, Self().restoreOnLaunch) + } +} + +extension TerminalTheme { + private enum CodingKeys: String, CodingKey { + case background, foreground, cursor, cursorAccent, selectionBackground, selectionInactiveBackground + case black, red, green, yellow, blue, magenta, cyan, white + case brightBlack, brightRed, brightGreen, brightYellow, brightBlue, brightMagenta, brightCyan, brightWhite + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + let d = Self() + background = c.value(.background, d.background) + foreground = c.value(.foreground, d.foreground) + cursor = c.value(.cursor, d.cursor) + cursorAccent = c.value(.cursorAccent, d.cursorAccent) + selectionBackground = c.value(.selectionBackground, d.selectionBackground) + selectionInactiveBackground = c.value(.selectionInactiveBackground, d.selectionInactiveBackground) + black = c.value(.black, d.black) + red = c.value(.red, d.red) + green = c.value(.green, d.green) + yellow = c.value(.yellow, d.yellow) + blue = c.value(.blue, d.blue) + magenta = c.value(.magenta, d.magenta) + cyan = c.value(.cyan, d.cyan) + white = c.value(.white, d.white) + brightBlack = c.value(.brightBlack, d.brightBlack) + brightRed = c.value(.brightRed, d.brightRed) + brightGreen = c.value(.brightGreen, d.brightGreen) + brightYellow = c.value(.brightYellow, d.brightYellow) + brightBlue = c.value(.brightBlue, d.brightBlue) + brightMagenta = c.value(.brightMagenta, d.brightMagenta) + brightCyan = c.value(.brightCyan, d.brightCyan) + brightWhite = c.value(.brightWhite, d.brightWhite) + } +} diff --git a/Sources/HelderCore/Config/ProjectTitle.swift b/Sources/HelderCore/Config/ProjectTitle.swift new file mode 100644 index 0000000..39f8aef --- /dev/null +++ b/Sources/HelderCore/Config/ProjectTitle.swift @@ -0,0 +1,27 @@ +import Foundation + +public enum ProjectTitle { + /// `APP_NAME` from a project's `.env` text, unquoted; nil when absent or empty. The last assignment wins. + public static func appName(fromEnv contents: String) -> String? { + var raw: String? + for line in contents.split(omittingEmptySubsequences: false, whereSeparator: \.isNewline) { + let trimmed = line.drop(while: { $0 == " " || $0 == "\t" }) + if trimmed.hasPrefix("#") { continue } + guard trimmed.hasPrefix("APP_NAME") else { continue } + let rest = trimmed.dropFirst("APP_NAME".count).drop(while: { $0 == " " || $0 == "\t" }) + guard rest.first == "=" else { continue } + raw = String(rest.dropFirst()) + } + guard var value = raw?.trimmingCharacters(in: .whitespaces) else { return nil } + if value.count >= 2, let first = value.first, first == "\"" || first == "'", value.last == first { + value = String(value.dropFirst().dropLast()) + } + value = value.trimmingCharacters(in: .whitespaces) + return value.isEmpty ? nil : value + } + + /// The title a window shows: `APP_NAME` when the project sets one, else the folder name. + public static func title(folderName: String, envContents: String?) -> String { + envContents.flatMap(appName(fromEnv:)) ?? folderName + } +} diff --git a/Sources/HelderCore/Diff/DiffModels.swift b/Sources/HelderCore/Diff/DiffModels.swift new file mode 100644 index 0000000..20bddcd --- /dev/null +++ b/Sources/HelderCore/Diff/DiffModels.swift @@ -0,0 +1,122 @@ +import Foundation + +/// One line of a unified diff: unchanged, removed or added. +public enum DiffSign: String, Sendable, Equatable { + case same = " " + case removed = "-" + case added = "+" +} + +public struct DiffRow: Sendable, Equatable { + public var sign: DiffSign + /// 1-based line number in the original; nil for an added line. + public var oldNo: Int? + /// 1-based line number in the updated text; nil for a removed line. + public var newNo: Int? + public var text: String + + public init(sign: DiffSign, oldNo: Int?, newNo: Int?, text: String) { + self.sign = sign + self.oldNo = oldNo + self.newNo = newNo + self.text = text + } +} + +public enum LineMark: String, Sendable, Equatable { + case added + case removed +} + +/// One line of one side of the diff, with its 1-based number in that side. +public struct SideLine: Sendable, Equatable { + public var no: Int + public var text: String + public var mark: LineMark? + + public init(no: Int, text: String, mark: LineMark? = nil) { + self.no = no + self.text = text + self.mark = mark + } +} + +/// A row of the side-by-side view; a nil side is the filler opposite an unpaired add or remove. +public struct SplitRow: Sendable, Equatable { + public var left: SideLine? + public var right: SideLine? + + public init(left: SideLine?, right: SideLine?) { + self.left = left + self.right = right + } +} + +/// Everything the Actual view and the Diff need, derived from one (original, updated) pair. +public struct Diff: Sendable, Equatable { + public var rows: [DiffRow] + public var left: [SideLine] + public var right: [SideLine] + public var split: [SplitRow] + public var added: Int + public var removed: Int + public var isDeletedFile: Bool + public var isAddedFile: Bool + public var original: String + public var updated: String + /// Built from a change over the diff cap: the texts are empty, not the file. + public var isTooBig = false + + public init( + rows: [DiffRow], left: [SideLine], right: [SideLine], split: [SplitRow], + added: Int, removed: Int, isDeletedFile: Bool, isAddedFile: Bool, + original: String, updated: String + ) { + self.rows = rows + self.left = left + self.right = right + self.split = split + self.added = added + self.removed = removed + self.isDeletedFile = isDeletedFile + self.isAddedFile = isAddedFile + self.original = original + self.updated = updated + } +} + +/// Which half of a file's changes a Diff shows: HEAD vs index, or index vs disk. +/// Absent (nil) means the whole file, HEAD vs disk, which Actual always shows. +public enum DiffSide: String, Codable, Sendable, Equatable { + case staged + case unstaged +} + +/// How a line is painted in the read-only editor panes. +public enum ViewLineStyle: String, Sendable, Equatable { + /// Full tint: a line the change added (Actual view). + case added +} + +/// Where a removed run's rule sits, since removed lines own no line of their own in Actual. +public enum GapEdge: String, Sendable, Equatable { + case above + case below +} + +/// A line descriptor for the editor panes. +public struct ViewLine: Sendable, Equatable { + public var no: Int? + public var text: String + public var sign: DiffSign? + public var style: ViewLineStyle? + public var gap: GapEdge? + + public init(no: Int?, text: String, sign: DiffSign? = nil, style: ViewLineStyle? = nil, gap: GapEdge? = nil) { + self.no = no + self.text = text + self.sign = sign + self.style = style + self.gap = gap + } +} diff --git a/Sources/HelderCore/Diff/DiffViews.swift b/Sources/HelderCore/Diff/DiffViews.swift new file mode 100644 index 0000000..509546b --- /dev/null +++ b/Sources/HelderCore/Diff/DiffViews.swift @@ -0,0 +1,40 @@ +import Foundation + +public enum DiffViews { + /// The Actual view: the updated file with added lines tinted. + /// + /// A run of removed lines with no added line beside it puts its rule on the edge of + /// the next surviving line (`gap: .above`), or under the last line when the run ends + /// the file (`gap: .below`). A run that also added lines gets no gap rule. + public static func actual(_ diff: Diff) -> [ViewLine] { + var above = Set() + var endsWithRemoval = false + var removed = 0, added = 0 + func flush(nextNew: Int?) { + if removed > 0 && added == 0 { + if let nextNew { above.insert(nextNew) } else { endsWithRemoval = true } + } + removed = 0 + added = 0 + } + for row in diff.rows { + switch row.sign { + case .removed: removed += 1 + case .added: added += 1 + case .same: flush(nextNew: row.newNo) + } + } + flush(nextNew: nil) + + let last = diff.right.last?.no + return diff.right.map { line in + let gap: GapEdge? = above.contains(line.no) ? .above : (endsWithRemoval && line.no == last ? .below : nil) + return ViewLine(no: line.no, text: line.text, style: line.mark == .added ? .added : nil, gap: gap) + } + } + + /// A plain file with no diff, numbered from 1. + public static func plain(_ text: String) -> [ViewLine] { + LineDiff.droppingTrailingNewline(text).components(separatedBy: "\n").enumerated().map { ViewLine(no: $0.offset + 1, text: $0.element) } + } +} diff --git a/Sources/HelderCore/Diff/LineDiff.swift b/Sources/HelderCore/Diff/LineDiff.swift new file mode 100644 index 0000000..2b29944 --- /dev/null +++ b/Sources/HelderCore/Diff/LineDiff.swift @@ -0,0 +1,205 @@ +import Foundation + +public enum LineDiff { + /// Largest LCS matrix built in one go (4M cells); bigger regions are split on unique anchor lines. + public static let maxCells = 4_000_000 + + /// "" is zero lines, and one trailing "\n" is dropped. + public static func lines(_ text: String) -> [String] { + if text.isEmpty { return [] } + return droppingTrailingNewline(text).components(separatedBy: "\n") + } + + /// Drops one final "\n". `hasSuffix("\n")` misses it after a "\r", where "\r\n" is one Character. + static func droppingTrailingNewline(_ text: String) -> String { + text.utf8.last == 10 ? String(decoding: text.utf8.dropLast(), as: UTF8.self) : text + } + + /// Line-based LCS diff of two texts into rows, both sides and aligned split rows. + /// + /// On a tie the DP takes the deletion before the addition; flipping that reorders + /// removed and added lines in every view. + public static func build(original: String, updated: String, status: GitStatus? = nil) -> Diff { + let a = lines(original) + let b = lines(updated) + let (ia, ib) = intern(a, b) + var ops: [Op] = [] + ops.reserveCapacity(max(a.count, b.count)) + region(ia, ib, 0, ia.count, 0, ib.count, &ops) + + var rows: [DiffRow] = [] + rows.reserveCapacity(ops.count) + var removedLines = Set(), addedLines = Set() + for op in ops { + switch op { + case let .same(i, j): rows.append(DiffRow(sign: .same, oldNo: i + 1, newNo: j + 1, text: a[i])) + case let .del(i): + rows.append(DiffRow(sign: .removed, oldNo: i + 1, newNo: nil, text: a[i])) + removedLines.insert(i) + case let .add(j): + rows.append(DiffRow(sign: .added, oldNo: nil, newNo: j + 1, text: b[j])) + addedLines.insert(j) + } + } + let left = a.enumerated().map { SideLine(no: $0.offset + 1, text: $0.element, mark: removedLines.contains($0.offset) ? .removed : nil) } + let right = b.enumerated().map { SideLine(no: $0.offset + 1, text: $0.element, mark: addedLines.contains($0.offset) ? .added : nil) } + + return Diff( + rows: rows, left: left, right: right, split: splitRows(ops, a, b), + added: addedLines.count, removed: removedLines.count, + isDeletedFile: status == .deleted, isAddedFile: status == .added, + original: original, updated: updated + ) + } + + private enum Op { + case same(Int, Int) + case del(Int) + case add(Int) + } + + /// Maps every distinct line to an integer so the DP compares ints, not strings. + private static func intern(_ a: [String], _ b: [String]) -> ([Int], [Int]) { + var ids: [String: Int] = [:] + func id(_ line: String) -> Int { + if let known = ids[line] { return known } + let next = ids.count + ids[line] = next + return next + } + return (a.map(id), b.map(id)) + } + + /// Removed and added runs between two unchanged lines pair up side by side. + private static func splitRows(_ ops: [Op], _ a: [String], _ b: [String]) -> [SplitRow] { + var split: [SplitRow] = [] + var removed: [SideLine] = [], added: [SideLine] = [] + func flush() { + for k in 0.. a0 && b1 > b0 && a[a1 - 1] == b[b1 - 1] { + a1 -= 1 + b1 -= 1 + tail.append(.same(a1, b1)) + } + + let n = a1 - a0, m = b1 - b0 + func replaceAll() { + for i in a0..= dp[i * width + j + 1] { + ops.append(.del(a0 + i)) + i += 1 + } else { + ops.append(.add(b0 + j)) + j += 1 + } + } + while i < n { ops.append(.del(a0 + i)); i += 1 } + while j < m { ops.append(.add(b0 + j)); j += 1 } + } + + /// Lines that appear exactly once on each side, in an order both sides share. + private static func anchors(_ a: [Int], _ b: [Int], _ a0: Int, _ a1: Int, _ b0: Int, _ b1: Int) -> [(Int, Int)] { + var countA: [Int: Int] = [:], countB: [Int: Int] = [:], atB: [Int: Int] = [:] + for i in a0.. [(Int, Int)] { + var tails: [Int] = [] + var prev = [Int](repeating: -1, count: pairs.count) + for k in pairs.indices { + let v = pairs[k].1 + var lo = 0, hi = tails.count + while lo < hi { + let mid = (lo + hi) / 2 + if pairs[tails[mid]].1 < v { lo = mid + 1 } else { hi = mid } + } + prev[k] = lo > 0 ? tails[lo - 1] : -1 + if lo == tails.count { tails.append(k) } else { tails[lo] = k } + } + var out: [(Int, Int)] = [] + var k = tails.last ?? -1 + while k >= 0 { + out.append(pairs[k]) + k = prev[k] + } + return out.reversed() + } +} diff --git a/Sources/HelderCore/Diff/ViewMode.swift b/Sources/HelderCore/Diff/ViewMode.swift new file mode 100644 index 0000000..812944b --- /dev/null +++ b/Sources/HelderCore/Diff/ViewMode.swift @@ -0,0 +1,21 @@ +import Foundation + +/// The view the editor shows for the open file. Raw values are stored in sessions, so `.actual` stays "updated". +/// +/// `.diff` is the full-screen side-by-side overlay, not a pane mode. +public enum ViewMode: String, Codable, Sendable, CaseIterable { + /// The live buffer with changed lines marked. + case actual = "updated" + case diff + /// An unchanged file: the plain editable buffer. + case code + /// Rendered Markdown. + case preview + + public init(_ mode: DefaultDiffMode) { + switch mode { + case .updated: self = .actual + case .diff: self = .diff + } + } +} diff --git a/Sources/HelderCore/Files/ContextActions.swift b/Sources/HelderCore/Files/ContextActions.swift new file mode 100644 index 0000000..f3164fc --- /dev/null +++ b/Sources/HelderCore/Files/ContextActions.swift @@ -0,0 +1,126 @@ +import Foundation + +/// What was right-clicked. +public enum ContextTarget: Sendable, Equatable { + /// A line or selection in the editor; `code` is the selected text, if any. + case editor(reference: AgentReference, code: String?) + case file(path: String) + case directory(path: String) + /// A git row; the row carries its own half, since one file can have two rows. + case gitRow(path: String, staged: Bool) + /// The empty space under the tree: the project folder itself. + case projectRoot + case terminal(TerminalKind, hasSelection: Bool) + + public var path: String { + switch self { + case let .editor(reference, _): reference.path + case let .file(path), let .directory(path), let .gitRow(path, _): path + case .projectRoot, .terminal: "" + } + } +} + +public enum ContextAction: Sendable, Equatable { + /// Opens the pass-on prompt; with code for an editor selection. + case passOnReference(String, code: String?) + case copyReference(String) + case passOnFileName(String) + case copyFileName(String) + case newFile(inDirectory: String) + case newFolder(inDirectory: String) + case stage(String) + case unstage(String) + case openDiff(String) + case discard(String) + case rename(String, isDirectory: Bool) + case revealInFinder(String) + case delete(String, isDirectory: Bool) + case copyTerminalSelection(TerminalKind) + case pasteIntoTerminal(TerminalKind) + + /// Destructive items read in amber-deep. + public var isDestructive: Bool { + switch self { + case .discard, .delete: true + default: false + } + } +} + +/// A menu entry, or a separator between groups. +public enum ContextMenuEntry: Sendable, Equatable { + case action(ContextAction, label: String) + case separator +} + +public enum ContextActions { + /// The header line of the menu: the reference, or `project/` for the root. + public static func header(for target: ContextTarget, projectName: String) -> String { + switch target { + case let .editor(reference, _): reference.description + case let .directory(path): path + "/" + case let .file(path), let .gitRow(path, _): path + case .projectRoot: projectName + "/" + case .terminal: "" + } + } + + /// Menu entries: every "Pass on …" item has its "Copy …" twin directly below. + public static func entries(for target: ContextTarget) -> [ContextMenuEntry] { + switch target { + case let .editor(reference, code): + let ref = reference.description + let hasCode = !(code ?? "").isEmpty + return [ + .action(.passOnReference(ref, code: hasCode ? code : nil), label: hasCode ? "Pass on selection" : "Pass on reference"), + .action(.copyReference(ref), label: "Copy reference"), + ] + case .projectRoot: + return [ + .action(.newFile(inDirectory: ""), label: "New file"), + .action(.revealInFinder(""), label: "Show in Finder"), + ] + case let .file(path): + return fileHead(path) + [ + .separator, + .action(.rename(path, isDirectory: false), label: "Rename file"), + .action(.revealInFinder(path), label: "Show in Finder"), + .action(.delete(path, isDirectory: false), label: "Delete file"), + ] + case let .directory(path): + let ref = path + "/" + return [ + .action(.passOnReference(ref, code: nil), label: "Pass on reference"), + .action(.copyReference(ref), label: "Copy reference"), + .separator, + .action(.newFile(inDirectory: path), label: "New file"), + .action(.newFolder(inDirectory: path), label: "New folder"), + .separator, + .action(.rename(path, isDirectory: true), label: "Rename folder"), + .action(.revealInFinder(path), label: "Show in Finder"), + .action(.delete(path, isDirectory: true), label: "Delete folder"), + ] + case let .terminal(kind, hasSelection): + return (hasSelection ? [.action(.copyTerminalSelection(kind), label: "Copy")] : []) + + [.action(.pasteIntoTerminal(kind), label: "Paste")] + case let .gitRow(path, staged): + return fileHead(path) + [ + .separator, + staged ? .action(.unstage(path), label: "Unstage changes") : .action(.stage(path), label: "Stage changes"), + .action(.openDiff(path), label: "Open diff"), + .action(.discard(path), label: "Discard changes"), + ] + } + } + + private static func fileHead(_ path: String) -> [ContextMenuEntry] { + let name = PathUtils.basename(path) + return [ + .action(.passOnReference(path, code: nil), label: "Pass on reference"), + .action(.copyReference(path), label: "Copy reference"), + .action(.passOnFileName(name), label: "Pass on file name"), + .action(.copyFileName(name), label: "Copy file name"), + ] + } +} diff --git a/Sources/HelderCore/Files/FileLimits.swift b/Sources/HelderCore/Files/FileLimits.swift new file mode 100644 index 0000000..68da6d8 --- /dev/null +++ b/Sources/HelderCore/Files/FileLimits.swift @@ -0,0 +1,202 @@ +import Foundation + +public enum FileLimits { + /// Files above this size are left out of the content index. + public static let maxIndexedFileBytes = 300_000 + public static let maxIndexedFiles = 6000 + public static let maxImageBytes = 25_000_000 + /// Git reads a file above this size as having no text, so one dump or lock file cannot stall the column. + public static let maxDiffFileBytes = 1_000_000 + /// How deep the fallback directory walk goes. + public static let maxWalkDepth = 12 + + /// A NUL byte in the first 8000 bytes marks a file as binary, like git does. + public static func looksBinary(_ data: Data) -> Bool { + data.prefix(8000).contains(0) + } + + public static let imageMimeTypes: [String: String] = [ + "png": "image/png", "jpg": "image/jpeg", "jpeg": "image/jpeg", "jfif": "image/jpeg", + "gif": "image/gif", "webp": "image/webp", "svg": "image/svg+xml", "bmp": "image/bmp", + "ico": "image/x-icon", "avif": "image/avif", "apng": "image/apng", + ] +} + +public enum IgnoreRules { + /// Folders the fallback walk and the watcher never enter. + public static let walkIgnoredNames: Set = [ + "node_modules", ".git", "out", "dist", "build", ".next", ".nuxt", + ".cache", "coverage", "vendor", ".idea", ".vscode", ".helder", ".turbo", + ] + + /// Always passed to ripgrep as `!glob`, on top of gitignore and `files.exclude`. + /// `.DS_Store` is here because `followGitignore` defaults to false (rg runs with --no-ignore). + public static let ripgrepBaseIgnore = [ + "node_modules", ".git", "out", "dist", "build", ".cache", + "vendor", "coverage", ".helder", ".next", ".nuxt", ".turbo", ".idea", ".vscode", + ".DS_Store", + ] + + /// Declarations are indexed inside `vendor/` too, so framework classes stay clickable. + public static let symbolDeclarationIgnore = ripgrepBaseIgnore.filter { $0 != "vendor" && $0 != ".DS_Store" } + /// References skip `vendor/`: nobody wants to read how a framework uses a class. + public static let symbolReferenceIgnore = ripgrepBaseIgnore.filter { $0 != ".DS_Store" } + + /// True for a name the fallback walk skips. + public static func isWalkIgnored(_ name: String) -> Bool { + walkIgnoredNames.contains(name) || name == ".DS_Store" + } + + /// True when any segment of a relative path is an ignored folder; the watcher drops such events. + public static func isWatchIgnored(_ relativePath: String) -> Bool { + relativePath.split(separator: "/").contains { walkIgnoredNames.contains(String($0)) } + } + + /// Framework caches rewritten on every request or test run; watching them refreshes the project in a loop. + public static let watchIgnoredPrefixes = [ + "storage/framework/", "bootstrap/cache/", ".phpunit.result.cache", ".phpunit.cache/", + ] + + /// `isWatchIgnored`, plus the framework caches and the project's `files.exclude` globs. + public static func isWatchIgnored(_ relativePath: String, exclude: [String]) -> Bool { + if isWatchIgnored(relativePath) { return true } + if watchIgnoredPrefixes.contains(where: { relativePath == $0 || relativePath.hasPrefix($0) || $0 == relativePath + "/" }) { + return true + } + return exclude.contains { !$0.isEmpty && globMatches($0, path: relativePath) } + } + + /// The `--glob !x` pairs plus `--no-ignore` that make ripgrep honour the project's file settings. + public static func ripgrepArguments(files: HelderConfig.Files, base: [String] = ripgrepBaseIgnore) -> [String] { + var args: [String] = [] + for glob in base { args += ["--glob", "!" + glob] } + for glob in files.exclude where !glob.isEmpty { args += ["--glob", "!" + glob] } + if !files.followGitignore { args.append("--no-ignore") } + return args + } + + /// Gitignore-style glob match of a relative path, with ripgrep's `--glob` semantics. + /// + /// A pattern without a slash matches a basename at any depth; `**` crosses folders, `*` and `?` + /// stop at a slash. A matching folder matches everything under it, as in ripgrep. + public static func globMatches(_ glob: String, path: String) -> Bool { + var pattern = Substring(glob) + while pattern.hasSuffix("/") { pattern = pattern.dropLast() } + let rooted = pattern.hasPrefix("/") + if rooted { pattern = pattern.dropFirst() } + guard !pattern.isEmpty else { return false } + let anchored = rooted || pattern.contains("/") + let candidates = PathUtils.ancestors(path) + [path] + for alternative in expandBraces(String(pattern)) { + let chars = Array(alternative) + for candidate in candidates { + let subject = Array(anchored ? candidate : PathUtils.basename(candidate)) + var matcher = WildcardMatcher(pattern: chars, subject: subject) + if matcher.matches() { return true } + } + } + return false + } + + /// `{a,b}` alternation expanded into plain patterns; nested braces expand recursively. + static func expandBraces(_ pattern: String) -> [String] { + let chars = Array(pattern) + guard let open = chars.firstIndex(of: "{") else { return [pattern] } + var depth = 0 + var parts: [String] = [] + var current = "" + for k in (open + 1).. Bool { match(0, 0) } + + private mutating func match(_ p: Int, _ s: Int) -> Bool { + let key = p * (subject.count + 1) + s + if let known = memo[key] { return known } + let result = compute(p, s) + memo[key] = result + return result + } + + private mutating func compute(_ p: Int, _ s: Int) -> Bool { + guard p < pattern.count else { return s == subject.count } + switch pattern[p] { + case "*": + if p + 1 < pattern.count && pattern[p + 1] == "*" { + let afterStars = p + 2 + if afterStars < pattern.count && pattern[afterStars] == "/" && match(afterStars + 1, s) { return true } + for k in s...subject.count where match(afterStars, k) { return true } + return false + } + var k = s + while true { + if match(p + 1, k) { return true } + if k == subject.count || subject[k] == "/" { return false } + k += 1 + } + case "?": + return s < subject.count && subject[s] != "/" && match(p + 1, s + 1) + case "[": + guard s < subject.count, subject[s] != "/", let (hit, next) = classMatch(p, subject[s]) else { + return s < subject.count && subject[s] == "[" && match(p + 1, s + 1) + } + return hit && match(next, s + 1) + case "\\" where p + 1 < pattern.count: + return s < subject.count && subject[s] == pattern[p + 1] && match(p + 2, s + 1) + default: + return s < subject.count && subject[s] == pattern[p] && match(p + 1, s + 1) + } + } + + /// Whether `c` is in the class opening at `p`, and the index after it; nil for an unclosed `[`. + private func classMatch(_ p: Int, _ c: Character) -> (Bool, Int)? { + var k = p + 1 + let negated = k < pattern.count && (pattern[k] == "!" || pattern[k] == "^") + if negated { k += 1 } + var hit = false + var first = true + while k < pattern.count { + if pattern[k] == "]" && !first { return (hit != negated, k + 1) } + first = false + if k + 2 < pattern.count && pattern[k + 1] == "-" && pattern[k + 2] != "]" { + if pattern[k] <= c && c <= pattern[k + 2] { hit = true } + k += 3 + } else { + if pattern[k] == c { hit = true } + k += 1 + } + } + return nil + } +} diff --git a/Sources/HelderCore/Files/FileNode.swift b/Sources/HelderCore/Files/FileNode.swift new file mode 100644 index 0000000..0496aea --- /dev/null +++ b/Sources/HelderCore/Files/FileNode.swift @@ -0,0 +1,125 @@ +import Foundation + +public struct FileNode: Sendable, Equatable, Identifiable { + public enum Kind: String, Sendable, Equatable { + case directory + case file + } + + public var name: String + public var kind: Kind + /// Project-relative, "/"-separated; "" is the project root. + public var path: String + /// nil for files; an empty array for an empty folder. + public var children: [FileNode]? + + public var id: String { path } + public var isDirectory: Bool { kind == .directory } + public var isHidden: Bool { name.hasPrefix(".") } + + public init(name: String, kind: Kind, path: String, children: [FileNode]? = nil) { + self.name = name + self.kind = kind + self.path = path + self.children = kind == .directory ? (children ?? []) : nil + } +} + +/// One visible row of the Explorer, in render order. +public struct TreeRow: Sendable, Equatable { + public var path: String + public var kind: FileNode.Kind + /// 0 for a top-level entry; the Explorer indents 16px per level. + public var depth: Int + + public init(path: String, kind: FileNode.Kind, depth: Int) { + self.path = path + self.kind = kind + self.depth = depth + } +} + +public enum FileTree { + /// Nested tree from relative file paths: folders first, then files, each sorted by name. + /// + /// `emptyDirs` adds the folders that hold no file, which `rg --files` never lists. + /// Names sort case-insensitively, not in byte order. + public static func build(rootName: String, paths: [String], emptyDirs: [String] = []) -> FileNode { + var folders: [String: Set] = ["": []] + var files: [String: Set] = [:] + + func ensureFolder(_ parts: ArraySlice) -> String { + var parent = "" + for part in parts { + let path = PathUtils.join(parent, String(part)) + if folders[path] == nil { + folders[path] = [] + folders[parent, default: []].insert(path) + } + parent = path + } + return parent + } + + for path in paths { + let parts = path.split(separator: "/") + guard let name = parts.last else { continue } + let parent = ensureFolder(parts.dropLast()) + files[parent, default: []].insert(PathUtils.join(parent, String(name))) + } + for dir in emptyDirs { + _ = ensureFolder(dir.split(separator: "/")[...]) + } + + func node(folder path: String, name: String) -> FileNode { + let subfolders = (folders[path] ?? []).map { node(folder: $0, name: PathUtils.basename($0)) } + let leaves = (files[path] ?? []).map { FileNode(name: PathUtils.basename($0), kind: .file, path: $0) } + return FileNode(name: name, kind: .directory, path: path, children: sortedByName(subfolders) + sortedByName(leaves)) + } + return node(folder: "", name: rootName) + } + + /// Case-insensitive, locale-aware order. + static func sortedByName(_ nodes: [FileNode]) -> [FileNode] { + nodes.sorted { $0.name.compare($1.name, locale: sortLocale) == .orderedAscending } + } + + private static let sortLocale = Locale(identifier: "en_US") + + /// The node at a relative path ("" is the root), or nil. + public static func find(_ path: String, in tree: FileNode) -> FileNode? { + if path.isEmpty { return tree } + var node = tree + for part in path.split(separator: "/") { + guard let next = node.children?.first(where: { $0.name == part }) else { return nil } + node = next + } + return node + } + + /// A copy of the tree with the children of the node at `path` replaced; unchanged when the path is absent. + public static func replacingChildren(of path: String, with children: [FileNode], in tree: FileNode) -> FileNode { + if tree.path == path { + var copy = tree + copy.children = children + return copy + } + guard let kids = tree.children, path.hasPrefix(tree.path) else { return tree } + var copy = tree + copy.children = kids.map { replacingChildren(of: path, with: children, in: $0) } + return copy + } + + /// The visible rows under the root, honouring expanded folders and the hidden-files toggle. + public static func visibleRows(_ tree: FileNode, expanded: Set, showHidden: Bool) -> [TreeRow] { + var rows: [TreeRow] = [] + func walk(_ node: FileNode, depth: Int) { + for child in node.children ?? [] where showHidden || !child.isHidden { + rows.append(TreeRow(path: child.path, kind: child.kind, depth: depth)) + if child.isDirectory && expanded.contains(child.path) { walk(child, depth: depth + 1) } + } + } + walk(tree, depth: 0) + return rows + } +} diff --git a/Sources/HelderCore/Files/FileType.swift b/Sources/HelderCore/Files/FileType.swift new file mode 100644 index 0000000..642e2b5 --- /dev/null +++ b/Sources/HelderCore/Files/FileType.swift @@ -0,0 +1,100 @@ +import Foundation + +/// A highlighter grammar. +public enum Language: String, Sendable, CaseIterable { + case php, javascript, jsx, typescript, tsx, python, markup, css, json, markdown, bash, yaml +} + +/// One of the four badge fills; the UI maps each to a Palette colour. +public enum BadgeTint: String, Sendable { + case purple + case amber + case teal + case grey +} + +/// The small extension chip in rows and headers: ink text on a tinted fill. +public struct FileBadge: Sendable, Equatable { + public var text: String + public var tint: BadgeTint + + public init(_ text: String, _ tint: BadgeTint) { + self.text = text + self.tint = tint + } +} + +public enum FileType { + /// Lowercased extension; any `.env*` file reads as `env`. + public static func ext(_ path: String) -> String { + let base = PathUtils.basename(path) + if base.hasPrefix(".env") { return "env" } + guard let dot = base.lastIndex(of: ".") else { return "" } + return base[base.index(after: dot)...].lowercased() + } + + private static let languages: [String: Language] = [ + "php": .php, "js": .javascript, "mjs": .javascript, "cjs": .javascript, + "jsx": .jsx, "ts": .typescript, "tsx": .tsx, "py": .python, + "html": .markup, "xml": .markup, "svg": .markup, "vue": .markup, + "css": .css, "scss": .css, "json": .json, "md": .markdown, + "sh": .bash, "bash": .bash, "yml": .yaml, "yaml": .yaml, "env": .bash, + ] + + public static func language(for path: String) -> Language? { + languages[ext(path)] + } + + public static func isMarkdown(_ path: String) -> Bool { + language(for: path) == .markdown + } + + private static let labels: [String: String] = [ + "php": "PHP", "js": "JavaScript", "mjs": "JavaScript", "ts": "TypeScript", + "tsx": "TypeScript", "jsx": "JavaScript", "py": "Python", "html": "HTML", + "css": "CSS", "json": "JSON", "md": "Markdown", "sh": "Shell", "env": "Dotenv", + "yml": "YAML", "yaml": "YAML", + ] + + /// The status-bar language name. + public static func languageLabel(for path: String) -> String { + let e = ext(path) + return labels[e] ?? (e.isEmpty ? "Plain Text" : e.uppercased()) + } + + public static let imageExtensions: Set = ["png", "jpg", "jpeg", "gif", "webp", "svg", "bmp", "ico", "avif", "apng", "jfif"] + + /// Files the viewer shows as a picture instead of text. + public static func isImage(_ path: String) -> Bool { + imageExtensions.contains(ext(path)) + } + + /// Files that never open: the viewer flashes "Too big." instead. + public static let tooBigNames: Set = ["composer.lock"] + + private static let badges: [String: FileBadge] = [ + "php": FileBadge("php", .purple), "blade": FileBadge("php", .purple), + "ts": FileBadge("ts", .purple), "tsx": FileBadge("tsx", .purple), "vue": FileBadge("vue", .purple), + "js": FileBadge("js", .amber), "mjs": FileBadge("js", .amber), "cjs": FileBadge("js", .amber), + "jsx": FileBadge("jsx", .amber), "json": FileBadge("json", .amber), + "yml": FileBadge("yml", .amber), "yaml": FileBadge("yml", .amber), + "css": FileBadge("css", .teal), "scss": FileBadge("scss", .teal), "pcss": FileBadge("css", .teal), + "html": FileBadge("html", .teal), "sh": FileBadge("sh", .teal), "env": FileBadge("env", .teal), + "py": FileBadge("py", .teal), "sql": FileBadge("sql", .teal), + "md": FileBadge("md", .grey), "txt": FileBadge("txt", .grey), + "lock": FileBadge("lock", .grey), "svg": FileBadge("svg", .grey), + ] + + private static let nameBadges: [String: FileBadge] = [ + "composer.json": FileBadge("json", .purple), + "package.json": FileBadge("json", .amber), + ".env": FileBadge("env", .teal), + ] + + /// The badge for a path; unknown extensions get a grey chip with up to four letters, or "·". + public static func badge(for path: String) -> FileBadge { + if let named = nameBadges[PathUtils.basename(path)] { return named } + let e = ext(path) + return badges[e] ?? FileBadge(e.isEmpty ? "·" : String(e.prefix(4)), .grey) + } +} diff --git a/Sources/HelderCore/Files/PathUtils.swift b/Sources/HelderCore/Files/PathUtils.swift new file mode 100644 index 0000000..29b8162 --- /dev/null +++ b/Sources/HelderCore/Files/PathUtils.swift @@ -0,0 +1,63 @@ +import Foundation + +public enum PathUtils { + public static func basename(_ path: String) -> String { + path.split(separator: "/").last.map(String.init) ?? "" + } + + /// Everything before the last segment; "" for a top-level entry. + public static func dirname(_ path: String) -> String { + guard let slash = path.lastIndex(of: "/") else { return "" } + return String(path[.. String { + dir.isEmpty ? name : dir + "/" + name + } + + /// Every ancestor folder of a path, outermost first: `a/b/c.txt` → [a, a/b]. + public static func ancestors(_ path: String) -> [String] { + let parts = path.split(separator: "/").map(String.init) + guard parts.count > 1 else { return [] } + return (1.. Bool { + path.split(separator: "/").contains { $0.hasPrefix(".") } + } + + /// True for `path` itself and, when it is a folder, for everything under it. + public static func isInside(_ candidate: String, _ path: String, isDirectory: Bool) -> Bool { + candidate == path || (isDirectory && candidate.hasPrefix(path + "/")) + } + + /// Carries a path over a rename of `from` to `to`; folders move everything under them. + public static func remap(_ candidate: String, from: String, to: String, isDirectory: Bool) -> String { + if candidate == from { return to } + if isDirectory && candidate.hasPrefix(from + "/") { return to + candidate.dropFirst(from.count) } + return candidate + } + + /// A cleaned basename for a rename, or nil when it is empty, has a slash, or is `.`/`..`. + public static func validatedName(_ name: String) -> String? { + var clean = name.trimmingCharacters(in: .whitespacesAndNewlines) + while clean.hasSuffix("/") { clean.removeLast() } + if clean.isEmpty || clean.contains("/") || clean == "." || clean == ".." { return nil } + return clean + } + + /// The relative path a create-in-folder action targets; leading and trailing slashes are dropped. + public static func newEntryPath(inDirectory dir: String, name: String) -> String { + var clean = Substring(name) + while clean.hasPrefix("/") { clean = clean.dropFirst() } + while clean.hasSuffix("/") { clean = clean.dropLast() } + return join(dir, String(clean)) + } + + /// A reference to a project entry: folders end in a slash. + public static func reference(_ path: String, isDirectory: Bool) -> String { + isDirectory ? path + "/" : path + } +} diff --git a/Sources/HelderCore/Git/GitDerivation.swift b/Sources/HelderCore/Git/GitDerivation.swift new file mode 100644 index 0000000..3dc3081 --- /dev/null +++ b/Sources/HelderCore/Git/GitDerivation.swift @@ -0,0 +1,93 @@ +import Foundation + +public enum GitDerivation { + /// Turns a snapshot into rows plus per-row and per-file diffs; nil means "not a repository". + /// + /// Per file, HEAD comes from the staged row's original and disk from the unstaged row's + /// updated; with one row both come from it. The unstaged row owns the file-level status, + /// so a file staged as modified but deleted on disk reads as deleted. + public static func derive(_ snapshot: GitSnapshot?) -> GitWorkingState { + guard let snapshot else { return .empty } + var state = GitWorkingState(branch: snapshot.branch, ahead: snapshot.ahead, canPush: snapshot.canPush, isRepository: true) + var wholeFile: [String: (head: String, disk: String, status: GitStatus, rows: Int, rowID: String)] = [:] + var tooBig = Set() + for change in snapshot.changes { + var diff = LineDiff.build(original: change.original, updated: change.updated, status: change.status) + diff.isTooBig = change.isTooBig + if change.isTooBig { tooBig.insert(change.path) } + let row = Change(path: change.path, status: change.status, added: diff.added, removed: diff.removed, + staged: change.staged, originalPath: change.originalPath) + state.rowDiffs[row.id] = diff + state.changes.append(row) + if change.staged { state.stagedPaths.insert(change.path) } + if let previous = wholeFile[change.path] { + wholeFile[change.path] = change.staged + ? (change.original, previous.disk, previous.status, previous.rows + 1, previous.rowID) + : (previous.head, change.updated, change.status, previous.rows + 1, previous.rowID) + } else { + wholeFile[change.path] = (change.original, change.updated, change.status, 1, row.id) + } + } + for (path, whole) in wholeFile { + var diff = whole.rows == 1 + ? state.rowDiffs[whole.rowID] + : LineDiff.build(original: whole.head, updated: whole.disk, status: whole.status) + diff?.isTooBig = tooBig.contains(path) + state.fileDiffs[path] = diff + } + return state + } +} + +/// Rows of one folder in the Source Control list. +public struct ChangeGroup: Sendable, Equatable { + /// Folder path; "" is the project root. + public var dir: String + public var rows: [Change] + + public init(dir: String, rows: [Change]) { + self.dir = dir + self.rows = rows + } +} + +public enum SourceControlText { + /// Groups rows by folder in order of first appearance; keyboard navigation walks this same order. + public static func groupByDir(_ list: [Change]) -> [ChangeGroup] { + var groups: [ChangeGroup] = [] + var indexByDir: [String: Int] = [:] + for change in list { + let dir = PathUtils.dirname(change.path) + if let index = indexByDir[dir] { + groups[index].rows.append(change) + } else { + indexByDir[dir] = groups.count + groups.append(ChangeGroup(dir: dir, rows: [change])) + } + } + return groups + } + + /// The row order of the list: staged groups first, then unstaged, each folder by folder. + public static func navigationOrder(_ changes: [Change]) -> [Change] { + let staged = groupByDir(changes.filter(\.staged)).flatMap(\.rows) + let unstaged = groupByDir(changes.filter { !$0.staged }).flatMap(\.rows) + return staged + unstaged + } + + /// Dictation tools capitalise and add line breaks; a commit subject is one lowercase line. + public static func normalizeCommitMessage(_ value: String) -> String { + value.lowercased().replacingOccurrences(of: "[ \\t]*[\\r\\n]+[ \\t]*", with: " ", options: .regularExpression) + } + + public static func pushTooltip(canPush: Bool, ahead: Int) -> String { + if !canPush { return "Nothing to push (⌘P)" } + if ahead > 0 { return "Push \(ahead) commit\(ahead > 1 ? "s" : "") to remote (⌘P)" } + return "Push the branch to remote (⌘P)" + } + + /// Git rows under `tests/` or `cypress/` render dimmed. + public static func isTestFile(_ path: String) -> Bool { + path.hasPrefix("tests/") || path.hasPrefix("cypress/") + } +} diff --git a/Sources/HelderCore/Git/GitModels.swift b/Sources/HelderCore/Git/GitModels.swift new file mode 100644 index 0000000..c8ad687 --- /dev/null +++ b/Sources/HelderCore/Git/GitModels.swift @@ -0,0 +1,140 @@ +import Foundation + +/// The status letter a git row shows. Copies and untracked files read as `A`, conflicts as `M`. +public enum GitStatus: String, Codable, Sendable, CaseIterable { + case added = "A" + case modified = "M" + case deleted = "D" + case renamed = "R" + case unmerged = "U" +} + +/// One file half as `git load` reads it: the text on each side of that half. +public struct GitFileChange: Sendable, Equatable { + public var path: String + public var status: GitStatus + /// True for the HEAD→index half, false for the index→disk half. + public var staged: Bool + public var original: String + public var updated: String + /// The source path of a rename or copy; nil otherwise. + public var originalPath: String? + /// A side was over the diff cap, so both texts are left empty. + public var isTooBig: Bool + + public init(path: String, status: GitStatus, staged: Bool, original: String, updated: String, originalPath: String? = nil, + isTooBig: Bool = false) { + self.path = path + self.status = status + self.staged = staged + self.original = original + self.updated = updated + self.originalPath = originalPath + self.isTooBig = isTooBig + } +} + +/// What one `git status` read of the working tree returns. +public struct GitSnapshot: Sendable, Equatable { + public var branch: String + /// Commits the remote does not have yet; 0 when unknown. + public var ahead: Int + /// True when a push would send something, including a branch without an upstream. + public var canPush: Bool + public var changes: [GitFileChange] + + public init(branch: String, ahead: Int, canPush: Bool, changes: [GitFileChange]) { + self.branch = branch + self.ahead = ahead + self.canPush = canPush + self.changes = changes + } +} + +/// A row in the Source Control column. A file staged and then edited again has two rows. +public struct Change: Sendable, Equatable, Identifiable { + /// Row identity; the path alone is not unique (see `staged`). + public var id: String + public var path: String + public var status: GitStatus + public var added: Int + public var removed: Int + public var isDeleted: Bool + public var staged: Bool + /// The source path of a rename or copy; nil otherwise. + public var originalPath: String? + + public init(path: String, status: GitStatus, added: Int, removed: Int, staged: Bool, originalPath: String? = nil) { + self.id = Change.rowID(path: path, staged: staged) + self.path = path + self.status = status + self.added = added + self.removed = removed + self.isDeleted = status == .deleted + self.staged = staged + self.originalPath = originalPath + } + + /// `s:path` for the staged half, `w:path` for the working-tree half. + public static func rowID(path: String, staged: Bool) -> String { + (staged ? "s:" : "w:") + path + } +} + +/// The git slice of the workspace, derived from one snapshot. +public struct GitWorkingState: Sendable, Equatable { + public var branch: String + public var ahead: Int + public var canPush: Bool + public var changes: [Change] + /// Per path: HEAD vs disk. Drives the Actual view. + public var fileDiffs: [String: Diff] + /// Per row id: that row's own pair. Drives the Diff overlay. + public var rowDiffs: [String: Diff] + /// Paths that have a staged row. + public var stagedPaths: Set + /// False when the project is not a git repository. + public var isRepository: Bool + + public init( + branch: String = "—", ahead: Int = 0, canPush: Bool = false, changes: [Change] = [], + fileDiffs: [String: Diff] = [:], rowDiffs: [String: Diff] = [:], + stagedPaths: Set = [], isRepository: Bool = false + ) { + self.branch = branch + self.ahead = ahead + self.canPush = canPush + self.changes = changes + self.fileDiffs = fileDiffs + self.rowDiffs = rowDiffs + self.stagedPaths = stagedPaths + self.isRepository = isRepository + } + + public static let empty = GitWorkingState() + + /// Whole-project line counts for the status bar. + public var totals: (added: Int, removed: Int) { + changes.reduce((0, 0)) { ($0.0 + $1.added, $0.1 + $1.removed) } + } + + public var stagedCount: Int { changes.filter(\.staged).count } + public var unstagedCount: Int { changes.count - stagedCount } + + /// Distinct paths with an unstaged row, in row order: what "stage all" sends to git. + public var unstagedPaths: [String] { + var seen = Set() + return changes.filter { !$0.staged && seen.insert($0.path).inserted }.map(\.path) + } +} + +/// The outcome of a push, shown in a toast. +public struct PushResult: Sendable, Equatable { + public var ok: Bool + public var message: String + + public init(ok: Bool, message: String) { + self.ok = ok + self.message = message + } +} diff --git a/Sources/HelderCore/Git/Porcelain.swift b/Sources/HelderCore/Git/Porcelain.swift new file mode 100644 index 0000000..8931233 --- /dev/null +++ b/Sources/HelderCore/Git/Porcelain.swift @@ -0,0 +1,146 @@ +import Foundation + +public struct StatusEntry: Sendable, Equatable { + /// The index column of the porcelain XY code (" " when clean). + public var index: Character + /// The working-tree column of the porcelain XY code. + public var working: Character + /// The destination path for renames and copies. + public var path: String + /// The source path of a rename or copy; nil otherwise. + public var originalPath: String? + + public init(index: Character, working: Character, path: String, originalPath: String? = nil) { + self.index = index + self.working = working + self.path = path + self.originalPath = originalPath + } + + /// True when the index column records a rename, whose source is gone from the index. + public var isStagedRename: Bool { index == "R" && originalPath != nil } +} + +public struct ParsedStatus: Sendable, Equatable { + public var branch: String + public var ahead: Int + public var canPush: Bool + public var entries: [StatusEntry] + + public init(branch: String, ahead: Int, canPush: Bool, entries: [StatusEntry]) { + self.branch = branch + self.ahead = ahead + self.canPush = canPush + self.entries = entries + } +} + +/// One row a porcelain entry turns into. +public struct GitRowSpec: Sendable, Equatable { + public var status: GitStatus + public var staged: Bool + + public init(status: GitStatus, staged: Bool) { + self.status = status + self.staged = staged + } +} + +public enum Porcelain { + /// The arguments `GitService.load` passes to git; `-z` keeps paths unquoted. + public static let statusArguments = ["status", "--porcelain", "-b", "--untracked-files=all", "-z"] + + /// Parses `git status --porcelain -b -z`: NUL-separated, the `## ` header first. + /// + /// For a rename or copy (R or C in either column) the next NUL field is the source + /// path, not an entry of its own. A missing header leaves the branch at "HEAD". + public static func parseStatus(_ raw: String) -> ParsedStatus { + let parts = raw.split(separator: "\0", omittingEmptySubsequences: false) + var result = ParsedStatus(branch: "HEAD", ahead: 0, canPush: false, entries: []) + var sourceFollows = false + for part in parts { + if sourceFollows { + sourceFollows = false + result.entries[result.entries.count - 1].originalPath = String(part) + continue + } + if part.isEmpty { continue } + if part.hasPrefix("## ") { + let header = String(part.dropFirst(3)) + result.branch = parseBranch(header: header) + (result.ahead, result.canPush) = parseAhead(header: header) + continue + } + let chars = Array(part.prefix(2)) + let index = chars.first ?? " " + let working = chars.count > 1 ? chars[1] : " " + let path = String(part.dropFirst(3)) + if index == "R" || index == "C" || working == "R" || working == "C" { sourceFollows = true } + result.entries.append(StatusEntry(index: index, working: working, path: path)) + } + return result + } + + /// The display branch of a header such as `main...origin/main [ahead 1]`, + /// `No commits yet on main` (→ "main") or `HEAD (no branch)` (→ "HEAD"). + public static func parseBranch(header: String) -> String { + let noCommits = "No commits yet on " + if header.hasPrefix(noCommits) { return header.dropFirst(noCommits.count).trimmingCharacters(in: .whitespaces) } + if header.hasPrefix("HEAD ") { return "HEAD" } + let head = header.range(of: "...").map { header[..<$0.lowerBound] } ?? Substring(header) + let name = head.split(separator: " ", omittingEmptySubsequences: false).first.map(String.init) ?? "" + let trimmed = name.trimmingCharacters(in: .whitespaces) + return trimmed.isEmpty ? "HEAD" : trimmed + } + + /// Push state from a header. `[ahead N]` → (N, true); no `...` upstream → (0, true), + /// because a first push still sends every commit; "No commits yet" or detached → (0, false). + public static func parseAhead(header: String) -> (ahead: Int, canPush: Bool) { + if header.hasPrefix("No commits yet on ") || header.hasPrefix("HEAD ") { return (0, false) } + if let match = header.firstMatch(of: /\[[^\]]*\bahead (\d+)/), let count = Int(match.1) { return (count, true) } + return (0, !header.contains("...")) + } + + /// Maps one porcelain column letter to the letter the row shows. + public static func status(for code: Character) -> GitStatus { + switch code { + case "A", "C", "?": .added + case "D": .deleted + case "R": .renamed + default: .modified + } + } + + /// A merge conflict. Neither half can be staged on its own, so it stays one row. + public static func isConflict(index: Character, working: Character) -> Bool { + index == "U" || working == "U" || (index == "A" && working == "A") || (index == "D" && working == "D") + } + + /// Splits an XY pair into rows: "MM" is a staged row plus an unstaged row, never one folded row. + public static func classify(index: Character, working: Character) -> [GitRowSpec] { + if isConflict(index: index, working: working) { return [GitRowSpec(status: .modified, staged: true)] } + var rows: [GitRowSpec] = [] + if index != " " && index != "?" { rows.append(GitRowSpec(status: status(for: index), staged: true)) } + if working != " " { rows.append(GitRowSpec(status: status(for: working), staged: false)) } + return rows.isEmpty ? [GitRowSpec(status: status(for: index), staged: true)] : rows + } + + /// The toast line for a push: git reports on stderr, so the summary is pulled from there. + public static func pushSummary(exitCode: Int32, stdout: String, stderr: String) -> PushResult { + let source = stderr.isEmpty ? stdout : stderr + var lines = source.split(whereSeparator: \.isNewline) + .map { $0.trimmingCharacters(in: .whitespaces) } + .filter { !$0.isEmpty } + if exitCode != 0 { return PushResult(ok: false, message: lines.popLast() ?? "push failed") } + let summary = lines.first { line in + line.contains("->") || line.localizedCaseInsensitiveContains("up-to-date") + || line.localizedCaseInsensitiveContains("new branch") + } + return PushResult(ok: true, message: summary ?? lines.popLast() ?? "Pushed") + } + + /// True when a failed `git push` only needs `-u origin `. + public static func needsUpstream(stderr: String) -> Bool { + stderr.range(of: "no upstream branch|set-upstream", options: [.regularExpression, .caseInsensitive]) != nil + } +} diff --git a/Sources/HelderCore/Highlight/CSSGrammar.swift b/Sources/HelderCore/Highlight/CSSGrammar.swift new file mode 100644 index 0000000..39e7774 --- /dev/null +++ b/Sources/HelderCore/Highlight/CSSGrammar.swift @@ -0,0 +1,155 @@ +import Foundation + +/// CSS, and SCSS too: nesting, `$vars` and `//` comments. +enum CSSGrammar { + private enum Context { + case selector, property, value + } + + private static let important = Unit.literal("important") + private static let url = Unit.literal("url(") + + static func scan(_ lx: inout Lexer, _ st: inout GrammarState) { + let lineStart = lx.i + var context: Context = st.mode == .cssValue ? .value : statementContext(lx, depth: st.depth) + if st.mode == .cssValue { st.mode = .code } + while lx.i < lx.end { + if st.mode == .blockComment { + if lx.blockComment(from: lx.i, close: Literals.blockClose) { st.mode = .code } + continue + } + if lx.stop != nil && lx.atStop() { return } + let start = lx.i + let c = lx.u[start] + if Unit.isSpace(c) { + lx.i += 1 + continue + } + switch c { + case Unit.slash where lx.peek(1) == Unit.star: + lx.i += 2 + if !lx.blockComment(from: start, close: Literals.blockClose) { st.mode = .blockComment } + case Unit.slash where lx.peek(1) == Unit.slash && (start == lineStart || Unit.isSpace(lx.unit(at: start - 1))): + lx.lineComment() + case Unit.quote, Unit.apostrophe: + lx.i += 1 + _ = lx.quoted(from: start, quote: c) + case Unit.lbrace: + lx.i += 1 + st.depth += 1 + context = statementContext(lx, depth: st.depth) + case Unit.rbrace: + lx.i += 1 + st.depth = max(0, st.depth - 1) + context = statementContext(lx, depth: st.depth) + case Unit.semicolon: + lx.i += 1 + context = statementContext(lx, depth: st.depth) + case Unit.at where Unit.isIdentStart(lx.peek(1)): + lx.i += 1 + lx.identifier { $0 == Unit.minus } + lx.emit(start, lx.i, .keyword) + context = .value + case Unit.dollar where Unit.isIdentStart(lx.peek(1)): + lx.i += 1 + lx.identifier { $0 == Unit.minus } + lx.emit(start, lx.i, .variable) + if lx.nextNonSpace() == Unit.colon { context = .value } + case Unit.bang where lx.startsIgnoringCase(with: important, at: start + 1): + lx.i += 1 + important.count + lx.emit(start, lx.i, .keyword) + default: + switch context { + case .selector: selectorPart(&lx) + case .property: + if Unit.isIdentStart(c) || c == Unit.minus { + lx.identifier { $0 == Unit.minus } + if lx.nextNonSpace() == Unit.colon { + lx.emit(start, lx.i, .variable) + lx.skipSpaces() + lx.i += 1 + context = .value + } else { + lx.emit(start, lx.i, .number) + } + } else { + selectorPart(&lx) + } + case .value: valuePart(&lx) + } + } + } + if context == .value && st.depth > 0 && st.mode == .code { st.mode = .cssValue } + } + + /// Whether what follows is a selector or a declaration: at the top level always a selector, + /// inside a block a selector only when a `{` comes before any `;` or `}` on the line. + private static func statementContext(_ lx: Lexer, depth: Int) -> Context { + if depth == 0 { return .selector } + var k = lx.i + while k < lx.end { + switch lx.u[k] { + case Unit.lbrace: return .selector + case Unit.semicolon, Unit.rbrace: return .property + default: k += 1 + } + } + return .property + } + + private static func selectorPart(_ lx: inout Lexer) { + let start = lx.i + let c = lx.u[start] + switch c { + case Unit.colon: + lx.i += 1 + if lx.peek() == Unit.colon { lx.i += 1 } + lx.identifier { $0 == Unit.minus } + lx.emit(start, lx.i, .keyword) + case Unit.amp, Unit.greater, Unit.plus, Unit.tilde: + lx.i += 1 + lx.emit(start, lx.i, .keyword) + case Unit.lbracket: + while lx.i < lx.end && lx.u[lx.i] != Unit.rbracket { lx.i += 1 } + lx.i = min(lx.i + 1, lx.end) + lx.emit(start, lx.i, .number) + case Unit.dot, Unit.hash, Unit.star, Unit.percent: + lx.i += 1 + lx.identifier { $0 == Unit.minus } + lx.emit(start, lx.i, .number) + case _ where Unit.isIdentStart(c) || c == Unit.minus: + lx.identifier { $0 == Unit.minus } + lx.emit(start, lx.i, .number) + default: + lx.i += 1 + } + } + + private static func valuePart(_ lx: inout Lexer) { + let start = lx.i + let c = lx.u[start] + if c == Unit.hash && Unit.isHexDigit(lx.peek(1)) { + lx.i += 1 + lx.identifier() + lx.emit(start, lx.i, .number) + } else if Unit.isDigit(c) || ((c == Unit.dot || c == Unit.minus || c == Unit.plus) && (Unit.isDigit(lx.peek(1)) || (lx.peek(1) == Unit.dot && Unit.isDigit(lx.peek(2))))) { + lx.i += 1 + while lx.i < lx.end && (Unit.isDigit(lx.u[lx.i]) || lx.u[lx.i] == Unit.dot) { lx.i += 1 } + if lx.peek() == Unit.percent { lx.i += 1 } else { lx.identifier() } + lx.emit(start, lx.i, .number) + } else if lx.startsIgnoringCase(with: url) { + lx.i += url.count + let body = lx.i + while lx.i < lx.end && lx.u[lx.i] != Unit.rparen { lx.i += 1 } + lx.emit(body, lx.i, .string) + } else if c == Unit.minus && lx.peek(1) == Unit.minus { + lx.identifier { $0 == Unit.minus } + lx.emit(start, lx.i, .variable) + } else if Unit.isIdentStart(c) || c == Unit.minus { + lx.identifier { $0 == Unit.minus } + if lx.peek() != Unit.lparen { lx.emit(start, lx.i, .string) } + } else { + lx.i += 1 + } + } +} diff --git a/Sources/HelderCore/Highlight/JSONGrammar.swift b/Sources/HelderCore/Highlight/JSONGrammar.swift new file mode 100644 index 0000000..cf8efd0 --- /dev/null +++ b/Sources/HelderCore/Highlight/JSONGrammar.swift @@ -0,0 +1,44 @@ +import Foundation + +/// JSON with comments allowed, since tsconfig-style files carry them. +enum JSONGrammar { + private static let literals: Set = ["true", "false", "null"] + + static func scan(_ lx: inout Lexer, _ st: inout GrammarState) { + while lx.i < lx.end { + if st.mode == .blockComment { + if lx.blockComment(from: lx.i, close: Literals.blockClose) { st.mode = .code } + continue + } + let start = lx.i + let c = lx.u[start] + switch c { + case Unit.slash where lx.peek(1) == Unit.slash: + lx.lineComment() + case Unit.slash where lx.peek(1) == Unit.star: + lx.i += 2 + if !lx.blockComment(from: start, close: Literals.blockClose) { st.mode = .blockComment } + case Unit.quote: + lx.i += 1 + var closed = false + while lx.i < lx.end && !closed { + if lx.u[lx.i] == Unit.backslash { lx.i += 1 } else if lx.u[lx.i] == Unit.quote { closed = true } + lx.i += 1 + } + lx.i = min(lx.i, lx.end) + lx.emit(start, lx.i, lx.nextNonSpace() == Unit.colon ? .variable : .string) + case _ where Unit.isDigit(c) || (c == Unit.minus && Unit.isDigit(lx.peek(1))): + if c == Unit.minus { + lx.i += 1 + lx.emit(start, lx.i, .number) + } + lx.number() + case _ where Unit.isAlpha(c): + lx.identifier() + if literals.contains(lx.text(start, lx.i)) { lx.emit(start, lx.i, .number) } + default: + lx.i += 1 + } + } + } +} diff --git a/Sources/HelderCore/Highlight/JavaScriptGrammar.swift b/Sources/HelderCore/Highlight/JavaScriptGrammar.swift new file mode 100644 index 0000000..483d9f1 --- /dev/null +++ b/Sources/HelderCore/Highlight/JavaScriptGrammar.swift @@ -0,0 +1,256 @@ +import Foundation + +enum JavaScriptGrammar { + static let keywords: Set = [ + "as", "async", "await", "break", "case", "catch", "class", "const", "continue", "debugger", + "default", "delete", "do", "else", "enum", "export", "extends", "finally", "for", "from", + "function", "get", "if", "implements", "import", "in", "instanceof", "interface", "let", "new", + "of", "package", "private", "protected", "public", "return", "set", "static", "super", "switch", + "this", "throw", "try", "typeof", "var", "void", "while", "with", "yield", + ] + static let typeScriptKeywords: Set = [ + "abstract", "declare", "is", "keyof", "module", "namespace", "readonly", "type", "infer", + "satisfies", "override", "unique", "asserts", "accessor", + ] + /// Painted as builtins, in the number colour. + static let typeScriptBuiltins: Set = [ + "string", "number", "boolean", "any", "void", "never", "unknown", "object", "symbol", "bigint", + ] + static let constants: Set = ["true", "false", "null", "undefined", "NaN", "Infinity"] + /// Keywords after which the next name is a class. + private static let classIntroducers: Set = ["class", "extends", "implements", "new", "instanceof", "interface"] + /// Keywords after which a `/` starts a regex rather than a division. + private static let valueKeywords: Set = ["this", "super"] + + static func scan(_ lx: inout Lexer, _ st: inout GrammarState, typescript: Bool, jsx: Bool) { + var expectsValue = true + var classNext = false + while lx.i < lx.end { + switch st.mode { + case .blockComment: + if lx.blockComment(from: lx.i, close: Literals.blockClose) { st.mode = .code } + continue + case .template: + template(&lx, &st) + expectsValue = false + continue + case let .jsxTag(level, closing): + jsxTag(&lx, &st, level: level, closing: closing) + expectsValue = true + continue + case let .jsxText(level): + jsxText(&lx, &st, level: level) + expectsValue = true + continue + default: + break + } + if lx.stop != nil && lx.atStop() { return } + let c = lx.u[lx.i] + let start = lx.i + if Unit.isSpace(c) { + lx.i += 1 + continue + } + switch c { + case Unit.slash where lx.peek(1) == Unit.slash: + lx.lineComment() + case Unit.slash where lx.peek(1) == Unit.star: + lx.i += 2 + if !lx.blockComment(from: start, close: Literals.blockClose) { st.mode = .blockComment } + case Unit.slash where expectsValue && regex(&lx): + expectsValue = false + case Unit.quote, Unit.apostrophe: + lx.i += 1 + _ = lx.quoted(from: start, quote: c) + expectsValue = false + case Unit.backtick: + lx.i += 1 + lx.emit(start, lx.i, .string) + st.mode = .template + case _ where Unit.isDigit(c) || (c == Unit.dot && Unit.isDigit(lx.peek(1))): + lx.number() + expectsValue = false + case _ where Unit.isIdentStart(c) || c == Unit.dollar || (c == Unit.hash && Unit.isIdentStart(lx.peek(1))): + lx.i += 1 + lx.identifier { $0 == Unit.dollar } + let word = lx.text(start, lx.i) + if keywords.contains(word) || (typescript && typeScriptKeywords.contains(word)) { + lx.emit(start, lx.i, .keyword) + classNext = classIntroducers.contains(word) + expectsValue = !valueKeywords.contains(word) + continue + } + if constants.contains(word) || (typescript && typeScriptBuiltins.contains(word)) { + lx.emit(start, lx.i, .number) + } else if classNext { + lx.emit(start, lx.i, .variable) + } else if isConstantName(lx, start, lx.i) { + lx.emit(start, lx.i, .number) + } + classNext = false + expectsValue = false + continue + case Unit.lbrace: + lx.i += 1 + if !st.resumes.isEmpty { st.depth += 1 } + expectsValue = true + case Unit.rbrace: + lx.i += 1 + if let resume = st.resumes.last, resume.depth == st.depth { + st.resumes.removeLast() + st.mode = resume.mode + } else if !st.resumes.isEmpty { + st.depth -= 1 + } + expectsValue = true + case Unit.lparen, Unit.lbracket, Unit.comma, Unit.semicolon: + lx.i += 1 + expectsValue = true + case Unit.rparen, Unit.rbracket: + lx.i += 1 + expectsValue = false + case Unit.less where jsx && (expectsValue || lx.peek(1) == Unit.slash): + if !openJSX(&lx, &st, level: 0) { lx.operatorRun() } + case Unit.dot: + lx.i += 1 + while lx.peek() == Unit.dot { lx.i += 1 } + if lx.i - start > 1 { lx.emit(start, lx.i, .keyword) } + expectsValue = lx.i - start > 1 + case _ where Unit.isOperator(c): + lx.operatorRun() + expectsValue = true + default: + lx.i += 1 + } + classNext = false + } + } + + /// `FOO_BAR`: an all-caps name of two or more characters, painted as a constant. + static func isConstantName(_ lx: Lexer, _ from: Int, _ to: Int) -> Bool { + guard to - from >= 2, Unit.isUpper(lx.u[from]) else { return false } + for k in from.. Bool { + let start = lx.i + var k = start + 1 + var inClass = false + while k < lx.end { + let c = lx.u[k] + if c == Unit.backslash { + k += 2 + continue + } + if c == Unit.lbracket { inClass = true } + if c == Unit.rbracket { inClass = false } + if c == Unit.slash && !inClass { break } + k += 1 + } + guard k < lx.end, k > start + 1 else { return false } + k += 1 + while k < lx.end && Unit.isAlpha(lx.u[k]) { k += 1 } + lx.i = k + lx.emit(start, k, .string) + return true + } + + /// Template-literal text up to the closing backtick, a `${`, or the end of the line. + private static func template(_ lx: inout Lexer, _ st: inout GrammarState) { + let start = lx.i + while lx.i < lx.end { + let c = lx.u[lx.i] + if c == Unit.backslash { + lx.i = min(lx.i + 2, lx.end) + continue + } + if c == Unit.backtick { + lx.i += 1 + lx.emit(start, lx.i, .string) + st.mode = .code + return + } + if c == Unit.dollar && lx.peek(1) == Unit.lbrace { + lx.emit(start, lx.i, .string) + lx.i += 2 + st.resumes.append(Resume(depth: st.depth, mode: .template)) + st.mode = .code + return + } + lx.i += 1 + } + lx.emit(start, lx.i, .string) + } + + /// `` or ``; false (nothing consumed) for anything else. + private static func openJSX(_ lx: inout Lexer, _ st: inout GrammarState, level: Int) -> Bool { + var k = lx.i + 1 + let closing = lx.unit(at: k) == Unit.slash + if closing { k += 1 } + let first = lx.unit(at: k) + if first == Unit.greater { + lx.i = k + 1 + st.mode = children(closing ? level - 1 : level + 1) + return true + } + guard Unit.isAlpha(first) else { return false } + let nameStart = k + while k < lx.end && (Unit.isIdentPart(lx.u[k]) || lx.u[k] == Unit.dot || lx.u[k] == Unit.minus || lx.u[k] == Unit.colon) { k += 1 } + lx.emit(nameStart, k, .number) + lx.i = k + st.mode = .jsxTag(level: level, closing: closing) + return true + } + + private static func children(_ open: Int) -> Mode { + open > 0 ? .jsxText(level: open) : .code + } + + /// Attributes inside a JSX tag, up to `>` or `/>`; a `{` hands over to code until its `}`. + private static func jsxTag(_ lx: inout Lexer, _ st: inout GrammarState, level: Int, closing: Bool) { + while lx.i < lx.end { + let c = lx.u[lx.i] + let start = lx.i + if c == Unit.greater { + lx.i += 1 + st.mode = children(closing ? level - 1 : level + 1) + return + } else if c == Unit.slash && lx.peek(1) == Unit.greater { + lx.i += 2 + st.mode = children(level) + return + } else if c == Unit.lbrace { + lx.i += 1 + st.resumes.append(Resume(depth: st.depth, mode: .jsxTag(level: level, closing: closing))) + st.mode = .code + return + } else if c == Unit.quote || c == Unit.apostrophe { + lx.i += 1 + _ = lx.quoted(from: start, quote: c, escapes: false) + } else if Unit.isIdentStart(c) { + lx.identifier { $0 == Unit.minus || $0 == Unit.colon } + lx.emit(start, lx.i, .variable) + } else { + lx.i += 1 + } + } + } + + /// Children text: plain up to the next tag or `{` expression. + private static func jsxText(_ lx: inout Lexer, _ st: inout GrammarState, level: Int) { + while lx.i < lx.end { + let c = lx.u[lx.i] + if c == Unit.less && openJSX(&lx, &st, level: level) { return } + if c == Unit.lbrace { + lx.i += 1 + st.resumes.append(Resume(depth: st.depth, mode: .jsxText(level: level))) + st.mode = .code + return + } + lx.i += 1 + } + } +} diff --git a/Sources/HelderCore/Highlight/Lexer.swift b/Sources/HelderCore/Highlight/Lexer.swift new file mode 100644 index 0000000..85ea047 --- /dev/null +++ b/Sources/HelderCore/Highlight/Lexer.swift @@ -0,0 +1,206 @@ +import Foundation + +/// Where an embedded grammar hands control back to its host. +enum Terminator: Hashable, Sendable { + /// `?>` closes a PHP island inside markup. + case phpClose + /// `` or `\n

const

" + #expect(role("const", in: text, .markup) == .keyword) + #expect(role("// c", in: text, .markup) == .comment) + #expect(role("script", in: text, .markup, occurrence: 1) == .number) + #expect(role(".b", in: text, .markup) == .number) + #expect(role("color", in: text, .markup) == .variable) + #expect(role("const", in: text, .markup, occurrence: 1) == .plain) + } + + @Test("a JavaScript line comment stops at the closing script tag") + func scriptCloseInsideComment() { + let text = "

" + #expect(role("// x", in: text, .markup) == .comment) + #expect(role("p", in: text, .markup) == .number) + } + + @Test("a tag may wrap over lines, with a value that wraps too") + func multiLineTag() { + let text = "\nafter" + #expect(role(" b\"", in: text, .markup) == .string) + #expect(role("src", in: text, .markup) == .variable) + #expect(role("after", in: text, .markup) == .plain) + } + + @Test("Vue single-file components read their script block") + func vue() { + let text = "\n" + #expect(role(":class", in: text, .markup) == .variable) + #expect(role("@click", in: text, .markup) == .variable) + #expect(role("import", in: text, .markup) == .keyword) + } +} diff --git a/Tests/HelderCoreTests/Highlight/PHPGrammarTests.swift b/Tests/HelderCoreTests/Highlight/PHPGrammarTests.swift new file mode 100644 index 0000000..f1d1d04 --- /dev/null +++ b/Tests/HelderCoreTests/Highlight/PHPGrammarTests.swift @@ -0,0 +1,147 @@ +import HelderCore +import Testing + +@Suite struct PHPGrammarTests { + private let source = """ + name} $prefix") . self::STATUS_ACTIVE . 0x1F; + } + } + """ + + @Test("the open tag and keywords read as keywords") + func keywords() { + #expect(role(" is a function name, a property is a variable") + func arrowAccess() { + let text = "save(); $a->name;" + #expect(role("save", in: text, .php) == .plain) + #expect(role("name", in: text, .php) == .variable) + #expect(role("->", in: text, .php) == .keyword) + } + + @Test("strings interpolate variables, single quotes do not") + func interpolation() { + let text = "name}", in: source, .php) == .variable) + } + + @Test("comments: //, # and block comments") + func comments() { + #expect(role("// line comment", in: source, .php) == .comment) + #expect(role("# hash", in: "\">\n\n hi\n\n" + #expect(role("div", in: text, .php) == .number) + #expect(role("$cls", in: text, .php) == .variable) + #expect(role("?>", in: text, .php) == .keyword) + #expect(role("if", in: text, .php) == .keyword) + #expect(role("hi", in: text, .php) == .plain) + #expect(role("endif", in: text, .php) == .keyword) + } + + @Test("a PHP line comment ends at ?>") + func lineCommentEndsAtCloseTag() { + let text = "

after

" + #expect(role("// note ", in: text, .php) == .comment) + #expect(role("?>", in: text, .php) == .keyword) + #expect(role("after", in: text, .php) == .plain) + } + + @Test("a Blade file without name }}\n@endif" + #expect(role("$user", in: text, .php) == .variable) + } + + @Test("static, self and parent stay keywords before ::") + func scopeKeywords() { + let text = " (\n
\n {n.map((i) => {i})}\n
\n)\n", .tsx), + ("\n\n\n\n", .markup), + ("a {\n color: #fff;\n margin: 0 4px;\n}\n", .css), + ("{\n \"a\": [1, true, null]\n}\n", .json), + ("# T\n\n```php\n$x = 1;\n```\n- item `code`\n", .markdown), + ("#!/bin/sh\nif [ -f x ]; then echo \"$HOME\"; fi\ncat < 0) + position = token.location + token.length + } + #expect(position == text.utf16.count) + } + + @Test("adjacent runs of one role are merged", arguments: samples) + func adjacentRunsAreMerged(sample: (String, Language)) { + let tokens = SyntaxHighlighter.tokens(for: sample.0, language: sample.1) + for (a, b) in zip(tokens, tokens.dropFirst()) { + #expect(a.role != b.role) + } + } + + @Test("line-by-line tokens with carried state equal whole-buffer tokens", arguments: samples) + func incrementalMatchesWholeBuffer(sample: (String, Language)) { + let (text, language) = sample + var state = HighlightState(language: language, text: text) + var offset = 0 + var painted: [Token] = [] + for line in text.components(separatedBy: "\n") { + for token in SyntaxHighlighter.lineTokens(for: line, state: &state) where token.role != .plain { + painted.append(Token(location: token.location + offset, length: token.length, role: token.role)) + } + offset += line.utf16.count + 1 + } + let whole = SyntaxHighlighter.tokens(for: text, language: language).filter { $0.role != .plain } + #expect(painted == whole) + } + + @Test("an unknown language is one plain run") + func unknownLanguageIsPlain() { + #expect(SyntaxHighlighter.tokens(for: "a = 1", language: nil) == [Token(location: 0, length: 5, role: .plain)]) + } + + @Test("an empty buffer has no tokens") + func emptyBuffer() { + #expect(SyntaxHighlighter.tokens(for: "", language: .php).isEmpty) + #expect(SyntaxHighlighter.lineTokens(for: "", language: .javascript).isEmpty) + } + + @Test("offsets count UTF-16 units, so text after an emoji lines up") + func utf16Offsets() { + let text = "const s = \"😀\"; const n = 42" + let tokens = SyntaxHighlighter.tokens(for: text, language: .javascript) + let number = tokens.first { $0.role == .number } + #expect(number?.location == (text as NSString).range(of: "42").location) + #expect(number?.length == 2) + } + + @Test("CRLF line endings keep the carriage return inside the line") + func crlfLines() { + let text = "/* a\r\n b */\r\nlet x = 1\r\n" + #expect(role("b */", in: text, .javascript) == .comment) + #expect(role("let", in: text, .javascript) == .keyword) + #expect(role("1", in: text, .javascript, occurrence: 0) == .number) + } + + @Test("a single diff line is highlighted on its own, without state from the lines above") + func lineStandsAlone() { + let tokens = SyntaxHighlighter.lineTokens(for: " end */ let x", language: .javascript) + #expect(tokens.contains { $0.role == .keyword }) + #expect(!tokens.contains { $0.role == .comment }) + } + + @Test("the state reports an open construct at a line break") + func stateReportsOpenConstruct() { + var state = HighlightState(language: .javascript) + _ = SyntaxHighlighter.lineTokens(for: "/* open", state: &state) + #expect(state.isInsideConstruct) + _ = SyntaxHighlighter.lineTokens(for: "close */", state: &state) + #expect(!state.isInsideConstruct) + #expect(state == HighlightState(language: .javascript)) + } + + @Test("every language survives hostile input without hanging", arguments: Language.allCases) + func hostileInput(language: Language) { + let text = " ``` ---\n" + String(repeating: "\\", count: 20) + let tokens = SyntaxHighlighter.tokens(for: text, language: language) + #expect(tokens.map(\.length).reduce(0, +) == text.utf16.count) + } + + @Test("a 5,000-line file tokenizes well within a second, even in a debug build") + func performanceSanity() { + let block = """ + where('id', $id)->firstOrFail(); // fetch + return response()->json(["name" => "{$user->name} #{$id}", 'count' => 42]); + } + } + + """ + let text = String(repeating: block, count: 5000 / 12 + 1) + let clock = ContinuousClock() + let elapsed = clock.measure { + _ = SyntaxHighlighter.tokens(for: text, language: .php, knownSymbols: ["User"]) + } + #expect(elapsed < .seconds(1)) + } +} diff --git a/Tests/HelderCoreTests/Highlight/YAMLGrammarTests.swift b/Tests/HelderCoreTests/Highlight/YAMLGrammarTests.swift new file mode 100644 index 0000000..2615fbf --- /dev/null +++ b/Tests/HelderCoreTests/Highlight/YAMLGrammarTests.swift @@ -0,0 +1,42 @@ +import HelderCore +import Testing + +@Suite struct YAMLGrammarTests { + @Test("keys, scalars, booleans, numbers and comments") + func basics() { + let text = "name: helder # app\nport: 8080\ndebug: true\nempty: ~\nurl: http://x.test:80\n\"quoted key\": 'v'" + #expect(role("name", in: text, .yaml) == .keyword) + #expect(role("# app", in: text, .yaml) == .comment) + #expect(role("8080", in: text, .yaml) == .number) + #expect(role("true", in: text, .yaml) == .keyword) + #expect(role("~", in: text, .yaml) == .keyword) + #expect(role("http://x.test:80", in: text, .yaml) == .plain) + #expect(role("\"quoted key\"", in: text, .yaml) == .keyword) + #expect(role("'v'", in: text, .yaml) == .string) + } + + @Test("a block scalar runs while the lines stay indented") + func blockScalar() { + let text = "script: |\n echo: hi\n\n more\nnext: 1" + #expect(role(" echo: hi", in: text, .yaml) == nil) + #expect(role("echo: hi", in: text, .yaml) == .string) + #expect(role("more", in: text, .yaml) == .string) + #expect(role("next", in: text, .yaml) == .keyword) + } + + @Test("lists, anchors, aliases and tags") + func listsAndAnchors() { + let text = "base: &base\n - item: !!str 1\nuse: *base" + #expect(role("&base", in: text, .yaml) == .keyword) + #expect(role("item", in: text, .yaml) == .keyword) + #expect(role("!!str", in: text, .yaml) == .number) + #expect(role("*base", in: text, .yaml) == .keyword) + } + + @Test("flow collections split on commas") + func flow() { + let text = "tags: [a, 2, true]" + #expect(role("2", in: text, .yaml) == .number) + #expect(role("true", in: text, .yaml) == .keyword) + } +} diff --git a/Tests/HelderCoreTests/Markdown/MarkdownInlineParserTests.swift b/Tests/HelderCoreTests/Markdown/MarkdownInlineParserTests.swift new file mode 100644 index 0000000..15916c2 --- /dev/null +++ b/Tests/HelderCoreTests/Markdown/MarkdownInlineParserTests.swift @@ -0,0 +1,34 @@ +@testable import HelderCore +import Testing + +@Suite struct MarkdownInlineParserTests { + @Test("a link destination splits into URL and optional title", arguments: [ + ("https://x.com", "https://x.com", nil), + ("https://x.com \"Home\"", "https://x.com", "Home"), + (" 'T'", "a b.png", "T"), + ("x.png (Paren)", "x.png", "Paren"), + (" spaced ", "spaced", nil), + ] as [(String, String, String?)]) + func destination(raw: String, url: String, title: String?) { + let parsed = MarkdownInlineParser.destination(Substring(raw)) + #expect(parsed.url == url) + #expect(parsed.title == title) + } + + @Test("alt text flattens nested inline nodes") + func plainText() { + let nodes: [MarkdownInline] = [.text("a "), .strong([.code("b")]), .link(text: [.text(" c")], url: "#", title: nil)] + #expect(MarkdownInlineParser.plainText(nodes) == "a b c") + } + + @Test("placeholder look-alikes in the source stay literal text") + func placeholderLookAlike() { + let text = "x \u{E000}99\u{E001} y" + #expect(MarkdownInlineParser.parse(text, baseDir: "") == [.text(text)]) + } + + @Test("unmatched markers stay literal") + func unmatchedMarkers() { + #expect(MarkdownInlineParser.parse("a ** b ` c [d](", baseDir: "") == [.text("a ** b ` c [d](")]) + } +} diff --git a/Tests/HelderCoreTests/Markdown/MarkdownParserTests.swift b/Tests/HelderCoreTests/Markdown/MarkdownParserTests.swift new file mode 100644 index 0000000..82635c7 --- /dev/null +++ b/Tests/HelderCoreTests/Markdown/MarkdownParserTests.swift @@ -0,0 +1,209 @@ +import Foundation +import HelderCore +import Testing + +@Suite struct MarkdownParserTests { + @Test("headings, emphasis and links") + func headingsAndInline() { + let blocks = MarkdownParser.parse("# Title\n\nSome **bold** and *italic* and [a](https://x.com).") + #expect(blocks == [ + .heading(level: 1, content: [.text("Title")]), + .paragraph([ + .text("Some "), .strong([.text("bold")]), .text(" and "), .emphasis([.text("italic")]), + .text(" and "), .link(text: [.text("a")], url: "https://x.com", title: nil), .text("."), + ]), + ]) + } + + @Test("heading levels run from 1 to 6 and need a space", arguments: [("###### six", 6), ("## two ", 2)]) + func headingLevels(line: String, level: Int) { + guard case let .heading(parsed, _)? = MarkdownParser.parse(line).first else { + Issue.record("not a heading") + return + } + #expect(parsed == level) + #expect(MarkdownParser.parse("#nospace") == [.paragraph([.text("#nospace")])]) + #expect(MarkdownParser.parse("####### seven") == [.paragraph([.text("####### seven")])]) + } + + @Test("code spans survive next to digits and are never re-read") + func codeSpans() { + let blocks = MarkdownParser.parse("I have 0 cats and `**code**` and 1 dog.") + #expect(blocks == [.paragraph([.text("I have 0 cats and "), .code("**code**"), .text(" and 1 dog.")])]) + } + + @Test("raw HTML stays literal text") + func rawHTML() { + #expect(MarkdownParser.parse("A tag.") == [.paragraph([.text("A tag.")])]) + } + + @Test("dangerous link schemes are dropped but the text stays") + func unsafeLinks() { + #expect(MarkdownParser.parse("[click](javascript:alert(1))") == [.paragraph([.text("click)")])]) + #expect(MarkdownParser.parse("[click](javascript:x)") == [.paragraph([.text("click")])]) + } + + @Test("fenced code keeps its text and resolves its language") + func fencedCode() { + #expect(MarkdownParser.parse("```js\nconst a = 1\n\n b\n```\nafter") == [ + .code(language: .javascript, text: "const a = 1\n\n b"), + .paragraph([.text("after")]), + ]) + #expect(MarkdownParser.parse("```\nx") == [.code(language: nil, text: "x")]) + #expect(MarkdownParser.parse("```brainfuck\n+\n```") == [.code(language: nil, text: "+")]) + } + + @Test("bullet and numbered lists") + func lists() { + #expect(MarkdownParser.parse("- a\n* b\n+ c") == [.list(ordered: false, items: [[.text("a")], [.text("b")], [.text("c")]])]) + #expect(MarkdownParser.parse("1. a\n2) b") == [.list(ordered: true, items: [[.text("a")], [.text("b")]])]) + } + + @Test("rules need three marks of one kind") + func rules() { + #expect(MarkdownParser.parse("---") == [.rule]) + #expect(MarkdownParser.parse("* * *") == [.rule]) + #expect(MarkdownParser.parse("__ _") == [.rule]) + #expect(MarkdownParser.parse("-*-") != [.rule]) + } + + @Test("block quotes nest and parse their own blocks") + func quotes() { + #expect(MarkdownParser.parse("> # Hi\n> > deep\nout") == [ + .quote([.heading(level: 1, content: [.text("Hi")]), .quote([.paragraph([.text("deep")])])]), + .paragraph([.text("out")]), + ]) + } + + @Test("paragraph lines join with a space; a blank line ends a paragraph") + func paragraphs() { + #expect(MarkdownParser.parse("a\n b \n\nc") == [.paragraph([.text("a b")]), .paragraph([.text("c")])]) + } + + @Test("CRLF and bare CR read as newlines") + func lineEndings() { + #expect(MarkdownParser.parse("# A\r\nb\rc") == [.heading(level: 1, content: [.text("A")]), .paragraph([.text("b c")])]) + } + + @Test("an empty document has no blocks") + func empty() { + #expect(MarkdownParser.parse("").isEmpty) + #expect(MarkdownParser.parse("\n\n \n").isEmpty) + } + + // MARK: tables + + @Test("a GFM table has a header, alignments and body rows with inline markup") + func table() { + #expect(MarkdownParser.parse("| a | b |\n|---|---|\n| 1 | `x` |\n| 2 | **y** |") == [ + .table( + header: [[.text("a")], [.text("b")]], + alignments: [nil, nil], + rows: [[[.text("1")], [.code("x")]], [[.text("2")], [.strong([.text("y")])]]] + ), + ]) + } + + @Test("column alignment comes from the delimiter row") + func alignment() { + guard case let .table(_, alignments, _)? = MarkdownParser.parse("| l | c | r |\n| :-- | :-: | --: |\n| 1 | 2 | 3 |").first else { + Issue.record("not a table") + return + } + #expect(alignments == [.left, .center, .right]) + } + + @Test("escaped pipes, ragged rows and prose after the table") + func raggedRows() { + #expect(MarkdownParser.parse("| a | b |\n|---|---|\n| x \\| y | 2 | extra |\n| short |\n\nAfter.") == [ + .table( + header: [[.text("a")], [.text("b")]], + alignments: [nil, nil], + rows: [[[.text("x | y")], [.text("2")]], [[.text("short")], []]] + ), + .paragraph([.text("After.")]), + ]) + } + + @Test("a pipe-bearing paragraph without a delimiter row is not a table") + func notATable() { + #expect(MarkdownParser.parse("a | b\nnot a table") == [.paragraph([.text("a | b not a table")])]) + } + + // MARK: images + + @Test("a relative image resolves against the document folder") + func localImage() { + #expect(MarkdownParser.parse("![Forge](forge-app-config.png)", baseDir: "docs/how-to") == [ + .paragraph([.image(alt: "Forge", source: .local(path: "docs/how-to/forge-app-config.png"), title: nil)]), + ]) + } + + @Test("an image title stays out of the path, and .. walks up a folder") + func imageTitle() { + #expect(MarkdownParser.parse("![c](../img/a%20b.png \"A title\")", baseDir: "docs/how-to") == [ + .paragraph([.image(alt: "c", source: .local(path: "docs/img/a b.png"), title: "A title")]), + ]) + } + + @Test("a leading slash means the project root") + func rootImage() { + #expect(MarkdownParser.parse("![c](/img/a.png)", baseDir: "docs/how-to") == [ + .paragraph([.image(alt: "c", source: .local(path: "img/a.png"), title: nil)]), + ]) + } + + @Test("a remote image stays remote") + func remoteImage() { + #expect(MarkdownParser.parse("![c](https://x.com/a.png)", baseDir: "docs") == [ + .paragraph([.image(alt: "c", source: .remote(URL(string: "https://x.com/a.png")!), title: nil)]), + ]) + } + + @Test("a link title stays out of the URL") + func linkTitle() { + #expect(MarkdownParser.parse("[a](https://x.com \"Home\")") == [ + .paragraph([.link(text: [.text("a")], url: "https://x.com", title: "Home")]), + ]) + } + + @Test("an image inside a link, and a link inside strong text") + func nesting() { + #expect(MarkdownParser.parse("[![i](i.png)](https://x.com)") == [ + .paragraph([.link(text: [.image(alt: "i", source: .local(path: "i.png"), title: nil)], url: "https://x.com", title: nil)]), + ]) + #expect(MarkdownParser.parse("**see [a](#top)**") == [ + .paragraph([.strong([.text("see "), .link(text: [.text("a")], url: "#top", title: nil)])]), + ]) + } + + @Test("underscores inside words are not emphasis") + func intrawordUnderscore() { + #expect(MarkdownParser.parse("snake_case_name and _this_") == [ + .paragraph([.text("snake_case_name and "), .emphasis([.text("this")])]), + ]) + #expect(MarkdownParser.parse("__bold__ ~~gone~~") == [.paragraph([.strong([.text("bold")]), .text(" "), .strikethrough([.text("gone")])])]) + } + + // MARK: helpers + + @Test("safeURL keeps web, mail, anchors and relative paths only", arguments: [ + ("https://x", "https://x"), ("mailto:a@b", "mailto:a@b"), ("#top", "#top"), + ("./a", "./a"), ("../a", "../a"), ("img/x.png", "img/x.png"), (" /a ", "/a"), + ]) + func safeURLs(url: String, kept: String) { + #expect(MarkdownParser.safeURL(url) == kept) + } + + @Test("other schemes are unsafe", arguments: ["javascript:alert(1)", "JAVASCRIPT:x", "data:text/html,x", "file:///etc/passwd"]) + func unsafeURLs(url: String) { + #expect(MarkdownParser.safeURL(url) == nil) + } + + @Test("fence info strings map to grammars") + func fenceLanguages() { + #expect(MarkdownParser.fenceLanguage("TS") == .typescript) + #expect(MarkdownParser.fenceLanguage("shell") == .bash) + #expect(MarkdownParser.fenceLanguage("") == nil) + } +} diff --git a/Tests/HelderCoreTests/Search/FuzzyTests.swift b/Tests/HelderCoreTests/Search/FuzzyTests.swift new file mode 100644 index 0000000..a7ec8a5 --- /dev/null +++ b/Tests/HelderCoreTests/Search/FuzzyTests.swift @@ -0,0 +1,36 @@ +import HelderCore +import Testing + +@Suite struct FuzzyTests { + @Test func matchesSubsequencesCaseInsensitively() { + #expect(Fuzzy.match("uc", in: "UserController.php") == [0, 4]) + #expect(Fuzzy.match("xyz", in: "UserController.php") == nil) + } + + @Test func ranksBasenameMatchesFirst() { + let paths = ["src/user/list.php", "app/UserList.php", ".env"] + let ranked = Fuzzy.rankFileNames(query: "userl", paths: paths, showHidden: false) + #expect(ranked.map(\.path) == ["app/UserList.php", "src/user/list.php"]) + #expect(ranked[0].rank == 0 && ranked[1].rank == 1) + } +} + +@Suite struct FuzzyPortedTests { + @Test("an empty query matches nothing in the ranked list") + func emptyQuery() { + #expect(Fuzzy.rankFileNames(query: " ", paths: ["a.ts"], showHidden: true).isEmpty) + #expect(Fuzzy.match("", in: "abc") == []) + } + + @Test("hidden paths are left out unless asked for") + func hiddenPaths() { + #expect(Fuzzy.rankFileNames(query: "env", paths: [".env"], showHidden: false).isEmpty) + #expect(Fuzzy.rankFileNames(query: "env", paths: [".env"], showHidden: true).map(\.path) == [".env"]) + } + + @Test("in-file hits are case-insensitive with UTF-16 offsets") + func inFileHits() { + let hits = InFileSearch.hits(query: "Bal", in: "😀 balance\nnone\nBALANCE") + #expect(hits == [ContentHit(line: 1, text: "😀 balance", matchOffset: 3), ContentHit(line: 3, text: "BALANCE", matchOffset: 0)]) + } +} diff --git a/Tests/HelderCoreTests/Search/RipgrepJSONTests.swift b/Tests/HelderCoreTests/Search/RipgrepJSONTests.swift new file mode 100644 index 0000000..843da1d --- /dev/null +++ b/Tests/HelderCoreTests/Search/RipgrepJSONTests.swift @@ -0,0 +1,106 @@ +import HelderCore +import Testing + +@Suite struct RipgrepJSONTests { + private func matchLine(path: String = "/p/a.ts", text: String = "const balance = 2\n", line: Int = 2, start: Int = 6) -> String { + """ + {"type":"match","data":{"path":{"text":"\(path)"},"lines":{"text":"\(text.replacingOccurrences(of: "\n", with: "\\n"))"},"line_number":\(line),"absolute_offset":12,"submatches":[{"match":{"text":"balance"},"start":\(start),"end":13}]}} + """ + } + + @Test("a match event yields path, line, text without its newline, and the byte offset") + func parsesMatch() { + #expect(RipgrepJSON.parseLine(matchLine()) == RipgrepMatch(path: "/p/a.ts", line: 2, text: "const balance = 2", byteOffset: 6)) + } + + @Test("every other event type is skipped", arguments: [ + #"{"type":"begin","data":{"path":{"text":"/p/a.ts"}}}"#, + #"{"type":"end","data":{"path":{"text":"/p/a.ts"}}}"#, + #"{"type":"summary","data":{"elapsed_total":{"secs":0}}}"#, + "not json", + "", + ]) + func skipsOtherEvents(line: String) { + #expect(RipgrepJSON.parseLine(line) == nil) + } + + @Test("base64 bytes for a non-UTF-8 path or line skip the event") + func skipsBytes() { + #expect(RipgrepJSON.parseLine(#"{"type":"match","data":{"path":{"bytes":"L3AvYQ=="},"lines":{"text":"x\n"},"line_number":1,"submatches":[]}}"#) == nil) + #expect(RipgrepJSON.parseLine(#"{"type":"match","data":{"path":{"text":"/p/a"},"lines":{"bytes":"eA=="},"line_number":1,"submatches":[]}}"#) == nil) + } + + @Test("a match without submatches or a line number defaults to zero") + func defaults() { + let parsed = RipgrepJSON.parseLine(#"{"type":"match","data":{"path":{"text":"/p/a"},"lines":{"text":"x\r\n"}}}"#) + #expect(parsed == RipgrepMatch(path: "/p/a", line: 0, text: "x", byteOffset: 0)) + } + + @Test("paths are made relative to the root") + func relativePath() { + #expect(RipgrepJSON.relativePath("/p/src/a.ts", root: "/p") == "src/a.ts") + #expect(RipgrepJSON.relativePath("/p/src/a.ts", root: "/p/") == "src/a.ts") + #expect(RipgrepJSON.relativePath("/other/a.ts", root: "/p") == "/other/a.ts") + } +} + +@Suite struct ContentGrouperTests { + @Test("matches group per file in first-seen order") + func groups() { + var grouper = ContentGrouper(root: "/p") + grouper.add(RipgrepMatch(path: "/p/b.ts", line: 1, text: "x", byteOffset: 0)) + grouper.add(RipgrepMatch(path: "/p/a.ts", line: 3, text: "y", byteOffset: 0)) + grouper.add(RipgrepMatch(path: "/p/b.ts", line: 7, text: "z", byteOffset: 0)) + #expect(grouper.groups.map(\.path) == ["b.ts", "a.ts"]) + #expect(grouper.groups[0].hits.map(\.line) == [1, 7]) + } + + @Test("the byte offset becomes a UTF-16 offset", arguments: [ + ("const balance", 6, 6), + ("é balance", 3, 2), + ("😀 balance", 5, 3), + ]) + func utf16Offset(text: String, byteOffset: Int, expected: Int) { + var grouper = ContentGrouper(root: "/p") + grouper.add(RipgrepMatch(path: "/p/a", line: 1, text: text, byteOffset: byteOffset)) + #expect(grouper.groups[0].hits[0].matchOffset == expected) + } + + @Test("long lines are capped and the offset clamped to what is left") + func capsLongLines() { + var grouper = ContentGrouper(root: "/p") + let text = String(repeating: "a", count: 1500) + grouper.add(RipgrepMatch(path: "/p/a", line: 1, text: text, byteOffset: 1400)) + let hit = grouper.groups[0].hits[0] + #expect(hit.text.utf16.count == SearchLimits.maxLineLength) + #expect(hit.matchOffset == SearchLimits.maxLineLength) + } + + @Test("a cap never splits a surrogate pair") + func capKeepsSurrogates() { + var grouper = ContentGrouper(root: "/p") + let text = String(repeating: "a", count: SearchLimits.maxLineLength - 1) + "😀 tail" + grouper.add(RipgrepMatch(path: "/p/a", line: 1, text: text, byteOffset: 0)) + #expect(grouper.groups[0].hits[0].text == String(repeating: "a", count: SearchLimits.maxLineLength - 1)) + } + + @Test("new files beyond the file limit are dropped, known files still collect hits") + func fileLimit() { + var grouper = ContentGrouper(root: "/p") + for k in 0..<(SearchLimits.maxFiles + 5) { + grouper.add(RipgrepMatch(path: "/p/f\(k)", line: 1, text: "x", byteOffset: 0)) + } + grouper.add(RipgrepMatch(path: "/p/f0", line: 2, text: "x", byteOffset: 0)) + #expect(grouper.groups.count == SearchLimits.maxFiles) + #expect(grouper.groups[0].hits.count == 2) + } + + @Test("hits per file stop at the per-file limit") + func hitLimit() { + var grouper = ContentGrouper(root: "/p") + for k in 0..<(SearchLimits.maxHitsPerFile + 3) { + grouper.add(RipgrepMatch(path: "/p/a", line: k, text: "x", byteOffset: 0)) + } + #expect(grouper.groups[0].hits.count == SearchLimits.maxHitsPerFile) + } +} diff --git a/Tests/HelderCoreTests/Session/ColumnLayoutTests.swift b/Tests/HelderCoreTests/Session/ColumnLayoutTests.swift new file mode 100644 index 0000000..4acf18f --- /dev/null +++ b/Tests/HelderCoreTests/Session/ColumnLayoutTests.swift @@ -0,0 +1,19 @@ +import HelderCore +import Testing + +@Suite struct ColumnLayoutTests { + @Test func roomyWindowUsesTheDesignRatios() { + let w = ColumnLayout.fluid(windowWidth: 1760, focus: .terminal) + #expect(w == ColumnWidths(sourceControl: 236, explorer: 289, agent: 480)) + } + + @Test func tightWindowFollowsFocus() { + #expect(ColumnLayout.fluid(windowWidth: 1200, focus: .terminal).agent == 600) + #expect(ColumnLayout.fluid(windowWidth: 1200, focus: .editor).agent == 240) + } + + @Test func fittingKeepsTheEditorMinimum() { + let fitted = ColumnLayout.fitted(ColumnWidths(sourceControl: 400, explorer: 400, agent: 400), windowWidth: 1000, sourceControlVisible: true) + #expect(fitted.sourceControl + fitted.explorer + fitted.agent <= 1000 - 3 - ColumnLayout.minEditorWidth) + } +} diff --git a/Tests/HelderCoreTests/Session/SessionStateTests.swift b/Tests/HelderCoreTests/Session/SessionStateTests.swift new file mode 100644 index 0000000..377997a --- /dev/null +++ b/Tests/HelderCoreTests/Session/SessionStateTests.swift @@ -0,0 +1,25 @@ +import Foundation +import HelderCore +import Testing + +@Suite struct SessionStateTests { + @Test func anOlderSessionWithOpenTabsAndAnOriginalModeStillDecodes() throws { + let json = #""" + {"active":"b.php","openTabs":["a.php","b.php"], + "tabMode":{"a.php":"original","b.php":"preview","c.php":"updated"}, + "tabSide":{"b.php":"staged"}} + """# + let state = try JSONDecoder().decode(SessionState.self, from: Data(json.utf8)) + #expect(state.active == "b.php") + #expect(state.modes == ["b.php": .preview, "c.php": .actual]) + #expect(state.sides == ["b.php": .staged]) + } + + @Test func aSessionRoundTripsUnderItsStoredKeys() throws { + let state = SessionState(active: "a.php", modes: ["a.php": .preview], sides: ["a.php": .unstaged]) + let data = try JSONEncoder().encode(state) + let object = try #require(try JSONSerialization.jsonObject(with: data) as? [String: Any]) + #expect(Set(object.keys) == ["active", "tabMode", "tabSide"]) + #expect(try JSONDecoder().decode(SessionState.self, from: data) == state) + } +} diff --git a/Tests/HelderCoreTests/Symbols/PHPSymbolsTests.swift b/Tests/HelderCoreTests/Symbols/PHPSymbolsTests.swift new file mode 100644 index 0000000..f09d671 --- /dev/null +++ b/Tests/HelderCoreTests/Symbols/PHPSymbolsTests.swift @@ -0,0 +1,114 @@ +import HelderCore +import Testing + +@Suite struct PHPSymbolsTests { + @Test("every declaration keyword is read", arguments: [ + ("class Agent", "class", "Agent"), + ("interface Searchable {", "interface", "Searchable"), + ("trait HasVault", "trait", "HasVault"), + ("enum Status: string", "enum", "Status"), + ]) + func declarationKinds(line: String, kind: String, name: String) { + let declaration = PHPSymbols.parseDeclaration(line) + #expect(declaration?.kind == kind) + #expect(declaration?.name == name) + } + + @Test("parents and interfaces come off the declaration line") + func parents() { + let declaration = PHPSymbols.parseDeclaration("final class VaultSearch extends Base implements Searchable, Arrayable, Jsonable {") + #expect(declaration?.parents == ["Base"]) + #expect(declaration?.interfaces == ["Searchable", "Arrayable", "Jsonable"]) + } + + @Test("a fully qualified parent is reduced to its short name") + func qualifiedParents() { + let declaration = PHPSymbols.parseDeclaration("class A extends \\App\\Base implements \\App\\Contracts\\Runs") + #expect(declaration?.parents == ["Base"]) + #expect(declaration?.interfaces == ["Runs"]) + } + + @Test("an interface may extend several interfaces, an enum may implement one") + func interfaceAndEnum() { + #expect(PHPSymbols.parseDeclaration("interface A extends B, C")?.parents == ["B", "C"]) + #expect(PHPSymbols.parseDeclaration("enum Status: string implements HasLabel")?.interfaces == ["HasLabel"]) + } + + @Test("without a clause the lists are empty") + func noClause() { + #expect(PHPSymbols.parseDeclaration("class Plain {") == PHPDeclaration(kind: "class", name: "Plain", parents: [], interfaces: [])) + } + + @Test("the modifiers PHP allows may precede the keyword", arguments: [ + "final class A extends B", "abstract class A", "final readonly class A", " class A", "\tabstract final class A", + ]) + func modifiers(line: String) { + #expect(PHPSymbols.parseDeclaration(line)?.name == "A") + } + + @Test("a mention that is not a declaration is ignored", arguments: [ + "$x = Agent::class;", "// class Agent lives here", "use App\\Models\\Agent;", "return $a instanceof Agent;", "classy Thing", + ]) + func notDeclarations(line: String) { + #expect(PHPSymbols.parseDeclaration(line) == nil) + } + + @Test("an implements list wrapped onto the next line yields fewer interfaces, never wrong ones") + func wrappedImplements() { + #expect(PHPSymbols.parseDeclaration("class A extends B implements")?.interfaces == []) + #expect(PHPSymbols.parseDeclaration("class A extends B implements")?.parents == ["B"]) + } + + @Test("the namespace of a file") + func namespaces() { + #expect(PHPSymbols.parseNamespace("namespace App\\Console\\Commands;") == "App\\Console\\Commands") + #expect(PHPSymbols.parseNamespace("namespace App;") == "App") + #expect(PHPSymbols.parseNamespace(" namespace \\App\\X ;") == "App\\X") + #expect(PHPSymbols.parseNamespace("use App\\Models\\Agent;") == nil) + #expect(PHPSymbols.parseNamespace("class A {") == nil) + #expect(PHPSymbols.parseNamespace("namespace App {") == nil) + } + + @Test("an indented use mixes in one or more traits") + func traitUse() { + #expect(PHPSymbols.parseTraitUse(" use HasFactory;") == ["HasFactory"]) + #expect(PHPSymbols.parseTraitUse(" use HasFactory, Notifiable, SoftDeletes;") == ["HasFactory", "Notifiable", "SoftDeletes"]) + #expect(PHPSymbols.parseTraitUse("\tuse App\\Support\\HasVault;") == ["HasVault"]) + #expect(PHPSymbols.parseTraitUse(" use A, B { A::run insteadof B; }") == ["A", "B"]) + } + + @Test("what is not a trait use gives nothing", arguments: [ + "use App\\Models\\Agent;", " use function App\\tap;", " use const App\\X;", " $f = function () use ($x) {};", + ]) + func notTraitUse(line: String) { + #expect(PHPSymbols.parseTraitUse(line) == []) + } + + @Test("a namespace import is noise for reference search, a trait use is not") + func importLines() { + #expect(PHPSymbols.isImportLine("use App\\Models\\Agent;")) + #expect(PHPSymbols.isImportLine("use App\\Support\\Str as S;")) + #expect(PHPSymbols.isImportLine("use function App\\Support\\tap;")) + #expect(!PHPSymbols.isImportLine(" use HasFactory;")) + #expect(!PHPSymbols.isImportLine("\tuse HasFactory;")) + #expect(!PHPSymbols.isImportLine("$f = function () use ($agent) {};")) + #expect(!PHPSymbols.isImportLine("// use Agent for this")) + } + + @Test("the word under the caret", arguments: [ + ("return new Agent($x);", 12, "Agent"), ("return new Agent($x);", 11, "Agent"), ("return new Agent($x);", 16, "Agent"), + ("return new Agent($x);", 17, ""), (" ", 1, ""), ("$x = 42;", 6, ""), ("Agent", 0, "Agent"), ("Agent", 5, "Agent"), + ("Agent", 9, ""), ("Agent", -1, ""), + ]) + func wordAt(line: String, offset: Int, word: String) { + #expect(PHPSymbols.word(in: line, at: offset) == word) + } + + @Test("project declarations sort before vendor ones, then by path, capped") + func sortDefinitions() { + let defs = ["vendor/z.php", "b.php", "a.php"].map { SymbolDef(name: "A", path: $0, line: 1, kind: "class") } + #expect(PHPSymbols.sortDefinitions(defs).map(\.path) == ["a.php", "b.php", "vendor/z.php"]) + let many = (0..<40).map { SymbolDef(name: "A", path: "f\($0).php", line: 1, kind: "class") } + #expect(PHPSymbols.sortDefinitions(many).count == SymbolLimits.maxDefinitions) + } +} diff --git a/Tests/HelderServicesTests/Files/FSEventsWatcherTests.swift b/Tests/HelderServicesTests/Files/FSEventsWatcherTests.swift new file mode 100644 index 0000000..b47b563 --- /dev/null +++ b/Tests/HelderServicesTests/Files/FSEventsWatcherTests.swift @@ -0,0 +1,217 @@ +import CoreServices +import Foundation +import HelderCore +@testable import HelderServices +import Testing + +/// Collects watcher events from any queue. +private final class EventLog: @unchecked Sendable { + private let lock = NSLock() + private var events: [WatchEvent] = [] + + func append(_ event: WatchEvent) { lock.withLock { events.append(event) } } + func count(_ event: WatchEvent) -> Int { lock.withLock { events.filter { $0 == event }.count } } + func clear() { lock.withLock { events.removeAll() } } +} + +/// Real FSEvents against temp folders; the waits are generous so a busy machine does not fail them. +@Suite(.serialized) struct FSEventsWatcherTests { + private let debounce = WatchDebounce(project: 0.3, git: 0.2, config: 0.1) + + /// Starts a watcher and lets FSEvents settle so setup writes do not leak into the test. + private func watch(_ root: URL) async -> (FSEventsWatcher, EventLog) { + let log = EventLog() + let watcher = FSEventsWatcher(debounce: debounce) + watcher.start(root: root) { log.append($0) } + try? await Task.sleep(nanoseconds: 600_000_000) + log.clear() + return (watcher, log) + } + + private func settle() async { + try? await Task.sleep(nanoseconds: 1_000_000_000) + } + + @Test func aBurstOfProjectChangesFiresOneDebouncedEvent() async throws { + let dir = try TempDirectory() + let (watcher, log) = await watch(dir.root) + defer { watcher.stop() } + for i in 0..<5 { try dir.write("src/file\(i).txt", "\(i)") } + #expect(await eventually { log.count(.project) >= 1 }) + await settle() + #expect(log.count(.project) == 1) + #expect(log.count(.git) == 0) + } + + @Test func changesInsideIgnoredFoldersAreDropped() async throws { + let dir = try TempDirectory() + try dir.mkdir("node_modules/pkg") + try dir.mkdir("vendor") + let (watcher, log) = await watch(dir.root) + defer { watcher.stop() } + try dir.write("node_modules/pkg/index.js", "x") + try dir.write("vendor/autoload.php", "x") + try dir.write(".helder/recent.json", "[]") + await settle() + #expect(log.count(.project) == 0) + } + + @Test func theConfigFileFiresAConfigEventOnly() async throws { + let dir = try TempDirectory() + try dir.mkdir(".helder") + let (watcher, log) = await watch(dir.root) + defer { watcher.stop() } + try dir.write(".helder/config.json", #"{"editor":{"tabSize":2}}"#) + #expect(await eventually { log.count(.config) == 1 }) + await settle() + #expect(log.count(.project) == 0) + } + + @Test func aCommitFiresAGitEvent() async throws { + let repo = try TempGitRepo() + try repo.commit(["a.txt": "a\n"]) + let (watcher, log) = await watch(repo.root) + defer { watcher.stop() } + try repo.run("commit", "-q", "--allow-empty", "-m", "second") + #expect(await eventually { log.count(.git) >= 1 }) + } + + @Test func aCommitInAWorktreeFiresAGitEvent() async throws { + let repo = try TempGitRepo() + try repo.commit(["a.txt": "a\n"]) + let worktree = repo.root.deletingLastPathComponent().appendingPathComponent("helder-wt-\(UUID().uuidString)") + defer { try? FileManager.default.removeItem(at: worktree) } + try repo.run("worktree", "add", "-q", "-b", "side", worktree.path) + let (watcher, log) = await watch(worktree) + defer { watcher.stop() } + try repo.run("-C", worktree.path, "commit", "-q", "--allow-empty", "-m", "in the worktree") + #expect(await eventually { log.count(.git) >= 1 }) + } + + @Test func stopSilencesTheWatcher() async throws { + let dir = try TempDirectory() + let (watcher, log) = await watch(dir.root) + watcher.stop() + try dir.write("after.txt", "x") + await settle() + #expect(log.count(.project) == 0) + } + + @Test func laravelCachesAndConfiguredExcludesAreDropped() async throws { + let dir = try TempDirectory() + try dir.write(".helder/config.json", #"{"files":{"exclude":["*.log"]}}"#) + try dir.mkdir("storage/framework/views") + try dir.mkdir("storage/logs") + let (watcher, log) = await watch(dir.root) + defer { watcher.stop() } + try dir.write("storage/framework/views/abc.php", "x") + try dir.write("storage/logs/laravel.log", "x") + try dir.write(".phpunit.result.cache", "x") + await settle() + #expect(log.count(.project) == 0) + try dir.write("app/User.php", "x") + #expect(await eventually { log.count(.project) == 1 }) + } + + @Test func gitIgnoredChangesAreDroppedWhenTheProjectFollowsGitignore() async throws { + let repo = try TempGitRepo() + try repo.commit([".gitignore": "tmp/\n", ".helder/config.json": #"{"files":{"followGitignore":true}}"#]) + try FileManager.default.createDirectory(at: repo.root.appendingPathComponent("tmp"), withIntermediateDirectories: true) + let (watcher, log) = await watch(repo.root) + defer { watcher.stop() } + try repo.write("tmp/a.txt", "x") + try repo.write("tmp/b.txt", "x") + await settle() + #expect(log.count(.project) == 0) + try repo.write("tmp/c.txt", "x") + try repo.write("src/kept.txt", "x") + #expect(await eventually { log.count(.project) == 1 }) + } + + @Test func gitIgnoredChangesStillFireWhenTheProjectShowsIgnoredFiles() async throws { + let repo = try TempGitRepo() + try repo.commit([".gitignore": "tmp/\n"]) + try FileManager.default.createDirectory(at: repo.root.appendingPathComponent("tmp"), withIntermediateDirectories: true) + let (watcher, log) = await watch(repo.root) + defer { watcher.stop() } + try repo.write("tmp/a.txt", "x") + #expect(await eventually { log.count(.project) == 1 }) + } + + @Test func startingAgainMovesTheWatchToTheNewRoot() async throws { + let first = try TempDirectory() + let second = try TempDirectory() + let (watcher, log) = await watch(first.root) + defer { watcher.stop() } + watcher.start(root: second.root) { log.append($0) } + try? await Task.sleep(nanoseconds: 600_000_000) + log.clear() + try first.write("old.txt", "x") + await settle() + #expect(log.count(.project) == 0) + try second.write("new.txt", "x") + #expect(await eventually { log.count(.project) == 1 }) + } +} + +@Suite struct EventRouterTests { + private let root = "/p" + private let git = "/p/.git" + private let none = FSEventStreamEventFlags(0) + + private func classify(_ path: String, gitDirectory: String = "/p/.git", exclude: [String] = []) -> WatchEvent? { + EventRouter.classify(path: path, root: root, gitDirectory: gitDirectory, flags: none, exclude: exclude) + } + + @Test func projectFilesAreProjectEvents() { + #expect(classify("/p/src/a.ts") == .project) + #expect(classify("/p/.env") == .project) + } + + @Test func ignoredFoldersAtAnyDepthAreDropped() { + #expect(classify("/p/node_modules/x/y.js") == nil) + #expect(classify("/p/packages/web/dist/app.js") == nil) + #expect(classify("/p/.helder/recent.json") == nil) + #expect(classify("/p") == nil) + #expect(classify("/elsewhere/a.ts") == nil) + } + + @Test func frameworkCachesAndExcludedGlobsAreDropped() { + #expect(classify("/p/storage/framework/cache/data/x") == nil) + #expect(classify("/p/bootstrap/cache/services.php") == nil) + #expect(classify("/p/storage/logs/laravel.log") == .project) + #expect(classify("/p/storage/logs/laravel.log", exclude: ["storage/logs"]) == nil) + } + + @Test func theConfigFileIsAConfigEvent() { + #expect(classify("/p/.helder/config.json") == .config) + #expect(classify("/p/.helder/config.default.json") == nil) + } + + @Test func onlyTheGitStateEntriesAreGitEvents() { + #expect(classify("/p/.git/HEAD") == .git) + #expect(classify("/p/.git/index") == .git) + #expect(classify("/p/.git/refs/heads/feature/x") == .git) + #expect(classify("/p/.git/refs/remotes/origin/main") == .git) + #expect(classify("/p/.git/logs/HEAD") == .git) + #expect(classify("/p/.git/MERGE_HEAD") == .git) + #expect(classify("/p/.git/objects/ab/cdef") == nil) + #expect(classify("/p/.git/index.lock") == nil) + #expect(classify("/p/.git/refs/tags/v1") == nil) + } + + @Test func aWorktreeGitDirectoryOutsideTheRootIsWatchedToo() { + #expect(classify("/repo/.git/worktrees/wt/HEAD", gitDirectory: "/repo/.git/worktrees/wt") == .git) + #expect(classify("/p/.git", gitDirectory: "/repo/.git/worktrees/wt") == nil) + } + + @Test func aDroppedEventBatchRescansTheProject() { + let flags = FSEventStreamEventFlags(kFSEventStreamEventFlagMustScanSubDirs) + #expect(EventRouter.classify(path: "/p/node_modules", root: root, gitDirectory: git, flags: flags) == .project) + } + + @Test func realPathResolvesTheTempSymlinkEvenForAMissingFile() { + #expect(EventRouter.realPath("/var/nonexistent-helder-file") == "/private/var/nonexistent-helder-file") + #expect(EventRouter.realPath("/tmp") == "/private/tmp") + } +} diff --git a/Tests/HelderServicesTests/Files/FileServiceSafetyTests.swift b/Tests/HelderServicesTests/Files/FileServiceSafetyTests.swift new file mode 100644 index 0000000..54db6b5 --- /dev/null +++ b/Tests/HelderServicesTests/Files/FileServiceSafetyTests.swift @@ -0,0 +1,120 @@ +import Foundation +import HelderCore +import HelderServices +import Testing + +/// Saves that must not lose data, and paths that must not leave the project through a symlink. +@Suite struct FileServiceSafetyTests { + private func service(_ root: URL) -> FileService { + FileService(root: root, search: NoRipgrepSearch()) + } + + private func permissions(_ url: URL) throws -> Int { + try (FileManager.default.attributesOfItem(atPath: url.path)[.posixPermissions] as? NSNumber)?.intValue ?? -1 + } + + // MARK: Saving + + @Test func aSaveKeepsTheFilePermissions() async throws { + let dir = try TempDirectory() + try dir.write("run.sh", "echo old\n") + try FileManager.default.setAttributes([.posixPermissions: 0o750], ofItemAtPath: dir.url("run.sh").path) + try await service(dir.root).write("run.sh", contents: "echo new\n") + #expect(try dir.read("run.sh") == "echo new\n") + #expect(try permissions(dir.url("run.sh")) == 0o750) + } + + @Test func aSaveThroughASymlinkWritesTheTargetAndKeepsTheLink() async throws { + let dir = try TempDirectory() + try dir.write("real/config.php", "old\n") + try FileManager.default.createSymbolicLink(atPath: dir.url("config.php").path, withDestinationPath: "real/config.php") + try await service(dir.root).write("config.php", contents: "new\n") + #expect(try dir.read("real/config.php") == "new\n") + #expect(try FileManager.default.destinationOfSymbolicLink(atPath: dir.url("config.php").path) == "real/config.php") + } + + @Test func aSaveReplacesTheFileInOneStepAndLeavesNoTempFileBehind() async throws { + let dir = try TempDirectory() + try dir.write("a.txt", "old\n") + let before = try FileManager.default.attributesOfItem(atPath: dir.url("a.txt").path)[.systemFileNumber] as? NSNumber + try await service(dir.root).write("a.txt", contents: "new\n") + let after = try FileManager.default.attributesOfItem(atPath: dir.url("a.txt").path)[.systemFileNumber] as? NSNumber + #expect(before != after) + #expect(try FileManager.default.contentsOfDirectory(atPath: dir.root.path) == ["a.txt"]) + } + + @Test func aSaveOfANewFileCreatesIt() async throws { + let dir = try TempDirectory() + try await service(dir.root).write("fresh.txt", contents: "x\n") + #expect(try dir.read("fresh.txt") == "x\n") + } + + // MARK: Symlinks out of the project + + /// A project whose `link` folder is a symlink to a folder outside it holding `outside.txt`. + private func linkedProject() throws -> (project: TempDirectory, outside: TempDirectory) { + let project = try TempDirectory() + let outside = try TempDirectory() + try outside.write("outside.txt", "keep\n") + try FileManager.default.createSymbolicLink(at: project.url("link"), withDestinationURL: outside.root) + return (project, outside) + } + + @Test func deleteThroughASymlinkedFolderIsRefused() async throws { + let (project, outside) = try linkedProject() + await #expect(throws: FileServiceError.outsideProject) { try await service(project.root).delete("link/outside.txt") } + #expect(outside.exists("outside.txt")) + } + + @Test func renameThroughASymlinkedFolderIsRefused() async throws { + let (project, outside) = try linkedProject() + await #expect(throws: FileServiceError.outsideProject) { _ = try await service(project.root).rename("link/outside.txt", to: "moved.txt") } + #expect(outside.exists("outside.txt")) + #expect(!outside.exists("moved.txt")) + } + + @Test func creatingThroughASymlinkedFolderIsRefused() async throws { + let (project, outside) = try linkedProject() + let files = service(project.root) + await #expect(throws: FileServiceError.outsideProject) { try await files.createFile("link/new.txt") } + await #expect(throws: FileServiceError.outsideProject) { try await files.createDirectory("link/sub") } + await #expect(throws: FileServiceError.outsideProject) { try await files.write("link/new.txt", contents: "x") } + #expect(!outside.exists("new.txt")) + #expect(!outside.exists("sub")) + } + + @Test func editingAnExistingFileThroughASymlinkIsAllowed() async throws { + let (project, outside) = try linkedProject() + try await service(project.root).write("link/outside.txt", contents: "edited\n") + #expect(try outside.read("outside.txt") == "edited\n") + } + + @Test func deletingTheSymlinkItselfRemovesOnlyTheLink() async throws { + let (project, outside) = try linkedProject() + try await service(project.root).delete("link") + #expect(!project.exists("link")) + #expect(outside.exists("outside.txt")) + } + + // MARK: Case-only renames + + @Test func aCaseOnlyRenameOnACaseSensitiveVolumeNeverClobbersAnotherFile() async throws { + let volume = try CaseSensitiveVolume() + let root = volume.root.appendingPathComponent("project") + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + try Data("lower\n".utf8).write(to: root.appendingPathComponent("readme.md")) + try Data("upper\n".utf8).write(to: root.appendingPathComponent("README.md")) + await #expect(throws: FileServiceError.alreadyExists("README.md")) { _ = try await service(root).rename("readme.md", to: "README.md") } + #expect(try String(contentsOf: root.appendingPathComponent("README.md"), encoding: .utf8) == "upper\n") + #expect(try String(contentsOf: root.appendingPathComponent("readme.md"), encoding: .utf8) == "lower\n") + } + + @Test func aCaseOnlyRenameOnACaseSensitiveVolumeStillWorksWhenTheNameIsFree() async throws { + let volume = try CaseSensitiveVolume() + let root = volume.root.appendingPathComponent("project") + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + try Data("x\n".utf8).write(to: root.appendingPathComponent("notes.md")) + #expect(try await service(root).rename("notes.md", to: "Notes.md") == "Notes.md") + #expect(try FileManager.default.contentsOfDirectory(atPath: root.path) == ["Notes.md"]) + } +} diff --git a/Tests/HelderServicesTests/Files/FileServiceTests.swift b/Tests/HelderServicesTests/Files/FileServiceTests.swift new file mode 100644 index 0000000..cb33e50 --- /dev/null +++ b/Tests/HelderServicesTests/Files/FileServiceTests.swift @@ -0,0 +1,303 @@ +import Foundation +import HelderCore +import HelderServices +import Testing + +/// The tree and folder listings, through the walk (no ripgrep) and through ripgrep. +@Suite struct FileServiceTreeTests { + /// src/a.ts, README.md and a binary logo, plus node_modules and .git that must stay hidden. + private func fixture() throws -> TempDirectory { + let dir = try TempDirectory() + try dir.write("src/a.ts", "export const a = 1\n") + try dir.write("README.md", "# hi\n") + try dir.write("node_modules/pkg/index.js", "module.exports = 1\n") + try dir.write(".git/HEAD", "ref: refs/heads/main\n") + try dir.write("logo.bin", Data([0x00, 0x01, 0x02, 0x00, 0x99])) + return dir + } + + private func walkService(_ dir: TempDirectory) -> FileService { + FileService(root: dir.root, search: NoRipgrepSearch()) + } + + private func ripgrepService(_ dir: TempDirectory) -> FileService { + let search = RipgrepSearchService(root: dir.root, config: FixedConfig(), locator: Ripgrep.locator, environment: [:]) + return FileService(root: dir.root, search: search) + } + + private func names(_ nodes: [FileNode]?) -> [String] { + (nodes ?? []).map(\.name) + } + + @Test func theWalkListsFoldersBeforeFilesAndSkipsIgnoredFolders() async throws { + let dir = try fixture() + let tree = await walkService(dir).tree() + #expect(tree.name == dir.root.lastPathComponent) + #expect(tree.path == "") + #expect(names(tree.children) == ["src", "logo.bin", "README.md"]) + #expect(tree.children?.first?.children == [FileNode(name: "a.ts", kind: .file, path: "src/a.ts")]) + } + + @Test func theWalkSortsNamesCaseInsensitively() async throws { + let dir = try TempDirectory() + for name in ["b.txt", "A.txt", "c.txt", "Zeta", "alpha"] { + if name.hasSuffix(".txt") { try dir.write(name, "") } else { try dir.mkdir(name) } + } + #expect(names(await walkService(dir).tree().children) == ["alpha", "Zeta", "A.txt", "b.txt", "c.txt"]) + } + + @Test func theWalkShowsEmptyFoldersAndDotfiles() async throws { + let dir = try fixture() + try dir.mkdir("empty") + try dir.write(".env", "APP_NAME=x\n") + let tree = await walkService(dir).tree() + #expect(names(tree.children) == ["empty", "src", ".env", "logo.bin", "README.md"]) + #expect(tree.children?.first == FileNode(name: "empty", kind: .directory, path: "empty", children: [])) + } + + @Test func theWalkStopsAtTheDepthLimit() async throws { + let dir = try TempDirectory() + let deep = (0...FileLimits.maxWalkDepth + 2).map { "d\($0)" }.joined(separator: "/") + try dir.write(deep + "/leaf.txt", "x") + var node: FileNode? = await walkService(dir).tree() + var depth = 0 + while let next = node?.children?.first { + node = next + depth += 1 + } + #expect(depth == FileLimits.maxWalkDepth + 1) + } + + @Test(.enabled(if: Ripgrep.isPresent)) + func theRipgrepTreeAddsTheEmptyFoldersRipgrepCannotList() async throws { + let dir = try fixture() + try dir.mkdir("empty") + try dir.mkdir("src/nested/deep") + let tree = await ripgrepService(dir).tree() + #expect(names(tree.children) == ["empty", "src", "logo.bin", "README.md"]) + let src = FileTree.find("src", in: tree) + #expect(names(src?.children) == ["nested", "a.ts"]) + #expect(names(FileTree.find("src/nested", in: tree)?.children) == ["deep"]) + } + + @Test(.enabled(if: Ripgrep.isPresent)) + func theRipgrepTreeShowsGitignoredFilesByDefault() async throws { + let repo = try TempGitRepo() + try repo.write(".gitignore", "secret.txt\n") + try repo.write("secret.txt", "shh") + let search = RipgrepSearchService(root: repo.root, config: FixedConfig(), locator: Ripgrep.locator, environment: [:]) + let tree = await FileService(root: repo.root, search: search).tree() + #expect(names(tree.children) == [".gitignore", "secret.txt"]) + } + + @Test func childrenOfTheRootAndOfASubfolder() async throws { + let dir = try fixture() + let service = walkService(dir) + #expect(names(await service.children(of: "")) == ["src", "logo.bin", "README.md"]) + #expect(await service.children(of: "src") == [FileNode(name: "a.ts", kind: .file, path: "src/a.ts")]) + } + + @Test func childrenAreReadFreshOnEveryCall() async throws { + let dir = try fixture() + let service = walkService(dir) + _ = await service.children(of: "src") + try dir.write("src/b.ts", "export const b = 2\n") + try FileManager.default.removeItem(at: dir.url("src/a.ts")) + try dir.mkdir("src/fresh") + #expect(await service.children(of: "src") == [ + FileNode(name: "fresh", kind: .directory, path: "src/fresh", children: []), + FileNode(name: "b.ts", kind: .file, path: "src/b.ts"), + ]) + } + + @Test func childrenOutsideTheProjectAreEmpty() async throws { + let dir = try fixture() + #expect(await walkService(dir).children(of: "../").isEmpty) + } + + @Test(.enabled(if: Ripgrep.isPresent)) + func ripgrepChildrenIncludeAFreshEmptyFolder() async throws { + let dir = try fixture() + try dir.mkdir("src/fresh") + let service = ripgrepService(dir) + #expect(await service.children(of: "src") == [ + FileNode(name: "fresh", kind: .directory, path: "src/fresh", children: []), + FileNode(name: "a.ts", kind: .file, path: "src/a.ts"), + ]) + #expect(!names(await service.children(of: "")).contains("node_modules")) + } + + @Test func emptyDirectoriesAreFoldersWithoutAnyFileBelow() async throws { + let dir = try fixture() + try dir.mkdir("empty") + try dir.mkdir("src/nested/deep") + try dir.mkdir("node_modules/also-empty") + let service = walkService(dir) + #expect(Set(await service.emptyDirectories()) == ["empty", "src/nested", "src/nested/deep"]) + #expect(Set(await service.emptyDirectories(under: "src")) == ["src/nested", "src/nested/deep"]) + } + + @Test func aFolderHoldingOnlyAnIgnoredFolderCountsAsEmpty() async throws { + let dir = try TempDirectory() + try dir.write("app/node_modules/x.js", "x") + #expect(await walkService(dir).emptyDirectories() == ["app"]) + } +} + +/// Reading, writing, creating, renaming and deleting single entries. +@Suite struct FileServiceEntryTests { + private func service(_ dir: TempDirectory) -> FileService { + FileService(root: dir.root, search: NoRipgrepSearch()) + } + + @Test func writeThenReadRoundTrips() async throws { + let dir = try TempDirectory() + let files = service(dir) + try await files.write("note.txt", contents: "hello world\n") + #expect(try await files.read("note.txt") == "hello world\n") + } + + @Test func aBinaryFileReadsAsEmpty() async throws { + let dir = try TempDirectory() + try dir.write("logo.bin", Data([0x89, 0x00, 0x01])) + #expect(try await service(dir).read("logo.bin") == "") + } + + @Test func readTextTellsAnEmptyFileFromABinaryOne() async throws { + let dir = try TempDirectory() + try dir.write("empty.txt", "") + try dir.write("logo.bin", Data([0x89, 0x00, 0x01])) + try dir.write("note.txt", "hello\n") + let files = service(dir) + #expect(try await files.readText("empty.txt") == .text("")) + #expect(try await files.readText("logo.bin") == .binary) + #expect(try await files.readText("note.txt") == .text("hello\n")) + } + + @Test func aNulByteAfterTheFirst8000BytesStillReadsAsText() async throws { + let dir = try TempDirectory() + try dir.write("long.txt", Data(repeating: 0x61, count: 8000) + Data([0x00])) + #expect(try await service(dir).readText("long.txt") == .text(String(repeating: "a", count: 8000) + "\0")) + } + + @Test func readingOutsideTheProjectThrows() async throws { + let dir = try TempDirectory() + await #expect(throws: FileServiceError.outsideProject) { try await service(dir).read("../etc/passwd") } + } + + @Test func createFileMakesAnEmptyFileAndItsFolders() async throws { + let dir = try TempDirectory() + try await service(dir).createFile("src/new/fresh.ts") + #expect(try dir.read("src/new/fresh.ts") == "") + } + + @Test func createFileRefusesToOverwrite() async throws { + let dir = try TempDirectory() + try dir.write("keep.txt", "precious\n") + await #expect(throws: FileServiceError.alreadyExists("keep.txt")) { try await service(dir).createFile("keep.txt") } + #expect(try dir.read("keep.txt") == "precious\n") + } + + @Test func createFileRefusesTheRootAndPathsOutsideIt() async throws { + let dir = try TempDirectory() + let files = service(dir) + await #expect(throws: FileServiceError.outsideProject) { try await files.createFile("../escape.txt") } + await #expect(throws: FileServiceError.outsideProject) { try await files.createFile("") } + #expect(!FileManager.default.fileExists(atPath: dir.root.deletingLastPathComponent().appendingPathComponent("escape.txt").path)) + } + + @Test func createDirectoryMakesNestedFolders() async throws { + let dir = try TempDirectory() + try await service(dir).createDirectory("a/b/c") + var isDirectory: ObjCBool = false + #expect(FileManager.default.fileExists(atPath: dir.url("a/b/c").path, isDirectory: &isDirectory) && isDirectory.boolValue) + } + + @Test func createDirectoryRefusesATakenName() async throws { + let dir = try TempDirectory() + try dir.mkdir("taken") + try dir.write("file", "") + let files = service(dir) + await #expect(throws: FileServiceError.alreadyExists("taken")) { try await files.createDirectory("taken") } + await #expect(throws: FileServiceError.alreadyExists("file")) { try await files.createDirectory("file") } + await #expect(throws: FileServiceError.outsideProject) { try await files.createDirectory("../out") } + } + + @Test func renameMovesAFileWithinItsFolder() async throws { + let dir = try TempDirectory() + try dir.write("src/old.ts", "x\n") + #expect(try await service(dir).rename("src/old.ts", to: "new.ts") == "src/new.ts") + #expect(try dir.read("src/new.ts") == "x\n") + #expect(!dir.exists("src/old.ts")) + } + + @Test func renameMovesAFolderWithEverythingInside() async throws { + let dir = try TempDirectory() + try dir.write("old/a.ts", "a\n") + #expect(try await service(dir).rename("old", to: "new") == "new") + #expect(try dir.read("new/a.ts") == "a\n") + } + + @Test func renameCanChangeOnlyTheCase() async throws { + let dir = try TempDirectory() + try dir.write("notes.md", "hi\n") + #expect(try await service(dir).rename("notes.md", to: "Notes.md") == "Notes.md") + #expect(try FileManager.default.contentsOfDirectory(atPath: dir.root.path) == ["Notes.md"]) + } + + @Test func renameToTheSameNameIsANoOp() async throws { + let dir = try TempDirectory() + try dir.write("a.txt", "a\n") + #expect(try await service(dir).rename("a.txt", to: " a.txt/ ") == "a.txt") + } + + @Test func renameRefusesATakenName() async throws { + let dir = try TempDirectory() + try dir.write("a.txt", "a\n") + try dir.write("b.txt", "b\n") + await #expect(throws: FileServiceError.alreadyExists("b.txt")) { try await service(dir).rename("a.txt", to: "b.txt") } + #expect(try dir.read("b.txt") == "b\n") + #expect(try dir.read("a.txt") == "a\n") + } + + @Test(arguments: ["sub/a.txt", "../a.txt", " ", "..", "."]) + func renameRefusesAPathShapedOrEmptyName(_ name: String) async throws { + let dir = try TempDirectory() + try dir.mkdir("sub") + try dir.write("a.txt", "a\n") + await #expect(throws: FileServiceError.invalidName(name)) { try await service(dir).rename("a.txt", to: name) } + #expect(try dir.read("a.txt") == "a\n") + } + + @Test func renameRefusesTheRootAndEscapes() async throws { + let dir = try TempDirectory() + let files = service(dir) + await #expect(throws: FileServiceError.outsideProject) { _ = try await files.rename("", to: "x") } + await #expect(throws: FileServiceError.outsideProject) { _ = try await files.rename("../x", to: "y") } + } + + @Test func renameOfAMissingEntryThrows() async throws { + let dir = try TempDirectory() + await #expect(throws: (any Error).self) { _ = try await service(dir).rename("missing.txt", to: "other.txt") } + } + + @Test func deleteRemovesAFolderButNeverTheRoot() async throws { + let dir = try TempDirectory() + try dir.write("folder/a.txt", "a") + let files = service(dir) + try await files.delete("folder") + #expect(!dir.exists("folder")) + await #expect(throws: FileServiceError.outsideProject) { try await files.delete("") } + #expect(FileManager.default.fileExists(atPath: dir.root.path)) + } + + @Test func readImageReturnsBytesOnlyForImages() async throws { + let dir = try TempDirectory() + try dir.write("pic.png", Data([0x89, 0x50, 0x4E, 0x47])) + try dir.write("notes.txt", "text") + let files = service(dir) + #expect(await files.readImage("pic.png") == Data([0x89, 0x50, 0x4E, 0x47])) + #expect(await files.readImage("notes.txt") == nil) + #expect(await files.readImage("missing.png") == nil) + } +} diff --git a/Tests/HelderServicesTests/Git/GitServiceTests.swift b/Tests/HelderServicesTests/Git/GitServiceTests.swift new file mode 100644 index 0000000..d7b2813 --- /dev/null +++ b/Tests/HelderServicesTests/Git/GitServiceTests.swift @@ -0,0 +1,536 @@ +import Foundation +import HelderCore +@testable import HelderServices +import Testing + +@Suite struct GitServiceLoadTests { + /// A repository with `a.txt` committed as three lines. + private func repo() throws -> TempGitRepo { + let repo = try TempGitRepo() + try repo.commit(["a.txt": "1\n2\n3\n"], message: "init") + return repo + } + + private func rows(_ snapshot: GitSnapshot?, _ path: String) -> [GitFileChange] { + snapshot?.changes.filter { $0.path == path } ?? [] + } + + @Test func aFolderOutsideGitLoadsAsNil() async throws { + let dir = try TempDirectory() + #expect(try await GitService(root: dir.root).load() == nil) + } + + @Test func aModifiedFileCarriesHeadAndDiskText() async throws { + let repo = try repo() + try repo.write("a.txt", "1\nX\n3\n") + let snapshot = try #require(try await GitService(root: repo.root).load()) + #expect(snapshot.branch == "main") + #expect(rows(snapshot, "a.txt") == [GitFileChange(path: "a.txt", status: .modified, staged: false, original: "1\n2\n3\n", updated: "1\nX\n3\n")]) + } + + @Test func anUntrackedFileIsAnUnstagedAddition() async throws { + let repo = try repo() + try repo.write("new.txt", "fresh\n") + let snapshot = try await GitService(root: repo.root).load() + #expect(rows(snapshot, "new.txt") == [GitFileChange(path: "new.txt", status: .added, staged: false, original: "", updated: "fresh\n")]) + } + + @Test func aStagedFileHasOneStagedRow() async throws { + let repo = try repo() + try repo.write("a.txt", "1\n2\n3\n4\n") + let service = GitService(root: repo.root) + try await service.stage(["a.txt"]) + let snapshot = try await service.load() + #expect(rows(snapshot, "a.txt") == [GitFileChange(path: "a.txt", status: .modified, staged: true, original: "1\n2\n3\n", updated: "1\n2\n3\n4\n")]) + } + + @Test func aFileStagedThenEditedHasTwoRowsEachWithItsOwnPair() async throws { + let repo = try repo() + let service = GitService(root: repo.root) + try repo.write("a.txt", "1\nSTAGED\n3\n") + try await service.stage(["a.txt"]) + try repo.write("a.txt", "1\nSTAGED\n3\n4\n") + let snapshot = try await service.load() + #expect(rows(snapshot, "a.txt") == [ + GitFileChange(path: "a.txt", status: .modified, staged: true, original: "1\n2\n3\n", updated: "1\nSTAGED\n3\n"), + GitFileChange(path: "a.txt", status: .modified, staged: false, original: "1\nSTAGED\n3\n", updated: "1\nSTAGED\n3\n4\n"), + ]) + } + + @Test func aStagedNewFileEditedAgainIsAnAdditionPlusAModification() async throws { + let repo = try repo() + let service = GitService(root: repo.root) + try repo.write("fresh.txt", "one\n") + try await service.stage(["fresh.txt"]) + try repo.write("fresh.txt", "one\ntwo\n") + let snapshot = try await service.load() + #expect(rows(snapshot, "fresh.txt") == [ + GitFileChange(path: "fresh.txt", status: .added, staged: true, original: "", updated: "one\n"), + GitFileChange(path: "fresh.txt", status: .modified, staged: false, original: "one\n", updated: "one\ntwo\n"), + ]) + } + + @Test func aDeletedFileHasNoDiskText() async throws { + let repo = try repo() + try FileManager.default.removeItem(at: repo.root.appendingPathComponent("a.txt")) + let snapshot = try await GitService(root: repo.root).load() + #expect(rows(snapshot, "a.txt") == [GitFileChange(path: "a.txt", status: .deleted, staged: false, original: "1\n2\n3\n", updated: "")]) + } + + @Test func aStagedRenameIsOneRowUnderTheNewPath() async throws { + let repo = try repo() + try repo.run("mv", "a.txt", "b.txt") + let snapshot = try #require(try await GitService(root: repo.root).load()) + #expect(snapshot.changes.map(\.path) == ["b.txt"]) + #expect(snapshot.changes.first?.status == .renamed) + #expect(snapshot.changes.first?.staged == true) + } + + @Test func aBinaryFileReadsAsEmptyText() async throws { + let repo = try repo() + try Data([0x00, 0x01, 0x02]).write(to: repo.root.appendingPathComponent("logo.bin")) + let snapshot = try await GitService(root: repo.root).load() + #expect(rows(snapshot, "logo.bin").first?.updated == "") + } + + @Test func aheadCountsCommitsTheRemoteLacks() async throws { + let remote = try TempGitRepo(bare: true) + let repo = try repo() + try repo.run("remote", "add", "origin", remote.root.path) + try repo.run("push", "-q", "-u", "origin", "main") + try repo.commit(["b.txt": "b\n"], message: "second") + let snapshot = try #require(try await GitService(root: repo.root).load()) + #expect(snapshot.ahead == 1) + #expect(snapshot.canPush) + } + + @Test func aWorktreeWithAGitFileLoads() async throws { + let repo = try repo() + let worktree = repo.root.deletingLastPathComponent().appendingPathComponent("helder-wt-\(UUID().uuidString)") + defer { try? FileManager.default.removeItem(at: worktree) } + try repo.run("worktree", "add", "-q", "-b", "side", worktree.path) + try Data("changed\n".utf8).write(to: worktree.appendingPathComponent("a.txt")) + let snapshot = try #require(try await GitService(root: worktree).load()) + #expect(snapshot.branch == "side") + #expect(snapshot.changes.map(\.path) == ["a.txt"]) + } + + @Test func aFailingStatusIsRetriedThenThrowsWithGitsStderr() async throws { + let runner = ScriptedRunner { call in + if call.arguments.first == "rev-parse" { return ProcessResult(exitCode: 0, stdout: "true\n", stderr: "") } + return ProcessResult(exitCode: 128, stdout: "", stderr: "fatal: Unable to create '.git/index.lock': File exists.\n") + } + let service = GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner, statusAttempts: 3, statusRetryDelay: 0.01) + await #expect(throws: GitError.commandFailed(arguments: Porcelain.statusArguments, exitCode: 128, + stderr: "fatal: Unable to create '.git/index.lock': File exists.")) { + try await service.load() + } + #expect(runner.calls.filter { $0.arguments == Porcelain.statusArguments }.count == 3) + #expect(runner.calls.last?.environment?["GIT_OPTIONAL_LOCKS"] == "0") + } + + @Test func overlappingLoadsShareOneReadPlusOneTrailingRead() async throws { + let gate = Gate() + let runner = ScriptedRunner { call in + if call.arguments.first == "rev-parse" { + await gate.wait() + return ProcessResult(exitCode: 0, stdout: "true\n", stderr: "") + } + return ProcessResult(exitCode: 1, stdout: "", stderr: "stop here") + } + let service = GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner, statusAttempts: 1) + let first = Task { try? await service.load() } + #expect(await eventually { !runner.calls.isEmpty }) + let later = (0..<5).map { _ in Task { _ = try? await service.load() } } + #expect(await eventuallyAsync { await service.coalescedLoads == 5 }) + await gate.open() + _ = await first.value + for task in later { await task.value } + #expect(runner.calls.filter { $0.arguments.first == "rev-parse" }.count == 2) + } + + @Test func anUntrackedFileOverTheSizeCapLoadsWithoutText() async throws { + let repo = try repo() + try repo.write("dump.sql", String(repeating: "insert;\n", count: 200)) + let snapshot = try await GitService(root: repo.root, maxDiffBytes: 1000).load() + #expect(rows(snapshot, "dump.sql") == [GitFileChange(path: "dump.sql", status: .added, staged: false, original: "", updated: "", + isTooBig: true)]) + } + + @Test func aCommittedFileOverTheSizeCapLoadsWithoutTextOnEitherSide() async throws { + let repo = try repo() + try repo.commit(["big.txt": String(repeating: "line\n", count: 300)]) + try repo.write("big.txt", String(repeating: "line\n", count: 301)) + let snapshot = try await GitService(root: repo.root, maxDiffBytes: 1000).load() + #expect(rows(snapshot, "big.txt") == [GitFileChange(path: "big.txt", status: .modified, staged: false, original: "", updated: "", + isTooBig: true)]) + } + + @Test func aFileThatOutgrewTheCapDropsTheSmallSideToo() async throws { + let repo = try repo() + try repo.commit(["grew.txt": "small\n"]) + try repo.write("grew.txt", String(repeating: "line\n", count: 300)) + let snapshot = try await GitService(root: repo.root, maxDiffBytes: 1000).load() + let row = try #require(rows(snapshot, "grew.txt").first) + #expect(row.isTooBig) + #expect(row.original.isEmpty && row.updated.isEmpty) + } + + @Test func aFileUnderTheSizeCapStillCarriesItsText() async throws { + let repo = try repo() + try repo.write("small.txt", "ok\n") + let snapshot = try await GitService(root: repo.root, maxDiffBytes: 1000).load() + #expect(rows(snapshot, "small.txt").first?.updated == "ok\n") + #expect(rows(snapshot, "small.txt").first?.isTooBig == false) + } + + @Test func aStagedRenameCarriesItsSourcePath() async throws { + let repo = try repo() + try repo.run("mv", "a.txt", "b.txt") + let snapshot = try #require(try await GitService(root: repo.root).load()) + #expect(snapshot.changes.first?.originalPath == "a.txt") + } +} + +@Suite struct GitServiceWriteTests { + private func repo() throws -> TempGitRepo { + let repo = try TempGitRepo() + try repo.commit(["a.txt": "1\n2\n3\n", "b.txt": "b\n"], message: "init") + return repo + } + + private func status(_ repo: TempGitRepo) throws -> String { + try repo.run("status", "--porcelain") + } + + @Test func stagingADeletionRemovesTheFileFromTheIndex() async throws { + let repo = try repo() + try FileManager.default.removeItem(at: repo.root.appendingPathComponent("a.txt")) + try await GitService(root: repo.root).stage(["a.txt"]) + #expect(try status(repo) == "D a.txt\n") + } + + @Test func stagingBothSidesOfAMoveRecordsARename() async throws { + let repo = try repo() + try FileManager.default.moveItem(at: repo.root.appendingPathComponent("a.txt"), to: repo.root.appendingPathComponent("c.txt")) + try await GitService(root: repo.root).stage(["a.txt", "c.txt"]) + #expect(try status(repo) == "R a.txt -> c.txt\n") + } + + @Test func unstagingADeletionKeepsTheFileDeletedOnDisk() async throws { + let repo = try repo() + try repo.run("rm", "-q", "a.txt") + try await GitService(root: repo.root).unstage(["a.txt"]) + #expect(try status(repo) == " D a.txt\n") + } + + @Test func unstagingARenameLeavesTheOldPathStagedAsDeleted() async throws { + let repo = try repo() + try repo.run("mv", "a.txt", "c.txt") + try await GitService(root: repo.root).unstage(["c.txt"]) + #expect(try status(repo) == "D a.txt\n?? c.txt\n") + } + + @Test func unstagingWorksInARepositoryWithoutCommits() async throws { + let repo = try TempGitRepo() + try repo.write("first.txt", "x\n") + let service = GitService(root: repo.root) + try await service.stage(["first.txt"]) + #expect(try status(repo) == "A first.txt\n") + try await service.unstage(["first.txt"]) + #expect(try status(repo) == "?? first.txt\n") + } + + @Test func stagingNothingRunsNoGit() async throws { + let runner = ScriptedRunner { _ in ProcessResult(exitCode: 0, stdout: "", stderr: "") } + let service = GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner) + try await service.stage([]) + try await service.unstage([]) + #expect(runner.calls.isEmpty) + } + + @Test func aFailedCommitThrowsWithGitsStderr() async throws { + let repo = try repo() + do { + try await GitService(root: repo.root).commit(message: "nothing") + Issue.record("commit with nothing staged should fail") + } catch let GitError.commandFailed(arguments, exitCode, _) { + #expect(arguments == ["commit", "-m", "nothing"]) + #expect(exitCode != 0) + } + } + + @Test func aFailedStageCarriesStderr() async throws { + let repo = try repo() + do { + try await GitService(root: repo.root).stage(["missing.txt"]) + Issue.record("staging a missing path should fail") + } catch let GitError.commandFailed(_, _, stderr) { + #expect(stderr.contains("missing.txt")) + } + } + + @Test func discardRevertsAModifiedFileToHead() async throws { + let repo = try repo() + try repo.write("a.txt", "1\nCHANGED\n3\n") + try await GitService(root: repo.root).discard(["a.txt"]) + #expect(try repo.read("a.txt") == "1\n2\n3\n") + #expect(try status(repo) == "") + } + + @Test func discardRevertsAFileStagedThenEdited() async throws { + let repo = try repo() + try repo.write("a.txt", "staged\n") + try repo.run("add", "a.txt") + try repo.write("a.txt", "edited again\n") + try await GitService(root: repo.root).discard(["a.txt"]) + #expect(try repo.read("a.txt") == "1\n2\n3\n") + #expect(try status(repo) == "") + } + + @Test func discardRemovesAnUntrackedFile() async throws { + let repo = try repo() + try repo.write("new.txt", "fresh\n") + try await GitService(root: repo.root).discard(["new.txt"]) + #expect(!FileManager.default.fileExists(atPath: repo.root.appendingPathComponent("new.txt").path)) + } + + @Test func discardUnstagesAndRemovesAStagedNewFile() async throws { + let repo = try repo() + try repo.write("staged-new.txt", "x\n") + try repo.run("add", "staged-new.txt") + try await GitService(root: repo.root).discard(["staged-new.txt"]) + #expect(!FileManager.default.fileExists(atPath: repo.root.appendingPathComponent("staged-new.txt").path)) + #expect(try status(repo) == "") + } + + @Test func discardRestoresADeletedFile() async throws { + let repo = try repo() + try FileManager.default.removeItem(at: repo.root.appendingPathComponent("a.txt")) + try await GitService(root: repo.root).discard(["a.txt"]) + #expect(try repo.read("a.txt") == "1\n2\n3\n") + } + + @Test func discardRestoresAStagedDeletion() async throws { + let repo = try repo() + try repo.run("rm", "-q", "a.txt") + try await GitService(root: repo.root).discard(["a.txt"]) + #expect(try repo.read("a.txt") == "1\n2\n3\n") + #expect(try status(repo) == "") + } + + @Test func discardHandlesSeveralPathsInOneCall() async throws { + let repo = try repo() + try repo.write("a.txt", "changed\n") + try repo.write("new.txt", "new\n") + try await GitService(root: repo.root).discard(["a.txt", "new.txt"]) + #expect(try status(repo) == "") + } + + @Test func discardNeverDeletesAFolderOrAnythingOutsideTheProject() async throws { + let repo = try repo() + let outside = repo.root.deletingLastPathComponent().appendingPathComponent("helder-outside-\(UUID().uuidString).txt") + try Data("keep\n".utf8).write(to: outside) + defer { try? FileManager.default.removeItem(at: outside) } + try repo.write("folder/inner.txt", "keep\n") + let service = GitService(root: repo.root) + try await service.discard(["folder", "../" + outside.lastPathComponent]) + #expect(FileManager.default.fileExists(atPath: outside.path)) + #expect(try repo.read("folder/inner.txt") == "keep\n") + } + + @Test func discardingAStagedRenameRestoresTheSourceAndRemovesTheTarget() async throws { + let repo = try repo() + try repo.run("mv", "a.txt", "c.txt") + try await GitService(root: repo.root).discard(["c.txt"]) + #expect(try repo.read("a.txt") == "1\n2\n3\n") + #expect(!FileManager.default.fileExists(atPath: repo.root.appendingPathComponent("c.txt").path)) + #expect(try status(repo) == "") + } + + @Test func discardingAStagedRenameEditedAfterwardsStillRestoresTheSource() async throws { + let repo = try repo() + try repo.run("mv", "a.txt", "c.txt") + try repo.write("c.txt", "edited\n") + try await GitService(root: repo.root).discard(["c.txt"]) + #expect(try repo.read("a.txt") == "1\n2\n3\n") + #expect(!FileManager.default.fileExists(atPath: repo.root.appendingPathComponent("c.txt").path)) + #expect(try status(repo) == "") + } + + @Test func contentsReadsTheHeadAndIndexCopies() async throws { + let repo = try repo() + try repo.write("a.txt", "staged\n") + try repo.run("add", "a.txt") + try repo.write("a.txt", "disk\n") + let service = GitService(root: repo.root) + #expect(await service.contents(of: "a.txt", at: .head) == "1\n2\n3\n") + #expect(await service.contents(of: "a.txt", at: .index) == "staged\n") + #expect(await service.contents(of: "nope.txt", at: .head) == "") + } + + @Test func isRepositoryAcceptsAWorktreeGitFile() async throws { + let repo = try repo() + let worktree = repo.root.deletingLastPathComponent().appendingPathComponent("helder-wt-\(UUID().uuidString)") + defer { try? FileManager.default.removeItem(at: worktree) } + try repo.run("worktree", "add", "-q", "-b", "side", worktree.path) + let service = GitService(root: worktree) + #expect(await service.isRepository()) + try Data("wt\n".utf8).write(to: worktree.appendingPathComponent("a.txt")) + try await service.discard(["a.txt"]) + #expect(try String(contentsOf: worktree.appendingPathComponent("a.txt"), encoding: .utf8) == "1\n2\n3\n") + } +} + +/// Names git would read as globs or options unless every pathspec is literal. +@Suite struct GitServiceLiteralPathTests { + private func repo() throws -> TempGitRepo { + let repo = try TempGitRepo() + try repo.commit([ + "pages/[id].vue": "id\n", "pages/i.vue": "i\n", "pages/d.vue": "d\n", + "a*.txt": "star\n", "ab.txt": "ab\n", "a?.txt": "q\n", "ac.txt": "ac\n", + "-dash.txt": "dash\n", "with space.txt": "space\n", + ], message: "init") + return repo + } + + private func status(_ repo: TempGitRepo) throws -> String { + try repo.run("status", "--porcelain") + } + + private func editAll(_ repo: TempGitRepo) throws { + for path in ["pages/[id].vue", "pages/i.vue", "pages/d.vue", "a*.txt", "ab.txt", "a?.txt", "ac.txt", "-dash.txt", "with space.txt"] { + try repo.write(path, "changed\n") + } + } + + @Test func discardTouchesOnlyTheNamedFile() async throws { + let repo = try repo() + try editAll(repo) + try await GitService(root: repo.root).discard(["pages/[id].vue", "a*.txt", "a?.txt", "-dash.txt", "with space.txt"]) + #expect(try repo.read("pages/[id].vue") == "id\n") + #expect(try repo.read("pages/i.vue") == "changed\n") + #expect(try repo.read("pages/d.vue") == "changed\n") + #expect(try repo.read("a*.txt") == "star\n") + #expect(try repo.read("ab.txt") == "changed\n") + #expect(try repo.read("ac.txt") == "changed\n") + #expect(try repo.read("-dash.txt") == "dash\n") + #expect(try repo.read("with space.txt") == "space\n") + } + + @Test func discardOfAnUntrackedGlobNameRemovesOnlyThatFile() async throws { + let repo = try repo() + try repo.write("new/[x].txt", "n\n") + try repo.write("new/x.txt", "keep\n") + try await GitService(root: repo.root).discard(["new/[x].txt"]) + #expect(!FileManager.default.fileExists(atPath: repo.root.appendingPathComponent("new/[x].txt").path)) + #expect(try repo.read("new/x.txt") == "keep\n") + } + + @Test func stageAndUnstageTouchOnlyTheNamedFile() async throws { + let repo = try repo() + try editAll(repo) + let service = GitService(root: repo.root) + try await service.stage(["pages/[id].vue", "a*.txt", "a?.txt", "-dash.txt", "with space.txt"]) + let staged = try repo.run("diff", "--cached", "--name-only") + #expect(staged == "-dash.txt\na*.txt\na?.txt\npages/[id].vue\nwith space.txt\n") + try await service.stage(["pages/i.vue", "ab.txt"]) + try await service.unstage(["pages/[id].vue", "a*.txt"]) + #expect(try repo.run("diff", "--cached", "--name-only") == "-dash.txt\na?.txt\nab.txt\npages/i.vue\nwith space.txt\n") + } + + @Test func contentsReadsANameWithGlobCharactersOrALeadingDash() async throws { + let repo = try repo() + let service = GitService(root: repo.root) + #expect(await service.contents(of: "pages/[id].vue", at: .head) == "id\n") + #expect(await service.contents(of: "-dash.txt", at: .head) == "dash\n") + #expect(await service.contents(of: "with space.txt", at: .index) == "space\n") + } + + @Test func everyGitCallRunsWithLiteralPathspecs() async throws { + let runner = ScriptedRunner { call in + if call.arguments.first == "rev-parse" { return ProcessResult(exitCode: 0, stdout: "true\n", stderr: "") } + return ProcessResult(exitCode: 0, stdout: "", stderr: "") + } + let service = GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner) + _ = try await service.load() + try await service.stage(["a"]) + try await service.unstage(["a"]) + try await service.discard(["a"]) + _ = await service.contents(of: "a", at: .head) + try await service.commit(message: "m") + _ = await service.push() + #expect(!runner.calls.isEmpty) + #expect(runner.calls.allSatisfy { $0.environment?["GIT_LITERAL_PATHSPECS"] == "1" }) + } +} + +@Suite struct GitServicePushTests { + /// A committed repository plus a bare remote it knows as `origin`. + private func repoWithRemote() throws -> (repo: TempGitRepo, remote: TempGitRepo) { + let remote = try TempGitRepo(bare: true) + let repo = try TempGitRepo() + try repo.commit(["a.txt": "a\n"], message: "init") + try repo.run("remote", "add", "origin", remote.root.path) + return (repo, remote) + } + + @Test func aFirstPushSetsTheUpstream() async throws { + let (repo, remote) = try repoWithRemote() + defer { withExtendedLifetime(remote) {} } + let result = await GitService(root: repo.root).push() + #expect(result.ok) + #expect(result.message.contains("main")) + #expect(try repo.run("rev-parse", "--abbrev-ref", "main@{upstream}") == "origin/main\n") + } + + @Test func aPushWithNothingNewReportsUpToDate() async throws { + let (repo, remote) = try repoWithRemote() + defer { withExtendedLifetime(remote) {} } + try repo.run("push", "-q", "-u", "origin", "main") + let result = await GitService(root: repo.root).push() + #expect(result == PushResult(ok: true, message: "Everything up-to-date")) + } + + @Test func aPushWithoutARemoteFailsWithGitsLastLine() async throws { + let repo = try TempGitRepo() + try repo.commit(["a.txt": "a\n"]) + let result = await GitService(root: repo.root).push() + #expect(!result.ok) + #expect(!result.message.isEmpty) + } + + @Test func pushTurnsOffCredentialPrompts() async throws { + let runner = ScriptedRunner { _ in ProcessResult(exitCode: 0, stdout: "", stderr: "Everything up-to-date\n") } + _ = await GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner).push() + #expect(runner.calls.first?.arguments == ["push"]) + #expect(runner.calls.first?.environment?["GIT_TERMINAL_PROMPT"] == "0") + } + + @Test func aPushWithoutUpstreamRetriesWithTheCurrentBranch() async throws { + let runner = ScriptedRunner { call in + switch call.arguments { + case ["push"]: + return ProcessResult(exitCode: 128, stdout: "", stderr: "fatal: The current branch feature has no upstream branch.\n") + case ["rev-parse", "--abbrev-ref", "HEAD"]: + return ProcessResult(exitCode: 0, stdout: "feature\n", stderr: "") + default: + return ProcessResult(exitCode: 0, stdout: "", stderr: " * [new branch] feature -> feature\n") + } + } + let result = await GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner).push() + #expect(runner.calls.map(\.arguments).last == ["push", "-u", "origin", "feature"]) + #expect(result == PushResult(ok: true, message: "* [new branch] feature -> feature")) + } + + @Test func aHangingPushGivesUpAfterTheTimeout() async throws { + let runner = ScriptedRunner { _ in + try await Task.sleep(nanoseconds: 30_000_000_000) + return ProcessResult(exitCode: 0, stdout: "", stderr: "") + } + let started = Date() + let result = await GitService(root: URL(fileURLWithPath: "/tmp"), runner: runner, pushTimeout: 0.2).push() + #expect(result == PushResult(ok: false, message: "push timed out")) + #expect(Date().timeIntervalSince(started) < 5) + } +} diff --git a/Tests/HelderServicesTests/Git/TempGitRepoTests.swift b/Tests/HelderServicesTests/Git/TempGitRepoTests.swift new file mode 100644 index 0000000..4c77201 --- /dev/null +++ b/Tests/HelderServicesTests/Git/TempGitRepoTests.swift @@ -0,0 +1,32 @@ +import Foundation +import HelderServices +import Testing + +@Suite struct TempGitRepoTests { + @Test func createsCommitsAndCleansUp() throws { + var repo: TempGitRepo? = try TempGitRepo() + let root = try #require(repo?.root) + try repo?.commit(["README.md": "hello\n"], message: "first") + try repo?.write("README.md", "hello\nworld\n") + let status = try repo?.run("status", "--porcelain") + #expect(status == " M README.md\n") + #expect(try repo?.run("log", "--format=%s") == "first\n") + repo = nil + #expect(!FileManager.default.fileExists(atPath: root.path)) + } + + @Test func gitServiceStagesAndCommits() async throws { + let repo = try TempGitRepo() + try repo.commit(["a.txt": "one\n"]) + try repo.write("a.txt", "two\n") + let service = GitService(root: repo.root) + #expect(await service.isRepository()) + try await service.stage(["a.txt"]) + #expect(try repo.run("status", "--porcelain") == "M a.txt\n") + try await service.unstage(["a.txt"]) + #expect(try repo.run("status", "--porcelain") == " M a.txt\n") + try await service.stage(["a.txt"]) + try await service.commit(message: "second") + #expect(try repo.run("log", "--format=%s") == "second\ncommit\n") + } +} diff --git a/Tests/HelderServicesTests/Logging/FileLoggerTests.swift b/Tests/HelderServicesTests/Logging/FileLoggerTests.swift new file mode 100644 index 0000000..8d6e09c --- /dev/null +++ b/Tests/HelderServicesTests/Logging/FileLoggerTests.swift @@ -0,0 +1,104 @@ +import Foundation +import HelderServices +import Testing + +@Suite struct FileLoggerTests { + private let noon = Date(timeIntervalSince1970: 1_784_109_600) + + private func read(_ dir: TempDirectory, _ name: String = "helder.log") throws -> String { + try dir.read(name) + } + + @Test func aLineHoldsTimestampPaddedLevelPidScopeAndMessage() { + let line = FileLogger.formatLine(level: .info, scope: "git", message: "loaded", pid: 42, date: noon) + #expect(line == "2026-07-15T10:00:00.000Z INFO 42 git loaded\n") + } + + @Test func continuationLinesAreIndentedSoTheyNeverLookLikeANewEntry() { + let line = FileLogger.formatLine(level: .warn, scope: "console", message: "line one\nline two\r\nline three", pid: 1, date: noon) + #expect(line == "2026-07-15T10:00:00.000Z WARN 1 console line one\n line two\n line three\n") + } + + @Test func writingCreatesTheFolderAndAppendsLines() throws { + let dir = try TempDirectory() + let logger = FileLogger(directory: dir.url("a/b")) + logger.write(level: .info, scope: "boot", message: "hello") + logger.write(level: .warn, scope: "boot", message: "careful") + let lines = try dir.read("a/b/helder.log").split(separator: "\n") + #expect(lines.count == 2) + #expect(lines[0].contains("INFO") && lines[0].hasSuffix("boot hello")) + #expect(lines[1].contains("WARN") && lines[1].hasSuffix("careful")) + #expect(logger.fileURL == dir.url("a/b/helder.log")) + } + + @Test func linesBelowTheFloorAreDropped() throws { + let dir = try TempDirectory() + let logger = FileLogger(directory: dir.root, minimumLevel: .warn) + logger.write(level: .debug, scope: "x", message: "debug line") + logger.write(level: .info, scope: "x", message: "info line") + logger.write(level: .error, scope: "x", message: "error line") + let out = try read(dir) + #expect(!out.contains("debug line")) + #expect(!out.contains("info line")) + #expect(out.contains("ERROR")) + } + + @Test func anUnwritableFolderIsSilentlyIgnored() throws { + let dir = try TempDirectory() + try dir.write("wall", "x") + let logger = FileLogger(directory: dir.url("wall/sub")) + logger.write(level: .error, scope: "x", message: "still fine") + #expect(!dir.exists("wall/sub/helder.log")) + } + + @Test func theFileRotatesPastTheCapAndKeepsWriting() throws { + let dir = try TempDirectory() + let logger = FileLogger(directory: dir.root) + let big = String(repeating: "x", count: 4000) + for _ in 0..<700 { logger.write(level: .info, scope: "bulk", message: big) } + #expect(dir.exists("helder.1.log")) + logger.write(level: .info, scope: "after", message: "still logging") + let live = try read(dir) + #expect(live.contains("still logging")) + #expect(live.utf8.count <= FileLogger.maxBytes) + } + + @Test func rotationKeepsAtMostThreeOldFiles() throws { + let dir = try TempDirectory() + let logger = FileLogger(directory: dir.root) + let big = String(repeating: "y", count: 100_000) + for _ in 0..<(21 * 5) { logger.write(level: .info, scope: "bulk", message: big) } + #expect(dir.exists("helder.3.log")) + #expect(!dir.exists("helder.4.log")) + } + + @Test func aLoggerPicksUpTheSizeOfAnExistingFile() throws { + let dir = try TempDirectory() + try dir.write("helder.log", String(repeating: "z", count: FileLogger.maxBytes - 10)) + FileLogger(directory: dir.root).write(level: .info, scope: "x", message: "tips it over") + #expect(dir.exists("helder.1.log")) + #expect(try read(dir).contains("tips it over")) + } + + @Test func concurrentWritersNeverInterleaveWithinALine() async throws { + let dir = try TempDirectory() + let logger = FileLogger(directory: dir.root) + await withTaskGroup(of: Void.self) { group in + for i in 0..<8 { + group.addTask { for j in 0..<50 { logger.write(level: .debug, scope: "t\(i)", message: "message \(j)") } } + } + } + let lines = try read(dir).split(separator: "\n") + #expect(lines.count == 400) + #expect(lines.allSatisfy { $0.contains(" DEBUG ") && $0.contains("message ") }) + } + + @Test func logForwardsToTheInstalledSink() throws { + let dir = try TempDirectory() + let logger = FileLogger(directory: dir.root) + Log.setSink(logger) + Log.info("sink-test-\(dir.root.lastPathComponent)", "forwarded") + Log.setSink(nil) + #expect(try read(dir).contains("forwarded")) + } +} diff --git a/Tests/HelderServicesTests/Process/ChildReaperTests.swift b/Tests/HelderServicesTests/Process/ChildReaperTests.swift new file mode 100644 index 0000000..fc66ce5 --- /dev/null +++ b/Tests/HelderServicesTests/Process/ChildReaperTests.swift @@ -0,0 +1,44 @@ +import Darwin +import Foundation +import HelderServices +import Testing + +/// Children spawned with `posix_spawn`, so nothing but the reaper ever waits on them. +@Suite struct ChildReaperTests { + private func spawn(_ arguments: [String]) throws -> pid_t { + var pid: pid_t = 0 + let argv: [UnsafeMutablePointer?] = arguments.map { strdup($0) } + [nil] + defer { argv.forEach { free($0) } } + let status = posix_spawn(&pid, arguments[0], nil, nil, argv, environ) + guard status == 0 else { throw POSIXError(POSIXErrorCode(rawValue: status) ?? .EIO) } + return pid + } + + /// True while the pid names a process, zombies included. + private func exists(_ pid: pid_t) -> Bool { + kill(pid, 0) == 0 || errno == EPERM + } + + @Test(.timeLimit(.minutes(1))) + func aTerminatedChildIsReapedInsteadOfLeftAsAZombie() async throws { + let pid = try spawn(["/bin/sleep", "30"]) + kill(pid, SIGTERM) + await ChildReaper.reap(pid, grace: 5) + #expect(!exists(pid)) + } + + @Test(.timeLimit(.minutes(1))) + func aChildThatIgnoresSigtermIsKilledAfterTheGracePeriod() async throws { + let pid = try spawn(["/bin/sh", "-c", "trap '' TERM; while :; do sleep 1; done"]) + kill(pid, SIGTERM) + let started = Date() + await ChildReaper.reap(pid, grace: 0.3) + #expect(!exists(pid)) + #expect(Date().timeIntervalSince(started) < 10) + } + + @Test func aPidThatIsNotOurChildIsLeftAlone() async throws { + await ChildReaper.reap(1, grace: 0.1) + #expect(exists(1)) + } +} diff --git a/Tests/HelderServicesTests/Process/ProcessRunnerTests.swift b/Tests/HelderServicesTests/Process/ProcessRunnerTests.swift new file mode 100644 index 0000000..9de09c6 --- /dev/null +++ b/Tests/HelderServicesTests/Process/ProcessRunnerTests.swift @@ -0,0 +1,65 @@ +import Foundation +import HelderServices +import Testing + +@Suite struct ProcessRunnerTests { + let runner = ProcessRunner() + + @Test func capturesStdoutAndExitCode() async throws { + let result = try await runner.run("echo", ["hello", "world"]) + #expect(result == ProcessResult(exitCode: 0, stdout: "hello world\n", stderr: "")) + #expect(result.succeeded) + } + + @Test func nonZeroExitIsAResultNotAnError() async throws { + let result = try await runner.run("sh", ["-c", "echo oops >&2; exit 3"]) + #expect(result.exitCode == 3) + #expect(result.stderr == "oops\n") + #expect(!result.succeeded) + } + + @Test func runsInTheGivenDirectory() async throws { + let dir = URL(fileURLWithPath: "/usr/lib") + let result = try await runner.run("pwd", [], in: dir) + #expect(result.stdout == "/usr/lib\n") + } + + @Test func passesTheEnvironment() async throws { + let result = try await runner.run("sh", arguments: ["-c", "printf %s \"$HELDER_TEST\""], in: nil, + environment: ["HELDER_TEST": "yes", "PATH": "/usr/bin:/bin"]) + #expect(result.stdout == "yes") + } + + @Test func stdinIsClosed() async throws { + let result = try await runner.run("cat", []) + #expect(result == ProcessResult(exitCode: 0, stdout: "", stderr: "")) + } + + @Test func largeOutputOnBothPipesDoesNotDeadlock() async throws { + let script = "i=0; while [ $i -lt 20000 ]; do echo line$i; echo err$i >&2; i=$((i+1)); done" + let result = try await runner.run("sh", ["-c", script]) + #expect(result.stdout.split(separator: "\n").count == 20000) + #expect(result.stderr.split(separator: "\n").count == 20000) + } + + @Test func unknownExecutableThrows() async { + await #expect(throws: ProcessRunnerError.executableNotFound("helder-no-such-tool")) { + try await runner.run("helder-no-such-tool", []) + } + } + + @Test func cancellationTerminatesTheChild() async throws { + let started = Date() + let task = Task { try await runner.run("sleep", ["10"]) } + try await Task.sleep(for: .milliseconds(200)) + task.cancel() + await #expect(throws: CancellationError.self) { try await task.value } + #expect(Date().timeIntervalSince(started) < 5) + } + + @Test func locatorFindsToolsOnThePath() { + #expect(ExecutableLocator.standard.locate("sh")?.path.hasSuffix("/sh") == true) + #expect(ExecutableLocator(directories: []).locate("sh") == nil) + #expect(ExecutableLocator(directories: []).locate("/bin/sh")?.path == "/bin/sh") + } +} diff --git a/Tests/HelderServicesTests/Project/ConfigServiceTests.swift b/Tests/HelderServicesTests/Project/ConfigServiceTests.swift new file mode 100644 index 0000000..dbea316 --- /dev/null +++ b/Tests/HelderServicesTests/Project/ConfigServiceTests.swift @@ -0,0 +1,49 @@ +import Foundation +import HelderCore +import HelderServices +import Testing + +@Suite struct ConfigServiceTests { + @Test func aFreshProjectGetsTheDefaultsFileAndTheDefaults() async throws { + let dir = try TempDirectory() + let config = await ConfigService(root: dir.root).resolve() + #expect(config == .defaults) + let written = try Data(contentsOf: dir.url(".helder/config.default.json")) + #expect(try JSONDecoder().decode(HelderConfig.self, from: written) == .defaults) + } + + @Test func aSparseConfigMergesOverTheDefaults() async throws { + let dir = try TempDirectory() + try dir.write(".helder/config.json", #"{"ai":{"command":"claude --model opus"},"editor":{"tabSize":2}}"#) + let config = await ConfigService(root: dir.root).resolve() + #expect(config.ai.command == "claude --model opus") + #expect(config.ai.autoLaunch) + #expect(config.editor.tabSize == 2) + #expect(!config.editor.autoSave) + #expect(config.git.confirmDiscard) + } + + @Test func theDefaultsFileIsRewrittenWithTheBuiltInValues() async throws { + let dir = try TempDirectory() + try dir.write(".helder/config.json", #"{"ai":{"command":"x"}}"#) + try dir.write(".helder/config.default.json", #"{"ai":{"command":"stale"}}"#) + _ = await ConfigService(root: dir.root).resolve() + let written = try JSONDecoder().decode(HelderConfig.self, from: Data(contentsOf: dir.url(".helder/config.default.json"))) + #expect(written.ai.command == "claude") + } + + @Test func currentReturnsTheLastResolvedConfig() async throws { + let dir = try TempDirectory() + let service = ConfigService(root: dir.root) + #expect(await service.current() == .defaults) + try dir.write(".helder/config.json", #"{"editor":{"tabSize":8}}"#) + await service.resolve() + #expect(await service.current().editor.tabSize == 8) + } + + @Test func anUnwritableProjectStillYieldsTheDefaults() async throws { + let dir = try TempDirectory() + try dir.write(".helder", "a file where the folder should be") + #expect(await ConfigService(root: dir.root).resolve() == .defaults) + } +} diff --git a/Tests/HelderServicesTests/Project/ProjectServicesTests.swift b/Tests/HelderServicesTests/Project/ProjectServicesTests.swift new file mode 100644 index 0000000..1331360 --- /dev/null +++ b/Tests/HelderServicesTests/Project/ProjectServicesTests.swift @@ -0,0 +1,46 @@ +import Foundation +import HelderCore +import HelderServices +import Testing + +@Suite struct ProjectServicesTests { + private func tempDir() throws -> URL { + let url = FileManager.default.temporaryDirectory.appendingPathComponent("helder-test-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) + return url + } + + @Test func configServiceWritesDefaultsAndReadsOverrides() async throws { + let root = try tempDir() + defer { try? FileManager.default.removeItem(at: root) } + let folder = root.appendingPathComponent(".helder") + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + try Data(#"{"editor":{"tabSize":2}}"#.utf8).write(to: folder.appendingPathComponent("config.json")) + + let config = await ConfigService(root: root).resolve() + #expect(config.editor.tabSize == 2) + #expect(FileManager.default.fileExists(atPath: folder.appendingPathComponent("config.default.json").path)) + #expect(try String(contentsOf: folder.appendingPathComponent(".gitignore"), encoding: .utf8) == HelderConfig.gitignoreBody) + } + + @Test func notesRoundTrip() async throws { + let root = try tempDir() + defer { try? FileManager.default.removeItem(at: root) } + let notes = NotesService(root: root) + #expect(await notes.read() == "") + try await notes.write("tell the agent\n") + #expect(await notes.read() == "tell the agent\n") + } + + @Test func recentProjectsAreNewestFirstAndDeduplicated() async throws { + let dir = try tempDir() + defer { try? FileManager.default.removeItem(at: dir) } + let a = try tempDir(), b = try tempDir() + defer { try? FileManager.default.removeItem(at: a); try? FileManager.default.removeItem(at: b) } + let store = RecentProjectsStore(fileURL: dir.appendingPathComponent("recent.json")) + await store.add(a.path) + await store.add(b.path) + await store.add(a.path) + #expect(await store.list().map(\.path) == [a.standardizedFileURL.path, b.standardizedFileURL.path]) + } +} diff --git a/Tests/HelderServicesTests/Search/ProjectScannerTests.swift b/Tests/HelderServicesTests/Search/ProjectScannerTests.swift new file mode 100644 index 0000000..3360175 --- /dev/null +++ b/Tests/HelderServicesTests/Search/ProjectScannerTests.swift @@ -0,0 +1,179 @@ +import Foundation +import HelderCore +@testable import HelderServices +import Testing + +@Suite struct ProjectScannerTests { + private let defaults = ScanFilter(base: IgnoreRules.ripgrepBaseIgnore, files: HelderConfig.Files()) + + private func walk(_ dir: TempDirectory) -> WalkScanner { + WalkScanner(root: dir.root, runner: ProcessRunner()) + } + + // MARK: ripgrep arguments + + @Test func contentSearchPassesTheOldAppsRipgrepFlags() { + let query = LineQuery(pattern: .smartCaseLiteral("needle"), maxPerFile: 50, maxColumns: 2000) + let args = RipgrepScanner.searchArguments(query, filter: defaults, target: "/p") + #expect(Array(args.prefix(9)) == ["--json", "--fixed-strings", "--smart-case", "--hidden", "--max-count", "50", "--max-columns", "2000", "--glob"]) + #expect(args.suffix(4) == ["-e", "needle", "--", "/p"]) + #expect(args.contains("!node_modules")) + #expect(args.contains("--no-ignore")) + } + + @Test func aRegexSearchOverPHPFilesIsCaseSensitive() { + let filter = ScanFilter(base: IgnoreRules.symbolDeclarationIgnore, files: HelderConfig.Files()) + let args = RipgrepScanner.searchArguments(LineQuery(pattern: .regex("^class"), fileExtension: "php"), filter: filter, target: "/p") + #expect(Array(args.prefix(4)) == ["--json", "--hidden", "--glob", "*.php"]) + #expect(!args.contains("--smart-case")) + #expect(!args.contains("!vendor")) + #expect(args.suffix(4) == ["-e", "^class", "--", "/p"]) + } + + @Test func aWordSearchUsesWordRegexp() { + let args = RipgrepScanner.searchArguments(LineQuery(pattern: .word("Agent"), fileExtension: "php"), filter: defaults, target: "/p") + #expect(args.contains("--word-regexp")) + #expect(args.suffix(4) == ["-e", "Agent", "--", "/p"]) + } + + @Test func fileListingHonoursExcludesAndGitignore() { + var files = HelderConfig.Files() + files.exclude = ["*.log", ""] + files.followGitignore = true + let args = RipgrepScanner.fileArguments(filter: ScanFilter(base: ["vendor"], files: files), target: "/p/src") + #expect(args == ["--files", "--hidden", "--glob", "!vendor", "--glob", "!*.log", "--", "/p/src"]) + } + + @Test func aMissingRipgrepBinaryYieldsNoResultsInsteadOfThrowing() async { + let scanner = RipgrepScanner(root: URL(fileURLWithPath: "/tmp"), binary: URL(fileURLWithPath: "/nonexistent/rg"), + runner: ProcessRunner()) + #expect(await scanner.files(under: nil, filter: defaults).isEmpty) + } + + @Test func rgBinaryInTheEnvironmentWinsOverTheLocator() { + #expect(ProjectScanner.ripgrep(locator: Ripgrep.absent, environment: ["RG_BINARY": "/bin/sh"])?.path == "/bin/sh") + #expect(ProjectScanner.ripgrep(locator: Ripgrep.absent, environment: ["RG_BINARY": "/nonexistent"]) == nil) + #expect(ProjectScanner.ripgrep(locator: Ripgrep.absent, environment: [:]) == nil) + } + + // MARK: walk + + @Test func theWalkListsFilesAndDotfilesButNotTheBaseIgnores() async throws { + let dir = try TempDirectory() + try dir.write("src/a.ts", "a") + try dir.write(".env", "x") + try dir.write(".DS_Store", "x") + try dir.write("node_modules/p/i.js", "x") + try dir.write("lib/vendor/v.php", "x") + #expect(await walk(dir).files(under: nil, filter: defaults) == [".env", "src/a.ts"]) + #expect(await walk(dir).files(under: "src", filter: defaults) == ["src/a.ts"]) + } + + @Test func theWalkSkipsGitignoredFilesOnlyWhenAsked() async throws { + let repo = try TempGitRepo() + try repo.write(".gitignore", "secret.txt\nlogs/\n") + try repo.write("secret.txt", "shh") + try repo.write("logs/today.txt", "x") + try repo.write("keep.txt", "ok") + let scanner = WalkScanner(root: repo.root, runner: ProcessRunner()) + #expect(await scanner.files(under: nil, filter: defaults) == [".gitignore", "keep.txt", "logs/today.txt", "secret.txt"]) + var following = defaults + following.files.followGitignore = true + #expect(await scanner.files(under: nil, filter: following) == [".gitignore", "keep.txt"]) + } + + @Test + func theWalkHonoursExcludeGlobs() async throws { + let dir = try TempDirectory() + try dir.write("a.log", "x") + try dir.write("deep/b.log", "x") + try dir.write("keep.txt", "x") + var filter = defaults + filter.files.exclude = ["*.log"] + #expect(await walk(dir).files(under: nil, filter: filter) == ["keep.txt"]) + } + + @Test func aLowercaseQueryMatchesAnyCase() async throws { + let dir = try TempDirectory() + try dir.write("a.ts", "const x = 1\nconst Balance = 2\n") + let matches = await walk(dir).matches(LineQuery(pattern: .smartCaseLiteral("balance")), filter: defaults) + #expect(matches == [RipgrepMatch(path: dir.root.path + "/a.ts", line: 2, text: "const Balance = 2", byteOffset: 6)]) + } + + @Test func anUppercaseQueryIsCaseSensitive() async throws { + let dir = try TempDirectory() + try dir.write("a.ts", "balance\nBalance\n") + let matches = await walk(dir).matches(LineQuery(pattern: .smartCaseLiteral("Balance")), filter: defaults) + #expect(matches.map(\.line) == [2]) + } + + @Test func theByteOffsetCountsUTF8Bytes() async throws { + let dir = try TempDirectory() + try dir.write("a.txt", "héllo wörld\n") + let matches = await walk(dir).matches(LineQuery(pattern: .smartCaseLiteral("wörld")), filter: defaults) + #expect(matches.first?.byteOffset == 7) + } + + @Test func theWalkStopsAtTheLimitPerFileAndAtTheFileLimit() async throws { + let dir = try TempDirectory() + for name in ["a", "b", "c"] { try dir.write("\(name).txt", String(repeating: "hit\n", count: 5)) } + let matches = await walk(dir).matches(LineQuery(pattern: .smartCaseLiteral("hit"), maxPerFile: 2, maxFiles: 2), filter: defaults) + #expect(matches.map { "\(PathUtils.basename($0.path)):\($0.line)" } == ["a.txt:1", "a.txt:2", "b.txt:1", "b.txt:2"]) + } + + @Test func theWalkSkipsBinaryAndOversizedFiles() async throws { + let dir = try TempDirectory() + try dir.write("bin.dat", Data("needle\0".utf8)) + try dir.write("big.txt", "needle\n" + String(repeating: "x", count: 400)) + try dir.write("ok.txt", "needle\n") + var scanner = walk(dir) + scanner.maxFileBytes = 100 + let matches = await scanner.matches(LineQuery(pattern: .smartCaseLiteral("needle")), filter: defaults) + #expect(matches.map { PathUtils.basename($0.path) } == ["ok.txt"]) + } + + @Test func aRegexQueryReadsOnlyTheRequestedExtension() async throws { + let dir = try TempDirectory() + try dir.write("A.php", " Bool = { ($0.path, $0.line) < ($1.path, $1.line) } + #expect(await rg.matches(query, filter: defaults).sorted(by: sort) == walk(dir).matches(query, filter: defaults).sorted(by: sort)) + } + } + + @Test(.enabled(if: Ripgrep.isPresent)) + func ripgrepAndTheWalkListTheSameFiles() async throws { + let dir = try TempDirectory() + try dir.write("src/a.ts", "a") + try dir.write(".env", "x") + try dir.write(".DS_Store", "x") + try dir.write("node_modules/p/i.js", "x") + try dir.mkdir("empty") + let rg = RipgrepScanner(root: dir.root, binary: try #require(Ripgrep.binary), runner: ProcessRunner()) + #expect(await rg.files(under: nil, filter: defaults) == walk(dir).files(under: nil, filter: defaults)) + #expect(await rg.files(under: "src", filter: defaults) == ["src/a.ts"]) + } +} diff --git a/Tests/HelderServicesTests/Search/RipgrepSearchServiceTests.swift b/Tests/HelderServicesTests/Search/RipgrepSearchServiceTests.swift new file mode 100644 index 0000000..18a8bd9 --- /dev/null +++ b/Tests/HelderServicesTests/Search/RipgrepSearchServiceTests.swift @@ -0,0 +1,128 @@ +import Foundation +import HelderCore +import HelderServices +import Testing + +@Suite struct RipgrepSearchServiceTests { + private func withRipgrep(_ dir: URL, config: HelderConfig = .defaults) -> RipgrepSearchService { + RipgrepSearchService(root: dir, config: FixedConfig(config: config), locator: Ripgrep.locator, environment: [:]) + } + + private func withoutRipgrep(_ dir: URL, config: HelderConfig = .defaults) -> RipgrepSearchService { + RipgrepSearchService(root: dir, config: FixedConfig(config: config), locator: Ripgrep.absent, environment: [:]) + } + + /// a.ts holds "balance" on line 2; b.ts holds nothing relevant. + private func fixture() throws -> TempDirectory { + let dir = try TempDirectory() + try dir.write("a.ts", "const x = 1\nconst balance = 2\n") + try dir.write("b.ts", "nothing relevant\n") + return dir + } + + @Test func availabilityFollowsTheLocatorAndRgBinary() async throws { + let dir = try TempDirectory() + #expect(await !withoutRipgrep(dir.root).isAvailable()) + let viaEnvironment = RipgrepSearchService(root: dir.root, config: FixedConfig(), locator: Ripgrep.absent, + environment: ["RG_BINARY": "/bin/sh"]) + #expect(await viaEnvironment.isAvailable()) + } + + @Test(.enabled(if: Ripgrep.isPresent)) + func ripgrepIsFoundWhereTheOldAppShipsIt() async throws { + let dir = try TempDirectory() + #expect(await withRipgrep(dir.root).isAvailable()) + } + + @Test(arguments: ["", "a", " b "]) + func aQueryUnderTwoCharactersFindsNothing(_ query: String) async throws { + let dir = try fixture() + #expect(await withoutRipgrep(dir.root).searchContent(query).isEmpty) + #expect(await withRipgrep(dir.root).searchContent(query).isEmpty) + } + + @Test(.enabled(if: Ripgrep.isPresent)) + func ripgrepFindsContentWithLineAndOffset() async throws { + let dir = try fixture() + let groups = await withRipgrep(dir.root).searchContent("balance") + #expect(groups == [ContentGroup(path: "a.ts", hits: [ContentHit(line: 2, text: "const balance = 2", matchOffset: 6)])]) + } + + @Test + func theWalkFindsContentWithLineAndOffset() async throws { + let dir = try fixture() + let groups = await withoutRipgrep(dir.root).searchContent("balance") + #expect(groups == [ContentGroup(path: "a.ts", hits: [ContentHit(line: 2, text: "const balance = 2", matchOffset: 6)])]) + } + + @Test + func theWalkCapsHitsPerFile() async throws { + let dir = try TempDirectory() + try dir.write("many.txt", String(repeating: "needle\n", count: SearchLimits.maxHitsPerFile + 10)) + let groups = await withoutRipgrep(dir.root).searchContent("needle") + #expect(groups.first?.hits.count == SearchLimits.maxHitsPerFile) + } + + @Test(.enabled(if: Ripgrep.isPresent)) + func ripgrepContentSearchSkipsExcludedFiles() async throws { + let dir = try fixture() + try dir.write("node_modules/p/index.js", "balance\n") + try dir.write("build.log", "balance\n") + var config = HelderConfig.defaults + config.files.exclude = ["*.log"] + #expect(await withRipgrep(dir.root, config: config).searchContent("balance").map(\.path) == ["a.ts"]) + } + + @Test(.enabled(if: Ripgrep.isPresent)) + func ripgrepListsFilesIncludingDotfiles() async throws { + let dir = try fixture() + try dir.write(".env", "APP_NAME=x\n") + try dir.write(".DS_Store", "x") + try dir.write("node_modules/p/index.js", "x") + #expect(await withRipgrep(dir.root).listFiles(under: nil) == [".env", "a.ts", "b.ts"]) + } + + @Test(.enabled(if: Ripgrep.isPresent)) + func ripgrepListsOneSubtreeWithRootRelativePaths() async throws { + let dir = try fixture() + try dir.write("src/deep/c.ts", "c") + #expect(await withRipgrep(dir.root).listFiles(under: "src") == ["src/deep/c.ts"]) + } + + @Test(.enabled(if: Ripgrep.isPresent)) + func ripgrepShowsGitignoredFilesUnlessTheConfigFollowsGitignore() async throws { + let repo = try TempGitRepo() + try repo.write(".gitignore", "secret.txt\n") + try repo.write("secret.txt", "shh") + try repo.write("keep.txt", "ok") + #expect(await withRipgrep(repo.root).listFiles(under: nil) == [".gitignore", "keep.txt", "secret.txt"]) + var config = HelderConfig.defaults + config.files.followGitignore = true + #expect(await withRipgrep(repo.root, config: config).listFiles(under: nil) == [".gitignore", "keep.txt"]) + } + + @Test(.enabled(if: Ripgrep.isPresent)) + func ripgrepHonoursExcludeGlobs() async throws { + let dir = try fixture() + try dir.write("logs/today.log", "x") + var config = HelderConfig.defaults + config.files.exclude = ["*.log"] + #expect(await withRipgrep(dir.root, config: config).listFiles(under: nil) == ["a.ts", "b.ts"]) + } + + @Test func theWalkListsFilesWithoutRipgrep() async throws { + let dir = try fixture() + try dir.write(".env", "x") + try dir.write("vendor/x.php", "x") + try dir.write("src/c.ts", "c") + let search = withoutRipgrep(dir.root) + #expect(await search.listFiles(under: nil) == [".env", "a.ts", "b.ts", "src/c.ts"]) + #expect(await search.listFiles(under: "src") == ["src/c.ts"]) + } + + @Test func listingOutsideTheProjectIsEmpty() async throws { + let dir = try fixture() + #expect(await withoutRipgrep(dir.root).listFiles(under: "..").isEmpty) + #expect(await withRipgrep(dir.root).listFiles(under: "../..").isEmpty) + } +} diff --git a/Tests/HelderServicesTests/Support/CaseSensitiveVolume.swift b/Tests/HelderServicesTests/Support/CaseSensitiveVolume.swift new file mode 100644 index 0000000..355a744 --- /dev/null +++ b/Tests/HelderServicesTests/Support/CaseSensitiveVolume.swift @@ -0,0 +1,38 @@ +import Foundation + +/// A small case-sensitive APFS disk image, attached for one test and detached on deinit. +final class CaseSensitiveVolume { + let root: URL + private let image: URL + + init() throws { + let base = FileManager.default.temporaryDirectory + .appendingPathComponent("helder-cs-\(UUID().uuidString)") + .resolvingSymlinksInPath() + try FileManager.default.createDirectory(at: base, withIntermediateDirectories: true) + image = base.appendingPathComponent("volume.dmg") + root = base.appendingPathComponent("mount") + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + try Self.hdiutil(["create", "-quiet", "-size", "8m", "-fs", "Case-sensitive APFS", "-volname", "HelderCS", image.path]) + try Self.hdiutil(["attach", "-quiet", "-nobrowse", "-mountpoint", root.path, image.path]) + } + + deinit { + try? Self.hdiutil(["detach", "-quiet", "-force", root.path]) + try? FileManager.default.removeItem(at: image.deletingLastPathComponent()) + } + + private static func hdiutil(_ arguments: [String]) throws { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/hdiutil") + process.arguments = arguments + process.standardInput = FileHandle.nullDevice + process.standardOutput = FileHandle.nullDevice + process.standardError = FileHandle.nullDevice + try process.run() + process.waitUntilExit() + guard process.terminationStatus == 0 else { + throw NSError(domain: "hdiutil", code: Int(process.terminationStatus), userInfo: [NSLocalizedDescriptionKey: arguments.joined(separator: " ")]) + } + } +} diff --git a/Tests/HelderServicesTests/Support/Fakes.swift b/Tests/HelderServicesTests/Support/Fakes.swift new file mode 100644 index 0000000..f41d0b0 --- /dev/null +++ b/Tests/HelderServicesTests/Support/Fakes.swift @@ -0,0 +1,106 @@ +import Foundation +import HelderCore +import HelderServices + +/// A config service that always returns the same config. +struct FixedConfig: ConfigServicing { + var config = HelderConfig.defaults + + func resolve() async -> HelderConfig { config } + func current() async -> HelderConfig { config } +} + +/// A search service without ripgrep, which sends FileService down its walk. +struct NoRipgrepSearch: SearchServicing { + func isAvailable() async -> Bool { false } + func searchContent(_ query: String) async -> [ContentGroup] { [] } + func listFiles(under directory: String?) async -> [String] { [] } +} + +/// One process call a `ScriptedRunner` saw. +struct RecordedCall: Sendable, Equatable { + var executable: String + var arguments: [String] + var environment: [String: String]? +} + +/// Records every call and answers from a script; for tests of argument construction and error paths. +final class ScriptedRunner: ProcessRunning, @unchecked Sendable { + private let lock = NSLock() + private var recorded: [RecordedCall] = [] + private let respond: @Sendable (RecordedCall) async throws -> ProcessResult + + init(_ respond: @escaping @Sendable (RecordedCall) async throws -> ProcessResult) { + self.respond = respond + } + + var calls: [RecordedCall] { + lock.withLock { recorded } + } + + func run(_ executable: String, arguments: [String], in directory: URL?, environment: [String: String]?) async throws -> ProcessResult { + let call = RecordedCall(executable: executable, arguments: arguments, environment: environment) + lock.withLock { recorded.append(call) } + return try await respond(call) + } +} + +enum Ripgrep { + /// `$RG_BINARY`, or the ripgrep in `vendor/ripgrep`; nil when neither exists. + static var binary: URL? { + if let env = ProcessInfo.processInfo.environment["RG_BINARY"], FileManager.default.isExecutableFile(atPath: env) { + return URL(fileURLWithPath: env) + } + let packageRoot = URL(fileURLWithPath: #filePath) + .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() + let bundled = packageRoot.appendingPathComponent("vendor/ripgrep/rg") + return FileManager.default.isExecutableFile(atPath: bundled.path) ? bundled : nil + } + + static var isPresent: Bool { binary != nil } + + /// A locator that finds only that ripgrep. + static var locator: ExecutableLocator { + ExecutableLocator(directories: binary.map { [$0.deletingLastPathComponent().path] } ?? []) + } + + /// A locator that finds no ripgrep, whatever is installed. + static let absent = ExecutableLocator(directories: []) +} + +/// Polls until `condition` holds or `timeout` passes; returns whether it held. +func eventually(timeout: TimeInterval = 5, _ condition: () -> Bool) async -> Bool { + let deadline = Date().addingTimeInterval(timeout) + while Date() < deadline { + if condition() { return true } + try? await Task.sleep(nanoseconds: 20_000_000) + } + return condition() +} + +/// Polls an async condition until it holds or `timeout` passes; returns whether it held. +func eventuallyAsync(timeout: TimeInterval = 5, _ condition: () async -> Bool) async -> Bool { + let deadline = Date().addingTimeInterval(timeout) + while Date() < deadline { + if await condition() { return true } + try? await Task.sleep(nanoseconds: 5_000_000) + } + return await condition() +} + +/// Holds every waiter until `open()`; waiters arriving after that pass straight through. +actor Gate { + private var isOpen = false + private var waiters: [CheckedContinuation] = [] + + func wait() async { + if isOpen { return } + await withCheckedContinuation { waiters.append($0) } + } + + func open() { + isOpen = true + waiters.forEach { $0.resume() } + waiters = [] + } +} diff --git a/Tests/HelderServicesTests/Support/TempDirectory.swift b/Tests/HelderServicesTests/Support/TempDirectory.swift new file mode 100644 index 0000000..8fd6d59 --- /dev/null +++ b/Tests/HelderServicesTests/Support/TempDirectory.swift @@ -0,0 +1,44 @@ +import Foundation + +/// A throwaway folder, removed on deinit. +final class TempDirectory { + let root: URL + + init() throws { + root = FileManager.default.temporaryDirectory + .appendingPathComponent("helder-test-\(UUID().uuidString)") + .resolvingSymlinksInPath() + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + } + + deinit { + try? FileManager.default.removeItem(at: root) + } + + func url(_ path: String) -> URL { + root.appendingPathComponent(path) + } + + /// Writes a file relative to the root, creating folders as needed. + func write(_ path: String, _ contents: String) throws { + try write(path, Data(contents.utf8)) + } + + func write(_ path: String, _ data: Data) throws { + let url = url(path) + try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try data.write(to: url) + } + + func mkdir(_ path: String) throws { + try FileManager.default.createDirectory(at: url(path), withIntermediateDirectories: true) + } + + func read(_ path: String) throws -> String { + try String(contentsOf: url(path), encoding: .utf8) + } + + func exists(_ path: String) -> Bool { + FileManager.default.fileExists(atPath: url(path).path) + } +} diff --git a/Tests/HelderServicesTests/Support/TempGitRepo.swift b/Tests/HelderServicesTests/Support/TempGitRepo.swift new file mode 100644 index 0000000..c9d1af1 --- /dev/null +++ b/Tests/HelderServicesTests/Support/TempGitRepo.swift @@ -0,0 +1,74 @@ +import Foundation +import HelderServices + +/// A throwaway git repository in a temp folder, removed on deinit. For integration tests. +final class TempGitRepo { + let root: URL + private let git: URL + + /// Creates the folder, runs `git init -b main`, and sets a local user so commits work anywhere. + /// A bare repository serves as a push remote. + init(bare: Bool = false) throws { + guard let git = ExecutableLocator.standard.locate("git") else { + throw ProcessRunnerError.executableNotFound("git") + } + self.git = git + root = FileManager.default.temporaryDirectory + .appendingPathComponent("helder-test-\(UUID().uuidString)") + .resolvingSymlinksInPath() + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + if bare { + try run("init", "-q", "--bare", "-b", "main") + return + } + try run("init", "-q", "-b", "main") + try run("config", "user.name", "Helder Tests") + try run("config", "user.email", "tests@helder.invalid") + try run("config", "commit.gpgsign", "false") + } + + deinit { + try? FileManager.default.removeItem(at: root) + } + + /// Writes a file relative to the root, creating folders as needed. + func write(_ path: String, _ contents: String) throws { + let url = root.appendingPathComponent(path) + try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data(contents.utf8).write(to: url) + } + + func read(_ path: String) throws -> String { + try String(contentsOf: root.appendingPathComponent(path), encoding: .utf8) + } + + /// Writes the files, stages everything and commits. + func commit(_ files: [String: String] = [:], message: String = "commit") throws { + for (path, contents) in files { try write(path, contents) } + try run("add", "-A") + try run("commit", "-q", "--allow-empty", "-m", message) + } + + /// Runs git synchronously in the repo and returns stdout; throws on a non-zero exit. + @discardableResult + func run(_ arguments: String...) throws -> String { + let process = Process() + process.executableURL = git + process.arguments = arguments + process.currentDirectoryURL = root + process.standardInput = FileHandle.nullDevice + let out = Pipe() + let err = Pipe() + process.standardOutput = out + process.standardError = err + try process.run() + let data = out.fileHandleForReading.readDataToEndOfFile() + let errData = err.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + guard process.terminationStatus == 0 else { + throw GitError.commandFailed(arguments: arguments, exitCode: process.terminationStatus, + stderr: String(decoding: errData, as: UTF8.self)) + } + return String(decoding: data, as: UTF8.self) + } +} diff --git a/Tests/HelderServicesTests/Symbols/SymbolServiceTests.swift b/Tests/HelderServicesTests/Symbols/SymbolServiceTests.swift new file mode 100644 index 0000000..badf29c --- /dev/null +++ b/Tests/HelderServicesTests/Symbols/SymbolServiceTests.swift @@ -0,0 +1,111 @@ +import Foundation +import HelderCore +import HelderServices +import Testing + +/// Each test runs once through ripgrep (when present) and once through the walk. +@Suite struct SymbolServiceTests { + enum Engine: String, CaseIterable, Sendable { case ripgrep, walk } + + private static let engines: [Engine] = Ripgrep.isPresent ? Engine.allCases : [.walk] + + private func service(_ root: URL, _ engine: Engine) -> SymbolService { + SymbolService(root: root, config: FixedConfig(), runner: ProcessRunner(), + locator: engine == .ripgrep ? Ripgrep.locator : Ripgrep.absent, environment: [:]) + } + + /// A small Laravel-shaped project: a model with a trait, a controller using it, and a vendor class. + private func project() throws -> TempDirectory { + let dir = try TempDirectory() + try dir.write("app/Models/Agent.php", """ + .self) { group in + for _ in 0..<8 { group.addTask { await symbols.names() } } + return await group.reduce(into: [Set]()) { $0.append($1) } + } + #expect(Set(results).count == 1) + } +} diff --git a/Tests/HelderUITests/Editor/DiffCanvasSelectionTests.swift b/Tests/HelderUITests/Editor/DiffCanvasSelectionTests.swift new file mode 100644 index 0000000..2deb586 --- /dev/null +++ b/Tests/HelderUITests/Editor/DiffCanvasSelectionTests.swift @@ -0,0 +1,53 @@ +import AppKit +import HelderCore +@testable import HelderUI +import Testing + +@MainActor +@Suite struct DiffCanvasSelectionTests { + private func canvas() -> DiffCanvasView { + let view = DiffCanvasView(frame: NSRect(x: 0, y: 0, width: 800, height: 400)) + view.load(rows: [ + SplitRow(left: SideLine(no: 1, text: "old one"), right: SideLine(no: 1, text: "new one")), + SplitRow(left: nil, right: SideLine(no: 2, text: "added", mark: .added)), + SplitRow(left: SideLine(no: 2, text: "old two"), right: SideLine(no: 3, text: "new three")), + ], language: nil, knownSymbols: [], scale: 1) + return view + } + + private func mouse(_ type: NSEvent.EventType, row: Int, right: Bool) -> NSEvent { + let y = DiffOverlayLayout.topPadding + (CGFloat(row) + 0.5) * DiffOverlayLayout.rowHeight + return NSEvent.mouseEvent(with: type, location: NSPoint(x: right ? 600 : 200, y: y), modifierFlags: [], + timestamp: 0, windowNumber: 0, context: nil, eventNumber: 0, clickCount: 1, pressure: 1)! + } + + @Test func draggingSelectsWholeLinesOnOneSide() { + let view = canvas() + view.mouseDown(with: mouse(.leftMouseDown, row: 0, right: true)) + view.mouseDragged(with: mouse(.leftMouseDragged, row: 2, right: false)) + #expect(view.selectedText == "new one\nadded\nnew three") + } + + @Test func theOtherSidesBlankRowsAreSkipped() { + let view = canvas() + view.mouseDown(with: mouse(.leftMouseDown, row: 2, right: false)) + view.mouseDragged(with: mouse(.leftMouseDragged, row: 0, right: false)) + #expect(view.selectedText == "old one\nold two") + } + + @Test func aClickWithoutADragSelectsNothing() { + let view = canvas() + view.mouseDown(with: mouse(.leftMouseDown, row: 1, right: true)) + #expect(!view.hasSelection) + } + + @Test func selectAllTakesTheSelectedSideElseTheOriginal() { + let view = canvas() + view.selectAll(nil) + #expect(view.selectedText == "old one\nold two") + view.mouseDown(with: mouse(.leftMouseDown, row: 0, right: true)) + view.mouseDragged(with: mouse(.leftMouseDragged, row: 0, right: true)) + view.selectAll(nil) + #expect(view.selectedText == "new one\nadded\nnew three") + } +} diff --git a/Tests/HelderUITests/Editor/EditorFocusAndBinaryTests.swift b/Tests/HelderUITests/Editor/EditorFocusAndBinaryTests.swift new file mode 100644 index 0000000..dd9f09a --- /dev/null +++ b/Tests/HelderUITests/Editor/EditorFocusAndBinaryTests.swift @@ -0,0 +1,46 @@ +import Foundation +import HelderCore +@testable import HelderUI +import Testing + +@MainActor +@Suite struct EditorBinaryTests { + @Test func aFileWithBinaryContentCannotBeDisplayedWhateverItsName() async { + let h = EditorHarness(files: ["data.txt": ""]) + h.files.setBinary("data.txt") + h.store.open("data.txt") + await h.store.settle() + #expect(h.store.binaryPaths == ["data.txt"]) + #expect(h.store.presentation(for: "data.txt").kind == .binary) + } + + @Test func anEmptyTextFileIsStillText() async { + let h = EditorHarness(files: ["empty.txt": ""]) + h.store.open("empty.txt") + await h.store.settle() + #expect(h.store.binaryPaths.isEmpty) + #expect(h.store.presentation(for: "empty.txt").kind == .text) + } +} + +@MainActor +@Suite struct EditorFocusTests { + @Test func closingTheDiffHandsTheKeyboardBackToTheText() async { + let h = EditorHarness(files: ["a.php": "new"]) + h.git.change("a.php", makeDiff(original: "old", updated: "new")) + h.store.open("a.php") + h.store.setMode(.diff, for: "a.php") + let before = h.store.textFocusRequest + h.store.collapseDiff() + #expect(h.store.textFocusRequest > before) + #expect(h.overlays.diffDismissals == 1) + } + + @Test func movingFocusToTheEditorColumnAsksForTheTextView() async { + let harness = WorkspaceHarness(contents: ["a.php": ""]) + await harness.start() + let before = harness.model.editor?.textFocusRequest ?? 0 + harness.model.perform(.focus(.editor)) + #expect(harness.model.editor?.textFocusRequest == before + 1) + } +} diff --git a/Tests/HelderUITests/Editor/EditorLayoutTests.swift b/Tests/HelderUITests/Editor/EditorLayoutTests.swift new file mode 100644 index 0000000..772c245 --- /dev/null +++ b/Tests/HelderUITests/Editor/EditorLayoutTests.swift @@ -0,0 +1,284 @@ +import CoreGraphics +import Foundation +import HelderCore +@testable import HelderUI +import Testing + +@Suite struct EditorPresentationTests { + @Test func anUnchangedFileShowsItsEditableCodeViewAndNoButtons() { + let view = EditorPresentation(path: "a.php", requested: nil, diff: nil) + #expect(view.mode == .code) + #expect(view.barButtons.isEmpty) + #expect(view.isEditable) + } + + @Test func aChangedFileOffersOnlyTheDiffButton() { + let view = EditorPresentation(path: "a.php", requested: nil, diff: makeDiff(original: "a", updated: "b")) + #expect(view.mode == .actual) + #expect(view.barButtons == [.diff]) + #expect(view.opensDiffOnClick) + } + + @Test func unchangedMarkdownOffersOnlyPreview() { + let view = EditorPresentation(path: "README.md", requested: nil, diff: nil) + #expect(view.barButtons == [.preview]) + } + + @Test func changedMarkdownOffersPreviewThenDiff() { + let view = EditorPresentation(path: "README.md", requested: .preview, diff: makeDiff(original: "a", updated: "b")) + #expect(view.barButtons == [.preview, .diff]) + #expect(view.mode == .preview) + #expect(!view.isEditable) + } + + @Test func aFileOverTheDiffCapStillShowsItsLiveText() { + var diff = makeDiff(original: "", updated: "", added: 0) + diff.isTooBig = true + let view = EditorPresentation(path: "dump.sql", requested: .actual, diff: diff) + #expect(view.placeholder == nil) + #expect(view.isEditable) + } + + @Test func aDiffRequestOnAnUnchangedFileFallsBackToCode() { + let view = EditorPresentation(path: "a.php", requested: .diff, diff: nil) + #expect(view.mode == .code) + } + + @Test func aCodeModeOnAChangedFileResolvesToActual() { + let view = EditorPresentation(path: "a.php", requested: .code, diff: makeDiff(original: "a", updated: "b")) + #expect(view.mode == .actual) + } + + @Test func theDiffOverlayLeavesActualInThePaneBehindIt() { + let view = EditorPresentation(path: "a.php", requested: .diff, diff: makeDiff(original: "a", updated: "b")) + #expect(view.mode == .diff) + #expect(view.paneMode == .actual) + } + + @Test func anAddedFileHasNoClickToDiff() { + let diff = makeDiff(original: "", updated: "b", isAddedFile: true) + let actual = EditorPresentation(path: "a.php", requested: .actual, diff: diff) + #expect(actual.placeholder == nil) + #expect(!actual.opensDiffOnClick) + #expect(actual.status == .added) + } + + @Test func aDeletedFileHasNoUpdatedVersion() { + let diff = makeDiff(original: "a", updated: "", isDeletedFile: true) + let view = EditorPresentation(path: "a.php", requested: .actual, diff: diff) + #expect(view.placeholder == .noUpdated) + #expect(!view.isEditable) + } + + @Test func aBinaryFileGetsAPlaceholderAndNoButtons() { + let view = EditorPresentation(path: "font.woff2", requested: nil, diff: makeDiff(original: "", updated: "")) + #expect(view.placeholder == .cannotDisplay) + #expect(view.barButtons.isEmpty) + #expect(!view.hasDiff) + } + + @Test func anImageIsNeitherTextNorDiffed() { + let view = EditorPresentation(path: "logo.png", requested: nil, diff: makeDiff(original: "", updated: "")) + #expect(view.kind == .image) + #expect(view.barButtons.isEmpty) + #expect(!view.isEditable) + } +} + +@Suite struct LineIndexTests { + @Test func linesAreFoundByUTF16Offset() { + let index = LineIndex("ab\ncd\n") + #expect(index.lineCount == 3) + #expect(index.line(containing: 0) == 1) + #expect(index.line(containing: 2) == 1) + #expect(index.line(containing: 3) == 2) + #expect(index.line(containing: 6) == 3) + #expect(index.column(of: 4) == 2) + #expect(index.start(ofLine: 2) == 3) + } + + @Test func anEmptyTextIsOneEmptyLine() { + let index = LineIndex("") + #expect(index.lineCount == 1) + #expect(index.line(containing: 0) == 1) + } + + @Test func wrappedRowsShowTheNumberOnlyOnTheirFirstRow() { + // Line 1 folds into three rows (starting at 0, 10, 20); line 2 is one row at 31. + let index = LineIndex(String(repeating: "x", count: 30) + "\nshort") + #expect(GutterNumbers.labels(rowStarts: [0, 10, 20, 31], index: index) == [1, nil, nil, 2]) + } +} + +@Suite struct ChangeMarksTests { + @Test func actualTintsAddedLinesAndRulesTheEdgeOfAPureDeletion() { + let lines = [ + ViewLine(no: 1, text: "a"), + ViewLine(no: 2, text: "b", style: .added), + ViewLine(no: 3, text: "c", gap: .above), + ViewLine(no: 4, text: "d", gap: .below), + ] + let marks = ChangeMarks.actual(lines) + #expect(marks[1] == nil) + #expect(marks[2] == CodeLineMark(tint: true, tone: .added)) + #expect(marks[3] == CodeLineMark(tint: false, tone: nil, gap: .above)) + #expect(marks[4]?.gap == .below) + } +} + +/// Marks and layout built from real Core diffs, end to end. +@Suite struct EditorRealDiffTests { + @Test func actualMarksComeFromTheRealDiff() { + let diff = LineDiff.build(original: "a\nb\nc\n", updated: "a\nc\n") + #expect(ChangeMarks.actual(DiffViews.actual(diff))[2]?.gap == .above) + } +} + +@Suite struct DiffOverlayLayoutTests { + private func rows(_ count: Int) -> [SplitRow] { + (1...count).map { SplitRow(left: SideLine(no: $0, text: ""), right: SideLine(no: $0, text: "")) } + } + + @Test func theClickedLineLandsInTheMiddleOfTheViewport() { + let index = DiffOverlayLayout.rowIndex(forUpdatedLine: 100, in: rows(200))! + let offset = DiffOverlayLayout.centredOffset(rowIndex: index, rowCount: 200, viewportHeight: 440) + let rowMid = 6 + CGFloat(index) * 22 + 11 + #expect(rowMid - offset == 220) + } + + @Test func aLineNearTheTopGoesAsNearTheMiddleAsTheFilePermits() { + #expect(DiffOverlayLayout.centredOffset(rowIndex: 1, rowCount: 200, viewportHeight: 440) == 0) + } + + @Test func aLineNearTheEndStopsAtTheBottom() { + let offset = DiffOverlayLayout.centredOffset(rowIndex: 199, rowCount: 200, viewportHeight: 440) + #expect(abs(offset - CGFloat(12 + 200 * 22 - 440)) < 0.001) + } + + @Test func fillerRowsOnTheUpdatedSideAreSkipped() { + let split = [ + SplitRow(left: SideLine(no: 1, text: "a", mark: .removed), right: nil), + SplitRow(left: nil, right: SideLine(no: 1, text: "b", mark: .added)), + ] + #expect(DiffOverlayLayout.rowIndex(forUpdatedLine: 1, in: split) == 1) + } +} + +@Suite struct IndentationTests { + @Test func tabOnOneLineInsertsSpacesAtTheCaret() { + let edit = Indentation.edit("ab", selection: NSRange(location: 1, length: 0), tabSize: 4, outdent: false) + #expect(edit == TextEdit(range: NSRange(location: 1, length: 0), replacement: " ", selection: NSRange(location: 5, length: 0))) + } + + @Test func tabOverSeveralLinesIndentsEveryTouchedLine() { + let edit = Indentation.edit("a\nb\nc", selection: NSRange(location: 0, length: 3), tabSize: 2, outdent: false)! + #expect(edit.replacement == " a\n b") + #expect(edit.range == NSRange(location: 0, length: 3)) + } + + @Test func aSelectionEndingAtColumnZeroLeavesThatLineAlone() { + let edit = Indentation.edit("a\nb\nc", selection: NSRange(location: 0, length: 4), tabSize: 2, outdent: false)! + #expect(edit.replacement == " a\n b") + } + + @Test func shiftTabOutdentsTheCurrentLine() { + let edit = Indentation.edit("x\n ab", selection: NSRange(location: 7, length: 0), tabSize: 4, outdent: true)! + #expect(edit.replacement == "ab") + #expect(edit.selection == NSRange(location: 3, length: 0)) + } + + @Test func shiftTabOnAnUnindentedLineChangesNothing() { + #expect(Indentation.edit("ab", selection: NSRange(location: 1, length: 0), tabSize: 4, outdent: true) == nil) + } +} + +@Suite struct EditorReferenceTests { + @Test func aSelectionNamesItsFirstAndLastLine() { + let index = LineIndex("a\nb\nc\nd\n") + let lines = EditorReference.lines(of: NSRange(location: 2, length: 3), in: index) + #expect(lines == 2...3) + #expect(EditorReference.make(path: "x.php", selectedLines: lines, clickedLine: 9).description == "x.php:2-3") + } + + @Test func aSingleLineSelectionIsASingleLineReference() { + #expect(EditorReference.make(path: "x.php", selectedLines: 4...4, clickedLine: 9).description == "x.php:4") + } + + @Test func withoutASelectionTheClickedLineIsTheReference() { + #expect(EditorReference.make(path: "x.php", selectedLines: nil, clickedLine: 42).description == "x.php:42") + } +} + +@Suite struct IncrementalLineIndexTests { + private func edited(_ text: String, replacing range: NSRange, with insert: String) -> (LineIndex, String) { + var index = LineIndex(text) + let next = (text as NSString).replacingCharacters(in: range, with: insert) + let insertedLength = (insert as NSString).length + index.applyEdit(editedRange: NSRange(location: range.location, length: insertedLength), + delta: insertedLength - range.length, inserted: insert) + return (index, next) + } + + @Test func typingANewlineMatchesAFullRescan() { + let (index, text) = edited("ab\ncd\nef", replacing: NSRange(location: 4, length: 0), with: "\n") + #expect(index == LineIndex(text)) + } + + @Test func deletingAcrossLinesMatchesAFullRescan() { + let (index, text) = edited("ab\ncd\nef\ngh", replacing: NSRange(location: 1, length: 6), with: "") + #expect(index == LineIndex(text)) + } + + @Test func pastingSeveralLinesMatchesAFullRescan() { + let (index, text) = edited("ab\ncd", replacing: NSRange(location: 3, length: 1), with: "x\ny\nz") + #expect(index == LineIndex(text)) + } +} + +@Suite struct HighlightDiffTests { + @Test func typingInsidePlainTextRepaintsOnlyTheEditedRange() { + let old = [Token(location: 0, length: 3, role: .keyword), Token(location: 10, length: 2, role: .number)] + let new = [Token(location: 0, length: 3, role: .keyword), Token(location: 11, length: 2, role: .number)] + let range = HighlightDiff.repaintRange(old: old, new: new, edited: NSRange(location: 5, length: 1), delta: 1, newLength: 14) + #expect(range == NSRange(location: 5, length: 1)) + } + + @Test func growingAStringRepaintsTheWholeToken() { + let old = [Token(location: 4, length: 4, role: .string)] + let new = [Token(location: 4, length: 5, role: .string)] + let range = HighlightDiff.repaintRange(old: old, new: new, edited: NSRange(location: 6, length: 1), delta: 1, newLength: 20) + #expect(range == NSRange(location: 4, length: 5)) + } + + @Test func openingABlockCommentRepaintsEverythingAfterIt() { + let old = [Token(location: 10, length: 3, role: .keyword), Token(location: 30, length: 3, role: .keyword)] + let new = [Token(location: 0, length: 40, role: .comment)] + let range = HighlightDiff.repaintRange(old: old, new: new, edited: NSRange(location: 0, length: 2), delta: 2, newLength: 40) + #expect(range == NSRange(location: 0, length: 40)) + } +} + +@Suite struct SymbolTargetsTests { + private let lookup = SymbolLookup( + name: "User", + definitions: [SymbolDef(name: "User", path: "app/User.php", line: 7, kind: "class", namespace: "App")], + references: [RefGroup(path: "a.php", hits: [ContentHit(line: 3, text: "", matchOffset: 0), ContentHit(line: 9, text: "", matchOffset: 0)])], + referenceCount: 2) + + @Test func theKeyboardWalksDeclarationsThenEveryReferenceLine() { + #expect(SymbolTargets.flatten(lookup) == [ + SymbolTarget(path: "app/User.php", line: 7), SymbolTarget(path: "a.php", line: 3), SymbolTarget(path: "a.php", line: 9), + ]) + } + + @Test func oneDeclarationIsNamedInFull() { + #expect(SymbolTargets.title("User", lookup) == "App\\User") + } + + @Test func severalDeclarationsFallBackToTheShortName() { + var two = lookup + two.definitions.append(SymbolDef(name: "User", path: "b/User.php", line: 1, kind: "class", namespace: "B")) + #expect(SymbolTargets.title("User", two) == "User") + #expect(SymbolTargets.title("User", nil) == "User") + } +} diff --git a/Tests/HelderUITests/Editor/EditorScrollOriginTests.swift b/Tests/HelderUITests/Editor/EditorScrollOriginTests.swift new file mode 100644 index 0000000..3e7cd81 --- /dev/null +++ b/Tests/HelderUITests/Editor/EditorScrollOriginTests.swift @@ -0,0 +1,41 @@ +import AppKit +import HelderCore +@testable import HelderUI +import Testing + +@MainActor +@Suite struct EditorScrollOriginTests { + private static let text = (1...60).map { line in + line % 3 == 0 + ? "\(line): " + String(repeating: "a long line that runs well past ninety characters ", count: 3) + : "\(line): short line" + }.joined(separator: "\n") + + private func open(wrap: Bool) -> (CodeEditorController, NSWindow) { + let controller = CodeEditorController() + let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 700, height: 900), styleMask: [.titled], + backing: .buffered, defer: false) + window.contentView = controller.scrollView + controller.apply(CodeEditorConfiguration(documentID: "notes.md", path: "notes.md", text: Self.text, revision: 1, + language: nil, isEditable: true, wrap: wrap, tabSize: 4, marksKey: "", makeMarks: { [:] }, + opensDiffOnClick: false, knownSymbols: [], symbolsVersion: 0, flash: nil, focusRequest: 0, + selectAllRequest: 0, fontScale: 1, isShown: true)) + return (controller, window) + } + + @Test(arguments: [true, false]) + func aNewDocumentStartsRightOfTheGutter(wrap: Bool) { + let (controller, window) = open(wrap: wrap) + let clip = controller.scrollView.contentView + #expect(clip.bounds.origin.x == -clip.contentInsets.left) + withExtendedLifetime(window) {} + } + + @Test func wrappedTextFitsTheWidthRightOfTheGutter() { + let (controller, window) = open(wrap: true) + RunLoop.main.run(until: Date().addingTimeInterval(0.2)) + window.displayIfNeeded() + let scrollView = controller.scrollView + #expect(controller.textView.frame.width == scrollView.contentSize.width - scrollView.contentView.contentInsets.left) + } +} diff --git a/Tests/HelderUITests/Editor/EditorStoreSafetyTests.swift b/Tests/HelderUITests/Editor/EditorStoreSafetyTests.swift new file mode 100644 index 0000000..44b7d62 --- /dev/null +++ b/Tests/HelderUITests/Editor/EditorStoreSafetyTests.swift @@ -0,0 +1,171 @@ +import Foundation +import HelderCore +@testable import HelderUI +import Testing + +@MainActor +@Suite struct EditorStoreSafetyTests { + private func autoSaving(_ files: [String: String]) -> EditorHarness { + let h = EditorHarness(files: files) + var config = HelderConfig.Editor() + config.autoSave = true + h.store.editorConfig = config + return h + } + + @Test func autoSaveKeepsAPendingSaveWhenTheTabChanges() async { + let h = autoSaving(["a.txt": "a", "b.txt": "b"]) + h.store.open("a.txt") + await h.store.settle() + h.store.edit("a edited") + h.store.open("b.txt") + h.store.edit("b edited") + await h.store.settle() + #expect(h.files.current("a.txt") == "a edited") + #expect(h.files.current("b.txt") == "b edited") + } + + @Test func pendingAutoSavesAreWrittenBeforeTheUnsavedPrompt() async { + let h = autoSaving(["a.txt": "a"]) + var asked: [String] = [] + h.store.confirmUnsavedClose = { asked.append($0); return .cancel } + h.store.open("a.txt") + await h.store.settle() + h.store.edit("typed") + #expect(await h.store.resolveUnsaved()) + #expect(h.files.current("a.txt") == "typed") + #expect(asked.isEmpty) + } + + @Test func anOlderReadThatLandsLastIsDropped() async { + let h = EditorHarness(files: ["a.txt": "old"]) + h.store.open("a.txt") + await h.store.settle() + let gate = h.files.holdNextRead("a.txt") + let stale = Task { await h.store.filesChanged(nil) } + #expect(await eventually { gate.isWaiting }) + h.files.set("a.txt", "new") + await h.store.reloadFromDisk("a.txt") + gate.open() + await stale.value + #expect(h.store.text(for: "a.txt") == "new") + } + + @Test func forgettingAFileDropsEveryPieceOfItsState() async { + let h = EditorHarness(files: ["a.php": "x"]) + h.files.setImage("logo.png", Data([1])) + h.git.change("a.php", makeDiff(original: "", updated: "x")) + h.store.open("a.php", OpenOptions(side: .staged)) + h.store.open("logo.png") + await h.store.settle() + h.store.forget("a.php", isDirectory: false) + h.store.forget("logo.png", isDirectory: false) + #expect(h.store.states.isEmpty) + #expect(h.store.modes.isEmpty && h.store.sides.isEmpty && h.store.images.isEmpty) + } + + @Test func renamingCarriesImagesAlong() async { + let h = EditorHarness() + h.files.setImage("img/logo.png", Data([1, 2])) + h.store.open("img/logo.png") + await h.store.settle() + h.store.remap(from: "img", to: "assets", isDirectory: true) + #expect(h.store.image(for: "assets/logo.png") == Data([1, 2])) + #expect(h.store.image(for: "img/logo.png") == nil) + } + + @Test func aReopenedFileNeverReusesAnOldRevision() async { + let h = EditorHarness(files: ["a.txt": "one"]) + h.store.open("a.txt") + await h.store.settle() + let first = h.store.revision(for: "a.txt") + h.store.forget("a.txt", isDirectory: false) + h.files.set("a.txt", "two") + h.store.open("a.txt") + await h.store.settle() + #expect(h.store.revision(for: "a.txt") != first) + #expect(h.store.text(for: "a.txt") == "two") + } + + @Test func aFileDeletedOnDiskKeepsItsTextAsUnsavedEdits() async { + let h = EditorHarness(files: ["a.txt": "precious"]) + h.store.open("a.txt") + await h.store.settle() + h.files.remove("a.txt") + await h.store.filesChanged(nil) + #expect(h.store.isDeleted("a.txt")) + #expect(h.store.isDirty("a.txt")) + #expect(h.store.text(for: "a.txt") == "precious") + #expect(h.files.writes.isEmpty) + } + + @Test func autoSaveNeverResurrectsADeletedFile() async { + let h = autoSaving(["a.txt": "precious"]) + h.store.open("a.txt") + await h.store.settle() + h.files.remove("a.txt") + await h.store.filesChanged(nil) + h.store.edit("precious, edited") + await h.store.settle() + #expect(h.files.writes.isEmpty) + } + + @Test func savingADeletedFileWritesItBackOnPurpose() async throws { + let h = EditorHarness(files: ["a.txt": "precious"]) + h.store.open("a.txt") + await h.store.settle() + h.files.remove("a.txt") + await h.store.filesChanged(nil) + try await h.store.save() + #expect(h.files.current("a.txt") == "precious") + #expect(!h.store.isDeleted("a.txt")) + #expect(!h.store.isDirty("a.txt")) + } + + @Test func aFileThatComesBackIsCleanAgain() async { + let h = EditorHarness(files: ["a.txt": "same"]) + h.store.open("a.txt") + await h.store.settle() + h.files.remove("a.txt") + await h.store.filesChanged(nil) + h.files.set("a.txt", "same") + await h.store.filesChanged(nil) + #expect(!h.store.isDeleted("a.txt")) + #expect(!h.store.isDirty("a.txt")) + } + + @Test func theUnsavedPromptAsksForEveryDirtyFileTheOpenOneFirst() async { + let h = EditorHarness(files: ["a.txt": "a", "b.txt": "b"]) + var asked: [String] = [] + h.store.confirmUnsavedClose = { path in + asked.append(path) + return path == "a.txt" ? .save : .discard + } + h.store.open("a.txt") + await h.store.settle() + h.store.edit("a2") + h.store.open("b.txt") + await h.store.settle() + h.store.edit("b2") + #expect(await h.store.resolveUnsaved()) + #expect(h.store.activePath == "b.txt") + #expect(asked == ["b.txt", "a.txt"]) + #expect(h.files.current("a.txt") == "a2") + #expect(h.files.current("b.txt") == "b") + #expect(h.store.dirtyPaths.isEmpty) + } + + @Test func cancellingThePromptKeepsEveryEdit() async { + let h = EditorHarness(files: ["a.txt": "a", "b.txt": "b"]) + h.store.confirmUnsavedClose = { $0 == "a.txt" ? .discard : .cancel } + h.store.open("a.txt") + await h.store.settle() + h.store.edit("a2") + h.store.open("b.txt") + await h.store.settle() + h.store.edit("b2") + #expect(await h.store.resolveUnsaved() == false) + #expect(h.store.text(for: "a.txt") == "a2") + #expect(h.store.text(for: "b.txt") == "b2") + } +} diff --git a/Tests/HelderUITests/Editor/EditorStoreTests.swift b/Tests/HelderUITests/Editor/EditorStoreTests.swift new file mode 100644 index 0000000..8f08d10 --- /dev/null +++ b/Tests/HelderUITests/Editor/EditorStoreTests.swift @@ -0,0 +1,533 @@ +import Foundation +import HelderCore +@testable import HelderUI +import Testing + +@MainActor +@Suite struct EditorStoreOpenFileTests { + @Test func openingAFileMakesItTheActiveFileAndReadsItFromDisk() async { + let h = EditorHarness(files: ["a.php": " EditorHarness { + let h = EditorHarness(files: ["a.txt": "one"]) + h.store.open("a.txt") + await h.store.settle() + h.store.edit("two") + return h + } + + @Test func closingADirtyFileAsksAndCancelKeepsItOpen() async { + let h = await dirtyHarness() + var asked: [String] = [] + h.store.confirmUnsavedClose = { asked.append($0); return .cancel } + let closed = await h.store.requestCloseActive() + #expect(!closed) + #expect(asked == ["a.txt"]) + #expect(h.store.activePath == "a.txt") + #expect(h.store.isDirty("a.txt")) + } + + @Test func saveWritesThenCloses() async { + let h = await dirtyHarness() + h.store.confirmUnsavedClose = { _ in .save } + let closed = await h.store.requestCloseActive() + #expect(closed) + #expect(h.files.current("a.txt") == "two") + #expect(h.store.activePath == nil) + } + + @Test func discardClosesWithoutWriting() async { + let h = await dirtyHarness() + h.store.confirmUnsavedClose = { _ in .discard } + let closed = await h.store.requestCloseActive() + #expect(closed) + #expect(h.files.writes.isEmpty) + #expect(h.store.buffers.isEmpty) + #expect(h.store.activePath == nil) + } + + @Test func discardingThenReopeningShowsTheDiskTextToTheView() async { + let h = await dirtyHarness() + let revision = h.store.revision(for: "a.txt") + h.store.confirmUnsavedClose = { _ in .discard } + await h.store.requestCloseActive() + h.store.open("a.txt") + await h.store.settle() + #expect(h.store.text(for: "a.txt") == "one") + #expect(h.store.revision(for: "a.txt") != revision) + } + + @Test func withoutAPromptADirtyFileNeverClosesSilently() async { + let h = await dirtyHarness() + let closed = await h.store.requestCloseActive() + #expect(!closed) + } + + @Test func aCleanFileClosesWithoutAsking() async { + let h = EditorHarness(files: ["a.txt": "one"]) + var asked = false + h.store.confirmUnsavedClose = { _ in asked = true; return .cancel } + h.store.open("a.txt") + await h.store.settle() + #expect(await h.store.requestCloseActive()) + #expect(!asked) + } + + @Test func closingAsksOnlyAboutTheOpenFile() async { + let h = EditorHarness(files: ["a.txt": "one", "b.txt": "b"]) + h.store.open("a.txt") + await h.store.settle() + h.store.edit("two") + h.store.open("b.txt") + await h.store.settle() + var asked = false + h.store.confirmUnsavedClose = { _ in asked = true; return .cancel } + #expect(await h.store.requestCloseActive()) + #expect(!asked) + #expect(h.store.isDirty("a.txt")) + } + + @Test func resolvingUnsavedSeesABufferThatIsNoLongerOpen() async { + let h = EditorHarness(files: ["a.txt": "one", "b.txt": "b"]) + h.store.open("a.txt") + await h.store.settle() + h.store.edit("two") + h.store.open("b.txt") + await h.store.settle() + var asked: [String] = [] + h.store.confirmUnsavedClose = { asked.append($0); return .save } + #expect(await h.store.resolveUnsaved()) + #expect(asked == ["a.txt"]) + #expect(h.files.current("a.txt") == "two") + } +} + +@MainActor +@Suite struct EditorStoreReloadTests { + @Test func aWatcherChangeUpdatesACleanBuffer() async { + let h = EditorHarness(files: ["a.txt": "one"]) + h.store.open("a.txt") + await h.store.settle() + let revision = h.store.revision(for: "a.txt") + h.files.set("a.txt", "agent wrote this") + await h.store.filesChanged(["a.txt"]) + #expect(h.store.text(for: "a.txt") == "agent wrote this") + #expect(h.store.revision(for: "a.txt") != revision) + } + + @Test func aWatcherChangeNeverClobbersADirtyBuffer() async { + let h = EditorHarness(files: ["a.txt": "one"]) + h.store.open("a.txt") + await h.store.settle() + h.store.edit("my edit") + h.files.set("a.txt", "agent wrote this") + await h.store.filesChanged(nil) + #expect(h.store.text(for: "a.txt") == "my edit") + #expect(h.store.diskText["a.txt"] == "agent wrote this") + #expect(h.store.isDirty("a.txt")) + } + + @Test func forcedReloadLetsDiskWinOverTheBuffer() async { + let h = EditorHarness(files: ["a.txt": "one"]) + h.store.open("a.txt") + await h.store.settle() + h.store.edit("my edit") + h.files.set("a.txt", "agent wrote this") + await h.store.reloadActiveFromDisk() + #expect(h.store.text(for: "a.txt") == "agent wrote this") + #expect(!h.store.isDirty("a.txt")) + } + + @Test func aDiskChangeThatMatchesTheBufferCleansIt() async { + let h = EditorHarness(files: ["a.txt": "one"]) + h.store.open("a.txt") + await h.store.settle() + h.store.edit("same") + h.files.set("a.txt", "same") + await h.store.filesChanged(["a.txt"]) + #expect(!h.store.isDirty("a.txt")) + #expect(h.store.buffers["a.txt"] == nil) + } + + @Test func anImageIsReadAsBytesNotText() async { + let h = EditorHarness() + h.files.setImage("logo.png", Data([1, 2, 3])) + h.store.open("logo.png") + await h.store.settle() + #expect(h.store.image(for: "logo.png") == Data([1, 2, 3])) + #expect(h.store.diskText["logo.png"] == nil) + } +} + +@MainActor +@Suite struct EditorStoreModeTests { + @Test func aChangedFileLandsInActual() async { + let h = EditorHarness(files: ["a.php": "new"]) + h.git.change("a.php", makeDiff(original: "old", updated: "new")) + h.store.open("a.php") + #expect(h.store.mode(for: "a.php") == .actual) + #expect(h.overlays.presented.isEmpty) + } + + @Test func commandMDoesNothingOnAFileWithoutPreview() { + let h = EditorHarness(files: ["a.php": "new", "b.php": "x"]) + h.git.change("a.php", makeDiff(original: "old", updated: "new")) + h.store.open("b.php") + h.store.togglePreview() + #expect(h.store.mode(for: "b.php") == .code) + h.store.open("a.php") + h.store.togglePreview() + #expect(h.store.mode(for: "a.php") == .actual) + #expect(h.overlays.presented.isEmpty) + } + + @Test func aDiffDefaultStillLandsInActualWithoutPoppingTheOverlay() { + let h = EditorHarness(files: ["a.php": "new"]) + h.git.change("a.php", makeDiff(original: "old", updated: "new")) + h.store.defaultMode = .diff + h.store.open("a.php") + #expect(h.store.mode(for: "a.php") == .actual) + #expect(h.overlays.presented.isEmpty) + } + + @Test func unchangedMarkdownTogglesBetweenCodeAndPreview() { + let h = EditorHarness(files: ["README.md": "# x"]) + h.store.open("README.md") + h.store.togglePreview() + #expect(h.store.mode(for: "README.md") == .preview) + h.store.togglePreview() + #expect(h.store.mode(for: "README.md") == .code) + } + + @Test func changedMarkdownTogglesBetweenActualAndPreviewAndNeverTheDiff() { + let h = EditorHarness(files: ["README.md": "# x"]) + h.git.change("README.md", makeDiff(original: "", updated: "# x")) + h.store.open("README.md") + h.store.togglePreview() + #expect(h.store.mode(for: "README.md") == .preview) + h.store.togglePreview() + #expect(h.store.mode(for: "README.md") == .actual) + #expect(h.overlays.presented.isEmpty) + } + + @Test func enteringDiffPresentsTheOverlayWithTheFilesGitSide() { + let h = EditorHarness(files: ["a.php": "new"]) + h.git.change("a.php", makeDiff(original: "old", updated: "new")) + h.store.open("a.php", OpenOptions(side: .staged)) + h.store.setMode(.diff, for: "a.php") + #expect(h.overlays.presented == [.diff(DiffOverlayRequest(path: "a.php", side: .staged))]) + } + + @Test func closingTheDiffReturnsToTheModeItCovered() { + let h = EditorHarness(files: ["README.md": "new"]) + h.git.change("README.md", makeDiff(original: "old", updated: "new")) + h.store.open("README.md") + h.store.setMode(.preview, for: "README.md") + h.store.setMode(.diff, for: "README.md") + h.store.closeDiff() + #expect(h.store.mode(for: "README.md") == .preview) + } + + @Test func togglingPreviewOverTheDiffClosesTheOverlay() { + let h = EditorHarness(files: ["README.md": "new"]) + h.git.change("README.md", makeDiff(original: "old", updated: "new")) + h.store.open("README.md") + h.store.setMode(.diff, for: "README.md") + h.store.togglePreview() + #expect(h.overlays.diffDismissals == 1) + #expect(h.store.mode(for: "README.md") == .preview) + } + + @Test func aClickOnAMarkedLineOpensTheDiffOnHeadVersusDiskAtThatLine() { + let h = EditorHarness(files: ["a.php": "new"]) + h.git.change("a.php", makeDiff(original: "old", updated: "new")) + h.store.open("a.php", OpenOptions(side: .unstaged)) + h.store.openDiff(atLine: 42) + #expect(h.overlays.presented == [.diff(DiffOverlayRequest(path: "a.php", side: nil, focusLine: 42))]) + h.store.collapseDiff() + #expect(h.store.mode(for: "a.php") == .actual) + #expect(h.overlays.diffDismissals == 1) + } + + @Test func showDiffOpensStraightIntoTheOverlay() { + let h = EditorHarness(files: ["a.php": "new"]) + h.git.change("a.php", makeDiff(original: "old", updated: "new")) + h.store.open("a.php", OpenOptions(showDiff: true)) + #expect(h.store.mode(for: "a.php") == .diff) + #expect(h.overlays.presented.count == 1) + } +} + +@MainActor +@Suite struct EditorStoreSessionTests { + @Test func sessionRoundTripsTheActiveFileItsModeAndSide() async { + let h = EditorHarness(files: ["a.md": "a", "b.php": "b"]) + h.git.change("a.md", makeDiff(original: "", updated: "a")) + await h.store.restore(restoreSession: true) + h.store.open("b.php") + h.store.open("a.md", OpenOptions(side: .unstaged)) + h.store.setMode(.preview, for: "a.md") + await h.store.persist() + #expect(h.session.sessions["/fake"] == SessionState(active: "a.md", modes: ["a.md": .preview], sides: ["a.md": .unstaged])) + + let next = EditorStore(root: "/fake", files: h.files, gitState: { h.git.state }, + session: h.session, recentFiles: h.recent) + await next.restore(restoreSession: true) + #expect(next.activePath == "a.md") + #expect(next.mode(for: "a.md") == .preview) + #expect(next.sides["a.md"] == .unstaged) + #expect(next.history == ["a.md", "b.php"]) + #expect(next.text(for: "a.md") == "a") + } + + @Test func aRestoredDiffModeComesBackAsActual() async { + let h = EditorHarness(files: ["a.php": "a"]) + h.git.change("a.php", makeDiff(original: "", updated: "a")) + h.session.sessions["/fake"] = SessionState(active: "a.php", modes: ["a.php": .diff]) + await h.store.restore(restoreSession: true) + #expect(h.store.mode(for: "a.php") == .actual) + #expect(h.overlays.presented.isEmpty) + } + + @Test func withRestoreOffOnlyTheRecentFilesComeBack() async { + let h = EditorHarness(files: ["a.php": "a"], recent: ["x.php"]) + h.session.sessions["/fake"] = SessionState(active: "z.php") + await h.store.restore(restoreSession: false) + #expect(h.store.activePath == nil) + #expect(h.store.history == ["x.php"]) + h.store.open("a.php") + await h.store.settle() + #expect(h.session.sessions["/fake"]?.active == "z.php") + #expect(h.recent.paths == ["a.php", "x.php"]) + } + + @Test func nothingIsWrittenBackBeforeTheSessionWasRead() async { + let h = EditorHarness(files: ["a.php": "a"], recent: ["old.php"]) + h.store.open("a.php") + await h.store.settle() + #expect(h.recent.paths == ["old.php"]) + } +} + +@MainActor +@Suite struct EditorStorePassOnTests { + @Test func theCaretLineIsTheReferenceWithoutASelection() async { + let h = EditorHarness(files: ["src/a.php": "x"]) + h.store.open("src/a.php") + h.store.updateCursor(line: 42, column: 3) + #expect(h.store.currentReference()?.description == "src/a.php:42") + } + + @Test func aSelectionIsPassedAsARangeWithItsCode() async { + let h = EditorHarness(files: ["src/a.php": "x"]) + h.store.open("src/a.php") + h.store.updateSelection(lines: 42...58, code: "code") + let request = h.store.passOnSelectionRequest(anchor: .zero) + #expect(request == PassOnRequest(reference: "src/a.php:42-58", code: "code", anchor: .zero)) + #expect(PassOn.compose(note: "fix", reference: request!.reference, code: request!.code) == "fix src/a.php:42-58\n```\ncode\n```") + } + + @Test func withoutASelectionCommandRightPassesNothing() async { + let h = EditorHarness(files: ["src/a.php": "x"]) + h.store.open("src/a.php") + #expect(h.store.passOnSelectionRequest(anchor: .zero) == nil) + } + + @Test func theRightClickMenuIsPassOnThenCopyReference() { + let h = EditorHarness(files: ["src/a.php": "x"]) + let menu = h.store.contextMenuRequest(reference: AgentReference(path: "src/a.php", startLine: 42), code: nil, anchor: .zero) + #expect(menu.header == "src/a.php:42") + #expect(menu.entries == [ + .action(.passOnReference("src/a.php:42", code: nil), label: "Pass on reference"), + .action(.copyReference("src/a.php:42"), label: "Copy reference"), + ]) + } + + @Test func anEmptyNotePassesTheBareReference() { + #expect(PassOn.compose(note: " ", reference: "src/a.php:42") == "src/a.php:42") + } +} + +@MainActor +@Suite struct EditorStoreSymbolTests { + @Test func aSymbolLookupOpensThePopupAtOnceAndFillsItLater() async { + let h = EditorHarness() + let symbols = FakeSymbols() + symbols.lookups["User"] = SymbolLookup(name: "User", definitions: [SymbolDef(name: "User", path: "app/User.php", line: 7, kind: "class")]) + h.store.symbols = symbols + h.store.lookupSymbol("User") + #expect(h.overlays.presented == [.symbol(name: "User")]) + #expect(h.store.symbolLookup == nil) + await h.store.settle() + #expect(h.store.symbolLookup?.definitions.first?.path == "app/User.php") + } + + @Test func knownSymbolsComeFromTheSymbolService() async { + let h = EditorHarness() + let symbols = FakeSymbols() + symbols.declared = ["User", "Order"] + h.store.symbols = symbols + await h.store.loadKnownSymbols() + #expect(h.store.knownSymbols == ["User", "Order"]) + } +} + +@MainActor +@Suite struct EditorStoreStatusTests { + @Test func theStatusBarReadsPositionLanguageAndIndentation() async { + let h = EditorHarness(files: ["a.php": "x"]) + h.store.editorConfig.tabSize = 2 + h.store.open("a.php") + h.store.updateCursor(line: 3, column: 7) + #expect(h.store.cursorLine == 3) + #expect(h.store.cursorColumn == 7) + #expect(h.store.activeLanguage == "PHP") + #expect(h.store.indentationLabel == "Spaces: 2") + #expect(h.store.activeMode == .code) + } +} diff --git a/Tests/HelderUITests/Explorer/ExplorerStoreTests.swift b/Tests/HelderUITests/Explorer/ExplorerStoreTests.swift new file mode 100644 index 0000000..dc8b91d --- /dev/null +++ b/Tests/HelderUITests/Explorer/ExplorerStoreTests.swift @@ -0,0 +1,231 @@ +import CoreGraphics +import Foundation +import HelderCore +import HelderServices +import HelderUI +import Testing + +@MainActor +@Suite struct ExplorerStoreTests { + private func makeStore() async -> (ExplorerStore, FakeFiles, Recorder) { + let files = FakeFiles(tree: sampleTree(), root: URL(fileURLWithPath: "/tmp/project")) + let recorder = Recorder() + let store = ExplorerStore(files: files, system: recorder.system) + store.notify = recorder.notify + await store.reload() + return (store, files, recorder) + } + + private func paths(_ store: ExplorerStore, showHidden: Bool = false) -> [String] { + store.rows(showHidden: showHidden).map(\.path) + } + + // MARK: Tree and expansion + + @Test func aFreshTreeStartsCollapsedAndHidesDotfiles() async { + let (store, _, _) = await makeStore() + #expect(paths(store) == ["src", "empty", "README.md"]) + #expect(paths(store, showHidden: true) == [".github", "src", "empty", ".env", "README.md"]) + } + + @Test func expandingAFolderShowsItsChildrenOneLevelDeeperAndReReadsIt() async { + let (store, files, _) = await makeStore() + await store.toggle("src").value + #expect(paths(store) == ["src", "src/Http", "src/app.php", "empty", "README.md"]) + #expect(store.rows(showHidden: false)[1].depth == 1) + #expect(files.childReads == ["src"]) + } + + @Test func collapsingKeepsTheFolderButHidesItsChildren() async { + let (store, files, _) = await makeStore() + await store.toggle("src").value + await store.toggle("src").value + #expect(paths(store) == ["src", "empty", "README.md"]) + #expect(files.childReads == ["src", "src"]) + } + + @Test func expandingPicksUpFilesAddedSinceTheTreeWasRead() async { + let (store, files, _) = await makeStore() + var tree = sampleTree() + tree = FileTree.replacingChildren(of: "empty", with: [file("empty/new.txt")], in: tree) + files.setTree(tree) + await store.toggle("empty").value + #expect(paths(store).contains("empty/new.txt")) + } + + @Test func anEmptyFolderStillHasARow() async { + let (store, _, _) = await makeStore() + #expect(store.rows(showHidden: false).first { $0.path == "empty" }?.kind == .directory) + } + + @Test func reloadKeepsTheExpansion() async { + let (store, files, _) = await makeStore() + await store.toggle("src").value + await store.reload() + #expect(store.expanded == ["src"]) + #expect(files.treeLoads == 2) + } + + @Test func loadIfNeededReadsTheTreeOnlyOnce() async { + let (store, files, _) = await makeStore() + await store.loadIfNeeded() + #expect(files.treeLoads == 1) + } + + @Test func selectingAFileRevealsItsFolders() async { + let (store, _, _) = await makeStore() + store.select("src/Http/Kernel.php") + #expect(store.expanded == ["src", "src/Http"]) + #expect(store.rows(showHidden: false).first { $0.path == store.selectedPath }?.depth == 2) + } + + // MARK: Keyboard cursor + + @Test func theCursorWalksTheVisibleRowsAndClamps() async { + let (store, _, _) = await makeStore() + store.moveSelection(by: 1, showHidden: false) + #expect(store.selectedPath == "src") + store.moveSelection(by: 5, showHidden: false) + #expect(store.selectedPath == "README.md") + store.selectedPath = ".env" + store.moveSelection(by: 1, showHidden: false) + #expect(store.selectedPath == "src") + } + + // MARK: Create, rename, delete + + @Test func newFileLandsInItsFolderAndExpandsIt() async throws { + let (store, files, _) = await makeStore() + let path = try await store.createFile(in: "src/Http", name: " Router.php ") + #expect(path == "src/Http/Router.php") + #expect(files.created == ["src/Http/Router.php"]) + #expect(store.expanded.isSuperset(of: ["src", "src/Http"])) + #expect(files.treeLoads == 2) + } + + @Test func newFolderExpandsTheParentAndItself() async throws { + let (store, files, _) = await makeStore() + let path = try await store.createFolder(in: "src", name: "Jobs/") + #expect(path == "src/Jobs") + #expect(files.createdDirectories == ["src/Jobs"]) + #expect(store.expanded.isSuperset(of: ["src", "src/Jobs"])) + } + + @Test func aBlankNameCreatesNothing() async { + let (store, files, _) = await makeStore() + await #expect(throws: FileServiceError.self) { _ = try await store.createFile(in: "src", name: " ") } + #expect(files.created.isEmpty) + } + + @Test func renamingAFolderCarriesTheExpansionAndCursorAlong() async throws { + let (store, files, _) = await makeStore() + store.select("src/Http/Kernel.php") + let next = try await store.rename("src", to: "lib", isDirectory: true) + #expect(next == "lib") + #expect(files.renamed.map(\.1) == ["lib"]) + #expect(store.expanded == ["lib", "lib/Http"]) + #expect(store.selectedPath == "lib/Http/Kernel.php") + } + + @Test func anInvalidRenameNeverReachesTheDisk() async { + let (store, files, _) = await makeStore() + await #expect(throws: FileServiceError.self) { _ = try await store.rename("README.md", to: "a/b", isDirectory: false) } + #expect(files.renamed.isEmpty) + } + + @Test func deletingAFolderDropsTheCursorAndExpansionInsideIt() async throws { + let (store, files, _) = await makeStore() + store.select("src/Http/Kernel.php") + try await store.delete("src") + #expect(files.deleted == ["src"]) + #expect(store.expanded.isEmpty) + #expect(store.selectedPath == nil) + } + + // MARK: Prompt flows + + @Test func submittingTheNamePromptCreatesRenamesAndToasts() async { + let (store, _, recorder) = await makeStore() + #expect(await store.submitName("notes.md", for: .newFile(inDirectory: "")) == "notes.md") + #expect(await store.submitName("docs", for: .newFolder(inDirectory: "")) == "docs") + #expect(await store.submitName("GUIDE.md", for: .rename(path: "README.md", isDirectory: false)) == "GUIDE.md") + #expect(await store.submitName("GUIDE.md", for: .rename(path: "GUIDE.md", isDirectory: false)) == nil) + #expect(recorder.toastTitles == ["Created file", "Created folder", "Renamed file"]) + } + + @Test func aFailedCreateOrRenameSaysSoAndReturnsNil() async { + let (store, files, recorder) = await makeStore() + files.failWrites = true + #expect(await store.submitName("a.txt", for: .newFile(inDirectory: "src")) == nil) + #expect(await store.submitName("b.txt", for: .rename(path: "README.md", isDirectory: false)) == nil) + #expect(recorder.toastTitles == ["Create failed", "Rename failed"]) + #expect(recorder.toasts.map(\.1) == ["src/a.txt", "b.txt"]) + } + + @Test func thePromptPreviewShowsTheTargetPath() { + #expect(ExplorerStore.promptTarget(for: .newFile(inDirectory: "src"), name: " a.php ") == "src/a.php") + #expect(ExplorerStore.promptTarget(for: .newFolder(inDirectory: ""), name: "jobs") == "jobs/") + #expect(ExplorerStore.promptTarget(for: .rename(path: "src/Http", isDirectory: true), name: "Web") == "src/Web/") + #expect(ExplorerStore.promptTarget(for: .rename(path: "src/a.php", isDirectory: false), name: "a.php") == nil) + #expect(ExplorerStore.promptTarget(for: .newFile(inDirectory: ""), name: " ") == nil) + } + + // MARK: Menu actions + + @Test func deleteAlwaysAsksFirstAndNothingElseDoes() async { + let (store, _, _) = await makeStore() + let request = store.confirmation(for: .delete("src", isDirectory: true)) + #expect(request?.title == "Delete folder?") + #expect(request?.body == "src/ and everything inside it will be permanently deleted.") + #expect(store.confirmation(for: .delete("README.md", isDirectory: false))?.title == "Delete file?") + #expect(store.confirmation(for: .copyReference("README.md")) == nil) + #expect(store.confirmation(for: .rename("README.md", isDirectory: false)) == nil) + } + + @Test func aConfirmedDeleteRemovesAndToasts() async { + let (store, files, recorder) = await makeStore() + #expect(await store.perform(.delete("README.md", isDirectory: false))) + #expect(files.deleted == ["README.md"]) + #expect(recorder.toastTitles == ["Deleted file"]) + } + + @Test func copyActionsGoToTheClipboardWithAToast() async { + let (store, _, recorder) = await makeStore() + #expect(await store.perform(.copyReference("src/"))) + #expect(await store.perform(.copyFileName("app.php"))) + #expect(recorder.copied == ["src/", "app.php"]) + #expect(recorder.toastTitles == ["Copied reference", "Copied"]) + } + + @Test func showInFinderRevealsTheAbsolutePath() async { + let (store, files, recorder) = await makeStore() + #expect(await store.perform(.revealInFinder("src/app.php"))) + #expect(await store.perform(.revealInFinder(""))) + #expect(recorder.revealed.map(\.path) == [files.root.appendingPathComponent("src/app.php").path, files.root.path]) + } + + @Test func promptAndAgentActionsAreLeftToTheWorkspace() async { + let (store, _, _) = await makeStore() + #expect(await !store.perform(.newFile(inDirectory: "src"))) + #expect(await !store.perform(.rename("README.md", isDirectory: false))) + #expect(await !store.perform(.passOnReference("README.md", code: nil))) + } + + @Test func eachTargetGetsItsOwnMenu() { + func menu(_ target: ContextTarget) -> ContextMenuRequest { + ContextMenuRequest(target: target, header: ContextActions.header(for: target, projectName: "console"), + entries: ContextActions.entries(for: target), anchor: .zero) + } + let fileMenu = menu(.file(path: "src/app.php")) + let folderMenu = menu(.directory(path: "src")) + let rootMenu = menu(.projectRoot) + #expect(menuLabels(fileMenu) == ["Pass on reference", "Copy reference", "Pass on file name", "Copy file name", + "Rename file", "Show in Finder", "Delete file"]) + #expect(menuLabels(folderMenu) == ["Pass on reference", "Copy reference", "New file", "New folder", + "Rename folder", "Show in Finder", "Delete folder"]) + #expect(menuLabels(rootMenu) == ["New file", "Show in Finder"]) + #expect(folderMenu.header == "src/") + #expect(rootMenu.header == "console/") + #expect(ExplorerStore.target(for: TreeRow(path: "src", kind: .directory, depth: 0)) == .directory(path: "src")) + } +} diff --git a/Tests/HelderUITests/Overlays/ContextMenuTintTests.swift b/Tests/HelderUITests/Overlays/ContextMenuTintTests.swift new file mode 100644 index 0000000..323cd8b --- /dev/null +++ b/Tests/HelderUITests/Overlays/ContextMenuTintTests.swift @@ -0,0 +1,51 @@ +import CoreGraphics +import HelderCore +@testable import HelderUI +import Testing + +@Suite struct ContextMenuTintTests { + @Test func addingActionsAreTeal() { + #expect(ContextMenuOverlay.tint(for: .newFile(inDirectory: "")) == .add) + #expect(ContextMenuOverlay.tint(for: .newFolder(inDirectory: "src")) == .add) + #expect(ContextMenuOverlay.tint(for: .stage("a.php")) == .add) + } + + @Test func finderUnstageAndCopyFileNameAreAmberSoft() { + #expect(ContextMenuOverlay.tint(for: .revealInFinder("a.php")) == .modify) + #expect(ContextMenuOverlay.tint(for: .unstage("a.php")) == .modify) + #expect(ContextMenuOverlay.tint(for: .copyFileName("a.php")) == .modify) + } + + @Test func passOnOpenDiffAndRenameAreGrey() { + #expect(ContextMenuOverlay.tint(for: .passOnReference("a.php", code: nil)) == .rename) + #expect(ContextMenuOverlay.tint(for: .passOnFileName("a.php")) == .rename) + #expect(ContextMenuOverlay.tint(for: .openDiff("a.php")) == .rename) + #expect(ContextMenuOverlay.tint(for: .rename("a.php", isDirectory: false)) == .rename) + } + + @Test func copyReferenceKeepsThePlainIconThatTurnsAmberOnHighlight() { + #expect(ContextMenuOverlay.tint(for: .copyReference("a.php")) == .plain) + #expect(MenuIconTint.plain.color == nil) + } + + @Test func destructiveActionsAreAmberDeep() { + #expect(ContextMenuOverlay.tint(for: .discard("a.php")) == .danger) + #expect(ContextMenuOverlay.tint(for: .delete("a", isDirectory: true)) == .danger) + } +} + +@Suite struct MenuDismissalTests { + private let menu = CGRect(x: 100, y: 100, width: 320, height: 200) + + @Test func aClickOutsideTheMenuClosesIt() { + #expect(MenuDismissal.closes(clickAt: CGPoint(x: 20, y: 20), menuBounds: menu, sameWindow: true)) + } + + @Test func aClickOnTheMenuLeavesItOpen() { + #expect(!MenuDismissal.closes(clickAt: CGPoint(x: 150, y: 150), menuBounds: menu, sameWindow: true)) + } + + @Test func aClickInAnotherWindowLeavesItOpen() { + #expect(!MenuDismissal.closes(clickAt: CGPoint(x: 20, y: 20), menuBounds: menu, sameWindow: false)) + } +} diff --git a/Tests/HelderUITests/Overlays/NoteStoreTests.swift b/Tests/HelderUITests/Overlays/NoteStoreTests.swift new file mode 100644 index 0000000..20ac260 --- /dev/null +++ b/Tests/HelderUITests/Overlays/NoteStoreTests.swift @@ -0,0 +1,99 @@ +import HelderUI +import Testing + +@MainActor +@Suite struct NoteStoreTests { + @Test func loadsTheNoteThatIsAlreadyOnDisk() async { + let store = NoteStore(notes: FakeNotes("earlier thoughts\n")) + await store.load() + #expect(store.text == "earlier thoughts\n") + #expect(!store.isDirty) + } + + @Test func nothingIsWrittenWhileTyping() async { + let notes = FakeNotes() + let store = NoteStore(notes: notes) + await store.load() + store.text = "buy milk" + #expect(notes.writes.isEmpty) + #expect(store.isDirty) + } + + @Test func savingOnFocusLossWritesTheEditedText() async { + let notes = FakeNotes() + let store = NoteStore(notes: notes) + await store.load() + store.text = "buy milk" + await store.save() + #expect(notes.writes == ["buy milk"]) + #expect(notes.onDisk == "buy milk") + #expect(!store.isDirty) + } + + @Test func anUnchangedNoteIsNeverRewritten() async { + let notes = FakeNotes("unchanged") + let store = NoteStore(notes: notes) + await store.load() + await store.save() + await store.save() + #expect(notes.writes.isEmpty) + } + + @Test func aFailedWriteLeavesTheNoteDirtyForTheNextTry() async { + let notes = FakeNotes() + notes.failWrites = true + let store = NoteStore(notes: notes) + store.text = "keep me" + await store.save() + #expect(store.isDirty) + } + + @Test func passableTextIsTheTrimmedNote() { + let store = NoteStore(notes: FakeNotes()) + store.text = " refactor the policy\n\n" + #expect(store.passableText == "refactor the policy") + } + + @Test func anEmptyNoteHasNothingToPass() { + let store = NoteStore(notes: FakeNotes()) + store.text = " \n " + #expect(store.passableText == nil) + } + + @Test func aFailedWriteRaisesAToast() async { + let notes = FakeNotes() + notes.failWrites = true + let store = NoteStore(notes: notes) + var toasts: [String?] = [] + store.notify = { title, detail in toasts.append(title + " " + (detail ?? "")) } + store.text = "keep me" + #expect(await store.save() == false) + #expect(toasts == ["Save failed .notes.txt"]) + } + + @Test func anOutsideEditReplacesACleanNote() async { + let notes = FakeNotes("old") + let store = NoteStore(notes: notes) + await store.load() + notes.setOnDisk("new from the agent") + await store.reloadIfClean() + #expect(store.text == "new from the agent") + #expect(!store.isDirty) + } + + @Test func anOutsideEditNeverReplacesUnsavedTyping() async { + let notes = FakeNotes("old") + let store = NoteStore(notes: notes) + await store.load() + store.text = "typing" + notes.setOnDisk("new from the agent") + await store.reloadIfClean() + #expect(store.text == "typing") + } + + @Test func theFooterCountsCharacters() { + let store = NoteStore(notes: FakeNotes()) + store.text = "héllo" + #expect(store.characterCount == 5) + } +} diff --git a/Tests/HelderUITests/Overlays/OverlayListTests.swift b/Tests/HelderUITests/Overlays/OverlayListTests.swift new file mode 100644 index 0000000..888a8c2 --- /dev/null +++ b/Tests/HelderUITests/Overlays/OverlayListTests.swift @@ -0,0 +1,126 @@ +import CoreGraphics +import Foundation +import HelderCore +@testable import HelderUI +import Testing + +@Suite struct ShortcutCatalogTests { + @Test func theGroupsAreNavigateAgentGitFileInThatOrder() { + #expect(ShortcutCatalog.groups.map(\.title) == ["Navigate", "Agent", "Git", "File"]) + } + + @Test func everyShortcutTheAppHandlesIsListed() { + let listed = Set(ShortcutCatalog.groups.flatMap(\.rows).map { $0.keys.joined() }) + let handled = ["⌘F", "⌘↑↓", "↵", "⌘←→", "↑↓", "⇧⌘O", "⌘O", "⌘→", "⌘N", "⌘P", + "⌘C", "⌘↵", "⌘G", "⌘M", "⌘S", "⌘.", "⌘A", "⌘L", "Esc", + "⌘W", "⌘R", "⇧⌘N", "?", "⌘click", "⌘0", "⌘+", "⌘−"] + #expect(Set(handled).subtracting(listed).isEmpty) + } + + @Test func theNewRowsKeepTheOldFourGroups() { + func group(of keys: String) -> String? { + ShortcutCatalog.groups.first { $0.rows.contains { $0.keys.joined() == keys } }?.title + } + #expect(group(of: "⇧⌘N") == "Navigate") + #expect(group(of: "⌘click") == "Navigate") + #expect(group(of: "?") == "Navigate") + #expect(group(of: "⌘W") == "File") + #expect(group(of: "⌘R") == "File") + #expect(["⌘0", "⌘+", "⌘−"].allSatisfy { group(of: $0) == "File" }) + } + + @Test func everyRowHasKeysAndADescription() { + for row in ShortcutCatalog.groups.flatMap(\.rows) { + #expect(!row.keys.isEmpty && row.keys.allSatisfy { !$0.isEmpty }) + #expect(!row.label.isEmpty) + } + } + + @Test func theNotePassOnSitsInTheAgentGroup() { + let agent = ShortcutCatalog.groups.first { $0.title == "Agent" } + #expect(agent?.rows.contains(ShortcutRow(keys: ["⌘", "P"], label: "Pass on the whole note")) == true) + } +} + +@Suite struct ListCursorTests { + @Test func movesStopAtBothEnds() { + #expect(ListCursor.step(0, by: -1, count: 3) == 0) + #expect(ListCursor.step(2, by: 1, count: 3) == 2) + #expect(ListCursor.step(1, by: 1, count: 3) == 2) + #expect(ListCursor.step(4, by: 0, count: 0) == 0) + } + + @Test func commandDownStartsOnThePreviousFileAndCommandUpOnTheCurrentOne() { + #expect(ListCursor.recentFilesStart(movingDown: true, count: 5) == 1) + #expect(ListCursor.recentFilesStart(movingDown: true, count: 1) == 0) + #expect(ListCursor.recentFilesStart(movingDown: false, count: 5) == 0) + } +} + +@Suite struct MenuCursorTests { + private let entries: [ContextMenuEntry] = [ + .action(.copyReference("a"), label: "Copy reference"), + .separator, + .action(.rename("a", isDirectory: false), label: "Rename file"), + .action(.delete("a", isDirectory: false), label: "Delete file"), + ] + + @Test func theFirstItemIsPreHighlighted() { + #expect(MenuCursor.first(in: [.separator] + entries) == 1) + } + + @Test func arrowsSkipSeparatorsAndWrapAround() { + #expect(MenuCursor.step(0, by: 1, in: entries) == 2) + #expect(MenuCursor.step(2, by: -1, in: entries) == 0) + #expect(MenuCursor.step(3, by: 1, in: entries) == 0) + #expect(MenuCursor.step(0, by: -1, in: entries) == 3) + } +} + +@Suite struct NamePromptTextTests { + @Test func aNewFilePreviewsItsPathInTheFolder() { + let text = NamePromptText(NamePromptRequest(purpose: .newFile(inDirectory: "src"), anchor: .zero)) + #expect(text.title == "New file") + #expect(text.preview(for: " a.php ") == "src/a.php") + #expect(text.preview(for: "") == "…") + #expect(!text.canSubmit(" ")) + } + + @Test func aNewFolderPreviewEndsInASlash() { + let text = NamePromptText(NamePromptRequest(purpose: .newFolder(inDirectory: ""), anchor: .zero)) + #expect(text.title == "New folder") + #expect(text.preview(for: "docs") == "docs/") + } + + @Test func aRenameSelectsTheStemAndRefusesTheSameName() { + let request = NamePromptRequest(purpose: .rename(path: "docs/notes.md", isDirectory: false), + initialName: "notes.md", anchor: .zero) + let text = NamePromptText(request) + #expect(text.title == "Rename file") + #expect(text.previewLabel == "renames to") + #expect(text.initialSelection == NSRange(location: 0, length: 5)) + #expect(!text.canSubmit("notes.md")) + #expect(text.canSubmit("todo.md")) + #expect(text.preview(for: "todo.md") == "docs/todo.md") + } + + @Test func aDotfileRenameSelectsTheWholeName() { + let request = NamePromptRequest(purpose: .rename(path: ".env", isDirectory: false), initialName: ".env", anchor: .zero) + #expect(NamePromptText(request).initialSelection == NSRange(location: 0, length: 4)) + } +} + +@Suite struct SearchHighlightTests { + @Test func theMatchRunCoversTheQueryLengthFromTheHitOffset() { + let hit = ContentHit(line: 6, text: "use App\\UserRepository;", matchOffset: 8) + let line = SearchHighlight.line(hit, length: 4, selected: true) + let runs = line.runs.map { String(line[$0.range].characters) } + #expect(runs == ["use App\\", "User", "Repository;"]) + } + + @Test func anOffsetPastTheLineIsClamped() { + let hit = ContentHit(line: 1, text: "abc", matchOffset: 99) + let line = SearchHighlight.line(hit, length: 4, selected: false) + #expect(String(line.characters) == "abc") + } +} diff --git a/Tests/HelderUITests/Overlays/SearchComputeOnceTests.swift b/Tests/HelderUITests/Overlays/SearchComputeOnceTests.swift new file mode 100644 index 0000000..4608004 --- /dev/null +++ b/Tests/HelderUITests/Overlays/SearchComputeOnceTests.swift @@ -0,0 +1,106 @@ +import Foundation +import HelderCore +@testable import HelderUI +import Testing + +/// Counts how often the file-name ranking runs. +@MainActor +private final class CountingRanker { + var calls = 0 + + func rank(_ query: String, _ paths: [String], _ showHidden: Bool) -> [FileNameMatch] { + calls += 1 + return Fuzzy.rankFileNames(query: query, paths: paths, showHidden: showHidden) + } +} + +@MainActor +@Suite struct SearchComputeOnceTests { + private func makeModel(_ ranker: CountingRanker, results: [String: [ContentGroup]] = [:], + files: [String] = []) -> SearchModel { + let service = FakeSearch(results: results, files: files) + return SearchModel(search: service, activePath: "a.php", activeText: "user\nnone", + debounce: .milliseconds(20), ranker: { ranker.rank($0, $1, $2) }) + } + + @Test func aQueryChangeRanksTheFileNamesOnceHoweverOftenTheResultsAreRead() async { + let ranker = CountingRanker() + let model = makeModel(ranker, files: ["user.php", "user.js", "readme.md"]) + await model.start() + ranker.calls = 0 + model.setQuery("user") + for _ in 0..<5 { + _ = model.summary + _ = model.extensionChips + _ = model.fileMatches + _ = model.shownFileMatches + _ = model.emptyMessage(for: .files) + _ = model.target() + } + #expect(ranker.calls == 1) + } + + @Test func choosingATypeFiltersWithoutRankingAgain() async { + let ranker = CountingRanker() + let model = makeModel(ranker, files: ["user.php", "user.js"]) + await model.start() + model.setQuery("user") + ranker.calls = 0 + model.toggleExtension("js") + #expect(model.fileMatches.map(\.path) == ["user.js"]) + #expect(ranker.calls == 0) + } + + @Test func arrivingContentResultsDoNotRankTheFileNamesAgain() async { + let ranker = CountingRanker() + let model = makeModel(ranker, results: ["user": [ContentGroup(path: "b.js", hits: [ContentHit(line: 1, text: "user", matchOffset: 0)])]], + files: ["user.php"]) + await model.start() + model.setQuery("user") + ranker.calls = 0 + await model.pendingSearch?.value + #expect(model.groups.map(\.path) == ["b.js"]) + #expect(ranker.calls == 0) + } + + @Test func theHiddenToggleRanksAgainOnce() async { + let ranker = CountingRanker() + let model = makeModel(ranker, files: [".env", "env.php"]) + await model.start() + model.setQuery("env") + ranker.calls = 0 + model.showHidden = true + #expect(ranker.calls == 1) + #expect(Set(model.fileMatches.map(\.path)) == [".env", "env.php"]) + } + + @Test func theThisFileHitsFollowTheQuery() { + let model = makeModel(CountingRanker()) + model.setQuery("user") + #expect(model.inFileHits.map(\.line) == [1]) + model.setQuery("zzz") + #expect(model.inFileHits.isEmpty) + } +} + +@Suite struct SearchChipTooltipTests { + @Test func aChipSaysHowManyResultsItHasAndWhatAClickDoes() { + #expect(SearchModel.chipTooltip(count: 3, isChosen: false) == "3 results · click to show only this type") + #expect(SearchModel.chipTooltip(count: 1, isChosen: false) == "1 result · click to show only this type") + } + + @Test func theChosenChipOffersEveryTypeBack() { + #expect(SearchModel.chipTooltip(count: 2, isChosen: true) == "2 results · click to show every type") + } + + @MainActor + @Test func chipsCarryTheirResultCounts() async { + let service = FakeSearch(results: ["user": [ContentGroup(path: "a.php", hits: [ContentHit(line: 1, text: "user", matchOffset: 0)])]], + files: ["user.php", "user.js"]) + let model = SearchModel(search: service, debounce: .milliseconds(20)) + await model.start() + model.setQuery("user") + await model.pendingSearch?.value + #expect(model.chips == [SearchModel.ExtensionChip(ext: "php", count: 2), SearchModel.ExtensionChip(ext: "js", count: 1)]) + } +} diff --git a/Tests/HelderUITests/Overlays/SearchModelTests.swift b/Tests/HelderUITests/Overlays/SearchModelTests.swift new file mode 100644 index 0000000..fbe7d9b --- /dev/null +++ b/Tests/HelderUITests/Overlays/SearchModelTests.swift @@ -0,0 +1,232 @@ +import Foundation +import HelderCore +@testable import HelderUI +import Testing + +private func group(_ path: String, lines: ClosedRange) -> ContentGroup { + ContentGroup(path: path, hits: lines.map { ContentHit(line: $0, text: "let user = \($0)", matchOffset: 4) }) +} + +@MainActor +private func makeModel(results: [String: [ContentGroup]] = [:], delays: [String: Duration] = [:], + files: [String] = [], seed: String = "", activePath: String? = nil, + activeText: String = "", showHidden: Bool = false) -> (SearchModel, FakeSearch) { + let service = FakeSearch(results: results, delays: delays, files: files) + let model = SearchModel(search: service, seed: seed, activePath: activePath, activeText: activeText, + showHidden: showHidden, debounce: .milliseconds(20)) + return (model, service) +} + +@MainActor +@Suite struct SearchModelTests { + @Test func keystrokesWithinTheDebounceRunOnlyTheLastSearch() async { + let (model, service) = makeModel(results: ["user": [group("a.php", lines: 1...2)]]) + model.setQuery("us") + model.setQuery("use") + model.setQuery("user") + await model.pendingSearch?.value + #expect(service.contentQueries == ["user"]) + #expect(model.content.map(\.path) == ["a.php"]) + } + + @Test func aSlowStaleSearchNeverOverwritesTheNewerResult() async { + let (model, service) = makeModel( + results: ["ab": [group("old.php", lines: 1...1)], "abc": [group("new.php", lines: 1...1)]], + delays: ["ab": .milliseconds(300)] + ) + model.setQuery("ab") + #expect(await eventually { service.contentQueries == ["ab"] }) + model.setQuery("abc") + await model.pendingSearch?.value + #expect(await eventually { service.answeredQueries.contains("ab") }) + await Task.yield() + #expect(model.content.map(\.path) == ["new.php"]) + } + + @Test func contentSearchStartsAtTwoCharacters() async { + let (model, service) = makeModel() + model.setQuery("u") + await model.pendingSearch?.value + #expect(service.contentQueries.isEmpty) + #expect(model.emptyMessage(for: .project) == "Type at least two characters.") + } + + @Test func shorteningTheQueryBelowTwoCharactersClearsTheResults() async { + let (model, _) = makeModel(results: ["us": [group("a.php", lines: 1...1)]]) + model.setQuery("us") + await model.pendingSearch?.value + model.setQuery("u") + #expect(model.content.isEmpty) + } + + @Test func theSeedIsSearchedWhenTheOverlayStartsAndTheFileListLoads() async { + let (model, service) = makeModel(results: ["user": [group("a.php", lines: 1...1)]], + files: ["src/UserController.php", "public/store.js"], seed: "user") + await model.start() + await model.pendingSearch?.value + #expect(service.contentQueries == ["user"]) + #expect(model.shownFileMatches.map(\.path) == ["src/UserController.php"]) + } + + @Test func eachGroupShowsTwelveLinesButCountsEveryHit() async { + let (model, _) = makeModel(results: ["user": [group("a.php", lines: 1...18), group("b.js", lines: 5...7)]]) + model.setQuery("user") + await model.pendingSearch?.value + #expect(model.groups.map(\.hitCount) == [18, 3]) + #expect(model.groups.map(\.rows.count) == [12, 3]) + #expect(model.hitRows.map(\.index) == Array(0..<15)) + #expect(model.totalHits == 21) + } + + @Test func dotfileHitsStayHiddenUntilTheToggleIsOn() async { + let results = ["key": [group(".env", lines: 1...1), group("config/app.php", lines: 2...2)]] + let (model, _) = makeModel(results: results, files: [".env", "config/app.php"]) + await model.start() + model.setQuery("key") + await model.pendingSearch?.value + #expect(model.groups.map(\.path) == ["config/app.php"]) + model.showHidden = true + #expect(model.groups.map(\.path) == [".env", "config/app.php"]) + } + + @Test func aTypeChipFiltersBothColumnsAndAClickOnItAgainShowsEveryType() async { + let results = ["user": [group("a.php", lines: 1...1), group("b.js", lines: 1...1)]] + let (model, _) = makeModel(results: results, files: ["user.php", "user.js"]) + await model.start() + model.setQuery("user") + await model.pendingSearch?.value + #expect(Set(model.extensionChips) == ["php", "js"]) + model.toggleExtension("js") + #expect(model.groups.map(\.path) == ["b.js"]) + #expect(model.fileMatches.map(\.path) == ["user.js"]) + model.toggleExtension("js") + #expect(model.extensionFilter == nil) + #expect(model.groups.count == 2) + } + + @Test func aChosenTypeTheNewResultsNoLongerCarryFallsBackToEveryType() async { + let results = ["user": [group("a.php", lines: 1...1), group("b.js", lines: 1...1)], + "users": [group("a.php", lines: 1...1), group("c.py", lines: 1...1)]] + let (model, _) = makeModel(results: results) + model.setQuery("user") + await model.pendingSearch?.value + model.toggleExtension("js") + model.setQuery("users") + await model.pendingSearch?.value + #expect(model.extensionFilter == nil) + } + + @Test func thereAreNoChipsForASingleFileType() async { + let (model, _) = makeModel(results: ["user": [group("a.php", lines: 1...1)]]) + model.setQuery("user") + await model.pendingSearch?.value + #expect(model.extensionChips.isEmpty) + } + + @Test func theSummaryCountsThisFileHitsAndFiles() async { + let (model, _) = makeModel(results: ["user": [group("a.php", lines: 1...2)]], files: ["User.php"], + activePath: "README.md", activeText: "no match here") + await model.start() + model.setQuery("user") + await model.pendingSearch?.value + #expect(model.summary == "0 here · 2 hits · 1 file") + } + + @Test func withoutAnOpenFileThereIsNoThisFileColumn() { + let (model, _) = makeModel() + #expect(model.columns == [.project, .files]) + #expect(!model.summary.contains("here")) + } + + @Test func columnMovesStopAtTheEdgesAndStartOnProject() { + let (model, _) = makeModel(activePath: "a.php") + #expect(model.column == .project) + model.moveColumn(by: -1) + model.moveColumn(by: -1) + #expect(model.column == .thisFile) + model.moveColumn(by: 1) + model.moveColumn(by: 1) + model.moveColumn(by: 1) + #expect(model.column == .files) + } + + @Test func rowMovesStayInsideTheFocusedColumn() async { + let (model, _) = makeModel(results: ["user": [group("a.php", lines: 1...3)]], files: ["user.php", "users.php"]) + await model.start() + model.setQuery("user") + await model.pendingSearch?.value + model.moveRow(by: 5) + #expect(model.projectSelection == 2) + model.moveRow(by: -9) + #expect(model.projectSelection == 0) + model.moveColumn(by: 1) + model.moveRow(by: 1) + #expect(model.fileSelection == 1) + #expect(model.projectSelection == 0) + } + + @Test func enterOpensTheSelectedHitAtItsLine() async { + let (model, _) = makeModel(results: ["user": [group("a.php", lines: 4...6)]]) + model.setQuery("user") + await model.pendingSearch?.value + model.moveRow(by: 1) + #expect(model.target() == SearchModel.Target(path: "a.php", line: 5)) + } + + @Test func enterInTheFilesColumnOpensTheFileWithoutALine() async { + let (model, _) = makeModel(files: ["src/UserController.php"]) + await model.start() + model.setQuery("usercon") + model.moveColumn(by: 1) + #expect(model.target() == SearchModel.Target(path: "src/UserController.php", line: nil)) + } + + @Test func enterInAnEmptyProjectColumnFallsBackToTheFirstFileName() async { + let (model, _) = makeModel(files: ["user.php"]) + await model.start() + model.setQuery("user") + await model.pendingSearch?.value + #expect(model.target() == SearchModel.Target(path: "user.php", line: nil)) + } + + @Test func enterInThisFileJumpsToTheLineInTheOpenFile() { + let (model, _) = makeModel(seed: "", activePath: "notes.md", activeText: "one\nuser two\nthree user") + model.setQuery("user") + model.moveColumn(by: -1) + model.moveRow(by: 1) + #expect(model.inFileHits.map(\.line) == [2, 3]) + #expect(model.target() == SearchModel.Target(path: "notes.md", line: 3)) + } + + @Test func aNewQueryResetsEverySelection() async { + let (model, _) = makeModel(results: ["user": [group("a.php", lines: 1...3)]]) + model.setQuery("user") + await model.pendingSearch?.value + model.moveRow(by: 2) + model.setQuery("users") + #expect(model.projectSelection == 0) + } + + @Test func emptyColumnsSayOnePlainSentence() async { + let (model, _) = makeModel(activePath: "a.php", activeText: "nothing") + #expect(model.emptyMessage(for: .thisFile) == "Type to search this file.") + #expect(model.emptyMessage(for: .files) == "Type to search file names.") + model.setQuery("zzz") + await model.pendingSearch?.value + #expect(model.emptyMessage(for: .thisFile) == "No matches in this file.") + #expect(model.emptyMessage(for: .project) == "No content matches.") + #expect(model.emptyMessage(for: .files) == "No file names match.") + } + + @Test func theFocusedColumnTakesSeventyPercentAndTheSidesKeepTheirMinimum() { + let three: [SearchModel.Column] = [.thisFile, .project, .files] + let resting = SearchModel.widths(total: 1000, columns: three, focused: .project) + #expect(resting[.thisFile] == 230) + #expect(resting[.files] == 250) + #expect(resting[.project] == 520) + let files = SearchModel.widths(total: 1000, columns: three, focused: .files) + #expect(files[.files] == 700) + #expect(files[.thisFile] == 180) + #expect(files[.project] == 120) + } +} diff --git a/Tests/HelderUITests/Shell/KeyRouterTests.swift b/Tests/HelderUITests/Shell/KeyRouterTests.swift new file mode 100644 index 0000000..c510009 --- /dev/null +++ b/Tests/HelderUITests/Shell/KeyRouterTests.swift @@ -0,0 +1,152 @@ +import HelderCore +@testable import HelderUI +import Testing + +@Suite struct KeyRouterTests { + private func cmd(_ c: String, shift: Bool = false) -> KeyPress { KeyPress(.character(c), command: true, shift: shift) } + private func route(_ press: KeyPress, _ context: KeyContext = KeyContext()) -> KeyRoute { KeyRouter.route(press, context) } + + @Test(arguments: [ + ("n", Command.showNote), ("p", .push), ("s", .save), ("m", .cycleMode), ("g", .toggleGit), + ("l", .toggleAutoFit), (".", .toggleHidden), ("w", .closeFileOrWindow), + ]) + func commandLettersMapToTheirCommand(key: String, command: Command) { + #expect(route(cmd(key)) == .perform(command)) + #expect(route(cmd(key), KeyContext(owner: .text(in: .editor))) == .perform(command)) + } + + @Test func searchIsSeededWithTheSelection() { + #expect(route(cmd("f"), KeyContext(searchSeed: "needle")) == .perform(.showSearch(seed: "needle"))) + } + + @Test func shiftCommandOOpensTheRecentProjectsAndPlainOIsLeftToTheMenu() { + #expect(route(cmd("o", shift: true)) == .perform(.showRecentProjects)) + #expect(route(cmd("o")) == .pass) + #expect(route(cmd("r")) == .pass) + #expect(route(cmd("n", shift: true)) == .pass) + } + + @Test func commandASelectsTheOpenFileOutsideAFieldAndCommandLTogglesFluid() { + #expect(route(cmd("a")) == .perform(.selectAllInFile)) + #expect(route(cmd("l")) == .perform(.toggleAutoFit)) + #expect(route(cmd("a"), KeyContext(owner: .text(in: .editor))) == .pass) + #expect(route(cmd("a"), KeyContext(owner: .terminal)) == .pass) + } + + @Test func commandCFocusesTheCommitBoxUnlessThereIsSomethingToCopy() { + #expect(route(cmd("c")) == .perform(.focusCommitMessage)) + #expect(route(cmd("c"), KeyContext(owner: .text(in: .editor), hasTextSelection: true)) == .pass) + #expect(route(cmd("c"), KeyContext(hasEditorLineSelection: true)) == .pass) + #expect(route(cmd("c"), KeyContext(owner: .terminal)) == .perform(.focusCommitMessage)) + #expect(route(cmd("c"), KeyContext(owner: .terminal, hasTextSelection: true)) == .pass) + } + + @Test func commandEnterCommitsExceptInTheCommitBoxItself() { + #expect(route(KeyPress(.enter, command: true)) == .perform(.commit)) + #expect(route(KeyPress(.enter, command: true), KeyContext(owner: .text(in: .sourceControl))) == .pass) + } + + @Test func arrowsMoveTheRowCursorOnlyInAListWithoutAField() { + let list = KeyContext(activePanel: .explorer) + #expect(route(KeyPress(.down), list) == .perform(.moveRowCursor(1))) + #expect(route(KeyPress(.up), list) == .perform(.moveRowCursor(-1))) + #expect(route(KeyPress(.enter), list) == .perform(.openSelectedRow)) + #expect(route(KeyPress(.down), KeyContext(activePanel: .editor)) == .pass) + #expect(route(KeyPress(.down), KeyContext(owner: .text(in: .sourceControl), activePanel: .sourceControl)) == .pass) + #expect(route(KeyPress(.enter), KeyContext(owner: .terminal, activePanel: .terminal)) == .pass) + } + + @Test func commandRightOpensTheRowMenuPassesASelectionOrMovesFocus() { + #expect(route(KeyPress(.right, command: true), KeyContext(activePanel: .sourceControl)) == .perform(.openRowMenu)) + let selection = TextSelectionInfo(text: "x", startLine: 3, endLine: 4) + #expect(route(KeyPress(.right, command: true), KeyContext(owner: .text(in: .editor), editorTextSelection: selection)) + == .perform(.passSelection(selection))) + #expect(route(KeyPress(.right, command: true), KeyContext(hasEditorLineSelection: true, activePanel: .editor)) + == .perform(.passSelection(nil))) + #expect(route(KeyPress(.right, command: true), KeyContext(activePanel: .editor)) == .perform(.focusNeighbour(step: 1))) + #expect(route(KeyPress(.right, command: true), KeyContext(owner: .text(in: .editor))) == .pass) + } + + @Test func commandLeftMovesFocusButNotOutOfATextField() { + #expect(route(KeyPress(.left, command: true)) == .perform(.focusNeighbour(step: -1))) + #expect(route(KeyPress(.left, command: true), KeyContext(owner: .text(in: .editor))) == .pass) + } + + @Test func commandUpAndDownOpenRecentFilesFromTheEditor() { + let editor = KeyContext(focusZone: .editor, recentFileCount: 3) + #expect(route(KeyPress(.down, command: true), editor) == .perform(.showRecentFiles(initialSelection: 1))) + #expect(route(KeyPress(.up, command: true), editor) == .perform(.showRecentFiles(initialSelection: 0))) + #expect(route(KeyPress(.down, command: true), KeyContext(focusZone: .editor, recentFileCount: 1)) == .perform(.showRecentFiles(initialSelection: 0))) + #expect(route(KeyPress(.down, command: true), KeyContext(focusZone: .terminal, recentFileCount: 3)) == .pass) + #expect(route(KeyPress(.down, command: true), KeyContext(focusZone: .editor)) == .pass) + } + + @Test func questionMarkOpensHelpButTypesInAField() { + #expect(route(KeyPress(.character("?"), shift: true)) == .perform(.showShortcuts)) + #expect(route(KeyPress(.character("?"), shift: true), KeyContext(owner: .text(in: .sourceControl))) == .pass) + #expect(route(KeyPress(.character("?"), shift: true), KeyContext(owner: .terminal)) == .pass) + } + + @Test func escapeClosesAnOverlayAndOtherwiseReachesTheTerminal() { + #expect(route(KeyPress(.escape), KeyContext(overlay: .other)) == .perform(.dismissOverlay)) + #expect(route(KeyPress(.escape), KeyContext(overlay: .note, owner: .text(in: nil))) == .perform(.dismissOverlay)) + #expect(route(KeyPress(.escape), KeyContext(owner: .terminal)) == .pass) + } + + @Test func anOpenOverlayOwnsEveryOtherKey() { + let search = KeyContext(overlay: .other, activePanel: .explorer) + #expect(route(cmd("g"), search) == .pass) + #expect(route(KeyPress(.down), search) == .pass) + #expect(route(KeyPress(.right, command: true), search) == .pass) + } + + @Test func commandPPassesTheNoteWhileItIsOpen() { + #expect(route(cmd("p"), KeyContext(overlay: .note)) == .perform(.passNote)) + #expect(route(cmd("g"), KeyContext(overlay: .note)) == .pass) + } + + @Test func theBareLauncherTakesArrowsAndEnter() { + let context = KeyContext(hasProject: false) + #expect(route(KeyPress(.down), context) == .perform(.launcherMove(1))) + #expect(route(KeyPress(.up, command: true), context) == .perform(.launcherMove(-1))) + #expect(route(KeyPress(.enter), context) == .perform(.launcherActivate)) + #expect(route(cmd("o"), context) == .pass) + } + + @Test func theRecentProjectListOwnsItsKeysButEsc() { + let context = KeyContext(overlay: OverlayKind(.launcher)) + #expect(route(KeyPress(.down), context) == .pass) + #expect(route(KeyPress(.enter), context) == .pass) + #expect(route(KeyPress(.escape), context) == .perform(.dismissOverlay)) + } + + @Test func theWorkspaceShortcutsKeepWorkingOverTheDiff() { + let diff = KeyContext(overlay: .diff(busy: false), activePanel: .editor) + #expect(route(cmd("m"), diff) == .perform(.cycleMode)) + #expect(route(cmd("p"), diff) == .perform(.push)) + #expect(route(cmd("s"), diff) == .perform(.save)) + #expect(route(cmd("c"), diff) == .perform(.focusCommitMessage)) + #expect(route(KeyPress(.enter, command: true), diff) == .perform(.commit)) + #expect(route(KeyPress(.down, command: true), KeyContext(overlay: .diff(busy: false), focusZone: .editor, recentFileCount: 2)) + == .perform(.showRecentFiles(initialSelection: 1))) + #expect(route(KeyPress(.escape), diff) == .perform(.dismissOverlay)) + } + + @Test func overTheDiffCopyAndSelectAllStayWithItsPanes() { + #expect(route(cmd("c"), KeyContext(overlay: .diff(busy: false), hasTextSelection: true)) == .pass) + #expect(route(cmd("a"), KeyContext(overlay: .diff(busy: false))) == .pass) + } + + @Test func theDiffsOwnMenuOrPromptTakesEveryKey() { + let busy = KeyContext(overlay: .diff(busy: true)) + #expect(route(KeyPress(.down), busy) == .pass) + #expect(route(KeyPress(.enter), busy) == .pass) + #expect(route(KeyPress(.escape), busy) == .pass) + #expect(route(cmd("m"), busy) == .pass) + } + + @Test func controlAndOptionChordsAlwaysReachTheFocusedView() { + #expect(route(KeyPress(.character("c"), control: true)) == .pass) + #expect(route(KeyPress(.character("g"), command: true, option: true)) == .pass) + } +} diff --git a/Tests/HelderUITests/Shell/LauncherListTests.swift b/Tests/HelderUITests/Shell/LauncherListTests.swift new file mode 100644 index 0000000..5c46283 --- /dev/null +++ b/Tests/HelderUITests/Shell/LauncherListTests.swift @@ -0,0 +1,37 @@ +import HelderCore +@testable import HelderUI +import Testing + +@Suite struct LauncherListTests { + private let recents = [ + RecentProject(path: "/code/a", name: "a"), + RecentProject(path: "/code/b", name: "b"), + ] + + @Test func theFirstRowOpensTheFolderPicker() { + let list = LauncherList(recents: recents) + #expect(list.count == 3) + #expect(list.selectedChoice == .chooseFolder) + } + + @Test func arrowsMoveThroughTheRowsAndStopAtTheEnds() { + var list = LauncherList(recents: recents) + list.move(by: -1) + #expect(list.selection == 0) + list.move(by: 1) + #expect(list.selectedChoice == .open(path: "/code/a")) + list.move(by: 5) + #expect(list.selectedChoice == .open(path: "/code/b")) + } + + @Test func theOpenProjectIsNotOfferedAgain() { + let list = LauncherList(recents: recents, excluding: "/code/a") + #expect(list.recents.map(\.path) == ["/code/b"]) + } + + @Test func hoverSelectionIsClamped() { + var list = LauncherList(recents: recents) + list.select(99) + #expect(list.selection == 2) + } +} diff --git a/Tests/HelderUITests/SourceControl/SourceControlStoreTests.swift b/Tests/HelderUITests/SourceControl/SourceControlStoreTests.swift new file mode 100644 index 0000000..730bd19 --- /dev/null +++ b/Tests/HelderUITests/SourceControl/SourceControlStoreTests.swift @@ -0,0 +1,284 @@ +import Foundation +import HelderCore +import HelderServices +import HelderUI +import Testing + +@MainActor +@Suite struct SourceControlStoreTests { + private let sample = snapshot([ + ("src/b.php", .modified, false), + ("src/a.php", .added, true), + ("README.md", .modified, false), + ("src/a.php", .modified, false), + ("config/app.json", .modified, true), + ("src/c.php", .deleted, false), + ]) + + private func makeStore(_ snapshot: GitSnapshot? = nil) async -> (SourceControlStore, FakeGit, Recorder) { + let git = FakeGit(snapshot ?? sample) + let store = SourceControlStore(git: git, derive: TestDerivation.derive) + let recorder = Recorder() + store.notify = recorder.notify + await store.refresh() + return (store, git, recorder) + } + + // MARK: Loading + + @Test func refreshDerivesTheRowsFromGit() async { + let (store, _, _) = await makeStore() + #expect(store.hasLoaded) + #expect(store.state.isRepository) + #expect(store.state.stagedCount == 2) + #expect(store.state.unstagedCount == 4) + } + + @Test func aProjectWithoutGitReadsAsNotARepository() async { + let git = FakeGit(nil) + let store = SourceControlStore(git: git, derive: TestDerivation.derive) + await store.refresh() + #expect(store.hasLoaded) + #expect(!store.state.isRepository) + } + + @Test func anOlderSlowerRefreshCannotOverwriteANewerOne() async { + let git = FakeGit() + let store = SourceControlStore(git: git, derive: TestDerivation.derive) + git.queue(snapshot([("old.txt", .modified, false)]), after: .milliseconds(150)) + git.queue(snapshot([("new.txt", .modified, false)]), after: .zero) + let slow = Task { await store.refresh() } + #expect(await eventually { git.loads == 1 }) + await store.refresh() + await slow.value + #expect(store.state.changes.map(\.path) == ["new.txt"]) + } + + @Test func theDerivationRunsOffTheMainThread() async { + let onMain = Locked<[Bool]>([]) + let store = SourceControlStore(git: FakeGit(sample)) { snapshot in + onMain.mutate { $0.append(Thread.isMainThread) } + return TestDerivation.derive(snapshot) + } + await store.refresh() + #expect(onMain.current == [false]) + #expect(store.state.changes.count == 6) + } + + @Test(.timeLimit(.minutes(1))) + func aSlowDerivationOvertakenByANewerRefreshIsDropped() async { + let git = FakeGit() + git.queue(snapshot([("old.txt", .modified, false)]), after: .zero) + git.queue(snapshot([("new.txt", .modified, false)]), after: .zero) + let release = DispatchSemaphore(value: 0) + let started = Locked(0) + let store = SourceControlStore(git: git) { snapshot in + if snapshot?.changes.first?.path == "old.txt" { + started.mutate { $0 += 1 } + release.wait() + } + return TestDerivation.derive(snapshot) + } + let slow = Task { await store.refresh() } + #expect(await eventually { started.current == 1 }) + await store.refresh() + release.signal() + await slow.value + #expect(store.state.changes.map(\.path) == ["new.txt"]) + } + + @Test func loadIfNeededReadsGitOnlyOnce() async { + let (store, git, _) = await makeStore() + await store.loadIfNeeded() + #expect(git.loads == 1) + } + + // MARK: Grouping and order + + @Test func rowsWalkStagedFoldersFirstThenUnstagedFoldersInOrderOfFirstAppearance() async { + let (store, _, _) = await makeStore() + #expect(store.stagedGroups.map(\.dir) == ["src", "config"]) + #expect(store.unstagedGroups.map(\.dir) == ["src", ""]) + #expect(store.unstagedGroups[0].rows.map(\.path) == ["src/b.php", "src/a.php", "src/c.php"]) + #expect(store.rows.map(\.id) == [ + "s:src/a.php", "s:config/app.json", + "w:src/b.php", "w:src/a.php", "w:src/c.php", "w:README.md", + ]) + } + + @Test func aFileStagedAndEditedAgainHasTwoRows() async { + let (store, _, _) = await makeStore() + #expect(store.rows.filter { $0.path == "src/a.php" }.map(\.staged) == [true, false]) + } + + @Test func theExplorerLetterComesFromTheUnstagedRow() async { + let (store, _, _) = await makeStore() + #expect(store.fileStatuses["src/a.php"] == .modified) + #expect(store.fileStatuses["config/app.json"] == .modified) + #expect(store.fileStatuses["src/c.php"] == .deleted) + } + + // MARK: Keyboard cursor + + @Test func theCursorStartsAtTheTopClampsAtTheEndsAndFollowsRowIDs() async { + let (store, _, _) = await makeStore() + store.moveSelection(by: 1) + #expect(store.selectedRowID == "s:src/a.php") + store.moveSelection(by: -1) + #expect(store.selectedRowID == "s:src/a.php") + store.moveSelection(by: 100) + #expect(store.selectedRowID == "w:README.md") + #expect(store.selectedRow?.path == "README.md") + } + + @Test func aCursorWhoseRowVanishedStartsOverAtTheTop() async { + let (store, git, _) = await makeStore() + store.selectedRowID = "w:src/c.php" + git.set(snapshot([("x.txt", .modified, true)])) + await store.refresh() + store.moveSelection(by: 1) + #expect(store.selectedRowID == "s:x.txt") + } + + // MARK: Staging + + @Test func stagingAndUnstagingSendTheRowPathAndReload() async { + let (store, git, _) = await makeStore() + await store.stage("src/b.php") + await store.unstage("config/app.json") + #expect(git.staged == [["src/b.php"]]) + #expect(git.unstaged == [["config/app.json"]]) + #expect(git.loads == 3) + } + + @Test func stageAllSendsEveryPathWithAnUnstagedRowOnce() async { + let (store, git, _) = await makeStore() + await store.stageAll() + #expect(git.staged == [["src/b.php", "README.md", "src/a.php", "src/c.php"]]) + } + + @Test func unstageAllSendsEveryStagedPath() async { + let (store, git, _) = await makeStore() + await store.unstageAll() + #expect(git.unstaged == [["src/a.php", "config/app.json"]]) + } + + @Test func stageAllWithNothingToStageCallsNoGit() async { + let (store, git, _) = await makeStore(snapshot([("a.txt", .modified, true)])) + await store.stageAll() + #expect(git.staged.isEmpty) + } + + // MARK: Commit + + @Test func commitNeedsAStagedFileAndAMessage() async { + let (store, _, _) = await makeStore() + #expect(!store.canCommit) + store.setCommitMessage(" ") + #expect(!store.canCommit) + store.setCommitMessage("fix it") + #expect(store.canCommit) + + let (clean, git, _) = await makeStore(snapshot([("a.txt", .modified, false)])) + clean.setCommitMessage("fix it") + #expect(!clean.canCommit) + #expect(await clean.commit() == 0) + #expect(git.commits.isEmpty) + } + + @Test func commitSendsTheMessageClearsTheDraftAndCountsDistinctFiles() async { + let (store, git, recorder) = await makeStore() + store.setCommitMessage("add the payment service ") + let count = await store.commit() + #expect(count == 2) + #expect(git.commits == ["add the payment service"]) + #expect(store.commitMessage.isEmpty) + #expect(recorder.toastTitles == ["Committed 2 files"]) + } + + @Test func aFailedCommitKeepsTheDraft() async { + let (store, git, recorder) = await makeStore() + git.setFailCommit(true) + store.setCommitMessage("wip") + #expect(await store.commit() == 0) + #expect(store.commitMessage == "wip") + #expect(recorder.toastTitles == ["Commit failed"]) + } + + @Test func dictatedMessagesBecomeOneLowercaseLine() { + let store = SourceControlStore(git: FakeGit(), derive: TestDerivation.derive) + store.setCommitMessage("Fix The Bug\n And The Test") + #expect(store.commitMessage == "fix the bug and the test") + } + + // MARK: Push + + @Test func pushTellsTheOutcomeInAToast() async { + let (store, git, recorder) = await makeStore() + git.setPushResult(PushResult(ok: false, message: "rejected")) + let result = await store.push() + #expect(!result.ok) + #expect(!store.isPushing) + #expect(git.pushes == 1) + #expect(recorder.toastTitles == ["Pushing…", "Push failed"]) + #expect(recorder.toasts.last?.1 == "rejected") + } + + // MARK: Discard and confirmations + + @Test func discardAsksFirstWhileConfirmDiscardIsOn() async { + let (store, _, _) = await makeStore() + let request = store.confirmation(for: .discard("src/b.php")) + #expect(request?.title == "Discard changes to src/b.php?") + #expect(request?.confirmLabel == "Discard") + #expect(request?.action == .discard("src/b.php")) + + store.config.confirmDiscard = false + #expect(store.confirmation(for: .discard("src/b.php")) == nil) + } + + @Test func stagingAsksOnlyWhenTheConfigSaysSo() async { + let (store, _, _) = await makeStore() + #expect(store.confirmation(for: .stage("a")) == nil) + #expect(store.confirmation(for: .unstage("a")) == nil) + store.config.confirmStage = true + store.config.confirmUnstage = true + #expect(store.confirmation(for: .stage("a"))?.title == "Stage a?") + #expect(store.confirmation(for: .unstage("a"))?.title == "Unstage a?") + #expect(store.confirmation(for: .copyReference("a")) == nil) + } + + @Test func performRunsGitActionsAndDeclinesTheRest() async { + let (store, git, recorder) = await makeStore() + #expect(await store.perform(.discard("src/b.php"))) + #expect(git.discarded == [["src/b.php"]]) + #expect(recorder.toasts.last?.0 == "Discarded changes") + #expect(await store.perform(.stage("README.md"))) + #expect(git.staged == [["README.md"]]) + #expect(await !store.perform(.openDiff("README.md"))) + #expect(await !store.perform(.copyReference("README.md"))) + } + + // MARK: Polling + + @Test func pollingReReadsGitOnTheIntervalUntilStopped() async throws { + let (store, git, _) = await makeStore() + store.config.refreshInterval = 20 + store.startPolling() + #expect(store.isPolling) + #expect(await eventually { git.loads >= 3 }) + store.stopPolling() + #expect(!store.isPolling) + let loads = git.loads + try await Task.sleep(for: .milliseconds(100)) + // One read may already have been in flight when polling stopped. + #expect(git.loads <= loads + 1) + } + + @Test func aZeroIntervalDisablesPolling() async { + let (store, _, _) = await makeStore() + store.config.refreshInterval = 0 + store.startPolling() + #expect(!store.isPolling) + } +} diff --git a/Tests/HelderUITests/State/LayoutStoreTests.swift b/Tests/HelderUITests/State/LayoutStoreTests.swift new file mode 100644 index 0000000..11886b7 --- /dev/null +++ b/Tests/HelderUITests/State/LayoutStoreTests.swift @@ -0,0 +1,159 @@ +import HelderCore +import HelderServices +@testable import HelderUI +import Testing + +private struct MemorySession: SessionStoring { + func loadSession(root: String) -> SessionState? { nil } + func saveSession(_ session: SessionState, root: String) {} + func loadLayout() -> LayoutState { LayoutState(agentFraction: 0.9) } + func saveLayout(_ layout: LayoutState) {} +} + +@MainActor +@Suite struct LayoutStoreTests { + @Test func restoresAClampedAgentSplit() { + #expect(LayoutStore(session: MemorySession()).agentFraction == 0.82) + } + + @Test func draggingLocksTheColumns() { + let layout = LayoutStore(session: MemorySession()) + layout.windowResized(width: 1760) + #expect(layout.fluid) + layout.dragExplorer(by: 1000) + #expect(!layout.fluid) + #expect(layout.widths.explorer == 520) + } + + @Test func sourceControlDragsStayInsideTheirRange() { + let layout = LayoutStore(session: MemorySession()) + layout.dragSourceControl(by: -1000) + #expect(layout.widths.sourceControl == 160) + layout.dragSourceControl(by: 5000) + #expect(layout.widths.sourceControl == 460) + } + + @Test func theAgentColumnNeverSqueezesTheEditorBelowItsMinimum() { + let layout = LayoutStore(session: MemorySession()) + layout.windowResized(width: 1760) + layout.dragAgent(by: -5000) + let editor = 1760 - 3 - layout.widths.sourceControl - layout.widths.explorer - layout.widths.agent + #expect(editor >= ColumnLayout.minEditorWidth) + } + + @Test func roomyWindowsUseTheDesignProportions() { + let layout = LayoutStore(session: MemorySession()) + layout.windowResized(width: 1760) + #expect(layout.widths == ColumnWidths(sourceControl: 236, explorer: 289, agent: 480)) + } + + @Test func focusChangesTheFluidWidthsOnlyBelow1600() { + let layout = LayoutStore(session: MemorySession()) + layout.windowResized(width: 1500) + layout.focus(.terminal) + #expect(layout.widths.agent == 750) + layout.focus(.editor) + #expect(layout.widths.agent == 300) + layout.windowResized(width: 1800) + layout.focus(.terminal) + #expect(layout.widths.agent == (1800 * 0.273).rounded()) + } + + @Test func autoFitBackOnRefitsImmediately() { + let layout = LayoutStore(session: MemorySession()) + layout.windowResized(width: 1760) + layout.dragExplorer(by: 100) + #expect(!layout.fluid) + layout.toggleFluid() + #expect(layout.fluid) + #expect(layout.widths.explorer == 289) + } + + @Test func lockedColumnsShrinkToKeepTheEditorWhenTheWindowNarrows() { + let layout = LayoutStore(session: MemorySession()) + layout.windowResized(width: 1760) + layout.dragExplorer(by: 0) + layout.windowResized(width: 1100) + let total = layout.widths.sourceControl + layout.widths.explorer + layout.widths.agent + #expect(total <= 1100 - 3 - ColumnLayout.minEditorWidth) + } + + @Test func hidingGitDropsItsFocus() { + let layout = LayoutStore(session: MemorySession()) + layout.focus(.sourceControl) + layout.toggleGit() + #expect(layout.activePanel == nil) + layout.focus(.sourceControl) + #expect(layout.activePanel == nil) + } + + @Test func aProjectsColumnsSurviveARestart() { + let store = FakeLayouts() + let first = LayoutStore(session: MemorySession(), persistence: store) + first.restore(root: "/p") + first.windowResized(width: 1760) + first.dragExplorer(by: 40) + first.endDrag() + first.toggleGit() + + let second = LayoutStore(session: MemorySession(), persistence: store) + second.windowResized(width: 1760) + second.restore(root: "/p") + #expect(!second.fluid) + #expect(!second.gitVisible) + #expect(second.widths.explorer == first.widths.explorer) + #expect(second.widths.agent == first.widths.agent) + } + + @Test func projectsKeepSeparateLayouts() { + let store = FakeLayouts() + let layout = LayoutStore(session: MemorySession(), persistence: store) + layout.restore(root: "/a") + layout.toggleGit() + layout.restore(root: "/b") + #expect(layout.gitVisible) + layout.restore(root: "/a") + #expect(!layout.gitVisible) + } + + @Test func dragsSaveOnlyWhenTheyEnd() { + let store = FakeLayouts() + let layout = LayoutStore(session: MemorySession(), persistence: store) + layout.restore(root: "/p") + layout.dragExplorer(by: 10) + #expect(store.saved["/p"] == nil) + layout.endDrag() + #expect(store.saved["/p"]?.fluid == false) + } + + @Test func theAgentSplitFollowsTheDragAndStaysClamped() { + let session = FakeSession() + let layout = LayoutStore(session: session) + layout.dragAgentSplit(by: 100, height: 1000) + #expect(abs(layout.agentFraction - 0.62) < 0.0001) + #expect(abs(session.layout.agentFraction - 0.62) < 0.0001) + layout.dragAgentSplit(by: 5000, height: 1000) + #expect(layout.agentFraction == 0.82) + } + + @Test func aWindowXMapsToTheColumnUnderIt() { + let layout = LayoutStore(session: MemorySession()) + layout.windowResized(width: 1760) + #expect(layout.panel(atX: 10) == .sourceControl) + #expect(layout.panel(atX: 300) == .explorer) + #expect(layout.panel(atX: 900) == .editor) + #expect(layout.panel(atX: 1700) == .terminal) + #expect(layout.panel(atX: 236, splitterMargin: 4) == nil) + layout.toggleGit() + #expect(layout.panel(atX: 10) == .explorer) + } + + @Test func neighbourColumnsClampAtTheEdgesAndSkipAHiddenGitColumn() { + let layout = LayoutStore(session: MemorySession()) + #expect(layout.neighbour(of: nil, step: 1) == .terminal) + #expect(layout.neighbour(of: .terminal, step: 1) == .terminal) + #expect(layout.neighbour(of: .explorer, step: -1) == .sourceControl) + layout.toggleGit() + #expect(layout.neighbour(of: .explorer, step: -1) == .explorer) + } +} diff --git a/Tests/HelderUITests/State/OverlayStoreTests.swift b/Tests/HelderUITests/State/OverlayStoreTests.swift new file mode 100644 index 0000000..230f333 --- /dev/null +++ b/Tests/HelderUITests/State/OverlayStoreTests.swift @@ -0,0 +1,27 @@ +@testable import HelderUI +import Testing + +@MainActor +@Suite struct OverlayStoreTests { + @Test func overlaysNeverStack() { + let store = OverlayStore() + store.present(.search(seed: "foo")) + store.present(.note) + #expect(store.current == .note) + store.dismiss() + #expect(store.current == .none) + #expect(!store.isPresented) + } + + @Test func everyChangeIsReportedWithTheOverlayItReplaced() { + let store = OverlayStore() + var changes: [(Overlay, Overlay)] = [] + store.onChange = { changes.append(($0, $1)) } + store.present(.note) + store.present(.note) + store.present(.shortcuts) + store.dismiss() + #expect(changes.map(\.0) == [.none, .note, .shortcuts]) + #expect(changes.map(\.1) == [.note, .shortcuts, .none]) + } +} diff --git a/Tests/HelderUITests/State/TerminalStoreTests.swift b/Tests/HelderUITests/State/TerminalStoreTests.swift new file mode 100644 index 0000000..c2f6634 --- /dev/null +++ b/Tests/HelderUITests/State/TerminalStoreTests.swift @@ -0,0 +1,38 @@ +import HelderUI +import Testing + +@MainActor +private final class RecordingTerminal: TerminalSessionHandle { + var sent: [String] = [] + func send(_ text: String) { sent.append(text) } + func terminate() {} +} + +@MainActor +@Suite struct TerminalStoreTests { + @Test func insertIntoAgentIsABracketedPasteOnItsOwnLine() { + let store = TerminalStore(projectRoot: "/p") + let agent = RecordingTerminal() + store.attach(agent, as: .agent) + store.insertIntoAgent(text: "a.php:1") + store.insertIntoAgent(text: "b.php:2-3") + #expect(agent.sent == ["\u{1b}[200~a.php:1\u{1b}[201~", "\u{1b}[200~\nb.php:2-3\u{1b}[201~"]) + } + + @Test func enterEmptiesTheComposer() { + let store = TerminalStore() + let agent = RecordingTerminal() + store.attach(agent, as: .agent) + store.agentReceivedInput("x") + #expect(store.agentComposerHasText) + store.agentReceivedInput("\r") + store.insertIntoAgent(text: "ref") + #expect(agent.sent == ["\u{1b}[200~ref\u{1b}[201~"]) + } + + @Test func withoutAnAgentNothingIsSent() { + let store = TerminalStore() + store.insertIntoAgent(text: "ref") + #expect(!store.agentComposerHasText) + } +} diff --git a/Tests/HelderUITests/State/ToastStoreTests.swift b/Tests/HelderUITests/State/ToastStoreTests.swift new file mode 100644 index 0000000..0df9596 --- /dev/null +++ b/Tests/HelderUITests/State/ToastStoreTests.swift @@ -0,0 +1,13 @@ +@testable import HelderUI +import Testing + +@MainActor +@Suite struct ToastStoreTests { + @Test func toastsStackInArrivalOrder() { + let toasts = ToastStore() + toasts.show("Saved", detail: "a.php") + toasts.show("Pushed") + #expect(toasts.toasts.map(\.title) == ["Saved", "Pushed"]) + #expect(toasts.toasts.first?.detail == "a.php") + } +} diff --git a/Tests/HelderUITests/State/WorkspaceCloseTests.swift b/Tests/HelderUITests/State/WorkspaceCloseTests.swift new file mode 100644 index 0000000..2122735 --- /dev/null +++ b/Tests/HelderUITests/State/WorkspaceCloseTests.swift @@ -0,0 +1,132 @@ +import CoreGraphics +import Foundation +import HelderCore +import HelderServices +@testable import HelderUI +import Testing + +@MainActor +@Suite struct WorkspaceCloseTests { + private func dirtyHarness() async -> WorkspaceHarness { + let harness = WorkspaceHarness(contents: ["a.php": " Bool) async -> Bool { + let clock = ContinuousClock() + let deadline = clock.now + timeout + while clock.now < deadline { + if condition() { return true } + try? await Task.sleep(for: .milliseconds(10)) + } + return condition() +} diff --git a/Tests/HelderUITests/Support/Fakes/FakeConfig.swift b/Tests/HelderUITests/Support/Fakes/FakeConfig.swift new file mode 100644 index 0000000..e5731c0 --- /dev/null +++ b/Tests/HelderUITests/Support/Fakes/FakeConfig.swift @@ -0,0 +1,24 @@ +import Foundation +import HelderCore +import HelderServices + +/// A config service whose answer the test can change, as if `.helder/config.json` was edited. +final class FakeConfig: ConfigServicing, @unchecked Sendable { + private let state: Locked<(config: HelderConfig, resolves: Int)> + + init(_ config: HelderConfig = .defaults) { + state = Locked((config, 0)) + } + + var resolves: Int { state.current.resolves } + func set(_ config: HelderConfig) { state.mutate { $0.config = config } } + + func resolve() async -> HelderConfig { + state.mutate { state in + state.resolves += 1 + return state.config + } + } + + func current() async -> HelderConfig { state.current.config } +} diff --git a/Tests/HelderUITests/Support/Fakes/FakeFiles.swift b/Tests/HelderUITests/Support/Fakes/FakeFiles.swift new file mode 100644 index 0000000..0e220bb --- /dev/null +++ b/Tests/HelderUITests/Support/Fakes/FakeFiles.swift @@ -0,0 +1,169 @@ +import Foundation +import HelderCore +import HelderServices + +/// An in-memory project: a tree for the Explorer and file texts for the editor. Records every disk change. +final class FakeFiles: FileServicing, @unchecked Sendable { + private struct State { + var tree: FileNode + var contents: [String: String] + var images: [String: Data] = [:] + var binary: Set = [] + var treeLoads = 0 + var childReads: [String] = [] + var writes: [(path: String, text: String)] = [] + var created: [String] = [] + var createdDirectories: [String] = [] + var renamed: [(String, String)] = [] + var deleted: [String] = [] + var failWrites = false + } + + let root: URL + private let state: Locked + private let gates = Locked([String: [ReadGate]]()) + + init(tree: FileNode = FileNode(name: "project", kind: .directory, path: "", children: []), + contents: [String: String] = [:], root: URL = URL(fileURLWithPath: "/fake")) { + self.root = root + state = Locked(State(tree: tree, contents: contents)) + } + + var treeLoads: Int { state.current.treeLoads } + var childReads: [String] { state.current.childReads } + var writes: [(path: String, text: String)] { state.current.writes } + var created: [String] { state.current.created } + var createdDirectories: [String] { state.current.createdDirectories } + var renamed: [(String, String)] { state.current.renamed } + var deleted: [String] { state.current.deleted } + + /// Makes every write, create, rename and delete throw. + var failWrites: Bool { + get { state.current.failWrites } + set { state.mutate { $0.failWrites = newValue } } + } + + func setTree(_ tree: FileNode) { state.mutate { $0.tree = tree } } + func set(_ path: String, _ text: String) { state.mutate { $0.contents[path] = text } } + func setImage(_ path: String, _ data: Data) { state.mutate { $0.images[path] = data } } + /// Makes a path read as binary, as a file with NUL bytes does. + func setBinary(_ path: String) { state.mutate { $0.binary.insert(path) } } + func current(_ path: String) -> String? { state.current.contents[path] } + /// The file disappears from disk, as when another program deletes it. + func remove(_ path: String) { state.mutate { $0.contents[path] = nil } } + + /// The next read of `path` takes the contents it finds at once but returns only when the gate opens. + func holdNextRead(_ path: String) -> ReadGate { + let gate = ReadGate() + gates.mutate { $0[path, default: []].append(gate) } + return gate + } + + func tree() async -> FileNode { + state.mutate { state in + state.treeLoads += 1 + return state.tree + } + } + + func children(of directory: String) async -> [FileNode] { + state.mutate { state in + state.childReads.append(directory) + return FileTree.find(directory, in: state.tree)?.children ?? [] + } + } + + func read(_ path: String) async throws -> String { + let text = state.current.contents[path] + let gate: ReadGate? = gates.mutate { gates in + guard var waiting = gates[path], !waiting.isEmpty else { return nil } + let first = waiting.removeFirst() + gates[path] = waiting + return first + } + await gate?.wait() + guard let text else { throw CocoaError(.fileNoSuchFile) } + return text + } + + func readText(_ path: String) async throws -> FileContents { + if state.current.binary.contains(path) { return .binary } + return .text(try await read(path)) + } + + func readImage(_ path: String) async -> Data? { state.current.images[path] } + + func write(_ path: String, contents text: String) async throws { + try change { state in + state.contents[path] = text + state.writes.append((path, text)) + } + } + + func createFile(_ path: String) async throws { + try change { $0.created.append(path) } + } + + func createDirectory(_ path: String) async throws { + try change { $0.createdDirectories.append(path) } + } + + func rename(_ path: String, to name: String) async throws -> String { + try change { $0.renamed.append((path, name)) } + return PathUtils.join(PathUtils.dirname(path), name) + } + + func delete(_ path: String) async throws { + try change { $0.deleted.append(path) } + } + + private func change(_ apply: (inout State) -> Void) throws { + try state.mutate { state in + if state.failWrites { throw FakeError() } + apply(&state) + } + } +} + +func dir(_ path: String, _ children: [FileNode] = []) -> FileNode { + FileNode(name: PathUtils.basename(path), kind: .directory, path: path, children: children) +} + +func file(_ path: String) -> FileNode { + FileNode(name: PathUtils.basename(path), kind: .file, path: path) +} + +/// root/ ├ .github/ci.yml ├ src/ (Http/Kernel.php, app.php) ├ empty/ ├ .env └ README.md +func sampleTree() -> FileNode { + FileNode(name: "project", kind: .directory, path: "", children: [ + dir(".github", [file(".github/ci.yml")]), + dir("src", [dir("src/Http", [file("src/Http/Kernel.php")]), file("src/app.php")]), + dir("empty"), + file(".env"), + file("README.md"), + ]) +} + +/// Holds one read until the test opens it, so a slower read can be made to land last. +final class ReadGate: @unchecked Sendable { + private let stream: AsyncStream + private let continuation: AsyncStream.Continuation + private let started = Locked(false) + + init() { + (stream, continuation) = AsyncStream.makeStream() + } + + /// True once a read is waiting on the gate. + var isWaiting: Bool { started.current } + + func open() { + continuation.yield() + continuation.finish() + } + + func wait() async { + started.mutate { $0 = true } + for await _ in stream { break } + } +} diff --git a/Tests/HelderUITests/Support/Fakes/FakeGit.swift b/Tests/HelderUITests/Support/Fakes/FakeGit.swift new file mode 100644 index 0000000..59736ad --- /dev/null +++ b/Tests/HelderUITests/Support/Fakes/FakeGit.swift @@ -0,0 +1,72 @@ +import Foundation +import HelderCore +import HelderServices + +/// Records every git call; `load` returns queued snapshots first (each after its delay), then the current one. +final class FakeGit: GitServicing, @unchecked Sendable { + private struct State { + var loads = 0 + var staged: [[String]] = [] + var unstaged: [[String]] = [] + var commits: [String] = [] + var discarded: [[String]] = [] + var pushes = 0 + var queued: [(GitSnapshot?, Duration)] = [] + var current: GitSnapshot? + var failCommit = false + var pushResult = PushResult(ok: true, message: "main -> main") + } + + private let state: Locked + + init(_ snapshot: GitSnapshot? = nil) { + state = Locked(State(current: snapshot)) + } + + var loads: Int { state.current.loads } + var staged: [[String]] { state.current.staged } + var unstaged: [[String]] { state.current.unstaged } + var commits: [String] { state.current.commits } + var discarded: [[String]] { state.current.discarded } + var pushes: Int { state.current.pushes } + + func set(_ snapshot: GitSnapshot?) { state.mutate { $0.current = snapshot } } + func queue(_ snapshot: GitSnapshot?, after delay: Duration) { state.mutate { $0.queued.append((snapshot, delay)) } } + func setFailCommit(_ value: Bool) { state.mutate { $0.failCommit = value } } + func setPushResult(_ value: PushResult) { state.mutate { $0.pushResult = value } } + + func load() async throws -> GitSnapshot? { + let (snapshot, delay): (GitSnapshot?, Duration) = state.mutate { state in + state.loads += 1 + return state.queued.isEmpty ? (state.current, .zero) : state.queued.removeFirst() + } + if delay > .zero { try? await Task.sleep(for: delay) } + return snapshot + } + + func stage(_ paths: [String]) async throws { state.mutate { $0.staged.append(paths) } } + func unstage(_ paths: [String]) async throws { state.mutate { $0.unstaged.append(paths) } } + + func commit(message: String) async throws { + try state.mutate { state in + if state.failCommit { throw FakeError() } + state.commits.append(message) + } + } + + func push() async -> PushResult { + state.mutate { state in + state.pushes += 1 + return state.pushResult + } + } + + func discard(_ paths: [String]) async throws { state.mutate { $0.discarded.append(paths) } } +} + +/// A snapshot with one change per row: (path, status, staged). +func snapshot(_ rows: [(String, GitStatus, Bool)], branch: String = "main") -> GitSnapshot { + GitSnapshot(branch: branch, ahead: 0, canPush: false, changes: rows.map { + GitFileChange(path: $0.0, status: $0.1, staged: $0.2, original: "a", updated: "b") + }) +} diff --git a/Tests/HelderUITests/Support/Fakes/FakeLayouts.swift b/Tests/HelderUITests/Support/Fakes/FakeLayouts.swift new file mode 100644 index 0000000..6011455 --- /dev/null +++ b/Tests/HelderUITests/Support/Fakes/FakeLayouts.swift @@ -0,0 +1,26 @@ +import Foundation +import HelderCore +import HelderServices +@testable import HelderUI + +/// Column layouts per project, in memory instead of UserDefaults. +final class FakeLayouts: LayoutPersisting, @unchecked Sendable { + private let state = Locked([String: ColumnLayoutSnapshot]()) + + var saved: [String: ColumnLayoutSnapshot] { + get { state.current } + set { state.mutate { $0 = newValue } } + } + + func load(root: String) -> ColumnLayoutSnapshot? { state.current[root] } + func save(_ snapshot: ColumnLayoutSnapshot, root: String) { state.mutate { $0[root] = snapshot } } + + private let zoom = Locked(0.0) + var zoomLevel: Double { + get { zoom.current } + set { zoom.mutate { $0 = newValue } } + } + + func loadZoom() -> Double { zoom.current } + func saveZoom(_ level: Double) { zoom.mutate { $0 = level } } +} diff --git a/Tests/HelderUITests/Support/Fakes/FakeNotes.swift b/Tests/HelderUITests/Support/Fakes/FakeNotes.swift new file mode 100644 index 0000000..007e66b --- /dev/null +++ b/Tests/HelderUITests/Support/Fakes/FakeNotes.swift @@ -0,0 +1,33 @@ +import Foundation +import HelderCore +import HelderServices + +/// The project note in memory; records every write. +final class FakeNotes: NotesServicing, @unchecked Sendable { + private let state: Locked<(stored: String, writes: [String], failWrites: Bool)> + + init(_ stored: String = "") { + state = Locked((stored, [], false)) + } + + var writes: [String] { state.current.writes } + var onDisk: String { state.current.stored } + + var failWrites: Bool { + get { state.current.failWrites } + set { state.mutate { $0.failWrites = newValue } } + } + + /// Another program rewrote the note file. + func setOnDisk(_ text: String) { state.mutate { $0.stored = text } } + + func read() async -> String { state.current.stored } + + func write(_ text: String) async throws { + try state.mutate { state in + if state.failWrites { throw CocoaError(.fileWriteNoPermission) } + state.writes.append(text) + state.stored = text + } + } +} diff --git a/Tests/HelderUITests/Support/Fakes/FakeRecentFiles.swift b/Tests/HelderUITests/Support/Fakes/FakeRecentFiles.swift new file mode 100644 index 0000000..c4866d0 --- /dev/null +++ b/Tests/HelderUITests/Support/Fakes/FakeRecentFiles.swift @@ -0,0 +1,17 @@ +import Foundation +import HelderCore +import HelderServices + +/// The per-project recent-files list. +final class FakeRecentFiles: RecentFilesStoring, @unchecked Sendable { + private let state: Locked<[String]> + + init(_ paths: [String] = []) { + state = Locked(paths) + } + + var paths: [String] { state.current } + + func load() async -> [String] { state.current } + func save(_ paths: [String]) async { state.mutate { $0 = paths } } +} diff --git a/Tests/HelderUITests/Support/Fakes/FakeRecentProjects.swift b/Tests/HelderUITests/Support/Fakes/FakeRecentProjects.swift new file mode 100644 index 0000000..dc9e436 --- /dev/null +++ b/Tests/HelderUITests/Support/Fakes/FakeRecentProjects.swift @@ -0,0 +1,20 @@ +import Foundation +import HelderCore +import HelderServices + +/// The machine-wide recent-projects list; never the user's real one. +final class FakeRecentProjects: RecentProjectsStoring, @unchecked Sendable { + private let state: Locked<[RecentProject]> + + init(_ projects: [RecentProject] = []) { + state = Locked(projects) + } + + var projects: [RecentProject] { state.current } + + func list() async -> [RecentProject] { state.current } + + func add(_ path: String) async { + state.mutate { $0 = RecentLists.pushing(RecentProject(path: path, name: PathUtils.basename(path)), onto: $0) } + } +} diff --git a/Tests/HelderUITests/Support/Fakes/FakeSearch.swift b/Tests/HelderUITests/Support/Fakes/FakeSearch.swift new file mode 100644 index 0000000..46597da --- /dev/null +++ b/Tests/HelderUITests/Support/Fakes/FakeSearch.swift @@ -0,0 +1,36 @@ +import Foundation +import HelderCore +import HelderServices + +/// Canned search answers, an optional delay per query, and a log of what was asked. +final class FakeSearch: SearchServicing, @unchecked Sendable { + private let results: [String: [ContentGroup]] + private let delays: [String: Duration] + private let files: [String] + private let available: Bool + private let queries = Locked<[String]>([]) + private let answered = Locked<[String]>([]) + + init(results: [String: [ContentGroup]] = [:], delays: [String: Duration] = [:], files: [String] = [], + available: Bool = true) { + self.results = results + self.delays = delays + self.files = files + self.available = available + } + + var contentQueries: [String] { queries.current } + /// Queries whose answer has been returned, in the order they finished. + var answeredQueries: [String] { answered.current } + + func isAvailable() async -> Bool { available } + + func searchContent(_ query: String) async -> [ContentGroup] { + queries.mutate { $0.append(query) } + if let delay = delays[query] { try? await Task.sleep(for: delay) } + answered.mutate { $0.append(query) } + return results[query] ?? [] + } + + func listFiles(under directory: String?) async -> [String] { files } +} diff --git a/Tests/HelderUITests/Support/Fakes/FakeSession.swift b/Tests/HelderUITests/Support/Fakes/FakeSession.swift new file mode 100644 index 0000000..e1a1a6e --- /dev/null +++ b/Tests/HelderUITests/Support/Fakes/FakeSession.swift @@ -0,0 +1,21 @@ +import Foundation +import HelderCore +import HelderServices +@testable import HelderUI + +/// Sessions and the agent split, in memory instead of UserDefaults. +final class FakeSession: SessionStoring, @unchecked Sendable { + private let state = Locked((sessions: [String: SessionState](), layout: LayoutState())) + + var sessions: [String: SessionState] { + get { state.current.sessions } + set { state.mutate { $0.sessions = newValue } } + } + + var layout: LayoutState { state.current.layout } + + func loadSession(root: String) -> SessionState? { state.current.sessions[root] } + func saveSession(_ session: SessionState, root: String) { state.mutate { $0.sessions[root] = session } } + func loadLayout() -> LayoutState { state.current.layout } + func saveLayout(_ layout: LayoutState) { state.mutate { $0.layout = layout } } +} diff --git a/Tests/HelderUITests/Support/Fakes/FakeSymbols.swift b/Tests/HelderUITests/Support/Fakes/FakeSymbols.swift new file mode 100644 index 0000000..d9487d5 --- /dev/null +++ b/Tests/HelderUITests/Support/Fakes/FakeSymbols.swift @@ -0,0 +1,38 @@ +import Foundation +import HelderCore +import HelderServices + +/// Declared class names and lookups set by the test; counts invalidations. +final class FakeSymbols: SymbolServicing, @unchecked Sendable { + private struct State { + var declared: Set = [] + var lookups: [String: SymbolLookup] = [:] + var invalidations = 0 + var nameLoads = 0 + } + + private let state = Locked(State()) + + var declared: Set { + get { state.current.declared } + set { state.mutate { $0.declared = newValue } } + } + + var lookups: [String: SymbolLookup] { + get { state.current.lookups } + set { state.mutate { $0.lookups = newValue } } + } + + var invalidations: Int { state.current.invalidations } + var nameLoads: Int { state.current.nameLoads } + + func names() async -> Set { + state.mutate { state in + state.nameLoads += 1 + return state.declared + } + } + + func lookup(_ name: String) async -> SymbolLookup { state.current.lookups[name] ?? .empty(name) } + func invalidate() async { state.mutate { $0.invalidations += 1 } } +} diff --git a/Tests/HelderUITests/Support/Fakes/FakeSystem.swift b/Tests/HelderUITests/Support/Fakes/FakeSystem.swift new file mode 100644 index 0000000..54228e7 --- /dev/null +++ b/Tests/HelderUITests/Support/Fakes/FakeSystem.swift @@ -0,0 +1,30 @@ +import Foundation +import HelderCore +@testable import HelderUI + +/// Dialogs, pasteboard and Finder, recorded instead of shown. +@MainActor +final class FakeSystem: SystemActing { + var chosenFolder: URL? + var unsavedCloseChoice = UnsavedCloseChoice.cancel + var clipboard: String? + private(set) var copied: [String] = [] + private(set) var revealed: [URL] = [] + private(set) var unsavedCloseQuestions: [String] = [] + /// Each `openNewInstance` call's folder; nil for the launcher. + private(set) var newInstances: [URL?] = [] + + func chooseFolder() async -> URL? { chosenFolder } + func copy(_ text: String) { copied.append(text) } + func pasteboardText() -> String? { clipboard } + func revealInFinder(_ url: URL) { revealed.append(url) } + + func confirmUnsavedClose(_ path: String) -> UnsavedCloseChoice { + unsavedCloseQuestions.append(path) + return unsavedCloseChoice + } + + func openLog() {} + func revealLog() {} + func openNewInstance(_ root: URL?) { newInstances.append(root) } +} diff --git a/Tests/HelderUITests/Support/Fakes/FakeTerminal.swift b/Tests/HelderUITests/Support/Fakes/FakeTerminal.swift new file mode 100644 index 0000000..9d34189 --- /dev/null +++ b/Tests/HelderUITests/Support/Fakes/FakeTerminal.swift @@ -0,0 +1,18 @@ +import Foundation +import HelderCore +@testable import HelderUI + +/// A terminal pane without a PTY: records what the store sends and spawns. +@MainActor +final class FakeTerminal: TerminalSessionHandle { + var sent: [String] = [] + var starts: [(launch: TerminalLaunch, argv0: String)] = [] + var terminations = 0 + var selectedText: String? + var pasted: [String] = [] + + func send(_ text: String) { sent.append(text) } + func terminate() { terminations += 1 } + func paste(_ text: String) { pasted.append(text) } + func start(_ launch: TerminalLaunch, argv0: String) { starts.append((launch, argv0)) } +} diff --git a/Tests/HelderUITests/Support/Fakes/FakeWatcher.swift b/Tests/HelderUITests/Support/Fakes/FakeWatcher.swift new file mode 100644 index 0000000..f0175d0 --- /dev/null +++ b/Tests/HelderUITests/Support/Fakes/FakeWatcher.swift @@ -0,0 +1,18 @@ +import Foundation +import HelderCore +import HelderServices + +/// A watcher the test fires by hand. +final class FakeWatcher: FileWatching { + private(set) var root: URL? + private(set) var stopped = false + private var handler: (@Sendable (WatchEvent) -> Void)? + + func start(root: URL, handler: @escaping @Sendable (WatchEvent) -> Void) { + self.root = root + self.handler = handler + } + + func stop() { stopped = true } + func emit(_ event: WatchEvent) { handler?(event) } +} diff --git a/Tests/HelderUITests/Support/Fakes/Locked.swift b/Tests/HelderUITests/Support/Fakes/Locked.swift new file mode 100644 index 0000000..c121e38 --- /dev/null +++ b/Tests/HelderUITests/Support/Fakes/Locked.swift @@ -0,0 +1,22 @@ +import Foundation + +/// A value behind a lock, so a fake can be `Sendable` and still be read synchronously from a test. +final class Locked: @unchecked Sendable { + private let lock = NSLock() + private var value: Value + + init(_ value: Value) { + self.value = value + } + + var current: Value { lock.withLock { value } } + + @discardableResult + func mutate(_ change: (inout Value) throws -> T) rethrows -> T { + lock.lock() + defer { lock.unlock() } + return try change(&value) + } +} + +struct FakeError: Error {} diff --git a/Tests/HelderUITests/Support/MenuLabels.swift b/Tests/HelderUITests/Support/MenuLabels.swift new file mode 100644 index 0000000..c5db16b --- /dev/null +++ b/Tests/HelderUITests/Support/MenuLabels.swift @@ -0,0 +1,10 @@ +import HelderCore +import HelderUI + +/// The labels of a menu's action entries, separators left out. +func menuLabels(_ request: ContextMenuRequest) -> [String] { + request.entries.compactMap { entry -> String? in + guard case let .action(_, label) = entry else { return nil } + return label + } +} diff --git a/Tests/HelderUITests/Support/StoreHarnesses.swift b/Tests/HelderUITests/Support/StoreHarnesses.swift new file mode 100644 index 0000000..c6c155a --- /dev/null +++ b/Tests/HelderUITests/Support/StoreHarnesses.swift @@ -0,0 +1,78 @@ +import Foundation +import HelderCore +import HelderServices +@testable import HelderUI + +/// A simple stand-in for `GitDerivation.derive`: one row per change, no diffs. +enum TestDerivation { + static func derive(_ snapshot: GitSnapshot?) -> GitWorkingState { + guard let snapshot else { return GitWorkingState() } + let changes = snapshot.changes.map { + Change(path: $0.path, status: $0.status, added: $0.updated.isEmpty ? 0 : 1, + removed: $0.original.isEmpty ? 0 : 1, staged: $0.staged) + } + return GitWorkingState(branch: snapshot.branch, ahead: snapshot.ahead, canPush: snapshot.canPush, + changes: changes, stagedPaths: Set(changes.filter(\.staged).map(\.path)), + isRepository: true) + } +} + +/// Collects a store's toasts, plus the pasteboard and Finder calls it makes through `system`. +@MainActor +final class Recorder { + let system = FakeSystem() + var toasts: [(String, String?)] = [] + + var toastTitles: [String] { toasts.map(\.0) } + var copied: [String] { system.copied } + var revealed: [URL] { system.revealed } + + func notify(_ title: String, _ detail: String?) { + toasts.append((title, detail)) + } +} + +/// A whole-file diff built by hand, for tests that only need "this file changed". +func makeDiff(original: String, updated: String, added: Int = 1, removed: Int = 0, + isAddedFile: Bool = false, isDeletedFile: Bool = false) -> Diff { + Diff(rows: [], left: [], right: [], split: [], added: added, removed: removed, + isDeletedFile: isDeletedFile, isAddedFile: isAddedFile, original: original, updated: updated) +} + +/// The git state an EditorStore follows, mutable from a test. +@MainActor +final class GitStateBox { + var state = GitWorkingState.empty + + func change(_ path: String, _ diff: Diff) { + state.fileDiffs[path] = diff + } +} + +@MainActor +final class OverlayRecorder { + var presented: [Overlay] = [] + var diffDismissals = 0 +} + +/// An EditorStore on fakes, with its overlay hooks recorded. +@MainActor +struct EditorHarness { + let files: FakeFiles + let git = GitStateBox() + let session = FakeSession() + let recent: FakeRecentFiles + let store: EditorStore + let overlays = OverlayRecorder() + + init(files: [String: String] = [:], recent: [String] = []) { + self.files = FakeFiles(contents: files) + self.recent = FakeRecentFiles(recent) + let git = self.git + store = EditorStore(root: "/fake", files: self.files, gitState: { git.state }, + session: session, recentFiles: self.recent) + let overlays = self.overlays + store.presentOverlay = { overlays.presented.append($0) } + store.dismissDiffOverlay = { overlays.diffDismissals += 1 } + } +} diff --git a/Tests/HelderUITests/Support/Tags.swift b/Tests/HelderUITests/Support/Tags.swift new file mode 100644 index 0000000..fa5c6d1 --- /dev/null +++ b/Tests/HelderUITests/Support/Tags.swift @@ -0,0 +1,6 @@ +import Testing + +extension Tag { + /// Spawns a real process in a pseudo-terminal. + @Tag static var realProcess: Self +} diff --git a/Tests/HelderUITests/Support/WorkspaceHarness.swift b/Tests/HelderUITests/Support/WorkspaceHarness.swift new file mode 100644 index 0000000..99b6328 --- /dev/null +++ b/Tests/HelderUITests/Support/WorkspaceHarness.swift @@ -0,0 +1,83 @@ +import Foundation +import HelderCore +import HelderServices +@testable import HelderUI + +/// A workspace wired entirely to fakes (no disk, no git, no user defaults), with a handle on each fake. +@MainActor +struct WorkspaceHarness { + let root: URL + let model: WorkspaceModel + let git: FakeGit + let files: FakeFiles + let config: FakeConfig + let notes: FakeNotes + let symbols: FakeSymbols + let recentFiles: FakeRecentFiles + let recents: FakeRecentProjects + let session: FakeSession + let layouts: FakeLayouts + let system: FakeSystem + let watchers: WatcherBox + let agent = FakeTerminal() + + final class WatcherBox { + var made: [FakeWatcher] = [] + var last: FakeWatcher? { made.last } + } + + init(root: URL? = URL(fileURLWithPath: "/fake/project"), config: HelderConfig = .defaults, note: String = "", + git: GitSnapshot? = nil, tree: FileNode = sampleTree(), contents: [String: String] = [:], + recents: [RecentProject] = [], session: FakeSession = FakeSession()) { + let git = FakeGit(git) + let files = FakeFiles(tree: tree, contents: contents, root: root ?? URL(fileURLWithPath: "/")) + let config = FakeConfig(config) + let notes = FakeNotes(note) + let symbols = FakeSymbols() + let recentFiles = FakeRecentFiles() + let recentStore = FakeRecentProjects(recents) + let layouts = FakeLayouts() + let system = FakeSystem() + let watchers = WatcherBox() + let app = AppServices( + recentProjects: recentStore, session: session, layouts: layouts, system: system, + makeWorkspace: { _ in + WorkspaceServices(git: git, files: files, search: FakeSearch(), symbols: symbols, + config: config, notes: notes, recentFiles: recentFiles) + }, + makeWatcher: { + let watcher = FakeWatcher() + watchers.made.append(watcher) + return watcher + } + ) + model = WorkspaceModel(root: root, app: app, timings: .immediate) + self.root = root ?? URL(fileURLWithPath: "/") + self.git = git + self.files = files + self.config = config + self.notes = notes + self.symbols = symbols + self.recentFiles = recentFiles + self.recents = recentStore + self.session = session + self.layouts = layouts + self.system = system + self.watchers = watchers + model.terminal.attach(agent, as: .agent) + } + + /// Starts the model and waits for everything it kicked off. + func start() async { + await model.start() + await model.settle() + } + + /// Runs a command and waits for the work it started. + func perform(_ command: Command) async { + model.perform(command) + await model.settle() + } + + var toastTitles: [String] { model.toasts.toasts.map(\.title) } +} diff --git a/Tests/HelderUITests/Terminal/TerminalStoreSessionTests.swift b/Tests/HelderUITests/Terminal/TerminalStoreSessionTests.swift new file mode 100644 index 0000000..8a781e2 --- /dev/null +++ b/Tests/HelderUITests/Terminal/TerminalStoreSessionTests.swift @@ -0,0 +1,230 @@ +import Foundation +import HelderCore +@testable import HelderUI +import Testing + +@MainActor +@Suite struct TerminalStoreSessionTests { + private let guiEnvironment = [ + "SHELL": "/bin/zsh", "HOME": "/Users/me", "PATH": "/usr/bin:/bin", + "npm_config_prefix": "/opt/homebrew", + ] + + @Test func theAgentPaneRunsTheConfiguredCommandThroughAnInteractiveShellInTheProject() { + let store = TerminalStore(projectRoot: "/code/app", environment: guiEnvironment) + store.config.ai.command = "claude --continue" + let launch = store.launch(for: .agent) + #expect(launch.executable == "/bin/zsh") + #expect(launch.arguments == ["-i", "-c", "claude --continue"]) + #expect(launch.workingDirectory == "/code/app") + } + + @Test func theAgentPaneIsAPlainShellWhenAutoLaunchIsOff() { + let store = TerminalStore(projectRoot: "/code/app", environment: guiEnvironment) + store.config.ai.autoLaunch = false + #expect(store.launch(for: .agent).arguments.isEmpty) + } + + @Test func theShellPaneUsesTheConfiguredShellOverTheLoginOne() { + let store = TerminalStore(projectRoot: "/code/app", environment: guiEnvironment) + #expect(store.launch(for: .shell).executable == "/bin/zsh") + store.config.terminal.shell = "/opt/homebrew/bin/fish" + let launch = store.launch(for: .shell) + #expect(launch.executable == "/opt/homebrew/bin/fish") + #expect(launch.arguments.isEmpty) + } + + @Test func theChildEnvironmentGetsAUTF8LocaleTruecolorAndNoNpmPrefix() { + let env = TerminalStore(projectRoot: "/p", environment: guiEnvironment).launch(for: .shell).environment + #expect(env["TERM"] == "xterm-256color") + #expect(env["COLORTERM"] == "truecolor") + #expect(env["LANG"] == "en_US.UTF-8") + #expect(env["npm_config_prefix"] == nil) + #expect(env["PATH"] == "/usr/bin:/bin") + } + + @Test func withoutAProjectThePanesStartInTheHomeFolder() { + let store = TerminalStore(projectRoot: nil, environment: guiEnvironment) + #expect(store.launch(for: .shell).workingDirectory == "/Users/me") + } + + @Test func everyPaneStartsAsALoginShellSoTheProfileRepairsPath() { + #expect(TerminalStore.loginArgv0(for: "/bin/zsh") == "-zsh") + #expect(TerminalStore.loginArgv0(for: "/opt/homebrew/bin/fish") == "-fish") + } + + @Test func startingAPaneAttachesItAndSpawnsItsLaunch() { + let store = TerminalStore(projectRoot: "/p", environment: guiEnvironment) + let agent = FakeTerminal() + store.start(.agent, on: agent) + #expect(store.agent === agent) + #expect(agent.starts.count == 1) + #expect(agent.starts.first?.launch == store.launch(for: .agent)) + #expect(agent.starts.first?.argv0 == "-zsh") + } + + @Test func panesWaitUntilTheProjectConfigArrives() { + let store = TerminalStore(projectRoot: "/p", environment: guiEnvironment) + #expect(!store.isConfigured) + store.config = HelderConfig.defaults + #expect(store.isConfigured) + } + + @Test func anExitIsReportedPerPane() { + let store = TerminalStore(projectRoot: "/p", environment: guiEnvironment) + store.start(.shell, on: FakeTerminal()) + store.processExited(.shell, exitCode: 1) + #expect(store.hasExited(.shell)) + #expect(!store.hasExited(.agent)) + } + + @Test func restartKillsTheOldProcessAndSpawnsAFreshOne() { + let store = TerminalStore(projectRoot: "/p", environment: guiEnvironment) + let agent = FakeTerminal() + store.start(.agent, on: agent) + store.agentReceivedInput("half typed") + store.processExited(.agent, exitCode: 0) + store.restart(.agent) + #expect(agent.terminations == 1) + #expect(agent.starts.count == 2) + #expect(!store.agentExited) + #expect(!store.agentComposerHasText) + } + + @Test func restartWithoutAPaneDoesNothing() { + let store = TerminalStore(projectRoot: "/p", environment: guiEnvironment) + store.restart(.shell) + #expect(store.shell == nil) + } + + @Test func aMultiLinePasteIsWrappedAsOneBracketedPasteAndNeverSubmits() { + let store = TerminalStore(projectRoot: "/p", environment: guiEnvironment) + let agent = FakeTerminal() + store.start(.agent, on: agent) + store.insertIntoAgent(text: "fix this\n```\nlet x = 1\n```") + #expect(agent.sent == ["\u{1b}[200~fix this\n```\nlet x = 1\n```\u{1b}[201~"]) + #expect(agent.sent.allSatisfy { !$0.hasSuffix("\r") }) + } + + @Test func aPasteAfterTypingStartsOnAFreshLine() { + let store = TerminalStore(projectRoot: "/p", environment: guiEnvironment) + let agent = FakeTerminal() + store.start(.agent, on: agent) + store.agentReceivedInput("h") + store.insertIntoAgent(text: "a.php:3") + #expect(agent.sent == ["\u{1b}[200~\na.php:3\u{1b}[201~"]) + } + + @Test func controlSequencesDoNotCountAsComposerText() { + let store = TerminalStore(projectRoot: "/p", environment: guiEnvironment) + store.start(.agent, on: FakeTerminal()) + store.agentReceivedInput("\u{1b}[A") + #expect(!store.agentComposerHasText) + } + + @Test func closingTheWindowTerminatesBothPanes() { + let store = TerminalStore(projectRoot: "/p", environment: guiEnvironment) + let agent = FakeTerminal() + let shell = FakeTerminal() + store.start(.agent, on: agent) + store.start(.shell, on: shell) + store.terminateAll() + #expect(agent.terminations == 1) + #expect(shell.terminations == 1) + #expect(store.agent == nil && store.shell == nil) + } + + @Test func aClosingWindowReleasesItsPaneOnceEvenAfterTerminateAll() { + let store = TerminalStore(projectRoot: "/p", environment: guiEnvironment) + let agent = FakeTerminal() + let shell = FakeTerminal() + store.start(.agent, on: agent) + store.start(.shell, on: shell) + store.release(agent) + #expect(agent.terminations == 1) + #expect(store.agent == nil) + store.terminateAll() + store.release(shell) + #expect(agent.terminations == 1) + #expect(shell.terminations == 1) + } + + @Test func pastingIntoTheAgentMarksItsComposerAsFilled() { + let store = TerminalStore(projectRoot: "/p", environment: guiEnvironment) + let agent = FakeTerminal() + store.start(.agent, on: agent) + store.paste("hello", into: .agent) + store.paste("", into: .agent) + #expect(agent.pasted == ["hello"]) + #expect(store.agentComposerHasText) + } + + @Test func anEmptySelectionReadsAsNone() { + let store = TerminalStore(projectRoot: "/p", environment: guiEnvironment) + let shell = FakeTerminal() + store.start(.shell, on: shell) + #expect(store.selection(.shell) == nil) + shell.selectedText = "" + #expect(store.selection(.shell) == nil) + shell.selectedText = "ls -la" + #expect(store.selection(.shell) == "ls -la") + } +} + +@MainActor +@Suite struct TerminalPseudoTerminalTests { + @Test(.tags(.realProcess), .timeLimit(.minutes(1))) + func aRealChildRunsInAPseudoTerminalAndItsExitIsReported() async throws { + let store = TerminalStore(projectRoot: NSTemporaryDirectory(), environment: ["PATH": "/usr/bin:/bin"]) + let view = HelderTerminalView(kind: .shell, store: store) + store.attach(view, as: .shell) + view.start(TerminalLaunch(executable: "/bin/echo", arguments: ["helder-smoke"], + environment: ["PATH": "/usr/bin:/bin", "TERM": "xterm-256color"], + workingDirectory: "/tmp"), + argv0: "echo") + let screen = { String(decoding: view.terminal.getBufferAsData(), as: UTF8.self) } + #expect(await eventually(timeout: .seconds(20)) { screen().contains("helder-smoke") }) + #expect(await eventually(timeout: .seconds(20)) { store.shellExited }) + #expect(await eventually { screen().contains("[process exited]") }) + view.terminate() + } + + @Test(.tags(.realProcess), .timeLimit(.minutes(1))) + func closingThePanesReapsTheChildSoNoZombieIsLeft() async throws { + let store = TerminalStore(projectRoot: NSTemporaryDirectory(), environment: ["PATH": "/usr/bin:/bin"]) + let view = HelderTerminalView(kind: .shell, store: store) + store.attach(view, as: .shell) + view.start(TerminalLaunch(executable: "/bin/sleep", arguments: ["30"], + environment: ["PATH": "/usr/bin:/bin"], workingDirectory: "/tmp"), + argv0: "sleep") + let pid = try #require(view.processID) + #expect(kill(pid, 0) == 0) + store.terminateAll() + #expect(await eventually(timeout: .seconds(20)) { kill(pid, 0) == -1 && errno == ESRCH }) + } + + @Test(.tags(.realProcess), .timeLimit(.minutes(1))) + func restartingAPaneReapsTheOldChild() async throws { + let store = TerminalStore(projectRoot: NSTemporaryDirectory(), environment: ["PATH": "/usr/bin:/bin", "SHELL": "/bin/sh"]) + store.config.ai.autoLaunch = false + let view = HelderTerminalView(kind: .shell, store: store) + store.start(.shell, on: view) + let first = try #require(view.processID) + store.restart(.shell) + let second = try #require(view.processID) + #expect(first != second) + #expect(await eventually(timeout: .seconds(20)) { kill(first, 0) == -1 && errno == ESRCH }) + store.terminateAll() + #expect(await eventually(timeout: .seconds(20)) { kill(second, 0) == -1 && errno == ESRCH }) + } +} + +@MainActor +@Suite struct TerminalZoomTests { + @Test func theTerminalFontFollowsTheWindowZoom() { + var settings = HelderConfig.defaults.terminal + settings.fontSize = 10 + #expect(TerminalAppearance.font(settings).pointSize == 10) + #expect(abs(TerminalAppearance.font(settings, scale: 1.2).pointSize - 12) < 0.001) + } +} diff --git a/Tests/HelderUITests/Theme/FontRegistryTests.swift b/Tests/HelderUITests/Theme/FontRegistryTests.swift new file mode 100644 index 0000000..5c045ee --- /dev/null +++ b/Tests/HelderUITests/Theme/FontRegistryTests.swift @@ -0,0 +1,26 @@ +import AppKit +import HelderUI +import Testing + +@Suite struct FontRegistryTests { + @Test func bundledPlexFacesRegister() { + let names = FontRegistry.registerBundledFonts() + for face in PlexFace.allCases { + #expect(names.contains(face.rawValue), "missing \(face.rawValue)") + #expect(NSFont(name: face.rawValue, size: 12) != nil) + } + } + + @Test func typeRolesResolveToPlex() { + FontRegistry.registerBundledFonts() + #expect(Typography.code.nsFont.fontName == "IBMPlexMono-Regular") + #expect(Typography.row.nsFont.fontName == "IBMPlexSans-Regular") + } +} + +@Suite struct CommitLabelTests { + @Test func theCommitLabelIsPlexSansSemiBold() { + FontRegistry.registerBundledFonts() + #expect(Typography.commitButton.nsFont.fontName == "IBMPlexSans-SemiBold") + } +} diff --git a/Tests/HelderUITests/Theme/PaletteTests.swift b/Tests/HelderUITests/Theme/PaletteTests.swift new file mode 100644 index 0000000..e50e43f --- /dev/null +++ b/Tests/HelderUITests/Theme/PaletteTests.swift @@ -0,0 +1,13 @@ +import AppKit +import HelderUI +import Testing + +@Suite struct PaletteTests { + @Test func parsesTheConfigColourFormats() throws { + let hex = try #require(NSColor(css: "#E8913A")) + #expect(abs(hex.redComponent - 232.0 / 255) < 0.001) + let rgba = try #require(NSColor(css: "rgba(232,145,58,0.22)")) + #expect(abs(rgba.alphaComponent - 0.22) < 0.001) + #expect(NSColor(css: "teal") == nil) + } +} diff --git a/assets/icon.png b/assets/icon.png new file mode 100644 index 0000000..4dd1f5a Binary files /dev/null and b/assets/icon.png differ diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..1524674 --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,106 @@ +# Architecture + +Swift package at the repo root, macOS 14+, one project per window and one window per process. The behaviour spec is [behaviour.md](behaviour.md), the visual system [design/README.md](design/README.md). + +## Layers + +``` +Helder (executable) → HelderUI → HelderServices → HelderCore + └→ SwiftTerm +``` + +| Target | May import | Rules | +|---|---|---| +| `HelderCore` | Foundation | Pure logic and value types, all `Sendable`. No AppKit, no SwiftUI, no disk, no processes. Swift 6 mode. | +| `HelderServices` | HelderCore, Foundation, CoreServices | Everything that touches disk or spawns `git`/`rg`, behind a protocol. Processes only through `ProcessRunning`. | +| `HelderUI` | Core, Services, SwiftUI, AppKit, SwiftTerm | `@Observable @MainActor` stores plus views. Never runs a process or touches project files directly, only through the service protocols (the SwiftTerm terminals are the one exception). | +| `Helder` | HelderUI | The `@main` app. Keep it tiny. | + +## How a window works + +- `WorkspaceModel` owns one window (`WorkspaceModel.swift`: state and `perform`; `+Commands`, `+ContextActions`, `+Lifecycle`, `+Refresh` hold the rest): the stores (`SourceControlStore`, `ExplorerStore`, `EditorStore`, `NoteStore`, `TerminalStore`, `LayoutStore`, `OverlayStore`, `ToastStore`) and every action that spans more than one of them. A store never reaches into a sibling; `EditorStore` only reads the git state through a closure. +- **One entry point.** Views, the menu bar and the key router all call `WorkspaceModel.perform(Command)` (`Shell/Command.swift`). Context-menu items arrive as `.context(ContextAction)`; the model asks `SourceControlStore.confirmation(for:)` / `ExplorerStore.confirmation(for:)` first and shows the confirm overlay, and `.confirmPending` runs the action. The name prompt submits with `.submitName`, the pass-on prompt with `.passToAgent`, the note's ⌘P with `.passNote`. +- **Overlays never stack.** `OverlayStore.current` is one `Overlay` enum; only the model presents or dismisses it. `OverlayStore.onChange` lets the model run closing behaviour however an overlay went away (the note saves, the Diff gives back the mode it covered). `OverlayHost` draws the current overlay. `.launcher` is the ⇧⌘O "Open recent project" list; the bare window's launcher is part of the shell, not an overlay. The key router only sees `OverlayKind` (`none`, `note`, `diff(busy:)`, `other`): over the Diff the workspace keys keep working unless its own menu or prompt is open (`busy`). Toasts (`ToastStore`) may sit on top. The Diff draws its own right-click menu and pass-on prompt inside itself, so it stays open. +- **Stores report, the model shows.** Stores raise toasts through `notify`/`showToast` hooks the model wires to `ToastStore`; the model never toasts a second time for the same action. +- **Closing.** A window close, a project switch and ⌘Q all run `prepareToClose()` first: every unsaved file is asked about, and a cancel keeps everything open. Then `closeProject()` waits for running work, writes the note and session and ends the terminals. +- **Lifecycle.** `start()`: recents → config (applied to every store and the terminals) → git, tree and note in parallel → `editor.restore` → watcher → git polling (`git.refreshInterval`) → the PHP class list 1.5 s later. Watcher events: `.project` re-reads git, the tree, the open file and every unsaved buffer (the edits kept), invalidates the symbol index and reloads the class list 2 s after the last change; `.git` re-reads git; `.config` re-resolves and re-applies the config. ⌘R re-reads git and the tree and lets the disk win in the open file. A project switch or window close saves the note and the session, stops the watcher and polling, and ends both terminals. +- **Terminals.** `TerminalStore` owns both panes' handles. Ending a pane goes through the store (`terminateAll`, `restart`, or `release` when a pane's window closes), which signals the child and lets `ChildReaper` collect it, so no zombie or orphan is left. A pane whose child exited restarts on the next key press. Right-click raises `contextMenuRequested`; the model shows the app's own menu (`.terminal` target: Copy with a selection, Paste). Font size follows `layout.textScale` (⌘0/⌘+/⌘−) live. +- **Git and files.** Git gets paths as literal pathspecs (`GIT_LITERAL_PATHSPECS=1`, so `pages/[id].vue` is one file). A changed file over `FileLimits.maxDiffFileBytes` (1 MB) keeps its row but loads no text: `GitFileChange.isTooBig` → `Diff.isTooBig`, and the Diff shows "Too big.". Saves are atomic (temp file, then rename, keeping permissions). Writes, creates, renames and deletes are refused when the entry's folder resolves (symlinks included) outside the project (`containedURL`). The watcher drops `IgnoreRules.walkIgnoredNames`, framework caches (`storage/framework/`, `bootstrap/cache/`, `.phpunit*`) and `files.exclude`. +- **Processes.** Every new window (⇧⌘N, the Dock's New Window, Open Folder or Open Recent with no key window) is a new Helder process via `SystemActing.openNewInstance`: `NSWorkspace` with `createsNewApplicationInstance` in the bundle, `InstanceLauncher` (Foundation `Process`) under `swift run`. The folder travels as `-HelderProject `, which `ProjectLocator.initialRoot` reads as its directory argument; a bare path could reach AppKit as a file to open. Switching projects (⌘O, Open Recent in a window) stays in the process. `AppName` renames the process to the project's title (the launcher is "Helder"), so Mission Control, the Dock and ⌘Tab tell projects apart. Windows are not restorable and `NSQuitAlwaysKeepsWindows` is off, so a launch opens exactly one window. +- **Editor.** `EditorStore` shows exactly one file (`activePath`); opening another replaces it, and there are no tabs. Unsaved buffers live per path in `states` and outlive the file being open, so switching away never prompts and coming back shows the edits; `dirtyPaths` and the close/quit flow see every one. ⌘W closes the open file (asking first when dirty) and shows the empty state. `EditorBar` above the code shows the type badge, the path, the unsaved dot and `+N`/`−N`, then a Preview button for Markdown and a Diff button for a changed file (`EditorPresentation.barButtons`). A changed file shows Actual (the live buffer with changed lines marked), an unchanged one plain code; ⌘M only flips Markdown between code and preview. The session stores the open file and its mode and side; a stored `openTabs` list and unknown modes are ignored. +- **Focus.** `WorkspaceModel.focusRequest` names where the keyboard should go (a column, the commit box); the view that takes it calls `focusTaken(_:)`. The editor's text view follows `EditorStore.textFocusRequest`, which also moves when the Diff closes. + +## Where things live + +``` +Sources/HelderCore/ + Agent/ AgentReference, BracketedPaste, TerminalLaunch + Config/ HelderConfig (tolerant decoding), config resolution, .env title + Diff/ Diff models, LineDiff, DiffViews, ViewMode + Files/ FileNode + FileTree, PathUtils, FileType (language, badge), limits + ignore rules, ContextActions (menus) + Git/ GitStatus/Change/GitSnapshot, Porcelain parsing, GitDerivation (rows, grouping, commit text) + Highlight/ SyntaxHighlighter and one grammar per language + Markdown/ block/inline tree and parser + Search/ result models, Fuzzy, InFileSearch, rg --json parsing + Session/ SessionState, LayoutState, recents, ColumnLayout, Cursor/LineSelection/OpenOptions + Symbols/ PHP symbol models and line parsers +Sources/HelderServices/ + Files/ FileServicing (read, readText → .binary), FileService, FSEventsWatcher + WatchDebounce + Git/ GitServicing, GitService, GitDirectory (worktrees) + Logging/ Log (unified log) + FileLogger (~/Library/Logs/Helder/helder.log) + Process/ ProcessRunner, ExecutableLocator, ChildReaper, InstanceLauncher + Project/ ConfigService, NotesService, RecentStores, SessionStore, ProjectLocator + Search/ SearchServicing + RipgrepSearchService, ProjectScanner (rg, or a Swift walk) + Symbols/ SymbolService +Sources/HelderUI/ + State/ WorkspaceModel (+ extension files), WorkspaceServices/AppServices, one file per store + Shell/ AppDelegate, HelderScene (menus), WorkspaceWindow, WindowBridge (NSWindow, key monitor), AppName, + KeyRouter, Command, SystemActions, title bar, status bar, launcher, toasts, focus flash + Components/ OverlayShell/OverlayCard/OverlayHeader/OverlayFooter, ContextMenuPanel/Header/Row/Separator, + Keycap, EscChip, Primary/Secondary button styles, focusRing, SegmentButton, Splitter, + ToolbarToggle, Tooltip, TypeBadge, PanelLabel/PanelHeader, Hairline, selectableRow, Blink + SourceControl/ the git column and the commit box + Explorer/ the file tree column and the row glyphs + Editor/ the bar above the code, code/markdown/image panes, Diff overlay, pass-on panel, symbol popup + Terminal/ agent + shell panes over SwiftTerm + Overlays/ OverlayHost, search, note, shortcuts, recent files, context menu, name prompt, confirm, OverlayKeys + Theme/ Palette, Typography, Metrics, FontRegistry + Resources/Fonts/ IBM Plex Mono 400–700, Plex Sans 400/500/600/700/400i (WOFF2, OFL) +Tests/Tests// +Tests/HelderUITests/Support/ WorkspaceHarness, StoreHarnesses (EditorHarness, Recorder), Eventually, Tags +Tests/HelderUITests/Support/Fakes/ one fake per service protocol (FakeGit, FakeFiles, FakeSystem, …) +assets/icon.png the app icon; bundle.sh turns it into Helder.icns +vendor/ripgrep/rg ripgrep 15 for Apple silicon, from the @vscode/ripgrep build (its LICENSE beside it), bundled as Contents/Helpers/rg +docs/design/ design tokens, the design canvas and reference screenshots +``` + +## Commands + +```bash +scripts/build.sh [--release] +scripts/test.sh [--filter Name] # e.g. --filter HelderUITests. or --filter WorkspaceModel +scripts/run.sh [project-folder] +scripts/bundle.sh [--install [--force]] +``` + +Always go through the scripts: they set the toolchain (see Gotchas). Every test runs; there is no skip switch. + +## Tests + +How the suites are organised and how to run one: see the Testing section of the [README](../README.md#testing). + +- Stores and the model are tested on fakes (`WorkspaceHarness` wires a whole window to them). `AppServices` and `WorkspaceModel` take every store explicitly, so no test can reach the user's recents, sessions, layouts or the log file. Services tests use temp folders and temp git repos. +- Wait with `eventually { … }` or `model.settle()` / `editor.settle()`, never a sleep. The FSEvents tests are the exception: they need a quiet window to prove no event fired. + +## Gotchas + +- **Toolchain.** `scripts/env.sh` puts Xcode's toolchain on `PATH` but sets `DEVELOPER_DIR` to the Command Line Tools. With Xcode's developer dir, `/usr/bin/xcrun` and `/usr/bin/git` call the broken `xcodebuild`; SwiftPM then cannot read the manifest API's deployment target, compiles plugins for macOS 11, and SwiftTerm's `swift-argument-parser` plugin fails to build. `swift test` needs the extra Testing flags in `scripts/test.sh`. +- **`Bundle.module` is off limits** in HelderUI: its accessor looks next to the `.app`, not in `Contents/Resources`, and falls back to an absolute build path. `FontRegistry.fontsDirectory()` searches itself. SwiftTerm does the same for its own bundle. +- **Fonts.** CoreText registers the WOFF2 files directly. Use PostScript names (`PlexFace`); the Medium face reports its family as "IBM Plex Mono Medium". +- **ripgrep** is not on this machine's `PATH`. `bundle.sh` copies `$RG_BINARY`, else `vendor/ripgrep/rg`, else an `rg` on `PATH` into `Contents/Helpers/rg`, which `ExecutableLocator.standard` checks first. `$RG_BINARY` overrides it at runtime; the tests use it, else `vendor/ripgrep/rg`. Without any rg, search, the file list and the symbol index fall back to a Swift walk (slower, same results). +- **Own data.** The recent-projects list (`~/Library/Application Support/Helder/recent-projects.json`, read by ⇧⌘O and the launcher) and the log (`~/Library/Logs/Helder/helder.log`) belong to this app alone. Running it on a scratch folder adds that folder to the list; remove it afterwards. Under `swift run` the UserDefaults domain is `Helder` (sessions, layouts), in the bundle `nl.blijnder.helder`. +- **`bundle.sh --install`** refuses to replace a `~/Applications/Helder.app` with a different bundle id without `--force`. +- **⌘N** is the note, so "New Window" is ⇧⌘N. New Window starts a new process on the launcher, and the child never inherits `HELDER_PROJECT` (it would win over the folder argument). ⌘A is select-all in the focused view (in the code pane, the whole file); fluid columns are ⌘L. +- **Config.** `files.followGitignore` defaults to **false** (the main-process value). There is no CSS layer: code font and size come from config/Typography. +- **One file, no Original.** The editor deliberately has no tabs and no Original mode. `git.defaultDiffMode: "original"` in an older config decodes as `"updated"`. +- **SwiftTerm** has no line-height or letter-spacing setting, so `terminal.lineHeight`/`letterSpacing` from the config are ignored. diff --git a/docs/behaviour.md b/docs/behaviour.md new file mode 100644 index 0000000..5833655 --- /dev/null +++ b/docs/behaviour.md @@ -0,0 +1,253 @@ +# Helder Functional Design + +This document describes how Helder behaves: every panel, interaction, and state, at the functional and UX level. It does not cover technical architecture. It is written to match the agreed user interface exactly. + +Helder is a dark, AI-first macOS code editor for reviewing and navigating code written by an AI agent. It opens one project per window and has no light mode and no theme toggle. + +--- + +## 1. Window layout + +The window has three horizontal regions stacked top to bottom: + +1. A top bar. +2. The main body, split into four resizable columns. +3. A bottom status bar. + +The four columns of the body, left to right, are: + +1. **Source Control** +2. **Explorer** (file tree) +3. **Editor** (one file and its code) +4. **Agent and Terminal**, a single column split into two stacked panes: the Claude agent pane on top and a shell terminal below it. + +Every boundary between panes is a draggable splitter. The vertical splitters between the four columns adjust their widths. The horizontal splitter between the agent pane and the terminal pane adjusts their heights. Splitter positions persist across launches. Panes have sensible minimum widths and heights so they cannot be collapsed to nothing by dragging. + +The interface is dark only. Code is always syntax highlighted, in every panel and every view. + +--- + +## 2. Top bar + +The top bar contains, left to right: + +- The Helder wordmark. +- A breadcrumb showing the path to the active file, for example `console / src / Http / Controller / UserController.php`. The breadcrumb is **display only** for now. It is not clickable and does not navigate. +- On the right, two controls: **Go to File** (`Cmd+P`) and **Search** (`Cmd+F`). Both open overlays described in section 9. + +--- + +## 3. Source Control panel + +The leftmost column. It shows the working state of the project's git repository and is where staging and committing happen. + +### Header + +A `SOURCE CONTROL` header with a count badge showing the total number of changed files (staged plus unstaged). + +### Commit area + +Directly under the header: + +- A single-line **commit message** input. +- A **Commit** button whose label includes the staged count, for example `Commit 2`. +- The Commit button is enabled only when there is at least one staged change and the message field is not empty. Clicking it commits the staged changes with the typed message, clears the message field, and moves the committed files out of the staged section. The working tree updates accordingly. + +### Sections + +Two stacked sections, each with its own header and count: + +1. **STAGED CHANGES (n)** on top, listing files that are staged. +2. **CHANGES (n)** below, listing unstaged working-tree changes (added, modified, deleted). + +### Row anatomy + +Each row, identical in both sections: + +- A status letter on the far left: `A` added, `M` modified, `D` deleted, each in its own color (added teal, modified amber, deleted amber-deep). +- A file-type icon, then the file name. +- The dimmed relative path, aligned to the right of the name. +- Change counts at the far right: additions in teal (`+N`) and deletions in amber-deep (`-N`). +- Deleted files are shown with the file name struck through and dimmed. +- Rows have default, hover, and selected states. The selected row is the file currently open in the editor. + +### Interactions + +- **Left-click** a row opens that file in the editor, on the live file. It does not open the full-screen Diff. +- **Right-click** a row opens a context menu, designed to grow over time: + - In CHANGES (unstaged): **Open diff**, **Stage file**, and **Discard changes**. + - In STAGED: **Open diff**, and **Unstage file**. + - **Open diff** is the explicit way into the full-screen Diff (section 5). +- **Hover quick action**: on hover, an unstaged row shows a `+` to stage it in one click, and a staged row shows a `-` to unstage it. +- Optional section actions: **Stage all** on the CHANGES header and **Unstage all** on the STAGED header. +- **Discard** is a destructive action. It asks for confirmation first (controlled by `git.confirmDiscard`, default on). Discarding reverts a modified file to its committed state and restores a deleted file. +- Staging and unstaging do not ask for confirmation by default (`git.confirmStage` and `git.confirmUnstage`, default off). + +### Branch summary bar + +At the very bottom of this column, a bar shows the current branch name and the total line changes across the working tree, for example `feat/payments-balance +50 -38`. This bar is **display only**. It does not switch branches. + +### Empty states + +- When nothing is staged, the STAGED section shows a dimmed line: `No staged changes`. +- When the working tree is clean, the CHANGES section shows a dimmed line: `Working tree clean`. + +Scope note: git in this version covers staging, unstaging, committing, and discarding. Push, pull, fetch, and branch switching are not part of this version. + +--- + +## 4. Explorer panel + +The second column. A standard project file tree. + +- An `EXPLORER` header. +- Folders expand and collapse. Files and folders use type icons. +- Files that have changes show the same status letter as the Source Control panel (`A`, `M`, `D`) on the right of their row. +- **Left-click** a file opens it in the editor. The selected file is highlighted. +- The tree hides paths matched by `files.exclude` and, when `files.followGitignore` is on, paths ignored by git. +- **Right-click** a file offers **Copy reference**, which copies the file's project-relative path to the clipboard (the file-level form of the editor's Copy reference). + +--- + +## 5. Editor + +The third and widest column. It shows exactly one file: a bar on top and the code below. Opening another file replaces it. Unsaved edits are kept per file, so switching away never prompts and coming back shows the edits. + +### Editor bar + +A row above the code, holding for the open file, left to right: + +- A type badge and the project-relative path. +- An unsaved indicator (a dot) when the file has unsaved edits. This matters because auto-save is off by default (`editor.autoSave`). +- For a file with changes relative to its committed state, the change counts: additions in teal (`+N`) and deletions in amber-deep (`−N`). +- On the right, a **Preview** button on Markdown files and a **Diff** button on changed files. The button of the active view is highlighted. + +With no file open, the bar stays empty. + +### Views + +All are presentations of the same file: + +1. **The live file**: the current, editable version. On a changed file it marks the changed lines in place, with a teal tint, a 2px teal left rule, and a teal line number. There is no sign column, no `+` or `-` pair, and no removed line inline. A pure deletion has no current line to mark, so the neighbouring current line carries a 2px amber-deep rule on its top edge, or on its bottom edge at the end of the file. An unchanged file shows plain code. +2. **Preview**: Markdown files only. It shows the rendered document instead of the source. `Cmd+M` switches a Markdown file between code and the rendered preview. +3. **Diff**: changed files only. The editor expands to full screen, covering the other columns. The original file is on the left and the updated file is on the right, lines aligned. `Esc`, or a collapse control in the corner, returns to the live file. + +A changed file opens on the live file, or on the Diff when `git.defaultDiffMode` is `diff`. + +**On the live file, a click on a marked line opens the Diff.** The full-screen side-by-side view comes up on the pair of the whole file, HEAD against disk, and both panes scroll so that the clicked line sits in the middle of the window. A line near the start or the end of the file goes as near to the middle as the file permits. `Esc` returns to the live file. Hover does nothing, and there is no animation. A new file, where every line is marked, does not open the Diff on click. + +Shared rules: teal is what the file holds now, amber-deep is what it held before. There is no green and no red anywhere. Syntax highlighting stays on in all modes. Line numbers follow `editor.lineNumbers` (default absolute). + +### Editing behavior + +- A file with no changes opens directly in a normal editable view with no Diff button, since there is nothing to diff. +- Editing follows the editor settings: indentation, indent width, trim trailing whitespace, insert final newline, word wrap, indent guides, whitespace rendering, and active-line highlight, all read from configuration (section 10). +- **Word wrap** follows `editor.wordWrap`: `markdown` (default), `on`, or `off`. When it is on, a line too wide for the pane folds onto the next row instead of scrolling sideways. Only the first row of a folded line carries a line number; the rows below it stay blank. Diff never wraps, because its two panes align row by row. + +### Right-click in code + +Right-clicking inside the code area, with or without a selection, shows a context menu with exactly two items: + +1. **Copy reference**: copies a reference to the clicked location to the clipboard. With no selection it is path plus single line, for example `src/Http/Controller/UserController.php:42`. With a selection it is path plus start and end line, for example `src/Http/Controller/UserController.php:42-58`. The path is project-relative. +2. **Pass on to Agent**: opens a small inline input popup anchored near the click or selection, with a single optional text field. On confirm (`Enter`), it composes one line, the typed text followed by the same reference, and inserts it into the agent pane's input. The insert does **not** submit. It lands as a new, unsubmitted line and the cursor sits on a fresh line, so the action can be repeated to stack several references before the user sends. `Esc` cancels with no insert. An empty field passes the bare reference. + +### File-state behavior in the views + +- **Added file**: only the current content exists. The live file marks every line as added, and Diff shows an empty left pane with the file on the right. +- **Deleted file**: only the committed content exists. The editor shows a short placeholder saying there is no updated version, and Diff shows the file on the left with an empty right pane. +- **Binary or unsupported file**: cannot be shown as editable text. The editor shows a short placeholder stating the file cannot be displayed, and the Preview and Diff buttons are not shown. + +--- + +## 6. Agent pane + +The top pane of the fourth column. + +- A `claude` header with an `agent session` label. +- It is a single terminal running the configured agent command. On launch it auto-runs that command when `ai.autoLaunch` is on (default), using `ai.command` (default `claude`). +- The pane shows the live agent session and has an input line at the bottom. +- It receives the **Pass on to Agent** inserts from the editor: text arrives in the input as content, never as a submitted command, so the user can stack several and send when ready. +- It is one terminal only. There are no additional agent sessions in this version. + +--- + +## 7. Terminal pane + +The bottom pane of the fourth column. + +- A header showing the shell and working directory, for example `zsh` and the project path. +- It is a single shell terminal. It uses the operating system default shell, or the override in `terminal.shell` when set. +- It behaves as a normal terminal for that shell. +- It is one terminal only. There are no additional terminals in this version. + +--- + +## 8. Status bar + +A bar across the bottom of the window. All items are **display only** for now; none are clickable. + +- On the left: the current branch and the working-tree line totals, for example `feat/payments-balance +50 -38`. +- On the right: cursor position (`Ln, Col`), indentation (`Spaces: 4`), encoding (`UTF-8`), language (`PHP`), and the active view. + +--- + +## 9. Global interactions + +### Go to File (`Cmd+P`) + +Opens a fuzzy file-open overlay. The user types part of a file name or path, the list narrows as they type, and selecting a result opens that file in the editor. `Esc` closes the overlay. + +### Search (`Cmd+F`) + +Opens a modal search overlay that searches **both** file contents and file names at once. The overlay covers 90 percent of the application width and is centered over a dimmed background. + +Inside the overlay: + +- A query field at the top. +- Two result columns below: + - **Left column, 70 percent width**: matches found inside files (content search), grouped by file, each match shown as the matching line with the query highlighted in context. + - **Right column, 30 percent width**: files whose name or path matches the query. +- Selecting a content result opens the file and jumps to that line. Selecting a file-name result opens that file. +- When nothing matches, each column shows a brief no-results message. +- `Esc` closes the overlay. The respected excludes are the same as the Explorer (`files.exclude` and, when on, gitignore). + +### Pane resizing + +Dragging any splitter resizes the adjacent panes. Positions persist across launches. + +### Session restore + +When `session.restoreOnLaunch` is on (default), reopening a project restores the previously open file, its view, and the pane and splitter layout. + +--- + +## 10. Configuration + +Settings are project-scoped and live in a `.helder` folder in the project root. + +- **`.helder/config.json`**: the user's settings. It is sparse and holds only the values the user has overridden. +- **`.helder/config.default.json`**: the full set of defaults, with a default for every value. Helder regenerates this file on launch from its built-in defaults, so it always matches the installed version and serves as live documentation of every available setting. The app never reads user edits from this file. +- **Effective value** of any setting: the value from `config.json` if present, otherwise the value from `config.default.json`, merged key by key. +- There is no theme file. The code font and size are built in; `Cmd+0`, `Cmd++` and `Cmd+−` zoom the editor, Diff and terminal text. + +Settings that affect behavior described above include indentation and editor display, file and search excludes, the default diff mode (`updated` or `diff`), git confirmation prompts, the terminal shell override, the agent auto-launch and command, and session restore. + +--- + +## 11. States and edge cases summary + +- **No project open**: the window shows an empty state inviting the user to open a project folder. +- **Clean working tree**: Source Control shows its empty-section messages; the Explorer still shows the full tree. +- **Unchanged file open**: normal editable view, no Diff button. +- **Added or deleted file**: views behave as described in section 5. +- **Binary or unsupported file**: placeholder, no Preview or Diff button. +- **Search with no matches**: per-column no-results messages. +- **Agent command not available**: the agent pane is a terminal, so a missing or failing command surfaces as ordinary terminal output in that pane. + +--- + +## Open assumptions to confirm + +- In the Search overlay, content matches are on the left (70 percent) and file-name matches on the right (30 percent). Confirm this assignment, or swap the two sides. +- The editor bar shows an unsaved indicator because auto-save defaults to off. Confirm that behavior is wanted. +- The Explorer right-click offers a file-level Copy reference (path only), consistent with the editor's Copy reference. Confirm this is in scope. \ No newline at end of file diff --git a/docs/design/README.md b/docs/design/README.md new file mode 100644 index 0000000..8a70d45 --- /dev/null +++ b/docs/design/README.md @@ -0,0 +1,382 @@ +# Design: Helder — editor for working with Claude Code + +## Overview + +Helder is a macOS code editor built around one job: work on a codebase together with +Claude Code. It replaces a general IDE with four columns — source control, explorer, +editor, agent — plus five overlays (search, keyboard shortcuts, project note, project +launcher, expanded diff) and a set of small surfaces (context menus, a pass-on-to-agent +prompt, tooltips, a markdown preview). + +This document describes one consistent visual system for all of those screens. + +## About the design files + +The files in this folder are **design references written in HTML**. They show the +intended look, spacing and states. They are not production code to copy: the app +recreates these screens in SwiftUI and AppKit. + +`design-canvas.dc.html` is a single-canvas board: every screen sits on one page, side by +side, at real pixel sizes. Open it in a browser to inspect any value with devtools. + +## Fidelity + +**High fidelity.** Colours, type, row heights, paddings, radii and states are final and +exact. Recreate them pixel-for-pixel. Everything is authored with inline styles so any +element's computed value can be read directly from the file. + +Two things are deliberately *not* final: +- The code shown inside the editor panes is sample content, not a spec. +- Icons are Unicode stand-ins (`⌕ ▤ ◇ ⧉ ✎ ↺ ⇄ ⑂ ◆ →`). Ship them as Lucide glyphs at + stroke width 1.75, 16px inline / 18px standalone. + +--- + +## Design tokens + +### Surfaces (four, no more) + +| Token | Hex | Use | +|---|---|---| +| `editor` | `#101720` | Editor canvas, terminal, launcher backdrop, code blocks | +| `panel` | `#18202B` | Title bar, side panels, status bar, overlays, menus, tooltip host | +| `raised` | `#232C39` | Selected row, hairline borders, tooltip surface, keycap borders | +| `hover` | `#1E2733` | Row hover fill only | + +### Text on dark + +| Token | Hex | Use | +|---|---|---| +| `text-1` | `#F4F5F4` | Active file, dialog titles, selected row | +| `text-2` | `#E4E7E6` | Body copy, code plain text | +| `text-3` | `#BAC0C0` | Inactive rows, identifiers, secondary copy | +| `text-4` | `#6C7783` | Labels, paths, meta, comments | +| `text-5` | `#3A424C` | Line numbers, disabled | + +### Accent — amber, reserved + +`#E8913A` primary · `#C4741F` deep · `#F0B476` soft · `rgba(232,145,58,.10)` tint · +`rgba(232,145,58,.22)` focus ring. + +Amber is allowed **only** for: the active toolbar toggle (tint fill), the 2px selection +rule, the caret, keycap glyphs, the blinking period in the wordmark, the primary button +fill (ink text on amber, never white), the search-hit highlight, section markers, list +markers, links, and counts in the status bar. Never an amber panel, never an amber +heading. + +### Light canvas (this board only) + +`#EFF0EE` page · `#E5E7E4` spec card · `#CDD1CD` hairline · `#171C22` ink · +`#3A424C` ink muted · `#6B7480` ink dim. The application itself is dark only. + +### Syntax — six colours, all muted + +| Role | Hex | +|---|---| +| plain / function name | `#E4E7E6` | +| variable / property | `#BAC0C0` | +| comment | `#6C7783` | +| keyword / operator / pseudo-class | `#C3A6CE` | +| string / value / type path | `#8FBFB4` | +| number / tag / hex literal | `#F0B476` | + +No bold, no italic in code. Weight stays 400 so the column reads flat. + +### Diff + +- added: text `#8FBFB4`, fill `rgba(143,191,180,.12)`, 2px left rule `#8FBFB4` +- removed: text `#C4741F`, fill `rgba(196,116,31,.14)`, 2px left rule `#C4741F` +- counts in headers: `+1` in `#8FBFB4`, `−1` in `#C4741F` (real minus sign U+2212) + +No green, no red anywhere. The diff reads on shape and on the 2px rule. + +### Type + +- `IBM Plex Mono` — 400/500/600/700. All labels, paths, code, keycaps, titles, numbers. +- `IBM Plex Sans` — 400/500. Rows, menu items, tooltips, buttons, running text. + +| Role | Spec | +|---|---| +| Board display | Mono 700, 58px/1.02, `-0.04em` | +| Section title | Mono 700, 20px/1.2, `-0.02em` | +| Dialog title | Mono 700, 14px/1 | +| Section/panel label | Mono 700, 10px, `0.14em`, uppercase, `#6C7783` | +| Board label | Mono 700, 10–11px, `0.14em`, uppercase, `#6B7480` | +| Code | Mono 400, 13px / 20px line box | +| Search hit line | Mono 400, 12px / 24px line box | +| Path / meta / status bar | Mono 400, 11–12px | +| Keycap | Mono 600, 12px, padding 4px 6px, 1px `#232C39`, radius 2px, glyph `#E8913A` | +| Row label | Sans 400 13px (500 when selected) | +| Body copy | Sans 400, 14px/1.7, max 68ch | +| Tooltip | Sans 400, 12px/1.5 | + +### Geometry + +| Value | Where | +|---|---| +| 24px | Explorer / launcher-adjacent row height | +| 26px | Source-control row height | +| 28px | Status bar, state-specimen rows | +| 30px | Context-menu item height | +| 34px | Editor bar, markdown/code panel header | +| 44px | Title bar and toolbar | +| 20px | Code line box (13px type) | +| 2px | Radius: buttons, inputs, tags, keycaps, menus' inner rows, code blocks | +| 4px | Radius: panels, cards, menus | +| 8px | Radius: overlays (modals) only | +| 1px | Every hairline (`#232C39` on dark, `#CDD1CD` on light) | +| 2px | Accent rule: selection, focus border, pull-quote | +| 9999px | Traffic-light dots and avatars only | + +Column widths in the workspace: source control 236 · explorer 288 · editor flex · +agent 480. Agent terminal block 190px tall. Full frame 1760 × 1000. + +### Elevation + +Only two shadows exist: +- dropdown / context menu: `0 4px 16px rgba(23,28,34,.10)` +- overlay: `0 16px 48px rgba(23,28,34,.18)` + +No ambient card shadow, no glow. + +### Motion + +Colour transitions only, 160ms `cubic-bezier(0.22,1,0.36,1)` (120ms on small controls). +The single exception is `blink`: a stepped 1.1s on/off (no fade) used for the caret, the +terminal block cursor and the amber period in the wordmark. No entrance animation, no +lift, no scale, no parallax. + +--- + +## Screens + +### 01 · Workspace (1760 × 1000) + +Vertical stack: title bar 44px → body (flex row) → status bar 28px. + +**Title bar** (`#18202B`, 1px bottom `#232C39`, padding 0 14px, gap 18px) +Traffic lights 12px (`#E8913A`, `#6C7783`, `#3A424C`, gap 8px) · wordmark +`Helder` Mono 700 13px `#F4F5F4` with a blinking `.` in `#E8913A` · project `odynt` +Mono 12px `#6C7783` · `·` · branch `main` Mono 500 12px `#E8913A` · breadcrumb of the +open path in Mono 12px `#6C7783`, last segment `#F4F5F4` 600, `›` separators · then the +toolbar, right-aligned, gap 4px. + +Toolbar toggle: label Sans 12px + keycap. Off = label `#BAC0C0`, no fill. On = fill +`rgba(232,145,58,.10)`, label `#F4F5F4` 500, keycap border `rgba(232,145,58,.35)`. +Hidden-files-off is the muted case: label and keycap both `#6C7783`. Toggles: +Search ⌘F · Fluid ⌘L · Hidden ⌘. · Note ⌘N · Git ⌘G · `?` (26px square, 1px border). + +**Source control column** (236px, `#18202B`, 1px right border) +Commit box: 52px `#101720` field, 1px `#232C39`, radius 2, placeholder +"Shift+Enter to commit" `#6C7783`; 34px push button `↑` beside it, same border. +Group header: Mono 700 10px `0.14em` uppercase `#6C7783`, count right in `#E8913A` +("STAGED CHANGES 4", "CHANGES 1"). Rows 26px: status letter (Mono 600 10px — staged +`#8FBFB4`, unstaged `#F0B476`) · 8px type badge · file name Sans 12px, ellipsised. +Footer line "4 staged · 1 unstaged" Mono 11px `#6C7783`. + +**Explorer** (288px, `#18202B`) — 30px header ("EXPLORER" / project name), then 24px +rows. Indent 16px per level (12 · 28 · 44 · 60 · 76 padding-left). Collapsed `›` +`#6C7783`; expanded `⌄` `#E8913A`, its label `#F4F5F4`. File rows carry an 8px type +badge and, when dirty, a trailing `M` in `#8FBFB4`. + +Type badge: Mono 600 8px, ink text `#101720` on a per-extension fill, radius 2, +padding 3px 4px — php `#C3A6CE` · md `#BAC0C0` · js `#F0B476` · css `#8FBFB4`. + +**Editor** (flex, `#101720`) — 34px bar: type badge, path, unsaved dot, `+1` / `−1` +counts, then right-aligned buttons (1px `#232C39`, radius 2): Preview on Markdown, +Diff on a changed file. Active button = amber fill with `#171C22` text. +Code area: CSS grid `56px 1fr`, line box 20px, numbers right-aligned `#3A424C` with +14px right padding. **Indentation is padding-left on the code cell** (7.82px per space: +31.3 / 62.6 / 93.8 / 125.1) — do not ship non-breaking spaces. + +**Agent panel** (480px, `#18202B`, 1px left border) +Header: 60px `#232C39` square (mark), then `Claude Code` Mono 700 14px + version in +`#6C7783`, model line Sans 12px `#BAC0C0`, cwd Mono 12px `#6C7783`. +Notice strip: fill `rgba(232,145,58,.10)`, `[ ! ]` Mono 600 12px `#E8913A`, sentence +Sans 12px, inline command in Mono `#F0B476`. +Transcript: user turn prefixed `›` in `#E8913A`, agent turn `◆` in `#6C7783`, text +Sans 13px/1.6. Tool calls sit in a `#101720` block, 1px `#232C39`: verb in `#8FBFB4` +(read) or `#F0B476` (write), target and counts `#6C7783`. +Prompt field: 44px, `#101720`, **2px `#E8913A` border + `0 0 0 2px rgba(232,145,58,.22)` +ring** (this is the focus treatment everywhere), `›` prefix, blinking 1px caret. +Status line: Mono 11px `#6C7783`; project chip = amber fill with `#171C22` text; +`▸▸ auto mode` in `#E8913A`; slash hint right. +Terminal: 190px, `#101720`, Mono 12px/1.7 — `[main]` `#8FBFB4`, `[~/path]$` `#6C7783`, +output `#6C7783`, 7×14px blinking amber block cursor. + +**Status bar** (28px, `#18202B`) — `⑂ main` in `#E8913A`, `+16` `#8FBFB4`, `−12` +`#C4741F`, then right-aligned path · Ln/Col · UTF-8 · LF · language (`#BAC0C0`). + +### 02a · Search (⌘F) + +Overlay: flat ink scrim `rgba(16,23,32,.72)` (no blur), 34px inset, panel `#18202B`, +1px `#232C39`, radius 8, overlay shadow. + +- Query bar 54px: `⌕` `#E8913A`, query Mono 500 16px `#F4F5F4`, blinking caret; right + side = extension filters (active = amber fill + ink text; inactive = 1px border, + `#BAC0C0`) and a Mono 11px result summary `#6C7783` behind a 1px left divider. +- Three columns: **this file** (230px) · **project** (flex) · **files** (250px), split by + 1px borders. Column headers are the standard 10px mono labels; the focused column's + header is `#E8913A` with a count chip (amber fill, ink text). +- Result group header: type badge + path Mono 12px `#BAC0C0`, hit count right `#6C7783`. +- Hit lines: grid `64px 1fr`, line box 24px. Match run = amber fill with `#171C22` text + on the selected row, `#F0B476` text elsewhere. Selected row: `#232C39` fill, 2px amber + left rule, and the line number lifts to `#E8913A` (never leave it at `#3A424C`). +- Empty column state: one plain sentence, Sans 12px `#6C7783` ("No matches in this + file." / "No file names match."). No illustration. +- Footer 38px: key hints (`⌘←`/`⌘→` column, `⌘↑`/`⌘↓` row, `↵` open) with amber glyphs, + `esc` chip right. + +### 02b · Keyboard shortcuts (`?`) + +Same overlay shell. 50px header with `◇` `#E8913A` + "Keyboard shortcuts" + `esc` chip. +Body groups (`NAVIGATE`, `AGENT`, `GIT`, `FILE`) each a 10px mono label, then a +`92px 1fr` grid: keycap cluster left (gap 4px), description Sans 13px `#E4E7E6` right, +6px vertical padding per row. + +### 02c · Project note (⌘N) + +Same shell. Header: `▤` amber, "Note", filename `.notes.txt` Mono 12px `#6C7783`, then +the primary button — amber fill, `#171C22` text, Sans 500 12px, radius 2, padding +6px 10px, with a `⌘P` keycap at Mono 600 11px — then the `esc` chip. +Body: Mono 400 14px/1.7 `#E4E7E6`, max 68ch, 18px between paragraphs, blinking caret at +the end of the text. Footer 34px: "saved on focus loss · 412 characters". + +The note is plain text and it is the agent's input: ⌘P sends the whole note. + +### 02d · Project launcher + +Window `#101720` with only traffic lights (34px), no title bar. Centred panel on +`#18202B`, radius 8, overlay shadow, top-aligned with 20px/40px padding. +Header: `◆` amber + wordmark with blinking period + "Open a project to begin" Sans 12px +`#6C7783`. Then a 46px "Open new project…" row with `+` amber and an `↵` chip. +`RECENT` label, then 38px rows: `▤` icon, name Sans 500 13px, path Mono 11px `#6C7783`. +Selected row: `#232C39`, 2px amber left rule, icon and path lift one step. +Footer 36px: `⌘↑↓ navigate · ↵ open`. + +### 03 · Expanded diff (1760 × 620) + +Own window: 42px title bar (traffic lights, path Mono 500 12px `#F4F5F4`, "MODIFIED", +`+1` / `−1`, "staged → actual" Mono 11px `#6C7783`, and a right-aligned +"Collapse `esc`" button with 1px border). +Two panes split by a 1px border; each has a 30px header — left `ORIGINAL` + "before" +`#3A424C`, right `UPDATED` in `#E8913A` + "after". +Panes are grids `52px 1fr`, line box 22px, indentation as padding-left, and **identical +line numbering in both panes** so the eye can travel across. Changed row gets the fill, +the 2px left rule and a lifted number colour. + +### 04 · Small surfaces + +**Context menu** (explorer and source control) — 320px, `#18202B`, 1px `#232C39`, +radius 4, dropdown shadow, 8px vertical padding. First a path header (Mono 11px +`#6C7783`, 1px bottom border). Items 30px, Sans 13px `#BAC0C0`, icon `#6C7783`. +Highlighted item: `#232C39` fill, 2px amber left rule, label `#F4F5F4` 500, icon amber. +Destructive item ("Delete file", "Discard changes"): `#C4741F` label. Groups separated +by a 1px rule with 6px margins. + +Explorer items: Pass on reference · Copy reference · Pass on file name · Copy file name +| Rename file · Show in Finder · Delete file. +Source-control items: Pass on reference · Copy reference | Stage changes · Open diff · +Discard changes. + +**Pass on to agent** — 460px panel, 14px padding, gap 12. Title row (`◇` amber + +Mono 700 13px + `esc` chip), a focused 38px input (2px amber border + ring, blinking +caret), then an INSERTS preview: 10px mono label + the composed string on an amber fill +with `#171C22` text, radius 2, ellipsised. Footer hint `↵ insert into agent · esc cancel` +with amber glyphs. + +**Tooltip** — `#232C39` surface, 1px `#3A424C`, radius 2, padding 8px 10px, max 300px, +Sans 12px/1.5 `#E4E7E6`. No arrow, no shadow. The current state is named inside the +sentence in amber ("Hidden files: *hidden* — …", "Column widths: *fluid* — …"), then one +sentence saying what a click does. + +**Markdown code / Preview** — same 34px header on both halves; the active button is the +amber fill. Code = the code grid (`44px 1fr`, line box 20px) with +`##` headings in `#F0B476`. Preview: 18px/20px padding, max 68ch, Sans 13px/1.7 body, +Mono 700 headings with a 1px `#232C39` underline. + +### 06 · Code colours and markdown preview + +Four specimens at 620px: a JS module, a PHP class, a CSS file and the full markdown +preview. Each panel: 34px header with type badge, path Mono 500 12px, and a right +language label (or the Preview button). + +The markdown preview is the reading surface, so it is the one place where Sans body copy +gets room: +- eyebrow: 10px mono label `#6C7783` +- h2: Mono 700 24px/1.1, `-0.03em`, `#F4F5F4` +- h3: Mono 700 17px/1.2 with a 1px `#232C39` underline, 8px below the text +- paragraph: Sans 14px/1.7 `#E4E7E6`, max 68ch, `text-wrap: pretty` +- list: flex rows, gap 10, `—` marker in `#E8913A` (never a bullet, never an emoji) +- inline code: Mono 13px `#F0B476` on `#18202B`, 1px `#232C39`, radius 2, padding 1px 5px +- block quote: 2px amber left rule, 16px left padding, Sans *italic* 15px `#F0B476` +- code block: `#18202B`, 1px `#232C39`, radius 2, padding 14px 16px, Mono 13px/20px, + syntax palette as above +- table: 1px `#232C39` container, radius 2; header row on `#18202B` with 10px mono + labels; body rows Sans 13px `#BAC0C0`, cells 10px 14px, 1px row rules; state words use + `#8FBFB4` (done) and `#E8913A` (open) +- link: `#E8913A` with a 1px `#232C39` bottom border; hover lifts the text to `#F4F5F4` + and the border to `#E8913A`. `→` marks forward action. + +--- + +## Interactions and behaviour + +| Trigger | Result | +|---|---| +| `⌘F` | Search overlay, query seeded from the editor selection | +| `⌘↑` / `⌘↓` | Move the row cursor in the focused list | +| `⌘←` / `⌘→` | Move focus between search columns | +| `↵` | Open the selected row (search hit, file, recent project) | +| `⌘→` (editor) | Pass the current selection to the agent | +| `⌘M` | Markdown: code or rendered preview | +| `⌘C` / `⌘↵` / `⌘P` (git) | Focus commit message / commit staged / push branch | +| `⌘A` | Toggle auto-fit panels (columns re-fit on resize and focus) | +| `⌘.` | Toggle hidden dotfiles in tree and search | +| `⌘G` | Show or hide the source-control column | +| `⌘S` / `⌘W` / `⌘D` | Save / close / delete (confirm) the current file | +| `⌘N` | Open the project note; it saves on focus loss | +| `⌘P` (note open) | Send the whole note to the agent | +| right-click a row | Context menu, anchored to the pointer, first item pre-highlighted | +| `esc` | Close the top overlay, menu or prompt; never more than one | + +Rules that hold everywhere: +- Exactly one overlay at a time, on a flat ink scrim. Overlays never stack. +- Hover changes fill one step and nothing else. No lift, no scale, no shadow, no opacity. +- Press holds the hover colour. Nothing shrinks. +- Focus is always the 2px amber border plus the 2px 22% ring. Never remove it. +- Disabled is 40% opacity plus `cursor: not-allowed`, no recolouring. +- Empty and error states are one plain sentence starting with an em dash. No icon, no + apology, no exclamation mark. + +## State + +- `project` — path, branch, recent list (persisted) +- `openFile` — path, language, dirty flag, cursor line/col, view mode + (`code|actual|preview|diff`) +- `tree` — expanded paths, selected path, `showHidden` +- `git` — staged[], unstaged[], commit message draft, ahead/behind counts +- `agent` — model, session, transcript, prompt draft, pending tool calls, auth notices +- `overlay` — `null | search | shortcuts | note | diff | launcher | menu | passOn` +- `panels` — column widths, `autoFit`, `gitVisible` +- `note` — text, dirty flag (write on blur) + +Search runs per keystroke against three indexes (open file, project contents, file +names) and reports counts per column; a query with no hits leaves the columns in their +empty state rather than collapsing them. + +## Assets + +None. No images, no illustrations, no photography. Icons come from Lucide +(`lucide@0.544.0`, stroke width 1.75); the Unicode glyphs in the mock are placeholders. +Fonts are IBM Plex Mono and IBM Plex Sans (currently from Google Fonts — swap in local +woff2 for a desktop build). + +## Files + +- `design-canvas.dc.html` — the design board: all screens, one canvas, real sizes +- `tokens/*.css` — the Kade token files the board is built on (colour, type, spacing, + radius, elevation, motion, fonts) +- `styles.css` — the token entry point + +Open `design-canvas.dc.html` in a browser; the board is inert (no interaction) by design. diff --git a/docs/design/design-canvas.dc.html b/docs/design/design-canvas.dc.html new file mode 100644 index 0000000..94680ad --- /dev/null +++ b/docs/design/design-canvas.dc.html @@ -0,0 +1,873 @@ + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+
[ 00 ] design canvas · helder
+

Helder.

+

An editor for working with Claude Code. One slate shell, one amber accent, IBM Plex Mono for everything that is code or label. Every layer below uses the same four surfaces, the same 24px row height and the same selection marker: 2px amber on the left, fill one step deeper.

+
+ workspace + overlays + menus + foundations +
+
+ + +
+
+ [ 01 ] + Workspace + Four columns: source control · explorer · editor · agent. 1760 × 1000 +
+ +
+ + +
+
+ + + +
+
+ Helder. + odynt + · + main +
+
+ resources›views›admin›vaults› + form.blade.php +
+
+ Search ⌘F + Fluid ⌘L + Hidden ⌘. + Note ⌘N + Git ⌘G + ? +
+
+ +
+ + +
+
+
Shift+Enter to commit
+
↑
+
+
+ staged changes4 +
+
+
Mphpcategory.blade.php
+
Mphpform.blade.php
+
Mphpsubcategory.blade.php
+
Mphpdeclined-names.blade.php
+
+
+
+ changes1 +
+
Mphpdeclined-names.blade.php
+
+
4 staged · 1 unstaged
+
+ + +
+
explorerodynt
+
+
›▤app
+
›▤blueprints
+
›▤bootstrap
+
›▤config
+
›▤database
+
›▤docs
+
›▤lang
+
›▤public
+
⌄▤resources
+
›▤css
+
›▤js
+
›▤markdown
+
⌄▤views
+
⌄▤admin
+
⌄▤vaults
+
›▤_partials
+
phpcategory.blade.phpM
+
phpform.blade.phpM
+
phpindex.blade.php
+
phpsubcategory.blade.phpM
+
›▤components
+
›▤conversation
+
›▤help
+
›▤settings
+
›▤routes
+
›▤tests
+
mdAGENTS.md
+
mdCLAUDE.md
+
jsvite.config.js
+
+
+ + +
+
+ modified + +1 + −1 + +
+ Actual + Original + Diff + Split +
+
+
+ 1{{-- + 24B — the Vault editor. `$vault === null` means create. + 3--}} + 4 + 5@php + 6$isCreate = $vault === null; + 7$teamClass = \App\Models\Team::class; + 8$userClass = \App\Models\User::class; + 9@endphp + 10 + 11<x-layouts.app :title="$vault?->name"> + 12 + 13<style> + 14.vlt-head { + 15display: flex; + 16align-items: flex-end; + 17gap: 20px; + 18} + 19 + 20.vlt-card { + 21background: var(--color-surface-raised); + 22border: 1px solid var(--color-border-default); + 23border-radius: 4px; + 24padding: 22px 24px; + 25} + 26 + 27.vlt-group-label { + 28font-family: 'IBM Plex Mono', monospace; + 29letter-spacing: .14em; + 30text-transform: uppercase; + 31} + 32</style> +
+
+ + +
+
+
◆
+
+ Claude Code v2.1.259 + Opus 5 (1M context) · Claude Max + ~/code/odynt +
+
+
+ [ ! ] + 1 MCP server needs authentication — run /mcp +
+
+
+ › + Implement the vault admin screens from docs/design_handoff_vaults/README.md. +
+
+ ◆ + I read the handoff and the existing policies. Then I write the tests first. +
+
+ Read docs/design_handoff_vaults/README.md · 412 lines + Grep "VaultPolicy" · 7 hits + Edit app/Policies/VaultPolicy.php +
+
+
+ › + test the round trip with Playwright + +
+
+ [Opus 5 · 1M] + odynt + main + + ▸▸ auto mode + /rc +
+
+
[main][~/code/odynt]$ php artisan test --filter=Vault
+
PASS Tests\Feature\VaultAdminTest · 14 assertions
+
[main][~/code/odynt]$
+
+
+
+ + +
+ ⑂ main + +16−12 + + resources/views/admin/vaults/form.blade.php + ·Ln 20, Col 12·UTF-8·LF·Blade +
+
+
+ + +
+
+ [ 02 ] + Overlays + One rule: ink scrim, panel on slate-2, 8px radius, esc top right. +
+ +
+ + +
+
2a · search ⌘f
+
+
+
+ ⌕ + config( + + + php + md + js + 0 here · 226 hits · 0 files +
+
+
+
this file
+
phpConfigSyncCommand.php
+
No matches in this file.
+
+
+
project226
+
phpcypress/e2e/Conversation/ConversationWelcome.php4
+
+ 80function conversationSeedConfig(): void + 99conversationSeedConfig(); + 163conversationSeedConfig(); +
+
phpdatabase/seeders/DatabaseSeeder.php3
+
+ 230* This row is consumed by AppData::resolveDefaultThemeConfig() + 245'config' => self::guestThemeConfig(), + 257private static function guestThemeConfig(): array +
+
jscypress/e2e/blueprint-038-conversation-menu.cy.js1
+
+ 163cy.url().should('eq', Cypress.config('baseUrl') + '/conversation'); +
+
mdblueprints/done/012-dialog-page/blueprint.md1
+
+ 162— `config/ai.php` — providers.anthropic.api_key +
+
+
+
files0
+
No file names match.
+
+
+
+ ⌘← / ⌘→ column + ⌘↑ / ⌘↓ row + ↵ open + + esc +
+
+
+
+ + +
+
2b · shortcuts ?
+
+
+
+ ◇ + Keyboard shortcuts + + esc +
+
+
navigate
+
+ ⌘FSearch contents and names + ⌘↑↓Move through a list + ↵Open the selected item + ⌘←→Column left or right +
+
agent
+
+ ⌘→Pass the selection to the agent + ⌘NOpen the project note + ⌘PPass on the whole note +
+
git
+
+ ⌘CFocus the commit message + ⌘↵Commit the staged files + ⌘GSource Control column on or off + ⌘MCycle Actual · Original · Diff · Split +
+
file
+
+ ⌘SSave this file + ⌘WClose this file + ⌘.Hidden files on or off +
+
+
+
+
+ + +
+
2c · project note ⌘n
+
+
+
+ ▤ + Note + .notes.txt + + To the agent ⌘P + esc +
+
+

I've created a design for the admin screens that manage the vaults, vault_categories and the vault_subcategories.

+

Implement them. Let them respect the admin policies just like agents, teams and companies have their own policies.

+

The design can be found here: docs/design_handoff_vaults/README.md

+

The vaults index page replaces /crud/vaults. Remove that code and place this feature on /admin/vaults.

+
+
+ saved on focus loss·412 characters +
+
+
+
+ + +
+
2d · open a project
+
+
+ + + +
+
+
+
+ ◆ + + Helder. + Open a project to begin + +
+
+ + + Open new project… + + ↵ +
+
recent
+
+
▤odynt~/code/odynt
+
▤stedt~/code/stedt
+
▤loopt~/code/loopt
+
▤doen-r~/code/doen-r
+
▤vakwerk~/code/vakwerk
+
▤diagram~/code/diagram
+
▤marketingtools~/code/marketingtools
+
+
+ ⌘↑↓ navigate↵ open +
+
+
+
+
+
+
+ + +
+
+ [ 03 ] + Diff + Added is teal, removed is amber-deep. No green, no red. +
+ +
+
+
+ + + +
+ resources/views/help/vault/declined-names.blade.php + modified + +1 + −1 + staged → actual + + Collapse esc +
+
+
+
originalbefore
+
+ 18{{ __('A merge writes a declined row…') }} + 19</p> + 20</section> + 21 + 22<section class="odynt-help__section"> + 23<h2>{{ __('The reason a row can carry') }}</h2> + 24 + 25<p> + 26{{ __('A row can carry one of eleven reason codes…') }} + 27</p> + 28</section> +
+
+
+
updatedafter
+
+ 18{{ __('A merge writes a declined row…') }} + 19</p> + 20</section> + 21 + 22<section class="odynt-help__section is-reasons"> + 23<h2>{{ __('The reason a row can carry') }}</h2> + 24 + 25<p> + 26{{ __('A row can carry one of eleven reason codes…') }} + 27</p> + 28</section> +
+
+
+
+
+ + +
+
+ [ 04 ] + Details + Menus, prompts, tooltips and the markdown switch. All on 24px rows. +
+ +
+ +
+
4a · explorer menu
+
+
tests/Unit/ExampleTest.php
+
◇Pass on reference
+
⧉Copy reference
+
◇Pass on file name
+
⧉Copy file name
+
+
✎Rename file
+
▤Show in Finder
+
⌫Delete file
+
+
+ +
+
4b · source control menu
+
+
resources/views/help/vault/declined-names.blade.php
+
◇Pass on reference
+
⧉Copy reference
+
+
+Stage changes
+
⇄Open diff
+
↺Discard changes
+
+
+ +
+
4c · pass on to agent
+
+
+ ◇ + Pass on to agent + + esc +
+
+ write the test for this + +
+
+ inserts + write the test for this ⇒ tests/Unit/ExampleTest.php +
+
↵ insert into agent · esc cancel
+
+
+ +
+
4d · toolbar + tooltip
+
+
+ Search ⌘F + Fluid ⌘L + Hidden ⌘. + Note ⌘N + Git ⌘G +
+ +
+
Hidden files: hidden — dotfiles excluded from the tree and the search. Click to show.
+
Column widths: fluid — the columns re-fit on resize and focus. Click to lock them.
+
Project note (.notes.txt) — kept next to this project.
+
+
+
Tooltip: slate-3 surface, 1px border, no arrow, no shadow. The state is amber inside the sentence.
+
+
+ +
+
4e · markdown actual · preview
+
+
+
+ markdown + + + Actual + Preview + +
+
+ 1You write the handover record for a + 2conversation that is about to be cut. + 3 + 4The reader is a model with no access to + 5the original messages. + 6 + 7## Sources + 8 + 9Use only the messages, the tool results + 10and the previous summary. +
+
+
+
+ markdown + + + Actual + Preview + +
+
+

You write the handover record for a conversation that is about to be cut.

+

The reader is a model with no access to the original messages. Your record is the only input it gets.

+

Sources

+

Use only the messages, the tool results and the previous summary. If you cannot point to that source, delete the line.

+
+
+
+
+
+
+ + +
+
+ [ 05 ] + Foundations + Four surfaces, one accent, six syntax colours. +
+ +
+ +
+
surfaces and accent
+
+
#101720editor · terminal
+
#18202Bpanels · chrome
+
#232C39selection · border
+
#E8913Aaction · state · cursor
+
+

Amber is a reservation: active toggle, selection marker, cursor, the blinking period and the counts in the status bar. Never an amber surface as decoration.

+
+ +
+
syntax
+
+ text · #E4E7E6 + variable · #BAC0C0 + comment · #6C7783 + keyword · #C3A6CE + string · #8FBFB4 + number · tag · #F0B476 +
+
+ + added — #8FBFB4 op rgba(143,191,180,.12) + − removed — #C4741F op rgba(196,116,31,.14) +
+

Six colours, all muted. No green for good and no red for bad — the diff reads on shape and on the 2px rule, not on alarm.

+
+ +
+
type and rhythm
+
+ IBM Plex Mono 700 + titles, labels, paths, code, shortcuts + IBM Plex Sans 400 · 500 + rows, menu items, tooltips, running text +
+
+ row height · 24pxchrome · 44px + code line · 20pxstatus bar · 28px + radius control · 2pxradius overlay · 8px + border · 1pxmarker · 2px amber +
+
+ +
+
row states
+
+
rest
+
hover — fill one step deeper
+
selected — 2px amber on the left
+
not available — 40%
+
+

No movement, no shadow, no scale. Colour only, 160ms. The only animation in the whole editor is the blinking cursor and the period in the mark.

+
+
+
+ + +
+
+ [ 06 ] + Code colours + The same six colours across every language. Nothing bold, nothing italic — weight stays 400 so the column reads flat. +
+ +
+ +
+
6a · javascript
+
+
+ js + resources/js/symbols-service.js + + javascript +
+
+ 1// One request per file. The tree keeps the last answer. + 2 + 3import { cache } from './cache.js'; + 4 + 5const ENDPOINT = '/api/symbols'; + 6const TIMEOUT = 2500; + 7 + 8export async function readSymbols(path, signal) { + 9if (cache.has(path)) return cache.get(path); + 10 + 11const res = await fetch(`${ENDPOINT}?p=${path}`, { signal }); + 12 + 13if (!res.ok) { + 14throw new Error(`symbols: ${res.status}`); + 15} + 16 + 17const rows = await res.json(); + 18cache.set(path, rows); + 19 + 20return rows; + 21} +
+
+
+ +
+
6b · php
+
+
+ php + app/Console/Commands/ConfigSyncCommand.php + + php +
+
+ 1<?php + 2 + 3declare(strict_types=1); + 4 + 5namespace App\Console\Commands; + 6 + 7use App\Models\Config; + 8 + 9/** Writes one row per config group. */ + 10final class ConfigSyncCommand extends Command + 11{ + 12protected $signature = 'config:sync'; + 13 + 14public function handle(): int + 15{ + 16$created = 0; + 17 + 18foreach ($this->registry() as $key => $class) { + 19$row = Config::query()->find($key); + 20 + 21if ($row === null) { + 22$created++; + 23} + 24} + 25 + 26return self::SUCCESS; + 27} + 28} +
+
+
+ +
+
6c · css
+
+
+ css + resources/css/panels.css + + css +
+
+ 1/* Four surfaces, one accent. Nothing else. */ + 2 + 3:root { + 4--editor: #101720; + 5--panel: #18202B; + 6--accent: #E8913A; + 7} + 8 + 9.row { + 10display: flex; + 11gap: 8px; + 12height: 24px; + 13border-left: 2px solid transparent; + 14transition: background 160ms ease-out; + 15} + 16 + 17.row:hover { + 18background: #1E2733; + 19} + 20 + 21.row[aria-selected='true'] { + 22background: #232C39; + 23border-left-color: var(--accent); + 24} +
+
+
+ +
+
6d · markdown preview
+
+
+
+
+ +
+ + + + + + diff --git a/docs/design/screenshots/Screenshot 2026-09-03 at 09.34.16.png b/docs/design/screenshots/Screenshot 2026-09-03 at 09.34.16.png new file mode 100644 index 0000000..af059cd Binary files /dev/null and b/docs/design/screenshots/Screenshot 2026-09-03 at 09.34.16.png differ diff --git a/docs/design/screenshots/Screenshot 2026-09-03 at 09.34.21.png b/docs/design/screenshots/Screenshot 2026-09-03 at 09.34.21.png new file mode 100644 index 0000000..16f5aa9 Binary files /dev/null and b/docs/design/screenshots/Screenshot 2026-09-03 at 09.34.21.png differ diff --git a/docs/design/screenshots/Screenshot 2026-09-03 at 09.34.26.png b/docs/design/screenshots/Screenshot 2026-09-03 at 09.34.26.png new file mode 100644 index 0000000..bf4fdd2 Binary files /dev/null and b/docs/design/screenshots/Screenshot 2026-09-03 at 09.34.26.png differ diff --git a/docs/design/screenshots/Screenshot 2026-09-03 at 09.34.30.png b/docs/design/screenshots/Screenshot 2026-09-03 at 09.34.30.png new file mode 100644 index 0000000..bb25924 Binary files /dev/null and b/docs/design/screenshots/Screenshot 2026-09-03 at 09.34.30.png differ diff --git a/docs/design/screenshots/Screenshot 2026-09-03 at 09.34.36.png b/docs/design/screenshots/Screenshot 2026-09-03 at 09.34.36.png new file mode 100644 index 0000000..f8ed92d Binary files /dev/null and b/docs/design/screenshots/Screenshot 2026-09-03 at 09.34.36.png differ diff --git a/docs/design/screenshots/Screenshot 2026-09-03 at 09.34.41.png b/docs/design/screenshots/Screenshot 2026-09-03 at 09.34.41.png new file mode 100644 index 0000000..a394413 Binary files /dev/null and b/docs/design/screenshots/Screenshot 2026-09-03 at 09.34.41.png differ diff --git a/docs/design/screenshots/Screenshot 2026-09-03 at 09.34.45.png b/docs/design/screenshots/Screenshot 2026-09-03 at 09.34.45.png new file mode 100644 index 0000000..71cbd33 Binary files /dev/null and b/docs/design/screenshots/Screenshot 2026-09-03 at 09.34.45.png differ diff --git a/docs/design/screenshots/Screenshot 2026-09-03 at 09.34.49.png b/docs/design/screenshots/Screenshot 2026-09-03 at 09.34.49.png new file mode 100644 index 0000000..8cc4f35 Binary files /dev/null and b/docs/design/screenshots/Screenshot 2026-09-03 at 09.34.49.png differ diff --git a/docs/design/styles.css b/docs/design/styles.css new file mode 100644 index 0000000..b444b4c --- /dev/null +++ b/docs/design/styles.css @@ -0,0 +1,8 @@ +@import url("tokens/fonts.css"); +@import url("tokens/colors.css"); +@import url("tokens/typography.css"); +@import url("tokens/spacing.css"); +@import url("tokens/radius.css"); +@import url("tokens/elevation.css"); +@import url("tokens/motion.css"); +@import url("tokens/base.css"); diff --git a/docs/design/tokens/base.css b/docs/design/tokens/base.css new file mode 100644 index 0000000..f3df35f --- /dev/null +++ b/docs/design/tokens/base.css @@ -0,0 +1,23 @@ +*, +*::before, +*::after { box-sizing: border-box; } + +body { + margin: 0; + background: var(--color-stone); + color: var(--color-ink-body); + font-family: var(--font-body); + font-size: var(--text-base); + font-weight: var(--weight-body); + line-height: var(--leading-normal); + -webkit-font-smoothing: antialiased; +} + +a { color: var(--color-amber-deep); text-decoration-color: var(--color-stone-rule); text-underline-offset: 3px; transition: var(--transition-color); } +a:hover { color: var(--color-ink-body); text-decoration-color: var(--color-ink-dim); } +[data-surface="slate"] a { color: var(--color-amber); } +[data-surface="slate"] a:hover { color: var(--color-neutral-1); } + +::selection { background: var(--color-amber-ring); color: var(--color-ink-body); } + +:focus-visible { outline: 2px solid var(--color-amber); outline-offset: 2px; } diff --git a/docs/design/tokens/colors.css b/docs/design/tokens/colors.css new file mode 100644 index 0000000..d5be354 --- /dev/null +++ b/docs/design/tokens/colors.css @@ -0,0 +1,66 @@ +/* Kade palette — cool stone paper, slate-ink dark punctuation, amber as the only accent. */ +:root { + /* Stone — the default canvas. Cool, quarried, never white. */ + --color-stone: #EFF0EE; + --color-stone-2: #E5E7E4; + --color-stone-3: #D8DBD7; + --color-stone-rule: #CDD1CD; + + /* Ink ramp — text on stone. */ + --color-ink-body: #171C22; + --color-ink-muted: #3A424C; + --color-ink-dim: #6B7480; + + /* Slate — the sparing dark surface. One or two blocks per page. */ + --color-slate: #101720; + --color-slate-2: #18202B; + --color-slate-3: #232C39; + + /* Neutral ramp — text on slate. Pure white does not exist in this system. */ + --color-neutral-1: #F4F5F4; + --color-neutral-2: #E4E7E6; + --color-neutral-3: #BAC0C0; + --color-neutral-4: #6C7783; + + /* Amber — the single accent. Reserved for action, state and signal. */ + --color-amber: #E8913A; + --color-amber-deep: #C4741F; + --color-amber-soft: #F0B476; + --color-amber-tint: rgba(232, 145, 58, 0.10); + --color-amber-ring: rgba(232, 145, 58, 0.22); + + /* Semantic aliases — prefer these in component code. */ + --surface-page: var(--color-stone); + --surface-card: var(--color-stone-2); + --surface-card-hover: var(--color-stone-3); + --surface-dark: var(--color-slate); + --surface-dark-card: var(--color-slate-2); + + --text-body: var(--color-ink-body); + --text-muted: var(--color-ink-muted); + --text-dim: var(--color-ink-dim); + --text-accent: var(--color-amber-deep); + --text-on-accent: var(--color-ink-body); + + --border-hairline: var(--color-stone-rule); + --border-strong: var(--color-ink-muted); + + --action-fill: var(--color-amber); + --action-fill-hover: var(--color-amber-deep); + --focus-ring: var(--color-amber-ring); + --focus-border: var(--color-amber); + --signal-error: var(--color-amber-deep); +} + +/* Slate scope — inside a dark block the ramps invert. Apply to the block, not the page. */ +[data-surface="slate"] { + --surface-page: var(--color-slate); + --surface-card: var(--color-slate-2); + --surface-card-hover: var(--color-slate-3); + --text-body: var(--color-neutral-1); + --text-muted: var(--color-neutral-2); + --text-dim: var(--color-neutral-4); + --text-accent: var(--color-amber); + --border-hairline: var(--color-slate-3); + --border-strong: var(--color-neutral-3); +} diff --git a/docs/design/tokens/elevation.css b/docs/design/tokens/elevation.css new file mode 100644 index 0000000..e7a45df --- /dev/null +++ b/docs/design/tokens/elevation.css @@ -0,0 +1,8 @@ +/* Elevation is carried by the stone ramp, not by shadow. Shadows exist only for layers that + cross the page plane (dropdown, modal) and for the amber focus ring. */ +:root { + --shadow-none: none; + --shadow-dropdown: 0 4px 16px rgba(23, 28, 34, 0.10); + --shadow-modal: 0 16px 48px rgba(23, 28, 34, 0.18); + --ring-focus: 0 0 0 2px var(--color-amber-ring); +} diff --git a/docs/design/tokens/fonts.css b/docs/design/tokens/fonts.css new file mode 100644 index 0000000..4979a2a --- /dev/null +++ b/docs/design/tokens/fonts.css @@ -0,0 +1,10 @@ +/* Kade type stack — IBM Plex Mono (display + labels) and IBM Plex Sans (body + UI). + No licensed binaries shipped with the source skills, so the families load from Google Fonts. + Replace this @import with local @font-face rules once real woff2 files are supplied. */ +@import url("https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:ital,wght@0,400;0,500;0,600;0,700;1,400&family=IBM+Plex+Sans:ital,wght@0,400;0,500;0,600;0,700;1,400;1,500&display=swap"); + +:root { + --font-display: "IBM Plex Mono", ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; + --font-mono: "IBM Plex Mono", ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; + --font-body: "IBM Plex Sans", ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; +} diff --git a/docs/design/tokens/motion.css b/docs/design/tokens/motion.css new file mode 100644 index 0000000..ad143ff --- /dev/null +++ b/docs/design/tokens/motion.css @@ -0,0 +1,10 @@ +/* Colour shifts only. Kade never translates, lifts, or scales on hover. */ +:root { + --ease-out: cubic-bezier(0.22, 1, 0.36, 1); /* @kind other */ + --duration-fast: 120ms; /* @kind other */ + --duration-base: 160ms; /* @kind other */ + --duration-slow: 260ms; /* @kind other */ + --transition-color: color var(--duration-base) var(--ease-out), + background-color var(--duration-base) var(--ease-out), + border-color var(--duration-base) var(--ease-out); +} diff --git a/docs/design/tokens/radius.css b/docs/design/tokens/radius.css new file mode 100644 index 0000000..214201d --- /dev/null +++ b/docs/design/tokens/radius.css @@ -0,0 +1,11 @@ +/* Kade is rectangular. A rounded card is an antipattern. */ +:root { + --radius-none: 0px; + --radius-sm: 2px; + --radius-md: 4px; + --radius-lg: 8px; + --radius-full: 9999px; + + --border-width: 1px; + --border-width-accent: 2px; +} diff --git a/docs/design/tokens/spacing.css b/docs/design/tokens/spacing.css new file mode 100644 index 0000000..3a4dc82 --- /dev/null +++ b/docs/design/tokens/spacing.css @@ -0,0 +1,21 @@ +/* 4px base step. Section rhythm is deliberately generous; the calm comes from air, not decoration. */ +:root { + --space-1: 4px; + --space-2: 8px; + --space-3: 12px; + --space-4: 16px; + --space-5: 20px; + --space-6: 24px; + --space-8: 32px; + --space-10: 40px; + --space-12: 48px; + --space-16: 64px; + --space-20: 80px; + --space-24: 96px; + + --gutter: var(--space-6); + --section-y: var(--space-24); + --section-y-tight: var(--space-16); + --container: 1140px; + --measure: 68ch; +} diff --git a/docs/design/tokens/typography.css b/docs/design/tokens/typography.css new file mode 100644 index 0000000..f690b37 --- /dev/null +++ b/docs/design/tokens/typography.css @@ -0,0 +1,31 @@ +/* One scale for display (Plex Mono 700) and body (Plex Sans). Line-height tightens as size grows. */ +:root { + --text-2xs: 10px; + --text-xs: 11px; + --text-sm: 13px; + --text-base: 15px; + --text-md: 17px; + --text-lg: 20px; + --text-xl: 24px; + --text-2xl: 32px; + --text-4xl: 44px; + --text-6xl: 58px; + --text-7xl: 76px; + + --leading-display: 1.02; + --leading-tight: 1.15; + --leading-snug: 1.3; + --leading-normal: 1.6; + --leading-loose: 1.7; + + /* Plex Mono display tracking is negative; label tracking is wide. */ + --tracking-display: -0.04em; + --tracking-heading: -0.02em; + --tracking-normal: 0; + --tracking-label: 0.14em; + + --weight-body: 400; + --weight-medium: 500; + --weight-semibold: 600; + --weight-display: 700; +} diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 0000000..83f4e24 --- /dev/null +++ b/docs/index.md @@ -0,0 +1,5 @@ +# Helder docs + +- [Architecture](architecture.md): layers, folder map, commands, file ownership, gotchas. +- [Design tokens](design/README.md): the visual source of truth (colours, type, geometry, screens). +- [Behaviour spec](behaviour.md): every panel and interaction. diff --git a/screenshots/.gitignore b/screenshots/.gitignore new file mode 100644 index 0000000..d6b7ef3 --- /dev/null +++ b/screenshots/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore diff --git a/scripts/build.sh b/scripts/build.sh new file mode 100755 index 0000000..f7e47ed --- /dev/null +++ b/scripts/build.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +# Usage: scripts/build.sh [--release] +set -euo pipefail +source "$(dirname "$0")/env.sh" + +config=debug +for arg in "$@"; do + case "$arg" in + --release) config=release ;; + *) echo "unknown option: $arg" >&2; exit 2 ;; + esac +done + +swift build -c "$config" diff --git a/scripts/bundle.sh b/scripts/bundle.sh new file mode 100755 index 0000000..ba8c3c0 --- /dev/null +++ b/scripts/bundle.sh @@ -0,0 +1,93 @@ +#!/usr/bin/env bash +# Usage: scripts/bundle.sh [--install] [--force] +# --install copy "build/Helder.app" to ~/Applications +# --force let --install replace an app that has a different bundle id +set -euo pipefail +source "$(dirname "$0")/env.sh" + +install=false +force=false +for arg in "$@"; do + case "$arg" in + --install) install=true ;; + --force) force=true ;; + *) echo "unknown option: $arg" >&2; exit 2 ;; + esac +done + +BUNDLE_ID=nl.blijnder.helder +VERSION=0.2.0 +APP="build/Helder.app" + +swift build -c release --product Helder +BIN="$(swift build -c release --show-bin-path)" + +rm -rf "$APP" +mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources" "$APP/Contents/Helpers" +cp "$BIN/Helder" "$APP/Contents/MacOS/Helder" + +# SwiftPM resource bundles go in Contents/Resources: the .app root would break +# the code signature. FontRegistry and SwiftTerm both look there. +for bundle in "$BIN"/*.bundle; do + cp -R "$bundle" "$APP/Contents/Resources/" +done + +# ripgrep powers search and the file list. ExecutableLocator checks Contents/Helpers first. +RG="${RG_BINARY:-}" +[[ -z "$RG" && -x vendor/ripgrep/rg ]] && RG=vendor/ripgrep/rg +[[ -z "$RG" ]] && RG="$(command -v rg || true)" +if [[ -n "$RG" && -x "$RG" ]]; then + cp "$RG" "$APP/Contents/Helpers/rg" +else + echo "warning: no ripgrep found (set RG_BINARY); search falls back to a slow walk" >&2 +fi + +ICONSET="$(mktemp -d)/Helder.iconset" +mkdir -p "$ICONSET" +for size in 16 32 128 256 512; do + sips -z $size $size assets/icon.png --out "$ICONSET/icon_${size}x${size}.png" >/dev/null + sips -z $((size * 2)) $((size * 2)) assets/icon.png --out "$ICONSET/icon_${size}x${size}@2x.png" >/dev/null +done +iconutil -c icns "$ICONSET" -o "$APP/Contents/Resources/Helder.icns" +rm -rf "$(dirname "$ICONSET")" + +cat > "$APP/Contents/Info.plist" < + + + + CFBundleExecutableHelder + CFBundleIdentifier$BUNDLE_ID + CFBundleNameHelder + CFBundleDisplayNameHelder + CFBundlePackageTypeAPPL + CFBundleShortVersionString$VERSION + CFBundleVersion$VERSION + CFBundleIconFileHelder + CFBundleInfoDictionaryVersion6.0 + LSMinimumSystemVersion14.0 + LSApplicationCategoryTypepublic.app-category.developer-tools + NSHighResolutionCapable + NSPrincipalClassNSApplication + + +PLIST + +codesign --force --deep -s - "$APP" +codesign --verify --deep --strict "$APP" +echo "built $APP" + +if $install; then + target="$HOME/Applications/Helder.app" + if [[ -d "$target" ]]; then + existing="$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' "$target/Contents/Info.plist" 2>/dev/null || true)" + if [[ "$existing" != "$BUNDLE_ID" && "$force" != true ]]; then + echo "refusing to replace $target (bundle id '$existing'); pass --force to overwrite it" >&2 + exit 1 + fi + rm -rf "$target" + fi + mkdir -p "$HOME/Applications" + cp -R "$APP" "$target" + echo "installed $target" +fi diff --git a/scripts/env.sh b/scripts/env.sh new file mode 100755 index 0000000..67160e3 --- /dev/null +++ b/scripts/env.sh @@ -0,0 +1,13 @@ +# Sourced by the other scripts. The Command Line Tools swift is broken on this +# machine and so is xcodebuild, so we compile with Xcode's toolchain directly. +XCODE_DEV=/Applications/Xcode.app/Contents/Developer +export PATH=$XCODE_DEV/Toolchains/XcodeDefault.xctoolchain/usr/bin:$PATH +export SDKROOT=$XCODE_DEV/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk +# DEVELOPER_DIR points at the Command Line Tools on purpose: with Xcode's +# developer dir, /usr/bin/xcrun and /usr/bin/git ask the broken xcodebuild for +# every lookup. SwiftPM then cannot read the manifest API's deployment target, +# falls back to macOS 11, and fails to compile swift-argument-parser's plugin. +export DEVELOPER_DIR=/Library/Developer/CommandLineTools +PLATFORM_DEV=$XCODE_DEV/Platforms/MacOSX.platform/Developer +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$ROOT" diff --git a/scripts/run.sh b/scripts/run.sh new file mode 100755 index 0000000..453df1a --- /dev/null +++ b/scripts/run.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +# Usage: scripts/run.sh [project-path] +set -euo pipefail + +# Resolve the project before env.sh changes the working directory. +if [[ $# -gt 0 ]]; then + export HELDER_PROJECT="$(cd "$1" && pwd)" +fi +source "$(dirname "$0")/env.sh" + +swift build +exec "$(swift build --show-bin-path)/Helder" diff --git a/scripts/test.sh b/scripts/test.sh new file mode 100755 index 0000000..a38061e --- /dev/null +++ b/scripts/test.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash +# Usage: scripts/test.sh [swift test args...], e.g. scripts/test.sh --filter LineDiffTests +set -euo pipefail +source "$(dirname "$0")/env.sh" + +# Swift Testing lives in the platform developer dir, which the Xcode toolchain +# does not search on its own when invoked outside xcodebuild. +swift test \ + -Xswiftc -F -Xswiftc "$PLATFORM_DEV/Library/Frameworks" \ + -Xswiftc -I -Xswiftc "$PLATFORM_DEV/usr/lib" \ + -Xlinker -F -Xlinker "$PLATFORM_DEV/Library/Frameworks" \ + -Xlinker -rpath -Xlinker "$PLATFORM_DEV/Library/Frameworks" \ + -Xlinker -L -Xlinker "$PLATFORM_DEV/usr/lib" \ + -Xlinker -rpath -Xlinker "$PLATFORM_DEV/usr/lib" \ + "$@" diff --git a/vendor/ripgrep/LICENSE b/vendor/ripgrep/LICENSE new file mode 100644 index 0000000..4e2bb26 --- /dev/null +++ b/vendor/ripgrep/LICENSE @@ -0,0 +1,13 @@ +vscode-ripgrep + +Copyright (c) Microsoft Corporation + +All rights reserved. + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/ripgrep/rg b/vendor/ripgrep/rg new file mode 100755 index 0000000..43148bb Binary files /dev/null and b/vendor/ripgrep/rg differ