restores Helder in all its glory
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct AgentReferenceTests {
|
||||
@Test func formatsFileLineAndRange() {
|
||||
#expect(AgentReference(path: "src/A.php").description == "src/A.php")
|
||||
#expect(AgentReference(path: "src/A.php", startLine: 42).description == "src/A.php:42")
|
||||
#expect(AgentReference(path: "src/A.php", lines: 42...58).description == "src/A.php:42-58")
|
||||
#expect(AgentReference(path: "src/A.php", lines: 7...7).description == "src/A.php:7")
|
||||
}
|
||||
|
||||
@Test func composesPassOnText() {
|
||||
#expect(PassOn.compose(note: "", reference: "a.php:3") == "a.php:3")
|
||||
#expect(PassOn.compose(note: " fix this ", reference: "a.php:3") == "fix this => a.php:3")
|
||||
#expect(PassOn.compose(note: "why", reference: "a.php:3-4", code: "x\ny") == "why a.php:3-4\n```\nx\ny\n```")
|
||||
}
|
||||
|
||||
@Test func wrapsInBracketedPaste() {
|
||||
#expect(BracketedPaste.wrap("a.php:1", composerHasText: false) == "\u{1b}[200~a.php:1\u{1b}[201~")
|
||||
#expect(BracketedPaste.wrap("a.php:1", composerHasText: true) == "\u{1b}[200~\na.php:1\u{1b}[201~")
|
||||
}
|
||||
|
||||
@Test func pastedTextCannotEndThePasteAndSubmit() {
|
||||
let hostile = "note\u{1b}[201~\rrm -rf ~\r\u{1b}[200~ \u{9b}201~tail"
|
||||
let wrapped = BracketedPaste.wrap(hostile, composerHasText: false)
|
||||
#expect(wrapped == "\u{1b}[200~note[201~\rrm -rf ~\r[200~ 201~tail\u{1b}[201~")
|
||||
#expect(wrapped.unicodeScalars.filter { $0 == "\u{1b}" }.count == 2)
|
||||
}
|
||||
|
||||
@Test func terminalEnvironmentFillsTheGuiGaps() {
|
||||
let env = TerminalLaunch.environment(from: ["npm_config_prefix": "/opt/homebrew", "PATH": "/usr/bin"])
|
||||
#expect(env["npm_config_prefix"] == nil)
|
||||
#expect(env["LANG"] == "en_US.UTF-8")
|
||||
#expect(env["COLORTERM"] == "truecolor")
|
||||
#expect(TerminalLaunch.environment(from: ["LC_ALL": "nl_NL.UTF-8"])["LANG"] == nil)
|
||||
}
|
||||
|
||||
@Test func agentRunsTheCommandThroughAnInteractiveShell() {
|
||||
let launch = TerminalLaunch.make(kind: .agent, config: .defaults, projectRoot: "/p", environment: ["SHELL": "/bin/bash"])
|
||||
#expect(launch.executable == "/bin/bash")
|
||||
#expect(launch.arguments == ["-i", "-c", "claude"])
|
||||
#expect(launch.workingDirectory == "/p")
|
||||
#expect(TerminalLaunch.make(kind: .shell, config: .defaults, projectRoot: nil, environment: [:]).arguments.isEmpty)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct HelderConfigTests {
|
||||
@Test func defaultsMatchTheOldApp() {
|
||||
let c = HelderConfig.defaults
|
||||
#expect(c.ai.command == "claude")
|
||||
#expect(c.ai.autoLaunch)
|
||||
#expect(!c.editor.autoSave)
|
||||
#expect(c.editor.tabSize == 4)
|
||||
#expect(c.editor.wordWrap == .markdown)
|
||||
#expect(c.git.confirmDiscard)
|
||||
#expect(!c.git.confirmStage)
|
||||
#expect(!c.git.confirmUnstage)
|
||||
#expect(c.git.defaultDiffMode == .updated)
|
||||
#expect(c.git.refreshInterval == 10_000)
|
||||
#expect(c.files.exclude.isEmpty)
|
||||
#expect(!c.files.followGitignore)
|
||||
#expect(c.terminal.shell == nil)
|
||||
#expect(c.terminal.fontFamily == nil)
|
||||
#expect(c.terminal.fontSize == nil)
|
||||
#expect(c.terminal.lineHeight == 1.7)
|
||||
#expect(c.terminal.cursorStyle == .bar)
|
||||
#expect(c.terminal.scrollback == 8000)
|
||||
#expect(!c.terminal.optionIsMeta)
|
||||
#expect(c.terminal.theme.background == "#101720")
|
||||
#expect(c.terminal.theme.red == "#C4741F")
|
||||
#expect(c.terminal.theme.selectionBackground == "rgba(232,145,58,0.22)")
|
||||
#expect(c.session.restoreOnLaunch)
|
||||
}
|
||||
|
||||
@Test func anOlderOriginalDefaultDiffModeDecodesAsUpdated() throws {
|
||||
let json = #"{"git":{"defaultDiffMode":"original","confirmStage":true}}"#
|
||||
let c = try JSONDecoder().decode(HelderConfig.self, from: Data(json.utf8))
|
||||
#expect(c.git.defaultDiffMode == .updated)
|
||||
#expect(c.git.confirmStage)
|
||||
#expect(ViewMode(c.git.defaultDiffMode) == .actual)
|
||||
}
|
||||
|
||||
@Test func sparseOverridesMergeKeyByKey() {
|
||||
let json = ##"{"editor":{"tabSize":2},"terminal":{"fontSize":14,"theme":{"red":"#FF0000"}},"files":{"exclude":["*.log"]}}"##
|
||||
let c = HelderConfig.resolved(overrides: Data(json.utf8))
|
||||
#expect(c.editor.tabSize == 2)
|
||||
#expect(c.editor.wordWrap == .markdown)
|
||||
#expect(c.terminal.fontSize == 14)
|
||||
#expect(c.terminal.theme.red == "#FF0000")
|
||||
#expect(c.terminal.theme.green == "#8FBFB4")
|
||||
#expect(c.files.exclude == ["*.log"])
|
||||
#expect(c.ai == HelderConfig.defaults.ai)
|
||||
}
|
||||
|
||||
@Test func wrongTypesAndUnknownValuesKeepTheDefault() {
|
||||
let json = #"{"editor":{"tabSize":"two","wordWrap":"sometimes"},"git":{"refreshInterval":0},"unknown":true}"#
|
||||
let c = HelderConfig.resolved(overrides: Data(json.utf8))
|
||||
#expect(c.editor.tabSize == 4)
|
||||
#expect(c.editor.wordWrap == .markdown)
|
||||
#expect(c.git.refreshInterval == 0)
|
||||
}
|
||||
|
||||
@Test func explicitNullClearsAnOptionalSetting() {
|
||||
let c = HelderConfig.resolved(overrides: Data(#"{"terminal":{"shell":null,"fontFamily":"Menlo"}}"#.utf8))
|
||||
#expect(c.terminal.shell == nil)
|
||||
#expect(c.terminal.fontFamily == "Menlo")
|
||||
}
|
||||
|
||||
@Test(arguments: [nil, "", "{ not json", "[]"])
|
||||
func invalidInputGivesTheDefaults(_ text: String?) {
|
||||
#expect(HelderConfig.resolved(overrides: text.map { Data($0.utf8) }) == .defaults)
|
||||
}
|
||||
|
||||
@Test func defaultsFileRoundTripsAndWritesNulls() throws {
|
||||
let data = HelderConfig.defaultsJSON()
|
||||
let text = String(decoding: data, as: UTF8.self)
|
||||
#expect(text.contains(#""shell" : null"#))
|
||||
#expect(try JSONDecoder().decode(HelderConfig.self, from: data) == .defaults)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct ProjectTitleTests {
|
||||
@Test func readsAppNameAndStripsQuotes() {
|
||||
#expect(ProjectTitle.appName(fromEnv: "APP_ENV=local\nAPP_NAME=\"Loopt Shop\"\n") == "Loopt Shop")
|
||||
#expect(ProjectTitle.appName(fromEnv: "APP_NAME='x'") == "x")
|
||||
}
|
||||
|
||||
@Test func ignoresCommentsAndEmptyValues() {
|
||||
#expect(ProjectTitle.appName(fromEnv: "# APP_NAME=nope\nAPP_NAME=") == nil)
|
||||
#expect(ProjectTitle.title(folderName: "odynt", envContents: nil) == "odynt")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct DiffViewsTests {
|
||||
private func actual(_ original: String, _ updated: String) -> [ViewLine] {
|
||||
DiffViews.actual(LineDiff.build(original: original, updated: updated, status: .modified))
|
||||
}
|
||||
|
||||
@Test("a rewritten line is tinted in place and draws no gap rule")
|
||||
func rewrittenLine() {
|
||||
let lines = actual("a\nold\nb", "a\nnew\nb")
|
||||
#expect(lines.map(\.text) == ["a", "new", "b"])
|
||||
#expect(lines[1].style == .added)
|
||||
#expect(lines.allSatisfy { $0.gap == nil })
|
||||
}
|
||||
|
||||
@Test("a pure deletion marks the next line's top edge")
|
||||
func deletionMarksNextLine() {
|
||||
let lines = actual("a\ngone\nb", "a\nb")
|
||||
#expect(lines[1].text == "b")
|
||||
#expect(lines[1].gap == .above)
|
||||
#expect(lines[1].style == nil)
|
||||
}
|
||||
|
||||
@Test("a deletion at the end of the file rules under the last line")
|
||||
func deletionAtEnd() {
|
||||
let lines = actual("a\nb\ntail", "a\nb")
|
||||
#expect(lines[1].gap == .below)
|
||||
#expect(lines[0].gap == nil)
|
||||
}
|
||||
|
||||
@Test("a deletion at the start of the file rules above the first line")
|
||||
func deletionAtStart() {
|
||||
let lines = actual("gone\na", "a")
|
||||
#expect(lines == [ViewLine(no: 1, text: "a", gap: .above)])
|
||||
}
|
||||
|
||||
@Test("an insertion is tinted and leaves its neighbours alone")
|
||||
func insertion() {
|
||||
let lines = actual("a\nb", "a\nNEW\nb")
|
||||
#expect(lines[1].style == .added)
|
||||
#expect(lines.allSatisfy { $0.gap == nil })
|
||||
}
|
||||
|
||||
@Test("an unchanged file carries no marks")
|
||||
func unchanged() {
|
||||
let lines = actual("a\nb\n", "a\nb\n")
|
||||
#expect(lines.allSatisfy { $0.style == nil && $0.gap == nil })
|
||||
}
|
||||
|
||||
@Test("a deleted file has no Actual lines")
|
||||
func deletedFile() {
|
||||
#expect(DiffViews.actual(LineDiff.build(original: "a\nb", updated: "", status: .deleted)).isEmpty)
|
||||
}
|
||||
|
||||
@Test("the removed line only leaves one rule")
|
||||
func onlyOneRule() {
|
||||
let lines = actual("keep\ngone\ntail\n", "keep\ntail\n")
|
||||
#expect(lines.filter { $0.gap != nil }.count == 1)
|
||||
#expect(lines.filter { $0.style != nil }.isEmpty)
|
||||
}
|
||||
|
||||
@Test("a plain file is numbered from 1 and drops one trailing newline")
|
||||
func plain() {
|
||||
#expect(DiffViews.plain("x\ny\n") == [ViewLine(no: 1, text: "x"), ViewLine(no: 2, text: "y")])
|
||||
#expect(DiffViews.plain("") == [ViewLine(no: 1, text: "")])
|
||||
}
|
||||
}
|
||||
|
||||
@Suite struct DiffViewsLineEndingTests {
|
||||
@Test("a CRLF file keeps one line per CRLF in the plain view")
|
||||
func crlfPlain() {
|
||||
#expect(DiffViews.plain("a\r\nb\r\n").map(\.text) == ["a\r", "b\r"])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct LineDiffTests {
|
||||
@Test("identical text has no changes")
|
||||
func identical() {
|
||||
let diff = LineDiff.build(original: "a\nb\nc\n", updated: "a\nb\nc\n")
|
||||
#expect(diff.added == 0)
|
||||
#expect(diff.removed == 0)
|
||||
#expect(diff.rows.allSatisfy { $0.sign == .same })
|
||||
}
|
||||
|
||||
@Test("one changed line is one addition and one removal")
|
||||
func singleChange() {
|
||||
let diff = LineDiff.build(original: "a\nb\nc", updated: "a\nB\nc")
|
||||
#expect(diff.added == 1)
|
||||
#expect(diff.removed == 1)
|
||||
#expect(diff.rows.map(\.sign) == [.same, .removed, .added, .same])
|
||||
}
|
||||
|
||||
@Test("rows carry old and new line numbers")
|
||||
func lineNumbers() {
|
||||
let diff = LineDiff.build(original: "a\nold\nb", updated: "a\nnew\nb\nc")
|
||||
#expect(diff.rows == [
|
||||
DiffRow(sign: .same, oldNo: 1, newNo: 1, text: "a"),
|
||||
DiffRow(sign: .removed, oldNo: 2, newNo: nil, text: "old"),
|
||||
DiffRow(sign: .added, oldNo: nil, newNo: 2, text: "new"),
|
||||
DiffRow(sign: .same, oldNo: 3, newNo: 3, text: "b"),
|
||||
DiffRow(sign: .added, oldNo: nil, newNo: 4, text: "c"),
|
||||
])
|
||||
}
|
||||
|
||||
@Test("an empty original is all additions, as for a new file")
|
||||
func newFile() {
|
||||
let diff = LineDiff.build(original: "", updated: "x\ny", status: .added)
|
||||
#expect(diff.added == 2)
|
||||
#expect(diff.removed == 0)
|
||||
#expect(diff.left.isEmpty)
|
||||
#expect(diff.right.count == 2)
|
||||
#expect(diff.isAddedFile)
|
||||
#expect(!diff.isDeletedFile)
|
||||
}
|
||||
|
||||
@Test("an empty update is all removals, as for a deleted file")
|
||||
func deletedFile() {
|
||||
let diff = LineDiff.build(original: "x\ny\nz", updated: "", status: .deleted)
|
||||
#expect(diff.removed == 3)
|
||||
#expect(diff.added == 0)
|
||||
#expect(diff.right.isEmpty)
|
||||
#expect(diff.isDeletedFile)
|
||||
#expect(!diff.isAddedFile)
|
||||
}
|
||||
|
||||
@Test("both sides mark the changed line and leave the rest unmarked")
|
||||
func sideMarks() {
|
||||
let diff = LineDiff.build(original: "keep\nold\nkeep", updated: "keep\nnew\nkeep")
|
||||
#expect(diff.left.first { $0.text == "old" }?.mark == .removed)
|
||||
#expect(diff.right.first { $0.text == "new" }?.mark == .added)
|
||||
#expect(diff.left.first { $0.text == "keep" }?.mark == nil)
|
||||
}
|
||||
|
||||
@Test("split rows pair unchanged lines and stack changes beside each other")
|
||||
func splitAlignment() {
|
||||
let diff = LineDiff.build(original: "a\nold\nb", updated: "a\nnew\nb")
|
||||
#expect(diff.split.allSatisfy { $0.left != nil || $0.right != nil })
|
||||
let paired = diff.split.filter { $0.left != nil && $0.right != nil && $0.left?.text == $0.right?.text }
|
||||
#expect(paired.compactMap { $0.left?.text } == ["a", "b"])
|
||||
#expect(diff.split[1] == SplitRow(left: SideLine(no: 2, text: "old", mark: .removed), right: SideLine(no: 2, text: "new", mark: .added)))
|
||||
}
|
||||
|
||||
@Test("a longer removal than addition leaves fillers on the right")
|
||||
func splitFillers() {
|
||||
let diff = LineDiff.build(original: "a\nx\ny\nb", updated: "a\nz\nb")
|
||||
#expect(diff.split.map { [$0.left?.text, $0.right?.text] } == [["a", "a"], ["x", "z"], ["y", nil], ["b", "b"]])
|
||||
}
|
||||
|
||||
@Test("a single trailing newline difference is no change")
|
||||
func trailingNewline() {
|
||||
let diff = LineDiff.build(original: "a\nb", updated: "a\nb\n")
|
||||
#expect(diff.added == 0)
|
||||
#expect(diff.removed == 0)
|
||||
}
|
||||
|
||||
@Test("CRLF text keeps its carriage returns, so a line-ending change shows as a change")
|
||||
func crlf() {
|
||||
let diff = LineDiff.build(original: "a\r\nb\r\n", updated: "a\nb\n")
|
||||
#expect(diff.removed == 2)
|
||||
#expect(diff.added == 2)
|
||||
}
|
||||
|
||||
@Test("unicode lines compare whole")
|
||||
func unicode() {
|
||||
let diff = LineDiff.build(original: "café\n😀", updated: "cafe\u{301}\n😀")
|
||||
#expect(diff.rows.last == DiffRow(sign: .same, oldNo: 2, newNo: 2, text: "😀"))
|
||||
}
|
||||
|
||||
@Test("on a tie a removal comes before an addition")
|
||||
func tieOrder() {
|
||||
let diff = LineDiff.build(original: "a\nb", updated: "b\na")
|
||||
#expect(diff.rows.map(\.sign) == [.removed, .same, .added])
|
||||
}
|
||||
|
||||
@Test("the diff keeps the text pair it was built from")
|
||||
func carriesTexts() {
|
||||
let diff = LineDiff.build(original: "bye", updated: "", status: .deleted)
|
||||
#expect(diff.original == "bye")
|
||||
#expect(diff.updated == "")
|
||||
}
|
||||
|
||||
@Test("lines() drops one trailing newline and reads empty text as no lines")
|
||||
func lines() {
|
||||
#expect(LineDiff.lines("") == [])
|
||||
#expect(LineDiff.lines("a\n") == ["a"])
|
||||
#expect(LineDiff.lines("a\n\n") == ["a", ""])
|
||||
#expect(LineDiff.lines("\n") == [""])
|
||||
#expect(LineDiff.lines("a\r\nb\r\n") == ["a\r", "b\r"])
|
||||
}
|
||||
|
||||
@Test("a 60k-line file with one edit diffs without a full matrix")
|
||||
func largeFileSingleEdit() {
|
||||
var lines = (0..<60_000).map { "line \($0)" }
|
||||
let base = lines.joined(separator: "\n")
|
||||
lines[30_000] = "line 30000 edited"
|
||||
let diff = LineDiff.build(original: base, updated: lines.joined(separator: "\n"))
|
||||
#expect(diff.added == 1)
|
||||
#expect(diff.removed == 1)
|
||||
#expect(diff.right[30_000].mark == .added)
|
||||
}
|
||||
|
||||
@Test("a large rewrite with no shared lines replaces everything")
|
||||
func largeRewrite() {
|
||||
let a = (0..<40_000).map { "old \($0)" }.joined(separator: "\n")
|
||||
let b = (0..<40_000).map { "new \($0)" }.joined(separator: "\n")
|
||||
let diff = LineDiff.build(original: a, updated: b)
|
||||
#expect(diff.removed == 40_000)
|
||||
#expect(diff.added == 40_000)
|
||||
}
|
||||
|
||||
@Test("a large, heavily edited file keeps its unchanged head and tail")
|
||||
func largeHeadAndTail() {
|
||||
let head = (0..<5_000).map { "head \($0)" }
|
||||
let tail = (0..<5_000).map { "tail \($0)" }
|
||||
func middle(_ prefix: String) -> [String] { (0..<30_000).map { "\(prefix) \($0 % 7)" } }
|
||||
let diff = LineDiff.build(
|
||||
original: (head + middle("x") + tail).joined(separator: "\n"),
|
||||
updated: (head + middle("y") + tail).joined(separator: "\n")
|
||||
)
|
||||
#expect(diff.left.prefix(5_000).allSatisfy { $0.mark == nil })
|
||||
#expect(diff.left.suffix(5_000).allSatisfy { $0.mark == nil })
|
||||
#expect(diff.added == 30_000)
|
||||
}
|
||||
|
||||
@Test("over the cell budget, unique anchor lines still pair the moved-around middle")
|
||||
func anchorsSplitLargeRegions() {
|
||||
let shared = (0..<3_000).map { "shared \($0)" }
|
||||
let a = shared.flatMap { ["\($0)", "a-noise"] }
|
||||
let b = shared.flatMap { ["\($0)", "b-noise"] }
|
||||
let diff = LineDiff.build(original: a.joined(separator: "\n"), updated: b.joined(separator: "\n"))
|
||||
#expect(diff.rows.filter { $0.sign == .same }.count == 3_000)
|
||||
#expect(diff.added == 3_000)
|
||||
#expect(diff.removed == 3_000)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct ViewModeTests {
|
||||
@Test func rawValuesMatchTheOldSessionStrings() {
|
||||
#expect(ViewMode.actual.rawValue == "updated")
|
||||
#expect(ViewMode(DefaultDiffMode.updated) == .actual)
|
||||
#expect(ViewMode(DefaultDiffMode.diff) == .diff)
|
||||
}
|
||||
|
||||
@Test func anOriginalModeIsNotAViewMode() {
|
||||
#expect(ViewMode(rawValue: "original") == nil)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct TerminalContextMenuTests {
|
||||
private func labels(_ target: ContextTarget) -> [String] {
|
||||
ContextActions.entries(for: target).compactMap { entry in
|
||||
guard case let .action(_, label) = entry else { return nil }
|
||||
return label
|
||||
}
|
||||
}
|
||||
|
||||
@Test func copyAppearsOnlyWithASelection() {
|
||||
#expect(labels(.terminal(.agent, hasSelection: true)) == ["Copy", "Paste"])
|
||||
#expect(labels(.terminal(.shell, hasSelection: false)) == ["Paste"])
|
||||
}
|
||||
|
||||
@Test func theActionsNameTheirPane() {
|
||||
#expect(ContextActions.entries(for: .terminal(.shell, hasSelection: true)) == [
|
||||
.action(.copyTerminalSelection(.shell), label: "Copy"),
|
||||
.action(.pasteIntoTerminal(.shell), label: "Paste"),
|
||||
])
|
||||
}
|
||||
|
||||
@Test func theMenuHasNoHeader() {
|
||||
#expect(ContextActions.header(for: .terminal(.agent, hasSelection: false), projectName: "app").isEmpty)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct FileLimitsTests {
|
||||
@Test("a NUL byte in the first 8000 bytes marks a file binary")
|
||||
func binary() {
|
||||
#expect(FileLimits.looksBinary(Data([0x00, 0x01, 0x02])))
|
||||
#expect(!FileLimits.looksBinary(Data("plain text".utf8)))
|
||||
#expect(!FileLimits.looksBinary(Data(repeating: 0x41, count: 8000) + Data([0x00])))
|
||||
}
|
||||
|
||||
@Test("ripgrep gets the base ignores, the configured excludes and --no-ignore")
|
||||
func ripgrepArguments() {
|
||||
var files = HelderConfig.Files()
|
||||
files.exclude = ["*.log", ""]
|
||||
let args = IgnoreRules.ripgrepArguments(files: files, base: ["node_modules"])
|
||||
#expect(args == ["--glob", "!node_modules", "--glob", "!*.log", "--no-ignore"])
|
||||
files.exclude = []
|
||||
files.followGitignore = true
|
||||
let following = IgnoreRules.ripgrepArguments(files: files, base: [])
|
||||
#expect(following.isEmpty)
|
||||
}
|
||||
|
||||
@Test("symbol searches index vendor declarations but skip vendor references")
|
||||
func symbolIgnores() {
|
||||
#expect(!IgnoreRules.symbolDeclarationIgnore.contains("vendor"))
|
||||
#expect(IgnoreRules.symbolReferenceIgnore.contains("vendor"))
|
||||
}
|
||||
|
||||
@Test("the watcher drops events inside ignored folders")
|
||||
func watchIgnored() {
|
||||
#expect(IgnoreRules.isWatchIgnored("node_modules/x/y.js"))
|
||||
#expect(IgnoreRules.isWatchIgnored("a/.git/HEAD"))
|
||||
#expect(!IgnoreRules.isWatchIgnored("src/gitlike/x"))
|
||||
#expect(IgnoreRules.isWalkIgnored(".DS_Store"))
|
||||
}
|
||||
|
||||
@Test("the watcher drops framework caches and the configured excludes")
|
||||
func watchIgnoredWithExcludes() {
|
||||
#expect(IgnoreRules.isWatchIgnored("storage/framework/views/abc.php", exclude: []))
|
||||
#expect(IgnoreRules.isWatchIgnored("bootstrap/cache/packages.php", exclude: []))
|
||||
#expect(IgnoreRules.isWatchIgnored(".phpunit.result.cache", exclude: []))
|
||||
#expect(IgnoreRules.isWatchIgnored("node_modules/x.js", exclude: []))
|
||||
#expect(!IgnoreRules.isWatchIgnored("storage/logs/laravel.log", exclude: []))
|
||||
#expect(IgnoreRules.isWatchIgnored("storage/logs/laravel.log", exclude: ["*.log"]))
|
||||
#expect(IgnoreRules.isWatchIgnored("public/hot/x.js", exclude: ["public/hot"]))
|
||||
#expect(!IgnoreRules.isWatchIgnored("app/Models/User.php", exclude: ["*.log", ""]))
|
||||
}
|
||||
|
||||
@Test("glob matching follows ripgrep's --glob rules", arguments: [
|
||||
("*.log", "debug.log", true),
|
||||
("*.log", "logs/deep/debug.log", true),
|
||||
("*.log", "debug.log.txt", false),
|
||||
("node_modules", "node_modules", true),
|
||||
("node_modules", "a/node_modules/pkg/index.js", true),
|
||||
("node_modules", "node_modules_extra/x", false),
|
||||
("src/*.ts", "src/a.ts", true),
|
||||
("src/*.ts", "src/deep/a.ts", false),
|
||||
("src/*.ts", "lib/src/a.ts", false),
|
||||
("/build", "build/x.js", true),
|
||||
("/build", "app/build/x.js", false),
|
||||
("docs/", "docs/readme.md", true),
|
||||
("**/fixtures/*.json", "fixtures/a.json", true),
|
||||
("**/fixtures/*.json", "tests/unit/fixtures/a.json", true),
|
||||
("a/**/b", "a/b", true),
|
||||
("a/**/b", "a/x/y/b", true),
|
||||
("storage/**", "storage/logs/x.log", true),
|
||||
("file?.txt", "file1.txt", true),
|
||||
("file?.txt", "file10.txt", false),
|
||||
("[abc].md", "b.md", true),
|
||||
("[!abc].md", "b.md", false),
|
||||
("[a-c]x", "cx", true),
|
||||
("*.{js,ts}", "x.ts", true),
|
||||
("*.{js,ts}", "x.css", false),
|
||||
("", "a", false),
|
||||
("*.min.*", "dist-like/app.min.js", true),
|
||||
])
|
||||
func glob(pattern: String, path: String, matches: Bool) {
|
||||
#expect(IgnoreRules.globMatches(pattern, path: path) == matches)
|
||||
}
|
||||
|
||||
@Test("a pathological glob still answers quickly")
|
||||
func pathologicalGlob() {
|
||||
let path = String(repeating: "a", count: 200)
|
||||
#expect(!IgnoreRules.globMatches("*a*a*a*a*a*a*a*a*b", path: path))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct FileNodeTests {
|
||||
private func names(_ node: FileNode?) -> [String] {
|
||||
(node?.children ?? []).map(\.name)
|
||||
}
|
||||
|
||||
@Test("folders come before files, each sorted by name")
|
||||
func foldersFirst() {
|
||||
let tree = FileTree.build(rootName: "proj", paths: ["README.md", "src/a.ts", "logo.bin", "app/x.php"])
|
||||
#expect(tree.name == "proj")
|
||||
#expect(tree.path == "")
|
||||
#expect(names(tree) == ["app", "src", "logo.bin", "README.md"])
|
||||
}
|
||||
|
||||
@Test("sorting ignores case, like localeCompare")
|
||||
func caseInsensitiveSort() {
|
||||
let tree = FileTree.build(rootName: "p", paths: ["b.txt", "A.txt", "a.md", "C.txt"])
|
||||
#expect(names(tree) == ["a.md", "A.txt", "b.txt", "C.txt"])
|
||||
}
|
||||
|
||||
@Test("nested paths build nested folders with full relative paths")
|
||||
func nesting() {
|
||||
let tree = FileTree.build(rootName: "p", paths: ["a/b/c.txt", "a/d.txt"])
|
||||
let b = FileTree.find("a/b", in: tree)
|
||||
#expect(b?.kind == .directory)
|
||||
#expect(names(b) == ["c.txt"])
|
||||
#expect(FileTree.find("a/b/c.txt", in: tree)?.kind == .file)
|
||||
#expect(FileTree.find("a/b/c.txt", in: tree)?.children == nil)
|
||||
}
|
||||
|
||||
@Test("empty folders that rg cannot list are forced into the tree")
|
||||
func emptyFolders() {
|
||||
let tree = FileTree.build(rootName: "p", paths: ["src/a.ts"], emptyDirs: ["empty", "src/nested/deep"])
|
||||
#expect(names(tree) == ["empty", "src"])
|
||||
#expect(FileTree.find("empty", in: tree)?.children == [])
|
||||
#expect(names(FileTree.find("src/nested", in: tree)) == ["deep"])
|
||||
}
|
||||
|
||||
@Test("duplicate and malformed paths do not duplicate nodes")
|
||||
func duplicates() {
|
||||
let tree = FileTree.build(rootName: "p", paths: ["a.txt", "a.txt", "", "/b.txt", "c//d.txt"], emptyDirs: ["", "c"])
|
||||
#expect(names(tree) == ["c", "a.txt", "b.txt"])
|
||||
#expect(names(FileTree.find("c", in: tree)) == ["d.txt"])
|
||||
}
|
||||
|
||||
@Test("an empty listing is an empty root")
|
||||
func emptyListing() {
|
||||
#expect(FileTree.build(rootName: "p", paths: []) == FileNode(name: "p", kind: .directory, path: "", children: []))
|
||||
}
|
||||
|
||||
@Test("visible rows honour expanded folders and hidden files")
|
||||
func visibleRows() {
|
||||
let tree = FileTree.build(rootName: "p", paths: [".env", "src/a.ts", "src/.hidden", "b.txt"])
|
||||
#expect(FileTree.visibleRows(tree, expanded: [], showHidden: false).map(\.path) == ["src", "b.txt"])
|
||||
let open = FileTree.visibleRows(tree, expanded: ["src"], showHidden: true)
|
||||
#expect(open.map(\.path) == ["src", "src/.hidden", "src/a.ts", ".env", "b.txt"])
|
||||
#expect(open.map(\.depth) == [0, 1, 1, 0, 0])
|
||||
}
|
||||
|
||||
@Test("replacing a folder's children leaves the rest of the tree alone")
|
||||
func replacingChildren() {
|
||||
let tree = FileTree.build(rootName: "p", paths: ["src/a.ts", "lib/b.ts"])
|
||||
let fresh = FileNode(name: "z.ts", kind: .file, path: "src/z.ts")
|
||||
let updated = FileTree.replacingChildren(of: "src", with: [fresh], in: tree)
|
||||
#expect(names(FileTree.find("src", in: updated)) == ["z.ts"])
|
||||
#expect(names(FileTree.find("lib", in: updated)) == ["b.ts"])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct FileTypeTests {
|
||||
@Test func badgesFollowTheOldTable() {
|
||||
#expect(FileType.badge(for: "src/A.php") == FileBadge("php", .purple))
|
||||
#expect(FileType.badge(for: "package.json") == FileBadge("json", .amber))
|
||||
#expect(FileType.badge(for: "composer.json") == FileBadge("json", .purple))
|
||||
#expect(FileType.badge(for: ".env.local") == FileBadge("env", .teal))
|
||||
#expect(FileType.badge(for: "Makefile") == FileBadge("·", .grey))
|
||||
}
|
||||
|
||||
@Test func languagesAndLabels() {
|
||||
#expect(FileType.language(for: "a.tsx") == .tsx)
|
||||
#expect(FileType.languageLabel(for: "a.yml") == "YAML")
|
||||
#expect(FileType.languageLabel(for: "a.rs") == "RS")
|
||||
#expect(FileType.isImage("logo.PNG"))
|
||||
}
|
||||
|
||||
@Test func ripgrepArgumentsHonourTheConfig() {
|
||||
var files = HelderConfig.Files()
|
||||
files.exclude = ["*.log"]
|
||||
let args = IgnoreRules.ripgrepArguments(files: files, base: ["node_modules"])
|
||||
#expect(args == ["--glob", "!node_modules", "--glob", "!*.log", "--no-ignore"])
|
||||
}
|
||||
|
||||
@Test func pathHelpers() {
|
||||
#expect(PathUtils.ancestors("a/b/c.txt") == ["a", "a/b"])
|
||||
#expect(PathUtils.remap("a/b/c.txt", from: "a/b", to: "a/x", isDirectory: true) == "a/x/c.txt")
|
||||
#expect(PathUtils.validatedName(" ../ ") == nil)
|
||||
#expect(PathUtils.validatedName("new.md/") == "new.md")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct GitDerivationTests {
|
||||
private func change(_ path: String, _ status: GitStatus, staged: Bool, _ original: String, _ updated: String) -> GitFileChange {
|
||||
GitFileChange(path: path, status: status, staged: staged, original: original, updated: updated)
|
||||
}
|
||||
|
||||
@Test("a change over the diff cap marks its row and whole-file diffs as too big")
|
||||
func tooBig() {
|
||||
let snapshot = GitSnapshot(branch: "main", ahead: 0, canPush: false, changes: [
|
||||
GitFileChange(path: "dump.sql", status: .modified, staged: true, original: "", updated: "", isTooBig: false),
|
||||
GitFileChange(path: "dump.sql", status: .modified, staged: false, original: "", updated: "", isTooBig: true),
|
||||
change("a.txt", .modified, staged: false, "1\n", "2\n"),
|
||||
])
|
||||
let state = GitDerivation.derive(snapshot)
|
||||
#expect(state.changes.map(\.path) == ["dump.sql", "dump.sql", "a.txt"])
|
||||
#expect(state.rowDiffs["s:dump.sql"]?.isTooBig == false)
|
||||
#expect(state.rowDiffs["w:dump.sql"]?.isTooBig == true)
|
||||
#expect(state.fileDiffs["dump.sql"]?.isTooBig == true)
|
||||
#expect(state.fileDiffs["a.txt"]?.isTooBig == false)
|
||||
}
|
||||
|
||||
@Test("no snapshot means not a repository")
|
||||
func notARepository() {
|
||||
let state = GitDerivation.derive(nil)
|
||||
#expect(!state.isRepository)
|
||||
#expect(state.branch == "—")
|
||||
#expect(state.changes.isEmpty)
|
||||
}
|
||||
|
||||
@Test("one row per change, with its line counts and row diff")
|
||||
func rows() {
|
||||
let snapshot = GitSnapshot(branch: "main", ahead: 1, canPush: true, changes: [
|
||||
change("a.txt", .modified, staged: false, "1\n2\n3\n", "1\nX\n3\n4\n"),
|
||||
])
|
||||
let state = GitDerivation.derive(snapshot)
|
||||
#expect(state.isRepository)
|
||||
#expect(state.branch == "main")
|
||||
#expect(state.ahead == 1)
|
||||
#expect(state.canPush)
|
||||
#expect(state.changes == [Change(path: "a.txt", status: .modified, added: 2, removed: 1, staged: false)])
|
||||
#expect(state.rowDiffs["w:a.txt"]?.added == 2)
|
||||
#expect(state.fileDiffs["a.txt"]?.updated == "1\nX\n3\n4\n")
|
||||
#expect(state.stagedPaths.isEmpty)
|
||||
}
|
||||
|
||||
@Test("a staged-then-edited file compares HEAD with disk for the whole-file views")
|
||||
func twoRowsWholeFile() {
|
||||
let snapshot = GitSnapshot(branch: "main", ahead: 0, canPush: false, changes: [
|
||||
change("a.txt", .modified, staged: true, "1\n2\n3\n", "1\nSTAGED\n3\n"),
|
||||
change("a.txt", .modified, staged: false, "1\nSTAGED\n3\n", "1\nSTAGED\n3\n4\n"),
|
||||
])
|
||||
let state = GitDerivation.derive(snapshot)
|
||||
#expect(state.changes.map(\.id) == ["s:a.txt", "w:a.txt"])
|
||||
#expect(state.stagedPaths == ["a.txt"])
|
||||
let whole = state.fileDiffs["a.txt"]
|
||||
#expect(whole?.original == "1\n2\n3\n")
|
||||
#expect(whole?.updated == "1\nSTAGED\n3\n4\n")
|
||||
#expect(state.rowDiffs["s:a.txt"]?.updated == "1\nSTAGED\n3\n")
|
||||
#expect(state.rowDiffs["w:a.txt"]?.original == "1\nSTAGED\n3\n")
|
||||
}
|
||||
|
||||
@Test("the unstaged row owns the file status: staged as modified but deleted on disk reads deleted")
|
||||
func unstagedOwnsStatus() {
|
||||
let snapshot = GitSnapshot(branch: "main", ahead: 0, canPush: false, changes: [
|
||||
change("a.txt", .modified, staged: true, "old\n", "new\n"),
|
||||
change("a.txt", .deleted, staged: false, "new\n", ""),
|
||||
])
|
||||
let state = GitDerivation.derive(snapshot)
|
||||
#expect(state.fileDiffs["a.txt"]?.isDeletedFile == true)
|
||||
#expect(state.fileDiffs["a.txt"]?.original == "old\n")
|
||||
#expect(state.changes.last?.isDeleted == true)
|
||||
}
|
||||
|
||||
@Test("the unstaged row first and the staged row second still pair HEAD with disk")
|
||||
func reversedRowOrder() {
|
||||
let snapshot = GitSnapshot(branch: "main", ahead: 0, canPush: false, changes: [
|
||||
change("a.txt", .modified, staged: false, "index\n", "disk\n"),
|
||||
change("a.txt", .added, staged: true, "", "index\n"),
|
||||
])
|
||||
let whole = GitDerivation.derive(snapshot).fileDiffs["a.txt"]
|
||||
#expect(whole?.original == "")
|
||||
#expect(whole?.updated == "disk\n")
|
||||
#expect(whole?.isAddedFile == false)
|
||||
}
|
||||
|
||||
@Test("a renamed row keeps the path it was renamed from")
|
||||
func renameSource() {
|
||||
var renamed = change("new.txt", .renamed, staged: true, "a\n", "a\n")
|
||||
renamed.originalPath = "old.txt"
|
||||
let state = GitDerivation.derive(GitSnapshot(branch: "main", ahead: 0, canPush: false, changes: [renamed]))
|
||||
#expect(state.changes.first?.originalPath == "old.txt")
|
||||
#expect(state.fileDiffs["new.txt"] == state.rowDiffs["s:new.txt"])
|
||||
}
|
||||
|
||||
@Test("a new file is an added file diff")
|
||||
func newFile() {
|
||||
let snapshot = GitSnapshot(branch: "main", ahead: 0, canPush: true, changes: [change("n.txt", .added, staged: false, "", "fresh\n")])
|
||||
let state = GitDerivation.derive(snapshot)
|
||||
#expect(state.fileDiffs["n.txt"]?.isAddedFile == true)
|
||||
#expect(state.totals == (added: 1, removed: 0))
|
||||
#expect(state.unstagedPaths == ["n.txt"])
|
||||
}
|
||||
}
|
||||
|
||||
@Suite struct SourceControlTextTests {
|
||||
private func change(_ path: String, staged: Bool = false) -> Change {
|
||||
Change(path: path, status: .modified, added: 1, removed: 0, staged: staged)
|
||||
}
|
||||
|
||||
@Test("one group per folder, even when git returns the folder in separate runs")
|
||||
func oneGroupPerFolder() {
|
||||
let groups = SourceControlText.groupByDir([
|
||||
change("tests/Feature/AlphaTest.php"), change("app/Models/User.php"), change("tests/Feature/BetaTest.php"),
|
||||
])
|
||||
#expect(groups.map(\.dir) == ["tests/Feature", "app/Models"])
|
||||
#expect(groups[0].rows.map(\.path) == ["tests/Feature/AlphaTest.php", "tests/Feature/BetaTest.php"])
|
||||
}
|
||||
|
||||
@Test("every row is kept, so the keyboard cursor walks the full list")
|
||||
func keepsEveryRow() {
|
||||
let list = ["a/one.ts", "b/two.ts", "a/three.ts", "four.ts"].map { change($0) }
|
||||
let flat = SourceControlText.groupByDir(list).flatMap(\.rows)
|
||||
#expect(flat.count == list.count)
|
||||
#expect(Set(flat.map(\.id)).count == list.count)
|
||||
}
|
||||
|
||||
@Test("a project-root file sits in the empty-string group")
|
||||
func rootGroup() {
|
||||
#expect(SourceControlText.groupByDir([change("README.md")]) == [ChangeGroup(dir: "", rows: [change("README.md")])])
|
||||
}
|
||||
|
||||
@Test("navigation walks staged groups before unstaged ones")
|
||||
func navigationOrder() {
|
||||
let order = SourceControlText.navigationOrder([change("b/x"), change("a/y", staged: true), change("b/z")])
|
||||
#expect(order.map(\.path) == ["a/y", "b/x", "b/z"])
|
||||
}
|
||||
|
||||
@Test("a dictated commit message becomes one lowercase line")
|
||||
func commitMessage() {
|
||||
#expect(SourceControlText.normalizeCommitMessage("Fix The Bug\n In Parser \r\n") == "fix the bug in parser ")
|
||||
}
|
||||
|
||||
@Test("the push tooltip counts commits")
|
||||
func pushTooltip() {
|
||||
#expect(SourceControlText.pushTooltip(canPush: false, ahead: 0) == "Nothing to push (⌘P)")
|
||||
#expect(SourceControlText.pushTooltip(canPush: true, ahead: 1) == "Push 1 commit to remote (⌘P)")
|
||||
#expect(SourceControlText.pushTooltip(canPush: true, ahead: 3) == "Push 3 commits to remote (⌘P)")
|
||||
#expect(SourceControlText.pushTooltip(canPush: true, ahead: 0) == "Push the branch to remote (⌘P)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct PorcelainTests {
|
||||
// MARK: classify
|
||||
|
||||
@Test("the index column is the staged row, the working column the unstaged row")
|
||||
func columns() {
|
||||
#expect(Porcelain.classify(index: "M", working: " ") == [GitRowSpec(status: .modified, staged: true)])
|
||||
#expect(Porcelain.classify(index: " ", working: "M") == [GitRowSpec(status: .modified, staged: false)])
|
||||
#expect(Porcelain.classify(index: "A", working: " ") == [GitRowSpec(status: .added, staged: true)])
|
||||
#expect(Porcelain.classify(index: "D", working: " ") == [GitRowSpec(status: .deleted, staged: true)])
|
||||
#expect(Porcelain.classify(index: "R", working: " ") == [GitRowSpec(status: .renamed, staged: true)])
|
||||
}
|
||||
|
||||
@Test("an untracked file is one unstaged addition")
|
||||
func untracked() {
|
||||
#expect(Porcelain.classify(index: "?", working: "?") == [GitRowSpec(status: .added, staged: false)])
|
||||
}
|
||||
|
||||
@Test("a staged-then-edited file is two rows", arguments: [
|
||||
("M", "M", GitStatus.modified, GitStatus.modified),
|
||||
("A", "M", .added, .modified),
|
||||
("M", "D", .modified, .deleted),
|
||||
] as [(Character, Character, GitStatus, GitStatus)])
|
||||
func twoRows(index: Character, working: Character, staged: GitStatus, unstaged: GitStatus) {
|
||||
#expect(Porcelain.classify(index: index, working: working) == [
|
||||
GitRowSpec(status: staged, staged: true), GitRowSpec(status: unstaged, staged: false),
|
||||
])
|
||||
}
|
||||
|
||||
@Test("a merge conflict stays one row", arguments: [("U", "U"), ("A", "A"), ("D", "D"), ("U", "D")] as [(Character, Character)])
|
||||
func conflict(index: Character, working: Character) {
|
||||
#expect(Porcelain.classify(index: index, working: working) == [GitRowSpec(status: .modified, staged: true)])
|
||||
}
|
||||
|
||||
// MARK: headers
|
||||
|
||||
@Test("the ahead count comes from the header", arguments: [
|
||||
("main...origin/main [ahead 3]", 3, true),
|
||||
("main...origin/main [ahead 1, behind 2]", 1, true),
|
||||
("main...origin/main", 0, false),
|
||||
("main...origin/main [behind 2]", 0, false),
|
||||
("feature/x", 0, true),
|
||||
("No commits yet on main", 0, false),
|
||||
("HEAD (no branch)", 0, false),
|
||||
])
|
||||
func ahead(header: String, count: Int, canPush: Bool) {
|
||||
let result = Porcelain.parseAhead(header: header)
|
||||
#expect(result.ahead == count)
|
||||
#expect(result.canPush == canPush)
|
||||
}
|
||||
|
||||
@Test("the branch name comes from the header", arguments: [
|
||||
("main...origin/main [ahead 1]", "main"),
|
||||
("main", "main"),
|
||||
("feature/x...origin/feature/x", "feature/x"),
|
||||
("No commits yet on trunk", "trunk"),
|
||||
("HEAD (no branch)", "HEAD"),
|
||||
("", "HEAD"),
|
||||
])
|
||||
func branch(header: String, name: String) {
|
||||
#expect(Porcelain.parseBranch(header: header) == name)
|
||||
}
|
||||
|
||||
// MARK: parseStatus
|
||||
|
||||
@Test("status output is NUL-separated with the header first")
|
||||
func parseStatus() {
|
||||
let raw = "## main...origin/main [ahead 2]\0 M src/a.ts\0?? new file.txt\0MM both.php\0"
|
||||
let parsed = Porcelain.parseStatus(raw)
|
||||
#expect(parsed.branch == "main")
|
||||
#expect(parsed.ahead == 2)
|
||||
#expect(parsed.canPush)
|
||||
#expect(parsed.entries == [
|
||||
StatusEntry(index: " ", working: "M", path: "src/a.ts"),
|
||||
StatusEntry(index: "?", working: "?", path: "new file.txt"),
|
||||
StatusEntry(index: "M", working: "M", path: "both.php"),
|
||||
])
|
||||
}
|
||||
|
||||
@Test("a rename shows its destination and skips the source field")
|
||||
func renameSkipsSource() {
|
||||
let parsed = Porcelain.parseStatus("## main\0R new.ts\0old.ts\0 M other.ts\0")
|
||||
#expect(parsed.entries.map(\.path) == ["new.ts", "other.ts"])
|
||||
#expect(parsed.entries[0].index == "R")
|
||||
}
|
||||
|
||||
@Test("a rename carries its source path, a plain change carries none")
|
||||
func renameCarriesSource() {
|
||||
let parsed = Porcelain.parseStatus("## main\0R new.ts\0old.ts\0 M other.ts\0")
|
||||
#expect(parsed.entries[0] == StatusEntry(index: "R", working: " ", path: "new.ts", originalPath: "old.ts"))
|
||||
#expect(parsed.entries[1].originalPath == nil)
|
||||
}
|
||||
|
||||
@Test("a copy in the working column also skips its source field")
|
||||
func copySkipsSource() {
|
||||
let parsed = Porcelain.parseStatus(" C copy.ts\0orig.ts\0")
|
||||
#expect(parsed.entries.map(\.path) == ["copy.ts"])
|
||||
}
|
||||
|
||||
@Test("without a header the branch reads HEAD and nothing can be pushed")
|
||||
func noHeader() {
|
||||
let parsed = Porcelain.parseStatus(" M a.txt\0")
|
||||
#expect(parsed.branch == "HEAD")
|
||||
#expect(!parsed.canPush)
|
||||
#expect(parsed.entries.count == 1)
|
||||
}
|
||||
|
||||
@Test("empty output is a clean tree")
|
||||
func empty() {
|
||||
#expect(Porcelain.parseStatus("") == ParsedStatus(branch: "HEAD", ahead: 0, canPush: false, entries: []))
|
||||
}
|
||||
|
||||
@Test("paths keep spaces, unicode and no quoting")
|
||||
func unquotedPaths() {
|
||||
let parsed = Porcelain.parseStatus(" M dir/naïve file 😀.md\0")
|
||||
#expect(parsed.entries.first?.path == "dir/naïve file 😀.md")
|
||||
}
|
||||
|
||||
// MARK: push
|
||||
|
||||
@Test("a push toast prefers the ref line, a failure its last line")
|
||||
func pushSummary() {
|
||||
let ok = Porcelain.pushSummary(exitCode: 0, stdout: "", stderr: "To github.com:x/y.git\n abc..def main -> main\n")
|
||||
#expect(ok == PushResult(ok: true, message: "abc..def main -> main"))
|
||||
let failed = Porcelain.pushSummary(exitCode: 1, stdout: "", stderr: "error: failed to push\nhint: pull first\n")
|
||||
#expect(failed == PushResult(ok: false, message: "hint: pull first"))
|
||||
}
|
||||
|
||||
@Test("a missing upstream is detected from git's hint")
|
||||
func needsUpstream() {
|
||||
#expect(Porcelain.needsUpstream(stderr: "fatal: The current branch x has no upstream branch."))
|
||||
#expect(!Porcelain.needsUpstream(stderr: "rejected"))
|
||||
}
|
||||
|
||||
@Test("row ids keep the two halves of one file apart")
|
||||
func rowIDs() {
|
||||
#expect(Change.rowID(path: "a.txt", staged: true) == "s:a.txt")
|
||||
#expect(Change.rowID(path: "a.txt", staged: false) == "w:a.txt")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct CSSGrammarTests {
|
||||
@Test("selectors, properties and values")
|
||||
func basics() {
|
||||
let text = ".btn:hover > a, #main { color: #fff; margin: 0 4px 1.5em; display: flex !important; }"
|
||||
#expect(role(".btn", in: text, .css) == .number)
|
||||
#expect(role(":hover", in: text, .css) == .keyword)
|
||||
#expect(role(">", in: text, .css) == .keyword)
|
||||
#expect(role("#main", in: text, .css) == .number)
|
||||
#expect(role("color", in: text, .css) == .variable)
|
||||
#expect(role("#fff", in: text, .css) == .number)
|
||||
#expect(role("4px", in: text, .css) == .number)
|
||||
#expect(role("1.5em", in: text, .css) == .number)
|
||||
#expect(role("flex", in: text, .css) == .string)
|
||||
#expect(role("!important", in: text, .css) == .keyword)
|
||||
}
|
||||
|
||||
@Test("at-rules, functions, urls and custom properties")
|
||||
func atRulesAndFunctions() {
|
||||
let text = "@media (max-width: 600px) {\n nav { background: url(img/x.png); width: calc(100% - var(--gap)); }\n}"
|
||||
#expect(role("@media", in: text, .css) == .keyword)
|
||||
#expect(role("img/x.png", in: text, .css) == .string)
|
||||
#expect(role("calc", in: text, .css) == .plain)
|
||||
#expect(role("100%", in: text, .css) == .number)
|
||||
#expect(role("--gap", in: text, .css) == .variable)
|
||||
#expect(role("nav", in: text, .css) == .number)
|
||||
}
|
||||
|
||||
@Test("SCSS nesting tells a nested selector from a declaration")
|
||||
func scssNesting() {
|
||||
let text = ".card {\n $pad: 4px;\n padding: $pad;\n &:hover {\n color: red;\n }\n}"
|
||||
#expect(role("$pad", in: text, .css) == .variable)
|
||||
#expect(role("padding", in: text, .css) == .variable)
|
||||
#expect(role("&", in: text, .css) == .keyword)
|
||||
#expect(role(":hover", in: text, .css) == .keyword)
|
||||
#expect(role("color", in: text, .css) == .variable)
|
||||
}
|
||||
|
||||
@Test("a value may continue on the next line")
|
||||
func multiLineValue() {
|
||||
let text = "a {\n grid-template-areas:\n \"head head\"\n main;\n color: red;\n}"
|
||||
#expect(role("\"head head\"", in: text, .css) == .string)
|
||||
#expect(role("main", in: text, .css) == .string)
|
||||
#expect(role("color", in: text, .css) == .variable)
|
||||
}
|
||||
|
||||
@Test("comments, including SCSS line comments")
|
||||
func comments() {
|
||||
let text = "/* a\n b */\n// scss\na { b: c; }"
|
||||
#expect(role(" b */", in: text, .css) == .comment)
|
||||
#expect(role("// scss", in: text, .css) == .comment)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
|
||||
/// The role painted over `fragment` (its `occurrence`-th appearance), or nil when the
|
||||
/// fragment is missing or split over tokens of different roles.
|
||||
func role(
|
||||
_ fragment: String, in text: String, _ language: Language?,
|
||||
occurrence: Int = 0, symbols: Set<String> = []
|
||||
) -> TokenRole? {
|
||||
let source = text as NSString
|
||||
var searchFrom = 0
|
||||
var range = NSRange(location: NSNotFound, length: 0)
|
||||
for _ in 0...occurrence {
|
||||
range = source.range(of: fragment, range: NSRange(location: searchFrom, length: source.length - searchFrom))
|
||||
guard range.location != NSNotFound else { return nil }
|
||||
searchFrom = range.location + max(range.length, 1)
|
||||
}
|
||||
let tokens = SyntaxHighlighter.tokens(for: text, language: language, knownSymbols: symbols)
|
||||
let covering = tokens.filter { $0.location < range.location + range.length && $0.location + $0.length > range.location }
|
||||
guard let first = covering.first, covering.allSatisfy({ $0.role == first.role }) else { return nil }
|
||||
return first.role
|
||||
}
|
||||
|
||||
/// The non-plain runs of a text as `text:role` strings, for compact whole-line expectations.
|
||||
func paintedRuns(_ text: String, _ language: Language?) -> [String] {
|
||||
let source = text as NSString
|
||||
return SyntaxHighlighter.tokens(for: text, language: language)
|
||||
.filter { $0.role != .plain }
|
||||
.map { "\(source.substring(with: NSRange(location: $0.location, length: $0.length))):\($0.role.rawValue)" }
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct JSONGrammarTests {
|
||||
@Test("keys read as properties, values keep their own roles")
|
||||
func keysAndValues() {
|
||||
let text = "{\"name\": \"helder\", \"n\": -1.5e2, \"ok\": true, \"none\": null, \"list\": [\"a\"]}"
|
||||
#expect(role("\"name\"", in: text, .json) == .variable)
|
||||
#expect(role("\"helder\"", in: text, .json) == .string)
|
||||
#expect(role("-1.5e2", in: text, .json) == .number)
|
||||
#expect(role("true", in: text, .json) == .number)
|
||||
#expect(role("null", in: text, .json) == .number)
|
||||
#expect(role("\"a\"", in: text, .json) == .string)
|
||||
}
|
||||
|
||||
@Test("an escaped quote does not end the string")
|
||||
func escapedQuote() {
|
||||
#expect(role("\"a \\\" b\"", in: "{\"k\": \"a \\\" b\"}", .json) == .string)
|
||||
}
|
||||
|
||||
@Test("tsconfig-style comments are allowed")
|
||||
func comments() {
|
||||
let text = "{\n // line\n /* block */ \"a\": 1\n}"
|
||||
#expect(role("// line", in: text, .json) == .comment)
|
||||
#expect(role("/* block */", in: text, .json) == .comment)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct JavaScriptGrammarTests {
|
||||
@Test("keywords, strings, numbers and comments")
|
||||
func basics() {
|
||||
let text = "const a = 'x' + \"y\" // note\nlet b = 1.5e3"
|
||||
#expect(paintedRuns(text, .javascript) == [
|
||||
"const:keyword", "=:keyword", "'x':string", "+:keyword", "\"y\":string", "// note:comment",
|
||||
"let:keyword", "=:keyword", "1.5e3:number",
|
||||
])
|
||||
}
|
||||
|
||||
@Test("a template literal spans lines and highlights its interpolation as code")
|
||||
func templateLiteral() {
|
||||
let text = "const s = `a ${fn(1)} b\nstill string ${x}`\nconst after = 2"
|
||||
#expect(role("`a ", in: text, .javascript) == .string)
|
||||
#expect(role("1", in: text, .javascript) == .number)
|
||||
#expect(role("still string ", in: text, .javascript) == .string)
|
||||
#expect(role("after", in: text, .javascript) == .plain)
|
||||
#expect(role("2", in: text, .javascript) == .number)
|
||||
}
|
||||
|
||||
@Test("an interpolation holding braces returns to the template at its own brace")
|
||||
func nestedBraces() {
|
||||
let text = "`${ {a: 1}.a } tail`"
|
||||
#expect(role(" tail`", in: text, .javascript) == .string)
|
||||
}
|
||||
|
||||
@Test("a regex literal after an operator is a string, a slash after a value divides")
|
||||
func regexVersusDivision() {
|
||||
#expect(role("/ab+c/gi", in: "const r = /ab+c/gi", .javascript) == .string)
|
||||
#expect(role("/", in: "const q = a / b / c", .javascript) == .keyword)
|
||||
}
|
||||
|
||||
@Test("block comments carry over lines")
|
||||
func blockComment() {
|
||||
let text = "/**\n * Docs\n */\nfunction f() {}"
|
||||
#expect(role(" * Docs", in: text, .javascript) == .comment)
|
||||
#expect(role("function", in: text, .javascript) == .keyword)
|
||||
}
|
||||
|
||||
@Test("class names follow class, extends and new")
|
||||
func classNames() {
|
||||
let text = "class A extends B { m() { return new C() } }"
|
||||
#expect(role("A", in: text, .javascript) == .variable)
|
||||
#expect(role("B", in: text, .javascript) == .variable)
|
||||
#expect(role("C", in: text, .javascript) == .variable)
|
||||
#expect(role("m", in: text, .javascript) == .plain)
|
||||
}
|
||||
|
||||
@Test("constants and booleans read in the number colour")
|
||||
func constants() {
|
||||
let text = "if (x === undefined || y === true) MAX_SIZE"
|
||||
#expect(role("undefined", in: text, .javascript) == .number)
|
||||
#expect(role("true", in: text, .javascript) == .number)
|
||||
#expect(role("MAX_SIZE", in: text, .javascript) == .number)
|
||||
}
|
||||
|
||||
@Test("TypeScript adds its keywords and builtin types")
|
||||
func typescript() {
|
||||
let text = "interface A { readonly n: number }\ntype B = keyof A"
|
||||
#expect(role("readonly", in: text, .typescript) == .keyword)
|
||||
#expect(role("number", in: text, .typescript) == .number)
|
||||
#expect(role("keyof", in: text, .typescript) == .keyword)
|
||||
#expect(role("type", in: text, .javascript) == .plain)
|
||||
}
|
||||
|
||||
@Test("JSX tags, attributes and expressions", arguments: [Language.jsx, .tsx])
|
||||
func jsx(language: Language) {
|
||||
let text = "return <Card title=\"x\" onClick={() => go(1)}>\n Hi\n</Card>"
|
||||
#expect(role("Card", in: text, language) == .number)
|
||||
#expect(role("title", in: text, language) == .variable)
|
||||
#expect(role("\"x\"", in: text, language) == .string)
|
||||
#expect(role("=>", in: text, language) == .keyword)
|
||||
#expect(role("1", in: text, language) == .number)
|
||||
#expect(role("Card", in: text, language, occurrence: 1) == .number)
|
||||
}
|
||||
|
||||
@Test("a JSX tag may wrap its attributes over lines")
|
||||
func multiLineTag() {
|
||||
let text = "const a = <div\n className=\"x\"\n/>\nlet b"
|
||||
#expect(role("className", in: text, .jsx) == .variable)
|
||||
#expect(role("let", in: text, .jsx) == .keyword)
|
||||
}
|
||||
|
||||
@Test("a less-than between values stays an operator in JSX")
|
||||
func lessThan() {
|
||||
#expect(role("<", in: "if (a <b) {}", .jsx) == .keyword)
|
||||
}
|
||||
|
||||
@Test("an unterminated string ends at the line end")
|
||||
func unterminatedString() {
|
||||
let text = "const a = 'open\nconst b = 1"
|
||||
#expect(role("const", in: text, .javascript, occurrence: 1) == .keyword)
|
||||
}
|
||||
|
||||
@Test("JSX children are plain text, so an apostrophe opens no string")
|
||||
func childrenText() {
|
||||
let text = "const a = <p>Don't {name} if</p>\nconst b = 'x'"
|
||||
#expect(role("Don't ", in: text, .jsx) == .plain)
|
||||
#expect(role("if", in: text, .jsx) == .plain)
|
||||
#expect(role("p", in: text, .jsx, occurrence: 1) == .number)
|
||||
#expect(role("'x'", in: text, .jsx) == .string)
|
||||
}
|
||||
|
||||
@Test("nested elements and expressions over several lines return to code at the end")
|
||||
func nestedChildren() {
|
||||
let text = """
|
||||
const list = (
|
||||
<ul className="x">
|
||||
{items.map((item) => (
|
||||
<li key={item.id}>{item.label}</li>
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
let after = 1
|
||||
"""
|
||||
#expect(role("ul", in: text, .jsx) == .number)
|
||||
#expect(role("=>", in: text, .jsx) == .keyword)
|
||||
#expect(role("li", in: text, .jsx, occurrence: 1) == .number)
|
||||
#expect(role("key", in: text, .jsx) == .variable)
|
||||
#expect(role("ul", in: text, .jsx, occurrence: 1) == .number)
|
||||
#expect(role("let", in: text, .jsx) == .keyword)
|
||||
}
|
||||
|
||||
@Test("a fragment opens and closes like an element")
|
||||
func fragments() {
|
||||
let text = "return <>it's <b>x</b></>\nlet y"
|
||||
#expect(role("it's ", in: text, .tsx) == .plain)
|
||||
#expect(role("let", in: text, .tsx) == .keyword)
|
||||
}
|
||||
|
||||
@Test("a self-closing element at the top leaves code mode at once")
|
||||
func selfClosing() {
|
||||
#expect(role("let", in: "x = <Br />; let z", .jsx) == .keyword)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
@testable import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct LexerTests {
|
||||
private func lexer(_ text: String) -> Lexer {
|
||||
Lexer(units: Array(text.utf16), symbols: [])
|
||||
}
|
||||
|
||||
@Test("numbers take prefixes, separators, fractions, exponents and suffixes",
|
||||
arguments: ["0x1F", "0b1010", "1_000_000", "3.14", "1e10", "2.5E-3", "10n"])
|
||||
func numbers(literal: String) {
|
||||
var lx = lexer(literal + " rest")
|
||||
lx.number()
|
||||
#expect(lx.i == literal.utf16.count)
|
||||
#expect(lx.tokens == [Token(location: 0, length: literal.utf16.count, role: .number)])
|
||||
}
|
||||
|
||||
@Test("an unterminated string stops at the line end and says so")
|
||||
func unterminatedString() {
|
||||
var lx = lexer("'abc")
|
||||
lx.i = 1
|
||||
let closed = lx.quoted(from: 0, quote: Unit.apostrophe)
|
||||
#expect(!closed)
|
||||
#expect(lx.i == 4)
|
||||
}
|
||||
|
||||
@Test("an escape at the very end of a line never runs past it")
|
||||
func escapeAtLineEnd() {
|
||||
var lx = lexer("'ab\\")
|
||||
lx.i = 1
|
||||
let closed = lx.quoted(from: 0, quote: Unit.apostrophe)
|
||||
#expect(!closed)
|
||||
#expect(lx.i == 4)
|
||||
}
|
||||
|
||||
@Test("emitting next to a run of the same role extends it")
|
||||
func mergesAdjacentRuns() {
|
||||
var lx = lexer("abcd")
|
||||
lx.emit(0, 2, .keyword)
|
||||
lx.emit(2, 4, .keyword)
|
||||
#expect(lx.tokens == [Token(location: 0, length: 4, role: .keyword)])
|
||||
}
|
||||
|
||||
@Test("non-ASCII units count as identifier letters")
|
||||
func unicodeIdentifiers() {
|
||||
#expect(Unit.isIdentStart(Array("é".utf16)[0]))
|
||||
#expect(Array("😀".utf16).allSatisfy(Unit.isIdentPart))
|
||||
#expect(!Unit.isIdentStart(Unit.minus))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct MarkdownGrammarTests {
|
||||
@Test("headings read as keywords")
|
||||
func headings() {
|
||||
#expect(role("## Title", in: "## Title\ntext", .markdown) == .keyword)
|
||||
#expect(role("#hashtag", in: "#hashtag", .markdown) == .plain)
|
||||
}
|
||||
|
||||
@Test("a fenced block is highlighted in its own language and closes on its fence")
|
||||
func fencedCode() {
|
||||
let text = "```php\n$x = new Agent();\n```\nafter $x"
|
||||
#expect(role("```php", in: text, .markdown) == .comment)
|
||||
#expect(role("$x", in: text, .markdown) == .variable)
|
||||
#expect(role("new", in: text, .markdown) == .keyword)
|
||||
#expect(role("$x", in: text, .markdown, occurrence: 1) == .plain)
|
||||
}
|
||||
|
||||
@Test("a fence in an unknown language stays plain")
|
||||
func unknownFence() {
|
||||
let text = "~~~text\nif x\n~~~"
|
||||
#expect(role("if x", in: text, .markdown) == .plain)
|
||||
}
|
||||
|
||||
@Test("a fenced block comment carries over lines inside the fence")
|
||||
func fenceCarriesState() {
|
||||
let text = "```js\n/* a\nb */ let c\n```"
|
||||
#expect(role("b */", in: text, .markdown) == .comment)
|
||||
#expect(role("let", in: text, .markdown) == .keyword)
|
||||
}
|
||||
|
||||
@Test("inline code, link targets and autolinks")
|
||||
func inline() {
|
||||
let text = "Use `npm test` and [docs](https://x.test) or <https://y.test>."
|
||||
#expect(role("`npm test`", in: text, .markdown) == .keyword)
|
||||
#expect(role("(https://x.test)", in: text, .markdown) == .variable)
|
||||
#expect(role("docs", in: text, .markdown) == .plain)
|
||||
#expect(role("<https://y.test>", in: text, .markdown) == .variable)
|
||||
}
|
||||
|
||||
@Test("list markers, quotes and rules read as punctuation")
|
||||
func punctuation() {
|
||||
let text = "- one\n1. two\n> quote\n---"
|
||||
#expect(role("-", in: text, .markdown) == .comment)
|
||||
#expect(role("1.", in: text, .markdown) == .comment)
|
||||
#expect(role(">", in: text, .markdown) == .comment)
|
||||
#expect(role("---", in: text, .markdown) == .comment)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct MarkupGrammarTests {
|
||||
@Test("tags, attributes, values and entities")
|
||||
func basics() {
|
||||
let text = "<a href=\"/x\" data-id=1 hidden>Tom & Jerry</a>"
|
||||
#expect(paintedRuns(text, .markup) == [
|
||||
"a:number", "href:variable", "\"/x\":string", "data-id:variable", "1:string", "hidden:variable",
|
||||
"&:variable", "a:number",
|
||||
])
|
||||
}
|
||||
|
||||
@Test("comments, doctype and CDATA read as comments")
|
||||
func comments() {
|
||||
let text = "<!DOCTYPE html>\n<!-- a\n b -->\n<![CDATA[ x ]]>\n<p>"
|
||||
#expect(role("<!DOCTYPE html>", in: text, .markup) == .comment)
|
||||
#expect(role(" b -->", in: text, .markup) == .comment)
|
||||
#expect(role("<![CDATA[ x ]]>", in: text, .markup) == .comment)
|
||||
#expect(role("p", in: text, .markup) == .number)
|
||||
}
|
||||
|
||||
@Test("a script body is JavaScript and a style body is CSS")
|
||||
func embedded() {
|
||||
let text = "<script>\nconst a = 1 // c\n</script>\n<style>\n.b { color: red; }\n</style>\n<p>const</p>"
|
||||
#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 = "<script>// x</script><p>"
|
||||
#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 = "<img\n alt=\"a\n b\"\n src=\"x\">\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 = "<template><div :class=\"a\" @click=\"go\"/></template>\n<script setup>\nimport x from 'y'\n</script>"
|
||||
#expect(role(":class", in: text, .markup) == .variable)
|
||||
#expect(role("@click", in: text, .markup) == .variable)
|
||||
#expect(role("import", in: text, .markup) == .keyword)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct PHPGrammarTests {
|
||||
private let source = """
|
||||
<?php
|
||||
namespace App\\Domain;
|
||||
|
||||
use Illuminate\\Support\\Str;
|
||||
|
||||
#[Attribute]
|
||||
final class Agent extends Model implements HasLabel
|
||||
{
|
||||
use HasFactory;
|
||||
public const STATUS_ACTIVE = 'active';
|
||||
|
||||
public function label(?string $prefix = null): string
|
||||
{
|
||||
// line comment
|
||||
return Str::upper("{$this->name} $prefix") . self::STATUS_ACTIVE . 0x1F;
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
@Test("the open tag and keywords read as keywords")
|
||||
func keywords() {
|
||||
#expect(role("<?php", in: source, .php) == .keyword)
|
||||
#expect(role("final", in: source, .php) == .keyword)
|
||||
#expect(role("function", in: source, .php) == .keyword)
|
||||
#expect(role("string", in: source, .php, occurrence: 0) == .keyword)
|
||||
}
|
||||
|
||||
@Test("a namespace path reads as a type path")
|
||||
func namespacePath() {
|
||||
#expect(role("App\\Domain", in: source, .php) == .string)
|
||||
#expect(role("Illuminate\\Support\\", in: source, .php) == .string)
|
||||
}
|
||||
|
||||
@Test("class names read as variables, known ones as symbols", arguments: ["Agent", "Model", "HasLabel", "HasFactory", "Attribute", "Str"])
|
||||
func classNames(name: String) {
|
||||
#expect(role(name, in: source, .php) == .variable)
|
||||
#expect(role(name, in: source, .php, symbols: [name]) == .symbol)
|
||||
}
|
||||
|
||||
@Test("the last segment of an imported path is a class name")
|
||||
func importedClass() {
|
||||
#expect(role("Str", in: source, .php, symbols: ["Str"]) == .symbol)
|
||||
}
|
||||
|
||||
@Test("variables, properties and constants get their own roles")
|
||||
func variablesAndConstants() {
|
||||
#expect(role("$prefix", in: source, .php) == .variable)
|
||||
#expect(role("STATUS_ACTIVE", in: source, .php) == .number)
|
||||
#expect(role("STATUS_ACTIVE", in: source, .php, occurrence: 1) == .number)
|
||||
#expect(role("null", in: source, .php) == .number)
|
||||
#expect(role("0x1F", in: source, .php) == .number)
|
||||
}
|
||||
|
||||
@Test("a method call after -> is a function name, a property is a variable")
|
||||
func arrowAccess() {
|
||||
let text = "<?php $a->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 = "<?php $a = \"hi $name!\"; $b = 'hi $name';"
|
||||
#expect(role("\"hi ", in: text, .php) == .string)
|
||||
#expect(role("$name", in: text, .php, occurrence: 0) == .variable)
|
||||
#expect(role("'hi $name'", in: text, .php) == .string)
|
||||
#expect(role("{$this->name}", in: source, .php) == .variable)
|
||||
}
|
||||
|
||||
@Test("comments: //, # and block comments")
|
||||
func comments() {
|
||||
#expect(role("// line comment", in: source, .php) == .comment)
|
||||
#expect(role("# hash", in: "<?php # hash\n$a;", .php) == .comment)
|
||||
let block = "<?php /* one\n two */ $x;"
|
||||
#expect(role("two */", in: block, .php) == .comment)
|
||||
#expect(role("$x", in: block, .php) == .variable)
|
||||
}
|
||||
|
||||
@Test("a multi-line string carries over lines")
|
||||
func multiLineString() {
|
||||
let text = "<?php $sql = \"select *\n from users\n where id = 1\";\n$next = 2;"
|
||||
#expect(role(" from users", in: text, .php) == .string)
|
||||
#expect(role("$next", in: text, .php) == .variable)
|
||||
}
|
||||
|
||||
@Test("a heredoc runs to its closing marker, a nowdoc does not interpolate")
|
||||
func heredoc() {
|
||||
let text = "<?php\n$a = <<<EOT\n Hello $name\n EOT;\n$b = <<<'RAW'\n $raw\nRAW;\n$c = 1;"
|
||||
#expect(role(" Hello ", in: text, .php) == .string)
|
||||
#expect(role("$name", in: text, .php) == .variable)
|
||||
#expect(role("$raw", in: text, .php) == .string)
|
||||
#expect(role("$c", in: text, .php) == .variable)
|
||||
#expect(role("1", in: text, .php, occurrence: 0) == .number)
|
||||
}
|
||||
|
||||
@Test("a file with <?php is HTML with PHP islands")
|
||||
func template() {
|
||||
let text = "<div class=\"<?= $cls ?>\">\n<?php if ($x): ?>\n <b>hi</b>\n<?php endif; ?>\n</div>"
|
||||
#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 = "<p><?php // note ?> after</p>"
|
||||
#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 <?php is read as PHP")
|
||||
func bladeReadsAsPHP() {
|
||||
let text = "@if($user)\n {{ $user->name }}\n@endif"
|
||||
#expect(role("$user", in: text, .php) == .variable)
|
||||
}
|
||||
|
||||
@Test("static, self and parent stay keywords before ::")
|
||||
func scopeKeywords() {
|
||||
let text = "<?php static::make(); self::X; parent::boot(); Carbon::now();"
|
||||
#expect(role("static", in: text, .php) == .keyword)
|
||||
#expect(role("self", in: text, .php) == .keyword)
|
||||
#expect(role("parent", in: text, .php) == .keyword)
|
||||
#expect(role("Carbon", in: text, .php, symbols: ["Carbon"]) == .symbol)
|
||||
}
|
||||
|
||||
@Test("a qualified name marks only its last segment as the class")
|
||||
func qualifiedName() {
|
||||
let text = "<?php new \\App\\Models\\Agent();"
|
||||
#expect(role("\\App\\Models\\", in: text, .php) == .string)
|
||||
#expect(role("Agent", in: text, .php, symbols: ["Agent"]) == .symbol)
|
||||
}
|
||||
|
||||
@Test("PHP keywords are case-insensitive")
|
||||
func caseInsensitiveKeywords() {
|
||||
#expect(role("NEW", in: "<?php $a = NEW Foo;", .php) == .keyword)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct PythonGrammarTests {
|
||||
@Test("keywords, builtins, constants and comments")
|
||||
func basics() {
|
||||
let text = "def run(x):\n if x is None: # guard\n return len(x)\n return True"
|
||||
#expect(role("def", in: text, .python) == .keyword)
|
||||
#expect(role("run", in: text, .python) == .plain)
|
||||
#expect(role("None", in: text, .python) == .number)
|
||||
#expect(role("# guard", in: text, .python) == .comment)
|
||||
#expect(role("len", in: text, .python) == .number)
|
||||
#expect(role("True", in: text, .python) == .number)
|
||||
}
|
||||
|
||||
@Test("a triple-quoted string carries over lines")
|
||||
func tripleQuoted() {
|
||||
let text = "x = '''one\ntwo # not a comment\nthree'''\ny = 1"
|
||||
#expect(role("two # not a comment", in: text, .python) == .string)
|
||||
#expect(role("1", in: text, .python) == .number)
|
||||
}
|
||||
|
||||
@Test("string prefixes belong to the string", arguments: ["f\"a{b}\"", "rb'raw'", "u\"x\""])
|
||||
func prefixes(literal: String) {
|
||||
#expect(role(literal, in: "v = \(literal)", .python) == .string)
|
||||
}
|
||||
|
||||
@Test("a decorator at the start of a line reads as a keyword; matrix @ does not")
|
||||
func decorators() {
|
||||
let text = "@app.route('/')\ndef f(): return a @ b"
|
||||
#expect(role("@app.route", in: text, .python) == .keyword)
|
||||
#expect(role("@", in: text, .python, occurrence: 1) == .plain)
|
||||
}
|
||||
|
||||
@Test("the name after class reads as a class")
|
||||
func className() {
|
||||
#expect(role("Agent", in: "class Agent(Base):", .python) == .variable)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct ShellGrammarTests {
|
||||
@Test("keywords, builtins, variables and strings")
|
||||
func basics() {
|
||||
let text = "if [ -n \"$HOME\" ]; then echo \"dir: ${HOME}/x\" 'no $sub'; fi"
|
||||
#expect(role("if", in: text, .bash) == .keyword)
|
||||
#expect(role("$HOME", in: text, .bash) == .variable)
|
||||
#expect(role("echo", in: text, .bash) == .number)
|
||||
#expect(role("${HOME}", in: text, .bash) == .variable)
|
||||
#expect(role("'no $sub'", in: text, .bash) == .string)
|
||||
#expect(role("fi", in: text, .bash) == .keyword)
|
||||
}
|
||||
|
||||
@Test("a hash inside a word is not a comment")
|
||||
func hashInWord() {
|
||||
let text = "echo a#b # real"
|
||||
#expect(role("a#b", in: text, .bash) == .plain)
|
||||
#expect(role("# real", in: text, .bash) == .comment)
|
||||
}
|
||||
|
||||
@Test("a heredoc runs to its marker; a quoted marker turns interpolation off")
|
||||
func heredoc() {
|
||||
let text = "cat <<EOF\nhi $USER\nEOF\ncat <<'RAW'\n$keep\nRAW\necho done"
|
||||
#expect(role("hi ", in: text, .bash) == .string)
|
||||
#expect(role("$USER", in: text, .bash) == .variable)
|
||||
#expect(role("$keep", in: text, .bash) == .string)
|
||||
#expect(role("echo", in: text, .bash) == .number)
|
||||
}
|
||||
|
||||
@Test("a .env file reads keys as assignments")
|
||||
func dotenv() {
|
||||
let text = "APP_NAME=Helder\n# comment\nDB_PASSWORD=\"s3cret\""
|
||||
#expect(role("APP_NAME", in: text, .bash) == .variable)
|
||||
#expect(role("# comment", in: text, .bash) == .comment)
|
||||
#expect(role("\"s3cret\"", in: text, .bash) == .string)
|
||||
}
|
||||
|
||||
@Test("a quoted string may span lines")
|
||||
func multiLineString() {
|
||||
let text = "msg=\"one\ntwo\"\necho x"
|
||||
#expect(role("two\"", in: text, .bash) == .string)
|
||||
#expect(role("echo", in: text, .bash) == .number)
|
||||
}
|
||||
|
||||
@Test("dashes in a command name do not start a keyword")
|
||||
func dashedWords() {
|
||||
#expect(role("apt-get", in: "apt-get install -y done-thing", .bash) == .plain)
|
||||
#expect(role("done-thing", in: "apt-get install -y done-thing", .bash) == .plain)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
import Testing
|
||||
|
||||
@Suite struct SyntaxHighlighterTests {
|
||||
private static let samples: [(String, Language)] = [
|
||||
("<?php\nnamespace App;\n/* a\n block */\nclass A extends B {\n public function run(): string { return \"x $y\"; }\n}\n", .php),
|
||||
("const a = `x ${b} y`\n/* c\n d */ let e = /re/g\n", .javascript),
|
||||
("export const App = () => (\n <div className=\"x\">\n {n.map((i) => <b key={i}>{i}</b>)}\n </div>\n)\n", .tsx),
|
||||
("<html>\n<!-- c\n -->\n<script>\nlet a = 1\n</script>\n<style>a { color: red }</style>\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 <<EOF\nhi $USER\nEOF\n", .bash),
|
||||
("def f(x):\n \"\"\"doc\n string\"\"\"\n return None\n", .python),
|
||||
("a: 1\nb: |\n text\nc: true # note\n", .yaml),
|
||||
]
|
||||
|
||||
@Test("tokens tile the text end to end with no gaps or overlaps", arguments: samples)
|
||||
func tokensTileTheText(sample: (String, Language)) {
|
||||
let (text, language) = sample
|
||||
let tokens = SyntaxHighlighter.tokens(for: text, language: language)
|
||||
var position = 0
|
||||
for token in tokens {
|
||||
#expect(token.location == position)
|
||||
#expect(token.length > 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 = "<?php \"'`/*<!--<<<EOT\n${{[(\\\n\u{0}é😀\t\r\n?> </script> ``` ---\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 = """
|
||||
<?php
|
||||
namespace App\\Http\\Controllers;
|
||||
/** Docblock for the class. */
|
||||
final class UserController extends Controller implements HasMiddleware
|
||||
{
|
||||
public function show(Request $request, int $id): JsonResponse
|
||||
{
|
||||
$user = User::query()->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))
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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"),
|
||||
("<a b.png> '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](")])
|
||||
}
|
||||
}
|
||||
@@ -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 <script>alert(1)</script> tag.") == [.paragraph([.text("A <script>alert(1)</script> 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("", 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("", 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("", 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("", 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("[](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)
|
||||
}
|
||||
}
|
||||
@@ -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)])
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user